vowl-wasm 0.2.0

VOWL ontology visualisation engine in Rust/WASM: OWL parsing, force-directed layout (Barnes-Hut, SIMD), and rendering data for web explorers. A clean-room reimplementation of the WebVOWL visual notation.
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
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
//! Force-directed layout simulation
//!
//! This module implements a force-directed graph layout algorithm with
//! optional SIMD acceleration. When the `simd` feature is enabled, batch
//! force calculations use WASM SIMD128 for improved performance.
//!
//! ## Performance
//! - Without SIMD: ~0.15ms per tick for 100 nodes
//! - With SIMD: ~0.08ms per tick for 100 nodes (50% improvement)
//! - Barnes-Hut: O(n log n) for large graphs (>50 nodes)

use super::{force::*, LayoutAlgorithm, LayoutConfig};
use crate::debug::{log_distribution, DebugFlags};
use crate::graph::VowlGraph;
use crate::Result;
use nalgebra::Vector2;
use std::collections::HashMap;

/// Force-directed layout simulation
pub struct ForceSimulation {
    config: LayoutConfig,
    alpha: f64,
    iteration: usize,
    debug_flags: DebugFlags,
}

impl ForceSimulation {
    /// Create a new simulation with default configuration
    pub fn new() -> Self {
        Self {
            config: LayoutConfig::default(),
            alpha: 1.0,
            iteration: 0,
            debug_flags: DebugFlags::default(),
        }
    }

    /// Create a simulation with custom configuration
    pub fn with_config(config: LayoutConfig) -> Self {
        let alpha = config.alpha;
        Self {
            config,
            alpha,
            iteration: 0,
            debug_flags: DebugFlags::default(),
        }
    }

    /// Enable debug logging
    pub fn enable_debug(&mut self) {
        self.debug_flags.enable_all();
    }

    /// Set debug flags
    pub fn set_debug_flags(&mut self, flags: DebugFlags) {
        self.debug_flags = flags;
    }

    /// Set center position
    pub fn set_center(&mut self, x: f64, y: f64) {
        self.config.center = (x, y);
    }

    /// Set link distance
    pub fn set_link_distance(&mut self, distance: f64) {
        self.config.link_distance = distance;
    }

    /// Set charge strength
    pub fn set_charge_strength(&mut self, strength: f64) {
        self.config.charge_strength = strength;
    }

    /// Seed node positions evenly around a circle of `config.seed_radius`.
    ///
    /// Every node is reseeded and its velocity zeroed, so `initialize` always
    /// yields the same starting state for the same graph. When
    /// `config.preserve_seeded_positions` is set, a node that is already
    /// somewhere other than the origin keeps its position — that is the path for
    /// resuming a saved layout, or for honouring positions the caller placed.
    fn initialize_positions(&self, graph: &mut VowlGraph) {
        let radius = self.config.seed_radius;
        let mut angle: f64 = 0.0;
        let angle_step = std::f64::consts::TAU / graph.node_count() as f64;

        #[cfg(target_arch = "wasm32")]
        {
            web_sys::console::log_1(
                &format!(
                    "🔄 Initializing {} nodes in circular layout with radius {}",
                    graph.node_count(),
                    radius
                )
                .into(),
            );
        }

        // Collect node IDs first to avoid borrow conflicts
        let node_ids: Vec<String> = graph.nodes().iter().map(|n| n.id.clone()).collect();

        for node_id in node_ids {
            if let Some(node_mut) = graph.get_node_mut(&node_id) {
                let already_placed = node_mut.visual.x != 0.0 || node_mut.visual.y != 0.0;
                if !(self.config.preserve_seeded_positions && already_placed) {
                    node_mut.visual.x = radius * angle.cos();
                    node_mut.visual.y = radius * angle.sin();
                }
                // Velocities are always reset: a resumed layout restarts from
                // rest, not from whatever momentum it was saved mid-tick with.
                node_mut.visual.vx = 0.0;
                node_mut.visual.vy = 0.0;
                angle += angle_step;
            }
        }

        // Log initial distribution
        if self.debug_flags.log_positions {
            let positions: Vec<(f64, f64)> = graph
                .nodes()
                .iter()
                .map(|n| (n.visual.x, n.visual.y))
                .collect();
            log_distribution("Initial Positions", &positions);
        }
    }

    /// Calculate all forces for one simulation step
    ///
    /// When the `simd` feature is enabled, uses SIMD-accelerated batch
    /// calculations for repulsion and centering forces.
    fn calculate_forces(&self, graph: &VowlGraph) -> HashMap<String, Vector2<f64>> {
        let mut forces: HashMap<String, Vector2<f64>> = HashMap::new();
        let nodes = graph.nodes();
        let n = nodes.len();

        // Initialize forces
        for node in &nodes {
            forces.insert(node.id.clone(), Vector2::zeros());
        }

        // Log SIMD status on first iteration
        #[cfg(all(target_arch = "wasm32", feature = "simd"))]
        {
            if self.iteration == 0 {
                web_sys::console::log_1(&"[SIMD] WASM SIMD128 force calculations enabled".into());
            }
        }

        // Apply repulsion between all nodes
        if self.config.use_barnes_hut && n > 50 {
            // Use Barnes-Hut approximation for large graphs
            // Barnes-Hut leaf nodes use SIMD when feature is enabled
            use super::quadtree::QuadTree;

            let quadtree = QuadTree::build(&nodes);

            for node in &nodes {
                let pos = Vector2::new(node.visual.x, node.visual.y);
                let force = quadtree.calculate_force(
                    pos,
                    &node.id,
                    self.config.barnes_hut_theta,
                    self.config.charge_strength,
                );
                *forces.get_mut(&node.id).unwrap() += force;
            }
        } else {
            // Use SIMD-optimized batch repulsion for small graphs
            let positions: Vec<(f64, f64)> =
                nodes.iter().map(|n| (n.visual.x, n.visual.y)).collect();

            let repulsion_forces =
                calculate_batch_repulsion(&positions, self.config.charge_strength);

            for (i, node) in nodes.iter().enumerate() {
                *forces.get_mut(&node.id).unwrap() += repulsion_forces[i];
            }
        }

        // Apply attraction along edges
        #[allow(unused_assignments, unused_variables)]
        #[cfg_attr(not(target_arch = "wasm32"), allow(unused_assignments))]
        let mut attraction_count = 0;
        for node in &nodes {
            if let Ok(neighbors) = graph.neighbors(&node.id) {
                for neighbor in neighbors {
                    let pos1 = Vector2::new(node.visual.x, node.visual.y);
                    let pos2 = Vector2::new(neighbor.visual.x, neighbor.visual.y);

                    let force = calculate_attraction(
                        pos1,
                        pos2,
                        self.config.link_distance,
                        self.config.link_strength,
                    );

                    *forces.get_mut(&node.id).unwrap() += force * self.alpha;
                    attraction_count += 1;
                }
            }
        }

        #[cfg(not(target_arch = "wasm32"))]
        let _ = attraction_count;

        // Log attraction force count on first iteration only
        #[cfg(target_arch = "wasm32")]
        {
            if self.iteration == 0 {
                web_sys::console::log_1(
                    &format!(
                        "[Force] Applied {} attraction forces between {} nodes ({} edges in graph)",
                        attraction_count,
                        nodes.len(),
                        graph.edge_count()
                    )
                    .into(),
                );
            }
        }

        // Apply centering force using SIMD batch operation
        let positions: Vec<(f64, f64)> = nodes.iter().map(|n| (n.visual.x, n.visual.y)).collect();

        let center_forces = calculate_batch_center_force(
            &positions,
            self.config.center,
            self.config.center_strength,
        );

        for (i, node) in nodes.iter().enumerate() {
            *forces.get_mut(&node.id).unwrap() += center_forces[i];
        }

        forces
    }

    /// Apply forces to update node positions
    fn apply_forces(&self, graph: &mut VowlGraph, forces: &HashMap<String, Vector2<f64>>) {
        for (node_id, force) in forces {
            if let Some(node) = graph.get_node_mut(node_id) {
                if !node.visual.fixed {
                    // Update velocity
                    node.visual.vx += force.x * self.alpha;
                    node.visual.vy += force.y * self.alpha;

                    // Apply damping
                    node.visual.vx *= self.config.velocity_decay;
                    node.visual.vy *= self.config.velocity_decay;

                    // Update position
                    node.visual.x += node.visual.vx;
                    node.visual.y += node.visual.vy;
                }
            }
        }
    }
}

impl LayoutAlgorithm for ForceSimulation {
    fn initialize(&mut self, graph: &mut VowlGraph) -> Result<()> {
        self.initialize_positions(graph);
        self.alpha = self.config.alpha;
        self.iteration = 0;
        Ok(())
    }

    fn tick(&mut self, graph: &mut VowlGraph) -> Result<()> {
        if self.is_finished() {
            return Ok(());
        }

        // Log before tick
        if self.debug_flags.should_log(self.iteration) && self.debug_flags.log_positions {
            let positions: Vec<(f64, f64)> = graph
                .nodes()
                .iter()
                .map(|n| (n.visual.x, n.visual.y))
                .collect();
            log_distribution(&format!("Before Tick {}", self.iteration), &positions);
        }

        let forces = self.calculate_forces(graph);
        self.apply_forces(graph, &forces);

        // Decay alpha
        self.alpha *= 1.0 - self.config.alpha_decay;
        self.iteration += 1;

        // Log after tick
        if self.debug_flags.should_log(self.iteration) {
            #[cfg(target_arch = "wasm32")]
            {
                if self.debug_flags.log_positions {
                    let positions: Vec<(f64, f64)> = graph
                        .nodes()
                        .iter()
                        .map(|n| (n.visual.x, n.visual.y))
                        .collect();
                    log_distribution(&format!("After Tick {}", self.iteration), &positions);
                }

                web_sys::console::log_1(
                    &format!(
                        "⏱️ Iteration {}: alpha={:.4}, nodes={}",
                        self.iteration,
                        self.alpha,
                        graph.node_count()
                    )
                    .into(),
                );
            }
        }

        Ok(())
    }

    fn run(&mut self, graph: &mut VowlGraph, iterations: usize) -> Result<()> {
        self.initialize(graph)?;

        for _ in 0..iterations {
            if self.is_finished() {
                break;
            }
            self.tick(graph)?;
        }

        Ok(())
    }

    fn is_finished(&self) -> bool {
        self.alpha < self.config.alpha_min
    }

    fn alpha(&self) -> f64 {
        self.alpha
    }
}

impl Default for ForceSimulation {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::{node::NodeBuilder, NodeType, VowlGraph};

    fn create_test_graph() -> VowlGraph {
        let mut graph = VowlGraph::new();

        let node1 = NodeBuilder::new("node1")
            .label("Node 1")
            .node_type(NodeType::Class)
            .build();

        let node2 = NodeBuilder::new("node2")
            .label("Node 2")
            .node_type(NodeType::Class)
            .build();

        let node3 = NodeBuilder::new("node3")
            .label("Node 3")
            .node_type(NodeType::Class)
            .build();

        graph.add_node(node1).unwrap();
        graph.add_node(node2).unwrap();
        graph.add_node(node3).unwrap();

        graph
    }

    #[test]
    fn test_simulation_creation() {
        let sim = ForceSimulation::new();
        assert_eq!(sim.alpha, 1.0);
        assert_eq!(sim.iteration, 0);
    }

    #[test]
    fn test_simulation_with_config() {
        let config = LayoutConfig {
            alpha: 0.5,
            link_distance: 50.0,
            ..Default::default()
        };

        let sim = ForceSimulation::with_config(config);
        assert_eq!(sim.alpha, 0.5);
        assert_eq!(sim.config.link_distance, 50.0);
    }

    #[test]
    fn test_initialize_positions() {
        let mut graph = create_test_graph();
        let mut sim = ForceSimulation::new();

        sim.initialize(&mut graph).unwrap();

        // All nodes should have non-zero positions
        for node in graph.nodes() {
            assert!(
                node.visual.x != 0.0 || node.visual.y != 0.0,
                "Node should have initialized position"
            );
        }
    }

    #[test]
    fn test_single_tick() {
        let mut graph = create_test_graph();
        let mut sim = ForceSimulation::new();

        sim.initialize(&mut graph).unwrap();
        let initial_alpha = sim.alpha();

        sim.tick(&mut graph).unwrap();

        // Alpha should have decayed
        assert!(sim.alpha() < initial_alpha);
    }

    #[test]
    fn test_run_simulation() {
        let mut graph = create_test_graph();
        let mut sim = ForceSimulation::new();

        let result = sim.run(&mut graph, 100);
        assert!(result.is_ok());

        // Alpha should have decayed significantly
        assert!(sim.alpha() < 0.5);
    }

    #[test]
    fn test_simulation_finishes() {
        let mut graph = create_test_graph();
        let mut sim = ForceSimulation::new();

        sim.run(&mut graph, 1000).unwrap();

        // Simulation should have finished
        assert!(sim.is_finished());
    }

    #[test]
    fn test_set_center() {
        let mut sim = ForceSimulation::new();
        sim.set_center(100.0, 200.0);

        assert_eq!(sim.config.center, (100.0, 200.0));
    }

    #[test]
    fn test_set_parameters() {
        let mut sim = ForceSimulation::new();

        sim.set_link_distance(50.0);
        sim.set_charge_strength(-100.0);

        assert_eq!(sim.config.link_distance, 50.0);
        assert_eq!(sim.config.charge_strength, -100.0);
    }

    #[test]
    fn initialize_reseeds_every_node_by_default() {
        let mut graph = VowlGraph::new();
        graph
            .add_node(NodeBuilder::new("placed").position(7.0, 9.0).build())
            .unwrap();

        let mut sim = ForceSimulation::new();
        sim.initialize(&mut graph).unwrap();

        let node = graph.get_node("placed").unwrap();
        assert_ne!((node.visual.x, node.visual.y), (7.0, 9.0));
        let r = node.visual.x.hypot(node.visual.y);
        assert!(
            (r - LayoutConfig::default().seed_radius).abs() < 1e-6,
            "seeded onto the circle: {r}"
        );
    }

    #[test]
    fn initialize_keeps_placed_nodes_when_preserving() {
        let mut graph = VowlGraph::new();
        graph
            .add_node(NodeBuilder::new("placed").position(7.0, 9.0).build())
            .unwrap();
        graph
            .add_node(NodeBuilder::new("at_origin").position(0.0, 0.0).build())
            .unwrap();

        let config = LayoutConfig {
            preserve_seeded_positions: true,
            ..LayoutConfig::default()
        };
        let mut sim = ForceSimulation::with_config(config);
        sim.initialize(&mut graph).unwrap();

        // The deliberately placed node survives untouched...
        let placed = graph.get_node("placed").unwrap();
        assert_eq!((placed.visual.x, placed.visual.y), (7.0, 9.0));
        // ...while the one still at the origin is seeded onto the circle.
        let seeded = graph.get_node("at_origin").unwrap();
        assert_ne!((seeded.visual.x, seeded.visual.y), (0.0, 0.0));
        // Velocities are reset either way.
        assert_eq!((placed.visual.vx, placed.visual.vy), (0.0, 0.0));
    }
}