-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathpathsimRunner.ts
More file actions
917 lines (789 loc) · 27.1 KB
/
Copy pathpathsimRunner.ts
File metadata and controls
917 lines (789 loc) · 27.1 KB
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
/**
* PathSim Runner
* Converts graph state to Python code and runs simulations
*/
import type { NodeInstance, Connection, SimulationSettings } from '$lib/nodes/types';
import { DEFAULT_SIMULATION_SETTINGS } from '$lib/nodes/types';
import type { EventInstance } from '$lib/events/types';
import { nodeRegistry } from '$lib/nodes/registry';
import { eventRegistry } from '$lib/events/registry';
import { NODE_TYPES } from '$lib/constants/nodeTypes';
import { BLOCK_CATEGORY_ORDER } from '$lib/constants/python';
import { isSubsystem, isInterface } from '$lib/nodes/shapes';
import { blockImportPaths } from '$lib/nodes/generated/blocks';
import { ENGINE_MODULE, enginePath } from '$lib/constants/engine';
import { generateEngineSetup } from './engineCodegen';
import { graphStore, findParentSubsystem } from '$lib/stores/graph';
import {
runStreamingSimulation,
validateGraph as validateGraphBridge,
type SimulationResult,
type ValidationResult
} from './bridge';
import {
generateParamString,
generateConnectionLines,
generateNamedConnections,
generateListDefinition,
sanitizeName
} from './codeBuilder';
// Re-export sanitizeName for external use
export { sanitizeName } from './codeBuilder';
/**
* Get setting value or fall back to default
*/
function getSettingOrDefault<K extends keyof SimulationSettings>(
settings: SimulationSettings,
key: K
): SimulationSettings[K] {
const value = settings[key];
if (value === '' || value === null || value === undefined) {
return DEFAULT_SIMULATION_SETTINGS[key];
}
return value;
}
/**
* Generate block parameter string (skips internal params starting with _)
*/
function generateBlockParams(
params: Record<string, unknown>,
validParamNames: Set<string>,
multiLine: boolean = false
): string {
return generateParamString(params, validParamNames, {
multiLine,
skipInternal: true
});
}
/**
* Generate event parameter string
*/
function generateEventParams(
params: Record<string, unknown>,
validParamNames: Set<string>,
multiLine: boolean = false
): string {
return generateParamString(params, validParamNames, { multiLine });
}
/**
* Generate event definitions and return event variable names
*/
function generateEventDefinitions(
events: EventInstance[],
existingVarNames: string[],
lines: string[],
multiLine: boolean = false
): string[] {
const eventVarNames: string[] = [];
for (const event of events) {
const typeDef = eventRegistry.get(event.type);
if (!typeDef) continue;
let varName = sanitizeName(event.name);
if (!varName || existingVarNames.includes(varName) || eventVarNames.includes(varName)) {
varName = `event_${eventVarNames.length}`;
}
eventVarNames.push(varName);
const validParamNames = new Set(typeDef.params.map(p => p.name));
const params = generateEventParams(event.params, validParamNames, multiLine);
if (params) {
lines.push(`${varName} = ${typeDef.eventClass}(${params})`);
} else {
lines.push(`${varName} = ${typeDef.eventClass}()`);
}
}
return eventVarNames;
}
/**
* Generate the Simulation constructor
*/
function generateSimulationSetup(
settings: SimulationSettings,
hasEvents: boolean,
lines: string[],
indent: string = ' '
): void {
lines.push('sim = Simulation(');
lines.push(`${indent}blocks,`);
lines.push(`${indent}connections,`);
if (hasEvents) {
lines.push(`${indent}events,`);
}
lines.push(`${indent}Solver=${getSettingOrDefault(settings, 'solver')},`);
lines.push(`${indent}dt=${getSettingOrDefault(settings, 'dt')},`);
lines.push(`${indent}dt_min=${getSettingOrDefault(settings, 'dt_min')},`);
const dtMax = getSettingOrDefault(settings, 'dt_max');
if (dtMax) {
lines.push(`${indent}dt_max=${dtMax},`);
}
lines.push(`${indent}tolerance_lte_rel=${getSettingOrDefault(settings, 'rtol')},`);
lines.push(`${indent}tolerance_lte_abs=${getSettingOrDefault(settings, 'atol')},`);
lines.push(`${indent}tolerance_fpi=${getSettingOrDefault(settings, 'ftol')},`);
lines.push(')');
}
/**
* Recursively collect all nodes including those inside subsystems
*/
function getAllNodesRecursively(nodes: NodeInstance[]): NodeInstance[] {
const allNodes: NodeInstance[] = [];
for (const node of nodes) {
allNodes.push(node);
if (isSubsystem(node)) {
allNodes.push(...getAllNodesRecursively(node.graph?.nodes ?? []));
}
}
return allNodes;
}
/**
* Collect block classes used across all nodes, grouped by Python import path.
* Excludes Subsystem/Interface (imported from pathsim directly).
*/
function collectBlockImportGroups(nodes: NodeInstance[]): Map<string, Set<string>> {
const allNodes = getAllNodesRecursively(nodes);
const groups = new Map<string, Set<string>>();
for (const node of allNodes) {
if (isSubsystem(node) || isInterface(node)) continue;
const typeDef = nodeRegistry.get(node.type);
if (!typeDef) continue;
// Toolbox-registered blocks carry their own importPath; built-ins
// fall back to the static map. Last fallback is core pathsim.blocks.
// enginePath() rewrites core pathsim paths to the active engine module
// (identity in the default pathsim build).
const importPath = enginePath(
typeDef.importPath ?? blockImportPaths[typeDef.blockClass] ?? 'pathsim.blocks'
);
if (!groups.has(importPath)) groups.set(importPath, new Set());
groups.get(importPath)!.add(typeDef.blockClass);
}
return groups;
}
/** Options for subsystem code generation */
interface SubsystemCodeOptions {
/** Use multi-line formatting with keyword arguments (for export) */
formatted?: boolean;
}
/**
* Generate code for a subsystem and its contents
* Returns the variable name for the subsystem
*/
function generateSubsystemCode(
subsystemNode: NodeInstance,
nodeVars: Map<string, string>,
varNames: string[],
lines: string[],
prefix: string = '',
options: SubsystemCodeOptions = {}
): string {
const { formatted = false } = options;
const childNodes = subsystemNode.graph?.nodes ?? [];
const childConnections = subsystemNode.graph?.connections ?? [];
const childEvents = subsystemNode.graph?.events ?? [];
// Generate subsystem variable name
let subsystemVarName = sanitizeName(subsystemNode.name);
if (!subsystemVarName || varNames.includes(subsystemVarName)) {
subsystemVarName = `subsystem_${varNames.length}`;
}
varNames.push(subsystemVarName);
nodeVars.set(subsystemNode.id, subsystemVarName);
const subPrefix = prefix + subsystemVarName + '_';
// Find Interface block(s) inside this subsystem
const interfaceNodes = childNodes.filter(isInterface);
// Generate internal blocks (excluding Interface - it's handled separately)
const internalBlocks = childNodes.filter((n) => !isInterface(n));
const internalVarNames: string[] = [];
const internalNodeVars = new Map<string, string>();
// Add section comment for formatted output
if (formatted) {
lines.push('');
lines.push(`# Subsystem: ${subsystemNode.name}`);
}
// First, generate Interface block
for (const iface of interfaceNodes) {
const ifaceVarName = subPrefix + 'interface';
internalVarNames.push(ifaceVarName);
internalNodeVars.set(iface.id, ifaceVarName);
lines.push(`${ifaceVarName} = Interface()`);
}
// Generate internal blocks
for (const node of internalBlocks) {
// Check if this is a nested subsystem
if (isSubsystem(node)) {
// Recursively generate nested subsystem
generateSubsystemCode(
node,
internalNodeVars,
internalVarNames,
lines,
subPrefix,
options
);
} else {
const typeDef = nodeRegistry.get(node.type);
if (!typeDef) continue;
let varName = subPrefix + sanitizeName(node.name);
if (!varName || internalVarNames.includes(varName)) {
varName = `${subPrefix}block_${internalVarNames.length}`;
}
internalVarNames.push(varName);
internalNodeVars.set(node.id, varName);
const validParamNames = new Set(typeDef.params.map((p) => p.name));
const params = generateBlockParams(node.params, validParamNames, formatted);
if (params) {
lines.push(`${varName} = ${typeDef.blockClass}(${params})`);
} else {
lines.push(`${varName} = ${typeDef.blockClass}()`);
}
}
}
// Propagate internal block IDs to parent nodeVars (for _node_id_map)
for (const [nodeId, varName] of internalNodeVars) {
nodeVars.set(nodeId, varName);
}
// Generate internal events (need to be defined before Subsystem constructor)
const eventVarNames: string[] = [];
if (childEvents.length > 0) {
for (const event of childEvents) {
const typeDef = eventRegistry.get(event.type);
if (!typeDef) continue;
let eventVarName = subPrefix + sanitizeName(event.name);
if (!eventVarName || varNames.includes(eventVarName) || eventVarNames.includes(eventVarName)) {
eventVarName = `${subPrefix}event_${eventVarNames.length}`;
}
eventVarNames.push(eventVarName);
const validParamNames = new Set(typeDef.params.map(p => p.name));
const params = generateEventParams(event.params, validParamNames, formatted);
if (params) {
lines.push(`${eventVarName} = ${typeDef.eventClass}(${params})`);
} else {
lines.push(`${eventVarName} = ${typeDef.eventClass}()`);
}
}
}
// Connection variables (named for mutation support)
const subConnPrefix = `${subsystemVarName}_conn`;
const subConnResult = generateNamedConnections(childConnections, internalNodeVars, subConnPrefix);
for (const line of subConnResult.lines) {
lines.push(line);
}
// Create Subsystem with inline blocks and connections using kwargs
lines.push(`${subsystemVarName} = Subsystem(`);
// Blocks list
lines.push(' blocks=[');
for (const varName of internalVarNames) {
lines.push(` ${varName},`);
}
lines.push(' ],');
// Connections list (referencing named variables)
lines.push(' connections=[');
for (const connVarName of subConnResult.varNames) {
lines.push(` ${connVarName},`);
}
lines.push(' ],');
// Events list (if any)
if (childEvents.length > 0) {
lines.push(' events=[');
for (const eventVarName of eventVarNames) {
lines.push(` ${eventVarName},`);
}
lines.push(' ],');
}
lines.push(')');
if (!formatted) {
lines.push('');
}
return subsystemVarName;
}
/**
* Group nodes by category
*/
function groupNodesByCategory(
nodes: NodeInstance[]
): Map<string, { node: NodeInstance; typeDef: ReturnType<typeof nodeRegistry.get> }[]> {
const groups = new Map<string, { node: NodeInstance; typeDef: ReturnType<typeof nodeRegistry.get> }[]>();
for (const node of nodes) {
const typeDef = nodeRegistry.get(node.type);
if (!typeDef) continue;
const category = typeDef.category || 'Other';
if (!groups.has(category)) {
groups.set(category, []);
}
groups.get(category)!.push({ node, typeDef });
}
return groups;
}
/**
* Generate Python code from graph state
* @param includeNodeIdMap - Include node ID mapping for web data extraction (default: true)
* @param includeRun - Append sim.run() call (default: true, false for streaming)
*/
/** Result of Python code generation, includes variable mappings for mutation support */
export interface CodeGenResult {
code: string;
nodeVars: Map<string, string>; // nodeId → Python variable name
connVars: Map<string, string>; // connectionId → Python variable name
}
export function generatePythonCode(
nodes: NodeInstance[],
connections: Connection[],
settings: SimulationSettings,
codeContext: string,
includeNodeIdMap: boolean = true,
events: EventInstance[] = [],
includeRun: boolean = true
): CodeGenResult {
const lines: string[] = [];
// Check if we have any subsystems
const hasSubsystems = nodes.some(isSubsystem);
// Check if we have any events
const hasEvents = events.length > 0;
const eventClasses = new Set(
events.map(e => eventRegistry.get(e.type)?.eventClass).filter(Boolean)
);
// Collect block import paths dynamically
const importGroups = collectBlockImportGroups(nodes);
// 1. Imports
lines.push('# IMPORTS');
lines.push('import numpy as np');
if (hasSubsystems) {
lines.push(`from ${ENGINE_MODULE} import Simulation, Connection, Subsystem, Interface`);
} else {
lines.push(`from ${ENGINE_MODULE} import Simulation, Connection`);
}
for (const [importPath, classes] of importGroups) {
const sorted = [...classes].sort();
if (sorted.length === 1) {
lines.push(`from ${importPath} import ${sorted[0]}`);
} else {
lines.push(`from ${importPath} import ${sorted.join(', ')}`);
}
}
// Ensure at least pathsim.blocks is imported even if no blocks
if (!importGroups.has(`${ENGINE_MODULE}.blocks`)) {
lines.push(`from ${ENGINE_MODULE}.blocks import *`);
}
lines.push(`from ${ENGINE_MODULE}.solvers import ${getSettingOrDefault(settings, 'solver')}`);
if (hasEvents) {
lines.push(`from ${ENGINE_MODULE}.events import ${[...eventClasses].join(', ')}`);
}
lines.push('');
// 1b. Engine-specific setup (e.g. fastsim port() wraps); no-op by default.
const engineSetup = generateEngineSetup(importGroups);
if (engineSetup) {
lines.push(`# ${engineSetup.header}`);
lines.push(...engineSetup.lines);
lines.push('');
}
// 2. Code context (user-defined variables/functions)
if (codeContext.trim()) {
lines.push('# CODE CONTEXT');
lines.push(codeContext.trim());
lines.push('');
}
// 3. Create blocks
lines.push('# BLOCKS');
const nodeVars = new Map<string, string>();
const varNames: string[] = [];
// First, generate subsystems (they need to be defined before being used)
const subsystemNodes = nodes.filter(isSubsystem);
for (const subsystemNode of subsystemNodes) {
generateSubsystemCode(subsystemNode, nodeVars, varNames, lines);
}
// Then generate regular blocks (excluding subsystems and interfaces)
const regularNodes = nodes.filter((n) => !isSubsystem(n) && !isInterface(n));
regularNodes.forEach((node, index) => {
const typeDef = nodeRegistry.get(node.type);
if (!typeDef) {
console.warn(`Unknown node type: ${node.type}`);
return;
}
let varName = sanitizeName(node.name);
if (!varName || varNames.includes(varName)) {
varName = `block_${index}`;
}
varNames.push(varName);
nodeVars.set(node.id, varName);
const validParamNames = new Set(typeDef.params.map(p => p.name));
const params = generateBlockParams(node.params, validParamNames);
if (params) {
lines.push(`${varName} = ${typeDef.blockClass}(${params})`);
} else {
lines.push(`${varName} = ${typeDef.blockClass}()`);
}
});
lines.push('');
lines.push(...generateListDefinition('blocks', varNames));
lines.push('');
// Create node ID mapping for data extraction (only for web simulation)
if (includeNodeIdMap) {
lines.push('# NODE ID MAPPING (for data extraction)');
lines.push('_node_id_map = {');
for (const [nodeId, varName] of nodeVars) {
// _block_key (REPL setup) uses the engine's stable block_id when
// present and falls back to id(), so static entries here stay
// consistent with the mutation-added ones in _apply_mutations.
lines.push(` _block_key(${varName}): "${nodeId}",`);
}
lines.push('}');
lines.push('');
lines.push('# NODE NAME MAPPING');
lines.push('_node_name_map = {');
const allNodes = getAllNodesRecursively(nodes);
for (const node of allNodes) {
const escapedName = node.name.replace(/"/g, '\\"');
lines.push(` "${node.id}": "${escapedName}",`);
}
lines.push('}');
lines.push('');
}
// 4. Connections (named variables for mutation support)
lines.push('# CONNECTIONS');
const connResult = generateNamedConnections(connections, nodeVars);
for (const line of connResult.lines) {
lines.push(line);
}
lines.push(...generateListDefinition('connections', connResult.varNames));
lines.push('');
// 5. Events (if any)
if (hasEvents) {
lines.push('# EVENTS');
const eventVarNames = generateEventDefinitions(events, varNames, lines);
lines.push('');
lines.push(...generateListDefinition('events', eventVarNames));
lines.push('');
}
// 6. Simulation setup
lines.push('# SIMULATION');
generateSimulationSetup(settings, hasEvents, lines);
// 7. Run simulation (omitted for streaming mode)
if (includeRun) {
lines.push('');
lines.push('# RUN');
lines.push(`sim.run(duration=${getSettingOrDefault(settings, 'duration')}, reset=True)`);
}
return { code: lines.join('\n'), nodeVars, connVars: connResult.connVars };
}
/**
* Generate well-formatted Python code for standalone export
*/
function generateFormattedPythonCode(
nodes: NodeInstance[],
connections: Connection[],
settings: SimulationSettings,
codeContext: string,
events: EventInstance[] = []
): string {
const lines: string[] = [];
const divider = '# ' + '─'.repeat(76);
const now = new Date();
const timestamp = now.toISOString().replace('T', ' ').split('.')[0];
// Header banner
lines.push('#!/usr/bin/env python3');
lines.push('# -*- coding: utf-8 -*-');
lines.push('"""');
lines.push('PathSim Simulation');
lines.push('==================');
lines.push('');
lines.push(`Generated by PathView on ${timestamp}`);
lines.push('https://view.pathsim.org');
lines.push('');
lines.push('PathSim documentation: https://docs.pathsim.org');
lines.push('"""');
lines.push('');
// Check if we have subsystems
const hasSubsystems = nodes.some(isSubsystem);
// Check if we have events
const hasEvents = events.length > 0;
const eventClasses = new Set(
events.map(e => eventRegistry.get(e.type)?.eventClass).filter(Boolean)
);
// Imports section
lines.push(divider);
lines.push('# IMPORTS');
lines.push(divider);
lines.push('');
lines.push('import numpy as np');
lines.push('import matplotlib.pyplot as plt');
lines.push('');
if (hasSubsystems) {
lines.push(`from ${ENGINE_MODULE} import Simulation, Connection, Subsystem, Interface`);
} else {
lines.push(`from ${ENGINE_MODULE} import Simulation, Connection`);
}
// Collect block classes grouped by import path
const importGroups = collectBlockImportGroups(nodes);
// Generate explicit imports for each import path
for (const [importPath, classes] of importGroups) {
const sorted = [...classes].sort();
if (sorted.length === 1) {
lines.push(`from ${importPath} import ${sorted[0]}`);
} else {
lines.push(`from ${importPath} import (`);
for (let i = 0; i < sorted.length; i++) {
const comma = i < sorted.length - 1 ? ',' : '';
lines.push(` ${sorted[i]}${comma}`);
}
lines.push(')');
}
}
lines.push(`from ${ENGINE_MODULE}.solvers import ${getSettingOrDefault(settings, 'solver')}`);
if (hasEvents) {
lines.push(`from ${ENGINE_MODULE}.events import ${[...eventClasses].join(', ')}`);
}
lines.push('');
// Engine-specific setup (e.g. fastsim port() wraps); no-op by default.
const engineSetup = generateEngineSetup(importGroups);
if (engineSetup) {
lines.push(divider);
lines.push(`# ${engineSetup.header}`);
lines.push(divider);
lines.push('');
lines.push(...engineSetup.lines);
lines.push('');
}
// Code context (user-defined variables/functions)
if (codeContext.trim()) {
lines.push(divider);
lines.push('# USER-DEFINED CODE');
lines.push(divider);
lines.push('');
lines.push(codeContext.trim());
lines.push('');
}
// Blocks section - grouped by category
lines.push(divider);
lines.push('# BLOCKS');
lines.push(divider);
const nodeVars = new Map<string, string>();
const varNames: string[] = [];
let nodeIndex = 0;
// With nested structure, input nodes are already root-level
const rootNodes = nodes;
// First, generate subsystems (they need to be defined before being used in connections)
const subsystemNodes = rootNodes.filter(isSubsystem);
for (const subsystemNode of subsystemNodes) {
generateSubsystemCode(subsystemNode, nodeVars, varNames, lines, '', { formatted: true });
}
// Then generate regular blocks (excluding subsystems and interfaces)
// Group only root-level, non-subsystem, non-interface nodes
const regularRootNodes = rootNodes.filter((n) => !isSubsystem(n) && !isInterface(n));
const regularBlocksByCategory = groupNodesByCategory(regularRootNodes);
for (const category of BLOCK_CATEGORY_ORDER) {
if (category === 'Subsystem') continue; // Already handled above
const group = regularBlocksByCategory.get(category);
if (!group || group.length === 0) continue;
lines.push('');
lines.push(`# ${category}`);
for (const { node, typeDef } of group) {
// Generate variable name
let varName = sanitizeName(node.name);
if (!varName || varNames.includes(varName)) {
varName = `block_${nodeIndex}`;
}
varNames.push(varName);
nodeVars.set(node.id, varName);
nodeIndex++;
// Get valid param names from type definition
const validParamNames = new Set(typeDef!.params.map((p) => p.name));
// Generate parameter string (multi-line for readability)
const params = generateBlockParams(node.params, validParamNames, true);
if (params) {
lines.push(`${varName} = ${typeDef!.blockClass}(${params})`);
} else {
lines.push(`${varName} = ${typeDef!.blockClass}()`);
}
}
}
// Handle any remaining categories (excluding Subsystem)
for (const [category, group] of regularBlocksByCategory) {
if (BLOCK_CATEGORY_ORDER.includes(category)) continue;
lines.push('');
lines.push(`# ${category}`);
for (const { node, typeDef } of group) {
let varName = sanitizeName(node.name);
if (!varName || varNames.includes(varName)) {
varName = `block_${nodeIndex}`;
}
varNames.push(varName);
nodeVars.set(node.id, varName);
nodeIndex++;
const validParamNames = new Set(typeDef!.params.map((p) => p.name));
const params = generateBlockParams(node.params, validParamNames, true);
if (params) {
lines.push(`${varName} = ${typeDef!.blockClass}(${params})`);
} else {
lines.push(`${varName} = ${typeDef!.blockClass}()`);
}
}
}
// Add blocks list at end of section
lines.push('');
lines.push(...generateListDefinition('blocks', varNames));
lines.push('');
// Connections section
lines.push(divider);
lines.push('# CONNECTIONS');
lines.push(divider);
lines.push('');
// Connections (named variables for mutation support)
if (connections.length === 0) {
lines.push('connections = []');
} else {
const connResult = generateNamedConnections(connections, nodeVars);
for (const line of connResult.lines) {
lines.push(line);
}
lines.push('');
lines.push(...generateListDefinition('connections', connResult.varNames));
}
lines.push('');
// Events section (if any)
if (hasEvents) {
lines.push(divider);
lines.push('# EVENTS');
lines.push(divider);
lines.push('');
const eventVarNames = generateEventDefinitions(events, varNames, lines, true);
lines.push('');
lines.push(...generateListDefinition('events', eventVarNames));
lines.push('');
}
// Simulation section
lines.push(divider);
lines.push('# SIMULATION');
lines.push(divider);
lines.push('');
generateSimulationSetup(settings, hasEvents, lines);
lines.push('');
// Main block
lines.push(divider);
lines.push('# MAIN');
lines.push(divider);
lines.push('');
lines.push("if __name__ == '__main__':");
lines.push('');
lines.push(' # Run simulation');
lines.push(` sim.run(duration=${getSettingOrDefault(settings, 'duration')})`);
lines.push('');
lines.push(' # Plot results');
lines.push(' sim.plot()');
lines.push(' plt.show()');
lines.push('');
return lines.join('\n');
}
/**
* Run streaming simulation from graph state with live updates
* @param onUpdate - Callback called for each streaming update
*/
export async function runGraphStreamingSimulation(
nodes: NodeInstance[],
connections: Connection[],
settings: SimulationSettings,
codeContext: string,
events: EventInstance[] = [],
onUpdate?: (result: SimulationResult) => void
): Promise<SimulationResult | null> {
// Generate code without sim.run() - streaming will handle execution
const result = generatePythonCode(nodes, connections, settings, codeContext, true, events, false);
const duration = getSettingOrDefault(settings, 'duration');
return runStreamingSimulation(result.code, String(duration), onUpdate, result.nodeVars, result.connVars);
}
/**
* Export graph to standalone Python script
*/
export function exportToPython(
nodes: NodeInstance[],
connections: Connection[],
settings: SimulationSettings,
codeContext: string,
events: EventInstance[] = []
): string {
return generateFormattedPythonCode(nodes, connections, settings, codeContext, events);
}
/**
* Generate Python code for a single block
* For Subsystem blocks, generates the full hierarchical code with internal blocks/connections
*/
export function generateBlockCode(
node: NodeInstance,
allNodes?: NodeInstance[],
allConnections?: Connection[]
): string {
const typeDef = nodeRegistry.get(node.type);
if (!typeDef) return '';
// Handle Interface blocks - generate parent Subsystem code instead
if (node.type === NODE_TYPES.INTERFACE) {
const rootNodes = allNodes || graphStore.getAllNodes();
const parentSubsystem = findParentSubsystem(rootNodes, node.id);
if (parentSubsystem) {
return generateBlockCode(parentSubsystem, allNodes, allConnections);
}
return '# Interface block (no parent subsystem found)';
}
const varName = sanitizeName(node.name) || 'block';
// Handle Subsystem blocks specially - generate full hierarchical code
if (node.type === NODE_TYPES.SUBSYSTEM && allNodes && allConnections) {
const lines: string[] = [];
const nodeVars = new Map<string, string>();
const varNames: string[] = [];
generateSubsystemCode(node, nodeVars, varNames, lines, '', { formatted: true });
return lines.join('\n');
}
// Regular block - simple code generation
const validParamNames = new Set(typeDef.params.map((p) => p.name));
const params = generateBlockParams(node.params, validParamNames, true);
if (params) {
return `${varName} = ${typeDef.blockClass}(${params})`;
}
return `${varName} = ${typeDef.blockClass}()`;
}
/**
* Generate Python code for a single event instance
*/
export function generateSingleEventCode(event: EventInstance): string {
const typeDef = eventRegistry.get(event.type);
if (!typeDef) return '';
const varName = sanitizeName(event.name) || 'event';
const validParamNames = new Set(typeDef.params.map((p) => p.name));
const params = generateEventParams(event.params, validParamNames, true);
if (params) {
return `${varName} = ${typeDef.eventClass}(${params})`;
}
return `${varName} = ${typeDef.eventClass}()`;
}
/**
* Extract node parameters for validation
* Returns a map of nodeId -> { paramName: paramValue }
*/
function extractNodeParams(nodes: NodeInstance[]): Record<string, Record<string, string>> {
const result: Record<string, Record<string, string>> = {};
for (const node of nodes) {
const typeDef = nodeRegistry.get(node.type);
if (!typeDef) continue;
const validParamNames = new Set(typeDef.params.map((p) => p.name));
const nodeParams: Record<string, string> = {};
for (const [name, value] of Object.entries(node.params)) {
// Skip null/undefined/empty
if (value === null || value === undefined || value === '') continue;
// Skip internal params
if (name.startsWith('_')) continue;
// Skip params not in type definition
if (!validParamNames.has(name)) continue;
nodeParams[name] = String(value);
}
if (Object.keys(nodeParams).length > 0) {
result[node.id] = nodeParams;
}
}
return result;
}
/**
* Validate graph before running simulation
* Checks code context syntax and all parameter expressions
*/
export async function validateGraphSimulation(
nodes: NodeInstance[],
codeContext: string
): Promise<ValidationResult> {
const nodeParams = extractNodeParams(nodes);
return validateGraphBridge(codeContext, nodeParams);
}
export type { ValidationResult };