mevis

This is the package mevis.

Its main purpose is to provide interactive AtomSpace visualizations for the OpenCog project. Beyond that it comes with some inspection, filtering, conversion, layouting and I/O capabilities.

plot

plot(data, backend='vis', layout_method=None, layout_scale_x=1.0, layout_scale_y=1.0, layout_mirror_x=False, layout_mirror_y=True, layout_center_x=True, layout_center_y=True, filter_target=None, filter_context='atom', filter_mode='include', graph_annotated=True, graph_directed=True, node_label=None, node_color=None, node_opacity=None, node_size=None, node_shape=None, node_border_color=None, node_border_size=None, node_label_color=None, node_label_size=None, node_hover=None, node_click=None, node_image=None, node_properties=None, edge_label=None, edge_color=None, edge_opacity=None, edge_size=None, edge_label_color=None, edge_label_size=None, edge_hover=None, edge_click=None, **kwargs)[source]

Create a graph visualization of a given AtomSpace, list of Atoms or NetworkX graph.

Parameters
  • data (Atomspace, list of Atoms, NetworkX Graph, NetworkX DiGraph) – The input data that shall be visualized. If it is already a NetworkX Graph or NetworkX DiGraph, no conversion, layouting and filtering steps are performed, which means that most arguments have no effect.

  • backend (str) – Library used for the graph visualization.

    Possible values:

    • "d3": Uses d3.js to generate a 2d plot based on the HTML SVG element, which is vector graphics that can be exported as SVG, PNG or JPG.

    • "vis": Uses vis.js to generate a 2d plot based on the HTML Canvas element, which is raster graphics that can be exported as PNG or JPG.

    • "three": Uses three.js to generate a 3d plot based on HTML WebGL element, which is raster graphics that can be exported as PNG or JPG.

  • filter_[…] – See documentation of the filter() function.

  • graph_[…], node_[…], edge_[…] – See documentation of the convert() function.

  • layout_[…] – See documentation of the layout() function.

  • kwargs – Other keyword arguments are forwarded to the plotting method. See documentation of gravis. Various aspects of the graph visualizations can be changed interactively by a user in the HTML menus, but often it is desirable to set suitable initial values, e.g. edge_curvature=0.2 for curved instead of straight edges.

Returns

fig (Figure) – A figure object from gravis that can be used for displaying or exporting the plot.

Note

Pre-processing steps can be triggered by providing values for the arguments filter_target or layout_method and modified by providing values for arguments like node_color and node_size.

  1. Filter: Reduce the AtomSpace to a list of relevant Atoms.

  2. Convert: Transform the AtomSpace to a NetworkX graph and add annotations to its nodes and edges. By providing arguments like node_size it is possible to translate information such as truth values into visual properties such as node size, color or shape.

  3. Layout: Calculate x and y coordinates to better recognize structures in the AtomSpace such as hierarchies and clusters.

These steps are implemented by the functions filter(), convert() and layout(). They are called implicitely by this plotting function with default arguments. Alternatively, they can be called explicitly by a user on an AtomSpace for finer control. The result can then be fed into this plotting function.

inspect

inspect(data, count_details=True)[source]

Inspect an AtomSpace or graph by counting elements.

Parameters
  • data (AtomSpace, list of Atoms, NetworkX Graph, NetworkX DiGraph)

  • count_details (bool) – If True, some detailed properties of the AtomSpace or Graph are counted.

Returns

counts (dict) – A dictionary of element/count pairs.

  • If AtomSpace or list of Atoms: A dictionary that contains counts of Atoms, Nodes, Links and another dictionary with counts for each Atom type.

  • If NetworkX Graph or NetworkX DiGraph: A dictionary that contains counts of nodes, edges and annotations.

filter

filter(data, target, context='atom', mode='include')[source]

Apply a filter to an Atomspace or list of Atoms and return a list of selected Atoms.

Parameters
  • data (Atomspace, list of Atoms) – The given Atomspace or list of Atoms that is filtered and thereby reduced to a shorter list of Atoms.

  • target (str, int, Atom, list, Callable) – The targets that are selected by this filtering function.

    Possible types and their meaning:

    • str: A string that is matched against .name and .type_name of each Atom. Capitalization is ignored.

      Examples:

      • target="andlink" will include all Atoms of type AndLink.

      • target="$1" will include all Atoms with name "$1".

    • int: An OpenCog Atom type that is matched against .type of each Atom.

      Examples:

      • target=opencog.atomspace.types.OrLink selects all Atoms of type OrLink.

    • Atom: An Atom that is used as it is.

      Examples:

      • target=list(atomspace)[4] selects the fifth Atom in the AtomSpace.

    • list: A list of str, int and/or Atom. The types can be mixed freely.

      Examples:

      • target=["andlink", "OrLink"] selects all Atoms of type AndLink and OrLink.

      • target=["notlink", "$1", opencog.atomspace.types.OrLink, list(atomspace)[4]] selects all Atoms of type NotLink, all Atoms with name "$1", all Atoms of type OrLink, and the fifth Atom in the AtomSpace.

    • Callable: A function that gets an Atom as input and needs to return True or False to indicate whether the Atom is selected or not.

      Examples:

      • target=lambda atom: atom.is_link() selects all Atoms that are Links

      • target=lambda atom: atom.name.startswith("$") selects all Atoms that have a name starting with $.

  • context (str, tuple) – The context of the selection of Atoms to which it shall be expanded.

    Possible values:

    • atom: Only the Atoms specified by target are selected.

    • in: The Atoms specified by target and all their incoming neighbors are selected.

    • out: The Atoms specified by target and all their outgoing neighbors are selected.

    • both: The Atoms specified by target and all their incoming and outgoing neighbors are selected. This is also known as neighborhood in graph theory or egocentric network in social network analysis.

    • in_tree: The Atoms specified by target and all their incoming neighbors are selected, which is repeated until nothing can be added anymore. This is also known as in-tree or anti-arborescence in graph theory.

    • out_tree: The Atoms specified by target and all their outgoing Atoms are selected, which is repeated until nothing can be added anymore. This is also known as out-tree or arborescence in graph theory.

    • (context, size): In the case of in, out and both the context can come with a size, which means how often the selected Atoms are expanded in the chosen way.

      Examples:

      • ("out", 2) means that the selected Atoms are expanded twice by their outgoing Atoms, instead of just once when using out.

      • ("in", 3) means that the selected Atoms are expanded thrice by their incoming Atoms, instead of just once when using in.

      • ("both", 2) means that the selected Atoms are expanded twice by their incoming and outgoing Atoms, instead of just once when using both. Note that the result can be and usually is different than the combined results from ("in", 2) and ("out", 2), because adding an ingoing neighbor in step 1 and then its outgoing neighbors in step 2 (or vice versa) captures more Atoms.

  • mode (str) – The selection of Atoms can be the result of the filtering, but it is also possible to exclude those Atoms and instead return all other ones.

    Possible values:

    • include: The selection is included in the result.

    • exclude: The selection is excluded from the result. Everything else is included.

Returns

atoms (list of Atoms)

Note

Chaining is possible, which means that the output of a filter application can be used as input for another one. This allows to combine different targets, contexts and modes by performing a sequence of filtering steps. Example:

import mevis as mv

atomspace = mv.load('moses.scm')
atoms = mv.filter(atomspace, target="AndLink", context="out-tree", mode="include")
atoms = mv.filter(atoms, target="PredicateNode", context="atom", mode="exclude")
mv.plot(atoms, 'vis', 'dot')

The first line includes Atoms of type AndLink and their maximally expanded outgoing neighborhood. The second line excludes Atoms of type PredicateNode from the previous result.

convert

convert(data, graph_annotated=True, graph_directed=True, node_label=None, node_color=None, node_opacity=None, node_size=None, node_shape=None, node_border_color=None, node_border_size=None, node_label_color=None, node_label_size=None, node_hover=None, node_click=None, node_image=None, node_properties=None, edge_label=None, edge_color=None, edge_opacity=None, edge_size=None, edge_label_color=None, edge_label_size=None, edge_hover=None, edge_click=None)[source]

Convert an Atomspace or list of Atoms to a NetworkX graph with annotations.

Several arguments accept a Callable.

  • In case of node annotations, the Callable gets an Atom as input, which the node represents in the graph. The Callable needs to return one of the other types accepted by the argument, e.g. str or int/float.

  • In case of edge annotations, the Callable gets two Atoms as input, which the edge connects in the graph. The Callable needs to return one of the other types accepted by the argument, e.g. str or int/float.

Several arguments accept a color, which can be in following formats:

  • Name: "black", "red", "green", …

  • Color code

    • 6 digit hex RGB code: "#05ac05"

    • 3 digit hex RGB code: "#0a0" (equivalent to "#00aa00")

Parameters
  • data (Atomspace, list of Atoms) – Input that gets converted to a graph.

  • graph_annotated (bool) – If False, no annotations are added to the graph. This could be used for converting large AtomSpaces quickly to graphs that use less RAM and can be exported to smaller files (e.g. also compressed as gml.gz) for inspection with other tools.

  • graph_directed (bool) – If True, a NetworkX DiGraph is created. If False, a NetworkX Graph is created.

  • node_label (str, Callable) – Set a label for each node, which is shown as text below it.

  • node_color (str, Callable) – Set a color for each node, which becomes the fill color of its shape.

  • node_opacity (float between 0.0 and 1.0) – Set an opacity for each node, which becomes the opacity of its shape.

    Caution: This is only supported by d3.

  • node_size (int, float, Callable) – Set a size for each node, which becomes the height and width of its shape.

  • node_shape (str, Callable) – Set a shape for each node, which is some geometrical form that has the node coordinates in its center.

    Possible values: "circle", "rectangle", "hexagon"

  • node_border_color (str, Callable) – Set a border color for each node, which influences the border drawn around its shape.

  • node_border_size (int, float, Callable) – Set a border size for each node, which influences the border drawn around its shape.

  • node_label_color (str, Callable) – Set a label color for each node, which determines the font color of the text below the node.

  • node_label_size (int, float, Callable) – Set a label size for each node, which determines the font size of the text below the node.

  • node_hover (str, Callable) – Set a hover text for each node, which shows up besides the mouse cursor when hovering over a node.

  • node_click (str, Callable) – Set a click text for each node, which shows up in a div element below the plot when clicking on a node and can easily be copied and pasted.

  • node_image (str, Callable) – Set an image for each node, which appears within its shape.

    Possible values:

    • URL pointing to an image

    • Data URL encoding the image

  • node_properties (str, dict, Callable) – Set additional properties for each node, which may not immediately be translated into a visual element, but can be chosen in the data selection menu in the interactive HTML visualizations to map them on some plot element. These properties also appear when exporting a graph to a file in a format such as GML and may be recognized by external visualization tools. Note that a Callable needs to return a dict in this case, and each key becomes a property, which is equivalent to the other properties such as node_size and node_color.

    Special cases:

    • node_properties="tv" is a shortcut for using a function that returns {"mean": atom.tv.mean, "confidence": atom.tv.confidence}

    • Keys "x", "y" and "z" properties are translated into node coordinates.

    Examples:

    • dict(x=0.0): This fixes the x coordinate of each node to 0.0, so that the JavaScript layout algorithm does not influence it, but the nodes remain free to move in the y and z directions.

    • lambda atom: dict(x=2.0) if atom.is_node() else None: This fixes the x coordinate of each Atom of type Node to 2.0 but allows each Atom of type Link to move freely.

    • lambda atom: dict(y=-len(atom.out)*100) if atom.is_link() else dict(y=0) This fixes the y coordinates of Atoms at different heights. Atoms of type Node are put at the bottom and Atoms of type Link are ordered by the number of their outgoing edges. The results is a hierarchical visualization that has some similarity with the “dot” layout.

    • lambda atom: dict(x=-100) if atom.is_node() else dict(x=100): This fixes the x coordinate of Node Atoms at -100 and of Link Atoms at 100. The results is a visualization with two lines of nodes that has some similarity with the “bipartite” layout.

  • edge_label (str, Callable) – Set a label for each edge, which becomes the text plotted in the middle of the edge.

  • edge_color (str, Callable) – Set a color for each edge, which becomes the color of the line representing the edge.

  • edge_opacity (int, float, Callable) – Set an opacity for each edge, which allows to make it transparent to some degree.

  • edge_size (int, float, Callable) – Set a size for each edge, which becomes the width of the line representing the edge.

  • edge_label_color (str, Callable) – Set a color for each edge label, which becomes the color of the text in the midpoint of the edge.

  • edge_label_size (int, float, Callable) – Set a size for each edge label, which becomes the size of the text in the midpoint of the edge.

  • edge_hover (str, Callable)

  • edge_click (str, Callable)

Returns

graph (NetworkX Graph or DiGraph) – Whether an undirected or directed graph is created depends on the argument “directed”.

layout

layout(data, method='neato', scale_x=1.0, scale_y=1.0, mirror_x=False, mirror_y=True, center_x=True, center_y=True, **kwargs)[source]

Calculate a layout for a given NetworkX graph with a chosen method.

Parameters
  • data (NetworkX Graph, NetworkX DiGraph, AtomSpace, list of Atoms) – Input that gets augmented by a layout in form of x and y coordinates for each node.

    If the data is an AtomSpace or list of Atoms, it is first converted to a NetworkX graph by implicitely calling convert() with default arguments. Alternatively, it can also be called explicitly by a user on an AtomSpace for finer control. The result can then be fed into this layout function.

  • method (str) – Layout method for calculating node coordinates, e.g. a Graphviz layout engine.

    Possible values:

    • Graphviz layouts

      • "dot": hierarchical layout for directed graphs, see dot

      • "neato": spring model layout for up to 100 nodes, minimizes a global energy function, see neato

      • "twopi": radial layout placing nodes on concentric circles depending on their distance from a root node, see twopi

      • "circo": circular layout, see circo

      • "fdp": spring model layout for larger graphs, reduces forces with the Fruchterman-Reingold heuristic, see fdp

      • "sfdp": multiscale version of fdp for large graphs see sfdp

    • NetworkX layouts

      • bipartite: nodes in two straight lines, see bipartite_layout

      • circular: nodes on a circle, see circular_layout

      • kamada_kawai: using Kamada-Kawai path-length cost-function, see kamada_kawai_layout

      • planar: nodes without edge intersections, fails if the graph is not planar, see planar_layout

      • random: nodes uniformly at random in the unit square, see random_layout

      • shell: nodes in concentric circles, best with nlist defining list of nodes for each shell, see shell_layout

      • spectral: using the eigenvectors of the graph Laplacian, see spectral_layout

      • spiral: nodes in a spiral, see spiral_layout

      • spring: using Fruchterman-Reingold force-directed algorithm, see spring_layout

  • scale_x (int, float) – A number to contract or stretch the layout along the x coordinate.

  • scale_y (int, float) – A number to contract or stretch the layout along the y coordinate.

  • mirror_x (bool) – if True, the x coordinates are inverted.

  • mirror_y (bool) – if True, the y coordinates are inverted.

  • center_x (bool) – if True, the x coordinates are shifted so the extreme values have equal distance to 0.

  • center_y (bool) – if True, the y coordinates are shifted so the extreme values have equal distance to 0.

  • kwargs – Other keyword arguments are forwarded to the layout method.

Returns

graph (NetworkX Graph or NetworkX DiGraph)

References

Note

Graphviz layouts are influenced by graph properties, e.g. whether a graph is directed or undirected, or whether the shapes of nodes are circle or rectangle.

create

create(set_as_default=True)[source]

Create an empty AtomSpace and set it as default.

Parameters

set_as_default (bool) – If True, the newly created AtomSpace is set as default in OpenCog.

References

Returns

atomspace (AtomSpace)

load

load(filepath, method='primitive', verbose=False)[source]

Load an Atomspace from a given filepath with a chosen method.

Parameters
  • filepath (str) – Path of a text file that contains Atomese code.

  • method (str) – Possible values:

    • "basic": uses Scheme code (load "data.scm")

    • "primitive": uses Scheme code (primitive-load "data.scm")

    • "fast": uses Scheme code (load-file "data.scm")

    • "python": uses Python function opencog.utilities.load_file

  • verbose (bool) – if True, a short message is printed about the AtomSpace that was loaded.

References

Returns

atomspace (AtomSpace)

store

store(atomspace, filepath, method='basic', verbose=False, overwrite=False)[source]

Store an Atomspace to a given filepath with a chosen method.

Parameters
  • filepath (str) – Path of a text file that contains Atomese code.

  • method (str) – Possible values:

    • basic: uses Scheme code (export-all-atoms "data.scm")

    • file-storage-node: uses Scheme code (define fsn (FileStorageNode "data.scm"))

      Caution: This command adds a new FileStorageNode to the AtomSpace, which will also appear in the exported file.

  • verbose (bool) – if True, a short message is printed about the AtomSpace that was loaded.

  • overwrite (bool) – If False, a FileExistsError will be raised in case there is already a file with the given filepath. if True, the file will be overwritten.

References

export

export(graph, filepath, overwrite=False)[source]

Export a NetworkX graph in a chosen format.

Parameters
  • graph (NetworkX Graph, NetworkX DiGraph)

  • filepath (str) – Possible file extensions:

    • gml: Export the graph as Graph Modeling Language (GML) file.

    • gml.gz: Export the graph as GML file compressed with gzip.

    • gml.bz2: Export the graph as GML file compressed with bzip2. It takes longer than gzip but produces a bit smaller files.

References