Examples¶
Explore real-world applications of Q-Memetic AI through comprehensive examples. Each example includes complete code, explanations, and expected outcomes.
🧬 Basic Evolution Examples¶
Simple Text Evolution¶
Transform a simple idea through genetic evolution:
from qmemetic_ai import MemeticEngine
# Initialize engine
engine = MemeticEngine()
# Create initial meme
initial_idea = "Renewable energy is important"
meme = engine.create_meme(
content=initial_idea,
author="researcher",
domain="environment"
)
# Evolve over multiple generations
evolved_memes = engine.evolve(
memes=[meme],
generations=10,
population_size=30,
mutation_rate=0.3,
crossover_rate=0.7
)
# Show evolution progression
print("Evolution Results:")
for i, evolved in enumerate(evolved_memes[:5]):
print(f"{i+1}. Gen {evolved.metadata.generation}: {evolved.content}")
print(f" Fitness: {evolved.vector.fitness_score:.3f}")
print()
Expected Output:
Evolution Results:
1. Gen 5: Solar and wind energy are crucial for sustainable development
Fitness: 0.847
2. Gen 7: Renewable energy technologies will revolutionize global power systems
Fitness: 0.823
3. Gen 4: Clean energy is essential for combating climate change effectively
Fitness: 0.798
Multi-Domain Evolution¶
Evolve memes across different knowledge domains:
# Create memes in different domains
memes = [
engine.create_meme("AI will transform healthcare", domain="technology"),
engine.create_meme("Personalized medicine is the future", domain="medicine"),
engine.create_meme("Data privacy is fundamental", domain="ethics")
]
# Cross-pollinate ideas between domains
evolved_memes = engine.evolve(
memes=memes,
generations=8,
allow_cross_domain=True,
population_size=25
)
# Analyze domain mixing
for meme in evolved_memes:
domains = meme.metadata.domain_influences
print(f"Content: {meme.content[:60]}...")
print(f"Domain mix: {domains}")
print()
🔗 Entanglement Network Examples¶
Building Semantic Networks¶
Create networks of related concepts:
# Create a knowledge base of related memes
knowledge_memes = [
engine.create_meme("Machine learning algorithms learn from data", tags=["ML", "data"]),
engine.create_meme("Neural networks mimic brain structure", tags=["neural", "brain"]),
engine.create_meme("Deep learning uses multiple layers", tags=["deep", "layers"]),
engine.create_meme("AI can recognize patterns in images", tags=["AI", "vision"]),
engine.create_meme("Natural language processing understands text", tags=["NLP", "text"])
]
# Create entanglement network
network = engine.entangle()
# Analyze semantic relationships
for meme_id, connections in network['entanglements'].items():
meme = engine.get_meme(meme_id)
print(f"Meme: {meme.content[:40]}...")
print(f"Connected to {len(connections)} other memes:")
for connected_id, strength in connections[:3]: # Top 3 connections
connected_meme = engine.get_meme(connected_id)
print(f" → {connected_meme.content[:30]}... (strength: {strength:.3f})")
print()
Quantum Walk Exploration¶
Explore idea networks through quantum walks:
# Start quantum walk from a specific meme
start_meme = knowledge_memes[0]
walk_path = engine.quantum_walk(
start_meme=start_meme.meme_id,
steps=20,
teleport_probability=0.15
)
# Analyze the walk pattern
print("Quantum Walk Path:")
visited_concepts = []
for step, meme_id in enumerate(walk_path):
meme = engine.get_meme(meme_id)
concept = meme.content[:40] + "..."
if concept not in visited_concepts:
visited_concepts.append(concept)
print(f"Step {step}: {concept}")
print(f"\nVisited {len(visited_concepts)} unique concepts")
🌐 Federated Learning Examples¶
Distributed Meme Evolution¶
Coordinate evolution across multiple nodes:
# Initialize federated engine
fed_engine = MemeticEngine(
federated_mode=True,
federation_config={
"node_id": "research_lab_1",
"discovery_port": 8080
}
)
# Create local memes
local_memes = [
fed_engine.create_meme("Quantum computing breakthrough", author="lab1"),
fed_engine.create_meme("New optimization algorithm", author="lab1")
]
# Synchronize with network
async def federated_evolution():
# Share memes with network
await fed_engine.federated_sync(mode="push")
# Get memes from other nodes
received_memes = await fed_engine.federated_sync(mode="pull")
# Evolve combined pool
all_memes = local_memes + received_memes
evolved = fed_engine.evolve(all_memes, generations=5)
# Share evolved results
await fed_engine.federated_sync(mode="bidirectional")
return evolved
# Run federated evolution
import asyncio
evolved_memes = asyncio.run(federated_evolution())
🎨 Visualization Examples¶
Interactive Noosphere Map¶
Create rich visualizations of your memetic ecosystem:
# Create diverse meme population
memes = []
domains = ["science", "art", "philosophy", "technology"]
for domain in domains:
for i in range(5):
meme = engine.create_meme(
content=f"Innovative {domain} concept #{i+1}",
domain=domain,
author=f"{domain}_expert"
)
memes.append(meme)
# Create entanglement network
network = engine.entangle()
# Generate interactive visualization
viz_path = engine.visualize_noosphere(
network_data=network,
layout="force_directed",
color_by="domain",
size_by="fitness",
show_labels=True,
interactive=True,
save_path="noosphere_map.html"
)
print(f"Interactive map saved to: {viz_path}")
Evolution Timeline¶
Visualize how memes evolve over time:
# Track evolution with detailed history
evolution_history = engine.evolve(
memes=[engine.create_meme("Original idea")],
generations=10,
track_history=True,
population_size=20
)
# Create timeline visualization
timeline_path = engine.visualizer.create_evolution_timeline(
evolution_data=evolution_history,
show_fitness_curves=True,
show_generation_trees=True,
save_path="evolution_timeline.html"
)
print(f"Evolution timeline saved to: {timeline_path}")
🧠 Cognitive Modeling Examples¶
Personalized Meme Adaptation¶
Adapt memes to individual cognitive profiles:
# Create cognitive profile
user_profile = engine.create_cognitive_profile(
user_id="researcher_123",
preferences={
"technical_level": 0.8,
"domain_interests": ["AI", "quantum", "biology"],
"communication_style": "formal",
"complexity_preference": 0.7
}
)
# Create and adapt memes for this user
original_meme = engine.create_meme(
"Machine learning models can be trained on quantum computers"
)
adapted_meme = engine.adapt_for_user(
meme=original_meme,
user_profile=user_profile
)
print("Original:", original_meme.content)
print("Adapted:", adapted_meme.content)
print("Adaptation score:", adapted_meme.cognitive_fit_score)
Multi-User Cognitive Evolution¶
Evolve memes through multiple cognitive filters:
# Create multiple user profiles
users = [
engine.create_cognitive_profile("expert", {"technical_level": 0.9}),
engine.create_cognitive_profile("student", {"technical_level": 0.3}),
engine.create_cognitive_profile("general", {"technical_level": 0.5})
]
# Evolve meme through different cognitive lenses
meme = engine.create_meme("Artificial intelligence systems")
for user in users:
evolved = engine.cognitive_evolution(
meme=meme,
user_profile=user,
generations=3
)
print(f"For {user.user_id}: {evolved.content}")
📊 Analytics Examples¶
Comprehensive Meme Analysis¶
Deep dive into meme properties and relationships:
# Create and analyze a meme
meme = engine.create_meme(
content="Quantum entanglement enables instant communication",
author="physicist",
domain="quantum_physics",
tags=["quantum", "entanglement", "communication"]
)
# Get detailed analytics
analytics = engine.get_meme_analytics(meme.meme_id)
print("=== Meme Analytics ===")
print(f"Fitness Score: {analytics['fitness']['overall']:.3f}")
print(f"Semantic Coherence: {analytics['fitness']['semantic_coherence']:.3f}")
print(f"Novelty Score: {analytics['fitness']['novelty']:.3f}")
print(f"Domain Relevance: {analytics['fitness']['domain_relevance']:.3f}")
print(f"\nNetwork Position:")
print(f"Centrality: {analytics['network']['centrality']:.3f}")
print(f"Connected Memes: {len(analytics['network']['neighbors'])}")
print(f"\nEvolution Potential:")
print(f"Mutation Susceptibility: {analytics['evolution']['mutation_rate']:.3f}")
print(f"Crossover Compatibility: {analytics['evolution']['crossover_rate']:.3f}")
System-Wide Metrics¶
Monitor the health of your memetic ecosystem:
# Get comprehensive system status
status = engine.get_system_status()
print("=== System Health ===")
print(f"Total Memes: {status['data_metrics']['total_memes']}")
print(f"Network Density: {status['network_health']['graph_density']:.3f}")
print(f"Average Fitness: {status['data_metrics']['average_fitness']:.3f}")
print(f"Connected Components: {status['network_health']['connected_components']}")
# Analyze evolution trends
trends = engine.analyze_evolution_trends()
print(f"\n=== Evolution Trends ===")
print(f"Fitness Improvement Rate: {trends['fitness_improvement']:.3f}")
print(f"Diversity Index: {trends['diversity_index']:.3f}")
print(f"Innovation Rate: {trends['innovation_rate']:.3f}")
🛠️ Advanced Configuration Examples¶
Custom Evolution Parameters¶
Fine-tune the evolution process:
from qmemetic_ai.core.evolution import EvolutionParameters
# Create custom evolution parameters
custom_params = EvolutionParameters(
mutation_rate=0.4,
crossover_rate=0.8,
selection_pressure=0.6,
elitism_ratio=0.1,
diversity_weight=0.3,
fitness_function="custom",
population_dynamics="variable"
)
# Run evolution with custom parameters
evolved_memes = engine.evolve(
memes=initial_memes,
generations=15,
evolution_params=custom_params
)
Performance Optimization¶
Optimize for large-scale operations:
# Configure for high performance
engine = MemeticEngine(
license_key="your-key",
performance_config={
"max_memory": 16000, # MB
"parallel_workers": 8,
"gpu_acceleration": True,
"batch_size": 1000,
"cache_size": 5000
}
)
# Batch process multiple memes
batch_memes = [
engine.create_meme(f"Idea #{i}", batch_mode=True)
for i in range(1000)
]
# Efficient batch evolution
results = engine.batch_evolve(
meme_batches=batch_memes,
batch_size=100,
generations=5
)
🔍 Debugging Examples¶
Evolution Debugging¶
Track what happens during evolution:
# Enable debug mode
engine.set_debug_mode(True)
# Run evolution with detailed logging
evolved = engine.evolve(
memes=[initial_meme],
generations=5,
debug_callbacks={
"on_generation_start": lambda g: print(f"Starting generation {g}"),
"on_mutation": lambda m: print(f"Mutated: {m.content[:30]}..."),
"on_crossover": lambda p1, p2, c: print(f"Crossover created: {c.content[:30]}..."),
"on_selection": lambda selected: print(f"Selected {len(selected)} memes")
}
)
Network Analysis¶
Debug entanglement relationships:
# Analyze network structure
network = engine.entangle()
# Find isolated nodes
isolated = engine.find_isolated_memes()
print(f"Isolated memes: {len(isolated)}")
# Find highly connected hubs
hubs = engine.find_network_hubs(min_connections=5)
print(f"Hub memes: {len(hubs)}")
# Detect communities
communities = engine.detect_meme_communities()
print(f"Found {len(communities)} communities")
for i, community in enumerate(communities):
print(f"Community {i}: {len(community)} memes")
📈 Next Steps¶
These examples demonstrate the power and flexibility of Q-Memetic AI. To go deeper:
- Theory Guide - Understand the algorithms
- API Reference - Complete method documentation
- Performance Guide - Optimization techniques
- Advanced Guide - Enterprise features
Ready to build your own memetic applications? Check out our development guide!