### Install Graphbrain from Source Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/installation.md Commands to clone the repository and install the package in standard or editable mode. ```bash $ git clone https://github.com/graphbrain/graphbrain.git $ cd graphbrain ``` ```bash $ pip install . ``` ```bash $ pip install -e . ``` -------------------------------- ### macOS Prerequisites Installation Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/installation.md Commands to install necessary tools on macOS systems. ```bash $ xcode-select --install ``` ```bash $ brew install python3 ``` ```bash $ sudo easy_install pip ``` ```bash $ sudo -H pip install virtualenv ``` -------------------------------- ### Development and Testing Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/installation.md Commands for installing development dependencies and running the test suite. ```bash $ pip install '.[dev]' ``` ```bash $ pytest ``` -------------------------------- ### Install Graphbrain via pip Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/installation.md Standard installation command for the Graphbrain package. ```bash $ pip install graphbrain ``` -------------------------------- ### Basic SH Notation Example Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notation.md Illustrates a simple sentence representation in SH notation. This format is human-friendly and can convey basic meaning. ```default (is/P (the/M sky/C) blue/C) ``` -------------------------------- ### SH Notation: Builder Type Example Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notation.md Constructs concepts from other concepts using the 'B' type for builders. ```default (of/B capital/C germany/C) ``` -------------------------------- ### Parser Accuracy Results Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/internals/create-parser.md Example output showing parser accuracy results for different categories and overall. ```text news accuracy: 0.962852897473997 [648 correct out of 673] science accuracy: 0.9427083333333334 [543 correct out of 576] fiction accuracy: 0.9581881533101045 [275 correct out of 287] non-fiction accuracy: 0.9338235294117647 [254 correct out of 272] wikipedia accuracy: 0.9482288828337875 [696 correct out of 734] overall accuracy: 0.950432730133753 [2416 correct out of 2542] ``` -------------------------------- ### Represent propositions and concepts Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/overview.md Examples of using connectors to define predicates, combine concepts, and modify concepts. ```default (is berlin nice) ``` ```default (of capital germany) ``` ```default (and meat potatoes) ``` ```default (highest (in mountain brazil)) ``` ```default (when (is (the sky) blue)) ``` ```default (climbs mary (the (highest (in mountain brazil)))) ``` -------------------------------- ### Execute GraphBrain Command Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/cli.md This is the direct command to execute GraphBrain tasks after installation. It provides a streamlined way to access all functionalities. ```bash graphbrain ... ``` -------------------------------- ### SH Notation: Predicate Type Example Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notation.md Builds a relation using the 'P' type for predicates. Arguments can be atomic concepts. ```default (is/P berlin/C nice/C) ``` -------------------------------- ### Configure Plyvel Setup for Libraries Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/backends.md Modify the 'setup.py' file for Plyvel to include the necessary compiled libraries: LevelDB, and several Boost libraries. Ensure the library names and versions match your compiled output. ```python Extension( ... libraries=['leveldb vaskomitanov-r x64', 'libboost_chrono-vc141-mt-x64-1_69', 'libboost_date_time-vc141-mt-x64-1_69', 'libboost_filesystem-vc141-mt-x64-1_69', 'libboost_system-vc141-mt-x64-1_69', 'libboost_thread-vc141-mt-x64-1_69'], ... ) ``` -------------------------------- ### Create and Use a Natural Language Parser Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Initializes a spaCy-based NLP parser for a specified language and uses it to parse sentences into semantic hypergraphs. Requires spaCy models to be installed. ```python from graphbrain.parsers import create_parser parser = create_parser(lang='en') text = "Einstein first published the theory of relativity in 1905" result = parser.parse(text) main_edge = result['parses'][0]['main_edge'] print(f"Main edge: {main_edge}") atom2word = result['parses'][0]['atom2word'] for atom, (word, position) in atom2word.items(): print(f" {atom} <- '{word}' (position {position})") ``` -------------------------------- ### Coreference Resolution Example Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/parsing.md Illustrates parser-level coreference resolution, showing how pronouns are linked to their antecedents and how this information is added to parser results. ```default "Alice says that she likes her dog." ``` ```default (says/Pd.sr alice/C (that/T (likes/P.so alice/C (poss/Bp.am/. alice/C dog/C)))) ``` ```default (gender/P/. alice/Cp.s/en female), (number/P/. alice/Cp.s/en singular), (animacy/P/. alice/Cp.s/en animate) ``` -------------------------------- ### SH Notation: Conjunction Type Example Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notation.md Defines sequences of hyperedges using the 'J' type for conjunctions. ```default (and/J meat/C potatoes/C) ``` -------------------------------- ### Lemma Specification Example Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/parsing.md Illustrates the GraphBrain hyperedge format for specifying lemma relationships. The `lemma/J/.` conjunction indicates a lemma, followed by the word and its lemma form. ```default (lemma/J/. published/P/en publish/P/en) ``` -------------------------------- ### Identify Actor Hyperedge Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/cli.md This example shows the format of a hyperedge added when an entity is identified as an actor. It indicates that 'mary/Cp.s/en' is recognized as an actor. ```default (actor/P/. mary/Cp.s/en) ``` -------------------------------- ### Execute GraphBrain Module Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/cli.md Use this command to run GraphBrain tasks by executing the root module with Python. Ensure GraphBrain is installed in your Python environment. ```bash python -m graphbrain ... ``` -------------------------------- ### SH Notation: Trigger Type Example Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notation.md Builds specifications using the 'T' type for triggers, often used with temporal information. ```default (in/T 1994/C) ``` -------------------------------- ### Python Coreference Resolution and Inference Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/parsing.md A complete Python example demonstrating parser creation with coreference resolution enabled, parsing a sentence, and displaying the resolved coreferences and inferred attributes. ```pycon >>> parser = create_parser(lang='en', corefs=True) >>> parser.parse('Alice says that she likes her dog.') {'parses': ({'main_edge': (says/Pd.sr.|f--3s-/en alice/Cp.s/en (that/T/en (likes/P.so.|f--3s-/en she/Ci/en (her/Mp/en dog/Cc.s/en)))), 'extra_edges': set(), 'failed': False, 'text': 'Alice says that she likes her dog.', 'atom2word': {says/Pd.sr.|f--3s-/en: ('says', 1), alice/Cp.s/en: ('Alice', 0), that/T/en: ('that', 2), likes/P.so.|f--3s-/en: ('likes', 4), she/Ci/en: ('she', 3), her/Mp/en: ('her', 5), dog/Cc.s/en: ('dog', 6)}, 'atom2token': {alice/Cp.s/en: Alice, that/T/en: that, she/Ci/en: she, her/Mp/en: her, dog/Cc.s/en: dog, says/Pd.sr.|f--3s-/en: says, likes/P.so.|f--3s-/en: likes}, 'spacy_sentence': Alice says that she likes her dog., 'resolved_corefs': (says/Pd.sr.|f--3s-/en alice/Cp.s/en (that/T/en (likes/P.so.|f--3s-/en alice/Cp.s/en (poss/Bp.am/. alice/Cp.s/en dog/Cc.s/en))))},), 'inferred_edges': [(gender/P/. alice/Cp.s/en female), (number/P/. alice/Cp.s/en singular), (animacy/P/. alice/Cp.s/en animate)]} ``` -------------------------------- ### Representing Claims in GraphBrain Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/overview.md This example shows how to represent a claim, such as 'Mary states that Berlin is nice', using GraphBrain's hypergraph notation. It demonstrates attributing facts to sources. ```default (claims mary (is berlin nice)) ``` -------------------------------- ### Inferring Taxonomy with GraphBrain Agent Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/overview.md This example illustrates a hyperedge produced by the taxonomy agent, inferring that 'city of Berlin' is a type of 'city'. It showcases how agents derive new knowledge. ```default (type_of/P/. city/C (of/B city/C berlin/C)) ``` -------------------------------- ### Derive Taxonomy - Builder Defined Concepts Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/cli.md This example shows deriving a taxonomy from concepts defined with builders. It illustrates that 'founder of psychoanalysis' is a type of 'founder'. ```default (type_of/P/. (of/Br.ma founder/Cc.s psychoanalysis/Cc.s) founder/Cc.s) ``` -------------------------------- ### Bootstrap Boost.lib Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/backends.md Run this command to bootstrap the Boost.lib build process. Ensure 'cl' is in your environment variables and you are using the x64 Native Tools Command Prompt for VS2017. ```bash $ bootstrap.bat ``` -------------------------------- ### Set and Get Hyperedge Float Attribute Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/hypergraph-operations.md Associate a float attribute with a hyperedge using `set_attribute()` and retrieve it with `get_float_attribute()`. The attribute name 'height' is used as an example. ```python >>> hg.set_attribute('alice/C', 'height', 1.2) True >>> hg.get_float_attribute('alice/C', 'height') 1.2 ``` -------------------------------- ### Set and Get Hyperedge Integer Attribute Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/hypergraph-operations.md Use `set_attribute()` to assign an integer value to a hyperedge and `get_int_attribute()` to retrieve it. The attribute name 'age' is used as an example. ```python >>> hg.set_attribute('alice/C', 'age', 7) True >>> hg.get_int_attribute('alice/C', 'age') 7 ``` -------------------------------- ### Set and Get Hyperedge String Attribute Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/hypergraph-operations.md Associate a string attribute with a hyperedge using `set_attribute()` and retrieve it with `get_str_attribute()`. The attribute name 'text' is used as an example. ```python >>> hg.set_attribute('(in/B alice/C wonderland/C)', 'text', 'Alice in Wonderland') True >>> hg.get_str_attribute('(in/B alice/C wonderland/C)', 'text') 'Alice in Wonderland' ``` -------------------------------- ### Search hypergraph with wildcards Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/patterns.md Demonstrates initializing a hypergraph and performing a search using wildcard patterns. ```default >>> from graphbrain import * >>> hg = hgraph('example.db') >>> hg.add('(plays/P.so alice/C chess/C)') (plays/P.so alice/C chess/C) >>> list(hg.search('(plays/P.so * *)')) [(plays/P.so alice/C chess/C)] ``` -------------------------------- ### Build Boost.lib Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/backends.md Execute this command to build the Boost.lib library. Specify the toolset, address model, stagedir, threading, build type, and build directory. This step can take a significant amount of time. ```bash $ b2.exe stage --toolset=msvc-14.1 address-model=64 --stagedir="E:\mylib\boost\bin1.64.0\VC14. 1" threading=multi --build-type=complete --build-dir="E:\mylib\boost\boost_1_64_0\build" ``` -------------------------------- ### Initialize a hypergraph Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/tutorials/hypergraph-operations.md Creates or opens a hypergraph database file. ```python hg = hgraph('example.db') ``` -------------------------------- ### Install plyvel from Conda Forge Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/backends.md Use this command to install the plyvel library from the conda-forge channel, which can resolve compatibility issues on macOS with Anaconda. ```bash pip uninstall plyvel conda install -c conda-forge plyvel ``` -------------------------------- ### Create hypergraph instance Source: https://github.com/graphbrain/graphbrain-archive/blob/master/notebooks/hypergraph.ipynb Initializes a new hypergraph file. ```python hg = hgraph('example.hg') ``` -------------------------------- ### Create Empty Hypergraph Database Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/cli.md Use the 'create' command to initialize an empty hypergraph database. Specify the database file path using the --hg argument. ```bash graphbrain --hg create ``` -------------------------------- ### Initialize Graphbrain environment Source: https://github.com/graphbrain/graphbrain-archive/blob/master/notebooks/hypergraph.ipynb Imports necessary modules for hypergraph operations and notebook integration. ```python from graphbrain import * from graphbrain.notebook import * from graphbrain.parsers import * ``` -------------------------------- ### Configure Boost.lib Project Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/backends.md Modify the 'project-config.jam' file to specify your Visual Studio version and the path to 'cl.exe'. Set 'keep-going' to false to stop on the first error. ```jam $ import option ; $ using msvc : 14.1 : ‘E: \VS2017\VC\Tools\MSVC\14.1-.250117\bin\HostX64\x64\cl.exe’ ; $ option.set keep-going : false ; ``` -------------------------------- ### Create Virtual Environment Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/installation.md Commands to create and activate a virtual environment to isolate dependencies. ```bash $ virtualenv -p venv ``` ```bash $ python3 -m venv venv ``` ```bash $ source venv/bin/activate $ pip install graphbrain ``` -------------------------------- ### Create a New Hypergraph Database via CLI Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Initializes a new GraphBrain hypergraph database file using the command-line interface. This is the first step before populating the database with data. ```bash graphbrain --hg knowledge.db create ``` -------------------------------- ### SH Notation: Specifier Type Example Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notation.md Specifies relations, such as conditions or time, using the 'S' type. This is a non-atomic type. ```default (in/T 1976/C) ``` -------------------------------- ### Create a parser and parse a sentence Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/parsing.md Initializes an English parser and extracts the main hyperedge from the parse results. Note that initialization may take 10-20 seconds to load language models. ```default >>> from graphbrain.parsers import create_parser >>> parser = create_parser(lang='en') >>> parse_results = parser.parse('Einstein first published the theory of relativity in 1905') >>> parse_results['parses'][0]['main_edge'] ((first/M/en published/Pd.sox.>> hg.degree('alice/C') 2 >>> hg.deep_degree('alice/C') 3 ``` -------------------------------- ### Set LevelDB.lib Properties Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/backends.md Configure the project properties in Visual Studio for LevelDB.lib. Ensure the configuration type is set to LIB, define the preprocessor definitions, and specify the additional library directory for Boost. ```plaintext • project – properties – configuration properties – configuration type: *LIB* • configuration properties – C/C++ - General – preprocessor – preprocessor definition: *LEVELDB_PLATFORM_WINDOWS;OS_WIN; WIN32* • linker – general – additional library directory: *E:LIBboost64stagelib* (use your own path) ``` -------------------------------- ### Batch Operations with `hopen()` Context Manager Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt This section explains how to use the `hopen()` context manager for efficient batch operations on hypergraph databases, ensuring operations are wrapped in a transaction. ```APIDOC ## Batch Operations with `hopen()` Context Manager ### Description The `hopen()` context manager enables efficient batch operations when adding large numbers of hyperedges by wrapping operations in a database transaction. ### Method `hopen(database_path)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from graphbrain import hopen, hedge # Efficient batch insertion using context manager edges_to_add = [ '(likes/P alice/C music/C)', '(likes/P bob/C sports/C)', '(knows/P alice/C bob/C)', '(works_at/P alice/C (tech/M company/C))', '(studies/P bob/C mathematics/C)' ] with hopen('batch_example.db') as hg: for edge_str in edges_to_add: hg.add(edge_str) # Operations within the context are batched hg.add('(friends/P alice/C bob/C)') hg.set_attribute('alice/C', 'role', 'engineer') # Database is automatically closed after the with block # Transaction is committed efficiently ``` ### Response #### Success Response (200) - **Database Transaction**: Operations within the `with` block are batched and committed upon exiting the block. #### Response Example ```json { "batch_operation_status": "completed", "database_path": "batch_example.db" } ``` ``` -------------------------------- ### GraphBrain CLI Usage Overview Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/cli.md This displays the general usage and available arguments for the GraphBrain command-line interface. It outlines positional and optional arguments for various commands. ```bash usage: graphbrain [-h] [--col COL] [--corefs] [--hg HG] [--indir INDIR] [--infile INFILE] [--lang LANG] [--outfile OUTFILE] [--parser PARSER] [--sequence SEQUENCE] [--url URL] command positional arguments: command command to execute optional arguments: -h, --help show this help message and exit --col table column --corefs perform coreference resolution --hg HG hypergraph db --indir INDIR input directory --infile INFILE input file --lang LANG language --outfile OUTFILE output file --parser PARSER parser --sequence SEQUENCE sequence name --url URL url ``` -------------------------------- ### Configure LevelDB Project in Visual Studio Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/backends.md When creating a new Visual Studio project for LevelDB, specify the project type as LIB, set the preprocessor definitions, and add the include search paths for LevelDB source and headers. ```plaintext • file – new – project from existing code • choose the type of project: *Visual C++* • project file location: the directory of *LevelDB* • project name: *LevelDB* • project type: *LIB* • preprocessor definition: *LEVELDB_PLATFORM_WINDOWS;OS_WIN; WIN32* • include search path: *E:LIBleveldb-windows;E:LIBleveldb-windowsinclude* (the directory of *LevelDB* and its *include*) • click *finish* ``` -------------------------------- ### Initialize a Graphbrain parser Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/tutorials/parsing-a-sentence.md Creates a parser instance for the English language. Note that initialization may take time due to loading language models. ```python from graphbrain.parsers import * parser = create_parser(lang='en') ``` -------------------------------- ### Working with Hyperedge Sequences Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/hypergraph-operations.md This section describes how to organize hyperedges into ordered sequences, add them to sequences, and retrieve sequences and their elements. ```APIDOC ## Working with Hyperedge Sequences ### Description This API provides functionality to organize hyperedges into ordered sequences, which is useful for maintaining the order of elements, such as sentences from a text. Hyperedges can be added to the end of a sequence identified by a string label. ### Method `add_to_sequence(sequence_label, hyperedge)` ### Endpoint N/A (Method call within the hypergraph object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (parameters are passed directly to the method) ### Parameters for `add_to_sequence` - **sequence_label** (string) - Required - The label identifying the sequence. - **hyperedge** (string) - Required - The hyperedge to add to the sequence. ### Request Example ```python hg.add_to_sequence('sentences', '(is/P this/C (the/M (first/M sentence/C)))') ``` ### Response #### Success Response (Implicit) A new hyperedge is created, assigning the provided hyperedge to the specified sequence at the next available position. A special `seq/P/.` edge is created or updated. #### Response Example ``` (seq/P/. sentences 0 (is/P this/C (the/M (first/M sentence/C)))) ``` ### Sequence Attributes #### Description A special hyperedge `(seq_attrs/P/. sequence_label)` is created for each sequence to store attributes, such as the current size of the sequence. #### Method `sequences()` ### Description Returns a generator for all the sequences contained in the hypergraph. ### Request Example ```python list(hg.sequences()) ``` ### Response Example ``` ['sentences'] ``` #### Method `sequence(sequence_label)` ### Description Provides a generator for all the hyperedges contained in a given sequence, in order. ### Parameters - **sequence_label** (string) - Required - The label of the sequence to retrieve. ### Request Example ```python hg.add_to_sequence('sentences', '(is/P this/C (the/M (second/M sentence/C)))') hg.add_to_sequence('sentences', '(is/P this/C (the/M (third/M sentence/C)))') list(hg.sequence('sentences')) ``` ### Response Example ``` [(is/P this/C (the/M (first/M sentence/C))), (is/P this/C (the/M (second/M sentence/C))), (is/P this/C (the/M (third/M sentence/C)))] ``` ``` -------------------------------- ### Render Hyperedges with show() Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/tutorials/parsing-a-sentence.md Use the `show()` function to render hyperedges in a more readable format within notebooks. This replaces the default `print()` output for better visualization. ```python show(edge) ``` -------------------------------- ### Get Edges Containing a Specific Hyperedge Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Retrieves all edges that directly connect to a given hyperedge. Useful for exploring immediate neighborhood relationships in the graph. ```python from graphbrain.hypergraph import hg, hedge star = list(hg.star(hedge('berlin/C'))) print(f"Berlin appears in {len(star)} edges:") for edge in star: print(f" {edge}") ``` -------------------------------- ### Perform Batch Operations Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Use the hopen() context manager to wrap multiple database operations into a single transaction for improved performance. ```python from graphbrain import hopen, hedge # Efficient batch insertion using context manager edges_to_add = [ '(likes/P alice/C music/C)', '(likes/P bob/C sports/C)', '(knows/P alice/C bob/C)', '(works_at/P alice/C (tech/M company/C))', '(studies/P bob/C mathematics/C)' ] with hopen('batch_example.db') as hg: for edge_str in edges_to_add: hg.add(edge_str) # Operations within the context are batched hg.add('(friends/P alice/C bob/C)') hg.set_attribute('alice/C', 'role', 'engineer') # Database is automatically closed after the with block # Transaction is committed efficiently ``` -------------------------------- ### Visualize Hyperedge with show() Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notebooks.md Use the show() function for an indented visualization with syntax highlighting. It's suitable for general hyperedge representation in notebooks. ```python from graphbrain.notebook import * show('((first/M published/P.sox) einstein/C (the/M (of/B theory/C relativity/C)) (in/T 1905/C))') ``` -------------------------------- ### Derive Taxonomy - Modifier Defined Concepts Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/cli.md This example demonstrates deriving a taxonomy by defining a concept with modifiers. It shows how 'black cat' is recognized as a type of 'cat'. ```default (type_of/P/. (black/Ma cat/Cc.s) cat/Cc.s) ``` -------------------------------- ### Batch Hyperedge Insertion Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/hypergraph-operations.md Use the hopen context manager to optimize performance when adding large numbers of edges. ```python with hopen('example.db') as hg: for edge in large_edge_list: hg.add(edge) ``` -------------------------------- ### GraphBrain Python: Predicate Argument Roles Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Access and modify argument roles for predicate atoms. Use 'argroles()' to get current roles and 'replace_argroles()' to change them. ```python from graphbrain import hedge # Access predicate argument roles pred = hedge('likes/Pd.so') print(pred.argroles()) # 'so' (subject, object) # Replace argument roles new_pred = pred.replace_argroles('sox') print(new_pred) # likes/Pd.sox ``` -------------------------------- ### Get Hyperedge Degree Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/hypergraph-operations.md Obtain the degree of a hyperedge using the `degree()` method. This method accepts string representations of hyperedges and returns 0 for non-existent hyperedges. ```python >>> from graphbrain import * >>> hg = hgraph('example.db') >>> hg.degree('alice/C') 0 ``` ```python >>> hg.add('(in/B alice/C wonderland/C)') (in/B alice/C wonderland/C) >>> hg.degree('alice/C') 1 >>> hg.degree('(in/B alice/C wonderland/C)') 0 >>> hg.add('(reads/P john/C (in/B alice/C wonderland/C))') (reads/P john/C (in/B alice/C wonderland/C)) >>> hg.degree('(in/B alice/C wonderland/C)') 1 >>> hg.add('(plays/P alice/C chess/C)') (plays/P alice/C chess/C) >>> hg.degree('alice/C') 2 ``` -------------------------------- ### Distinguish Atoms with Subparts Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notation.md Add subparts to namespaces to distinguish atoms that have different meanings but would otherwise correspond to the same string. This example distinguishes two 'cambridge' atoms. ```default cambridge/Cp.s/en.1 ``` ```default cambridge/Cp.s/en.2 ``` -------------------------------- ### Hyperedge Visualization with show() Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notebooks.md The show() function produces an indented visualization with syntax highlighting according to hyperedge type. It accepts an optional 'style' argument ('indented' or 'line'). ```APIDOC ## show() ### Description Produces an indented visualization with syntax highlighting according to hyperedge type. ### Method N/A (Function call within a notebook) ### Endpoint N/A (Function call within a notebook) ### Parameters #### Arguments - **edge_string** (string) - Required - The hyperedge to visualize as a string. - **style** (string) - Optional - The layout style. Possible options are "indented" (default) and "line". ### Request Example ```python from graphbrain.notebook import show show('((first/M published/P.sox) einstein/C (the/M (of/B theory/C relativity/C)) (in/T 1905/C))', style='indented') ``` ### Response N/A (Visual output within a notebook) ``` -------------------------------- ### Create natural language parser Source: https://github.com/graphbrain/graphbrain-archive/blob/master/notebooks/hypergraph.ipynb Instantiates a parser for the specified language. ```python parser = create_parser(lang='en') ``` -------------------------------- ### Create Parser with Lemmas Enabled Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/parsing.md Demonstrates how to create a GraphBrain parser instance with lemma extraction enabled for a specific language. Ensure the `lemmas` parameter is set to `True`. ```python from graphbrain.parsers import create_parser parser = create_parser(lang='en', lemmas=True) ``` -------------------------------- ### Get Ego Network of a Hyperedge Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Retrieves the ego network for a given hyperedge, which includes all atoms directly connected to it. This provides a localized view of the graph around a specific node. ```python from graphbrain.hypergraph import hg, hedge ego = hg.ego('berlin/C') print(f"Ego network: {ego}") ``` -------------------------------- ### Import Notebook Utilities Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/tutorials/parsing-a-sentence.md Import specific utility functions for working with notebooks in Graphbrain. These utilities enhance the notebook experience. ```python from graphbrain.notebook import * ``` -------------------------------- ### GraphBrain CLI: Import Hypergraph Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Import a hypergraph from a JSON file using the 'import' command. ```bash graphbrain --hg knowledge.db --infile backup.json import ``` -------------------------------- ### Add and Verify Hyperedges Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/hypergraph-operations.md Add hyperedges to the database and verify their existence or primary status. ```python hg.add(edge) ``` ```python >>> hg.exists(edge) True ``` ```python >>> hg.exists(edge[1]) True ``` ```python >>> hg.is_primary(edge) True >>> hg.is_primary(edge[1]) False ``` ```python >>> moon = hedge('(of/B.ma moon/C jupiter/C)') >>> hg.add(moon, primary=False) (of/B.ma moon/C jupiter/C) >>> hg.is_primary(moon) False ``` -------------------------------- ### Parse Web Page Content via CLI Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Leverages the GraphBrain CLI to fetch content from a given URL, parse it into hyperedges, and store it in the hypergraph database. Supports generic URL parsing. ```bash graphbrain --hg knowledge.db --url "https://example.com/article" url ``` -------------------------------- ### GraphBrain CLI: Claim Detection Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Run the claim detection processor on a sequence of articles. ```bash graphbrain --hg knowledge.db --sequence articles claims ``` -------------------------------- ### Explore Neighbors with star() Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt The star() method retrieves all hyperedges that contain a specific hyperedge, facilitating neighborhood exploration. ```python from graphbrain import hgraph, hedge hg = hgraph('star_example.db') # Build a small knowledge graph hg.add('(is/P berlin/C (capital/B germany/C))') hg.add('(is/P berlin/C city/C)') hg.add('(located_in/P berlin/C europe/C)') hg.add('(population/P berlin/C (3.6/M million/C))') hg.add('(visited/P alice/C berlin/C)') ``` -------------------------------- ### Import Hypergraph from JSON Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/cli.md Imports data into a hypergraph database from a JSON file. Specify the database with --hg and the input file with --infile. ```bash graphbrain --hg --infile import ``` -------------------------------- ### Add and Iterate Through Hyperedge Sequences Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Demonstrates how to add hyperedges to a named sequence in a hypergraph database and then iterate through the sequence in the order edges were added. Useful for preserving document structure. ```python from graphbrain import hgraph, hedge hg = hgraph('sequence_example.db') hg.add_to_sequence('chapter1', '(is/P this/C (the/M (first/M sentence/C)))') hg.add_to_sequence('chapter1', '(is/P this/C (the/M (second/M sentence/C)))') hg.add_to_sequence('chapter1', '(is/P this/C (the/M (third/M sentence/C)))') print("Chapter 1 sentences:") for edge in hg.sequence('chapter1'): print(f" {edge}") print("All sequences:", list(hg.sequences())) ``` -------------------------------- ### GraphBrain CLI: Taxonomy Processor Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Run the taxonomy processor to derive type hierarchies. ```bash graphbrain --hg knowledge.db taxonomy ``` -------------------------------- ### Manual Parser Testing Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/internals/create-parser.md Manually test the full parser using an interactive script. Input is a sentence file, and output is a CSV file of test results. Use a corpus different from the training data for meaningful results. ```bash $ python -m graphbrain.scripts.manual-parser-test --parser .parser_xx.ParserXX --infile parser-training-data/xx/sentences/manual-test-sentences.txt --outfile parser-training-data/de/manual-test-results.csv ``` -------------------------------- ### GraphBrain CLI: Conflict Detection Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Run the conflict detection processor on a sequence of news. ```bash graphbrain --hg knowledge.db --sequence news conflicts ``` -------------------------------- ### GraphBrain CLI: Actor Identification Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Run the actor identification processor. ```bash graphbrain --hg knowledge.db actors ``` -------------------------------- ### Visualize Hyperedge with blocks() Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notebooks.md Generate a block diagram visualization using the blocks() function. This function uses colors to distinguish hyperedge types and accepts arguments to control detail levels. ```python blocks('((first/M published/P.sox) einstein/C (the/M (of/B theory/C relativity/C)) (in/T 1905/C))') ``` -------------------------------- ### Creating and Manipulating Hyperedges with `hedge()` Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt This section details how to create and interact with hyperedge objects using the `hedge()` function. Hyperedges represent structured semantic information. ```APIDOC ## Creating and Manipulating Hyperedges with `hedge()` ### Description The `hedge()` function creates hyperedge objects from string representations using Semantic Hypergraph notation. Hyperedges are recursive structures where the first element is a connector followed by arguments, and each element has a type (C=concept, P=predicate, M=modifier, B=builder, T=trigger, J=conjunction, R=relation, S=specifier). ### Method `hedge(string_representation)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from graphbrain import hedge # Create a simple relation hyperedge edge = hedge('(plays/P.so mary/C chess/C)') # Hyperedges are tuple-like sequences print(edge[0]) # plays/P.so (the connector) print(edge[1]) # mary/C (first argument) print(edge[2]) # chess/C (second argument) # Check if hyperedge is atomic print(edge.atom) # False (it's a compound hyperedge) print(edge[1].atom) # True (mary/C is an atom) # Get hyperedge type print(edge.type()) # 'R' (relation, inferred from predicate connector) print(edge[0].type()) # 'P' (predicate) print(edge[1].type()) # 'C' (concept) # Create nested hyperedge nested = hedge('(is/Pd.sc (the/Md sky/Cc) blue/Ca)') print(nested.label()) # "the sky is blue" # Get all atoms in a hyperedge atoms = nested.atoms() print(atoms) # {is/Pd.sc, the/Md, sky/Cc, blue/Ca} # Calculate hyperedge depth and size print(nested.depth()) # 2 (maximum nesting level) print(nested.size()) # 4 (total number of atoms) # Extract argument roles from predicate print(nested[0].argroles()) # 'sc' (subject, complement) ``` ### Response #### Success Response (200) - **edge object**: A hyperedge object representing the parsed string. #### Response Example ```json { "edge_representation": "(plays/P.so mary/C chess/C)" } ``` ``` -------------------------------- ### Define a basic wildcard pattern Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/patterns.md Use the * wildcard to match any hyperedge in a pattern. ```default (plays/P * *) ``` -------------------------------- ### Create a Hyperedge Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/hypergraph-operations.md Use the hedge function to instantiate a Hyperedge object from a string representation. ```python from graphbrain import hedge edge = hedge('(plays/P.so mary/C chess/C)') ``` -------------------------------- ### Search Hyperedges Using Patterns Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/hypergraph-operations.md Utilize the `search()` method with patterns to find hyperedges. The wildcard `*` matches any hyperedge, enabling flexible searches. ```python >>> list(hg.search('(of/B.ma * *)')) [(of/B.ma moon/C jupiter/C), (of/B.ma moon/C saturn/C)] ``` -------------------------------- ### Creating and Managing Hypergraph Databases with `hgraph()` Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt This section covers the creation and management of persistent hypergraph databases using the `hgraph()` function. It includes adding, checking existence, removing, and querying hyperedges and their attributes. ```APIDOC ## Creating and Managing Hypergraph Databases with `hgraph()` ### Description The `hgraph()` function creates or opens a persistent hypergraph database where hyperedges can be stored, indexed, and queried. The database uses SQLite by default and supports files with `.db`, `.sqlite`, or `.sqlite3` extensions. ### Method `hgraph(database_path)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from graphbrain import hgraph, hedge # Create/open a hypergraph database hg = hgraph('knowledge.db') # Add hyperedges to the database edge = hedge('(plays/P.so alice/C chess/C)') hg.add(edge) # Check if edge exists print(hg.exists(edge)) # True print(hg.exists(edge[1])) # True (alice/C was added recursively) # Primary vs non-primary edges print(hg.is_primary(edge)) # True (directly added) print(hg.is_primary(edge[1])) # False (added recursively) # Add with count tracking hg.add('(likes/P bob/C pizza/C)', count=True) hg.add('(likes/P bob/C pizza/C)', count=True) print(hg.get_int_attribute('(likes/P bob/C pizza/C)', 'count')) # 2 # Remove hyperedges hg.remove(edge) hg.remove('(likes/P bob/C pizza/C)', deep=True) # Also remove subedges # Set and get attributes hg.add('(wrote/P einstein/C (theory/C relativity/C))') hg.set_attribute('einstein/C', 'birth_year', 1879) hg.set_attribute('einstein/C', 'field', 'physics') print(hg.get_int_attribute('einstein/C', 'birth_year')) # 1879 print(hg.get_str_attribute('einstein/C', 'field')) # 'physics' # Get edge degrees (connectivity measure) hg.add('(is/P einstein/C genius/C)') print(hg.degree('einstein/C')) # 2 (appears in 2 edges) print(hg.deep_degree('einstein/C')) # Includes nested connections ``` ### Response #### Success Response (200) - **hypergraph object**: A hypergraph object representing the database connection. #### Response Example ```json { "database_status": "connected", "database_path": "knowledge.db" } ``` ``` -------------------------------- ### Annotate Sentences to Generate Parser Training Data Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/internals/create-parser.md This script annotates extracted sentences to create a dataset for training the parser. It requires the parser class, an input directory of sentences, and an output file for the parsed data. ```bash $ python -m graphbrain.scripts.generate-parser-training-data --parser .parser_xx.ParserXX --indir parser-training-data/de/sentences --outfile parser-training-data/xx/sentence-parses.json ``` -------------------------------- ### Query Hypergraphs with match() Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt The match() method retrieves both hyperedges and their variable bindings from the database. Also supports sequence-based matching. ```python from graphbrain import hgraph, hedge hg = hgraph('match_example.db') # Add sample relations hg.add('(is/Pd.cs blue/Ca (the/M sky/C))') hg.add('(is/Pd.sc (the/M sky/C) blue/Ca)') hg.add('(is/Pd.sc (the/M ocean/C) vast/Ca)') hg.add('(likes/P alice/C (italian/M food/C))') # Match with variables extracts structured data results = list(hg.match('(is/P.{sc} OBJ/C PROPERTY)', strict=False)) for edge, matches in results: for match in matches: print(f"Edge: {edge}") print(f" Object: {match['OBJ']}") print(f" Property: {match['PROPERTY']}") # Output: # Edge: (is/Pd.cs blue/Ca (the/M sky/C)) # Object: (the/M sky/C) # Property: blue/Ca # Edge: (is/Pd.sc (the/M sky/C) blue/Ca) # Object: (the/M sky/C) # Property: blue/Ca # ... # Match against a specific sequence hg.add_to_sequence('facts', '(is/P earth/C round/C)') hg.add_to_sequence('facts', '(is/P water/C wet/C)') results = list(hg.match_sequence('facts', '(is/P THING PROP)')) for edge, matches in results: print(f"{matches[0]['THING']} is {matches[0]['PROP']}") ``` -------------------------------- ### Listing Sequences Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/hypergraph-operations.md Retrieve all sequence labels present in the hypergraph using sequences(). ```default >>> list(hg.sequences()) [sentences] ``` -------------------------------- ### Search Hypergraphs with Wildcards Source: https://context7.com/graphbrain/graphbrain-archive/llms.txt Use the search() method to find hyperedges matching specific patterns. Wildcards include * for any edge, . for atoms, (*) for non-atomic edges, and ... for open-ended patterns. ```python from graphbrain import hgraph, hedge hg = hgraph('search_example.db') # Populate with sample data hg.add('(plays/P.so alice/C chess/C)') hg.add('(plays/P.so bob/C tennis/C)') hg.add('(plays/P.sox carol/C piano/C (at/T home/C))') hg.add('(likes/P alice/C (red/M apples/C))') # Search with wildcards # * matches any hyperedge (atomic or non-atomic) results = list(hg.search('(plays/P * *)')) print(results) # [(plays/P.so alice/C chess/C), (plays/P.so bob/C tennis/C)] # . matches only atoms results = list(hg.search('(likes/P . *)')) print(results) # [(likes/P alice/C (red/M apples/C))] # (*) matches only non-atomic edges results = list(hg.search('(likes/P * (*))')) print(results) # [(likes/P alice/C (red/M apples/C))] # ... allows additional arguments results = list(hg.search('(plays/P * * ...)')) print(results) # Includes edge with (at/T home/C) specifier # Non-strict search (matches more general patterns) hg.add('(plays/Pd.so alice/Cp.s chess/Cc.s)') results = list(hg.search('(plays/P alice/C *)', strict=False)) print(results) # Matches despite different subtypes # Count matching edges count = hg.count('(plays/P * *)') print(f"Found {count} playing relations") ``` -------------------------------- ### Exclude LevelDB Test and POSIX Files Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/backends.md In the Solution Explorer, exclude files that end with '_test.cc' or '_bench.cc', as well as POSIX-specific port files, to ensure a clean build for Windows. ```plaintext • files ends with *\_test.cc* and *\_bench.cc* • *port/port_android.cc* • *port/port_posix.cc* • *util/env_posix.cc* ``` -------------------------------- ### Hyperedge Visualization with blocks() Source: https://github.com/graphbrain/graphbrain-archive/blob/master/docs/source/manual/notebooks.md The blocks() function produces a block diagram, using colors to distinguish hyperedge types. It accepts optional arguments to control the level of detail. ```APIDOC ## blocks() ### Description Produces a block diagram visualization, using colors to distinguish hyperedge types. ### Method N/A (Function call within a notebook) ### Endpoint N/A (Function call within a notebook) ### Parameters #### Arguments - **edge_string** (string) - Required - The hyperedge to visualize as a string. - **subtypes** (boolean) - Optional - Controls the level of detail for subtypes (default: False). - **argroles** (boolean) - Optional - Controls the level of detail for argument roles (default: True). - **namespaces** (boolean) - Optional - Controls the level of detail for namespaces (default: False). ### Request Example ```python from graphbrain.notebook import blocks blocks('((first/M published/P.sox) einstein/C (the/M (of/B theory/C relativity/C)) (in/T 1905/C))', subtypes=True, argroles=False) ``` ### Response N/A (Visual output within a notebook) ```