sublinear 0.2.0

High-performance sublinear-time solver for asymmetric diagonally dominant systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
#!/usr/bin/env node

const StrangeLoop = require('strange-loops');

/**
 * Strange Loops Purposeful Agent Examples
 *
 * This demonstrates how to create nano-agents with specific purposes and behaviors.
 * Each agent operates within nanosecond budgets while collectively solving complex problems.
 */

// ============================================================================
// 1. MARKET PREDICTION AGENTS
// ============================================================================

async function createMarketPredictionSwarm() {
  console.log('📈 Creating Market Prediction Swarm...\n');

  // Initialize temporal predictor for financial data
  const predictor = await StrangeLoop.createTemporalPredictor({
    horizonNs: 50_000_000, // 50ms prediction horizon
    historySize: 1000      // Track 1000 historical data points
  });

  // Create specialized agent swarm
  const swarm = await StrangeLoop.createSwarm({
    agentCount: 5000,
    topology: 'hierarchical', // Hierarchical for decision aggregation
    tickDurationNs: 10000     // 10 microsecond budget per tick
  });

  // Define agent behaviors
  const agents = {
    // Pattern recognition agents (40% of swarm)
    patternDetectors: {
      count: 2000,
      behavior: async (data) => {
        // Each agent looks for different patterns
        const patterns = [
          'ascending_triangle',
          'head_shoulders',
          'double_bottom',
          'breakout',
          'reversal'
        ];
        return detectPattern(data, patterns);
      }
    },

    // Sentiment analysis agents (30% of swarm)
    sentimentAnalyzers: {
      count: 1500,
      behavior: async (news, social) => {
        // Analyze market sentiment from multiple sources
        return analyzeSentiment(news, social);
      }
    },

    // Risk assessment agents (20% of swarm)
    riskAssessors: {
      count: 1000,
      behavior: async (position, market) => {
        // Calculate risk metrics
        return calculateRisk(position, market);
      }
    },

    // Decision aggregators (10% of swarm)
    aggregators: {
      count: 500,
      behavior: async (signals) => {
        // Aggregate signals from other agents
        return aggregateDecisions(signals);
      }
    }
  };

  // Run prediction cycle
  const marketData = generateMarketData();

  for (let t = 0; t < 100; t++) {
    // Feed current data to predictor
    await predictor.updateHistory([marketData[t]]);

    // Get temporal prediction
    const prediction = await predictor.predict([marketData[t]]);

    // Run swarm analysis
    const swarmResult = await swarm.run(100); // 100ms analysis window

    console.log(`Time ${t}: Price=${marketData[t].toFixed(2)}, Predicted=${prediction[0].toFixed(2)}`);
  }

  return { predictor, swarm, agents };
}

// ============================================================================
// 2. DISTRIBUTED SEARCH AGENTS
// ============================================================================

async function createSearchSwarm() {
  console.log('🔍 Creating Distributed Search Swarm...\n');

  // Create mesh topology for collaborative search
  const swarm = await StrangeLoop.createSwarm({
    agentCount: 10000,
    topology: 'mesh', // Mesh for peer-to-peer communication
    tickDurationNs: 5000 // 5 microsecond budget
  });

  // Quantum-enhanced search space exploration
  const quantum = await StrangeLoop.createQuantumContainer(4); // 16 states
  await quantum.createSuperposition();

  const searchSpace = {
    dimensions: 100,
    target: generateRandomTarget(100),

    // Agent explores a quantum-influenced region
    exploreRegion: async (agentId, quantumState) => {
      const region = mapQuantumToRegion(quantumState, agentId);
      return evaluateFitness(region, searchSpace.target);
    }
  };

  // Run distributed search
  let bestSolution = null;
  let bestFitness = -Infinity;

  for (let iteration = 0; iteration < 50; iteration++) {
    // Quantum measurement influences search direction
    const quantumState = await quantum.measure();

    // Run swarm exploration
    const result = await swarm.run(1000); // 1 second search iteration

    // Simulate agent discoveries
    const agentFitness = Math.random() * 100 - 50 + iteration;

    if (agentFitness > bestFitness) {
      bestFitness = agentFitness;
      bestSolution = { iteration, fitness: agentFitness, quantumState };
      console.log(`🎯 New best solution found! Fitness: ${bestFitness.toFixed(2)}`);
    }
  }

  return { swarm, quantum, bestSolution };
}

// ============================================================================
// 3. OPTIMIZATION AGENTS
// ============================================================================

async function createOptimizationSwarm() {
  console.log('⚡ Creating Optimization Swarm...\n');

  // Create star topology with central coordinator
  const swarm = await StrangeLoop.createSwarm({
    agentCount: 3000,
    topology: 'star', // Star for centralized optimization
    tickDurationNs: 20000 // 20 microsecond budget
  });

  // Temporal consciousness for meta-learning
  const consciousness = await StrangeLoop.createTemporalConsciousness({
    maxIterations: 1000,
    integrationSteps: 100,
    enableQuantum: true
  });

  // Optimization problem: minimize complex function
  const problem = {
    dimensions: 50,
    objective: (x) => {
      // Rastrigin function (highly multimodal)
      const A = 10;
      return A * x.length + x.reduce((sum, xi) =>
        sum + xi * xi - A * Math.cos(2 * Math.PI * xi), 0
      );
    }
  };

  // Agent strategies
  const strategies = {
    explorers: {
      count: 1000,
      behavior: 'random_walk',
      temperature: 1.0
    },
    exploiters: {
      count: 1000,
      behavior: 'gradient_descent',
      learningRate: 0.01
    },
    innovators: {
      count: 1000,
      behavior: 'quantum_leap',
      quantumProbability: 0.1
    }
  };

  // Run optimization
  for (let gen = 0; gen < 100; gen++) {
    // Evolve consciousness
    const consciousnessState = await consciousness.evolveStep();

    // Adjust strategy based on consciousness index
    if (consciousnessState.consciousnessIndex > 0.8) {
      strategies.innovators.quantumProbability *= 1.5;
      console.log(`🧠 High consciousness detected! Increasing innovation.`);
    }

    // Run swarm optimization
    const result = await swarm.run(500);

    // Simulate optimization progress
    const currentBest = 1000 * Math.exp(-gen / 20) + Math.random() * 10;
    console.log(`Generation ${gen}: Best fitness = ${currentBest.toFixed(2)}`);
  }

  return { swarm, consciousness, strategies };
}

// ============================================================================
// 4. MONITORING & ALERTING AGENTS
// ============================================================================

async function createMonitoringSwarm() {
  console.log('🚨 Creating Monitoring & Alerting Swarm...\n');

  // Ring topology for sequential monitoring
  const swarm = await StrangeLoop.createSwarm({
    agentCount: 1000,
    topology: 'ring', // Ring for round-robin monitoring
    tickDurationNs: 1000 // 1 microsecond for rapid checks
  });

  // Temporal predictor for anomaly detection
  const predictor = await StrangeLoop.createTemporalPredictor({
    horizonNs: 100_000_000, // 100ms ahead
    historySize: 10000      // Large history for pattern learning
  });

  // Monitoring targets
  const monitors = {
    systemHealth: {
      agents: 250,
      metrics: ['cpu', 'memory', 'disk', 'network'],
      threshold: 0.8,
      action: 'alert'
    },
    securityThreats: {
      agents: 250,
      patterns: ['ddos', 'intrusion', 'malware', 'anomaly'],
      sensitivity: 0.95,
      action: 'isolate'
    },
    performanceBottlenecks: {
      agents: 250,
      targets: ['latency', 'throughput', 'errors', 'timeouts'],
      baseline: 'adaptive',
      action: 'scale'
    },
    dataIntegrity: {
      agents: 250,
      checks: ['consistency', 'corruption', 'drift', 'staleness'],
      frequency: 'continuous',
      action: 'repair'
    }
  };

  // Simulate monitoring cycle
  for (let cycle = 0; cycle < 1000; cycle++) {
    // Generate system metrics
    const metrics = {
      cpu: 0.5 + Math.random() * 0.5,
      memory: 0.6 + Math.random() * 0.4,
      latency: 10 + Math.random() * 90,
      errors: Math.floor(Math.random() * 10)
    };

    // Predict future state
    const prediction = await predictor.predict([
      metrics.cpu,
      metrics.memory,
      metrics.latency / 100,
      metrics.errors / 10
    ]);

    // Run monitoring swarm
    const alerts = await swarm.run(10); // 10ms monitoring window

    // Check for anomalies
    if (prediction[0] > 0.9 || metrics.errors > 5) {
      console.log(`  Alert at cycle ${cycle}: CPU prediction=${(prediction[0]*100).toFixed(1)}%, Errors=${metrics.errors}`);
    }

    // Update predictor history
    await predictor.updateHistory([
      metrics.cpu,
      metrics.memory,
      metrics.latency / 100,
      metrics.errors / 10
    ]);
  }

  return { swarm, predictor, monitors };
}

// ============================================================================
// 5. COLLABORATIVE PROBLEM-SOLVING AGENTS
// ============================================================================

async function createCollaborativeSwarm() {
  console.log('🤝 Creating Collaborative Problem-Solving Swarm...\n');

  // Create multiple swarms for different sub-problems
  const swarms = {
    analysis: await StrangeLoop.createSwarm({
      agentCount: 2000,
      topology: 'hierarchical',
      tickDurationNs: 15000
    }),

    synthesis: await StrangeLoop.createSwarm({
      agentCount: 2000,
      topology: 'mesh',
      tickDurationNs: 15000
    }),

    validation: await StrangeLoop.createSwarm({
      agentCount: 1000,
      topology: 'star',
      tickDurationNs: 10000
    })
  };

  // Quantum entanglement for instant coordination
  const quantum1 = await StrangeLoop.createQuantumContainer(3);
  const quantum2 = await StrangeLoop.createQuantumContainer(3);

  // Create entangled state
  await quantum1.createSuperposition();
  await quantum2.createSuperposition();

  // Collaborative task: Solve complex optimization with constraints
  const task = {
    objective: 'minimize_cost',
    constraints: ['budget', 'time', 'resources', 'quality'],

    phases: {
      1: 'decompose_problem',
      2: 'parallel_exploration',
      3: 'solution_synthesis',
      4: 'constraint_validation',
      5: 'consensus_building'
    }
  };

  // Run collaborative solving
  for (const [phase, description] of Object.entries(task.phases)) {
    console.log(`\nPhase ${phase}: ${description}`);

    // Quantum measurement for phase coordination
    const q1State = await quantum1.measure();
    const q2State = await quantum2.measure();

    // Different swarms handle different phases
    if (phase <= 2) {
      const result = await swarms.analysis.run(2000);
      console.log(`  Analysis swarm: ${result.totalTicks} operations`);
    } else if (phase == 3) {
      const result = await swarms.synthesis.run(2000);
      console.log(`  Synthesis swarm: ${result.totalTicks} operations`);
    } else {
      const result = await swarms.validation.run(1000);
      console.log(`  Validation swarm: ${result.totalTicks} operations`);
    }

    // Re-create superposition for next phase
    await quantum1.createSuperposition();
    await quantum2.createSuperposition();
  }

  return { swarms, quantum: [quantum1, quantum2], task };
}

// ============================================================================
// HELPER FUNCTIONS
// ============================================================================

function generateMarketData() {
  const data = [];
  let price = 100;
  for (let i = 0; i < 1000; i++) {
    price += (Math.random() - 0.5) * 2;
    price = Math.max(price, 10);
    data.push(price);
  }
  return data;
}

function generateRandomTarget(dimensions) {
  return Array(dimensions).fill(0).map(() => Math.random() * 10 - 5);
}

function mapQuantumToRegion(quantumState, agentId) {
  return {
    center: quantumState * agentId % 100,
    radius: 10
  };
}

function detectPattern(data, patterns) {
  return patterns[Math.floor(Math.random() * patterns.length)];
}

function analyzeSentiment(news, social) {
  return Math.random() * 2 - 1; // -1 to 1
}

function calculateRisk(position, market) {
  return Math.random();
}

function aggregateDecisions(signals) {
  return signals.reduce((a, b) => a + b, 0) / signals.length;
}

function evaluateFitness(region, target) {
  return -Math.abs(region.center - target[0]);
}

// ============================================================================
// MAIN EXECUTION
// ============================================================================

async function main() {
  console.log('╔══════════════════════════════════════════════════════════╗');
  console.log('║     STRANGE LOOPS: PURPOSEFUL AGENT DEMONSTRATIONS       ║');
  console.log('╚══════════════════════════════════════════════════════════╝\n');

  try {
    // Initialize Strange Loops
    await StrangeLoop.init();

    // Demonstrate each type of purposeful agent system
    const demos = [
      { name: 'Market Prediction', fn: createMarketPredictionSwarm },
      { name: 'Distributed Search', fn: createSearchSwarm },
      { name: 'Optimization', fn: createOptimizationSwarm },
      { name: 'Monitoring & Alerting', fn: createMonitoringSwarm },
      { name: 'Collaborative Problem-Solving', fn: createCollaborativeSwarm }
    ];

    for (const demo of demos) {
      console.log('\n' + '='.repeat(60));
      console.log(`Running: ${demo.name}`);
      console.log('='.repeat(60) + '\n');

      await demo.fn();

      console.log(`\n ${demo.name} demonstration completed!\n`);
    }

    console.log('\n╔══════════════════════════════════════════════════════════╗');
    console.log('║              ALL DEMONSTRATIONS COMPLETED!               ║');
    console.log('╚══════════════════════════════════════════════════════════╝\n');

  } catch (error) {
    console.error('❌ Error:', error.message);
    process.exit(1);
  }
}

// Run if executed directly
if (require.main === module) {
  main().catch(console.error);
}

// Export for use as library
module.exports = {
  createMarketPredictionSwarm,
  createSearchSwarm,
  createOptimizationSwarm,
  createMonitoringSwarm,
  createCollaborativeSwarm
};