Code Examples

Real-world examples showing how to use GenusCore for dynamic graph analytics and combinatorial optimization.

Example 1: Dynamic Graph with Incremental Updates

This example demonstrates GenusCore's key advantage: incremental shortest path updates that are 1000x faster than full recomputation. Perfect for real-time applications like traffic routing.

dynamic_graph_example.py
from genuscore import DynamicGraph
import numpy as np

def example_dynamic_graph():
    """
    Dynamic Graph with Incremental Shortest Paths
    
    Demonstrates 1000x faster updates compared to recomputation.
    """
    print("Creating 10x10 grid graph (100 nodes)...")
    
    # Create graph with 100 nodes
    G = DynamicGraph(num_nodes=100)
    
    # Build a grid topology
    for i in range(10):
        for j in range(10):
            node_id = i * 10 + j
            
            # Connect to right neighbor
            if j < 9:
                G.add_edge(node_id, node_id + 1, weight=1.0)
            
            # Connect to bottom neighbor
            if i < 9:
                G.add_edge(node_id, node_id + 10, weight=1.0)
    
    # Compute shortest paths from corner (node 0)
    print("Computing shortest paths from node 0...")
    distances = G.shortest_paths(source=0)
    
    print(f"Distance to opposite corner (node 99): {distances[99]}")
    # Expected: 18.0 (9 steps right + 9 steps down)
    
    # Create a shortcut
    print("\nAdding shortcut edge (0 → 99) with weight 5.0...")
    G.add_edge(0, 99, weight=5.0)
    
    # Incremental update (FAST!)
    print("Running incremental update...")
    new_distances = G.update_shortest_paths(source=0)
    
    print(f"New distance to node 99: {new_distances[99]}")
    # Expected: 5.0 (direct via shortcut)
    
    print("\n✓ Incremental update completed in milliseconds!")

if __name__ == "__main__":
    example_dynamic_graph()

Example 2: Max-Cut Optimization

Solve the NP-hard Max-Cut problem using the SwarmOptimizer. This partitions graph nodes to maximize the total weight of edges crossing the partition.

maxcut_example.py
from genuscore import SwarmOptimizer

def example_maxcut():
    """
    Max-Cut Optimization with SwarmOptimizer
    
    Find the optimal partition to maximize cut edges.
    """
    # Create optimizer for 10-node graph
    opt = SwarmOptimizer(num_nodes=10)
    
    # Define graph edges (cycle + cross-edges)
    edges = [
        # Main cycle
        (0, 1), (1, 2), (2, 3), (3, 4),
        (4, 5), (5, 6), (6, 7), (7, 8),
        (8, 9), (9, 0),
        # Cross-edges for more interesting structure
        (0, 5), (2, 7), (4, 9)
    ]
    
    print(f"Loaded graph with {len(edges)} edges")
    
    # Load graph into optimizer
    opt.load_graph(edges)
    
    # Solve Max-Cut
    print("Solving Max-Cut with swarm optimization...")
    result = opt.solve_maxcut(
        iterations=500,
        noise_schedule=(1.0, 0.1)  # (initial_noise, final_noise)
    )
    
    # Results
    print(f"\n✓ Optimization complete!")
    print(f"  Cut value: {result.objective_value}")
    print(f"  Best cut found: {result.best_objective}")
    print(f"  Iterations: {result.iterations}")
    print(f"  Time: {result.time_ms:.2f}ms")
    
    # Interpret partition
    partition_0 = [i for i, p in enumerate(result.solution) if p == 0]
    partition_1 = [i for i, p in enumerate(result.solution) if p == 1]
    
    print(f"\n  Partition 0: {partition_0}")
    print(f"  Partition 1: {partition_1}")

if __name__ == "__main__":
    example_maxcut()

Example 3: Ising Machine

Use the IsingMachine for optimization problems formulated as finding ground states of Ising Hamiltonians. Supports both graph-based and QUBO formulations.

ising_example.py
from genuscore import IsingMachine
import numpy as np

def example_ising():
    """
    Ising Machine for Combinatorial Optimization
    
    Solve via ground state search.
    """
    # Create Ising machine with 20 spins
    ising = IsingMachine(num_spins=20)
    
    # Create a frustrated lattice (ring with skip connections)
    edges = []
    for i in range(20):
        edges.append((i, (i + 1) % 20))   # Ring connections
        edges.append((i, (i + 2) % 20))   # Skip connections
    
    print(f"Created frustrated lattice with {len(edges)} edges")
    
    # Load graph
    ising.load_graph(edges)
    
    # Solve with parallel runs for better results
    print("Solving with Ising machine (4 parallel runs)...")
    result = ising.solve(
        iterations=500,
        parallel_runs=4,
        damping=0.1
    )
    
    print(f"\n✓ Optimization complete!")
    print(f"  Best energy: {result.objective_value}")
    print(f"  Iterations: {result.iterations}")
    print(f"  Time: {result.time_ms:.2f}ms")
    
    # Count +1 and -1 spins
    spins = result.solution
    num_up = np.sum(spins == 1)
    num_down = np.sum(spins == -1)
    
    print(f"\n  Spins up (+1): {num_up}")
    print(f"  Spins down (-1): {num_down}")

if __name__ == "__main__":
    example_ising()

Example 4: Performance Benchmark

Measure the speedup of incremental updates vs. full recomputation on larger graphs.

benchmark_example.py
from genuscore import DynamicGraph
import numpy as np
import time

def benchmark_incremental():
    """
    Benchmark: Incremental vs Full Recomputation
    
    Shows the dramatic speedup of incremental updates.
    """
    print("Creating 1000-node random graph...")
    
    G = DynamicGraph(num_nodes=1000)
    
    # Create random graph with 5000 edges
    np.random.seed(42)
    for _ in range(5000):
        u = np.random.randint(0, 1000)
        v = np.random.randint(0, 1000)
        if u != v:
            w = np.random.random()
            G.add_edge(u, v, weight=w)
    
    print("Graph created with ~5000 edges\n")
    
    # Full computation
    print("Running FULL shortest paths computation...")
    start = time.time()
    distances = G.shortest_paths(source=0, max_iterations=200)
    full_time = (time.time() - start) * 1000
    print(f"  Full computation: {full_time:.2f}ms")
    
    # Update some edges
    print("\nUpdating 10 random edges...")
    for _ in range(10):
        u = np.random.randint(0, 1000)
        v = np.random.randint(0, 1000)
        try:
            G.update_edge(u, v, weight=np.random.random() * 0.5)
        except ValueError:
            pass  # Edge doesn't exist
    
    # Incremental update
    print("Running INCREMENTAL update...")
    start = time.time()
    new_distances = G.update_shortest_paths(source=0, max_iterations=20)
    incr_time = (time.time() - start) * 1000
    print(f"  Incremental update: {incr_time:.2f}ms")
    
    # Speedup
    if incr_time > 0:
        speedup = full_time / incr_time
        print(f"\n✓ Speedup: {speedup:.1f}x faster!")
    
    print("\nThis is GenusCore's key advantage:")
    print("  → Update edges without full recomputation")
    print("  → Essential for real-time applications")

if __name__ == "__main__":
    benchmark_incremental()

Example 5: Real-time Routing Application

A practical example showing how to use GenusCore for real-time route optimization with dynamic traffic conditions.

routing_example.py
from genuscore import DynamicGraph
import numpy as np

class TrafficRouter:
    """
    Real-time routing with dynamic traffic updates.
    
    Use case: Navigation system that adapts to live traffic.
    """
    
    def __init__(self, num_intersections: int):
        self.graph = DynamicGraph(num_nodes=num_intersections)
        self.base_weights = {}
    
    def add_road(self, from_intersection: int, to_intersection: int, 
                 base_travel_time: float):
        """Add a road with base travel time (minutes)."""
        self.graph.add_edge(from_intersection, to_intersection, base_travel_time)
        self.base_weights[(from_intersection, to_intersection)] = base_travel_time
    
    def update_traffic(self, from_int: int, to_int: int, congestion_factor: float):
        """
        Update road with traffic congestion.
        
        congestion_factor: 1.0 = normal, 2.0 = double travel time, etc.
        """
        base = self.base_weights.get((from_int, to_int), 1.0)
        new_weight = base * congestion_factor
        self.graph.update_edge(from_int, to_int, new_weight)
    
    def compute_routes(self, origin: int) -> np.ndarray:
        """Compute travel times from origin (full computation)."""
        return self.graph.shortest_paths(source=origin)
    
    def update_routes(self, origin: int) -> np.ndarray:
        """Update routes after traffic change (fast incremental)."""
        return self.graph.update_shortest_paths(source=origin)


def example_routing():
    # Create router for 500 intersections
    router = TrafficRouter(num_intersections=500)
    
    # Build road network (simplified grid)
    for i in range(500):
        if i + 1 < 500:
            router.add_road(i, i + 1, base_travel_time=2.0)
        if i + 20 < 500:
            router.add_road(i, i + 20, base_travel_time=3.0)
    
    # Initial route computation
    print("Computing initial routes from intersection 0...")
    travel_times = router.compute_routes(origin=0)
    print(f"Travel time to intersection 100: {travel_times[100]:.1f} min")
    
    # Traffic incident! Road 50→51 is congested
    print("\n⚠️  Traffic incident on road 50→51!")
    router.update_traffic(50, 51, congestion_factor=5.0)
    
    # Fast incremental update
    print("Updating routes (incremental)...")
    new_times = router.update_routes(origin=0)
    print(f"New travel time to intersection 100: {new_times[100]:.1f} min")
    
    print("\n✓ Routes updated in real-time!")

if __name__ == "__main__":
    example_routing()

Ready to try GenusCore?

Start with a free 14-day trial. Full access to all features.