Hypergraph¶
Pathfinder Class¶
- class constrainthg.hypergraph.Pathfinder(target: Node, sources: list, nodes: dict, no_weights: bool = False, memory_mode: bool = False)¶
Bases:
objectObject for searching a path through the hypergraph from a collection of source nodes to a single target node. If the hypergraph is fully constrained and viable, then the result of the search is a singular value of the target node.
- __init__(target: Node, sources: list, nodes: dict, no_weights: bool = False, memory_mode: bool = False)¶
Creates a new Pathfinder object.
- Parameters:
target (Node) – The Node that the Pathfinder will attempt to solve for.
sources (list) – A list of Node objects that have static values for the simulation.
nodes (dict) – A dictionary of nodes taken from the hypergraph as {label : Node}.
no_weights (bool, default=False) – Optional run mode where weights aren’t considered. This speeds up the simulation but prevents model switching.
memory_mode (bool, default=False) – Optional run mode where all encountered TNodes are stored to a list property. Increases memory usage.
Properties¶
- search_counterint
Number of nodes explored.
- explored_edgesdict
Dict counting the number of times edges were processed {label : int}.
- explored_tnodeslist
Dict containing the all TNodes explored during searching, if not running in memory mode.
- edge_resolves_input(parent_t: TNode)¶
Returns True if the edge attempts to resolve the first index of an input.
Note that inputs can be resolved as part of cycles, but only for later indices (2 or greater).
- explore(t: TNode, debug_nodes: list = None, debug_edges: list = None)¶
Discovers all possible routes from the TNode.
- get_edges_to_explore(t: TNode, debug_nodes: list = None) list¶
Finds and orders all edges leading from the node by label.
- log_debugging_report()¶
Prints a debugging report of the search.
- make_parent_tnode(source_tnodes: list, node: Node, edge: Edge)¶
Creates a TNode for the next step along the edge.
- merge_found_values(parent_val, parent_label, source_tnodes: list) dict¶
Merges the values found in the source nodes with the parent node.
- search(min_index: int = 0, debug_nodes: list = None, debug_edges: list = None, search_depth: int = 10000)¶
Searches the hypergraph for a path from the source nodes to the target node. Returns the solved TNode for the target, with a dictionary of found values {label : [Any,]} given by the target.values.
- Parameters:
min_index (int, default=0) – Minimum index of the target node.
debug_nodes (list, optional) – List of nodes to log additional information for.
debug_edges (list, optional) – List of edges to log additional information for.
search_depth (int, default=10000) – Number of TNodes to explore before search is failed.
Hypergraph Class¶
- class constrainthg.hypergraph.Hypergraph(name: str = None, no_weights: bool = False, setup_logger: bool = False, logging_level=None, memory_mode: bool = False)¶
Bases:
objectBuilder class for a hypergraph. See demos for examples on how to use.
Properties¶
- nodesdict
Nodes in the hypergraph, {label : Node}
- edgesdict
Edges in the hypergraph, {label : Edge}
- solved_tnodeslist
List of solved TNodes from a simulation. Only set if run in memory_mode.
- no_weightsbool
Indicates no weights have been given to the edges in the Hypergraph, speeding up processing (but preventing model switching).
- memory_modebool
Indicates whether the TNodes in the Hypergraph should be saved between calls.
- __init__(name: str = None, no_weights: bool = False, setup_logger: bool = False, logging_level=None, memory_mode: bool = False)¶
Initialize a Hypergraph.
- Parameters:
name (str, optional) – Arbitrary name for the Hypergraph.
no_weights (bool, default=False) – Optional run mode where weights aren’t considered. This speeds up the simulation but prevents model switching.
setup_logger (bool, default=False) – Sets up logging in the library (off by default). The logging level can be set by calling Hypergraph.set_logging_level.
logging_level (int | str, optional) – Sets the logging level for the library. Setting the logging level requires an additional logging handler to be passed to logger.getLogger(‘constrainthg’). This can be done at the application level (in the calling script) or automatically by passing setup_logger as True.
memory_mode (bool, default=False) – Store every solved for TNode to the Hypergraph.
- add_edge(sources: dict, target, rel, via=None, index_via=None, weight: float = 1.0, label: str = None, index_offset: int = 0, disposable=None, edge_props=None)¶
Adds an edge to the hypergraph.
- Parameters:
sources (dict{str : Node | Tuple(Node, str)} | list[Node |) – Tuple(Node, str)] | Tuple(Node, str) | Node A dictionary of Node objects forming the source nodes of the edge, where the key is the identifiable label for each source used in rel processing. The Node object may be a Node, or a length-2 Tuple with the second element a string referencing an attribute of the Node to use as the value (a pseudo node).
targets (list | str | Node) – A list of nodes that are the target of the given edge, with the same type as sources. Since each edge can only have one target, this makes a unique edge for each target.
rel (Callable) – A function taking in a value for each source node that returns a single value for the target.
via (Callable, optional) – A function that must be true for the edge to be traversable (viable). Defaults to unconditionally true if not set.
index_via (Callable, optional) – A function that takes in handles of source nodes as inputs in reference to the index of each referenced source node, returns a boolean condition relating the indices of each. Defaults to unconditionally true if not set, meaning any index of source node is valid.
weight (float, default=1.0) – The cost of traversing the edge. Must be positive.
label (str, optional) – A unique identifier for the edge.
index_offset (int, default=0) – Offset to apply to the target once solved for. Akin to iterating to the next level of a cycle.
disposable (list, optional) – A list of source node handles that should not be evaluated for future cyclic executions of the edge. That is, each tnode that corresponds to a handle in disposable is removed from found_tnodes after a successful edge calculation.
edge_props (List(EdgeProperty) | EdgeProperty | str | int, optional) – A list of enumerated types that are used to configure the edge.
- add_node(node=None, *args, **kwargs) Node¶
Creates (if necessary) a Node and inserts into the hypergraph.
Wraps
Hypergraph.insert_nodeandNode.__init__.- Parameters:
node (Node | str, optional) – The node (or node label) to add to the hypergraph. If not provided, then args and kwargs are passed to Node.__init__.
- check_if_logger_setup() bool¶
Checks if a Handler beyond the NullHandler was created for the logger.
- clear()¶
Resets the Hypergraph and removes any saved runs.
- edge_in_cycle(edge: Edge, t: TNode)¶
Returns true if the edge is part of a cycle in the tree rooted at the TNode.
- get_constant_nodes(inputs: list = None)¶
Returns all the constant nodes in the Hypergraph, optionally filtered by nodes not in inputs.
- get_frames() list¶
Returns a list of frames in the Hypergraph.
Each frame is a set of values for the nodes in the Hypergraph, with no more than one value for each node.
- get_join_status(index, num_children)¶
Returns whether or not the node at the given index is part of a hyperedge (join) or specifically the last node in a hyperedge (join_stop) or a singular edge (none)
- print_nodes() str¶
- process_source_nodes(inputs)¶
Processes source nodes for the simulation.
- request_edge_label(requested_label: str = None, source_nodes: list = None) str¶
Generates a unique label for an edge in the hypergraph.
- request_node_label(requested_label=None) str¶
Generates a unique label for a node in the hypergraph
- reset()¶
Removes all values in the hypergraph.
- set_logging_level(logging_level=20)¶
Sets the logging level.
- Parameters:
logging_level (int | str, default=logging.INFO (20)) – The level to set logging to, based on the Python logging library. More information is available at https://docs.python.org/3/howto/logging.html#logging-levels
Notes
The logging approach is the following, with higher levels include all items logged on lower ones: - logging.DEBUG (10): all edges and found combinations are listed, as well as search trees at each explored node. - logging.DEBUG+1 (11): debugging report is logged after a search is complete. - logging.DEBUG+2 (12): edges passed to debug_edges and nodes passed to debug_nodes as arguments to Hypergraph.solve are logged, as well as search trees at each explored node. - logging.INFO (20): start and end of a search are logged. - Warnings and errors are handled by the logging package (logging.WARNING and logging.ERROR). Note that these will not print to sys.stderr, though they will normally get raised and returned by the library.
- set_node_values(node_values: dict)¶
Sets the values of the given nodes.
Creates a new node in the hypergraph if the given label is not found.
- setup_logger() Logger¶
An optional call to setup logging.
- solve(target, inputs: dict = None, to_print: bool = False, min_index: int = 0, debug_nodes: list = None, debug_edges: list = None, search_depth: int = 100000, memory_mode: bool = False, logging_level=None, to_reset: bool = True) TNode¶
Runs a BFS search to identify the first valid solution for target.
- Parameters:
target (Node | str) – The node or label of the node to solve for.
inputs (dict, optional) – A dictionary {label : value} of input values.
to_print (bool, default=False) – Prints the search tree if set to true.
min_index (int, default=0) – The minumum index of the node to solve for.
debug_nodes (List[label,], optional) – A list of node labels to log debugging information for.
debug_edges (List[label,], optional) – A list of edge labels to log debugging information for.
search_depth (int, default=100000) – Number of nodes to explore before concluding no valid path.
memory_mode (bool, default=False) – Found TNodes in the path are saved to the Hypergraph.
logging_level (int | str, optional) – The logging level to use for the simulation. Configures logging if not already configured. logging.DEBUG or logging.INFO are informative levels. See Hypergraph.set_logging_level for more information.
to_reset (bool, default=True) – Resets the Hypergraph so that only nodes with static values are preseeded. Should be True for independent simulations, False for repeated simulations of different values from the same scenario.
- Returns:
the TNode for the minimum-cost path found
- Return type:
TNode | None
- summary(target, to_print: bool = False) str¶
Returns a str of the hypertree of all paths to the target node.
- to_dict() dict¶
Returns a dict representation of the Hypergraph.
- to_json() str¶
Returns a JSON representation of the Hypergraph.
- static union(a, *args)¶
Merges with another Hypergraph via a union operation, preserving all nodes and edges in the two graphs.