Skip to main content

Graphizy is a fast, flexible Python library for building and analyzing computational geometry-based graphs from 2D coordinates.

Project description

Documentation Status PyPI Version Python Version CI Tests GPL-2.0 License

Graphizy

Graphizy

Graphizy is a powerful, fast, and flexible Python library for building and analyzing graphs from 2D spatial data. Designed for computational geometry and network visualization, it supports multiple graph types, real-time analysis, memory-enhanced temporal graphs, and comprehensive weight computation systems โ€” all powered by OpenCV and igraph with a modern, unified API.

Detection to Graph

Convert spatial coordinates to analyzed graphs in milliseconds. Real-time graph analytics accessible through comprehensive igraph integration with enhanced memory and weight systems.

Documentation

๐Ÿ“– Full Documentation

โœจ Key Features

  • One API for All Graphs Create Delaunay, k-NN, MST, Gabriel, Proximity, and even custom graphs with a single make_graph() call. Plugin-friendly, smart defaults, and fully type-safe.

  • Temporal Memory System Track how connections evolve over time. Use built-in memory features for persistence-aware analysis, temporal filtering, and age-based visualization.

  • Rich Graph Types, Easily Extended From spatial graphs to domain-specific topologies: support includes Delaunay triangulations, proximity graphs, k-nearest neighbors, MSTs, and custom plugins.

  • Instant Network Analysis Access over 200 igraph algorithms with real-time stats: clustering, centrality, components, and more. All robust to disconnections. NetworkX compatible.

  • Custom Weights, Real-Time Ready Define weights using distance, inverse, Gaussian, or custom formulas. Memory-aware weight updates and vectorized for performance.

  • Advanced Tools for Spatial & Temporal Insights Includes percolation thresholds, service accessibility, social dynamics, and time-aware community tracking โ€” all tailored for dynamic networks.

  • Visualization & Streaming Visualize network memory with age-based coloring and transparency. Stream updates in real time, or export static snapshots. Comes with CLI tools and interactive demos.

๐Ÿ”„ Unified Graph Creation Interface

  • Modern API: Single make_graph() method for all graph types
  • Plugin System: Easily add custom graph algorithms
  • Smart Defaults: Intelligent parameter handling with memory and weight integration
  • Type Safety: Runtime configuration validation with detailed error messages

๐Ÿ“Š Comprehensive Graph Types

  • Delaunay Triangulation: Optimal triangular meshes from point sets
  • Proximity Graphs: Connect nearby points based on distance thresholds
  • K-Nearest Neighbors: Connect each point to its k closest neighbors
  • Minimum Spanning Tree: Minimal connected graph with shortest total edge length
  • Gabriel Graph: Geometric proximity graph (subset of Delaunay triangulation)
  • Custom Graphs: Extensible plugin system for domain-specific algorithms

๐Ÿง  Advanced Memory Systems

  • Temporal Analysis: Track connections across time steps for dynamic systems
  • Smart Integration: Automatic memory updates with configurable retention policies
  • Age-Based Visualization: Visual feedback showing connection persistence over time
  • Performance Optimized: Vectorized operations for real-time applications

โš–๏ธ Sophisticated Weight Computation

  • Multiple Methods: Distance, inverse distance, Gaussian, and custom formulas
  • Real-Time Computation: Optimized fast computers for high-performance applications
  • Edge Attributes: Compute any edge attribute using mathematical expressions
  • Memory Integration: Weight computation on memory-enhanced graph structures

๐Ÿ“ˆ Comprehensive Graph Analysis

  • igraph Integration: Full access to 200+ graph analysis algorithms
  • Resilient Methods: Robust analysis that handles disconnected graphs gracefully
  • Real-Time Statistics: Vertex count, edge count, connectivity, clustering, centrality
  • Component Analysis: Detailed connectivity and community structure analysis

๐ŸŽจ Advanced Visualization & Real-Time Processing

  • Memory Visualization: Age-based coloring and transparency effects
  • Real-Time Streaming: High-performance streaming with async support
  • Flexible Configuration: Runtime-configurable parameters using type-safe dataclasses
  • Interactive Demos: Built-in demonstrations and CLI tools

๐Ÿš€ Installation

pip install graphizy

For development:

git clone https://github.com/cfosseprez/graphizy.git
cd graphizy
pip install -e .

โšก Quick Start

Modern Unified Interface

from graphizy import Graphing, GraphizyConfig, generate_and_format_positions

# Generate sample data
data = generate_and_format_positions(size_x=800, size_y=600, num_particles=100)

# Configure and create grapher
config = GraphizyConfig(dimension=(800, 600))
grapher = Graphing(config=config)

# Create different graph types using unified interface
delaunay_graph = grapher.make_graph("delaunay", data)
proximity_graph = grapher.make_graph("proximity", data, proximity_thresh=50.0)
knn_graph = grapher.make_graph("knn", data, k=4)
mst_graph = grapher.make_graph("mst", data)
gabriel_graph = grapher.make_graph("gabriel", data)

# Visualize results
image = grapher.draw_graph(delaunay_graph)
grapher.show_graph(image, "Delaunay Graph")
grapher.save_graph(image, "delaunay.jpg")

Advanced Analysis with Modern API

# Comprehensive graph analysis
results = grapher.get_graph_info(delaunay_graph) # This call is instantaneous

# Print a clean, pre-formatted summary
print(results.summary())

# Access specific metrics as properties (computed on first access)
print(f"Density: {results.density:.3f}")
print(f"Diameter: {results.diameter}")

# Use helper methods for deeper analysis
top_hubs = results.get_top_n_by('degree', n=3)
print(f"Top 3 hubs (by degree): {top_hubs}")

betweenness_stats = results.get_metric_stats('betweenness')
print(f"Betweenness Centrality Stats: {betweenness_stats}")

๐Ÿง  Memory-Enhanced Temporal Graphs

Track connections over time for dynamic system analysis:

import numpy as np

# Initialize memory system
grapher.init_memory_manager(max_memory_size=200, track_edge_ages=True)

# Simulate evolution over time with automatic memory integration
for iteration in range(100):
    # Update positions (e.g., particle movement)
    data[:, 1:3] += np.random.normal(0, 2, (len(data), 2))
    
    # Create memory-enhanced graph (automatic with smart defaults)
    memory_graph = grapher.make_graph("proximity", data, proximity_thresh=60.0)
    # Automatically: use_memory=True, update_memory=True, compute_weights=True
    
    # Visualize with age-based coloring every 10 iterations
    if iteration % 10 == 0:
        memory_image = grapher.draw_memory_graph(
            memory_graph, 
            use_age_colors=True,
            alpha_range=(0.3, 1.0)  # Older connections fade
        )
        grapher.save_graph(memory_image, f"memory_frame_{iteration:03d}.jpg")

# Analyze memory evolution
memory_stats = grapher.get_memory_analysis()
print(f"Total historical connections: {memory_stats['total_connections']}")
print(f"Average edge age: {memory_stats['edge_age_stats']['avg_age']:.1f}")

โš–๏ธ Advanced Weight Computation

Compute sophisticated edge weights with multiple methods:

# Initialize weight computation system
grapher.init_weight_computer(method="gaussian", target_attribute="similarity")

# Create graphs with automatic weight computation
weighted_graph = grapher.make_graph("proximity", data, 
                                   proximity_thresh=70.0,
                                   compute_weights=True)

# Analyze edge weights
if 'similarity' in weighted_graph.es.attributes():
    weights = weighted_graph.es['similarity']
    print(f"Weight statistics: mean={np.mean(weights):.3f}, std={np.std(weights):.3f}")

# Custom weight formulas
grapher.compute_edge_attribute(weighted_graph, "custom_weight", 
                              method="formula", 
                              formula="1.0 / (1.0 + distance * 0.01)")

# Real-time optimized weight computation
grapher.setup_fast_attributes(
    distance={"method": "distance", "target": "dist"},
    strength={"method": "inverse_distance", "target": "strength"}
)
fast_graph = grapher.make_graph("delaunay", data, compute_weights=False)
grapher.compute_all_attributes_fast(fast_graph)  # High-performance computation

๐Ÿ”„ Automated Multi-Graph Processing

Process multiple graph types automatically with memory and weights:

# Configure automatic processing
grapher.set_graph_type(['delaunay', 'proximity', 'knn', 'mst'])
grapher.update_graph_params('proximity', proximity_thresh=60.0, metric='euclidean')
grapher.update_graph_params('knn', k=5)

# Initialize integrated systems
grapher.init_memory_manager(max_memory_size=150, track_edge_ages=True)
grapher.init_weight_computer(method="distance", target_attribute="weight")

# Process all graph types with full pipeline: graph โ†’ memory โ†’ weights
all_graphs = grapher.update_graphs(data)  # Smart defaults: use_memory=True, update_memory=True, compute_weights=True

# Analyze results
for graph_type, graph in all_graphs.items():
    if graph:
        info = grapher.get_graph_info(graph)
        print(f"{graph_type}: {info['edge_count']} edges, density={info['density']:.3f}")
        
        # Check for computed weights
        if 'weight' in graph.es.attributes():
            weights = graph.es['weight']
            print(f"  Weights: avg={np.mean(weights):.3f}")

๐ŸŽฏ Graph Types Comparison

Graph Type Connectivity Typical Edges Use Case Memory Compatible Weight Compatible
Delaunay Always ~3n Mesh generation, spatial analysis โœ… โœ…
Proximity Variable ~distanceยฒ Local neighborhoods, clustering โœ… โœ…
K-NN Variable kร—n Machine learning, recommendation โœ… โœ…
MST Always n-1 Minimal connectivity, optimization โœ… โœ…
Gabriel Variable โІ Delaunay Wireless networks, geometric constraints โœ… โœ…
Memory Variable Historical Temporal analysis, evolution tracking N/A โœ…

๐Ÿƒโ€โ™‚๏ธ Real-Time Streaming

High-performance real-time graph processing:

# Create stream manager for real-time processing
stream_manager = grapher.create_stream_manager(
    buffer_size=1000,
    update_interval=0.05,  # 20 FPS
    auto_memory=True
)

# Add real-time visualization callback
def visualize_callback(graphs):
    if 'proximity' in graphs and graphs['proximity']:
        image = grapher.draw_memory_graph(graphs['proximity'], use_age_colors=True)
        grapher.show_graph(image, "Real-time Graph", block=False)

stream_manager.add_callback(visualize_callback)
stream_manager.start_streaming()

# Feed real-time data
for frame in data_stream:
    stream_manager.push_data(frame)

# Async streaming for high-performance applications
async_manager = grapher.create_async_stream_manager(buffer_size=2000)
# ... async processing

๐Ÿ”ง Plugin System

Easily extend Graphizy with custom graph types:

from graphizy import graph_type_plugin
import igraph as ig

@graph_type_plugin(
    name="custom_algorithm",
    description="Your custom graph algorithm",
    category="custom",
    parameters={
        "threshold": {"type": "float", "default": 0.5, "description": "Algorithm threshold"}
    }
)
def create_custom_graph(data_points, dimension, **kwargs):
    # Your algorithm implementation
    # ... create igraph Graph
    return graph

# Use immediately with unified interface
custom_graph = grapher.make_graph("custom_algorithm", data, threshold=0.7)

๐Ÿ“Š Performance & Scalability

  • Real-time Processing: Handle 1000+ points at 60+ FPS
  • Memory Efficiency: Optimized data structures with configurable memory limits
  • Vectorized Operations: NumPy and OpenCV optimizations throughout
  • Async Support: High-performance asynchronous streaming capabilities
  • Smart Caching: Intelligent caching of expensive computations

๐Ÿ› ๏ธ Advanced Configuration

Type-safe, runtime-configurable parameters:

# Comprehensive configuration
config = GraphizyConfig(
    dimension=(1200, 800),
    drawing={
        "line_color": (255, 0, 0),
        "point_color": (0, 255, 255), 
        "line_thickness": 2,
        "point_radius": 8
    },
    graph={
        "proximity_threshold": 75.0,
        "distance_metric": "euclidean"
    },
    memory={
        "max_memory_size": 200,
        "auto_update_from_proximity": True
    },
    weight={
        "auto_compute_weights": True,
        "weight_method": "gaussian"
    }
)

grapher = Graphing(config=config)

# Runtime updates
grapher.update_config(
    drawing={"line_thickness": 3},
    memory={"max_memory_size": 300}
)

๐Ÿ“š Examples & Documentation

Comprehensive examples demonstrating all features:

  • 1_basic_usage.py - Modern unified interface and all graph types
  • 2_graph_metrics.py - Advanced analysis with resilient methods
  • 3_advanced_memory.py - Memory systems and temporal analysis
  • 4_weight_computation.py - Weight systems and custom formulas
  • 5_add_new_graph_type.py - Plugin system and custom algorithms
  • 6_stream_example.py - Real-time streaming and async processing
# Run examples
python examples/1_basic_usage.py
python examples/2_graph_metrics.py
python examples/3_advanced_memory.py

# Interactive demo
python examples/0_interactive_demo.py

๐Ÿ”ฌ Advanced Use Cases

Scientific Computing

# Particle physics simulations with temporal tracking
grapher.init_memory_manager(max_memory_size=1000, track_edge_ages=True)
for timestep in simulation:
    particle_graph = grapher.make_graph("delaunay", particle_positions[timestep])
    analyze_particle_interactions(particle_graph)

Network Analysis

# Social network evolution with weight analysis
grapher.init_weight_computer(method="inverse_distance", target_attribute="friendship_strength")
social_graph = grapher.make_graph("proximity", user_positions, 
                                 proximity_thresh=influence_radius,
                                 compute_weights=True)

Computer Vision

# Feature point tracking in video streams
async for frame_features in video_stream:
    feature_graph = grapher.make_graph("knn", frame_features, k=8)
    track_feature_evolution(feature_graph)

๐Ÿ“‹ Requirements

  • Python >= 3.8
  • NumPy >= 1.20.0
  • OpenCV >= 4.5.0
  • python-igraph >= 0.9.0
  • SciPy >= 1.7.0 (for KNN and MST)
  • networkx >= 3.0 (for NetworkX bridge)

๐Ÿงช Development & Testing

# Install development dependencies
pip install -e ".[dev]"

# Run tests with coverage
pytest tests/ --cov=graphizy --cov-report=html

# Code quality
black src/
flake8 src/
mypy src/graphizy/

# Performance testing
python examples/benchmark_comparison.py

๐Ÿ“ˆ Changelog

v0.1.17 (Current)

  • โœ… Unified make_graph() Interface: Single method for all graph types
  • โœ… Enhanced Memory Systems: Smart defaults and vectorized operations
  • โœ… Advanced Weight Computation: Multiple methods with real-time optimization
  • โœ… Resilient Analysis Methods: Robust handling of disconnected graphs
  • โœ… Plugin System Enhancements: Advanced parameter validation and documentation
  • โœ… Real-Time Streaming: Async support and performance optimizations
  • โœ… Comprehensive Documentation: Updated examples and API reference

Previous Versions

  • v0.1.16: Added MST and Gabriel graph types, enhanced memory visualization
  • v0.1.15: Initial memory system and weight computation
  • v0.1.14: Plugin system and custom graph types
  • v0.1.13: Core graph types and visualization

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Add comprehensive tests for new functionality
  4. Ensure all tests pass (pytest tests/)
  5. Update documentation and examples
  6. Commit changes (git commit -m 'Add amazing feature')
  7. Push to branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

๐Ÿ“„ License

GPL-2.0-or-later License - see LICENSE file for details.

๐Ÿ‘จโ€๐Ÿ’ป Author

Charles Fosseprez
๐Ÿ“ง Email: charles.fosseprez.pro@gmail.com
๐Ÿ™ GitHub: @cfosseprez
๐Ÿ“– Documentation: graphizy.readthedocs.io

๐Ÿ™ Acknowledgments

Built with powerful open-source libraries:

  • OpenCV for high-performance computer vision operations
  • igraph for comprehensive graph analysis algorithms
  • NumPy for efficient numerical computations
  • SciPy for scientific computing functions

Built with โค๏ธ for computational geometry, network analysis, and real-time graph processing

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

graphizy-0.1.20.tar.gz (149.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

graphizy-0.1.20-py3-none-any.whl (114.4 kB view details)

Uploaded Python 3

File details

Details for the file graphizy-0.1.20.tar.gz.

File metadata

  • Download URL: graphizy-0.1.20.tar.gz
  • Upload date:
  • Size: 149.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.9.13 Windows/10

File hashes

Hashes for graphizy-0.1.20.tar.gz
Algorithm Hash digest
SHA256 5bed6d7a5979b0e4ac2e011407ba2db7785a3f394b39e810513ae6da79dab6a1
MD5 a849dfb5673e40bedde15cdb4607189c
BLAKE2b-256 a29797871bbc5b08ca312f6f7d4081b8c095d8c74e18d967822d30f5b8d3e47d

See more details on using hashes here.

File details

Details for the file graphizy-0.1.20-py3-none-any.whl.

File metadata

  • Download URL: graphizy-0.1.20-py3-none-any.whl
  • Upload date:
  • Size: 114.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.9.13 Windows/10

File hashes

Hashes for graphizy-0.1.20-py3-none-any.whl
Algorithm Hash digest
SHA256 4362df93bd85a61a26ae3a06ec49a9ac525d494ba9157a0548287dd21e9173ad
MD5 de5d922a072cf460848119906a885d79
BLAKE2b-256 a785a8f506b625b68cd0116798558529d1f3e585d144e12bd2c6d3b0dbe790f4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page