qtruss 0.13.0

A simple finite-element solver for trusses.
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
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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
//! Describes a 2D truss.

use std::{
    thread::Builder,
    time::Instant,
};

use raqote::*;

use maria_linalg::{
    Matrix,
    Vector,
};

use super::{
    Constraints,
    Element,
    Material,
    PlottableElement,
};

/// Width of canvas (in px) for plotting.
const CANVAS_WIDTH: i32 = 1024;

/// Height of canvas (in px) for plotting.
const CANVAS_HEIGHT: i32 = 768;

/// Maximum element thickness (in px).
const MAX_THICKNESS: f32 = 10.0;

/// Default stack size for optimization.
const DEFAULT_STACK_SIZE: usize = 4 * 1024 * 1024;

/// Finite difference for autodifferentiation.
const DX: f64 = 1E-6;

/// Maximum permitted gradient contribution.
const MAX_GRAD_CONTR: f64 = 1E+6;

#[derive(Clone, Copy, PartialEq, Debug)]
/// Enumerates the types of constraints available on
/// truss nodes.
pub enum Constraint {
    /// A free node
    Free (Vector<2>),
    /// A pinned node
    Pin,
    /// A node free to slide in the X direction, but not in the Y direction.
    HorizontalSlide (Vector<2>),
    /// A node free to slide in the Y direction, but not in the X direction.
    VerticalSlide (Vector<2>),
}

#[derive(Clone, Copy, PartialEq, Debug)]
/// A 2D truss node.
pub struct Node {
    pub location: Vector<2>,
    pub constraint: Constraint,
}

impl Node {
    /// Constructs an empty "zero" node.
    pub fn zero() -> Self {
        Self {
            location: Vector::zero(),
            constraint: Constraint::Free (Vector::zero()),
        }
    }

    /// Constructs a new node.
    pub fn new(
        location: Vector<2>,
        constraint: Constraint,
    ) -> Self {
        Self {
            location,
            constraint,
        }
    }
}

#[derive(Clone, Copy, Debug)]
/// A 2D truss with `N` nodes, `K` elements, and `F` degrees of freedom.
pub struct Truss<const N: usize, const K: usize, const F: usize> {
    nodes: [Node; N],
    pub elements: [Element; K],
    i: usize,
    pub forces: Option<Vector<F>>,
    pub displacements: Option<Vector<F>>,
}

impl<const N: usize, const K: usize, const F: usize> Truss<N, K, F> {
    pub fn new(nodes: [Node; N]) -> Self {
        Self {
            nodes,
            elements: [Element::zero(); K],
            i: 0,
            forces: None,
            displacements: None,
        }
    }

    /// Add an element to this truss and returns the index of this element.
    /// 
    /// Element indices begin at `0` and end at `K - 1`.
    pub fn add(&mut self, one: usize, two: usize) -> Option<usize> {
        // Quit if the node numbers are invalid
        if one >= N {
            println!("Invalid node number: {}", one);
            return None;
        }
        if two >= N {
            println!("Invalid node number: {}", two);
            return None;
        }

        let node_one = self.nodes[one];
        let node_two = self.nodes[two];
        self.elements[self.i] = Element::new(
            one,
            node_one.location,
            two,
            node_two.location,
        );

        let output = self.i;
        self.i += 1;

        Some (output)
    }

    /// Constructs a new sparsely connected truss, given dimensions, node counts, and constraints.
    pub fn sparse(width: f64, height: f64, x_nodes: usize, y_nodes: usize, constraints: [Constraint; N]) -> Option<Self> {
        if x_nodes * y_nodes != N {
            println!(
                "Inconsistent node count: cannot construct {}x{} mesh with {} nodes",
                x_nodes,
                y_nodes,
                N
            );
            return None;
        }

        let mut nodes = [Node::zero(); N];

        let x_spacing = width / (x_nodes - 1) as f64;
        let y_spacing = height / (y_nodes - 1) as f64;

        for j in 0..y_nodes {
            for i in 0..x_nodes {
                let x = i as f64 * x_spacing;
                let y = j as f64 * y_spacing;

                nodes[j*x_nodes + i] = Node::new(
                    [x, y].into(),
                    constraints[j*x_nodes + i],
                );
            }
        }

        let mut truss = Self::new(nodes);

        // Construct sparse mesh
        // 
        // Each node should create up to four new elements
        // Top left, top, top right, right
        for n in 0..N {
            let i = n%x_nodes;
            let j = (n - i)/x_nodes;

            // Top left
            if i > 0 && j < y_nodes - 1 {
                truss.add(n, n + x_nodes - 1);
            }

            // Top
            if j < y_nodes - 1 {
                truss.add(n, n + x_nodes);
            }

            // Top right
            if j < y_nodes - 1 && i < x_nodes - 1 {
                truss.add(n, n + x_nodes + 1);
            }

            // Right
            if i < x_nodes - 1 {
                truss.add(n, n + 1);
            }
        }

        Some (truss)
    }

    /// Constructs a new densely connected truss, given dimensions, node counts, and constraints.
    pub fn dense(width: f64, height: f64, x_nodes: usize, y_nodes: usize, constraints: [Constraint; N]) -> Option<Self> {
        if x_nodes * y_nodes != N {
            println!(
                "Inconsistent node count: cannot construct {}x{} mesh with {} nodes",
                x_nodes,
                y_nodes,
                N
            );
            return None;
        }

        let mut nodes = [Node::zero(); N];

        let x_spacing = width / (x_nodes - 1) as f64;
        let y_spacing = height / (y_nodes - 1) as f64;

        for j in 0..y_nodes {
            for i in 0..x_nodes {
                let x = i as f64 * x_spacing;
                let y = j as f64 * y_spacing;

                nodes[j*x_nodes + i] = Node::new(
                    [x, y].into(),
                    constraints[j*x_nodes + i],
                );
            }
        }

        let mut truss = Self::new(nodes);

        // Construct dense mesh
        for i in 0..N {
            for j in (i + 1)..N {
                truss.add(i, j);
            }
        }

        Some (truss)
    }

    /// Assemble the global stiffness matrix for this truss.
    /// 
    /// The global stiffness matrix has dimensions `(F, F)`.
    pub fn global_stiffness_matrix(&self, areas: [f64; K], materials: [Material; K]) -> Option<Matrix<F>> {
        // If we don't have enough elements, quit
        if self.i < K {
            return None;
        }

        // Create a new `F` by `F` matrix
        let mut matrix = Matrix::zero();

        // Assemble a list of free degrees (up to two per node)
        // `degrees[i]` represents the global indices (if they exist) at node `i`
        let mut degrees: [(Option<usize>, Option<usize>); N] = [(None, None); N];
        let mut f = 0;
        for (n, node) in self.nodes.iter().enumerate() {
            // Create an X degree of freedom, if necessary
            if matches!(node.constraint, Constraint::Free (_))
                || matches!(node.constraint, Constraint::HorizontalSlide (_))
            {
                degrees[n].0 = Some (f);
                f += 1;
            }

            // Create a Y degree of freedom, if necessary
            if matches!(node.constraint, Constraint::Free (_))
                || matches!(node.constraint, Constraint::VerticalSlide (_))
            {
                degrees[n].1 = Some (f);
                f += 1;
            }
        }

        for k in 0..K {
            let element = self.elements[k];
            let area = areas[k];
            let e = materials[k].e;

            let attached: [Option<usize>; 4] = [
                degrees[element.one].0,
                degrees[element.one].1,
                degrees[element.two].0,
                degrees[element.two].1,
            ];

            for (i, a0) in attached.iter().enumerate() {
                for (j, a1) in attached.iter().enumerate() {
                    if let Some (arow) = a0 {
                        if let Some (acol) = a1 {
                            matrix[(*arow, *acol)] += area * e * element.stiffness[(i, j)];
                        }
                    }
                }
            }
        }

        Some (matrix)
    }
    
    /// Solves this truss.
    pub fn solve(&self, areas: [f64; K], materials: [Material; K]) -> Option<(Vector<F>, Vector<F>)> {
        // Get forces applied
        let mut f = Vector::zero();
        let mut i = 0;

        for node in self.nodes {
            match node.constraint {
                Constraint::Pin => (),
                Constraint::Free (applied) => {
                    f[i] = applied[0];
                    f[i + 1] = applied[1];
                    i += 2;
                }
                Constraint::HorizontalSlide (applied) => {
                    f[i] = applied[0];
                    i += 1;
                }
                Constraint::VerticalSlide (applied) => {
                    f[i] = applied[0];
                    i += 1;
                }
            }
        }

        // Get global stiffness matrix
        let k = match self.global_stiffness_matrix(areas, materials) {
            Some (mx) => mx,
            None => {
                println!("Global stiffness matrix is singular.");
                return None;
            },
        };

        // Compute displacements
        let displacements = k.inverse().mult(f);

        Some ((f, displacements))
    }

    /// Gets the displacements of a provided node, given its index.
    pub fn displacement(&self, areas: [f64; K], materials: [Material; K], node: usize) -> Option<Vector<2>> {
        // Get global displacements
        let displacements = match self.solve(areas, materials) {
            Some ((_, d)) => d,
            None => {
                println!("Could not compute displacement of node `{}`.", node);
                return None;
            },
        };

        self.node_displacement(displacements, node)
    }

    /// Gets the displacements of a provided node, given its index.
    /// 
    /// *Note*, this requires the global displacement vector.
    fn node_displacement(&self, displacements: Vector<F>, node: usize) -> Option<Vector<2>> {
        // Start a counter
        let mut i = 0;

        // Iterate through the nodes, up to the current node index
        for k in 0..node {
            // Get the current node
            let n = self.nodes[k];

            i += match n.constraint {
                Constraint::Pin => 0,
                Constraint::Free (_) => 2,
                Constraint::HorizontalSlide (_) => 1,
                Constraint::VerticalSlide (_) => 1,
            };
        }

        let mut output: Vector<2> = Vector::zero();

        match self.nodes[node].constraint {
            // A pin doesn't move
            Constraint::Pin => return Some (output),
            
            // A free node can move in either dimension
            Constraint::Free (_) => {
                output[0] = displacements[i];
                output[1] = displacements[i + 1];
            },

            // A slider can move in only one dimension
            Constraint::HorizontalSlide (_) => output[0] = displacements[i],
            Constraint::VerticalSlide (_) => output[1] = displacements[i],
        }

        Some (output)
    }

    /// Computes the internal force in a provided element, given its index.
    pub fn internal_force(&self, areas: [f64; K], materials: [Material; K], elt: usize) -> Option<f64> {
        // Get this element
        let element = self.elements[elt];

        // Get this element's displacements
        let mut u: Vector<4> = Vector::zero();

        let left_constraint = self.nodes[element.one].constraint;
        let right_constraint = self.nodes[element.two].constraint;

        let left_displacement = match self.displacement(areas, materials, element.one) {
            Some (d) => d,
            None => {
                println!("Could not compute internal force of element `{}`.", elt);
                return None;
            },
        };
        match left_constraint {
            Constraint::Pin => {
                u[0] = 0.0;
                u[1] = 0.0;
            },
            Constraint::Free (_) => {
                u[0] = left_displacement[0];
                u[1] = left_displacement[1];
            },
            Constraint::HorizontalSlide (_) => {
                u[0] = left_displacement[0];
                u[1] = 0.0;
            },
            Constraint::VerticalSlide (_) => {
                u[0] = 0.0;
                u[1] = left_displacement[1];
            },
        }

        let right_displacement = match self.displacement(areas, materials, element.two) {
            Some (d) => d,
            None => {
                println!("Could not compute internal force of element `{}`.", elt);
                return None;
            },
        };
        match right_constraint {
            Constraint::Pin => {
                u[2] = 0.0;
                u[3] = 0.0;
            },
            Constraint::Free (_) => {
                u[2] = right_displacement[0];
                u[3] = right_displacement[1];
            },
            Constraint::HorizontalSlide (_) => {
                u[2] = right_displacement[0];
                u[3] = 0.0;
            },
            Constraint::VerticalSlide (_) => {
                u[2] = 0.0;
                u[3] = right_displacement[1];
            },
        }
        
        // Get this element's stiffness matrix
        let k = element.stiffness;

        // Get the reaction forces on this element
        let force = k.mult(u);

        // Get the internal force in this element
        // 
        // Note: for reasons of convention, we always take the last two
        // values of the reaction forces vector
        let internal = Vector::new([
            force[2],
            force[3],
        ]);

        // Get the direction of this element
        let direction = element.direction;

        // Return the internal force of this element
        Some (internal.dot(direction))
    }

    /// Computes the internal stress in a provided element.
    pub fn stress(&self, areas: [f64; K], materials: [Material; K], elt: usize) -> Option<f64> {
        let force = match self.internal_force(areas, materials, elt) {
            Some (d) => d,
            None => {
                println!("Could not compute internal stress of element `{}`.", elt);
                return None;
            },
        };
        let area = areas[elt];
        Some (force / area)
    }

    /// Computes the compliance of this truss.
    pub fn compliance(&self, areas: [f64; K], materials: [Material; K]) -> Option<f64> {
        let (forces, displacements) = match self.solve(areas, materials) {
            Some ((f, d)) => (f, d),
            None => return None,
        };

        Some (forces.dot(displacements))
    }

    /// Checks if truss materials can hold stress applied.
    pub fn check(&self, areas: [f64; K], materials: [Material; K]) -> bool {
        // Check internal stress in each element
        for k in 0..K {
            let material = materials[k];

            let stress = match self.stress(areas, materials, k) {
                Some (s) => s,
                None => return false,
            };

            // Does the element fail?
            if let Some (s) = material.minstress {
                if stress < s {
                    return false;
                }
            } else if let Some (s) = material.maxstress {
                if stress > s {
                    return false;
                }
            }
        }

        true
    }

    /// Computes fabrication complexity.
    pub fn complexity(&self, areas: [f64; K], maxarea: f64, beta: f64) -> f64 {
        let mut complexity = 0.0;

        for k in 0..K {
            let area = areas[k];

            if area < maxarea {
                complexity += 1.0 - (-beta * area).exp() + area * (-beta).exp();
            } else {
                complexity += 1.0;
            }
        }

        complexity
    }

    /// Computes the total volume of material contained in this truss.
    pub fn volume(&self, areas: [f64; K]) -> f64 {
        let mut volume = 0.0;

        for k in 0..K {
            let element = self.elements[k];
            let area = areas[k];
            volume += area * element.length;
        }

        volume
    }

    /// Computes the total mass of material contained in this truss.
    pub fn mass(&self, areas: [f64; K], materials: [Material; K]) -> f64 {
        let mut mass = 0.0;

        for k in 0..K {
            mass += areas[k] * self.elements[k].length * materials[k].density;
        }

        mass
    }

    /// Computes the *magnitude* of the maximum internal stress and the maximum area in this truss.
    /// 
    /// *Note*: the maximum stress does not necessarily correspond to the maximum area.  This function
    /// enables truss plotting.
    fn maximum(&self, areas: [f64; K], materials: [Material; K], min_area: f64) -> (f64, f64) {
        let mut max_stress: f64 = 0.0;
        let mut max_area: f64 = 0.0;

        for k in 0..K {
            if let Some (s) = self.stress(areas, materials, k) {
                if s.abs() > max_stress.abs() && areas[k] > min_area {
                    max_stress = s;
                }
            }

            if areas[k] > max_area {
                max_area = areas[k];
            }
        }

        (max_stress.abs(), max_area)
    }

    /// Returns the top-left corner and dimensions of the rectangular bounding box around the truss.
    fn bounding_box(&self) -> (f64, f64, f64, f64) {
        let mut topleft = Vector::zero();
        let mut bottomright = Vector::zero();

        let score = |vec: Vector<2>| {
            -vec[0] + vec[1]
        };

        for k in 0..K {
            let one = self.nodes[self.elements[k].one].location;
            let two = self.nodes[self.elements[k].two].location;

            if score(one) > score(topleft) {
                topleft = one;
            } else if score(two) > score(topleft) {
                topleft = two;
            }

            if score(one) < score(bottomright) {
                bottomright = one;
            } else if score(two) < score(bottomright) {
                bottomright = two;
            }
        }

        (
            topleft[1],
            topleft[0],
            bottomright[0] - topleft[0],
            topleft[1] - bottomright[1],
        )
    }

    /// Returns a list of plottable elements.
    fn make_plottable_elements(&self, areas: [f64; K], materials: [Material; K], min_plot_area: f64) -> [PlottableElement; K] {
        let mut plottable = [PlottableElement::zero(); K];

        let (top, left, width, height) = self.bounding_box();
        let (maxstress, maxarea) = self.maximum(areas, materials, min_plot_area);

        for k in 0..K {
            let stress = self.stress(areas, materials, k).unwrap_or(0.0);
            let area = if areas[k] > min_plot_area {
                areas[k]
            } else {
                0.0
            };

            plottable[k] = self.elements[k].to_plottable(
                top,
                left,
                width,
                height,
                stress,
                maxstress,
                area,
                maxarea,
            );
        }

        plottable
    }

    /// Returns a list of visualizable elements.
    fn make_visualizable_elements(&self) -> [PlottableElement; K] {
        let mut plottable = [PlottableElement::zero(); K];

        let (top, left, width, height) = self.bounding_box();

        for k in 0..K {
            plottable[k] = self.elements[k].to_plottable(
                top,
                left,
                width,
                height,
                1.0,
                1.0,
                1.0,
                1.0,
            );
        }

        plottable
    }

    /// Visualizes this truss's topology.
    /// 
    /// Note: this only displays a truss's topology.
    /// This function does not attempt to solve the truss, nor does it color elements by stress.
    pub fn visualize(&self, filename: &str) -> Option<()> {
        let elements = self.make_visualizable_elements();
    
        // Construct canvas
        let mut dt = DrawTarget::new(CANVAS_WIDTH, CANVAS_HEIGHT);

        // Construct white background
        dt.fill_rect(
            0.0,
            0.0,
            CANVAS_WIDTH as f32,
            CANVAS_HEIGHT as f32,
            &Source::Solid(SolidSource {
                r: 0xff,
                g: 0xff,
                b: 0xff,
                a: 0xff,
            }),
            &DrawOptions::new(),
        );

        for element in elements {
            let mut pb = PathBuilder::new();
            pb.move_to(CANVAS_WIDTH as f32 * element.x1, CANVAS_HEIGHT as f32 * element.y1);
            pb.line_to(CANVAS_WIDTH as f32 * element.x2, CANVAS_HEIGHT as f32 * element.y2);
            let path = pb.finish();
    
            dt.stroke(
                &path,
                &Source::Solid(SolidSource {
                    r: 0x00,
                    g: 0x00,
                    b: 0x00,
                    a: 0xff,
                }),
                &StrokeStyle {
                    cap: LineCap::Square,
                    join: LineJoin::Round,
                    width: element.thickness * MAX_THICKNESS,
                    miter_limit: 0.,
                    dash_array: Vec::new(),
                    dash_offset: 0.,
                },
                &DrawOptions::new(),
            );
        }
    
        dt.write_png(filename).ok()
    }

    /// Plots this truss.
    pub fn plot(&self, areas: [f64; K], materials: [Material; K], min_plot_area: f64, filename: &str) -> Option<()> {
        let elements = self.make_plottable_elements(areas, materials, min_plot_area);
    
        // Construct canvas
        let mut dt = DrawTarget::new(CANVAS_WIDTH, CANVAS_HEIGHT);

        // Construct white background
        dt.fill_rect(
            0.0,
            0.0,
            CANVAS_WIDTH as f32,
            CANVAS_HEIGHT as f32,
            &Source::Solid(SolidSource {
                r: 0xff,
                g: 0xff,
                b: 0xff,
                a: 0xff,
            }),
            &DrawOptions::new(),
        );

        for element in elements {
            let mut pb = PathBuilder::new();
            pb.move_to(CANVAS_WIDTH as f32 * element.x1, CANVAS_HEIGHT as f32 * element.y1);
            pb.line_to(CANVAS_WIDTH as f32 * element.x2, CANVAS_HEIGHT as f32 * element.y2);
            let path = pb.finish();

            let (r, g, b, a) = element.rgba();
    
            dt.stroke(
                &path,
                &Source::Solid(SolidSource {
                    r,
                    g,
                    b,
                    a,
                }),
                &StrokeStyle {
                    cap: LineCap::Square,
                    join: LineJoin::Round,
                    width: element.thickness * MAX_THICKNESS,
                    miter_limit: 0.,
                    dash_array: Vec::new(),
                    dash_offset: 0.,
                },
                &DrawOptions::new(),
            );
        }
    
        dt.write_png(filename).ok()
    }

    /// Numerically computes the Hessian.
    #[allow(dead_code)]
    #[deprecated]
    fn hessian(
        &self,
        areas: Vector<K>,
        materials: [Material; K],
        min_area: f64,
        max_mass: f64,
    ) -> Matrix<K> {
        let mut hessian = Matrix::zero();

        for i in 0..K {
            let vector = areas;
            let mut high = vector;
            let mut low = vector;

            high[i] += DX / 2.0;
            low[i] -= DX / 2.0;

            let f_high = self.gradient(high, materials, min_area, max_mass);
            let f_low = self.gradient(low, materials, min_area, max_mass);

            let row = (f_high - f_low).scale(1.0 / DX);

            for j in 0..K {
                hessian[(i, j)] = row[j];
            }
        }

        hessian
    }

    /// Analytically computes the gradient, accounting for barrier functions.
    fn gradient(
        &self,
        areas: Vector<K>,
        materials: [Material; K],
        min_area: f64,
        max_mass: f64,
    ) -> Vector<K> {
        let mut gradient = Vector::zero();

        let mu = 1E-4;

        let (_forces, displacements) = self.solve(areas.into(), materials).unwrap();

        for elt in 0..K {
            // Find objective gradient
            let e = materials[elt].e;
            let element = self.elements[elt];
            let k = element.stiffness.scale(e);
            let u1 = self.node_displacement(displacements, element.one).unwrap();
            let u2 = self.node_displacement(displacements, element.two).unwrap();
            let u: Vector<4> = [
                u1[0],
                u1[1],
                u2[0],
                u2[1],
            ].into();

            gradient[elt] += u.scale(-1.0).dot(k.mult(u));

            // Find area barrier gradient
            let area = areas[elt];
            gradient[elt] += - (mu / (area - min_area)).min(MAX_GRAD_CONTR);

            // Find mass barrier gradient
            let mass = self.mass(areas.into(), materials);
            let density = materials[elt].density;
            let length = self.elements[elt].length;
            gradient[elt] += (mu * density * length / (max_mass - mass)).min(MAX_GRAD_CONTR);
        }

        gradient
    }

    /// Updates element areas according to a line-search algorithm, using
    ///     the theoretical best step size as the initial guess.
    fn update(
        &self,
        areas: Vector<K>,
        materials: [Material; K],
        step: Vector<K>,
        stepsize: f64,
        min_area: f64,
        max_mass: f64,
    ) -> Vector<K> {
        let mut s = stepsize;
        let mut output = areas + step.scale(s);
        let mut mass = self.mass(output.into(), materials);

        let objective = self.compliance(
            areas.into(),
            materials,
        ).unwrap_or(f64::MAX);
        let mut new_objective = self.compliance(
            output.into(),
            materials,
        ).unwrap_or(f64::MAX);

        while !output.check(
            [Some (min_area); K],
            [None; K],
        ) || mass > max_mass
          || new_objective > objective {
            s *= 0.5;
            output = areas + step.scale(s);
            mass = self.mass(output.into(), materials);
            new_objective = self.compliance(
                output.into(),
                materials,
            ).unwrap_or(f64::MAX);
        }

        output
    }

    /// Determines the minimum-compliance areas and materials for this truss.
    /// 
    /// *Note*: this function accepts a stack size (in bytes) in order to 
    ///     avoid stack overflows for large problems.  If no stack size is
    ///     provided, it defaults to 4 MB.
    pub fn optimize(
        &self,
        materials: [Material; K],
        constraints: Constraints,
        stacksize: Option<usize>,
    ) -> [f64; K] {
        let s = stacksize.unwrap_or(DEFAULT_STACK_SIZE);

        let builder = Builder::new()
            .stack_size(s);
        let truss = *self;
        let handler = builder.spawn(move || {
            truss.optimize_truss(materials, constraints)
        }).unwrap();

        handler.join().unwrap()
    }

    /// Determines the minimum-compliance areas and materials for this truss.
    fn optimize_truss(
        &self,
        materials: [Material; K],
        constraints: Constraints,
    ) -> [f64; K] {
        // Start a timer
        let start = Instant::now();

        let mut areas: Vector<K> = [2.0 * constraints.min_area; K].into();

        let mut i = 0;

        let mut step = self.gradient(
            areas,
            materials,
            constraints.min_area,
            constraints.max_mass,
        ).scale(-1.0);

        while i < constraints.max_iter && step.norm() > constraints.criterion {
            let iterstart = Instant::now();

            areas = self.update(
                areas,
                materials,
                step,
                constraints.stepsize,
                constraints.min_area,
                constraints.max_mass,
            );
            step = self.gradient(
                areas,
                materials,
                constraints.min_area,
                constraints.max_mass,
            ).scale(-1.0);

            let objective = self.compliance(
                areas.into(),
                materials,
            ).unwrap_or(f64::NAN);

            i += 1;

            let itertime = iterstart.elapsed().as_micros() as f64 / 1000.0;

            println!("Iteration: {}", i);
            println!("Iteration time: {:.3} ms", itertime);
            println!("Step size: {}", constraints.stepsize);
            println!("Objective: {:.8}", objective);
            println!("Gradient magnitude: {:.8}", step.norm());
            println!("");
        }

        let time = start.elapsed().as_micros() as f64 / 1000.0;

        if i == constraints.max_iter {
            println!("Maximum iteration limit reached in {:.3} milliseconds", time);
        } else {
            println!("Convergence achieved in {:.3} milliseconds", time);
        }

        let compliance = self.compliance(areas.into(), materials).unwrap_or(f64::NAN);

        println!("Areas\n{}", areas);
        println!("Objective: {:.8}", compliance);

        areas.into()
    }
}

#[test]
/// Visualize a 3x3 densely connected ground structure.
fn visualize_dense() {
    let constraints = [Constraint::Free (Vector::zero()); 25];

    let truss = Truss::<25, 300, 50>::dense(
        100.0,
        100.0,
        5,
        5,
        constraints,
    ).unwrap();

    truss.visualize("dense.png");
}

#[test]
/// Visualize a 3x3 sparsely connected ground structure.
fn visualize_sparse() {
    let constraints = [Constraint::Free (Vector::zero()); 9];

    let truss = Truss::<9, 20, 18>::sparse(
        30.0,
        30.0,
        3,
        3,
        constraints,
    ).unwrap();

    truss.visualize("sparse.png");
}

#[test]
fn optimize_dense() {
    let mut constraints = [Constraint::Free (Vector::zero()); 25];
    constraints[20] = Constraint::Pin;
    constraints[0] = Constraint::VerticalSlide (Vector::zero());
    constraints[14] = Constraint::Free ([0.0, -10.0].into());

    let truss = Truss::<25, 300, 47>::dense(
        100.0,
        100.0,
        5,
        5,
        constraints,
    ).unwrap();

    let materials = [Material::new(30E+3, 1.0, None, None); 300];

    let areas = truss.optimize(
        materials,
        Constraints {
            max_mass: 300.0,
            min_area: 1E-3,
            max_iter: 4_000,
            criterion: 1E-4,
            stepsize: 2E-5,
        },
        Some (32 * 1024 * 1024),
    );
    
    truss.plot(areas.into(), materials, 0.04, "optimized.png");
}