User Guide¶
Comprehensive guide to using Q-Memetic AI for research, development, and production applications.
🎯 Core Concepts¶
Understanding Memes¶
In Q-Memetic AI, a meme is a computational unit that represents an idea with:
- Content: The textual representation of the idea
- Vector: High-dimensional semantic embedding
- Metadata: Author, domain, tags, generation info
- Fitness: Quality metrics and evolutionary potential
from qmemetic_ai import MemeticEngine
engine = MemeticEngine()
# Create a meme with full metadata
meme = engine.create_meme(
content="Artificial intelligence will revolutionize education",
author="dr_smith",
domain="education_technology",
tags=["AI", "education", "future"],
metadata={
"institution": "University of AI",
"research_area": "Educational Technology",
"confidence_level": 0.85
}
)
print(f"Meme ID: {meme.meme_id}")
print(f"Fitness: {meme.vector.fitness_score:.3f}")
print(f"Vector dimension: {meme.vector.dimension}")
Evolution Process¶
Memes evolve through genetic algorithms with quantum-inspired operations:
Mutation¶
Ideas are mutated using LLM-powered transformations:
# Configure mutation parameters
evolution_config = {
"mutation_rate": 0.3,
"mutation_types": ["semantic", "structural", "creative"],
"llm_model": "gpt-4",
"temperature": 0.7
}
# Single meme mutation
mutated = engine.mutate_meme(meme, config=evolution_config)
print(f"Original: {meme.content}")
print(f"Mutated: {mutated.content}")
Crossover¶
Two parent memes combine to create offspring:
# Create two parent memes
parent1 = engine.create_meme("Quantum computing enables new algorithms")
parent2 = engine.create_meme("Machine learning requires massive datasets")
# Perform crossover
offspring = engine.crossover_memes(parent1, parent2)
print(f"Parent 1: {parent1.content}")
print(f"Parent 2: {parent2.content}")
print(f"Child: {offspring.content}")
Selection¶
Fittest memes are selected based on multiple criteria:
# Configure fitness function
fitness_config = {
"weights": {
"semantic_coherence": 0.3,
"novelty": 0.3,
"domain_relevance": 0.2,
"user_preference": 0.2
},
"selection_method": "tournament",
"tournament_size": 3
}
# Get fitness breakdown
fitness_details = engine.analyze_fitness(meme, config=fitness_config)
print("Fitness Components:")
for component, score in fitness_details.items():
print(f" {component}: {score:.3f}")
Quantum Entanglement¶
Memes become entangled based on semantic similarity and interaction patterns:
# Create multiple related memes
memes = [
engine.create_meme("Deep learning neural networks", domain="AI"),
engine.create_meme("Artificial neural networks mimic the brain", domain="neuroscience"),
engine.create_meme("Machine learning algorithms learn from data", domain="computer_science")
]
# Calculate entanglement strengths
entanglement_matrix = engine.calculate_entanglement(memes)
# Display entanglement relationships
for i, meme1 in enumerate(memes):
for j, meme2 in enumerate(memes[i+1:], i+1):
strength = entanglement_matrix[i][j]
if strength > 0.5: # Strong entanglement
print(f"Strong entanglement ({strength:.3f}):")
print(f" Meme 1: {meme1.content[:40]}...")
print(f" Meme 2: {meme2.content[:40]}...")
🛠️ Working with the Engine¶
Engine Configuration¶
Customize the engine for your specific needs:
# Basic configuration
engine = MemeticEngine(
license_key="your-key",
data_dir="./my_memetic_data",
federated_mode=False
)
# Advanced configuration
advanced_engine = MemeticEngine(
license_key="your-key",
data_dir="./advanced_data",
federated_mode=True,
config={
# Performance settings
"max_memory": 8000, # MB
"parallel_workers": 4,
"batch_size": 500,
# Evolution settings
"default_population_size": 50,
"default_generations": 10,
"mutation_rate": 0.25,
# Network settings
"entanglement_threshold": 0.3,
"max_connections_per_meme": 20,
# LLM settings
"llm_provider": "openai",
"model_name": "gpt-4",
"api_key": "your-openai-key"
}
)
Data Management¶
Efficiently manage your memetic data:
# Save engine state
engine.save_state("my_experiment.json")
# Load previous state
engine.load_state("my_experiment.json")
# Export specific memes
selected_memes = engine.get_memes_by_tag("important")
engine.export_memes(selected_memes, "important_memes.json")
# Import memes from external source
imported_memes = engine.import_memes("external_memes.json")
print(f"Imported {len(imported_memes)} memes")
# Backup entire system
backup_path = engine.create_backup()
print(f"Backup saved to: {backup_path}")
Search and Retrieval¶
Find memes using various criteria:
# Search by content similarity
similar_memes = engine.search_similar(
query="artificial intelligence in healthcare",
top_k=10,
similarity_threshold=0.7
)
# Search by metadata
tagged_memes = engine.search_by_metadata(
domain="healthcare",
author="medical_researcher",
tags=["AI", "diagnosis"]
)
# Advanced semantic search
semantic_results = engine.semantic_search(
query="quantum computing applications",
filters={
"fitness_min": 0.5,
"generation_min": 3,
"domain": ["technology", "science"]
},
sort_by="fitness",
limit=20
)
# Search by evolution lineage
family_memes = engine.get_evolution_family(meme.meme_id)
print(f"Found {len(family_memes)} related memes in evolution family")
🎨 Visualization and Analysis¶
Creating Visualizations¶
Generate rich visualizations of your memetic ecosystem:
# Basic noosphere visualization
viz_path = engine.visualize_noosphere(
layout="force_directed",
color_by="domain",
size_by="fitness"
)
# Advanced customization
custom_viz = engine.visualize_noosphere(
layout="hierarchical",
color_by="generation",
size_by="centrality",
node_labels=True,
edge_labels=True,
interactive=True,
theme="dark",
width=1200,
height=800,
save_path="custom_noosphere.html"
)
# Evolution timeline
timeline = engine.create_evolution_timeline(
meme_families=family_memes,
show_fitness_progression=True,
show_mutation_events=True,
animation_speed=1.5
)
# Fitness landscape
landscape = engine.visualize_fitness_landscape(
population=evolved_memes,
dimensions=["novelty", "coherence"],
show_pareto_front=True
)
Analytics and Metrics¶
Deep analysis of your memetic system:
# System-wide analytics
analytics = engine.get_comprehensive_analytics()
print("=== Population Analytics ===")
print(f"Total memes: {analytics['population']['total']}")
print(f"Active memes: {analytics['population']['active']}")
print(f"Average fitness: {analytics['population']['avg_fitness']:.3f}")
print(f"Fitness std dev: {analytics['population']['fitness_std']:.3f}")
print("\n=== Network Analytics ===")
print(f"Network density: {analytics['network']['density']:.3f}")
print(f"Average clustering: {analytics['network']['clustering']:.3f}")
print(f"Small world coefficient: {analytics['network']['small_world']:.3f}")
print(f"Network diameter: {analytics['network']['diameter']}")
print("\n=== Evolution Analytics ===")
print(f"Generation diversity: {analytics['evolution']['diversity']:.3f}")
print(f"Innovation rate: {analytics['evolution']['innovation_rate']:.3f}")
print(f"Selection pressure: {analytics['evolution']['selection_pressure']:.3f}")
# Individual meme analysis
meme_analysis = engine.analyze_meme_detailed(meme.meme_id)
print(f"\n=== Meme Analysis: {meme.meme_id} ===")
print(f"Content quality: {meme_analysis['quality']['content']:.3f}")
print(f"Semantic coherence: {meme_analysis['quality']['coherence']:.3f}")
print(f"Network influence: {meme_analysis['influence']['centrality']:.3f}")
print(f"Evolution potential: {meme_analysis['evolution']['potential']:.3f}")
Performance Monitoring¶
Monitor system performance and optimization:
# Performance metrics
perf_metrics = engine.get_performance_metrics()
print("=== Performance Metrics ===")
print(f"Memory usage: {perf_metrics['memory']['used']:.1f} MB")
print(f"CPU utilization: {perf_metrics['cpu']['usage']:.1f}%")
print(f"Evolution speed: {perf_metrics['evolution']['memes_per_second']:.1f}")
print(f"Network update rate: {perf_metrics['network']['updates_per_second']:.1f}")
# Profiling evolution runs
with engine.profile_evolution() as profiler:
evolved = engine.evolve(memes, generations=5)
profile_report = profiler.get_report()
print(f"Evolution took {profile_report['total_time']:.2f} seconds")
print(f"Bottlenecks: {profile_report['bottlenecks']}")
🌐 Federated Operations¶
Setting Up Federation¶
Configure distributed memetic computing:
# Initialize federated engine
fed_engine = MemeticEngine(
license_key="your-key",
federated_mode=True,
federation_config={
"node_id": "research_node_1",
"discovery_port": 8080,
"sync_interval": 300, # seconds
"max_peers": 10,
"trust_threshold": 0.7
}
)
# Register with network
await fed_engine.register_with_network()
# Discover peers
peers = await fed_engine.discover_peers()
print(f"Found {len(peers)} peer nodes")
Federated Evolution¶
Coordinate evolution across multiple nodes:
async def run_federated_evolution():
# Create local memes
local_memes = [
fed_engine.create_meme("Local research insight 1"),
fed_engine.create_meme("Local research insight 2")
]
# Synchronize with network
sync_result = await fed_engine.federated_sync(
mode="bidirectional",
max_memes_exchange=100
)
print(f"Synchronized with {sync_result['peers_contacted']} peers")
print(f"Sent {sync_result['memes_sent']} memes")
print(f"Received {sync_result['memes_received']} memes")
# Get combined meme pool
all_memes = fed_engine.get_all_memes()
# Run distributed evolution
evolved_memes = await fed_engine.federated_evolve(
memes=all_memes,
generations=5,
coordination_strategy="democratic"
)
return evolved_memes
# Run federated evolution
import asyncio
results = asyncio.run(run_federated_evolution())
Trust and Security¶
Manage trust and security in federated networks:
# Configure trust settings
trust_config = {
"require_signatures": True,
"min_trust_score": 0.6,
"reputation_decay": 0.95,
"byzantine_tolerance": 0.33
}
fed_engine.update_trust_config(trust_config)
# Monitor peer reputation
peer_stats = fed_engine.get_peer_statistics()
for peer_id, stats in peer_stats.items():
print(f"Peer {peer_id}:")
print(f" Trust score: {stats['trust_score']:.3f}")
print(f" Memes contributed: {stats['contributions']}")
print(f" Uptime: {stats['uptime']:.1f}%")
# Audit federated operations
audit_log = fed_engine.get_federation_audit()
print(f"Total federated operations: {len(audit_log)}")
for operation in audit_log[-5:]: # Last 5 operations
print(f" {operation['timestamp']}: {operation['type']} - {operation['status']}")
🔧 Advanced Features¶
Custom Fitness Functions¶
Create domain-specific fitness evaluation:
def scientific_fitness(meme, context):
"""Custom fitness function for scientific content."""
score = 0.0
# Check for scientific rigor
if "experiment" in meme.content.lower():
score += 0.2
if "hypothesis" in meme.content.lower():
score += 0.2
if "evidence" in meme.content.lower():
score += 0.1
# Penalize unscientific language
if "definitely proves" in meme.content.lower():
score -= 0.3
if "always" in meme.content.lower() or "never" in meme.content.lower():
score -= 0.1
# Domain relevance
if meme.metadata.domain in ["science", "research"]:
score += 0.3
return max(0.0, min(1.0, score))
# Register custom fitness function
engine.register_fitness_function("scientific", scientific_fitness)
# Use in evolution
evolved = engine.evolve(
memes=science_memes,
fitness_function="scientific",
generations=10
)
Plugin System¶
Extend functionality with plugins:
# Create custom mutation plugin
class CreativeMutation:
def __init__(self, creativity_level=0.8):
self.creativity_level = creativity_level
def mutate(self, meme, context):
# Implement creative mutation logic
prompt = f"Creatively transform this idea: {meme.content}"
mutated_content = context.llm.generate(
prompt,
temperature=self.creativity_level
)
return meme.copy_with_content(mutated_content)
# Register plugin
engine.register_mutation_plugin("creative", CreativeMutation)
# Use in evolution
evolved = engine.evolve(
memes=base_memes,
mutation_plugins=["creative"],
generations=8
)
Batch Processing¶
Handle large-scale operations efficiently:
# Batch create memes
meme_data = [
{"content": f"Research finding #{i}", "domain": "science"}
for i in range(1000)
]
batch_memes = engine.batch_create_memes(meme_data, batch_size=100)
print(f"Created {len(batch_memes)} memes in batches")
# Batch evolution
evolution_batches = engine.batch_evolve(
meme_populations=[batch_memes[i:i+50] for i in range(0, len(batch_memes), 50)],
generations=5,
parallel_batches=4
)
# Batch analysis
analysis_results = engine.batch_analyze(
memes=all_memes,
analysis_types=["fitness", "network_position", "evolution_potential"],
batch_size=200
)
🎯 Best Practices¶
Performance Optimization¶
# Configure for optimal performance
optimal_config = {
"memory_management": {
"cache_size": 5000,
"gc_threshold": 1000,
"memory_limit": 16000
},
"parallel_processing": {
"worker_count": min(8, cpu_count()),
"batch_size": 500,
"async_operations": True
},
"network_optimization": {
"connection_pooling": True,
"request_batching": True,
"compression": True
}
}
engine.configure_performance(optimal_config)
Error Handling¶
from qmemetic_ai.exceptions import (
MemeticEvolutionError,
NetworkEntanglementError,
FederationError
)
try:
evolved_memes = engine.evolve(memes, generations=10)
except MemeticEvolutionError as e:
print(f"Evolution failed: {e}")
# Fallback to simpler evolution
evolved_memes = engine.simple_evolve(memes, generations=5)
except NetworkEntanglementError as e:
print(f"Network error: {e}")
# Continue without entanglement
evolved_memes = engine.evolve(memes, skip_entanglement=True)
except Exception as e:
print(f"Unexpected error: {e}")
# Log and recover
engine.log_error(e)
engine.restore_last_known_good_state()
Resource Management¶
# Use context managers for automatic cleanup
with MemeticEngine(license_key="your-key") as engine:
# Engine automatically initialized and cleaned up
memes = engine.create_memes(content_list)
evolved = engine.evolve(memes, generations=5)
results = engine.analyze_results(evolved)
# Engine automatically saves state and cleans up resources
# Manual resource management
engine = MemeticEngine(license_key="your-key")
try:
# Your operations here
pass
finally:
engine.cleanup() # Always cleanup
📚 Next Steps¶
Now that you understand the core usage patterns:
- CLI Reference - Command-line interface details
- Configuration - Advanced configuration options
- Theory - Deep dive into the algorithms
- API Reference - Complete API documentation
- Performance - Optimization techniques
Ready for advanced features? Check out the licensing guide for enterprise capabilities.