graphizy package

Submodules

graphizy.main module

Main graphing class for graphizy

This module provides the primary interface for creating, manipulating, and visualizing various types of graphs including Delaunay triangulations, proximity graphs, k-nearest neighbor graphs, Gabriel graphs, minimum spanning trees, and memory-based graphs.

Examples

Basic usage:

from graphizy import Graphing
import numpy as np

# Create sample data
data = np.random.rand(100, 3)  # 100 points with [id, x, y]

# Initialize graphing object
grapher = Graphing(dimension=(800, 600), aspect="array")

# Create different types of graphs
delaunay_graph = grapher.make_delaunay(data)
proximity_graph = grapher.make_proximity(data, proximity_thresh=50.0)

# Visualize
image = grapher.draw_graph(delaunay_graph)
grapher.show_graph(image, title="Delaunay Triangulation")
class graphizy.main.Graphing(config: GraphizyConfig | None = None, **kwargs)[source]

Bases: object

Main graphing class for creating and visualizing various types of graphs.

This class provides a unified interface for creating different types of graphs from point data, including geometric graphs (Delaunay, Gabriel), proximity-based graphs (k-NN, proximity), and spanning trees. It also supports memory-based graphs for temporal analysis and comprehensive graph visualization.

The class supports two data formats: - “array”: NumPy arrays with columns [id, x, y] - “dict”: Dictionaries with keys “id”, “x”, “y”

config

Configuration object containing graph and drawing settings

Type:

GraphizyConfig

dimension

Canvas dimensions (width, height)

Type:

Tuple[int, int]

aspect

Data format (“array” or “dict”)

Type:

str

dinter

Data interface for handling different data formats

Type:

DataInterface

memory_manager

Optional memory manager for temporal graphs

Type:

MemoryManager

# Drawing configuration shortcuts
line_thickness

Thickness of graph edges

Type:

int

line_color

RGB color for edges

Type:

Tuple[int, int, int]

point_thickness

Thickness of point borders

Type:

int

point_radius

Radius of graph vertices

Type:

int

point_color

RGB color for vertices

Type:

Tuple[int, int, int]

Examples

>>> # Basic initialization
>>> grapher = Graphing(dimension=(800, 600), aspect="array")
>>> # With custom configuration
>>> config = GraphizyConfig()
>>> config.drawing.line_color = (255, 0, 0)  # Red edges
>>> grapher = Graphing(config=config)
>>> # Create and visualize a graph
>>> data = np.random.rand(50, 3)
>>> graph = grapher.make_delaunay(data)
>>> image = grapher.draw_graph(graph)
>>> grapher.show_graph(image)
static average_path_length(graph: Any) float[source]

Calculate the average shortest path length between all pairs of vertices.

This metric indicates how “close” vertices are to each other on average. Lower values suggest better connectivity and shorter communication paths.

Parameters:

graph – igraph Graph object, must be connected for meaningful results.

Returns:

Average path length across all vertex pairs.

Return type:

float

Raises:

IgraphMethodError – If calculation fails (e.g., disconnected graph).

Examples

>>> avg_path = Graphing.average_path_length(graph)
>>> print(f"Average path length: {avg_path:.2f}")
>>> # Compare different graph types
>>> delaunay_avg = Graphing.average_path_length(delaunay_graph)
>>> mst_avg = Graphing.average_path_length(mst_graph)
>>> print(f"Delaunay: {delaunay_avg:.2f}, MST: {mst_avg:.2f}")

Note

  • Requires connected graph (use call_method_safe for disconnected graphs)

  • Computed over all pairs of vertices

  • Values typically range from 1 (complete graph) to n-1 (path graph)

  • Higher values indicate less efficient connectivity

call_method_brutal(graph: Any, method_name: str, return_format: str = 'auto', *args, **kwargs) Any[source]

Call any igraph method with intelligent return type formatting.

This method provides flexible access to igraph’s extensive method library with automatic formatting of results into user-friendly formats. It handles the conversion between igraph’s internal representations and more intuitive Python data structures.

Parameters:
  • graph – igraph Graph object to operate on.

  • method_name – Name of the igraph method to call (e.g., “betweenness”, “closeness”).

  • return_format – Output format specification: - “auto”: Intelligent format detection (recommended) - “dict”: Force dict format {object_id: value} for per-vertex results - “list”: Force list format [value1, value2, …] for array results - “raw”: Return exactly what igraph provides (no processing)

  • *args – Positional arguments passed to the igraph method.

  • **kwargs – Keyword arguments passed to the igraph method.

Returns:

Method result formatted according to return_format:
  • Per-vertex results: dict mapping object_id -> value (auto/dict)

  • Per-edge results: list of values (auto/list)

  • Scalar results: single value (all formats)

  • Complex results: depends on method and format

Return type:

Any

Raises:

Examples

>>> # Get degree centrality as dict
>>> degrees = grapher.call_method_brutal(graph, "degree", "dict")
>>> print(f"Object 5 degree: {degrees[5]}")
>>> # Get betweenness centrality with auto-formatting
>>> betweenness = grapher.call_method_brutal(graph, "betweenness")
>>> # Returns dict {object_id: betweenness_value}
>>> # Get raw igraph output
>>> raw_closeness = grapher.call_method_brutal(graph, "closeness", "raw")
>>> # Call method with parameters
>>> shortest_paths = grapher.call_method_brutal(
...     graph, "shortest_paths", "raw",
...     source=0, target=5
... )
>>> # Edge-related method (returns list)
>>> edge_betweenness = grapher.call_method_brutal(graph, "edge_betweenness")

Note

  • “auto” format is usually the most convenient

  • Per-vertex methods automatically map to object IDs when possible

  • Some methods may not support all return formats

  • Use “raw” format when you need igraph’s exact output

  • Method availability depends on igraph version and graph type

static call_method_raw(graph: Any, method_name: str, *args, **kwargs) Any[source]

Call any igraph method on the graph, returning unformatted output.

This method provides direct access to igraph’s methods without any processing or formatting of the results. Useful when you need the exact output format that igraph provides.

Parameters:
  • graph – igraph Graph object to operate on.

  • method_name – Name of the igraph method to call.

  • *args – Positional arguments for the method.

  • **kwargs – Keyword arguments for the method.

Returns:

Exact result from the igraph method call, no processing applied.

Return type:

Any

Raises:

IgraphMethodError – If method call fails or method doesn’t exist.

Examples

>>> # Get raw degree sequence
>>> raw_degrees = Graphing.call_method_raw(graph, "degree")
>>> print(type(raw_degrees))  # <class 'list'>
>>> # Get raw connected components
>>> raw_components = Graphing.call_method_raw(graph, "connected_components")
>>> print(type(raw_components))  # igraph-specific type
>>> # Call with parameters
>>> raw_paths = Graphing.call_method_raw(
...     graph, "shortest_paths",
...     source=0, target=[1, 2, 3]
... )

Note

  • No processing, formatting, or error handling beyond basic method call

  • Returns exactly what igraph provides (may be igraph-specific types)

  • Use when you need maximum control over the output format

  • Static method - can be called without Graphing instance

call_method_safe(graph: Any, method_name: str, return_format: str = 'auto', component_mode: str = 'connected_only', handle_disconnected: bool = True, default_value: Any | None = None, *args, **kwargs) Any[source]

Resilient version of call_method that handles disconnected graphs intelligently.

Many graph algorithms fail on disconnected graphs. This method provides robust computation by applying different strategies for handling disconnected components, with graceful fallback to default values when computation fails.

Parameters:
  • graph – igraph Graph object to analyze.

  • method_name – Name of the igraph method to call.

  • return_format – Output format (“auto”, “dict”, “list”, “raw”).

  • component_mode – Strategy for disconnected graphs: - “all”: Compute on all components separately - “largest”: Compute only on largest component - “connected_only”: Compute only on components with >1 vertex

  • handle_disconnected – Whether to apply special disconnected graph handling.

  • default_value – Value to return/use when computation fails (default: None).

  • *args – Positional arguments for the igraph method.

  • **kwargs – Keyword arguments for the igraph method.

Returns:

Method result with appropriate disconnected graph handling and formatting.

Return type:

Any

Examples

>>> # Safe diameter computation (fails on disconnected graphs normally)
>>> diameter = grapher.call_method_safe(graph, "diameter", default_value=float('inf'))
>>> # Betweenness centrality for all components
>>> betweenness = grapher.call_method_safe(
...     graph, "betweenness", "dict",
...     component_mode="all", default_value=0.0
... )
>>> # Average path length only for largest component
>>> avg_path = grapher.call_method_safe(
...     graph, "average_path_length",
...     component_mode="largest", default_value=None
... )
>>> # Robust clustering coefficient
>>> clustering = grapher.call_method_safe(
...     graph, "transitivity_local_undirected", "dict",
...     component_mode="connected_only", default_value=0.0
... )

Note

  • Automatically detects connectivity-sensitive methods

  • Provides meaningful results even for highly fragmented graphs

  • Maps component-level results back to full graph vertex space

  • Graceful degradation with informative logging

  • Essential for robust analysis pipelines

clear_graph_types()[source]

Clear all configured graph types and current graphs.

compute_all_attributes_fast(graph)[source]

Compute all pre-configured attributes quickly.

compute_component_metrics(graph: Any, metrics_list: List[str], component_mode: str = 'largest') Dict[str, Any][source]

Compute multiple graph metrics with consistent component handling.

This method efficiently computes multiple metrics on the same graph with unified handling of disconnected components. Ideal for comprehensive graph analysis with consistent treatment of connectivity issues.

Parameters:
  • graph – igraph Graph object to analyze.

  • metrics_list

    List of metric names to compute. Examples: [‘degree’, ‘betweenness’, ‘closeness’, ‘diameter’,

    ’transitivity_undirected’, ‘average_path_length’]

  • component_mode – Strategy for disconnected graphs (“all”, “largest”, “connected_only”).

Returns:

Dictionary with computed metrics:
  • connectivity_info: Detailed connectivity analysis

  • [metric_name]: Result for each requested metric

  • Failed metrics are set to None with warning logged

Return type:

Dict[str, Any]

Examples

>>> # Comprehensive analysis of a graph
>>> metrics = grapher.compute_component_metrics(
...     graph,
...     ['degree', 'betweenness', 'closeness', 'diameter', 'transitivity_undirected'],
...     component_mode="all"
... )
>>>
>>> print(f"Graph diameter: {metrics['diameter']}")
>>> print(f"Average degree: {np.mean(list(metrics['degree'].values()))}")
>>>
>>> # Check connectivity
>>> if not metrics['connectivity_info']['is_connected']:
...     print(f"Warning: Graph has {metrics['connectivity_info']['num_components']} components")
>>> # Focus on largest component only
>>> largest_metrics = grapher.compute_component_metrics(
...     graph,
...     ['average_path_length', 'diameter', 'betweenness'],
...     component_mode="largest"
... )

Note

  • Provides comprehensive analysis in a single call

  • Handles disconnected graphs gracefully

  • Includes connectivity analysis automatically

  • Failed metrics are logged but don’t stop other computations

  • Efficient for multiple related metrics on same graph

compute_edge_attribute(graph, attribute_name, method='formula', **kwargs)[source]

Compute any edge attribute.

create_async_stream_manager(buffer_size: int = 1000) AsyncStreamManager[source]

Create async stream manager for high-performance streaming

create_stream_manager(buffer_size: int = 1000, update_interval: float = 0.1, auto_memory: bool = True) StreamManager[source]

Create a stream manager for real-time data processing

static density(graph: Any) float[source]

Calculate the density of the graph.

Density is the ratio of actual edges to possible edges, indicating how close the graph is to being complete. Values range from 0 (no edges) to 1 (complete graph).

Parameters:

graph – igraph Graph object.

Returns:

Graph density between 0.0 and 1.0.

Return type:

float

Examples

>>> density = Graphing.density(graph)
>>> print(f"Graph density: {density:.3f} ({density*100:.1f}% of possible edges)")
>>> # Compare sparsity of different graph types
>>> print(f"Delaunay density: {Graphing.density(delaunay_graph):.3f}")
>>> print(f"MST density: {Graphing.density(mst_graph):.3f}")
>>> print(f"k-NN density: {Graphing.density(knn_graph):.3f}")

Note

  • MSTs have density 2(n-1)/(n(n-1)) = 2/(n) for n vertices

  • Complete graphs have density 1.0

  • Empty graphs have density 0.0

  • Useful for comparing graph sparsity

draw_all_graphs(**kwargs) Dict[str, ndarray][source]

Draw all current graphs to image arrays.

Parameters:

**kwargs – Drawing parameters passed to draw_graph().

Returns:

Dictionary mapping graph types to image arrays.

Return type:

Dict[str, np.ndarray]

draw_graph(graph: Any, **kwargs) ndarray[source]

Draw a graph to an image array.

This method provides a convenient top-level API by delegating the drawing task to the internal Visualizer instance.

Parameters:
  • graph – igraph Graph object to draw.

  • **kwargs – Additional arguments for the visualizer, e.g., ‘radius’, ‘thickness’.

Returns:

An RGB image array of the drawn graph.

Return type:

np.ndarray

draw_memory_graph(graph: Any, **kwargs) ndarray[source]

Draw a memory graph with optional age-based coloring.

Delegates to the Visualizer’s draw_memory_graph method.

Parameters:
  • graph – igraph Graph object to draw.

  • **kwargs – Additional arguments like ‘use_age_colors’, ‘alpha_range’.

Returns:

An RGB image array of the drawn memory graph.

Return type:

np.ndarray

property drawing_config: DrawingConfig

Get current drawing configuration.

Returns:

Current drawing configuration object containing

line and point styling parameters.

Return type:

DrawingConfig

static get_connections_per_object(graph: Any) Dict[Any, int][source]

Calculate the degree (number of connections) for each vertex in the graph.

This method provides a user-friendly mapping from original object IDs to their connectivity counts, which is essential for analyzing graph structure and identifying hubs or isolated nodes.

Parameters:

graph – igraph Graph object with vertices having “id” attributes.

Returns:

Dictionary mapping each object’s original ID to its degree.

Empty dict if graph is None or has no vertices.

Return type:

Dict[Any, int]

Raises:

IgraphMethodError – If degree calculation fails.

Examples

>>> connections = Graphing.get_connections_per_object(graph)
>>> print(f"Object 101 has {connections[101]} connections")
>>>
>>> # Find most connected objects
>>> sorted_objects = sorted(connections.items(), key=lambda x: x[1], reverse=True)
>>> print(f"Most connected: {sorted_objects[:5]}")
>>>
>>> # Find isolated objects
>>> isolated = [obj_id for obj_id, degree in connections.items() if degree == 0]
>>> print(f"Isolated objects: {isolated}")
>>> # Degree distribution analysis
>>> from collections import Counter
>>> degree_dist = Counter(connections.values())
>>> print(f"Degree distribution: {dict(degree_dist)}")

Note

  • Returns degree in graph-theoretic sense (number of incident edges)

  • For undirected graphs, each edge contributes 1 to each endpoint’s degree

  • For directed graphs, returns total degree (in-degree + out-degree)

  • Empty graphs return empty dictionary

  • Object IDs must be stored in vertex “id” attribute

get_connectivity_info(graph: Any) Dict[str, Any][source]

Get comprehensive connectivity information about the graph.

This method analyzes the graph’s connectivity structure, identifying connected components and providing statistics about graph cohesion. Essential for understanding graph topology and planning analyses.

Parameters:

graph – igraph Graph object to analyze.

Returns:

Comprehensive connectivity information:
  • is_connected: Boolean indicating if graph is fully connected

  • num_components: Number of disconnected components

  • components: List of vertex lists for each component

  • component_sizes: List of component sizes

  • largest_component_size: Size of largest component

  • largest_component_index: Index of largest component

  • connectivity_ratio: Fraction of vertices in largest component

  • isolation_ratio: Fraction of isolated vertices (size-1 components)

Return type:

Dict[str, Any]

Examples

>>> conn_info = grapher.get_connectivity_info(graph)
>>> if conn_info['is_connected']:
...     print("Graph is fully connected")
... else:
...     print(f"Graph has {conn_info['num_components']} components")
...     print(f"Largest component: {conn_info['largest_component_size']} vertices")
>>> # Analyze fragmentation
>>> if conn_info['isolation_ratio'] > 0.1:
...     print(f"Warning: {conn_info['isolation_ratio']:.1%} vertices are isolated")
>>> # Focus analysis on largest component
>>> if not conn_info['is_connected']:
...     largest_comp = conn_info['components'][conn_info['largest_component_index']]
...     subgraph = graph.subgraph(largest_comp)
...     # Analyze subgraph...

Note

  • Connected components are maximal sets of mutually reachable vertices

  • Component indices refer to the components list

  • Isolated vertices form size-1 components

  • Useful for determining appropriate analysis methods

get_current_graph(graph_type: str) Any[source]

Get the most recent graph of a specific type.

Parameters:

graph_type – The type of graph to retrieve.

Returns:

The igraph Graph object, or None if not available.

Return type:

Any

get_current_graphs() Dict[str, Any][source]

Get the most recently generated graphs.

Returns:

Dictionary of current graphs by type name.

Return type:

Dict[str, Any]

get_graph_info(graph: Any) GraphAnalysisResult[source]

Get a lazy-loading analysis object for the graph.

This method is the entry point for all graph analysis. It returns a powerful result object where metrics are computed on-demand, ensuring maximum performance and a responsive user experience.

Parameters:

graph – igraph Graph object to analyze.

Returns:

An object for lazily accessing graph metrics.

Return type:

GraphAnalysisResult

Examples

>>> # This call is instantaneous
>>> results = grapher.get_graph_info(graph)
>>> # The first access to a property computes the metric
>>> print(f"Density: {results.density}")
>>> # Subsequent access is instant (from cache)
>>> print(f"Graph density is {results.density:.4f}")
>>> # Compute advanced metrics on the fly
>>> top_hubs = results.get_top_n_by('degree', n=3)
>>> betweenness_stats = results.get_metric_stats('betweenness')
get_graph_type_info() Dict[str, Any][source]

Get information about current graph type configuration.

Returns:

Configuration information including types, parameters, and status.

Return type:

Dict[str, Any]

get_memory_analysis() Dict[str, Any][source]

Get comprehensive memory analysis including age statistics.

This method provides detailed analysis of the temporal patterns in the memory manager’s data, including connection persistence, age distributions, and temporal stability metrics.

Returns:

Comprehensive analysis including:
  • Basic statistics (count, usage, etc.)

  • Age distributions and temporal patterns

  • Connection persistence metrics

  • Stability analysis

  • Temporal trends

Return type:

Dict[str, Any]

Examples

>>> analysis = grapher.get_memory_analysis()
>>> print("Connection age distribution:")
>>> for age, count in analysis['age_distribution'].items():
...     print(f"  Age {age}: {count} connections")
>>>
>>> print(f"Average connection persistence: {analysis['avg_persistence']:.2f}")
get_networkx_analyzer() NetworkXAnalyzer[source]

Get NetworkX analyzer for advanced graph analysis.

Returns:

NetworkXAnalyzer instance for this Graphing object

Examples

>>> # Get analyzer
>>> nx_analyzer = grapher.get_networkx_analyzer()
>>>
>>> # Analyze current graphs
>>> analysis = nx_analyzer.analyze('delaunay')
>>> print(f"Communities: {analysis['num_communities']}")
>>>
>>> # Direct NetworkX access
>>> nx_graph = nx_analyzer.get_networkx('proximity')
>>> custom_centrality = nx.eigenvector_centrality(nx_graph)
static get_plugin_info(graph_type: str) Dict[str, Any][source]

Get detailed information about a specific graph type.

Parameters:

graph_type – Name of the graph type to query.

Returns:

Detailed information including:
  • info: General information (description, category, version)

  • parameters: List of available parameters with descriptions

  • examples: Usage examples if available

  • requirements: Special requirements or dependencies

Return type:

Dict[str, Any]

Raises:

ValueError – If graph_type is not found in the registry.

Examples

>>> # Get info about proximity graphs
>>> prox_info = Graphing.get_plugin_info('proximity')  # ✅ Fixed method name
>>> print(prox_info['info']['description'])
>>> print("Parameters:", prox_info['parameters'])
>>> # Check parameter details before calling
>>> knn_info = Graphing.get_plugin_info('knn')  # ✅ Fixed method name
>>> k_param = knn_info['parameters']['k']
>>> print(f"k parameter: {k_param['description']}")
get_weight_analysis() Dict[str, Any][source]

:Todo implement the weight statistics

property graph_config: GraphConfig

Get current graph configuration.

Returns:

Current graph configuration object containing

dimension, aspect, and algorithm parameters.

Return type:

GraphConfig

static identify_graph(graph: Any) Any[source]

Replace graph vertex names with proper particle IDs for consistency.

This method ensures that graph vertices have consistent naming by setting the “name” attribute to match the “id” attribute. This is useful for maintaining data consistency across different graph operations.

Parameters:

graph – igraph Graph object to modify.

Returns:

The modified graph object with updated vertex names.

Return type:

Any

Raises:

GraphCreationError – If graph is None or modification fails.

Note

This method modifies the graph in-place and also returns it for method chaining convenience.

Examples

>>> graph = grapher.make_delaunay(data)
>>> identified_graph = Graphing.identify_graph(graph)
>>> # Now graph.vs["name"] == graph.vs["id"] for all vertices
init_memory_manager(max_memory_size: int = 100, max_iterations: int | None = None, track_edge_ages: bool = True) MemoryManager[source]

Initialize memory manager for temporal graph analysis.

The memory manager enables tracking of graph connections over time, allowing for analysis of persistent vs. transient relationships and temporal patterns in graph structure.

Parameters:
  • max_memory_size – Maximum number of connections to remember. Older connections are forgotten when this limit is reached. Larger values provide longer memory but use more resources.

  • max_iterations – Maximum number of time steps to track. If None, tracks indefinitely until max_memory_size is reached.

  • track_edge_ages – Whether to track the age/persistence of each edge. Enables advanced temporal analysis but uses more memory.

Returns:

The initialized memory manager instance.

Return type:

MemoryManager

Raises:

GraphCreationError – If memory manager initialization fails.

Examples

>>> # Basic memory manager
>>> memory_mgr = grapher.init_memory_manager()
>>> # Large memory for long-term analysis
>>> memory_mgr = grapher.init_memory_manager(
...     max_memory_size=1000,
...     max_iterations=100,
...     track_edge_ages=True
... )
>>> # Lightweight memory for real-time applications
>>> memory_mgr = grapher.init_memory_manager(
...     max_memory_size=50,
...     track_edge_ages=False
... )

Note

  • Must be called before using memory-based graph methods

  • Only one memory manager per Graphing instance

  • Memory manager persists until explicitly reset or object destroyed

init_weight_computer(**kwargs)[source]

Initialize flexible weight computer.

is_connected(graph: Any) bool[source]

Check if the graph is connected (single component).

Parameters:

graph – igraph Graph object to test.

Returns:

True if graph is connected, False otherwise.

Return type:

bool

static list_graph_types(category: str | None = None) Dict[str, Any][source]

List all available graph types in the plugin registry.

Parameters:

category – Optional category filter to show only specific types: - ‘built-in’: Core graph types included with graphizy - ‘community’: Community-contributed plugins - ‘experimental’: Experimental or unstable plugins - None: Show all available types

Returns:

Dictionary mapping graph type names to their information.

Each entry contains metadata about the graph type including description, category, version, and available parameters.

Return type:

Dict[str, Any]

Examples

>>> # List all graph types
>>> all_types = Graphing.list_graph_types()
>>> for name, info in all_types.items():
...     print(f"{name}: {info['description']}")
>>> # List only built-in types
>>> builtin_types = Graphing.list_graph_types(category='built-in')
>>> # Check if specific type is available
>>> available_types = Graphing.list_graph_types()
>>> if 'delaunay' in available_types:
...     print("Delaunay triangulation is available")
make_graph(graph_type: str, data_points: ndarray | Dict[str, Any], graph_params: Dict | None = None, update_memory: bool | None = None, use_memory: bool | None = None, compute_weights: bool | None = None, do_timing: bool = False, validate_data: bool = False, **kwargs) Any[source]

Create a graph using the extensible plugin system with intelligent memory defaults.

This method provides access to both built-in and community-contributed graph types through a unified interface. It automatically handles data format conversion and passes the appropriate parameters to the graph creation algorithm. Optionally integrates with memory system using smart defaults.

Parameters:
  • graph_type – Name of the graph type to create. Built-in types include: ‘delaunay’, ‘proximity’, ‘knn’, ‘gabriel’, ‘mst’, ‘memory’. Additional types may be available through plugins.

  • data_points – Point data in the format specified by self.aspect: - For “array”: NumPy array with shape (n, 3) containing [id, x, y] - For “dict”: Dictionary with keys “id”, “x”, “y” as lists/arrays

  • graph_params – Dictionary of parameters specific to the graph type. If None, uses empty dict. These are the algorithm-specific parameters: - proximity: {‘proximity_thresh’: 50.0, ‘metric’: ‘euclidean’} - knn: {‘k’: 5} - mst: {‘metric’: ‘euclidean’} - etc.

  • update_memory – Whether to update memory manager with the created graph. If None and memory manager exists, defaults based on use_memory. Only works if memory_manager is initialized.

  • use_memory – Whether to create a memory-enhanced graph from existing connections. If None and memory manager exists, defaults to True. Only works if memory_manager is initialized.

  • compute_weights – Whether to compute edges weights. Only works if weight_computer is initialized.

  • do_timing – Whether to print the performances

  • validate_data – Whether to validate the data (careful at each call this will degrade the performances)

  • **kwargs – Additional graph-type specific parameters that override graph_params. These are merged with graph_params, with kwargs taking precedence.

Returns:

igraph Graph object of the specified type, optionally memory-enhanced.

Return type:

Any

Raises:
  • ValueError – If graph_type is not found in the registry.

  • GraphCreationError – If graph creation fails due to invalid parameters or computation errors.

Smart Defaults:
  • If memory_manager exists and use_memory=None → use_memory=True

  • If use_memory=True and update_memory=None → update_memory=True

  • If no memory_manager → both default to False

Examples

>>> # Simple direct usage (most common)
>>> graph = grapher.make_graph('delaunay', data)
>>> connections = grapher.make_graph('proximity', data, proximity_thresh=80.0)
>>> knn_graph = grapher.make_graph('knn', data, k=5)
>>> # Using graph_params dictionary (for complex configs)
>>> prox_params = {'proximity_thresh': 75.0, 'metric': 'manhattan'}
>>> graph = grapher.make_graph('proximity', data, graph_params=prox_params)
>>> # Mixed usage - kwargs override graph_params
>>> graph = grapher.make_graph('proximity', data,
...                          graph_params={'proximity_thresh': 50.0},
...                          proximity_thresh=100.0)  # This wins
>>> # Memory control with direct parameters
>>> graph = grapher.make_graph('knn', data, k=8, use_memory=False, update_memory=True)
>>> # Both styles work seamlessly
>>> algorithm_params = {'proximity_thresh': 60.0, 'metric': 'euclidean'}
>>> graph1 = grapher.make_graph('proximity', data, graph_params=algorithm_params)
>>> graph2 = grapher.make_graph('proximity', data, proximity_thresh=60.0, metric='euclidean')
>>> # graph1 and graph2 are equivalent

Note

  • Direct kwargs are the most convenient: make_graph(‘proximity’, data, proximity_thresh=80.0)

  • graph_params provides clean organization for complex configurations

  • kwargs override graph_params for convenient parameter overrides

  • Both styles can be mixed: graph_params for base config, kwargs for overrides

  • Smart defaults make memory usage automatic when memory_manager exists

  • Explicit parameters always override defaults

  • use_memory=True: Uses EXISTING memory connections from previous calls

  • update_memory=True: Adds current graph connections to memory for future use

  • Memory creates historical connection patterns for temporal analysis

make_memory_graph(data_points: ndarray | Dict[str, Any], memory_connections: Dict | None = None) Any[source]

Create a graph based on accumulated memory connections.

Memory graphs use historical connection data to create graphs that represent persistent relationships over time. This is useful for analyzing temporal stability and identifying core vs. peripheral connections in dynamic systems.

Parameters:
  • data_points – Current point data in the format specified by self.aspect: - For “array”: NumPy array with shape (n, 3) containing [id, x, y] - For “dict”: Dictionary with keys “id”, “x”, “y” as lists/arrays

  • memory_connections – Optional explicit memory connections. If None, uses the current memory manager’s accumulated connections. Format: {(id1, id2): connection_strength, …}

Returns:

igraph Graph object representing memory-based connections.

Edge weights may represent connection persistence/frequency.

Return type:

Any

Raises:

GraphCreationError – If memory manager is not initialized and no memory_connections provided, or if graph creation fails.

Examples

>>> # Initialize memory and accumulate connections over time
>>> grapher.init_memory_manager(max_memory_size=200)
>>>
>>> # Update memory with multiple proximity snapshots
>>> for t in range(10):
...     dynamic_data = get_data_at_time(t)  # Your data source
...     grapher.update_memory_with_proximity(dynamic_data)
>>>
>>> # Create memory graph from accumulated connections
>>> current_data = get_current_data()
>>> memory_graph = grapher.make_memory_graph(current_data)
>>> # Use explicit memory connections
>>> custom_memory = {(1, 2): 0.8, (2, 3): 0.6, (1, 3): 0.3}
>>> memory_graph = grapher.make_memory_graph(data, custom_memory)

Note

  • Requires either initialized memory manager or explicit connections

  • Memory graphs can be much sparser than instantaneous graphs

  • Edge weights typically represent temporal persistence

  • Useful for identifying stable vs. transient relationships

overlay_collision(image_graph: ndarray, graph: Any) ndarray[source]

Overlay an additional graph onto an existing image.

Delegates to the Visualizer’s overlay_graph method.

Parameters:
  • image_graph – The base image to draw on.

  • graph – The igraph Graph object to overlay.

Returns:

The modified image array.

Return type:

np.ndarray

overlay_graph(image_graph: ndarray, graph: Any) ndarray[source]

Overlay an additional graph onto an existing image.

Delegates to the Visualizer’s overlay_graph method.

Parameters:
  • image_graph – The base image to draw on.

  • graph – The igraph Graph object to overlay.

Returns:

The modified image array.

Return type:

np.ndarray

save_graph(image_graph: ndarray, filename: str) None[source]

Save a graph image to a file.

Delegates to the Visualizer’s save_graph method.

Parameters:
  • image_graph – The image array to save.

  • filename – The path to save the file to.

set_graph_type(graph_type: str | List[str] | Tuple[str], **default_kwargs)[source]

Set the type(s) of graph to generate automatically during updates.

This method configures the Graphing object to automatically create specific graph types when update_graphs() is called with new data. Supports single or multiple graph types with default parameters.

Parameters:
  • graph_type – Graph type(s) to generate automatically. Can be: - str: Single graph type (e.g., ‘delaunay’) - List[str]: Multiple graph types (e.g., [‘delaunay’, ‘proximity’]) - Tuple[str]: Multiple graph types as tuple

  • **default_kwargs – Default parameters for graph creation, applied to all types. Type-specific parameters can be set using update_graph_params().

Raises:

Examples

>>> # Set single graph type
>>> grapher.set_graph_type('delaunay')
>>> # Set multiple graph types
>>> grapher.set_graph_type(['delaunay', 'proximity', 'knn'])
>>> # Set with default parameters
>>> grapher.set_graph_type('proximity', proximity_thresh=50.0, metric='euclidean')
>>> # Set multiple types with defaults
>>> grapher.set_graph_type(['knn', 'gabriel'], k=6)  # k applies only to knn
setup_fast_attributes(**config)[source]

Setup fast attribute computer for real-time use.

show_all_graphs(**kwargs)[source]

Display all current graphs in separate windows.

Parameters:

**kwargs – Parameters passed to show_graph().

show_graph(image_graph: ndarray, title: str = 'Graphizy', **kwargs) None[source]

Display a graph image in a window.

Delegates to the Visualizer’s show_graph method.

Parameters:
  • image_graph – The image array to display.

  • title – The title of the window.

  • **kwargs – Additional arguments like ‘block’.

to_networkx(graph_type: str | None = None, igraph_graph: Any | None = None) Any[source]

Convert graph to NetworkX format.

Parameters:
  • graph_type – Type from current graphs

  • igraph_graph – Manual igraph to convert

Returns:

NetworkX Graph object

update(**kwargs)[source]

Update configuration values at runtime from keyword arguments. This method can intelligently route flat keys (e.g., ‘line_color’) to the correct nested config object (e.g., self.drawing).

update_config(**kwargs) None[source]

Update configuration parameters at runtime.

This method allows dynamic reconfiguration of the Graphing object without requiring re-initialization. Changes are applied immediately and cached values are updated.

Parameters:

**kwargs – Configuration parameters to update. Can include nested parameters using dictionary syntax: - drawing={‘line_color’: (255,0,0), ‘point_radius’: 8} - graph={‘proximity_threshold’: 100.0} - Direct parameters: line_thickness=3, aspect=’dict’

Raises:

GraphCreationError – If configuration update fails due to invalid parameters.

Examples

>>> # Update drawing parameters
>>> grapher.update_config(
...     drawing={'line_color': (0, 255, 0), 'line_thickness': 2}
... )
>>> # Update graph parameters
>>> grapher.update_config(
...     graph={'proximity_threshold': 75.0, 'distance_metric': 'manhattan'}
... )
>>> # Mixed updates
>>> grapher.update_config(
...     line_color=(255, 255, 0),
...     graph={'dimension': (1200, 800)}
... )
update_graph_params(graph_type: str, **kwargs)[source]

Update parameters for a specific graph type.

Parameters:
  • graph_type – The graph type to update parameters for.

  • **kwargs – Parameters to set for this graph type.

Examples

>>> grapher.set_graph_type(['proximity', 'knn'])
>>> grapher.update_graph_params('proximity', proximity_thresh=75.0, metric='manhattan')
>>> grapher.update_graph_params('knn', k=8)
update_graphs(data_points: ndarray | Dict[str, Any], update_memory: bool | None = None, use_memory: bool | None = None, compute_weights: bool | None = None, **override_kwargs) Dict[str, Any][source]

Update all configured graph types with new data using smart memory and weight defaults.

This method automatically creates graphs of all types specified by set_graph_type() using the provided data. Optionally updates memory manager, computes weights, and returns all generated graphs. Uses the same smart defaults as make_graph().

Processing Flow: graph → memory → weights (for each graph type)

Parameters:
  • data_points – New point data in the format specified by self.aspect.

  • update_memory – Whether to update memory manager with new graphs. If None and memory manager exists, defaults based on use_memory. Only works if memory_manager is initialized.

  • use_memory – Whether to create memory-enhanced graphs from existing connections. If None and memory manager exists, defaults to True. Only works if memory_manager is initialized.

  • compute_weights – Whether to compute edge weights for final graphs. If None, uses self.auto_compute_weights default. Only works if weight_computer is initialized.

  • **override_kwargs – Parameters that override defaults for this update only.

Returns:

Dictionary mapping graph type names to generated graph objects.

Each graph follows the pipeline: base_graph → memory → weights

Return type:

Dict[str, Any]

Smart Defaults:

Memory: - If memory_manager exists and use_memory=None → use_memory=True - If use_memory=True and update_memory=None → update_memory=True - If no memory_manager → both default to False

Weights: - If compute_weights=None → use self.auto_compute_weights - If weight_computer not set → weights skipped regardless of setting

Examples

>>> # Set up automatic graph generation with memory and weights
>>> grapher.set_graph_type(['delaunay', 'proximity', 'knn'])
>>> grapher.init_memory_manager(max_memory_size=200)
>>> grapher.init_weight_computer(WeightComputer(method="distance"))
>>> grapher.update_graph_params('proximity', proximity_thresh=60.0)
>>> grapher.update_graph_params('knn', k=5)
>>> # Basic update - uses all smart defaults
>>> new_data = np.random.rand(100, 3) * 100
>>> graphs = grapher.update_graphs(new_data)
>>> # Each graph: structure → memory → weights
>>> # Explicit control over all processing steps
>>> graphs = grapher.update_graphs(
...     new_data,
...     use_memory=False,      # Skip memory
...     update_memory=True,    # But learn from current
...     compute_weights=True   # Force weights
... )
>>> # Memory + parameter overrides
>>> graphs = grapher.update_graphs(
...     new_data,
...     use_memory=True,
...     compute_weights=False,  # Skip weights this time
...     proximity_thresh=75.0   # Override proximity threshold
... )
>>> # Different settings per call
>>> learning_graphs = grapher.update_graphs(new_data, use_memory=False, update_memory=True)
>>> memory_graphs = grapher.update_graphs(new_data, use_memory=True, update_memory=False)

Note

  • All graphs follow the same pipeline: graph → memory → weights

  • Memory processing can change which edges exist before weights are computed

  • Weight computation adds attributes to final edge set

  • Smart defaults minimize configuration while maintaining full control

  • Failed graphs are set to None but don’t stop other graph generation

update_graphs_learning_only(data_points: ndarray | Dict[str, Any], compute_weights: bool | None = None, **override_kwargs) Dict[str, Any][source]

Convenience method to create regular graphs and update memory (no memory usage).

This creates graphs from current data and adds the connections to memory for future use, but doesn’t use existing memory for the current graphs. Can still compute weights on the current edges.

Parameters:
  • data_points – Current point data.

  • compute_weights – Whether to compute weights on current edges. If None, uses auto_compute_weights default.

  • **override_kwargs – Parameter overrides for graph creation.

Returns:

Dictionary of current graphs with optional weights

(memory updated as side effect).

Return type:

Dict[str, Any]

Examples

>>> # Build up memory without using it yet (with weights for analysis)
>>> grapher.update_graphs_learning_only(data1, compute_weights=True)
>>> grapher.update_graphs_learning_only(data2, compute_weights=True)
>>> # Now use accumulated memory
>>> memory_graphs = grapher.update_graphs_memory_only(current_data)
update_graphs_memory_only(data_points: ndarray | Dict[str, Any], compute_weights: bool | None = None, **override_kwargs) Dict[str, Any][source]

Convenience method to update graphs using only memory (no current data learning).

This creates graphs purely from accumulated memory connections without updating the memory with current data. Useful for seeing what the “remembered” graph structure looks like. Can still compute weights on the memory-based edges.

Parameters:
  • data_points – Current point data (positions only, connections from memory).

  • compute_weights – Whether to compute weights on memory-based edges. If None, uses auto_compute_weights default.

  • **override_kwargs – Parameter overrides for graph creation.

Returns:

Dictionary of memory-based graphs with optional weights.

Return type:

Dict[str, Any]

Examples

>>> # Build up memory over time
>>> grapher.update_graphs(data1)  # Learn from data1
>>> grapher.update_graphs(data2)  # Learn from data2
>>> # See what the accumulated memory looks like (with weights)
>>> memory_graphs = grapher.update_graphs_memory_only(current_data, compute_weights=True)
>>> # Pure memory structure without weights
>>> memory_structure = grapher.update_graphs_memory_only(current_data, compute_weights=False)
update_memory_with_custom(data_points: ndarray | Dict[str, Any], connection_function: callable, **kwargs) Dict[str, List[str]][source]

Update memory using a custom connection function.

This method allows integration of custom graph algorithms or connection rules with the memory system. The connection function should return pairs of point IDs that should be connected.

Parameters:
  • data_points – Point data in the format specified by self.aspect: - For “array”: NumPy array with shape (n, 3) containing [id, x, y] - For “dict”: Dictionary with keys “id”, “x”, “y” as lists/arrays

  • connection_function – Callable that takes data_points and returns connections. Should return iterable of (id1, id2) tuples or similar.

  • **kwargs – Additional arguments passed to the connection function.

Raises:

GraphCreationError – If memory manager is not initialized or update fails.

Examples

>>> # Define custom connection rule
>>> def angular_connections(data_points, angle_thresh=45):
...     """Connect points with similar angles from origin"""
...     connections = []
...     # Your custom logic here
...     angles = np.arctan2(data_points[:, 2], data_points[:, 1])  # y, x
...     for i, angle_i in enumerate(angles):
...         for j, angle_j in enumerate(angles[i+1:], i+1):
...             if abs(angle_i - angle_j) < np.radians(angle_thresh):
...                 connections.append((data_points[i, 0], data_points[j, 0]))
...     return connections
>>>
>>> # Initialize memory and use custom function
>>> grapher.init_memory_manager()
>>> grapher.update_memory_with_custom(
...     data,
...     angular_connections,
...     angle_thresh=30
... )
>>> # Example with lambda function for simple rules
>>> grapher.update_memory_with_custom(
...     data,
...     lambda pts: [(pts[i,0], pts[j,0]) for i in range(len(pts))
...                  for j in range(i+1, len(pts))
...                  if abs(pts[i,1] - pts[j,1]) < 10]  # Connect similar x-coords
... )

Note

  • Connection function should be efficient for large datasets

  • Function should return iterable of (id1, id2) pairs

  • Memory manager handles deduplication and aging automatically

  • Useful for domain-specific connection rules

update_memory_with_graph(graph: Any) Dict[str, List[str]][source]

Update memory manager from any existing graph object.

This method extracts connections from an existing igraph Graph object and adds them to the memory manager. This is useful for incorporating connections computed by external algorithms or for combining multiple graph types in memory.

Parameters:

graph – igraph Graph object with vertices having “id” attributes and edges representing connections to remember.

Raises:

GraphCreationError – If memory manager is not initialized or update fails.

Examples

>>> # Initialize memory
>>> grapher.init_memory_manager()
>>>
>>> # Create various graph types and add to memory
>>> delaunay_graph = grapher.make_delaunay(data)
>>> grapher.update_memory_with_graph(delaunay_graph)
>>>
>>> knn_graph = grapher.make_knn(data, k=5)
>>> grapher.update_memory_with_graph(knn_graph)
>>>
>>> # Memory now contains union of both graph types
>>> combined_memory_graph = grapher.make_memory_graph(data)
>>> # Update with external graph
>>> external_graph = some_external_algorithm(data)
>>> grapher.update_memory_with_graph(external_graph)

Note

  • Graph must have vertex “id” attributes matching your data

  • All edges in the graph will be added to memory

  • Useful for combining multiple graph construction methods

  • Can be used with any igraph-compatible graph object

graphizy.builtin_plugins module

Built-in Graph Type Plugins for Graphizy

This module defines and registers the core graph construction algorithms as plugins, making them available through the unified Graphing API.

class graphizy.builtin_plugins.DelaunayPlugin[source]

Bases: GraphTypePlugin

Delaunay triangulation graph plugin

create_graph(data_points: ndarray, dimension: tuple, data_shape: List[Tuple[str, Any]] | None = None, **kwargs) Any[source]

Create Delaunay triangulation graph by calling the algorithm directly.

property info: GraphTypeInfo

Return information about this graph type

class graphizy.builtin_plugins.GabrielPlugin[source]

Bases: GraphTypePlugin

Gabriel graph plugin

create_graph(data_points: ndarray, dimension: tuple, data_shape: List[Tuple[str, Any]] | None = None, **kwargs) Any[source]

Create Gabriel graph by calling the algorithm directly.

property info: GraphTypeInfo

Return information about this graph type

class graphizy.builtin_plugins.KNNPlugin[source]

Bases: GraphTypePlugin

K-Nearest Neighbors graph plugin

create_graph(data_points: ndarray, dimension: tuple, data_shape: List[Tuple[str, Any]] | None = None, **kwargs) Any[source]

Create k-nearest neighbors graph by calling the algorithm directly.

property info: GraphTypeInfo

Return information about this graph type

class graphizy.builtin_plugins.MSTPlugin[source]

Bases: GraphTypePlugin

Minimum Spanning Tree graph plugin

create_graph(data_points: ndarray, dimension: tuple, data_shape: List[Tuple[str, Any]] | None = None, **kwargs) Any[source]

Create minimum spanning tree graph by calling the algorithm directly.

property info: GraphTypeInfo

Return information about this graph type

class graphizy.builtin_plugins.ProximityPlugin[source]

Bases: GraphTypePlugin

Proximity graph plugin

create_graph(data_points: ndarray, dimension: tuple, data_shape: List[Tuple[str, Any]] | None = None, **kwargs) Any[source]

Create proximity graph by calling the algorithm directly.

property info: GraphTypeInfo

Return information about this graph type

class graphizy.builtin_plugins.VisibilityPlugin[source]

Bases: GraphTypePlugin

Visibility graph plugin

create_graph(data_points: ndarray, dimension: tuple, data_shape: List[Tuple[str, Any]] | None = None, **kwargs) Any[source]

Create visibility graph by calling the algorithm directly.

property info: GraphTypeInfo

Return information about this graph type

class graphizy.builtin_plugins.VoronoiCellPlugin[source]

Bases: GraphTypePlugin

Voronoi cell graph plugin

create_graph(data_points: ndarray, dimension: tuple, data_shape: List[Tuple[str, Any]] | None = None, **kwargs) Any[source]

Create Voronoi cell graph by calling the algorithm directly.

property info: GraphTypeInfo

Return information about this graph type

graphizy.builtin_plugins.register_all_builtins()[source]

A convenience function to register all built-in plugins. This is typically called once when the graphizy package is initialized.

graphizy.plugins_logic module

Graph Type Plugin System for Graphizy

This module provides a plugin-based architecture for easily adding new graph types without modifying core graphizy files.

class graphizy.plugins_logic.GraphTypeInfo(name: str, description: str, parameters: Dict[str, Dict[str, Any]], category: str = 'custom', author: str = '', version: str = '1.0.0', requires_external_deps: bool = False, external_deps: list | None = None)[source]

Bases: object

Information about a graph type for documentation and discovery

author: str = ''
category: str = 'custom'
description: str
external_deps: list = None
name: str
parameters: Dict[str, Dict[str, Any]]
requires_external_deps: bool = False
version: str = '1.0.0'
class graphizy.plugins_logic.GraphTypePlugin[source]

Bases: ABC

Abstract base class for graph type plugins

abstract create_graph(data_points: ndarray, dimension: tuple, data_shape: List[Tuple[str, Any]] | None = None, **kwargs) Any[source]

Create a graph from the given data points.

Parameters:
  • data_points – Standardized NumPy array of shape (n, m).

  • dimension – Image dimensions (width, height).

  • data_shape – List of tuples defining the data structure.

  • **kwargs – Algorithm-specific parameters.

Returns:

igraph Graph object.

abstract property info: GraphTypeInfo

Return information about this graph type

validate_parameters(**kwargs) Dict[str, Any][source]

Validate and process parameters for this graph type.

class graphizy.plugins_logic.GraphTypeRegistry[source]

Bases: object

Registry for managing graph type plugins

create_graph(graph_type: str, data_points: ndarray, dimension: tuple, data_shape: List[Tuple[str, Any]], **kwargs) Any[source]

Create a graph using a registered plugin

get_plugin(name: str) GraphTypePlugin[source]

Get a registered plugin by name

list_plugins(category: str | None = None) Dict[str, GraphTypeInfo][source]

List all registered plugins, optionally filtered by category

register(plugin: GraphTypePlugin) None[source]

Register a new graph type plugin

graphizy.plugins_logic.get_graph_registry() GraphTypeRegistry[source]

Get the global graph type registry

graphizy.plugins_logic.graph_type_plugin(name: str, description: str, parameters: Dict | None = None, category: str = 'custom', **info_kwargs)[source]

Decorator to easily create graph type plugins from functions

graphizy.plugins_logic.register_graph_type(plugin: GraphTypePlugin) None[source]

Register a graph type plugin globally

graphizy.algorithms module

Graph algorithms for graphizy

graphizy.algorithms.call_igraph_method(graph: Any, method_name: str, *args, **kwargs) Any[source]

Call any igraph method on the graph safely

Parameters:
  • graph – igraph Graph object

  • method_name – Name of the method to call

  • *args – Positional arguments for the method

  • **kwargs – Keyword arguments for the method

Returns:

Result of the method call

Raises:

IgraphMethodError – If method call fails

graphizy.algorithms.create_delaunay_graph(data_points: ndarray | Dict[str, Any], aspect: str = 'array', dimension: Tuple[int, int] = (1200, 1200), data_shape: List[Tuple[str, Any]] | None = None) Any[source]

Create a Delaunay triangulation graph from point data

Parameters:
  • data_points – Point data as array or dictionary

  • aspect – Data format (“array” or “dict”)

  • dimension – Image dimensions (width, height)

  • data_shape – shape of the data to pass (if extra column of information)

Returns:

igraph Graph object with Delaunay triangulation

Raises:

GraphCreationError – If Delaunay graph creation fails

graphizy.algorithms.create_gabriel_graph(positions: ndarray, aspect: str = 'array', data_shape: List[Tuple[str, Any]] | None = None) Any[source]

Create a Gabriel graph from point positions using an optimized, vectorized approach.

A Gabriel graph is a subgraph of the Delaunay triangulation where for any edge (p, q), the disk with diameter pq contains no other point r.

Parameters:
  • positions – Point data array with shape (n, >=3) containing [id, x, y, …].

  • aspect – Data format (currently only “array” is supported).

  • data_shape – shape of the data to pass (if extra column of information)

Returns:

An igraph Graph object representing the Gabriel graph.

Return type:

igraph.Graph

Raises:

GraphCreationError – If graph creation fails.

graphizy.algorithms.create_graph(data_points: ndarray | Dict[str, Any], graph_type: str, aspect: str = 'array', dimension: Tuple[int, int] = (1200, 1200), **kwargs) Any[source]

Create any type of graph from point data

Parameters:
  • data_points – Point data as array or dictionary

  • graph_type – Type of graph (“delaunay”, “proximity”, “knn”, “mst”, “gabriel”)

  • aspect – Data format (“array” or “dict”)

  • dimension – Image dimensions (width, height)

  • **kwargs – Graph-specific parameters

Returns:

igraph Graph object

Raises:
graphizy.algorithms.create_graph_array(point_array: ndarray, data_shape: List[Tuple[str, Any]] | None = None) Any[source]

Create a graph from a point array, dynamically adding attributes.

Parameters:
  • point_array – Array of points with columns corresponding to the data_shape.

  • data_shape – List of tuples defining the data structure, e.g., [(‘id’, int), (‘x’, float), (‘velocity’, float)]. If None, defaults to the legacy [id, x, y] behavior.

Returns:

igraph Graph object.

Raises:

GraphCreationError – If graph creation fails.

graphizy.algorithms.create_graph_dict(point_dict: Dict[str, Any]) Any[source]

Create a graph from a point dictionary.

This function dynamically adds all keys from the dictionary as vertex attributes.

Parameters:

point_dict – Dictionary with keys ‘id’, ‘x’, ‘y’, and other optional attributes. All values should be lists or arrays of the same length.

Returns:

igraph Graph object

Raises:

GraphCreationError – If graph creation fails

graphizy.algorithms.create_knn_graph(positions: ndarray, k: int = 3, aspect: str = 'array', data_shape: List[Tuple[str, Any]] | None = None) Any[source]

Create graph connecting each point to its k nearest neighbors

Parameters:
  • positions – Point data array

  • k – Number of nearest neighbors

  • aspect – Data format

  • data_shape – shape of the data to pass (if extra column of information)

graphizy.algorithms.create_mst_graph(positions: ndarray, aspect: str = 'array', metric: str = 'euclidean', data_shape: List[Tuple[str, Any]] | None = None) Any[source]

Create minimum spanning tree graph from a standardized array.

Parameters:
  • positions – Point data array

  • aspect – Data format

  • metric – Distance metric for MST construction

  • data_shape – shape of the data to pass (if extra column of information)

graphizy.algorithms.create_proximity_graph(data_points: ndarray | Dict[str, Any], proximity_thresh: float, aspect: str = 'array', metric: str = 'euclidean', data_shape: List[Tuple[str, Any]] | None = None) Any[source]

Create a proximity graph from point data

Parameters:
  • data_points – Point data as array or dictionary

  • proximity_thresh – Distance threshold for connections

  • aspect – Data format (“array” or “dict”)

  • metric – Distance metric to use for the graph construction

  • data_shape – shape of the data to pass (if extra column of information)

Returns:

igraph Graph object with proximity connections and distance attributes

Raises:

GraphCreationError – If proximity graph creation fails

graphizy.algorithms.create_visibility_graph(positions: ndarray, obstacles: List | None = None, aspect: str = 'array') Any[source]

Create visibility graph where points are connected if they have line-of-sight.

Parameters:
  • positions – Point data array

  • obstacles – List of obstacle polygons (optional)

  • aspect – Data format

  • add_distance – Whether to add distance attributes

graphizy.algorithms.create_voronoi_cell_graph(positions: ndarray, dimension: Tuple[int, int], aspect: str = 'array') Any[source]

Create graph from Voronoi diagram structure: - Nodes are Voronoi vertices (intersections of cell boundaries) - Edges connect adjacent Voronoi vertices

graphizy.algorithms.find_vertex(trilist: List, subdiv: Any, g: Any) Any[source]

Find vertices in triangulation and add edges to graph

Parameters:
  • trilist – List of triangles

  • subdiv – OpenCV subdivision

  • g – igraph Graph object

Returns:

Modified graph

Raises:

GraphCreationError – If vertex finding fails

graphizy.algorithms.get_delaunay(point_array: ndarray, dim: List | Tuple) ndarray[source]

Make the delaunay triangulation of set of points

Parameters:
  • point_array – Array of points

  • dim – Dimensions

Returns:

Triangle list

Raises:

TriangulationError – If triangulation fails

graphizy.algorithms.get_distance(position_array: ndarray, proximity_thresh: float, metric: str = 'euclidean') List[List[int]][source]

Filter points by proximity, return the points within specified distance of each point

Parameters:
  • position_array – Array of position of shape (n, 2)

  • proximity_thresh – Only keep points within this distance

  • metric – Type of distance calculated

Returns:

List of lists containing indices of nearby points

Raises:

GraphCreationError – If distance calculation fails

graphizy.algorithms.graph_delaunay(graph: Any, subdiv: Any, trilist: List) Any[source]

From CV to original ID and igraph

Parameters:
  • graph – igraph object

  • subdiv – OpenCV subdivision

  • trilist – List of triangles

Returns:

Modified graph

Raises:

GraphCreationError – If graph creation fails

graphizy.algorithms.graph_distance(graph: Any, position2d: ndarray, proximity_thresh: float, metric: str = 'euclidean') Any[source]

Construct a distance graph

Parameters:
  • graph – igraph Graph object

  • position2d – 2D position array

  • proximity_thresh – Distance threshold

  • metric – Distance metric

Returns:

Modified graph

Raises:

GraphCreationError – If distance graph creation fails

graphizy.algorithms.graph_distance_optimized(graph: Any, position2d: ndarray, proximity_thresh: float, metric: str = 'euclidean') Any[source]

Construct a distance graph using optimized vectorized operations

Parameters:
  • graph – igraph Graph object

  • position2d – 2D position array

  • proximity_thresh – Distance threshold

  • metric – Distance metric

Returns:

Modified graph with distance attributes on edges

Raises:

GraphCreationError – If distance graph creation fails

graphizy.algorithms.make_delaunay(subdiv: Any) ndarray[source]

Return a Delaunay triangulation

Parameters:

subdiv – An opencv subdivision

Returns:

A triangle list

Raises:

TriangulationError – If triangulation fails

graphizy.algorithms.make_subdiv(point_array: ndarray, dimensions: List | Tuple, do_print: bool = False) Any[source]

Make the opencv subdivision with enhanced error handling

Parameters:
  • point_array – A numpy array of the points to add

  • dimensions – The dimension of the image (width, height)

  • do_print – Whether to print debug information

Returns:

An opencv subdivision object

Raises:

SubdivisionError – If subdivision creation fails

graphizy.algorithms.normalize_distance_metric(metric: str) str[source]

Normalize distance metric names to scipy-compatible format.

Parameters:

metric – Distance metric name

Returns:

Scipy-compatible metric name

graphizy.algorithms.normalize_id(obj_id: Any) str[source]

Normalize object ID to consistent string format for real-time applications.

Optimized for performance: - Handles int, float, str inputs - Converts float IDs like 1.0, 2.0 to “1”, “2” - Preserves non-integer floats as-is

Parameters:

obj_id – Object ID of any type

Returns:

Normalized string ID

graphizy.cli module

Command Line Interface for graphizy

graphizy.cli.cmd_both(args) None[source]

Handle both command

graphizy.cli.cmd_delaunay(args) None[source]

Handle delaunay command

graphizy.cli.cmd_info(args) None[source]

Handle info command

graphizy.cli.cmd_memory(args)[source]

Handle memory command

graphizy.cli.cmd_proximity(args) None[source]

Handle proximity command

graphizy.cli.create_config_from_args(args) GraphizyConfig[source]

Create configuration from command line arguments

graphizy.cli.create_parser() ArgumentParser[source]

Create command line argument parser

graphizy.cli.generate_data(config: GraphizyConfig) ndarray[source]

Generate particle data

graphizy.cli.load_config(config_file: str) Dict[str, Any][source]

Load configuration from JSON file

graphizy.cli.main() None[source]

Main CLI entry point

graphizy.cli.parse_color(color_str: str) tuple[source]

Parse color string to tuple

graphizy.cli.setup_logging(verbose: bool) None[source]

Setup logging configuration

graphizy.config module

Configuration module for graphizy

class graphizy.config.DrawingConfig(line_color: Tuple[int, int, int] = (0, 255, 0), line_thickness: int = 1, point_color: Tuple[int, int, int] = (0, 0, 255), point_thickness: int = 3, point_radius: int = 8)[source]

Bases: object

Configuration for drawing parameters

line_color: Tuple[int, int, int] = (0, 255, 0)
line_thickness: int = 1
point_color: Tuple[int, int, int] = (0, 0, 255)
point_radius: int = 8
point_thickness: int = 3
class graphizy.config.GenerationConfig(size_x: int = 1200, size_y: int = 1200, num_particles: int = 200, to_array: bool = True, convert_to_float: bool = True)[source]

Bases: object

Configuration for position generation

convert_to_float: bool = True
num_particles: int = 200
size_x: int = 1200
size_y: int = 1200
to_array: bool = True
class graphizy.config.GraphConfig(dimension: ~typing.Tuple[int, int] = (1200, 1200), data_shape: list = <factory>, aspect: str = 'array', proximity_threshold: float = 50.0, distance_metric: str = 'euclidean')[source]

Bases: object

Configuration for graph creation parameters

aspect: str = 'array'
data_shape: list
dimension: Tuple[int, int] = (1200, 1200)
distance_metric: str = 'euclidean'
proximity_threshold: float = 50.0
class graphizy.config.GraphizyConfig(**kwargs)[source]

Bases: object

Master configuration class combining all config sections

copy() GraphizyConfig[source]

Create a deep copy of the configuration

drawing: DrawingConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.DrawingConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
generation: GenerationConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.GenerationConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
graph: GraphConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.GraphConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
logging: LoggingConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.LoggingConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
memory: MemoryConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.MemoryConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
set_drawing(**kwargs)[source]
set_generation(**kwargs)[source]
set_graph(**kwargs)[source]
set_logging(**kwargs)[source]
set_memory(**kwargs)[source]
to_dict() dict[source]

Convert configuration to dictionary

update(**kwargs)[source]

Update configuration values at runtime

weight: WeightConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.WeightConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
class graphizy.config.LoggingConfig(level: str = 'INFO', format: str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')[source]

Bases: object

Configuration for logging

format: str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
level: str = 'INFO'
class graphizy.config.MemoryConfig(max_memory_size: int = 3, max_iterations: int | None = None, auto_update_from_proximity: bool = True, memory_decay_factor: float = 1.0)[source]

Bases: object

Configuration for memory graph parameters

auto_update_from_proximity: bool = True
max_iterations: int | None = None
max_memory_size: int = 3
memory_decay_factor: float = 1.0
class graphizy.config.WeightConfig(auto_compute_weights: bool = True, weight_method: str = 'distance', normalize_weights: bool = True, weight_range: ~typing.Tuple[float, float] = (0.0, 1.0), distance_metric: str = 'euclidean', weight_attribute: str = 'weight', distance_attribute: str = 'distance', weight_formula: str | None = None, epsilon: float = 1e-10, default_value: float = 1.0, age_mode: str = 'exponential', decay_rate: float = 0.1, weight_factors: ~typing.Dict[str, float] = <factory>)[source]

Bases: object

Configuration for weight computation

age_mode: str = 'exponential'
auto_compute_weights: bool = True
decay_rate: float = 0.1
default_value: float = 1.0
distance_attribute: str = 'distance'
distance_metric: str = 'euclidean'
epsilon: float = 1e-10
normalize_weights: bool = True
weight_attribute: str = 'weight'
weight_factors: Dict[str, float]
weight_formula: str | None = None
weight_method: str = 'distance'
weight_range: Tuple[float, float] = (0.0, 1.0)

graphizy.drawing module

Drawing utilities for graphizy

class graphizy.drawing.Visualizer(config: DrawingConfig, dimension: Tuple[int, int])[source]

Bases: object

Handles all visualization tasks for Graphizy.

This class is responsible for drawing graphs, overlaying information, and managing the display or saving of the resulting images. It separates the visualization logic from the graph creation and analysis logic.

draw_graph(graph: Any, radius: int | None = None, thickness: int | None = None) ndarray[source]

Draw a graph to an image array with customizable appearance.

This is the primary method for converting igraph Graph objects into visual representations. It handles both vertices (as circles) and edges (as lines) with configurable styling.

Parameters:
  • graph – igraph Graph object with vertices having “x”, “y” coordinates

  • radius – Point radius override. If None, uses self.point_radius from config.

  • thickness – Point border thickness override. If None, uses self.point_thickness.

  • direct_show – If True, immediately display the graph using show_graph(). Convenient for interactive use.

  • kwargs_show – Additional parameters passed to show_graph() if direct_show=True. E.g., {‘title’: ‘My Graph’, ‘block’: False}

Returns:

RGB image array with shape (height, width, 3) and dtype uint8.

Background is black (0,0,0), drawn elements use configured colors.

Return type:

np.ndarray

Raises:

DrawingError – If graph is None, missing coordinates, or drawing operations fail.

Examples

>>> # Basic drawing
>>> graph = grapher.make_delaunay(data)
>>> image = grapher.draw_graph(graph)
>>> grapher.show_graph(image)
>>> # Custom appearance
>>> image = grapher.draw_graph(graph, radius=10, thickness=3)
>>> # Draw and show immediately
>>> image = grapher.draw_graph(
...     graph,
...     direct_show=True,
...     kwargs_show={'title': 'Delaunay Triangulation', 'block': True}
... )
>>> # Multiple graphs on same image
>>> image = grapher.draw_graph(delaunay_graph)
>>> image = grapher.overlay_graph(image, mst_graph)  # Overlay MST
>>> grapher.show_graph(image, title="Combined Graph")

Note

  • Graph must have vertex attributes “x” and “y” for coordinates

  • Coordinates are in image pixel space (0 to dimension)

  • Drawing order: edges first, then vertices (vertices on top)

  • Image dimensions set by self.dimension from config

  • Colors set by self.point_color and self.line_color from config

draw_memory_graph(graph: Any, radius: int | None = None, thickness: int | None = None, use_age_colors: bool = True, alpha_range: Tuple[float, float] = (0.3, 1.0)) ndarray[source]

Draw memory graph with optional age-based edge coloring and transparency.

This specialized drawing method can visualize temporal information by varying edge appearance based on connection age/persistence in memory. Newer or more frequent connections can be highlighted while older connections are drawn more subtly.

Parameters:
  • graph – igraph Graph object to draw

  • radius – Point radius override. If None, uses config default.

  • thickness – Point thickness override. If None, uses config default.

  • use_age_colors – Whether to apply age-based styling to edges. If True, requires memory_manager with age tracking enabled.

  • alpha_range – (min_alpha, max_alpha) tuple for transparency range. Older connections use min_alpha, newer use max_alpha.

Returns:

Image array representing the drawn graph.

Return type:

np.ndarray

Raises:

DrawingError – If drawing fails or memory manager required but not available.

Examples

>>> # Basic memory graph drawing
>>> memory_graph = grapher.make_memory_graph(data)
>>> image = grapher.draw_memory_graph(memory_graph)
>>> grapher.show_graph(image, title="Memory Graph")
>>> # Custom age-based visualization
>>> image = grapher.draw_memory_graph(
...     memory_graph,
...     use_age_colors=True,
...     alpha_range=(0.1, 1.0),  # Very faded old connections
...     radius=8,
...     thickness=2
... )
>>> # Disable age coloring for standard appearance
>>> image = grapher.draw_memory_graph(
...     memory_graph,
...     use_age_colors=False
... )

Note

  • Age-based coloring requires memory manager with track_edge_ages=True

  • Alpha blending may not be supported in all drawing backends

  • Performance may be slower with age-based coloring for large graphs

  • Falls back to standard drawing if age information unavailable

overlay_collision(image_graph: ndarray, graph: Any) ndarray[source]

Overlay collision/intersection points on graph edges.

This debugging/analysis method draws midpoints of all edges with prominent markers. Useful for visualizing edge density, detecting potential intersections, or highlighting edge midpoints for analysis.

Parameters:
  • image_graph – Existing image array to draw on. Modified in-place.

  • graph – igraph Graph object with edges to mark.

Returns:

The modified image array with collision points added.

Return type:

np.ndarray

Raises:

DrawingError – If either image or graph is None, or if drawing operations fail.

Examples

>>> # Visualize edge midpoints for analysis
>>> graph = grapher.make_delaunay(data)
>>> image = grapher.draw_graph(graph)
>>> image = grapher.overlay_collision(image, graph)
>>> grapher.show_graph(image, title="Graph with Edge Midpoints")
>>> # Analyze edge density in different regions
>>> dense_graph = grapher.make_proximity(data, proximity_thresh=50)
>>> image = grapher.draw_graph(dense_graph)
>>> image = grapher.overlay_collision(image, dense_graph)

Note

  • Collision points are drawn as large, prominent circles

  • Useful for debugging edge placement and density analysis

  • Midpoint calculation uses integer arithmetic (may have rounding)

  • Collision markers use current point_color configuration

overlay_graph(image_graph: ndarray, graph: Any) ndarray[source]

Overlay additional graph elements onto an existing image.

This method allows combining multiple graphs in a single visualization by drawing additional vertices and edges on top of an existing image. Useful for comparing different graph types or showing graph evolution.

Parameters:
  • image_graph – Existing image array to draw on. Modified in-place.

  • graph – igraph Graph object to overlay with vertices having “x”, “y” coordinates.

Returns:

The modified image array (same object as input for chaining).

Return type:

np.ndarray

Raises:

DrawingError – If either image or graph is None, or if drawing operations fail.

Examples

>>> # Compare Delaunay triangulation with MST
>>> delaunay_graph = grapher.make_delaunay(data)
>>> mst_graph = grapher.make_mst(data)
>>>
>>> # Draw Delaunay as base
>>> image = grapher.draw_graph(delaunay_graph)
>>>
>>> # Overlay MST with different color
>>> grapher.update_config(line_color=(255, 0, 0))  # Red for MST
>>> image = grapher.overlay_graph(image, mst_graph)
>>> grapher.show_graph(image, title="Delaunay + MST")
>>> # Chain multiple overlays
>>> image = grapher.draw_graph(delaunay_graph)
>>> image = grapher.overlay_graph(image, mst_graph)
>>> image = grapher.overlay_graph(image, knn_graph)

Note

  • Image is modified in-place and also returned for method chaining

  • Overlay uses current drawing configuration (colors, thickness, etc.)

  • Later overlays draw on top of earlier ones

  • Vertices are drawn on top of edges within each overlay

  • Consider using different colors for different overlays

save_graph(image_graph: ndarray, filename: str) None[source]

Save a graph image to a file.

show_graph(image_graph: ndarray, title: str = 'Graphizy', **kwargs) None[source]

Display a graph image in a window.

update_config(config: DrawingConfig, dimension: Tuple[int, int])[source]

Update the visualizer’s configuration at runtime.

graphizy.drawing.create_memory_graph_image(graph: Any, memory_manager: Any, dimension: Tuple[int, int], point_color: Tuple[int, int, int] = (0, 0, 255), line_color: Tuple[int, int, int] = (0, 255, 0), point_radius: int = 8, point_thickness: int = 3, line_thickness: int = 1, use_age_colors: bool = True, alpha_range: Tuple[float, float] = (0.3, 1.0)) ndarray[source]

Create a complete memory graph image

Parameters:
  • graph – igraph Graph object

  • memory_manager – MemoryManager instance

  • dimension – Image dimensions (width, height)

  • point_color – Color for points (B, G, R)

  • line_color – Base color for lines (B, G, R)

  • point_radius – Point radius

  • point_thickness – Point thickness

  • line_thickness – Line thickness

  • use_age_colors – Whether to use age-based edge coloring

  • alpha_range – (min_alpha, max_alpha) for age-based transparency

Returns:

Image array

Raises:

DrawingError – If image creation fails

graphizy.drawing.draw_delaunay(img: ndarray, subdiv: Any, color_line: Tuple[int, int, int] = (0, 255, 0), thickness_line: int = 1, color_point: Tuple[int, int, int] = (0, 0, 255), thickness_point: int = 1) None[source]

Draw delaunay triangles from openCV Subdiv2D

Parameters:
  • img – Image to draw on

  • subdiv – OpenCV Subdiv2D object

  • color_line – Line color (B, G, R)

  • thickness_line – Line thickness

  • color_point – Point color (B, G, R)

  • thickness_point – Point thickness

Raises:

DrawingError – If drawing operation fails

graphizy.drawing.draw_line(img: ndarray, x0: int, y0: int, x1: int, y1: int, color: Tuple[int, int, int], thickness: int = 1) None[source]

Draw a line on the image with enhanced error handling

Parameters:
  • img – Image array to draw on

  • x0 – Start point coordinates

  • y0 – Start point coordinates

  • x1 – End point coordinates

  • y1 – End point coordinates

  • color – Color tuple (B, G, R)

  • thickness – Line thickness

Raises:

DrawingError – If drawing operation fails

graphizy.drawing.draw_memory_graph_with_aging(img: ndarray, graph: Any, memory_manager: Any, point_color: Tuple[int, int, int], line_color: Tuple[int, int, int], point_radius: int = 8, point_thickness: int = 3, line_thickness: int = 1, use_age_colors: bool = True, alpha_range: Tuple[float, float] = (0.3, 1.0)) None[source]

Draw memory graph with optional edge aging visualization

Parameters:
  • img – Image array to draw on

  • graph – igraph Graph object

  • memory_manager – MemoryManager instance (for edge ages)

  • point_color – Color for points (B, G, R)

  • line_color – Base color for lines (B, G, R)

  • point_radius – Point radius

  • point_thickness – Point thickness

  • line_thickness – Line thickness

  • use_age_colors – Whether to use age-based edge coloring

  • alpha_range – (min_alpha, max_alpha) for age-based transparency

Raises:

DrawingError – If drawing operation fails

graphizy.drawing.draw_point(img: ndarray, p: Tuple[float, float], color: Tuple[int, int, int], radius: int = 4, thickness: int = 1) None[source]

Draw a point on the image with enhanced error handling

Parameters:
  • img – Image array to draw on

  • p – Point coordinates (x, y)

  • color – Color tuple (B, G, R)

  • radius – Point radius

  • thickness – Line thickness

Raises:

DrawingError – If drawing operation fails

graphizy.drawing.save_graph(image_graph: ndarray, filename: str) None[source]

Save graph image to file.

This is a convenience wrapper around the global save_graph function that handles various image formats and provides error handling.

Parameters:
  • image_graph – Image array to save with shape (height, width, 3).

  • filename – Output filename with extension. Extension determines format (e.g., .png, .jpg, .tiff, .bmp).

Examples

>>> image = grapher.draw_graph(graph)
>>> Graphing.save_graph(image, "delaunay_triangulation.png")
>>> # Save with timestamp
>>> import datetime
>>> timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
>>> filename = f"graph_{timestamp}.png"
>>> Graphing.save_graph(image, filename)

Note

  • File format determined by extension

  • Overwrites existing files without warning

  • Directory must exist (not created automatically)

  • Static method can be called without Graphing instance

graphizy.drawing.show_graph(image_graph: ndarray, title: str = 'My beautiful graph', block: bool = False, delay_display: int = 100) None[source]

Display a graph image using the configured display backend.

This is a convenience wrapper around the global show_graph function that provides consistent image display with customizable options.

Parameters:
  • image_graph – Image array to display with shape (height, width, 3).

  • title – Window title for the display.

  • **kwargs – Additional arguments passed to the underlying show_graph function: - block: Whether to block execution until window is closed - delay_display: Delay before showing (for animations) - save_path: Optionally save image while displaying - Backend-specific options

Examples

>>> image = grapher.draw_graph(graph)
>>> Graphing.show_graph(image, title="Delaunay Triangulation")
>>> # Non-blocking display for animations
>>> Graphing.show_graph(image, title="Animation Frame", block=False)
>>> # Display with save
>>> Graphing.show_graph(
...     image,
...     title="Final Result",
...     save_path="output.png"
... )

Note

  • Display backend depends on system configuration (matplotlib, opencv, etc.)

  • Window behavior (blocking, resizing) depends on backend

  • Static method can be called without Graphing instance

graphizy.exceptions module

Custom exceptions for graphizy package with enhanced error tracking

exception graphizy.exceptions.ConfigurationError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: GraphizyError

Raised when configuration is invalid

exception graphizy.exceptions.DependencyError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: GraphizyError

Raised when required dependencies are missing

exception graphizy.exceptions.DrawingError(message: str, image=None, point=None, **kwargs)[source]

Bases: GraphizyError

Raised when drawing operations fail

exception graphizy.exceptions.GraphCreationError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: GraphizyError

Raised when graph creation fails

exception graphizy.exceptions.GraphizyError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: Exception

Base exception for all graphizy errors with enhanced debugging

log_error() None[source]

Log this error with full context

exception graphizy.exceptions.IgraphMethodError(message: str, method_name: str | None = None, graph_info: Dict[str, Any] | None = None, **kwargs)[source]

Bases: GraphizyError

Raised when igraph method execution fails

exception graphizy.exceptions.InvalidAspectError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: GraphizyError

Raised when invalid aspect is provided

exception graphizy.exceptions.InvalidDataShapeError(message: str, data_shape: Any | None = None, **kwargs)[source]

Bases: GraphizyError

Raised when invalid data shape is provided

exception graphizy.exceptions.InvalidDimensionError(message: str, dimensions: Any | None = None, **kwargs)[source]

Bases: GraphizyError

Raised when invalid dimensions are provided

exception graphizy.exceptions.InvalidPointArrayError(message: str, array_info: Dict[str, Any] | None = None, **kwargs)[source]

Bases: GraphizyError

Raised when invalid point array is provided

exception graphizy.exceptions.PositionGenerationError(message: str, size_x: int | None = None, size_y: int | None = None, num_particles: int | None = None, **kwargs)[source]

Bases: GraphizyError

Raised when position generation fails

exception graphizy.exceptions.SubdivisionError(message: str, point_array=None, dimensions=None, **kwargs)[source]

Bases: GraphizyError

Raised when OpenCV subdivision fails

exception graphizy.exceptions.TriangulationError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: GraphizyError

Raised when Delaunay triangulation fails

graphizy.exceptions.handle_subdivision_bounds_error(point_array, dimensions, coordinate_type='x')[source]

Create detailed subdivision bounds error

graphizy.exceptions.log_warning_with_context(message: str, **context)[source]

Log warning with context without raising exception

graphizy.utils module

Just some utilities functions

graphizy.utils.setup_output_directory()[source]

Create output directory for saving images

graphizy.utils.validate_graphizy_input(data_points, aspect='array', data_shape=None, dimension=(1200, 1200), proximity_thresh=None, verbose=True)[source]

Helper function to validate input data for graphizy operations

Parameters:
  • data_points – Input data (numpy array or dict)

  • aspect – “array” or “dict”

  • data_shape – Expected data shape structure

  • dimension – Image dimensions (width, height)

  • proximity_thresh – Proximity threshold if applicable

  • verbose – Print detailed validation info

Returns:

Validation results with errors, warnings, and info

Return type:

dict

graphizy.streaming module

Real-time data streaming managers for Graphizy.

This module provides both thread-based and asyncio-based managers for handling real-time data streams, processing them into graphs, and invoking callbacks.

class graphizy.streaming.AsyncStreamManager(grapher: Graphing, buffer_size: int = 1000)[source]

Bases: object

Async version of StreamManager for high-throughput applications using asyncio.

add_callback(callback: Callable[[Any], None]) None[source]

Add a callback function to be called on each graph update.

async push_data(data_points: ndarray) bool[source]

Push data asynchronously without blocking.

async start_streaming() None[source]

Start the async streaming task.

async stop_streaming() None[source]

Stop the async streaming task gracefully.

class graphizy.streaming.StreamManager(grapher: Graphing, buffer_size: int = 1000, update_interval: float = 0.1, auto_memory: bool = True)[source]

Bases: object

Manages streaming data processing for real-time graph updates using threads.

add_callback(callback: Callable[[Any], None]) None[source]

Add a callback function to be called on each graph update.

push_data(data_points: ndarray) bool[source]

Push new data to the streaming queue.

Returns:

True if data was queued, False if the queue is full.

Return type:

bool

start_streaming() None[source]

Start the streaming processing thread.

stop_streaming() None[source]

Stop the streaming processing thread.

Module contents

Graphizy - A graph maker for computational geometry and network visualization

class graphizy.AccessibilityAnalyzer(grapher: Graphing)[source]

Bases: object

Analyzer for spatial accessibility and service coverage.

This class provides tools for analyzing urban accessibility, service coverage, and spatial equity in service distribution.

analyze_service_accessibility(population_points: ndarray, service_points: ndarray, service_type: str, service_distance: float) AccessibilityResult[source]

Analyze accessibility to urban services.

Parameters:
  • population_points – Array of population locations [id, x, y]

  • service_points – Array of service locations [id, x, y]

  • service_type – Type of service being analyzed

  • service_distance – Maximum acceptable distance to service

Returns:

AccessibilityResult with coverage analysis

compare_accessibility(results_list: List[AccessibilityResult]) Dict[str, Any][source]

Compare accessibility across multiple services or scenarios.

Parameters:

results_list – List of AccessibilityResult objects

Returns:

Dictionary with comparative analysis

identify_service_gaps(accessibility_result: AccessibilityResult, cluster_distance: float = 200.0) List[Dict][source]

Identify spatial clusters of underserved areas (service gaps).

Parameters:
  • accessibility_result – Result from analyze_service_accessibility

  • cluster_distance – Distance threshold for clustering underserved areas

Returns:

List of service gap clusters with statistics

class graphizy.AccessibilityResult(service_type: str, service_distance: float, population_count: int, service_count: int, coverage_statistics: Dict[str, float], underserved_areas: List[Dict])[source]

Bases: object

Results from accessibility analysis

coverage_statistics: Dict[str, float]
get_coverage_percentage() float[source]
get_equity_score() float[source]

Calculate spatial equity score (higher = more equitable)

population_count: int
service_count: int
service_distance: float
service_type: str
underserved_areas: List[Dict]
class graphizy.BrownianSimulator(width: int = 800, height: int = 600, num_particles: int = 50, use_memory: bool = False, memory_size: int = 25)[source]

Bases: object

Brownian motion simulation using the new graph update system

add_info_overlay(image: ndarray, graph_type: int, time_graph_update: float | None = None) ndarray[source]

Add information overlay to the image

adjust_memory_size(delta: int)[source]

Adjust memory size during simulation

create_visualization(graph_type: int) Tuple[ndarray, float] | None[source]

Create visualization using the simplified update system

handle_keyboard_input(key: int) bool[source]

Handle keyboard input. Returns False if should exit.

run_simulation(graph_type: int = 1, max_iterations: int = 1000, fps: int = 30)[source]

Main interactive simulation loop

toggle_memory()[source]

Toggle memory on/off during simulation

update_positions(dt: float = 1.0)[source]

Update particle positions using Brownian motion

exception graphizy.ConfigurationError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: GraphizyError

Raised when configuration is invalid

class graphizy.DataInterface(data_shape: List[Tuple[str, type]] | None = None)[source]

Bases: object

Interface for handling different data formats

getidx_id() int[source]

Get index of id column

getidx_xpos() int[source]

Get index of x position column

getidx_ypos() int[source]

Get index of y position column

to_array(data_points: ndarray | Dict[str, Any], validate_data: bool = False) ndarray[source]

Convert data points to standardized array format.

Automatically detects input format and converts accordingly.

Parameters:
  • data_points – Input data in array or dict format

  • validate_data – Whether to validate the data (careful at each call this will degrade the performances)

Returns:

Data in standardized array format

Return type:

np.ndarray

Raises:

InvalidPointArrayError – If conversion fails or data is invalid

to_dict(point_array: ndarray) Dict[str, Any][source]

Convert point array to dictionary format

Parameters:

point_array – Array to convert

Returns:

Dictionary with id, x, y keys

Raises:

InvalidPointArrayError – If conversion fails

validate_array(point_array: ndarray) None[source]

Validate that array has the correct structure for this data interface.

Parameters:

point_array – Array to validate

Raises:

InvalidPointArrayError – If array structure is invalid

exception graphizy.DependencyError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: GraphizyError

Raised when required dependencies are missing

class graphizy.DrawingConfig(line_color: Tuple[int, int, int] = (0, 255, 0), line_thickness: int = 1, point_color: Tuple[int, int, int] = (0, 0, 255), point_thickness: int = 3, point_radius: int = 8)[source]

Bases: object

Configuration for drawing parameters

line_color: Tuple[int, int, int] = (0, 255, 0)
line_thickness: int = 1
point_color: Tuple[int, int, int] = (0, 0, 255)
point_radius: int = 8
point_thickness: int = 3
exception graphizy.DrawingError(message: str, image=None, point=None, **kwargs)[source]

Bases: GraphizyError

Raised when drawing operations fail

class graphizy.GenerationConfig(size_x: int = 1200, size_y: int = 1200, num_particles: int = 200, to_array: bool = True, convert_to_float: bool = True)[source]

Bases: object

Configuration for position generation

convert_to_float: bool = True
num_particles: int = 200
size_x: int = 1200
size_y: int = 1200
to_array: bool = True
class graphizy.GraphAnalysisResult(graph: Graph, grapher: Graphing)[source]

Bases: object

A lazy-loading object holding the results of a graph analysis.

This object behaves like both a standard object (e.g., results.density) and a dictionary (e.g., results[‘density’]), providing maximum flexibility.

Metrics are computed on-demand the first time they are accessed and then cached for subsequent calls.

property accessibility_analyzer: AccessibilityAnalyzer

Get accessibility analyzer instance (lazy-loaded)

property average_path_length: float | None

Returns the average shortest path length of the largest component. (Cached)

property density: float

Returns the graph density. (Cached on first access)

property diameter: int | None

Returns the diameter of the largest component. (Cached)

property edge_count: int

Returns the number of edges. (Cached on first access)

get_metric(metric_name: str, **kwargs) Any[source]

Computes any igraph metric on the fly using the robust call_method_safe. Results are cached to avoid re-computation.

For dictionary results, entries with None values are filtered out.

get_metric_stats(metric_name: str, **kwargs) Dict[str, float][source]

Computes descriptive statistics for a numeric metric. Handles None values by ignoring them in the calculation.

get_top_n_by(metric_name: str, n: int = 5, **kwargs) List[tuple][source]

Returns the top N nodes sorted by a given per-vertex metric. Handles None values by treating them as the lowest possible value.

property is_connected: bool

Returns True if the graph is fully connected. (Cached on first access)

property num_components: int

Returns the number of disconnected components. (Cached on first access)

property percolation_analyzer: PercolationAnalyzer

Get percolation analyzer instance (lazy-loaded)

property social_analyzer: SocialNetworkAnalyzer

Get social network analyzer instance (lazy-loaded)

summary() str[source]

Provides a clean, readable summary of the key metrics.

property transitivity: float | None

Returns the global clustering coefficient (transitivity). (Cached)

property vertex_count: int

Returns the number of vertices. (Cached on first access)

class graphizy.GraphConfig(dimension: ~typing.Tuple[int, int] = (1200, 1200), data_shape: list = <factory>, aspect: str = 'array', proximity_threshold: float = 50.0, distance_metric: str = 'euclidean')[source]

Bases: object

Configuration for graph creation parameters

aspect: str = 'array'
data_shape: list
dimension: Tuple[int, int] = (1200, 1200)
distance_metric: str = 'euclidean'
proximity_threshold: float = 50.0
exception graphizy.GraphCreationError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: GraphizyError

Raised when graph creation fails

class graphizy.GraphTypeInfo(name: str, description: str, parameters: Dict[str, Dict[str, Any]], category: str = 'custom', author: str = '', version: str = '1.0.0', requires_external_deps: bool = False, external_deps: list | None = None)[source]

Bases: object

Information about a graph type for documentation and discovery

author: str = ''
category: str = 'custom'
description: str
external_deps: list = None
name: str
parameters: Dict[str, Dict[str, Any]]
requires_external_deps: bool = False
version: str = '1.0.0'
class graphizy.GraphTypePlugin[source]

Bases: ABC

Abstract base class for graph type plugins

abstract create_graph(data_points: ndarray, dimension: tuple, data_shape: List[Tuple[str, Any]] | None = None, **kwargs) Any[source]

Create a graph from the given data points.

Parameters:
  • data_points – Standardized NumPy array of shape (n, m).

  • dimension – Image dimensions (width, height).

  • data_shape – List of tuples defining the data structure.

  • **kwargs – Algorithm-specific parameters.

Returns:

igraph Graph object.

abstract property info: GraphTypeInfo

Return information about this graph type

validate_parameters(**kwargs) Dict[str, Any][source]

Validate and process parameters for this graph type.

class graphizy.Graphing(config: GraphizyConfig | None = None, **kwargs)[source]

Bases: object

Main graphing class for creating and visualizing various types of graphs.

This class provides a unified interface for creating different types of graphs from point data, including geometric graphs (Delaunay, Gabriel), proximity-based graphs (k-NN, proximity), and spanning trees. It also supports memory-based graphs for temporal analysis and comprehensive graph visualization.

The class supports two data formats: - “array”: NumPy arrays with columns [id, x, y] - “dict”: Dictionaries with keys “id”, “x”, “y”

config

Configuration object containing graph and drawing settings

Type:

GraphizyConfig

dimension

Canvas dimensions (width, height)

Type:

Tuple[int, int]

aspect

Data format (“array” or “dict”)

Type:

str

dinter

Data interface for handling different data formats

Type:

DataInterface

memory_manager

Optional memory manager for temporal graphs

Type:

MemoryManager

# Drawing configuration shortcuts
line_thickness

Thickness of graph edges

Type:

int

line_color

RGB color for edges

Type:

Tuple[int, int, int]

point_thickness

Thickness of point borders

Type:

int

point_radius

Radius of graph vertices

Type:

int

point_color

RGB color for vertices

Type:

Tuple[int, int, int]

Examples

>>> # Basic initialization
>>> grapher = Graphing(dimension=(800, 600), aspect="array")
>>> # With custom configuration
>>> config = GraphizyConfig()
>>> config.drawing.line_color = (255, 0, 0)  # Red edges
>>> grapher = Graphing(config=config)
>>> # Create and visualize a graph
>>> data = np.random.rand(50, 3)
>>> graph = grapher.make_delaunay(data)
>>> image = grapher.draw_graph(graph)
>>> grapher.show_graph(image)
static average_path_length(graph: Any) float[source]

Calculate the average shortest path length between all pairs of vertices.

This metric indicates how “close” vertices are to each other on average. Lower values suggest better connectivity and shorter communication paths.

Parameters:

graph – igraph Graph object, must be connected for meaningful results.

Returns:

Average path length across all vertex pairs.

Return type:

float

Raises:

IgraphMethodError – If calculation fails (e.g., disconnected graph).

Examples

>>> avg_path = Graphing.average_path_length(graph)
>>> print(f"Average path length: {avg_path:.2f}")
>>> # Compare different graph types
>>> delaunay_avg = Graphing.average_path_length(delaunay_graph)
>>> mst_avg = Graphing.average_path_length(mst_graph)
>>> print(f"Delaunay: {delaunay_avg:.2f}, MST: {mst_avg:.2f}")

Note

  • Requires connected graph (use call_method_safe for disconnected graphs)

  • Computed over all pairs of vertices

  • Values typically range from 1 (complete graph) to n-1 (path graph)

  • Higher values indicate less efficient connectivity

call_method_brutal(graph: Any, method_name: str, return_format: str = 'auto', *args, **kwargs) Any[source]

Call any igraph method with intelligent return type formatting.

This method provides flexible access to igraph’s extensive method library with automatic formatting of results into user-friendly formats. It handles the conversion between igraph’s internal representations and more intuitive Python data structures.

Parameters:
  • graph – igraph Graph object to operate on.

  • method_name – Name of the igraph method to call (e.g., “betweenness”, “closeness”).

  • return_format – Output format specification: - “auto”: Intelligent format detection (recommended) - “dict”: Force dict format {object_id: value} for per-vertex results - “list”: Force list format [value1, value2, …] for array results - “raw”: Return exactly what igraph provides (no processing)

  • *args – Positional arguments passed to the igraph method.

  • **kwargs – Keyword arguments passed to the igraph method.

Returns:

Method result formatted according to return_format:
  • Per-vertex results: dict mapping object_id -> value (auto/dict)

  • Per-edge results: list of values (auto/list)

  • Scalar results: single value (all formats)

  • Complex results: depends on method and format

Return type:

Any

Raises:

Examples

>>> # Get degree centrality as dict
>>> degrees = grapher.call_method_brutal(graph, "degree", "dict")
>>> print(f"Object 5 degree: {degrees[5]}")
>>> # Get betweenness centrality with auto-formatting
>>> betweenness = grapher.call_method_brutal(graph, "betweenness")
>>> # Returns dict {object_id: betweenness_value}
>>> # Get raw igraph output
>>> raw_closeness = grapher.call_method_brutal(graph, "closeness", "raw")
>>> # Call method with parameters
>>> shortest_paths = grapher.call_method_brutal(
...     graph, "shortest_paths", "raw",
...     source=0, target=5
... )
>>> # Edge-related method (returns list)
>>> edge_betweenness = grapher.call_method_brutal(graph, "edge_betweenness")

Note

  • “auto” format is usually the most convenient

  • Per-vertex methods automatically map to object IDs when possible

  • Some methods may not support all return formats

  • Use “raw” format when you need igraph’s exact output

  • Method availability depends on igraph version and graph type

static call_method_raw(graph: Any, method_name: str, *args, **kwargs) Any[source]

Call any igraph method on the graph, returning unformatted output.

This method provides direct access to igraph’s methods without any processing or formatting of the results. Useful when you need the exact output format that igraph provides.

Parameters:
  • graph – igraph Graph object to operate on.

  • method_name – Name of the igraph method to call.

  • *args – Positional arguments for the method.

  • **kwargs – Keyword arguments for the method.

Returns:

Exact result from the igraph method call, no processing applied.

Return type:

Any

Raises:

IgraphMethodError – If method call fails or method doesn’t exist.

Examples

>>> # Get raw degree sequence
>>> raw_degrees = Graphing.call_method_raw(graph, "degree")
>>> print(type(raw_degrees))  # <class 'list'>
>>> # Get raw connected components
>>> raw_components = Graphing.call_method_raw(graph, "connected_components")
>>> print(type(raw_components))  # igraph-specific type
>>> # Call with parameters
>>> raw_paths = Graphing.call_method_raw(
...     graph, "shortest_paths",
...     source=0, target=[1, 2, 3]
... )

Note

  • No processing, formatting, or error handling beyond basic method call

  • Returns exactly what igraph provides (may be igraph-specific types)

  • Use when you need maximum control over the output format

  • Static method - can be called without Graphing instance

call_method_safe(graph: Any, method_name: str, return_format: str = 'auto', component_mode: str = 'connected_only', handle_disconnected: bool = True, default_value: Any | None = None, *args, **kwargs) Any[source]

Resilient version of call_method that handles disconnected graphs intelligently.

Many graph algorithms fail on disconnected graphs. This method provides robust computation by applying different strategies for handling disconnected components, with graceful fallback to default values when computation fails.

Parameters:
  • graph – igraph Graph object to analyze.

  • method_name – Name of the igraph method to call.

  • return_format – Output format (“auto”, “dict”, “list”, “raw”).

  • component_mode – Strategy for disconnected graphs: - “all”: Compute on all components separately - “largest”: Compute only on largest component - “connected_only”: Compute only on components with >1 vertex

  • handle_disconnected – Whether to apply special disconnected graph handling.

  • default_value – Value to return/use when computation fails (default: None).

  • *args – Positional arguments for the igraph method.

  • **kwargs – Keyword arguments for the igraph method.

Returns:

Method result with appropriate disconnected graph handling and formatting.

Return type:

Any

Examples

>>> # Safe diameter computation (fails on disconnected graphs normally)
>>> diameter = grapher.call_method_safe(graph, "diameter", default_value=float('inf'))
>>> # Betweenness centrality for all components
>>> betweenness = grapher.call_method_safe(
...     graph, "betweenness", "dict",
...     component_mode="all", default_value=0.0
... )
>>> # Average path length only for largest component
>>> avg_path = grapher.call_method_safe(
...     graph, "average_path_length",
...     component_mode="largest", default_value=None
... )
>>> # Robust clustering coefficient
>>> clustering = grapher.call_method_safe(
...     graph, "transitivity_local_undirected", "dict",
...     component_mode="connected_only", default_value=0.0
... )

Note

  • Automatically detects connectivity-sensitive methods

  • Provides meaningful results even for highly fragmented graphs

  • Maps component-level results back to full graph vertex space

  • Graceful degradation with informative logging

  • Essential for robust analysis pipelines

clear_graph_types()[source]

Clear all configured graph types and current graphs.

compute_all_attributes_fast(graph)[source]

Compute all pre-configured attributes quickly.

compute_component_metrics(graph: Any, metrics_list: List[str], component_mode: str = 'largest') Dict[str, Any][source]

Compute multiple graph metrics with consistent component handling.

This method efficiently computes multiple metrics on the same graph with unified handling of disconnected components. Ideal for comprehensive graph analysis with consistent treatment of connectivity issues.

Parameters:
  • graph – igraph Graph object to analyze.

  • metrics_list

    List of metric names to compute. Examples: [‘degree’, ‘betweenness’, ‘closeness’, ‘diameter’,

    ’transitivity_undirected’, ‘average_path_length’]

  • component_mode – Strategy for disconnected graphs (“all”, “largest”, “connected_only”).

Returns:

Dictionary with computed metrics:
  • connectivity_info: Detailed connectivity analysis

  • [metric_name]: Result for each requested metric

  • Failed metrics are set to None with warning logged

Return type:

Dict[str, Any]

Examples

>>> # Comprehensive analysis of a graph
>>> metrics = grapher.compute_component_metrics(
...     graph,
...     ['degree', 'betweenness', 'closeness', 'diameter', 'transitivity_undirected'],
...     component_mode="all"
... )
>>>
>>> print(f"Graph diameter: {metrics['diameter']}")
>>> print(f"Average degree: {np.mean(list(metrics['degree'].values()))}")
>>>
>>> # Check connectivity
>>> if not metrics['connectivity_info']['is_connected']:
...     print(f"Warning: Graph has {metrics['connectivity_info']['num_components']} components")
>>> # Focus on largest component only
>>> largest_metrics = grapher.compute_component_metrics(
...     graph,
...     ['average_path_length', 'diameter', 'betweenness'],
...     component_mode="largest"
... )

Note

  • Provides comprehensive analysis in a single call

  • Handles disconnected graphs gracefully

  • Includes connectivity analysis automatically

  • Failed metrics are logged but don’t stop other computations

  • Efficient for multiple related metrics on same graph

compute_edge_attribute(graph, attribute_name, method='formula', **kwargs)[source]

Compute any edge attribute.

create_async_stream_manager(buffer_size: int = 1000) AsyncStreamManager[source]

Create async stream manager for high-performance streaming

create_stream_manager(buffer_size: int = 1000, update_interval: float = 0.1, auto_memory: bool = True) StreamManager[source]

Create a stream manager for real-time data processing

static density(graph: Any) float[source]

Calculate the density of the graph.

Density is the ratio of actual edges to possible edges, indicating how close the graph is to being complete. Values range from 0 (no edges) to 1 (complete graph).

Parameters:

graph – igraph Graph object.

Returns:

Graph density between 0.0 and 1.0.

Return type:

float

Examples

>>> density = Graphing.density(graph)
>>> print(f"Graph density: {density:.3f} ({density*100:.1f}% of possible edges)")
>>> # Compare sparsity of different graph types
>>> print(f"Delaunay density: {Graphing.density(delaunay_graph):.3f}")
>>> print(f"MST density: {Graphing.density(mst_graph):.3f}")
>>> print(f"k-NN density: {Graphing.density(knn_graph):.3f}")

Note

  • MSTs have density 2(n-1)/(n(n-1)) = 2/(n) for n vertices

  • Complete graphs have density 1.0

  • Empty graphs have density 0.0

  • Useful for comparing graph sparsity

draw_all_graphs(**kwargs) Dict[str, ndarray][source]

Draw all current graphs to image arrays.

Parameters:

**kwargs – Drawing parameters passed to draw_graph().

Returns:

Dictionary mapping graph types to image arrays.

Return type:

Dict[str, np.ndarray]

draw_graph(graph: Any, **kwargs) ndarray[source]

Draw a graph to an image array.

This method provides a convenient top-level API by delegating the drawing task to the internal Visualizer instance.

Parameters:
  • graph – igraph Graph object to draw.

  • **kwargs – Additional arguments for the visualizer, e.g., ‘radius’, ‘thickness’.

Returns:

An RGB image array of the drawn graph.

Return type:

np.ndarray

draw_memory_graph(graph: Any, **kwargs) ndarray[source]

Draw a memory graph with optional age-based coloring.

Delegates to the Visualizer’s draw_memory_graph method.

Parameters:
  • graph – igraph Graph object to draw.

  • **kwargs – Additional arguments like ‘use_age_colors’, ‘alpha_range’.

Returns:

An RGB image array of the drawn memory graph.

Return type:

np.ndarray

property drawing_config: DrawingConfig

Get current drawing configuration.

Returns:

Current drawing configuration object containing

line and point styling parameters.

Return type:

DrawingConfig

static get_connections_per_object(graph: Any) Dict[Any, int][source]

Calculate the degree (number of connections) for each vertex in the graph.

This method provides a user-friendly mapping from original object IDs to their connectivity counts, which is essential for analyzing graph structure and identifying hubs or isolated nodes.

Parameters:

graph – igraph Graph object with vertices having “id” attributes.

Returns:

Dictionary mapping each object’s original ID to its degree.

Empty dict if graph is None or has no vertices.

Return type:

Dict[Any, int]

Raises:

IgraphMethodError – If degree calculation fails.

Examples

>>> connections = Graphing.get_connections_per_object(graph)
>>> print(f"Object 101 has {connections[101]} connections")
>>>
>>> # Find most connected objects
>>> sorted_objects = sorted(connections.items(), key=lambda x: x[1], reverse=True)
>>> print(f"Most connected: {sorted_objects[:5]}")
>>>
>>> # Find isolated objects
>>> isolated = [obj_id for obj_id, degree in connections.items() if degree == 0]
>>> print(f"Isolated objects: {isolated}")
>>> # Degree distribution analysis
>>> from collections import Counter
>>> degree_dist = Counter(connections.values())
>>> print(f"Degree distribution: {dict(degree_dist)}")

Note

  • Returns degree in graph-theoretic sense (number of incident edges)

  • For undirected graphs, each edge contributes 1 to each endpoint’s degree

  • For directed graphs, returns total degree (in-degree + out-degree)

  • Empty graphs return empty dictionary

  • Object IDs must be stored in vertex “id” attribute

get_connectivity_info(graph: Any) Dict[str, Any][source]

Get comprehensive connectivity information about the graph.

This method analyzes the graph’s connectivity structure, identifying connected components and providing statistics about graph cohesion. Essential for understanding graph topology and planning analyses.

Parameters:

graph – igraph Graph object to analyze.

Returns:

Comprehensive connectivity information:
  • is_connected: Boolean indicating if graph is fully connected

  • num_components: Number of disconnected components

  • components: List of vertex lists for each component

  • component_sizes: List of component sizes

  • largest_component_size: Size of largest component

  • largest_component_index: Index of largest component

  • connectivity_ratio: Fraction of vertices in largest component

  • isolation_ratio: Fraction of isolated vertices (size-1 components)

Return type:

Dict[str, Any]

Examples

>>> conn_info = grapher.get_connectivity_info(graph)
>>> if conn_info['is_connected']:
...     print("Graph is fully connected")
... else:
...     print(f"Graph has {conn_info['num_components']} components")
...     print(f"Largest component: {conn_info['largest_component_size']} vertices")
>>> # Analyze fragmentation
>>> if conn_info['isolation_ratio'] > 0.1:
...     print(f"Warning: {conn_info['isolation_ratio']:.1%} vertices are isolated")
>>> # Focus analysis on largest component
>>> if not conn_info['is_connected']:
...     largest_comp = conn_info['components'][conn_info['largest_component_index']]
...     subgraph = graph.subgraph(largest_comp)
...     # Analyze subgraph...

Note

  • Connected components are maximal sets of mutually reachable vertices

  • Component indices refer to the components list

  • Isolated vertices form size-1 components

  • Useful for determining appropriate analysis methods

get_current_graph(graph_type: str) Any[source]

Get the most recent graph of a specific type.

Parameters:

graph_type – The type of graph to retrieve.

Returns:

The igraph Graph object, or None if not available.

Return type:

Any

get_current_graphs() Dict[str, Any][source]

Get the most recently generated graphs.

Returns:

Dictionary of current graphs by type name.

Return type:

Dict[str, Any]

get_graph_info(graph: Any) GraphAnalysisResult[source]

Get a lazy-loading analysis object for the graph.

This method is the entry point for all graph analysis. It returns a powerful result object where metrics are computed on-demand, ensuring maximum performance and a responsive user experience.

Parameters:

graph – igraph Graph object to analyze.

Returns:

An object for lazily accessing graph metrics.

Return type:

GraphAnalysisResult

Examples

>>> # This call is instantaneous
>>> results = grapher.get_graph_info(graph)
>>> # The first access to a property computes the metric
>>> print(f"Density: {results.density}")
>>> # Subsequent access is instant (from cache)
>>> print(f"Graph density is {results.density:.4f}")
>>> # Compute advanced metrics on the fly
>>> top_hubs = results.get_top_n_by('degree', n=3)
>>> betweenness_stats = results.get_metric_stats('betweenness')
get_graph_type_info() Dict[str, Any][source]

Get information about current graph type configuration.

Returns:

Configuration information including types, parameters, and status.

Return type:

Dict[str, Any]

get_memory_analysis() Dict[str, Any][source]

Get comprehensive memory analysis including age statistics.

This method provides detailed analysis of the temporal patterns in the memory manager’s data, including connection persistence, age distributions, and temporal stability metrics.

Returns:

Comprehensive analysis including:
  • Basic statistics (count, usage, etc.)

  • Age distributions and temporal patterns

  • Connection persistence metrics

  • Stability analysis

  • Temporal trends

Return type:

Dict[str, Any]

Examples

>>> analysis = grapher.get_memory_analysis()
>>> print("Connection age distribution:")
>>> for age, count in analysis['age_distribution'].items():
...     print(f"  Age {age}: {count} connections")
>>>
>>> print(f"Average connection persistence: {analysis['avg_persistence']:.2f}")
get_networkx_analyzer() NetworkXAnalyzer[source]

Get NetworkX analyzer for advanced graph analysis.

Returns:

NetworkXAnalyzer instance for this Graphing object

Examples

>>> # Get analyzer
>>> nx_analyzer = grapher.get_networkx_analyzer()
>>>
>>> # Analyze current graphs
>>> analysis = nx_analyzer.analyze('delaunay')
>>> print(f"Communities: {analysis['num_communities']}")
>>>
>>> # Direct NetworkX access
>>> nx_graph = nx_analyzer.get_networkx('proximity')
>>> custom_centrality = nx.eigenvector_centrality(nx_graph)
static get_plugin_info(graph_type: str) Dict[str, Any][source]

Get detailed information about a specific graph type.

Parameters:

graph_type – Name of the graph type to query.

Returns:

Detailed information including:
  • info: General information (description, category, version)

  • parameters: List of available parameters with descriptions

  • examples: Usage examples if available

  • requirements: Special requirements or dependencies

Return type:

Dict[str, Any]

Raises:

ValueError – If graph_type is not found in the registry.

Examples

>>> # Get info about proximity graphs
>>> prox_info = Graphing.get_plugin_info('proximity')  # ✅ Fixed method name
>>> print(prox_info['info']['description'])
>>> print("Parameters:", prox_info['parameters'])
>>> # Check parameter details before calling
>>> knn_info = Graphing.get_plugin_info('knn')  # ✅ Fixed method name
>>> k_param = knn_info['parameters']['k']
>>> print(f"k parameter: {k_param['description']}")
get_weight_analysis() Dict[str, Any][source]

:Todo implement the weight statistics

property graph_config: GraphConfig

Get current graph configuration.

Returns:

Current graph configuration object containing

dimension, aspect, and algorithm parameters.

Return type:

GraphConfig

static identify_graph(graph: Any) Any[source]

Replace graph vertex names with proper particle IDs for consistency.

This method ensures that graph vertices have consistent naming by setting the “name” attribute to match the “id” attribute. This is useful for maintaining data consistency across different graph operations.

Parameters:

graph – igraph Graph object to modify.

Returns:

The modified graph object with updated vertex names.

Return type:

Any

Raises:

GraphCreationError – If graph is None or modification fails.

Note

This method modifies the graph in-place and also returns it for method chaining convenience.

Examples

>>> graph = grapher.make_delaunay(data)
>>> identified_graph = Graphing.identify_graph(graph)
>>> # Now graph.vs["name"] == graph.vs["id"] for all vertices
init_memory_manager(max_memory_size: int = 100, max_iterations: int | None = None, track_edge_ages: bool = True) MemoryManager[source]

Initialize memory manager for temporal graph analysis.

The memory manager enables tracking of graph connections over time, allowing for analysis of persistent vs. transient relationships and temporal patterns in graph structure.

Parameters:
  • max_memory_size – Maximum number of connections to remember. Older connections are forgotten when this limit is reached. Larger values provide longer memory but use more resources.

  • max_iterations – Maximum number of time steps to track. If None, tracks indefinitely until max_memory_size is reached.

  • track_edge_ages – Whether to track the age/persistence of each edge. Enables advanced temporal analysis but uses more memory.

Returns:

The initialized memory manager instance.

Return type:

MemoryManager

Raises:

GraphCreationError – If memory manager initialization fails.

Examples

>>> # Basic memory manager
>>> memory_mgr = grapher.init_memory_manager()
>>> # Large memory for long-term analysis
>>> memory_mgr = grapher.init_memory_manager(
...     max_memory_size=1000,
...     max_iterations=100,
...     track_edge_ages=True
... )
>>> # Lightweight memory for real-time applications
>>> memory_mgr = grapher.init_memory_manager(
...     max_memory_size=50,
...     track_edge_ages=False
... )

Note

  • Must be called before using memory-based graph methods

  • Only one memory manager per Graphing instance

  • Memory manager persists until explicitly reset or object destroyed

init_weight_computer(**kwargs)[source]

Initialize flexible weight computer.

is_connected(graph: Any) bool[source]

Check if the graph is connected (single component).

Parameters:

graph – igraph Graph object to test.

Returns:

True if graph is connected, False otherwise.

Return type:

bool

static list_graph_types(category: str | None = None) Dict[str, Any][source]

List all available graph types in the plugin registry.

Parameters:

category – Optional category filter to show only specific types: - ‘built-in’: Core graph types included with graphizy - ‘community’: Community-contributed plugins - ‘experimental’: Experimental or unstable plugins - None: Show all available types

Returns:

Dictionary mapping graph type names to their information.

Each entry contains metadata about the graph type including description, category, version, and available parameters.

Return type:

Dict[str, Any]

Examples

>>> # List all graph types
>>> all_types = Graphing.list_graph_types()
>>> for name, info in all_types.items():
...     print(f"{name}: {info['description']}")
>>> # List only built-in types
>>> builtin_types = Graphing.list_graph_types(category='built-in')
>>> # Check if specific type is available
>>> available_types = Graphing.list_graph_types()
>>> if 'delaunay' in available_types:
...     print("Delaunay triangulation is available")
make_graph(graph_type: str, data_points: ndarray | Dict[str, Any], graph_params: Dict | None = None, update_memory: bool | None = None, use_memory: bool | None = None, compute_weights: bool | None = None, do_timing: bool = False, validate_data: bool = False, **kwargs) Any[source]

Create a graph using the extensible plugin system with intelligent memory defaults.

This method provides access to both built-in and community-contributed graph types through a unified interface. It automatically handles data format conversion and passes the appropriate parameters to the graph creation algorithm. Optionally integrates with memory system using smart defaults.

Parameters:
  • graph_type – Name of the graph type to create. Built-in types include: ‘delaunay’, ‘proximity’, ‘knn’, ‘gabriel’, ‘mst’, ‘memory’. Additional types may be available through plugins.

  • data_points – Point data in the format specified by self.aspect: - For “array”: NumPy array with shape (n, 3) containing [id, x, y] - For “dict”: Dictionary with keys “id”, “x”, “y” as lists/arrays

  • graph_params – Dictionary of parameters specific to the graph type. If None, uses empty dict. These are the algorithm-specific parameters: - proximity: {‘proximity_thresh’: 50.0, ‘metric’: ‘euclidean’} - knn: {‘k’: 5} - mst: {‘metric’: ‘euclidean’} - etc.

  • update_memory – Whether to update memory manager with the created graph. If None and memory manager exists, defaults based on use_memory. Only works if memory_manager is initialized.

  • use_memory – Whether to create a memory-enhanced graph from existing connections. If None and memory manager exists, defaults to True. Only works if memory_manager is initialized.

  • compute_weights – Whether to compute edges weights. Only works if weight_computer is initialized.

  • do_timing – Whether to print the performances

  • validate_data – Whether to validate the data (careful at each call this will degrade the performances)

  • **kwargs – Additional graph-type specific parameters that override graph_params. These are merged with graph_params, with kwargs taking precedence.

Returns:

igraph Graph object of the specified type, optionally memory-enhanced.

Return type:

Any

Raises:
  • ValueError – If graph_type is not found in the registry.

  • GraphCreationError – If graph creation fails due to invalid parameters or computation errors.

Smart Defaults:
  • If memory_manager exists and use_memory=None → use_memory=True

  • If use_memory=True and update_memory=None → update_memory=True

  • If no memory_manager → both default to False

Examples

>>> # Simple direct usage (most common)
>>> graph = grapher.make_graph('delaunay', data)
>>> connections = grapher.make_graph('proximity', data, proximity_thresh=80.0)
>>> knn_graph = grapher.make_graph('knn', data, k=5)
>>> # Using graph_params dictionary (for complex configs)
>>> prox_params = {'proximity_thresh': 75.0, 'metric': 'manhattan'}
>>> graph = grapher.make_graph('proximity', data, graph_params=prox_params)
>>> # Mixed usage - kwargs override graph_params
>>> graph = grapher.make_graph('proximity', data,
...                          graph_params={'proximity_thresh': 50.0},
...                          proximity_thresh=100.0)  # This wins
>>> # Memory control with direct parameters
>>> graph = grapher.make_graph('knn', data, k=8, use_memory=False, update_memory=True)
>>> # Both styles work seamlessly
>>> algorithm_params = {'proximity_thresh': 60.0, 'metric': 'euclidean'}
>>> graph1 = grapher.make_graph('proximity', data, graph_params=algorithm_params)
>>> graph2 = grapher.make_graph('proximity', data, proximity_thresh=60.0, metric='euclidean')
>>> # graph1 and graph2 are equivalent

Note

  • Direct kwargs are the most convenient: make_graph(‘proximity’, data, proximity_thresh=80.0)

  • graph_params provides clean organization for complex configurations

  • kwargs override graph_params for convenient parameter overrides

  • Both styles can be mixed: graph_params for base config, kwargs for overrides

  • Smart defaults make memory usage automatic when memory_manager exists

  • Explicit parameters always override defaults

  • use_memory=True: Uses EXISTING memory connections from previous calls

  • update_memory=True: Adds current graph connections to memory for future use

  • Memory creates historical connection patterns for temporal analysis

make_memory_graph(data_points: ndarray | Dict[str, Any], memory_connections: Dict | None = None) Any[source]

Create a graph based on accumulated memory connections.

Memory graphs use historical connection data to create graphs that represent persistent relationships over time. This is useful for analyzing temporal stability and identifying core vs. peripheral connections in dynamic systems.

Parameters:
  • data_points – Current point data in the format specified by self.aspect: - For “array”: NumPy array with shape (n, 3) containing [id, x, y] - For “dict”: Dictionary with keys “id”, “x”, “y” as lists/arrays

  • memory_connections – Optional explicit memory connections. If None, uses the current memory manager’s accumulated connections. Format: {(id1, id2): connection_strength, …}

Returns:

igraph Graph object representing memory-based connections.

Edge weights may represent connection persistence/frequency.

Return type:

Any

Raises:

GraphCreationError – If memory manager is not initialized and no memory_connections provided, or if graph creation fails.

Examples

>>> # Initialize memory and accumulate connections over time
>>> grapher.init_memory_manager(max_memory_size=200)
>>>
>>> # Update memory with multiple proximity snapshots
>>> for t in range(10):
...     dynamic_data = get_data_at_time(t)  # Your data source
...     grapher.update_memory_with_proximity(dynamic_data)
>>>
>>> # Create memory graph from accumulated connections
>>> current_data = get_current_data()
>>> memory_graph = grapher.make_memory_graph(current_data)
>>> # Use explicit memory connections
>>> custom_memory = {(1, 2): 0.8, (2, 3): 0.6, (1, 3): 0.3}
>>> memory_graph = grapher.make_memory_graph(data, custom_memory)

Note

  • Requires either initialized memory manager or explicit connections

  • Memory graphs can be much sparser than instantaneous graphs

  • Edge weights typically represent temporal persistence

  • Useful for identifying stable vs. transient relationships

overlay_collision(image_graph: ndarray, graph: Any) ndarray[source]

Overlay an additional graph onto an existing image.

Delegates to the Visualizer’s overlay_graph method.

Parameters:
  • image_graph – The base image to draw on.

  • graph – The igraph Graph object to overlay.

Returns:

The modified image array.

Return type:

np.ndarray

overlay_graph(image_graph: ndarray, graph: Any) ndarray[source]

Overlay an additional graph onto an existing image.

Delegates to the Visualizer’s overlay_graph method.

Parameters:
  • image_graph – The base image to draw on.

  • graph – The igraph Graph object to overlay.

Returns:

The modified image array.

Return type:

np.ndarray

save_graph(image_graph: ndarray, filename: str) None[source]

Save a graph image to a file.

Delegates to the Visualizer’s save_graph method.

Parameters:
  • image_graph – The image array to save.

  • filename – The path to save the file to.

set_graph_type(graph_type: str | List[str] | Tuple[str], **default_kwargs)[source]

Set the type(s) of graph to generate automatically during updates.

This method configures the Graphing object to automatically create specific graph types when update_graphs() is called with new data. Supports single or multiple graph types with default parameters.

Parameters:
  • graph_type – Graph type(s) to generate automatically. Can be: - str: Single graph type (e.g., ‘delaunay’) - List[str]: Multiple graph types (e.g., [‘delaunay’, ‘proximity’]) - Tuple[str]: Multiple graph types as tuple

  • **default_kwargs – Default parameters for graph creation, applied to all types. Type-specific parameters can be set using update_graph_params().

Raises:

Examples

>>> # Set single graph type
>>> grapher.set_graph_type('delaunay')
>>> # Set multiple graph types
>>> grapher.set_graph_type(['delaunay', 'proximity', 'knn'])
>>> # Set with default parameters
>>> grapher.set_graph_type('proximity', proximity_thresh=50.0, metric='euclidean')
>>> # Set multiple types with defaults
>>> grapher.set_graph_type(['knn', 'gabriel'], k=6)  # k applies only to knn
setup_fast_attributes(**config)[source]

Setup fast attribute computer for real-time use.

show_all_graphs(**kwargs)[source]

Display all current graphs in separate windows.

Parameters:

**kwargs – Parameters passed to show_graph().

show_graph(image_graph: ndarray, title: str = 'Graphizy', **kwargs) None[source]

Display a graph image in a window.

Delegates to the Visualizer’s show_graph method.

Parameters:
  • image_graph – The image array to display.

  • title – The title of the window.

  • **kwargs – Additional arguments like ‘block’.

to_networkx(graph_type: str | None = None, igraph_graph: Any | None = None) Any[source]

Convert graph to NetworkX format.

Parameters:
  • graph_type – Type from current graphs

  • igraph_graph – Manual igraph to convert

Returns:

NetworkX Graph object

update(**kwargs)[source]

Update configuration values at runtime from keyword arguments. This method can intelligently route flat keys (e.g., ‘line_color’) to the correct nested config object (e.g., self.drawing).

update_config(**kwargs) None[source]

Update configuration parameters at runtime.

This method allows dynamic reconfiguration of the Graphing object without requiring re-initialization. Changes are applied immediately and cached values are updated.

Parameters:

**kwargs – Configuration parameters to update. Can include nested parameters using dictionary syntax: - drawing={‘line_color’: (255,0,0), ‘point_radius’: 8} - graph={‘proximity_threshold’: 100.0} - Direct parameters: line_thickness=3, aspect=’dict’

Raises:

GraphCreationError – If configuration update fails due to invalid parameters.

Examples

>>> # Update drawing parameters
>>> grapher.update_config(
...     drawing={'line_color': (0, 255, 0), 'line_thickness': 2}
... )
>>> # Update graph parameters
>>> grapher.update_config(
...     graph={'proximity_threshold': 75.0, 'distance_metric': 'manhattan'}
... )
>>> # Mixed updates
>>> grapher.update_config(
...     line_color=(255, 255, 0),
...     graph={'dimension': (1200, 800)}
... )
update_graph_params(graph_type: str, **kwargs)[source]

Update parameters for a specific graph type.

Parameters:
  • graph_type – The graph type to update parameters for.

  • **kwargs – Parameters to set for this graph type.

Examples

>>> grapher.set_graph_type(['proximity', 'knn'])
>>> grapher.update_graph_params('proximity', proximity_thresh=75.0, metric='manhattan')
>>> grapher.update_graph_params('knn', k=8)
update_graphs(data_points: ndarray | Dict[str, Any], update_memory: bool | None = None, use_memory: bool | None = None, compute_weights: bool | None = None, **override_kwargs) Dict[str, Any][source]

Update all configured graph types with new data using smart memory and weight defaults.

This method automatically creates graphs of all types specified by set_graph_type() using the provided data. Optionally updates memory manager, computes weights, and returns all generated graphs. Uses the same smart defaults as make_graph().

Processing Flow: graph → memory → weights (for each graph type)

Parameters:
  • data_points – New point data in the format specified by self.aspect.

  • update_memory – Whether to update memory manager with new graphs. If None and memory manager exists, defaults based on use_memory. Only works if memory_manager is initialized.

  • use_memory – Whether to create memory-enhanced graphs from existing connections. If None and memory manager exists, defaults to True. Only works if memory_manager is initialized.

  • compute_weights – Whether to compute edge weights for final graphs. If None, uses self.auto_compute_weights default. Only works if weight_computer is initialized.

  • **override_kwargs – Parameters that override defaults for this update only.

Returns:

Dictionary mapping graph type names to generated graph objects.

Each graph follows the pipeline: base_graph → memory → weights

Return type:

Dict[str, Any]

Smart Defaults:

Memory: - If memory_manager exists and use_memory=None → use_memory=True - If use_memory=True and update_memory=None → update_memory=True - If no memory_manager → both default to False

Weights: - If compute_weights=None → use self.auto_compute_weights - If weight_computer not set → weights skipped regardless of setting

Examples

>>> # Set up automatic graph generation with memory and weights
>>> grapher.set_graph_type(['delaunay', 'proximity', 'knn'])
>>> grapher.init_memory_manager(max_memory_size=200)
>>> grapher.init_weight_computer(WeightComputer(method="distance"))
>>> grapher.update_graph_params('proximity', proximity_thresh=60.0)
>>> grapher.update_graph_params('knn', k=5)
>>> # Basic update - uses all smart defaults
>>> new_data = np.random.rand(100, 3) * 100
>>> graphs = grapher.update_graphs(new_data)
>>> # Each graph: structure → memory → weights
>>> # Explicit control over all processing steps
>>> graphs = grapher.update_graphs(
...     new_data,
...     use_memory=False,      # Skip memory
...     update_memory=True,    # But learn from current
...     compute_weights=True   # Force weights
... )
>>> # Memory + parameter overrides
>>> graphs = grapher.update_graphs(
...     new_data,
...     use_memory=True,
...     compute_weights=False,  # Skip weights this time
...     proximity_thresh=75.0   # Override proximity threshold
... )
>>> # Different settings per call
>>> learning_graphs = grapher.update_graphs(new_data, use_memory=False, update_memory=True)
>>> memory_graphs = grapher.update_graphs(new_data, use_memory=True, update_memory=False)

Note

  • All graphs follow the same pipeline: graph → memory → weights

  • Memory processing can change which edges exist before weights are computed

  • Weight computation adds attributes to final edge set

  • Smart defaults minimize configuration while maintaining full control

  • Failed graphs are set to None but don’t stop other graph generation

update_graphs_learning_only(data_points: ndarray | Dict[str, Any], compute_weights: bool | None = None, **override_kwargs) Dict[str, Any][source]

Convenience method to create regular graphs and update memory (no memory usage).

This creates graphs from current data and adds the connections to memory for future use, but doesn’t use existing memory for the current graphs. Can still compute weights on the current edges.

Parameters:
  • data_points – Current point data.

  • compute_weights – Whether to compute weights on current edges. If None, uses auto_compute_weights default.

  • **override_kwargs – Parameter overrides for graph creation.

Returns:

Dictionary of current graphs with optional weights

(memory updated as side effect).

Return type:

Dict[str, Any]

Examples

>>> # Build up memory without using it yet (with weights for analysis)
>>> grapher.update_graphs_learning_only(data1, compute_weights=True)
>>> grapher.update_graphs_learning_only(data2, compute_weights=True)
>>> # Now use accumulated memory
>>> memory_graphs = grapher.update_graphs_memory_only(current_data)
update_graphs_memory_only(data_points: ndarray | Dict[str, Any], compute_weights: bool | None = None, **override_kwargs) Dict[str, Any][source]

Convenience method to update graphs using only memory (no current data learning).

This creates graphs purely from accumulated memory connections without updating the memory with current data. Useful for seeing what the “remembered” graph structure looks like. Can still compute weights on the memory-based edges.

Parameters:
  • data_points – Current point data (positions only, connections from memory).

  • compute_weights – Whether to compute weights on memory-based edges. If None, uses auto_compute_weights default.

  • **override_kwargs – Parameter overrides for graph creation.

Returns:

Dictionary of memory-based graphs with optional weights.

Return type:

Dict[str, Any]

Examples

>>> # Build up memory over time
>>> grapher.update_graphs(data1)  # Learn from data1
>>> grapher.update_graphs(data2)  # Learn from data2
>>> # See what the accumulated memory looks like (with weights)
>>> memory_graphs = grapher.update_graphs_memory_only(current_data, compute_weights=True)
>>> # Pure memory structure without weights
>>> memory_structure = grapher.update_graphs_memory_only(current_data, compute_weights=False)
update_memory_with_custom(data_points: ndarray | Dict[str, Any], connection_function: callable, **kwargs) Dict[str, List[str]][source]

Update memory using a custom connection function.

This method allows integration of custom graph algorithms or connection rules with the memory system. The connection function should return pairs of point IDs that should be connected.

Parameters:
  • data_points – Point data in the format specified by self.aspect: - For “array”: NumPy array with shape (n, 3) containing [id, x, y] - For “dict”: Dictionary with keys “id”, “x”, “y” as lists/arrays

  • connection_function – Callable that takes data_points and returns connections. Should return iterable of (id1, id2) tuples or similar.

  • **kwargs – Additional arguments passed to the connection function.

Raises:

GraphCreationError – If memory manager is not initialized or update fails.

Examples

>>> # Define custom connection rule
>>> def angular_connections(data_points, angle_thresh=45):
...     """Connect points with similar angles from origin"""
...     connections = []
...     # Your custom logic here
...     angles = np.arctan2(data_points[:, 2], data_points[:, 1])  # y, x
...     for i, angle_i in enumerate(angles):
...         for j, angle_j in enumerate(angles[i+1:], i+1):
...             if abs(angle_i - angle_j) < np.radians(angle_thresh):
...                 connections.append((data_points[i, 0], data_points[j, 0]))
...     return connections
>>>
>>> # Initialize memory and use custom function
>>> grapher.init_memory_manager()
>>> grapher.update_memory_with_custom(
...     data,
...     angular_connections,
...     angle_thresh=30
... )
>>> # Example with lambda function for simple rules
>>> grapher.update_memory_with_custom(
...     data,
...     lambda pts: [(pts[i,0], pts[j,0]) for i in range(len(pts))
...                  for j in range(i+1, len(pts))
...                  if abs(pts[i,1] - pts[j,1]) < 10]  # Connect similar x-coords
... )

Note

  • Connection function should be efficient for large datasets

  • Function should return iterable of (id1, id2) pairs

  • Memory manager handles deduplication and aging automatically

  • Useful for domain-specific connection rules

update_memory_with_graph(graph: Any) Dict[str, List[str]][source]

Update memory manager from any existing graph object.

This method extracts connections from an existing igraph Graph object and adds them to the memory manager. This is useful for incorporating connections computed by external algorithms or for combining multiple graph types in memory.

Parameters:

graph – igraph Graph object with vertices having “id” attributes and edges representing connections to remember.

Raises:

GraphCreationError – If memory manager is not initialized or update fails.

Examples

>>> # Initialize memory
>>> grapher.init_memory_manager()
>>>
>>> # Create various graph types and add to memory
>>> delaunay_graph = grapher.make_delaunay(data)
>>> grapher.update_memory_with_graph(delaunay_graph)
>>>
>>> knn_graph = grapher.make_knn(data, k=5)
>>> grapher.update_memory_with_graph(knn_graph)
>>>
>>> # Memory now contains union of both graph types
>>> combined_memory_graph = grapher.make_memory_graph(data)
>>> # Update with external graph
>>> external_graph = some_external_algorithm(data)
>>> grapher.update_memory_with_graph(external_graph)

Note

  • Graph must have vertex “id” attributes matching your data

  • All edges in the graph will be added to memory

  • Useful for combining multiple graph construction methods

  • Can be used with any igraph-compatible graph object

class graphizy.GraphizyConfig(**kwargs)[source]

Bases: object

Master configuration class combining all config sections

copy() GraphizyConfig[source]

Create a deep copy of the configuration

drawing: DrawingConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.DrawingConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
generation: GenerationConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.GenerationConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
graph: GraphConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.GraphConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
logging: LoggingConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.LoggingConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
memory: MemoryConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.MemoryConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
set_drawing(**kwargs)[source]
set_generation(**kwargs)[source]
set_graph(**kwargs)[source]
set_logging(**kwargs)[source]
set_memory(**kwargs)[source]
to_dict() dict[source]

Convert configuration to dictionary

update(**kwargs)[source]

Update configuration values at runtime

weight: WeightConfig = Field(name=None,type=None,default=<dataclasses._MISSING_TYPE object>,default_factory=<class 'graphizy.config.WeightConfig'>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE object>,_field_type=None)
exception graphizy.GraphizyError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: Exception

Base exception for all graphizy errors with enhanced debugging

log_error() None[source]

Log this error with full context

exception graphizy.IgraphMethodError(message: str, method_name: str | None = None, graph_info: Dict[str, Any] | None = None, **kwargs)[source]

Bases: GraphizyError

Raised when igraph method execution fails

exception graphizy.InvalidAspectError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: GraphizyError

Raised when invalid aspect is provided

exception graphizy.InvalidDataShapeError(message: str, data_shape: Any | None = None, **kwargs)[source]

Bases: GraphizyError

Raised when invalid data shape is provided

exception graphizy.InvalidDimensionError(message: str, dimensions: Any | None = None, **kwargs)[source]

Bases: GraphizyError

Raised when invalid dimensions are provided

exception graphizy.InvalidPointArrayError(message: str, array_info: Dict[str, Any] | None = None, **kwargs)[source]

Bases: GraphizyError

Raised when invalid point array is provided

class graphizy.LoggingConfig(level: str = 'INFO', format: str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')[source]

Bases: object

Configuration for logging

format: str = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
level: str = 'INFO'
class graphizy.MemoryConfig(max_memory_size: int = 3, max_iterations: int | None = None, auto_update_from_proximity: bool = True, memory_decay_factor: float = 1.0)[source]

Bases: object

Configuration for memory graph parameters

auto_update_from_proximity: bool = True
max_iterations: int | None = None
max_memory_size: int = 3
memory_decay_factor: float = 1.0
class graphizy.MemoryManager(max_memory_size: int = 10000, max_iterations: int | None = None, track_edge_ages: bool = True)[source]

Bases: object

Ultra-simplified MemoryManager using igraph’s built-in deduplication

This implementation is radically simplified: - No complex data structures - No manual deduplication - Just store edges and let igraph handle everything

add_connections(connections: Dict[Any, List[Any]]) None[source]

COMPATIBILITY METHOD: Add connections in dict format

This is kept for backward compatibility.

add_graph_vectorized(graph: Graph, return_memory_graph: bool = False) Dict[str, Any] | Graph[source]

Add graph edges to memory and optionally return memory-enhanced graph

This is the main method - extremely simplified: 1. Extract edges from graph 2. Add to our edge list 3. If requested, create memory graph using simplify()

clear() None[source]

Clear all memory

create_memory_graph(data_points: ndarray | Dict[str, Any]) Graph[source]

Create a memory-only graph from current positions

This creates a graph with vertices from data_points but edges only from memory.

get_current_memory_graph() Dict[str, List[str]][source]

COMPATIBILITY METHOD: Return memory in dict format

This is kept for backward compatibility but is less efficient.

get_memory_stats() Dict[str, Any][source]

Get memory statistics

class graphizy.PercolationAnalyzer(grapher: Graphing)[source]

Bases: object

Analyzer for percolation phenomena and critical behavior in spatial networks.

This class provides tools for studying phase transitions, cluster formation, and critical thresholds in spatial systems.

analyze_percolation_threshold(positions: ndarray, interaction_ranges: List[float]) PercolationResult[source]

Analyze percolation behavior as a function of interaction range.

Parameters:
  • positions – Array of particle positions in format [id, x, y]

  • interaction_ranges – List of interaction ranges to test

Returns:

PercolationResult with threshold analysis

detect_phase_transition(result: PercolationResult, gradient_threshold: float = 0.1) Dict[str, Any][source]

Detect phase transition characteristics from percolation results.

Parameters:
  • result – PercolationResult from analyze_percolation_threshold

  • gradient_threshold – Minimum gradient to identify transition

Returns:

Dictionary with phase transition analysis

class graphizy.PercolationResult(interaction_ranges: List[float], largest_cluster_sizes: List[int], total_clusters: List[int], percolation_probabilities: List[float], critical_range: float | None)[source]

Bases: object

Results from percolation analysis

critical_range: float | None
get_critical_probability() float[source]

Get percolation probability at critical range

interaction_ranges: List[float]
largest_cluster_sizes: List[int]
percolation_probabilities: List[float]
total_clusters: List[int]
exception graphizy.PositionGenerationError(message: str, size_x: int | None = None, size_y: int | None = None, num_particles: int | None = None, **kwargs)[source]

Bases: GraphizyError

Raised when position generation fails

class graphizy.SocialNetworkAnalyzer(grapher: Graphing)[source]

Bases: object

Analyzer for social network patterns and role identification.

This class provides tools for identifying social roles, tracking temporal changes in network position, and analyzing social dynamics.

get_role_stability(temporal_roles: Dict[int, Dict[str, List]]) Dict[int, float][source]

Calculate role stability for each individual.

Parameters:

temporal_roles – Output from track_temporal_roles

Returns:

Dictionary mapping node IDs to stability scores (0-1)

identify_social_roles(graph: Graph, betweenness_threshold: float = 0.8, degree_threshold: float = 0.8) Dict[int, SocialRole][source]

Identify social roles based on network centrality measures.

Parameters:
  • graph – igraph Graph object

  • betweenness_threshold – Percentile threshold for bridge identification

  • degree_threshold – Percentile threshold for hub identification

Returns:

Dictionary mapping node IDs to SocialRole objects

track_temporal_roles(graph_sequence: List[Graph]) Dict[int, Dict[str, List]][source]

Track how social roles evolve over time.

Parameters:

graph_sequence – List of graphs representing temporal sequence

Returns:

Dictionary with temporal role tracking for each individual

class graphizy.SocialRole(roles: List[str], stats: Dict[str, float])[source]

Bases: object

Individual social role classification

is_bridge() bool[source]
is_hub() bool[source]
is_peripheral() bool[source]
roles: List[str]
stats: Dict[str, float]
exception graphizy.SubdivisionError(message: str, point_array=None, dimensions=None, **kwargs)[source]

Bases: GraphizyError

Raised when OpenCV subdivision fails

exception graphizy.TriangulationError(message: str, context: Dict[str, Any] | None = None, original_exception: Exception | None = None)[source]

Bases: GraphizyError

Raised when Delaunay triangulation fails

class graphizy.WeightComputer(method: str = 'distance', auto_add_distance: bool = True, distance_metric: str = 'euclidean', formula: str | None = None, custom_function: Callable | None = None, normalize: bool = False, target_attribute: str | None = None, **method_params)[source]

Bases: object

Advanced weight computation system for graph edges.

This class provides a flexible framework for computing any edge attribute using various strategies. It can compute multiple attributes (distance, weight, custom) and use existing edge attributes in formulas. Optimized for real-time applications.

Examples

# Compute distance and weight separately computer = WeightComputer(method=”distance”, target_attribute=”distance”) graph = computer.compute_weights(graph, data_points)

computer = WeightComputer(method=”formula”, formula=”1/distance”, target_attribute=”weight”) graph = computer.compute_weights(graph, data_points)

# Chain multiple computations computer.compute_attribute(graph, data_points, “distance”, method=”distance”) computer.compute_attribute(graph, data_points, “weight”, method=”formula”, formula=”1/(distance + 0.1)”) computer.compute_attribute(graph, data_points, “strength”, method=”formula”, formula=”weight * age”)

compute_attribute(graph: Any, target_attribute: str, method: str | None = None, formula: str | None = None, custom_function: Callable | None = None, normalize: bool = False, do_timing: bool = False, **method_params) Any[source]

Compute and assign values to any specified edge attribute.

This is the core method that allows computing multiple different attributes on the same graph. Perfect for real-time applications where you need both distance and weight attributes.

Parameters:
  • graph – igraph Graph object

  • target_attribute – Name of edge attribute to store results

  • method – Override method for this computation

  • formula – Override formula for this computation

  • custom_function – Override function for this computation

  • normalize – Whether to normalize results for this computation

  • do_timing – Whether to print the performances

  • **method_params – Additional parameters for this computation

Returns:

Graph with computed values in target_attribute

Examples

# Compute distance and store in “distance” attribute computer.compute_attribute(graph, data, “distance”, method=”distance”)

# Then compute weight using the distance attribute computer.compute_attribute(graph, data, “weight”, method=”formula”, formula=”1/distance”)

# Compute importance using multiple attributes computer.compute_attribute(graph, data, “importance”, method=”formula”,

formula=”weight * age / max_age”, max_age=100)

compute_weights(graph: Any) Any[source]

Compute and assign values to target edge attribute.

Parameters:

graph – igraph Graph object

Returns:

Graph with computed values assigned to target attribute

get_attribute_info(graph: Any, attribute: str) Dict[str, Any][source]

Get information about computed attribute values.

graphizy.call_igraph_method(graph: Any, method_name: str, *args, **kwargs) Any[source]

Call any igraph method on the graph safely

Parameters:
  • graph – igraph Graph object

  • method_name – Name of the method to call

  • *args – Positional arguments for the method

  • **kwargs – Keyword arguments for the method

Returns:

Result of the method call

Raises:

IgraphMethodError – If method call fails

graphizy.create_gabriel_graph(positions: ndarray, aspect: str = 'array', data_shape: List[Tuple[str, Any]] | None = None) Any[source]

Create a Gabriel graph from point positions using an optimized, vectorized approach.

A Gabriel graph is a subgraph of the Delaunay triangulation where for any edge (p, q), the disk with diameter pq contains no other point r.

Parameters:
  • positions – Point data array with shape (n, >=3) containing [id, x, y, …].

  • aspect – Data format (currently only “array” is supported).

  • data_shape – shape of the data to pass (if extra column of information)

Returns:

An igraph Graph object representing the Gabriel graph.

Return type:

igraph.Graph

Raises:

GraphCreationError – If graph creation fails.

graphizy.create_graph_array(point_array: ndarray, data_shape: List[Tuple[str, Any]] | None = None) Any[source]

Create a graph from a point array, dynamically adding attributes.

Parameters:
  • point_array – Array of points with columns corresponding to the data_shape.

  • data_shape – List of tuples defining the data structure, e.g., [(‘id’, int), (‘x’, float), (‘velocity’, float)]. If None, defaults to the legacy [id, x, y] behavior.

Returns:

igraph Graph object.

Raises:

GraphCreationError – If graph creation fails.

graphizy.create_graph_dict(point_dict: Dict[str, Any]) Any[source]

Create a graph from a point dictionary.

This function dynamically adds all keys from the dictionary as vertex attributes.

Parameters:

point_dict – Dictionary with keys ‘id’, ‘x’, ‘y’, and other optional attributes. All values should be lists or arrays of the same length.

Returns:

igraph Graph object

Raises:

GraphCreationError – If graph creation fails

graphizy.create_knn_graph(positions: ndarray, k: int = 3, aspect: str = 'array', data_shape: List[Tuple[str, Any]] | None = None) Any[source]

Create graph connecting each point to its k nearest neighbors

Parameters:
  • positions – Point data array

  • k – Number of nearest neighbors

  • aspect – Data format

  • data_shape – shape of the data to pass (if extra column of information)

graphizy.create_memory_graph_image(graph: Any, memory_manager: Any, dimension: Tuple[int, int], point_color: Tuple[int, int, int] = (0, 0, 255), line_color: Tuple[int, int, int] = (0, 255, 0), point_radius: int = 8, point_thickness: int = 3, line_thickness: int = 1, use_age_colors: bool = True, alpha_range: Tuple[float, float] = (0.3, 1.0)) ndarray[source]

Create a complete memory graph image

Parameters:
  • graph – igraph Graph object

  • memory_manager – MemoryManager instance

  • dimension – Image dimensions (width, height)

  • point_color – Color for points (B, G, R)

  • line_color – Base color for lines (B, G, R)

  • point_radius – Point radius

  • point_thickness – Point thickness

  • line_thickness – Line thickness

  • use_age_colors – Whether to use age-based edge coloring

  • alpha_range – (min_alpha, max_alpha) for age-based transparency

Returns:

Image array

Raises:

DrawingError – If image creation fails

graphizy.create_mst_graph(positions: ndarray, aspect: str = 'array', metric: str = 'euclidean', data_shape: List[Tuple[str, Any]] | None = None) Any[source]

Create minimum spanning tree graph from a standardized array.

Parameters:
  • positions – Point data array

  • aspect – Data format

  • metric – Distance metric for MST construction

  • data_shape – shape of the data to pass (if extra column of information)

graphizy.draw_delaunay(img: ndarray, subdiv: Any, color_line: Tuple[int, int, int] = (0, 255, 0), thickness_line: int = 1, color_point: Tuple[int, int, int] = (0, 0, 255), thickness_point: int = 1) None[source]

Draw delaunay triangles from openCV Subdiv2D

Parameters:
  • img – Image to draw on

  • subdiv – OpenCV Subdiv2D object

  • color_line – Line color (B, G, R)

  • thickness_line – Line thickness

  • color_point – Point color (B, G, R)

  • thickness_point – Point thickness

Raises:

DrawingError – If drawing operation fails

graphizy.draw_line(img: ndarray, x0: int, y0: int, x1: int, y1: int, color: Tuple[int, int, int], thickness: int = 1) None[source]

Draw a line on the image with enhanced error handling

Parameters:
  • img – Image array to draw on

  • x0 – Start point coordinates

  • y0 – Start point coordinates

  • x1 – End point coordinates

  • y1 – End point coordinates

  • color – Color tuple (B, G, R)

  • thickness – Line thickness

Raises:

DrawingError – If drawing operation fails

graphizy.draw_memory_graph_with_aging(img: ndarray, graph: Any, memory_manager: Any, point_color: Tuple[int, int, int], line_color: Tuple[int, int, int], point_radius: int = 8, point_thickness: int = 3, line_thickness: int = 1, use_age_colors: bool = True, alpha_range: Tuple[float, float] = (0.3, 1.0)) None[source]

Draw memory graph with optional edge aging visualization

Parameters:
  • img – Image array to draw on

  • graph – igraph Graph object

  • memory_manager – MemoryManager instance (for edge ages)

  • point_color – Color for points (B, G, R)

  • line_color – Base color for lines (B, G, R)

  • point_radius – Point radius

  • point_thickness – Point thickness

  • line_thickness – Line thickness

  • use_age_colors – Whether to use age-based edge coloring

  • alpha_range – (min_alpha, max_alpha) for age-based transparency

Raises:

DrawingError – If drawing operation fails

graphizy.draw_point(img: ndarray, p: Tuple[float, float], color: Tuple[int, int, int], radius: int = 4, thickness: int = 1) None[source]

Draw a point on the image with enhanced error handling

Parameters:
  • img – Image array to draw on

  • p – Point coordinates (x, y)

  • color – Color tuple (B, G, R)

  • radius – Point radius

  • thickness – Line thickness

Raises:

DrawingError – If drawing operation fails

graphizy.format_positions(positions: ndarray | List[Tuple[float, ...]], ids: ndarray | List | None = None, start_id: int = 0) ndarray[source]

Formats positions into the standard graphizy data array by adding IDs. This function is now more flexible and can handle positions with extra columns.

Parameters:
  • positions – A NumPy array of shape (n, m) or a list of (x, y, …) tuples, where m >= 2.

  • ids – An optional list or NumPy array of IDs. If provided, its length must match the number of positions.

  • start_id – The starting integer for sequential IDs, used only if ids is not provided (default: 0).

Returns:

A NumPy array of shape (n, m+1) with columns [id, x, y, …].

Raises:

ValueError – If the input positions are not in a valid 2D format, or if the length of provided IDs does not match the number of positions.

graphizy.generate_and_format_positions(size_x: int, size_y: int, num_particles: int, start_id: int = 0, add_more: Dict[str, Callable[[], Any]] | None = None, to_array=True, convert: bool = True) ndarray[source]

Convenience function: generate unique positions and format with IDs.

Parameters:
  • size_x – Size of the target array in x.

  • size_y – Size of the target array in y.

  • num_particles – Number of particles to place in the array.

  • start_id – The starting integer for sequential IDs.

  • add_more – A dictionary defining extra attributes to generate. Example: {‘velocity’: lambda: random.uniform(0, 5)}

  • to_array – If the output should be converted to a numpy array.

  • convert – If the output should be converted to float.

Returns:

np.ndarray of shape (num_particles, n) with columns (id, x, y, …).

graphizy.generate_positions(size_x: int, size_y: int, num_particles: int, to_array: bool = True, add_more: Dict[str, Callable[[], Any]] | None = None, convert: bool = True) List | ndarray[source]

Generate a number of non-repetitive positions with optional extra attributes.

Parameters:
  • size_x – Size of the target array in x.

  • size_y – Size of the target array in y.

  • num_particles – Number of particles to place in the array.

  • to_array – If the output should be converted to a numpy array.

  • add_more – A dictionary defining extra attributes to generate. Keys are attribute names (str), and values are functions that return a random value for that attribute. Example: {‘velocity’: lambda: random.uniform(0, 5)}

  • convert – If the output should be converted to float (when using to_array).

Returns:

(x, y, extra_val_1, extra_val_2, …).

Return type:

List or numpy array of positions. Each position is a tuple

Raises:

PositionGenerationError – If position generation fails.

graphizy.get_delaunay(point_array: ndarray, dim: List | Tuple) ndarray[source]

Make the delaunay triangulation of set of points

Parameters:
  • point_array – Array of points

  • dim – Dimensions

Returns:

Triangle list

Raises:

TriangulationError – If triangulation fails

graphizy.get_distance(position_array: ndarray, proximity_thresh: float, metric: str = 'euclidean') List[List[int]][source]

Filter points by proximity, return the points within specified distance of each point

Parameters:
  • position_array – Array of position of shape (n, 2)

  • proximity_thresh – Only keep points within this distance

  • metric – Type of distance calculated

Returns:

List of lists containing indices of nearby points

Raises:

GraphCreationError – If distance calculation fails

graphizy.get_graph_registry() GraphTypeRegistry[source]

Get the global graph type registry

graphizy.graph_distance(graph: Any, position2d: ndarray, proximity_thresh: float, metric: str = 'euclidean') Any[source]

Construct a distance graph

Parameters:
  • graph – igraph Graph object

  • position2d – 2D position array

  • proximity_thresh – Distance threshold

  • metric – Distance metric

Returns:

Modified graph

Raises:

GraphCreationError – If distance graph creation fails

graphizy.graph_type_plugin(name: str, description: str, parameters: Dict | None = None, category: str = 'custom', **info_kwargs)[source]

Decorator to easily create graph type plugins from functions

graphizy.make_delaunay(subdiv: Any) ndarray[source]

Return a Delaunay triangulation

Parameters:

subdiv – An opencv subdivision

Returns:

A triangle list

Raises:

TriangulationError – If triangulation fails

graphizy.make_subdiv(point_array: ndarray, dimensions: List | Tuple, do_print: bool = False) Any[source]

Make the opencv subdivision with enhanced error handling

Parameters:
  • point_array – A numpy array of the points to add

  • dimensions – The dimension of the image (width, height)

  • do_print – Whether to print debug information

Returns:

An opencv subdivision object

Raises:

SubdivisionError – If subdivision creation fails

graphizy.register_graph_type(plugin: GraphTypePlugin) None[source]

Register a graph type plugin globally

graphizy.save_graph(image_graph: ndarray, filename: str) None[source]

Save graph image to file.

This is a convenience wrapper around the global save_graph function that handles various image formats and provides error handling.

Parameters:
  • image_graph – Image array to save with shape (height, width, 3).

  • filename – Output filename with extension. Extension determines format (e.g., .png, .jpg, .tiff, .bmp).

Examples

>>> image = grapher.draw_graph(graph)
>>> Graphing.save_graph(image, "delaunay_triangulation.png")
>>> # Save with timestamp
>>> import datetime
>>> timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
>>> filename = f"graph_{timestamp}.png"
>>> Graphing.save_graph(image, filename)

Note

  • File format determined by extension

  • Overwrites existing files without warning

  • Directory must exist (not created automatically)

  • Static method can be called without Graphing instance

graphizy.show_graph(image_graph: ndarray, title: str = 'My beautiful graph', block: bool = False, delay_display: int = 100) None[source]

Display a graph image using the configured display backend.

This is a convenience wrapper around the global show_graph function that provides consistent image display with customizable options.

Parameters:
  • image_graph – Image array to display with shape (height, width, 3).

  • title – Window title for the display.

  • **kwargs – Additional arguments passed to the underlying show_graph function: - block: Whether to block execution until window is closed - delay_display: Delay before showing (for animations) - save_path: Optionally save image while displaying - Backend-specific options

Examples

>>> image = grapher.draw_graph(graph)
>>> Graphing.show_graph(image, title="Delaunay Triangulation")
>>> # Non-blocking display for animations
>>> Graphing.show_graph(image, title="Animation Frame", block=False)
>>> # Display with save
>>> Graphing.show_graph(
...     image,
...     title="Final Result",
...     save_path="output.png"
... )

Note

  • Display backend depends on system configuration (matplotlib, opencv, etc.)

  • Window behavior (blocking, resizing) depends on backend

  • Static method can be called without Graphing instance

graphizy.validate_graphizy_input(data_points, aspect='array', data_shape=None, dimension=(1200, 1200), proximity_thresh=None, verbose=True)[source]

Helper function to validate input data for graphizy operations

Parameters:
  • data_points – Input data (numpy array or dict)

  • aspect – “array” or “dict”

  • data_shape – Expected data shape structure

  • dimension – Image dimensions (width, height)

  • proximity_thresh – Proximity threshold if applicable

  • verbose – Print detailed validation info

Returns:

Validation results with errors, warnings, and info

Return type:

dict