File: phylo.rules

package info (click to toggle)
polymake 4.14-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 35,888 kB
  • sloc: cpp: 168,933; perl: 43,407; javascript: 31,575; ansic: 3,007; java: 2,654; python: 632; sh: 268; xml: 117; makefile: 61
file content (707 lines) | stat: -rw-r--r-- 26,363 bytes parent folder | download
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
#  Copyright (c) 1997-2024
#  Ewgenij Gawrilow, Michael Joswig, and the polymake team
#  Technische Universität Berlin, Germany
#  https://polymake.org
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by the
#  Free Software Foundation; either version 2, or (at your option) any
#  later version: http://www.gnu.org/licenses/gpl.txt.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#-------------------------------------------------------------------------------

sub dfs_cm {
   my ($node, $len, $tree, $visited, $ini, $Mat, $n) = @_;
   $visited -> [$node] = 1;

   if ($DebugLevel) {
      print "node = $node; len = $len; ini = $ini; visited = \n $visited \n===\n";
      print $tree -> ADJACENCY -> nodes, "+++", $tree -> ADJACENCY -> degree($node) , "\n";
   }

   if ($tree -> ADJACENCY -> degree($node) == 1 && $node != 0) {
      my $label = $tree -> LABELS -> [$node];
      my $index = 0;
      for (my $k = 0; $k < $n && $index == 0; ++$k) {
         if ($tree -> TAXA -> [$k] eq $label) {
            $index = $k;
         }
      }
      $Mat -> [$ini][$index] = $len;
      $Mat -> [$index][$ini] = $len;
   }

   my @neighbours = @{$tree -> ADJACENCY -> adjacent_nodes($node)};
   for (my $j = 0; $j < scalar @neighbours; ++$j) {
      if ($visited -> [$neighbours[$j]] == 0) {
         my $dist = $tree -> EDGE_LENGTHS -> edge($node, $neighbours[$j]);

         print "before dfs : ", $tree -> ADJACENCY -> nodes, "\n" if $DebugLevel;

         dfs_cm($neighbours[$j], $len + $dist, $tree, $visited, $ini, $Mat, $n);
      }
   }
}

sub dfs_nh {
   my ($node, $tree, $visited, $node_ht, $scal_type) = @_;
   $visited -> [$node] = 1;

   if ($tree -> ADJACENCY -> degree($node) == 1 && $node != 0) {
      $node_ht -> [$node] = 0;
      return (true, 0);
   } else {
      my $height = 0;
      my $first_check = false;
      my $first_ht = 0;
      my $is_equi = true;
      my @neighbours = @{$tree -> ADJACENCY -> adjacent_nodes($node)};
      for (my $j = 0; $j < scalar @neighbours; ++$j) {
         if ($visited -> [$neighbours[$j]] == 0) {
            my ($child_equi, $value) = dfs_nh($neighbours[$j], $tree, $visited, $node_ht, $scal_type);
            $is_equi = ($is_equi and $child_equi);
            my $edge_len = $tree -> EDGE_LENGTHS -> edge($node, $neighbours[$j]);
            if ($height < $value + $edge_len) {
               $height = $value + $edge_len;
            }

            if ($is_equi) {
               if ($first_check) {
                  if ($scal_type -> equal -> ($value + $edge_len, $first_ht) == false) {
                     $is_equi = false;
                  }
               } else {
                  $first_ht = $value + $edge_len;
                  $first_check = true;
               }
            }
         }
      }
      $node_ht -> [$node] = $height;
      return ($is_equi, $height);
   }
}

sub dfs_contract {
   my ($node, $graph, $edge_lengths, $visited, $leaf_threshold, $scal_type) = @_;
   $visited -> [$node] = 1;

   my @neighbours = @{$graph -> adjacent_nodes($node)};
   for (my $j = 0; $j < scalar @neighbours; ++$j) {
      if ($neighbours[$j] > $leaf_threshold && $visited -> [$neighbours[$j]] == 0) {
         dfs_contract($neighbours[$j], $graph, $edge_lengths, $visited, $scal_type);
         if ($scal_type -> equal -> ($edge_lengths -> edge($node, $neighbours[$j]), 0)) {
            $graph -> contract_edge($node, $neighbours[$j]);
         }
      }
   }
}

sub dfs_nw {
   my ($node, $tree, $visited, $parent) = @_;
   $visited -> [$node] = 1;

   my @neighbours = @{$tree -> ADJACENCY -> adjacent_nodes($node)};
   my $str = "";

   if (scalar @neighbours == 1) {
      $str = $str.($tree -> LABELS -> [$node]) . ":" . ($tree -> EDGE_LENGTHS -> edge($parent,$node));
   } else {
      $str = "(";
      my $not_first = 0;
      for (my $j = 0; $j < scalar @neighbours; ++$j) {
         if ($visited -> [$neighbours[$j]] == 0) {
            my $str0 = dfs_nw($neighbours[$j], $tree, $visited, $node);
            if ($not_first) {
               $str = $str.",";
            }
            $not_first = 1;
            $str = $str.$str0;
         }
      }
      $str = $str = $str.($tree -> LABELS -> [$node]) . "):" . ($tree -> EDGE_LENGTHS -> edge($parent,$node)) ;
   }

   return $str;
}

# @category Phylogenetics
# Contains a rooted phylogenetic tree (see Definition 2.2.1 from [C. Semple, M. Steel: Phylogenetics]) with edge lengths.
# Every edge must have a positive length.
# They can be defined in terms of the distance matrix and the taxa only if the distance is ultrametric; see Section 7.2 from [C. Semple, M. Steel: Phylogenetics].
# The root has always index 0.
# @tparam Scalar edge length type
declare object PhylogeneticTree<Scalar=Rational> : Graph<Undirected> {

   # The edge lengths.
   property EDGE_LENGTHS : EdgeMap<Undirected, Scalar> : construct(ADJACENCY);

   # The labels associated to the nodes.
   # @example The following prints the labels of the nodes.
   # The root is unlabeled, so an empty string is printed.
   # > $T = new PhylogeneticTree(NEWICK => "(Rabbit:5,(Rat:2,Mouse:2)Muroidea:3)Glires:5,Wolf:10;");
   # > print $T -> LABELS;
   # |  Glires Rabbit Muroidea Rat Mouse Wolf
   property LABELS : NodeMap<Undirected, String> : construct(ADJACENCY);

   # The indices of the taxa.
   property LEAVES : Map<String, Int>;

   # The distances from nodes to any of its descendant leaves.
   # @example
   # > $T = new PhylogeneticTree(NEWICK => "(Rabbit:5,(Rat:2,Mouse:2):3):5,Wolf:10;");
   # > print rows_labeled($T -> ADJACENCY);
   # | 0:1 6
   # | 1:0 2 3
   # | 2:1
   # | 3:1 4 5
   # | 4:3
   # | 5:3
   # | 6:0
   # > print $T -> EDGE_LENGTHS;
   # | 5 5 3 2 2 10
   # > print $T -> NODE_HEIGHTS;
   # | 10 5 0 2 0 0 0
   property NODE_HEIGHTS : NodeMap<Undirected, Scalar>;

   # Checks if the input tree is equidistant.
   property EQUIDISTANT: Bool;

   # The names of the taxa, i.e. the labels of the leaves.
   # @example The following prints the taxa. Note that two internal nodes are labeled; they do not count as taxa.
   # > $T = new PhylogeneticTree(NEWICK => "(Rabbit:5,(Rat:2,Mouse:2)Muroidea:3)Glires:5,Wolf:10;");
   # > print $T -> TAXA;
   # | Mouse Rabbit Rat Wolf
   property TAXA : Array<String>;

   # The number of taxa.
   # @example The following prints the number of taxa. Note that two internal nodes are labeled; they do not count as taxa.
   # > $T = new PhylogeneticTree(NEWICK => "(Rabbit:5,(Rat:2,Mouse:2)Muroidea:3)Glires:5,Wolf:10;");
   # > print $T -> N_TAXA;
   # | 4
   property N_TAXA : Int;

   # The corresponding tree distance matrix.
   # @example The following prints the cophenetic matrix. The entries correspond to alphabetically ordered taxa.
   # > $T = new PhylogeneticTree(NEWICK => "(Rabbit:5,(Rat:2,Mouse:2):3):5,Wolf:10;");
   # > print $T -> TAXA;
   # | Mouse Rabbit Rat Wolf
   # > print $T -> COPHENETIC_MATRIX;
   # | 0 10 4 20
   # | 10 0 10 20
   # | 4 10 0 20
   # | 20 20 20 0
   property COPHENETIC_MATRIX : Matrix<Scalar>;

   # A valid representation in the Newick format (see: https://evolution.genetics.washington.edu/phylip/newicktree.html).
   # @example Prints a Newick representation of a tree given by the cophenetic matrix and its list of taxa.
   # > $T0 = new PhylogeneticTree(COPHENETIC_MATRIX=>[[0,10,4,20],[10,0,10,20],[4,10,0,20],[20,20,20,0]], TAXA => ["Mouse","Rabbit","Rat","Wolf"]);
   # > print $T0 -> NEWICK;
   # | Wolf:10,(Rabbit:5,(Mouse:2,Rat:2):3):5;
   property NEWICK : String;


   rule ADJACENCY, EDGE_LENGTHS, LABELS, LEAVES : NEWICK {
      my $ga = new GraphAdjacency<Undirected>();
      my $el = new EdgeMap<Undirected, Scalar>($ga);
      my $la = new NodeMap<Undirected, String>($ga);
      my $lv = new Map<String, Int>();

      $ga -> add_node();

      my $str = $this -> NEWICK;

      my $index_semicolon = index($str, ';');
      if ($index_semicolon < 0) {
         die "Error: Invalid Newick format; semicolon not found";
      }
      $str = substr($str, 0, $index_semicolon);

      $str =~ tr/ //ds; # this eliminates the spaces from the string

      if ($str =~ /^\((.*)\)(\w+)$/) {
         $str = $1;
         $la -> [0] = $2;
      }
      else {
         if ($str =~ /^\((.*)\)$/) {
            $str = $1;
         }
      }

      my $open_bracket_count = 0;
      my @node_stack = (0); # will contain a path from the root to an internal node during parsing

      while ($str ne "") {
         if ($str =~ /^\(/) {
            ++$open_bracket_count;
            $ga -> add_node();
            push @node_stack, $ga -> nodes - 1;
            $ga -> add_edge($node_stack[-2], $node_stack[-1]);
            $str = substr $str, 1;
            next;
         }

         # an iternal node was encountered
         if ($str =~ /^\)/) {
            if ($open_bracket_count <= 0) {
               print $str, "\n" if $DebugLevel;
               die "Error: Invalid Newick format; brackets do not properly close";
            }
            --$open_bracket_count;
            $str = substr $str, 1;

            # check if it is labeled
            if ($str =~ /^(\w+)/) {
               my $label = $1;
               $la -> [$node_stack[-1]] = $label;
               $str = substr $str, length($label);
            }

            # edge length extraction
            if ($str =~ /^:\d+/) {
               # check if given in scientific notation
               if ($str =~ /^:(\d+|\d+\.\d+)e([+|-]?\d+)/) {
                  if (typeof Scalar == typeof Int) {
                     print $str, "\n" if $DebugLevel;
                     die "Error: Floating point entry for tree with integer lengths";
                  }
                  my $significand = $1;
                  my $exponent = $2;
                  $str = substr $str, 2 + length($1) + length($2);
                  if (typeof Scalar == typeof Float) {
                     my $signif = new Float($significand);
                     my $expo = new Float(10) ** (new Int($exponent));
                     my $fraction = $signif * $expo;
                     $el -> edge($node_stack[-2], $node_stack[-1]) = $fraction;
                  } else {
                     if ($significand =~ /^:\d+\.\d+/) {
                        $significand =~ /(\d+).(\d+)/;
                        my $numerator = new Rational($1);
                        my $denominator = new Rational($2);
                        my $expo = new Rational($exponent);
                        my $pow = new Rational(10) ** ( new Int(length($2)) + $expo );
                        my $fraction = ( $numerator + ($denominator / $pow) );
                        $el -> edge($node_stack[-2], $node_stack[-1]) = $fraction;
                     } else {
                        my $signif = new Rational($significand);
                        my $expo = new Rational(10) ** ( new Int($exponent) );
                        my $fraction = $signif * $expo;
                        $el -> edge($node_stack[-2], $node_stack[-1]) = $fraction;
                     }
                  }
               } elsif ($str =~ /^:(\d+\.\d+)/) {
                  if (typeof Scalar == typeof Int) {
                     print $str, "\n" if $DebugLevel;
                     die "Error: Floating point entry for tree with integer lengths";
                  }
                  my $number = $1;
                  $str = substr $str, 1 + length($number);
                  if (typeof Scalar == typeof Float) {
                     $el -> edge($node_stack[-2], $node_stack[-1]) = new Float($number);
                  } else {
                     $number =~ /(\d+).(\d+)/;
                     my $numerator = new Rational($1);
                     my $denominator = new Rational($2);
                     my $pow = new Rational(10) ** length($2);
                     my $fraction = ( $numerator + ($denominator / $pow) );
                     $el -> edge($node_stack[-2], $node_stack[-1]) = $fraction;
                  }
               } else {
                  $str =~ /^:(\d+)/;
                  my $number = $1;
                  $str = substr $str, 1 + length($number);
                  $el -> edge($node_stack[-2], $node_stack[-1]) = new Scalar($number);
               }
            } else {
               print $str, "\n" if $DebugLevel;
               die "Error: Invalid Newick format; no edge length from internal node to parent";
            }
            pop @node_stack; # the internal node was processes and removed from the path from the root
            next;
         }

         # a leaf was encountered; extract the label and the edge length
         if ($str =~ /^(\w+)/) {
            my $label = $1;
            $str = substr $str, length($label);
            $ga -> add_node();
            my $leaf_node = $ga -> nodes - 1;
            $la -> [$leaf_node] = $label;
            $lv -> {$label} = $leaf_node;

            # edge length extraction
            if ($str =~ /^:\d+/) {
               # check if given in scientific notation
               if ($str =~ /^:(\d+|\d+\.\d+)e([+|-]?\d+)/) {
                  if (typeof Scalar == typeof Int) {
                     print $str, "\n" if $DebugLevel;
                     die "Error: Floating point entry for tree with integer lengths";
                  }
                  my $significand = $1;
                  my $exponent = $2;
                  $str = substr $str, 2 + length($1) + length($2);
                  if (typeof Scalar == typeof Float) {
                     my $signif = new Float($significand);
                     my $expo = new Float(10) ** ( new Int($exponent) );
                     my $fraction = $signif * $expo;
                     $el -> edge($node_stack[-1], $leaf_node) = $fraction;
                  } else {
                     if ($significand =~ /^:\d+\.\d+/) {
                        $significand =~ /(\d+).(\d+)/;
                        my $numerator = new Rational($1);
                        my $denominator = new Rational($2);
                        my $expo = new Rational($exponent);
                        my $pow = new Rational(10) ** ( new Int(length($2)) + $expo );
                        my $fraction = ( $numerator + ($denominator / $pow) );
                        $el -> edge($node_stack[-1], $leaf_node) = $fraction;
                     } else {
                        my $signif = new Rational($significand);
                        my $expo = new Rational(10) ** ( new Int($exponent) );
                        my $fraction = $signif * $expo;
                        $el -> edge($node_stack[-1], $leaf_node) = $fraction;
                     }
                  }
               } elsif ($str =~ /^:(\d+\.\d+)/) {
                  if (typeof Scalar == typeof Int) {
                     print $str, "\n" if $DebugLevel;
                     die "Error: Floating point entry for tree with integer lengths";
                  }
                  my $number = $1;
                  $str = substr $str, 1 + length($number);
                  if (typeof Scalar == typeof Float) {
                     $el -> edge($node_stack[-1], $leaf_node) = new Float($number);
                  } else {
                     $number =~ /(\d+).(\d+)/;
                     my $numerator = new Rational($1);
                     my $denominator = new Rational($2);
                     my $pow = new Rational(10) ** length($2);
                     my $fraction = ( $numerator + ($denominator / $pow) );
                     $el -> edge($node_stack[-1], $leaf_node) = $fraction;
                  }
               } else {
                  $str =~ /^:(\d+)/;
                  my $number = $1;
                  $str = substr $str, 1 + length($number);
                  $el -> edge($node_stack[-1], $leaf_node) = new Scalar($number);
               }
             } else {
               print $str, "\n" if $DebugLevel;
               die "Error: Invalid Newick format; no edge length from leaf to parent";
            }
            next;
         }

         if ($str =~ /^,/) {
            $str = substr $str, 1;
            next;
         }

         print $str, "\n" if $DebugLevel;
         die "Error: Invalid Newick format.";
      }

      $this -> ADJACENCY = $ga;
      $this -> EDGE_LENGTHS = $el;
      $this -> LABELS = $la;
      $this -> LEAVES = $lv;
   }
   weight 1.10;

   rule TAXA : LEAVES {
      $this -> TAXA = new Array<String>(keys(%{$this -> LEAVES}));
   }
   weight 1.10;

   rule N_TAXA : TAXA {
      $this -> N_TAXA = $this -> TAXA -> size();
   }
   weight 1.10;

   rule COPHENETIC_MATRIX : ADJACENCY, EDGE_LENGTHS, TAXA, N_TAXA, LEAVES, LABELS {
      my $ntaxa = $this -> N_TAXA;
      my $mat = new Matrix<Scalar>($ntaxa, $ntaxa);

      for (my $i = 0; $i < $ntaxa; ++$i) {
         my $visited = new Vector<Int>(2 * ($this -> N_TAXA));

         # print "before dfs : ", $this -> ADJACENCY -> nodes, "\n";

         dfs_cm($this -> LEAVES -> {$this -> TAXA -> [$i]}, 0, $this, $visited, $i, $mat, $ntaxa);
      }

      $this -> COPHENETIC_MATRIX = $mat;
   }
   weight 2.10;

   rule NODE_HEIGHTS, EQUIDISTANT : ADJACENCY, EDGE_LENGTHS, N_TAXA {

      my $nh = new NodeMap<Undirected, Scalar>($this -> ADJACENCY);
      # my $is_equidistant = true;
      my $scalarType = typeof Scalar;

      my $visited = new Vector<Int>(2 * $this -> N_TAXA);
      my ($is_equidistant) = dfs_nh(0, $this, $visited, $nh, $scalarType);

      $this -> NODE_HEIGHTS = $nh;
      $this -> EQUIDISTANT = $is_equidistant;
   }
   weight 1.10;
   
   rule initial: COPHENETIC_MATRIX, TAXA {
      my $n = $this -> COPHENETIC_MATRIX -> rows;
      if ($n != $this -> COPHENETIC_MATRIX -> cols) {
         die "Error: Cophenetic matrix is not square.";
      }
      if ($n != $this -> TAXA -> size) {
         die "Error: The number of taxa does not match the matrix size.";
      }

      if ($this -> COPHENETIC_MATRIX != transpose($this -> COPHENETIC_MATRIX)) {
         die "Error: The cophenetic matrix is not symmetric.";
      }

      my $scalarType = typeof Scalar;

      for (my $i = 0; $i < $n; ++$i) {
         for (my $j = $i + 1; $j < $n; ++$j) {
            for (my $k = $j + 1; $k < $n; ++$k) {
               my $dij = $this -> COPHENETIC_MATRIX -> [$i][$j];
               my $djk = $this -> COPHENETIC_MATRIX -> [$j][$k];
               my $dki = $this -> COPHENETIC_MATRIX -> [$k][$i];
               my $minim = min($dij, min($djk, $dki));
               my $maxim = max($dij, max($djk, $dki));
               my $middl = $dij + $djk + $dki - $minim - $maxim;
               if ($scalarType -> equal -> ($maxim, $middl) == false) {
                  die "Error: The dissimilarity is not ultrametric.";
               }
            }
          }
      }
   }
   precondition : exists(COPHENETIC_MATRIX);
   precondition : exists(TAXA);
   
   rule ADJACENCY, EDGE_LENGTHS, LABELS, LEAVES, NODE_HEIGHTS: COPHENETIC_MATRIX, TAXA {
      my $n = $this -> COPHENETIC_MATRIX -> rows;
      my $scalarType = typeof Scalar;
      my $ga = new GraphAdjacency<Undirected>();
      my $el = new EdgeMap<Undirected, Scalar>($ga);
      my $la = new NodeMap<Undirected, String>($ga);
      my $lv = new Map<String, Int>();
      my $nh = new NodeMap<Undirected, Scalar>($ga);

      $ga -> add_node(); # The root has index 0

      for (my $i = 1; $i <= $n; ++$i) {
         $ga -> add_node();
         $la -> [$i] = $this -> TAXA -> [$i - 1];
         $lv -> {$this -> TAXA -> [$i - 1]} = $i;
      }

      my $repr = new Vector<Int>(2 * $n - 1);
      my $curr_cluster = new Vector<Int>(2 * $n - 1);
      for (my $i = 1; $i <= $n; ++$i) {
         $repr -> [$i] = $i - 1;
         $curr_cluster -> [$i] = 1;
      }

      for (my $counter = 1; $counter < $n - 1; ++$counter) {
         my $opt_i = 0;
         my $opt_j = 0;
         my $dist_opt = 0;
         for (my $i = 1; $i < 2 * $n - 1; ++$i) {
            if ($curr_cluster -> [$i]) {
               for (my $j = $i + 1; $j < 2 * $n - 1; ++$j) {
                  if ($curr_cluster -> [$j]) {
                     if ($opt_i == 0 && $opt_j == 0) {
                        $opt_i = $i;
                        $opt_j = $j;
                        $dist_opt = $this -> COPHENETIC_MATRIX -> [$repr -> [$i]][$repr -> [$j]];
                     } else {
                        my $dist_ij = $this -> COPHENETIC_MATRIX -> [$repr -> [$i]][$repr -> [$j]];
                        if ($dist_ij < $dist_opt) {
                           $opt_i = $i;
                           $opt_j = $j;
                           $dist_opt = $dist_ij;
                        }
                     }
                  }
               }
            }
         }
         $ga -> add_node();
         my $node = $ga -> nodes - 1;
         $repr -> [$node] = $repr -> [$opt_i];
         $ga -> add_edge($node, $opt_i);
         $ga -> add_edge($node, $opt_j);
         $curr_cluster -> [$opt_i] = 0;
         $curr_cluster -> [$opt_j] = 0;
         $curr_cluster -> [$node] = 1;
         $nh -> [$node] = $dist_opt / 2;
         $el -> edge($node, $opt_i) = $nh -> [$node] - $nh -> [$opt_i];
         $el -> edge($node, $opt_j) = $nh -> [$node] - $nh -> [$opt_j];
      }

      my $opt_i = 0;
      my $opt_j = 0;
      for (my $i = 1; $i < 2 * $n - 1; ++$i) {
         if ($curr_cluster -> [$i]) {
            if ($opt_i) {
               $opt_j = $i;
            }
            else {
               $opt_i = $i;
            }
         }
      }
      my $dist_opt = $this -> COPHENETIC_MATRIX -> [$repr -> [$opt_i]][$repr -> [$opt_j]];
      $ga -> add_edge(0, $opt_i);
      $ga -> add_edge(0, $opt_j);
      $nh -> [0] = $dist_opt / 2;
      $el -> edge(0, $opt_i) = $nh -> [0] - $nh -> [$opt_i];
      $el -> edge(0, $opt_j) = $nh -> [0] - $nh -> [$opt_j];

      my $visited = new Vector<Int>(2 * $n - 1);
      dfs_contract(0, $ga, $el, $visited, $n, $scalarType);

      $this -> ADJACENCY = $ga;
      $this -> EDGE_LENGTHS = $el;
      $this -> LABELS = $la;
      $this -> LEAVES = $lv;
      $this -> NODE_HEIGHTS = $nh;
   }
   weight 3.10;

   rule NEWICK : ADJACENCY, EDGE_LENGTHS, LABELS, N_TAXA {

      my $visited = new Vector<Int>(2 * $this -> N_TAXA - 1);
      my $str = "";

      $visited -> [0] = 1;
      my @neighbours = @{$this -> ADJACENCY -> adjacent_nodes(0)};
      for (my $j = 0; $j < scalar @neighbours; ++$j) {
         my $str0 = dfs_nw($neighbours[$j], $this, $visited, 0);
         if ($j) {
            $str = $str.",";
         }
         $str = $str.$str0;
      }
      $str = $str.";";
      $this -> NEWICK = $str;
   }
   weight 1.10;

}

sub dfs_mequi {

   my ($node, $tree, $visited, $length, $addit, $th) = @_;
   $visited -> [$node] = 1;

   # print "Enter ", $node, " *** ", $length, "\n";

   if ($tree -> ADJACENCY -> degree($node) == 1 && $node != 0) {
      $addit -> {$tree -> LABELS -> [$node]} = $th - $length;
   } else {
      my @neighbours = @{$tree -> ADJACENCY -> adjacent_nodes($node)};
      for (my $j = 0; $j < scalar @neighbours; ++$j) {
         if ($visited -> [$neighbours[$j]] == 0) {
            my $edge_len = $tree -> EDGE_LENGTHS -> edge($node, $neighbours[$j]);
            dfs_mequi($neighbours[$j], $tree, $visited, $length + $edge_len, $addit, $th);
         }
      }

   }
}

# We add extra procedures for manipulating non-equidisitant trees.
# The following function constructs an equidisitant tree from a possibly non-equidisitant input tree.
# The output tree has the same internal edge lenghts as the input tree.
function makeEquidistant<Scalar>(PhylogeneticTree<Scalar>) {

   my ($inputTree) = @_;

   if ($inputTree -> EQUIDISTANT) {
      #return new PhylogeneticTree<Scalar>(NEWICK => ($inputTree -> NEWICK));
      return $inputTree;
   }

   my $totalHeight = $inputTree -> NODE_HEIGHTS -> [0];
   my $addition = new Map<String, Scalar>();

   my $visited = new Vector<Int>(2 * $inputTree -> N_TAXA);
   dfs_mequi(0, $inputTree, $visited, new Scalar(0), $addition, $totalHeight);

   # print $addition, "\n";

   my $newCophMatrix = new Matrix<Scalar>($inputTree -> COPHENETIC_MATRIX);
   my $n = $inputTree -> N_TAXA;
   for (my   $i = 0; $i < $n; ++$i) {
      for (my $j = $i + 1; $j < $n; ++$j) {
         $newCophMatrix -> elem($i, $j) += $addition -> {$inputTree -> TAXA -> [$i]} + $addition -> {$inputTree -> TAXA -> [$j]};
         $newCophMatrix -> elem($j, $i) = $newCophMatrix -> elem($i, $j);
      }
   }

   my $outputTree = new PhylogeneticTree<Scalar>(COPHENETIC_MATRIX => $newCophMatrix, TAXA => ($inputTree -> TAXA));
   return $outputTree;
}

function makeEquidistant<Scalar>(Array<PhylogeneticTree<Scalar>>) {
   my ($tree_array) = @_;
   my @a = ();
   for (my $i = 0; $i < $tree_array -> size(); ++$i) {
      push(@a, makeEquidistant($tree_array -> [$i]));
   }
   return new Array<PhylogeneticTree<Scalar>>(@a);
}

function subtree<Scalar>(PhylogeneticTree<Scalar>, Set<Int>) {
   my ($tree, $r) = @_;
   my $coph_mat = $tree -> COPHENETIC_MATRIX -> minor($r, $r);
   my $mymap = new Map<Int, String>;
   for (my $i = 0; $i < $tree -> N_TAXA; ++$i) {
      if ($r -> contains($i)) {
         $mymap -> {$i} = $tree -> TAXA -> [$i];
      }
   }
   my $taxa = new Array<String>(values(%{$mymap}));
   my $newtree = new PhylogeneticTree<Scalar>(COPHENETIC_MATRIX => $coph_mat, TAXA => $taxa);
   return $newtree;
}

function subtree<Scalar>(Array<PhylogeneticTree<Scalar>>, Set<Int>) {
   my ($tree_array, $r) = @_;
   my @a = ();
   for (my $i = 0; $i < $tree_array -> size(); ++$i) {
      push(@a, subtree($tree_array -> [$i], $r));
   }
   return new Array<PhylogeneticTree<Scalar>>(@a);
}

function read_trees<Scalar=Rational>(String) {
   my ($filename) = @_;
   open(FH, '<', $filename) or die $!;
   my @a = ();

   while(<FH>) {
      chomp;
      my $tree = new PhylogeneticTree<Scalar>(NEWICK => $_);
      push (@a, $tree);
   }

   close(FH);

   return new Array<PhylogeneticTree<Scalar>>(@a);
}

# Local Variables:
# mode: perl
# cperl-indent-level: 3
# indent-tabs-mode:nil
# End: