-
Notifications
You must be signed in to change notification settings - Fork 49
/
traits.jl
3661 lines (3157 loc) · 145 KB
/
traits.jl
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
# Continuous trait evolution on network
# default tolerances to optimize parameters in continuous trait evolution models
# like lambda, sigma2_withinspecies / sigma2_BM, etc.
const fAbsTr = 1e-10
const fRelTr = 1e-10
const xAbsTr = 1e-10
const xRelTr = 1e-10
"""
MatrixTopologicalOrder
Matrix associated to an [`HybridNetwork`](@ref) in which rows/columns
correspond to nodes in the network, sorted in topological order.
The following functions and extractors can be applied to it: [`tipLabels`](@ref), `obj[:Tips]`, `obj[:InternalNodes]`, `obj[:TipsNodes]` (see documentation for function [`getindex(::MatrixTopologicalOrder, ::Symbol)`](@ref)).
Functions [`sharedPathMatrix`](@ref) and [`simulate`](@ref) return objects of this type.
The `MatrixTopologicalOrder` object has fields: `V`, `nodeNumbersTopOrder`, `internalNodeNumbers`, `tipNumbers`, `tipNames`, `indexation`.
Type in "?MatrixTopologicalOrder.field" to get documentation on a specific field.
"""
struct MatrixTopologicalOrder
"V: the matrix per se"
V::Matrix # Matrix in itself
"nodeNumbersTopOrder: vector of nodes numbers in the topological order, used for the matrix"
nodeNumbersTopOrder::Vector{Int} # Vector of nodes numbers for ordering of the matrix
"internalNodeNumbers: vector of internal nodes number, in the original net order"
internalNodeNumbers::Vector{Int} # Internal nodes numbers (original net order)
"tipNumbers: vector of tips numbers, in the origial net order"
tipNumbers::Vector{Int} # Tips numbers (original net order)
"tipNames: vector of tips names, in the original net order"
tipNames::Vector # Tips Names (original net order)
"""
indexation: a string giving the type of matrix `V`:
-"r": rows only are indexed by the nodes of the network
-"c": columns only are indexed by the nodes of the network
-"b": both rows and columns are indexed by the nodes of the network
"""
indexation::AbstractString # Are rows ("r"), columns ("c") or both ("b") indexed by nodes numbers in the matrix ?
end
function Base.show(io::IO, obj::MatrixTopologicalOrder)
println(io, "$(typeof(obj)):\n$(obj.V)")
end
# docstring already in descriptive.jl
function tipLabels(obj::MatrixTopologicalOrder)
return obj.tipNames
end
# This function takes an init and update funtions as arguments
# It does the recursion using these functions on a preordered network.
function recursionPreOrder(net::HybridNetwork,
checkPreorder=true::Bool,
init=identity::Function,
updateRoot=identity::Function,
updateTree=identity::Function,
updateHybrid=identity::Function,
indexation="b"::AbstractString,
params...)
net.isRooted || error("net needs to be rooted for a pre-oreder recursion")
if(checkPreorder)
preorder!(net)
end
M = recursionPreOrder(net.nodes_changed, init, updateRoot, updateTree, updateHybrid, params)
# Find numbers of internal nodes
nNodes = [n.number for n in net.node]
nleaf = [n.number for n in net.leaf]
deleteat!(nNodes, indexin(nleaf, nNodes))
MatrixTopologicalOrder(M, [n.number for n in net.nodes_changed], nNodes, nleaf, [n.name for n in net.leaf], indexation)
end
"""
recursionPreOrder(nodes, init_function, root_function, tree_node_function,
hybrid_node_function, parameters)
recursionPreOrder!(nodes, AbstractArray, root_function, tree_node_function,
hybrid_node_function, parameters)
updatePreOrder(index, nodes, updated_matrix, root_function, tree_node_function,
hybrid_node_function, parameters)
Generic tool to apply a pre-order (or topological ordering) algorithm.
Used by `sharedPathMatrix` and by `pairwiseTaxonDistanceMatrix`.
"""
function recursionPreOrder(nodes::Vector{Node},
init::Function,
updateRoot::Function,
updateTree::Function,
updateHybrid::Function,
params)
M = init(nodes, params)
recursionPreOrder!(nodes, M, updateRoot, updateTree, updateHybrid, params)
end
@doc (@doc recursionPreOrder) recursionPreOrder!
function recursionPreOrder!(nodes::Vector{Node},
M::AbstractArray,
updateRoot::Function,
updateTree::Function,
updateHybrid::Function,
params)
for i in 1:length(nodes) #sorted list of nodes
updatePreOrder!(i, nodes, M, updateRoot, updateTree, updateHybrid, params)
end
return M
end
@doc (@doc recursionPreOrder) updatePreOrder!
function updatePreOrder!(i::Int,
nodes::Vector{Node},
V::AbstractArray, updateRoot::Function,
updateTree::Function,
updateHybrid::Function,
params)
parent = getparents(nodes[i]) # vector of nodes (empty, size 1 or 2)
if(isempty(parent)) #nodes[i] is root
updateRoot(V, i, params)
elseif(length(parent) == 1) #nodes[i] is tree
parentIndex = getIndex(parent[1],nodes)
edge = getConnectingEdge(nodes[i],parent[1])
updateTree(V, i, parentIndex, edge, params)
elseif(length(parent) == 2) #nodes[i] is hybrid
parentIndex1 = getIndex(parent[1],nodes)
parentIndex2 = getIndex(parent[2],nodes)
edge1 = getConnectingEdge(nodes[i],parent[1])
edge2 = getConnectingEdge(nodes[i],parent[2])
edge1.hybrid || error("connecting edge between node $(nodes[i].number) and $(parent[1].number) should be a hybrid egde")
edge2.hybrid || error("connecting edge between node $(nodes[i].number) and $(parent[2].number) should be a hybrid egde")
updateHybrid(V, i, parentIndex1, parentIndex2, edge1, edge2, params)
end
end
## Same, but in post order (tips to root). see docstring below
function recursionPostOrder(net::HybridNetwork,
checkPreorder=true::Bool,
init=identity::Function,
updateTip=identity::Function,
updateNode=identity::Function,
indexation="b"::AbstractString,
params...)
net.isRooted || error("net needs to be rooted for a post-order recursion")
if(checkPreorder)
preorder!(net)
end
M = recursionPostOrder(net.nodes_changed, init, updateTip, updateNode, params)
# Find numbers of internal nodes
nNodes = [n.number for n in net.node]
nleaf = [n.number for n in net.leaf]
deleteat!(nNodes, indexin(nleaf, nNodes))
MatrixTopologicalOrder(M, [n.number for n in net.nodes_changed], nNodes, nleaf, [n.name for n in net.leaf], indexation)
end
"""
recursionPostOrder(net::HybridNetwork, checkPreorder::Bool,
init_function, tip_function, node_function,
indexation="b", parameters...)
recursionPostOrder(nodes, init_function, tip_function, node_function,
parameters)
updatePostOrder!(index, nodes, updated_matrix, tip_function, node_function,
parameters)
Generic tool to apply a post-order (or topological ordering) algorithm,
acting on a matrix where rows & columns correspond to nodes.
Used by `descendenceMatrix`.
"""
function recursionPostOrder(nodes::Vector{Node},
init::Function,
updateTip::Function,
updateNode::Function,
params)
n = length(nodes)
M = init(nodes, params)
for i in n:-1:1 #sorted list of nodes
updatePostOrder!(i, nodes, M, updateTip, updateNode, params)
end
return M
end
@doc (@doc recursionPostOrder) updatePostOrder!
function updatePostOrder!(i::Int,
nodes::Vector{Node},
V::Matrix,
updateTip::Function,
updateNode::Function,
params)
children = getchildren(nodes[i]) # vector of nodes (empty, size 1 or 2)
if(isempty(children)) #nodes[i] is a tip
updateTip(V, i, params)
else
childrenIndex = [getIndex(n, nodes) for n in children]
edges = [getConnectingEdge(nodes[i], c) for c in children]
updateNode(V, i, childrenIndex, edges, params)
end
end
# Extract the right part of a matrix in topological order
# !! Extract sub-matrices in the original net nodes numbers !!
"""
getindex(obj, d,[ indTips, nonmissing])
Getting submatrices of an object of type [`MatrixTopologicalOrder`](@ref).
# Arguments
* `obj::MatrixTopologicalOrder`: the matrix from which to extract.
* `d::Symbol`: a symbol precising which sub-matrix to extract. Can be:
* `:Tips` columns and/or rows corresponding to the tips
* `:InternalNodes` columns and/or rows corresponding to the internal nodes
Includes tips not listed in `indTips` or missing data according to `nonmissing`.
* `:TipsNodes` columns corresponding to internal nodes, and row to tips (works only is indexation="b")
* `indTips::Vector{Int}`: optional argument precising a specific order for the tips (internal use).
* `nonmissing::BitArray{1}`: optional argument saying which tips have data (internal use).
Tips with missing data are treated as internal nodes.
"""
function Base.getindex(obj::MatrixTopologicalOrder,
d::Symbol,
indTips=collect(1:length(obj.tipNumbers))::Vector{Int},
nonmissing=trues(length(obj.tipNumbers))::BitArray{1})
tipnums = obj.tipNumbers[indTips][nonmissing]
maskTips = indexin(tipnums, obj.nodeNumbersTopOrder)
if d == :Tips # Extract rows and/or columns corresponding to the tips with data
obj.indexation == "b" && return obj.V[maskTips, maskTips] # both columns and rows are indexed by nodes
obj.indexation == "c" && return obj.V[:, maskTips] # Only the columns
obj.indexation == "r" && return obj.V[maskTips, :] # Only the rows
end
intnodenums = [obj.internalNodeNumbers ; setdiff(obj.tipNumbers, tipnums)]
maskNodes = indexin(intnodenums, obj.nodeNumbersTopOrder)
#= indices in obj.nodeNumbersTopOrder, in this order:
1. internal nodes, in the same order as in obj.internalNodeNumbers,
that is, same order as in net.node (excluding leaves)
2. tips absent from indTips or missing data according to nonmissing,
in the same order as in obj.tipNumbers.
=#
if d == :InternalNodes # Idem, for internal nodes
obj.indexation == "b" && return obj.V[maskNodes, maskNodes]
obj.indexation == "c" && return obj.V[:, maskNodes]
obj.indexation == "r" && return obj.V[maskNodes, :]
end
if d == :TipsNodes
obj.indexation == "b" && return obj.V[maskTips, maskNodes]
obj.indexation == "c" && error("""Both rows and columns must be net
ordered to take the submatrix tips vs internal nodes.""")
obj.indexation == "r" && error("""Both rows and columns must be net
ordered to take the submatrix tips vs internal nodes.""")
end
d == :All && return obj.V
end
###############################################################################
## phylogenetic variance-covariance between tips
###############################################################################
"""
vcv(net::HybridNetwork; model="BM"::AbstractString,
corr=false::Bool,
checkPreorder=true::Bool)
This function computes the variance covariance matrix between the tips of the
network, assuming a Brownian model of trait evolution (with unit variance).
If optional argument `corr` is set to `true`, then the correlation matrix is returned instead.
The function returns a `DataFrame` object, with columns named by the tips of the network.
The calculation of the covariance matrix requires a pre-ordering of nodes to be fast.
If `checkPreorder` is true (default), then [`preorder!`](@ref) is run on the network beforehand.
Otherwise, the network is assumed to be already in pre-order.
This function internally calls [`sharedPathMatrix`](@ref), which computes the variance
matrix between all the nodes of the network.
# Examples
```jldoctest
julia> tree_str = "(((t2:0.14,t4:0.33):0.59,t3:0.96):0.14,(t5:0.70,t1:0.18):0.90);";
julia> tree = readTopology(tree_str);
julia> C = vcv(tree)
5×5 DataFrame
Row │ t2 t4 t3 t5 t1
│ Float64 Float64 Float64 Float64 Float64
─────┼─────────────────────────────────────────────
1 │ 0.87 0.73 0.14 0.0 0.0
2 │ 0.73 1.06 0.14 0.0 0.0
3 │ 0.14 0.14 1.1 0.0 0.0
4 │ 0.0 0.0 0.0 1.6 0.9
5 │ 0.0 0.0 0.0 0.9 1.08
```
The following block needs `ape` to be installed (not run):
```julia
julia> using RCall # Comparison with ape vcv function
julia> R"ape::vcv(ape::read.tree(text = \$tree_str))"
RCall.RObject{RCall.RealSxp}
t2 t4 t3 t5 t1
t2 0.87 0.73 0.14 0.0 0.00
t4 0.73 1.06 0.14 0.0 0.00
t3 0.14 0.14 1.10 0.0 0.00
t5 0.00 0.00 0.00 1.6 0.90
t1 0.00 0.00 0.00 0.9 1.08
```
The covariance can also be calculated on a network
(for the model, see Bastide et al. 2018)
```jldoctest
julia> net = readTopology("((t1:1.0,#H1:0.1::0.30):0.5,((t2:0.9)#H1:0.2::0.70,t3:1.1):0.4);");
julia> C = vcv(net)
3×3 DataFrame
Row │ t1 t2 t3
│ Float64 Float64 Float64
─────┼───────────────────────────
1 │ 1.5 0.15 0.0
2 │ 0.15 1.248 0.28
3 │ 0.0 0.28 1.5
```
"""
function vcv(net::HybridNetwork;
model="BM"::AbstractString,
corr=false::Bool,
checkPreorder=true::Bool)
@assert (model == "BM") "The 'vcv' function only works for a BM process (for now)."
V = sharedPathMatrix(net; checkPreorder=checkPreorder)
C = V[:Tips]
corr && StatsBase.cov2cor!(C, sqrt.(diag(C)))
Cd = DataFrame(C, map(Symbol, V.tipNames))
return(Cd)
end
"""
sharedPathMatrix(net::HybridNetwork; checkPreorder=true::Bool)
This function computes the shared path matrix between all the nodes of a
network. It assumes that the network is in the pre-order. If checkPreorder is
true (default), then it runs function `preorder!` on the network beforehand.
Returns an object of type [`MatrixTopologicalOrder`](@ref).
"""
function sharedPathMatrix(net::HybridNetwork;
checkPreorder=true::Bool)
check_nonmissing_nonnegative_edgelengths(net,
"""The variance-covariance matrix of the network is not defined.
A phylogenetic regression cannot be done.""")
recursionPreOrder(net,
checkPreorder,
initsharedPathMatrix,
updateRootSharedPathMatrix!,
updateTreeSharedPathMatrix!,
updateHybridSharedPathMatrix!,
"b")
end
function updateRootSharedPathMatrix!(V::AbstractArray, i::Int, params)
return
end
function updateTreeSharedPathMatrix!(V::Matrix,
i::Int,
parentIndex::Int,
edge::Edge,
params)
for j in 1:(i-1)
V[i,j] = V[j,parentIndex]
V[j,i] = V[j,parentIndex]
end
V[i,i] = V[parentIndex,parentIndex] + edge.length
end
function updateHybridSharedPathMatrix!(V::Matrix,
i::Int,
parentIndex1::Int,
parentIndex2::Int,
edge1::Edge,
edge2::Edge,
params)
for j in 1:(i-1)
V[i,j] = V[j,parentIndex1]*edge1.gamma + V[j,parentIndex2]*edge2.gamma
V[j,i] = V[i,j]
end
V[i,i] = edge1.gamma*edge1.gamma*(V[parentIndex1,parentIndex1] + edge1.length) + edge2.gamma*edge2.gamma*(V[parentIndex2,parentIndex2] + edge2.length) + 2*edge1.gamma*edge2.gamma*V[parentIndex1,parentIndex2]
end
function initsharedPathMatrix(nodes::Vector{Node}, params)
n = length(nodes)
return(zeros(Float64,n,n))
end
"""
check_nonmissing_nonnegative_edgelengths(net, str="")
Throw an Exception if `net` has undefined edge lengths (coded as -1.0) or
negative edge lengths. The error message indicates the number of the offending
edge(s), followed by `str`.
"""
function check_nonmissing_nonnegative_edgelengths(net::HybridNetwork, str="")
if any(e.length == -1.0 for e in net.edge)
undefined = [e.number for e in net.edge if e.length == -1.0]
error(string("Branch(es) number ", join(undefined,","), " have no length.\n", str))
end
if any(e.length < 0 for e in net.edge)
negatives = [e.number for e in net.edge if e.length < 0.0]
error(string("Branch(es) number ", join(negatives,","), " have negative length.\n", str))
end
end
###############################################################################
"""
descendenceMatrix(net::HybridNetwork; checkPreorder=true::Bool)
Descendence matrix between all the nodes of a network:
object `D` of type [`MatrixTopologicalOrder`](@ref) in which
`D[i,j]` is the proportion of genetic material in node `i` that can be traced
back to node `j`. If `D[i,j]>0` then `j` is a descendent of `i` (and `j` is
an ancestor of `i`).
The network is assumed to be pre-ordered if `checkPreorder` is false.
If `checkPreorder` is true (default), `preorder!` is run on the network beforehand.
"""
function descendenceMatrix(net::HybridNetwork;
checkPreorder=true::Bool)
recursionPostOrder(net,
checkPreorder,
initDescendenceMatrix,
updateTipDescendenceMatrix!,
updateNodeDescendenceMatrix!,
"r")
end
function updateTipDescendenceMatrix!(::Matrix, ::Int, params)
return
end
function updateNodeDescendenceMatrix!(V::Matrix,
i::Int,
childrenIndex::Vector{Int},
edges::Vector{Edge},
params)
for j in 1:length(edges)
V[:,i] .+= edges[j].gamma .* V[:,childrenIndex[j]]
end
end
function initDescendenceMatrix(nodes::Vector{Node}, params)
n = length(nodes)
return(Matrix{Float64}(I, n, n)) # identity matrix
end
###############################################################################
"""
regressorShift(node::Vector{Node}, net::HybridNetwork; checkPreorder=true)
regressorShift(edge::Vector{Edge}, net::HybridNetwork; checkPreorder=true)
Compute the regressor vectors associated with shifts on edges that are above nodes
`node`, or on edges `edge`, on a network `net`. It uses function [`descendenceMatrix`](@ref), so
`net` might be modified to sort it in a pre-order.
Return a `DataFrame` with as many rows as there are tips in net, and a column for
each shift, each labelled according to the pattern shift_{number_of_edge}. It has
an aditional column labelled `tipNames` to allow easy fitting afterward (see example).
# Examples
```jldoctest
julia> net = readTopology("(A:2.5,((B:1,#H1:0.5::0.4):1,(C:1,(D:0.5)#H1:0.5::0.6):1):0.5);");
julia> preorder!(net)
julia> using PhyloPlots
julia> plot(net, shownodenumber=true); # to locate nodes
julia> nodes_shifts = indexin([1,-5], [n.number for n in net.node]) # Put a shift on edges ending at nodes 1 and -5
2-element Vector{Union{Nothing, Int64}}:
1
7
julia> params = ParamsBM(10, 0.1, ShiftNet(net.node[nodes_shifts], [3.0, -3.0], net))
ParamsBM:
Parameters of a BM with fixed root:
mu: 10
Sigma2: 0.1
There are 2 shifts on the network:
──────────────────────────
Edge Number Shift Value
──────────────────────────
8.0 -3.0
1.0 3.0
──────────────────────────
julia> using Random; Random.seed!(2468); # sets the seed for reproducibility
julia> sim = simulate(net, params); # simulate a dataset with shifts
julia> using DataFrames # to handle data frames
julia> dat = DataFrame(trait = sim[:Tips], tipNames = sim.M.tipNames);
julia> dat = DataFrame(trait = [13.391976856737717, 9.55741491696386, 7.17703734817448, 7.889062527849697],
tipNames = ["A","B","C","D"]) # hard-coded, to be independent of random number generator
4×2 DataFrame
Row │ trait tipNames
│ Float64 String
─────┼────────────────────
1 │ 13.392 A
2 │ 9.55741 B
3 │ 7.17704 C
4 │ 7.88906 D
julia> dfr_shift = regressorShift(net.node[nodes_shifts], net) # the regressors matching the shifts.
4×3 DataFrame
Row │ shift_1 shift_8 tipNames
│ Float64 Float64 String
─────┼────────────────────────────
1 │ 1.0 0.0 A
2 │ 0.0 0.0 B
3 │ 0.0 1.0 C
4 │ 0.0 0.6 D
julia> dfr = innerjoin(dat, dfr_shift, on=:tipNames); # join data and regressors in a single dataframe
julia> using StatsModels # for statistical model formulas
julia> fitBM = phylolm(@formula(trait ~ shift_1 + shift_8), dfr, net; reml=false) # actual fit
PhyloNetworkLinearModel
Formula: trait ~ 1 + shift_1 + shift_8
Model: Brownian motion
Parameter Estimates, using ML:
phylogenetic variance rate: 0.0112618
Coefficients:
────────────────────────────────────────────────────────────────────────
Coef. Std. Error t Pr(>|t|) Lower 95% Upper 95%
────────────────────────────────────────────────────────────────────────
(Intercept) 9.48238 0.327089 28.99 0.0220 5.32632 13.6384
shift_1 3.9096 0.46862 8.34 0.0759 -2.04479 9.86399
shift_8 -2.4179 0.422825 -5.72 0.1102 -7.7904 2.95461
────────────────────────────────────────────────────────────────────────
Log Likelihood: 1.8937302027
AIC: 4.2125395947
```
# See also
[`phylolm`](@ref), [`descendenceMatrix`](@ref), [`regressorHybrid`](@ref).
"""
function regressorShift(node::Vector{Node},
net::HybridNetwork; checkPreorder=true::Bool)
T = descendenceMatrix(net; checkPreorder=checkPreorder)
regressorShift(node, net, T)
end
function regressorShift(node::Vector{Node},
net::HybridNetwork,
T::MatrixTopologicalOrder)
## Get the descendence matrix for tips
T_t = T[:Tips]
## Get the indices of the columns to keep
ind = zeros(Int, length(node))
for i in 1:length(node)
!node[i].hybrid || error("Shifts on hybrid edges are not allowed")
ind[i] = getIndex(node[i], net.nodes_changed)
end
## get column names
eNum = [getMajorParentEdgeNumber(n) for n in net.nodes_changed[ind]]
function tmp_fun(x::Int)
return(Symbol("shift_$(x)"))
end
df = DataFrame(T_t[:, ind], [tmp_fun(num) for num in eNum])
df[!,:tipNames]=T.tipNames
return(df)
end
function regressorShift(edge::Vector{Edge},
net::HybridNetwork; checkPreorder=true::Bool)
childs = [getchild(ee) for ee in edge]
return(regressorShift(childs, net; checkPreorder=checkPreorder))
end
regressorShift(edge::Edge, net::HybridNetwork; checkPreorder=true::Bool) = regressorShift([edge], net; checkPreorder=checkPreorder)
regressorShift(node::Node, net::HybridNetwork; checkPreorder=true::Bool) = regressorShift([node], net; checkPreorder=checkPreorder)
"""
regressorHybrid(net::HybridNetwork; checkPreorder=true::Bool)
Compute the regressor vectors associated with shifts on edges that imediatly below
all hybrid nodes of `net`. It uses function [`descendenceMatrix`](@ref) through
a call to [`regressorShift`](@ref), so `net` might be modified to sort it in a pre-order.
Return a `DataFrame` with as many rows as there are tips in net, and a column for
each hybrid, each labelled according to the pattern shift_{number_of_edge}. It has
an aditional column labelled `tipNames` to allow easy fitting afterward (see example).
This function can be used to test for heterosis.
# Examples
```jldoctest
julia> using DataFrames # Needed to handle data frames.
julia> net = readTopology("(A:2.5,((B:1,#H1:0.5::0.4):1,(C:1,(D:0.5)#H1:0.5::0.6):1):0.5);");
julia> preorder!(net)
julia> using PhyloPlots
julia> plot(net, shownodenumber=true); # to locate nodes: node 5 is child of hybrid node
julia> nodes_hybrids = indexin([5], [n.number for n in net.node]) # Put a shift on edges below hybrids
1-element Vector{Union{Nothing, Int64}}:
5
julia> params = ParamsBM(10, 0.1, ShiftNet(net.node[nodes_hybrids], [3.0], net))
ParamsBM:
Parameters of a BM with fixed root:
mu: 10
Sigma2: 0.1
There are 1 shifts on the network:
──────────────────────────
Edge Number Shift Value
──────────────────────────
6.0 3.0
──────────────────────────
julia> using Random; Random.seed!(2468); # sets the seed for reproducibility
julia> sim = simulate(net, params); # simulate a dataset with shifts
julia> dat = DataFrame(trait = sim[:Tips], tipNames = sim.M.tipNames);
julia> dat = DataFrame(trait = [10.391976856737717, 9.55741491696386, 10.17703734817448, 12.689062527849698],
tipNames = ["A","B","C","D"]) # hard-code values for more reproducibility
4×2 DataFrame
Row │ trait tipNames
│ Float64 String
─────┼────────────────────
1 │ 10.392 A
2 │ 9.55741 B
3 │ 10.177 C
4 │ 12.6891 D
julia> dfr_hybrid = regressorHybrid(net) # the regressors matching the hybrids.
4×3 DataFrame
Row │ shift_6 tipNames sum
│ Float64 String Float64
─────┼────────────────────────────
1 │ 0.0 A 0.0
2 │ 0.0 B 0.0
3 │ 0.0 C 0.0
4 │ 1.0 D 1.0
julia> dfr = innerjoin(dat, dfr_hybrid, on=:tipNames); # join data and regressors in a single dataframe
julia> using StatsModels
julia> fitBM = phylolm(@formula(trait ~ shift_6), dfr, net; reml=false) # actual fit
PhyloNetworkLinearModel
Formula: trait ~ 1 + shift_6
Model: Brownian motion
Parameter Estimates, using ML:
phylogenetic variance rate: 0.041206
Coefficients:
────────────────────────────────────────────────────────────────────────
Coef. Std. Error t Pr(>|t|) Lower 95% Upper 95%
────────────────────────────────────────────────────────────────────────
(Intercept) 10.064 0.277959 36.21 0.0008 8.86805 11.26
shift_6 2.72526 0.315456 8.64 0.0131 1.36796 4.08256
────────────────────────────────────────────────────────────────────────
Log Likelihood: -0.7006021946
AIC: 7.4012043891
```
# See also
[`phylolm`](@ref), [`descendenceMatrix`](@ref), [`regressorShift`](@ref).
"""
function regressorHybrid(net::HybridNetwork; checkPreorder=true::Bool)
childs = [getchild(nn) for nn in net.hybrid] # checks that each hybrid node has a single child
dfr = regressorShift(childs, net; checkPreorder=checkPreorder)
dfr[!,:sum] = sum.(eachrow(select(dfr, Not(:tipNames), copycols=false)))
return(dfr)
end
# Type for shifts
"""
ShiftNet
Shifts associated to a [`HybridNetwork`](@ref) sorted in topological order.
Its `shift` field is a vector of shift values, one for each node,
corresponding to the shift on the parent edge of the node
(which makes sense for tree nodes only: they have a single parent edge).
Two `ShiftNet` objects on the same network can be concatened with `*`.
`ShiftNet(node::Vector{Node}, value::AbstractVector, net::HybridNetwork; checkPreorder=true::Bool)`
Constructor from a vector of nodes and associated values. The shifts are located
on the edges above the nodes provided. Warning, shifts on hybrid edges are not
allowed.
`ShiftNet(edge::Vector{Edge}, value::AbstractVector, net::HybridNetwork; checkPreorder=true::Bool)`
Constructor from a vector of edges and associated values.
Warning, shifts on hybrid edges are not allowed.
Extractors: [`getShiftEdgeNumber`](@ref), [`getShiftValue`](@ref)
"""
struct ShiftNet
shift::Matrix{Float64}
net::HybridNetwork
end
# Default
ShiftNet(net::HybridNetwork, dim::Int) = ShiftNet(zeros(length(net.node), dim), net)
ShiftNet(net::HybridNetwork) = ShiftNet(net, 1)
function ShiftNet(node::Vector{Node}, value::AbstractMatrix,
net::HybridNetwork; checkPreorder=true::Bool)
n_nodes, dim = size(value)
if length(node) != n_nodes
error("The vector of nodes/edges and of values must have the same number or rows.")
end
if checkPreorder
preorder!(net)
end
obj = ShiftNet(net, dim)
for i in 1:length(node)
!node[i].hybrid || error("Shifts on hybrid edges are not allowed")
ind = findfirst(x -> x===node[i], net.nodes_changed)
obj.shift[ind, :] .= @view value[i, :]
end
return(obj)
end
function ShiftNet(node::Vector{Node}, value::AbstractVector,
net::HybridNetwork; checkPreorder=true::Bool)
return ShiftNet(node, reshape(value, (length(value), 1)), net,
checkPreorder = checkPreorder)
end
# Construct from edges and values
function ShiftNet(edge::Vector{Edge},
value::Union{AbstractVector, AbstractMatrix},
net::HybridNetwork; checkPreorder=true::Bool)
childs = [getchild(ee) for ee in edge]
return(ShiftNet(childs, value, net; checkPreorder=checkPreorder))
end
ShiftNet(edge::Edge, value::Float64, net::HybridNetwork; checkPreorder=true::Bool) = ShiftNet([edge], [value], net; checkPreorder=checkPreorder)
ShiftNet(node::Node, value::Float64, net::HybridNetwork; checkPreorder=true::Bool) = ShiftNet([node], [value], net; checkPreorder=checkPreorder)
function ShiftNet(edge::Edge, value::AbstractVector{Float64},
net::HybridNetwork; checkPreorder=true::Bool)
return ShiftNet([edge], reshape(value, (1, length(value))), net,
checkPreorder = checkPreorder)
end
function ShiftNet(node::Node, value::AbstractVector{Float64},
net::HybridNetwork; checkPreorder=true::Bool)
return ShiftNet([node], reshape(value, (1, length(value))), net,
checkPreorder = checkPreorder)
end
"""
shiftHybrid(value::Vector{T} where T<:Real, net::HybridNetwork; checkPreorder=true::Bool)
Construct an object [`ShiftNet`](@ref) with shifts on all the edges below
hybrid nodes, with values provided. The vector of values must have the
same length as the number of hybrids in the network.
"""
function shiftHybrid(value::Union{Matrix{T}, Vector{T}} where T<:Real,
net::HybridNetwork; checkPreorder=true::Bool)
if length(net.hybrid) != size(value, 1)
error("You must provide as many values as the number of hybrid nodes.")
end
childs = [getchild(nn) for nn in net.hybrid] # checks for single child
return(ShiftNet(childs, value, net; checkPreorder=checkPreorder))
end
shiftHybrid(value::Real, net::HybridNetwork; checkPreorder=true::Bool) = shiftHybrid([value], net; checkPreorder=checkPreorder)
"""
getShiftEdgeNumber(shift::ShiftNet)
Get the edge numbers where the shifts are located, for an object [`ShiftNet`](@ref).
If a shift is placed at the root node with no parent edge, the edge number
of a shift is set to -1 (as if missing).
"""
function getShiftEdgeNumber(shift::ShiftNet)
nodInd = getShiftRowInds(shift)
[getMajorParentEdgeNumber(n) for n in shift.net.nodes_changed[nodInd]]
end
function getMajorParentEdgeNumber(n::Node)
try
getparentedge(n).number
catch
-1
end
end
function getShiftRowInds(shift::ShiftNet)
n, p = size(shift.shift)
inds = zeros(Int, n)
counter = 0
for i = 1:n
use_row = !all(iszero, @view shift.shift[i, :])
if use_row
counter += 1
inds[counter] = i
end
end
return inds[1:counter]
end
"""
getShiftValue(shift::ShiftNet)
Get the values of the shifts, for an object [`ShiftNet`](@ref).
"""
function getShiftValue(shift::ShiftNet)
rowInds = getShiftRowInds(shift)
shift.shift[rowInds, :]
end
function shiftTable(shift::ShiftNet)
sv = getShiftValue(shift)
if size(sv, 2) == 1
shift_labels = ["Shift Value"]
else
shift_labels = ["Shift Value $i" for i = 1:size(sv, 2)]
end
CoefTable(hcat(getShiftEdgeNumber(shift), sv),
["Edge Number"; shift_labels],
fill("", size(sv, 1)))
end
function Base.show(io::IO, obj::ShiftNet)
println(io, "$(typeof(obj)):\n",
shiftTable(obj))
end
function Base.:*(sh1::ShiftNet, sh2::ShiftNet)
isEqual(sh1.net, sh2.net) || error("Shifts to be concatenated must be defined on the same network.")
size(sh1.shift) == size(sh2.shift) || error("Shifts to be concatenated must have the same dimensions.")
shiftNew = zeros(size(sh1.shift))
for i in 1:length(sh1.shift)
if iszero(sh1.shift[i])
shiftNew[i] = sh2.shift[i]
elseif iszero(sh2.shift[i])
shiftNew[i] = sh1.shift[i]
elseif sh1.shift[i] == sh2.shift[i]
shiftNew[i] = sh1.shift[i]
else
error("The two shifts matrices you provided affect the same " *
"trait for the same edge, so I cannot choose which one you want.")
end
end
return(ShiftNet(shiftNew, sh1.net))
end
# function Base.:(==)(sh1::ShiftNet, sh2::ShiftNet)
# isEqual(sh1.net, sh2.net) || return(false)
# sh1.shift == sh2.shift || return(false)
# return(true)
# end
###################################################
# types to hold parameters for evolutionary process
# like scalar BM, multivariate BM, OU?
abstract type ParamsProcess end
"""
ParamsBM <: ParamsProcess
Type for a BM process on a network. Fields are `mu` (expectation),
`sigma2` (variance), `randomRoot` (whether the root is random, default to `false`),
and `varRoot` (if the root is random, the variance of the root, default to `NaN`).
"""
mutable struct ParamsBM <: ParamsProcess
mu::Real # Ancestral value or mean
sigma2::Real # variance
randomRoot::Bool # Root is random ? default false
varRoot::Real # root variance. Default NaN
shift::Union{ShiftNet, Missing} # shifts
function ParamsBM(mu::Real,
sigma2::Real,
randomRoot::Bool,
varRoot::Real,
shift::Union{ShiftNet, Missing})
if !ismissing(shift) && size(shift.shift, 2) != 1
error("ShiftNet must have only a single shift dimension.")
end
return new(mu, sigma2, randomRoot, varRoot, shift)
end
end
# Constructor
ParamsBM(mu::Real, sigma2::Real) = ParamsBM(mu, sigma2, false, NaN, missing) # default values
ParamsBM(mu::Real, sigma2::Real, net::HybridNetwork) = ParamsBM(mu, sigma2, false, NaN, ShiftNet(net)) # default values
ParamsBM(mu::Real, sigma2::Real, shift::ShiftNet) = ParamsBM(mu, sigma2, false, NaN, shift) # default values
function anyShift(params::ParamsProcess)
if ismissing(params.shift) return(false) end
for v in params.shift.shift
if v != 0 return(true) end
end
return(false)
end
function process_dim(::ParamsBM)
return 1
end
function Base.show(io::IO, obj::ParamsBM)
disp = "$(typeof(obj)):\n"
pt = paramstable(obj)
if obj.randomRoot
disp = disp * "Parameters of a BM with random root:\n" * pt
else
disp = disp * "Parameters of a BM with fixed root:\n" * pt
end
println(io, disp)
end
function paramstable(obj::ParamsBM)
disp = "mu: $(obj.mu)\nSigma2: $(obj.sigma2)"
if obj.randomRoot
disp = disp * "\nvarRoot: $(obj.varRoot)"
end
if anyShift(obj)
disp = disp * "\n\nThere are $(length(getShiftValue(obj.shift))) shifts on the network:\n"
disp = disp * "$(shiftTable(obj.shift))"
end
return(disp)
end
"""
ParamsMultiBM <: ParamsProcess
Type for a multivariate Brownian diffusion (MBD) process on a network. Fields are `mu` (expectation),
`sigma` (covariance matrix), `randomRoot` (whether the root is random, default to `false`),
`varRoot` (if the root is random, the covariance matrix of the root, default to `[NaN]`),
`shift` (a ShiftNet type, default to `missing`),
and `L` (the lower triangular of the cholesky decomposition of `sigma`, computed automatically)
# Constructors
```jldoctest
julia> ParamsMultiBM([1.0, -0.5], [2.0 0.3; 0.3 1.0]) # no shifts
ParamsMultiBM:
Parameters of a MBD with fixed root:
mu: [1.0, -0.5]
Sigma: [2.0 0.3; 0.3 1.0]
julia> net = readTopology("((A:1,B:1):1,C:2);");
julia> shifts = ShiftNet(net.node[2], [-1.0, 2.0], net);
julia> ParamsMultiBM([1.0, -0.5], [2.0 0.3; 0.3 1.0], shifts) # with shifts
ParamsMultiBM:
Parameters of a MBD with fixed root:
mu: [1.0, -0.5]
Sigma: [2.0 0.3; 0.3 1.0]
There are 2 shifts on the network:
───────────────────────────────────────────
Edge Number Shift Value 1 Shift Value 2
───────────────────────────────────────────
2.0 -1.0 2.0
───────────────────────────────────────────
```
"""
mutable struct ParamsMultiBM <: ParamsProcess
mu::AbstractArray{Float64, 1}
sigma::AbstractArray{Float64, 2}
randomRoot::Bool
varRoot::AbstractArray{Float64, 2}
shift::Union{ShiftNet, Missing}
L::LowerTriangular{Float64}
function ParamsMultiBM(mu::AbstractArray{Float64, 1},
sigma::AbstractArray{Float64, 2},
randomRoot::Bool,
varRoot::AbstractArray{Float64, 2},
shift::Union{ShiftNet, Missing},
L::LowerTriangular{Float64})
dim = length(mu)
if size(sigma) != (dim, dim)