-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathselfthin.dtx
2433 lines (2433 loc) · 85.6 KB
/
selfthin.dtx
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
%
% \iffalse
%<*driver>
\documentclass{tclldoc}
\usepackage{amsmath}
\usepackage{hyperref}
\PageIndex
\setcounter{IndexColumns}{2}
\begin{document}
\DocInput{selfthin.dtx}
\PrintIndex
\end{document}
%</driver>
% \fi
%
% \title{The \texttt{selfthin} scripts}
% \author{Lars Hellstr\"om}
% \date{2012--2017}
% \maketitle
%
%
% \begin{abstract}
% The following code performs various simple simulations of
% branch growth tempered by self-thinning. It is primarily a
% library of subroutines that can be combined to perform such
% simulations, but included are also a variety of scripts that
% demonstrate such combinations.
%
% There are furthermore utilities for exporting the simulated
% results into a variety of formats: SQLite databases, CSV files,
% Matlab tree-lists, and in particular MetaPost graphics. Not all
% of the export options have been in use throughout the development
% process, so some of them may be incomplete.
% \end{abstract}
%
% \tableofcontents
%
%
% \subsection*{Preamble}
%
% This document are Literate Programming sources in the
% \textsf{DocStrip} style (as used for most things \LaTeX). To
% generate the stripped source files expected by an interpreter, one
% typically runs \LaTeX\ on an accompanying \texttt{.ins} file, which
% copies selected modules from this file to a new file.
%
% The main module is named \textsf{pkg}. In
% Sections~\ref{Sec:database} and~\ref{Sec:figures} there are a
% number of modules (e.g.~\textsf{GUI20130122},
% \textsf{simplerun20170510}, \textsf{branchgrowfig}) that (together
% with \textsf{pkg}) produce scripts for specific runs.
% The \textsf{database} module is for storing data in a database
% (usually SQLite via TDBC interface); the alternative would be to
% output such data to CSV files.
%
%
%
% \section{Data structure}
%
% The main data structure is a standard data-tree, where nodes have
% one of the two formats
% \begin{displaysyntax}
% bud |{} {}|\par
% node \word{attr-dict} \word{child-list}
% \end{displaysyntax}
% The \word{attr-dict} is presently only used for fine details of
% data export (which nodes should be marked?). It is sort-of implied
% that there are metamers at the root ends of \texttt{node}s, but
% let's not worry about that at the moment.
%
%
% \section{Growth}
%
% The growth operation maps each \texttt{bud} to a \texttt{node} with
% $\mu$ \texttt{bud} children, and each \texttt{node} to itself
% (recursively applying the growth operation to the children,
% though). It is implemented as a data-is-code operation with call
% syntax
% \begin{displaysyntax}
% namespace inscope selfthin::grow \word{tree} \word{mu}
% \end{displaysyntax}
% \setnamespace{selfthin::grow}
% \begin{tcl}
%<*pkg>
namespace eval selfthin::grow {}
% \end{tcl}
%
% \begin{proc}{bud}
% The \texttt{bud} procedure thus has the call syntax
% \begin{displaysyntax}
% selfthin::grow::bud \word{attr} \word{dummy-children} \word{mu}
% \end{displaysyntax}
%
% \begin{tcl}
proc selfthin::grow::bud {attr children mu} {
list node $attr [lrepeat $mu {bud {} {}}]
}
% \end{tcl}
% \end{proc}
%
% \begin{proc}{node}
% The \texttt{node} procedure similarly has the call syntax
% \begin{displaysyntax}
% node \word{attr} \word{children} \word{mu}
% \end{displaysyntax}
% \begin{tcl}
proc selfthin::grow::node {attr children mu} {
set L {}
foreach child $children {lappend L [{*}$child $mu]}
return [list node $attr $L]
}
% \end{tcl}
% \end{proc}
%
%
% \subsection{Random branching growth}
%
% The following variation on the basic growth operation instead
% randomly selects the number of \texttt{bud} children for each new
% \texttt{node}, treating $\mu$ as a stochastic variable. It is
% implemented as a data-is-code operation with call syntax
% \begin{displaysyntax}
% namespace inscope selfthin::rgrow \word{tree} \word{distribution}
% \end{displaysyntax}
% where \word{distribution} is a list of real numbers that give the
% probability distribution. The first element should be |-Inf|.
% Element $k$ should be the probability that \(\mu < k\), i.e.,
% $\sum_{i=0}^{k-1} \mathrm{P}[\mu =\nobreak i]$. Only probabilities
% $<1$ need to be explicitly included in the list.
%
% \setnamespace{selfthin::rgrow}
% \begin{tcl}
namespace eval selfthin::rgrow {}
% \end{tcl}
%
% \begin{proc}{bud}
% The \texttt{bud} procedure thus has the call syntax
% \begin{displaysyntax}
% bud \word{attr} \word{dummy-children} \word{distribution}
% \end{displaysyntax}
%
% \begin{tcl}
proc selfthin::rgrow::bud {attr children distribution} {
list node $attr [lrepeat [
lsearch -real -sorted -bisect $distribution [expr {rand()}]
] {bud {} {}}]
}
% \end{tcl}
% \end{proc}
%
% \begin{proc}{node}
% The \texttt{node} procedure similarly has the call syntax
% \begin{displaysyntax}
% node \word{attr} \word{children} \word{distribution}
% \end{displaysyntax}
% \begin{tcl}
proc selfthin::rgrow::node {attr children distribution} {
set L {}
foreach child $children {lappend L [{*}$child $distribution]}
return [list node $attr $L]
}
% \end{tcl}
% \end{proc}
%
%
% \subsection{Growth with identity}
%
% Another variation on the basic growth operation is to equip each
% \texttt{node} and \texttt{bud} with an identity, to allow tracing
% them as the tree ages. The call syntax is simply
% \begin{displaysyntax}
% namespace inscope selfthin::igrow \word{tree} \word{mu}
% \end{displaysyntax}
% \setnamespace{selfthin::igrow}
% which returns the grown \word{tree}. What happens is that each new
% |bud| gets an \texttt{id} attribute obtained by |lappend|ing its
% position index to the \texttt{id} attribute of the parent (that
% transforms into a |node|).
%
% \setnamespace{selfthin::igrow}
% \begin{tcl}
namespace eval selfthin::igrow {}
% \end{tcl}
%
% \begin{proc}{bud}
% The \texttt{bud} procedure thus has the call syntax
% \begin{displaysyntax}
% bud \word{attr} \word{dummy-children} \word{mu}
% \end{displaysyntax}
% This works by copying all attributes from parent to children,
% modifying only the \texttt{id} one (which is usually the only one
% there is).
% \begin{tcl}
proc selfthin::igrow::bud {attr children mu} {
set children {}
while {[llength $children] < $mu} {
set cattr $attr
dict lappend cattr id [llength $children]
lappend children [list bud $cattr {}]
}
return [list node $attr $children]
}
% \end{tcl}
% \end{proc}
%
% \begin{proc}{node}
% The \texttt{node} procedure similarly has the call syntax
% \begin{displaysyntax}
% node \word{attr} \word{children} \word{mu}
% \end{displaysyntax}
% \begin{tcl}
proc selfthin::igrow::node {attr children mu} {
set L {}
foreach child $children {lappend L [{*}$child $mu]}
return [list node $attr $L]
}
% \end{tcl}
% \end{proc}
%
%
%
% \section{Counting}
%
% The \texttt{histogram} operation returns a list of counts of items
% at different distances from the root in the tree. The call syntax is
% \begin{displaysyntax}
% namespace inscope selfthin::histogram \word{tree}
% \end{displaysyntax}
%
% \begin{tcl}
namespace eval selfthin::histogram {}
% \end{tcl}
% \setnamespace{selfthin::histogram}
%
% \begin{proc}{bud}
% A \texttt{bud} has no children, so the return value is the list
% of $1$.
% \begin{tcl}
proc selfthin::histogram::bud {attr children} {list 1}
% \end{tcl}
% \end{proc}
%
% \begin{proc}{node}
% A \texttt{node} goes through its children, sums the lists up, and
% then prepends a $1$ for itself.
% \begin{tcl}
proc selfthin::histogram::node {attr children} {
if {![llength $children]} then {return [list 1]}
set sum [{*}[lindex $children 0]]
foreach child [lrange $children 1 end] {
set term [{*}$child]
while {[llength $term] < [llength $sum]} {lappend term 0}
while {[llength $term] > [llength $sum]} {lappend sum 0}
set newsum {}
foreach a $sum b $term {lappend newsum [expr {$a+$b}]}
set sum $newsum
}
return [list 1 {*}$sum]
}
% \end{tcl}
% \end{proc}
%
%
% The \texttt{harvest} operation returns a list of all subtrees at a
% given height. The call syntax is
% \begin{displaysyntax}
% namespace inscope selfthin::harvest \word{tree} \word{height}
% \end{displaysyntax}
% where \(\mathit{height} = 0\) corresponds to returning the
% (one-element list whose only element is the) \word{tree}.
%
% \begin{tcl}
namespace eval selfthin::harvest {}
% \end{tcl}
% \setnamespace{selfthin::harvest}
%
% \begin{proc}{node}
% The main case is that of cutting at a node. This is most
% efficient at \(\mathit{height} = 1\), but \(\mathit{height} =
% 0\) must also be supported. For \(\mathit{height} > 1\), there is
% a straightforward recursion.
%
% \begin{tcl}
proc selfthin::harvest::node {attr children height} {
if {$height == 1} then {
return $children
} elseif {$height > 1} then {
incr height -1
set res {}
foreach child $children {
lappend res {*}[{*}$child $height]
}
return $res
} else {
return [list [list node $attr $children]]
}
}
% \end{tcl}
% \end{proc}
%
%
% \begin{proc}{bud}
% A \texttt{bud} has no children, so only the \(\mathit{height} =
% 0\) case can return anything nonempty.
% \begin{tcl}
proc selfthin::harvest::bud {attr children height} {
if {$height == 0} then {
return [list {bud {} {}}]
} else {
return {}
}
}
% \end{tcl}
% \end{proc}
%
%
% \subsection{Work with identities}
%
% The |identities| operation returns the flat list of all
% \texttt{id}s found in a tree. The call syntax is
% \begin{displaysyntax}
% selfthin::identities \word{tree}
% \end{displaysyntax}
% Since this treats all node types equally, it does not need to be a
% data-is-code operation.
%
% \setnamespace{selfthin}
%
% \begin{proc}{identities}
% It is however highly recursive.
% \begin{tcl}
proc selfthin::identities {tree} {
set res {}
foreach child [lindex $tree 2] {
lappend res {*}[identities $child]
}
if {[dict exists [lindex $tree 1] id]} then {
lappend res [dict get [lindex $tree 1] id]
}
return $res
}
% \end{tcl}
% \end{proc}
%
% \begin{proc}{aritybyid}
% The |aritybyid| procedure is similar, but returns a dictionary
% mapping |id| to arity of the node is question. The idea is that
% this allows for restricting to branching points.
% \begin{tcl}
proc selfthin::aritybyid {tree} {
set call [list ::dict merge]
foreach child [lindex $tree 2] {
lappend call [aritybyid $child]
}
if {[dict exists [lindex $tree 1] id]} then {
lappend call [dict create [dict get [lindex $tree 1] id]\
[llength [lindex $tree 2]]]
}
return [{*}$call]
}
% \end{tcl}
% \end{proc}
%
% \begin{proc}{markwhere}
% This procedure sets an attribute on all |node|s and |bud|s in a
% tree where the value of an(other) attribute passes a custom test.
% The call syntax is
% \begin{displaysyntax}
% selfthin::markwhere \word{tree} \word{select-attr}
% \word{select-prefix} \word{set-attr} \word{set-value}
% \end{displaysyntax}
% and the return value is a modified \word{tree}. The
% \word{select-prefix} is a command prefix with the syntax
% \begin{displaysyntax}
% \meta{select-prefix} \word{value}
% \end{displaysyntax}
% that returns a boolean, where \word{value} is the value of the
% \word{select-attr} in the attribute dictionary of a node. If the
% \meta{select-prefix} call returns true, then node attributes are
% modified by setting the \word{set-attr} attribute to
% \word{set-value}.
%
% To set up a set membership test, encode the set as a dictionary
% and use |dict exists |\word{set} as \meta{select-prefix}.
%
% This, too, is highly recursive.
% \begin{tcl}
proc selfthin::markwhere {tree selname selprefix setname setval} {
foreach {type attrD children} $tree {break}
if {[dict exists $attrD $selname] && [
{*}$selprefix [dict get $attrD $selname]
]} then {
dict set attrD $setname $setval
}
return [list $type $attrD [lmap child $children {
markwhere $child $selname $selprefix $setname $setval
}]]
}
% \end{tcl}
% \end{proc}
%
%
%
% \section{Thinning}
%
% \subsection{Deterministic thinning}
%
% The \texttt{up1d} operation performs thinning of a tree by thinning
% subtrees that exceed a size bound. The thinning is performed by
% dropping a branch, not one at the node in which the size bound
% violation is detected, but at the next branching above---hence the
% \texttt{up1}. The \texttt{d} is because the thinning is
% deterministic rather than pseudorandom, although the rule (as
% explained below) is somewhat arbitrary.
%
% The call syntax is
% \begin{displaysyntax}
% namespace inscope selfthin::up1d \word{tree} \word{limits-list}
% \word{limits-index} \word{seed}
% \end{displaysyntax}
% and the return value is a list
% \begin{displaysyntax}
% \word{thinned tree} \word{bud-counts-list}
% \end{displaysyntax}
% As a transformation on the \word{tree}, the result is the
% \word{thinned tree}. The \word{bud-counts-list} is a list, with one
% element for each child of the first \texttt{node} that is a
% branching point, of how many \texttt{bud}s the respective child
% tree contains. If there is no branching anywhere, then the
% \word{bud-counts-list} has one element.
%
% The \word{limits-list} is a list of limits on the number of buds
% a subtree can have without being subjected to thinning. The
% \word{limits-index} is the index of the position in the list that
% is relevant for the root of the \word{tree}; this is decremented by
% $1$ in each recursive call. No thinning happens if the
% \word{limits-index} is negative. The \word{seed} is an integer
% which is subjected to modulo operations to choose which subbranch
% to prune; the same \word{seed} value is used in recursive calls.
% \begin{tcl}
namespace eval selfthin::up1d {}
% \end{tcl}
% \setnamespace{selfthin::up1d}
%
% \begin{proc}{bud}
% Buds have no branching, and are one bud.
% \begin{tcl}
proc selfthin::up1d::bud {attr children limitsL limitsIdx seed} {
list {bud {} {}} [list 1]
}
% \end{tcl}
% \end{proc}
%
% \begin{proc}{node}
% For a \texttt{node}, the first order of business is to
% recursively apply the operation to all children.
% \begin{tcl}
proc selfthin::up1d::node {attr children limitsL limitsidx seed} {
set childL {}
set coundsL {}
set nextidx [expr {$limitsidx-1}]
foreach child $children {
set res [{*}$child $limitsL $nextidx $seed]
lappend childL [lindex $res 0]
lappend countsL [lindex $res 1]
}
% \end{tcl}
% Next check if there is pruning to do. The check (and thus the
% pruning) is skipped if there is only one child, since in that
% case something in that child should have already checked a
% tighter limit.
% \begin{tcl}
if {[llength $childL] > 1 && $limitsidx>=0 &&\
[::tcl::mathop::+ {*}[concat {*}$countsL]] >\
[lindex $limitsL $limitsidx]} then {
% \end{tcl}
% $i$ is the index of the child that will be subjected to pruning.
% If there is no branch point in that subtree, then the whole child
% is dropped.
% \begin{tcl}
set i [expr {$seed % [llength $childL]}]
if {[llength [lindex $countsL $i]] <= 1} then {
set childL [lreplace $childL $i $i]
set countsL [lreplace $countsL $i $i]
} else {
% \end{tcl}
% Otherwise one branch (with index $j$) of the child is pruned. This
% branch may sit several levels down in the recursion, so |pruneIL|
% is constructed to hold the list of indices that will address the
% right list of children.
% \begin{tcl}
set pruneIL [list $i 2]
set subchildL [lindex $childL $pruneIL]
while {[llength $subchildL] == 1} {
lappend pruneIL 0 2
set subchildL [lindex $subchildL 0 2]
}
set j [expr {($seed / [llength $childL]) %\
[llength $subchildL]}]
lset childL $pruneIL [lreplace $subchildL $j $j]
lset countsL $i [lreplace [lindex $countsL $i] $j $j]
}
}
% \end{tcl}
% Now we are ready to return the result. If there is only one child
% left, then use the list of counts for that. Otherwise add up the
% count lists for each child.
% \begin{tcl}
if {[llength $childL] == 1} then {
set newcounts [lindex $countsL 0]
} else {
set newcounts {}
foreach L $countsL {
lappend newcounts [::tcl::mathop::+ {*}$L]
}
}
% \end{tcl}
% And return the result.
% \begin{tcl}
return [list [list node $attr $childL] $newcounts]
}
% \end{tcl}
% \end{proc}
%
%
% \subsection{Mildly stochastic thinning}
%
% The \texttt{up1r} operation is similar to the \texttt{up1d}
% operation in that it performs thinning of a tree by thinning
% subtrees that exceed a size bound, but it adds some randomness to
% the process, to give it more the appearance of a simulation.
%
% The thinning is again performed by dropping a branch, not one at the
% node in which the size bound violation is detected, but at the next
% branching above---hence the \texttt{up1}. The \texttt{r} is of
% course for being random, although the randomness source (the
% \texttt{rand} function) is not of particularly high quality. There
% are two things that are subject to randomness:
% \begin{itemize}
% \item
% The choice of which branch to drop is random. The algorithm is
% a simple multiply uniform random $\mathopen{]}0,1\mathclose{[}$
% by number-of-choices and truncate to produce target index.
% \item
% There is also a certain probability $p$ for ignoring a size bound
% violation. Linus suggested this, and it is extremely easy to
% implement, so why not?
% \end{itemize}
%
%
% The recommended calling syntax is
% \begin{displaysyntax}
% selfthin::up1r \word{tree} \word{limits-list}
% \word{limits-index} \word{ignore-probability}
% \end{displaysyntax}
% which returns a self-thinned form of the \word{tree}. The
% \word{limits-list} is the list of those sizes which will trigger
% dropping of some subbranch when exceeded, and the
% \word{limits-index} is the index into this list which applies for
% the root of the \word{tree}; this will then be decremented by $1$
% for each \texttt{node} the operation recurses into. The
% \word{ignore-probability} is the probability (\(p \in [0,1]\)) that
% no subbranch is dropped even after a size violation
% has been detected, at one node, and this time the call is made.
%
% There is also a more bare data-is-code operation, for which the call
% syntax is
% \begin{displaysyntax}
% namespace inscope selfthin::up1r \word{tree} \word{limits-list}
% \word{limits-index} \word{ignore-probability}
% \end{displaysyntax}
% and the return value is a pair
% \begin{displaysyntax}
% \word{thinned tree} \word{bud-counts-list}
% \end{displaysyntax}
% As a transformation on the \word{tree}, the result is the
% \word{thinned tree}. The \word{bud-counts-list} is a list, with one
% element for each child of the first \texttt{node} that is a
% branching point, of how many \texttt{bud}s the respective child
% tree contains. If there is no branching anywhere, then the
% \word{bud-counts-list} has one element.
%
% \begin{tcl}
namespace eval selfthin::up1r {}
% \end{tcl}
% \setnamespace{selfthin::up1r}
%
% \begin{proc}{bud}
% Buds have no branching, and are one bud.
% \begin{tcl}
proc selfthin::up1r::bud {attr children limitsL limitsIdx p} {
list {bud {} {}} [list 1]
}
% \end{tcl}
% \end{proc}
%
% \begin{proc}{node}
% For a \texttt{node}, the first order of business is to
% recursively apply the operation to all children.
% \begin{tcl}
proc selfthin::up1r::node {attr children limitsL limitsidx p} {
set childL {}
set coundsL {}
set nextidx [expr {$limitsidx-1}]
foreach child $children {
set res [{*}$child $limitsL $nextidx $p]
lappend childL [lindex $res 0]
lappend countsL [lindex $res 1]
}
% \end{tcl}
% Next check if there is pruning to do. The check (and thus the
% pruning) is skipped if there is only one child, since in that
% case something in that child should have already checked a
% tighter limit.
% \begin{tcl}
if {[llength $childL] > 1 && $limitsidx>=0 &&\
[::tcl::mathop::+ {*}[concat {*}$countsL]] >\
[lindex $limitsL $limitsidx] && rand()>=$p} then {
% \end{tcl}
% $i$ is the index of the child that will be subjected to pruning.
% If there is no branch point in that subtree, then the whole child
% is dropped.
% \begin{tcl}
set i [expr {int(rand()*[llength $childL])}]
if {[llength [lindex $countsL $i]] <= 1} then {
set childL [lreplace $childL $i $i]
set countsL [lreplace $countsL $i $i]
} else {
% \end{tcl}
% Otherwise one branch (with index $j$) of the child is pruned. This
% branch may sit several levels down in the recursion, so |pruneIL|
% is constructed to hold the list of indices that will address the
% right list of children.
% \begin{tcl}
set pruneIL [list $i 2]
set subchildL [lindex $childL $pruneIL]
while {[llength $subchildL] == 1} {
lappend pruneIL 0 2
set subchildL [lindex $subchildL 0 2]
}
set j [expr {int(rand()*[llength $subchildL])}]
lset childL $pruneIL [lreplace $subchildL $j $j]
lset countsL $i [lreplace [lindex $countsL $i] $j $j]
}
}
% \end{tcl}
% Now we are ready to return the result. If there is only one child
% left, then use the list of counts for that. Otherwise add up the
% count lists for each child.
% \begin{tcl}
if {[llength $childL] == 1} then {
set newcounts [lindex $countsL 0]
} else {
set newcounts {}
foreach L $countsL {
lappend newcounts [::tcl::mathop::+ {*}$L]
}
}
% \end{tcl}
% And return the result.
% \begin{tcl}
return [list [list node $attr $childL] $newcounts]
}
% \end{tcl}
% \end{proc}
%
%
% \setnamespace{selfthin}
%
% \begin{proc}{up1r}
% The top-level |up1r| procedure has as one task to strip off the
% \word{bud-counts-list} returned by the bare operation, but it
% also performs an extra self-thinning step just like
% \texttt{node}, to ensure that every \texttt{node} may lose a
% branch.
%
% \begin{tcl}
proc selfthin::up1r {tree limitsL limitsidx p} {
foreach {tree counts} [
namespace inscope up1r $tree $limitsL $limitsidx $p
] break
% \end{tcl}
% Next check if there is pruning to do. The check for having
% multiple children is dropped, or perhaps rather replaced with a
% check that there is a branch point somewhere in the tree.
% \begin{tcl}
if {$limitsidx>=0 && rand()>=$p && [llength $counts]>1 &&\
[::tcl::mathop::+ {*}$counts] > [lindex $limitsL $limitsidx]} then {
% \end{tcl}
% Otherwise one branch (with index $j$) of the child is pruned. This
% branch may sit several levels down in the recursion, so |pruneIL|
% is constructed to hold the list of indices that will address the
% right list of children.
% \begin{tcl}
set pruneIL [list 2]
set subchildL [lindex $tree $pruneIL]
while {[llength $subchildL] == 1} {
lappend pruneIL 0 2
set subchildL [lindex $subchildL 0 2]
}
set j [expr {int(rand()*[llength $subchildL])}]
lset tree $pruneIL [lreplace $subchildL $j $j]
}
return $tree
}
% \end{tcl}
% \end{proc}
%
% Simulations indicate that the root rule applied by |up1r| does not
% match the general node rule of |up1r::node|---the root rule leads
% on average to a tree whose first branch point comes quite early
% (within the first four levels on a tree of height $100$), followed
% by a sharp decrease in the rate at which $g(k,n)$ grows with $k$.
% On retrospect, this should not be that surprising; the above root
% rule only comes into play in cases where the first branch point
% would otherwise remain oversaturated after thinning, and that is
% way less often than one might see pruning at other branch points.
% Hence there could be a point in seeking a root rule that harmonises
% better with the general node rule.
%
% One approach to devising such an alternative root rule is to
% emulate a virtual branch point below the root, and apply the
% ordinary node rule logic (even if not its implementation) to that
% branch point. The size of the virtual branch meeting the full tree
% can simply be taken to be equal to that of the tree, and this far
% down in the tree it would be unusual with a branching of degree
% higher than $2$, even if the underlying $\mu$ is larger. The tricky
% matter is however how far down below the root that the virtual
% branch point should be considered to be, as that determines the
% bound against which the tree size should be compared.
%
% \begin{proc}{up1r_Poisson}
% The |up1r_Poisson| procedure answers the question about the
% position of the virtual branching point by making it (the
% distance from root to virtual branching point) a Poisson
% distributed random variable. The argument for a Poisson
% distribution is mainly that it ``has the right shape''---one may
% prescribe the average, there is a maximum around that average,
% and there is no arbitrary upper cut-off---but one can also make a
% slightly more analytical argument for why it should be about right.
% First, the Poisson distribution arises as the \(n \to \infty\)
% limit of the binomial distribution when one keeps the expected
% value fixed. Second, the binomial distribution is a sum of a
% number of independent identically distributed $\{0,1\}$ variables.
% Third, the length of the path between two branching points does
% indeed reflect a number of times that $1$ was chosen rather than
% $0$, namely the number of self-thinnings which went down that
% branch and not its sibling (although the true distribution there is
% probably much more complicated than a simple binomial
% distribution).
%
% The call syntax for this procedure is
% \begin{displaysyntax}
% |up1r_Poisson| \word{tree} \word{limits-list}
% \word{limits-index} \word{ignore-probability}
% \word{dimensionality}
% \end{displaysyntax}
% The first four arguments are as for |up1r|. The fifth
% \word{dimensionality} argument is\slash should be the exponent in
% the asymptotic growth of the \word{limits-list} elements. It is
% used for estimating the expected position of the virtual
% branching point, as explained below.
%
% As with |up1r|, the first step is the self-thinning of the tree
% based on real nodes in it.
% \begin{tcl}
proc selfthin::up1r_Poisson {tree limitsL limitsidx p d} {
foreach {tree counts} [
namespace inscope up1r $tree $limitsL $limitsidx $p
] break
% \end{tcl}
% The second step is to check whether there is some pruning to do.
% Unlike the case in a normal node, the choice of whether to go
% down this branch (as opposed to its virtual sibling) is done
% first, because it is much less work than checking whether the
% saturation bound has been reached. Also, it can be combined with
% the \word{ignore-probability} randomness for not pruning even if
% saturation is exceeded.
% \begin{tcl}
if {[llength $counts]<=1 || 2*rand()<1+$p} then {return $tree}
% \end{tcl}
% Next, the expected distance $\lambda$ down to the virtual
% branching point is computed; this will then determine the
% distribution of the random variable. The idea motivating this
% calculation is that the distance between branching points
% decreases by a factor $2^{1/d}$ for every branching point one
% passes (because that is what it takes to stay on the saturation
% limit), so the length of the root segment can be approximated by
% taking an average of lengths higher up in the tree, appropriately
% scaled. Arbitrarily, the average is taken with a recursion depth
% of two.
% \begin{tcl}
set L [up1r_Poisson,sample $tree 2 1 [expr {pow(2,1.0/$d)}]]
set lambda [expr {[
::tcl::mathop::+ {*}[lrange $L 1 end]
]/([llength $L]-1) - [lindex $L 0]}]
% \end{tcl}
% Then comes the sampling of the Poisson random variable. The
% algorithm used for this is the one of Knuth, which roughly
% amounts to adding exponentially distributed continuous random
% variables until the sum exceeds the sought $\lambda$, and then
% declaring the number of terms the sampled value of the Poisson
% random variable. Although instead of stepping a separate
% variable, |limitsidx| is increased by one for each term.
% \begin{tcl}
set E [expr {exp(-$lambda)}]
set prod 1.0
while {$prod > $E} {
incr limitsidx
if {$limitsidx >= [llength $limitsL]} then {return $tree}
set prod [expr {$prod*rand()}]
}
% \end{tcl}
% So, now there is \emph{finally} a pruning check to carry out.
% \begin{tcl}
if {2*[::tcl::mathop::+ {*}$counts] > [lindex $limitsL $limitsidx]}\
then {
set pruneIL [list 2]
set subchildL [lindex $tree $pruneIL]
while {[llength $subchildL] == 1} {
lappend pruneIL 0 2
set subchildL [lindex $subchildL 0 2]
}
set j [expr {int(rand()*[llength $subchildL])}]
lset tree $pruneIL [lreplace $subchildL $j $j]
}
return $tree
}
% \end{tcl}
%
% \begin{proc}{up1r_Poisson,sample}
% This is a helper procedure for |up1r_Poisson| which samples the
% distances between branching points in a tree. The call syntax is
% \begin{displaysyntax}
% |up1r_Poisson,sample| \word{tree} \word{depth} \word{weight}
% \word{factor}
% \end{displaysyntax}
% where \word{tree} is the tree to sample and \word{depth} is how
% deep the recusion should be. If depth is $0$, then the data
% returned reflects only the distance to the first branching
% point in the \word{tree}, but for every $1$ that the \word{depth}
% is increased, another layer of branching points are sampled.
%
% The return value is a list of sample values, with the first one
% being for the first (rootmost) branching point. All sample
% values are weighted; those at this level by a factor
% \word{weight}, and for each subsequent level the weight is
% multiplied by the \word{factor}.
%
% \begin{tcl}
proc selfthin::up1r_Poisson,sample {tree depth weight factor} {
set n 1
while {[llength [lindex $tree 2]] == 1} {
incr n
set tree [lindex $tree 2 0]
}
set res [list [expr {$n * $weight}]]
if {[incr depth -1] < 0} then {return $res}
set weight [expr {$weight*$factor}]
foreach child [lindex $tree 2] {
lappend res {*}[
up1r_Poisson,sample $child $depth $weight $factor
]
}
return $res
}
% \end{tcl}
% \end{proc}
% \end{proc}
%
%
% \subsection{Non-uniform stochastic thinning}
%
% The point of the \texttt{} operation is to take stress into
% account when picking branches to prune: the more in excess of
% carrying capacity a branch is, the higher will the probability be
% of a pruning operation picking just that (among its siblings and
% cousins). Define the stress level $x$ of a branch to be the
% quotient of number of buds to carrying capacity. If
% $x_1,\dotsc,x_n$ are the stress levels of the branches that a
% pruning candidates, then the probability of picking branch $i$
% should be
% \begin{equation}
% \frac{x_i^q}{\sum_{j=1}^n x_j^q}
% \end{equation}
% where the exponent $q$ is a parameter of the model. \(q=0\)
% reproduces uniform probability (except that it's one-step uniform,
% rather than two uniform steps as for \texttt{up1d} and
% \texttt{up1r}; there is a difference only where branching arity is
% not constant, which requires \(\mu>2\)). Higher values of $q$
% concentrates the weight to stressed branches.
%
% In order to make these calculations convenient, the bare
% \texttt{up1n} operation needs to return a bit more information about
% the thinned tree than the previous operations. The return value is
% a list
% \begin{displaysyntax}
% \word{tree} \word{subbranch-statuses} \word{self-status}
% \end{displaysyntax}
% where a \emph{status} is a pair
% \begin{displaysyntax}
% \word{bud-count} \word{bud-limit}
% \end{displaysyntax}
% The call syntax is
% \begin{displaysyntax}
% namespace inscope selfthin::up1n \word{tree} \word{limits-list}
% \word{limits-index} \word{ignore-probability}
% \word{weighting-exponent}
% \end{displaysyntax}
%
% As before, there is also a wrapped calling syntax
% \begin{displaysyntax}
% selfthin::up1n \word{tree} \word{limits-list}
% \word{limits-index} \word{ignore-probability}
% \word{weighting-exponent}
% \end{displaysyntax}
% which returns a self-thinned form of the \word{tree}. This also
% applies a root rule, to allow pruning at the first branching point.
%
%
% \begin{tcl}
namespace eval selfthin::up1n {}
% \end{tcl}
% \setnamespace{selfthin::up1n}
%
% \begin{proc}{bud}
% Buds have no branching, and are one bud.
% \begin{tcl}
proc selfthin::up1n::bud {attr children limitsL limitsIdx p q} {
list [list bud $attr {}] {} [list 1 [lindex $limitsL $limitsIdx]]
}
% \end{tcl}
% \end{proc}
%
% \begin{proc}{node}
% For a \texttt{node}, the first order of business is to
% recursively apply the operation to all children.
% \begin{tcl}
proc selfthin::up1n::node {attr children limitsL limitsidx p q} {
set childL {}
set substatusL {}
set selfstatusL {}
set buds 0
set nextidx [expr {$limitsidx-1}]
foreach child $children {
set res [{*}$child $limitsL $nextidx $p $q]
lappend childL [lindex $res 0]
lappend substatusL [lindex $res 1]
lappend selfstatusL [lindex $res 2]
incr buds [lindex $res 2 0]
}
% \end{tcl}
% In the fairly common case that there is only one child, there is
% no pruning to do and the statuses can all be reused, so we return
% early.
% \begin{tcl}
if {[llength $childL] <= 1} then {
lset res 0 [list node $attr $childL]
return $res
}
% \end{tcl}
% Otherwise check if there is pruning to do. When there is, the
% next step is to pick a subbranch to prune. The stochastic side is
% handled by building a list of $\sum_{l=1}^k x_l^q$ values,
% rescaling a random number to its range, and then doing a
% |-bisect| search to find the right range. Since this produces a
% linear index for the subbranch, it is also necessary to keep
% track of the branching system positions of each candidate
% subbranch, which is what the |posL| list is for.
% \begin{tcl}
if {$limitsidx>=0 && $buds > [lindex $limitsL $limitsidx] &&\
rand()>=$p} then {
set distL [list -Inf]
set posL {}
set sum 0.0
set i 0
foreach L $substatusL {
set j 0
foreach status $L {
set sum [expr {$sum + pow(
double([lindex $status 0])/[lindex $status 1], $q
)}]
lappend distL $sum
lappend posL [list $i $j]
incr j
}
incr i
}
set k [lsearch -sorted -real -bisect $distL [expr {$sum * rand()}]]
set i [lindex $posL $k 0]
set j [lindex $posL $k 1]
% \end{tcl}
% $i$ is the index of the child that will be subjected to pruning.
% $j$ is the index at its first branching point of the subbranch to
% remove. This branching point may sit several levels down in the
% recursion, so |pruneIL| is constructed to hold the list of indices
% that will address the right list of children.
% \begin{tcl}
if {[lindex $selfstatusL $i 0] > 1} then {
set pruneIL [list $i 2]