licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.1.0
d2362147a98d73e1c6a42584844f97d1da35b94c
docs
4744
## Example: Using Planar Flow Here we provide a minimal demonstration of learning a synthetic 2d banana distribution using *planar flows* (Renzende *et al.* 2015) by maximizing the [Evidence Lower Bound (ELBO)](@ref). To complete this task, the two key inputs are: - the log-density function of the target distribution, - the planar flow. #### The Target Distribution The `Banana` object is defined in `example/targets/banana.jl`, see the [source code](https://github.com/zuhengxu/NormalizingFlows.jl/blob/main/example/targets/banana.jl) for details. ```julia p = Banana(2, 1.0f-1, 100.0f0) logp = Base.Fix1(logpdf, p) ``` Visualize the contour of the log-density and the sample scatters of the target distribution: ![Banana](banana.png) #### The Planar Flow The planar flow is defined by repeated applying a sequence of invertible transformations to a base distribution $q_0$. The building blocks for a planar flow of length $N$ are the following invertible transformations, called *planar layers*: ```math \text{planar layers}: T_{n, \theta_n}(x)=x+u_n \cdot \tanh \left(w_n^T x+b_n\right), \quad n=1, \ldots, N, ``` where $\theta_n = (u_n, w_n, b_n), n=1, \dots, N$ are the parameters to be learned. Thankfully, [`Bijectors.jl`](https://github.com/TuringLang/Bijectors.jl) provides a nice framework to define a normalizing flow. Here we used the `PlanarLayer()` from `Bijectors.jl` to construct a 20-layer planar flow, of which the base distribution is a 2d standard Gaussian distribution. ```julia using Bijectors, FunctionChains function create_planar_flow(n_layers::Int, q₀) d = length(q₀) Ls = [f32(PlanarLayer(d)) for _ in 1:n_layers] ts = fchain(Ls) return transformed(q₀, ts) end # create a 20-layer planar flow flow = create_planar_flow(20, MvNormal(zeros(Float32, 2), I)) flow_untrained = deepcopy(flow) # keep a copy of the untrained flow for comparison ``` *Notice that here the flow layers are chained together using `fchain` function from [`FunctionChains.jl`](https://github.com/oschulz/FunctionChains.jl). Alternatively, one can do* ```julia ts = reduce(∘, [f32(PlanarLayer(d)) for i in 1:20]) ``` *However, we recommend using `fchain` to reduce the compilation time when the number of layers is large. See [this comment](https://github.com/TuringLang/NormalizingFlows.jl/blob/8f4371d48228adf368d851e221af076ff929f1cf/src/NormalizingFlows.jl#L52) for how the compilation time might be a concern.* #### Flow Training Then we can train the flow by maximizing the ELBO using the [`train_flow`](@ref) function as follows: ```julia using NormalizingFlows using ADTypes using Optimisers sample_per_iter = 10 # callback function to track the number of samples used per iteration cb(iter, opt_stats, re, θ) = (sample_per_iter=sample_per_iter,) # defined stopping criteria when the gradient norm is less than 1e-3 checkconv(iter, stat, re, θ, st) = stat.gradient_norm < 1e-3 flow_trained, stats, _ = train_flow( elbo, flow, logp, sample_per_iter; max_iters=200_00, optimiser=Optimisers.ADAM(), callback=cb, hasconverged=checkconv, ADbackend=AutoZygote(), # using Zygote as the AD backend ) ``` Examine the loss values during training: ```julia using Plots losses = map(x -> x.loss, stats) plot(losses; xlabel = "#iteration", ylabel= "negative ELBO", label="", linewidth=2) ``` ![elbo](elbo.png) ## Evaluating Trained Flow Finally, we can evaluate the trained flow by sampling from it and compare it with the target distribution. Since the flow is defined as a `Bijectors.TransformedDistribution`, one can easily sample from it using `rand` function, or examine the density using `logpdf` function. See [documentation of `Bijectors.jl`](https://turinglang.org/Bijectors.jl/dev/distributions/) for details. ```julia using Random, Distributions nsample = 1000 samples_trained = rand(flow_trained, n_samples) # 1000 iid samples from the trained flow samples_untrained = rand(flow_untrained, n_samples) # 1000 iid samples from the untrained flow samples_true = rand(p, n_samples) # 1000 iid samples from the target # plot scatter(samples_true[1, :], samples_true[2, :]; label="True Distribution", color=:blue, markersize=2, alpha=0.5) scatter!(samples_untrained[1, :], samples_untrained[2, :]; label="Untrained Flow", color=:red, markersize=2, alpha=0.5) scatter!(samples_trained[1, :], samples_trained[2, :]; label="Trained Flow", color=:green, markersize=2, alpha=0.5) plot!(title = "Comparison of Trained and Untrained Flow", xlabel = "X", ylabel= "Y", legend=:topleft) ``` ![compare](comparison.png) ## Reference - Rezende, D. and Mohamed, S., 2015. *Variational inference with normalizing flows*. International Conference on Machine Learning
NormalizingFlows
https://github.com/TuringLang/NormalizingFlows.jl.git
[ "MIT" ]
0.1.0
d2362147a98d73e1c6a42584844f97d1da35b94c
docs
4029
```@meta CurrentModule = NormalizingFlows ``` # NormalizingFlows.jl Documentation for [NormalizingFlows](https://github.com/TuringLang/NormalizingFlows.jl). The purpose of this package is to provide a simple and flexible interface for variational inference (VI) and normalizing flows (NF) for Bayesian computation and generative modeling. The key focus is to ensure modularity and extensibility, so that users can easily construct (e.g., define customized flow layers) and combine various components (e.g., choose different VI objectives or gradient estimates) for variational approximation of general target distributions, *without being tied to specific probabilistic programming frameworks or applications*. See the [documentation](https://turinglang.org/NormalizingFlows.jl/dev/) for more. ## Installation To install the package, run the following command in the Julia REPL: ``` ] # enter Pkg mode (@v1.9) pkg> add [email protected]:TuringLang/NormalizingFlows.jl.git ``` Then simply run the following command to use the package: ```julia using NormalizingFlows ``` ## What are normalizing flows? Normalizing flows transform a simple reference distribution $q_0$ (sometimes known as base distribution) to a complex distribution $q_\theta$ using invertible functions with trainable parameter $\theta$, aiming to approximate a target distribution $p$. The approximation is achieved by minimizing some statistical distances between $q$ and $p$. In more details, given the base distribution, usually a standard Gaussian distribution, i.e., $q_0 = \mathcal{N}(0, I)$, we apply a series of parameterized invertible transformations (called flow layers), $T_{1, \theta_1}, \cdots, T_{N, \theta_k}$, yielding that ```math Z_N = T_{N, \theta_N} \circ \cdots \circ T_{1, \theta_1} (Z_0) , \quad Z_0 \sim q_0,\quad Z_N \sim q_{\theta}, ``` where $\theta = (\theta_1, \dots, \theta_N)$ are the parameters to be learned, and $q_{\theta}$ is the transformed distribution (typically called the variational distribution or the flow distribution). This describes **sampling procedure** of normalizing flows, which requires sending draws from the base distribution through a forward pass of these flow layers. Since all the transformations are invertible (technically [diffeomorphic](https://en.wikipedia.org/wiki/Diffeomorphism)), we can evaluate the density of a normalizing flow distribution $q_{\theta}$ by the change of variable formula: ```math q_\theta(x)=\frac{q_0\left(T_1^{-1} \circ \cdots \circ T_N^{-1}(x)\right)}{\prod_{n=1}^N J_n\left(T_n^{-1} \circ \cdots \circ T_N^{-1}(x)\right)} \quad J_n(x)=\left|\operatorname{det} \nabla_x T_n(x)\right|. ``` Here we drop the subscript $\theta_n, n = 1, \dots, N$ for simplicity. Density evaluation of normalizing flow requires computing the **inverse** and the **Jacobian determinant** of each flow layer. Given the feasibility of i.i.d. sampling and density evaluation, normalizing flows can be trained by minimizing some statistical distances to the target distribution $p$. The typical choice of the statistical distance is the forward and reverse Kullback-Leibler (KL) divergence, which leads to the following optimization problems: ```math \begin{aligned} \text{Reverse KL:}\quad &\argmin _{\theta} \mathbb{E}_{q_{\theta}}\left[\log q_{\theta}(Z)-\log p(Z)\right] \\ &= \argmin _{\theta} \mathbb{E}_{q_0}\left[\log \frac{q_\theta(T_N\circ \cdots \circ T_1(Z_0))}{p(T_N\circ \cdots \circ T_1(Z_0))}\right] \\ &= \argmax _{\theta} \mathbb{E}_{q_0}\left[ \log p\left(T_N \circ \cdots \circ T_1(Z_0)\right)-\log q_0(X)+\sum_{n=1}^N \log J_n\left(F_n \circ \cdots \circ F_1(X)\right)\right] \end{aligned} ``` and ```math \begin{aligned} \text{Forward KL:}\quad &\argmin _{\theta} \mathbb{E}_{p}\left[\log q_{\theta}(Z)-\log p(Z)\right] \\ &= \argmin _{\theta} \mathbb{E}_{p}\left[\log q_\theta(Z)\right] \end{aligned} ``` Both problems can be solved via standard stochastic optimization algorithms, such as stochastic gradient descent (SGD) and its variants.
NormalizingFlows
https://github.com/TuringLang/NormalizingFlows.jl.git
[ "MIT" ]
0.1.0
d2362147a98d73e1c6a42584844f97d1da35b94c
docs
928
# NormalizingFlows Model-Zoo This folder contains various demonstrations of the usage of the `NormalizingFlows.jl` package. `targets/` contains a collection of example target distributions for testing/benchmarking normalizing flows. Each `*_flow.jl` file provides a demonstration of how to train the corresponding normalizing flow to approximate the target distribution using `NormalizingFlows.jl` package. ## Usage Currently, all examples share the same [Julia project](https://pkgdocs.julialang.org/v1/environments/#Using-someone-else's-project). To run the examples, first activate the project environment: ```julia # pwd() = "NormalizingFlows.jl/" using Pkg; Pkg.activate("example"); Pkg.instantiate() ``` This will install all needed packages, at the exact versions when the model was last updated. Then you can run the model code with include("<example-to-run>.jl"), or by running the example script line-by-line.
NormalizingFlows
https://github.com/TuringLang/NormalizingFlows.jl.git
[ "MIT" ]
1.0.0
6a4b1f62d366073837f350cfdccdfe3477ff2535
code
775
insert!(LOAD_PATH, 1, joinpath(@__DIR__, "..")) using PropertyMethods using Documenter DocMeta.setdocmeta!(PropertyMethods, :DocTestSetup, :(using PropertyMethods); recursive=true) makedocs(; modules=[PropertyMethods], authors="MarkNahabedian <[email protected]> and contributors", repo="https://github.com/MarkNahabedian/PropertyMethods.jl/blob/{commit}{path}#{line}", sitename="PropertyMethods.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://MarkNahabedian.github.io/PropertyMethods.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/MarkNahabedian/PropertyMethods.jl", devbranch="main", )
PropertyMethods
https://github.com/MarkNahabedian/PropertyMethods.jl.git
[ "MIT" ]
1.0.0
6a4b1f62d366073837f350cfdccdfe3477ff2535
code
54
module PropertyMethods include("properties.jl") end
PropertyMethods
https://github.com/MarkNahabedian/PropertyMethods.jl.git
[ "MIT" ]
1.0.0
6a4b1f62d366073837f350cfdccdfe3477ff2535
code
2578
# Rather than use a conditional tree to determine which peoperty is # being queried by `getproperty`, we can method specialize # `getproperty` on Val types. # We should then be able to automate `propertynames` and `hasproperty` # based on the defined methods. # A struct might have fields, which are exposed as properties. The # `Val` methods will not shadow the method that implements that. export @property_trampolines, @delegate """ propertynames_from_val_methods(t::Type, private::Bool) Compute and return the `propertynames` for type `t` from its fields and `Val` specialized methods. """ function propertynames_from_val_methods(t::Type, private::Bool) props = collect(fieldnames(t)) for m in methods(Base.getproperty, [t, Any]).ms if m.sig isa DataType if m.sig.parameters[2] == t p = m.sig.parameters[3] if p <: Val push!(props, p.parameters[1]) end end end end props end """ @property_trampolines MyStruct Define the methods necessary so that `Val` specialized `getproperty` methods for `MyStruct` will find `Val` specialized properties. """ macro property_trampolines(structname) quote Base.getproperty(o::$(esc(structname)), prop::Symbol) = Base.getproperty(o, Val(prop)) Base.getproperty(o::$(esc(structname)), prop::Val{T}) where {T} = getfield(o, T) Base.propertynames(o::$(esc(structname)), private::Bool=false) = propertynames_from_val_methods(typeof(o), private) Base.hasproperty(o::$(esc(structname)), prop::Symbol) = prop in propertynames_from_val_methods(typeof(o), true) end end """ @delegate from_type to_field properties... Defines `getproperty` methods on `from_type` that for each of the enumerated `properties` that will return the value of that property from a `from_type` instance's `to_field`. """ macro delegate(from_type, to_field, properties...) methods = [] for prop in properties push!(methods, esc(Expr(:(=), Expr(:call, Expr(:(.), :Base, QuoteNode(:getproperty)), Expr(:(::), :o, from_type), Expr(:(::), Expr(:curly, :Val, QuoteNode(prop)))), Expr(Symbol("."), Expr(:(.), :o, QuoteNode(to_field)), QuoteNode(prop))))) end quote $(methods...) end end
PropertyMethods
https://github.com/MarkNahabedian/PropertyMethods.jl.git
[ "MIT" ]
1.0.0
6a4b1f62d366073837f350cfdccdfe3477ff2535
code
92
using PropertyMethods using Test include("test_properties.jl") include("test_delegate.jl")
PropertyMethods
https://github.com/MarkNahabedian/PropertyMethods.jl.git
[ "MIT" ]
1.0.0
6a4b1f62d366073837f350cfdccdfe3477ff2535
code
198
struct MyWrapper target end @delegate MyWrapper target a @property_trampolines MyWrapper @testset "test @delegate" begin ms = MyStruct(3) mw = MyWrapper(ms) @test mw.a == 3 end
PropertyMethods
https://github.com/MarkNahabedian/PropertyMethods.jl.git
[ "MIT" ]
1.0.0
6a4b1f62d366073837f350cfdccdfe3477ff2535
code
389
struct MyStruct a::Int end @property_trampolines MyStruct function Base.getproperty(o::MyStruct, prop::Val{:b}) o.a * 2 end @testset "Val dispatch for properties" begin ms = MyStruct(3) @test ms.a == 3 @test ms.b == 6 @test Set(propertynames(ms)) == Set([:a, :b]) @test hasproperty(ms, :a) @test hasproperty(ms, :b) @test !hasproperty(ms, :c) end
PropertyMethods
https://github.com/MarkNahabedian/PropertyMethods.jl.git
[ "MIT" ]
1.0.0
6a4b1f62d366073837f350cfdccdfe3477ff2535
docs
1163
# PropertyMethods [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://MarkNahabedian.github.io/PropertyMethods.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://MarkNahabedian.github.io/PropertyMethods.jl/dev/) [![Build Status](https://github.com/MarkNahabedian/PropertyMethods.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/MarkNahabedian/PropertyMethods.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/MarkNahabedian/PropertyMethods.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/MarkNahabedian/PropertyMethods.jl) PropertyMethods is a small package that allows one to add computed properties to a struct by defining a `Val` specialized method for each property. Unrelated properties no longer need to be enumerated in the conditioonal tree of a single `getproperty` method. Properties defined in this way will automatically be recognized by the struct's `propertynames` and `hasproperty` methods. This mackage also provide a macro to generate trampoline methods for the *Delegation* pattern. See the documentation linked above for details.
PropertyMethods
https://github.com/MarkNahabedian/PropertyMethods.jl.git
[ "MIT" ]
1.0.0
6a4b1f62d366073837f350cfdccdfe3477ff2535
docs
1844
```@meta CurrentModule = PropertyMethods ``` # PropertyMethods Suppose a type needs to define non-field properties. This might be because it needs to implement some of the properties of another type to whose interface it must conform. The *Delegation* pattern is an example. There could be other reasons why some properties need to be computed rather than directly read. Here is an example, though somewhat contrived: ```@example 1 using PropertyMethods mutable struct Rectangle x y width height end mutable struct OffsetRectangle rect x_offset y_offset end Base.getproperty(r::OffsetRectangle, ::Val{:x}) = r.x_offset + r.rect.x Base.getproperty(r::OffsetRectangle, ::Val{:y}) = r.y_offset + r.rect.y Base.getproperty(r::OffsetRectangle, ::Val{:width}) = r.rect.width Base.getproperty(r::OffsetRectangle, ::Val{:height}) = r.rect.height @property_trampolines OffsetRectangle ``` `@property_trampolines` is necessary to define some additional methods: ```@example 1 using MacroTools MacroTools.striplines(@macroexpand @property_trampolines OffsetRectangle) ``` ```@example 1 rect1 = Rectangle(0, 1, 2, 4) orect = OffsetRectangle(rect1, 2, 2) for prop in propertynames(orect) println(prop, '\t', getproperty(orect, prop)) end ``` Some of the `getproperty` methods we defined just trampoline to the value of the `OffsetRectangle`'s `rect` field. This is just boilerplate. We can do better: ```@example 1 MacroTools.striplines(@macroexpand @delegate Rectangle rect width height) ``` So, instead of explicitly coding the OffsetRectangle methods for the `width` and `height` fields, we can write ```@example 1 @delegate Rectangle rect width height ``` ```@example 1 orect.width ``` ## Index ```@index ``` ## Definitions ```@autodocs Modules = [PropertyMethods] ```
PropertyMethods
https://github.com/MarkNahabedian/PropertyMethods.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
579
using Documenter, TransferMatrix makedocs( sitename = "TransferMatrix.jl", modules = [TransferMatrix], pages = [ "Introduction" => "index.md", "Tutorial" => Any[ "Quick Start" => "guide/quickstart.md", "Tutorial" => "guide/tutorial.md" ], "Library" => Any[ "Public" => "lib/public.md", "Internals" => "lib/internals.md" ], "References" => "bibliography.md" ] ) deploydocs( repo = "github.com/garrekstemo/TransferMatrix.jl.git", )
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
937
using Revise using RefractiveIndex using TransferMatrix using GLMakie n_air = RefractiveMaterial("other", "air", "Ciddor") n_glass = RefractiveMaterial("glass", "BK7", "SCHOTT")[1] air = Layer(n_air, 0.1) glass = Layer(n_glass, 0.1) layers = [air, glass] λ = 1.0 θs = 0.0:1:85.0 res = angle_resolved([λ], deg2rad.(θs), layers) brewster = rad2deg(atan(n_glass(λ))) air.dispersion(λ) glass.dispersion(λ) TransferMatrix.refractive_index(n_glass)(λ) fig = Figure() ax = Axis(fig[1, 1], xlabel = "Incidence Angle (°)", ylabel = "Reflectance / Transmittance") lines!(θs, res.Tss[:, 1], label = "Ts", color = :firebrick3) lines!(θs, res.Tpp[:, 1], label = "Tp", color = :orangered3) lines!(θs, res.Rss[:, 1], label = "Rs", color = :dodgerblue4) lines!(θs, res.Rpp[:, 1], label = "Rp", color = :dodgerblue1) vlines!(ax, brewster, color = :black, linestyle = :dash) text!("Brewster angle\n(Rp = 0)", position = (35, 0.6)) axislegend(ax) fig
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
1578
# DBR cavity example using Revise using RefractiveIndex using TransferMatrix using GLMakie n_air = RefractiveMaterial("other", "air", "Ciddor") n_tio2 = RefractiveMaterial("main", "TiO2", "Sarkar") n_sio2 = RefractiveMaterial("main", "SiO2", "Rodriguez-de_Marcos") λ_0 = 1.0 # μm nperiods = 6 t_tio2 = λ_0 / (4 * n_tio2(λ_0)) t_sio2 = λ_0 / (4 * n_sio2(λ_0)) t_middle = λ_0 / 2 air = Layer(n_air, t_middle) tio2 = Layer(n_tio2, t_tio2) sio2 = Layer(n_sio2, t_sio2) dbr_unit = [tio2, sio2] layers = [air, repeat(dbr_unit, nperiods)..., air, repeat(reverse(dbr_unit), nperiods)..., air]; λs = 0.8:0.001:1.2 νs = 10^4 ./ λs Tpp = Float64[] Tss = Float64[] Rpp = Float64[] Rss = Float64[] for λ in λs Tpp_, Tss_, Rpp_, Rss_ = calculate_tr(λ, layers) push!(Tpp, Tpp_) push!(Tss, Tss_) push!(Rpp, Rpp_) push!(Rss, Rss_) end λ = 1.0 field = electric_field(λ_0, layers) fig = Figure(size = (450, 600)) DataInspector() ax1 = Axis(fig[1, 1], title = "ZnS / MgF₂ quarter-wave stack with 3 layers", xlabel = "Wavelength (μm)", ylabel = "Transmittance / Reflectance", yticks = LinearTicks(5), xticks = LinearTicks(10)) lines!(λs, Tpp, label = "T") lines!(λs, Rpp, label = "R") axislegend(ax1, position = :rc) ax2 = Axis(fig[2, 1], title = "Electric Field at λ = $(Int(λ * 1e3)) nm", xlabel = "z position (nm)", ylabel = "Field intensity (a.u.)") lines!(field.z .* 1e3, real(field.p[1, :])) vlines!(field.boundaries[1], color = :black, linestyle = :dash) vlines!(field.boundaries[end] .* 1e3, color = :black, linestyle = :dash) fig
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
1551
# Fabry-Pérot cavity example using Revise using RefractiveIndex using TransferMatrix using GLMakie caf2 = RefractiveMaterial("main", "CaF2", "Malitson") au = RefractiveMaterial("main", "Au", "Rakic-LD") air = RefractiveMaterial("other", "air", "Ciddor") λ_0 = 5.0 t_middle = λ_0 / 2 layers = [Layer(air, 8.0), Layer(au, 0.01), Layer(air, t_middle), Layer(au, 0.01), Layer(air, 8.0)]; λs = range(2.0, 6.0, length = 500) νs = 10^4 ./ λs Tpp = Float64[] Tss = Float64[] Rpp = Float64[] Rss = Float64[] for λ in λs Tpp_, Tss_, Rpp_, Rss_ = calculate_tr(λ, layers) push!(Tpp, Tpp_) push!(Tss, Tss_) push!(Rpp, Rpp_) push!(Rss, Rss_) end λ_min = findfirst(λs .> 4.9) λ_max = findfirst(λs .> 5.5) peak = findmax(Tpp[λ_min:λ_max])[2] + λ_min - 1 λ = λs[peak] field = electric_field(λ, layers) fig = Figure(size = (450, 600)) DataInspector() ax1 = Axis(fig[1, 1], title = "Fabry-Pérot Cavity", xlabel = "Wavelength (μm)", ylabel = "Transmittance / Reflectance", yticks = LinearTicks(5), xticks = LinearTicks(10)) lines!(νs, Tpp, label = "T") scatter!(10^4 / λs[peak], Tpp[peak], color = :red, markersize = 5) # lines!(νs, Rpp, label = "R") axislegend(ax1, position = :rc) ax2 = Axis(fig[2, 1], title = "Electric Field at λ = $(round(Int, λ * 1e3)) nm", xlabel = "z position (nm)", ylabel = "Field intensity (a.u.)") lines!(field.z .* 1e3, real(field.p[1, :])) vlines!(field.boundaries[1], color = :black, linestyle = :dash) vlines!(field.boundaries[end] .* 1e3, color = :black, linestyle = :dash) fig
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
3677
using Revise using BenchmarkTools using Peaks using RefractiveIndex using TransferMatrix using GLMakie function dielectric_real(ω, p) A, ω_0, Γ = p return @. A * (ω_0^2 - ω^2) / ((ω^2 - ω_0^2)^2 + (Γ * ω)^2) end function dielectric_imag(ω, p) A, ω_0, Γ = p return @. A * Γ * ω / ((ω^2 - ω_0^2)^2 + (Γ * ω)^2) end function find_resonance(spectra, atol=1e-3) for i in eachindex(spectra) pks, vals = findmaxima(spectra[i, :]) if length(pks) == 2 && isapprox(vals[1], vals[2], atol=atol) return i, pks end end end function draw_index_profile(ax, indices, thicknesses) prev_x = 0 prev_n = indices[1] for (i, n) in enumerate(indices) current_x = sum(thicknesses[1:i]) lines!(ax, [prev_x, current_x], [n, n], color = :black, linewidth = 0.5) # Plot the horizontal line if i > 1 lines!(ax, [prev_x, prev_x], [prev_n, n], color = :black, linewidth = 0.5) # Plot the vertical line end prev_x = current_x prev_n = n end end n_air = RefractiveMaterial("other", "air", "Ciddor") n_tio2 = RefractiveMaterial("main", "TiO2", "Kischkat") n_sio2 = RefractiveMaterial("main", "SiO2", "Kischkat") λ_0 = 5.0 λs = range(4.8, 5.2, length = 200) frequencies = 10^4 ./ λs θs = range(0, 30, length = 50) # absorbing material n_bg = 1.4 A_0 = 3000.0 ω_0 = 10^4 / λ_0 # cm^-1 Γ_0 = 5 p0 = [A_0, ω_0, Γ_0] ε1 = dielectric_real(frequencies, p0) .+ n_bg^2 ε2 = dielectric_imag(frequencies, p0) n_medium = @. sqrt((sqrt(abs2(ε1) + abs2(ε2)) + ε1) / 2) k_medium = @. sqrt((sqrt(abs2(ε1) + abs2(ε2)) - ε1) / 2) # dbr layers t_tio2 = λ_0 / (4 * n_tio2(λ_0)) t_sio2 = λ_0 / (4 * n_sio2(λ_0)) t_cav = 1 * λ_0 / n_bg + 0.1 # Slightly offset the cavity length to get negative detuning air = Layer(n_air, 2.0); tio2 = Layer(n_tio2, t_tio2); sio2 = Layer(n_sio2, t_sio2); absorber = Layer(λs, n_medium, k_medium, t_cav); nperiods = 6 unit = [tio2, sio2] layers = [air, repeat(unit, nperiods)..., absorber, repeat(reverse(unit), nperiods)..., air]; res = angle_resolved(λs, deg2rad.(θs), layers) θ_idx, peaks = find_resonance(res.Tpp) T_plot = res.Tpp[θ_idx, :] θ_plot = θs[θ_idx] field1 = electric_field(λs[peaks[1]], layers) field2 = electric_field(λs[peaks[2]], layers) ## fig = Figure(size = (750, 600)) ax1 = Axis(fig[1, 1], title = "Polariton dispersion", xlabel = "Incidence angle (°)", ylabel = "Frequency (cm⁻¹)") heatmap!(θs, νs, res.Tpp, colormap = :deep) ax2 = Axis(fig[2, 1], title = "Normal mode splitting at (θ ≈ $(round(Int, θ_plot)))°", xlabel = "Frequency (cm⁻¹)", ylabel = "Transmittance") lines!(frequencies, T_plot) scatter!(frequencies[peaks], T_plot[peaks], color = :red, marker = 'x', markersize = 15) ax3 = Axis(fig[1, 2], ylabel = "Photon field") lines!(field1.z .* 1e3, real(field1.p[1, :]), label = "LP") lines!(field2.z .* 1e3, real(field2.p[1, :]), label = "UP") hlines!(0, color = :black, linestyle = :dash, linewidth = 0.5) n1 = round(real(sio2.dispersion(λ_0)), digits=2) n2 = round(real(tio2.dispersion(λ_0)), digits=2) ax4 = Axis(fig[2, 2], xlabel = "Distance (μm)", ylabel = "Refractive index", yticks = [n1, n2]) # Draw DBR cavity structure refractive_indices = [real(layer.dispersion(λ_0)) for layer in layers[2:end-1]] thicknesses = [layer.thickness for layer in layers[2:end-1]] draw_index_profile(ax4, refractive_indices, thicknesses) axislegend(ax3) hidexdecorations!(ax3) hideydecorations!(ax3, label = false, ticks = false, ticklabels = false) hidexdecorations!(ax4, label = false, ticks = false, ticklabels = false) hideydecorations!(ax4, label = false, ticks = false, ticklabels = false) fig
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
1077
# Quarter-wave stack example # from documentation using Revise using RefractiveIndex using TransferMatrix using GLMakie n_air = RefractiveMaterial("other", "air", "Ciddor") n_tio2 = RefractiveMaterial("main", "TiO2", "Sarkar") n_sio2 = RefractiveMaterial("main", "SiO2", "Rodriguez-de_Marcos") λ_0 = 0.63 # μm t_tio2 = λ_0 / (4 * n_tio2(λ_0)) t_sio2 = λ_0 / (4 * n_sio2(λ_0)) air = Layer(n_air, 0.1) tio2 = Layer(n_tio2, t_tio2) sio2 = Layer(n_sio2, t_sio2) layers = [air, tio2, sio2, tio2, sio2, tio2, sio2]; λs = 0.4:0.002:1.0 Rpp = Float64[] for λ in λs Tpp_, Tss_, Rpp_, Rss_ = calculate_tr(λ, layers) push!(Rpp, Rpp_) end fig, ax, l = lines(λs .* 1e3, Rpp) ax.xlabel = "Wavelength (nm)" ax.ylabel = "Reflectance" fig ## nperiods = 6 for i in 1:nperiods push!(layers, tio2) push!(layers, sio2) Rpp = Float64[] if i%3 == 0 for λ in λs Tpp_, Tss_, Rpp_, Rss_ = calculate_tr(λ, layers) push!(Rpp, Rpp_) end lines!(ax, λs .* 1e3, Rpp, label = "$(i + 3) periods") end end axislegend(ax) fig
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
1526
using Revise using BenchmarkTools using RefractiveIndex using TransferMatrix using GLMakie function dielectric_real(ω, p) A, ω_0, Γ = p return @. A * (ω_0^2 - ω^2) / ((ω^2 - ω_0^2)^2 + (Γ * ω)^2) end function dielectric_imag(ω, p) A, ω_0, Γ = p return @. A * Γ * ω / ((ω^2 - ω_0^2)^2 + (Γ * ω)^2) end n_air = RefractiveMaterial("other", "air", "Ciddor") n_tio2 = RefractiveMaterial("main", "TiO2", "Kischkat") n_sio2 = RefractiveMaterial("main", "SiO2", "Kischkat") λ_0 = 5.0 λs = range(4.8, 5.2, length = 300) νs = 10^4 ./ λs thicknesses = 0.1:0.01:5 # absorbing material n_bg = 1.4 A_0 = 2000.0 ω_0 = 10^4 / λ_0 Γ_0 = 5 p0 = [A_0, ω_0, Γ_0] ε1 = dielectric_real(νs, p0) .+ n_bg^2 ε2 = dielectric_imag(νs, p0) n_medium = @. sqrt((sqrt(abs2(ε1) + abs2(ε2)) + ε1) / 2) k_medium = @. sqrt((sqrt(abs2(ε1) + abs2(ε2)) - ε1) / 2) # dbr layers t_tio2 = λ_0 / (4 * n_tio2(λ_0)) t_sio2 = λ_0 / (4 * n_sio2(λ_0)) t_cav = 1 * λ_0 / n_bg + 0.1 # Slightly offset the cavity length to get negative detuning air = Layer(n_air, 2.0); tio2 = Layer(n_tio2, t_tio2); sio2 = Layer(n_sio2, t_sio2); absorber = Layer(λs, n_medium, k_medium, t_cav); nperiods = 6 unit = [tio2, sio2] layers = [air, repeat(unit, nperiods)..., absorber, repeat(reverse(unit), nperiods)..., air]; ## res = tune_thickness(λs, thicknesses, layers, 14) fig = Figure() ax = Axis(fig[1, 1], title = "Polariton dispersion", xlabel = "Thickness (μm)", ylabel = "Frequency (cm⁻¹)") heatmap!(thicknesses, νs, res.Tpp, colormap = :deep) fig
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
603
module TransferMatrix using DataInterpolations using LinearAlgebra using RefractiveIndex using StaticArrays export Layer, angle_resolved, calculate_tr, dielectric_constant, dielectric_tensor, electric_field, find_bounds, fresnel, stopband, dbr_reflectivity, refractive_index, tune_thickness include("matrix_constructors.jl") include("layer.jl") include("general_TMM.jl") include("optics_functions.jl") const ε_0::Float64 = 8.8541878128e-12 const μ_0::Float64 = 1.25663706212e-6 const c_0::Float64 = 299792458 end # module
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
12121
struct Poynting out_p::SVector{3, Float64} in_p::SVector{3, Float64} out_s::SVector{3, Float64} in_s::SVector{3, Float64} refl_p::SVector{3, Float64} refl_s::SVector{3, Float64} function Poynting(out_p::T, in_p::T, out_s::T, in_s::T, refl_p::T, refl_s::T) where {T<:SVector{3, Float64}} new(out_p, in_p, out_s, in_s, refl_p, refl_s) end end struct ElectricField z::Array{Float64} p::Matrix{ComplexF64} s::Matrix{ComplexF64} boundaries::Array{Float64} end struct AngleResolvedResult Rpp::Matrix{Float64} Rss::Matrix{Float64} Tpp::Matrix{Float64} Tss::Matrix{Float64} end """ poynting(Ψ, a) Calculates the Poynting vector for the structure from Ψ and matrix ``a``. From Berreman, 1972, Ψ is the column matrix: ```math \\Psi = \\begin{pmatrix} Ex \\\\\ Hy \\\\\ Ey \\\\\ -Hx \\end{pmatrix} ``` for a right-handed Cartesian coordinate system with the z-axis along the normal to the multilayer structure. Berreman, 1972, DOI: 10.1364/JOSA.62.000502 """ function poynting(Ψ, a) S = @MMatrix zeros(ComplexF64, 3, 4) for m in 1:4 Ex = Ψ[1, m] Ey = Ψ[3, m] Hx = -Ψ[4, m] Hy = Ψ[2, m] Ez = a[3,1] * Ex + a[3,2] * Ey + a[3,4] * Hx + a[3,5] * Hy Hz = a[6,1] * Ex + a[6,2] * Ey + a[6,4] * Hx + a[6,5] * Hy S[1, m] = Ey * Hz - Ez * Hy S[2, m] = Ez * Hx - Ex * Hz S[3, m] = Ex * Hy - Ey * Hx end return SMatrix(S) end """ poynting(ξ, q_in, q_out, γ_in, γ_out, t_coefs, r_coefs) Calculate the Poynting vector from wavevectors ``q``, componments of the electric field γ, and transmission and reflection coefficients. """ function poynting(ξ, q_in, q_out, γ_in, γ_out, t_coefs, r_coefs) # create the wavevector in the first layer k_in = @MMatrix zeros(ComplexF64, 4, 3) k_in[:, 1] .= ξ for (i, q_i) in enumerate(q_in) k_in[i, 3] = q_i end k_in ./= c_0 k_in = SMatrix(k_in) E_forward_in_p = γ_in[1, :] # p-polarized incident electric field E_forward_in_s = γ_in[2, :] # s-polarized incident electric field # E_backward_in_p = γ_in[3, :] # E_backward_in_s = γ_in[4, :] E_out_p = t_coefs[1] * γ_out[1, :] + t_coefs[2] * γ_out[2, :] E_out_s = t_coefs[3] * γ_out[1, :] + t_coefs[4] * γ_out[2, :] E_ref_p = r_coefs[1] * γ_in[3, :] + r_coefs[2] * γ_in[4, :] E_ref_s = r_coefs[3] * γ_in[3, :] + r_coefs[4] * γ_in[4, :] S_in_p = real(0.5 * E_forward_in_p × conj(k_in[1, :] × E_forward_in_p)) S_in_s = real(0.5 * E_forward_in_s × conj(k_in[2, :] × E_forward_in_s)) k_out = @MMatrix zeros(ComplexF64, 4, 3) k_out[:, 1] .= ξ for (i, q_i) in enumerate(q_out) k_out[i, 3] = q_i end k_out ./= c_0 k_out = SMatrix(k_out) S_out_p = real(0.5 * E_out_p × conj(k_out[1, :] × E_out_p)) S_out_s = real(0.5 * E_out_s × conj(k_out[2, :] × E_out_s)) S_refl_p = real(0.5 * E_ref_p × conj(k_out[3, :] × E_ref_p)) S_refl_s = real(0.5 * E_ref_s × conj(k_out[4, :] × E_ref_s)) return Poynting(S_out_p, S_in_p, S_out_s, S_in_s, S_refl_p, S_refl_s) end """ evaluate_birefringence(Ψ, S, t_modes, r_modes) For the four modes (two transmitting and two reflecting), the ratio ```math \\begin{aligned} C &= |E_x|^2 / (|E_x|^2 + |E_y|^2) \\\\\ &= |Ψ_1|^2 / (|Ψ_1|^2 + |Ψ_3|^2) \\end{aligned} ``` is evaluated. Recall that the values for the electric field are contained in the eigenvector matrix, Ψ. If the layer material is birefringent, there will be anisotropy in the dielectric tensor. If this is the case, the x and y components of the Poynting vector needs to be analyzed (eqn 15 in Passler et al., 2017): ```math C = |S_x|^2 / (|S_x|^2 + |S_y|^2) ``` If there is no birefringence, then the electric field is analyzed. This analysis follows Li et al., 1988, DOI: 10.1364/AO.27.001334 and the use of the Poynting vector is from Passler et al., 2017, DOI: 10.1364/JOSAB.34.002128 and Passler et al., 2019, DOI: 10.1364/JOSAB.36.003246 """ function evaluate_birefringence(Ψ, S, t_modes, r_modes) C_q1 = abs_ratio(S[1, t_modes[1]], S[2, t_modes[1]]) C_q2 = abs_ratio(S[1, t_modes[2]], S[2, t_modes[2]]) # Note: isapprox(NaN, NaN) = false, # which is important in the case that both Sx and Sy are zero. if isapprox(C_q1, C_q2) if C_q2 > C_q1 reverse!(t_modes) end C_q3 = abs_ratio(S[1, r_modes[1]], S[2, r_modes[1]]) C_q4 = abs_ratio(S[1, r_modes[2]], S[2, r_modes[2]]) if C_q4 > C_q3 reverse!(r_modes) end else C_q1 = abs_ratio(Ψ[1, t_modes[1]], Ψ[3, t_modes[1]]) C_q2 = abs_ratio(Ψ[1, t_modes[2]], Ψ[3, t_modes[2]]) if C_q2 > C_q1 reverse!(t_modes) end C_q3 = abs_ratio(Ψ[1, r_modes[1]], Ψ[3, r_modes[1]]) C_q4 = abs_ratio(Ψ[1, r_modes[2]], Ψ[3, r_modes[2]]) if C_q4 > C_q3 reverse!(r_modes) end end return t_modes, r_modes end """ Ratio of the absolution squares of two components used to evaluate if a material is birefringent. """ abs_ratio(a, b) = abs2(a) / (abs2(a) + abs2(b)) """ propagate(λ, layers, θ, μ) Calculate the transfer matrix for the entire structure, as well as the Poynting vector for the structure. """ function propagate(λ, layers, θ, μ) first_layer = layers[1] last_layer = layers[end] n_in = first_layer.dispersion(λ) ε_0in = dielectric_constant(n_in) ξ = √(ε_0in) * sin(θ) Λ_1324 = @SMatrix [1 0 0 0; 0 0 1 0; 0 1 0 0; 0 0 0 1] D_0, P_0, γ_0, q_0 = layer_matrices(first_layer, λ, ξ, μ) D_f, P_f, γ_f, q_f = layer_matrices(last_layer, λ, ξ, μ) Γ = I Ds = [D_0] Ps = Function[P_0] γs = [γ_0] for layer in layers[2:end - 1] D_i, P_i, γ_i, q_i = layer_matrices(layer, λ, ξ, μ) T_i = D_i * P_i(layer.thickness) * inv(D_i) Γ *= T_i push!(Ds, D_i) push!(Ps, P_i) push!(γs, γ_i) end push!(Ds, D_f) push!(Ps, P_f) push!(γs, γ_f) Γ = inv(Λ_1324) * inv(D_0) * Γ * D_f * Λ_1324 r, R, t, T = calculate_tr(Γ) S = poynting(ξ, q_0, q_f, γ_0, γ_f, t, r) return Γ, S, Ds, Ps, γs end """ calculate_tr(Γ) Calculate reflectance and transmittance for the total structure. This takes the matrix Γ*, but for brevity we call it Γ in this function. This follows the formalism in: Yeh, Electromagnetic propagation in birefringent layered media, 1979, DOI: 10.1364/JOSA.69.000742 but the ordering is taken from Passler, et al., 2017 DOI: 10.1364/JOSAB.34.002128 """ function calculate_tr(Γ) d = Γ[1,1] * Γ[3,3] - Γ[1,3] * Γ[3,1] rpp = (Γ[2,1] * Γ[3,3] - Γ[2,3] * Γ[3,1]) / d rss = (Γ[1,1] * Γ[4,3] - Γ[4,1] * Γ[1,3]) / d rps = (Γ[4,1] * Γ[3,3] - Γ[4,3] * Γ[3,1]) / d rsp = (Γ[1,1] * Γ[2,3] - Γ[2,1] * Γ[1,3]) / d tpp = Γ[3,3] / d tss = Γ[1,1] / d tps = -Γ[3,1] / d tsp = -Γ[1,3] / d Rpp = abs2(rpp) Rss = abs2(rss) Rps = abs2(rps) Rsp = abs2(rsp) Tpp = abs2(tpp) Tss = abs2(tss) Tps = abs2(tps) Tsp = abs2(tsp) r = [rpp, rps, rss, rsp] R = [Rpp, Rss, Rsp, Rps] t = [tpp, tps, tsp, tss] T = [Tpp, Tss, Tsp, Tps] return r, R, t, T end """ calculate_tr(S::Poynting) Calculate transmittance from the Poynting vector struct, which contains incident and transmitted energy for both p-polarized and s-polarized waves. """ function calculate_tr(S::Poynting) Tpp = S.out_p[3] / S.in_p[3] Tss = S.out_s[3] / S.in_s[3] Rpp = -S.refl_p[3] / S.in_p[3] Rss = -S.refl_s[3] / S.in_s[3] return Tpp, Tss, Rpp, Rss end """ calculate_tr(layers, θ, μ) Calculate the transmittance and reflectance spectrum of the structure at a single incidence angle θ. Accurate transmittance must be calculated via the Poynting vector. Reflectance is calculated directly from the transfer matrix elements. """ function calculate_tr(λ, layers, θ=0.0, μ=1.0+0.0im) Γ, S, Ds, Ps, γs = propagate(λ, layers, θ, μ) r, R, t, T = calculate_tr(Γ) Tpp, Tss, Rpp_, Rss_ = calculate_tr(S) Rpp = R[1] Rss = R[2] return Tpp, Tss, Rpp, Rss end function angle_resolved(λs, θs, layers) Tpp = Array{Float64}(undef, length(θs), length(λs)) Tss = Array{Float64}(undef, length(θs), length(λs)) Rpp = Array{Float64}(undef, length(θs), length(λs)) Rss = Array{Float64}(undef, length(θs), length(λs)) Threads.@threads for (i, θ) in collect(enumerate(θs)) for (j, λ) in collect(enumerate(λs)) Tpp_, Tss_, Rpp_, Rss_ = calculate_tr(λ, layers, θ) Tpp[i, j] = Tpp_ Tss[i, j] = Tss_ Rpp[i, j] = Rpp_ Rss[i, j] = Rss_ end end return AngleResolvedResult(Rpp, Rss, Tpp, Tss) end function tune_thickness(λs, ts, layers, t_index, θ=0.0) Tpp = Matrix{Float64}(undef, length(ts), length(λs)) Tss = Matrix{Float64}(undef, length(ts), length(λs)) Rpp = Matrix{Float64}(undef, length(ts), length(λs)) Rss = Matrix{Float64}(undef, length(ts), length(λs)) Threads.@threads for (i, t) in collect(enumerate(ts)) changing_layer = Layer(layers[t_index].dispersion, t) new_layers = [layers[1:t_index-1]; changing_layer; layers[t_index+1:end]] for (j, λ) in collect(enumerate(λs)) Tpp_, Tss_, Rpp_, Rss_ = calculate_tr(λ, new_layers, θ) Tpp[i, j] = Tpp_ Tss[i, j] = Tss_ Rpp[i, j] = Rpp_ Rss[i, j] = Rss_ end end return AngleResolvedResult(Rpp, Rss, Tpp, Tss) end """ electric_field(layers, λ, θ; dz) Calculate the electric field profile for the entire structure as a function of z for a given incidence angle θ. """ function electric_field(λ, layers, θ=0.0, μ=1.0+0.0im; dz=0.001) Γ, S, Ds, Ps, γs = propagate(λ, layers, θ, μ) r, R, t, T = calculate_tr(Γ) first_layer = layers[1] last_layer = layers[end] Eplus_p = zeros(ComplexF64, length(layers), 4) Eminus_p = zeros(ComplexF64, length(layers), 4) Eplus_s = zeros(ComplexF64, length(layers), 4) Eminus_s = zeros(ComplexF64, length(layers), 4) Eplus_p[end, :] = [t[1], t[2], 0, 0] Eplus_s[end, :] = [t[3], t[4], 0, 0] P_f = Ps[end] Eminus_p[end, :] = inv(P_f(last_layer.thickness)) * Eplus_p[end, :] Eminus_s[end, :] = inv(P_f(last_layer.thickness)) * Eplus_s[end, :] D_i = Ds[end] for l in reverse(eachindex(layers)) if l >= 2 layer = layers[l - 1] D_prev = Ds[l - 1] P_prev = Ps[l - 1] L_i = inv(Ds[l - 1]) * D_i Eminus_p[l - 1, :] = L_i * Eplus_p[l, :] Eminus_s[l - 1, :] = L_i * Eplus_s[l, :] Eplus_p[l - 1, :] = P_prev(layer.thickness) * Eminus_p[l - 1, :] Eplus_s[l - 1, :] = P_prev(layer.thickness) * Eminus_s[l - 1, :] D_i = D_prev end end interface_positions, total_thickness = find_bounds(layers) interface_positions .-= first_layer.thickness zs = range(-first_layer.thickness, interface_positions[end], step=dz) field_p = [] field_s = [] field = zeros(ComplexF64, 6, length(zs)) i = 1 currentlayer = layers[i] for (j, z) in enumerate(zs) if z > interface_positions[i] i += 1 currentlayer = layers[i] end P_i = Ps[i] field_p = P_i(-(z - interface_positions[i])) * Eminus_p[i, :] field_s = P_i(-(z - interface_positions[i])) * Eminus_s[i, :] @views field[1:3, j] = field_p[1] * γs[i][1, :] + field_p[2] * γs[i][2, :] + field_p[3] * γs[i][3, :] + field_p[4] * γs[i][4, :] @views field[4:6, j] = field_s[1] * γs[i][1, :] + field_s[2] * γs[i][2, :] + field_s[3] * γs[i][3, :] + field_s[4] * γs[i][4, :] end return ElectricField(zs, field[1:3, :], field[4:6, :], interface_positions[1:end - 1]) end
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
2543
""" Layer(material, thickness) Construct a single layer with keywords: * `material`: refractive material containing dispersion and extinction data (if available) * `thickness`: thickness of the layer """ struct Layer dispersion::Function thickness::Real function Layer(material, thickness) thickness ≥ 0 || throw(DomainError("Layer thickness must be non-negative")) new(material, thickness) end end Layer(material::RefractiveMaterial, thickness::Real) = Layer(refractive_index(material), thickness) Layer(λs::AbstractVector, dispersion::AbstractVector, extinction::AbstractVector, thickness::Real) = Layer(refractive_index(λs, dispersion, extinction), thickness) """ refractive_index() Return a function that takes a wavelength and gives the real and imaginary parts of the refractive index """ function refractive_index(material::RefractiveMaterial) return λ -> begin n_imag = 0.0im # Define n_imag before the try block try n_imag = im * extinction(material, λ) catch e if isa(e, ArgumentError) n_imag = 0.0im else rethrow(e) end end return dispersion(material, λ) + n_imag end end function refractive_index(λs::AbstractVector, ns::AbstractVector, ks::AbstractVector) n_real = LinearInterpolation(ns, λs) n_imag = LinearInterpolation(ks, λs) return λ -> begin n_real(λ) + im * n_imag(λ) end end """ find_bounds(layers) Find the unitful z coordinate for all layer-layer interfaces in the structure, with the first interface starting at z = 0. (negative z corresponds to positions inside the first layer.) """ function find_bounds(layers) total_thickness = 0.0 interface_positions = Float64[] for layer in layers push!(interface_positions, total_thickness + layer.thickness) total_thickness += layer.thickness end return interface_positions, total_thickness end """ dielectric_constant(n_re::Real, n_im::Real) Return the complex dielectric function from the real and imaginary parts of the index of refraction. The complex index of refraction, given by n' = n_re + i * n_im (in terms of n_re and n_im), can be used to obtain the frequency-dependent complex dielectric function ε_r(ω) = ε' + iε'' via the relation (n_re + i * n_im)^2 = ε' + iε''. """ dielectric_constant(n_re::Real, n_im::Real) = (n_re + n_im * im)^2 dielectric_constant(n::Complex) = n^2
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
8190
""" dielectric_tensor(ε1, ε2, ε3) Return the diagonal complex dielectric tensor ```math \\varepsilon = \\begin{pmatrix} \\varepsilon_1 & 0 & 0 \\\\\ 0 & \\varepsilon_2 & 0 \\\\\ 0 & 0 & \\varepsilon_3 \\end{pmatrix} ``` """ dielectric_tensor(ε1, ε2, ε3) = Diagonal(SVector{3, ComplexF64}(ε1, ε2, ε3)) """ permeability_tensor(μ1, μ2, μ3) This produces the diagonal permeability tensor, which is identical to the way we build the `dielectric_tensor`, and we include this function simply for completeness. """ permeability_tensor(μ1, μ2, μ3) = Diagonal(SVector{3, ComplexF64}(μ1, μ2, μ3)) """ layer_matrices(ω, ξ, layer, μ) Calculate all parameters for a single layer, particularly the propagation matrix and dynamical matrix so that the overall transfer matrix can be calculated. """ function layer_matrices(layer, λ, ξ, μ_i) ω = 2π * c_0 / λ n_i = layer.dispersion(λ) ε_i = dielectric_constant(n_i) ε = dielectric_tensor(ε_i, ε_i, ε_i) μ = permeability_tensor(μ_i, μ_i, μ_i) M = construct_M(ε, μ) a = construct_a(ξ, M) Δ = construct_Δ(ξ, M, a) q, S = calculate_q(Δ, a) γ = calculate_γ(ξ, q, ε, μ_i) D = dynamical_matrix(ξ, q, γ, μ_i) P = propagation_matrix(ω, q) return D, P, γ, q end """ construct_M(ε, μ, ρ1, ρ2) Construct the 6x6 matrix M from the dielectric and permeability tensors. """ function construct_M(ε, μ=Diagonal(ones(3)), ρ1=zeros(3, 3), ρ2=zeros(3, 3)) return [ε ρ1; ρ2 μ] end """ construct_a(ξ, M) Construct the elements of the intermediate 6x6 matrix ``a`` in terms of the elements of matrix ``M`` (the 6x6 matrix holding the material dielectric and permeability tensors) and propagation vector ξ. This is implemented as described in Berreman, 1972. https://doi.org/10.1364/JOSA.62.000502 """ function construct_a(ξ, M) d = M[3,3] * M[6,6] - M[3,6] * M[6,3] a31 = (M[6,1] * M[3,6] - M[3,1] * M[6,6]) / d a32 =((M[6,2] - ξ) * M[3,6] - M[3,2] * M[6,6]) / d a34 = (M[6,4] * M[3,6] - M[3,4] * M[6,6]) / d a35 = (M[6,5] * M[3,6] - (M[3,5] + ξ) * M[6,6]) / d a61 = (M[6,3] * M[3,1] - M[3,3] * M[6,1]) / d a62 = (M[6,3] * M[3,2] - M[3,3] * (M[6,2] - ξ)) / d a64 = (M[6,3] * M[3,4] - M[3,3] * M[6,4]) / d a65 = (M[6,3] * (M[3,5] + ξ) - M[3,3] * M[6,5]) / d return SMatrix{6, 6}([ 0 0 0 0 0 0; 0 0 0 0 0 0; a31 a32 0 a34 a35 0; 0 0 0 0 0 0; 0 0 0 0 0 0; a61 a62 0 a64 a65 0 ]) end """ construct_Δ(ξ, M, a) Construct the reordered matrix Δ in terms of the elements of the two matrices, M and a, and the in-plane reduced wavevector ξ = ``k_x / k_0``. The matrix Δ is involved in the relation ```math \\frac{\\delta}{\\delta z}\\Psi = \\frac{i \\omega}{c}\\Delta \\Psi ``` and Δ is the reordered S matrix in Berreman's formulation. Berreman, 1972. https://doi.org/10.1364/JOSA.62.000502 """ function construct_Δ(ξ, M, a) Δ11 = M[5,1] + (M[5,3] + ξ) * a[3,1] + M[5,6] * a[6,1] Δ12 = M[5,5] + (M[5,3] + ξ) * a[3,5] + M[5,6] * a[6,5] Δ13 = M[5,2] + (M[5,3] + ξ) * a[3,2] + M[5,6] * a[6,2] Δ14 = -M[5,4] - (M[5,3] + ξ) * a[3,4] - M[5,6] * a[6,4] Δ21 = M[1,1] + M[1,3] * a[3,1] + M[1,6] * a[6,1] Δ22 = M[1,5] + M[1,3] * a[3,5] + M[1,6] * a[6,5] Δ23 = M[1,2] + M[1,3] * a[3,2] + M[1,6] * a[6,2] Δ24 = -M[1,4] - M[1,3] * a[3,4] - M[1,6] * a[6,4] Δ31 = -M[4,1] - M[4,3] * a[3,1] - M[4,6] * a[6,1] Δ32 = -M[4,5] - M[4,3] * a[3,5] - M[4,6] * a[6,5] Δ33 = -M[4,2] - M[4,3] * a[3,2] - M[4,6] * a[6,2] Δ34 = M[4,4] + M[4,3] * a[3,4] + M[4,6] * a[6,4] Δ41 = M[2,1] + M[2,3] * a[3,1] + (M[2,6] - ξ) * a[6,1] Δ42 = M[2,5] + M[2,3] * a[3,5] + (M[2,6] - ξ) * a[6,5] Δ43 = M[2,2] + M[2,3] * a[3,2] + (M[2,6] - ξ) * a[6,2] Δ44 = -M[2,4] - M[2,3] * a[3,4] - (M[2,6] - ξ) * a[6,4] return SMatrix{4, 4}([ Δ11 Δ12 Δ13 Δ14; Δ21 Δ22 Δ23 Δ24; Δ31 Δ32 Δ33 Δ34; Δ41 Δ42 Δ43 Δ44 ]) end """ calculate_q(Δ, a) The four eigenvalues of ``q`` may be obtained from the 4x4 matrix Δ and then eigenvectors may be found for each eigenvalue. Here the eigenvalues must be sorted appropriately to avoid potentially discontinuous solutions. This extends from the work in Li et al, 1988. https://doi.org/10.1364/AO.27.001334 """ function calculate_q(Δ, a) q_unsorted, Ψ_unsorted = eigen(Δ) transmitted_mode = [0, 0] reflected_mode = [0, 0] kt = 1 kr = 1 if isreal(q_unsorted) for m in 1:4 if real(q_unsorted[m]) >= 0.0 transmitted_mode[kt] = m kt += 1 else reflected_mode[kr] = m kr += 1 end end else for m in 1:4 if imag(q_unsorted[m]) >= 0.0 transmitted_mode[kt] = m kt += 1 else reflected_mode[kr] = m kr += 1 end end end S_unsorted = poynting(Ψ_unsorted, a) t, r = evaluate_birefringence(Ψ_unsorted, S_unsorted, transmitted_mode, reflected_mode) q = SVector(q_unsorted[t[1]], q_unsorted[t[2]], q_unsorted[r[1]], q_unsorted[r[2]]) S = SVector(S_unsorted[t[1]], S_unsorted[t[2]], S_unsorted[r[1]], S_unsorted[r[2]]) return q, S end """ calculate_γ(ξ, q, ε, μ) The 4 x 3 matrix γ contains vector components that belong to the electric field calculated such that singularities are identified and removed. `q[1]` and `q[2]` are forward-traveling modes and `q[3]` and `q[4]` are backward-traveling modes. This is based on the work in: Xu et al. Optical degeneracies in anisotropic layered media: Treatment of singularities in a 4x4 matrix formalism, 2000. DOI: 10.1103/PhysRevB.61.1740 """ function calculate_γ(ξ, q, ε, μ) γ = @MMatrix zeros(ComplexF64, 4, 3) γ[1,1] = 1 γ[2,2] = 1 γ[4,2] = 1 γ[3,1] = -1 if isapprox(q[1], q[2]) γ[1,2] = 0 γ[2,1] = 0 else γ[1,2] = (μ * ε[2,3] * (μ * ε[3,1] + ξ * q[1]) - μ * ε[2,1] * (μ * ε[3,3] - ξ^2)) / ((μ * ε[3,3] - ξ^2) * (μ * ε[2,2] - ξ^2 - q[1]^2) - μ^2 * ε[2,3] * ε[3,2]) γ[2,1] = (μ * ε[3,2] * (μ * ε[1,3] + ξ * q[2]) - μ * ε[1,2] * (μ * ε[3,3] - ξ^2)) / ((μ * ε[3,3] - ξ^2) * (μ * ε[1,1] - q[2]^2) - (μ * ε[1,3] + ξ * q[2]) * (μ * ε[3,1] + ξ * q[2])) end γ[1,3] = (-μ * ε[3,1] - ξ * q[1] - μ * ε[3,2] * γ[1,2]) / (μ * ε[3,3] - ξ^2) γ[2,3] = (-(μ * ε[3,1] + ξ * q[2]) * γ[2,1] - μ * ε[3,2]) / (μ * ε[3,3] - ξ^2) if isapprox(q[3], q[4]) γ[3,2] = 0.0 γ[4,1] = 0.0 else γ[3,2] = (μ * ε[2,1] * (μ * ε[3,3] - ξ^2) - μ * ε[2,3] * (μ * ε[3,1] + ξ * q[3])) / ((μ * ε[3,3] - ξ^2) * (μ * ε[2,2] - ξ^2 - q[3]^2) - μ^2 * ε[2,3] * ε[3,2]) γ[4,1] = (μ * ε[3,2] * (μ * ε[1,3] + ξ * q[4]) - μ * ε[1,2] * (μ * ε[3,3] - ξ^2)) / ((μ * ε[3,3] - ξ^2) * (μ * ε[1,1] - q[4]^2) - (μ * ε[1,3] + ξ * q[4]) * (μ * ε[3,1] + ξ * q[4])) end γ[3,3] = (μ * ε[3,1] + ξ * q[3] + μ * ε[3,2] * γ[3,2]) / (μ * ε[3,3] - ξ^2) γ[4,3] = (-(μ * ε[3,1] + ξ * q[4]) * γ[4,1] - μ * ε[3,2] ) / (μ * ε[3,3] - ξ^2) # normalize γ for i in 1:4 Z = √(γ[i, :] ⋅ γ[i, :]') for j in 1:3 γ[i, j] /= Z end end return SMatrix(γ) end """ dynamical_matrix(ξ, q, γ, μ) The dynamical matrix relating two layers at the interface where matrix ``A_i`` for layer ``i`` relates the field ``E_i`` to the field in the previous layer ``i - 1`` via ```math A_{i-1}E_{i-1} = A_{i}E_{i} ``` Xu et al., 2000, DOI: 10.1103/PhysRevB.61.1740 """ function dynamical_matrix(ξ, q, γ, μ) A_3 = (γ[:, 1] .* q .- ξ * γ[:, 3]) ./ μ A_4 = γ[:, 2] .* q ./ μ return SMatrix{4, 4}([ γ[1, 1] γ[2, 1] γ[3, 1] γ[4, 1]; γ[1, 2] γ[2, 2] γ[3, 2] γ[4, 2]; A_3[1] A_3[2] A_3[3] A_3[4]; A_4[1] A_4[2] A_4[3] A_4[4] ]) end """ propagation_matrix(ω, q) Returns a function that propagates the electromagnetic field a distance z through a material for a frequency ω and wavevector ``q``. """ function propagation_matrix(ω, q) return z -> Diagonal(exp.(-im * ω * q * z / c_0)) end
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
1644
""" fresnel(θ, n1, n2) Calculate the reflectance for s-polarized and p-polarized light given the incidence angle `θ` and indices of refraction of two media `n1` and `n2` at a plane interface. [Fresnel equations](https://en.wikipedia.org/wiki/Fresnel_equations) """ function fresnel(θ, n1, n2) α = √(1 - (n1 * sin(θ) / n2)^2) / cos(θ) β = n2 / n1 Rs = abs2((1/β - α) / (1/β + α)) Rp = abs2((α - β) / (α + β)) return Rs, Rp end """ stopband(n1, n2) Calculate the frequency bandwidth Δf of the photonic stopband for a distributed bragg reflector (DBR) with two alternating materials of refractive indices `n1` and `n2`. ```math \\frac{\\Delta f_0}{f_0} = \\frac{4}{\\pi} \\arcsin \\left( \\frac{n_2 - n_1}{n_2 + n_1} \\right) ``` [Distributed Bragg reflector](https://en.wikipedia.org/wiki/Distributed_Bragg_reflector) """ function stopband(n1, n2) 4 * asin(abs(n2 - n1) / (n2 + n1)) / π end """ dbr_reflectivity(no, n2, n1, n2, N) Approximate the reflectivity of a DBR structure with originating medium with refractive index `no`, substrate with index `ns`, and alternating materials with indices `n1` and `n2` and number of repetitions `N`. The repeated pair of materials are assumed to have quarter-wave thickness ``nd = \\lambda / 4``, where ``n`` is the refractive index, ``d`` is the layer thickness, and ``\\lambda`` is the wavelength of the light. [Distributed Bragg reflector](https://en.wikipedia.org/wiki/Distributed_Bragg_reflector) """ function dbr_reflectivity(no, ns, n1, n2, N) r = (no * n2^(2 * N) - ns * n1^(2 * N)) / (no * n2^(2 * N) + ns * n1^(2 * N)) return r^2 end
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
2738
# Test other functions in TransferMatrix.jl @testset "abs_ratio" begin S = ComplexF64[ 1 1 0 0; 1 2 0 0; 0 0 0 0 ] a = TransferMatrix.abs_ratio(S[1, 1], S[2, 1]) b = TransferMatrix.abs_ratio(S[1, 2], S[2, 2]) c = TransferMatrix.abs_ratio(S[1, 3], S[2, 3]) d = TransferMatrix.abs_ratio(S[1, 4], S[2, 4]) @test isapprox(a, b) == false @test a > b @test isapprox(c, d) == false @test isnan(c) == true @test isnan(d) == true end @testset "evaluate_birefringence" begin Ψ1 = ComplexF64[ 1 2 1 2; 0 0 0 0; 2 1 2 1; 0 0 0 0 ] # Evaluate 2/5 > 1/5 in reflected modes S = ComplexF64[ 1 1 1 2; 1 1 2 1; 0 0 0 0 ] # Setting elements of the Poynting vector to zero # forces the electric field to be evaluated. S1 = zeros(Int64, 3, 4) t1, r1 = TransferMatrix.evaluate_birefringence(Ψ1, S, [1, 2], [3, 4]) t2, r2 = TransferMatrix.evaluate_birefringence(Ψ1, S, [2, 1], [3, 4]) t3, r3 = TransferMatrix.evaluate_birefringence(Ψ1, S1, [1, 2], [3, 4]) t4, r4 = TransferMatrix.evaluate_birefringence(Ψ1, S1, [2, 1], [4, 3]) # transmitted modes not reversed in either case @test t1 == [1, 2] @test t2 == [2, 1] # reflected modes reversed @test r1 == [4, 3] @test r1 != [3, 4] # both transmitted and reflected modes reversed @test t3 == [2, 1] @test r3 == [4, 3] # neither are reversed @test t4 == [2, 1] @test r4 == [4, 3] end # @testset "poynting" begin # M = Array{ComplexF64}(undef, 6, 6) # ε = Diagonal([1, 1, 1]) # μ = Diagonal([1, 1, 1]) # M[1:3, 1:3] = ε # M[4:6, 4:6] = μ # a = TransferMatrix.construct_a(0., M) # Δ = TransferMatrix.construct_Δ(0., M, a) # q, Ψ = eigen(Δ) # # This just makes the elements of Ψ all 1 or -1 # # for convenience when calculating by hand. # Ψ ./= √2 / 2 # # Ψ now looks like the following: # # Ψ = [1 0 1 0; # # -1 0 1 0; # # 0 1 0 1; # # 0 -1 0 1] # # The relevant indices of the matrix, a, above are zero, # # so we give them arbitrary values here to check that # # all elements of the Poynting vector are calculated: # a[3,1] = 1 # a[3,2] = 2 # a[3,4] = 3 # a[3,5] = 4 # a[6,1] = 5 # a[6,2] = 6 # a[6,4] = 7 # a[6,5] = 8 # S = TransferMatrix.poynting(Ψ, a) # # Calculated by hand with the above a and Ψ following Passler et al. 2017. # S_test = ComplexF64[ # -3 13 -5 -1; # 3 5 -13 1; # -1 -1 1 1] # @test isapprox(S, S_test, atol=1e-13) # end
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
9086
@testset "find_bounds" begin l1 = TransferMatrix.Layer(RefractiveMaterial("main", "Au", "Rakic-LD"), 1) l2 = TransferMatrix.Layer(RefractiveMaterial("main", "SiO2", "Malitson"), 2) l3 = TransferMatrix.Layer(RefractiveMaterial("main", "Au", "Rakic-LD"), 3) layers = [l1, l2, l3] interface_positions, total_thickness = TransferMatrix.find_bounds(layers) @test interface_positions == [1.0, 3.0, 6.0] @test total_thickness == 6.0 end @testset "refractive_index" begin air = RefractiveMaterial("other", "air", "Ciddor") au = RefractiveMaterial("main", "Au", "Rakic-LD") @test TransferMatrix.refractive_index(air)(1.0) == 1.0002741661312147 + 0.0im @test TransferMatrix.refractive_index(au)(1.0) == 0.2557301597051597 + 5.986408108108109im λs = [1.0, 2.0, 3.0] ns = [1.5, 2.0, 2.5] ks = [0.5, 1.0, 1.5] refractive_index_func = refractive_index(λs, ns, ks) @test refractive_index_func(1.0) == 1.5 + 0.5im @test refractive_index_func(2.0) == 2.0 + 1.0im @test refractive_index_func(3.0) == 2.5 + 1.5im end @testset "dielectric_constant" begin au = RefractiveMaterial("main", "Au", "Rakic-LD") l = TransferMatrix.Layer(au, 1.0) ε = TransferMatrix.dielectric_constant.([1.0, 1.0, 1.0], [2.0, 2.0, 2.0]) @test real(ε) == [-3.0, -3.0, -3.0] @test imag(ε) == [4.0, 4.0, 4.0] @test TransferMatrix.dielectric_constant(1.0, 2.0) == -3.0 + 4.0im @test TransferMatrix.dielectric_constant(1.0 + 2.0im) == -3.0 + 4.0im end @testset "dielectric_tensor" begin @test TransferMatrix.dielectric_tensor(1.0, 1.0, 1.0) == [1.0 0 0; 0 1.0 0; 0 0 1.0] @test TransferMatrix.dielectric_tensor(1.0 + 1.0im, 1.0 + 1.0im, 1.0) == [complex(1.0, 1.0) 0 0; 0 complex(1.0, 1.0) 0; 0 0 1.0] end @testset "permeability_tensor" begin μ1, μ2, μ3 = 1.0 + 1.0im, 2.0 + 2.0im, 3.0 + 3.0im expected_tensor = Diagonal(SVector{3, ComplexF64}(μ1, μ2, μ3)) @test TransferMatrix.permeability_tensor(μ1, μ2, μ3) == expected_tensor end @testset "construct_M" begin ε_i = (1.0 + 2.0im)^2 μ_i = 1.0 + 0.0im ε = Diagonal([ε_i, ε_i, ε_i]) μ = Diagonal(fill(μ_i, 3)) ρ1 = [1.0 2.0 3.0; 4.0 5.0 6.0; 7.0 8.0 9.0] ρ2 = [9.0 8.0 7.0; 6.0 5.0 4.0; 3.0 2.0 1.0] M1 = TransferMatrix.construct_M(ε, μ, ρ1, ρ2) M1_true = [ ε_i 0.0 0.0 1.0 2.0 3.0; 0.0 ε_i 0.0 4.0 5.0 6.0; 0.0 0.0 ε_i 7.0 8.0 9.0; 9.0 8.0 7.0 μ_i 0.0 0.0; 6.0 5.0 4.0 0.0 μ_i 0.0; 3.0 2.0 1.0 0.0 0.0 μ_i ] M2 = TransferMatrix.construct_M(ε, μ) M2_true = [ ε_i 0.0 0.0 0.0 0.0 0.0; 0.0 ε_i 0.0 0.0 0.0 0.0; 0.0 0.0 ε_i 0.0 0.0 0.0; 0.0 0.0 0.0 μ_i 0.0 0.0; 0.0 0.0 0.0 0.0 μ_i 0.0; 0.0 0.0 0.0 0.0 0.0 μ_i ] M3 = TransferMatrix.construct_M(ε) M3_true = [ ε_i 0.0 0.0 0.0 0.0 0.0; 0.0 ε_i 0.0 0.0 0.0 0.0; 0.0 0.0 ε_i 0.0 0.0 0.0; 0.0 0.0 0.0 1.0 0.0 0.0; 0.0 0.0 0.0 0.0 1.0 0.0; 0.0 0.0 0.0 0.0 0.0 1.0 ] @test M1 == M1_true @test M2 == M2_true @test M3 == M3_true end @testset "construct_a" begin # Test orthorhombic crystal with principal axes # parallel to x, y, z. M is constant and diagonal. # The only nonzero coefficients are # a[3,5] = -ξ / M[3, 3] # a[6,2] = ξ / M[6, 6] # Berreman, Optics in Stratefied and Anisotropic Media, 1972 # DOI: 10.1364/JOSA.62.000502 ξ = 15.0 + 15im ε = Diagonal([1 + 1im, 1 + 1im, 1 + 1im]) μ = Diagonal([1 + 0im, 1 + 0im, 1 + 0im]) ε[3,3] = 3.0 + 0im μ[3,3] = 0.0 + 5im M = @MMatrix zeros(ComplexF64, 6, 6) M[1:3, 1:3] = ε M[4:6, 4:6] = μ a = TransferMatrix.construct_a(ξ, M) to_subtract = @MMatrix zeros(ComplexF64, 6, 6) to_subtract[3,5] = -5.0 - 5im to_subtract[6,2] = 3.0 - 3im b = a - to_subtract test_against = zeros(ComplexF64, 6, 6) @test isapprox(b, zeros(ComplexF64, 6, 6), atol=1e-15) end @testset "construct_Δ" begin # Continue the test from `construct_a`. # For an orthorhombic crystal described above, the only nonzero elements of Δ are # Δ[2,1] = M[1,1] = ε[1,1] # Δ[4,3] = M[2,2] - ξ^2 / M[6,6] = ε[2,2] - ξ^2 / μ[3,3] # Δ[3,4] = M[4,4] = μ[1,1] # Δ[1,2] = M[5,5] - ξ^2 / M[3,3] = μ[2,2] - ξ^2 / ε[3,3] ξ = 0. ε = Diagonal([1 + 1im, 1 + 1im, 1 + 1im]) μ = Diagonal([1 + 0im, 1 + 0im, 1 + 0im]) ε[3,3] = 3.0 + 0im μ[3,3] = 0.0 + 5im M = zeros(ComplexF64, 6, 6) M[1:3, 1:3] = ε M[4:6, 4:6] = μ a = TransferMatrix.construct_a(ξ, M) Δ = TransferMatrix.construct_Δ(ξ, M, a) Δ21 = ε[1,1] Δ43 = ε[2,2] - ξ^2 / μ[3,3] Δ34 = μ[1,1] Δ12 = μ[2,2] - ξ^2 / ε[3,3] Δ_squared = Diagonal([Δ12 * Δ21, Δ12 * Δ21, Δ34 * Δ43, Δ34 * Δ43]) Δ_cubed = Δ^3 @test Δ^2 == Δ_squared @test Δ_cubed[1,1] == 0.0 + 0im @test Δ_cubed[1,2] == Δ12^2 * Δ21 ξ = 1.0 + 1.0im M = rand(ComplexF64, 6, 6) a = rand(ComplexF64, 6, 6) Δ = TransferMatrix.construct_Δ(ξ, M, a) @test Δ[1,1] == M[5,1] + (M[5,3] + ξ) * a[3,1] + M[5,6] * a[6,1] @test Δ[1,2] == M[5,5] + (M[5,3] + ξ) * a[3,5] + M[5,6] * a[6,5] @test Δ[1,3] == M[5,2] + (M[5,3] + ξ) * a[3,2] + M[5,6] * a[6,2] @test Δ[1,4] == -M[5,4] - (M[5,3] + ξ) * a[3,4] - M[5,6] * a[6,4] @test Δ[2,1] == M[1,1] + M[1,3] * a[3,1] + M[1,6] * a[6,1] @test Δ[2,2] == M[1,5] + M[1,3] * a[3,5] + M[1,6] * a[6,5] @test Δ[2,3] == M[1,2] + M[1,3] * a[3,2] + M[1,6] * a[6,2] @test Δ[2,4] == -M[1,4] - M[1,3] * a[3,4] - M[1,6] * a[6,4] @test Δ[3,1] == -M[4,1] - M[4,3] * a[3,1] - M[4,6] * a[6,1] @test Δ[3,2] == -M[4,5] - M[4,3] * a[3,5] - M[4,6] * a[6,5] @test Δ[3,3] == -M[4,2] - M[4,3] * a[3,2] - M[4,6] * a[6,2] @test Δ[3,4] == M[4,4] + M[4,3] * a[3,4] + M[4,6] * a[6,4] @test Δ[4,1] == M[2,1] + M[2,3] * a[3,1] + (M[2,6] - ξ) * a[6,1] @test Δ[4,2] == M[2,5] + M[2,3] * a[3,5] + (M[2,6] - ξ) * a[6,5] @test Δ[4,3] == M[2,2] + M[2,3] * a[3,2] + (M[2,6] - ξ) * a[6,2] @test Δ[4,4] == -M[2,4] - M[2,3] * a[3,4] - (M[2,6] - ξ) * a[6,4] end @testset "calculate_γ" begin μ = 1.0 ξ1 = 0.0 ξ2 = 1.0 ξ3 = 1.0 + 1im ε1 = I ε2 = fill(1, (3, 3)) ε3 = [3 1 1 ; 1 2 1 ; 1 1 2] ε4 = [1 1 1 ; 1 1 1 ; 1 1 2] ε5 = [1 + 1im 1 1; 1 1 + 1im 1; 1 1 2 + 2im] q1 = [1., 1., 1., 1.] q2 = [1., 2., 1., 2.] q3 = [1. + 1im, 1. + 1im, 1. + 1im, 1. + 1im] q4 = [1. + 1im, 2. + 1im, 1. + 1im, 2. + 1im] γ1 = TransferMatrix.calculate_γ(ξ1, q1, ε1, μ) γ2 = TransferMatrix.calculate_γ(ξ1, q1, ε2, μ) γ3 = TransferMatrix.calculate_γ(ξ2, q2, ε3, μ) γ4 = TransferMatrix.calculate_γ(ξ2, q1, ε4, μ) γ5 = TransferMatrix.calculate_γ(ξ3, q3, ε5, μ) γ6 = TransferMatrix.calculate_γ(ξ3, q4, ε5, μ) γ1_test = ComplexF64[ 1 0 0; 0 1 0; -1 0 0; 0 1 0 ] γ2_test = ComplexF64[ 1 0 -1; 0 1 -1; -1 0 1; 0 1 -1 ] γ3_test = ComplexF64[ 1.0 -1.0 -1.0; -0.2 1.0 -0.4; -1.0 1.0 3.0; -0.2 1.0 -0.4 ] γ4_test = ComplexF64[ 1.0 0.0 -2.0; 0.0 1.0 -1.0; -1.0 0.0 2.0; 0.0 1.0 -1.0 ] γ5_test = ComplexF64[ 1.0 0.0 -0.5 - 1im; 0.0 1.0 -0.5; -1.0 0.0 0.5 + 1im; 0.0 1.0 -0.5 ] γ6_test = ComplexF64[ 1.0+0.0im -0.351351-0.108108im -0.324324-0.945946im -0.166154+0.00923077im 1.0+0.0im -0.32+0.24im -1.0+0.0im 0.351351+0.108108im 0.675676+1.05405im -0.166154+0.00923077im 1.0+0.0im -0.32+0.24im ] for m in 1:4 γ2_test[m, :] /= √(γ2_test[m, :] ⋅ γ2_test[m, :]') γ3_test[m, :] /= √(γ3_test[m, :] ⋅ γ3_test[m, :]') γ4_test[m, :] /= √(γ4_test[m, :] ⋅ γ4_test[m, :]') γ5_test[m, :] /= √(γ5_test[m, :] ⋅ γ5_test[m, :]') γ6_test[m, :] /= √(γ6_test[m, :] ⋅ γ6_test[m, :]') end @test γ1 == γ1_test @test γ2 == γ2_test @test isapprox(γ3, γ3_test) @test isapprox(γ4, γ4_test) @test isapprox(γ5, γ5_test) @test isapprox(γ6, γ6_test, atol=1e-5) end @testset "dynamical_matrix" begin γ = ComplexF64[ 11 12 13; 21 22 23; 31 32 33; 41 42 43] q = ComplexF64[1, 2, 3, 4] ξ = 1.0 + 1.0im μ = 2.0 A_test = ComplexF64[ 11 21 31 41 12 22 32 42 -2 - 13im 19 - 23im 60 - 33im 121 - 43im 12 44 96 168 ] A_test[3, :] ./= μ A_test[4, :] ./= μ A = TransferMatrix.dynamical_matrix(ξ, q, γ, μ) for (i, col) in enumerate(eachrow(A)) @test A[:, i] == A_test[:, i] end end @testset "propagation_matrix" begin q = [1., 2., 3., 4.] d = π / 2 ω = c_0 P_test = Diagonal([-1.0im, -1.0, 1.0im, 1.0]) P = TransferMatrix.propagation_matrix(ω, q) @test P(d) ≈ P_test end
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
1131
@testset "fresnel" begin n1 = 1.0 # air n2 = 1.5 # glass θ = 0.0 Rs, Rp = fresnel(θ, n1, n2) @test Rs ≈ Rp # expected reflectance for s-polarized light θ = π / 4 Rs, Rp = fresnel(θ, n1, n2) @test Rp ≈ Rs^2 # expected reflectance for s-polarized light # @test Rp ≈ 0.11 # expected reflectance for p-polarized light θ = π / 2 # 90 degrees Rs, Rp = fresnel(θ, n1, n2) @test Rs ≈ 1.0 # expected reflectance for s-polarized light at Brewster's angle @test Rp ≈ 1.0 # expected reflectance for p-polarized light at Brewster's angle end @testset "stopband" begin Δf = TransferMatrix.stopband(2.5, 1.5) * 630 # for 630 nm light @test isapprox(Δf, 202.685, atol = 1e-3) end @testset "dbr_reflectivity" begin no = 1.0 # air ns = 1.5 # glass n1 = 2.5 # TiO2 n2 = 1.5 # SiO2 r = dbr_reflectivity(no, ns, n1, n2, 3) @test isapprox(r, 0.883, atol = 1e-3) r = dbr_reflectivity(no, ns, n1, n2, 6) @test isapprox(r, 0.994, atol = 1e-3) r = dbr_reflectivity(no, ns, n1, n2, 9) @test isapprox(r, 0.999, atol = 1e-3) end
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
211
using Test using LinearAlgebra using RefractiveIndex using StaticArrays using TransferMatrix const c_0 = 299792458 include("functions.jl") include("layer.jl") include("types.jl") include("optics_functions.jl")
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
code
879
# Test types.jl @testset "Layer" begin n_au = RefractiveMaterial("main", "Au", "Rakic-LD") au = TransferMatrix.Layer(n_au, 10e-6) @test au.thickness ≈ 0.00001 @test real(au.dispersion(2.0)) == 0.777149018404908 @test imag(au.dispersion(2.0)) == 12.597128834355829 n_sio2 = RefractiveMaterial("main", "SiO2", "Malitson") @test isa(au, TransferMatrix.Layer) @test_throws DomainError TransferMatrix.Layer(n_sio2, -1.0) λs = [1.0, 2.0, 3.0] dispersion = [1.5, 2.0, 2.5] extinction = [0.5, 1.0, 1.5] thickness = 1.0 layer = TransferMatrix.Layer(λs, dispersion, extinction, thickness) @test isa(layer, TransferMatrix.Layer) @test layer.thickness == thickness @test layer.dispersion(1.0) == 1.5 + 0.5im @test layer.dispersion(2.0) == 2.0 + 1.0im @test layer.dispersion(3.0) == 2.5 + 1.5im end
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
docs
1056
Copyright (c) 2022: Garrek Stemo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
docs
806
# TransferMatrix.jl [![codecov](https://codecov.io/gh/garrekstemo/TransferMatrix.jl/graph/badge.svg?token=WO2ITE125C)](https://codecov.io/gh/garrekstemo/TransferMatrix.jl) [![CI](https://github.com/garrekstemo/TransferMatrix.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/garrekstemo/TransferMatrix.jl/actions/workflows/CI.yml) [![stable](https://img.shields.io/badge/docs-stable-blue)](https://garrek.org/TransferMatrix.jl/stable/) A general 4x4 transfer matrix method implementation for optical waves in layered media in Julia. ## Installation ``` julia>] pkg> add TransferMatrix ``` Start using TransferMatrix.jl ``` using TransferMatrix ``` ## Documentation For more details, including a comprehensive tutorial, see the [documentation website](https://garrek.org/TransferMatrix.jl).
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
docs
1523
# References All references used for writing TransferMatrix.jl. [1] N. C. Passler, M. Jeannin, and A. Paarmann, Layer-Resolved Absorption of Light in Arbitrarily Anisotropic Heterostructures, Phys. Rev. B 101, 165425 (2020). \ [2] B. Garibello, N. Avilán, J. A. Galvis, and C. A. Herreño-Fierro, On the Singularity of the Yeh 4 × 4 Transfer Matrix Formalism, Journal of Modern Optics 67, 832 (2020). \ [3] N. C. Passler and A. Paarmann, Generalized 4 × 4 Matrix Formalism for Light Propagation in Anisotropic Stratified Media: Study of Surface Phonon Polaritons in Polar Dielectric Heterostructures: Erratum, J. Opt. Soc. Am. B 36, 3246 (2019). \ [4] N. C. Passler and A. Paarmann, Generalized 4 × 4 Matrix Formalism for Light Propagation in Anisotropic Stratified Media: Study of Surface Phonon Polaritons in Polar Dielectric Heterostructures, J. Opt. Soc. Am. B 34, 2128 (2017). \ [5] P. Yeh, Optical Waves in Layered Media (Wiley, 2005). \ [6] W. Xu, L. T. Wood, and T. D. Golding, Optical Degeneracies in Anisotropic Layered Media: Treatment of Singularities in a 4×4 Matrix Formalism, Phys. Rev. B 61, 1740 (2000). \ [7] Z.-M. Li, B. T. Sullivan, and R. R. Parsons, Use of the 4 × 4 Matrix Method in the Optics of Multilayer Magnetooptic Recording Media, Appl. Opt., AO 27, 1334 (1988). \ [8] P. Yeh, Electromagnetic Propagation in Birefringent Layered Media, J. Opt. Soc. Am. 69, 742 (1979). \ [9] D. W. Berreman, Optics in Stratified and Anisotropic Media: 4×4-Matrix Formulation, J. Opt. Soc. Am. 62, 502 (1972).
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
docs
2398
# TransferMatrix.jl TransferMatrix.jl provides a general 4x4 transfer matrix method for optical waves propagating in layered media implemented in Julia. The core is an electrodynamics simulation based on Pochi Yeh's 4x4 transfer matrix method. Recent corrections and improvements are incorporated to deal with singularities and numerical instabilities for some types of multi-layered structures. The algorithms implemented are based on the efforts of others and sources are cited both in the documentation and docstrings where appropriate. A comprehensive [bibliography](https://garrek.org/TransferMatrix.jl/stable/bibliography/) is also available as part of the documentation. ## Why make another transfer matrix program? There are a lot of transfer matrix programs out there. Many are proprietary and some are part of graduate theses. The problem with the proprietary ones are that the source code cannot be examined nor modified (and are not free). The problem with programs written for papers are that they are rarely maintained, are not well documented, are not well tested, and are poorly organized. This makes it very difficult to use them. TransferMatrix.jl solves these problems and provides the first generalized 4x4 transfer matrix algorithm available for Julia. ## API Only exported (i.e. can be used without the `TransferMatrix.` qualifier after loading the TransferMatrix.jl package with `using TransferMatrix`) types and functions are considered part of the public API of the TransferMatrix.jl package. All of these objects are documented in this manual. If not, please [open an issue](https://github.com/garrekstemo/TransferMatrix.jl/issues/new). The advanced user is encouraged, however, to access the guts of TransferMatrix.jl and modify portions to achieve a desired outcome or test a different approach to the algorithm. This implementation is as modular as possible to maximize flexibility; each function is as small as possible so that the user may easily change any step along the way in calculating the transfer matrix, reflection or transmission spectra, electric field profile, etc. ## Issues and contributions If you spot any errors or improvements to make, please [open an issue](https://github.com/garrekstemo/TransferMatrix.jl/issues/new) and if you want to contribute consider making a [pull request](https://github.com/garrekstemo/TransferMatrix.jl/pulls).
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
docs
2366
# Quick Start If you just want to get started with a transfer matrix calculation and plot the transmittance or reflectance spectrum, this is the place to start. First install TransferMatrix.jl by typing `]` from the Julia REPL to enter package mode, then enter ``` pkg> add TransferMatrix ``` ## Quarter-wave mirror Let's make a simple quarter-wave mirror, or [distributed bragg reflector](https://en.wikipedia.org/wiki/Distributed_Bragg_reflector) (DBR). We will do this via alternating layers of titanium dioxide (n = 2.13) and silica (n = 1.46) optimized for a wavelength of 630 nm. We'll make three periods of these two layers and and layer of air. This 4x4 transfer matrix method simultaneously calculates the transmittance and reflectance for s-polarized and p-polarized radiation. (We are using the powerful plotting library [Makie.jl](https://makie.juliaplots.org/) to produce the figures.) ```@example dbr using TransferMatrix using CairoMakie using RefractiveIndex n_air = RefractiveMaterial("other", "air", "Ciddor") n_tio2 = RefractiveMaterial("main", "TiO2", "Sarkar") n_sio2 = RefractiveMaterial("main", "SiO2", "Rodriguez-de_Marcos") λ_0 = 0.63 # μm t_tio2 = λ_0 / (4 * n_tio2(λ_0)) t_sio2 = λ_0 / (4 * n_sio2(λ_0)) air = Layer(n_air, 0.1) tio2 = Layer(n_tio2, t_tio2) sio2 = Layer(n_sio2, t_sio2) layers = [air, tio2, sio2, tio2, sio2, tio2, sio2] λs = 0.4:0.002:1.0 Rpp = Float64[] for λ in λs Tpp_, Tss_, Rpp_, Rss_ = calculate_tr(λ, layers) push!(Rpp, Rpp_) end fig, ax, l = lines(λs .* 1e3, Rpp) ax.xlabel = "Wavelength (nm)" ax.ylabel = "Reflectance" fig ``` Now let's try a few more periods and plot them all together to see how the reflectance changes with increasing number of layers. Notice that we are adding new layers directly to the structure and not creating a new structure. ```@example dbr nperiods = 6 for i in 1:nperiods push!(layers, tio2) push!(layers, sio2) Rpp = Float64[] if i%3 == 0 for λ in λs Tpp_, Tss_, Rpp_, Rss_ = calculate_tr(λ, layers) push!(Rpp, Rpp_) end lines!(ax, λs .* 1e3, Rpp, label = "$(i + 3) periods") end end axislegend(ax) fig ``` You can see that it's quite simple to make a structure and modify the layers. Note that while an individual `Layer` is immutable, you can modify the properties of a `Structure`.
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
docs
4666
# Tutorial ## Installation TransferMatrix.jl is a part of Julia's general registry and the source code can be found at <https://github.com/garrekstemo/TransferMatrix.jl>. From the [Julia REPL](https://docs.julialang.org/en/v1/stdlib/REPL/), enter the package manager mode mode by typing `]`. Then just enter the following to install the package: ``` pkg> add TransferMatrix ``` ## A simple calculation To get you up and running, let's build a simple two-layer structure of air and glass and calculate the reflectance and transmittance to visualize the [Brewster angle](https://en.wikipedia.org/wiki/Brewster%27s_angle) for p-polarized light. We fix the wavelength of incident light and vary the angle of incidence. We start by making a `Layer` of air and a `Layer` of glass. We'll do this for a wavelength of 1 μm. Since there are only two layers and the transfer matrix method treats the first and last layers as semi-infinite, there is no need to provide a thickness for our glass and air layers. From the examples below, you can see that there are fields for - the material - the layer thickness The material is a `RefractiveMaterial` from the RefractiveIndex.jl package. You can also initize a `Layer` with data for the refractive index and extinction coefficient. ```@example tutorial using TransferMatrix using RefractiveIndex n_air = RefractiveMaterial("other", "air", "Ciddor") n_glass = RefractiveMaterial("glass", "BK7", "SCHOTT")[1] air = Layer(n_air, 0.1) glass = Layer(n_glass, 0.1) layers = [air, glass] ``` Now that we have our glass and air layers, we can iterate over the angles of incidence and compute the reflectance and transmittance for light of wavelength 1 μm. ```@example tutorial λ = 1.0 θs = 0.0:1:85.0 result = angle_resolved([λ], deg2rad.(θs), layers) ``` Let's now plot the result using the [Makie.jl](https://makie.juliaplots.org/) data visualization package. ```@example tutorial using CairoMakie brewster = atan(n_glass(λ)) * 180 / π fig = Figure() ax = Axis(fig[1, 1], xlabel = "Incidence Angle (°)", ylabel = "Reflectance / Transmittance") lines!(θs, result.Tss[:, 1], label = "Ts", color = :firebrick3) lines!(θs, result.Tpp[:, 1], label = "Tp", color = :orangered3) lines!(θs, result.Rss[:, 1], label = "Rs", color = :dodgerblue4) lines!(θs, result.Rpp[:, 1], label = "Rp", color = :dodgerblue1) vlines!(ax, brewster, color = :black, linestyle = :dash) text!("Brewster angle\n(Rp = 0)", position = (35, 0.6)) axislegend(ax) fig ``` We can see that the result of the angle-resolved calculation has four solutions: the s-wave and p-wave for both the reflected and transmitted waves. And we see that the Brewster angle is ``\arctan\left( n_\text{glass} /n_\text{air} \right) \approx 56^{\circ}``, as expected. Simultaneous calculation of s- and p-polarized incident waves is a feature of the general 4x4 transfer matrix method being used. The `angle_resolved` function will also loop through all wavelengths so that you can plot a color plot of wavelength and angle versus transmittance (or reflectance). ## A simple multi-layered structure Now that we can make `Layer`s, we can put them together to calculate the transfer matrix for a multi-layered structure and plot the reflectance and transmittance spectra. An important structure in optics is the Fabry-Pérot etalon, made with two parallel planar mirrors with a gap between them. If we set the optical path length to be an integer multiple of half the wavelength, we get constructive interference and a resonance in the transmittance spectrum. In the frequency domain, the cavity modes are evenly spaced by the free spectral range (FSR). We will scan in the mid infrared between 4 and 6 μm and use data generated via the [Lorentz-Drude model](https://en.wikipedia.org/wiki/Lorentz_oscillator_model) for each 10 nm-thick gold mirror. (Note that we stay in units of micrometers for the wavelength.) ```@example tutorial caf2 = RefractiveMaterial("main", "CaF2", "Malitson") au = RefractiveMaterial("main", "Au", "Rakic-LD") air = RefractiveMaterial("other", "air", "Ciddor") λ_0 = 5.0 t_middle = λ_0 / 2 layers = [Layer(air, 8.0), Layer(au, 0.01), Layer(air, t_middle), Layer(au, 0.01), Layer(air, 8.0)]; λs = range(2.0, 6.0, length = 500) frequencies = 10^4 ./ λs Tp = Float64[] Ts = Float64[] Rp = Float64[] Rs = Float64[] for λ in λs Tp_, Ts_, Rp_, Rs_ = calculate_tr(λ, layers) push!(Tp, Tp_) push!(Ts, Ts_) push!(Rp, Rp_) push!(Rs, Rs_) end fig, ax, l = lines(frequencies, Ts) ax.xlabel = "Frequency (cm⁻¹)" ax.ylabel = "Transmittance" fig ``` More examples are available in the examples folder of the package source code.
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
docs
464
# Internals These functions are not exported by the TransferMatrix.jl module and can be called using the `TransferMatrix.` qualifier. Use these methods if you wish to construct a transfer matrix method manually step by step or modify intermediate steps. ## Index ```@index Pages = ["internals.md"] ``` ## General Transfer Matrix Method ```@autodocs Modules = [TransferMatrix] Pages = ["general_TMM.jl", "layer.jl", "matrix_constructors.jl"] Public = false ```
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
2.0.0
fab68c794b9f7cc96e3a83e28d2934492e92010f
docs
540
# Public Documentation These functions and types are to be used for transfer matrix calculation based on the sources used. If you wish to modify any of the steps in the calculation, refer to the private API. ## Index ```@index Pages = ["public.md"] ``` ## Transfer Matrix Functions ```@autodocs Modules = [TransferMatrix] Pages = ["general_TMM.jl", "layer.jl", "matrix_constructors.jl"] Private = false ``` ## Miscellaneous Optics Functions ```@autodocs Modules = [TransferMatrix] Pages = ["optics_functions.jl"] Private = false ```
TransferMatrix
https://github.com/garrekstemo/TransferMatrix.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
3812
using BenchmarkTools, PhyloNetworks, DataFrames, Logging #suppresses @warn and @info for benchmarks logger = SimpleLogger(stderr, Logging.Error); old_logger = global_logger(logger); # Define a parent BenchmarkGroup to contain our SUITE const SUITE = BenchmarkGroup() SUITE["nasm"] = BenchmarkGroup(["JC69", "HKY85"]) SUITE["fitDiscreteFixed"] = BenchmarkGroup(["ERSM", "BTSM", "JC69", "HKY85"]) SUITE["fitdiscrete"] = BenchmarkGroup(["ERSM", "BTSM", "JC69", "HKY85"]) # Add benchmarks to nasm group SUITE["nasm"]["JC69"] = @benchmarkable JC69([0.5]) m1 = HKY85([.5], [0.25, 0.25, 0.25, 0.25]); SUITE["nasm"]["HKY85"] = @benchmarkable P!(P(m1, 1.0), m1, 3.0) # fitDiscreteFixed benchmarks net_dat = readTopology("(((A:2.0,(B:1.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5,D:2.0);") species_alone = ["C","A","B","D"] dat_alone = DataFrame(trait=["hi","lo","lo","hi"]) SUITE["fitDiscreteFixed"]["ERSM"] = @benchmarkable fitdiscrete(net_dat, :ERSM, species_alone, dat_alone; optimizeQ=false, optimizeRVAS=false) SUITE["fitDiscreteFixed"]["BTSM"] = @benchmarkable fitdiscrete(net_dat, :BTSM, species_alone, dat_alone; optimizeQ=false, optimizeRVAS=false) fastafile = joinpath(@__DIR__, "..", "examples", "Ae_bicornis_Tr406_Contig10132.aln") dna_dat, dna_weights = readfastatodna(fastafile, true); net_dna = readTopology("((((((((((((((Ae_caudata_Tr275,Ae_caudata_Tr276),Ae_caudata_Tr139))#H1,#H2),(((Ae_umbellulata_Tr266,Ae_umbellulata_Tr257),Ae_umbellulata_Tr268),#H1)),((Ae_comosa_Tr271,Ae_comosa_Tr272),(((Ae_uniaristata_Tr403,Ae_uniaristata_Tr357),Ae_uniaristata_Tr402),Ae_uniaristata_Tr404))),(((Ae_tauschii_Tr352,Ae_tauschii_Tr351),(Ae_tauschii_Tr180,Ae_tauschii_Tr125)),(((((((Ae_longissima_Tr241,Ae_longissima_Tr242),Ae_longissima_Tr355),(Ae_sharonensis_Tr265,Ae_sharonensis_Tr264)),((Ae_bicornis_Tr408,Ae_bicornis_Tr407),Ae_bicornis_Tr406)),((Ae_searsii_Tr164,Ae_searsii_Tr165),Ae_searsii_Tr161)))#H2,#H4))),(((T_boeoticum_TS8,(T_boeoticum_TS10,T_boeoticum_TS3)),T_boeoticum_TS4),((T_urartu_Tr315,T_urartu_Tr232),(T_urartu_Tr317,T_urartu_Tr309)))),(((((Ae_speltoides_Tr320,Ae_speltoides_Tr323),Ae_speltoides_Tr223),Ae_speltoides_Tr251))H3,((((Ae_mutica_Tr237,Ae_mutica_Tr329),Ae_mutica_Tr244),Ae_mutica_Tr332))#H4))),Ta_caputMedusae_TB2),S_vavilovii_Tr279),Er_bonaepartis_TB1),H_vulgare_HVens23);"); for edge in net_dna.edge #adds branch lengths setLength!(edge,1.0) if edge.gamma < 0 setGamma!(edge, 0.5) end end SUITE["fitDiscreteFixed"]["JC69"] = @benchmarkable fitdiscrete(net_dna, :JC69, dna_dat, dna_weights; optimizeQ=false, optimizeRVAS=false) SUITE["fitDiscreteFixed"]["HKY85"] = @benchmarkable fitdiscrete(net_dna, :HKY85, dna_dat, dna_weights; optimizeQ=false, optimizeRVAS=false) ## fitdiscrete benchmarks SUITE["fitdiscrete"]["ERSM"] = @benchmarkable fitdiscrete(net_dat, :ERSM, species_alone, dat_alone; optimizeQ=true, optimizeRVAS=true) SUITE["fitdiscrete"]["BTSM"] = @benchmarkable fitdiscrete(net_dat, :BTSM, species_alone, dat_alone; optimizeQ=true, optimizeRVAS=true) SUITE["fitdiscrete"]["JC69"] = @benchmarkable fitdiscrete(net_dna, :JC69, dna_dat, dna_weights; optimizeQ=true, optimizeRVAS=true) SUITE["fitdiscrete"]["HKY85"] = @benchmarkable fitdiscrete(net_dna, :HKY85, dna_dat, dna_weights; optimizeQ=true, optimizeRVAS=true) # If a cache of tuned parameters already exists, use it, otherwise, tune and cache # the benchmark parameters. Reusing cached parameters is faster and more reliable # than re-tuning `SUITE` every time the file is included. paramspath = joinpath(dirname(@__FILE__), "params.json") if isfile(paramspath) loadparams!(SUITE, BenchmarkTools.load(paramspath)[1], :evals); else tune!(SUITE) BenchmarkTools.save(paramspath, params(SUITE)); end global_logger(old_logger) #restores typical logging at end of benchmarks
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
184
using Pkg Pkg.activate("/Users/cora/.julia/environments/net") #sets up development environment using PkgBenchmark using BenchmarkTools using PhyloNetworks benchmarkpkg("PhyloNetworks")
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
2255
using Documenter using Pkg Pkg.add(PackageSpec(name="PhyloPlots", rev="master")) using PhyloNetworks DocMeta.setdocmeta!(PhyloNetworks, :DocTestSetup, :(using PhyloNetworks); recursive=true) using PhyloPlots # to trigger any precompilation warning outside jldoctests makedocs( sitename = "PhyloNetworks.jl", authors = "Claudia Solís-Lemus, Cécile Ané, Paul Bastide and contributors.", modules = [PhyloNetworks], # to list methods from PhyloNetworks only, not from Base etc. format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true", # easier local build size_threshold = 600 * 2^10, size_threshold_warn = 500 * 2^10, # 600 KiB canonical="https://crsl4.github.io/PhyloNetworks.jl/stable/", edit_link="master", ), # exception, so warning-only for :missing_docs. List all others: warnonly = Documenter.except(:autodocs_block, :cross_references, :docs_block, :doctest, :eval_block, :example_block, :footnote, :linkcheck_remotes, :linkcheck, :meta_block, :parse_error, :setup_block), pages = [ "Home" => "index.md", "Manual" => [ "Installation" => "man/installation.md", "Network manipulation" => "man/netmanipulation.md", "Input Data for SNaQ" => "man/inputdata.md", "TICR pipeline" => "man/ticr_howtogetQuartetCFs.md", "Network estimation and display" => "man/snaq_plot.md", "Network comparison and manipulation" => "man/dist_reroot.md", "Candidate Networks" => "man/fixednetworkoptim.md", "Extract Expected CFs" => "man/expectedCFs.md", "Bootstrap" => "man/bootstrap.md", "Multiple Alleles" => "man/multiplealleles.md", "Continuous Trait Evolution" => "man/trait_tree.md", "Parsimony on networks" => "man/parsimony.md", "Discrete Trait Evolution" => "man/fitDiscrete.md", "Neighbour Joining" => "man/nj.md", ], "Library" => [ "Public" => "lib/public.md", "Internals" => "lib/internals.md", ] ], ) deploydocs( repo = "github.com/crsl4/PhyloNetworks.jl.git", push_preview = true, devbranch = "master", )
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
1514
# example "Case f" (plot in ipad) # this is the bad diamond case # Claudia August 2014 # # in julia: include("case_f_example.jl") ed1=Edge(1,0.6,true,0.7); ed2=Edge(2,0.7,true,0.3); ed3=Edge(3,0.9); ed4=Edge(4,0.1); ed5=Edge(5,0.2); ed6=Edge(6,0.1); ed7=Edge(7,0.1); ed8=Edge(8,0.1); ed9=Edge(9,0.1); ed10=Edge(10,0.1); n1=Node(1,false,false,[ed1,ed5,ed6]); n2=Node(2,false,true,[ed1,ed2,ed3]); n3=Node(3,false,false,[ed2,ed4,ed7]); n4=Node(4,true,false,[ed3]); n5=Node(5,false,false,[ed4,ed5,ed9]); n6=Node(6,true, false,[ed6]); n7=Node(7,true, false,[ed7]); n8=Node(8,true, false,[ed8]); n9=Node(9,false,false,[ed8,ed9,ed10]); n10=Node(10,true, false,[ed10]); setNode!(ed1,n1) setNode!(ed1,n2) setNode!(ed2,n2); setNode!(ed2,n3); setNode!(ed5,[n5,n1]); setNode!(ed4,[n3,n5]); setNode!(ed3,n2); setNode!(ed3,n4); setNode!(ed6,[n1,n6]); setNode!(ed7,[n3,n7]); setNode!(ed8,[n8,n9]); setNode!(ed9,[n5,n9]); setNode!(ed10,[n9,n10]); #ed1.inCycle=2; #ed2.inCycle=2; #ed4.inCycle=2; #ed5.inCycle=2; net=HybridNetwork([n1,n2,n3,n4,n5,n6,n7,n8,n9,n10],[ed1,ed2,ed3,ed4,ed5,ed6,ed7,ed8,ed9,ed10]); node=searchHybridNode(net); n2.name = "H1"; n4.name = "4"; n6.name = "6"; n7.name = "7"; n8.name = "8"; n10.name = "10" net.names=["1","2","3","4","5","6","7","8","9","10"] flag, nocycle,edges, nodes = updateInCycle!(net,node[1]); flag2, edges2 = updateContainRoot!(net,node[1]); flag3, edges3 = updateGammaz!(net,node[1]); #printEdges(net) #deleteHybrid!(node[1],net,false) #changeDirectionUpdate!(node[1],net);
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
241
# Case G example # Claudia December 2014 tree = "((((6:0.1,4:1.5)1:0.2,(7)11#H1)5:0.1,(11#H1,8)),10:0.1);" # Case G #f = open("prueba_tree.txt","w") #write(f,tree) #close(f) net = readTopologyLevel1(tree) #printEdges(net) #printNodes(net)
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
243
# Case I example: Bad diamond II # Claudia January 2015 tree = "((((8,10))#H1,7),6,(4,#H1));" # Case I Bad diamond II #f = open("prueba_tree.txt","w") #write(f,tree) #close(f) net = readTopologyLevel1(tree) #printEdges(net) #printNodes(net)
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
5791
__precompile__() module PhyloNetworks # stdlib (standard libraries) using Dates using Distributed using LinearAlgebra: diag, I, logdet, norm, LowerTriangular, mul!, lmul!, rmul!, Diagonal, cholesky, qr, BLAS # alternative: drop support for julia v1.4, because LinearAlgebra.rotate! requires julia v1.5 # using LinearAlgebra # bring all of LinearAlgebra into scope # import LinearAlgebra.rotate! # allow re-definition of rotate! using Printf: @printf, @sprintf using Random using Statistics: mean, quantile, median # other libraries, indicate compatible version in Project.toml using BioSequences using BioSymbols using Combinatorics: combinations using CSV using DataFrames # innerjoin new in v0.21 using DataStructures # for updateInCycle with priority queue using Distributions #for RateVariationAcrossSites using FASTX using Functors: fmap using GLM # for the lm function using NLopt # for branch lengths optimization using StaticArrays using StatsBase # sample, coef etc. using StatsFuns # logsumexp, logaddexp, log2π, various cdf using StatsModels # re-exported by GLM. for ModelFrame ModelMatrix Formula etc import Base: show import GLM: ftest import StatsModels: coefnames const DEBUGC = false # even more debug messages global CHECKNET = false # for debugging only export ftest export ## Network Definition HybridNetwork, DataCF, Quartet, readTopology, readTopologyLevel1, tipLabels, writeTopology, writeSubTree!, hybridlambdaformat, deleteleaf!, deleteaboveLSA!, removedegree2nodes!, shrink2cycles!, shrink3cycles!, printEdges, printNodes, sorttaxa!, ## SNAQ readTrees2CF, countquartetsintrees, readTableCF, readTableCF!, writeTableCF, mapAllelesCFtable, readInputTrees, readnexus_treeblock, summarizeDataCF, snaq!, readSnaqNetwork, topologyMaxQPseudolik!, topologyQPseudolik!, ## getters # fixit: add ancestors? getsibling? getdescendants (currently descendants)? getroot, isrootof, isleaf, isexternal, isparentof, ischildof, hassinglechild, getchild, getchildren, getchildedge, getparent, getparents, getparentminor, getparentedge, getparentedgeminor, getpartneredge, ## Network Manipulation rootatnode!, rootonedge!, directEdges!, preorder!, cladewiseorder!, fittedQuartetCF, rotate!, setLength!, setGamma!, deleteHybridThreshold!, displayedTrees, majorTree, minorTreeAt, displayedNetworkAt!, hardwiredClusters, hardwiredCluster, hardwiredCluster!, hardwiredClusterDistance, biconnectedComponents, blobDecomposition!, blobDecomposition, nni!, checkroot!, treeedgecomponents, ## Network Bootstrap treeEdgesBootstrap, hybridDetection, summarizeHFdf, hybridBootstrapSupport, bootsnaq, readBootstrapTrees, writeMultiTopology, readMultiTopologyLevel1, readMultiTopology, hybridatnode!, undirectedOtherNetworks, ## Network Calibration getNodeAges, pairwiseTaxonDistanceMatrix, calibrateFromPairwiseDistances!, ## Network PCM phylolm, PhyloNetworkLinearModel, simulate, TraitSimulation, ParamsBM, ParamsMultiBM, ShiftNet, shiftHybrid, getShiftEdgeNumber, getShiftValue, sharedPathMatrix, descendenceMatrix, regressorShift, regressorHybrid, ancestralStateReconstruction, ReconstructedStates, sigma2_phylo, sigma2_within, mu_phylo, lambda_estim, expectations, expectationsPlot, predint, predintPlot, vcv, ## Discrete Trait PCM parsimonySoftwired, parsimonyGF, maxParsimonyNet, TraitSubstitutionModel, EqualRatesSubstitutionModel, BinaryTraitSubstitutionModel, TwoBinaryTraitSubstitutionModel, JC69, HKY85, nstates, Q, getlabels, nparams, RateVariationAcrossSites, randomTrait, randomTrait!, fitdiscrete, readfastatodna, stationary, empiricalDNAfrequencies, # phyLiNC, # neighbor joining nj include("types.jl") include("nloptsummary.jl") include("auxiliary.jl") include("generate_topology.jl") include("update.jl") include("undo.jl") include("addHybrid_snaq.jl") include("addHybrid.jl") include("deleteHybrid.jl") include("moves_snaq.jl") include("moves_semidirected.jl") include("readwrite.jl") include("readData.jl") include("snaq_optimization.jl") include("pseudolik.jl") include("descriptive.jl") include("manipulateNet.jl") include("bootstrap.jl") include("multipleAlleles.jl") include("compareNetworks.jl") include("traits.jl") include("parsimony.jl") include("pairwiseDistanceLS.jl") include("interop.jl") include("substitutionModels.jl") include("graph_components.jl") include("traitsLikDiscrete.jl") include("deprecated.jl") include("nj.jl") include("phyLiNCoptimization.jl") end #module
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
10998
# functions to add hybridizations to a semi-directed network # subject to topological constraints; no level restriction """ addhybridedge!(net::HybridNetwork, nohybridladder::Bool, no3cycle::Bool, constraints=TopologyConstraint[]::Vector{TopologyConstraint}; maxattempts=10::Int, fixroot=false::Bool) Randomly choose two edges in `net` then: add hybrid edge from edge 1 to edge 2 of length 0.01. The two halves of edge 1 (and of edge 2) have equal lengths. The hybrid partner edge (top half of edge 2, if fixroot is true) will point towards the newly-created node on the middle of the original edge 2. If the resulting network is a DAG, satisfies the constraint(s), does not contain any 3-cycle (if `no3cycle=true`), and does not have a hybrid ladder (if `nohybridladder=true`) then the proposal is successful: `net` is modified, and the function returns the newly created hybrid node and newly created hybrid edge. If the resulting network is not acceptable, then a new set of edges is proposed (using a blacklist) until one is found acceptable, or until a maximum number of attempts have been made (`maxattempts`). If none of the attempted proposals are successful, `nothing` is returned (without causing an error). After a pair of edges is picked, the "top" half of edge2 is proposed as the partner hybrid edge with probability 0.8 if `fixroot` is false, (to avoid changing the direction of edge2 with more than 50% chance) and with probability 1.0 if `fixroot` is true. If this choice does not work and if `fixroot` is false, the other half of edge2 is proposed as the partner hybrid edge. Note that choosing the "bottom" half of edge2 as the partner edge requires to flip the direction of edge 2, and to move the root accordingly (to the original child of edge2). # examples ```jldoctest julia> net = readTopology("((S1,(((S2,(S3)#H1),(#H1,S4)))#H2),(#H2,S5));"); julia> using Random julia> Random.seed!(170); julia> PhyloNetworks.addhybridedge!(net, true, true) (PhyloNetworks.Node: number:9 name:H3 hybrid node attached to 3 edges, numbered: 5 16 17 , PhyloNetworks.EdgeT{PhyloNetworks.Node}: number:17 length:0.01 minor hybrid edge with gamma=0.32771460911632916 attached to 2 node(s) (parent first): 8 9 ) julia> writeTopology(net, round=true, digits=2) "((S1,(((#H1,S4),((S2,(S3)#H1))#H3:::0.67))#H2),((#H2,S5),#H3:0.01::0.33));" ``` """ function addhybridedge!(net::HybridNetwork, nohybridladder::Bool, no3cycle::Bool, constraints=TopologyConstraint[]::Vector{TopologyConstraint}; maxattempts=10::Int, fixroot=false::Bool) all(con.type == 1 for con in constraints) || error("only type-1 constraints implemented so far") numedges = length(net.edge) blacklist = Set{Tuple{Int,Int}}() nmax_blacklist = numedges * (numedges-1) # all sets of edge1 -> edge2 nattempts = 0 while nattempts < maxattempts && length(blacklist) < nmax_blacklist e1 = Random.rand(1:numedges) # presumably faster than Random.randperm or Random.shuffle edge1 = net.edge[e1] e2 = Random.rand(1:(numedges-1)) # e2 must be different from e1: only numedges-1 options edge2 = net.edge[(e2<e1 ? e2 : e2+1)] (e1,e2) ∉ blacklist || # try another pair without adding to the # of attempts continue # if (e1,e2) was already attempted nattempts += 1 ## check that constraints are met p1 = getparent(edge1) p2 = getparent(edge2) constraintsmet = true for con in constraints if con.type == 1 # forbid going out of (edge1) or into (edge2) the species group if con.node === p1 || con.node === p2 push!(blacklist, (e1,e2)) constraintsmet = false break # of constraint loop end end end constraintsmet || continue # try another pair if constraints not met ## check for no 3-cycle, if no3cycle is requested if no3cycle && hybrid3cycle(edge1, edge2) # does not depend on which partner edge is chosen push!(blacklist, (e1,e2)) continue end ## check for no hybrid ladder, if requested: # edge2 cannot be a hybrid edge or the child of a hybrid node if nohybridladder && (edge2.hybrid || getparent(edge2).hybrid) push!(blacklist, (e1,e2)) continue end hybridpartnernew = (fixroot ? true : rand() > 0.2) # if true: partner hybrid = new edge above edge 2 ## check that the new network will be a DAG: no directional conflict if directionalconflict(p1, edge2, hybridpartnernew) if fixroot # don't try to change the direction of edge2 push!(blacklist, (e1,e2)) continue end # else: try harder: change direction of edge2 and move root hybridpartnernew = !hybridpartnernew # try again with opposite if directionalconflict(p1, edge2, hybridpartnernew) push!(blacklist, (e1,e2)) continue end # else: switching hybridpartnernew worked end newgamma = rand()*0.5; # in (0,.5) to create a minor hybrid edge return addhybridedge!(net, edge1, edge2, hybridpartnernew, 0.01, newgamma) end # if we get here: none of the max number of attempts worked - return nothing. # if an attempt had worked, we would have returned something. return nothing end """ addhybridedge!(net::HybridNetwork, edge1::Edge, edge2::Edge, hybridpartnernew::Bool, edgelength=-1.0::Float64, gamma=-1.0::Float64) Add hybridization to `net` coming from `edge1` going into `edge2`. 2 new nodes and 3 new edges are created: `edge1` are `edge2` are both cut into 2 edges, and a new edge is created linking the 2 new "middle" nodes, pointing from `edge1` to `edge2`. The new node in the middle of `edge1` is a tree node. The new node in the middle of `edge2` is a hybrid node. Its parent edges are the newly created hybrid edge (with γ = gamma, missing by default), and either the newly edge "above" `edge2` if `hybridpartnernew=true`, or the old `edge2` otherwise (which would reverse the direction of `edge2` and others). Should be called from the other method, which performs a bunch of checks. Updates `containRoot` attributes for edges below the new hybrid node. Output: new hybrid node (middle of the old `edge2`) and new hybrid edge. # examples ```jldoctest julia> net = readTopology("((S8,(((S1,(S5)#H1),(#H1,S6)))#H2),(#H2,S10));"); julia> hybnode, hybedge = PhyloNetworks.addhybridedge!(net, net.edge[13], net.edge[8], true, 0.0, 0.2) (PhyloNetworks.Node: number:9 name:H3 hybrid node attached to 3 edges, numbered: 8 16 17 , PhyloNetworks.EdgeT{PhyloNetworks.Node}: number:17 length:0.0 minor hybrid edge with gamma=0.2 attached to 2 node(s) (parent first): 8 9 ) julia> writeTopology(net) "((S8,(((S1,(S5)#H1),((#H1,S6))#H3:::0.8))#H2),(#H2,(S10,#H3:0.0::0.2)));" ``` """ function addhybridedge!(net::HybridNetwork, edge1::Edge, edge2::Edge, hybridpartnernew::Bool, edgelength::Float64=-1.0, gamma::Float64=-1.0) gamma == -1.0 || (gamma <= 1.0 && gamma >= 0.0) || error("invalid γ to add a hybrid edge") gbar = (gamma == -1.0 ? -1.0 : 1.0 - gamma) # 1-gamma, with γ=-1 as missing newnode1_tree, edgeabovee1 = breakedge!(edge1, net) # new tree node newnode2_hybrid, edgeabovee2 = breakedge!(edge2, net) # new hybrid node newnode2_hybrid.hybrid = true pushHybrid!(net, newnode2_hybrid) # updates net.hybrid and net.numHybrids # new hybrid edge, minor if γ missing (-1) hybrid_edge = Edge(maximum(e.number for e in net.edge) + 1, edgelength, true, gamma, gamma>0.5) # number, length, hybrid, gamma, isMajor # partner edge: update hybrid status, γ and direction if hybridpartnernew edgeabovee2.hybrid = true edgeabovee2.gamma = gbar if gamma>0.5 edgeabovee2.isMajor = false end else c2 = getchild(edge2) # child of edge2 before we switch its direction i2 = findfirst(isequal(c2), net.node) net.root = i2 # makes c2 the new root node edge2.hybrid = true edge2.gamma = gbar if gamma>0.5 edge2.isMajor = false end edge2.isChild1 = !edge2.isChild1 # reverse the direction of edge2 edgeabovee2.isChild1 = !edgeabovee2.isChild1 end # parse hyb names to find the next available. assignhybridnames! would do them all rx = r"^H(\d+)$" hnum = net.numHybrids # to name the new hybrid, potentially for n in net.node m = match(rx, n.name) if m !== nothing hi = parse(Int, m[1]) hnum > hi || (hnum = hi+1) end end newnode2_hybrid.name = "H$hnum" setNode!(hybrid_edge, [newnode2_hybrid, newnode1_tree]) # [child node, parent node] to match isChild1=true setEdge!(newnode1_tree, hybrid_edge) setEdge!(newnode2_hybrid, hybrid_edge) pushEdge!(net, hybrid_edge) if hybridpartnernew # @debug "triple-check it's a DAG" directEdges!(net) norootbelow!(edge2) else directEdges!(net) norootbelow!(edgeabovee2) end return newnode2_hybrid, hybrid_edge end """ hybrid3cycle(edge1::Edge, edge2::Edge) Check if proposed hybrid edge from `edge1` into `edge2` would create a 3 cycle, that is, if `edge1` and `edge2` have a node in common. (This move cannot create a 2-cycles because new nodes would be created in the middle of edges 1 and 2.) """ function hybrid3cycle(edge1::Edge, edge2::Edge) !isempty(findall(in(edge1.node), edge2.node)) end """ directionalconflict(parent::Node, edge::Edge, hybridpartnernew::Bool) Check if creating a hybrid edge down of `parent` node into the middle of `edge` would create a directed cycle in `net`, i.e. not a DAG. The proposed hybrid would go in the direction of `edge` down its child node if `hybridpartnernew` is true. Otherwise, both halves of `edge` would have their direction reversed, for the hybrid to go towards the original parent node of `edge`. Does *not* modify the network. Output: `true` if a conflict would arise (non-DAG), `false` if no conflict. """ function directionalconflict(parent::Node, edge2::Edge, hybridpartnernew::Bool) if hybridpartnernew # all edges would retain their directions: use isChild1 fields c2 = getchild(edge2) return parent === c2 || isdescendant(parent, c2) else # after hybrid addition, edge 2 would be reversed: "up" toward its own parent if !edge2.containRoot || edge2.hybrid return true # direction of edge2 cannot be reversed else # net would be a DAG with reversed directions, could even be rooted on edge2 p2 = getparent(edge2) return parent === p2 || isdescendant_undirected(parent, p2, edge2) end end end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
21854
# functions to add a hybridization # originally in functions.jl # Claudia March 2015 # ------------------------------------------------ add new hybridization------------------------------------ # function to add hybridization event # input: edge1, edge2 are the edges to remove # edge3, edge4, edge5 are the new tree edges to add # net is the network # gamma is the gamma for the hybridization # warning: assumes that edge1, edge2 are tree edges with inCycle=-1 # assumes the hybrid edge goes from edge1 to edge2 # sets minor hybrid edge length to zero # this function create the hybrid node/edges and connect everything # and deletes edge1,2 from the nodes, and removes the nodes from edge1,2 # returns the hybrid node to start future updates there function createHybrid!(edge1::Edge, edge2::Edge, edge3::Edge, edge4::Edge, net::HybridNetwork, gamma::Float64) 0 < gamma < 1 || error("gamma must be between 0 and 1: $(gamma)") (edge1.hybrid || edge2.hybrid) ? error("edges to delete must be tree edges") : nothing (edge3.hybrid || edge4.hybrid) ? error("edges to add must be tree edges") : nothing pushEdge!(net,edge3); pushEdge!(net,edge4); # create hybridization max_node = maximum([e.number for e in net.node]); max_edge = maximum([e.number for e in net.edge]); gamma < 0.5 || @warn "adding a major hybrid edge with gamma $(gamma), this can cause problems when updating incycle" hybrid_edge = Edge(max_edge+1,0.0,true,gamma,gamma>=0.5); pushEdge!(net,hybrid_edge); hybrid_node = Node(max_node+1,false,true,[edge2,hybrid_edge,edge4]); tree_node = Node(max_node+2,false,false,[edge1,edge3,hybrid_edge]); setNode!(hybrid_edge,[tree_node,hybrid_node]); setNode!(edge3,[tree_node,edge1.node[2]]); setNode!(edge4,[hybrid_node,edge2.node[2]]); setEdge!(edge1.node[2],edge3); setEdge!(edge2.node[2],edge4); removeEdge!(edge2.node[2],edge2); removeEdge!(edge1.node[2],edge1); removeNode!(edge1.node[2],edge1); setNode!(edge1,tree_node); removeNode!(edge2.node[2],edge2); #[n.number for n in edge2.node] setNode!(edge2,hybrid_node) pushNode!(net,hybrid_node); pushNode!(net,tree_node); #pushHybrid!(net,hybrid_node); return hybrid_node end # aux function for chooseEdgesGamma to identify # if two edges are sisters and if they are cherry # (have leaves) # returns true/false for sisters, true/false for cherry # true/false for nonidentifiable (two leaves, k=1 node crossed by hybridization) function sisterOrCherry(edge1::Edge,edge2::Edge) sisters = false cherry = false nonidentifiable = false node = nothing; if isEqual(edge1.node[1],edge2.node[1]) || isEqual(edge1.node[1],edge2.node[2]) node = edge1.node[1]; elseif isEqual(edge1.node[2],edge2.node[1]) || isEqual(edge1.node[2],edge2.node[2]) node = edge1.node[2]; end if node !== nothing size(node.edge,1) == 3 || error("node found $(node.number) that does not have exactly 3 edges, it has $(size(node.edge,1)) edges instead.") sisters = true if getOtherNode(edge1,node).leaf && getOtherNode(edge2,node).leaf cherry = true elseif getOtherNode(edge1,node).leaf || getOtherNode(edge2,node).leaf edge = nothing for e in node.edge if(!isEqual(e,edge1) && !isEqual(e,edge2)) edge = e end end if getOtherNode(edge,node).leaf nonidentifiable = true end end end return sisters, cherry, nonidentifiable end # aux function to addHybridization # it chooses the edges in the network and the gamma value # warning: chooses edge1, edge2, gamma randomly, but # we could do better later # check: gamma is uniform(0,1/2) to avoid big gammas # fixit: add different function to choose gamma # fixit: how to stop from infinite loop if there are no options # blacklist used for afterOptBLAll # input: edges, list of edges from which to choose, default is net.edge # warning: if edges is not net.edge, it still need to contain Edge objects from net (not deepcopies) function chooseEdgesGamma(net::HybridNetwork, blacklist::Bool, edges::Vector{Edge}) index1 = 1; index2 = 1; inlimits = false inblack = true cherry = false nonidentifiable = false while !inlimits || edges[index1].inCycle != -1 || edges[index2].inCycle != -1 || inblack || cherry || nonidentifiable index1 = round(Integer,rand()*size(edges,1)); index2 = round(Integer,rand()*size(edges,1)); if index1 != index2 && index1 != 0 && index2 != 0 && index1 <= size(edges,1) && index2 <= size(edges,1) inlimits = true sisters, cherry, nonidentifiable = sisterOrCherry(edges[index1],edges[index2]); else inlimits = false end if blacklist && !isempty(net.blacklist) length(net.blacklist) % 2 == 0 || error("net.blacklist should have even number of entries, not length: $(length(net.blacklist))") i = 1 while i < length(net.blacklist) if edges[index1].number == net.blacklist[i] if edges[index2].number == net.blacklist[i+1] inblack = true else inblack = false end elseif edges[index2].number == net.blacklist[i] if edges[index1].number == net.blacklist[i+1] inblack = true else inblack = false end end i += 2 end else inblack = false end end gamma = rand()*0.5; @debug "choose edges and gamma: from $(edges[index1].number) to $(edges[index2].number), $(gamma)" return edges[index1],edges[index2],gamma end chooseEdgesGamma(net::HybridNetwork) = chooseEdgesGamma(net, false, net.edge) chooseEdgesGamma(net::HybridNetwork, blacklist::Bool) = chooseEdgesGamma(net, blacklist, net.edge) # aux function for addHybridization # that takes the output edge1, edge2. # returns edge3, edge4, and adjusts edge1, edge2 to shorter length # fixit: problem if edge1 or edge2 have a missing length, coded as -1.0. # would be best to set lengths of e3, e4 to 0.0, and leave lengths of e1,e2 unchanged function parameters4createHybrid!(edge1::Edge, edge2::Edge,net::HybridNetwork) max_edge = maximum([e.number for e in net.edge]); t1 = rand()*edge1.length; t3 = edge1.length - t1; edge3 = Edge(max_edge+1,t3); edge1.length = t1; t1 = rand()*edge2.length; t3 = edge2.length - t1; edge4 = Edge(max_edge+2,t3); edge2.length = t1; edge3.containRoot = edge1.containRoot edge4.containRoot = edge2.containRoot return edge3, edge4 end # aux function to add the hybridization # without checking all the updates # returns the hybrid node of the new hybridization # calls chooseEdgesGamma, parameter4createHybrid and createHybrid # blacklist used in afterOptBLAll # usePartition=true if we use the information on net.partition, default true function addHybridization!(net::HybridNetwork, blacklist::Bool, usePartition::Bool) if(net.numHybrids > 0 && usePartition) !isempty(net.partition) || error("net has $(net.numHybrids) but net.partition is empty") index = choosePartition(net) if(index == 0) #no place for new hybrid @debug "no partition suitable to place new hybridization" return nothing end partition = splice!(net.partition,index) #type partition @debug "add hybrid with partition $([n.number for n in partition.edges])" edge1, edge2, gamma = chooseEdgesGamma(net, blacklist,partition.edges); else edge1, edge2, gamma = chooseEdgesGamma(net, blacklist); end @debug "add hybridization between edge1, $(edge1.number) and edge2 $(edge2.number) with gamma $(gamma)" edge3, edge4 = parameters4createHybrid!(edge1,edge2,net); hybrid = createHybrid!(edge1, edge2, edge3, edge4, net, gamma); return hybrid end addHybridization!(net::HybridNetwork) = addHybridization!(net, false, true) # function to update who is the major hybrid # after a new hybridization is added and # inCycle is updated # warning: needs updateInCycle! run first # can return the updated edge for when undoing network moves, not needed now function updateMajorHybrid!(net::HybridNetwork, node::Node) node.hybrid || error("node $(node.number) is not hybrid, cannot update major hybrid after updateInCycle") length(node.edge) == 3 || error("hybrid node $(node.number) has $(length(node.edge)) edges, should have 3") hybedge = nothing edgecycle = nothing for e in node.edge if(e.hybrid) hybedge = e elseif(e.inCycle != -1 && !e.hybrid) edgecycle = e end end !isa(hybedge,Nothing) || error("hybrid node $(node.number) does not have hybrid edge") !isa(edgecycle,Nothing) || error("hybrid node $(node.number) does not have tree edge in cycle to update to hybrid edge after updateInCycle") #println("updating hybrid status to edgeincycle $(edgecycle.number) for hybedge $(hybedge.number)") makeEdgeHybrid!(edgecycle,node,1-hybedge.gamma) end # function to update everything of a new hybridization # it follows the flow diagram in ipad # input: new added hybrid, network, # updatemajor (bool) to decide if we need to update major edge # only need to update if new hybrid added, if read from file not needed # allow=true allows extreme/very bad triangles, needed when reading # updatePart = true will update PArtition at this moment, it makes sense with a newly added hybrid # but not if net just read (because in this case it needs all inCycle updated before) # returns: success bool, hybrid, flag, nocycle, flag2, flag3 function updateAllNewHybrid!(hybrid::Node,net::HybridNetwork, updatemajor::Bool, allow::Bool, updatePart::Bool) flag, nocycle, edgesInCycle, nodesInCycle = updateInCycle!(net,hybrid); if(nocycle) return false, hybrid, flag, nocycle, false, false else if(flag) if(updatemajor) updateMajorHybrid!(net,hybrid); end flag2, edgesGammaz = updateGammaz!(net,hybrid,allow); if(flag2) flag3, edgesRoot = updateContainRoot!(net,hybrid); if(updatePart) updatePartition!(net,nodesInCycle) end if(flag3) parameters!(net) return true, hybrid, flag, nocycle, flag2, flag3 else #undoContainRoot!(edgesRoot); #undoistIdentifiable!(edgesGammaz); #undoGammaz!(hybrid,net); #undoInCycle!(edgesInCycle, nodesInCycle); return false, hybrid, flag, nocycle, flag2, flag3 end else if(updatePart) updatePartition!(net,nodesInCycle) end flag3, edgesRoot = updateContainRoot!(net,hybrid); #update contain root even if it is bad triangle to writeTopologyLevel1 correctly #undoistIdentifiable!(edgesGammaz); #undoGammaz!(hybrid,net); #undoInCycle!(edgesInCycle, nodesInCycle); return false, hybrid, flag, nocycle, flag2, flag3 end else # no need to do updatePartition in this case, because we only call deleteHybrid after undoInCycle!(edgesInCycle, nodesInCycle); return false, hybrid, flag, nocycle, true, true end end end updateAllNewHybrid!(hybrid::Node,net::HybridNetwork, updatemajor::Bool) = updateAllNewHybrid!(hybrid,net, updatemajor, false, true) # function to add a new hybridization event # it calls chooseEdgesGamma and createHybrid! # input: network # check: assumes that one of the two possibilities for # major hybrid edge gives you a cycle, true? # warning: "while" removed, it does not attempt to add until # success, it attempts to add once # returns: success (bool), hybrid, flag, nocycle, flag2, flag3 # blacklist used in afterOptBLAll function addHybridizationUpdate!(net::HybridNetwork, blacklist::Bool, usePartition::Bool) hybrid = addHybridization!(net,blacklist, usePartition); isa(hybrid,Nothing) && return false,nothing,false,false,false,false updateAllNewHybrid!(hybrid,net,true) end addHybridizationUpdate!(net::HybridNetwork) = addHybridizationUpdate!(net, false, true) addHybridizationUpdate!(net::HybridNetwork, blacklist::Bool) = addHybridizationUpdate!(net, blacklist::Bool, true) # function that will add a hybridization with addHybridizationUpdate, # if success=false, it will try to move the hybridization before # declaring failure # blacklist used in afterOptBLAll function addHybridizationUpdateSmart!(net::HybridNetwork, blacklist::Bool, N::Integer) global CHECKNET @debug "MOVE: addHybridizationUpdateSmart" success, hybrid, flag, nocycle, flag2, flag3 = addHybridizationUpdate!(net, blacklist) @debug begin printEverything(net) "success $(success), flag $(flag), flag2 $(flag2), flag3 $(flag3)" end i = 0 if !success if isa(hybrid,Nothing) @debug "MOVE: could not add hybrid by any means" else while((nocycle || !flag) && i < N) #incycle failed @debug "MOVE: added hybrid causes conflict with previous cycle, need to delete and add another" deleteHybrid!(hybrid,net,true) success, hybrid, flag, nocycle, flag2, flag3 = addHybridizationUpdate!(net, blacklist) end if(nocycle || !flag) @debug "MOVE: added hybridization $(i) times trying to avoid incycle conflicts, but failed" else if(!flag3 && flag2) #containRoot failed @debug "MOVE: added hybrid causes problems with containRoot, will change the direction to fix it" success = changeDirectionUpdate!(net,hybrid) #change dir of minor elseif(!flag2 && flag3) #gammaz failed @debug "MOVE: added hybrid has problem with gammaz (not identifiable bad triangle)" if(flag3) @debug "MOVE: we will move origin to fix the gammaz situation" success = moveOriginUpdateRepeat!(net,hybrid,true) else @debug "MOVE: we will move target to fix the gammaz situation" success = moveTargetUpdateRepeat!(net,hybrid,true) end elseif(!flag2 && !flag3) #containRoot AND gammaz failed @debug "MOVE: containRoot and gammaz both fail" end end if !success @debug "MOVE: could not fix the added hybrid by any means, we will delete it now" CHECKNET && checkNet(net) @debug begin printEverything(net); "printed everything" end deleteHybridizationUpdate!(net,hybrid) @debug begin printEverything(net); "printed everything" end CHECKNET && checkNet(net) end end end success && @debug "MOVE: added hybridization SUCCESSFUL: new hybrid $(hybrid.number)" return success end addHybridizationUpdateSmart!(net::HybridNetwork, N::Integer) = addHybridizationUpdateSmart!(net, false,N) # --- add alternative hybridizations found in bootstrap """ addAlternativeHybridizations!(net::HybridNetwork, BSe::DataFrame; cutoff=10::Number, top=3::Int) Modify the network `net` (the best estimated network) by adding some of the hybridizations present in the bootstrap networks. By default, it will only add hybrid edges with more than 10% bootstrap support (`cutoff`) and it will only include the top 3 hybridizations (`top`) sorted by bootstrap support. The dataframe `BSe` is also modified. In the original `BSe`, supposedly obtained with `hybridBootstrapSupport`, hybrid edges that do not appear in the best network have a missing number. After hybrid edges from bootstrap networks are added, `BSe` is modified to include the edge numbers of the newly added hybrid edges. To distinguish hybrid edges present in the original network versus new edges, an extra column of true/false values is also added to `BSe`, named "alternative", with true for newly added edges absent from the original network. The hybrid edges added to `net` are added as minor edges, to keep the underlying major tree topology. # example ```jldoctest julia> bootnet = readMultiTopology(joinpath(dirname(pathof(PhyloNetworks)), "..","examples", "bootsnaq.out")); # vector of 10 networks julia> bestnet = readTopology("((O,(E,#H7:::0.196):0.314):0.332,(((A)#H7:::0.804,B):10.0,(C,D):10.0):0.332);"); julia> BSn, BSe, BSc, BSgam, BSedgenum = hybridBootstrapSupport(bootnet, bestnet); julia> BSe[1:6,[:edge,:hybrid_clade,:sister_clade,:BS_hybrid_edge]] 6×4 DataFrame Row │ edge hybrid_clade sister_clade BS_hybrid_edge │ Int64? String String Float64 ─────┼───────────────────────────────────────────────────── 1 │ 7 H7 B 33.0 2 │ 3 H7 E 32.0 3 │ missing c_minus3 c_minus8 44.0 4 │ missing c_minus3 H7 44.0 5 │ missing E O 12.0 6 │ missing c_minus6 c_minus8 9.0 julia> PhyloNetworks.addAlternativeHybridizations!(bestnet, BSe) julia> BSe[1:6,[:edge,:hybrid_clade,:sister_clade,:BS_hybrid_edge,:alternative]] 6×5 DataFrame Row │ edge hybrid_clade sister_clade BS_hybrid_edge alternative │ Int64? String String Float64 Bool ─────┼────────────────────────────────────────────────────────────────── 1 │ 7 H7 B 33.0 false 2 │ 3 H7 E 32.0 false 3 │ 16 c_minus3 c_minus8 44.0 true 4 │ 19 c_minus3 H7 44.0 true 5 │ 22 E O 12.0 true 6 │ missing c_minus6 c_minus8 9.0 false julia> # using PhyloPlots; plot(bestnet, edgelabel=BSe[:,[:edge,:BS_hybrid_edge]]); ``` """ function addAlternativeHybridizations!(net::HybridNetwork,BSe::DataFrame; cutoff=10::Number,top=3::Int) top > 0 || error("top must be greater than 0") BSe[!,:alternative] = falses(nrow(BSe)) newBSe = subset(BSe, :BS_hybrid_edge => x -> x.> cutoff, :edge => ByRow( ismissing), :hybrid => ByRow(!ismissing), :sister => ByRow(!ismissing), ) top = min(top,nrow(newBSe)) if top==0 @info "no alternative hybridizations with support > cutoff $cutoff%, so nothing added." return end for i in 1:top hybnum = newBSe[i,:hybrid] sisnum = newBSe[i,:sister] edgenum = addHybridBetweenClades!(net, hybnum, sisnum) if isnothing(edgenum) @warn "cannot add desired hybrid (BS=$(newBSe[i,:BS_hybrid_edge])): the network would have a directed cycle" continue end ind1 = findall(x->!ismissing(x) && x==hybnum, BSe[!,:hybrid]) ind2 = findall(x->!ismissing(x) && x==sisnum, BSe[!,:sister]) ind = intersect(ind1,ind2) BSe[ind,:edge] .= edgenum BSe[ind,:alternative] .= true end end """ addHybridBetweenClades!(net::HybridNetwork, hybnum::Number, sisnum::Number) Modify `net` by adding a minor hybrid edge from "donor" to "recipient", where "donor" is the major parent edge `e1` of node number `hybnum` and "recipient" is the major parent edge `e2` of node number `sisnum`. The new nodes are currently inserted at the middle of these parent edges. If a hybrid edge from `e1` to `e2` would create a directed cycle in the network, then this hybrid cannot be added. In that case, the donor edge `e1` is moved up if its parent is a hybrid node, to ensure that the sister clade to the new hybrid would be a desired (the descendant taxa from `e1`) and a new attempt is made to create a hybrid edge. Output: number of the new hybrid edge, or `nothing` if the desired hybridization is not possible. See also: [`addhybridedge!`](@ref) (used by this method) and [`directionalconflict`](@ref) to check that `net` would still be a DAG. """ function addHybridBetweenClades!(net::HybridNetwork, hybnum::Number, sisnum::Number) hybind = getIndexNode(hybnum,net) sisind = getIndexNode(sisnum,net) e1 = getparentedge(net.node[sisind]) # major parent edges e2 = getparentedge(net.node[hybind]) p1 = getparent(e1) if directionalconflict(p1, e2, true) # then: first try to move the donor up # so long as the descendant taxa (= sister clade) remain the same while p1.hybrid e1 = getparentedge(p1) # major parent edge: same descendant taxa p1 = getparent(e1) end directionalconflict(p1, e2, true) && return nothing end hn, he = addhybridedge!(net, e1, e2, true) # he: missing length & gamma by default # ideally: add option "where" to breakedge!, used by addhybridedge! # so as to place the new nodes at the base of each clade. # currently: the new nodes are inserted at the middle of e1 and e2. return he.number end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
66823
# auxiliary functions for all the other methods # originally in functions.jl # Claudia February 2015 ##################### function setCHECKNET(b::Bool) global CHECKNET CHECKNET = b CHECKNET && @warn "PhyloNetworks.CHECKNET is true: will slow snaq! down." b || @info "PhyloNetworks.CHECKNET set to false" end # ----- aux general functions --------------- #based in coupon's collector: E+sqrt(V) function coupon(n::Number) return n*log(n) + n end function binom(n::Number,k::Number) n >= k || return 0 n == 1 && return 1 k == 0 && return 1 binom(n-1,k-1) + binom(n-1,k) #recursive call end function approxEq(a::Number,b::Number,absTol::Number,relTol::Number) if(a<eps() || b<eps()) abs(a-b) < absTol else abs(a-b) < relTol*eps(abs(a)+abs(b)) end end approxEq(a::Number,b::Number) = approxEq(a,b,1e-5,100) # isEqual functions: to test if 2 edges (or 2 nodes etc.) "look" alike. # Useful after a deepcopy of a network. # For nodes (or edges etc.) in the same network, use instead n1 == n2 or n1 != n2. function isEqual(n1::Node,n2::Node) return (n1.number == n2.number && approxEq(n1.gammaz,n2.gammaz) && n1.inCycle == n2.inCycle) end function isEqual(n1::Edge,n2::Edge) return (n1.number == n2.number && approxEq(n1.length,n2.length)) end function isEqual(net1::HybridNetwork, net2::HybridNetwork) result = true result &= (net1.numTaxa == net2.numTaxa) result &= (net1.numNodes == net2.numNodes) result &= (net1.numEdges == net2.numEdges) ## result &= (net1.node == net2.node) ## result &= (net1.edge == net2.edge) result &= (net1.root == net2.root) result &= (net1.names == net2.names) ## result &= (net1.hybrid == net2.hybrid) result &= (net1.numHybrids == net2.numHybrids) ## result &= (net1.leaf == net2.leaf) result &= (net1.ht == net2.ht) result &= (net1.numht == net2.numht) result &= (net1.numBad == net2.numBad) result &= (net1.hasVeryBadTriangle == net2.hasVeryBadTriangle) result &= (net1.index == net2.index) result &= (net1.loglik == net2.loglik) return result end #------------- functions to allow for ------------# # missing values (lengths or gammas) # # adds x+y but interprets -1.0 as missing: so -1.0 + x = -1.0 here. function addBL(x::Number,y::Number) (x==-1.0 || y==-1.0) ? -1.0 : x+y end function multiplygammas(x::Number,y::Number) (x==-1.0 || y==-1.0) ? -1.0 : x * y end #------------- EDGE functions --------------------# # warning: node needs to be defined as hybrid before adding to a # hybrid edge. First, an edge is defined as hybrid, and then # the nodes are added to it. If the node added is leaf, the # edge length is set unidentifiable (as it is external edge) function setNode!(edge::Edge, node::Node) size(edge.node,1) != 2 || error("vector of nodes already has 2 values"); push!(edge.node,node); if size(edge.node,1) == 1 if edge.hybrid edge.isChild1 = node.hybrid end edge.istIdentifiable = !node.leaf else if node.leaf !edge.node[1].leaf || error("edge $(edge.number) has two leaves") edge.istIdentifiable = false; else if edge.hybrid if node.hybrid # @debug (edge.node[1].hybrid ? "hybrid edge $(edge.number) has two hybrid nodes" : "") edge.isChild1 = false; else edge.node[1].hybrid || error("hybrid edge $(edge.number) has no hybrid nodes"); edge.isChild1 = true; end else #edge is tree if !edge.node[1].leaf if !node.hybrid && !edge.node[1].hybrid edge.istIdentifiable = !edge.fromBadDiamondI else if node.hybrid && (node.isBadDiamondI || node.isBadDiamondII || node.isBadTriangle) edge.istIdentifiable = false elseif edge.node[1].hybrid && (edge.node[1].isBadDiamondI ||edge.node[1].isBadDiamondII || edge.node[1].isBadTriangle) edge.istIdentifiable = false else edge.istIdentifiable = true end end else edge.istIdentifiable = false end end end end end # warning: node needs to be defined as hybrid before adding to a hybrid edge. # First, an edge is defined as hybrid, and then the nodes are added to it. # If there is a leaf in node, the edge.istIdentifiable=false function setNode!(edge::Edge,node::Array{Node,1}) size(node,1) == 2 || error("vector of nodes must have exactly 2 values") edge.node = node; if(edge.hybrid) if(node[1].hybrid) edge.isChild1 = true; else node[2].hybrid || error("hybrid edge without hybrid node"); edge.isChild1 = false; end end if(edge.node[1].leaf || edge.node[2].leaf) edge.istIdentifiable = false; else edge.istIdentifiable = true; end end """ getroot(net) Node used to root `net`. If `net` is to be considered as semi-directed or unrooted, this root node is used to write the networks' Newick parenthetical description or for network traversals. See also: [`isrootof`](@ref) """ getroot(net::HybridNetwork) = net.node[net.root] """ isrootof(node, net) `true` if `node` is the root of `net` (or used as such for network traversals in case the network is considered as semi-directed); `false` otherwise. isleaf(node) isexternal(edge) `true` if `node` is a leaf or `edge` is adjacent to a leaf, `false` otherwise. See also: [`getroot`](@ref), [`getparent`](@ref), [`getchild`](@ref) """ isrootof(node::Node, net::HybridNetwork) = node === getroot(net) @doc (@doc isrootof) isleaf isleaf(node::Node) = node.leaf @doc (@doc isrootof) isexternal isexternal(edge::Edge) = any(isleaf.(edge.node)) """ isparentof(node, edge) ischildof(node, edge) `true` if `node` is the tail / head, or parent / child, of `edge`; `false` otherwise. Assumes that the edge's direction is correct, meaning it's field `isChild1` is reliable (in sync with the rooting). See also: [`getparent`](@ref), [`getchild`](@ref), [`isrootof`](@ref) """ isparentof(node::Node, edge::Edge) = node === getparent(edge) @doc (@doc isparentof) ischildof ischildof( node::Node, edge::Edge) = node === getchild(edge) """ hassinglechild(node) `true` if `node` has a single child, based on the edges' `isChild1` field; `false` otherwise. See also: [`getchild`](@ref), [`getparent`](@ref) """ hassinglechild(node::Node) = sum(e -> getparent(e) === node, node.edge) == 1 """ getchild(edge) getchild(node) getchildren(node) Get child(ren) **node(s)**. - `getchild`: single child node of `edge`, or of `node` after checking that `node` has a single child. - `getchildren`: vector of all children *nodes* of `node`. getchildedge(node) Single child **edge** of `node`. Checks that it's a single child. *Warning*: these functions rely on correct edge direction, via their `isChild1` field. See also: [`getparent`](@ref), [`getpartneredge`](@ref), [`isparentof`](@ref), [`hassinglechild`](@ref). """ getchild(edge::Edge) = edge.node[edge.isChild1 ? 1 : 2] getchild(node::Node) = getchild(getchildedge(node)) @doc (@doc getchild) getchildren function getchildren(node::Node) children = Node[] for e in node.edge if isparentof(node, e) push!(children, getchild(e)) end end return children end @doc (@doc getchild) getchildedge function getchildedge(node::Node) ce_ind = findall(e -> isparentof(node, e), node.edge) length(ce_ind) == 1 || error("node number $(node.number) has $(length(ce_ind)) children instead of 1 child") return node.edge[ce_ind[1]] end """ getparent(edge) getparent(node) getparentminor(node) getparents(node) Get parental **node(s)**. - `getparent`: **major** (or only) parent node of `edge` or `node` - `getparentminor`: minor parent node of `node` - `getparents`: vector of all parent nodes of `node`. getparentedge(node) getparentedgeminor(node) Get one parental **edge** of a `node`. - `getparentedge`: major parent edge. For a tree node, it's its only parent edge. - `getparentedgeminor`: minor parent edge, if `node` is hybrid (with an error if `node` has no minor parent). If `node` has multiple major (resp. minor) parent edges, the first one would be returned without any warning or error. *Warning*: these functions use the field `isChild1` of edges. See also: [`getchild`](@ref), [`getpartneredge`](@ref). """ getparent(edge::Edge) = edge.node[edge.isChild1 ? 2 : 1] @inline function getparent(node::Node) for e in node.edge if e.isMajor && ischildof(node, e) return getparent(e) end end error("could not find major parent of node $(node.number)") end @doc (@doc getparent) getparentminor @inline function getparentminor(node::Node) for e in node.edge if !e.isMajor && node == getchild(e) return getparent(e) end end error("could not find minor parent of node $(node.number)") end @doc (@doc getparent) getparents @inline function getparents(node::Node) parents = Node[] for e in node.edge if ischildof(node, e) push!(parents, getparent(e)) end end return parents end @doc (@doc getparent) getparentedge @inline function getparentedge(n::Node) for ee in n.edge if ee.isMajor && ischildof(n,ee) return ee end end error("node $(n.number) has no major parent") end @doc (@doc getparent) getparentedgeminor @inline function getparentedgeminor(n::Node) for ee in n.edge if !ee.isMajor && n == ee.node[(ee.isChild1 ? 1 : 2)] return ee end end error("node $(n.number) has no minor parent") end """ getpartneredge(edge::Edge) getpartneredge(edge::Edge, node::Node) Edge that is the hybrid partner of `edge`, meaning that is has the same child `node` as `edge`. This child `node` is given as an argument in the second method. Assumptions, not checked: - no in-coming polytomy: a node has 0, 1 or 2 parents, no more - when `node` is given, it is assumed to be the child of `edge` (the first method calls the second). See also: [`getparent`](@ref), [`getchild`](@ref) """ @inline function getpartneredge(edge) node = getchild(edge) getpartneredge(edge, node) end @inline function getpartneredge(edge::Edge, node::Node) for e in node.edge if e.hybrid && e !== edge && node === getchild(e) return e end end error("did not find a partner for edge $(edge.number)") end """ edgerelation(e::Edge, node::Node, origin::Edge) Return a symbol: - `:origin` if `e` is equal to `origin`, and otherwise: - `:parent` if `e` is a parent of `node`, - `:child` if `e` is a child of `node` using the `isChild1` attribute of edges. Useful when `e` iterates over all edges adjacent to `node` and when `origin` is one of the edges adjacent to `node`, to known the order in which these edges come. example: ```julia labs = [edgerelation(e, u, uv) for e in u.edge] # assuming u is a node of edge uv parentindex = findfirst(isequal(:parent), labs) # could be 'nothing' if no parent childindices = findall( isequal(:child), labs) # vector. could be empty ``` """ function edgerelation(ee::Edge, n::Node, origin::Edge) (ee===origin ? :origin : (n===getchild(ee) ? :parent : :child)) end # -------------- NODE -------------------------# function setEdge!(node::Node,edge::Edge) push!(node.edge,edge); node.hasHybEdge = any(e -> e.hybrid, node.edge) end function getOtherNode(edge::Edge, node::Node) edge.node[1] === node ? edge.node[2] : edge.node[1] end # -------------- NETWORK ----------------------- # function getIndex(node::Node, net::Network) i = 1; while(i<= size(net.node,1) && !isEqual(node,net.node[i])) i = i+1; end i <= size(net.node,1) || error("node $(node.number) not in network") return i end function getIndex(edge::Edge, net::Network) i = 1; while(i<= size(net.edge,1) && !isEqual(edge,net.edge[i])) i = i+1; end i <= size(net.edge,1) || error("edge $(edge.number) not in network") return i end function getIndex(edge::Edge, edges::Vector{Edge}) i = 1; while(i<= size(edges,1) && !isEqual(edge,edges[i])) i = i+1; end i <= size(edges,1) || error("edge $(edge.number) not in array of edges") return i end # aux function to find the index of a node in a # node array function getIndex(name::Node, array::Array{Node,1}) i = 1; while(i<= size(array,1) && !isequal(name,array[i])) i = i+1; end i <= size(array,1) || error("$(name.number) not in array") return i end function getIndexNode(number::Integer,net::Network) ind = findfirst(n -> n.number == number, net.node) if ind === nothing error("node number not in net.node") end return ind end function getIndexEdge(number::Integer,net::Network) ind = findfirst(x -> x.number == number, net.edge) if ind === nothing error("edge number not in net.edge") end return ind end # find the index of an edge in node.edge function getIndexEdge(edge::Edge,node::Node) findfirst(e -> isequal(edge,e), node.edge) end # find the index of an edge with given number in node.edge # bug found & fixed 2019-08-22. Unused function? function getIndexEdge(number::Integer,node::Node) findfirst(e -> isequal(number,e.number), node.edge) end # find the index of a node in edge.node function getIndexNode(edge::Edge,node::Node) size(edge.node,1) == 2 || @warn "this edge $(edge.number) has more or less than 2 nodes: $([n.number for n in edge.node])" if isequal(node,edge.node[1]) return 1 elseif isequal(node,edge.node[2]) return 2 else error("node not in edge.node") end end # function to find hybrid index in net.hybrid function getIndexHybrid(node::Node, net::Network) node.hybrid || error("node $(node.number) is not hybrid so it cannot be in net.hybrid") i = 1; while(i<= size(net.hybrid,1) && !isEqual(node,net.hybrid[i])) i = i+1; end if i>size(net.hybrid,1) error("hybrid node not in network"); end return i end # function that given two nodes, it gives you the edge that connects them # returns error if they are not connected by an edge function getConnectingEdge(node1::Node,node2::Node) found = false; i = 1; while(i<= size(node1.edge,1) && !found) if(isequal(getOtherNode(node1.edge[i],node1),node2)) found = true; end i = i+1; end if(found) return node1.edge[i-1] else error("nodes not connected") end end """ isconnected(node1::Node, node2::Node) Check if two nodes are connected by an edge. Return true if connected, false if not connected. """ function isconnected(node1, node2) for e in node1.edge if e in node2.edge return true end end return false end # function to check in an edge is in an array by comparing # edge numbers (could use isEqual for adding comparisons of gammaz and inCycle) # needed for updateHasEdge function isEdgeNumIn(edge::Edge,array::Array{Edge,1}) enum = edge.number return any(e -> e.number == enum, array) end # function to check in a leaf is in an array by comparing # the numbers (uses isEqual) # needed for updateHasEdge function isNodeNumIn(node::Node,array::Array{Node,1}) return all((e->!isEqual(node,e)), array) ? false : true end # function to push a Node in net.node and # update numNodes and numTaxa function pushNode!(net::Network, n::Node) push!(net.node,n); net.numNodes += 1; if(n.leaf) net.numTaxa += 1 push!(net.leaf,n); end if(n.hybrid) pushHybrid!(net,n) end end # function to push an Edge in net.edge and # update numEdges function pushEdge!(net::Network, e::Edge) push!(net.edge,e); net.numEdges += 1; end # function to push a hybrid Node in net.hybrid and # update numHybrids function pushHybrid!(net::Network, n::Node) if(n.hybrid) push!(net.hybrid,n); net.numHybrids += 1; else error("node $(n.number) is not hybrid, so cannot be pushed in net.hybrid") end end """ deleteNode!(net::HybridNetwork, n::Node) deleteNode!(net::QuartetNetwork, n::Node) Delete node `n` from a network, i.e. removes it from net.node, and from net.hybrid or net.leaf as appropriate. Update attributes `numNodes`, `numTaxa`, `numHybrids`. Warning: `net.names` is *not* updated, and this is a feature (not a bug) for networks of type QuartetNetwork. Warning: if the root is deleted, the new root is arbitrarily set to the first node in the list. This is intentional to save time because this function is used frequently in snaq!, which handles semi-directed (unrooted) networks. """ function deleteNode!(net::HybridNetwork, n::Node) index = findfirst(no -> no===n, net.node) # warning: isequal does === # isEqual (from above) could match nodes across different networks index !== nothing || error("Node $(n.number) not in network"); deleteat!(net.node,index); net.numNodes -= 1; if net.root == index # do not check containRoot to save time in snaq! net.root = 1 # arbitrary elseif net.root > index net.root -= 1 end if n.hybrid removeHybrid!(net,n) end if n.leaf removeLeaf!(net,n) end end function deleteNode!(net::QuartetNetwork, n::Node) index = findfirst(no -> no.number == n.number, net.node) # isEqual (from above) checks for more than node number index !== nothing || error("Node $(n.number) not in quartet network"); deleteat!(net.node,index); net.numNodes -= 1 if n.hybrid removeHybrid!(net,n) end if n.leaf index = findfirst(no -> no === n, net.leaf) index !== nothing || error("node $(n.number) not net.leaf") deleteat!(net.leaf,index) net.numTaxa -= 1 end end """ deleteEdge!(net::HybridNetwork, e::Edge; part=true) deleteEdge!(net::QuartetNetwork, e::Edge) Delete edge `e` from `net.edge` and update `net.numEdges`. If `part` is true, update the network's partition field. """ function deleteEdge!(net::HybridNetwork, e::Edge; part=true::Bool) if part if e.inCycle == -1 && !e.hybrid && !isempty(net.partition) && !isTree(net) ind = whichPartition(net,e) indE = getIndex(e,net.partition[ind].edges) deleteat!(net.partition[ind].edges,indE) end end i = findfirst(x -> x===e, net.edge) i !== nothing || error("edge $(e.number) not in network: can't delete"); deleteat!(net.edge, i); net.numEdges -= 1; end # function to delete an Edge in net.edge and # update numEdges from a QuartetNetwork function deleteEdge!(net::QuartetNetwork, e::Edge) index = findfirst(x -> x.number == e.number, net.edge) # isEqual (from above) checks for more than edge number index !== nothing || error("edge not in quartet network"); deleteat!(net.edge,index); net.numEdges -= 1; end """ removeHybrid!(net::Network, n::Node) Delete a hybrid node `n` from `net.hybrid`, and update `net.numHybrid`. The actual node `n` is not deleted. It is kept in the full list `net.node`. """ function removeHybrid!(net::Network, n::Node) n.hybrid || error("cannot delete node $(n.number) from net.hybrid because it is not hybrid") i = findfirst(x -> x===n, net.hybrid) i !== nothing || error("hybrid node $(n.number) not in the network's list of hybrids"); deleteat!(net.hybrid, i); net.numHybrids -= 1; end # function to delete a leaf node in net.leaf # and update numTaxa function removeLeaf!(net::Network,n::Node) n.leaf || error("cannot delete node $(n.number) from net.leaf because it is not leaf") index = findfirst(no -> no === n, net.leaf) index !== nothing || error("leaf node $(n.number) not in network") deleteat!(net.leaf,index) net.numTaxa -= 1 end # function to delete an internal node with only 2 edges function deleteIntNode!(net::Network, n::Node) size(n.edge,1) == 2 || error("node $(n.number) does not have only two edges") index = n.edge[1].number < n.edge[2].number ? 1 : 2; edge1 = n.edge[index]; # edge1 will be kept edge2 = n.edge[index==1 ? 2 : 1] # we will delete edge2 and n, except if edge2 is hybrid if edge2.hybrid (edge2, edge1) = (edge1, edge2) if getchild(edge1) === n || edge2.hybrid @error "node with incoming hybrid edge or incident to 2 hybrid edges: will not be removed" return nothing end end node2 = getOtherNode(edge2,n) removeEdge!(node2,edge2) removeNode!(n,edge1) setEdge!(node2,edge1) setNode!(edge1,node2) deleteNode!(net,n) deleteEdge!(net,edge2) return nothing end # search the hybrid node(s) in network: returns the hybrid node(s) # in an array # throws error if no hybrid in network function searchHybridNode(net::Network) a = [n for n in net.node if n.hybrid] suma = length(a) suma != 0 || error("network has no hybrid node") return a end # search and returns the hybrid edges in network # throws error if no hybrid in network function searchHybridEdge(net::Network) a = [n for n in net.edge if n.hybrid] suma = length(a) suma != 0 || error("network has no hybrid edge") return a end """ printEdges(net) printEdges(io::IO, net) Print information on the edges of a `HybridNetwork` or `QuartetNetwork` object `net`: edge number, numbers of nodes attached to it, edge length, whether it's a hybrid edge, its γ inheritance value, whether it's a major edge, if it could contain the root (this field is not always updated, though) and attributes pertaining to level-1 networks used in SNaQ: in which cycle it is contained (-1 if no cycle), and if the edge length is identifiable (based on quartet concordance factors). """ printEdges(x) = printEdges(stdout::IO, x) function printEdges(io::IO, net::HybridNetwork) if net.numBad > 0 println(io, "net has $(net.numBad) bad diamond I. Some γ and edge lengths t are not identifiable, although their γ * (1-exp(-t)) are.") end miss = "" println(io, "edge parent child length hybrid isMajor gamma containRoot inCycle istIdentitiable") for e in net.edge @printf(io, "%-4d %-6d %-6d ", e.number, getparent(e).number, getchild(e).number) if e.length==-1.0 @printf(io, "%-7s ", miss); else @printf(io, "%-7.3f ", e.length); end @printf(io, "%-6s %-7s ", e.hybrid, e.isMajor) if e.gamma==-1.0 @printf(io, "%-7s ", miss); else @printf(io, "%-7.4g ", e.gamma); end @printf(io, "%-11s %-7d %-5s\n", e.containRoot, e.inCycle, e.istIdentifiable) end end function printEdges(io::IO, net::QuartetNetwork) println(io, "edge parent child length hybrid isMajor gamma containRoot inCycle istIdentitiable") for e in net.edge @printf(io, "%-4d %-6d %-6d ", e.number, getparent(e).number, getchild(e).number) @printf(io, "%-7.3f %-6s %-7s ", e.length, e.hybrid, e.isMajor) @printf(io, "%-7.4g %-11s %-7d %-5s\n", e.gamma, e.containRoot, e.inCycle, e.istIdentifiable) end end # print for every node, inCycle and edges """ printNodes(net) printNodes(io, net) Print information on the nodes of a `HybridNetwork` net: node number, whether it's a leaf, whether it's a hybrid node, whether it's connected to one or more hybrid edges, it's name (label), the cycle in which it is belong (-1 if no cycle; makes sense for level-1 networks), and the list of edges attached to it, by their numbers. """ printNodes(x) = printNodes(stdout::IO, x) function printNodes(io::IO, net::Network) namepad = max(4, maximum(length.([n.name for n in net.node]))) println(io, "node leaf hybrid hasHybEdge ", rpad("name", namepad), " inCycle edges'numbers") for n in net.node @printf(io, "%-4d %-5s %-6s %-10s ", n.number, n.leaf, n.hybrid, n.hasHybEdge) print(io, rpad(n.name,namepad)) @printf(io, " %-7d", n.inCycle) for e in n.edge @printf(io, " %-4d", e.number) end print(io, "\n") end end """ hybridEdges(node::Node) Return the 3 edges attached to `node` in a specific order [e1,e2,e3]. **Warning**: assume a level-1 network with node field `hasHybEdge` and edge field `inCycle` up-to-date. If `node` is a hybrid node: - e1 is the major hybrid parent edge of `node` - e2 is the minor hybrid parent edge - e3 is the tree edge, child of `node`. If `node` is a tree node parent of one child edge: - e1 is the hybrid edge, child of `node` - e2 is the tree edge that belongs to the cycle created by e1 - e3 is the other tree edge attached to `node` (not in a cycle) Otherwise: - e3 is an external edge from `node` to a leaf, if one exists. """ function hybridEdges(node::Node) size(node.edge,1) == 3 || error("node $(node.number) has $(size(node.edge,1)) edges instead of 3"); if(node.hybrid) hybmajor = nothing; hybminor = nothing; tree = nothing; for e in node.edge (e.hybrid && e.isMajor) ? hybmajor = e : nothing (e.hybrid && !e.isMajor) ? hybminor = e : nothing !e.hybrid ? tree = e : nothing end return hybmajor, hybminor, tree elseif(node.hasHybEdge) hybrid = nothing; treecycle = nothing; tree = nothing; for e in node.edge (e.hybrid) ? hybrid = e : nothing (!e.hybrid && e.inCycle != -1) ? treecycle = e : nothing (!e.hybrid && e.inCycle == -1) ? tree = e : nothing end return hybrid, treecycle, tree else #@warn "node $(node.number) is not hybrid $(node.hybrid) nor tree with hybrid edges (hasHybEdge) $(node.hasHybEdge), return the node.edge in order, unless a leaf is attached, then the edge attached to leaf is last"; edge1 = nothing edge2 = nothing edge3 = nothing leaffound = false ind = 1 for i in 1:3 if(getOtherNode(node.edge[i],node).leaf) leaffound = true edge3 = node.edge[i] ind = i break end end if(leaffound) if(ind == 1) return node.edge[2], node.edge[3], edge3 elseif(ind == 2) return node.edge[1], node.edge[3], edge3 elseif(ind == 3) return node.edge[1], node.edge[2], edge3 end else return node.edge[1], node.edge[2], node.edge[3] end end end """ hybridEdges(node::Node, e::Edge) Return the 2 edges connected to `node` other than `e`, in the same order as `node.edge`, except that `e` absent from the list. Despite what the name suggest, `node` need not be a hybrid node! `node` is assumed to have 3 edges, though. """ function hybridEdges(node::Node, edge::Edge) size(node.edge,1) == 3 || error("node $(node.number) has $(size(node.edge,1)) edges instead of 3") edge1 = nothing edge2 = nothing for e in node.edge if(!isequal(e,edge)) isa(edge1,Nothing) ? edge1 = e : edge2 = e end end return edge1,edge2 end # function to remove an edge from a node # warning: deletion is final, you can only # have edge back by pushing it again # warning: if the edge removed is hybrid and node is tree, # node.hasHybEdge is set to false # assuming any tree node can only have one # one hybrid edge function removeEdge!(node::Node, edg::Edge) index = findfirst(x -> x === edg, node.edge) index !== nothing || error("edge $(edg.number) not in node $(node.number)") deleteat!(node.edge,index) node.hasHybEdge = any(e -> e.hybrid, node.edge) end # function to remove a node from a edge # warning: deletion is final, you can only # have node back by pushing it again # warning: only removes node from edge, edge might still # be in node.edge function removeNode!(nod::Node, edge::Edge) index = findfirst(x -> x === nod, edge.node) index !== nothing || error("node $(nod.number) not in edge") deleteat!(edge.node,index); end # ---------------------------------------------------------------------------------------- # setLength # warning: allows to change edge length for istIdentifiable=false # but issues a warning # negative=true means it allows negative branch lengths (useful in qnet typeHyb=4) function setLength!(edge::Edge, new_length::Number, negative::Bool) (negative || new_length >= 0) || error("length has to be nonnegative: $(new_length), cannot set to edge $(edge.number)") new_length >= -0.4054651081081644 || error("length can be negative, but not too negative (greater than -log(1.5)) or majorCF<0: new length is $(new_length)") #println("setting length $(new_length) to edge $(edge.number)") if(new_length > 10.0) new_length = 10.0; end edge.length = new_length; edge.y = exp(-new_length); edge.z = 1.0 - edge.y; #edge.istIdentifiable || @warn "set edge length for edge $(edge.number) that is not identifiable" return nothing end """ setLength!(edge, newlength)` Set the length of `edge`, and set `edge.y` and `edge.z` accordingly. Warning: specific to SNaQ. Use [`setlengths!`](@ref) or [`setBranchLength!`](@ref) for more general tools. - The new length is censored to 10: if the new length is above 10, the edge's length will be set to 10. Lengths are interpreted in coalescent units, and 10 is close to infinity: near perfect gene tree concordance. 10 is used as an upper limit to coalescent units that can be reliably estimated. - The new length is allowed to be negative, but must be greater than -log(1.5), to ensure that the major quartet concordance factor (1 - 2/3 exp(-length)) is >= 0. """ setLength!(edge::Edge, new_length::Number) = setLength!(edge, new_length, false) """ setBranchLength!(Edge, newlength) Set the length of an Edge object. The new length needs to be non-negative, or -1.0 to be interpreted as missing. `edge.y` and `edge.z` are updated accordingly. """ function setBranchLength!(edge::Edge, new_length::Number) (new_length >= 0 || new_length == -1.0) || error("length $(new_length) has to be nonnegative or -1.0 (for missing).") edge.length = new_length; edge.y = exp(-new_length); edge.z = 1.0 - edge.y; end """ setGamma!(Edge, new γ) setGamma!(Edge, new γ, change_other=true::Bool) Set inheritance probability γ for an edge, which must be a hybrid edge. The new γ needs to be in [0,1]. The γ of the "partner" hybrid edge is changed accordingly, to 1-γ. The field `isMajor` is also changed accordingly. If the new γ is approximately 0.5, `Edge` is set to the major parent, its partner is set to the minor parent. If `net` is a HybridNetwork object, `printEdges(net)` will show the list of edges and their γ's. The γ of the third hybrid edge (say) can be changed to 0.2 with `setGamma!(net.edge[3],0.2)`. This will automatically set γ of the partner hybrid edge to 0.8. The last argument is true by default. If false: the partner edge is not updated. This is useful if the new γ is 0.5, and the partner's γ is already 0.5, in which case the `isMajor` attributes can remain unchanged. """ setGamma!(edge::Edge, new_gamma::Float64) = setGamma!(edge, new_gamma, true) # warning in the bad diamond/triangle cases because gamma is not identifiable # changeOther = true, looks for the other hybrid edge and changes gamma too function setGamma!(edge::Edge, new_gamma::Float64, changeOther::Bool) new_gamma >= 0.0 || error("gamma has to be positive: $(new_gamma)") new_gamma <= 1.0 || error("gamma has to be less than 1: $(new_gamma)") edge.hybrid || error("cannot change gamma in a tree edge"); node = getchild(edge) # child of hybrid edge node.hybrid || @warn "hybrid edge $(edge.number) not pointing at hybrid node" # @debug (node.isBadDiamondI ? "bad diamond situation: gamma not identifiable" : "") partner = Edge[] # list of other hybrid parents of node, other than edge for e in node.edge if e.hybrid && e != edge && node == getchild(e) push!(partner, e) end end length(partner) == 1 || error("strange hybrid node $(node.number) with $(length(partner)+1) hybrid parents") e2 = partner[1] onehalf = isapprox(new_gamma,0.5) if onehalf new_gamma=0.5; end new_ismajor = new_gamma >= 0.5 edge.gamma = new_gamma if changeOther edge.isMajor = new_ismajor e2.gamma = 1.0 - new_gamma e2.isMajor = !new_ismajor else if onehalf # who is major is arbitrary: so we pick what's consistent with the partner edge.isMajor = !e2.isMajor else edge.isMajor = new_ismajor end end return nothing end @inline function setmultiplegammas!(edges::Vector{Edge}, gammas::Vector{Float64}) for (e,g) in zip(edges, gammas) setGamma!(e, g) end end """ setGammaBLfromGammaz!(node, network) Update the γ values of the two sister hybrid edges in a bad diamond I, given the `gammaz` values of their parent nodes, and update the branch lengths t1 and t2 of their parent edges (those across from the hybrid nodes), in such a way that t1=t2 and that these branch lengths and γ values are consistent with the `gammaz` values in the network. Similar to the first section of [`undoGammaz!`](@ref), but does not update anything else than γ and t's. Unlike `undoGammaz!`, no error if non-hybrid `node` or not at bad diamond I. """ function setGammaBLfromGammaz!(node::Node, net::HybridNetwork) if !node.isBadDiamondI || !node.hybrid return nothing end edge_maj, edge_min, tree_edge2 = hybridEdges(node); other_maj = getOtherNode(edge_maj,node); other_min = getOtherNode(edge_min,node); edgebla,tree_edge_incycle1,tree_edge = hybridEdges(other_min); edgebla,tree_edge_incycle2,tree_edge = hybridEdges(other_maj); if(approxEq(other_maj.gammaz,0.0) && approxEq(other_min.gammaz,0.0)) edge_maj.gamma = 1.0 # γ and t could be anything if both gammaz are 0 edge_min.gamma = 0.0 # will set t's to 0 and minor γ to 0. newt = 0.0 else ((approxEq(other_min.gammaz,0.0) || other_min.gammaz >= 0.0) && (approxEq(other_maj.gammaz,0.0) || other_maj.gammaz >= 0.0) ) || error("bad diamond I in node $(node.number) but missing (or <0) gammaz") ztotal = other_maj.gammaz + other_min.gammaz edge_maj.gamma = other_maj.gammaz / ztotal edge_min.gamma = other_min.gammaz / ztotal newt = -log(1-ztotal) end setLength!(tree_edge_incycle1,newt) setLength!(tree_edge_incycle2,newt) end function numTreeEdges(net::HybridNetwork) 2*net.numTaxa - 3 + net.numHybrids end function numIntTreeEdges(net::HybridNetwork) 2*net.numTaxa - 3 + net.numHybrids - net.numTaxa end # function to get the partition where an edge is # returns the index of the partition, or error if not found # better to return the index than the partition itself, because we need the index # to use splice and delete it from net.partition later on # cycle: is the number to look for partition on that cycle only function whichPartition(net::HybridNetwork,edge::Edge,cycle::Integer) !edge.hybrid || error("edge $(edge.number) is hybrid so it cannot be in any partition") edge.inCycle == -1 || error("edge $(edge.number) is in cycle $(edge.inCycle) so it cannot be in any partition") @debug "search partition for edge $(edge.number) in cycle $(cycle)" in(edge,net.edge) || error("edge $(edge.number) is not in net.edge") for i in 1:length(net.partition) @debug "looking for edge $(edge.number) in partition $(i): $([e.number for e in net.partition[i].edges])" if(in(cycle,net.partition[i].cycle)) @debug "looking for edge $(edge.number) in partition $(i), with cycle $(cycle): $([e.number for e in net.partition[i].edges])" if in(edge,net.partition[i].edges) @debug "partition for edge $(edge.number) is $([e.number for e in net.partition[i].edges])" return i end end end @debug begin; printPartitions(net); "" end error("edge $(edge.number) is not hybrid, nor part of any cycle, and it is not in any partition") end # function to get the partition where an edge is # returns the index of the partition, or error if not found # better to return the index than the partition itself, because we need the index # to use splice and delete it from net.partition later on function whichPartition(net::HybridNetwork,edge::Edge) !edge.hybrid || error("edge $(edge.number) is hybrid so it cannot be in any partition") edge.inCycle == -1 || error("edge $(edge.number) is in cycle $(edge.inCycle) so it cannot be in any partition") @debug "search partition for edge $(edge.number) without knowing its cycle" in(edge,net.edge) || error("edge $(edge.number) is not in net.edge") for i in 1:length(net.partition) @debug "looking for edge $(edge.number) in partition $(i): $([e.number for e in net.partition[i].edges])" if(in(edge,net.partition[i].edges)) @debug "partition for edge $(edge.number) is $([e.number for e in net.partition[i].edges])" return i end end @debug begin printPartitions(net); "printed partitions" end error("edge $(edge.number) is not hybrid, nor part of any cycle, and it is not in any partition") end # function that will print the partition of net function printPartitions(net::HybridNetwork) println("partition.cycle\t partition.edges") for p in net.partition println("$(p.cycle)\t\t $([e.number for e in p.edges])") end end # function to find if a given partition is in net.partition function isPartitionInNet(net::HybridNetwork,desc::Vector{Edge},cycle::Vector{Int}) for p in net.partition if(sort(cycle) == sort(p.cycle)) if(sort([e.number for e in desc]) == sort([e.number for e in p.edges])) return true end end end return false end # function to check that everything matches in a network # in particular, cycles, partitions and containRoot # fixit: need to add check on identification of bad diamonds, triangles # and correct computation of gammaz # light=true: it will not collapse with nodes with 2 edges, will return a flag of true # returns true if found egde with BL -1.0 (only when light=true, ow error) # added checkPartition for undirectedOtherNetworks that do not need correct hybrid node number function checkNet(net::HybridNetwork, light::Bool; checkPartition=true::Bool) @debug "checking net" net.numHybrids == length(net.hybrid) || error("discrepant number on net.numHybrids (net.numHybrids) and net.hybrid length $(length(net.hybrid))") net.numTaxa == length(net.leaf) || error("discrepant number on net.numTaxa (net.numTaxa) and net.leaf length $(length(net.leaf))") net.numNodes == length(net.node) || error("discrepant number on net.numNodes (net.numNodes) and net.node length $(length(net.node))") net.numEdges == length(net.edge) || error("discrepant number on net.numEdges (net.numEdges) and net.edge length $(length(net.edge))") if(isTree(net)) all(x->x.containRoot,net.edge) || error("net is a tree, but not all edges can contain root") all(x->x.isMajor,net.edge) || error("net is a tree, but not all edges are major") all(x->!(x.hybrid),net.edge) || error("net is a tree, but not all edges are tree") all(x->!(x.hybrid),net.node) || error("net is a tree, but not all nodes are tree") all(x->!(x.hasHybEdge),net.node) || error("net is a tree, but not all nodes hasHybEdge=false") all(x->(x.gamma == 1.0 ? true : false),net.edge) || error("net is a tree, but not all edges have gamma 1.0") end for h in net.hybrid if(isBadTriangle(h)) @debug "hybrid $(h.number) is very bad triangle" net.hasVeryBadTriangle || error("hybrid node $(h.number) is very bad triangle, but net.hasVeryBadTriangle is $(net.hasVeryBadTriangle)") h.isVeryBadTriangle || h.isExtBadTriangle || error("hybrid node $(h.number) is very bad triangle but it does not know it") end nocycle,edges,nodes = identifyInCycle(net,h) for e in edges e.inCycle == h.number || error("edge $(e.number) is in cycle of hybrid node $(h.number) but its inCycle attribute is $(e.inCycle)") if(e.length == -1.0) if(light) return true else error("found edge with BL -1.0") end end if(e.hybrid) !e.containRoot || error("hybrid edge $(e.number) should not contain root") # fixit: disagree o = getOtherNode(e,h) o.hasHybEdge || error("found node $(o.number) attached to hybrid edge but hasHybEdge=$(o.hasHybEdge)") end end for n in nodes n.inCycle == h.number || error("node $(n.number) is in cycle of hybrid node $(h.number) but its inCycle attribute is $(n.inCycle)") e1,e2,e3 = hybridEdges(n) i = 0 for e in [e1,e2,e3] if(isa(e,Nothing) && h.k != 2) error("edge found that is Nothing, and hybrid node $(h.number) k is $(h.k). edge as nothing can only happen when k=2") elseif(!isa(e,Nothing)) if(e.inCycle == -1) i += 1 desc = [e] cycleNum = [h.number] getDescendants!(getOtherNode(e,n),e,desc,cycleNum) if(checkPartition && !isPartitionInNet(net,desc,cycleNum)) printPartitions(net) error("partition with cycle $(cycleNum) and edges $([e.number for e in desc]) not found in net.partition") end end end end i == 1 || error("strange node $(n.number) incycle $(h.number) but with $(i) edges not in cycle, should be only one") edgesRoot = identifyContainRoot(net,h) for edge in edgesRoot if edge.containRoot @debug begin printEverything(net); "printed everything" end error("edge $(edge.number) should not contain root") end end end end for n in net.node if(n.leaf) length(n.edge) == 1 || error("leaf $(n.number) with $(length(n.edge)) edges instead of 1") else if(light) if(length(n.edge) != 3) @debug "warning: node $(n.number) with $(length(n.edge)) edges instead of 3" return true end else length(n.edge) == 3 || error("node $(n.number) with $(length(n.edge)) edges instead of 3") end end end for e in net.edge if(e.length == -1.0) if(light) return true else error("edge found with BL -1.0") end end end @debug "no errors in checking net" return false end checkNet(net::HybridNetwork) = checkNet(net, false) # function to print everything for a given net # this is used a lot inside snaq to debug, so need to use level1 attributes # and not change the network: with writeTopologyLevel1 function printEverything(net::HybridNetwork) printEdges(net) printNodes(net) printPartitions(net) println("$(writeTopologyLevel1(net))") end # function to check if a node is very or ext bad triangle function isBadTriangle(node::Node) node.hybrid || error("cannot check if node $(node.number) is very bad triangle because it is not hybrid") if(node.k == 3) edgemaj, edgemin, treeedge = hybridEdges(node) othermaj = getOtherNode(edgemaj,node) othermin = getOtherNode(edgemin,node) treenode = getOtherNode(treeedge,node) edges1 = hybridEdges(othermaj) o1 = getOtherNode(edges1[3],othermaj) edges2 = hybridEdges(othermin) o2 = getOtherNode(edges2[3],othermin) leaves = sum([n.leaf ? 1 : 0 for n in [treenode,o1,o2]]) if(leaves == 1 || leaves == 2) return true else return false end else return false end end # function to check if a partition is already in net.partition # used in updatePartition function isPartitionInNet(net::HybridNetwork,partition::Partition) if(isempty(net.partition)) return false end for p in net.partition cycle = isempty(setdiff(p.cycle,partition.cycle)) && isempty(setdiff(partition.cycle,p.cycle)) edges = isempty(setdiff([n.number for n in p.edges],[n.number for n in partition.edges])) && isempty(setdiff([n.number for n in partition.edges],[n.number for n in p.edges])) if(cycle && edges) return true end end return false end # function to switch a hybrid node in a network to another node in the cycle function switchHybridNode!(net::HybridNetwork, hybrid::Node, newHybrid::Node) hybrid.hybrid || error("node $(hybrid.number) has to be hybrid to switch to a different hybrid") newHybrid.inCycle == hybrid.number || error("new hybrid needs to be in the cycle of old hybrid: $(hybrid.number)") !newHybrid.hybrid || error("strange hybrid node $(newHybrid.number) in cycle of another hybrid $(hybrid.number)") newHybrid.hybrid = true newHybrid.hasHybEdge = true newHybrid.name = hybrid.name pushHybrid!(net,newHybrid) makeNodeTree!(net,hybrid) end """ assignhybridnames!(net) Assign names to hybrid nodes in the network `net`. Hybrid nodes with an empty `name` field ("") are modified with a name that does not conflict with other hybrid names in the network. The preferred name is "H3" if the node number is 3 or -3, but an index other than 3 would be used if "H3" were the name of another node already. If two hybrid nodes have non-empty and equal names, the name of one of them is changed and re-assigned as described above (with a warning). """ function assignhybridnames!(net::HybridNetwork) rx = r"^H(\d+)$" # prep: collect indices 'i' of any tree nodes named like Hi trenum = Int[] # indices 'i' in tree node name, in case some are named Hi for n in net.node !n.hybrid || continue # do nothing if node n is hybrid m = match(rx, n.name) m === nothing || push!(trenum, parse(Int, m[1])) end # first: go through *all* existing non-empty names hybnum = Int[] # indices 'i' in hybrid names: Hi for ih in 1:length(net.hybrid) hnode = net.hybrid[ih] lab = hnode.name lab != "" || continue # do nothing if label is missing jh = findfirst(isequal(lab), [net.hybrid[j].name for j in 1:ih-1]) if jh !== nothing # set repeated names to "" @warn "hybrid nodes $(hnode.number) and $(net.hybrid[jh].number) have the same label: $lab. Will change the name of the former." hnode.name = "" else # fill in list of existing indices "i" in Hi m = match(rx, lab) m !== nothing || continue # skip the rest if name is not of the form Hi ind = parse(Int, m[1]) if ind in trenum @warn "hybrid node $(hnode.number) had same label as a tree node: H$ind. Will change hybrid name." hnode.name = "" else push!(hybnum, ind) end end end # second: assign empty names to "Hi" for some i hnext = 1 for ih in 1:length(net.hybrid) net.hybrid[ih].name == "" || continue # do nothing if non-empty label hnum = abs(net.hybrid[ih].number) while hnum in hybnum || hnum in trenum hnum = hnext # not efficient, but rare hnext += 1 # and okay on small networks end push!(hybnum, hnum) net.hybrid[ih].name = "H$hnum" end end """ sorttaxa!(DataFrame, columns) Reorder the 4 taxa and reorders the observed concordance factors accordingly, on each row of the data frame. If `columns` is ommitted, taxon names are assumed to be in columns 1-4 and CFs are assumed to be in columns 5-6 with quartets in this order: `12_34`, `13_24`, `14_23`. Does **not** reorder credibility interval values, if present. sorttaxa!(DataCF) sorttaxa!(Quartet, permutation_tax, permutation_cf) Reorder the 4 taxa in each element of the DataCF `quartet`. For a given Quartet, reorder the 4 taxa in its fields `taxon` and `qnet.quartetTaxon` (if non-empty) and reorder the 3 concordance values accordingly, in `obsCF` and `qnet.expCF`. `permutation_tax` and `permutation_cf` should be vectors of short integers (Int8) of length 4 and 3 respectively, whose memory allocation gets reused. Their length is *not checked*. `qnet.names` is unchanged: the order of taxon names here relates to the order of nodes in the network (???) """ function sorttaxa!(dat::DataCF) ptax = Array{Int8}(undef, 4) # to hold the sort permutations pCF = Array{Int8}(undef, 3) for q in dat.quartet sorttaxa!(q, ptax, pCF) end end function sorttaxa!(df::DataFrame, co=Int[]::Vector{Int}) if length(co)==0 co = collect(1:7) end length(co) > 6 || error("column vector must be of length 7 or more") ptax = Array{Int8}(undef, 4) pCF = Array{Int8}(undef, 3) taxnam = Array{eltype(df[!,co[1]])}(undef, 4) for i in 1:size(df,1) for j=1:4 taxnam[j] = df[i,co[j]]; end sortperm!(ptax, taxnam) sorttaxaCFperm!(pCF, ptax) # update permutation pCF according to taxon permutation df[i,co[1]], df[i,co[2]], df[i,co[3]], df[i,co[4]] = taxnam[ptax[1]], taxnam[ptax[2]], taxnam[ptax[3]], taxnam[ptax[4]] df[i,co[5]], df[i,co[6]], df[i,co[7]] = df[i,co[pCF[1]+4]], df[i,co[pCF[2]+4]], df[i,co[pCF[3]+4]] end return df end function sorttaxa!(qua::Quartet, ptax::Vector{Int8}, pCF::Vector{Int8}) qt = qua.taxon if length(qt)==4 sortperm!(ptax, qt) sorttaxaCFperm!(pCF, ptax) # update permutation pCF accordingly qt[1], qt[2], qt[3], qt[4] = qt[ptax[1]], qt[ptax[2]], qt[ptax[3]], qt[ptax[4]] qua.obsCF[1], qua.obsCF[2], qua.obsCF[3] = qua.obsCF[pCF[1]], qua.obsCF[pCF[2]], qua.obsCF[pCF[3]] # do *NOT* modify qua.qnet.quartetTaxon: it points to the same array as qua.taxon eCF = qua.qnet.expCF if length(eCF)==3 eCF[1], eCF[2], eCF[3] = eCF[pCF[1]], eCF[pCF[2]], eCF[pCF[3]] end elseif length(qt)!=0 error("Quartet with $(length(qt)) taxa") end return qua end # find permutation pCF of the 3 CF values: 12_34, 13_24, 14_23. 3!=6 possible permutations # ptax = one of 4!=24 possible permutations on the 4 taxon names # kernel: pCF = identity if ptax = 1234, 2143, 3412 or 4321 # very long code, but to minimize equality checks at run time function sorttaxaCFperm!(pcf::Vector{Int8}, ptax::Vector{Int8}) if ptax[1]==1 if ptax[2]==2 pcf[1]=1 if ptax[3]==3 # ptax = 1,2,3,4 pcf[2]=2; pcf[3]=3 else # ptax = 1,2,4,3 pcf[2]=3; pcf[3]=2 end elseif ptax[2]==3 pcf[1]=2 if ptax[3]==2 # ptax = 1,3,2,4 pcf[2]=1; pcf[3]=3 else # ptax = 1,3,4,2 pcf[2]=3; pcf[3]=1 end else # ptax[2]==4 pcf[1]=3 if ptax[3]==2 # ptax = 1,4,2,3 pcf[2]=1; pcf[3]=2 else # ptax = 1,4,3,2 pcf[2]=2; pcf[3]=1 end end elseif ptax[1]==2 if ptax[2]==1 pcf[1]=1 if ptax[3]==4 # ptax = 2,1,4,3 pcf[2]=2; pcf[3]=3 else # ptax = 2,1,3,4 pcf[2]=3; pcf[3]=2 end elseif ptax[2]==4 pcf[1]=2 if ptax[3]==1 # ptax = 2,4,1,3 pcf[2]=1; pcf[3]=3 else # ptax = 2,4,3,1 pcf[2]=3; pcf[3]=1 end else # ptax[2]==3 pcf[1]=3 if ptax[3]==1 # ptax = 2,3,1,4 pcf[2]=1; pcf[3]=2 else # ptax = 2,3,4,1 pcf[2]=2; pcf[3]=1 end end elseif ptax[1]==3 if ptax[2]==4 pcf[1]=1 if ptax[3]==1 # ptax = 3,4,1,2 pcf[2]=2; pcf[3]=3 else # ptax = 3,4,2,1 pcf[2]=3; pcf[3]=2 end elseif ptax[2]==1 pcf[1]=2 if ptax[3]==4 # ptax = 3,1,4,2 pcf[2]=1; pcf[3]=3 else # ptax = 3,1,2,4 pcf[2]=3; pcf[3]=1 end else # ptax[2]==2 pcf[1]=3 if ptax[3]==4 # ptax = 3,2,4,1 pcf[2]=1; pcf[3]=2 else # ptax = 3,2,1,4 pcf[2]=2; pcf[3]=1 end end else # ptax[1]==4 if ptax[2]==3 pcf[1]=1 if ptax[3]==2 # ptax = 4,3,2,1 pcf[2]=2; pcf[3]=3 else # ptax = 4,3,1,2 pcf[2]=3; pcf[3]=2 end elseif ptax[2]==2 pcf[1]=2 if ptax[3]==3 # ptax = 4,2,3,1 pcf[2]=1; pcf[3]=3 else # ptax = 4,2,1,3 pcf[2]=3; pcf[3]=1 end else # ptax[2]==1 pcf[1]=3 if ptax[3]==3 # ptax = 4,1,3,2 pcf[2]=1; pcf[3]=2 else # ptax = 4,1,2,3 pcf[2]=2; pcf[3]=1 end end end end """ setlengths!(edges::Vector{Edge}, lengths::Vector{Float64}) Assign new lengths to a vector of `edges`. """ @inline function setlengths!(edges::Vector{Edge}, lengths::Vector{Float64}) for (e,l) in zip(edges, lengths) e.length = l end end """ getlengths(edges::Vector{Edge}) Vector of edge lengths for a vector of `edges`. """ getlengths(edges::Vector{Edge}) = [e.length for e in edges] """ hashybridladder(net::HybridNetwork) Return true if `net` contains a hybrid ladder: where a hybrid node's child is itself a hybrid node. This makes the network not treechild, assuming it is fully resolved. (One of the nodes does not have any tree-node child). """ function hashybridladder(net::HybridNetwork) for h in net.hybrid if any(n.hybrid for n in getparents(h)) return true end end return false end """ shrinkedge!(net::HybridNetwork, edge::Edge) Delete `edge` from net, provided that it is a non-external tree edge. Specifically: delete its child node (as determined by `isChild1`) and connect all edges formerly incident to this child node to the parent node of `edge`, thus creating a new polytomy, unless the child was of degree 2. Warning: it's best for `isChild1` to be in sync with the root for this. If not, the shrinking may fail (if `edge` is a tree edge but its "child" is a hybrid) or the root may change arbitrarily (if the child of `edge` is the root). Output: true if the remaining node (parent of `edge`) becomes a hybrid node with more than 1 child after the shrinking; false otherwise (e.g. no polytomy was created, or the new polytomy is below a tree node) """ function shrinkedge!(net::HybridNetwork, edge2shrink::Edge) edge2shrink.hybrid && error("cannot shrink hybrid edge number $(edge2shrink.number)") cn = getchild(edge2shrink) cn.hybrid && error("cannot shrink tree edge number $(edge2shrink.number): its child node is a hybrid. run directEdges! ?") pn = getparent(edge2shrink) isexternal(edge2shrink) && # (isleaf(cn) || isleaf(pn)) && error("won't shrink edge number $(edge2shrink.number): it is incident to a leaf") removeEdge!(pn,edge2shrink) empty!(edge2shrink.node) # should help gc for ee in cn.edge ee !== edge2shrink || continue cn_index = findfirst(x -> x === cn, ee.node) ee.node[cn_index] = pn # ee.isChild1 remains synchronized push!(pn.edge, ee) end pn.hasHybEdge = any(e -> e.hybrid, pn.edge) empty!(cn.edge) # should help to garbage-collect cn deleteEdge!(net, edge2shrink; part=false) deleteNode!(net, cn) badpolytomy = false if pn.hybrid # count the number of pn's children, without relying on isChild1 of tree edges nc = sum((!e.hybrid || getchild(e) !== pn) for e in pn.edge) badpolytomy = (nc > 1) end return badpolytomy end @doc raw""" shrink2cycles!(net::HybridNetwork, unroot=false::Bool) If `net` contains a 2-cycle, collapse the cycle into one edge of length tA + γt1+(1-γ)t2 + tB (see below), and return true. Return false otherwise. A 2-cycle is a set of 2 parallel hybrid edges, from the same parent node to the same hybrid child node. A A | tA | parent | | \ | t2,1-γ | | t1,γ | tA + γ*t1 + (1-γ)*t2 + tB | / | hybrid | | tB | B B If any of the lengths or gammas associated with a 2-cycle are missing, the combined length is missing. If γ is missing, branch lengths are calculated using γ=0.5. If `unroot` is false and the root is up for deletion, it will be kept only if it is has degree 2 or more. If `unroot` is true and the root is up for deletion, it will be kept only if it has degree 3 or more. A root node with degree 1 will be deleted in both cases. """ function shrink2cycles!(net::HybridNetwork, unroot=false::Bool) foundcycle = false nh = length(net.hybrid) ih = nh # hybrids deleted from the end while ih > 0 h = net.hybrid[ih] minor = getparentedgeminor(h) major = getparentedge(h) pmin = getparent(minor) # minor parent node pmaj = getparent(major) # major parent node if pmin !== pmaj # no 2-cycle ih -= 1 continue end # 2-cycle foundcycle = true shrink2cycleat!(net, minor, major, unroot) nh = length(net.hybrid) ih = nh # we re-do if a cycle was removed: a new cycle might have appeared end return foundcycle end """ shrink2cycleat!(net::HybridNetwork, minor::Edge, major::Edge, unroot::Bool) Remove `minor` edge then update the branch length of the remaining `major` edge. Called by [`shrink2cycles!`](@ref) Assumption: `minor` and `major` do form a 2-cycle. That is, they start and end at the same node. """ function shrink2cycleat!(net::HybridNetwork, minor::Edge, major::Edge, unroot::Bool) g = minor.gamma if g == -1.0 g=.5; end major.length = addBL(multiplygammas( g, minor.length), multiplygammas(1.0-g, major.length)) deletehybridedge!(net, minor, false,unroot,false,false,false) # nofuse,unroot,multgammas,simplify return nothing end """ shrink3cycles!(net::HybridNetwork, unroot=false::Bool) Remove all 2- and 3-cycles from a network. Return true if `net` contains a 2-cycle or a 3-cycle; false otherwise. A 3-cycle (2-cycle) is a set of 3 (2) nodes that are all connected. One of them must be a hybrid node, since `net` is a DAG. If `unroot` is false and the root is up for deletion, it will be kept only if it is has degree 2 or more. If `unroot` is true and the root is up for deletion, it will be kept only if it has degree 3 or more. A root node with degree 1 will be deleted in both cases. See [`shrink3cycleat!`](@ref) for details on branch lengths and inheritance values. """ function shrink3cycles!(net::HybridNetwork, unroot=false::Bool) foundcycle = false nh = length(net.hybrid) ih = nh # hybrids deleted from the end while ih > 0 h = net.hybrid[ih] minor = getparentedgeminor(h) major = getparentedge(h) pmin = getparent(minor) # minor parent node pmaj = getparent(major) # major parent node if pmin === pmaj # 2-cycle foundcycle = true shrink2cycleat!(net, minor, major, unroot) nh = length(net.hybrid) ih = nh + 1 # start over if a cycle was removed by setting ih = nh + 1. # Shrinking could have created a new cycle. else # 3-cycle result = shrink3cycleat!(net, h, minor, major, pmin, pmaj, unroot) if result foundcycle = true nh = length(net.hybrid) ih = nh + 1 # start over as above end end ih -= 1 end return foundcycle end @doc raw""" shrink3cycleat!(net::HybridNetwork, hybrid::Node, edge1::Edge, edge2::Edge, node1::Node, node2::Node, unroot::Bool) Replace a 3-cycle at a given `hybrid` node by a single node, if any. Assumption: `edge1` (`node1`) and `edge2` (`node2`) are the parent edges (nodes) of `hybrid`. Return true if a 3-cycle is found and removed, false otherwise. There is a 3-cycle if nodes 1 & 2 are connected, by an edge called `e3` below. There are two cases, with differing effects on the γ inheritance values and branch lengths. **Hybrid case**: the 3-cycle is shrunk to a hybrid node, which occurs if either node 1 or 2 is a hybrid node (that is, e3 is hybrid). If e3 goes from node 1 to node 2, the 3-cycle (left) is shrunk as on the right: \eA /eB \eA /eB 1--e3->2 γ1+γ2γ3 \ / γ2(1-γ3) \ / hybrid γ1\ /γ2 hybrid with new branch lengths: new tA = tA + (γ1.t1 + γ2γ3.(t2+t3))/(γ1+γ2γ3), new tB = tB + t2, provided that γ1, γ2=1-γ1, and γ3 are not missing. If one of them is missing then γ1 and γ2 remain as is, and e3 is deleted naively, such that new tA = tA + t1 and new tB = tB + t2. If γ's are not missing but one of t1,t2,t3 is missing, then the γ's are updated to γ1+γ2γ3 and γ2(1-γ3), but t's are update naively. **Tree case**: the 3-cycle is shrunk to a tree node, which occurs if node 1 & 2 are both tree nodes (that is, e3 is a tree edge). If eC is the child edge of `hybrid`, the 3-cycle (left) is shrunk as on the right: \eA \eA 1--e3--2--eB-- \ \ / n--eB-- γ1\ /γ2 | hybrid |eC | |eC with new branch lengths: new tA = tA + γ2.t3, new tB = tB + γ1.t3, new tC = tC + γ1.t1 + γ2.t2, provided that γ1, γ2=1-γ1, t1, t2 and t3 are not missing. If one is missing, then e1 is deleted naively such that tB is unchanged, new tC = tC + t2 and new tA = tA + t3. """ function shrink3cycleat!(net::HybridNetwork, hybrid::Node, edge1::Edge, edge2::Edge, node1::Node, node2::Node, unroot::Bool) # check for presence of 3 cycle edge3 = nothing for e in node1.edge # find edge connecting node1 and node2 e !== edge1 || continue n = getOtherNode(e, node1) if n === node2 edge3 = e break end end !isnothing(edge3) || return false # no 3-cycle at node h # identify case type if edge3.hybrid # one of the parent nodes is a hybrid # to shrink this, delete edge connecting these two nodes (edge3 here) if getchild(edge3) === node1 node1, node2 = node2, node1 edge1, edge2 = edge2, edge1 end # now: node1 --edge3--> node2 edgeA = nothing for e in node1.edge if e!== edge1 && e !== edge2 edgeA = e break end end g1 = edge1.gamma g2g3 = multiplygammas(edge2.gamma, edge3.gamma) g1tilde = addBL(g1, g2g3) if g1tilde != -1.0 # else one of the γ is missing: do nothing with γs and ts edge1.gamma = g1tilde edge2.gamma = 1.0-g1tilde edge1.isMajor = g1tilde >= 0.5 edge2.isMajor = !edge1.isMajor if edge1.length != -1.0 && edge2.length != -1.0 && edge3.length != -1.0 edge1.length = (edge1.length *g1 + (edge3.length + edge2.length)*g2g3)/g1tilde end end deletehybridedge!(net, edge3, false,unroot,false,false) # nofuse,unroot,multgammas,simplify else # parent nodes 1 and 2 are both tree nodes edgeB = nothing for e in node2.edge if e !== edge1 && e !==edge3 edgeB = e break end end g1t1 = multiplygammas(edge1.gamma, edge1.length) t3 = edge3.length if g1t1 != -1.0 && edge2.length != -1.0 && t3 != -1.0 # else do nothing: keep tA, tB, tC as is edgeB.length = addBL(edgeB.length, edge1.gamma * t3) edge3.length = t3 * edge2.gamma edge2.length = g1t1 + edge2.gamma * edge2.length end deletehybridedge!(net, edge1, false,unroot,false,false) # nofuse,unroot,multgammas,simplify end return true end """ adjacentedges(centeredge::Edge) Vector of all edges that share a node with `centeredge`. """ function adjacentedges(centeredge::Edge) n = centeredge.node length(n) == 2 || error("center edge is connected to $(length(n)) nodes") @inbounds edges = copy(n[1].edge) # shallow copy, to avoid modifying the first node @inbounds for ei in n[2].edge ei === centeredge && continue # don't add the center edge again getOtherNode(ei, n[2]) === n[1] && continue # any parallel edge would have been in `edges` already push!(edges, ei) end return edges end #------------------------------------ function citation() bibfile = joinpath(@__DIR__, "..", "CITATION.bib") out = readlines(bibfile) println("Bibliography in bibtex format also in CITATION.bib") println(join(out,'\n')) end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
48370
# julia functions for bootstrap # Claudia October 2015 # Cecile April 2016 """ readBootstrapTrees(listfile; relative2listfile=true) Read the list of file names in `listfile`, then read all the trees in each of these files. Output: vector of vectors of trees (networks with h>0 allowed). `listfile` should be the name of a file containing the path/name to multiple bootstrap files, one on each line (no header). Each named bootstrap file should contain multiple trees, one per line (such as bootstrap trees from a single gene). The path/name to each bootstrap file should be relative to `listfile`. Otherwise, use option `relative2listfile=false`, in which case the file names are interpreted as usual: relative to the user's current directory if not given as absolute paths. """ function readBootstrapTrees(filelist::AbstractString; relative2listfile=true::Bool) filelistdir = dirname(filelist) bootfiles = DataFrame(CSV.File(filelist, header=false, types=Dict(1=>String)); copycols=false) size(bootfiles)[2] > 0 || error("there should be a column in file $filelist: with a single bootstrap file name on each row (no header)") ngenes = size(bootfiles)[1] bf = (relative2listfile ? joinpath.(filelistdir, bootfiles[!,1]) : bootfiles[!,1]) treelists = Array{Vector{HybridNetwork}}(undef, ngenes) for igene in 1:ngenes treelists[igene] = readMultiTopology(bf[igene]) print("read $igene/$ngenes bootstrap tree files\r") # using \r for better progress display end return treelists end """ sampleBootstrapTrees(vector of tree lists; seed=0::Integer, generesampling=false, row=0) sampleBootstrapTrees!(tree list, vector of tree lists; seed=0::Integer, generesampling=false, row=0) Sample bootstrap gene trees, 1 tree per gene. Set the seed with keyword argument `seed`, which is 0 by default. When `seed=0`, the actual seed is set using the clock. Assumes a vector of vectors of networks (see `readBootstrapTrees`), each one of length 1 or more (error if one vector is empty, tested in `bootsnaq`). - site resampling: always, from sampling one bootstrap tree from each given list. This tree is sampled at **random** unless `row>0` (see below). - gene resampling: if `generesampling=true` (default is false), genes (i.e. lists) are sampled with replacement. - `row=i`: samples the ith bootstrap tree for each gene. `row` is turned back to 0 if gene resampling is true. output: one vector of trees. the modifying function (!) modifies the input tree list and returns it. """ function sampleBootstrapTrees(trees::Vector{Vector{HybridNetwork}}; seed=0::Integer, generesampling=false::Bool, row=0::Integer) bootTrees = Array{HybridNetwork}(undef, length(trees)) sampleBootstrapTrees!(bootTrees, trees, seed=seed, generesampling=generesampling, row=row) end function sampleBootstrapTrees!(bootTrees::Vector{HybridNetwork}, trees::Vector{Vector{HybridNetwork}}; seed=0::Integer, generesampling=false::Bool, row=0::Integer) numgen = length(trees) ## number of genes numgen>0 || error("needs at least 1 array of trees") numgen <= length(bootTrees) || error("the input tree list needs to be of length $numgen at least") if (generesampling) row=0; end if row==0 if seed == 0 t = time()/1e9 a = split(string(t),".") seed = parse(Int,a[2][end-4:end]) #better seed based on clock println("using seed $(seed) for bootstrap trees") end Random.seed!(seed) if generesampling indxg = sample(1:numgen, numgen) # default is with replacement. good! end end for g in 1:numgen ig = (generesampling ? indxg[g] : g ) if row==0 indxt = sample(1:length(trees[ig]),1)[1] else indxt = row length(trees[ig]) >= row || error("gene $g has fewer than $row bootstrap trees.") end bootTrees[g] = trees[ig][indxt] end return bootTrees end """ sampleCFfromCI(data frame, seed=0) sampleCFfromCI!(data frame, seed=0) Read a data frame containing CFs and their credibility intervals, and sample new obsCF uniformly within the CIs. These CFs are then rescaled to sum up to 1 for each 4-taxon sets. Return a data frame with taxon labels in first 4 columns, sampled obs CFs in columns 5-7 and credibility intervals in columns 8-13. - The non-modifying function creates a new data frame (with re-ordered columns) and returns it. If `seed=-1`, the new df is a deep copy of the input df, with no call to the random number generator. Otherwise, `seed` is passed to the modifying function. - The modifying function overwrites the input data frame with the sampled CFs and returns it. If `seed=0`, the random generator is seeded from the clock. Otherwise the random generator is seeded using `seed`. Warning: the modifying version does *not* check the data frame: assumes correct columns. optional argument: `delim=','` by default: how columns are delimited. """ function sampleCFfromCI(df::DataFrame, seed=0::Integer) @debug "order of columns should be: t1,t2,t3,t4,cf1234,cf1324,cf1423,cf1234LO,cf1234HI,..." size(df,2) == 13 || size(df,2) == 14 || @warn "sampleCFfromCI function assumes table from TICR: CF, CFlo, CFhi" obsCFcol = [findfirst(isequal(:CF12_34), DataFrames.propertynames(df)), findfirst(isequal(:CF13_24), DataFrames.propertynames(df)), findfirst(isequal(:CF14_23), DataFrames.propertynames(df))] nothing ∉ obsCFcol || error("""CF columns were not found: should be named like 'CF12_34'""") obsCFcol == [5,8,11] || @warn """CF columns were found, but not in the expected columns. Lower/upper bounds of credibility intervals assumed in columns 6,7, 9,10 and 12,13.""" colsTa = [1,2,3,4] # column numbers for taxon names colsCI = [6,7,9,10,12,13] # for lower/upper CI bounds length(findall(in(obsCFcol), colsTa)) ==0 || error("CFs found in columns 1-4 where taxon labels are expected") length(findall(in(obsCFcol), colsCI)) ==0 || error("CFs found in columns where credibility intervals are expected") newdf = df[:, [colsTa; obsCFcol; colsCI] ] if seed==-1 return newdf else return sampleCFfromCI!(newdf::DataFrame, seed) end end function sampleCFfromCI!(df::DataFrame, seed=0::Integer) if seed == 0 t = time()/1e9 a = split(string(t),".") seed = parse(Int,a[2][end-4:end]) #better seed based on clock println("using seed $(seed) for bootstrap table") end Random.seed!(seed) for i in 1:size(df,1) c1 = (df[i, 9]-df[i, 8])*rand()+df[i, 8] c2 = (df[i,11]-df[i,10])*rand()+df[i,10] c3 = (df[i,13]-df[i,12])*rand()+df[i,12] suma = c1+c2+c3 df[i,5] = c1/suma df[i,6] = c2/suma df[i,7] = c3/suma end return df end sampleCFfromCI(file::AbstractString; delim=','::Char,seed=0::Integer) = sampleCFfromCI(DataFrame(CSV.File(file, delim=delim); copycols=false),seed) # function that will do bootstrap of snaq estimation in series # it repeats optTopRuns nrep times # it has the same arguments as optTopRuns except for: # - need data table of CF with conf intervals (instead of d DataCF), # or vector of vector of HybridNetworks # - new argument nrep: number of bootstrap replicates (default 10) # - new argument runs2: percentage of bootstrap replicates to start in the best network, by default 0.25 # - new argument bestNet: to start the optimization. if prcnet>0.0 and bestNet is not input as argument from a previous run, it will estimate it inside # - quartetfile if it was used in original data ("none" if all quartets used) # recall: optTopRuns! does *not* modify its input starting network function optTopRunsBoot(currT0::HybridNetwork, data::Union{DataFrame,Vector{Vector{HybridNetwork}}}, hmax::Integer, liktolAbs::Float64, Nfail::Integer, ftolRel::Float64,ftolAbs::Float64,xtolRel::Float64,xtolAbs::Float64, verbose::Bool, closeN::Bool, Nmov0::Vector{Int}, runs1::Integer, outgroup::AbstractString, filename::AbstractString, seed::Integer, probST::Float64, nrep::Integer, runs2::Integer, bestNet::HybridNetwork, quartetfile::AbstractString) println("BOOTSTRAP OF SNAQ ESTIMATION") writelog = true if filename != "" logfile = open(string(filename,".log"),"w") write(logfile, "BOOTSTRAP OF SNAQ ESTIMATION \n") else writelog = false logfile = stdout end inputastrees = isa(data, Vector{Vector{HybridNetwork}}) inputastrees || isa(data, DataFrame) || error("Input data not recognized: $(typeof(data))") if runs1>0 && runs2>0 str = """Will use this network as starting topology for $runs1 run(s) for each bootstrap replicate: $(writeTopologyLevel1(currT0)) and this other network for $runs2 run(s): $(writeTopologyLevel1(bestNet)) """ writelog && write(logfile, str) print(str) end if inputastrees # allocate memory, to be re-used later newtrees = sampleBootstrapTrees(data, row=1) newd = readTrees2CF(newtrees, quartetfile=quartetfile, writeTab=false, writeSummary=false) taxa = unionTaxa(newtrees) else newdf = sampleCFfromCI(data, -1) # column names check, newdf has obsCF in columns 5-7 # seed=-1: deep copy only, no rand() newd = readTableCF!(newdf, collect(1:7)) # allocate memory for DataCF object end if runs1>0 && isTree(currT0) # get rough first estimate of branch lengths in startnet updateBL!(currT0, newd) end if seed == 0 t = time()/1e9 a = split(string(t),".") seed = parse(Int,a[2][end-4:end]) #better seed based on clock end println("main seed $(seed)") writelog && write(logfile,"\nmain seed $(seed)\n") writelog && flush(logfile) Random.seed!(seed) seedsData = round.(Int,floor.(rand(nrep)*100000)) # seeds to sample bootstrap data if runs1>0 seeds = round.(Int,floor.(rand(nrep)*100000)) # seeds for all optimizations from currT0 end if runs2>0 seedsOtherNet = round.(Int,floor.(rand(nrep)*100000)) # for runs starting from other net end bootNet = HybridNetwork[] writelog && write(logfile,"\nBEGIN: $(nrep) replicates\n$(Libc.strftime(time()))\n") writelog && flush(logfile) for i in 1:nrep str = "\nbegin replicate $(i)\nbootstrap data simulation: seed $(seedsData[i])\n" writelog && write(logfile, str) print(str) if !inputastrees sampleCFfromCI!(newdf, seedsData[i]) readTableCF!(newd, newdf, [5,6,7]) else sampleBootstrapTrees!(newtrees, data, seed=seedsData[i]) calculateObsCFAll!(newd,taxa) # do not use readTrees2CF: to save memory and gc time end if runs1>0 str = "estimation, $runs1 run" * (runs1>1 ? "s" : "") * ": seed $(seeds[i])\n" writelog && write(logfile, str) print(str) rootname = "" @debug begin rootname = string(filename,"_",i); "rootname set to $rootname"; end net1 = optTopRuns!(currT0, liktolAbs, Nfail, newd, hmax,ftolRel, ftolAbs, xtolRel, xtolAbs, verbose, closeN, Nmov0, runs1, outgroup, rootname,seeds[i],probST) if runs2==0 net = net1 end end if runs2>0 str = "estimation, $runs2 run" * (runs2>1 ? "s" : "") * " starting from other net: seed $(seedsOtherNet[i])\n" writelog && write(logfile, str) print(str) rootname = "" @debug begin rootname = string(filename,"_",i,"_startNet2"); "rootname set to $rootname"; end net2 = optTopRuns!(bestNet, liktolAbs, Nfail, newd, hmax,ftolRel, ftolAbs, xtolRel, xtolAbs, verbose, closeN, Nmov0, runs2, outgroup, rootname,seedsOtherNet[i],probST) if runs1==0 net = net2 end end if runs1>0 && runs2>0 net = (net1.loglik < net2.loglik ? net1 : net2) end writelog && flush(logfile) push!(bootNet, net) str = (outgroup=="none" ? writeTopologyLevel1(net) : writeTopologyLevel1(net,outgroup)) if writelog write(logfile, str) write(logfile,"\n") flush(logfile) end println(str) # net also printed by each optTopRuns! but separately from the 2 starting points end # of the nrep bootstrap replicates writelog && close(logfile) if writelog s = open(string(filename,".out"),"w") for n in bootNet if outgroup == "none" write(s,"$(writeTopologyLevel1(n))\n") else write(s,"$(writeTopologyLevel1(n,outgroup))\n") end # "with -loglik $(n.loglik)" not printed: not comparable across bootstrap networks end close(s) end return bootNet end # like snaq, only calls optTopRunsBoot # undocumented arguments: closeN, Nmov0 """ bootsnaq(T::HybridNetwork, df::DataFrame) bootsnaq(T::HybridNetwork, vector of tree lists) Bootstrap analysis for SNaQ. Bootstrap data can be quartet concordance factors (CF), drawn from sampling uniformly in their credibility intervals, as given in the data frame `df`. Alternatively, bootstrap data can be gene trees sampled from a vector of tree lists: one list of bootstrap trees per locus (see `readBootstrapTrees` to generate this, from a file containing a list of bootstrap files: one per locus). From each bootstrap replicate, a network is estimated with snaq!, with a search starting from topology `T`. Optional arguments include the following, with default values in parentheses: - `hmax` (1): max number of reticulations in the estimated networks - `nrep` (10): number of bootstrap replicates. - `runs` (10): number of independent optimization runs for each replicate - `filename` ("bootsnaq"): root name for output files. No output files if "". - `seed` (0 to get a random seed from the clock): seed for random number generator - `otherNet` (empty): another starting topology so that each replicate will start prcnet% runs on otherNet and (1-prcnet)% runs on `T` - `prcnet` (0): percentage of runs starting on `otherNet`; error if different than 0.0, and otherNet not specified. - `ftolRel`, `ftolAbs`, `xtolRel`, `xtolAbs`, `liktolAbs`, `Nfail`, `probST`, `verbose`, `outgroup`: see `snaq!`, same defaults. If `T` is a tree, its branch lengths are first optimized roughly with [`updateBL!`](@ref) (by using the average CF of all quartets defining each branch and calculating the coalescent units corresponding to this quartet CF). If `T` has one or more reticulations, its branch lengths are taken as is to start the search. The branch lengths of `otherNet` are always taken as is to start the search. """ function bootsnaq(startnet::HybridNetwork, data::Union{DataFrame,Vector{Vector{HybridNetwork}}}; hmax=1::Integer, liktolAbs=likAbs::Float64, Nfail=numFails::Integer, ftolRel=fRel::Float64, ftolAbs=fAbs::Float64, xtolRel=xRel::Float64, xtolAbs=xAbs::Float64, verbose=false::Bool, closeN=true::Bool, Nmov0=numMoves::Vector{Int}, runs=10::Integer, outgroup="none"::AbstractString, filename="bootsnaq"::AbstractString, seed=0::Integer, probST=0.3::Float64, nrep=10::Integer, prcnet=0.0::Float64, otherNet=HybridNetwork()::HybridNetwork, quartetfile="none"::AbstractString) inputastrees = isa(data, Vector{Vector{HybridNetwork}}) inputastrees || isa(data, DataFrame) || error("Input data not recognized: $(typeof(data))") if !inputastrees (DataFrames.propertynames(data)[[6,7,9,10,12,13]] == [:CF12_34_lo,:CF12_34_hi,:CF13_24_lo,:CF13_24_hi,:CF14_23_lo,:CF14_23_hi]) || @warn """assume table with CI from TICR: CFlo, CFhi in columns 6,7; 9,10; and 12,13. Found different column names: $(DataFrames.names(data)[[6,7,9,10,12,13]])""" else # check 1+ genes, each with 1+ trees, all with h=0. ngenes = length(data) ngenes > 0 || error("empty list of bootstrap trees (0 genes)") for igene in 1:ngenes btr = data[igene] length(btr) > 0 || error("no bootstrap trees for $(igene)th gene") for itree in 1:length(btr) btr[itree].numHybrids == 0 || error("network $itree is not a tree for $(igene)th gene") end end end prcnet >= 0 || error("percentage of times to use the best network as starting topology should be positive: $(prcnet)") prcnet = (prcnet <= 1.0) ? prcnet : prcnet/100 runs2 = round(Int, runs*prcnet) # runs starting from otherNet runs1 = runs - runs2 # runs starting from startnet if runs1>0 startnet=readTopologyLevel1(writeTopologyLevel1(startnet)) # does not modify startnet outside flag = checkNet(startnet,true) # light checking only flag && error("starting topology suspected not level-1") try checkNet(startnet) catch err println("starting topology is not of level 1:") rethrow(err) end end runs2 == 0 || otherNet.numTaxa > 0 || error("""otherNet not given and prcnet>0. Please set prcnet to 0 to start optimizations from the same network always, or else provide an other network "otherNet" to start the optimization from this other network in pcrnet % of runs.""") if runs2 > 0 otherNet=readTopologyLevel1(writeTopologyLevel1(otherNet)) flag = checkNet(otherNet,true) # light checking only flag && error("starting topology 'otherNet' suspected not level-1") try checkNet(otherNet) catch err println("starting topology 'otherNet' not a level 1 network:") rethrow(err) end end # for multiple alleles: expand into two leaves quartets like sp1 sp1 sp2 sp3. if (@isdefined originald) && !isempty(originald.repSpecies) ## not defined if treefile empty, but not needed expandLeaves!(originald.repSpecies,startnet) end optTopRunsBoot(startnet,data,hmax, liktolAbs, Nfail,ftolRel, ftolAbs, xtolRel, xtolAbs, verbose, closeN, Nmov0, runs1, outgroup, filename, seed, probST, nrep, runs2, otherNet, quartetfile) end """ `treeEdgesBootstrap(boot_net::Vector{HybridNetwork}, ref_net::HybridNetwork)` Read a list of bootstrap networks (`boot_net`) and a reference network (`ref_net`), and calculate the bootstrap support of the tree edges in the reference network. All minor hybrid edges (γ<0.5) are removed to extract the major tree from each network. All remaining edges are tree edges, each associated with a bipartition. output: - a data frame with one row per tree edge and two columns: edge number, bootstrap support (as a percentage) - the major tree from the reference network, where minor hybrid edges (with γ<0.5) have been removed. """ function treeEdgesBootstrap(net::Vector{HybridNetwork}, net0::HybridNetwork) # estimated network, major tree and matrix S = tipLabels(net0) tree0 =majorTree(net0, unroot=true) M0 = tree2Matrix(tree0,S, rooted=false) M = Matrix[] tree = HybridNetwork[] for n in net t = majorTree(n, unroot=true) push!(tree,t) mm = tree2Matrix(t,S, rooted=false) push!(M,mm) end df = DataFrame(edgeNumber=Int[], proportion=Float64[]) for i in 1:size(M0,1) #rows in M0: internal edges cnt = 0 #count for j in 1:length(M) #for every M for k in 1:size(M[j],1) #check every row in M if M0[i,2:end] == M[j][k,2:end] || M0[i,2:end] == map(x->(x+1)%2,M[j][k,2:end]) #same row #println("found same row: $(M0[i,2:end]) and $(M[j][k,2:end])") cnt += 1 break end end end push!(df,[M0[i,1] cnt*100/length(M)]) # fixit later, when edges have an attribute for bootstrap support: # set BS to cnt/length(M) for the edge numbered M0[i,1]. end @info """edge numbers in the data frame correspond to the current edge numbers in the network. If the network is modified, the edge numbers in the (modified) network might not correspond to those in the bootstrap table. Plot the bootstrap values onto the current network with plot(network_name, edgelabel=bootstrap_table_name)""" return df, tree0 end """ hybridDetection(net::Vector{HybridNetwork}, net1::HybridNetwork, outgroup::AbstractString) function can only compare hybrid nodes in networks that have the same underlying major tree also, need to root all networks in the same place, and the root has to be compatible with the direction of the hybrid edges it computes the rooted hardwired distance between networks, the root matters. input: vector of bootstrap networks (net), estimated network (net1), outgroup returns - a matrix with one row per bootstrap network, and 2*number of hybrids in net1, column i corresponds to whether hybrid i (`net1.hybrid[i]`) is found in the bootstrap network, column 2i+1 corresponds to the estimated gamma on the bootstrap network (0.0 if hybrid not found). To know the order of hybrids, print `net1.hybrid` or `h.name for h in net1.hybrid` - list of discrepant trees (trees not matching the main tree in net1) """ function hybridDetection(net::Vector{HybridNetwork}, net1::HybridNetwork, outgroup::AbstractString) tree1 = majorTree(net1, unroot=true) rootnet1 = deepcopy(net1) rootatnode!(rootnet1,outgroup) # HF for "hybrid found?" HFmat = zeros(length(net),net1.numHybrids*2) # discrepant trees discTrees = HybridNetwork[] # major trees majorTrees = HybridNetwork[] i = 1 for n in net tree = majorTree(n, unroot=true) push!(majorTrees,tree) RFmajor = hardwiredClusterDistance(tree, tree1, false) if RFmajor != 0 push!(discTrees,tree) i+=1 continue # skip replicate if major tree is *not* correct end found = zeros(Bool, net1.numHybrids) # repeats false gamma = zeros(Float64,net1.numHybrids) # repeats 0.0 # re-root estimated network if not rooted correctly reroot = true if length(n.node[n.root].edge) == 2 # check if root connects to correct outgroup for e in n.node[n.root].edge for node in e.node if node.name == outgroup reroot = false break end end if (!reroot) break end end end !reroot || println("Will need to reroot the estimated network...") for trueh = 1:net1.numHybrids netT = deepcopy(rootnet1) displayedNetworkAt!(netT, netT.hybrid[trueh]) # bug: need correct attributes to re-root later... for esth = 1:n.numHybrids netE = deepcopy(n) displayedNetworkAt!(netE, netE.hybrid[esth]) if reroot rootatnode!(netE, outgroup) # if re-rooting is not possible, end # then the hybridization doesn't match. if hardwiredClusterDistance(netT, netE, true) == 0 # true: rooted found[trueh] = true node = netE.hybrid[1] edges = hybridEdges(node) edges[2]. hybrid || error("edge should be hybrid") !edges[2]. isMajor || error("edge should be minor hybrid") edges[2].gamma <= 0.5 || error("gamma should be less than 0.5") gamma[trueh] = edges[2].gamma break # to exit loop over esth end end end HFmat[i,1:net1.numHybrids] = found HFmat[i,(net1.numHybrids+1):end] = gamma i+=1 end treeMatch=size(HFmat[sum(HFmat,2).>0,:],1) #number of bootstrap trees that match tree1 println("$(treeMatch) out of $(length(net)) bootstrap major trees match with the major tree in the estimated network") println("order of hybrids:") for h in net1.hybrid println("$(h.name)") end return HFmat,discTrees end """ `hybridBootstrapSupport(boot_net::Vector{HybridNetwork}, ref_net::HybridNetwork; rooted=false)` Match hybrid nodes in a reference network with those in an array of networks, like bootstrap networks. All networks must be fully resolved, and on the same taxon set. If `rooted=true`, all networks are assumed to have been properly rooted beforehand. Otherwise, the origin of each hybrid edge is considered as an unrooted bipartition (default). Two hybrid edges in two networks are said to match if they share the same "hybrid" clade (or recipient) and the same "donor clade", which is a sister to the hybrid clade in the network. Since a hybrid clade has 2 parent edges, it is sister to two clades simultaneously: one is its major sister (following the major hybrid edge with γ>0.5) and one is its minor sister (following the major hybrid edge with γ<0.5). To calculate these hybrid and sister clades at a given hybrid node, all other hybrid edges are first removed from the network. Then, the hybrid clade is the hardwired cluster (descendants) of either hybrid edge and major/minor clade is the hardwired cluster of the sibling edge of the major/minor hybrid parent. If `rooted=false`, sister clades are considered as bipartitions. Output: 1. a "node" data frame (see below) 2. an "edge" data frame (see below) 3. a "clade" data frame to describe the make up of all clades found as hybrids or sisters, starting with a column `taxa` that lists all taxa. All other columns correspond to a given clade and contain true/false values. `true` means that a given taxon belongs in a given clade. For a clade named `H1`, for instance, and if the data frame was named `cla`, the list of taxa in this clade can be obtained with `cla[:taxa][cla[:H1]]`. 4. an array of gamma values, with one row for each bootstrap network and two columns (major/minor) for each hybrid edge in the reference network. If this hybrid edge was found in the bootstrap network (i.e. same hybrid and sister clades, after removal of all other hybrid nodes), its bootstrap gamma value is recorded here. Otherwise, the gamma entry is 0.0. 5. a vector with the number of each hybrid edge in the reference network, in the same order as for the columns in the array of gamma values above. The "node" data frame has one row per clade and 9 columns giving: - `:clade`: the clade's name, like the taxon name (if a hybrid is a single taxon) or the hybrid tag (like 'H1') in the reference network - `:node`: the node number in the reference network. missing if the clade is not in this network. - `:hybridnode`: typically the same node number as above, except for hybrid clades in the reference network. For those, the hybrid node number is listed here. - `:edge`: number of the parent edge, parent to the node in column 2, if found in the ref network. missing otherwise. - `:BS_hybrid`: percentage of bootstrap networks in which the clade is found to be a hybrid clade. - `:BS_sister`: percentage of bootstrap networks in which the clade is found to be sister to some hybrid clade (sum of the next 2 columns) - `:BS_major_sister`: percentage of bootstrap networks in which the clade is found to be the major sister to some hybrid clade - `:BS_minor_sister`: same as previous, but minor - `:BS_hybrid_samesisters`: percentage of bootstrap networks in which the clade is found to be a hybrid and with the same set of sister clades as in the reference network. Applies to hybrid clades found in the reference network only, missing for all other clades. The "edge" data frame has one row for each pair of clades, and 8 columns: - `:edge`: hybrid edge number, if the edge appears in the reference network. missing otherwise. - `:hybrid_clade`: name of the clade found to be a hybrid, descendent of 'edge' - `:hybrid`: node number of that clade, if it appears in the reference network. missing otherwise. - `:sister_clade`: name of the clade that is sister to 'edge', i.e. be sister to a hybrid - `:sister`: node number of that clade, if in the ref network. - `:BS_hybrid_edge`: percentage of bootstrap networks in which 'edge' is found to be a hybrid edge, i.e. when the clade in the 'hybrid' column is found to be a hybrid and the clade in the 'sister' column is one of its sisters. - `:BS_major`: percentage of bootstrap networks in which 'edge' is found to be a major hybrid edge, i.e. when 'hybrid' is found to be a hybrid clade and 'sister' is found to be its major sister. - `:BS_minor`: same as previous, but minor """ function hybridBootstrapSupport(nets::Vector{HybridNetwork}, refnet::HybridNetwork; rooted=false::Bool) numNets = length(nets) numNets>0 || error("there aren't any test (bootstrap) networks") numHybs = refnet.numHybrids numHybs>0 || error("there aren't any hybrid in reference network") try directEdges!(refnet) catch err if isa(err, RootMismatch) err.msg *= "\nPlease change the root in reference network (see rootatnode! or rootonedge!)" end rethrow(err) end taxa = tipLabels(refnet) ntax = length(taxa) # extract hardwired clusters of each tree edge in major tree of reference net, # and of each hybrid edge after all other hybrids are removed following the major edge. clade = Vector{Bool}[] # list all clades in reference and in bootstrap networks treenode = Int[] # node number for each clade: of tree node if found in reference net treeedge = Int[] # number of tree edge corresponding to the clade (parent of treenode) leafname = AbstractString[] # "" if internal node, leaf name if leaf # clade, treenode, treeedge: same size. leafname and hybparent: same size initially only hybind = Int[] # indices in 'clade', that appear as hybrid clades in reference hybnode = Int[] # for those hybrid clades: number of hybrid node majsisedge = Int[] # for those hybrid clades: number of major sister edge (in ref net) minsisedge = Int[] # minor majsisind = Int[] # for those hybrid clades: index of major sister clade in 'clade' minsisind = Int[] # minor # hybind, hybnode, majsis*, minsis*: same size = number of hybrid nodes in reference network if !rooted && length(refnet.node[refnet.root].edge)==2 && any(e -> e.hybrid, refnet.node[refnet.root].edge) refnet = deepcopy(refnet) # new binding inside function fuseedgesat!(refnet.root, refnet) end # issues otherwise: correct tree edge for root bipartitions, find sister clades, ... reftre = majorTree(refnet, unroot=true) skipone = (!rooted && length(reftre.node[reftre.root].edge)<3) # not count same bipartition twice for pe in reftre.edge hwc = hardwiredCluster(pe,taxa) # not very efficient, but human readable if skipone && refnet.node[refnet.root] ≡ getparent(pe) && sum(hwc)>1 skipone = false # wrong algo for trivial 2-taxon rooted tree (A,B); println("skip edge $(pe.number)") else push!(clade, hwc) push!(treeedge, pe.number) cn = getchild(pe) # child node of pe push!(treenode, cn.number) push!(leafname, (cn.leaf ? cn.name : "")) end end hybparent = zeros(Int,length(clade)) # 0 if has no hybrid parent node. Index in hybnode otherwise. for trueh = 1:numHybs net0 = deepcopy(refnet) displayedNetworkAt!(net0, net0.hybrid[trueh]) # removes all minor hybrid edges but one hn = net0.hybrid[1] hemaj, hemin, ce = hybridEdges(hn) # assumes no polytomy at hybrid nodes and correct node.hybrid (hemin.hybrid && !hemin.isMajor) || error("edge should be hybrid and minor") (hemaj.hybrid && hemaj.isMajor) || error("edge should be hybrid and major") ic = findfirst(isequal(ce.number), treeedge) ic !== nothing || error("hybrid node $(hn.number): child edge not found in major tree") hybparent[ic] = trueh push!(hybind,ic) push!(hybnode, hn.number) push!(majsisedge, hemaj.number) push!(minsisedge, hemin.number) for sis in ["min","maj"] he = (sis=="min" ? hemin : hemaj) pn = getparent(he) # parent node of sister (origin of gene flow if minor) atroot = (!rooted && pn ≡ net0.node[net0.root]) # polytomy at root pn of degree 3: will exclude one child edge hwc = zeros(Bool,ntax) # new binding each time. pushed to clade below. for ce in pn.edge # important if polytomy if ce ≢ he && pn ≡ getparent(ce) hw = hardwiredCluster(ce,taxa) if atroot && any(hw .& clade[ic]) # sister clade intersects child clade (hw .& clade[ic]) == clade[ic] || @warn "weird clusters at the root in reference, hybrid node $(hn.number)" else hwc .|= hw end end end i = findfirst(isequal(hwc), clade) if (!rooted && i===nothing) i = findfirst(isequal(.!hwc), clade) end i !== nothing || error(string("hyb node $(hn.number): ",sis,"or clade not found in main tree")) if (sis=="min") push!(minsisind, i) else push!(majsisind, i) end if sis=="min" # need to get clade not in main tree: hybrid + minor sister pe = nothing # looking for the (or one) parent edge of pn for ce in pn.edge if pn ≡ getchild(ce) pe=ce break end end # pe == nothing if minor hybrid is at root and rooted=true. Will just miss edge and node number # for that clade, but in that case, the minor sister might have been assigned that edge anyway... if pe != nothing hwc = hardwiredCluster(pe,taxa) i = findfirst(isequal(hwc), clade) # i>0: (hybrid + minor sister) can be in main tree if # hybrid origin is ancestral, i.e. hybrid clade is nested within minor sister. if i===nothing push!(clade, hwc) push!(treenode, pn.number) push!(treeedge, pe.number) push!(hybparent, 0) push!(leafname, (pn.leaf ? pn.name : "")) end end end end end # for cl in clade @show taxa[cl]; end; @show treenode; @show treeedge; @show hybparent; @show leafname # @show hybind; @show hybnode; @show majsisedge; @show minsisedge; @show majsisind; @show minsisind # node-associated summaries: nclades = length(clade) nh = length(hybnode) nedges = 2*nh BShyb = zeros(Float64, nclades) # clade = hybrid BSmajsis = zeros(Float64, nclades) # clade = major sister of some hybrid BSminsis = zeros(Float64, nclades) # clade = minor sister of some hybrid # edge-associated summaries, i.e. associated to a pair of clades (hyb,sis): hybcladei = repeat(hybind, inner=[2]) # indices in 'clade' siscladei = Array{Int}(undef, nedges) # edge order: (major then minor) for all hybrids edgenum = Array{Int}(undef, nedges) for i=1:nh siscladei[2*i-1] = majsisind[i] siscladei[2*i] = minsisind[i] edgenum[2*i-1] = majsisedge[i] edgenum[2*i] = minsisedge[i] end # less desirable order: [majsisind; minsisind], corresponds to outer=[2] for hybcladei BShybmajsis = zeros(Float64, nedges) # one clade = hybrid, one clade = major sister BShybminsis = zeros(Float64, nedges) # one clade = hybrid, one clade = minor sister # network*edge-associated values: only keep those for edges in ref net gamma = zeros(Float64,numNets,nedges) # node-associate 3-way partition summary: BShybsamesis = zeros(Float64, nh) # same hybrid & sister set as in ref net nextnum = max(maximum([n.number for n in refnet.edge]), maximum([n.number for n in refnet.node]) ) + 1 for i = 1:numNets net = nets[i] length(tipLabels(net))==ntax || error("networks have non-matching taxon sets") try directEdges!(net) # make sure the root is admissible catch err if isa(err, RootMismatch) err.msg *= "\nPlease change the root in test network (see rootatnode! or rootatedge!)" end rethrow(err) end for esth = 1:net.numHybrids # try to match estimated hybrid edge hwcPar = zeros(Bool,ntax) # minor sister clade hwcChi = zeros(Bool,ntax) # child clade hwcSib = zeros(Bool,ntax) # major sister clade net1 = deepcopy(net) displayedNetworkAt!(net1, net1.hybrid[esth]) hn = net1.hybrid[1] if !rooted && length(net1.node[net1.root].edge)==2 && any(e -> e.hybrid, net1.node[net1.root].edge) fuseedgesat!(net1.root, net1) end hemaj, hemin, ce = hybridEdges(hn) # assumes no polytomy at hybrid node (hemin.hybrid && !hemin.isMajor) || error("edge should be hybrid and minor") (hemaj.hybrid && hemaj.isMajor) || error("edge should be hybrid and major") hardwiredCluster!(hwcChi,hemin,taxa) for sis in ["min","maj"] he = (sis=="min" ? hemin : hemaj) pn = getparent(he) # parent of hybrid edge atroot = (!rooted && pn ≡ net1.node[net1.root]) # if at root: exclude the child edge in the same cycle as he. # its cluster includes hwcChi. all other child edges do not interest hwcChi. # if (atroot) @show i; @warn "$(sis)or edge is at the root!"; end for ce in pn.edge if ce ≢ he && pn ≡ getparent(ce) hwc = hardwiredCluster(ce,taxa) if !atroot || sum(hwc .& hwcChi) == 0 # empty intersection if (sis=="maj") hwcSib .|= hwc; else hwcPar .|= hwc; end elseif (hwc .& hwcChi) != hwcChi @warn "weird clusters at the root. bootstrap net i=$i, hybrid $(net.hybrid[esth].name)" end end end # will use complement too: test network may be rooted differently end # @show taxa[hwcChi]; @show taxa[hwcPar] if all(hwcPar) || all(hwcSib) || all(.!hwcPar) || all(.!hwcSib) @warn "parent or sibling cluster is full or empty. bootstrap net i=$i, hybrid $(net.hybrid[esth].name)" end ihyb = findfirst(isequal(hwcChi), clade) newhyb = (ihyb===nothing) # hwcChi not found in clade list if newhyb push!(clade, hwcChi) push!(treenode, nextnum) push!(treeedge, nextnum) push!(BShyb, 1.0) push!(BSmajsis, 0.0) push!(BSminsis, 0.0) ihyb = length(clade) # was nothing; converted to nex available integer nextnum += 1 else BShyb[ihyb] += 1.0 end iSmaj = findfirst(isequal(hwcSib), clade) iSmin = findfirst(isequal(hwcPar), clade) if (!rooted && iSmaj===nothing) iSmaj = findfirst(isequal(.!hwcSib), clade) end if (!rooted && iSmin===nothing) iSmin = findfirst(isequal(.!hwcPar), clade) end newmaj = (iSmaj===nothing) if newmaj push!(clade, hwcSib) push!(treenode, nextnum) push!(treeedge, nextnum) push!(BShyb, 0.0) push!(BSmajsis, 1.0) push!(BSminsis, 0.0) iSmaj = length(clade) # was nothing; now integer nextnum += 1 else BSmajsis[iSmaj] += 1.0 end newmin = (iSmin===nothing) if newmin push!(clade, hwcPar) push!(treenode, nextnum) push!(treeedge, nextnum) push!(BShyb, 0.0) push!(BSmajsis, 0.0) push!(BSminsis, 1.0) iSmin = length(clade) # was nothing; now integer nextnum += 1 else BSminsis[iSmin] += 1.0 end samehyb = (newhyb ? Int[] : findall(isequal(ihyb), hybcladei)) for sis in ["maj","min"] newpair = newhyb || (sis=="min" ? newmin : newmaj) iSsis = (sis=="min" ? iSmin : iSmaj) if !newpair # hyb and sis clades were already found, but not sure if together iish = findfirst(isequal(iSsis), siscladei[samehyb]) if iish !== nothing # pair was indeed found ipair = samehyb[iish] if (sis=="min") BShybminsis[ipair] += 1.0 else BShybmajsis[ipair] += 1.0 end if ipair <= nedges # pair = edge in reference network gamma[i,ipair] = (sis=="min" ? hemin.gamma : hemaj.gamma) end else newpair = true; end end if newpair push!(hybcladei, ihyb) push!(siscladei, iSsis) push!(BShybminsis, (sis=="min" ? 1.0 : 0.0)) push!(BShybmajsis, (sis=="min" ? 0.0 : 1.0)) end end if ihyb<=nclades && hybparent[ihyb]>0 # hyb clade match in ref net th = hybparent[ihyb] if ((iSmaj==majsisind[th] && iSmin==minsisind[th]) || (iSmin==majsisind[th] && iSmaj==minsisind[th]) ) BShybsamesis[th] += 1 end end end # loop over hybrid nodes end # loop over bootstrap nets fac = 100/numNets BShyb *= fac # size: length(clade) BSmajsis *= fac BSminsis *= fac BShybmajsis *= fac # size: length of hybcladei or siscladei BShybminsis *= fac BShybsamesis *= fac # size: length(hybnode) = nedges/2 # combine results into 2 dataframes: node & edge summaries # and 1 dataframe to describe clades # first: detect nodes with all BS=0 keepc = ones(Bool,length(clade)) # keep clade h in output tables? for h=nclades:-1:1 if BShyb[h]==0.0 && BSmajsis[h]==0.0 && BSminsis[h]==0.0 keepc[h] = false deleteat!(BShyb,h); deleteat!(BSmajsis,h); deleteat!(BSminsis,h) end end nkeepc = sum(keepc) # clade descriptions resCluster = DataFrame(taxa=taxa) cladestr = Array{String}(undef, length(clade)) rowh = 1 for h=1:length(clade) nn = treenode[h] # node number in ref net cladestr[h] = string("c_", (nn<0 ? "minus" : ""), abs(nn)) # column name for a clade at node 5: "c_5". At node -5: "c_minus5" # because symbol :c_-5 causes an error. if h <= nclades && leafname[h] != "" # replace "c5" by leaf name, e.g. "taxon1" cladestr[h] = leafname[h] end if h <= nclades && hybparent[h]>0 # replace "c5" or leaf name by hybrid name, e.g. "H1" na = refnet.hybrid[hybparent[h]].name cladestr[h] = (na=="" ? string("H", refnet.hybrid[hybparent[h]].number) : replace(na, r"^#" => "")) end if keepc[h] rowh += 1 insertcols!(resCluster, rowh, Symbol(cladestr[h]) => clade[h]) end end # node summaries resNode = DataFrame(clade=cladestr[keepc], node=allowmissing(treenode[keepc]), hybridnode=allowmissing(treenode[keepc]), edge=allowmissing(treeedge[keepc]), BS_hybrid=BShyb, BS_sister = BSmajsis + BSminsis, BS_major_sister=BSmajsis, BS_minor_sister=BSminsis, BS_hybrid_samesisters=Vector{Union{Missing,Float64}}(undef, nkeepc)) rowh = 1 for h=1:length(clade) if h <= nclades && keepc[h] && hybparent[h]>0 resNode[rowh,:hybridnode] = hybnode[hybparent[h]] resNode[rowh,:BS_hybrid_samesisters] = BShybsamesis[hybparent[h]] elseif keepc[h] resNode[rowh,:BS_hybrid_samesisters] = missing end if h>nclades # clade *not* in the reference network resNode[rowh,:node] = missing resNode[rowh,:hybridnode] = missing resNode[rowh,:edge] = missing end if keepc[h] rowh += 1; end end insertcols!(resNode, 10, :BS_all => resNode[!,:BS_hybrid]+resNode[!,:BS_sister]) sort!(resNode, [:BS_all,:BS_hybrid]; rev=true) select!(resNode, Not(:BS_all)) # edge summaries resEdge = DataFrame(edge = Vector{Union{Int, Missing}}(undef, length(hybcladei)), hybrid_clade=cladestr[hybcladei], hybrid=Vector{Union{Int, Missing}}(treenode[hybcladei]), sister_clade=cladestr[siscladei], sister=Vector{Union{Int, Missing}}(treenode[siscladei]), BS_hybrid_edge = BShybmajsis+BShybminsis, BS_major=BShybmajsis, BS_minor=BShybminsis) for i=1:length(hybcladei) h = hybcladei[i] if h <= nclades && hybparent[h]>0 resEdge[i,:hybrid] = hybnode[hybparent[h]] end if h>nclades resEdge[i,:hybrid]=missing; end if siscladei[i]>nclades resEdge[i,:sister]=missing; end if i <= nedges resEdge[i,:edge] = edgenum[i] else resEdge[i,:edge] = missing end end o = [1:nedges; sortperm(resEdge[nedges+1:length(hybcladei),:BS_hybrid_edge],rev=true) .+ nedges] return resNode, resEdge[o,:], resCluster, gamma, edgenum end """ summarizeHFdf(HFmat::Matrix) Summarize data frame output from [`hybridDetection`](@ref). Output: dataframe with one row per hybrid, and 5 columns: - hybrid index (order from estimated network, see [`hybridDetection`](@ref), - number of bootstrap trees that match the underlying tree of estimated network - number of bootstrap networks that have the hybrid - mean estimated gamma in the bootstrap networks that have the hybrid - sd estimated gamma in the bootstrap networks that have the hybrid also last row has index -1, and the third column has the number of networks that have all hybrids (hybrid index, mean gamma, sd gamma are meaningless in this last row) """ function summarizeHFdf(HFmat::Matrix) HFmat2 = HFmat[sum(HFmat,2) .>0,:] gt = size(HFmat2,1) total = size(HFmat,1) numH = round(Int,size(HFmat,2)/2) df = DataFrame(hybrid=Int[],goodTrees=Float64[],netWithHybrid=Float64[],meanGamma=Float64[], sdGamma=Float64[]) for i in 1:numH mat = HFmat2[HFmat2[:,i] .> 0, :] n = size(mat,1) g = mean(mat[:,round(Int,numH+i)]) s = std(mat[:,round(Int,numH+i)]) push!(df,[i gt n g s]) end which = Bool[] for i in 1:size(HFmat2,1) push!(which,sum(HFmat2[i,1:numH]) == numH) end push!(df, [-1 gt sum(which) -1.0 -1.0]) return df end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
36497
# functions to compare unrooted networks # Claudia & Cecile November 2015 # Traverses a tree postorder and modifies matrix M # with edges as rows and species as columns (see tree2Matrix) # S should be sorted --fixit: are you sure? function traverseTree2Matrix!(node::Node, edge::Edge, ie::Vector{Int}, M::Matrix{Int}, S::Union{Vector{String},Vector{Int}}) child = getOtherNode(edge,node) # must not be a leaf indedge = ie[1] M[indedge,1] = edge.number ie[1] += 1 # mutable array: to modify edge index 'ie' outside function scope for e in child.edge #postorder traversal if(!isEqual(e,edge)) # assumes a tree here grandchild = getOtherNode(e,child) if grandchild.leaf indsp = findfirst(isequal(grandchild.name), S) indsp != nothing || error("leaf $(grandchild.name) not in species list $(S)") M[indedge,indsp+1] = 1 #indsp+1 bc first column is edge numbers else inde = ie[1]; traverseTree2Matrix!(child,e,ie,M,S) M[indedge,2:size(M,2)] .|= M[inde,2:size(M,2)] end end end end # takes a tree and a list of species as input, # and produces a matrix M with edges as rows and species as columns: # Mij=1 if species j is descendant of edge i, 0 ow. # allows for missing taxa: # Mij=0 if species not present in tree. This is handled in calculateObsCFAll with sameTaxa function function tree2Matrix(T::HybridNetwork, S::Union{Vector{String},Vector{Int}}; rooted=true::Bool) length(T.hybrid)==0 || error("tree2Matrix only works on trees. Network has $(T.numHybrids) hybrid nodes.") # sort!(S) # why sort 'taxa', again and again for each tree? Benefits? ne = length(T.edge)-T.numTaxa # number of internal branch lengths if (T.node[T.root].leaf) # the root is a leaf: the 1 edge stemming from the root is an external edge ne += 1 # and will need to get a row in the matrix, to be deleted later. end M = zeros(Int,ne,length(S)+1) # M[:,1] = sort!([e.number for e in T.edge]) ie = [1] # index of next edge to be documented: row index in M for e in T.node[T.root].edge child = getOtherNode(e,T.node[T.root]) if !isleaf(child) traverseTree2Matrix!(T.node[T.root],e,ie,M,S) end end if (!rooted && length(T.node[T.root].edge)<3) # remove first row of M: 1st edge at the root, duplicated edge # if the tree is to be considered as unrooted, or just leaf. M = M[2:size(M,1),:] # makes a copy, too bad. end return M end """ hardwiredClusters(net::HybridNetwork, taxon_labels) Returns a matrix describing all the hardwired clusters in a network, with taxa listed in same order as in `taxon_labels` to describe their membership in each cluster. Allows for missing taxa, with entries all 0. Warnings: - clusters are rooted, so the root must be correct. - each hybrid node is assumed to have exactly 2 parents (no more). Each row corresponds to one internal edge, that is, external edges are excluded. If the root is a leaf node, the external edge to that leaf is included (first row). Both parent hybrid edges to a given hybrid node only contribute a single row (they share the same hardwired cluster). - first column: edge number - next columns: 0/1. 1=descendant of edge, 0=not a descendant, or missing taxon. - last column: 10/11 values. 10=tree edge, 11=hybrid edge See also [`hardwiredClusterDistance`](@ref) and [`hardwiredCluster`](@ref). """ function hardwiredClusters(net::HybridNetwork, S::Union{AbstractVector{String},AbstractVector{Int}}) ne = length(net.edge)-net.numTaxa # number of internal branch lengths ne -= length(net.hybrid) # to remove duplicate rows for the 2 parent edges of each hybrid if (net.node[net.root].leaf) # root is leaf: the 1 edge stemming from the root is an external edge ne += 1 # but needs to be included still (rooted clusters). end M = zeros(Int,ne,length(S)+2) ie = [1] # index of next edge to be documented: row index in M for e in net.node[net.root].edge hardwiredClusters!(net.node[net.root],e,ie,M,S) end return M end function hardwiredClusters!(node::Node, edge::Edge, ie::AbstractVector{Int}, M::Matrix{Int}, S::Union{AbstractVector{String},AbstractVector{Int}}) child = getOtherNode(edge,node) !child.leaf || return 0 # do nothing if child is a leaf. if (edge.hybrid) # edge is a hybrid. Need to find its partner. (edge.isChild1 ? edge.node[1] == child : edge.node[2] == child) || error( "inconsistency during network traversal: node $(child.number) supposed to be child of hybrid edge $(edge.number), inconsistent with isChild1.") partner = nothing partnerVisited = true indpartner = 0 for e in child.edge if (e.hybrid && e != edge && (e.isChild1 ? e.node[1] == child : e.node[2] == child)) partner = e indpartner = findfirst(isequal(partner.number), M[:,1]) if isnothing(indpartner) partnerVisited = false # will need to continue traversal end break # partner hybrid edge was found end end partner !== nothing || error("partner hybrid edge not found for edge $(edge.number), child $(child.number)") !partnerVisited || return indpartner end indedge = ie[1] M[indedge,1] = edge.number M[indedge,end] = edge.hybrid ? 11 : 10 ie[1] += 1 # mutable array for e in child.edge # postorder traversal if (e != edge && (!edge.hybrid || e!=partner)) # do not go back to (either) parent edge. grandchild = getOtherNode(e,child) if grandchild.leaf indsp = findfirst(isequal(grandchild.name), S) indsp != nothing || error("leaf $(grandchild.name) not in species list $(S)") M[indedge,indsp+1] = 1 #indsp+1 because first column is edge numbers else inde = hardwiredClusters!(child,e,ie,M,S) M[indedge,2:end-1] .|= M[inde,2:end-1] end end end return indedge end """ hardwiredCluster(edge::Edge, taxa::Union{AbstractVector{String},AbstractVector{Int}}) hardwiredCluster!(v::Vector{Bool}, edge::Edge, taxa) hardwiredCluster!(v::Vector{Bool}, edge::Edge, taxa, visited::Vector{Int}) Calculate the hardwired cluster of `edge`, coded as a vector of booleans: true for taxa that are descendent of the edge, false for other taxa (including missing taxa). The edge should belong in a rooted network for which `isChild1` is up-to-date. Run `directEdges!` beforehand. This is very important, otherwise one might enter an infinite loop, and the function does not test for this. visited: vector of node numbers, of all visited nodes. # Examples: ```jldoctest julia> net5 = "(A,((B,#H1),(((C,(E)#H2),(#H2,F)),(D)#H1)));" |> readTopology |> directEdges! ; julia> taxa = net5 |> tipLabels # ABC EF D 6-element Vector{String}: "A" "B" "C" "E" "F" "D" julia> hardwiredCluster(net5.edge[12], taxa) # descendants of 12th edge = CEF 6-element Vector{Bool}: 0 0 1 1 1 0 ``` See also [`hardwiredClusterDistance`](@ref) and [`hardwiredClusters`](@ref) """ function hardwiredCluster(edge::Edge,taxa::Union{AbstractVector{String},AbstractVector{Int}}) v = zeros(Bool,length(taxa)) hardwiredCluster!(v,edge,taxa) return v end hardwiredCluster!(v::Vector{Bool},edge::Edge,taxa::Union{AbstractVector{String},AbstractVector{Int}}) = hardwiredCluster!(v,edge,taxa,Int[]) function hardwiredCluster!(v::Vector{Bool},edge::Edge,taxa::Union{AbstractVector{String},AbstractVector{Int}}, visited::Vector{Int}) n = getchild(edge) if n.leaf j = findall(isequal(n.name), taxa) length(j)==1 || error("taxon $(n.name) was not found in taxon list, or more than once") v[j[1]]=true return nothing end if n.number in visited return nothing # n was already visited: exit. avoid infinite loop is isChild1 was bad. end push!(visited, n.number) for ce in n.edge if n === getparent(ce) hardwiredCluster!(v,ce,taxa,visited) end end return nothing end """ descendants(edge::Edge, internal::Bool=false) Return the node numbers of the descendants of a given edge: all descendant nodes if `internal` is true (internal nodes and tips), or descendant tips only otherwise (defaults). `edge` should belong in a rooted network for which `isChild1` is up-to-date. Run `directEdges!` beforehand. This is very important, otherwise one might enter an infinite loop, and the function does not test for this. ## Examples ```jldoctest julia> net5 = "(A,((B,#H1),(((C,(E)#H2),(#H2,F)),(D)#H1)));" |> readTopology |> directEdges! ; julia> PhyloNetworks.descendants(net5.edge[12], true) # descendants of 12th edge: all of them 7-element Vector{Int64}: -6 -7 4 6 5 -9 7 julia> PhyloNetworks.descendants(net5.edge[12]) # descendant leaves only 3-element Vector{Int64}: 4 5 7 ``` """ function descendants(edge::Edge, internal::Bool=false) visited = Int[] des = Int[] descendants!(des, visited, edge, internal) return des end function descendants!(des::Vector{Int}, visited::Vector{Int}, edge::Edge, internal::Bool=false) n = getchild(edge) if n.hybrid # only need to check previous visits for hybrid nodes n.number in visited && return nothing push!(visited, n.number) end if internal || n.leaf push!(des, n.number) end for ce in n.edge if isparentof(n, ce) descendants!(des, visited, ce, internal) end end return nothing end """ isdescendant(des:Node, anc::Node) Return true if `des` is a strict descendant of `anc`, using `isChild1` fields to determine the direction of edges. See [`isdescendant_undirected`](@ref) for a version that does not use `isChild1`. """ function isdescendant(des::Node, anc::Node) visited = Int[] for e in anc.edge anc !== getchild(e) || continue # skip parents of anc if isdescendant!(visited, des, e) return true end end return false end function isdescendant!(visited::Vector{Int}, des::Node, e::Edge) n = getchild(e) if n == des return true end if n.hybrid # only need to check previous visits for hybrid nodes if n.number in visited # n & its descendants were already visited: exit return false end push!(visited, n.number) end for ce in n.edge if isparentof(n, ce) if isdescendant!(visited, des, ce) return true; end end end return false end """ isdescendant_undirected(des:Node, ancestor::Node, parentedge) Return `true` if `des` is a strict descendant of `ancestor` when starting from edge `parentedge` and going towards `ancestor` onward, regardless of the field `isChild1` of tree edges; `false` otherwise. This is useful to know how descendant relationships would change as a result of reverting the direction of a tree edge, without actually modifying the direction (`isChild1`) of any edge. `parentedge` should be connected to `ancestor` (not checked). The direction of hybrid edges is respected (via `isChild1`), that is, the traversal does not go from the child to the parent of a hybrid edge. """ function isdescendant_undirected(des::Node, anc::Node, parentedge::Edge) visited = Int[] isdescendant_undirected!(visited, des, anc, parentedge) end function isdescendant_undirected!(visited::Vector{Int}, des::Node, anc::Node, parentedge::Edge) for e in anc.edge e !== parentedge || continue # do not go back up where we came from !e.hybrid || getparent(e) === anc || continue # do not go back up a parent hybrid edge of anc n = getOtherNode(e, anc) if n === des return true end if n.hybrid !(n.number in visited) || continue # skip to next edge is n already visited push!(visited, n.number) end if isdescendant_undirected!(visited, des, n, e) return true end end return false end """ ladderpartition(tree::HybridNetwork) For each node in `tree`, calculate the clade below each child edge of the node, and each clade moving up the "ladder" from the node to the root. The output is a tuple of 2 vectors (node) of vector (clade) of vectors (taxon in clade): `below,above`. More specifically, for node number `n`, `below[n]` is generally of vector of 2 clades: one for the left child and one for the right child of the node (unless the node is of degree 2 or is a polytomy). `above[n]` contains the grade of clades above node number `n`. WARNING: assumes that 1. node numbers and edge numbers can be used as indices, that is, be all distinct, positive, covering exactly 1:#nodes and 1:#edges. 2. edges are corrected directed (`isChild1` is up-to-date) and nodes have been pre-ordered already (field `nodes_changed` up-to-date). # examples ```jldoctest julia> tree = readTopology("(O,A,((B1,B2),(E,(C,D))));"); julia> PhyloNetworks.resetNodeNumbers!(tree; checkPreorder=true, type=:postorder) julia> printNodes(tree) node leaf hybrid hasHybEdge name inCycle edges'numbers 1 true false false O -1 1 2 true false false A -1 2 3 true false false B1 -1 3 4 true false false B2 -1 4 8 false false false -1 3 4 5 5 true false false E -1 6 6 true false false C -1 7 7 true false false D -1 8 9 false false false -1 7 8 9 10 false false false -1 6 9 10 11 false false false -1 5 10 11 12 false false false -1 1 2 11 julia> below, above = PhyloNetworks.ladderpartition(tree); julia> below 12-element Vector{Vector{Vector{Int64}}}: [[1]] [[2]] [[3]] [[4]] [[5]] [[6]] [[7]] [[3], [4]] [[6], [7]] [[5], [6, 7]] [[3, 4], [5, 6, 7]] [[1], [2], [3, 4, 5, 6, 7]] julia> for n in 8:12 println("clades below node ", n, ": ", join(below[n], " ")) end clades below node 8: [3] [4] clades below node 9: [6] [7] clades below node 10: [5] [6, 7] clades below node 11: [3, 4] [5, 6, 7] clades below node 12: [1] [2] [3, 4, 5, 6, 7] julia> above[8:12] # clades sister to and above nodes 8 through 12: 5-element Vector{Vector{Vector{Int64}}}: [[5, 6, 7], [1], [2]] [[5], [3, 4], [1], [2]] [[3, 4], [1], [2]] [[1], [2]] [] ``` """ function ladderpartition(net::HybridNetwork) nnodes = length(net.node) nleaf = length(net.leaf) for n in net.node n.number > 0 && n.number <= nnodes || error("node numbers must be in 1 - #nodes") end sort!([n.number for n in net.leaf]) == collect(1:nleaf) || error("leaves must come first") below = Vector{Vector{Vector{Int}}}(undef, nnodes) above = Vector{Vector{Vector{Int}}}(undef, nnodes) for nni in nnodes:-1:1 # post-order (not pre-order) traversal nn = net.nodes_changed[nni] above[nn.number] = Vector{Vector{Int}}(undef,0) # initialize if nn.leaf below[nn.number] = [[nn.number]] continue end below[nn.number] = Vector{Vector{Int}}(undef,0) # initialize !nn.hybrid || error("ladder partitions not implemented for non-tree networks") children = [getchild(e) for e in nn.edge] filter!(n -> n!=nn, children) for cc in children allbelowc = union(below[cc.number]...) push!(below[nn.number], allbelowc) for cc2 in children cc2 !=cc || continue push!(above[cc2.number], allbelowc) end end end # so far: above[n] contains the clades *sister* to node number n, only. # add those above = any above n's parent, using pre-order this time. for nni in 2:nnodes # avoid 1: it's the root, no parent, nothing to update nn = net.nodes_changed[nni] pn = getparent(nn).number # major parent number for clade in above[pn] push!(above[nn.number], clade); end end return below,above end """ deleteHybridThreshold!(net::HybridNetwork, threshold::Float64, nofuse=false, unroot=false, multgammas=false, keeporiginalroot=false) Deletes from a network all hybrid edges with heritability below a threshold gamma. Returns the network. - if threshold<0.5: delete minor hybrid edges with γ < threshold (or with a missing γ, for any threshold > -1.0) - if threshold=0.5: delete all minor hybrid edges (i.e normally with γ < 0.5, if γ non-missing) - `nofuse`: if true, do not fuse edges and keep original nodes. - `unroot`: if false, the root will not be deleted if it becomes of degree 2. - `multgammas`: if true, the modified edges have γ values equal to the proportion of genes that the extracted subnetwork represents. For an edge `e` in the modified network, the inheritance γ for `e` is the product of γs of all edges in the original network that have been merged into `e`. -`keeporiginalroot`: if true, the root will be retained even if of degree 1. Warnings: - by default, `nofuse` is false, partner hybrid edges are fused with their child edge and have their γ changed to 1.0. If `nofuse` is true: the γ's of partner hybrid edges are unchanged. - assumes correct `isMajor` fields, and correct `isChild1` fields to update `containRoot`. """ function deleteHybridThreshold!(net::HybridNetwork, gamma::Float64, nofuse=false::Bool, unroot=false::Bool, multgammas=false::Bool, keeporiginalroot=false::Bool) gamma <= 0.5 || error("deleteHybridThreshold! called with gamma = $(gamma)>0.5") for i = net.numHybrids:-1:1 # starting from last because net.hybrid changes as hybrids are removed. Empty range if 0 hybrids. i > lastindex(net.hybrid) && continue # removing 1 hybrid could remove several, if non-tree child net e = getparentedgeminor(net.hybrid[i]) # remove minor edge e if γ < threshold OR threshold=0.5 # warning: no check if γ and isMajor are in conflict if e.gamma < gamma || gamma == 0.5 # note: γ=-1 if missing, so < gamma threshold # deleteHybrid!(net.hybrid[i],net,true,false) # requires non-missing edge lengths # deleteHybridizationUpdate! requires level-1 network with corresponding attributes deletehybridedge!(net, e, nofuse, unroot, multgammas, true, keeporiginalroot) end end return net end """ displayedNetworks!(net::HybridNetwork, node::Node, keepNode=false, unroot=false, multgammas=false, keeporiginalroot=false) Extracts the two networks that simplify a given network at a given hybrid node: deleting either one or the other parent hybrid edge. If `nofuse` is true, the original edges (and nodes) are kept in both networks, provided that they have one or more descendant leaves. If `unroot` is true, the root will be deleted if it becomes of degree 2. If `keeporiginalroot` is true, the root is retained even if it is of degree 1. - the original network is modified: the minor edge removed. - returns one HybridNetwork object: the network with the major edge removed """ function displayedNetworks!(net::HybridNetwork, node::Node, nofuse=false::Bool, unroot=false::Bool, multgammas=false::Bool, keeporiginalroot=false::Bool) node.hybrid || error("will not extract networks from tree node $(node.number)") ind = findfirst(x -> x===node, net.node) ind !== nothing || error("node $(node.number) was not found in net") netmin = deepcopy(net) emin = getparentedgeminor(node) deletehybridedge!(net , emin, nofuse, unroot, multgammas, true, keeporiginalroot) emaj = getparentedge(netmin.node[ind]) # hybrid node & edge in netmin deletehybridedge!(netmin, emaj, nofuse, unroot, multgammas, true, keeporiginalroot) return netmin end """ displayedTrees(net::HybridNetwork, gamma::Float64; nofuse=false::Bool, unroot=false::Bool, multgammas=false::Bool, keeporiginalroot=false::Bool) Extracts all trees displayed in a network, following hybrid edges with heritability >= γ threshold (or >0.5 if threshold=0.5) and ignoring any hybrid edge with heritability lower than γ. Returns an array of trees, as HybridNetwork objects. `nofuse`: if true, do not fuse edges (keep degree-2 nodes) during hybrid edge removal. `unroot`: if false, the root will not be deleted if it becomes of degree 2 unless keeporiginalroot is true. `multgammas`: if true, the edges in the displayed trees have γ values equal to the proportion of genes that the edge represents, even though all these edges are tree edges. The product of all the γ values across all edges is the proportion of genes that the tree represents. More specifically, edge `e` in a given displayed tree has γ equal to the product of γs of all edges in the original network that have been merged into `e`. `keeporiginalroot`: if true, keep root even if of degree 1. Warnings: - if `nofuse` is true: the retained partner hybrid edges have their γ values unchanged, but their `isMajor` is changed to true - assume correct `isMajor` attributes. """ function displayedTrees(net0::HybridNetwork, gamma::Float64; nofuse=false::Bool, unroot=false::Bool, multgammas=false::Bool, keeporiginalroot=false::Bool) trees = HybridNetwork[] net = deepcopy(net0) deleteHybridThreshold!(net,gamma,nofuse,unroot, multgammas, keeporiginalroot) displayedTrees!(trees,net,nofuse,unroot, multgammas, keeporiginalroot) return trees # should have length 2^net.numHybrids end """ inheritanceWeight(tree::HybridNetwork) Return the *log* inheritance weight of a network or tree (as provided by [`displayedTrees`](@ref) with `nofuse` = true for instance). For a tree displayed in a network, its inheritance weight is the log of the product of γ's of all edges retained in the tree. To avoid underflow, the log is calculated: i.e. sum of log(γ) across retained edges. If any edge has a negative γ, it is assumed to mean that its γ is missing, and the function returns `missing`. # Example ```julia-repl julia> net = readTopology("(((A,(B)#H1:::0.9),(C,#H1:::0.1)),D);"); julia> trees = displayedTrees(net,0.0; nofuse=true); julia> PhyloNetworks.inheritanceWeight.(trees) 2-element Vector{Float64}: -0.105361 -2.30259 ``` """ function inheritanceWeight(tree::HybridNetwork) ltw = 0.0 for e in tree.edge e.gamma != 1.0 || continue if e.gamma < 0.0 return missing; end # any negative γ assumed -1.0: missing ltw += log(e.gamma) end return ltw end """ majorTree(net::HybridNetwork; nofuse=false::Bool, unroot=false::Bool, keeporiginalroot=false::Bool) Extract the major tree displayed in a network, keeping the major edge and dropping the minor edge at each hybrid node. `nofuse`: if true, edges and degree-2 nodes are retained during edge removal. Otherwise, at each reticulation the child edge (below the hybrid node) is retained: the major hybrid edge is fused with it. `unroot`: is true, the root will be deleted if it becomes of degree 2. `keeporiginalroot`: the network's root is kept even if it becomes of degree 1. Warnings: - if `nofuse` is true: the hybrid edges that are retained (without fusing) have their γ values unchanged, but their `isMajor` is changed to true - assume correct `isMajor` attributes. """ majorTree(net::HybridNetwork; nofuse=false::Bool, unroot=false::Bool, keeporiginalroot=false::Bool) = displayedTrees(net,0.5; nofuse=nofuse, unroot=unroot, keeporiginalroot=keeporiginalroot)[1] # expands current list of trees, with trees displayed in a given network function displayedTrees!(trees::Array{HybridNetwork,1}, net::HybridNetwork, nofuse=false::Bool, unroot=false::Bool, multgammas=false::Bool, keeporiginalroot=false::Bool) if isTree(net) # warning: no update of edges' containRoot (true) or edges' and nodes' inCycle (-1) push!(trees, net) else netmin = displayedNetworks!(net, net.hybrid[1], nofuse, unroot, multgammas, keeporiginalroot) displayedTrees!(trees, net, nofuse, unroot, multgammas, keeporiginalroot) displayedTrees!(trees, netmin, nofuse, unroot, multgammas, keeporiginalroot) end end """ minorTreeAt(net::HybridNetwork, hybindex::Integer, nofuse=false, unroot=false::Bool) Extract the tree displayed in the network, following the major hybrid edge at each hybrid node, except at the ith hybrid node (i=`hybindex`), where the minor hybrid edge is kept instead of the major hybrid edge. If `nofuse` is true, edges are not fused (degree-2 nodes are kept). If `unroot` is true, the root will be deleted if it becomes of degree 2. Warning: assume correct `isMajor` fields. """ function minorTreeAt(net::HybridNetwork, hybindex::Integer, nofuse=false::Bool, unroot=false::Bool) hybindex <= length(net.hybrid) || error("network has fewer hybrid nodes than index $(hybindex).") tree = deepcopy(net) hybedge = getparentedge(tree.hybrid[hybindex]) # major parent deletehybridedge!(tree, hybedge, nofuse, unroot) # delete major hybrid edge at reticulation of interest return majorTree(tree; nofuse=nofuse, unroot=unroot) # all remaining minor edges removed: now it's a tree. end """ displayedNetworkAt!(net::HybridNetwork, node::Node, nofuse=false, unroot=false, multgammas=false) Delete all the minor hybrid edges, except at input node. The network is left with a single hybridization, and otherwise displays the same major tree as before. If `nofuse` is true, edges are not fused (degree-2 nodes are kept). Warning: assume correct `isMajor` fields. """ function displayedNetworkAt!(net::HybridNetwork, node::Node, nofuse=false::Bool, unroot=false::Bool, multgammas=false::Bool) node.hybrid || error("will not extract network from tree node $(node.number)") for i = net.numHybrids:-1:1 # starting from last because net.hybrid changes as hybrids are removed. Empty range if 0 hybrids. net.hybrid[i] != node || continue emin = getparentedgeminor(net.hybrid[i]) deletehybridedge!(net, emin, nofuse, unroot, multgammas) end end """ hardwiredClusterDistance(net1::HybridNetwork, net2::HybridNetwork, rooted::Bool) Hardwired cluster distance between the topologies of `net1` and `net2`, that is, the number of hardwired clusters found in one network and not in the other (with multiplicity, see below). If the 2 networks are trees, this is the Robinson-Foulds distance. If rooted=false, then both networks are considered as semi-directed. Networks are assumed bicombining (each hybrid has exactly 2 parents, no more). ## Dissimilarity vs distance This is *not* a distance per se on the full space of phylogenetic networks: there are pairs of distinct networks for which this dissimilarity is 0. But it is a distance on some classes of networks, such as the class of tree-child networks that are "normal" (without shortcuts), or the class of tree-child networks that can be assigned node ages such that hybrid edges have length 0 and tree edges have non-negative lengths. See [Cardona, Rossello & Valiente (2008)](https://doi.org/10.1016/j.mbs.2007.11.003), [Cardona, Llabres, Rossello & Valiente (2008)](https://doi.org/10.1109/TCBB.2008.70), and [Huson, Rupp, Scornavacca (2010)](https://doi.org/10.1017/CBO9780511974076). ## Example ```jldoctest julia> net1 = readTopology("(t6,(t5,((t4,(t3,((t2,t1))#H1)),#H1)));"); julia> taxa = sort(tipLabels(net1)); # t1 through t6, sorted alphabetically julia> # using PhyloPlots; plot(net1, showedgenumber=true); julia> # in matrix below: column 1: edge number. last column: tree (10) vs hybrid (11) edge # middle columns: for 'taxa': t1,...t6. 1=descendant, 0=not descendant hardwiredClusters(net1, taxa) 6×8 Matrix{Int64}: 13 1 1 1 1 1 0 10 12 1 1 1 1 0 0 10 10 1 1 1 1 0 0 10 9 1 1 1 0 0 0 10 8 1 1 0 0 0 0 11 7 1 1 0 0 0 0 10 julia> net2 = readTopology("(t6,(t5,((t4,(t3)#H1),(#H1,(t1,t2)))));"); julia> hardwiredClusters(net2, taxa) 6×8 Matrix{Int64}: 13 1 1 1 1 1 0 10 12 1 1 1 1 0 0 10 6 0 0 1 1 0 0 10 5 0 0 1 0 0 0 11 11 1 1 1 0 0 0 10 10 1 1 0 0 0 0 10 julia> hardwiredClusterDistance(net1, net2, true) # true: as rooted networks 4 ``` ## What is a hardwired cluster? Each edge in a network is associated with its *hardwired cluster*, that is, the set of all its descendant taxa (leaves). The set of hardwired cluster of a network is the set of its edges' hardwired clusters. The dissimilarity `d_hard` defined in [Huson, Rupp, Scornavacca (2010)](https://doi.org/10.1017/CBO9780511974076) is the number of hardwired clusters that are in one network but not in the other. This implementation is a slightly more discriminative version of `d_hard`, where each cluster is counted with multiplicity and annotated with its edge's hybrid status, as follows: - External edges are not counted (they are tree edges to a leaf, shared by all phylogenetic networks). - A cluster is counted for each edge for which it's the hardwired cluster. - At a given hybrid node, both hybrid partner edges have the same cluster, so this cluster is only counted once for both partners. - A given cluster is matched between the two networks only if it's the cluster from a tree edge in both networks, or from a hybrid edge in both networks. In the example above, `net1` has a shortcut (hybrid edge 11) resulting in 2 tree edges (12 and 10) with the same cluster {t1,t2,t3,t4}. So cluster {t1,t2,t3,t4} has multiplicity 2 in `net1`. `net2` also has this cluster, but only associated with 1 tree edge, so this cluster contributes (2-1)=1 towards the hardwired cluster distance between the two networks. The distance of 4 corresponds to these 4 clusters: - {t1,t2,t3,t4}: twice in net1, once in net2 - {t3,t4}: absent in net1, once in net2 - {t1,t2}: twice in net1 (from a hybrid edge & a tree edge), once in net2 - {t3}: absent in net1 (because external edges are not counted), once in net2 (from a hybrid edge). Degree-2 nodes cause multiple edges to have the same cluster, so counting clusters with multiplicity distinguishes a network with extra degree-2 nodes from the "same" network after these nodes have been suppressed (e.g. with [`PhyloNetworks.fuseedgesat!`](@ref) or [`PhyloNetworks.shrinkedge!`](@ref)). ## Networks as semi-directed If `rooted` is false and one of the phylogenies is not a tree (1+ reticulations), then all degree-2 nodes are removed before comparing the hardwired clusters, and the minimum distance is returned over all possible ways to root the networks at internal nodes. See also: [`hardwiredClusters`](@ref), [`hardwiredCluster`](@ref) """ function hardwiredClusterDistance(net1::HybridNetwork, net2::HybridNetwork, rooted::Bool) bothtrees = (net1.numHybrids == 0 && net2.numHybrids == 0) rooted || bothtrees || return hardwiredClusterDistance_unrooted(net1, net2) # tries all roots, but removes degree-2 nodes taxa = sort!(String[net1.leaf[i].name for i in 1:net1.numTaxa]) length(setdiff(taxa, String[net2.leaf[i].name for i in 1:net2.numTaxa])) == 0 || error("net1 and net2 do not share the same taxon set. Please prune networks first.") nTax = length(taxa) if bothtrees # even if rooted, different treatment at the root if root=leaf M1 = tree2Matrix(net1, taxa, rooted=rooted) M2 = tree2Matrix(net2, taxa, rooted=rooted) else M1 = hardwiredClusters(net1, taxa) # last row: 10/11 if tree/hybrid edge. M2 = hardwiredClusters(net2, taxa) #println("M1="); print(M1); println("\nM2="); print(M2); println("\n"); end dis = 0 n2ci = collect(1:size(M2, 1)) # cluster indices for i1 in 1:size(M1,1) found = false m1 = 1 .- M1[i1,2:end] # going to the end: i.e. we want to match a tree edge with a tree edge # and hybrid edge with hybrid edge for j in length(n2ci):-1:1 # check only unmatched cluster indices, in reverse i2 = n2ci[j] if (M1[i1,2:end] == M2[i2,2:end] || ( !rooted && m1 == M2[i2,2:end]) ) found = true deleteat!(n2ci, j) # a cluster can be repeated break end end if !found dis += 1 end end # (size(M1)[1] - dis) edges have been found in net2, dis edges have not. # so size(M2)[1] - (size(M1)[1] - dis) edges in net2 are not in net1. dis + dis + size(M2)[1] - size(M1)[1] end """ hardwiredClusterDistance_unrooted(net1::HybridNetwork, net2::HybridNetwork) Miminum hardwired cluster dissimilarity between the two networks, considered as unrooted (or semi-directed). This dissimilarity is defined as the minimum rooted distance, over all root positions that are compatible with the direction of hybrid edges. Called by [`hardwiredClusterDistance`](@ref). To avoid repeating identical clusters, all degree-2 nodes are deleted before starting the comparison. Since rooting the network at a leaf creates a root node of degree 2 and an extra cluster, leaves are excluded from possible rooting positions. """ function hardwiredClusterDistance_unrooted(net1::HybridNetwork, net2::HybridNetwork) return hardwiredClusterDistance_unrooted!(deepcopy(net1), deepcopy(net2)) end function hardwiredClusterDistance_unrooted!(net1::HybridNetwork, net2::HybridNetwork) #= fixit: inefficient function, because r1 * r2 "M" matrices of hardwiredClusters() are calculated, where ri = # root positions in neti. Rewrite to calculate only r1 + r2 M's. =# removedegree2nodes!(net1) # because re-rooting would remove them in an removedegree2nodes!(net2) # unpredictable order # find all permissible positions for the root net1roots = [n.number for n in net1.node if !n.leaf] #= disallow the root at a leaf: adding a degree-2 node adds a cluster that could be artificially matched to a cluster from a degree-3 node sister to a hybrid edge, when a the leaf edge is the donor. =# for i in length(net1roots):-1:1 # reverse order, to delete some of them try rootatnode!(net1, net1roots[i]) # tricky: rootatnode adds a degree-2 node if i is a leaf, # and delete former root node if it's of degree 2. catch e isa(e, RootMismatch) || rethrow(e) deleteat!(net1roots, i) end end net2roots = [n.number for n in net2.node if !n.leaf] for i in length(net2roots):-1:1 try rootatnode!(net2, net2roots[i]) catch e isa(e, RootMismatch) || rethrow(e) deleteat!(net2roots, i) end end bestdissimilarity = typemax(Int) bestns = missing for n1 in net1roots rootatnode!(net1, n1) for n2 in net2roots rootatnode!(net2, n2) diss = hardwiredClusterDistance(net1, net2, true) # rooted = true now if diss < bestdissimilarity bestns = (n1, n2) bestdissimilarity = diss end end end # @info "best root nodes: $bestns" # warning: original roots (and edge directions) NOT restored return bestdissimilarity end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
20894
# functions to delete hybridization # originally in functions.jl # Claudia MArch 2015 # --------------------------------- delete hybridization ------------------------------- # function to identify inCycle (with priority queue) # based on updateInCycle as it is the exact same code # only without changing the incycle attribute # only returning array of edges/nodes affected by the hybrid # used when attempting to delete # input: hybrid node around which we want to identify inCycle # returns tuple: nocycle, array of edges changed, array of nodes changed # check: is this traversal much faster than a simple loop over # all edges/nodes and check if incycle==hybrid.number? function identifyInCycle(net::Network,node::Node) node.hybrid || error("node $(node.number) is not hybrid, cannot identifyInCycle") start = node; hybedge = getparentedgeminor(node) lastnode = getOtherNode(hybedge,node) dist = 0; queue = PriorityQueue(); path = Node[]; net.edges_changed = Edge[]; net.nodes_changed = Node[]; push!(net.edges_changed,hybedge); push!(net.nodes_changed,node); found = false; net.visited = [false for i = 1:size(net.node,1)]; enqueue!(queue,node,dist); while(!found) if(isempty(queue)) return true, net.edges_changed, net.nodes_changed else curr = dequeue!(queue); if isEqual(curr,lastnode) found = true; push!(path,curr); elseif !net.visited[getIndex(curr,net)] net.visited[getIndex(curr,net)] = true atstart = isEqual(curr,start) for e in curr.edge e.isMajor || continue other = getOtherNode(e,curr) if atstart || (!other.leaf && !net.visited[getIndex(other,net)]) other.prev = curr dist = dist+1 enqueue!(queue,other,dist) end end end end end # end while curr = pop!(path); while(!isEqual(curr, start)) if(curr.inCycle == start.number) push!(net.nodes_changed, curr); edge = getConnectingEdge(curr,curr.prev); if(edge.inCycle == start.number) push!(net.edges_changed, edge); end curr = curr.prev; end end return false, net.edges_changed, net.nodes_changed end # aux function to traverse the network # similar to traverseContainRoot but only # identifying the edges that would be changed by a given # hybridization # warning: it does not go accross hybrid node/edge, # nor tree node with minor hybrid edge function traverseIdentifyRoot(node::Node, edge::Edge, edges_changed::Array{Edge,1}) if(!node.leaf && !node.hybrid) for e in node.edge if(!isEqual(edge,e) && e.isMajor && !e.hybrid) other = getOtherNode(e,node); push!(edges_changed, e); if(!other.hybrid) #if(!other.hasHybEdge) traverseIdentifyRoot(other,e, edges_changed); #else # if(hybridEdges(other)[1].isMajor) # traverseIdentifyRoot(other,e, edges_changed); # end #end end end end end end # function to identify containRoot # depending on a hybrid node on the network # input: hybrid node (can come from searchHybridNode) # return array of edges affected by the hybrid node function identifyContainRoot(net::HybridNetwork, node::Node) node.hybrid || error("node $(node.number) is not hybrid, cannot identify containRoot") net.edges_changed = Edge[]; for e in node.edge if(!e.hybrid) other = getOtherNode(e,node); push!(net.edges_changed,e); traverseIdentifyRoot(other,e, net.edges_changed); end end return net.edges_changed end # function to undo the effect of a hybridization # and then delete it # input: network, hybrid node, random flag # random = true, deletes one hybrid egde at random # (minor with prob 1-gamma, major with prob gamma) # random = false, deletes the minor edge always # warning: it uses the gamma of the hybrid edges even if # it is not identifiable like in bad diamond I (assumes undone by now) # blacklist = true: add the edge as a bad choice to put a hybridization (not fully tested) function deleteHybridizationUpdate!(net::HybridNetwork, hybrid::Node, random::Bool, blacklist::Bool) hybrid.hybrid || error("node $(hybrid.number) is not hybrid, so we cannot delete hybridization event around it") @debug "MOVE: delete hybridization on hybrid node $(hybrid.number)" nocycle, edgesInCycle, nodesInCycle = identifyInCycle(net,hybrid); !nocycle || error("the hybrid node $(hybrid.number) does not create a cycle") edgesRoot = identifyContainRoot(net,hybrid); edges = hybridEdges(hybrid); undoGammaz!(hybrid,net); othermaj = getOtherNode(edges[1],hybrid) edgesmaj = hybridEdges(othermaj) @debug "edgesmaj[3] $(edgesmaj[3].number) is the one to check if containRoot=false already: $(edgesmaj[3].containRoot)" if(edgesmaj[3].containRoot) #if containRoot=true, then we need to undo push!(edgesRoot, edges[1]) ## add hybrid edges to edgesRoot to undo containRoot push!(edgesRoot, edges[2]) undoContainRoot!(edgesRoot); end limit = edges[1].gamma @debug (limit < 0.5 ? "strange major hybrid edge $(edges[1].number) with γ $limit < 0.5" : (limit == 1.0 ? "strange major hybrid edge $(edges[1].number) with γ = $limit" : "")) if(random) minor = rand() < limit ? false : true else minor = true; end deleteHybrid!(hybrid,net,minor, blacklist) undoInCycle!(edgesInCycle, nodesInCycle); #moved after deleteHybrid to mantain who is incycle when deleteEdge and look for partition undoPartition!(net,hybrid, edgesInCycle) end deleteHybridizationUpdate!(net::HybridNetwork, hybrid::Node) = deleteHybridizationUpdate!(net, hybrid, true, false) # function to delete a hybridization event # input: hybrid node and network # minor: true (deletes minor edge), false (deletes major) # warning: it is meant after undoing the effect of the # hybridization in deleteHybridizationUpdate! # by itself, it leaves things as is # branch lengths of -1.0 are interpreted as missing. function deleteHybrid!(node::Node,net::HybridNetwork,minor::Bool, blacklist::Bool) node.hybrid || error("node $(node.number) has to be hybrid for deleteHybrid") if(minor) hybedge1,hybedge2,treeedge1 = hybridEdges(node); other1 = getOtherNode(hybedge1,node); other2 = getOtherNode(hybedge2,node); other3 = getOtherNode(treeedge1,node); if(hybedge1.number > treeedge1.number) setLength!(treeedge1, addBL(treeedge1.length, hybedge1.length)); removeNode!(node,treeedge1); setNode!(treeedge1,other1); setEdge!(other1,treeedge1); removeEdge!(other1, hybedge1); deleteEdge!(net,hybedge1); #treeedge1.containRoot = (!treeedge1.containRoot || !hybedge1.containRoot) ? false : true #causes problems if hybrid.CR=false if(blacklist) println("put in blacklist edge $(treeedge1.number)") push!(net.blacklist, treeedge1.number) end else makeEdgeTree!(hybedge1,node) other1.hasHybEdge = false; setLength!(hybedge1, addBL(hybedge1.length, treeedge1.length)); removeNode!(node,hybedge1); setNode!(hybedge1,other3); setEdge!(other3,hybedge1); removeEdge!(other3,treeedge1); deleteEdge!(net,treeedge1); hybedge1.containRoot = (!treeedge1.containRoot || !hybedge1.containRoot) ? false : true if(blacklist) println("put in blacklist edge $(hybedge1.number)") push!(net.blacklist, hybedge1.number) end end hybindex = findfirst([e.hybrid for e in other2.edge]); isnothing(hybindex) && error("didn't find hybrid edge in other2") if(hybindex == 1) treeedge1 = other2.edge[2]; treeedge2 = other2.edge[3]; elseif(hybindex == 2) treeedge1 = other2.edge[1]; treeedge2 = other2.edge[3]; elseif(hybindex == 3) treeedge1 = other2.edge[1]; treeedge2 = other2.edge[2]; else error("strange node has more than three edges") end treenode1 = getOtherNode(treeedge1,other2); treenode2 = getOtherNode(treeedge2,other2); if(abs(treeedge1.number) > abs(treeedge2.number)) setLength!(treeedge2, addBL(treeedge2.length, treeedge1.length)); removeNode!(other2,treeedge2); setNode!(treeedge2,treenode1); setEdge!(treenode1,treeedge2); removeEdge!(treenode1,treeedge1); deleteEdge!(net,treeedge1); treeedge2.containRoot = (!treeedge1.containRoot || !treeedge2.containRoot) ? false : true if(blacklist) println("put in blacklist edge $(treeedge2.number)") push!(net.blacklist, treeedge2.number) end else setLength!(treeedge1, addBL(treeedge2.length, treeedge1.length)); removeNode!(other2,treeedge1); setNode!(treeedge1,treenode2); setEdge!(treenode2,treeedge1); removeEdge!(treenode2,treeedge2); deleteEdge!(net,treeedge2); treeedge1.containRoot = (!treeedge1.containRoot || !treeedge2.containRoot) ? false : true if(blacklist) println("put in blacklist edge $(treeedge1.number)") push!(net.blacklist, treeedge1.number) end end #removeHybrid!(net,node); deleteNode!(net,node); deleteNode!(net,other2); deleteEdge!(net,hybedge2); else hybedge1,hybedge2,treeedge1 = hybridEdges(node); other1 = getOtherNode(hybedge1,node); other2 = getOtherNode(hybedge2,node); setLength!(treeedge1, addBL(treeedge1.length, hybedge2.length)) removeEdge!(other2,hybedge2) removeNode!(node,treeedge1) setEdge!(other2,treeedge1) setNode!(treeedge1,other2) #removeHybrid!(net,node) deleteNode!(net,node) deleteEdge!(net,hybedge1) deleteEdge!(net,hybedge2) removeEdge!(other1,hybedge1) size(other1.edge,1) == 2 || error("strange node $(other1.number) had 4 edges") if(abs(other1.edge[1].number) < abs(other1.edge[2].number)) edge = other1.edge[1] otheredge = other1.edge[2] else edge = other1.edge[2] otheredge = other1.edge[1] end setLength!(other1.edge[1], addBL(other1.edge[1].length, other1.edge[2].length)) other3 = getOtherNode(otheredge,other1); removeNode!(other1,edge) removeEdge!(other3,otheredge) setEdge!(other3,edge) setNode!(edge,other3) deleteNode!(net,other1) deleteEdge!(net,otheredge) end end deleteHybrid!(node::Node,net::HybridNetwork,minor::Bool) = deleteHybrid!(node,net,minor, false) """ deletehybridedge!(net::HybridNetwork, edge::Edge, nofuse=false, unroot=false, multgammas=false, simplify=true, keeporiginalroot=false) Delete a hybrid `edge` from `net` and return the network. The network does not have to be of level 1 and may contain polytomies, although each hybrid node must have exactly 2 parents. Branch lengths are updated, allowing for missing values. If `nofuse` is false, when `edge` is removed, its child (hybrid) node is removed and its partner hybrid edge is removed. Its child edge is retained (below the hybrid node), fused with the former partner, with new length: old length + length of `edge`'s old partner. Any 2-cycle is simplified into a single edge, unless `simplify` is false. If `nofuse` is true, edges with descendant leaves are kept as is, and are not fused. Nodes are retained during edge removal, provided that they have at least one descendant leaf. The hybrid edge that is partner to `edge` becomes a tree edge, but has its γ value unchanged (it is not set to 1), since it is not merged with its child edge after removal of the reticulation. Also, 2-cycles are not simplified if `nofuse` is true. That is, if we get 2 hybrid edges both from the same parent to the same child, these hybrid edges are retained without being fused into a single tree edge. If `unroot` is false and if the root is up for deletion during the process, it will be kept if it's of degree 2 or more. A root node of degree 1 will be deleted unless `keeporiginalroot` is true. If `multgammas` is true: inheritance weights are kept by multiplying together the inheritance γ's of edges that are merged. For example, if there is a hybrid ladder, the partner hybrid edge remains a hybrid edge (with a new partner), and its γ is the product of the two hybrid edges that have been fused. So it won't add up to 1 with its new partner's γ. If `keeporiginalroot` is true, a root of degree one will not be deleted. Warnings: - `containRoot` is updated, but this requires correct `isChild1` fields - if the parent of `edge` is the root and if `nofuse` is false, the root is moved to keep the network unrooted with a root of degree two. - does *not* update attributes needed for snaq! (like inCycle, edge.z, edge.y etc.) """ function deletehybridedge!(net::HybridNetwork, edge::Edge, nofuse=false::Bool, unroot=false::Bool, multgammas=false::Bool, simplify=true::Bool, keeporiginalroot=false::Bool) edge.hybrid || error("edge $(edge.number) has to be hybrid for deletehybridedge!") n1 = getchild(edge) # child of edge, to be deleted unless nofuse n1.hybrid || error("child node $(n1.number) of hybrid edge $(edge.number) should be a hybrid.") n1degree = length(n1.edge) n2 = getparent(edge) # parent of edge, to be deleted too n2degree = length(n2.edge) # next: keep hybrid node n1 if it has 4+ edges or if keepNode. # otherwise: detach n1, then delete recursively delete_n1_recursively = false if n1degree < 3 error("node $(n1.number) has $(length(n1.edge)) edges instead of 3+"); # alternatively: error if degree < 2 or leaf, # warning if degree=2 and internal node, then # delete_n1_recursively = true # n1 doesn't need to be detached first elseif n1degree == 3 && !nofuse # then fuse 2 of the edges and detach n1 delete_n1_recursively = true pe = nothing # will be other parent (hybrid) edge of n1 ce = nothing # will be child edge of n1, to be merged with pe for e in n1.edge if e.hybrid && e!==edge && n1===getchild(e) pe = e; end if !e.hybrid || n1===getparent(e) ce = e; end # does *not* assume correct isChild1 for tree edges :) end pn = getparent(pe); # parent node of n1, other than n2 atRoot = (net.node[net.root] ≡ n1) # n1 should not be root, but if so, pn will be new root # if pe may contain the root, then allow the root on ce and below if pe.containRoot allowrootbelow!(ce) # warning: assumes correct `isChild1` for ce and below end # next: replace ce by pe+ce, detach n1 from pe & ce, remove pe from network. ce.length = addBL(ce.length, pe.length) if multgammas ce.gamma = multiplygammas(ce.gamma, pe.gamma) end removeNode!(n1,ce) # ce now has 1 single node cn setNode!(ce,pn) # ce now has 2 nodes in this order: cn, pn ce.isChild1 = true setEdge!(pn,ce) removeEdge!(pn,pe) # if (pe.number<ce.number) ce.number = pe.number; end # bad to match edges between networks removeEdge!(n1,pe); removeEdge!(n1,ce) # now n1 attached to edge only deleteEdge!(net,pe,part=false) # decreases net.numEdges by 1 removeHybrid!(net,n1) # decreases net.numHybrids by 1 n1.hybrid = false edge.hybrid = false; edge.isMajor = true # n1 not leaf, and not added to net.leaf, net.numTaxa unchanged if atRoot i = findfirst(x -> x===pn, net.node) i !== nothing || error("node $(pn.number) not in net!") net.root = i end # below: we will need to delete n1 recursively (hence edge) else # n1 has 4+ edges (polytomy) or 3 edges but we want to keep it anyway: # keep n1 but detach it from 'edge', set its remaining parent to major tree edge pe = getpartneredge(edge, n1) # partner edge: keep it this time if !pe.isMajor pe.isMajor=true; end pe.hybrid = false # note: pe.gamma *not* set to 1.0 here removeEdge!(n1,edge) # does not update n1.hybrid at this time removeHybrid!(net,n1) # removes n1 from net.hybrid, updates net.numHybrids n1.hybrid = false if pe.containRoot allowrootbelow!(pe) # warning: assumes correct `isChild1` for pe and below end # below: won't delete n1, delete edge instead end formernumhyb = net.numHybrids # next: delete n1 recursively, or delete edge and delete n2 recursively. # keep n2 if it has 4+ edges (or if nofuse). 1 edge should never occur. # If root, would have no parent: treat network as unrooted and change the root. if delete_n1_recursively deleteleaf!(net, n1.number; index=false, nofuse=nofuse, simplify=simplify, unroot=unroot, multgammas=multgammas, keeporiginalroot=keeporiginalroot) # else: delete "edge" then n2 as appropriate elseif n2degree == 1 error("node $(n2.number) (parent of hybrid edge $(edge.number) to be deleted) has 1 edge only!") else # fixit: if n2degree == 2 && n2 === net.node[net.root] and # if we want to keep original root: then delete edge but keep n2 # detach n2 from edge, remove hybrid 'edge' from network removeEdge!(n2,edge) deleteEdge!(net,edge,part=false) # remove n2 as appropriate later (recursively) deleteleaf!(net, n2.number; index=false, nofuse=nofuse, simplify=simplify, unroot=unroot, multgammas=multgammas, keeporiginalroot=keeporiginalroot) end if net.numHybrids != formernumhyb # deleteleaf! does not update containRoot allowrootbelow!(net) end return net end # function to update net.partition after deleting a hybrid node # needs a list of the edges in cycle function undoPartition!(net::HybridNetwork, hybrid::Node, edgesInCycle::Vector{Edge}) hybrid.hybrid || error("node $(hybrid.number) is not hybrid, and we need hybrid node inside deleteHybUpdate for undoPartition") if(net.numHybrids == 0) net.partition = Partition[] else cycles = Int[] edges = Edge[] N = length(net.partition) i = 1 while(i <= N) @debug "hybrid number is $(hybrid.number) and partition is $([e.number for e in net.partition[i].edges]), with cycle $(net.partition[i].cycle)" if(in(hybrid.number,net.partition[i].cycle)) @debug "hybrid number matches with partition.cycle" p = splice!(net.partition,i) @debug "after splice, p partition has edges $([e.number for e in p.edges]) and cycle $(p.cycle)" ind = findfirst(isequal(hybrid.number), p.cycle) isnothing(ind) && error("hybrid not found in p.cycle") deleteat!(p.cycle,ind) #get rid of that hybrid number cycles = vcat(cycles,p.cycle) edges = vcat(edges,p.edges) @debug "edges is $([e.number for e in edges]) and cycles is $(cycles)" N = length(net.partition) else i += 1 end end for e in edgesInCycle @debug "edge in cycle is $(e.number)" if(isEdgeNumIn(e,net.edge)) #only include edge if still in net @debug "edge is in net still" push!(edges,e) end end newPartition = Partition(unique(cycles),edges) @debug "new partition with cycle $(newPartition.cycle), edges $([e.number for e in newPartition.edges])" push!(net.partition,newPartition) end end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
1667
@deprecate readNexusTrees readnexus_treeblock @deprecate getChild getchild false @deprecate getChildren getchildren false @deprecate getChildEdge getchildedge false @deprecate getParents getparents false @deprecate getParent getparent false @deprecate getMajorParent getparent false @deprecate getMinorParent getparentminor false @deprecate getMajorParentEdge getparentedge false @deprecate getMinorParentEdge getparentedgeminor false @deprecate getPartner getpartneredge false function Base.getproperty(mm::PhyloNetworkLinearModel, f::Symbol) if f === :model Base.depwarn("""accessing the 'model' field of PhyloNetworkLinearModel's is deprecated, as they are no longer wrapped in a TableRegressionModel. They can be used directly now.""", :getproperty) # force=true to show warning. currently silent by default return mm elseif f === :mf Base.depwarn("""accessing the 'mf' field of PhyloNetworkLinearModel's is deprecated, as they are no longer wrapped in a TableRegressionModel. Use `formula(m)` to access the model formula.""", :getproperty) form = formula(mm) return ModelFrame{Nothing, typeof(mm)}(form, nothing, nothing, typeof(mm)) elseif f === :mm Base.depwarn("""accessing the 'mm' field of PhyloNetworkLinearModel's is deprecated, as they are no longer wrapped in a TableRegressionModel. Use `modelmatrix(m)` to access the model matrix.""", :getproperty) modmatr = modelmatrix(mm) return ModelMatrix{typeof(modmatr)}(modmatr, Int[]) else return getfield(mm, f) end end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
8538
# functions to describe a HybridNetwork object to avoid accessing the attributes directly # Claudia August 2015 """ tipLabels(x) Return a vector of taxon names at the leaves, for objects of various types: `HybridNetwork`, Vector of `HybridNetwork`s (in which case the union is taken then sorted), Vector of `Quartet`s, `DataCF`, `TraitSimulation`, `MatrixTopologicalOrder`. For a network, the taxon names are coerced to strings. """ function tipLabels(net::HybridNetwork) return String[l.name for l in net.leaf] # AbstractString does not work for use by tree2Matrix end """ `fittedQuartetCF(d::DataCF, format::Symbol)` return a data frame with the observed and expected quartet concordance factors after estimation of a network with snaq(T,d). The format can be :wide (default) or :long. - if wide, the output has one row per 4-taxon set, and each row has 10 columns: 4 columns for the taxon names, 3 columns for the observed CFs and 3 columns for the expected CF. - if long, the output has one row per quartet, i.e. 3 rows per 4-taxon sets, and 7 columns: 4 columns for the taxon names, one column to give the quartet resolution, one column for the observed CF and the last column for the expected CF. see also: `topologyQPseudolik!` and `topologyMaxQPseudolik!` to update the fitted CF expected under a specific network, inside the DataCF object `d`. """ function fittedQuartetCF(d::DataCF, format=:wide::Symbol) if format == :wide df=DataFrame( tx1 = [q.taxon[1] for q in d.quartet], tx2 = [q.taxon[2] for q in d.quartet], tx3 = [q.taxon[3] for q in d.quartet], tx4 = [q.taxon[4] for q in d.quartet], obsCF12=[q.obsCF[1] for q in d.quartet], obsCF13=[q.obsCF[2] for q in d.quartet], obsCF14=[q.obsCF[3] for q in d.quartet], expCF12=[q.qnet.expCF[1] for q in d.quartet], expCF13=[q.qnet.expCF[2] for q in d.quartet], expCF14=[q.qnet.expCF[3] for q in d.quartet]) elseif format == :long nQ = length(d.quartet) df = DataFrame( tx1 = repeat([q.taxon[1] for q in d.quartet], inner=[3]), tx2 = repeat([q.taxon[2] for q in d.quartet], inner=[3]), tx3 = repeat([q.taxon[3] for q in d.quartet], inner=[3]), tx4 = repeat([q.taxon[4] for q in d.quartet], inner=[3]), quartet = repeat(["12_34","13_24","14_23"], outer=[nQ]), obsCF = Array{Float64}(undef, 3*nQ), expCF = Array{Float64}(undef, 3*nQ) ) row = 1 for i in 1:nQ for j in 1:3 df[row, 6] = d.quartet[i].obsCF[j] df[row, 7] = d.quartet[i].qnet.expCF[j] row += 1 end end else error("format $(format) was not recognized. Should be :wide or :long.") end return df end """ `setNonIdBL!(net)` Set non-identifiable edge branch lengths to -1.0 (i.e. missing) for a level-1 network `net`, except for edges in - a good triangle: the edge below the hybrid is constrained to 0. - a bad diamond II: the edge below the hybrid is constrained to 0 - a bad diamond I: the edges across from the hybrid node have non identifiable lengths but are kept, because the two γ*(1-exp(-t)) values are identifiable. will break if `inCycle` attributes are not initialized (at -1) or giving a correct node number. see [`Node`](@ref) for the meaning of boolean attributes `isBadTriangle` (which corresponds to a "good" triangle above), `isBadDiamondI` and `isBadDiamondII`. """ function setNonIdBL!(net::HybridNetwork) for e in net.edge if !e.istIdentifiable keeplength = any(n -> (n.isBadDiamondII || n.isBadTriangle), e.node) # if below 'bad' hybrid node, length=0 by constraint. If above, length estimated. # next: keep length if edge across from hybrid node in bad diamond I. if !keeplength && e.inCycle != -1 hyb = net.node[getIndexNode(e.inCycle, net)] if hyb.isBadDiamondI keeplength |= !any(n -> (n==hyb), e.node) # only if e across hyb: no touching it end end if !keeplength e.length = -1.0 # not setLength, which does not allow too negative BLs end end end end """ setBLGammaParsimony!(net::HybridNetwork) Maximum parsimony function does not provide estimates for branch lengths, or gamma. But since the `maxParsimonyNet` function is using snaq move functions, branch lengths and gamma values are set randomly (to initialize optimization). We need to remove these random values before returning the maximum parsimony network. """ function setBLGammaParsimony!(net::HybridNetwork) for e in net.edge e.length = -1.0 if e.hybrid e.gamma = -1.0 end end end # function that we need to overwrite to avoid printing useless scary # output for HybridNetworks # PROBLEM: writeTopology changes the network and thus show changes the network function Base.show(io::IO, obj::HybridNetwork) disp = "$(typeof(obj)), " if obj.isRooted disp = disp * "Rooted Network" else disp = disp * "Un-rooted Network" end disp = disp * "\n$(obj.numEdges) edges\n" disp = disp * "$(obj.numNodes) nodes: $(obj.numTaxa) tips, " disp = disp * "$(obj.numHybrids) hybrid nodes, " disp = disp * "$(obj.numNodes - obj.numTaxa - obj.numHybrids) internal tree nodes.\n" tipslabels = [n.name for n in obj.leaf] if length(tipslabels) > 1 || !all(tipslabels .== "") disptipslabels = "$(tipslabels[1])" for i in 2:min(obj.numTaxa, 4) disptipslabels = disptipslabels * ", $(tipslabels[i])" end if obj.numTaxa > 4 disptipslabels = disptipslabels * ", ..." end disp *= "tip labels: " * disptipslabels end par = "" try # par = writeTopology(obj,round=true) # but writeTopology changes the network, not good s = IOBuffer() writeSubTree!(s, obj, false,true, true,3,true) par = String(take!(s)) catch err println("ERROR with writeSubTree!:") showerror(stdout, err) println("Trying writeTopologyLevel1") par = writeTopologyLevel1(obj) end disp *= "\n$par" println(io, disp) end # and QuartetNetworks (which cannot be just written because they do not have root) function Base.show(io::IO, net::QuartetNetwork) print(io,"taxa: $(net.quartetTaxon)\n") print(io,"number of hybrid nodes: $(net.numHybrids)\n") if(net.split != [-1,-1,-1,-1]) print(io,"split: $(net.split)\n") end end function Base.show(io::IO,d::DataCF) print(io,"Object DataCF\n") print(io,"number of quartets: $(d.numQuartets)\n") if(d.numTrees != -1) print(io,"number of trees: $(d.numTrees)\n") end end function Base.show(io::IO,q::Quartet) print(io,"number: $(q.number)\n") print(io,"taxon names: $(q.taxon)\n") print(io,"observed CF: $(q.obsCF)\n") print(io,"pseudo-deviance under last used network: $(q.logPseudoLik) (meaningless before estimation)\n") print(io,"expected CF under last used network: $(q.qnet.expCF) (meaningless before estimation)\n") if(q.ngenes != -1) print(io,"number of genes used to compute observed CF: $(q.ngenes)\n") end end function Base.show(io::IO, obj::Node) disp = "$(typeof(obj)):" disp = disp * "\n number:$(obj.number)" if (obj.name != "") disp *= "\n name:$(obj.name)" end if (obj.hybrid) disp *= "\n hybrid node" end if (obj.leaf) disp *= "\n leaf node" end disp *= "\n attached to $(length(obj.edge)) edges, numbered:" for e in obj.edge disp *= " $(e.number)"; end println(io, disp) end function Base.show(io::IO, obj::Edge) disp = "$(typeof(obj)):" disp *= "\n number:$(obj.number)" disp *= "\n length:$(obj.length)" if (obj.hybrid) disp *= "\n " * (obj.isMajor ? "major" : "minor") disp *= " hybrid edge with gamma=$(obj.gamma)" elseif (!obj.isMajor) disp *= "\n minor tree edge" end disp *= "\n attached to $(length(obj.node)) node(s) (parent first):" if (length(obj.node)==1) disp *= " $(obj.node[1].number)"; elseif (length(obj.node)==2) disp *= " $(obj.node[obj.isChild1 ? 2 : 1].number)" disp *= " $(obj.node[obj.isChild1 ? 1 : 2].number)" end println(io, disp) end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
3379
""" startree_newick(n, l) String for the Newick parenthetical description of the star tree with `n` tips, and all branch lengths equal to `l`. """ function startree_newick(n::Integer, ell=1.0) return "(" * join(["t$i:$ell" for i=1:n], ",") * ");" end """ symmetrictree_newick(n::Int, ell::Real, i=1) String for the Newick parenthetical description of a symmetric tree with 2^n tips, numbered from i to i+2^n-1. All branch lengths are set equal to `ell`. The tree can be created later by reading the string with [`readTopology`](@ref). """ function symmetrictree_newick(n::Int, ell::Real, i=1::Int) tree = "A$(i-1+2^n):$(ell)" if n==0 return("("*"A$(i-1+2^n):0"*");") end for k in 1:(n-1) tree = "(" * tree * "," * tree * "):$(ell)" end tree = "(" * tree * "," * tree * ");" # Rename tips for k in (2^n-1):-1:1 tree = replace(tree, "A$(i-1+k+1):$(ell)"=>"A$(i-1+k):$(ell)", count=k) end return(tree) end """ symmetricnet_newick(n::Int, i::Int, j::Int, γ::Real, l::Real) Newick string for a network with a symmetric major tree with 2^n tips, numbered from 1 to 2^n. All the branch lengths of the major tree are set to `l`. One hybrid branch, going from level i to level j is added, cutting in half each initial edge in the tree. The new edge has length `l` and inheritance `γ`. """ function symmetricnet_newick(n::Int, i::Int, j::Int, gamma::Real, ell::Real) (n < i || i < j || j < 1) && error("must have n >= i >= j > 0") # Underlying tree tree = symmetrictree_newick(n, ell) ## start hyb op = "(A1:$(ell)" clo = "A$(2^(i-1)):$(ell)):$(ell)" for k in 3:i op = "("*op clo = clo*"):$(ell)" end clobis = clo[1:(length(clo)-length("$(ell)"))]*"$(0.5*ell)" tree = replace(tree, op => "(#H:$(ell)::$(gamma),"*op) tree = replace(tree, clo => clobis*"):$(0.5*ell)") ## end hyb op = "A$(2^(i-1)+1):$(ell)" clo = "A$(2^(i-1) + 2^(j-1)):$(ell)" for k in 2:j op = "("*op clo = clo*"):$(ell)" end clobis = clo[1:(length(clo)-length("$(ell)"))]*"$(0.5*ell)" tree = replace(tree, op => "("*op) tree = replace(tree, clo => clobis*")#H:$(0.5*ell)::$(1-gamma)") return(tree) end """ symmetricnet_newick(n::Int, h::Int, γ::Real) Create a string for a symmetric network with 2^n tips, numbered from 1 to 2^n, with a symmetric major tree, whose branch lengths are all equal. 2^(n-h) hybrids are added from level h to h-1 "symmetrically". The network is time-consistent and ultrametric, with a total height of 1. """ function symmetricnet_newick(n::Int, h::Int, gamma::Real, i=1::Int) (n < h || h < 2) && error("must have n >= h > 1.") # length of branch ell = 1.0/n # Element net net = symmetricnet_newick(h, h, h-1, gamma, ell) # Iterate if n==h return(net) end net = chop(net) for k in 1:(n-h) net = "(" * net * ":$(ell)," * net * ":$(ell))" end net = net * ";" # Rename hybrids net = replace(net, "H" => "H$(2^(n-h))") for k in (2^(n-h)-1):-1:1 net = replace(net, "H$(k+1)" => "H$(k)", count=2*k) end # Rename tips for k in (2^h):-1:1 net = replace(net, "A$(k):" => "A$(i-1+2^n):") end for k in (2^n-1):-1:1 net = replace(net, "A$(i-1+k+1):" => "A$(i-1+k):", count=k) end return(net) end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
22285
""" biconnectedComponents(network, ignoreTrivial=false) Calculate biconnected components (aka "blobs") using Tarjan's algorithm. Output: array of arrays of edges. - the length of the array is the number of blobs - each element is an array of all the edges inside a given blob. These blobs are returned in post-order, but within a blob, edges are *not* necessarily sorted in topological order. If `ignoreTrivial` is true, trivial components (of a single edge) are not returned. The network is assumed to be connected. *Warnings*: for nodes, fields `k` and `inCycle` are modified during the algorithm. They are used to store the node's "index" (time of visitation), "lowpoint", and the node's "parent", as defined by the order in which nodes are visited. For edges, field `fromBadDiamondI` is modified, to store whether the edge has been already been visited or not. References: - p. 153 of [Tarjan (1972)](http://epubs.siam.org/doi/pdf/10.1137/0201010). Depth first search and linear graph algorithms, SIAM Journal on Computing, 1(2):146-160 - on [geeksforgeeks](https://www.geeksforgeeks.org/biconnected-components/), there is an error (as of 2018-01-30): `elif v != parent[u] and low[u] > disc[v]:` (python version) should be replaced by `elif v != parent[u] and disc[u] > disc[v]:` - nice explanation at this [url](https://www.cs.cmu.edu/~avrim/451f12/lectures/biconnected.pdf) """ function biconnectedComponents(net, ignoreTrivial=false::Bool) for n in net.node n.inCycle = -1 # inCycle = lowpoint. -1 for missing, until the node is visited n.k = -1 # k = index, order of visit during depth-first search end for e in net.edge e.fromBadDiamondI = false # true after edge is visited, during depth-first search end S = Edge[] # temporary stack blobs = Vector{Edge}[] # will contain the blobs biconnectedComponents(net.node[net.root], [0], S, blobs, ignoreTrivial) # if stack not empty: create last connected component length(S) == 0 || @error("stack of edges not empty at the end: $S") return blobs end """ biconnectedComponents(node, index, S, blobs, ignoreTrivial) Helper recursive function starting at a node (not a network). `index` is an array containing a single integer, thus mutable: order in which nodes are visited. """ function biconnectedComponents(node, index, S, blobs, ignoreTrivial) #println("\nentering biconnect, index=$(index[1])") children = 0 # set depth index for v to the smallest unused index node.k = index[1] # index / disc node.inCycle = index[1] # lowpoint / lowlink #println(" for node $(node.number): k=$(node.k), low=$(node.inCycle)") index[1] += 1 #print(" stack: "); @show [e.number for e in S] for e in node.edge # each (v, w) in E do w = (e.node[1] == node) ? e.node[2] : e.node[1] #println(" w: $(w.number) along edge $(e.number)") if w.k == -1 # w not yet visited, therefore e not yet visited either #println(" w's parent = $(node.number)") e.fromBadDiamondI = true children += 1 push!(S, e) #println(" edge $(e.number) on stack, intermediate step for node=$(node.number)") biconnectedComponents(w, index, S, blobs, ignoreTrivial) # check if subtree rooted at w has connection to # one of the ancestors of node # Case 1 -- per Strongly Connected Components Article node.inCycle = min(node.inCycle, w.inCycle) # lowpoint #print(" case 1, low=$(node.inCycle) for node $(node.number); ") #println("low=$(w.inCycle) for w $(w.number)") # if node is an articulation point: pop until e if w.inCycle >= node.k # @info "found root or articulation: node number $(node.number), entry to new blob." # start a new strongly connected component bb = Edge[] while length(S)>0 e2 = pop!(S) #println(" popping: edge $(e2.number)") push!(bb, e2) e2 !== e || break end if !ignoreTrivial || length(bb)>1 push!(blobs, bb) end end elseif !e.fromBadDiamondI && node.k > w.k # e is a back edge, not cross edge. Case 2 in article. e.fromBadDiamondI = true node.inCycle = min(node.inCycle, w.k) #println(" case 2, node $(node.number): low=$(node.inCycle)") push!(S, e) #println(" edge $(e.number) now on stack, final step for node $(node.number)") else #println(" nothing to do from node $(node.number) to w $(w.number) along edge $(e.number)") end end return nothing end """ biconnectedcomponent_entrynodes(net, bcc, preorder=true) Array containing the entry node of the each biconnected component in `bcc`. `bcc` is supposed to contain the biconnected components as output by [`biconnectedComponents`](@ref), that is, an array of array of edges. These entry nodes depend on the rooting (whereas the BCC only depend on the unrooted graph). They are either the root of the network or cut node (articulation points). """ function biconnectedcomponent_entrynodes(net, bcc, preorder=true::Bool) if preorder directEdges!(net) preorder!(net) end entrynode = Node[] # one entry node for each blob: cut node or root for bicomp in bcc jmin = length(net.node) for edge in bicomp n = getparent(edge) j = findfirst(x -> x===n, net.nodes_changed) isnothing(j) && error("node not found in net's pre-ordering 'nodes_changed'") jmin = min(j, jmin) end push!(entrynode, net.nodes_changed[jmin]) end return entrynode end """ biconnectedcomponent_exitnodes(net, bcc, preorder=true) Array containing an array of the exit node(s) of the each biconnected component in `bcc`. `bcc` is supposed to contain the biconnected components as output by [`biconnectedComponents`](@ref), that is, an array of array of edges. These exit nodes depend on the rooting (whereas the BCC only depend on the unrooted graph). The degree of a blob is the number of exit nodes + 1 if the blob doesn't contain the root (its entry node is a cut node), or + 0 if the blob contains the root (which enters into the blob but isn't a cut node). *Warning* (or positive side effect?): the edge `.inCycle` attribute is modified. It stores the index (in `bcc`) of the biconnected component that an edge belongs to. If an edge doesn't belong in any (e.g. if trivial blobs are ignored), then its `.inCycle` is set to -1. """ function biconnectedcomponent_exitnodes(net, bcc, preorder=true::Bool) if preorder directEdges!(net) preorder!(net) end exitnode = Vector{Node}[] # one array of exit cut nodes for each blob for edge in net.edge edge.inCycle = -1; end # in case trivial blobs are ignored for (i,bicomp) in enumerate(bcc) for edge in bicomp edge.inCycle = i; end end for (i,bicomp) in enumerate(bcc) exitnode_blobi = Node[] for edge in bicomp edge.isMajor || continue # skip minor edges to avoid duplicating exit node n = getchild(edge) for e in n.edge e !== edge || continue if e.inCycle != i # then n is a cut point, incident to another blob push!(exitnode_blobi, n) break end end end push!(exitnode, exitnode_blobi) end return exitnode end """ blobInfo(network, ignoreTrivial=true) Calculate the biconnected components (blobs) using function [`biconnectedComponents`](@ref) then: - set node field `isExtBadTriangle` to true at the root of each non-trivial blob (and at the network root), false otherwise. (a better name for the field would be something like "isBlobRoot".) - output: 1. array of nodes that are the roots of each non-trivial blob, and the network root. If the root of the full network is not part of a non-trivial blob, a corresponding blob is added to the list. 2. array of arrays: for each non-trivial blob, array of major hybrid edges in that blob. 3. array of arrays: same as #2 but for minor hybrid edges, with hybrids listed in the same order, for each blob. Blobs are ordered in reverse topological ordering (aka post order). If `ignoreTrivial` is true, trivial components are ignored. keyword argument: `checkPreorder`, true by default. If false, the `isChild1` edge field and the `net.nodes_changed` network field are supposed to be correct. **warning**: see [`biconnectedComponents`](@ref) for node attributes modified during the algorithm. """ function blobInfo(net, ignoreTrivial=true::Bool; checkPreorder=true::Bool) if checkPreorder directEdges!(net) # update isChild1, needed for preorder preorder!(net) # creates / updates net.nodes_changed end bcc = biconnectedComponents(net, ignoreTrivial) bccRoots = biconnectedcomponent_entrynodes(net, bcc, false) # 1 entry node for each blob bccMajor = Vector{Edge}[] # one array for each blob bccMinor = Vector{Edge}[] for bicomp in bcc bccMa = Edge[] bccmi = Edge[] # find minor hybrid edges, in same order for edge in bicomp if edge.hybrid && edge.isMajor push!(bccMa, edge) e = getpartneredge(edge) !e.isMajor || @warn "major edge $(edge.number) has a major partner: edge $(e.number)" push!(bccmi, e) end end push!(bccMajor, bccMa) push!(bccMinor, bccmi) end # add the network root, if it was in a trivial bi-component (no hybrids) rootnode = getroot(net) if !any(n -> n === rootnode, bccRoots) push!(bccRoots, rootnode) push!(bccMajor, Edge[]) push!(bccMinor, Edge[]) end # update `isExtBadTriangle` to mark nodes that are blob roots: # these nodes will serve as dummy leaves when reached from other blobs for n in net.node n.isExtBadTriangle = false; end for r in bccRoots r.isExtBadTriangle = true; end return(bccRoots, bccMajor, bccMinor) end """ blobDecomposition!(network) blobDecomposition(network) Find blobs using [`biconnectedComponents`](@ref); find their roots using [`blobInfo`](@ref); create a forest in the form of a disconnected network (for efficiency), by deconnecting the root of each non-trivial blob from its parent. The root of each blob corresponds to a new leaf (in another tree of the forest): the number of the blob's root is given to the newly created leaf. The first (bang) version modifies the network and returns the array of blob roots. The second version copies the network then returns a tuple: the forest and the array of blob roots. Warnings: - the forest is represented by a single HybridNetwork object, on which most functions don't work (like `writeTopology`, plotting etc.) because the network is disconnected (to make the forest). Revert back to low-level functions, e.g. `printEdges` and `printNodes`. - see [`biconnectedComponents`](@ref) for node attributes modified during the algorithm. """ function blobDecomposition(net) net2 = deepcopy(net) blobR = blobDecomposition!(net2) return net2, blobR end function blobDecomposition!(net) nextnumber = maximum([n.number for n in net.node])+1 blobR, tmp, tmp = blobInfo(net, true) # true: ignore trivial single-edge blobs for r in blobR for e in r.edge r == e.node[e.isChild1 ? 1 : 2] || continue removeEdge!(r,e) # detach edge e from root r removeNode!(r,e) # detach root r from edge e dummyleaf = Node(nextnumber, true) # true: leaf nextnumber += 1 dummyleaf.name = string("dummy ", r.number) setEdge!(dummyleaf, e) # attach e to new dummy leaf setNode!(e,dummyleaf) # attach new leaf to edge e e.isChild1 = false pushNode!(net, dummyleaf) break end end return blobR end """ leaststableancestor(net, preorder=true::Bool) Return `(lsa, lsa_index)` where `lsa` is the least stable ancestor node (LSA) in `net`, and `lsa_index` is the index of `lsa` in `net.nodes_changed`. The LSA the lowest node `n` with the following property: *any* path between *any* leaf and the root must go through `n`. All such nodes with this property are ancestral to the LSA (and therefore must have an index that is lower or equal to `lsa_index`). Exception: if the network has a single leaf, the output `lsa` is the leaf's parent node, to maintain one external edge between the root and the leaf. *Warning*: uses [`biconnectedComponents`](@ref) and [`biconnectedcomponent_exitnodes`](@ref), therefore share the same caveats regarding the use of fields `.inCycle` (for edges and nodes), `.k` (for nodes) etc. As a positivie side effect, the biconnected components can be recovered via the edges' `.inCycle` field --including the trivial blobs (cut edges). See also: [`deleteaboveLSA!`](@ref) """ function leaststableancestor(net, preorder=true::Bool) net.node[net.root].leaf && error("The root can't be a leaf to find the LSA.") if preorder directEdges!(net) preorder!(net) end bcc = biconnectedComponents(net, false) entry = biconnectedcomponent_entrynodes(net, bcc, false) entryindex = indexin(entry, net.nodes_changed) exitnodes = biconnectedcomponent_exitnodes(net, bcc, false) bloborder = sortperm(entryindex) # pre-ordering for blobs in their own blob tree function atlsa(ib) # is bcc[ib] below the LSA? # above LSA if 1 exit and 1 entry that's not an entry to another blob # (0 exits: trivial blob (cut-edge) to a leaf) length(exitnodes[ib]) != 1 || sum(isequal(entryindex[ib]), entryindex) > 1 end lsaindex_j = findfirst(atlsa, bloborder) isnothing(lsaindex_j) && error("strange: couldn't find the LSA...") ib = bloborder[lsaindex_j] return entry[ib], entryindex[ib] end """ treeedgecomponents(net::HybridNetwork) Return the tree-edge components of the semidirected network as a `membership` dictionary `Node => Int`. Nodes with the same membership integer value are in the same tree-edge component. The tree-edge components of a network are the connected components of the network when all hybrid edges are removed. A `RootMismatch` error is thrown if there exists a cycle in any of the tree-edge components, or if a tree-edge component has more than one "entry" hybrid node. Warnings: - since `Node`s are mutable, the network should not be modified until usage of the output `membership` dictionary is over. - the component IDs are not predicable, but will be consecutive integers from 1 to the number of components. """ function treeedgecomponents(net::HybridNetwork) # partition nodes into tree-edge components (TECs) nodes = net.node n = length(nodes) unvisited = Set(nodes) dfs_stack = Vector{Node}() # stack for iterative depth-first search over tree edges dfs_parent = Dict{Node, Node}() # dfs_parent[node] = node's parent in DFS tree # membership[node] = id of undirected component that the node belongs to membership = Dict{Node, Int}() cur_id = 0 # undirected component id while !isempty(unvisited) # loop over undirected components # start with an unvisited node, DFS with undirected edges cur_id += 1 node = pop!(unvisited) # unpredictable ordering: because unvisited is a set push!(dfs_stack, node) curnode = node dfs_parent[curnode] = curnode entrynode = nothing while !isempty(dfs_stack) # DFS loop over one tree-edge component curnode = pop!(dfs_stack) delete!(unvisited, curnode) membership[curnode] = cur_id for e in curnode.edge if !e.hybrid # for tree edge, do DFS, check for undirected cycles nextnode = getOtherNode(e, curnode) # if run into visited node (other than parent), then component has cycle if nextnode !== dfs_parent[curnode] if !in(nextnode, unvisited) throw(RootMismatch( "Undirected cycle exists, starting at node number $(nextnode.number)")) else dfs_parent[nextnode] = curnode push!(dfs_stack, nextnode) end end else # for hybrid edge, check there is at most one entry node into the TEC if curnode === getchild(e) if isnothing(entrynode) entrynode = curnode elseif entrynode !== curnode throw(RootMismatch( """Multiple entry nodes for tree-edge component, numbered: $(entrynode.number) and $(curnode.number)""")) end end end end end end return membership end """ checkroot!(net) checkroot!(net::HybridNetwork, membership::Dict{Node, Int}) Set the root of `net` to an appropriate node and update the edges `containRoot` field appropriately, using the `membership` output by [`treeedgecomponents`](@ref). A node is appropriate to serve as root if it belongs in the root tree-edge component, that is, the root of the tree-edge component graph. - If the current root is appropriate, it is left as is. The direction of edges (via `isChild1`) is also left as is, assuming it was in synch with the existing root. - Otherwise, the root is set to the first appropriate node in `net.node`, that is not a leaf. Then edges are directed away from this root. A `RootMismatch` error is thrown if `net` is not a valid semidirected phylogenetic network (i.e. it is not possible to root the network in a way compatible with the given hybrid edges). Output: the `membership` ID of the root component. The full set of nodes in the root component can be obtained as shown below. Warning: only use the output component ID after calling the second version `checkroot!(net, membership)`. ```jldoctest julia> net = readTopology("(#H1:::0.1,#H2:::0.2,(((b)#H1)#H2,a));"); julia> membership = treeedgecomponents(net); julia> rootcompID = checkroot!(net, membership); julia> rootcomp = keys(filter(p -> p.second == rootcompID, membership)); julia> sort([n.number for n in rootcomp]) # number of nodes in the root component 3-element Vector{Int64}: -3 -2 4 ``` """ function checkroot!(net::HybridNetwork) membership = treeedgecomponents(net) # dict Node => Int return checkroot!(net, membership) end function checkroot!(net::HybridNetwork, membership::Dict{Node,Int}) # do not modify nodes or edges until we are done with membership nodes = net.node ncomp = maximum(values(membership)) # TECs are numbered 1,2,...,ncomp #= 1. construct TEC graph: directed graph in which vertices = TECs of original network, and edge Ci --> Cj for each original hybrid edge: node in Ci --> node in Cj. =# tecG = [Set{Int}() for comp in 1:ncomp] # tecG[i] = set of children of ith TEC noparent = trues(ncomp) # will stay true for TECs with no parent for e in net.edge e.hybrid || continue # skip tree edges up, down = e.isChild1 ? (e.node[2], e.node[1]) : (e.node[1], e.node[2]) uc_up, uc_down = membership[up], membership[down] noparent[uc_down] = false push!(tecG[uc_up], uc_down) end # 2. check that the TEC graph has a single root tec_root = findfirst(noparent) if isnothing(tec_root) # all TECs have a parent: noparent are all false throw(RootMismatch( "Semidirected cycle exists: no component has in-degree 0")) elseif sum(noparent) > 1 r1 = findfirst(noparent) r2 = findlast(noparent) nr1 = findfirst(n -> membership[n] == r1, nodes) nr2 = findfirst(n -> membership[n] == r2, nodes) throw(RootMismatch("nodes number $(nodes[nr1].number) and $(nodes[nr2].number) have no common ancestor")) end # 3. topological sort: check the TEC graph has no cycles, that is, is a DAG indeg = zeros(Int, ncomp) # in-degree of vertex in TEC graph for uc in tecG for i in uc indeg[i] += 1 end end headstack = [tec_root] # stack of TEC vertices of degree 0 in topological sort while !isempty(headstack) uc = pop!(headstack) indeg[uc] -= 1 for i in tecG[uc] indeg[i] -= 1 if indeg[i] == 0 push!(headstack, i) end end end cyclehead = findfirst(indeg .!= -1) isnothing(cyclehead) || throw(RootMismatch( """Semidirected cycle exists, starting at TEC containing node number $(nodes[findfirst(n -> membership[n] == cyclehead, nodes)].number)""")) # 4. original network: reset the network root if needed, # and update the edges' containRoot accordingly. # NOT done: build the root component to return it. Instead: return tec_root # Set(node for node = nodes if membership[node] == tec_root) # Set(node for (node,comp) in membership if comp == tec_root) #rootcomp = keys(filter(p -> p.second == tec_root, membership)) curroot = nodes[net.root] if membership[curroot] == tec_root # update containRoot only: true for edges in or out of the root TEC for e in net.edge e.containRoot = (membership[getparent(e)] == tec_root) end else net.root = findfirst(n -> (!n.leaf && membership[n] == tec_root), nodes) directEdges!(net) # also updates containRoot of all edges end return tec_root # return rootcomp end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
5498
# helper functions used by PhyloPlot to export (then plot) # a network as a phylo R object. """ makemissing!(x::AbstractVector) Turn to `missing` any element of `x` exactly equal to -1.0. Used for branch lengths and γs. `x` needs to accept missing values. If not, this can be done with `allowmissing(x)`. """ @inline function makemissing!(x::AbstractVector) for i in 1:length(x) if x[i] == -1.0 x[i] = missing end end end """ majoredgematrix(net::HybridNetwork) Matrix of major edges from `net` where edge[i,1] is the number of the parent node of edge i and edge[i,2] is the number of the child node of edge i. Assume `nodes_changed` was updated, to list nodes in pre-order. # Examples ```jldoctest julia> net = readTopology("(A,(B,(C,D)));"); julia> PhyloNetworks.resetNodeNumbers!(net); julia> PhyloNetworks.majoredgematrix(net) 6×2 Matrix{Int64}: 5 1 5 6 6 2 6 7 7 3 7 4 ``` """ function majoredgematrix(net::HybridNetwork) edge = Matrix{Int}(undef, length(net.edge)-length(net.hybrid), 2) # major edges i = 1 #row index for edge matrix for n in net.nodes_changed # topological pre-order !n.leaf || continue # skip leaves: associate node with children edges for e in n.edge if e.node[e.isChild1 ? 2 : 1] == n && e.isMajor #exclude parent edge and minor hybrid edges edge[i,1] = n.number # parent edge[i,2] = e.node[e.isChild1 ? 1 : 2].number # child i += 1 end end end return edge end """ majoredgelength(net::HybridNetwork) Generate vector of edge lengths of major `net` edges organized in the same order as the `edge` matrix created via `majoredgematrix`. Considers values of `-1.0` as missing values, recognized as NA in `R`. Output: vector allowing for missing values. Assume `nodes_changed` was updated, to list nodes in pre-order. # Examples ```jldoctest julia> net = readTopology("(((A:3.1,(B:0.2)#H1:0.3::0.9),(C,#H1:0.3::0.1):1.1),D:0.7);"); julia> directEdges!(net); preorder!(net); julia> PhyloNetworks.majoredgelength(net) 8-element Vector{Union{Missing, Float64}}: missing 0.7 missing 1.1 missing 3.1 0.3 0.2 ``` """ #" function majoredgelength(net::HybridNetwork) edgeLength = Array{Union{Float64,Missing}}(undef, length(net.edge)-length(net.hybrid)) i=1 for n in net.nodes_changed # topological pre-order if !n.leaf for e in n.edge # for parent major edge below if e.node[e.isChild1 ? 2 : 1] == n && e.isMajor edgeLength[i] = e.length i=i+1 end end end end #-1.0 interpreted as missing makemissing!(edgeLength) return edgeLength end """ minorreticulationmatrix(net::HybridNetwork) Matrix of integers, representing the minor hybrid edges in `net`. edge[i,1] is the number of the parent node of the ith minor hybrid edge, and edge[i,2] is the number of its child node. Node numbers may be negative, unless they were modified by `resetNodeNumbers!`. Assumes correct `isChild1` fields. # Examples ```julia-repl julia> net = readTopology("(((A,(B)#H1:::0.9),(C,#H1:::0.1)),D);"); julia> PhyloNetworks.minorreticulationmatrix(net) 1×2 Matrix{Int64}: -6 3 ``` """ #" function minorreticulationmatrix(net::HybridNetwork) reticulation = Matrix{Int}(undef, length(net.hybrid), 2) # initialize j = 1 # row index, row = reticulate edge for e in net.edge if !e.isMajor # minor (hybrid) edges only reticulation[j,1] = getparent(e).number reticulation[j,2] = getchild(e).number j += 1 end end return reticulation end """ minorreticulationlength(net::HybridNetwork) Vector of lengths for the minor hybrid edges, organized in the same order as in the matrix created via `minorreticulationmatrix`. Replace values of `-1.0` with missing values recognized by `R`. Output: vector allowing for missing values. # Examples ```jldoctest julia> net = readTopology("(((A:3.1,(B:0.2)#H1:0.4::0.9),(C,#H1:0.3::0.1):1.1),D:0.7);"); julia> PhyloNetworks.minorreticulationlength(net) 1-element Vector{Union{Missing, Float64}}: 0.3 ``` """ #" function minorreticulationlength(net::HybridNetwork) reticulationLength = Vector{Union{Float64,Missing}}(undef, 0) # initialize for e in net.edge if !e.isMajor #find minor hybrid edge push!(reticulationLength, e.length) end end makemissing!(reticulationLength) return reticulationLength end """ minorreticulationgamma(net::HybridNetwork) Vector of minor edge gammas (inheritance probabilities) organized in the same order as in the matrix created via `minorreticulationmatrix`. Considers values of `-1.0` as missing values, recognized as NA in `R`. Output: vector allowing for missing values. # Examples ```julia-repl julia> net = readTopology("(((A,(B)#H1:::0.9),(C,#H1:::0.1)),D);"); julia> PhyloNetworks.minorreticulationgamma(net) 1-element Vector{Union{Float64, Missings.Missing}}: 0.1 ``` """ #" function minorreticulationgamma(net::HybridNetwork) reticulationGamma = Vector{Union{Float64,Missing}}(undef, 0) #initialize for e in net.edge if !e.isMajor # minor hybrid edges only push!(reticulationGamma, e.gamma) end end makemissing!(reticulationGamma) return reticulationGamma end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
54702
""" undirectedOtherNetworks(net::HybridNetwork) Return a vector of HybridNetwork objects, obtained by switching the placement of each hybrid node to other nodes inside its cycle. This amounts to changing the direction of a gene flow event (recursively to move around the whole cycle of each reticulation). Optional argument: `outgroup`, as a String. If an outgroup is specified, then networks conflicting with the placement of the root are avoided. Assumptions: `net` is assumed to be of level 1, that is, each blob has a single cycle with a single reticulation. All level-1 fields of `net` are assumed up-to-date. # Example ```julia julia> net = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); julia> vnet = undirectedOtherNetworks(net) ``` """ function undirectedOtherNetworks(net0::HybridNetwork; outgroup="none"::AbstractString, insideSnaq=false::Bool) # extra optional argument: "insideSnaq". When true, all level1-attributes are assumed up-to-date # So far, undirectedOtherNetworks is called inside optTopRuns only # Potential bug: if new node is -1, then inCycle will become meaningless: changed in readSubTree here # WARNING: does not update partition, because only thing to change is hybrid node number if !insideSnaq net0 = readTopologyLevel1(writeTopologyLevel1(net0)) end otherNet = HybridNetwork[] for i in 1:net0.numHybrids #need to do for by number, not node net = deepcopy(net0) # to avoid redoing attributes after each cycle is finished ## undo attributes at current hybrid node: hybrid = net.hybrid[i] nocycle, edgesInCycle, nodesInCycle = identifyInCycle(net,hybrid); @debug "nodesInCycle are: $([n.number for n in nodesInCycle])" !nocycle || error("the hybrid node $(hybrid.number) does not create a cycle") edgesRoot = identifyContainRoot(net,hybrid); edges = hybridEdges(hybrid); undoGammaz!(hybrid,net); othermaj = getOtherNode(edges[1],hybrid) edgesmaj = hybridEdges(othermaj) if edgesmaj[3].containRoot #if containRoot=true, then we need to undo undoContainRoot!(edgesRoot); end ## changes to new hybrid node: for newn in nodesInCycle if newn.number != hybrid.number # nodesInCycle contains the hybrid too newnet = deepcopy(net) newnocycle, newedgesInCycle, newnodesInCycle = identifyInCycle(newnet,newnet.hybrid[i]); !newnocycle || error("the hybrid node $(newnet.hybrid[i].number) does not create a cycle") ind = getIndexNode(newn.number,newnet) # find the newn node in the new network @debug "moving hybrid to node $(newnet.node[ind].number)" hybridatnode!(newnet, newnet.hybrid[i], newnet.node[ind]) @debug begin printEdges(newnet); "printed edges" end @debug begin printNodes(newnet); "printed nodes" end undoInCycle!(newedgesInCycle, newnodesInCycle); @debug begin printEdges(newnet); "printed edges" end @debug begin printNodes(newnet); "printed nodes" end ##undoPartition!(net,hybrid, edgesInCycle) success, hybrid0, flag, nocycle, flag2, flag3 = updateAllNewHybrid!(newnet.node[ind], newnet, false,false,false) if success @debug "successfully added new network: $(writeTopologyLevel1(newnet))" push!(otherNet,newnet) else println("the network obtained by putting the new hybrid in node $(newnet.node[ind].number) is not good, inCycle,gammaz,containRoot: $([flag,flag2,flag3]), we will skip it") end end end end # check root in good position if outgroup == "none" for n in otherNet !isTree(n) && checkRootPlace!(n, verbose=false) end return otherNet else ## root already in good place @debug "we will remove networks contradicting the outgroup in undirectedOtherNetworks" whichKeep = ones(Bool,length(otherNet)) # repeats 'true' i = 1 for n in otherNet if !isTree(n) try checkRootPlace!(n, verbose=true, outgroup=outgroup) catch @debug "found one network incompatible with outgroup" @debug "$(writeTopologyLevel1(n))" whichKeep[i] = false end end i = i+1; end return otherNet[whichKeep] end end """ hybridatnode!(net::HybridNetwork, nodeNumber::Integer) Change the direction and status of edges in network `net`, to move the hybrid node in a cycle to the node with number `nodeNumber`. This node must be in one (and only one) cycle, otherwise an error will be thrown. Check and update the nodes' field `inCycle`. Output: `net` after hybrid modification. Assumption: `net` must be of level 1, that is, each blob has a single cycle with a single reticulation. # example ```julia net = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); using PhyloPlots plot(net, shownodenumber=true); # to locate nodes and their numbers. D of hybrid origin hybridatnode!(net, -4) plot(net, shownodenumber=true); # hybrid direction reversed: now 2B of hybrid origin ``` """ function hybridatnode!(net::HybridNetwork, nodeNumber::Integer) undoInCycle!(net.edge, net.node) for n in net.hybrid flag, nocycle, edgesInCycle, nodesInCycle = updateInCycle!(net,n); flag || error("not level1 network, hybrid $(n.number) cycle intersects another cycle") !nocycle || error("strange network without cycle for hybrid $(n.number)") end ind = 0 try ind = getIndexNode(nodeNumber,net) catch error("cannot set node $(nodeNumber) as hybrid because it is not part of net") end net.node[ind].inCycle != -1 || error("node $(nodeNumber) is not part of any cycle, so we cannot make it hybrid") indhyb = 0 try indhyb = getIndexNode(net.node[ind].inCycle,net) catch error("cannot find the hybrid node with number $(net.node[ind].inCycle)") end hybrid = net.node[indhyb] hybridatnode!(net,hybrid,net.node[ind]) return net end """ hybridatnode!(net::HybridNetwork, hybrid::Node, newNode::Node) Move the reticulation from `hybrid` to `newNode`, which must in the same cycle. `net` is assumed to be of level 1, but **no checks** are made and fields are supposed up-to-date. Called by `hybridatnode!(net, nodenumber)`, which is itself called by [`undirectedOtherNetworks`](@ref). """ function hybridatnode!(net::HybridNetwork, hybrid::Node, newNode::Node) hybrid.hybrid || error("node $(hybrid.number) should be hybrid, but it is not") hybedges = hybridEdges(hybrid) makeEdgeTree!(hybedges[1],hybrid) makeEdgeTree!(hybedges[2],hybrid) hybedges[1].inCycle = hybrid.number #just to keep attributes ok hybedges[2].inCycle = hybrid.number switchHybridNode!(net,hybrid,newNode) found = false for e in newNode.edge if e.inCycle == hybrid.number if !found found = true makeEdgeHybrid!(e,newNode, 0.51, switchHyb=true) #first found, major edge, need to optimize gamma anyway ##e.gamma = -1 ##e.containRoot = true ## need attributes like in snaq else makeEdgeHybrid!(e,newNode, 0.49, switchHyb=true) #second found, minor edge ##e.gamma = -1 ##e.containRoot = true end end end end # Not used anywhere, but tested # does not call hybridatnode! but repeats its code: oops! violates DRY principle # nodeNumber should correspond to the number assigned by readTopologyLevel1, # and the node numbers in `net` are irrelevant. """ hybridatnode(net::HybridNetwork, nodeNumber::Integer) Move the hybrid node in a cycle to make node number `nodeNumber` a hybrid node Compared to [`hybridatnode!`], this method checks that `net` is of level 1 (required) and does not modify it. """ function hybridatnode(net0::HybridNetwork, nodeNumber::Integer) net = readTopologyLevel1(writeTopologyLevel1(net0)) # we need inCycle attributes ind = 0 try ind = getIndexNode(nodeNumber,net) catch error("cannot set node $(nodeNumber) as hybrid because it is not part of net") end net.node[ind].inCycle != -1 || error("node $(nodeNumber) is not part of any cycle, so we cannot make it hybrid") indhyb = 0 try indhyb = getIndexNode(net.node[ind].inCycle,net) catch error("cannot find the hybrid node with number $(net.node[ind].inCycle)") end hybrid = net.node[indhyb] hybrid.hybrid || error("node $(hybrid.number) should be hybrid, but it is not") hybedges = hybridEdges(hybrid) makeEdgeTree!(hybedges[1],hybrid) makeEdgeTree!(hybedges[2],hybrid) hybedges[1].inCycle = hybrid.number #just to keep attributes ok hybedges[2].inCycle = hybrid.number switchHybridNode!(net,hybrid,net.node[ind]) found = false for e in net.node[ind].edge if e.inCycle == hybrid.number if !found found = true makeEdgeHybrid!(e,net.node[ind], 0.51, switchHyb=true) #first found, major edge, need to optimize gamma anyway e.gamma = -1 e.containRoot = true else makeEdgeHybrid!(e,net.node[ind], 0.49, switchHyb=true) #second found, minor edge e.gamma = -1 e.containRoot = true end end end return net end """ rootatnode!(HybridNetwork, nodeNumber::Integer; index=false::Bool) rootatnode!(HybridNetwork, Node) rootatnode!(HybridNetwork, nodeName::AbstractString) Root the network/tree object at the node with name 'nodeName' or number 'nodeNumber' (by default) or with index 'nodeNumber' if index=true. Attributes isChild1 and containRoot are updated along the way. Use `plot(net, shownodenumber=true, showedgelength=false)` to visualize and identify a node of interest. (see package [PhyloPlots](https://github.com/cecileane/PhyloPlots.jl)) Return the network. Warnings: - If the node is a leaf, the root will be placed along the edge adjacent to the leaf. This might add a new node. - If the desired root placement is incompatible with one or more hybrids, then * the original network is restored with its old root and edges' direction. * a RootMismatch error is thrown. See also: [`rootonedge!`](@ref). """ function rootatnode!(net::HybridNetwork, node::Node; kwargs...) rootatnode!(net, node.number; kwargs..., index=false) end function rootatnode!(net::HybridNetwork, nodeName::AbstractString; kwargs...) tmp = findall(n -> n.name == nodeName, net.node) if length(tmp)==0 error("node named $nodeName was not found in the network.") elseif length(tmp)>1 error("several nodes were found with name $nodeName.") end rootatnode!(net, tmp[1]; kwargs..., index=true) end function rootatnode!(net::HybridNetwork, nodeNumber::Integer; index=false::Bool) ind = nodeNumber # good if index=true if !index try ind = getIndexNode(nodeNumber,net) catch error("cannot set node $(nodeNumber) as root because it is not part of net") end elseif ind > length(net.node) error("node index $ind too large: the network only has $(length(net.node)) nodes.") end if net.node[ind].leaf # @info "node $(net.node[ind].number) is a leaf. Will create a new node if needed, to set taxon \"$(net.node[ind].name)\" as outgroup." length(net.node[ind].edge)==1 || error("leaf has $(length(net.node[ind].edge)) edges!") pn = getOtherNode(net.node[ind].edge[1], net.node[ind]) if length(pn.edge) <= 2 # if parent of leaf has degree 2, use it as new root rootatnode!(net, pn.number) else # otherwise, create a new node between leaf and its parent rootonedge!(net,net.node[ind].edge[1]) end else rootsaved = net.root net.root = ind try directEdges!(net) catch e if isa(e, RootMismatch) # new root incompatible with hybrid directions: revert back net.root = rootsaved directEdges!(net) end throw(RootMismatch("""the desired root is below a reticulation, reverting to old root position.""")) end if (net.root != rootsaved && length(net.node[rootsaved].edge)==2) fuseedgesat!(rootsaved,net) # remove old root node if degree 2 end return net end end """ rootonedge!(HybridNetwork, edgeNumber::Integer; index=false::Bool) rootonedge!(HybridNetwork, Edge) Root the network/tree along an edge with number `edgeNumber` (by default) or with index `edgeNumber` if `index=true`. Attributes `isChild1` and `containRoot` are updated along the way. This adds a new node and a new edge to the network. Use `plot(net, showedgenumber=true, showedgelength=false)` to visualize and identify an edge of interest. (see package [PhyloPlots](https://github.com/cecileane/PhyloPlots.jl)) See also: [`rootatnode!`](@ref). """ function rootonedge!(net::HybridNetwork, edge::Edge; kwargs...) rootonedge!(net, edge.number, index=false; kwargs...) end function rootonedge!(net::HybridNetwork, edgeNumber::Integer; index=false::Bool) ind = edgeNumber # good if index=true if !index try ind = getIndexEdge(edgeNumber,net) catch error("cannot set root along edge $(edgeNumber): no such edge in network") end elseif ind > length(net.edge) error("edge index $ind too large: the network only has $(length(net.edge)) edges.") end rootsaved = net.root breakedge!(net.edge[ind],net) # returns new node, new edge (last ones pushed) net.root = length(net.node) # index of new node: was the last one pushed try directEdges!(net) catch e if isa(e, RootMismatch) # new root incompatible with hybrid directions: revert back fuseedgesat!(net.root,net) # reverts breakedge! net.root = rootsaved directEdges!(net) end throw(RootMismatch("""the desired root is below a reticulation, reverting to old root position.""")) end if (net.root != rootsaved && length(net.node[rootsaved].edge)==2) fuseedgesat!(rootsaved,net) # remove old root node if degree 2 end return net end """ breakedge!(edge::Edge, net::HybridNetwork) Break an edge into 2 edges, each of length half that of original edge, creating a new node of degree 2. Useful to root network along an edge. Return the new node and the new edge, which is the "top" half of the original starting edge. These new node & edge are pushed last in `net.node` and `net.edge`. If the starting edge was: ``` n1 --edge--> n2 ``` then we get this: ``` n1 --newedge--> newnode --edge--> n2 ``` `isChild1` and `containRoot` are updated, but not fields for level-1 networks like `inCycle`, `partition`, `gammaz`, etc. # examples ```jldoctest julia> net = readTopology("(((S8,S9),((((S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));"); julia> length(net.node) 19 julia> net.edge[4] # edge 4 goes from node -8 to 3 PhyloNetworks.EdgeT{PhyloNetworks.Node}: number:4 length:-1.0 attached to 2 node(s) (parent first): -8 3 julia> newnode, newedge = PhyloNetworks.breakedge!(net.edge[4], net); julia> length(net.node) # one more than before 20 julia> newedge # new edge 21 goes from node -8 and 11 (new) PhyloNetworks.EdgeT{PhyloNetworks.Node}: number:21 length:-1.0 attached to 2 node(s) (parent first): -8 11 julia> net.edge[4] # original edge 4 now goes from node 11 (new) to 3 PhyloNetworks.EdgeT{PhyloNetworks.Node}: number:4 length:-1.0 attached to 2 node(s) (parent first): 11 3 julia> writeTopology(net) # note extra pair of parentheses around S1 "(((S8,S9),((((S4,(S1)),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" ``` See also: [`fuseedgesat!`](@ref) """ function breakedge!(edge::Edge, net::HybridNetwork) pn = getparent(edge) # parent node # new child edge = old edge, same hybrid attribute removeEdge!(pn,edge) removeNode!(pn,edge) max_edge = maximum(e.number for e in net.edge) max_node = maximum(n.number for n in net.node) newedge = Edge(max_edge+1) # create new parent (tree) edge newnode = Node(max_node+1,false,false,[edge,newedge]) # tree node setNode!(edge,newnode) # newnode comes 2nd, and parent node along 'edge' edge.isChild1 = true setNode!(newedge,newnode) # newnode comes 1st in newedge, but child node newedge.isChild1 = true setEdge!(pn,newedge) setNode!(newedge,pn) # pn comes 2nd in newedge if edge.length == -1.0 newedge.length = -1.0 else edge.length /= 2 newedge.length = edge.length end newedge.containRoot = edge.containRoot pushEdge!(net,newedge) pushNode!(net,newnode) return newnode, newedge end """ fuseedgesat!(i::Integer,net::HybridNetwork, multgammas=false::Bool) Removes `i`th node in net.node, if it is of degree 2. The parent and child edges of this node are fused. If either of the edges is hybrid, the hybrid edge is retained. Otherwise, the edge with the lower edge number is retained. Reverts the action of [`breakedge!`](@ref). returns the fused edge. """ function fuseedgesat!(i::Integer, net::HybridNetwork, multgammas=false::Bool) i <= length(net.node) || error("node index $i too large: only $(length(net.node)) nodes in the network.") nodei = net.node[i] length(nodei.edge) == 2 || error("can't fuse edges at node number $(nodei.number): connected to $(length(nodei.edge)) edges.") !(nodei.edge[1].hybrid && nodei.edge[2].hybrid) || error("can't fuse edges at node number $(nodei.number): connected to exactly 2 hybrid edges") j = argmax([e.number for e in nodei.edge]) pe = nodei.edge[j] # edge to remove: pe.number > ce.number ce = nodei.edge[j==1 ? 2 : 1] if pe.hybrid # unless it's a hybrid: should be --tree--> node i --hybrid--> (ce,pe) = (pe,ce) # keep the hybrid edge: keep its isMajor end isnodeiparent = (nodei ≡ getparent(ce)) (!ce.hybrid || isnodeiparent) || error("node $(nodei.number) has 1 tree edge ($(pe.number)) and 1 hybrid edge ($(ce.number)), but is child of the hybrid edge.") pn = getOtherNode(pe,nodei) removeEdge!(nodei,ce) # perhaps useless. in case gc() on ith node affects its edges. removeNode!(nodei,ce) removeEdge!(pn,pe) removeNode!(pn,pe) # perhaps useless. in case gc() on pe affects its nodes. setEdge!(pn,ce) setNode!(ce,pn) # pn comes 2nd in ce now: ce.node is: [original, pn] ce.isChild1 = isnodeiparent # to retain same direction as before. ce.length = addBL(ce.length, pe.length) if multgammas ce.gamma = multiplygammas(ce.gamma, pe.gamma) end if net.root==i # isnodeiparent should be true, unless the root and ce's direction were not in sync newroot = pn if newroot.leaf && !ce.hybrid # then reverse ce's direction. pn.leaf and ce.hybrid should never both occur! newroot = ce.node[1] # getOtherNode(ce, pn) ce.isChild1 = false end net.root = findfirst(isequal(newroot), net.node) end deleteNode!(net,nodei) deleteEdge!(net,pe,part=false) # do not update partitions. irrelevant for networks of level>1. return ce end """ removedegree2nodes!(net::HybridNetwork, keeproot=false::Bool) Delete *all* nodes of degree two in `net`, fusing the two adjacent edges together each time, and return the network. If the network has a degree-2 root and `keeproot` is false, then the root is eliminated as well, leaving the network unrooted. The only exception to this rule is if the root is incident to 2 (outgoing) hybrid edges. Removing the root should leave a loop-edge (equal end point), which we don't want to do, to preserve the paths in the original network. In this case, the root is maintained even if `keeproot` is false. If `keeproot` is true, then the root is kept even if it's of degree 2. See [`fuseedgesat!`](@ref). ```jldoctest julia> net = readTopology("(((((S1,(S2)#H1),(#H1,S3)))#H2),(#H2,S4));"); julia> PhyloNetworks.breakedge!(net.edge[3], net); # create a degree-2 node along hybrid edge julia> PhyloNetworks.breakedge!(net.edge[3], net); # another one: 2 in a row julia> PhyloNetworks.breakedge!(net.edge[10], net); # another one, elsewhere julia> writeTopology(net) # extra pairs of parentheses "((#H2,S4),(((((S1,(((S2)#H1))),(#H1,S3)))#H2)));" julia> removedegree2nodes!(net); julia> writeTopology(net) # even the root is gone "(#H2,S4,(((S1,(S2)#H1),(#H1,S3)))#H2);" julia> net = readTopology("((((C:0.9)I1:0.1)I3:0.1,((A:1.0)I2:0.4)I3:0.6):1.4,(((B:0.2)H1:0.6)I2:0.5)I3:2.1);"); julia> removedegree2nodes!(net, true); julia> writeTopology(net, round=true) # the root was kept "((C:1.1,A:2.0):1.4,B:3.4);" ``` """ function removedegree2nodes!(net::HybridNetwork, keeproot=false::Bool) rootnode = getroot(net) # caution: the root and its incident edges may change when degree-2 nodes # are removed. Indices of nodes to be removed would change too. rootin2cycle(nn) = isrootof(nn,net) && all(e.hybrid for e in nn.edge) toberemoved(nn) = (keeproot ? length(nn.edge) == 2 && nn !== rootnode : length(nn.edge) == 2 && !rootin2cycle(nn)) ndegree2nodes = sum(toberemoved.(net.node)) for _ in 1:ndegree2nodes # empty if 0 degree-2 nodes i = findfirst(toberemoved, net.node) # i may be 'nothing' if the root was initially thought to be removed # but later its edges turned to be hybrids, so should not be removed isnothing(i) || fuseedgesat!(i, net) end return net end """ addleaf!(net::HybridNetwork, node::Node, leafname::String, edgelength::Float64=-1.0) addleaf!(net::HybridNetwork, edge::Edge, leafname::String, edgelength::Float64=-1.0) Add a new external edge between `node` or between the "middle" of `edge` and a newly-created leaf, of name `leafname`. By default, the new edge length is missing (-1). output: newly created leaf node. # examples ```jldoctest julia> net = readTopology("((S1,(((S2,(S3)#H1),(#H1,S4)))#H2),(#H2,S5));"); julia> net.node[6].name # leaf S4 "S4" julia> PhyloNetworks.addleaf!(net, net.node[6], "4a"); # adding leaf to a node julia> writeTopology(net, internallabel=true) "((S1,(((S2,(S3)#H1),(#H1,(4a)S4)))#H2),(#H2,S5));" julia> PhyloNetworks.addleaf!(net, net.node[6], "4b"); julia> writeTopology(net, internallabel=true) "((S1,(((S2,(S3)#H1),(#H1,(4a,4b)S4)))#H2),(#H2,S5));" ``` ```jldoctest julia> net = readTopology("((S1,(((S2,(S3)#H1),(#H1,S4)))#H2),(#H2,S5));"); julia> [n.name for n in net.edge[7].node] # external edge to S4 2-element Vector{String}: "S4" "" julia> PhyloNetworks.addleaf!(net, net.edge[7], "4a"); # adding leaf to an edge julia> writeTopology(net, internallabel=true) "((S1,(((S2,(S3)#H1),(#H1,(S4,4a))))#H2),(#H2,S5));" ``` """ function addleaf!(net::HybridNetwork, speciesnode::Node, leafname::String, edgelength::Float64=-1.0) exterioredge = Edge(maximum(e.number for e in net.edge) + 1, edgelength) # isChild1 = true by default in edge creation pushEdge!(net, exterioredge) setEdge!(speciesnode, exterioredge) if speciesnode.hybrid || (!isrootof(speciesnode, net) && !getparentedge(speciesnode).containRoot) exterioredge.containRoot = false end newleaf = Node(maximum(n.number for n in net.node) + 1, true, false, [exterioredge]) # Node(number, leaf, hybrid, edge array) newleaf.name = leafname setNode!(exterioredge, [newleaf, speciesnode]) # [child, parent] to match isChild1 = true by default if speciesnode.leaf deleteat!(net.leaf,findfirst(isequal(speciesnode), net.leaf)) speciesnode.leaf = false net.numTaxa -= 1 end pushNode!(net, newleaf) # push node into network (see auxillary.jl) return newleaf end function addleaf!(net::HybridNetwork, startingedge::Edge, leafname::String, edgelength::Float64=-1.0) newnode, _ = breakedge!(startingedge, net) return addleaf!(net, newnode, leafname, edgelength) end # Claudia SL & Paul Bastide: November 2015, Cecile: Feb 2016 ################################################# # Direct Edges ################################################# """ directEdges!(net::HybridNetwork; checkMajor=true::Bool) Updates the edges' attribute `isChild1`, according to the root placement. Also updates edges' attribute `containRoot`, for other possible root placements compatible with the direction of existing hybrid edges. Relies on hybrid nodes having exactly 1 major hybrid parent edge, but checks for that if checkMajor=true. Warnings: 1. Assumes that isChild1 is correct on hybrid edges (to avoid changing the identity of which nodes are hybrids and which are not). 2. Does not check for cycles (to maintain a network's DAG status) Returns the network. Throws a 'RootMismatch' Exception if the root was found to conflict with the direction of any hybrid edge. """ function directEdges!(net::HybridNetwork; checkMajor=true::Bool) if checkMajor # check each node has 2+ hybrid parent edges (if any), and exactly one major. for n in net.node nparents = 0 # 0 or 2 normally, but could be >2 if polytomy. nmajor = 0 # there should be exactly 1 major parent if nparents>0 for e in n.edge if e.hybrid && n == getchild(e) nparents += 1 if (e.isMajor) nmajor +=1; end end end (nparents!=1) || error("node $(n.number) has exactly 1 hybrid parent edge") (nparents==0 || nmajor == 1) || error("hybrid node $(n.number) has 0 or 2+ major hybrid parents") (nparents!=2 || n.hybrid) || @warn "node $(n.number) has 2 parents but its hybrid attribute is false. It is not used in directEdges!, but might cause an error elsewhere." # to fix this: change n.hybrid, net.hybrid, net.numHybrids etc. # none of those attributes are used here. end end net.cleaned = false # attributed used by snaq! Will change isChild1 and containRoot for e in net.node[net.root].edge traverseDirectEdges!(net.node[net.root],e,true) end net.isRooted = true return net end # containroot = true until the path goes through a hybrid node, below which # containroot is turned to false. function traverseDirectEdges!(node::Node, edge::Edge, containroot::Bool) if edge.hybrid && node==getchild(edge) throw(RootMismatch( "direction (isChild1) of hybrid edge $(edge.number) conflicts with the root. isChild1 and containRoot were updated for a subset of edges in the network only.")) end if node == edge.node[1] edge.isChild1 = false cn = edge.node[2] # cn = child node else edge.isChild1 = true cn = edge.node[1] end edge.containRoot = containroot if !cn.leaf && (!edge.hybrid || edge.isMajor) # continue down recursion if edge.hybrid containroot=false; end # changes containroot locally, intentional. nchildren=0 for e in cn.edge if e==edge continue; end if (e.hybrid && cn == getchild(e)) continue; end traverseDirectEdges!(cn,e,containroot) nchildren += 1 end if nchildren==0 throw(RootMismatch("non-leaf node $(cn.number) had 0 children. Could be a hybrid whose parents' direction conflicts with the root. isChild1 and containRoot were updated for a subset of edges in the network only.")) end end return nothing end ################################################# ## Topological sorting ################################################# """ preorder!(net::HybridNetwork) Updates attribute net.nodes_changed in which the nodes are pre-ordered (also called topological sorting), such that each node is visited after its parent(s). The edges' direction needs to be correct before calling preorder!, using directEdges! """ function preorder!(net::HybridNetwork) net.isRooted || error("net needs to be rooted for preorder!, run root functions or directEdges!") net.nodes_changed = Node[] # path of nodes in preorder. queue = Node[] # problem with PriorityQueue(): dequeue() takes a # random member if all have the same priority 1. net.visited = [false for i = 1:size(net.node,1)]; push!(queue,net.node[net.root]) # push root into queue while !isempty(queue) #println("at this moment, queue is $([n.number for n in queue])") curr = pop!(queue); # deliberate choice over shift! for cladewise order currind = findfirst(x -> x===curr, net.node) # the "curr"ent node may have been already visited: because simple loop (2-cycle) !net.visited[currind] || continue net.visited[currind] = true # visit curr node push!(net.nodes_changed,curr) #push curr into path for e in curr.edge if curr == getparent(e) other = getchild(e) if !e.hybrid push!(queue,other) # print("queuing: "); @show other.number else e2 = getpartneredge(e, other) parent = getparent(e2) if net.visited[findfirst(x -> x===parent, net.node)] push!(queue,other) # warning: if simple loop, the same node will be pushed twice: child of "curr" via 2 edges end end end end end # println("path of nodes is $([n.number for n in net.nodes_changed])") end """ cladewiseorder!(net::HybridNetwork) Updates attribute net.cladewiseorder_nodeIndex. Used for plotting the network. In the major tree, all nodes in a given clade are consecutive. On a tree, this function also provides a pre-ordering of the nodes. The edges' direction needs to be correct before calling [`cladewiseorder!`](@ref), using [`directEdges!`](@ref) """ function cladewiseorder!(net::HybridNetwork) net.isRooted || error("net needs to be rooted for cladewiseorder!\n run root functions or directEdges!") net.cladewiseorder_nodeIndex = Int[] queue = [net.root] # index (in net) of nodes in the queue # print("queued the root's children's indices: "); @show queue while !isempty(queue) ni = pop!(queue); # deliberate choice over shift! for cladewise order # @show net.node[ni].number push!(net.cladewiseorder_nodeIndex, ni) for e in net.node[ni].edge if net.node[ni] ≡ getparent(e) # net.node[ni] is parent node of e if e.isMajor push!(queue, findfirst(isequal(getchild(e)), net.node)) # print("queuing: "); @show other.number end end end end end """ rotate!(net::HybridNetwork, nodeNumber::Integer; orderedEdgeNum::Array{Int,1}) Rotates the order of the node's children edges. Useful for plotting, to remove crossing edges. If `node` is a tree node with no polytomy, the 2 children edges are switched and the optional argument `orderedEdgeNum` is ignored. Use `plot(net, shownodenumber=true, showedgenumber=false)` to map node and edge numbers on the network, as shown in the examples below. (see package [PhyloPlots](https://github.com/cecileane/PhyloPlots.jl)) Warning: assumes that edges are correctly directed (isChild1 updated). This is done by `plot(net)`. Otherwise run `directEdges!(net)`. # Example ```julia julia> net = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); julia> using PhyloPlots julia> plot(net, shownodenumber=true) julia> rotate!(net, -4) julia> plot(net) julia> net=readTopology("(4,((1,(2)#H7:::0.864):2.069,(6,5):3.423):0.265,(3,#H7:::0.136):10.0);"); julia> plot(net, shownodenumber=true, showedgenumber=true) julia> rotate!(net, -1, orderedEdgeNum=[1,12,9]) julia> plot(net, shownodenumber=true, showedgenumber=true) julia> rotate!(net, -3) julia> plot(net) ``` Note that `LinearAlgebra` also exports a function named `rotate!` in Julia v1.5. If both packages need to be used in Julia v1.5 or higher, usage of `rotate!` needs to be qualified, such as with `PhyloNetworks.rotate!`. """ function rotate!(net::HybridNetwork, nnum::Integer; orderedEdgeNum=Int[]::Array{Int,1}) nind = 0 nind = findfirst(n -> n.number == nnum, net.node) nind !== nothing || error("cannot find any node with number $nnum in network.") n = net.node[nind] ci = Int[] # children edge indices for i = 1:length(n.edge) if n == getparent(n.edge[i]) push!(ci,i) end end if length(ci) < 2 @warn "no edge to rotate: node $nnum has $(length(ci)) children edge." elseif length(ci)==2 || length(orderedEdgeNum)==0 etmp = n.edge[ci[1]] n.edge[ci[1]] = n.edge[ci[2]] n.edge[ci[2]] = etmp else # 3+ children edges and orderedEdgeNum provided length(orderedEdgeNum)==length(ci) || error("orderedEdgeNum $orderedEdgeNum should be of length $(length(ci))") length(unique(orderedEdgeNum))==length(ci) || error("orderedEdgeNum $orderedEdgeNum should not have duplicates") childrenedge = n.edge[ci] # makes a shallow copy, because of subsetting [ci] for i=1:length(ci) tmp = findall(x -> x.number == orderedEdgeNum[i], childrenedge) length(tmp)==1 || error("edge number $(orderedEdgeNum[i]) not found as child of node $(n.number)") n.edge[ci[i]] = childrenedge[tmp[1]] end end return nothing end ### WARNING: # deleteleaf! is similar but also very different from # deleteLeaf! in pseudolik.jl, which # - does not necessarily remove nodes of degree 2, # - requires and updates all attributes for level-1 networks: # inCycle, partition, branch lengths, diamond/triangle types etc. # - is used a lot within snaq! to extract quartets and retains info # on which parameters in the full network affect the quartet. # deleteIntLeaf! somewhat similar to fuseedgesat! """ deleteleaf!(HybridNetwork, leafName::AbstractString; ...) deleteleaf!(HybridNetwork, Node; ...) deleteleaf!(HybridNetwork, Integer; index=false, ...) Delete a node from the network, possibly from its name, number, or index in the network's array of nodes. The first two versions require that the node is a leaf. The third version does **not** require that the node is a leaf: If it has degree 3 or more, nothing happens. If it has degree 1 or 2, then it is deleted. ## keyword arguments `simplify`: if true and if deleting the node results in 2 hybrid edges forming a cycle of k=2 nodes, then these hybrid edges are merged and simplified as a single tree edge. `unroot`: if true, a root of degree 1 or 2 is deleted. If false, the root is deleted if it is of degree 1 (no root edge is left), but is kept if it is of degree 2. Deleting all leaves in an outgroup clade or grade will leave the ingroup rooted (that is, the new root will be of degree 2). `nofuse`: if true, keep nodes (and edges) provided that they have at least one descendant leaf, even if they are of degree 2. This will keep two-cycles (forcing `simplify` to false). Nodes without any descendant leaves are deleted. If `nofuse` is false, edges adjacent to degree-2 nodes are fused. `multgammas`: if true, the fused edge has γ equal to the product of the hybrid edges that have been fused together, which may result in tree edges with γ<1, or with reticulations in which the two parent γ don't add up to 1. `keeporiginalroot`: if true, keep the root even if it is of degree one (forcing `unroot` to be false). Warning: does **not** update edges' `containRoot` nor attributes related to level-1 networks such as inCycle, partition, gammaz, etc. Does not require branch lengths, and designed to work on networks of all levels. """ function deleteleaf!(net::HybridNetwork, node::Node; kwargs...) node.leaf || error("node number $(node.number) is not a leaf.") deleteleaf!(net, node.number; kwargs..., index=false) end function deleteleaf!(net::HybridNetwork, nodeName::AbstractString; kwargs...) tmp = findall(n -> n.name == nodeName, net.node) if length(tmp)==0 error("node named $nodeName was not found in the network.") elseif length(tmp)>1 error("several nodes were found with name $nodeName.") end deleteleaf!(net, tmp[1]; kwargs..., index=true) end # recursive algorithm. nodes previously removed are all necessaily # *younger* than the current node to remove. Stated otherwise: # edges previously removed all go "down" in time towards current node: # - tree edge down to an original leaf, # - 2 hybrid edges down to a hybrid node. # hybrid edges from node to another node are not removed. fused instead. # consequence: node having 2 hybrid edges away from node should not occur. function deleteleaf!(net::HybridNetwork, nodeNumber::Integer; index=false::Bool, nofuse=false::Bool, simplify=true::Bool, unroot=false::Bool, multgammas=false::Bool, keeporiginalroot=false::Bool) i = nodeNumber # good if index=true if !index i = findfirst(n -> n.number == nodeNumber, net.node) i !== nothing || error("cannot delete leaf number $(nodeNumber) because it is not part of net") elseif i > length(net.node) error("node index $i too large: the network only has $(length(net.node)) nodes.") end nodei = net.node[i] nodeidegree = length(nodei.edge) if nodeidegree == 0 length(net.node)==1 || error("leaf $(nodei.name) has no edge but network has $(length(net.node)) nodes (instead of 1).") @warn "Only 1 node. Removing it: the network will be empty" deleteNode!(net,nodei) # empties the network elseif nodeidegree == 1 pe = nodei.edge[1] pn = getOtherNode(pe, nodei) # parent node of leaf if net.root == i && keeporiginalroot return nothing end # keep nodei if pn is a leaf: keep 1 edge for the single remaining leaf if pn.leaf net.root = i # it should have been i before anyway length(net.edge)==1 || error("neighbor of degree-1 node $(nodei.name) is a leaf, but network had $(length(net.edge)) edges (instead of 1).") length(pn.edge)==1 || error("neighbor of $(nodei.name) is a leaf, incident to $(length(pn.edge)) edges (instead of 1)") return nothing end # remove nodei and pe. removeNode!(pn,pe) # perhaps useless. in case gc() on pe affects pn removeEdge!(pn,pe) deleteEdge!(net,pe,part=false) if net.root==i # if node was the root, new root = pn net.root = findfirst(x -> x===pn, net.node) end deleteNode!(net,nodei) # this updates the index net.root deleteleaf!(net, pn.number; nofuse = nofuse, simplify=simplify, unroot=unroot, multgammas=multgammas, keeporiginalroot=keeporiginalroot) return nothing elseif nodeidegree > 2 # do nothing: nodei has degree 3+ (through recursive calling) return nothing end # if we get to here, nodei has degree 2 exactly: --e1-- nodei --e2-- if i==net.root && (keeporiginalroot || !unroot) return nothing # node = root of degree 2 and we want to keep it end e1 = nodei.edge[1] e2 = nodei.edge[2] if e1.hybrid && e2.hybrid cn = getchild(e1) cn2 = getchild(e2) if !(nodei ≡ cn && nodei ≡ cn2) # nodei *not* the child of both e1 and e2 # possible at the root, in which case e1,e2 should have same child (i==net.root && cn ≡ cn2) || error("after removing descendants, node $(nodei.number) has 2 hybrid edges but is not the child of both.") # delete e1,e2,nodei and move the root to their child cn cn.hybrid || error("child node $(cn.number) of hybrid edges $(e1.number) and $(e2.number) should be a hybrid.") # check that cn doesn't have any other parent than e1 and e2 any(getchild(e) ≡ cn && e !== e1 && e !==e2 for e in cn.edge) && error("root has 2 hybrid edges, but their common child has an extra parent") removeEdge!(cn,e1); removeEdge!(cn,e2) removeHybrid!(net,cn) # removes cn from net.hybrid, updates net.numHybrids cn.hybrid = false # !! allowrootbelow! not called: would require correct isChild1 empty!(e1.node); empty!(e2.node) deleteEdge!(net,e1,part=false); deleteEdge!(net,e2,part=false) empty!(nodei.edge) deleteNode!(net,nodei) net.root = findfirst(x -> x ≡ cn, net.node) deleteleaf!(net, net.root; index=true, nofuse=nofuse, simplify=simplify, unroot=unroot, multgammas=multgammas, keeporiginalroot=keeporiginalroot) return nothing end # by now, nodei is the child of both e1 and e2 p1 = getparent(e1) # find both parents of hybrid leaf p2 = getparent(e2) # remove node1 and both e1, e2 sameparent = (p1≡p2) # 2-cycle removeNode!(p1,e1); removeNode!(p2,e2) # perhaps useless removeEdge!(p1,e1); removeEdge!(p2,e2) deleteEdge!(net,e1,part=false); deleteEdge!(net,e2,part=false) if net.root==i net.root=getIndex(p1,net); end # should never occur though. deleteNode!(net,nodei) # recursive call on both p1 and p2. deleteleaf!(net, p1.number; nofuse = nofuse, simplify=simplify, unroot=unroot, multgammas=multgammas, keeporiginalroot=keeporiginalroot) # p2 may have already been deleted: e.g. if sameparent, or other scenarios if !sameparent p2idx = findfirst(n -> n.number == p2.number, net.node) isnothing(p2idx) || deleteleaf!(net, p2idx; index=true, nofuse=nofuse, simplify=simplify, unroot=unroot, multgammas=multgammas, keeporiginalroot=keeporiginalroot) end elseif !nofuse e1 = fuseedgesat!(i,net, multgammas) # fused edge if simplify && e1.hybrid # check for 2-cycle at new hybrid edge cn = getchild(e1) e2 = getpartneredge(e1, cn) # companion hybrid edge pn = getparent(e1) if pn ≡ getparent(e2) # e1 and e2 have same child and same parent. Remove e1. e2.hybrid = false # assumes bicombining at cn: no third hybrid parent e2.isMajor = true e2.gamma = addBL(e1.gamma, e2.gamma) removeEdge!(pn,e1); removeEdge!(cn,e1) deleteEdge!(net,e1,part=false) removeHybrid!(net,cn) # removes cn from net.hybrid, updates net.numHybrids cn.hybrid = false # !! allowrootbelow! not called: would require correct isChild1 # call recursion again because pn and/or cn might be of degree 2 (or even 1). deleteleaf!(net, cn.number; nofuse = nofuse, simplify=simplify, unroot=unroot, multgammas=multgammas, keeporiginalroot=keeporiginalroot) pnidx = findfirst(n -> n.number == pn.number, net.node) isnothing(pnidx) || deleteleaf!(net, pnidx; index=true, nofuse=nofuse, simplify=simplify, unroot=unroot, multgammas=multgammas, keeporiginalroot=keeporiginalroot) end end end return nothing end """ deleteaboveLSA!(net, preorder=true::Bool) Delete edges and nodes above (ancestral to) the least stable ancestor (LSA) of the leaves in `net`. See [`leaststableancestor`](@ref) for the definition of the LSA. Output: modified network `net`. """ function deleteaboveLSA!(net::HybridNetwork, preorder=true::Bool) lsa, lsaindex = leaststableancestor(net, preorder) for _ in 1:(lsaindex-1) # the network may temporarily have multiple "roots" nodei = popfirst!(net.nodes_changed) for e in nodei.edge # delete all of nodei's edges (which much be outgoing) cn = getchild(e) removeEdge!(cn, e) # also updates cn.hasHybEdge empty!(e.node) deleteEdge!(net, e; part=false) end empty!(nodei.edge) deleteNode!(net, nodei) # resets net.root if nodei.name != "" j = findfirst(isequal(nodei.name), net.names) isnothing(j) || deleteat!(net.names, j) end end net.root = findfirst( n -> n===lsa, net.node) if lsa.hybrid # edge case: LSA may be hybrid if 1 single leaf in network removeHybrid!(net, lsa) lsa.hybrid = false end return net end """ resetNodeNumbers!(net::HybridNetwork; checkPreorder=true, type=:ape) Change internal node numbers of `net` to consecutive numbers from 1 to the total number of nodes. keyword arguments: - `type`: default is `:ape`, to get numbers that satisfy the conditions assumed by the `ape` R package: leaves are 1 to n, the root is n+1, and internal nodes are higher consecutive integers. If `:postorder`, nodes are numbered in post-order, with leaves from 1 to n (and the root last). If `:internalonly`, leaves are unchanged. Only internal nodes are modified, to take consecutive numbers from (max leaf number)+1 and up. With this last option, the post-ordering of nodes is by-passed. - `checkPreorder`: if false, the `isChild1` edge field and the `net.nodes_changed` network field are supposed to be correct (to get nodes in preorder). This is not needed when `type=:internalonly`. # Examples ```jldoctest julia> net = readTopology("(A,(B,(C,D)));"); julia> PhyloNetworks.resetNodeNumbers!(net) julia> printNodes(net) # first column "node": root is 5 node leaf hybrid hasHybEdge name inCycle edges'numbers 1 true false false A -1 1 2 true false false B -1 2 3 true false false C -1 3 4 true false false D -1 4 7 false false false -1 3 4 5 6 false false false -1 2 5 6 5 false false false -1 1 6 julia> net = readTopology("(A,(B,(C,D)));"); julia> PhyloNetworks.resetNodeNumbers!(net; type=:postorder) julia> printNodes(net) # first column "node": root is 7 node leaf hybrid hasHybEdge name inCycle edges'numbers 1 true false false A -1 1 2 true false false B -1 2 3 true false false C -1 3 4 true false false D -1 4 5 false false false -1 3 4 5 6 false false false -1 2 5 6 7 false false false -1 1 6 ``` """ function resetNodeNumbers!(net::HybridNetwork; checkPreorder=true::Bool, type::Symbol=:ape) if checkPreorder directEdges!(net) preorder!(net) # to create/update net.nodes_changed end # first: re-number the leaves if type == :internalonly lnum = maximum(n.number for n in net.node if n.leaf) + 1 else lnum = 1 # first number for n in net.node n.leaf || continue n.number = lnum lnum += 1 end end # second: re-number internal nodes if type == :ape nodelist = net.nodes_changed # pre-order: root first elseif type == :postorder nodelist = reverse(net.nodes_changed) # post-order elseif type == :internalonly nodelist = net.node end for n in nodelist !n.leaf || continue n.number = lnum lnum += 1 end end """ resetEdgeNumbers!(net::HybridNetwork, verbose=true) Check that edge numbers of `net` are consecutive numbers from 1 to the total number of edges. If not, reset the edge numbers to be so. """ function resetEdgeNumbers!(net::HybridNetwork, verbose=true::Bool) enum = [e.number for e in net.edge] ne = length(enum) unused = setdiff(1:ne, enum) if isempty(unused) return nothing # all good end verbose && @warn "resetting edge numbers to be from 1 to $ne" ind2change = findall(x -> x ∉ 1:ne, enum) length(ind2change) == length(unused) || error("can't reset edge numbers") for i in 1:length(unused) net.edge[ind2change[i]].number = unused[i] end return nothing; end """ norootbelow!(e::Edge) Set `containRoot` to `false` for edge `e` and all edges below, recursively. The traversal stops if `e.containRoot` is already `false`, assuming that `containRoot` is already false all the way below down that edge. """ function norootbelow!(e::Edge) e.containRoot || return nothing # if already false: stop # if true: turn to false then move down to e's children e.containRoot = false cn = getchild(e) # cn = child node for ce in cn.edge ce !== e || continue # skip e getparent(ce) === cn || continue # skip edges that aren't children of cn norootbelow!(ce) end return nothing end """ allowrootbelow!(e::Edge) allowrootbelow!(n::Node, parent_edge_of_n::Edge) Set `containRoot` to `true` for edge `e` and all edges below, recursively. The traversal stops whenever a hybrid node is encountered: if the child of `e` is a hybrid node (that is, if `e` is a hybrid edge) or if `n` is a hybrid node, then the edges below `e` or `n` are *not* traversed. """ function allowrootbelow!(e::Edge) e.containRoot = true e.hybrid && return nothing # e hybrid edge <=> its child hybrid node: stop allowrootbelow!(getchild(e), e) end function allowrootbelow!(n::Node, pe::Edge) # pe assumed to be the parent of n for ce in n.edge ce !== pe || continue # skip parent edge of n getparent(ce) === n || continue # skip edges that aren't children of n allowrootbelow!(ce) end return nothing end """ allowrootbelow!(net::HybridNetwork) Set `containRoot` to `true` for each edge below the root node, then traverses `net` in preorder to update `containRoot` of all edges (stopping at hybrid nodes): see the other methods. Assumes correct `isChild1` edge field. """ function allowrootbelow!(net::HybridNetwork) rn = net.node[net.root] for e in rn.edge if e.containRoot allowrootbelow!(getchild(e), e) end end end """ unzip_canonical!(net::HybridNetwork) Unzip all reticulations: set the length of child edge to 0, and increase the length of both parent edges by the original child edge's length, to obtain the canonical version of the network according to Pardi & Scornavacca (2015). Output: vector of hybrid node in postorder, vector of child edges whose length is constrained to be 0, and vector of their original branch lengths to re-zip if needed using [`rezip_canonical!`](@ref). Assumption: `net.hybrid` is correct, but a preordering of all nodes is *not* assumed. Note: This unzipping is not as straightforward as it might seem, because of "nested" zippers: when the child of a hybrid node is itself a hybrid node. The unzipping is propagated all the way through. """ function unzip_canonical!(net::HybridNetwork) hybchild = Dict{Int,Tuple{Edge,Float64}}() # keys: hybrid node number (immutable) hybladder = Dict{Int,Union{Nothing,Node}}() for h in net.hybrid ce = getchildedge(h) hybchild[h.number] = (ce, ce.length) # original lengths before unzipping hybladder[h.number] = (ce.hybrid ? getchild(ce) : nothing) end hybrid_po = Node[] # will list hybrid nodes with partial post-order hybpriority = PriorityQueue(h => i for (i,h) in enumerate(net.hybrid)) nextpriority = length(hybpriority)+1 while !isempty(hybpriority) h,p = peek(hybpriority) hl = hybladder[h.number] if isnothing(hl) || !haskey(hybpriority,hl) # hl no longer key because had priority < p, so already dequeued push!(hybrid_po, h) delete!(hybpriority, h) else hybpriority[h] = nextpriority nextpriority += 1 end end zeroedge = Edge[] originallength = Float64[] for h in hybrid_po # partial post-order: child < parent if hybrid ladder ce, ol = hybchild[h.number] # child edge, original length push!(zeroedge, ce) push!(originallength, ol) unzipat_canonical!(h,ce) end return hybrid_po, zeroedge, originallength end """ unzipat_canonical!(hyb::Node, childedge::Edge) Unzip the reticulation a node `hyb`. See [`unzip_canonical!`](@ref PhyloNetworks.unzip_canonical!). Warning: no check that `hyb` has a single child. Output: constrained edge (child of `hyb`) and its original length. """ function unzipat_canonical!(hybnode::Node, childedge::Edge) clen = childedge.length # might be different from original if hybrid ladder for e in hybnode.edge if e === childedge e.length = 0.0 else e.length += clen end end return clen end """ rezip_canonical!(hybridnodes::Vector{Node}, childedges::Vector{Edge}, originallengths::Vector{Float64}) Undo [`unzip_canonical!`](@ref). """ function rezip_canonical!(hybridnode::Vector{Node}, childedge::Vector{Edge}, originallength::Vector{Float64}) for (i,h) in enumerate(hybridnode) # assumed in post-order ce = childedge[i] ol = originallength[i] lendiff = ol - ce.length # ce.length might be temporarily < 0 if hybrid ladder for e in h.edge if e === ce e.length = ol else e.length -= lendiff end end end return nothing end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
45475
#= constraints: - species groups e.g. as polytomies (type 1), or - clades in the major tree (type 2), or - clades in *some* displayed tree (type 3, not implemented). outgroups "grades" can be coded as ingroup clades move types, all under topological constraints: - NNI = nearest neighbor interchange for undirected network, similar to NNIs for rooted networks defined in Gambette, van Iersel, Jones, Lafond, Pardi and Scornavacca (2017), Rearrangement moves on rooted phylogenetic networks. PLOS Computational Biology 13(8):e1005611. - move the root: needed for optimization of a semi-directed network, because the root position affects the feasibility of the NNIs starting from a BR configuration (bifurcation -> reticulation). - remove a hybrid edge: `deletehybridedge!` in file deleteHybrid.jl, but does not check for clade constraints - add a hybrid edge: in file addHybrid.jl - change the direction of a hybrid edge in `moves_snaq.jl`, functions are tailored to level-1 networks; here, functions apply to semidirected networks of all levels. =# """ Type for various topological constraints, such as: 1. a set of taxa forming a clade in the major tree 2. a set of individuals belonging to the same species 3. a set of taxa forming a clade in any one of the displayed trees """ mutable struct TopologyConstraint "type of constraint: 1=species, 2=clade in major tree. 3=clade in some displayed tree: not yet implemented." type::UInt8 "names of taxa in the constraint (clade / species members)" taxonnames::Vector{String} """ node numbers of taxa in the constraint (clade / species members). warning: interpretation dependent on the internal network representation """ taxonnums::Set{Int} "stem edge of the constrained group" edge::Edge "crown node, that is, child node of stem edge" node::Node end """ TopologyConstraint(type::UInt8, taxonnames::Vector{String}, net::HybridNetwork) Create a topology constraint from user-given type, taxon names, and network. There are 3 types of constraints: - type 1: A set of tips that forms a species. - type 2: A set of tips that forms a clade in the major tree. Note that the root matters. Constraining a set of species to be an outgroup is equivalent to constraining the ingroup to form a clade. - type 3: A set of tips that forms a clade in any one of the displayed trees. Note: currently, with type-1 constraints, hybridizations are prevented from coming into or going out of a species group. # examples ```jldoctest julia> net = readTopology("(((2a,2b),(((((1a,1b,1c),4),(5)#H1),(#H1,(6,7))))#H2),(#H2,10));"); julia> c_species1 = PhyloNetworks.TopologyConstraint(0x01, ["1a","1b","1c"], net) Species constraint, on tips: 1a, 1b, 1c stem edge number 7 crown node number -9 julia> c_species2 = PhyloNetworks.TopologyConstraint(0x01, ["2a","2b"], net) Species constraint, on tips: 2a, 2b stem edge number 3 crown node number -4 julia> nni!(net , net.edge[3], true, true, [c_species2]) === nothing # we get nothing: would break species 2 true julia> # the following gives an error, because 4,5 do not form a clade in "net" # PhyloNetworks.TopologyConstraint(0x02, ["4","5"], net) julia> c_clade145 = PhyloNetworks.TopologyConstraint(0x02, ["1a","1b","1c","4","5"], net) Clade constraint, on tips: 1a, 1b, 1c, 4, 5 stem edge number 12 crown node number -7 julia> nni!(net , net.edge[12], true, true, [c_species1, c_clade145]) # we get nothing (failed NNI): would break the clade ``` """ function TopologyConstraint(type::UInt8, taxonnames::Vector{String}, net::HybridNetwork) ntax_clade = length(taxonnames) ntax_clade >= 2 || error("there must be 2 or more taxon name in a clade or species constraint.") taxonnums = Set{Int}() indices = findall(in(taxonnames), [n.name for n in net.leaf]) length(indices) == ntax_clade || error("taxa cannot be matched to nodes. Check for typos.") outsideclade = setdiff([n.name for n in net.leaf], taxonnames) # find the set of node numbers that correspond to taxonnames for (i,taxon) in enumerate(taxonnames) index = findfirst(n -> n.name == taxon, net.leaf) !isnothing(index) || error("taxon $taxon is not found in the network. Check for typos.") push!(taxonnums, net.leaf[index].number) # note: not ordered as in taxonnames end # get interior ancestor edges in major tree (no hybrids) matrix = hardwiredClusters(majorTree(net), vcat(taxonnames, outsideclade)) # look for row with ones in relevant columns, zeros everywhere else (or zeros there and ones everywhere else) edgenum = 0 # 0 until we find the stem edge comparator = zeros(Int8, size(matrix)[2]-2) comparator[1:ntax_clade] = ones(Int8, ntax_clade) # go through matrix row by row to find match with comparator. Return number for i in 1:size(matrix, 1) if matrix[i,2:size(matrix)[2]-1] == comparator # found the mrca! edgenum = matrix[i, 1] break end end if edgenum == 0 comparator .= 1 .- comparator for i in 1:size(matrix)[1] if matrix[i,2:size(matrix)[2]-1] == comparator error("""The clade given is not rooted correctly, making it a grade instead of a clade. You can re-try after modifying the root of your network.""") end end error("The taxa given do not form a clade in the network") end edgei = findfirst(e -> e.number == edgenum, net.edge) edgei !== nothing || error("hmm. hardwiredClusters on the major tree got an edge number not in the network") stemedge = net.edge[edgei] mrcanode = getchild(stemedge) TopologyConstraint(type, taxonnames, taxonnums, stemedge, mrcanode) end function Base.show(io::IO, obj::TopologyConstraint) str = (obj.type == 0x01 ? "Species constraint, on tips: " : "Clade constraint, on tips: " ) str *= join(obj.taxonnames, ", ") str *= "\n stem edge number $(obj.edge.number)\n crown node number $(obj.node.number)" print(io, str) end """ constraintviolated(network::HybridNetwork, constraints::Vector{TopologyConstraint}) True if `network` violates one (or more) of the constraints of type 1 (individuals in a species group) or type 2 (must be clades in the major tree). Warning: constraints of type 3 are not implemented. """ function constraintviolated(net::HybridNetwork, constraints::Vector{TopologyConstraint}) # fixit next PR: add option to give a vector of constraint types to check, # then only check these constraint types if isempty(constraints) return false end # avoids extracting major tree when no constraint tree = majorTree(net) for con in constraints # checks directionality of stem edge hasn't changed if con.type in [0x01, 0x02] getchild(con.edge) === con.node || return true tei = findfirst(e -> e.number == con.edge.number, tree.edge) tei !== nothing || error("hmm. edge number $(con.edge.number) was not found in the network's major tree") treeedge = tree.edge[tei] des = descendants(treeedge) # vector of node numbers, descendant tips only by default Set(des) == con.taxonnums || return true end end return false end """ updateconstraints!(constraints::Vector{TopologyConstraint}, net::HybridNetwork) Update the set `taxonnum` in each constraint, assuming that the stem edge and the crown node are still correct, and that their descendants are still correct. May be needed if the node and edge numbers were modified by [`resetNodeNumbers!`](@ref) or [`resetEdgeNumbers!`](@ref). Warning: does *not* check that the names of leaves with numbers in `taxonnum` are `taxonnames`. ```jldoctest julia> net = readTopology("(((2a,2b),(((((1a,1b,1c),4),(5)#H1),(#H1,(6,7))))#H2),(#H2,10));"); julia> c_species1 = PhyloNetworks.TopologyConstraint(0x01, ["1a","1b","1c"], net) Species constraint, on tips: 1a, 1b, 1c stem edge number 7 crown node number -9 julia> c_species1.taxonnums Set{Int64} with 3 elements: 5 4 3 julia> c_clade145 = PhyloNetworks.TopologyConstraint(0x02, ["1a","1b","1c","4","5"], net) Clade constraint, on tips: 1a, 1b, 1c, 4, 5 stem edge number 12 crown node number -7 julia> PhyloNetworks.resetNodeNumbers!(net) julia> net.node[4].number = 111; julia> PhyloNetworks.updateconstraints!([c_species1, c_clade145], net) julia> c_species1 Species constraint, on tips: 1a, 1b, 1c stem edge number 7 crown node number 21 julia> c_species1.taxonnums Set{Int64} with 3 elements: 5 4 111 ``` """ function updateconstraints!(constraints::Vector{TopologyConstraint}, net::HybridNetwork) if isempty(constraints) return nothing end # avoids extracting major tree when no constraint tree = majorTree(net) for con in constraints if con.type in [0x01, 0x02] getchild(con.edge) === con.node || error("the stem edge and crown node have been disconnected") tei = findfirst(e -> e.number == con.edge.number, tree.edge) tei !== nothing || error("stem edge number $(con.edge.number) was not found in the network's major tree") des = descendants(tree.edge[tei]) # vector of node numbers, descendant tips only by default d1 = setdiff(con.taxonnums, des) # set d2 = setdiff(des, con.taxonnums) # array length(d1) == length(d2) || error("missing or extra taxa in the clade / species.") replace!(con.taxonnums, Dict(tn => d2[i] for (i,tn) in enumerate(d1))...) end end return nothing end """ updateconstraintfields!(constraints::Vector{TopologyConstraint}, net::HybridNetwork) Update fields stem `edge` and crown `node` to match the given `net`. Assumes that the constraints are still met in `net`, and that nodes & edges are numbered identically in `net` as in the network used to create all `constraints`. fixit: remove the assumption that constraints are still met, since an NNI near the crown of a constrained clade might change the crown node and / or the stem edge (u and v exchange). """ function updateconstraintfields!(constraints::Vector{TopologyConstraint}, net::HybridNetwork) for con in constraints num = con.edge.number con.edge = net.edge[findfirst([e.number == num for e in net.edge])] num = con.node.number con.node = net.node[findfirst([n.number == num for n in net.node])] end end #= nice to add: option to modify branch lengths during NNI =# """ nni!(net::HybridNetwork, e::Edge, nohybridladder::Bool=true, no3cycle::Bool=true, constraints=TopologyConstraint[]::Vector{TopologyConstraint}) Attempt to perform a nearest neighbor interchange (NNI) around edge `e`, randomly chosen among all possible NNIs (e.g 3, sometimes more depending on `e`) satisfying the constraints, and such that the new network is a DAG. The number of possible NNI moves around an edge depends on whether the edge's parent/child nodes are tree or hybrid nodes. This is calculated by [`nnimax`](@ref). The option `no3cycle` forbids moves that would create a 3-cycle in the network. When `no3cycle` = false, 2-cycle and 3-cycles may be generated. Note that the defaults values are for positional (not keyword) arguments, so two or more arguments can be used, but in a specific order: nni!(net, e) or nni!(net, e, nohybridladder), nni!(net, e, nohybridladder, no3cycle), nni!(net, e, nohybridladder, no3cycle, contraints). Assumptions: - The starting network does not have 3-cycles, if `no3cycle=true`. No check for the presence of 2- and 3-cycles in the input network. - The edges' field `isChild1` is correct in the input network. (This field will be correct in the output network.) Output: information indicating how to undo the move or `nothing` if all NNIs failed. # examples ```jldoctest julia> str_network = "(((S8,S9),(((((S1,S2,S3),S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));"; julia> net = readTopology(str_network); julia> using Random; Random.seed!(3); julia> undoinfo = nni!(net, net.edge[3], true, true); # true's to avoid hybrid ladders and 3-cycles julia> writeTopology(net) "(((S8,(((((S1,S2,S3),S4),(S5)#H1),(#H1,(S6,S7))))#H2),S9),(#H2,S10));" julia> nni!(undoinfo...); julia> writeTopology(net) == str_network # net back to original topology: the NNI was "undone" true ``` """ function nni!(net::HybridNetwork, e::Edge, nohybridladder::Bool=true, no3cycle::Bool=true, constraints=TopologyConstraint[]::Vector{TopologyConstraint}) for con in constraints # reject NNI if the focus edge is the stem of a constraint. # sufficient to maintain star species constraints # but not sufficient for clades. if con.edge === e return nothing end end nnirange = 0x01:nnimax(e) # 0x01 = 1 but UInt8 instead of Int nnis = Random.shuffle(nnirange) for nummove in nnis # iterate through all possible NNIs, but in random order moveinfo = nni!(net, e, nummove, nohybridladder, no3cycle) !isnothing(moveinfo) || continue # to next possible NNI # if constraintviolated(net, constraints) # # fixit for next PR: not needed for species constraints, # # not sufficient for clades if γ / isMajor modified later, or if # # constraints met after NNI but stem / crows need to be moved # nni!(moveinfo...) # undo the previous NNI # continue # try again # end return moveinfo end return nothing # if we get to this point, all NNIs failed end """ nnimax(e::Edge) Return the number of NNI moves around edge `e`, assuming that the network is semi-directed. Return 0 if `e` is not internal, and more generally if either node attached to `e` does not have 3 edges. Output: UInt8 (e.g. `0x02`) """ function nnimax(e::Edge) length(e.node[1].edge) == 3 || return 0x00 length(e.node[2].edge) == 3 || return 0x00 # e.hybrid and hybrid parent: RR case, 2 possible NNIs only # e.hybrid and tree parent: BR case, 3 or 6 NNIs if e is may contain the root # e not hybrid, hyb parent: RB case, 4 NNIs # e not hybrid, tree parent: BB case, 2 NNIs if directed, 8 if undirected hybparent = getparent(e).hybrid n = (e.hybrid ? (hybparent ? 0x02 : (e.containRoot ? 0x06 : 0x03)) : # RR & BR (hybparent ? 0x04 : (e.containRoot ? 0x08 : 0x02))) # RB & BB return n end """ nni!(net::HybridNetwork, uv::Edge, nummove::UInt8, nohybridladder::Bool, no3cycle::Bool) Modify `net` with a nearest neighbor interchange (NNI) around edge `uv`. Return the information necessary to undo the NNI, or `nothing` if the move was not successful (such as if the resulting graph was not acyclic (not a DAG) or if the focus edge is adjacent to a polytomy). If the move fails, the network is not modified. `nummove` specifies which of the available NNIs is performed. rooted-NNI options according to Gambette et al. (2017), fig. 8: * BB: 2 moves, both to BB, if directed edges. 8 moves if undirected. * RR: 2 moves, both to RR. * BR: 3 moves, 1 RB & 2 BRs, if directed. 6 moves if e is undirected. * RB: 4 moves, all 4 BRs. The extra options are due to assuming a semi-directed network, whereas Gambette et al (2017) describe options for rooted networks. On a semi-directed network, there might be a choice of how to direct the edges that may contain the root, e.g. choice of e=uv versus vu, and choice of labelling adjacent nodes as α/β (BB), or as α/γ (BR). `nohybridladder` = true prevents moves that would create a hybrid ladder in the network, that is, 2 consecutive hybrid nodes (one parent of the other). `no3cycle` = true prevents NNI moves that would make a 3-cycle, and assumes that the input network does not have any 2- or 3-cycles. If `no3cycle` is false, 3-cycles can be generated, but NNIs generating 2-cycles are prevented. The edge field `isChild1` is assumed to be correct according to the `net.root`. """ function nni!(net::HybridNetwork, uv::Edge, nummove::UInt8, nohybridladder::Bool, no3cycle::Bool) nmovemax = nnimax(uv) if nmovemax == 0x00 # uv not internal, or polytomy e.g. species represented by polytomy with >2 indiv return nothing end nummove <= nmovemax || error("nummove $(nummove) must be <= $nmovemax for edge number $(uv.number)") u = getparent(uv) v = getchild(uv) ## TASK 1: grab the edges adjacent to uv: αu, βu, vγ, vδ and adjacent nodes # get edges αu & βu connected to u # α = u's major parent if it exists, β = u's last child or minor parent if u.hybrid αu = getparentedge(u) βu = getparentedgeminor(u) α = getparent(αu) β = getparent(βu) else # u may not have any parent, e.g. if root node # pick αu = parent edge if possible, first edge of u (other than uv) otherwise labs = [edgerelation(e, u, uv) for e in u.edge] pti = findfirst(isequal(:parent), labs) # parent index: there should be 1 or 0 ci = findall( isequal(:child), labs) # vector. there should be 1 or 2 if pti === nothing length(ci) == 2 || error("node $(u.number) should have 2 children other than node number $(v.number)") pti = popfirst!(ci) αu = u.edge[pti] α = getchild(αu) else αu = u.edge[pti] α = getparent(αu) end βu = u.edge[ci[1]] β = getchild(βu) end # get edges vδ & vγ connected to v # δ = v's last child, γ = other child or v's parent other than u labs = [edgerelation(e, v, uv) for e in v.edge] if v.hybrid # then v must have another parent edge, other than uv vγ = v.edge[findfirst(isequal(:parent), labs)] # γ = getparent(vδ) ?this should be vγ right? #on net_hybridladder edge 1 get ERROR: ArgumentError: invalid index: nothing of type Nothing vδ = v.edge[findfirst(isequal(:child), labs)] γ = getparent(vγ) δ = getchild(vδ) else ci = findall(isequal(:child), labs) length(ci) == 2 || error("node $(v.number) should have 2 children") vγ = v.edge[ci[1]] # γ = getchild(vγ) vδ = v.edge[ci[2]] γ = getchild(vγ) δ = getchild(vδ) end ## TASK 2: semi-directed network swaps: ## swap u <-> v, α <-> β if undirected and according to move number if !u.hybrid && uv.containRoot # case BB or BR, with uv that may contain the root nmoves = 0x03 # number of moves in the rooted (directed) case if !v.hybrid # BB, uv and all adjacent edges are undirected: 8 moves if nummove > 0x04 # switch u & v with prob 1/2 nummove -= 0x04 # now in 1,2,3,4 (u,v) = (v,u) (α,αu,β,βu,γ,vγ,δ,vδ) = (γ,vγ,δ,vδ,α,αu,β,βu) end nmoves = 0x02 end # now nmoves should be in 1, ..., 2*nmoves: 1:4 (BB) or 1:6 (BR) #? should this be 2*nummoves? # next: switch α & β with probability 1/2 if nummove > nmoves nummove -= nmoves # now nummoves in 1,2 (BB) or 1,2,3 (BR) (α,αu,β,βu) = (β,βu,α,αu) end end ## TASK 3: rooted network swaps, then do the NNI if u.hybrid # RR or RB cases # swap α & β: reduce NNIs from 2 to 1 (RR) or from 4 to 2 (RB) if nummove == 0x02 || nummove == 0x04 (α,αu,β,βu) = (β,βu,α,αu) end if !v.hybrid && nummove > 0x02 # case RB, moves 3 or 4 (γ,vγ,vδ,δ) = (δ,vδ,vγ,γ) end # detach β and graft onto vδ if no3cycle # don't create a 3-cycle if problem4cycle(α,γ, β,δ) return nothing; end else # don't create a 2-cycle if α === γ || β === δ return nothing; end end res = nni!(αu, u, uv, v, vδ) else # u = bifurcation: BB or BR cases if !v.hybrid # case BB: 2 options if nummove == 0x02 (γ,vγ,vδ,δ) = (δ,vδ,vγ,γ) end # detach β and graft onto vδ if no3cycle if problem4cycle(α,γ, β,δ) return nothing; end elseif α === γ || β === δ return nothing end res = nni!(αu, u, uv, v, vδ) else # case BR: 3 options # DAG check # if α parent of u, check if β -> γ (directed or undirected) # if undirected with β parent of u, check α -> γ # if undirected and u = root: # moves 1 and 3 will fail if α -> γ # moves 2 and 3 will fail if β -> γ # nummove 3 always creates a nonDAG when u is the root αparentu = getchild(αu)===u βparentu = getchild(βu)===u if αparentu if γ === β || isdescendant(γ, β) return nothing; end elseif βparentu if γ === α || isdescendant(γ, α) return nothing; end else # cases when u is root if nummove == 0x01 && (γ === α || isdescendant(γ, α)) return nothing elseif nummove == 0x02 && (γ === β || isdescendant(γ, β)) return nothing elseif nummove == 0x03 # fail: not DAG return nothing end end if nummove == 0x01 # graft γ onto α if no3cycle if problem4cycle(α,γ, β,δ) return nothing; end elseif α === γ || β === δ return nothing end if nohybridladder && α.hybrid return nothing; end res = nni!(vδ, v, uv, u, αu) elseif nummove == 0x02 # graft γ onto β if nohybridladder && β.hybrid return nothing; end if no3cycle if problem4cycle(β,γ, α,δ) return nothing; end elseif β === γ || α === δ return nothing end res = nni!(vδ, v, uv, u, βu) else # nummove == 0x03 if αparentu # if α->u: graft δ onto α if no3cycle if problem4cycle(α,δ, β,γ) return nothing; end elseif β === γ || α === δ return nothing end if nohybridladder && α.hybrid return nothing; end res = nni!(vγ, v, uv, u, αu) else # if β->u: graft δ onto β if no3cycle if problem4cycle(α,γ, β,δ) return nothing; end elseif α === γ || β === δ return nothing end # we could check nohybridladder && β.hybrid but no need because # we only get here if uv.containRoot so β cannot be hybrid res = nni!(vγ, v, uv, u, βu) # case when u is root already excluded (not DAG) end end end end return res end """ nni!(αu, u, uv::Edge, v, vδ) nni!(αu,u,uv,v,vδ, flip::Bool, inner::Bool, indices) Transform a network locally around the focus edge `uv` with the following NNI, that detaches u-β and grafts it onto vδ: α - u -- v ------ δ | | β γ α ------ v -- u - δ | | γ β `flip` boolean indicates if the uv edge was flipped `inner` boolean indicates if edges αu and uv both point toward node u, i.e. α->u<-v<-δ. If this is true, we flip the hybrid status of αu and vδ. `indices` give indices for nodes and edges u_in_αu, αu_in_u, vδ_in_v, and v_in_vδ. These are interpreted as: u_in_αu: the index for u in the edge αu αu_in_u: the index for αu in node u vδ_in_v: the index for vδ in node v v_in_vδ: the index for v in edge vδ **Warnings**: - *No* check of assumed adjacencies - Not implemented for cases that are not necessary thanks to symmetry, such as cases covered by `nni!(vδ, v, uv, u, αu)` or `nni!(βu, u, v, vγ)`. More specifically, these cases are not implemented (and not checked): * u not hybrid & v hybrid * u hybrid, v not hybrid, α -> u <- v -> δ - Because of this, `nni(αu,u,uv,v,vδ, ...)` should not be used directly; use instead `nni!(net, uv, move_number)`. - nni!(undoinfo...) restores the topology, but edges below hybrid nodes will have length 0.0 even if they didn't before. Node numbers and edge numbers are not modified. Edge `uv` keeps its direction unchanged *unless* the directions were `α -> u -> v -> δ` or `α <- u <- v <- δ`, in which case the direction of `uv` is flipped. The second version's input has the same signature as the output, but will undo the NNI more easily. This means that if `output = nni!(input)`, then `nni!(output...)` is valid and undoes the first operation. Right now, branch lengths are not modified except when below a hybrid node. Future versions might implement options to modify branch lengths. """ function nni!(αu::Edge, u::Node, uv::Edge, v::Node, vδ::Edge) # find indices to detach αu from u, and to detach v from vδ u_in_αu = findfirst(n->n===u, αu.node) αu_in_u = findfirst(e->e===αu, u.edge) vδ_in_v = findfirst(e->e===vδ, v.edge) v_in_vδ = findfirst(n->n===v, vδ.node) # none of them should be 'nothing' --not checked αu_child = getchild(αu) uv_child = getchild(uv) vδ_child = getchild(vδ) # flip the direction of uv if α->u->v->δ or α<-u<-v<-δ flip = (αu_child === u && uv_child === v && vδ_child !== v) || (αu_child !== u && uv_child === u && vδ_child === v) inner = (flip ? false : αu_child === u && vδ_child === v ) # fixit: calculate new edge lengths here; give them as extra arguments to nni! below res = nni!(αu,u,uv,v,vδ, flip,inner, u_in_αu,αu_in_u,vδ_in_v,v_in_vδ) return res end function nni!(αu::Edge, u::Node, uv::Edge, v::Node, vδ::Edge, flip::Bool, inner::Bool, u_in_αu::Int, αu_in_u::Int, vδ_in_v::Int, v_in_vδ::Int) # extra arguments: new edge lengths # fixit: extract old edge lengths; update to new lengths; return old lengths as extra items ## TASK 1: do the NNI swap: to detach & re-attach at once (αu.node[u_in_αu], u.edge[αu_in_u], v.edge[vδ_in_v], vδ.node[v_in_vδ]) = (v, vδ, αu, u) ## TASK 2: update edges' directions if flip uv.isChild1 = !uv.isChild1 end ## TASK 3: update hybrid status of nodes (#? is it ever nodes?) # & edges, and edges containRoot field if u.hybrid && !v.hybrid if flip # RB, BR 1 or BR 2': flip hybrid status of uv and (αu or vδ) if uv.hybrid # BR 1 or BR 2' vδ.hybrid = true vδ.gamma = uv.gamma vδ.isMajor = uv.isMajor # length switches: for keeping the network unzipped. could be option later αu.length = uv.length uv.length = 0.0 uv.hybrid = false uv.gamma = 1.0 uv.isMajor = true norootbelow!(uv) else # RB uv.hybrid = true uv.gamma = αu.gamma uv.isMajor = αu.isMajor # length switches: for keeping the network unzipped. could be option later uv.length = vδ.length vδ.length = 0.0 αu.hybrid = false αu.gamma = 1.0 αu.isMajor = true if αu.containRoot allowrootbelow!(v, αu) end end else # assumes α<-u or v<-δ --- but not checked # not implemented: α->u<-v->δ: do uv.hybrid=false and γv.hybrid=true if inner # BR 3 or 4': α->u<-v<-δ: flip hybrid status of αu and vδ # no lengths to switch in these cases vδ.hybrid = true vδ.gamma = αu.gamma vδ.isMajor = αu.isMajor αu.hybrid = false αu.gamma = 1.0 αu.isMajor = true # containRoot: nothing to update else # BR 1' or 2: α<-u<-v->δ : hybrid status just fine # length switches: for keeping the network unzipped. could be option later αu.length = vδ.length vδ.length = 0.0 norootbelow!(vδ) if uv.containRoot allowrootbelow!(αu) end end end elseif u.hybrid && v.hybrid # RR: hybrid edges remain hybrids, but switch γs # we could have -αu-> -uv-> -vδ-> or <-αu- <-uv- <-vδ- hyb = ( getchild(αu) == v ? αu : vδ ) # uv's hybrid parent edge: either αu or vδ (uv.gamma, hyb.gamma) = (hyb.gamma, uv.gamma) (uv.isMajor, hyb.isMajor) = (hyb.isMajor, uv.isMajor) end # throw error if u not hybrid & v hybrid? (does not need to be implemented) return vδ, u, uv, v, αu, flip, inner, v_in_vδ, αu_in_u, vδ_in_v, u_in_αu end """ problem4cycle(β::Node, δ::Node, α::Node, γ::Node) Check if the focus edge uv has a 4 cycle that could lead to a 3 cycle after an chosen NNI. Return true if there is a problem 4 cycle, false if none. """ function problem4cycle(β::Node, δ::Node, α::Node, γ::Node) isconnected(β, δ) || isconnected(α, γ) end """ checkspeciesnetwork!(network::HybridNetwork, constraints::Vector{TopologyConstraint}) Check that the network satisfies a number of requirements: - no polytomies, other than at species constraints: throws an error otherwise - no unnecessary nodes: fuse edges at nodes with degree two, including at the root (hence the bang: `net` may be modified) - topology constraints are met. Output: true if all is good, false if one or more clades are violated. """ function checkspeciesnetwork!(net::HybridNetwork, constraints::Vector{TopologyConstraint}) for n in net.node # check for no polytomies: all nodes should have up to 3 edges if length(n.edge) > 3 # polytomies allowed at species constraints only coni = findfirst(c -> c.type == 1 && c.node === n, constraints) coni !== nothing || error("The network has a polytomy at node number $(n.number). Please resolve.") end end removedegree2nodes!(net) return !constraintviolated(net, constraints) end """ mapindividuals(net::HybridNetwork, mappingFile::String) Return a network expanded from `net`, where species listed in the mapping file are replaced by individuals mapped to that species. If a species has only 1 individual, the name of the leaf for that species is replaced by the name of its one individual representative. If a species has 2 or more individuals, the leaf for that species is expanded into a "star" (polytomy if 3 or more individuals) with a tip for each individual. If a species is in the network but not listed in the mapping file, the tip for that species is left as is. Species listed in the mapping file but not present in the network are ignored. The mapping file should be readable by `CSV.File` and contain two columns: one for the species names and one for the individual (or allele) names. fixit: make this function more flexible by accepting column names Output: individual-level network and vector of species constraint(s). # examples ```jldoctest julia> species_net = readTopology("(((S8,S9),((((S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));"); julia> filename = joinpath(dirname(Base.find_package("PhyloNetworks")), "..", "examples", "mappingIndividuals.csv"); julia> filename |> read |> String |> print # to see what the mapping file contains species,individual S1,S1A S1,S1B S1,S1C julia> individual_net, species_constraints = PhyloNetworks.mapindividuals(species_net, filename); julia> writeTopology(individual_net, internallabel=true) "(((S8,S9),(((((S1A,S1B,S1C)S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" julia> species_constraints 1-element Vector{PhyloNetworks.TopologyConstraint}: Species constraint, on tips: S1A, S1B, S1C stem edge number 4 crown node number 3 ``` """ function mapindividuals(net::HybridNetwork, mappingFile::String) mappingDF = DataFrame(CSV.File(mappingFile); copycols=false) specieslist = unique(mappingDF[:, 1]) individualnet = deepcopy(net) constraints = TopologyConstraint[] for species in specieslist individuals = mappingDF[mappingDF.species .== species, 2] res = addindividuals!(individualnet, species, individuals) res === nothing || # nothing if species not found in the network, or 0,1 individuals push!(constraints, res) end return individualnet, constraints end """ addindividuals!(net::HybridNetwork, species::AbstractString, individuals::Vector) Add individuals to their species leaf as a star, and return the corresponding species constraint. `nothing` is returned in 2 cases: - if `individuals` contains only 1 individual, in which case the name of the leaf for that species is replaced by the name of its one individual representative - if `species` is not found in the network Spaces in individuals' names are eliminated, see [`cleantaxonname`](@ref). Called by [`mapindividuals`](@ref). # examples ```jldoctest julia> net = readTopology("(S8,(((S1,S4),(S5)#H1),(#H1,S6)));"); julia> PhyloNetworks.addindividuals!(net, "S1", ["S1A", "S1B", "S1C"]) Species constraint, on tips: S1A, S1B, S1C stem edge number 2 crown node number 2 julia> writeTopology(net) # 3 new nodes, S1 now internal: not a tip "(S8,((((S1A,S1B,S1C)S1,S4),(S5)#H1),(#H1,S6)));" ``` """ function addindividuals!(net::HybridNetwork, species::AbstractString, individuals::Vector{<:AbstractString}) length(individuals) > 0 || return nothing species = strip(species) speciesnodeindex = findfirst(l -> l.name == species, net.node) if speciesnodeindex === nothing @warn "species $species not found in network (typo in mapping file?). will be ignored." return nothing end if length(individuals) == 1 # change species name into name of individual representative net.node[speciesnodeindex].name = cleantaxonname(individuals[1]) return nothing end # there are 2+ individuals: replace the species tip by a star, will need a species constraint taxnames = map(cleantaxonname, individuals) for tax in taxnames addleaf!(net, net.node[speciesnodeindex], tax); end return TopologyConstraint(0x01, taxnames, net) end """ cleantaxonname(taxonname::AbstractString) Return a String with leading and trailing spaces removed, and interior spaces replaced by underscores: good for using as tip names in a network without causing future error when reading the newick description of the network. """ function cleantaxonname(taxonname::AbstractString) tname = String(strip(taxonname)) # SubString if we don't do string() m = match(r"\s", tname) if m !== nothing @warn """Spaces in "$tname" may cause errors in future network readability: replaced by _""" tname = replace(tname, r"\s+" => "_") end return tname end """ moveroot!(net::HybridNetwork, constraints=TopologyConstraint[]::Vector{TopologyConstraint}) Move the root to a randomly chosen non-leaf node that is different from the current root, and not within a constraint clade or species. Output: `true` if successul, `nothing` otherwise. """ function moveroot!(net::HybridNetwork, constraints=TopologyConstraint[]::Vector{TopologyConstraint}) newrootrandomorder = Random.shuffle(1:length(net.node)) oldroot = net.root for newrooti in newrootrandomorder newrooti != oldroot || continue newrootnode = net.node[newrooti] isleaf(newrootnode) && continue # try next potential new root if current is a leaf # Check the new root is NOT at the top or inside contraint clade or within pecies newrootfound = true for con in constraints if con.node === newrootnode || isdescendant(newrootnode, con.node) # assumes the constraint is met newrootfound = false break # out of constraint loop end end newrootfound || continue # to next potential new root # Check for no directional conflict try net.root = newrooti directEdges!(net) # warning: assumes that the previous root has degree 3 # otherwise, need to delete previous root by fusing its 2 adjacent edges catch e # RootMismatch error if root placement is below a hybrid isa(e, RootMismatch) || rethrow(e) net.root = oldroot directEdges!(net) # revert edges' directions to match original rooting continue # to next potential new root end # if we get here: newrooti passed all the checks return true end # if we get here: none of the root positions worked return nothing end """ fliphybrid!(net::HybridNetwork, minor=true::Bool, nohybridladder=false::Bool, constraints=TopologyConstraint[]::Vector{TopologyConstraint}) Cycle through hybrid nodes in random order until an admissible flip is found. At this hybrid node, flip the indicated hybrid parent edge (minor or major). If an admissible flip is found, return the tuple: newhybridnode, flippededge, oldchildedge. Otherwise, return nothing. The flip can be undone with `fliphybrid!(net, newhybridnode, minor, constraints)`, or `fliphybrid!(net, newhybridnode, !flippededge.isMajor, constraints)` more generally, such as if the flipped edge had its γ modified after the original flip. *Warnings* - if the root needed to be reset and if the original root was of degree 2, then a node of degree 2 remains in the modified network. - undoing the flip may not recover the original root in case the root position was modified during the original flip. """ function fliphybrid!(net::HybridNetwork, minor=true::Bool, nohybridladder=false::Bool, constraints=TopologyConstraint[]::Vector{TopologyConstraint}) hybridindex = Random.shuffle(1:length(net.hybrid)) # indices in net.hybrid while !isempty(hybridindex) # all minor edges i = pop!(hybridindex) undoinfo = fliphybrid!(net, net.hybrid[i], minor, nohybridladder, constraints) if !isnothing(undoinfo) # if it failed, the network was not changed return undoinfo end # else, continue until explored all i in hybridindex end return nothing end """ fliphybrid!(net::HybridNetwork, hybridnode::Node, minor=true::Bool, nohybridladder=false::Bool, constraints=TopologyConstraint[]::Vector{TopologyConstraint}) Flip the direction of a single hybrid edge: the minor parent edge of `hybridnode` by default, or the major parent edge if `minor` is false. The parent node of the hybrid edge becomes the new hybrid node. The former hybrid edge partner is converted to a tree edge (with γ=1), and `hybridnode` becomes a tree node. For the flip to be admissible, the new network must be a semi-directed phylogenetic network: with a root such that the rooted version is a DAG. If `nohybridladder` is false (default), the flip may create a hybrid ladder If `nohybridladder` is true and if the flip would create a hybrid ladder, then the flip is not admissible. A hybrid ladder is when a hybrid child of another hybrid. The new hybrid partner is an edge adjacent to the new hybrid node, such that the flip is admissible (so it must be a tree edge). The flipped edge retains its original γ. The new hybrid edge is assigned inheritance 1-γ. Output: `(newhybridnode, flippededge, oldchildedge)` if the flip is admissible, `nothing` otherwise. The network is unchanged if the flip is not admissible. If the flip is admissible, the root position may be modified, and the direction of tree edges (via `isChild1`) is modified accordingly. If the root needs to be modified, then the new root is set to the old hybrid node. The index of the new hybrid node in `net.hybrid` is equal to that of the old `hybridnode`. Warning: Undoing this move may not recover the original root if the root position was modified. """ function fliphybrid!(net::HybridNetwork, hybridnode::Node, minor=true::Bool, nohybridladder=false::Bool, constraints=TopologyConstraint[]::Vector{TopologyConstraint}) #= for species constraints, there is nothing to check, because hybrids cannot point into or come out of the group for con in constraints if con.type == # 0x02/0x03 for types 2 and 3, need to consider more cases return nothing end end =# runDirectEdges = false edgetoflip, edgetokeep = minor ? (getparentedgeminor(hybridnode), getparentedge(hybridnode)) : (getparentedge(hybridnode), getparentedgeminor(hybridnode)) oldchildedge = getchildedge(hybridnode) newhybridnode = getparent(edgetoflip) if newhybridnode.hybrid # already has 2 parents: cannot had a third. return nothing end ## choose newhybridedge ## p2 = getparent(edgetokeep) # parent node isdesc = Bool[] for e in newhybridnode.edge # is p2 undirected descendant of nhn via this edge? isp2desc = false #= isp2desc = true means: there is a semi-directed path newhybridnode -e-> neighbor --...-> p2 so: flipping hybridedge without making e the new partner would: - make e a child of newhybridnode, and - create a directed cycle: p2 -hybridedge-> newhybridnode -e-> neibr --...-> p2 so we HAVE to make e the new partner hybrid edge if its "isp2desc" is true =# if e !== edgetoflip # e cannot be hybrid --e-> nhn because earlier check neibr = getOtherNode(e, newhybridnode) # neighbor of new hybrid node via e if !isleaf(neibr) && (p2 === neibr || isdescendant_undirected(p2, neibr, e)) isp2desc = true end end push!(isdesc, isp2desc) end sum_isdesc = sum(isdesc) if sum_isdesc > 1 # if 2+ edges have a semi-directed path to p2, # flipping either would create a semi-directed cycle via the other(s) return nothing end if sum_isdesc == 0 # no risk to create directed cycle. # choose the current parent edge of nhn to: keep its current direction # and keep reaching all nodes from a single root newhybridedge = getparentedge(newhybridnode) else newhybridedge = newhybridnode.edge[findfirst(isdesc)] if newhybridedge.hybrid # cannot flip another hybrid edge, but we needed return nothing # to calculate its isp2desc for total # of true's end end # @debug "edgetoflip is $edgetoflip, edgetokeep is $edgetokeep, newhybridedge is $newhybridedge" if nohybridladder # case when edgetoflip would be bottom rung of ladder if getOtherNode(newhybridedge, newhybridnode).hybrid return nothing end # case when edgetoflip would be the top rung: happens when # newhybridnode = center point of a W structure initially for e in newhybridnode.edge if e !== edgetoflip && e.hybrid # newhybridedge is NOT hybrid, so far return nothing end end end # change hybrid status and major status for nodes and edges hybridnode.hybrid = false edgetokeep.hybrid = false newhybridnode.hybrid = true newhybridedge.hybrid = true newhybridedge.isMajor = minor edgetokeep.isMajor = true # update node order to keep isChild1 attribute of hybrid edges true edgetoflip.isChild1 = !edgetoflip.isChild1 # just switch if getchild(newhybridedge) !== newhybridnode # includes the case when the newhybridnode was the root # then flip newhybridedge too: make it point towards newhybridnode newhybridedge.isChild1 = !newhybridedge.isChild1 net.root = findfirst(n -> n === hybridnode, net.node) runDirectEdges = true # many edges are likely to need to have directions flipped here end # give new hybridnode a name newhybridnode.name = hybridnode.name hybridnode.name = "" # remove name from former hybrid node # update gammas newhybridedge.gamma = edgetokeep.gamma edgetokeep.gamma = 1.0 # update hybrids in network (before directEdges!) hybridindex = findfirst(n -> n === hybridnode, net.hybrid) net.hybrid[hybridindex] = newhybridnode if runDirectEdges # direct edges only if root is moved directEdges!(net) else # if not, only update containRoot attributes # norootbelow in child edges of newhybridedge for ce in newhybridnode.edge ce !== newhybridedge || continue # skip e getparent(ce) === newhybridnode || continue # skip edges that aren't children of cn norootbelow!(ce) end # allow root for edges below old hybrid node if edgetokeep.containRoot #else, already forbidden below due to hybrid above allowrootbelow!(hybridnode, edgetokeep) # old hybrid node end end return newhybridnode, edgetoflip, oldchildedge end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
66204
# functions for moves: change direction, move origin, move target, nni # originally functions.jl # Claudia March 2015 # fixit: in moveOrigin/moveTarget when updating partitions with # splice, looking for same partition twice (before and after splice), # maybe there is a more efficient way to handle this # -------------------------- change direction of minor hybrid edge --------------------------------- # aux function to transform tree edge into hybrid edge # input: new edge, hybrid node (needs to be attached to new edge) # new gamma # swtichHyb=true if called in hybridatnode function makeEdgeHybrid!(edge::Edge,node::Node,gamma::Float64; switchHyb=false::Bool) !edge.hybrid || error("edge $(edge.number) already hybrid, cannot make it hybrid") node.hybrid || error("to make edge $(edge.number) hybrid, you need to give the hybrid node it is going to point to and node $(node.number) is not hybrid") #println("estamos en make edge hybrid en edge $(edge.number) y node $(node.number)") #println("vamos a hacer hashybedge true para $(getOtherNode(edge,node).number)") #println("$(getOtherNode(edge,node).hasHybEdge) debe ser true") size(edge.node,1) == 2 || error("strange edge $(edge.number) has $(size(edge.node,1)) nodes instead of 2") if(isEqual(edge.node[1],node)) edge.isChild1 = true elseif(isEqual(edge.node[2],node)) edge.isChild1 = false else error("node $(node.number) is not attached to edge $(edge.number)") end edge.hybrid = true getOtherNode(edge,node).hasHybEdge = true if switchHyb edge.gamma = gamma; edge.isMajor = (gamma>=0.5) ? true : false else setGamma!(edge,gamma,false) end edge.istIdentifiable = isEdgeIdentifiable(edge) edge.containRoot = false end # aux function to exchange who is the hybrid node # input: current hybrid, new hybrid # returns false if there is no need to updategammaz after # true if there is need to updategammaz after function exchangeHybridNode!(net::HybridNetwork, current::Node,new::Node) (current.hybrid && !new.hybrid) || error("either current node $(current.number) is not hybrid: current.hybrid $(current.hybrid) or new node $(new.number) is already hybrid: new.hybrid $(new.hybrid)") #println("find cycle for current node $(current.number)") nocycle,edgesInCycle,nodesInCycle = identifyInCycle(net,current) !nocycle || error("strange here: change direction on hybrid node $(current.number) that does not have a cycle to begin with") #println("edges in cycle for node $(current.number) are $([e.number for e in edgesInCycle]) and nodes in cycle $([n.number for n in nodesInCycle])") for e in edgesInCycle e.inCycle = new.number end for n in nodesInCycle n.inCycle = new.number end update = true new.hybrid = true new.k = current.k removeHybrid!(net,current) pushHybrid!(net,new) current.hybrid = false current.k = -1 if(current.isBadDiamondI || current.isBadDiamondII) current.isBadDiamondI = false current.isBadDiamondII = false update = false elseif(current.isBadTriangle) current.isBadTriangle = false update = true end return update end # function to change the direction of a hybrid edge # input: hybrid node, network, isminor=true: changes dir of minor edge # warning: it assumes that undoGammaz has been run before # and that the new hybridization has been # approved by the containRoot criterion # warning: it needs incycle attributes # returns flag of whether it needs update gammaz, and alreadyNoRoot = !edgemin2.containRoot function changeDirection!(node::Node, net::HybridNetwork, isminor::Bool) node.hybrid || error("node $(node.number) is not hybrid, so we cannot change the direction of the hybrid edge") major,minor,tree = hybridEdges(node); othermin = getOtherNode(minor,node); othermaj = getOtherNode(major,node); othertree = getOtherNode(tree,node); if(isminor) edgebla,edgemin1,edgemin2 = hybridEdges(othermin); nodemin1 = getOtherNode(edgemin1,othermin) nodemin2 = getOtherNode(edgemin2,othermin) removeEdge!(nodemin1,edgemin1) removeEdge!(nodemin2,edgemin2) removeEdge!(othermaj,major) removeEdge!(othertree,tree) removeNode!(nodemin1,edgemin1) removeNode!(nodemin2,edgemin2) removeNode!(othermaj,major) removeNode!(othertree,tree) setNode!(edgemin1,othermaj) setNode!(major,nodemin1) setNode!(edgemin2,othertree) setNode!(tree,nodemin2) setEdge!(othermaj,edgemin1) setEdge!(nodemin1,major) setEdge!(othertree,edgemin2) setEdge!(nodemin2,tree) tmajor = major.length ttree = tree.length tedmin1 = edgemin1.length tedmin2 = edgemin2.length setLength!(major,tedmin1) setLength!(tree,tedmin2) setLength!(edgemin1,tmajor) setLength!(edgemin2,ttree) # -- update partition indexPedgemin = whichPartition(net,edgemin2,node.number) indexPtree = whichPartition(net,tree,node.number) ind = getIndex(edgemin2,net.partition[indexPedgemin].edges) deleteat!(net.partition[indexPedgemin].edges,ind) ind = getIndex(tree,net.partition[indexPtree].edges) deleteat!(net.partition[indexPtree].edges,ind) push!(net.partition[indexPtree].edges,edgemin2) push!(net.partition[indexPedgemin].edges,tree) # -- @debug "edgemin2 is $(edgemin2.number) and its containRoot is $(edgemin2.containRoot)" alreadyNoRoot = !edgemin2.containRoot @debug "edgemin2 is $(edgemin2.number) and its containRoot is $(edgemin2.containRoot), alreadyNoRoot $(alreadyNoRoot)" else edgebla,edgemaj1,edgemaj2 = hybridEdges(othermaj); nodemaj1 = getOtherNode(edgemaj1,othermaj) nodemaj2 = getOtherNode(edgemaj2,othermaj) removeEdge!(nodemaj1,edgemaj1) removeEdge!(nodemaj2,edgemaj2) removeEdge!(othermin,minor) removeEdge!(othertree,tree) removeNode!(nodemaj1,edgemaj1) removeNode!(nodemaj2,edgemaj2) removeNode!(othermin,minor) removeNode!(othertree,tree) setNode!(edgemaj1,othermin) setNode!(minor,nodemaj1) setNode!(edgemaj2,othertree) setNode!(tree,nodemaj2) setEdge!(othermin,edgemaj1) setEdge!(nodemaj1,minor) setEdge!(othertree,edgemaj2) setEdge!(nodemaj2,tree) tminor = minor.length ttree = tree.length tedmaj1 = edgemaj1.length tedmaj2 = edgemaj2.length setLength!(minor,tedmaj1) setLength!(tree,tedmaj2) setLength!(edgemaj1,tminor) setLength!(edgemaj2,ttree) # -- update partition indexPedgemaj = whichPartition(net,edgemaj2,node.number) indexPtree = whichPartition(net,tree,node.number) ind = getIndex(edgemaj2,net.partition[indexPedgemaj].edges) deleteat!(net.partition[indexPedgemaj].edges,ind) ind = getIndex(tree,net.partition[indexPtree].edges) deleteat!(net.partition[indexPtree].edges,ind) push!(net.partition[indexPtree].edges,edgemaj2) push!(net.partition[indexPedgemaj].edges,tree) # -- @debug "edgemaj2 is $(edgemaj2.number) and its containRoot is $(edgemaj2.containRoot)" alreadyNoRoot = !edgemaj2.containRoot @debug "edgemaj2 is $(edgemaj2.number) and its containRoot is $(edgemaj2.containRoot), alreadyNoRoot $(alreadyNoRoot)" end if(node.isBadDiamondI || node.isBadDiamondII) node.isBadDiamondI = false node.isBadDiamondII = false return false, alreadyNoRoot elseif(node.isBadTriangle) return false, alreadyNoRoot end return true, alreadyNoRoot end changeDirection!(node::Node, net::HybridNetwork) = changeDirection!(node, net, true) # function to change the direction of the minor hybrid edge # and update necessary stepts before and after # input: hybrid node and network, random=false, changes dir of minor edge always # returns success # if success=false, it undoes the change direction function changeDirectionUpdate!(net::HybridNetwork,node::Node, random::Bool) global CHECKNET node.hybrid || error("cannot change the direction of minor hybrid edge since node $(node.number) is not hybrid") undoGammaz!(node,net) edgesRoot = identifyContainRoot(net,node); #undoContainRoot!(edgesRoot); now inside updateContainRootChangeDir if(random) edges = hybridEdges(node) edges[1].hybrid || error("hybrid node $(node.number) has as major edge a tree edge $(edges[1].number)") edges[1].gamma >= 0.5 || error("major hybrid edge $(edges[1].number) has gamma less than 0.5: $(edges[1].gamma)") minor = rand() < edges[1].gamma else minor = true end @debug "MOVE: change direction around hybrid node $(node.number) for minor $(minor)------- " update, alreadyNoRoot = changeDirection!(node,net,minor) if(node.k == 4 && update) flag2, edgesgammaz = updateGammaz!(net,node) else flag2 = true end if(flag2) # flag3,edgesroot = updateContainRoot!(net,node); now in updateContainRootChangeDir flag3,edgesroot = updateContainRootChangeDir!(net,node,edgesRoot, alreadyNoRoot) if(flag3) parameters!(net); @debug "MOVE: change direction around hybrid node $(node.number) SUCCESSFUL" return true else @debug "MOVE: change direction around hybrid node $(node.number) FAILED because of containRoot" CHECKNET && checkNet(net) node.isBadDiamondI || undoGammaz!(node,net) alreadyNoRoot || undoContainRoot!(edgesroot) #only undo edgesroot if there were changed: alreadyNoRoot=true => no change update,a = changeDirection!(node,net,minor); alreadyNoRoot == a || error("change direction alreadyNoRoot should match when done the first time and when undoing") if(node.k == 4 && update) flag2, edgesgammaz = updateGammaz!(net,node) else flag2 = true end flag2 || error("when undoing change direction, we should be able to update gammaz again") alreadyNoRoot || undoContainRoot!(edgesRoot,false); CHECKNET && checkNet(net) return false end else @debug "MOVE: change direction around hybrid node $(node.number) FAILED because of gammaz" CHECKNET && checkNet(net) node.isBadDiamondI || undoGammaz!(node,net) update,a = changeDirection!(node,net,minor); if(node.k == 4 && update) flag2, edgesgammaz = updateGammaz!(net,node) else flag2 = true end flag2 || error("when undoing change direction, we should be able to update gammaz again") #undoContainRoot!(edgesRoot,false); #redo containRoot as before NO NEED ANYMORE CHECKNET && checkNet(net) return false end end changeDirectionUpdate!(net::HybridNetwork,node::Node) = changeDirectionUpdate!(net,node, false) # function that will take care of the case when one cycle is above another cycle # edgesRoot come from identifyContainRoot before changeDirection # this function should be run after changeDirection which gives alreadyNoRoot # returns flag2, edgesroot function updateContainRootChangeDir!(net::HybridNetwork,node::Node,edgesRoot::Vector{Edge}, alreadyNoRoot::Bool) node.hybrid || error("cannot update contain root on node $(node.number) because it is not hybrid") @debug "updating contain root for hybrid node $(node.number), with alreadyNoRoot $(alreadyNoRoot)" if(!alreadyNoRoot) #only update root if new descendats were not forbidden to carry root already undoContainRoot!(edgesRoot); flag3,edgesroot = updateContainRoot!(net,node); @debug "alreadyNoRoot is $(alreadyNoRoot), undoing containRoot for $([e.number for e in edgesRoot]), updating containRoot for $([e.number for e in edgesroot]), with flag3 $(flag3)" return flag3,edgesroot else flag3,edgesroot = updateContainRoot!(net,node); return flag3,edgesroot end end # ------------------------- move origin of hybrid edge --------------------------------- # function to choose an edge to move origin of hybrid # but for a nni-like move: only to neighbors # input: hybridnode for the move # will choose one of 4 neighbor edges at random and see if # it is suitable. if none is suitable, stops # vector a is the vector of possible edges: comes from getNeighborsOrigin/Target # returns: success (bool), edge, ind function chooseEdgeOriginTarget!(neighbor::Vector{Edge}, node::Node) length(neighbor) < 5 || error("neighbor should have at most 4 edges: $([n.number for n in neighbor])") while(!isempty(neighbor)) ind = rand(1:length(neighbor)) if(!neighbor[ind].hybrid && (neighbor[ind].inCycle == -1 || neighbor[ind].inCycle == node.number)) return true, neighbor[ind], ind else deleteat!(neighbor,ind) end end return false, nothing, nothing end # function to move the origin of a hybrid edge # warning: it does not do any update # input: necessary nodes/edges, see moveOriginUpdate and # ipad notes # warning: it changes the branch lengths of newedge, tree1, tree2 to match the # optimum branch lengths in the corresponding other edge (see ipad notes) # needed tree1 and tree2 as parameters because we need to do undogammaz before moveOrigin # returns flag=true if newedge was incycle before, to be able to undo if needed (newedgeincycle) function moveOrigin!(net::HybridNetwork,node::Node,othermin::Node,tree1::Edge, tree2::Edge,newedge::Edge, undo::Bool, newedgeincycle::Bool) node.hybrid || error("cannot move origin of hybridization because node $(node.number) is not hybrid") size(newedge.node,1) == 2 || error("strange edge $(newedge.number) that has $(size(newedge.node,1)) nodes instead of 2") in(newedge,net.edge) || error("newedge $(newedge.number) not in net.edge") @debug "othermin $(othermin.number) with edges $([e.number for e in othermin.edge])" @debug "tree1 is $(tree1.number), tree2 is $(tree2.number)" if(tree1.inCycle == node.number && tree2.inCycle == -1) treej = tree1 treei = tree2 elseif(tree2.inCycle == node.number && tree1.inCycle == -1) treej = tree2 treei = tree1 else error("tree1 edge $(tree1.number) and tree2 edge $(tree2.number) should be one in cycle and one not incycle") end @debug "MOVE: newedge is $(newedge.number)" @debug "treei is $(treei.number), treej is $(treej.number) (the one incycle)" otheri = getOtherNode(treei,othermin); otherj = getOtherNode(treej,othermin); @debug "otheri is $(otheri.number), otherj is $(otherj.number)" node1 = newedge.node[1]; # not waste of memory, needed step node2 = newedge.node[2]; @debug "node1 is $(node1.number), node2 is $(node2.number)" neighbor = false from_otheri = false from_otherj = false if(isEqual(otheri,node1)) n1 = node1 n2 = node2 neighbor = true from_otheri = true elseif(isEqual(otheri,node2)) n1 = node2 n2 = node1 neighbor = true from_otheri = true elseif(isEqual(otherj,node1)) n1 = node1 n2 = node2 neighbor = true from_otherj = true elseif(isEqual(otherj,node2)) n1 = node2 n2 = node1 neighbor = true from_otherj = true end @debug "neighbor $(neighbor), from otheri $(otheri.number) $(from_otheri), from otherj $(otherj.number) $(from_otherj), n1 $(n1.number), n2 $(n2.number)" if(neighbor && from_otheri) ## println("leaving n1 $(n1.number) as it is") ##println("removing n2 $(n2.number) from newedge $(newedge.number) and viceversa") removeEdge!(n2,newedge) removeNode!(n2,newedge) #println("removing otherj $(otherj.number) from treej $(treej.number) and viceversa") removeEdge!(otherj,treej) removeNode!(otherj,treej) #println("setting newedge $(newedge.number) to otherj $(otherj.number) and viceversa") setNode!(newedge,otherj) setEdge!(otherj,newedge) #println("setting treej edge $(treej.number) to n2 $(n2.number) and viceversa") setNode!(treej,n2) setEdge!(n2,treej) elseif(neighbor && from_otherj) #println("leaving n1 $(n1.number) as it is") #println("removing n2 $(n2.number) from newedge $(newedge.number) and viceversa") removeEdge!(n2,newedge) removeNode!(n2,newedge) #println("removing otheri $(otheri.number) from treei edge $(treei.number) and viceversa") removeEdge!(otheri,treei) removeNode!(otheri,treei) #println("setting newedge $(newedge.number) to otheri $(otheri.number) and viceversa") setNode!(newedge,otheri) setEdge!(otheri,newedge) #println("setting treei edge $(treei.number) to n2 $(n2.number) and viceversa") setNode!(treei,n2) setEdge!(n2,treei) else error("move origin to edge $(newedge.number) not neighbor to tree1 edge $(tree1.number) nor tree2 edge $(tree2.number), function not debugged!") other1 = getOtherNode(tree1,othermin); other2 = getOtherNode(tree2,othermin); removeEdge!(other1,tree1) removeNode!(other1,tree1) removeEdge!(node1,newedge) removeNode!(node1,newedge) setEdge!(other1,newedge) setNode!(newedge,other1) setEdge!(node1,tree1) setNode!(tree1,node1) removeEdge!(other2,tree2) removeNode!(other2,tree2) removeEdge!(node2,newedge) removeNode!(node2,newedge) setEdge!(other2,newedge) setNode!(newedge,other2) setEdge!(node2,tree2) setNode!(tree2,node2) end ti = treei.length tj = treej.length t = newedge.length setLength!(newedge,ti+tj) if(approxEq(ti,0.0) && approxEq(tj,0.0)) setLength!(treei,ti) setLength!(treej,tj) else setLength!(treei,(ti/(ti+tj))*t) setLength!(treej,(tj/(ti+tj))*t) end @debug begin printEdges(net); "printed edges" end @debug writeTopologyLevel1(net) if !undo if from_otheri # -- update partition indexPtreei = whichPartition(net,treei,node.number) ind = getIndex(newedge,net.partition[indexPtreei].edges) deleteat!(net.partition[indexPtreei].edges,ind) ind = getIndex(treei,net.partition[indexPtreei].edges) deleteat!(net.partition[indexPtreei].edges,ind) push!(net.partition[indexPtreei].edges,treej) edges = hybridEdges(otheri) for i in 1:3 #check of 3 edges inside hybridEdges if(!isEqual(edges[i],treei) && !isEqual(edges[i],newedge)) descendants = [edges[i]] cycleNum = [node.inCycle] getDescendants!(getOtherNode(edges[i],otheri),edges[i],descendants,cycleNum) !isempty(descendants) || error("descendants is empty for node $(otheri.number)") @debug "for node $(otheri.number), descendants are $([e.number for e in descendants]), and cycleNum is $(cycleNum)" partition = Partition(unique(cycleNum),descendants) # create new partition push!(net.partition, partition) for e in descendants #delete edges from partition with tree originally ind = getIndex(e,net.partition[indexPtreei].edges) deleteat!(net.partition[indexPtreei].edges,ind) end net.partition[indexPtreei].cycle = union([node.inCycle],symdiff(net.partition[indexPtreei].cycle,cycleNum)) break end end # -- update in cycle newedge.inCycle = node.number switchCycleTree!(tree1,tree2,node) node.k += 1 otheri.inCycle = node.number elseif(from_otherj) if(newedge.inCycle == node.number) # -- update partition indexPtreei = whichPartition(net,treei,node.number) push!(net.partition[indexPtreei].edges,treej) push!(net.partition[indexPtreei].edges,newedge) ind = getIndex(treei,net.partition[indexPtreei].edges) deleteat!(net.partition[indexPtreei].edges,ind) edges = hybridEdges(otherj) for i in 1:3 #check of 3 edges inside hybridEdges if(!isEqual(edges[i],treej) && !isEqual(edges[i],newedge)) indexP = whichPartition(net,edges[i],node.number) for e in net.partition[indexP].edges push!(net.partition[indexPtreei].edges,e) end net.partition[indexPtreei].cycle = union(net.partition[indexPtreei].cycle,net.partition[indexP].cycle) part = splice!(net.partition,indexP) #splice at the end to not change indexPtreei break end end # -- update in cycle newedge.inCycle = -1 switchCycleTree!(tree1,tree2,node) otherj.inCycle = -1 node.k -= 1 return true else # -- update partition indexPnew = whichPartition(net,newedge,node.number) indexPtreei = whichPartition(net,treei,node.number) ind = getIndex(newedge,net.partition[indexPnew].edges) deleteat!(net.partition[indexPnew].edges,ind) ind = getIndex(treei,net.partition[indexPtreei].edges) deleteat!(net.partition[indexPtreei].edges,ind) push!(net.partition[indexPnew].edges,treei) push!(net.partition[indexPtreei].edges,newedge) end end else #yes undo if(newedge.inCycle == node.number) # -- update partition indexPtreei = whichPartition(net,treei,node.number) push!(net.partition[indexPtreei].edges,treej) push!(net.partition[indexPtreei].edges,newedge) ind = getIndex(treei,net.partition[indexPtreei].edges) deleteat!(net.partition[indexPtreei].edges,ind) edges = hybridEdges(otherj) for i in 1:3 #check of 3 edges inside hybridEdges if(!isEqual(edges[i],treej) && !isEqual(edges[i],newedge)) indexP = whichPartition(net,edges[i],node.number) for e in net.partition[indexP].edges push!(net.partition[indexPtreei].edges,e) end net.partition[indexPtreei].cycle = union(net.partition[indexPtreei].cycle,net.partition[indexP].cycle) part = splice!(net.partition,indexP) #splice at the end break end end # -- update in cycle newedge.inCycle = -1 switchCycleTree!(tree1,tree2,node) node.k -= 1 otherj.inCycle = -1 elseif(newedge.inCycle == -1) if(newedgeincycle) # -- update partition indexPtreei = whichPartition(net,treei,node.number) ind = getIndex(newedge,net.partition[indexPtreei].edges) deleteat!(net.partition[indexPtreei].edges,ind) ind = getIndex(treei,net.partition[indexPtreei].edges) deleteat!(net.partition[indexPtreei].edges,ind) push!(net.partition[indexPtreei].edges,treej) edges = hybridEdges(otheri) for i in 1:3 #check of 3 edges inside hybridEdges if(!isEqual(edges[i],treei) && !isEqual(edges[i],newedge)) descendants = [edges[i]] cycleNum = [node.inCycle] getDescendants!(getOtherNode(edges[i],otheri),edges[i],descendants,cycleNum) !isempty(descendants) || error("descendants is empty for node $(otheri.number)") @debug "for node $(otheri.number), descendants are $([e.number for e in descendants]), and cycleNum is $(cycleNum)" partition = Partition(unique(cycleNum),descendants) # create new partition push!(net.partition, partition) for e in descendants #delete edges from partition with tree originally ind = getIndex(e,net.partition[indexPtreei].edges) deleteat!(net.partition[indexPtreei].edges,ind) end net.partition[indexPtreei].cycle = union([node.inCycle],symdiff(net.partition[indexPtreei].cycle,cycleNum)) break end end # -- update in cycle newedge.inCycle = node.number switchCycleTree!(tree1,tree2,node) otheri.inCycle = node.number node.k += 1 else # -- update partition indexPnew = whichPartition(net,newedge,node.number) indexPtreei = whichPartition(net,treei,node.number) ind = getIndex(newedge,net.partition[indexPnew].edges) deleteat!(net.partition[indexPnew].edges,ind) ind = getIndex(treei,net.partition[indexPtreei].edges) deleteat!(net.partition[indexPtreei].edges,ind) push!(net.partition[indexPnew].edges,treei) push!(net.partition[indexPtreei].edges,newedge) end end end return false end moveOrigin!(net::HybridNetwork,node::Node,othermin::Node,tree1::Edge, tree2::Edge,newedge::Edge) = moveOrigin!(net,node,othermin,tree1, tree2,newedge, false,false) # function to switch the cycle of 2 tree edges in moveTarget function switchCycleTree!(tree1::Edge, tree2::Edge, node::Node) (!tree1.hybrid && !tree2.hybrid) || error("tree1 edge $(tree1.number) and tree2 $(tree2.number) cannot be hybrid to switch incycle attribute") (tree1.inCycle == node.number && tree2.inCycle == -1) || (tree2.inCycle == node.number && tree1.inCycle == -1) || error("tree1 edge or tree2 edge must by in cycle by node $(node.number) and the other -1, but: $([tree1.inCycle, tree2.inCycle])") k = tree1.inCycle m = tree2.inCycle tree2.inCycle = k tree1.inCycle = m end # function to choose minor/major hybrid edge # to move the origin or target # random=false always chooses the minor edge # returns the othermin node and majoredge for target function chooseMinorMajor(node::Node, random::Bool, target::Bool) node.hybrid || error("node $(node.number) is not hybrid, so we cannot delete hybridization event around it") major,minor,tree = hybridEdges(node); #println("hybrid node $(node.number) has major $(major.number), minor $(minor.number) and tree $(tree.number)") if random r = rand() major.gamma >= 0.5 || error("strange major hybrid edge $(major.number) with gamma $(major.gamma) less than 0.5") @debug (major.gamma != 1.0 ? "" : "strange major hybrid edge $(major.number) with gamma $(major.gamma) equal to 1.0") othermin = r < major.gamma ? getOtherNode(minor,node) : getOtherNode(major,node) majoredge = r < major.gamma ? major : minor @debug (r < major.gamma ? "MOVE: will do move on minor hybrid edge" : "MOVE: will do move on major hybrid edge") else @debug "MOVE: will do move on minor hybrid edge" majoredge = major othermin = getOtherNode(minor,node); end if target return othermin, majoredge else return othermin end end chooseMinorMajor(node::Node, random::Bool) = chooseMinorMajor(node, random, false) # function to give the vector of edges neighbor # that includes all the suitable neighbors of othermin # to move the origin function getNeighborsOrigin(othernode::Node) othernode.hasHybEdge || error("other node $(othernode.number) should the attach to the hybrid edge whose origin will be moved") !othernode.hybrid || error("other node $(othernode.number) must not be the hybrid node to move origin") edges = hybridEdges(othernode) length(edges) == 3 || error("length of node.edge for node $(othernode.number) should be 3, not $(length(edges))") edges[1].hybrid || error("edge $(edges[1].number) should be hybrid because it is the one to move the origin from") neighbor = Edge[] n1 = getOtherNode(edges[2],othernode) n2 = getOtherNode(edges[3],othernode) if(!n1.leaf) e = hybridEdges(n1,edges[2]) length(e) == 2 || error("node $(n1.number) is not a leaf but has $(length(e)+1) edges") push!(neighbor, e[1]) push!(neighbor, e[2]) end if(!n2.leaf) e = hybridEdges(n2,edges[3]) length(e) == 2 || error("node $(n1.number) is not a leaf but has $(length(e)+1) edges") push!(neighbor, e[1]) push!(neighbor, e[2]) end return neighbor end # function to move the origin of a hybrid edge # and update everything that needs update: gammaz # input: network, hybrid node, othermin already chosen with chooseMinorMajor # returns: success (bool), flag, nocycle, flag2 function moveOriginUpdate!(net::HybridNetwork, node::Node, othermin::Node, newedge::Edge) global CHECKNET node.hybrid || error("node $(node.number) is not hybrid, so we cannot delete hybridization event around it") @debug "MOVE: move Origin for hybrid node $(node.number)" in(newedge,net.edge) || error("newedge $(newedge.number) not in net.edge") edgebla, tree1, tree2 = hybridEdges(othermin); undoGammaz!(node,net); #println("othermin is $(othermin.number)") newedgeincycle = moveOrigin!(net,node,othermin,tree1,tree2,newedge) flag2, edgesGammaz = updateGammaz!(net,node) if(flag2) parameters!(net); @debug "MOVE: move Origin for hybrid node $(node.number) SUCCESSFUL" return true,flag2 else @debug "MOVE: move Origin for hybrid node $(node.number) FAILED" CHECKNET && checkNet(net) isempty(edgesGammaz) || undoistIdentifiable!(edgesGammaz) undoGammaz!(node,net); @debug "MOVE: undoing move origin for conflict: gammaz" moveOrigin!(net,node,othermin,tree1,tree2,newedge,true,newedgeincycle); flag2, edgesGammaz = updateGammaz!(net,node) (flag2 || node.isVeryBadTriangle || node.isExtBadTriangle) || error("updating gammaz for undone moveOrigin, should not be any problem") CHECKNET && checkNet(net) return false, flag2 end end # function to repeat moveOriginUpdate with all the neighbors # until success or failure of all for a given hybrid node # returns success (bool): failure from: neighbors not suitable to begin # with, or conflicts incycle function moveOriginUpdateRepeat!(net::HybridNetwork, node::Node, random::Bool) node.hybrid || error("cannot move origin because node $(node.number) is not hybrid") othermin = chooseMinorMajor(node,random) #println("othermin is $(othermin.number) with edges $([e.number for e in othermin.edge])") neighbor = getNeighborsOrigin(othermin) #println("neighbors list is $([n.number for n in neighbor])") success = false while(!isempty(neighbor) && !success) success1,newedge,ind = chooseEdgeOriginTarget!(neighbor,node) !isa(newedge,Nothing) || return false success1 || return false #println("newedge is $(newedge.number), success1 is $(success1)") in(newedge,net.edge) || error("newedge $(newedge.number) is not in net.edge") success,flag2 = moveOriginUpdate!(net, node, othermin, newedge) #println("after update, success is $(success)") if(!success) @debug "move origin failed, will delete that neighbor and try new one" deleteat!(neighbor,ind) end #println("neighbor list is $([n.number for n in neighbor])") end success || return false return true end # ----------------- move target of hybridization ------------------------------- """ getNeighborsTarget(hybrid_node, majoredge) Vector of edges that are incident to either: - the node incident to `majoredge` other than `hybrid_node`, or - the tree child of `hybrid_node`. This vector of edges is used as the list of suitable neighbors of "othermin" to move the target of a hybrid edge, in `moveTargetUpdateRepeat!`. """ function getNeighborsTarget(node::Node,majoredge::Edge) node.hybrid || error("node $(node.number) must be the hybrid node to move target") major,minor,tree = hybridEdges(node) neighbor = Edge[] n1 = getOtherNode(majoredge,node) n2 = getOtherNode(tree,node) if(!n1.leaf) e = hybridEdges(n1,majoredge) length(e) == 2 || error("node $(n1.number) is not a leaf but has $(length(e)+1) edges") push!(neighbor, e[1]) push!(neighbor, e[2]) end if(!n2.leaf) e = hybridEdges(n2,tree) length(e) == 2 || error("node $(n1.number) is not a leaf but has $(length(e)+1) edges") push!(neighbor, e[1]) push!(neighbor, e[2]) end return neighbor end # function to switch major and tree node in moveTarget function switchMajorTree!(major::Edge, tree::Edge, node::Node) !tree.hybrid || error("tree edge $(tree.number) cannot be hybrid to switch to major") major.hybrid || error("major edge $(major.number) has to be hybrid to switch to tree") @debug "switch major $(major.number) tree $(tree.number), node $(node.number)" g = major.gamma #needed because changed inside makeEdgeTree cycle = major.inCycle #needed because changed inside makeEdgeTree makeEdgeTree!(major,node) makeEdgeHybrid!(tree,node,g) tree.inCycle = cycle major.inCycle = -1 end # function to move the target of a hybrid edge # warning: it does not do any update # input: necessary nodes/edges, see moveOriginUpdate and # ipad notes, undo=true if it is undoing a previous moveTarget # warning: it changes the branch lengths of newedge, tree1, tree2 to match the # optimum branch lengths in the corresponding other edge (see ipad notes) # returns flag=true if newedge was incycle before, to be able to undo if needed (newedgeincycle) # also returns alreadyNoRoot function moveTarget!(net::HybridNetwork,node::Node, major::Edge, tree::Edge, newedge::Edge, undo::Bool, newedgeincycle::Bool) node.hybrid || error("cannot move origin of hybridization because node $(node.number) is not hybrid") length(newedge.node) == 2 || error("strange edge $(newedge.number) that has $(size(newedge.node,1)) nodes instead of 2") newedge.inCycle == node.number || newedge.inCycle == -1 || error("newedge in cycle must be -1 or $(node.number), not $(newedge.inCycle)") in(newedge,net.edge) || error("newedge $(newedge.number) not in net.edge") othermajor = getOtherNode(major,node); treenode = getOtherNode(tree,node); node1 = newedge.node[1]; # not waste of memory, needed step node2 = newedge.node[2]; @debug "MOVE: hybrid node is $(node.number), major edge $(major.number), tree edge $(tree.number)" @debug "MOVE: newedge is $(newedge.number), othermajor $(othermajor.number), treenode $(treenode.number), node1 $(node1.number), node2 $(node2.number)" neighbor = false from_othermajor = false from_treenode = false if(isEqual(othermajor,node1)) n1 = node1 n2 = node2 neighbor = true from_othermajor = true elseif(isEqual(othermajor,node2)) n1 = node2 n2 = node1 neighbor = true from_othermajor = true elseif(isEqual(treenode,node1)) n1 = node1 n2 = node2 neighbor = true from_treenode = true elseif(isEqual(treenode,node2)) n1 = node2 n2 = node1 neighbor = true from_treenode = true end # -- alreadyNoRoot? if(newedge.inCycle != -1) alreadyNoRoot = false else if(neighbor && from_othermajor) alreadyNoRoot = !newedge.containRoot elseif(neighbor && from_treenode) for e in node.edge if(!isEqual(e,major) && !isEqual(e,tree)) #looking for minor edge o = getOtherNode(e,node) for e2 in o.edge if(!e2.hybrid && e2.inCycle != -1) alreadyNoRoot = !e2.containRoot break end end break end end elseif(!neighbor) alreadyNoRoot = false end end @debug "neighbor $(neighbor), from othermajor $(from_othermajor), from treenode $(from_treenode), n1 $(n1.number), n2 $(n2.number), alreadyNoRoot $(alreadyNoRoot)" if(neighbor && from_othermajor) #println("leaving n1 $(n1.number) as it is") #println("removing n2 $(n2.number) from newedge $(newedge.number) and viceversa") removeEdge!(n2,newedge) removeNode!(n2,newedge) #println("removing treenode $(treenode.number) from tree edge $(tree.number) and viceversa") removeEdge!(treenode,tree) removeNode!(treenode,tree) #println("setting newedge $(newedge.number) to treenode $(treenode.number) and viceversa") setNode!(newedge,treenode) setEdge!(treenode,newedge) #println("setting tree edge $(tree.number) to n2 $(n2.number) and viceversa") setNode!(tree,n2) setEdge!(n2,tree) elseif(neighbor && from_treenode) #println("leaving n1 $(n1.number) as it is") #println("removing n2 $(n2.number) from newedge $(newedge.number) and viceversa") removeEdge!(n2,newedge) removeNode!(n2,newedge) #println("removing othermajor $(othermajor.number) from major edge $(major.number) and viceversa") removeEdge!(othermajor,major) removeNode!(othermajor,major) #println("setting newedge $(newedge.number) to othermajor $(othermajor.number) and viceversa") setNode!(newedge,othermajor) setEdge!(othermajor,newedge) #println("setting major edge $(major.number) to n2 $(n2.number) and viceversa") setNode!(major,n2) setEdge!(n2,major) else error("move target to edge $(newedge.number) not neighbor to major edge $(major.number) nor tree edge $(tree.number), function not debugged!") #println("removing major edge $(major.number) from othermajor node $(othermajor.number) and viceverse") removeEdge!(othermajor,major) removeNode!(othermajor,major) #println("removing treenode $(treenode.number) from tree edge $(tree.number) and viceversa") removeEdge!(treenode,tree) removeNode!(treenode,tree) #println("removing node1 $(node1.number) from newedge $(newedge.number) and viceversa") removeEdge!(node1,newedge) removeNode!(node1,newedge) #println("removing node2 $(node2.number) from newedge $(newedge.number) and viceversa") removeEdge!(node2,newedge) removeNode!(node2,newedge) #println("setting newedge $(newedge.number) to othermajor $(othermajor.number) and viceversa") setNode!(newedge,othermajor) setEdge!(othermajor,newedge) #println("setting newedge $(newedge.number) to treenode $(treenode.number) and viceversa") setNode!(newedge,treenode) setEdge!(treenode,newedge) #println("setting major edge $(major.number) to node1 $(node1.number) and viceversa") setNode!(major,node1) setEdge!(node1,major) #println("setting tree edge $(tree.number) to node2 $(node2.number) and viceversa") setNode!(tree,node2) setEdge!(node2,tree) end t1 = major.length t2 = tree.length t = newedge.length setLength!(newedge,t1+t2) if(approxEq(t1,0.0) && approxEq(t2,0.0)) setLength!(major,t1) setLength!(tree,t2) else setLength!(major,t1/(t1+t2)*t) setLength!(tree,t2/(t1+t2)*t) end if(!undo) if(from_treenode) # -- update partition indexPtree = whichPartition(net,tree,node.number) ind = getIndex(newedge,net.partition[indexPtree].edges) deleteat!(net.partition[indexPtree].edges,ind) ind = getIndex(tree,net.partition[indexPtree].edges) deleteat!(net.partition[indexPtree].edges,ind) push!(net.partition[indexPtree].edges,major) edges = hybridEdges(treenode) for i in 1:3 #check of 3 edges inside hybridEdges if(!isEqual(edges[i],tree) && !isEqual(edges[i],newedge)) descendants = [edges[i]] cycleNum = [node.inCycle] getDescendants!(getOtherNode(edges[i],treenode),edges[i],descendants,cycleNum) !isempty(descendants) || error("descendants is empty for node $(treenode.number)") @debug "for node $(treenode.number), descendants are $([e.number for e in descendants]), and cycleNum is $(cycleNum)" partition = Partition(unique(cycleNum),descendants) # create new partition push!(net.partition, partition) for e in descendants #delete edges from partition with tree originally ind = getIndex(e,net.partition[indexPtree].edges) deleteat!(net.partition[indexPtree].edges,ind) end net.partition[indexPtree].cycle = union([node.inCycle],symdiff(net.partition[indexPtree].cycle,cycleNum)) break end end # -- update in cycle @debug "from treenode treatment, switch major $(major.number) to tree $(tree.number)" switchMajorTree!(major,tree,node) node.k += 1 newedge.inCycle = node.number treenode.inCycle = node.number elseif(from_othermajor) if(newedge.inCycle == node.number) @debug "from othermajor and newedge incycle treatment, switch major $(major.number) to tree $(tree.number)" # -- update partition indexPtree = whichPartition(net,tree,node.number) push!(net.partition[indexPtree].edges,major) push!(net.partition[indexPtree].edges,newedge) ind = getIndex(tree,net.partition[indexPtree].edges) deleteat!(net.partition[indexPtree].edges,ind) edges = hybridEdges(othermajor) for i in 1:3 #check of 3 edges inside hybridEdges if(!isEqual(edges[i],major) && !isEqual(edges[i],newedge)) indexP = whichPartition(net,edges[i],node.number) for e in net.partition[indexP].edges push!(net.partition[indexPtree].edges,e) end net.partition[indexPtree].cycle = union(net.partition[indexPtree].cycle,net.partition[indexP].cycle) part = splice!(net.partition,indexP) #splice at the end break end end # -- update inCycle switchMajorTree!(major,tree,node) node.k -= 1 newedge.inCycle = -1 othermajor.inCycle = -1 return true, alreadyNoRoot else # -- update partition indexPnew = whichPartition(net,newedge,node.number) indexPtree = whichPartition(net,tree,node.number) ind = getIndex(newedge,net.partition[indexPnew].edges) deleteat!(net.partition[indexPnew].edges,ind) ind = getIndex(tree,net.partition[indexPtree].edges) deleteat!(net.partition[indexPtree].edges,ind) push!(net.partition[indexPnew].edges,tree) push!(net.partition[indexPtree].edges,newedge) # -- update in cycle major.istIdentifiable = isEdgeIdentifiable(major) end end else if(from_treenode) # -- update partition indexPmajor = whichPartition(net,major,node.number) push!(net.partition[indexPmajor].edges,tree) push!(net.partition[indexPmajor].edges,newedge) ind = getIndex(major,net.partition[indexPmajor].edges) deleteat!(net.partition[indexPmajor].edges,ind) edges = hybridEdges(treenode) for i in 1:3 #check of 3 edges inside hybridEdges if(!isEqual(edges[i],tree) && !isEqual(edges[i],newedge)) indexP = whichPartition(net,edges[i],node.number) for e in net.partition[indexP].edges push!(net.partition[indexPmajor].edges,e) end net.partition[indexPmajor].cycle = union(net.partition[indexPmajor].cycle,net.partition[indexP].cycle) part = splice!(net.partition,indexP) #splice at the end break end end # -- update in cycle switchMajorTree!(tree,major,node) node.k -= 1 newedge.inCycle = -1 treenode.inCycle = -1 elseif(from_othermajor) if(newedgeincycle) # -- update partition indexPmajor = whichPartition(net,major,node.number) ind = getIndex(major,net.partition[indexPmajor].edges) deleteat!(net.partition[indexPmajor].edges,ind) #delete major ind = getIndex(newedge,net.partition[indexPmajor].edges) deleteat!(net.partition[indexPmajor].edges,ind) # delete newedge push!(net.partition[indexPmajor].edges,tree) # add tree edges = hybridEdges(othermajor) for i in 1:3 #check of 3 edges inside hybridEdges if(!isEqual(edges[i],major) && !isEqual(edges[i],newedge)) descendants = [edges[i]] cycleNum = [node.inCycle] getDescendants!(getOtherNode(edges[i],othermajor),edges[i],descendants,cycleNum) !isempty(descendants) || error("descendants is empty for node $(othermajor.number)") @debug "for node $(othermajor.number), descendants are $([e.number for e in descendants]), and cycleNum is $(cycleNum)" partition = Partition(unique(cycleNum),descendants) # create new partition push!(net.partition, partition) for e in descendants #delete edges from partition with major originally ind = getIndex(e,net.partition[indexPmajor].edges) deleteat!(net.partition[indexPmajor].edges,ind) end net.partition[indexPmajor].cycle = union([node.inCycle],symdiff(net.partition[indexPmajor].cycle,cycleNum)) break end end # -- update inCycle switchMajorTree!(tree,major,node) node.k += 1 newedge.inCycle = node.number othermajor.inCycle = node.number else # -- update partition indexPnew = whichPartition(net,newedge,node.number) indexPtree = whichPartition(net,tree,node.number) ind = getIndex(newedge,net.partition[indexPnew].edges) deleteat!(net.partition[indexPnew].edges,ind) ind = getIndex(tree,net.partition[indexPtree].edges) deleteat!(net.partition[indexPtree].edges,ind) push!(net.partition[indexPnew].edges,tree) push!(net.partition[indexPtree].edges,newedge) # -- update in cycle major.istIdentifiable = isEdgeIdentifiable(major) end end end return false, alreadyNoRoot end moveTarget!(net::HybridNetwork,node::Node, major::Edge, tree::Edge, newedge::Edge) = moveTarget!(net,node, major, tree, newedge, false, false) # function to move the target of a hybrid edge """ moveTargetUpdate!(net, hybrid_node, majoredge, newedge) Modify a level-1 network `net` by moving `majoredge`, which should be a hybrid edge parent of `hybrid_node`. Within SNaQ, `majoredge` is chosen by `chooseMinorMajor`. - calls `moveTarget!(net,hybrid_node, majoredge, treeedge_belowhybrid, newedge)`, which does the move but does not update any attributes - updates all level-1 attributes needed for SNaQ: gammaz, containRoot - un-does the move and updates if the move is invalid, through another call to `moveTarget!` but with the "undo" option. `newedge` should be a tree edge (enforced by `chooseEdgeOriginTarget!`) adjacent to the parent node of `majoredge` or to the tree child of `hybrid_node` (enforced by `getNeighborsTarget`) Output: tuple of 3 booleans `(success, flag_triangle, flag_root)`. - `success` is false if the move failed (lead to an invalid network for SNaQ) - `flag_triangle` is false if `net.hasVeryBadTriangle` - `flag_root` is false if the set of edges to place the root is empty If `success` is false, then the flags are not meant to be used downstream. """ function moveTargetUpdate!(net::HybridNetwork, node::Node, majoredge::Edge, newedge::Edge) global CHECKNET node.hybrid || error("node $(node.number) is not hybrid, so we cannot delete hybridization event around it") @debug "MOVE: move Target for hybrid node $(node.number)" # reject the move if `node` is in a 3-cycle and `newedge` is in that cycle if node.k == 3 && newedge.inCycle == node.number # then invalid move: would create a 2-cycle node.isBadTriangle || @warn "network with a not-nice 3-cycle (at least 1 block has a single taxon)" return false,false,false end in(newedge,net.edge) || error("newedge $(newedge.number) not in net.edge") major,minor,tree = hybridEdges(node) undoGammaz!(node,net); edgesRoot = identifyContainRoot(net,node); edgesRoot = setdiff(edgesRoot,[tree]) #need to remove tree from edgesRoot or it will be undone/updated with containRoot #undoContainRoot!(edgesRoot); now in updateContainRootChangeDir #@debug "undoContainRoot for edges $([e.number for e in edgesRoot])" newedgeincycle, alreadyNoRoot = moveTarget!(net,node,majoredge,tree,newedge) flag2, edgesGammaz = updateGammaz!(net,node) if flag2 # flag3,edgesroot = updateContainRoot!(net,node) now in updateContainRootChangeDir flag3,edgesroot = updateContainRootChangeDir!(net,node,edgesRoot, alreadyNoRoot) if flag3 parameters!(net); @debug "MOVE: move Target for hybrid node $(node.number) SUCCESSFUL" return true,flag2, flag3 else @debug "MOVE: move Target for hybrid node $(node.number) FAILED" @debug begin printEverything(net); "printed everything" end alreadyNoRoot || undoContainRoot!(edgesroot) #only undo edgesroot if there were changed: alreadyNoRoot=true => no change alreadyNoRoot || undoContainRoot!(edgesRoot,false); isempty(edgesGammaz) || undoistIdentifiable!(edgesGammaz) undoGammaz!(node,net); @debug "MOVE: undoing move target for conflict: updategammaz" moveTarget!(net,node,majoredge,tree,newedge,true,newedgeincycle); flag2, edgesGammaz = updateGammaz!(net,node) #@debug "undoContainRoot for edges $([e.number for e in edgesRoot])" (flag2 || node.isVeryBadTriangle || node.isExtBadTriangle) || error("updating gammaz/root for undone moveTarget, should not be any problem, but flag2 $(flag2) and node not very/ext bad triangle") CHECKNET && checkNet(net) return false, flag2,flag3 end else @debug "MOVE: move Target for hybrid node $(node.number) FAILED" @debug begin printEverything(net); "printed everything" end if CHECKNET flag3,edgesroot = updateContainRootChangeDir!(net,node,edgesRoot, alreadyNoRoot) #only to be sure there are no errors in the modified net checkNet(net) alreadyNoRoot || undoContainRoot!(edgesroot) #only undo edgesroot if there were changed: alreadyNoRoot=true => no change alreadyNoRoot || undoContainRoot!(edgesRoot,false); end isempty(edgesGammaz) || undoistIdentifiable!(edgesGammaz) undoGammaz!(node,net); @debug "MOVE: undoing move target for conflict: updategammaz" moveTarget!(net,node,majoredge,tree,newedge,true,newedgeincycle); flag2, edgesGammaz = updateGammaz!(net,node) #@debug "undoContainRoot for edges $([e.number for e in edgesRoot])" (flag2 || node.isVeryBadTriangle || node.isExtBadTriangle) || error("updating gammaz/root for undone moveTarget, should not be any problem, but flag2 $(flag2) and node not very/ext bad triangle") CHECKNET && checkNet(net) return false, flag2, false end end # function to repeat moveTargetUpdate with all the neighbors # until success or failure of all for a given hybrid node # returns success (bool): failure from: neighbors not suitable to begin # with, or conflicts incycle function moveTargetUpdateRepeat!(net::HybridNetwork, node::Node, random::Bool) node.hybrid || error("cannot move origin because node $(node.number) is not hybrid") othermin,majoredge = chooseMinorMajor(node,random, true) #println("othermin is $(othermin.number), will move edge: majoredge $(majoredge.number)") neighbor = getNeighborsTarget(node,majoredge) #println("neighbors list is $([n.number for n in neighbor])") success = false while(!isempty(neighbor) && !success) success1,newedge,ind = chooseEdgeOriginTarget!(neighbor,node); success1 || return false #println("newedge is $(newedge.number), success1 is $(success1)") in(newedge,net.edge) || error("newedge $(newedge.number) not in net.edge") success,flag2 = moveTargetUpdate!(net, node, majoredge,newedge) #println("after update, success is $(success)") if(!success) @debug "move target failed, will delete neighbor and try new one" deleteat!(neighbor,ind) end #println("neighbor list is $([n.number for n in neighbor])") end return success end # ------------------------------------- tree move NNI ------------------------------------------- # function to check if an edge is internal edge function isInternalEdge(edge::Edge) length(edge.node) == 2 || error("edge $(edge.number) has $(length(edge.node)) nodes, should be 2") return !edge.node[1].leaf && !edge.node[2].leaf end # function to check if the two node of an edge # do not have hybrid edges function hasNeighborHybrid(edge::Edge) length(edge.node) == 2 || error("edge $(edge.number) has $(length(edge.node)) nodes, should be 2") return edge.node[1].hasHybEdge || edge.node[2].hasHybEdge end # function to choose a tree edge for NNI # its two nodes must have hasHybEdge=false function chooseEdgeNNI(net::Network,N::Integer) N > 0 || error("N must be positive: $(N)") index1 = 0 i = 0 while((index1 == 0 || index1 > size(net.edge,1) || net.edge[index1].hybrid || hasNeighborHybrid(net.edge[index1]) || !isInternalEdge(net.edge[index1])) && i < N) index1 = round(Integer,rand()*size(net.edge,1)); i += 1 end if(i < N) return true,net.edge[index1] else @debug "cannot find suitable tree edge for NNI after $(N) attempts" return false,nothing end end # tree move NNI # it does not consider keeping the same setup # as a possibility # input: edge from chooseEdgeNNI # returns success; failure if cannot do nni without creating intersecting cycles function NNI!(net::Network,edge::Edge) !edge.hybrid || error("cannot do NNI on hybrid edge: $(edge.number)") @debug "MOVE: NNI on tree edge $(edge.number)" edges1 = hybridEdges(edge.node[1],edge) edges2 = hybridEdges(edge.node[2],edge) (!edges1[1].hybrid && !edges1[2].hybrid) || error("cannot do tree move NNI if one of the edges is hybrid: check neighbors of edge $(edge.number)") (!edges2[1].hybrid && !edges2[2].hybrid) || error("cannot do tree move NNI if one of the edges is hybrid: check neighbors of edge $(edge.number)") if(rand() < 0.5) e1 = edges1[1] e2 = edges1[2] else e1 = edges1[2] e2 = edges1[1] end if(rand() < 0.5) e3 = edges2[1] e4 = edges2[2] else e3 = edges2[2] e4 = edges2[1] end t1 = e1.length t = edge.length t4 = e4.length n1 = edge.node[1] n2 = edge.node[2] nohybrid = false @debug "e1 is $(e1.number), e2 is $(e2.number), e3 is $(e3.number), e4 is $(e4.number), n1 is $(n1.number), n2 is $(n2.number)" if(edge.inCycle != -1) node = net.node[getIndexNode(edge.inCycle,net)] node.hybrid || error("edge $(edge.number) has incycle $(edge.inCycle) but node $(node.number) is not hybrid") (n1.inCycle == edge.inCycle && n2.inCycle == edge.inCycle) || error("edge $(edge.number) is in cycle $(edge.inCycle) but its nodes are not: $(n1.number), $(n2.number)") if((e2.inCycle == e3.inCycle == edge.inCycle && e1.inCycle == e4.inCycle == -1) || (e1.inCycle == e4.inCycle == edge.inCycle && e2.inCycle == e3.inCycle == -1)) nothing elseif((e2.inCycle == e4.inCycle == edge.inCycle && e1.inCycle == e3.inCycle == -1) || (e1.inCycle == e3.inCycle == edge.inCycle && e2.inCycle == e4.inCycle == -1)) # -- update partition if(e2.inCycle != -1) indexPe3 = whichPartition(net,e3,node.number) part = splice!(net.partition,indexPe3) # delete partition e3 indexPe1 = whichPartition(net,e1,node.number) for e in part.edges push!(net.partition[indexPe1].edges,e) #put into partition e1 end push!(net.partition[indexPe1].edges,edge) #put edge into partition e1 net.partition[indexPe1].cycle = union(net.partition[indexPe1].cycle,part.cycle) else indexPe2 = whichPartition(net,e2,node.number) part = splice!(net.partition,indexPe2) # delete partition e2 indexPe4 = whichPartition(net,e4,node.number) @debug "deleted partition $([e.number for e in part.edges]) from net.partition" for e in part.edges @debug "partition for e4 is $([e.number for e in net.partition[indexPe4].edges]), pushing edge $(e.number)" push!(net.partition[indexPe4].edges,e) #put into partition e4 end @debug "partition for e4 is $([e.number for e in net.partition[indexPe4].edges]), pushing edge $(edge.number)" push!(net.partition[indexPe4].edges,edge) #put edge into partition e4 @debug "added the edges of such partition to partition of e4, so new partition is $([e.number for e in net.partition[indexPe4].edges])" net.partition[indexPe4].cycle = union(net.partition[indexPe4].cycle,part.cycle) @debug "new partition has cycle $(net.partition[indexPe4].cycle)" end # -- update inCycle @debug "incycle e1 $(e1.inCycle), e2 $(e2.inCycle), e3 $(e3.inCycle), e4 $(e4.inCycle), edge $(edge.inCycle)" if(e2.inCycle == e4.inCycle == edge.inCycle) edge.inCycle = -1 n1.inCycle = -1 node.k -= 1; elseif(e1.inCycle == e3.inCycle == edge.inCycle) edge.inCycle = -1 n2.inCycle = -1 node.k -= 1; end else error("internal edge $(edge.number) is in cycle $(edge.inCycle), but it is not consistent with other edges") end else #edge not in cycle (e1.inCycle == e2.inCycle && e3.inCycle == e4.inCycle) || error("both edges in edges1 $([e.number for e in edges1]) (or edges2 $([e.number for e in edges2])) must have the same inCycle attribute") if(e1.inCycle != -1 && e3.inCycle != -1) @debug "cannot do tree NNI because it will create intersecting cycles, nothing done. e1,e2,e3,e4: $([e1.number,e2.number,e3.number,e4.number])" return false elseif(e1.inCycle != -1 && e3.inCycle == -1) node = net.node[getIndexNode(e1.inCycle,net)] node.hybrid || error("edge $(ed1.number) has incycle $(ed1.inCycle) but node $(node.number) is not hybrid") # -- update partition indexP = whichPartition(net,edge,node.number) # find partition where edge is ind = getIndex(edge,net.partition[indexP].edges) deleteat!(net.partition[indexP].edges,ind) edges = hybridEdges(n2) for i in 1:3 #check of 3 edges inside hybridEdges if(!isEqual(edges[i],e4) && !isEqual(edges[i],edge)) descendants = [edges[i]] cycleNum = [node.inCycle] getDescendants!(getOtherNode(edges[i],n2),edges[i],descendants,cycleNum) !isempty(descendants) || error("descendants is empty for node $(n2.number)") @debug "for node $(n2.number), descendants are $([e.number for e in descendants]), and cycleNum is $(cycleNum)" partition = Partition(unique(cycleNum),descendants) # create new partition push!(net.partition, partition) for e in descendants #delete edges from partition with tree originally ind = getIndex(e,net.partition[indexP].edges) deleteat!(net.partition[indexP].edges,ind) end net.partition[indexP].cycle = union([node.inCycle],symdiff(net.partition[indexP].cycle,cycleNum)) break end end # -- update in cycle edge.inCycle = e1.inCycle n2.inCycle = e1.inCycle node.k += 1 elseif(e3.inCycle != -1 && e1.inCycle == -1) node = net.node[getIndexNode(e3.inCycle,net)] node.hybrid || error("edge $(ed3.number) has incycle $(ed3.inCycle) but node $(node.number) is not hybrid") # -- update partition indexP = whichPartition(net,edge,node.number) # find partition where edge is ind = getIndex(edge,net.partition[indexP].edges) deleteat!(net.partition[indexP].edges,ind) edges = hybridEdges(n1) for i in 1:3 #check of 3 edges inside hybridEdges if(!isEqual(edges[i],e1) && !isEqual(edges[i],edge)) descendants = [edges[i]] cycleNum = [node.inCycle] getDescendants!(getOtherNode(edges[i],n1),edges[i],descendants,cycleNum) !isempty(descendants) || error("descendants is empty for node $(n1.number)") @debug "for node $(n1.number), descendants are $([e.number for e in descendants]), and cycleNum is $(cycleNum)" partition = Partition(unique(cycleNum),descendants) # create new partition push!(net.partition, partition) for e in descendants #delete edges from partition with tree originally ind = getIndex(e,net.partition[indexP].edges) deleteat!(net.partition[indexP].edges,ind) end net.partition[indexP].cycle = union([node.inCycle],symdiff(net.partition[indexP].cycle,cycleNum)) break end end # -- update in cycle edge.inCycle = e3.inCycle n1.inCycle = e3.inCycle node.k += 1 else nohybrid = true end end removeNode!(n1,e2) removeEdge!(n1,e2) removeNode!(n2,e3) removeEdge!(n2,e3) setNode!(e3,n1) setEdge!(n1,e3) setNode!(e2,n2) setEdge!(n2,e2) if(rand() < 0.5) # update lengths r = rand() setLength!(e1,r*t1) setLength!(edge,(1-r)*t1) setLength!(e4,t4+t) else r = rand() setLength!(e1,t1+t) setLength!(edge,(1-r)*t4) setLength!(e4,r*t4) end if(!isTree(net) && !nohybrid) undoGammaz!(node,net); flag,edges = updateGammaz!(net,node); flag || error("cannot encounter bad triangles with NNI move") end parameters!(net); @debug "MOVE: NNI around edge $(edge.number) SUCCESSFUL" return true end # function to repeat NNI until success function NNIRepeat!(net::HybridNetwork,N::Integer) N > 0 || error("N must be positive: $(N)") flag,edge = chooseEdgeNNI(net,N) flag || return false i = 0 success = false while(!success && i < N) success = NNI!(net,edge) i += 1 end success || return false return true end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
12663
# functions to extend snaq to multiple alleles case # Claudia November 2015 global repeatAlleleSuffix = "__2" repeatAlleleSuffix_re = Regex("$repeatAlleleSuffix\$") """ mapAllelesCFtable(mapping file, CF file; filename, columns, delim) Create a new DataFrame containing the same concordance factors as in the input CF file, but with modified taxon names. Each allele name in the input CF table is replaced by the species name that the allele maps onto, based on the mapping file. The mapping file should have column names: allele and species. Optional arguments: - file name to write/save resulting CF table. If not specified, then the output data frame is not saved to a file. - column numbers for the taxon names. 1-4 by default. - any keyword arguments that `CSV.File` would accept. For example, delim=',' by default: columns are delimited by commas. Unless specified otherwise by the user, `pool`=false (to read taxon names as Strings, not levels of a categorical factor, for combining the 4 columns with taxon names more easily). The same CSV arguments are used to read both input file (mapping file and quartet file) See also [`mapAllelesCFtable!`](@ref) to input DataFrames instead of file names. If a `filename` is specified, such as "quartetCF_speciesNames.csv" in the example below, this file is best read later with the option `pool=false`. example: ```julia mapAllelesCFtable("allele-species-map.csv", "allele-quartet-CF.csv"; filename = "quartetCF_speciesNames.csv") df_sp = CSV.read("quartetCF_speciesNames.csv", DataFrame); # DataFrame object dataCF_specieslevel = readTableCF!(df_sp, mergerows=true); # DataCF object ``` """ function mapAllelesCFtable(alleleDF::AbstractString, cfDF::AbstractString; filename=""::AbstractString, columns=Int[]::Vector{Int}, CSVargs...) # force pool=false unless the user wants otherwise if :pool ∉ [pair[1] for pair in CSVargs] CSVargs = (CSVargs..., :pool=>false) end d = DataFrame(CSV.File(alleleDF; CSVargs...); copycols=false) d2 = DataFrame(CSV.File(cfDF; CSVargs...); copycols=false) mapAllelesCFtable!(d2,d, columns, filename != "", filename) end """ mapAllelesCFtable!(quartet CF DataFrame, mapping DataFrame, columns, write?, filename) Modify (and return) the quartet concordance factor (CF) DataFrame: replace each allele name by the species name that the allele maps onto based on the mapping data frame. This mapping data frame should have columns named "allele" and "species" (see `rename!` to change column names if need be). If `write?` is `true`, the modified data frame is written to a file named "filename". Warning: [`mapAllelesCFtable`](@ref) takes the quartet data file as its second argument, while `mapAllelesCFtable!` takes the quartet data (which it modifies) as its first argument. """ function mapAllelesCFtable!(cfDF::DataFrame, alleleDF::DataFrame, co::Vector{Int},write::Bool,filename::AbstractString) size(cfDF,2) >= 7 || error("CF DataFrame should have 7+ columns: 4taxa, 3CF, and possibly ngenes") if length(co)==0 co=[1,2,3,4]; end allelecol, speciescol = compareTaxaNames(alleleDF,cfDF,co) for j in 1:4 for ia in 1:size(alleleDF,1) # for all alleles cfDF[!,co[j]] = map(x->replace(string(x), Regex("^$(string(alleleDF[ia,allelecol]))\$") => alleleDF[ia,speciescol]), cfDF[!,co[j]]) end end if write filename != "" || error("cannot write quartet CF with mapped alleles: empty filename") CSV.write(filename, cfDF) end return cfDF end # function to clean a df after changing allele names to species names # inside readTableCF! # by deleting rows that are not informative like sp1 sp1 sp1 sp2 # keepOne=true: we only keep one allele per species function cleanAlleleDF!(newdf::DataFrame, cols::Vector{<:Integer}; keepOne=false::Bool) delrows = Int[] # indices of rows to delete repSpecies = Set{String}() if(isa(newdf[1,cols[1]],Integer)) #taxon names as integers: we need this to be able to add __2 for j in 1:4 newdf[!,cols[j]] .= map(string, newdf[!,cols[j]]) end end row = Vector{String}(undef, 4) for i in 1:nrow(newdf) map!(j -> newdf[i,cols[j]], row, 1:4) uniq = unique(row) if(length(uniq) == 4) continue end # by now, at least 1 species is repeated if !keepOne # then we may choose to keep this row # 3 options: sp1 sp1 sp2 sp3; or sp1 sp1 sp2 sp2 (keep) # or sp1 sp1 sp1 sp2; or sp1 sp1 sp1 sp1 (do not keep) keep = false for u in uniq ind = row .== u # indices of taxon names matching u if sum(ind) == 2 keep = true push!(repSpecies, string(u)) # change the second instance of a repeated taxon name with suffix k = findlast(ind) newdf[i,cols[k]] = string(u, repeatAlleleSuffix) end end end keep || push!(delrows, i) end nrows = size(newdf,1) nkeep = nrows - length(delrows) if nkeep < nrows print("""found $(length(delrows)) 4-taxon sets uninformative about between-species relationships, out of $(nrows). These 4-taxon sets will be deleted from the data frame. $nkeep informative 4-taxon sets will be used. """) nkeep > 0 || @warn "All 4-taxon subsets are uninformative, so the dataframe will be left empty" deleteat!(newdf, delrows) # deleteat! requires DataFrames 1.3 end return collect(repSpecies) end # function to merge rows that have repeated taxon names by using the weigthed average of CF # (if info on number of genes is provided) or simple average function mergeRows(df::DataFrame, cols::Vector{Int}) sorttaxa!(df, cols) # sort taxa alphabetically within each row colnamtax = DataFrames.propertynames(df)[cols[1:4]] colnam = DataFrames.propertynames(df)[cols[5:end]] df = combine(groupby(df, colnamtax, sort=false, skipmissing=false), colnam .=> mean .=> colnam) # rename!(df, Dict((Symbol(n, "_mean"), n) for n in colnam) ) n4tax = size(df,1) # total number of 4-taxon sets print("$n4tax unique 4-taxon sets were found. CF values of repeated 4-taxon sets will be averaged") println((length(cols)>7 ? " (ngenes too)." : ".")) return df end # function to expand leaves in tree to two individuals # based on cf table with alleles mapped to species names function expandLeaves!(repSpecies::Union{Vector{String},Vector{Int}},tree::HybridNetwork) for sp in repSpecies for n in tree.node if(n.name == sp) #found leaf with sp name n.leaf || error("name $(sp) should correspond to a leaf, but it corresponds to an internal node") length(n.edge) == 1 || error("leaf $(sp) should have only one edge attached and it has $(length(n.edge))") if(n.edge[1].length == -1.0) setLength!(n.edge[1],1.0) end removeLeaf!(tree,n) n.leaf = false n.edge[1].istIdentifiable = true n.name = "" max_node = maximum([e.number for e in tree.node]); max_edge = maximum([e.number for e in tree.edge]); e1 = Edge(max_edge+1,0.0) e2 = Edge(max_edge+2,0.0) n1 = Node(max_node+1,true,false,[e1]) n2 = Node(max_node+2,true,false,[e2]) setNode!(e1,n1) setNode!(e1,n) setNode!(e2,n2) setNode!(e2,n) setEdge!(n,e1) setEdge!(n,e2) pushNode!(tree,n1) pushNode!(tree,n2) pushEdge!(tree,e1) pushEdge!(tree,e2) n1.name = string(sp) n2.name = string(sp,repeatAlleleSuffix) push!(tree.names,n2.name) break end end end end # function to compare the taxon names in the allele-species matching table # and the CF table function compareTaxaNames(alleleDF::DataFrame, cfDF::DataFrame, co::Vector{Int}) allelecol, speciescol = checkMapDF(alleleDF) CFtaxa = string.(mapreduce(x -> unique(skipmissing(x)), union, eachcol(cfDF[!,co[1:4]]))) alleleTaxa = map(string, alleleDF[!,allelecol]) # as string, too sizeCF = length(CFtaxa) sizeAllele = length(alleleTaxa) if sizeAllele > sizeCF @warn "some alleles in the mapping file do not occur in the quartet CF data. Extra allele names will be ignored" alleleTaxa = intersect(alleleTaxa,CFtaxa) end unchanged = setdiff(CFtaxa,alleleTaxa) if length(unchanged) == length(CFtaxa) @warn "None of the taxon names in CF table match with allele names in the mapping file" end if !isempty(unchanged) warnmsg = "not all alleles were mapped\n" warnmsg *= "alleles not mapped to a species name:" for n in unchanged warnmsg *= " $n"; end @warn warnmsg end return allelecol, speciescol end """ checkMapDF(mapping_allele2species::DataFrame) Check that the data frame has one column named "allele" or "individual", and one column named "species". Output: indices of these column. """ function checkMapDF(alleleDF::DataFrame) size(alleleDF,2) >= 2 || error("Allele-Species matching Dataframe should have at least 2 columns") colnames = DataFrames.propertynames(alleleDF) allelecol = findfirst(x -> x == :allele, colnames) if isnothing(allelecol) allelecol = findfirst(x -> x == :individual, colnames) end isnothing(allelecol) && error("In allele mapping file there is no column named 'allele' or 'individual'") speciescol = findfirst(x -> x == :species, colnames) isnothing(speciescol) && error("In allele mapping file there is no column named species") return allelecol, speciescol end ## function to check if a new proposed topology satisfies the condition for ## multiple alleles: no gene flow to either allele, and both alleles as sister ## returns false if the network is not ok function checkTop4multAllele(net::HybridNetwork) for n in net.leaf if occursin(repeatAlleleSuffix_re, n.name) n.leaf || error("weird node $(n.number) not leaf in net.leaf list") length(n.edge) == 1 || error("weird leaf with $(length(n.edge)) edges") par = getOtherNode(n.edge[1],n) if(par.hybrid) ## there is gene flow into n return false end nameOther = replace(n.name, repeatAlleleSuffix_re => "") foundOther = false for i in 1:3 other = getOtherNode(par.edge[i],par) if(other.leaf && other.name == nameOther) foundOther = true end end foundOther || return false end end return true end ## function to merge the two alleles into one function mergeLeaves!(net::HybridNetwork) leaves = copy(net.leaf) # bc we change this list for n in leaves if occursin(repeatAlleleSuffix_re, n.name) n.leaf || error("weird node $(n.number) not leaf in net.leaf list") length(n.edge) == 1 || error("weird leaf with $(length(n.edge)) edges") par = getOtherNode(n.edge[1],n) foundOther = false other = Node() nameOther = replace(n.name, repeatAlleleSuffix_re => "") for i in 1:3 other = getOtherNode(par.edge[i],par) if(other.leaf && other.name == nameOther) foundOther = true break end end if(!foundOther) checkTop4multAllele(net) || error("current network does not comply with multiple allele condition") error("strange network that passes checkTop4multAllele, but cannot find the other allele for $(n.name)") end removeEdge!(par,n.edge[1]) removeEdge!(par,other.edge[1]) deleteNode!(net,n) deleteNode!(net,other) deleteEdge!(net,n.edge[1]) deleteEdge!(net,other.edge[1]) par.name = other.name par.leaf = true push!(net.leaf,par) net.numTaxa += 1 end end end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
5349
function check_distance_matrix(D::Matrix{<:Real}) size(D, 1) > 1 || throw(DomainError(D, "Too few nodes")) if any(D .< 0) throw(DomainError(D, "Negative entries in distance matrix")) end if any(diag(D) .!= 0.0) throw(DomainError(D, "Diagonal entry not 0")) end end """ nj!(D::Matrix{Float64}, names::AbstractVector{<:AbstractString}=String[]; force_nonnegative_edges::Bool=false) Construct a phylogenetic tree from the input distance matrix and vector of names (as strings), using the Neighbour-Joinging algorithm ([Satou & Nei 1987](https://doi.org/10.1093/oxfordjournals.molbev.a040454)). The order of the `names` argument should match that of the row (and column) of the matrix `D`. With `force_nonnegative_edges` being `true`, any negative edge length is changed to 0.0 (with a message). Warning: `D` is modified. """ function nj!(D::Matrix{Float64}, names::AbstractVector{<:AbstractString}=String[]; force_nonnegative_edges::Bool=false) check_distance_matrix(D) n = size(D, 1) # number of species # when no names arg is supplied if isempty(names) names = string.(1:n) end # create empty network with n unconnected leaf nodes nodes = map(function(i) node = Node(i, true) node.name = names[i] return node end, 1:n) net = HybridNetwork(nodes, Edge[]) # an array of Node s.t. active_nodes[i] would correspond to the # ith entry in distance matrix D at each iteration active_nodes = copy(nodes) neglenp = 0 # number of negative edge lengths while n > 2 # compute Q matrix and find min # warning: here i and j are indeces for D, not actual id's sums = sum(D, dims = 1) cur = Inf min_index = (0, 0) for i = 1:n for j = i:n if j != i qij = (n-2) * D[i,j] - sums[i] - sums[j] if qij < cur cur = qij min_index = (i, j) end end end end # connect the nodes, compute the length of the edge (i, j) = min_index dik = D[i,j] / 2 + (sums[i] - sums[j]) / (2 * (n - 2)) djk = D[i,j] - dik # force negative lengths to 0, if any if dik < 0.0 neglenp += 1 if force_nonnegative_edges dik = 0.0; end end if djk < 0.0 neglenp += 1 if force_nonnegative_edges djk = 0.0; end end # create new edges and node, update tree edgenum = net.numEdges eik = Edge(edgenum + 1, dik) # edge length must be Float64 for Edge() ejk = Edge(edgenum + 2, djk) node_k = Node(net.numNodes+1, false, false, [eik, ejk]) # new node node_i = active_nodes[i] node_j = active_nodes[j] setNode!(eik, Node[node_i, node_k]) setNode!(ejk, Node[node_j, node_k]) setEdge!(node_i, eik) setEdge!(node_j, ejk) pushEdge!(net, eik) pushEdge!(net, ejk) pushNode!(net, node_k) # update map and D # replace D[l, i] with D[l, k], delete D[ , j] for l in 1:n if !(l in [i j]) D[l, i] = (D[l,i] + D[j,l] - D[i,j]) / 2 D[i, l] = D[l, i] end end newidx = filter(u->u!=j, 1:n) # index 1:n\{j} D = view(D, newidx, newidx) # update active_nodes active_nodes[i] = node_k active_nodes = view(active_nodes, newidx) n = n - 1 end # base case if D[1,2] < 0.0 neglenp += 1 if force_nonnegative_edges D[1,2] = 0.0; end end node1 = active_nodes[1] node2 = active_nodes[2] newedge = Edge(net.numEdges+1, D[1,2]) setNode!(newedge, [node1, node2]) # isChild1 = true by default: nodes are [child, parent] if node1.number == net.numNodes newedge.isChild1 = false # to direct the edge from the last created node to the other node end setEdge!(node1, newedge) setEdge!(node2, newedge) pushEdge!(net, newedge) net.root = net.numNodes # to place the root at the last created node, which is internal # report on number of negative branches if neglenp > 0 infostr = (force_nonnegative_edges ? "$neglenp branches had negative lengths, reset to 0" : "$neglenp branches have negative lengths" ) @info infostr end return net end """ nj(D::DataFrame; force_nonnegative_edges::Bool=false) Construct a tree from a distance matrix by neighbor joining, where `D` is a `DataFrame` of the distance matrix, with taxon names taken from the header of the data frame. The rows are assumed to correspond to tips in the tree in the same order as they do in columns. With `force_nonnegative_edges` being `true`, any negative edge length is changed to 0.0 (with a message). For the algorithm, see [Satou & Nei 1987](https://doi.org/10.1093/oxfordjournals.molbev.a040454). See [`nj!`](@ref) for using a matrix as input. """ function nj(D::DataFrame; force_nonnegative_edges::Bool=false) nj!(Matrix{Float64}(D), names(D); force_nonnegative_edges=force_nonnegative_edges) end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
2556
""" OptSummary{T<:AbstractFloat} Summary of an `NLopt` optimization. Idea and code taken from [`MixedModels`](https://github.com/JuliaStats/MixedModels.jl). `T` is the type of the function argument(s) and of the function value. """ mutable struct OptSummary{T<:AbstractFloat} "copy of initial param values in the optimization" initial::Vector{T} "lower bounds on the parameter values" lowerbd::Vector{T} "relative tolerance on the function value f(x), as in NLopt" ftol_rel::T "absolute tolerance on the function value f(x), as in NLopt" ftol_abs::T "relative tolerance on the argument value x, as in NLopt" xtol_rel::T "absolute tolerance on the argument value x" xtol_abs::Vector{T} "initial step sizes, as in NLopt" initial_step::Vector{T} "maximum number of function evaluations, as in NLopt" maxfeval::Int "copy of the final parameter values from the optimization" final::Vector{T} "final value of the objective function" fmin::T "number of function evaluations" feval::Int "name of the optimizer used, as a `Symbol`" algorithm::Symbol "return value, as a `Symbol`" returnvalue::Symbol end function OptSummary(initial::Vector{T}, lowerbd::Vector{T}, algorithm::Symbol; ftol_rel::T = zero(T), ftol_abs::T = zero(T), xtol_rel::T = zero(T), xtol_abs::Vector{T} = fill(zero, length(initial)), initial_step::Vector{T} = T[]) where {T<:AbstractFloat} OptSummary(initial, lowerbd, ftol_rel, ftol_abs, xtol_rel, xtol_abs, initial_step, -1, # maxeval: 0 or negative for no limit copy(initial), # final x T(Inf), # final value (will be finite after minimization) -1, # number of evals algorithm, :FAILURE) end function NLopt.Opt(optsum::OptSummary) lb = optsum.lowerbd np = length(lb) # number of parameters to optimize opt = NLopt.Opt(optsum.algorithm, np) NLopt.ftol_rel!(opt, optsum.ftol_rel) # relative criterion on objective NLopt.ftol_abs!(opt, optsum.ftol_abs) # absolute criterion on objective NLopt.xtol_rel!(opt, optsum.xtol_rel) # relative criterion on parameters NLopt.xtol_abs!(opt, optsum.xtol_abs) # absolute criterion on parameters NLopt.lower_bounds!(opt, lb) NLopt.maxeval!(opt, optsum.maxfeval) if isempty(optsum.initial_step) optsum.initial_step = NLopt.initial_step(opt, similar(lb)) else NLopt.initial_step!(opt, optsum.initial_step) end return opt end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
17403
""" getNodeAges(net) vector of node ages in pre-order, as in `nodes_changed`. *Warnings*: `net` is assumed to - have been preordered before (to calculate `nodes_changed`) - be time-consistent (all paths to the root to a given hybrid have the same length) - be ultrametric (all leaves have the same age: 0) """ function getNodeAges(net::HybridNetwork) x = Vector{Float64}(undef, length(net.nodes_changed)) for i in reverse(1:length(net.nodes_changed)) # post-order n = net.nodes_changed[i] if n.leaf x[i] = 0.0 continue end for e in n.edge if getparent(e) == n # n parent of e childnode = getchild(e) childIndex = getIndex(childnode, net.nodes_changed) x[i] = x[childIndex] + e.length break # use 1st child, ignores all others end end end return x end """ pairwiseTaxonDistanceMatrix(net; keepInternal=false, checkPreorder=true, nodeAges=[]) pairwiseTaxonDistanceMatrix!(M, net, nodeAges) Return the matrix `M` of pairwise distances between nodes in the network: - between all nodes (internal and leaves) if `keepInternal=true`, in which case the nodes are listed in `M` in the order in which they appear in `net.nodes_changed` - between taxa only otherwise, in which case the nodes are listed in `M` in the order in which they appear in `tipLabels(net)` (i.e. same order as in `net.leaf`) The second form modifies `M` in place, assuming all nodes. The distance between the root and a given hybrid node (to take an example) is the weighted average of path lengths from the root to that node, where each path is weighted by the product of γs of all edges on that path. This distance measures the average genetic distance across the genome, if branch lengths are in substitutions/site. optional arguments: - `checkPreorder`: if true, `net.nodes_changed` is updated to get a topological ordering of nodes. - `nodeAges`: if not provided, i.e. empty vector, the network is *not* modified. If provided and non-empty, `nodeAges` should list node ages in the pre-order in which nodes are listed in `nodes_changed` (including leaves), and **edge lengths** in `net` **are modified** accordingly. Providing node ages hence makes the network time consistent: such that all paths from the root to a given hybrid node have the same length. If node ages are not provided, the network need not be time consistent. """ function pairwiseTaxonDistanceMatrix(net::HybridNetwork; keepInternal=false::Bool, checkPreorder=true::Bool, nodeAges=Float64[]::Vector{Float64}) net.isRooted || error("net needs to be rooted for preorder recursion") if(checkPreorder) preorder!(net) end nnodes = net.numNodes M = zeros(Float64,nnodes,nnodes) if length(nodeAges)>0 length(nodeAges) == net.numNodes || error("there should be $(net.numNodes) node ages") end pairwiseTaxonDistanceMatrix!(M,net,nodeAges) if !keepInternal M = getTipSubmatrix(M, net) end return M end """ getTipSubmatrix(M, net; indexation=:both) Extract submatrix of M, with rows and/or columns corresponding to tips in the network, ordered like in `net.leaf`. In M, rows and/or columns are assumed ordered as in `net.nodes_changed`. indexation: one of `:rows`, `:cols` or `:both`: are nodes numbers indexed in the matrix by rows, by columns, or both? Subsetting is taken accordingly. """ function getTipSubmatrix(M::Matrix, net::HybridNetwork; indexation=:both) nodenames = [n.name for n in net.nodes_changed] tipind = Int[] for l in tipLabels(net) push!(tipind, findfirst(isequal(l), nodenames)) end if indexation == :both return M[tipind, tipind] elseif indexation == :rows return M[tipind, :] elseif indexation == :cols return M[:, tipind] else error("indexation must be one of :both :rows or :cols") end end function pairwiseTaxonDistanceMatrix!(M::Matrix{Float64},net::HybridNetwork,nodeAges) recursionPreOrder!(net.nodes_changed, M, # updates M in place updateRootSharedPathMatrix!, # does nothing updateTreePairwiseTaxonDistanceMatrix!, updateHybridPairwiseTaxonDistanceMatrix!, nodeAges) end function updateTreePairwiseTaxonDistanceMatrix!(V::Matrix, i::Int,parentIndex::Int,edge::Edge, params) nodeAges = params # assumed pre-ordered, as in nodes_changed if length(nodeAges)>0 edge.length= nodeAges[parentIndex] - nodeAges[i] end for j in 1:(i-1) V[i,j] = V[parentIndex,j]+edge.length V[j,i] = V[i,j] end V[i,i] = 0.0 end function updateHybridPairwiseTaxonDistanceMatrix!(V::Matrix, i::Int, parentIndex1::Int, parentIndex2::Int, edge1::Edge, edge2::Edge, params) nodeAges = params # should be pre-ordered if length(nodeAges)>0 edge1.length= nodeAges[parentIndex1] - nodeAges[i] edge2.length= nodeAges[parentIndex2] - nodeAges[i] end for j in 1:(i-1) V[i,j] = edge1.gamma*(edge1.length+V[parentIndex1,j]) + edge2.gamma*(edge2.length+V[parentIndex2,j]) V[j,i] = V[i,j] end end """ pairwiseTaxonDistanceGrad(net; checkEdgeNumber=true, nodeAges=[]) 3-dim array: gradient of pairwise distances between all nodes. (internal and leaves); gradient with respect to edge lengths if `nodeAges` is empty; with respect to node ages otherwise. Assume correct `net.nodes_changed` (preorder). This gradient depends on the network's topology and γ's only, not on branch lengths or node ages (distances are linear in either). WARNING: edge numbers need to range between 1 and #edges. """ function pairwiseTaxonDistanceGrad(net::HybridNetwork; checkEdgeNumber=true::Bool, nodeAges=Float64[]::Vector{Float64}) if checkEdgeNumber sort([e.number for e in net.edge]) == collect(1:net.numEdges) || error("edge numbers must range between 1 and #edges") end n = (length(nodeAges)==0 ? net.numEdges : net.numNodes) M = zeros(Float64, net.numNodes, net.numNodes, n) recursionPreOrder!(net.nodes_changed, M, updateRootSharedPathMatrix!, # does nothing updateTreePairwiseTaxonDistanceGrad!, updateHybridPairwiseTaxonDistanceGrad!, nodeAges) # nodeAges assumed pre-ordered, like nodes_changed return M end function updateTreePairwiseTaxonDistanceGrad!(V::Array{Float64,3}, i::Int, parentIndex::Int, edge::Edge, params) nodeAges = params # assumed pre-ordered for j in 1:(i-1) if length(nodeAges) == 0 # d/d(edge length) V[i,j,edge.number] = 1.0 else # d/d(node age) V[i,j,parentIndex] = 1.0 V[i,j,i] = -1.0 end for k in 1:size(V)[3] # brute force... V[i,j,k] += V[parentIndex,j,k] V[j,i,k] = V[i,j,k] end end # V[i,i,k] initialized to 0.0 already end function updateHybridPairwiseTaxonDistanceGrad!(V::Array{Float64,3},i::Int, parentIndex1::Int, parentIndex2::Int, edge1::Edge, edge2::Edge, params) nodeAges = params for j in 1:(i-1) if length(nodeAges) == 0 # d/d(edge length) V[i,j,edge1.number] = edge1.gamma V[i,j,edge2.number] = edge2.gamma else # d/d(node age) V[i,j,parentIndex1] = edge1.gamma V[i,j,parentIndex2] = edge2.gamma V[i,j,i] = - 1.0 # because γ1+γ2 = 1 end for k in 1:size(V)[3] V[i,j,k] += edge1.gamma*V[parentIndex1,j,k] + edge2.gamma*V[parentIndex2,j,k] V[j,i,k] = V[i,j,k] end end end """ calibrateFromPairwiseDistances!(net, distances::Matrix{Float64}, taxon_names::Vector{<:AbstractString}) Calibrate the network to match (as best as possible) input pairwise distances between taxa, such as observed from sequence data. `taxon_names` should provide the list of taxa, in the same order in which they they are considered in the `distances` matrix. The optimization criterion is the sum of squares between the observed distances, and the distances from the network (weighted average of tree distances, weighted by γ's). The network's edge lengths are modified. Warning: for many networks, mutiple calibrations can fit the pairwise distance data equally well (lack of identifiability). This function will output *one* of these equally good calibrations. optional arguments (default): - checkPreorder (true) - forceMinorLength0 (false) to force minor hybrid edges to have a length of 0 - NLoptMethod (`:LD_MMA`) for the optimization algorithm. Other options include `:LN_COBYLA` (derivative-free); see NLopt package. - tolerance values to control when the optimization is stopped: ftolRel (1e-12), ftolAbs (1e-10) on the criterion, and xtolRel (1e-10), xtolAbs (1e-10) on branch lengths / divergence times. - verbose (false) """ function calibrateFromPairwiseDistances!(net::HybridNetwork, D::Array{Float64,2}, taxNames::Vector{<:AbstractString}; checkPreorder=true::Bool, forceMinorLength0=false::Bool, verbose=false::Bool, ultrametric=true::Bool, NLoptMethod=:LD_MMA::Symbol, ftolRel=fRelBL::Float64, ftolAbs=fAbsBL::Float64, xtolRel=xRelBL::Float64, xtolAbs=xAbsBL::Float64) checkPreorder && preorder!(net) # fixit: remove root node if of degree 2, and if ultrametric=false defaultedgelength = median(D)/(length(net.edge)/2) for e in net.edge if e.length == -1.0 e.length=defaultedgelength; end # get smarter starting values: NJ? fast dating? end if ultrametric # get all node ages in pre-order na = getNodeAges(net) else na = Float64[]; end # get number and indices of edge/nodes to be optimized if forceMinorLength0 && !ultrametric parind = filter(i -> net.edge[i].isMajor, 1:net.numEdges) nparams = length(parind) # edges to be optimized: indices par = [e.length for e in net.edge][parind] # and lengths for i in 1:net.numEdges if !net.edge[i].isMajor net.edge[i].length=0.0; end end elseif !forceMinorLength0 && !ultrametric nparams = length(net.edge) # number of parameters to optimize par = [e.length for e in net.edge] parind = 1:nparams elseif !forceMinorLength0 && ultrametric nparams = net.numNodes - net.numTaxa # internal nodes to be optimized parind = filter(i -> !net.nodes_changed[i].leaf, 1:net.numNodes) par = na[parind] else # forceMinorLength0 && ultrametric nparams = net.numNodes - net.numTaxa - net.numHybrids parind = filter(i -> !(net.nodes_changed[i].leaf || net.nodes_changed[i].hybrid), 1:net.numNodes) par = na[parind] hybInd = filter(i -> net.nodes_changed[i].hybrid, 1:net.numNodes) hybParentInd = Int[] # index in nodes_changed of minor parent hybGParentI = Int[] # index in 1:nparams of minor (grand-)parent in param list for i in hybInd n = net.nodes_changed[i] p = getparentminor(n) pi = findfirst(n -> n===p, net.nodes_changed) push!(hybParentInd, pi) pii = findfirst(isequal(pi), parind) while pii===nothing # in case minor parent of n is also hybrid node p = getparentminor(p) pi = findfirst(n -> n===p, net.nodes_changed) pii = findfirst(isequal(pi), parind) end push!(hybGParentI, pii) end end # initialize M=dist b/w all nodes, G=gradient (constant) M = pairwiseTaxonDistanceMatrix(net, keepInternal=true, checkPreorder=false, nodeAges=na) if !ultrametric && sort([e.number for e in net.edge]) != collect(1:net.numEdges) for i in 1:net.numEdges # renumber edges, needed for G net.edge[i].number = i end end # G assumes edges numbered 1:#edges, if optim edge lengths G = pairwiseTaxonDistanceGrad(net, checkEdgeNumber=false, nodeAges=na) .* 2 # match order of leaves in input matrix, versus pre-order nodenames = [n.name for n in net.nodes_changed] # pre-ordered ntax = length(taxNames) tipind = Int[] # pre-order index for leaf #i in dna distances for l in taxNames i = findfirst(isequal(l), nodenames) i !== nothing || error("taxon $l not found in network") push!(tipind, i) end # contraints: to force a parent to be older than its child if ultrametric numConstraints = length(parind) -1 + net.numHybrids # calculate indices in param list of child & (grand-)parent once chii = Int[] # non-root internal node, can be repeated: once per constraint anii = Int[] # closest ancestor in param list ci = 1 # index of constraint for i in 2:length(net.nodes_changed) # 1=root, can skip n = net.nodes_changed[i] if n.leaf continue; end # node ages already bounded by 0 if n.hybrid && forceMinorLength0 # get index in param list of nii = hybGParentI[findfirst(isequal(i), hybInd)] # minor grand-parent (same age) else nii = findfirst(isequal(i), parind) end for e in n.edge if getchild(e) == n # n child of e p = getparent(e) # parent of n if forceMinorLength0 && n.hybrid && !e.isMajor continue; end # p and n at same age already pi = findfirst(isequal(p.number), [no.number for no in net.nodes_changed]) if forceMinorLength0 && p.hybrid pii = hybGParentI[findfirst(isequal(pi), hybInd)] else pii = findfirst(isequal(pi), parind) end push!(chii, nii) push!(anii, pii) verbose && println("node $(net.nodes_changed[parind[nii]].number) constrained by age of parent $(net.nodes_changed[parind[pii]].number)") ci += 1 end end end length(chii) == numConstraints || error("incorrect number of node age constraints: $numConstraints") function ageConstraints(result, nodeage, grad) if length(grad) > 0 # grad: nparams x nConstraints: ∂cj/∂xi = grad[i,j] fill!(grad, 0.0) end for j in 1:numConstraints nii = chii[j]; pii = anii[j] result[j] = nodeage[nii] - nodeage[pii] # jth constraint: cj ≤ 0 if length(grad) > 0 # nparams x nConstraints grad[nii, j] = 1. grad[pii, j] = -1. end end end end opt = NLopt.Opt(NLoptMethod,nparams) # :LD_MMA to use gradient # :LN_COBYLA for (non)linear constraits, :LN_BOBYQA for bound constraints NLopt.maxeval!(opt,1000) # max iterations NLopt.ftol_rel!(opt,ftolRel) NLopt.ftol_abs!(opt,ftolAbs) NLopt.xtol_rel!(opt,xtolRel) NLopt.xtol_abs!(opt,xtolAbs) # NLopt.maxtime!(opt, t::Real) NLopt.lower_bounds!(opt, zeros(nparams)) if ultrametric NLopt.inequality_constraint!(opt,ageConstraints,fill(0.0,numConstraints)) end counter = [0] function obj(x::Vector{Float64}, grad::Vector{Float64}) verbose && println("mismatch objective, BL = $(x)") counter[1] += 1 # update edge lengths or node ages if ultrametric # update na using x, in place for i in 1:nparams # na=0 at leaves already na[parind[i]] = x[i] end if forceMinorLength0 # set hybrid age to minor parent age for i in 1:net.numHybrids na[hybInd[i]] = na[hybParentInd[i]] # pre-order important end end else # not ultrametric: optimize branch lengths for i in 1:nparams # update network net.edge[parind[i]].length = x[i] end end # update distances in M, in place pairwiseTaxonDistanceMatrix!(M,net,na) ss = 0.0 # sum of squares between M and observed distances for i in 2:ntax; for j in 1:(i-1) ss += (M[tipind[i],tipind[j]]-D[i,j])^2 end; end if length(grad) > 0 # sum_ij 2 * dM_ij/dx_t * (M_ij-D_ij) for t in 1:nparams grad[t] = 0.0; end; for i in 2:ntax; for j in 1:(i-1); for t in 1:nparams G[tipind[i],tipind[j],parind[t]] != 0.0 || continue grad[t] += G[tipind[i],tipind[j],parind[t]] * (M[tipind[i],tipind[j]]-D[i,j]) end if ultrametric && forceMinorLength0 for i in 1:net.numHybrids # na[hybrid] set to na[minor parent] grad[hybGParentI[i]] += G[tipind[i],tipind[j],hybInd[i]] * (M[tipind[i],tipind[j]]-D[i,j]) end end end; end end return ss end NLopt.min_objective!(opt,obj) fmin, xmin, ret = NLopt.optimize(opt,par) # optimization here! verbose && println("got $(round(fmin, digits=5)) at $(round.(xmin, digits=5)) after $(counter[1]) iterations (return code $(ret))") return fmin,xmin,ret end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
57252
""" parsimonyBottomUpFitch!(node, states, score) Bottom-up phase (from tips to root) of the Fitch algorithm: assign sets of character states to internal nodes based on character states at tips. Polytomies okay. Assumes a *tree* (no reticulation) and correct isChild1 attribute. output: dictionary with state sets and most parsimonious score """ function parsimonyBottomUpFitch!(node::Node, possibleStates::Dict{Int,Set{T}}, parsimonyscore::Array{Int,1}) where {T} node.leaf && return # change nothing if leaf childrenStates = Set{T}[] # state sets for the 2 (or more) children for e in node.edge if e.node[e.isChild1 ? 1 : 2] == node continue; end # excluded parent edges only: assuming tree here child = getOtherNode(e, node) parsimonyBottomUpFitch!(child, possibleStates, parsimonyscore) if haskey(possibleStates, child.number) # false if missing data push!(childrenStates, possibleStates[child.number]) end end if length(childrenStates)==0 return; end # change nothing if no data below votes = Dict{T,Int}() # number of children that vote for a given state for set in childrenStates for i in set if haskey(votes,i) votes[i] += 1 else votes[i] = 1 end end end mv = maximum(values(votes)) filter!(p -> p.second==mv, votes) # keep states with max votes possibleStates[node.number] = Set(keys(votes)) parsimonyscore[1] += length(childrenStates) - mv # extra cost end """ parsimonyTopDownFitch!(node, states) Top-down phase (root to tips) of the Fitch algorithm: constrains character states at internal nodes based on the state of the root. Assumes a *tree*: no reticulation. output: dictionary with state sets """ function parsimonyTopDownFitch!(node::Node, possibleStates::Dict{Int,Set{T}}) where {T} for e in node.edge child = e.node[e.isChild1 ? 1 : 2] if child == node continue; end # exclude parent edges if child.leaf continue; end # no changing the state of tips commonState = intersect(possibleStates[node.number], possibleStates[child.number]) if !isempty(commonState) possibleStates[child.number] = Set(commonState) # restrain states to those with cost 0 end parsimonyTopDownFitch!(child, possibleStates) end return possibleStates # updated dictionary of sets of character states end """ parsimonySummaryFitch(tree, nodestates) summarize character states at nodes, assuming a *tree* """ function parsimonySummaryFitch(tree::HybridNetwork, nodestates::Dict{Int,Set{T}}) where {T} println("node number => character states on tree ", writeTopology(tree,di=true,round=true,digits=1)) for n in tree.node haskey(nodestates, n.number) || continue print(n.number) if n.name != "" print(" (",n.name,")"); end if n == tree.node[tree.root] print(" (root)"); end println(": ", sort(collect(nodestates[n.number]))) end end """ parsimonyDiscreteFitch(net, tipdata) Calculate the most parsimonious (MP) score of a network given a discrete character at the tips. The softwired parsimony concept is used: where the number of state transitions is minimized over all trees displayed in the network. Tip data can be given in a data frame, in which case the taxon names are to appear in column 1 or in a column named "taxon" or "species", and trait values are to appear in column 2 or in a column named "trait". Alternatively, tip data can be given as a dictionary taxon => trait. also return the union of all optimized character states at each internal node as obtained by Fitch algorithm, where the union is taken over displayed trees with the MP score. """ function parsimonyDiscreteFitch(net::HybridNetwork, tips::Dict{String,T}) where {T} # T = type of characters. Typically Int if data are binary 0-1 # initialize dictionary: node number -> admissible character states possibleStates = Dict{Int,Set{T}}() for l in net.leaf if haskey(tips, l.name) possibleStates[l.number] = Set(tips[l.name]) end end charset = union(possibleStates) # fixit # assign this set to all tips with no data directEdges!(net) # parsimonyBottomUpFitch! uses isChild1 attributes trees = displayedTrees(net, 0.0) # all displayed trees mpscore = Int[] # one score for each tree statesets = Dict{Int,Set{T}}[] # one state set dict per tree for tree in trees statedict = deepcopy(possibleStates) parsimonyscore = [0] # initialization, mutable parsimonyBottomUpFitch!(tree.node[tree.root], statedict, parsimonyscore) push!(mpscore, parsimonyscore[1]) push!(statesets, statedict) end mps = findmin(mpscore)[1] # MP score mpt = findall(x -> x==mps, mpscore) # indices of all trees with MP score statedictUnion = statesets[mpt[1]] # later: union over all MP trees # println("parsimony score: ", mps) for i in mpt # top down calculation for best trees only parsimonyTopDownFitch!(trees[i].node[trees[i].root], statesets[i]) parsimonySummaryFitch(trees[i], statesets[i]) if i == mpt[1] continue; end for n in keys(statesets[i]) if haskey(statedictUnion, n) # degree-2 nodes absent from trees union!(statedictUnion[n], statesets[i][n]) else statedictUnion[n] = statesets[i][n] end end # fixit: for each hybrid edge, count the number of MP trees that have it, # to return information on which hybrid edge is most parsimonious end return mps, statedictUnion end function parsimonyDiscreteFitch(net::HybridNetwork, dat::DataFrame) i = findfirst(isequal(:taxon), DataFrames.propertynames(dat)) if i===nothing i = findfirst(isequal(:species), DataFrames.propertynames(dat)); end if i===nothing i=1; end # first column if no column named "taxon" or "species" j = findfirst(isequal(:trait), DataFrames.propertynames(dat)) if j===nothing j=2; end if i==j error("""expecting taxon names in column 'taxon', or 'species' or column 1, and trait values in column 'trait' or column 2.""") end tips = Dict{String,eltype(dat[!,j])}() for r in 1:nrow(dat) if ismissing(dat[r,j]) continue; end tips[dat[r,i]] = dat[r,j] end parsimonyDiscreteFitch(net,tips) end """ parsimonyBottomUpSoftwired!(node, blobroot, states, w, scores) Computing the MP scores (one for each assignment of the root state) of a swicthing as described in Algorithm 1 in the following paper: Fischer, M., van Iersel, L., Kelk, S., Scornavacca, C. (2015). On computing the Maximum Parsimony score of a phylogenetic network. SIAM J. Discrete Math., 29(1):559-585. Assumes a *switching* (ie correct `fromBadDiamondI` field) and correct isChild1 field. The field `isExtBadTriangle` is used to know which nodes are at the root of a blob. """ function parsimonyBottomUpSoftwired!(node::Node, blobroot::Node, nchar::Integer, w::AbstractArray, parsimonyscore::AbstractArray) #println("entering with node $(node.number)") parsimonyscore[node.number,:] = w[node.number,:] # at all nodes to re-initialize between switchings if node.leaf || (node.isExtBadTriangle && node != blobroot) return nothing # isExtBadTriangle=dummy leaf: root of another blob end for e in node.edge if (e.hybrid && e.fromBadDiamondI) || getchild(e) == node continue; end # fromBadDiamondI= edge switched off son = getchild(e) parsimonyBottomUpSoftwired!(son, blobroot, nchar, w, parsimonyscore) end for s in 1:nchar for e in node.edge if (e.hybrid && e.fromBadDiamondI) || getchild(e) == node continue; end son = getchild(e) bestMin = Inf # best score from to this one child starting from s at the node for sf in 1:nchar # best assignement for the son minpars = parsimonyscore[son.number,sf] if s != sf minpars +=1 # could be variable cost of change delta(sf,s) end bestMin = min(minpars, bestMin) end parsimonyscore[node.number,s] += bestMin # add best assignement for the son to the PS of the parent end end #println("end of node $(node.number)") #@show parsimonyscore return nothing end """ parsimonySoftwired(net, tipdata) parsimonySoftwired(net, species, sequences) Calculate the most parsimonious (MP) score of a network given a discrete character at the tips. The softwired parsimony concept is used: where the number of state transitions is minimized over all trees displayed in the network. Data can given in one of the following: - `tipdata`: data frame for a single trait, in which case the taxon names are to appear in column 1 or in a column named "taxon" or "species", and trait values are to appear in column 2 or in a column named "trait". - `tipdata`: dictionary taxon => state, for a single trait. - `species`: array of strings, and `sequences`: array of sequences, in the order corresponding to the order of species names. ## algorithm The dynamic programming algorithm by Fischer et al. (2015) is used. The function loops over all the displayed subtrees within a blob (biconnected component), so its complexity is of the order of `n * m * c^2 * 2^level` where `n` is the number of tips, `m` the number of traits, `c` the number of states, and `level` is the level of the network: the maximum number of hybridizations within a blob. See [`parsimonyGF`](@ref) for a different algorithm, slower but extendable to other parsimony criteria. ## references 1. Fischer, M., van Iersel, L., Kelk, S., Scornavacca, C. (2015). On computing the Maximum Parsimony score of a phylogenetic network. SIAM J. Discrete Math., 29(1):559-585. """ function parsimonySoftwired(net::HybridNetwork, tips::Dict{String,T}) where {T} # T = type of characters. Typically Int if data are binary 0-1 species = String[] dat = Vector{T}[] for (k,v) in tips push!(species, k) push!(dat, [v]) end parsimonySoftwired(net, species, dat) end function parsimonySoftwired(net::HybridNetwork, dat::DataFrame) i = findfirst(isequal(:taxon), DataFrames.propertynames(dat)) if i===nothing i = findfirst(isequal(:species), DataFrames.propertynames(dat)); end if i===nothing i=1; end # first column if no column named "taxon" or "species" j = findfirst(isequal(:trait), DataFrames.propertynames(dat)) if j===nothing j=2; end if i==j error("""expecting taxon names in column 'taxon', or 'species' or column 1, and trait values in column 'trait' or column 2.""") end innet = findall(in(tipLabels(net)), dat[i]) # species in the network species = dat[innet, i] tips = dat[j][innet] indna = findall(ismissing, tips) # species with missing data deleteat!(species, indna) deleteat!(tips, indna) parsimonySoftwired(net,tips) end function parsimonySoftwired(net::HybridNetwork, species::Array{String}, sequenceData::AbstractArray) resetNodeNumbers!(net) nsites = length(sequenceData[1]) nspecies = length(species) # no check to see if == length(sequenceData) nchar = 0 # this is to allocate the needed memory for w and # parsimonyscore matrices below. Only the first few columns will be # used for sites that have fewer than the maximum number of states. for i in 1:nsites nchar = max(nchar, length(unique([s[i] for s in sequenceData]))) end w = zeros(Float64,(length(net.node), nchar)) parsimonyscore = zeros(Float64,(length(net.node), nchar)) tips = Dict{String, typeof(sequenceData[1][1])}() # to re-use memory later (?) checkGap = eltype(sequenceData) == BioSequences.BioSequence sequenceType = eltype(sequenceData[1]) blobroots, majorEdges, minorEdges = blobInfo(net) # calls directEdges!: sets isChild1 score = 0.0 #allscores = Float64[] for isite in 1:nsites for sp in 1:nspecies nu = sequenceData[sp][isite] # nucleotide if checkGap && (isgap(nu) || (sequenceType==BioSymbols.DNA && nu == BioSymbols.DNA_N) || (sequenceType==BioSymbols.RNA && nu == BioSymbols.RNA_N) || (sequenceType==BioSymbols.AminoAcid && nu == BioSymbols.AA_N) ) delete!(tips, species[sp]) else tips[species[sp]] = nu # fixit: allow for ambiguous nucleotides? end end # tips now contains data for 1 site charset = union(values(tips)) nchari = length(charset) # possibly < nchar nchari > 0 || continue initializeWeightsFromLeavesSoftwired!(w, net, tips, charset) # data are now in w fill!(parsimonyscore, 0.0) # reinitialize parsimonyscore too # @show tips; @show w for bcnumber in 1:length(blobroots) r = blobroots[bcnumber] nhyb = length(majorEdges[bcnumber]) # println("site $isite, r.number = $(r.number), nhyb=$(nhyb)") mpscoreSwitchings = Array{Float64}(undef, 2^nhyb, nchari) # grabs memory # fixit: move that outside to avoid grabbing memory over and over again iswitch = 0 perms = nhyb == 0 ? [()] : Iterators.product([[true, false] for i=1:nhyb]...) for switching in perms # next: modify the `fromBadDiamondI` of hybrid edges in the blob: # switching[h] = pick the major parent of hybrid h if true, pick minor if false iswitch += 1 #@show switching for h in 1:nhyb majorEdges[bcnumber][h].fromBadDiamondI = switching[h] minorEdges[bcnumber][h].fromBadDiamondI = !switching[h] end parsimonyBottomUpSoftwired!(r, r, nchari, w, parsimonyscore) # updates parsimonyscore for s in 1:nchari mpscoreSwitchings[iswitch,s] = parsimonyscore[r.number,s] end end for i in 1:nchari # add best assignement for the son to the PS of the parent w[r.number,i] += minimum(mpscoreSwitchings[:,i]) end bcnumber+=1 end bestMin = minimum(w[net.node[net.root].number, 1:nchari]) #if bestMin>0 println("site $isite, score $bestMin"); end #push!(allscores, bestMin) score += bestMin end return score #, allscores end """ initializeWeightsFromLeavesSoftwired!(w, net, tips, charset) Modify weight in w: to Inf for w[n, s] if the "tips" data has a state different from s at node number n. Assumes that w was initialized to 0 for the leaves. """ function initializeWeightsFromLeavesSoftwired!(w::AbstractArray, net::HybridNetwork, tips, charset) fill!(w, 0.0) for node in net.node node.leaf || continue haskey(tips, node.name) || continue for i in 1:length(charset) s = charset[i] if s != tips[node.name] w[node.number,i] = Inf end end #@show w[node.number,:] end end """ readFastaToArray(filename::AbstractString, sequencetype=BioSequences.LongDNA{4}) Read a fasta-formatted file. Return a tuple `species, sequences` where `species` is a vector of Strings with identifier names, and `sequences` is a vector of BioSequences, each of type `sequencetype` (DNA by default). **Warnings**: - assumes a *semi-sequential* format, *not interleaved*. More specifically, each taxon name should appear only once. For this one time, the corresponding sequence may be broken across several lines though. - fails if all sequences aren't of the same length """ function readFastaToArray(filename::AbstractString, sequencetype=BioSequences.LongDNA{4}) reader = FASTX.FASTA.Reader(open(filename)) sequences = Array{BioSequences.BioSequence}(undef, 0) species = String[] for record in reader push!(sequences, FASTX.sequence(sequencetype, record)) push!(species, FASTX.identifier(record)) end seqlengths = [length(s) for s in sequences] # values(dat) nsites, tmp = extrema(seqlengths) nsites == tmp || error("sequences not of same lengths: from $nsites to $tmp sites") return species, sequences end """ readfastatodna(filename::String, countPatterns=false::Bool) Read a fasta file to a dataframe containing a column for each site. If `countPatterns` is true, calculate weights and remove identical site patterns to reduce matrix dimension. Return a tuple containing: 1. data frame of BioSequence DNA sequences, with taxon names in column 1 followed by a column for each site pattern, in columns 2-npatterns; 2. array of weights, one weight for each of the site columns. The length of the weight vector is equal to npatterns. **Warning**: assumes a *semi-sequential* format, *not interleaved*, where each taxon name appears only once. For this one time, the corresponding sequence may be broken across several lines though. """ function readfastatodna(fastafile::String, countPatterns=false::Bool) reader = FASTX.FASTA.Reader(open(fastafile)) siteList = Vector{Vector}(undef, 0) # vector of vectors: one for each site species = String[] firstspecies = Bool(true) nsites = 0 for record in reader #by species (row) myseq = FASTX.sequence(BioSequences.LongDNA{4}, record) seqlen = length(myseq) if firstspecies nsites = seqlen for _ in 1:nsites # initialize an array for each site push!(siteList, Vector{BioSequences.DNA}(undef, 0)) end firstspecies = false end push!(species, FASTA.identifier(record)) seqlen == nsites || error("sequences of different length: current sequences is ", seqlen, " long while first sequence is ", nsites, " long") for site in 1:nsites push!(siteList[site], myseq[site]) end end # calculate weights and remove matching site patterns to reduce dimension of siteList weights = ones(Float64, nsites) if countPatterns for c in nsites:-1:1 target = siteList[c] for comparison in 1:(c-1) if target == siteList[comparison] weights[comparison] += weights[c] #add c's weight to comparison's weight deleteat!(siteList, c) # delete c in siteList deleteat!(weights, c) #delete c in weights break end end end end # column names: x1 through xn where n = # distinct sites dat = DataFrame(siteList, ["x$i" for i in 1:length(siteList)], copycols=false) insertcols!(dat, 1, :taxon => species) return (dat, weights) end """ readCSVtoArray(dat::DataFrame) readCSVtoArray(filename::String) Read a CSV table containing both species names and data, create two separate arrays: one for the species names, a second for the data, in a format that [`parsimonyGF`](@ref) needs. Warning: - it will try to find a column 'taxon' or 'species' for the taxon names. If none found, it will assume the taxon names are in column 1. - will use all other columns as characters """ function readCSVtoArray(dat::DataFrame) i = findfirst(isequal(:taxon), DataFrames.propertynames(dat)) if i===nothing i = findfirst(isequal(:species), DataFrames.propertynames(dat)); end if i===nothing @warn "expecting taxon names in column 'taxon', or 'species', so will assume column 1" i = 1 end species = String[] for d in dat[!,i] push!(species,string(d)) end ind = deleteat!(collect(1:size(dat,2)),i) ##character columns seq = Vector{Vector{Any}}(undef, 0) for j=1:size(dat,1) ##for every taxon: v = Vector{Any}(undef, 0) for ii in ind if ismissing(dat[j,ii]) push!(v,missing) else push!(v,dat[j,ii]) end end push!(seq,v) end return species,seq end function readCSVtoArray(filename::String) dat = DataFrame(CSV.File(filename); copycols=false) readCSVtoArray(dat) end """ parsimonyGF(net, tip_dictionary, criterion=:softwired) parsimonyGF(net, species, sequenceData, criterion=:softwired) Calculate the most parsimonious score of a network given discrete characters at the tips using a general framework (Van Iersel et al. 2018) allowing for various parsimony criteria: softwired (default), hardwired, parental etc. Only softwired is implemented at the moment. Data can given in one of the following: - `tipdata`: data frame for a single trait, in which case the taxon names are to appear in column 1 or in a column named "taxon" or "species", and trait values are to appear in column 2 or in a column named "trait". - `tipdata`: dictionary taxon => state, for a single trait. - `species`: array of strings, and `sequences`: array of sequences, in the order corresponding to the order of species names. ## algorithm The complexity of the algorithm is exponential in the level of the network, that is, the maximum number of hybridizations in a single blob, or biconnected component (Fischer et al. 2015). The function loops over all the state assignments of the minor parent of each hybrid node within a blob, so its complexity is of the order of `n * m * c^2 * c^level` where `n` is the number of tips, `m` the number of traits and `c` the number of states. See [`parsimonySoftwired`](@ref) for a faster algorithm, but solving the softwired criterion only. ## references 1. Leo Van Iersel, Mark Jones, Celine Scornavacca (2017). Improved Maximum Parsimony Models for Phylogenetic Networks, Systematic Biology, (https://doi.org/10.1093/sysbio/syx094). 2. Fischer, M., van Iersel, L., Kelk, S., Scornavacca, C. (2015). On computing the Maximum Parsimony score of a phylogenetic network. SIAM J. Discrete Math., 29(1):559-585. Use the recursive helper function [`parsimonyBottomUpGF!`](@ref). Use the fields `isChild1`, `isExtBadTriangle` to know which nodes are at the root of a blob, and `fromBadDiamondI` to know which edges are cut (below the minor parent of each hybrid). """ function parsimonyGF(net::HybridNetwork, tips::Dict{String,T}, criterion=:softwired::Symbol) where {T} # T = type of characters. Typically Int if data are binary 0-1 species = String[] dat = Vector{T}[] for (k,v) in tips push!(species, k) push!(dat, [v]) end parsimonyGF(net, species, dat, criterion) end function parsimonyGF(net::HybridNetwork, species::Array{String}, sequenceData::AbstractArray, criterion=:softwired::Symbol) resetNodeNumbers!(net) # direct edges and checks pre-order by default rootnumber = net.node[net.root].number nsites = length(sequenceData[1]) nspecies = length(species) # no check to see if == length(sequenceData) nstates = 0 # this is to allocate the needed memory for w and # parsimonyscore matrices below. Only the first few columns will be # used for sites that have fewer than the maximum number of states. for i in 1:nsites nstatesi = length(unique([s[i] for s in sequenceData])) if nstates < nstatesi nstates = nstatesi end end if criterion == :softwired # lineage states: ∅, 1, 2, 3, ..., nstates lineagestate = [Set{Int}()] # first element: empty set ∅ for i in 1:nstates push!(lineagestate, Set(i)) end nchar = length(lineagestate) allowedAtRoot = 2:nchar # ∅ is not allowed at root of network costfunction = function(finalset, parentsets) # parentsets = array of sets: 0, 1, 2 if length(finalset) > sum([length(s) for s in parentsets]) return Inf else # calculate final set minus (union of parent sets) missingstates = finalset for s in parentsets missingstates = setdiff(missingstates, s) end return length(missingstates) end end costmatrix1 = Array{Float64}(undef, nchar,nchar) # i = 1 parent set, j = final set for i in 1:nchar for j in 1:nchar costmatrix1[i,j] = costfunction(lineagestate[j], [lineagestate[i]]) end end costmatrix2 = Vector{Array{Float64}}(undef, nchar) # costmatrix2[k][i,j]: from parents k,i to final set j for k in 1:nchar costmatrix2[k] = Array{Float64}(undef, nchar,nchar) for i in 1:nchar for j in 1:nchar costmatrix2[k][i,j] = costfunction(lineagestate[j], [lineagestate[i], lineagestate[k]]) end end end elseif criterion == :parental error("parental parsimony not implemented yet") # costfunctionP = function(finalset, parentsets) # parentsets = array of sets: 0, 1, 2 # # Input: node v in network N with at most one parent u not in P, set S in Y, set Sprime # # in Y, assignment fprime. # # Return: cost on eduges entering v for any lineage function f that extends fprime and # # assigns f(u) = S (if u exists) and f(v) = Sprime # if node v is root of Network N # return 0 # else # if length(finalset) > sum([length(s) for s in parentsets]) # return Inf # else # calculate final set minus (union of parent sets) # missingstates = finalset # for s in parentsets # missingstates = setdiff(missingstates, s) # end # return length(missingstates) # end # end # for fprime in set of fprimes # for i in 1:r # for each vertex u (in reverse topology ordering) and s in Y # if u is a leaf in X # H[u,S] = 0*(S==alpha(u)) + inf(S!=alpha(u)) # end # if u in P # H[u,S] = 0*(S==fprime(u)) + inf(S!=fprime(u)) # end # if u has one child v in T # H[u,S] = min(H(v, Sprime)) + costfunctionP(v, s, sprime, fprime) # end # if u has two children v1,v2 in Ti # H[u,S] = min(H(v1, Sprime)) + costfunctionP(v1, s, sprime, fprime) + # min(H(v2, Sprime)) + costfunctionP(v2, s, sprime, fprime) # end # end # end # end # optfprime = min(H[rho1, (j)]) + min(costfunctionP(rho1, null, S, fprime) + H(rho[i], S)) # #note: its not clear where we optimize fprime ^ # return optfprime else error("criterion $criterion unknown") end w = zeros(Float64,(length(net.node), nchar)) parsimonyscore = zeros(Float64,(length(net.node), nchar)) tips = Dict{String, typeof(sequenceData[1][1])}() # to re-use memory later (?) checkGap = eltype(sequenceData) == BioSequences.BioSequence sequenceType = eltype(sequenceData[1]) blobroots, majorEdges, minorEdges = blobInfo(net) # calls directEdges!: sets isChild1 # fixit: use trivial biconnected components, and compare running time # pick 1 parent node (the minor parent arbitrarily) for each hybrid, then # "cut" both children edges of that parent: mark its `fromBadDiamondI` = false for e in net.edge e.fromBadDiamondI = false # don't cut by default end guessedparent = Vector{Node}[] for melist in minorEdges # minor edge list for one single blob + loop over blobs guessedparentBlob = Node[] for e in melist p = getparent(e) if p ∉ guessedparentBlob push!(guessedparentBlob, p) for e2 in p.edge p == getparent(e2) || continue e2.fromBadDiamondI = true # cut the edge: not followed in recursive call end end end push!(guessedparent, guessedparentBlob) end maxguessedParents = maximum([length(me) for me in guessedparent]) guessStates = Vector{Float64}(undef, nchar) # grabs memory # will contain the best score for a blob root starting at some state s, # from best guess so far (different guesses are okay for different s) # determine which nodes are the root of trees after we cut off edges # below guessed parents. For this, at each node, set its # inCycle = 0 if the node has (at least) 1 non-cut edge, and # inCycle = # of detached parents if the node has detached parents only. # Do this now to avoid re-doing it at each site. # `inCycle` was used earlier to find blobs. for n in net.node n.inCycle=0; end # first: calculate inCycle = # of detached parents for e in net.edge e.fromBadDiamondI || continue # to next edge if current edge not cut n = getchild(e) n.inCycle += 1 end # second: make inCycle = 0 if node has a non-detached parent for n in net.node n.inCycle > 0 || continue # to next node if inCycle = 0 already for e in n.edge n == getchild(e) || continue !e.fromBadDiamondI || continue n.inCycle = 0 # if e parent of n and e not cut: make inCycle 0 break end end score = 0.0 #allscores = Float64[] for isite in 1:nsites for sp in 1:nspecies nu = sequenceData[sp][isite] # nucleotide if checkGap && (isgap(nu) || (sequenceType==BioSymbols.DNA && nu == BioSymbols.DNA_N) || (sequenceType==BioSymbols.RNA && nu == BioSymbols.RNA_N) || (sequenceType==BioSymbols.AminoAcid && nu == BioSymbols.AA_N) ) delete!(tips, species[sp]) else tips[species[sp]] = nu # fixit: allow for ambiguous nucleotides? end end # tips now contains data for 1 site stateset = union(values(tips)) nstatesi = length(stateset) # possibly < nstates nstatesi > 0 || continue if criterion == :softwired nchari = nstatesi + 1 end initializeWeightsFromLeaves!(w, net, tips, stateset, criterion) # data are now in w #fill!(parsimonyscore, 0.0) # reinitialize parsimonyscore too # @show tips; @show w for bcnumber in 1:length(blobroots) r = blobroots[bcnumber] nhyb = length(majorEdges[bcnumber]) #println("site $isite, r.number = $(r.number), nhyb=$(nhyb)") firstguess = true gplen = length(guessedparent[bcnumber]) perms = gplen == 0 ? [()] : Iterators.product([1:nchari for i=1:gplen]...) for guesses in perms #@show guesses for pind in 1:nhyb p = guessedparent[bcnumber][pind] # detached parent of hybrid with index pind in blob number pcnumber # fixit: memory greedy below. check what was changed only. for s in 1:nchari w[p.number, s] = Inf end w[p.number, guesses[pind]] = 0.0 end parsimonyBottomUpGF!(r, r, nchari, w, parsimonyscore, costmatrix1, costmatrix2) # recursion above: updates parsimonyscore #@show nchari if firstguess for s in 1:nchari guessStates[s] = parsimonyscore[r.number,s] end firstguess = false else for s in 1:nchari if guessStates[s] > parsimonyscore[r.number,s] guessStates[s] = parsimonyscore[r.number,s] end end end #@show guessStates end for i in 1:nchari # add best assignement for the son to the PS of the parent w[r.number,i] += guessStates[i] end bcnumber+=1 end bestMin = Inf for s in allowedAtRoot s <= nchari || break if bestMin > w[rootnumber, s] bestMin = w[rootnumber, s] end end #if bestMin>0 println("site $isite, score $bestMin"); end #push!(allscores, bestMin) score += bestMin end return score #, allscores end """ initializeWeightsFromLeaves!(w, net, tips, stateset, criterion) Modify weight in w: to Inf for w[n, i] if the "tips" data has a state different from the lineage state of index i at node number n. Assumes that w was initialized to 0 for the leaves. criterion: should be one of `:softwired`, `:parental` or `:hardwired`. - softwired parsimony: lineage states are in this order: ∅,{1},{2},{3},...,{nstates} """ function initializeWeightsFromLeaves!(w::AbstractArray, net::HybridNetwork, tips, stateset, criterion::Symbol) fill!(w, 0.0) if criterion == :softwired nchar = length(stateset) + 1 elseif criterion == :parental error("parental parsimony not implemented yet") else error("unknown criterion: $criterion") end for node in net.node node.leaf || continue w[node.number,1] = Inf # ∅ comes first haskey(tips, node.name) || continue for i in 2:nchar s = stateset[i-1] # state s correspond to lineage at index s+1 if s != tips[node.name] w[node.number,i] = Inf end end #@show w[node.number,:] end end """ parsimonyBottomUpGF!(node, blobroot, nchar, w, scores, costmatrix1, costmatrix2) Compute the MP scores (one for each assignment of the blob root state) given the descendants of a blob, conditional on the states at predefined parents of hybrids in the blobs (one parent per hybrid) as described in Leo Van Iersel, Mark Jones, Celine Scornavacca (2017). Improved Maximum Parsimony Models for Phylogenetic Networks, Systematic Biology, (https://doi.org/10.1093/sysbio/syx094). Assumes a set of state *guesses*, ie correct initialization of `w` for predefined hybrid parents, and correct `fromBadDiamondI` field for the children edges of these predefined parents. `fromBadDiamondI` is true for edges that are cut. The field `isExtBadTriangle` is used to know which nodes are at the root of a blob. The field `isChild1` is used (and assumed correct). Field `inCycle` is assumed to store the # of detached parents (with guessed states) - `nchar`: number of characters considered at internal lineages. For softwired parsimony, this is # states + 1, because characters at internal nodes are ∅, {1}, {2}, etc. For parental parsimony, this is 2^#states -1, because characters are all sets on {1,2,...} except for the empty set ∅. - `costmatrix1`[i,j] and `costmatrix2`[k][i,j]: 2d array and vector of 2d arrays containing the cost of going to character j starting from character i when the end node has a single parent, or the cost of a child node having character j when its parents have characters k and i. These cost matrices are pre-computed depending on the parsimony criterion (softwired, hardwired, parental etc.) used by [`parsimonyGF`](@ref). """ function parsimonyBottomUpGF!(node::Node, blobroot::Node, nchar::Integer, w::AbstractArray, parsimonyscore::AbstractArray, costmatrix1::AbstractArray, costmatrix2::AbstractArray) #println("entering with node $(node.number)") parsimonyscore[node.number,1:nchar] = w[node.number,1:nchar] # at all nodes to re-initialize between guesses if !node.leaf && (!node.isExtBadTriangle || node == blobroot) # isExtBadTriangle=dummy leaf: root of another blob for e in node.edge # post-order traversal according to major tree: detached edges were minor. if !e.isMajor || getchild(e) == node continue; end # Even if we didn't visit one parent (yet), son = getchild(e) # that parent is a minor parent with an assigned guessed state. parsimonyBottomUpGF!(son, blobroot, nchar, w, parsimonyscore, costmatrix1, costmatrix2) end # check to see if "node" has guessed value: by checking to see if all its children edges were cut cutparent = false for e in node.edge if getchild(e) == node continue; end if e.fromBadDiamondI # if true: one child edge is cut, so all are cut cutparent = true break end end if !cutparent # look at best assignment of children, to score each assignment at node for e in node.edge # avoid edges that were cut: those for which fromBadDiamondI is true son = getchild(e) if son == node continue; end bestpars = [Inf for s in 1:nchar] # best score, so far, for state s at node. # calculate cost to go from each s (and from parents' guesses, stored in w) to son state: if son.hybrid # find potential other parent of son, detached with guessed states p2 = getparentminor(son) k = findfirst(isequal(0.0), w[p2.number, 1:nchar]) # guess made for parent p2 for sfinal in 1:nchar pars = parsimonyscore[son.number, sfinal] .+ costmatrix2[k][1:nchar,sfinal] for s in 1:nchar if bestpars[s] > pars[s] bestpars[s] = pars[s] end end end else # son has no guessed parent: has only 1 parent: "node" for sfinal in 1:nchar pars = parsimonyscore[son.number, sfinal] .+ costmatrix1[1:nchar,sfinal] for s in 1:nchar if bestpars[s] > pars[s] bestpars[s] = pars[s] end end end end parsimonyscore[node.number,1:nchar] .+= bestpars # add score from best assignement for this son end end end # of if: not leaf, not root of another blob #println("almost the end of node $(node.number)") #@show parsimonyscore #@show w node != blobroot || return nothing # if blob root has detached parents only, these are paid for in the blob # in which this blob root is a leaf. node.inCycle > 0 || return nothing # inCycle = # of detached parents # if we get here, it means that "node" is not root of current blob, but # is root of a tree after detaching all guessed parents from their children. # pay now for re-attaching the guessed parents to node cost = 0.0 # variable external to 'for' loops below if node.inCycle == 1 # 1 detached parent, no non-detached parents for e in node.edge par = getparent(e) if par == node continue; end # now 'par' is the single detached parent k = findfirst(isequal(0.0), w[par.number, 1:nchar]) # guess at parent cost = minimum(parsimonyscore[node.number, 1:nchar] + costmatrix1[k,1:nchar]) #println("node $(node.number), parent $(par.number), guess k=$k") break # out of for loop end else # node.inCycle should be 2: 2 detached parents k1 = 0 # guess made on first detached parent for e in node.edge par = getparent(e) if par == node continue; end # now 'par' is one of the 2 guessed parents if k1 == 0 k1 = findfirst(isequal(0.0), w[par.number, 1:nchar]) # guess at 1st parent else k2 = findfirst(isequal(0.0), w[par.number, 1:nchar]) # guess at 2nd parent cost = minimum(parsimonyscore[node.number, 1:nchar] + costmatrix2[k1][k2,1:nchar]) break end end end # now 'cost' is up-to-date for s in 1:nchar parsimonyscore[blobroot.number, s] += cost end #@show parsimonyscore #@show w #println("end of node $(node.number)") return nothing end ## -------------------------------------------------- ## Search for most parsimonious network ## start the search from (or near) topology currT, ## .loglik will save now parsimony score ## fixit: we are using the functions for level1 network, we need to include level-k networks ## this will be done by changing the current proposedTop! function ## the current search/moves functions are the same for snaq, so they need a "good" semi-directed ## network, so currently we propose new topology from this set of networks, and simply root to ## compute the parsimony score (we do not keep rooted networks as the search objects), ## that is, newT and currT are unrooted through the whole algorithm (because computing the parsimony destroys inCycle) ## criterion=softwired by default ## at this stage, currT is compatible with the outgroup, but still unrooted (for moves functions to work) ## tolAbs: could be set to 0.1 and removed from list of arguments. up to 0.5 should work, ## because parsimony scores are integers, but Float64 to extend cost function later perhaps """ Road map for various functions behind maxParsimonyNet maxParsimonyNet maxParsimonyNetRun1 maxParsimonyNetRun1! All return their optimized network. Only maxParsimonyNet returns a rooted network (though all functions guarantee that the returned networks agree with the outgroup). - maxParsimonyNet calls maxParsimonyNetRun1 per run, after a read(write(.)) of the starting network (to ensure level-1 and semi-directedness). - maxParsimonyNetRun1 will make a copy of the topology, and will call findStartingTopology! to modify the topology according to random NNI/move origin/move target moves. It then calls maxParsimonyNetRun1! on the modified network - maxParsimonyNetRun1! proposes new network with various moves (same moves as snaq), and stops when it finds the most parsimonious network, using [`parsimonyGF`](@ref PhyloNetworks.parsimonyGF). None of these functions allow for multiple alleles yet. Note that the search algorithm keeps two HybridNetworks at a time: currT (current topology) and newT (proposed topology). Both are kept unrooted (semi-directed), otherwise the moves in proposedTop! function fail. We only root the topologies to calculate the parsimony, so we create a rooted copy (currTr, newTr) to compute parsimony score in this copied topology. We do not root and calculate parsimony score in the original HybridNetworks objects (currT,newT) because the computation of the parsimony score overwrites the inCycle attribute of the Nodes, which messes with the search moves. Extensions: - other criteria: hardwired, parental (only softwired implemented now) - remove level-1 restriction: this will involve changing the proposedTop! function to use rSPR or rNNI moves (instead of the level-1 moves coded for snaq!). We need: - functions for rSPR and rNNI moves - create new proposedTop! function (proposedRootedTop?) to choose from the rSPR/rNNI/other moves - have the search in maxParsimonuNetRun1! to have rooted currT and rooted newT, instead of keeping semi-directed objects (currT, newT), only to root for the parsimony score (currTr, newTr) - outgroup is currently String or Node number, but it would be good if it allowed Edge number as an option too. Not sure best way to distinguish between Node number and Edge number, which is why left as Node number for now. """ function maxParsimonyNetRun1!(currT::HybridNetwork, tolAbs::Float64, Nfail::Integer, df::DataFrame, hmax::Integer, logfile::IO, writelog::Bool, outgroup::Union{AbstractString,Integer}, criterion=:softwired::Symbol) tolAbs >= 0 || error("tolAbs must be greater than zero: $(tolAbs)") Nfail > 0 || error("Nfail must be greater than zero: $(Nfail)") @debug begin printEverything(currT); "printed everything" end CHECKNET && checkNet(currT) count = 0 movescount = zeros(Int,18) #1:6 number of times moved proposed, 7:12 number of times success move (no intersecting cycles, etc.), 13:18 accepted by parsimony score movesfail = zeros(Int,6) #count of failed moves for current topology failures = 0 stillmoves = true Nmov = zeros(Int,6) species, traits = readCSVtoArray(df) currTr = deepcopy(currT) rootatnode!(currTr,outgroup) currT.loglik = parsimonyGF(currTr,species,traits,criterion) absDiff = tolAbs + 1 newT = deepcopy(currT) writelog && write(logfile, "\nBegins heuristic search of most parsimonious network------\n") while absDiff > tolAbs && failures < Nfail && stillmoves count += 1 calculateNmov!(newT,Nmov) move = whichMove(newT,hmax,movesfail,Nmov) if move != :none newT0 = deepcopy(newT) ## to go back if proposed topology conflicts with the outgroup flag = proposedTop!(move,newT,true, count,10, movescount,movesfail,false) #N=10 because with 1 it never finds an edge for nni newTr = deepcopy(newT) ##rooted version only to compute parsimony try rootatnode!(newTr,outgroup) catch flag = false end if flag #no need else in general because newT always undone if failed, but needed for conflicts with root @debug "successful move and correct root placement" accepted = false newT.loglik = parsimonyGF(newTr,species,traits,criterion) accepted = (newT.loglik < currT.loglik && abs(newT.loglik-currT.loglik) > tolAbs) ? true : false #newT better parsimony score: need to check for error or keeps jumping back and forth if accepted absDiff = abs(newT.loglik - currT.loglik) currT = deepcopy(newT) failures = 0 movescount[move2int[move]+12] += 1 movesfail = zeros(Int,6) #count of failed moves for current topology else failures += 1 movesfail[move2int[move]] += 1 newT = deepcopy(currT) end else @debug "unsuccessful move or incorrect root placement" newT = newT0 ## not counting errors in outgroup as failures, maybe we should end else stillmoves = false end end assignhybridnames!(newT) if absDiff <= tolAbs writelog && write(logfile,"\nSTOPPED by absolute difference criteria") elseif !stillmoves writelog && write(logfile,"\nSTOPPED for not having more moves to propose: movesfail $(movesfail), Nmov $(Nmov)") else writelog && write(logfile,"\nSTOPPED by number of failures criteria") end writelog && write(logfile,"\nEND: found minimizer topology at step $(count) (failures: $(failures)) with parsimony score=$(round(newT.loglik, digits=5))") writelog && printCounts(movescount,zeros(Int,13),logfile) ## zeroes in lieu of movesgamma, not used in parsimony setBLGammaParsimony!(newT) return newT end ## find the maximum parsimony network; ## transform the starting topology first ## does not allow multiple alleles @doc (@doc maxParsimonyNetRun1!) maxParsimonyNetRun1 function maxParsimonyNetRun1(currT0::HybridNetwork, df::DataFrame, Nfail::Integer, tolAbs::Float64, hmax::Integer,seed::Integer,logfile::IO, writelog::Bool, probST::Float64, outgroup::Union{AbstractString,Integer}, criterion=:softwired::Symbol) Random.seed!(seed) currT = findStartingTopology!(currT0, probST, false,writelog, logfile, outgroup=outgroup) net = maxParsimonyNetRun1!(currT, tolAbs, Nfail, df, hmax,logfile,writelog, outgroup, criterion) return net end ## find the most parsimonious network over multiple runs ## no multiple alleles for now; ## if rootname not defined, it does not save output files ## fixit: now it only works if currT0 is tree, or level-1 network ## also, throws an error if outgroup not compatible with starting network ## (instead of choosing another root) """ maxParsimonyNet(T::HybridNetwork, df::DataFrame) Search for the most parsimonious network (or tree). A level-1 network is assumed. `df` should be a data frame containing the species names in column 1, or in a column named `species` or `taxon`. Trait data are assumed to be in all other columns. The search starts from topology `T`, which can be a tree or a network with no more than `hmax` hybrid nodes (see optional arguments below for `hmax`). Output: - estimated network in file `.out` (also in `.log`): best network overall and list of networks from each individual run. - if any error occurred, file `.err` provides information (seed) to reproduce the error. Optional arguments include - hmax: maximum number of hybridizations allowed (default 1) - runs: number of starting points for the search (default 10); each starting point is `T` with probability `probST`=0.3 or a modification of `T` otherwise (using a NNI move, or a hybrid edge direction change) - Nfail: number of failures (proposed networks with equal or worse score) before the search is aborted. 75 by default: this is quite small, which is okay for a first trial. Larger values are recommended. - outgroup: outgroup taxon. It can be a taxon name (String) or Node number (Integer). If none provided, or if the outgroup conflicts the starting topology, the function returns an error - filename: root name for the output files. Default is "mp". If empty (""), files are *not* created, progress log goes to the screen only (standard out). - seed: seed to replicate a given search - criterion: parsimony score could be hardwired, softwired (default) or parental. Currently, only softwired is implemented # References 1. Leo Van Iersel, Mark Jones, Celine Scornavacca (2017). Improved Maximum Parsimony Models for Phylogenetic Networks, Systematic Biology, (https://doi.org/10.1093/sysbio/syx094). 2. Fischer, M., van Iersel, L., Kelk, S., Scornavacca, C. (2015). On computing the Maximum Parsimony score of a phylogenetic network. SIAM J. Discrete Math., 29(1):559-585. For a roadmap of the functions inside maxParsimonyNet, see [`maxParsimonyNetRun1!`](@ref). """ function maxParsimonyNet(currT::HybridNetwork, df::DataFrame; tolAbs=fAbs::Float64, Nfail=numFails::Integer, hmax=1::Integer, runs=10::Integer, outgroup="none"::Union{AbstractString,Integer}, rootname="mp"::AbstractString, seed=0::Integer, probST=0.3::Float64, criterion=:softwired::Symbol) currT0 = readTopologyUpdate(writeTopologyLevel1(currT)) # update all level-1 things flag = checkNet(currT0,true) # light checking only flag && error("starting topology suspected not level-1") writelog = true writelog_1proc = false if (rootname != "") julialog = string(rootname,".log") logfile = open(julialog,"w") juliaout = string(rootname,".out") if Distributed.nprocs() == 1 writelog_1proc = true juliaerr = string(rootname,".err") errfile = open(juliaerr,"w") end else writelog = false logfile = stdout # used in call to optTopRun1! end str = """optimization of topology using: hmax = $(hmax), max number of failed proposals = $(Nfail). """ ## need to root the network in a good place before parsimony ## throw an error if outgroup conflicts with starting topology, ## instead of choosing another outgroup outgroup == "none" && error("provide a sensible outgroup for parsimony score computation") rootatnode!(currT,outgroup) ##currT (not currT0) bc we just want to check that starting topology ##is not in conflict with outgroup, ##but we need a semi-directed level-1 "good" network (currT0) for search str *= (writelog ? "rootname for files: $(rootname)\n" : "no output files\n") str *= "BEGIN: $(runs) runs on starting tree $(writeTopology(currT0))\n" if Distributed.nprocs()>1 str *= " using $(Distributed.nprocs()) processors\n" end str *= " with parsimony criterion: $(string(criterion))\n" if (writelog) write(logfile,str) flush(logfile) end print(stdout,str) print(stdout, Dates.format(Dates.now(), "yyyy-mm-dd H:M:S.s") * "\n") # if 1 proc: time printed to logfile at start of every run, not here. if seed == 0 t = time()/1e9 a = split(string(t),".") seed = parse(Int,a[2][end-4:end]) #better seed based on clock end if writelog write(logfile,"\nmain seed $(seed)\n") flush(logfile) else print(stdout,"\nmain seed $(seed)\n"); end Random.seed!(seed) seeds = [seed;round.(Integer,floor.(rand(runs-1)*100000))] if writelog && !writelog_1proc for i in 1:runs # workers won't write to logfile write(logfile, "seed: $(seeds[i]) for run $(i)\n") end flush(logfile) end tstart = time_ns() bestnet = Distributed.pmap(1:runs) do i # for i in 1:runs logstr = "seed: $(seeds[i]) for run $(i), $(Dates.format(Dates.now(), "yyyy-mm-dd H:M:S.s"))\n" print(stdout, logstr) msg = "\nBEGIN Max Parsimony search for run $(i), seed $(seeds[i]) and hmax $(hmax)" if writelog_1proc # workers can't write on streams opened by master write(logfile, logstr * msg) flush(logfile) end GC.gc(); try best = maxParsimonyNetRun1(currT0, df, Nfail, tolAbs, hmax, seeds[i],logfile,writelog_1proc, probST,outgroup,criterion); logstr *= "\nFINISHED Max $(string(criterion)) parsimony for run $(i), parsimony of best: $(best.loglik)\n" if writelog_1proc logstr = writeTopology(best) logstr *= "\n---------------------\n" write(logfile, logstr) flush(logfile) end return best catch(err) msg = "\nERROR found on Max Parsimony for run $(i) seed $(seeds[i]): $(err)\n" logstr = msg * "\n---------------------\n" if writelog_1proc write(logfile, logstr) flush(logfile) write(errfile, msg) flush(errfile) end @warn msg # returns: nothing end end tend = time_ns() # in nanoseconds telapsed = round(convert(Int, tend-tstart) * 1e-9, digits=2) # in seconds writelog_1proc && close(errfile) msg = "\n" * Dates.format(Dates.now(), "yyyy-mm-dd H:M:S.s") if writelog write(logfile, msg) end filter!(n -> n !== nothing, bestnet) # remove "nothing", failed runs if length(bestnet)>0 ind = sortperm([n.loglik for n in bestnet]) bestnet = bestnet[ind] maxNet = bestnet[1]::HybridNetwork # tell type to compiler else error("all runs failed") end rootatnode!(maxNet,outgroup) writelog && write(logfile,"\nMaxNet is $(writeTopology(maxNet)) \nwith $(string(criterion)) parsimony score $(maxNet.loglik)\n") print(stdout,"\nMaxNet is $(writeTopology(maxNet)) \nwith $(string(criterion)) parsimony score $(maxNet.loglik)\n") s = writelog ? open(juliaout,"w") : stdout str = writeTopology(maxNet) * """ $(string(criterion)) parsimony score = $(maxNet.loglik) Dendroscope: $(writeTopology(maxNet,di=true)) Elapsed time: $(telapsed) seconds, $(runs) attempted runs ------- List of estimated networks for all runs (sorted by $(string(criterion)) parsimony score; the smaller, the better): """ for n in bestnet str *= " " str *= writeTopology(rootatnode!(n,outgroup)) str *= ", with $(string(criterion)) parsimony $(n.loglik)\n" end str *= "-------\n" write(s,str); writelog && close(s) # to close juliaout file (but not stdout!) writelog && close(logfile) return maxNet end ## unused function: ## function to check if currT agrees with the outgroup function correctRootPlace(currT::HybridNetwork, outgroup::AbstractString) try checkRootPlace!(currT,outgroup=outgroup) catch err if isa(err, RootMismatch) println("RootMismatch: ", err.msg, """\nThe starting topology has hybrid edges that are incompatible with the desired outgroup. """) else println("error trying to reroot: ", err.msg); end return false end return true end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
82960
# any change to these constants must be documented in phyLiNC! const moveweights_LiNC = Distributions.aweights([0.6, 0.2, 0.05, 0.05, 0.1]) const movelist_LiNC = ["nni", "addhybrid", "deletehybrid", "fliphybrid", "root"] const likAbsAddHybLiNC = 0.0 #= loglik improvement required to retain a hybrid. Greater values would raise the standard for newly-proposed hybrids, leading to fewer proposed hybrids accepted during the search =# const likAbsDelHybLiNC = 0.0 #= loglik decrease allowed when removing a hybrid lower (more negative) values of lead to more hybrids removed during the search =# const alphaRASmin = 0.02 const alphaRASmax = 50.0 const pinvRASmin = 1e-8 const pinvRASmax = 0.99 const kappamax = 20.0 const BLmin = 1.0e-8 # min_branch_length = 1.0e-6 in most cases in IQ-TREE v2.0 (see main/phyloanalysis.cpp) const BLmax = 10.0 # max_branch_length = 10.0 used in IQ-TREE v2.0 (see utils/tools.cpp) """ CacheGammaLiNC Type to store intermediate values during γ optimization, to limit time spent on garbage collection. """ struct CacheGammaLiNC "conditional likelihood under focus hybrid edge, length nsites" clike::Vector{Float64} "conditional likelihood under partner edge, length nsites" clikp::Vector{Float64} """conditional likelihood under displayed trees that have Neither the focus hybrid edge Nor its partner. Length: nsites""" clikn::Vector{Float64} """whether displayed trees have the focus hybrid edge (true) the partner edge (false) or none of them (missing), which can happen on non-tree-child networks""" hase::Vector{Union{Missing, Bool}} end function CacheGammaLiNC(obj::SSM) CacheGammaLiNC( Vector{Float64}(undef, obj.nsites), Vector{Float64}(undef, obj.nsites), Vector{Float64}(undef, obj.nsites), Vector{Union{Missing, Bool}}(undef, length(obj.displayedtree)) ) end """ CacheLengthLiNC Type to store intermediate values during optimization of one branch length, to limit time spent on garbage collection. Re-used across branches. See constructor below, from a `StatisticalSubstitutionModel`. """ struct CacheLengthLiNC """forward likelihood of descendants of focus edge: nstates x nsites x nrates x ntrees""" flike::Array{Float64,4} """likelihood of non-descendants of focus edge: direct * backwards * P(rate & tree). size: nstates x nsites x nrates x ntrees""" dblike::Array{Float64,4} """whether displayed trees have the focus edge (true) or not (false), which can happen for hybrid edges or on non-tree-child networks""" hase::Vector{Bool} "transition probability matrices: P(r*t) for each rate r" Prt::Vector{StaticArrays.MMatrix} "rQP(rt) for each rate r, for the gradient" rQP::Vector{StaticArrays.MMatrix} "site-specific gradient numerator for log-likelihood: nsites" glik::Vector{Float64} opt::NLopt.Opt end """ phyLiNC(net::HybridNetwork, fastafile::String, substitutionModel::Symbol) Estimate a phylogenetic network from concatenated DNA data using maximum likelihood, ignoring incomplete lineage sorting (phyLiNC: phylogenetic Likelihood Network from Concatenated data). The network is constrained to have `maxhybrid` reticulations at most, but can be of any level. The search starts at (or near) the network `net`, using a local hill-climbing search to optimize the topology (nearest-neighbor interchange moves, add hybridizations, and remove hybridizations). Also optimized are evolutionary rates, amount of rate variation across sites, branch lengths and inheritance γs. This search strategy is run `nruns` times, and the best of the `nruns` networks is returned. Return a [`StatisticalSubstitutionModel`](@ref) object, say `obj`, which contains the estimated network in `obj.net`. Required arguments: - `net`: a network or tree of type `HybridNetwork`, to serve as a starting point in the search for the best network. Newick strings can be converted to this format with [`readTopology`] (@ref). - `fastafile`: file with the sequence data in FASTA format. Ambiguous states are treated as missing. - `substitutionModel`: A symbol indicating which substitution model is used. Choose `:JC69` [`JC69`](@ref) for the Jukes-Cantor model or `:HKY85` for the Hasegawa, Kishino, Yano model [`HKY85`](@ref). The length of the edge below a reticulation is not identifiable. Therefore, phyLiNC estimates the canonical version of the network: with reticulations **unzipped**: edges below reticulations are set to 0, and hybrid edges (parental lineages) have estimated lengths that are increased accordingly. If any branch lengths are missing in the input network, phyLiNC estimates the starting branch lengths using pairwise distances. Otherwise, it uses the input branch lengths as starting branch lengths, only unzipping all reticulations, as described above. Optional arguments (default value in parenthesis): - symbol for the model of rate variation across sites (`:noRV` for no rate variation): use `:G` or `:Gamma` for Gamma-distributed rates, `:I` or `:Inv` for a proportion of invariable sites, and `:GI` or `:GammaInv` for a combination (not recommended). - integer (4) for the number of categories to use in estimating evolutionary rates using a discretized gamma model. When allowing for rate variation, four categories is standard. With 1 category, no rate variation is assumed. See [`RateVariationAcrossSites`] (@ref). Main optional keyword arguments (default value in parenthesis): - `speciesfile` (""): path to a csv file with samples in rows and two columns: species (column 1), individual (column 2) Include this file to group individuals by species. - `cladefile` (""): path to a csv file containing two columns: clades and individuals used to create one or more clade topology constraints to meet during the search. (NOTE: clade contraints not yet implemented.) - `filename` ("phyLiNC"): root name for the output files (`.out`, `.err`). If empty (""), files are *not* created, progress log goes to the screen only (standard out). - `maxhybrid` (1): maximum number of hybridizations allowed. `net` (starting network) must have `maxhybrid` or fewer reticulations. - `nruns` (10): number of independent starting points for the search - `no3cycle` (true): prevents 3-cycles, which are (almost) not identifiable - `nohybridladder` (true): prevents hybrid ladder in network. If true, the input network must not have hybrid ladders. Warning: Setting this to true will avoid most hybrid ladders, but some can still occur in some cases when deleting hybrid edges. This might be replaced with an option to avoid all non-tree-child networks in the future. Optional arguments controlling the search: - `seed` (default 0 to get it from the clock): seed to replicate a given search - `nreject` (75): maximum number of times that new topologies are proposed and rejected in a row. Lower values of `nreject` result in a less thorough but faster search. Controls when to stop proposing new network topologies. - `probST` (0.5): probability to use `net` as the starting topology for each given run. If probST < 1, the starting topology is k NNI moves away from `net`, where k is drawn from a geometric distribution: p (1-p)ᵏ, with success probability p = `probST`. - `maxmoves` (100): maximum number of topology moves before branch lengths, hybrid γ values, evolutionary rates, and rate variation parameters are reestimated. - `verbose` (true): set to false to turn off screen output - `alphamin` (0.02) and `alphamax` (50.0): minimum and maximum values for the shape parameter alpha for Gamma-distributed rates across sites. - `pinvmin` (1e-8) and `pinvmax` (0.99): minimum and maximum values for the proportion of invariable sites, if included in the model. The following optional arguments control when to stop the optimization of branch lengths and gamma values on each individual candidate network. Defaults in parentheses. - `ftolRel` (1e-6) and `ftolAbs` (1e-6): relative and absolute differences of the network score between the current and proposed parameters - `xtolRel` (1e-5) and `xtolAbs` (1e-5): relative and absolute differences between the current and proposed parameters. Greater values will result in a less thorough but faster search. These parameters are used when evaluating candidate networks only. Regardless of these arguments, once a final topology is chosen, branch lenghts are optimized using stricter tolerances (1e-10, 1e-12, 1e-10, 1e-10) for better estimates. """ function phyLiNC(net::HybridNetwork, fastafile::String, modSymbol::Symbol, rvsymbol=:noRV::Symbol, rateCategories=4::Int; maxhybrid=1::Int, no3cycle=true::Bool, nohybridladder=true::Bool, speciesfile=""::AbstractString, cladefile=""::AbstractString, verbose=true::Bool, kwargs...) # create constraints and new network if speciesfile if !isempty(speciesfile) net, constraints = mapindividuals(net, speciesfile) else net = deepcopy(net) constraints = TopologyConstraint[] end if !isempty(cladefile) error("Clade constraints not yet implemented.") end # create starting object for all runs obj = StatisticalSubstitutionModel(net, fastafile, modSymbol, rvsymbol, rateCategories; maxhybrid=maxhybrid) #= after SSM(), update constraint taxon names, taxonnums, edge, and node because some leaves may be pruned, and check_matchtaxonnames calls resetNodeNumbers! (changing leaf node numbers) and resetEdgeNumbers! =# for i in 1:length(constraints) constraints[i] = PhyloNetworks.TopologyConstraint(constraints[i].type, constraints[i].taxonnames, obj.net) end checknetwork_LiNC!(obj.net, maxhybrid, no3cycle, nohybridladder, constraints, verbose) #= checknetwork removes degree-2 nodes (including root) and 2- and 3-cycles and requires that the network is preordered. Warning: need to call updateSSM after using checknetwork_LiNC =# updateSSM!(obj, true; constraints=constraints) if any(e.length < 0.0 for e in obj.net.edge) # check for missing branch lengths startingBL!(obj.net, obj.trait, obj.siteweight) end unzip_canonical!(obj.net) for e in obj.net.edge # bring branch lengths inside bounds if e.length < BLmin && !getparent(e).hybrid e.length = BLmin elseif e.length > BLmax e.length = BLmax end end phyLiNC!(obj; maxhybrid=maxhybrid, no3cycle=no3cycle, nohybridladder=nohybridladder, constraints=constraints, verbose=verbose, kwargs...) end """ phyLiNC!(obj::SSM; kwargs...) Called by [`phyLiNC`](@ref) after `obj` is created (containing both the data and the model) and after checks are made to start from a network that satisfies all the constraints. Different runs are distributed to different processors, if more than one are available. """ function phyLiNC!(obj::SSM; maxhybrid=1::Int, no3cycle=true::Bool, nohybridladder=true::Bool, maxmoves=100::Int, nreject=75::Int, nruns=10::Int, filename="phyLiNC"::AbstractString, verbose=true::Bool, seed=0::Int, probST=0.5::Float64, ftolRel=1e-6::Float64, ftolAbs=1e-6::Float64, xtolRel=1e-10::Float64, xtolAbs=1e-5::Float64, constraints=TopologyConstraint[]::Vector{TopologyConstraint}, alphamin=alphaRASmin::Float64, alphamax=alphaRASmax::Float64, pinvmin=pinvRASmin::Float64, pinvmax=pinvRASmax::Float64) writelog = true writelog_1proc = false if filename != "" logfile = open(string(filename,".log"),"w") juliaout = string(filename,".out") if Distributed.nprocs() == 1 writelog_1proc = true juliaerr = string(filename,".err") errfile = open(juliaerr,"w") end else writelog = false logfile = stdout end γcache = CacheGammaLiNC(obj) # rough optimization of rates and alpha, for better starting values used by all runs obj.loglik = -Inf Random.seed!(0) # to re-run a single run (out of several) reproducibly fit!(obj; optimizeQ=(nparams(obj.model) > 0), optimizeRVAS=(nparams(obj.ratemodel) > 0), verbose=false, maxeval=20, ftolRel=ftolRel, ftolAbs=ftolAbs, xtolRel=xtolRel, xtolAbs=xtolAbs, alphamin=alphamin, alphamax=alphamax, pinvmin=pinvmin, pinvmax=pinvmax) @debug "loglik = $(loglikelihood(obj)) at the start" str = """ PhyLiNC network estimation starting. Parameters: maxhybrid = $(maxhybrid) nohybridladder = $nohybridladder no3cycle = $no3cycle probST= $probST max number of moves per cycle = $maxmoves max number of consecutive failed proposals = $(nreject) optimization tolerance: ftolRel=$(ftolRel), ftolAbs=$(ftolAbs), xtolAbs=$(xtolAbs), xtolRel=$(xtolRel). """ * (writelog ? " filename for log and err files: $(filename)\n" : " no output files\n") io = IOBuffer(); showdata(io, obj, true) # true for full site information str *= String(take!(io)) * "\n"; close(io) str *= "\n$(nruns) run(s) starting near network topology:\n$(writeTopology(obj.net))\nstarting model:\n" * replace(string(obj.model), r"\n" => "\n ") * "\n" * replace(string(obj.ratemodel), r"\n" => "\n ") * "\n" # fixit: add info about constraints: type and tip names for each constraint if Distributed.nprocs()>1 str *= "using $(Distributed.nworkers()) worker processors\n" end if writelog write(logfile,str) flush(logfile) end verbose && print(stdout,str) verbose && print(stdout, "Time: " * Dates.format(Dates.now(), "yyyy-mm-dd H:M:S.s") * "\n") # if 1 proc: time printed to logfile at start of every run, not here. if seed == 0 t = time()/1e9 a = split(string(t),".") seed = parse(Int,a[2][end-4:end]) # seed based on clock end if writelog write(logfile,"main seed = $(seed)\n---------------------\n") flush(logfile) end verbose && print(stdout,"main seed = $(seed)\n---------------------\n") Random.seed!(seed) seeds = [seed; round.(Integer,floor.(rand(nruns-1)*100000))] if writelog && !writelog_1proc for i in 1:nruns # workers won't write to logfile write(logfile, "For run $(i), seed = $(seeds[i])\n") end flush(logfile) end tstart = time_ns() startingnet = obj.net startingconstraints = constraints netvector = Distributed.pmap(1:nruns) do i # for i in 1:nruns msg = "BEGIN PhyLiNC run $(i)\nseed = $(seeds[i])\ntime = $(Dates.format(Dates.now(), "yyyy-mm-dd H:M:S.s"))\n" if writelog_1proc # workers can't write on streams opened by master write(logfile, msg) flush(logfile) end verbose && print(stdout, msg) GC.gc() try obj.net = deepcopy(startingnet) obj.model = deepcopy(obj.model) obj.ratemodel = deepcopy(obj.ratemodel) constraints = deepcopy(startingconstraints) # problem: nodes were copied on previous line. when nodes copied again on this line, they are now different phyLiNCone!(obj, maxhybrid, no3cycle, nohybridladder, maxmoves, nreject, verbose, writelog_1proc, logfile, seeds[i], probST, constraints, ftolRel, ftolAbs, xtolRel, xtolAbs, alphamin, alphamax, pinvmin, pinvmax, γcache, CacheLengthLiNC(obj, ftolRel,ftolAbs,xtolRel,xtolAbs, 20)) # 20=maxeval # NLopt segfault if we pass a pre-allocated lcache to a worker logstr = "\nFINISHED. loglik = $(obj.loglik)\n" verbose && print(stdout, logstr) if writelog_1proc logstr *= writeTopology(obj.net) logstr *= "\n---------------------\n" write(logfile, logstr) flush(logfile) end obj.net.loglik = obj.loglik return [obj.net, obj.model, obj.ratemodel] catch err msg = "\nERROR found on PhyLiNC for run $(i) seed $(seeds[i]):\n" * sprint(showerror,err) logstr = msg * "\n---------------------\n" print(stacktrace(catch_backtrace())) println() if writelog_1proc write(logfile, logstr) flush(logfile) write(errfile, msg) flush(errfile) end @warn msg # returns: nothing end end tend = time_ns() # in nanoseconds telapsed = round(convert(Int, tend-tstart) * 1e-9, digits=2) # in seconds writelog_1proc && close(errfile) msg = "All runs complete.\nend time: " * Dates.format(Dates.now(), "yyyy-mm-dd H:M:S.s") * "\ntime elapsed: $telapsed seconds" *"\n---------------------\n" writelog && write(logfile, msg) verbose && print(stdout, msg) #= post processing of the networks type of netvector: Array{Union{Nothing, Array{Int64,1}},1} each item holds [net, model, ratemodel] if sucessful, nothing if failed =# filter!(n -> n !== nothing, netvector) # remove "nothing": failed runs !isempty(netvector) || error("all runs failed") sort!(netvector, by = x -> x[1].loglik, rev=true) # @debug "loglik from all runs:" [n[1].loglik for n in netvector] obj.net = netvector[1][1]::HybridNetwork # best network, tell type to compiler obj.model = netvector[1][2] obj.ratemodel = netvector[1][3] obj.loglik = obj.net.loglik logstr = "Best topology:\n$(writeTopology(obj.net))\n" * "with loglik $(obj.loglik) under:\n" * replace(string(obj.model), r"\n" => "\n ") * "\n" * replace(string(obj.ratemodel), r"\n" => "\n ") * "\n---------------------\n" * "Final optimization of branch lengths and gammas on this network... " if writelog write(logfile, logstr) flush(logfile) end verbose && print(stdout,logstr) (no3cycle ? shrink3cycles!(obj.net, true) : shrink2cycles!(obj.net, true)) # not done in phyLiNCone # loglik changes after shrinkage, but recalculated below by optimizealllengths updateSSM!(obj, true; constraints = constraints) # warning: tolerance values from constants, not user-specified lcache = CacheLengthLiNC(obj, fRelBL, fAbsBL, xRelBL, xAbsBL, 1000) # maxeval=1000 optimizealllengths_LiNC!(obj, lcache) ghosthybrid = optimizeallgammas_LiNC!(obj, fAbsBL, γcache, 100) if ghosthybrid (no3cycle ? shrink3cycles!(obj.net, true) : shrink2cycles!(obj.net, true)) updateSSM!(obj, true; constraints=constraints) discrete_corelikelihood!(obj) # to get likelihood exact, even if not optimum end obj.net.loglik = obj.loglik toptimend = time_ns() # in nanoseconds telapsed = round(convert(Int, toptimend-tstart) * 1e-9, digits=2) # in seconds logstr = "complete.\nFinal log-likelihood: $(obj.loglik)\n" * "Final network:\n" * "$(writeTopology(obj.net))\n" * "Total time elapsed: $telapsed seconds (includes final branch length and gamma optimization)\n" * "Final time: " * Dates.format(Dates.now(), "yyyy-mm-dd H:M:S.s") * "\n---------------------\n" * "NOTE: This network should be interpreted as unrooted, since a likelihood model cannot identify\nthe root. The network can be rooted with an outgroup or other external information." * "\n---------------------\n" if writelog write(logfile, logstr) flush(logfile) close(logfile) end verbose && print(stdout,logstr) return obj end """ phyLiNCone!(obj::SSM, maxhybrid::Int, no3cycle::Bool, nohybridladder::Bool, maxmoves::Int, nrejectmax::Int, verbose::Bool, writelog_1proc::Bool, logfile::IO, seed::Int, probST::Float64, constraints::Vector{TopologyConstraint}, ftolRel::Float64, ftolAbs::Float64, xtolRel::Float64, xtolAbs::Float64, alphamin::Float64, alphamax::Float64, pinvmin::Float64, pinvmax::Float64, γcache::CacheGammaLiNC) Estimate one phylogenetic network (or tree) from concatenated DNA data, like [`phyLiNC!`](@ref), but doing one run only, and taking as input an StatisticalSubstitutionModel object `obj`. The starting network is `obj.net` and is assumed to meet all the requirements. `writelog_1proc` is passed by phyLiNC! an indicates if a log should be written. If the number of processors is > 1, this will be false because workers can't write on streams opened by master. `logfile` will be stdout if `writelog_1proc` is false. Otherwise, it will be the log file created by `phyLiNC!`. See [`phyLiNC`](@ref) for other arguments. """ function phyLiNCone!(obj::SSM, maxhybrid::Int, no3cycle::Bool, nohybridladder::Bool, maxmoves::Int, nrejectmax::Int, verbose::Bool, writelog_1proc::Bool, logfile::IO, seed::Int, probST::Float64, constraints::Vector{TopologyConstraint}, ftolRel::Float64, ftolAbs::Float64, xtolRel::Float64, xtolAbs::Float64, alphamin::Float64, alphamax::Float64, pinvmin::Float64, pinvmax::Float64, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) Random.seed!(seed) # update files inside topology constraint to match the deepcopied net in obj.net created by pmap updateconstraintfields!(constraints, obj.net) numNNI = (probST < 1.0 ? rand(Geometric(probST)) : 0) # number NNIs ~ geometric: p (1-p)^k if numNNI > 0 # modify starting tree by k nni moves (if possible) for i in 1:numNNI nni_LiNC!(obj, no3cycle, nohybridladder, constraints, ftolAbs, γcache, lcache) end logstr = "changed starting topology by $numNNI attempted NNI move(s)\n" writelog_1proc && write(logfile, logstr) verbose && print(stdout, logstr) end logstr = "starting at $(writeTopology(obj.net))\n" if writelog_1proc write(logfile, logstr) flush(logfile) end verbose && print(stdout, logstr) optQ = nparams(obj.model) > 0 optRAS = nparams(obj.ratemodel) > 0 nrejected = 0 while nrejected < nrejectmax nrejected = optimizestructure!(obj, maxmoves, maxhybrid, no3cycle, nohybridladder, nrejected, nrejectmax, constraints, ftolAbs, γcache, lcache) fit!(obj; optimizeQ=optQ, optimizeRVAS=optRAS, maxeval=20, ftolRel=ftolRel, ftolAbs=ftolAbs, xtolRel=xtolRel, xtolAbs=xtolAbs, alphamin=alphamin,alphamax=alphamax, pinvmin=pinvmin,pinvmax=pinvmax) optimizealllengths_LiNC!(obj, lcache) # 1 edge at a time, random order for i in Random.shuffle(1:obj.net.numHybrids) e = getparentedge(obj.net.hybrid[i]) optimizelocalgammas_LiNC!(obj, e, ftolAbs, γcache) end ghosthybrid = false # find hybrid edges with γ=0, to delete them for h in obj.net.hybrid minorhybridedge = getparentedgeminor(h) minorhybridedge.gamma == 0.0 || continue ghosthybrid = true deletehybridedge!(obj.net, minorhybridedge, false,true,false,false,false) end #= warning: after this while loop is done, phyLiNC only keeps net, model & likelihood. After shrinking cycles, the loglik would be slightly wrong because 3-cycles are nearly non-identifiable, not fully non-identifiable. Due to this, we shrink cycles only in the middle of optimization, not when optimization is finished. By avoiding shrinking cycles at the end, the final loglik is correct. This can lead to confusing results for users: They could choose no3cycle=true, but still have a 3-cycle in the final network. Might want to add something to docs about this. =# if ghosthybrid && (nrejected < nrejectmax) shrink3cycles!(obj.net, true) updateSSM!(obj, true; constraints=constraints) end end return obj end """ checknetwork_LiNC!(net::HybridNetwork, maxhybrid::Int, no3cycle::Bool, nohybridladder::Bool, constraints=TopologyConstraint[]::Vector{TopologyConstraint}, verbose::Bool=false) Check that `net` is an adequate starting network before `phyLiNC!`: remove nodes of degree 2 (possibly including the root); check that `net` meets the topological `constraints`, has no polytomies (except at species constraints), and `maxhybrid` of fewer reticulations. According to user-given options, also check for the absence of 3-cycles and/or hybrid ladders. ```jldoctest julia> maxhybrid = 3; julia> net = readTopology("(((A:2.0,(B:1.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5,D:2.0);"); julia> preorder!(net) # for correct unzipping in checknetwork_LiNC! julia> PhyloNetworks.checknetwork_LiNC!(net, maxhybrid, true, true) HybridNetwork, Rooted Network 8 edges 8 nodes: 4 tips, 1 hybrid nodes, 3 internal tree nodes. tip labels: A, B, C, D ((A:2.0,(B:1.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0,D:2.5); ``` """ function checknetwork_LiNC!(net::HybridNetwork, maxhybrid::Int, no3cycle::Bool, nohybridladder::Bool, constraints=TopologyConstraint[]::Vector{TopologyConstraint}, verbose::Bool=false) if maxhybrid > 0 net.numTaxa >= 3 || error("cannot estimate hybridizations in topologies with 3 or fewer tips: $(net.numTaxa) tips here.") end # checks for polytomies, constraint violations, nodes of degree 2 checkspeciesnetwork!(net, constraints) || error("The species or clade constraints are not satisfied in the starting network.") # checkspeciesnetwork removes nodes of degree 2, need to renumber with updateSSM !shrink2cycles!(net, true) || (verbose && @warn( """The input network contains one or more 2-cycles (after removing any nodes of degree 2 including the root). These 2-cycles have been removed.""")) if no3cycle !shrink3cycles!(net, true) || (verbose && @warn( """Options indicate there should be no 3-cycles in the returned network, but the input network contains one or more 3-cycles (after removing any nodes of degree 2 including the root). These 3-cycles have been removed.""")) # if nodes removed, need to renumber with updateSSM end if nohybridladder !hashybridladder(net) || error( """Options indicate there should be no hybrid ladders in the returned network, but the input network contains one or more hybrid ladders.""") end if length(net.hybrid) > maxhybrid error("""Options indicate a maximum of $(maxhybrid) reticulations, but the input network contains $(length(net.hybrid)) hybrid nodes. Please increase maxhybrid to $(length(net.hybrid)) or provide an input network with $(maxhybrid) or fewer reticulations.""") end return net end """ optimizestructure!(obj::SSM, maxmoves::Integer, maxhybrid::Integer, no3cycle::Bool, nohybridladder::Bool, nreject::Integer, nrejectmax::Integer, constraints::Vector{TopologyConstraint}, ftolAbs::Float64, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) Alternate NNI moves, hybrid additions / deletions, and root changes based on their respective weights in `moveweights_LiNC` ([0.4, 0.2, 0.2, 0.2]). Branch lengths and hybrid γs around the NNI focal edge or around the added / deleted hybrid edge are optimized (roughly) on the proposed network. Each proposed network is accepted --or not-- if the likelihood improves (or doesn't decrease much for hybrid deletion). After adding or removing a hybrid, `obj` is updated, to have correct displayed `trees` and node/edge numberings: done by [`nni_LiNC!`](@ref), [`addhybridedgeLiNC!`](@ref) and [`deletehybridedgeLiNC!`](@ref). Output: number of consecutive rejections so far. The percent of nni moves, hybrid additions, hybrid deletions, and root changes to be performed is in `PhyloNetworks.moveweights_LiNC`. - `maxmoves`: maximum number of moves to be performed, including root changes, which don't actually change the semi-directed topology and likelihood. - `nreject`: number of consecutive rejections (ignoring root changes), prior to starting the search (from a prior function call) - `nrejectmax`: the search stops when there has been this number of moves that have been rejected in a row (ignoring root changes) For a description of other arguments, see [`phyLiNC`](@ref). Assumptions: - `checknetworkbeforeLiNC` and `discrete_corelikelihood!` have been called on `obj.net`. - starting with a network without 2- and 3- cycles (checked by `checknetworkbeforeLiNC`) Note: When removing a hybrid edge, always removes the minor edge. """ function optimizestructure!(obj::SSM, maxmoves::Integer, maxhybrid::Integer, no3cycle::Bool, nohybridladder::Bool, nreject::Integer, nrejectmax::Integer, constraints::Vector{TopologyConstraint}, ftolAbs::Float64, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) nmoves = 0 moveweights = copy(moveweights_LiNC) if maxhybrid == 0 # prevent some moves, to avoid proposing non-admissible moves moveweights[2] = 0.0 # addhybrid moveweights[3] = 0.0 # deletehybrid moveweights[4] = 0.0 # fliphybrid moveweights ./= sum(moveweights) end while nmoves < maxmoves && nreject < nrejectmax # both should be true to continue currLik = obj.loglik movechoice = sample(movelist_LiNC, moveweights_LiNC) if movechoice == "nni" result = nni_LiNC!(obj, no3cycle, nohybridladder, constraints, ftolAbs, γcache, lcache) elseif movechoice == "addhybrid" nh = obj.net.numHybrids nh == maxhybrid && continue # skip & don't count towards nmoves if enough hybrids in net # alternative: switch "add" and "delete" as appropriate (not chosen) # would decrease the weight of NNIs compared to add/delete hybrid nh < maxhybrid || # nh > maxhybrid should never happen error("The network has $nh hybrids: more than the allowed max of $maxhybrid") result = addhybridedgeLiNC!(obj, currLik, no3cycle, nohybridladder, constraints, ftolAbs, γcache, lcache) elseif movechoice == "deletehybrid" obj.net.numHybrids == 0 && continue # skip & don't count towards nmoves if no hybrid in net result = deletehybridedgeLiNC!(obj, currLik, no3cycle, constraints, γcache, lcache) elseif movechoice == "fliphybrid" obj.net.numHybrids == 0 && continue # skip & don't count towards nmoves if no hybrid in net result = fliphybridedgeLiNC!(obj, currLik, nohybridladder, constraints, ftolAbs, γcache, lcache) else # change root (doesn't affect likelihood) result = moveroot!(obj.net, constraints) isnothing(result) || updateSSM_root!(obj) # edge direction used by updatecache_edge end # optimize γ's ghosthybrid = optimizeallgammas_LiNC!(obj, ftolAbs, γcache, 1) if ghosthybrid # delete hybrid edges with γ=0 (no3cycle ? shrink3cycles!(obj.net, true) : shrink2cycles!(obj.net, true)) # loglik change ignored, but loglik recalculated below by optimizelocalBL updateSSM!(obj, true; constraints=constraints) end # pick a random edge (internal or external), optimize adjancent lengths e = Random.rand(obj.net.edge) optimizelocalBL_LiNC!(obj, e, lcache) nmoves += 1 # next: update the number of consecutive rejections ignoring any root move # (which don't change the semi-directed topology or loglik) if !isnothing(result) && movechoice != "root" if result # move successful and accepted (loglik increase) nreject = 0 # reset else # move made, rejected, and undone nreject += 1 end end @debug "$(movechoice) move was " * (isnothing(result) ? "not permissible" : (result ? "accepted" : "rejected and undone")) * ", $nmoves total moves, $nreject rejected,\nloglik = $(obj.loglik)" end return nreject end """ nni_LiNC!(obj::SSM, no3cycle::Bool, nohybridladder::Bool, constraints::Vector{TopologyConstraint}, ftolAbs::Float64, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) Loop over possible edges for a nearest-neighbor interchange move until one is found. Performs move and compares the original and modified likelihoods. If the modified likelihood is greater than the original by `likAbs`, the move is accepted. Return true if move accepted, false if move rejected. Return nothing if there are no nni moves possible in the network. For arguments, see [`phyLiNC`](@ref). Called by [`optimizestructure!`](@ref), which is called by [`phyLiNC!`](@ref). Note: an RR move does not change the best likelihood. RR means that there's a hybrid ladder, so it looks like a hard polytomy at the reticulation after unzipping. Theoretically, we could avoid the re-optimizing the likelihood accept the move: just change inheritance values to get same likelihood, and update the tree priors. *Not* done. """ function nni_LiNC!(obj::SSM, no3cycle::Bool, nohybridladder::Bool, constraints::Vector{TopologyConstraint}, ftolAbs::Float64, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) currLik = obj.loglik savedpriorltw = copy(obj.priorltw) # in case we need to undo move saveddisplayedtree = obj.displayedtree # updateSSM creates a new "pointer" edgefound = false remainingedges = collect(1:length(obj.net.edge)) # indices in net.edge while !edgefound isempty(remainingedges) && return nothing i_in_remaining = Random.rand(1:length(remainingedges)) e1 = obj.net.edge[remainingedges[i_in_remaining]] # save BLs and gammas in case we need to undo move savededges = adjacentedges(e1) savedlen = [e.length for e in savededges] savedgam = [e.gamma for e in savededges] undoinfo = nni!(obj.net,e1,nohybridladder,no3cycle,constraints) #fixit: for clades, need to update cladeconstraints, then restore below if isnothing(undoinfo) deleteat!(remainingedges, i_in_remaining) continue # edge not found yet, try again end edgefound = true updateSSM!(obj, true; constraints=constraints) optimizelocalgammas_LiNC!(obj, e1, ftolAbs, γcache) # don't delete a hybrid edge with γ=0: to be able to undo the NNI # but: there's no point in optimizing the length of such an edge (caught inside optimizelocalBL) optimizelocalBL_LiNC!(obj, e1, lcache) if obj.loglik < currLik nni!(undoinfo...) # undo move obj.displayedtree = saveddisplayedtree # restore displayed trees and weights obj.priorltw = savedpriorltw obj.loglik = currLik # restore to loglik before move for (i,e) in enumerate(savededges) # restore edge lengths and gammas e.length = savedlen[i] if e.hybrid setGamma!(e, savedgam[i]) # some hybrid partners are not adjacent to focus edge else savedgam[i] == 1.0 || @warn "A tree edge had saved gamma != 1.0. Something fishy has happened." e.gamma = 1.0 # savedgam[i] should be 1.0 end end return false # false means: move was rejected else # keep nni move. If a γ became 0, optimizestructure will remove the edge return true # move was accepted: # rejections will be reset to zero end end return nothing # no NNI were available: none were DAGs or met constraints end """ addhybridedgeLiNC!(obj::SSM, currLik::Float64, no3cycle::Bool, nohybridladder::Bool, constraints::Vector{TopologyConstraint}, ftolAbs::Float64, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) Completes checks, adds hybrid in a random location, updates SSM object, and optimizes branch lengths and gammas locally as part of PhyLiNC optimization. Return true if accepted add hybrid move. If move not accepted, return false. If cannot add a hybrid, return nothing. For arguments, see [`phyLiNC`](@ref). Called by [`optimizestructure!`](@ref). """ function addhybridedgeLiNC!(obj::SSM, currLik::Float64, no3cycle::Bool, nohybridladder::Bool, constraints::Vector{TopologyConstraint}, ftolAbs::Float64, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) #= save displayed trees, priorltw, BLs, and gammas in case we need to undo move branch lengths are changed by addhybridedge. We can't use adjacentedges because newhybridedge is chosen randomly, so we save all branch lengths and gammas here =# saveddisplayedtree = obj.displayedtree savedpriorltw = copy(obj.priorltw) savedlen = [e.length for e in obj.net.edge] savedgam = [e.gamma for e in obj.net.edge] result = addhybridedge!(obj.net, nohybridladder, no3cycle, constraints; maxattempts=max(10,size(obj.directlik,2)), fixroot=true) # maxattempt ~ numEdges # fixroot=true: to restore edge2 if need be, with deletehybridedge! # so hybridpartnernew is always true. This means that the order of edges # in obj.net.edge can be restored by deletehybridedge below. # Before doing anything, first check that addhybrid edge was successful. # If not successful, result isnothing, so return nothing. isnothing(result) && return nothing newhybridnode, newhybridedge = result # next: increase length of split edges if they became < BLmin splitedges = getparent(newhybridedge).edge # new hybrid edge = splitedges[3] # splitedges[1] and splitedges[2] have length 1/2 of original edge... # except if hybrid ladder was created (and unzipped) for e in splitedges[1:2] if e.length < BLmin && !getparent(e).hybrid e.length = BLmin end end # unzip only at new node and its child edge unzipat_canonical!(newhybridnode, getchildedge(newhybridnode)) updateSSM!(obj) #, true; constraints=constraints) optimizelocalgammas_LiNC!(obj, newhybridedge, ftolAbs, γcache) if newhybridedge.gamma == 0.0 deletehybridedge!(obj.net, newhybridedge, false,true) # nofuse,unroot obj.displayedtree = saveddisplayedtree # restore displayed trees and tree weights obj.priorltw = savedpriorltw for (i,e) in enumerate(obj.net.edge) # restore e.gamma = savedgam[i] end return false elseif newhybridedge.gamma == 1.0 # ≃ subtree prune and regraft (SPR) move # loglik better because γ=1 better than γ=0, yet without new reticulation: accept deletehybridedge!(obj.net, getparentedgeminor(newhybridnode), false,true,false,false,false) (no3cycle ? shrink3cycles!(obj.net, true) : shrink2cycles!(obj.net, true)) # loglik will be updated in optimizeallgammas right after, in optimizestructure updateSSM!(obj, true; constraints=constraints) @debug "addhybrid resulted in SPR move: new hybrid edge had γ=1.0, its partner was deleted" return true end optimizelocalBL_LiNC!(obj, newhybridedge, lcache) if obj.loglik - currLik < likAbsAddHybLiNC # improvement too small or negative: undo deletehybridedge!(obj.net, newhybridedge, false,true) # nofuse,unroot #= rezip not needed because likelihood unchanged. If hybrid edge addition used hybridpartnernew = false, the root was changed and direction of edge2 was changed: but that doesn't affect the likelihood. We don't restore the same rooted network, but we do restore the same semi-directed version. The former displayed trees are fine to use, even though they don't use the same root as that in the restored rooted network. Further, fixroot=true so hybridpartnernew = true. =# obj.displayedtree = saveddisplayedtree # restore original displayed trees and weights obj.priorltw = savedpriorltw obj.loglik = currLik # restore to loglik before move for (i,e) in enumerate(obj.net.edge) # restore edges and length (assumes same order) e.length = savedlen[i] e.gamma = savedgam[i] end return false else return true end end """ deletehybridedgeLiNC!(obj::SSM, currLik::Float64, no3cycle::Bool, constraints::Vector{TopologyConstraint}, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) Deletes a random hybrid edge and updates SSM object as part of PhyLiNC optimization. Return true if the move is accepted, false if not. Note: if net is tree-child and a hybrid edge is deleted, then the resulting network is still tree-child. But: if `net` has no hybrid ladders, deleting an existing reticulation may create a hybrid ladder. It happens if there is a reticulation above a W structure (tree node whose children are both hybrid nodes). This creates a problem if the user asked for `nohybridladder`: this request may not be met. fixit: In future, we could check for this case and prevent it. For a description of arguments, see [`phyLiNC`](@ref). Called by [`optimizestructure!`](@ref), which does some checks. """ function deletehybridedgeLiNC!(obj::SSM, currLik::Float64, no3cycle::Bool, constraints::Vector{TopologyConstraint}, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) nh = length(obj.net.hybrid) hybridnode = obj.net.hybrid[Random.rand(1:nh)] minorhybridedge = getparentedgeminor(hybridnode) #= if type-3 constraints: check that proposed deletion meets constraints the constraint's stem edge must be a tree edge -> not disrupted species (type 1) or clade type-2 constraints: no problem, because the major tree displaying the constraint has major edges only type-3 constraints: problem if the tree displaying the constraint has the minor hybrid edge to be deleted. Not implemented. hybindices = Random.shuffle(1:nh) edgenotfound = true for hi in hybindices hybridnode = obj.net.hybrid[hi] minorhybridedge = getparentedgeminor(hybridnode) # edgenotfound = whether any type-3 constraints is violated edgenotfound || break end if edgenotfound # tried all hybrids return nothing end =# # set γ to 0 to delete the hybrid edge: makes it easy to undo. # update minor edge, and prior log tree weights in obj γ0 = minorhybridedge.gamma setGamma!(minorhybridedge, 0.0) l1mγ = log(1.0-γ0) nt, hase = updatecache_hase!(γcache, obj, minorhybridedge.number, getparentedge(hybridnode).number) for it in 1:nt @inbounds h = hase[it] ismissing(h) && continue # tree has unchanged weight: skip below if h obj.priorltw[it] = -Inf else obj.priorltw[it] -= l1mγ end end #= warning: after setting γ=0, the 2 other edges connected to the minor parent are non-identifiable -> do not optimize them. if hybrid ladder (minor parent is hybrid node): not identifiable at all otherwise: only their sum is identifiable, but not individual lengths so: optimize length of major hybrid edge only =# majhyb = getparentedge(hybridnode) len0 = majhyb.length # to restore later if deletion rejected update_logtrans(obj) # fixit: is that really needed? optimizelength_LiNC!(obj, majhyb, lcache, Q(obj.model)) # don't optimize gammas: because we want to constrain one of them to 0.0 if obj.loglik - currLik > likAbsDelHybLiNC # -0.0: loglik can decrease for parsimony deletehybridedge!(obj.net, minorhybridedge, false,true,false,false,false) # nofuse,unroot,multgammas,simplify (no3cycle ? shrink3cycles!(obj.net, true) : shrink2cycles!(obj.net, true)) updateSSM!(obj, true; constraints=constraints) # obj.loglik will be updated by optimizeallgammas within optimizestructure return true else # keep hybrid majhyb.length = len0 setGamma!(minorhybridedge, γ0) # note: transition probability for majhyb not updated here, but could be # if we wanted to avoid full update before each branch length optim updateSSM_priorltw!(obj) # displayedtree already correct obj.loglik = currLik # restore to likelihood before move return false end end """ fliphybridedgeLiNC!(obj::SSM, currLik::Float64, nohybridladder::Bool, constraints::Vector{TopologyConstraint}, ftolAbs::Float64, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) Randomly chooses a minor hybrid edge and tries to flip its direction (that is, reverse the direction of gene flow) using [`fliphybrid!`](@ref). If the flip fails, it looks for the next minor hybrid edge. If all minor edges fail, tries to flip major edges in random order. After a successful flip, optimize branch lengths and gammas, then compare the likelihood of the previous network with the new one. Return: - true if a flip hybrid move was completed and improved the likelihood - false if a move was completed but did not improve the likelihoood - nothing if no hybrid flip move was admissible in this network. Warning: Undoing this move may not recover the original root if the root position was modified. For arguments, see [`phyLiNC`](@ref). Called by [`optimizestructure!`](@ref). """ function fliphybridedgeLiNC!(obj::SSM, currLik::Float64, nohybridladder::Bool, constraints::Vector{TopologyConstraint}, ftolAbs::Float64, γcache::CacheGammaLiNC, lcache::CacheLengthLiNC) # save displayed trees, priorltw, BLs, and gammas in case we need to undo move saveddisplayedtree = obj.displayedtree savedpriorltw = copy(obj.priorltw) savedlen = [e.length for e in obj.net.edge] savedgam = [e.gamma for e in obj.net.edge] ## find admissible move ## minor = true # randomly choose a minor hybrid edge undoinfo = fliphybrid!(obj.net, minor, nohybridladder, constraints) # cycle through all hybrid nodes if isnothing(undoinfo) # then try flipping a major edge minor = false undoinfo = fliphybrid!(obj.net, minor, nohybridladder, constraints) isnothing(undoinfo) && return nothing # no edge can be flipped end newhybridnode, flippededge, oldchildedge = undoinfo ## after an admissible flip, optimize branch lengths and gammas ## # reassign old child edge to BLmin (was zero) oldchildedge.length = BLmin # adjacent to flippedge, saved above # unzip only at new node and its child edge getchildedge(newhybridnode).length = 0.0 # adjacent to flippedge, saved above updateSSM!(obj) #, true; constraints=constraints) # displayed trees have changed optimizelocalgammas_LiNC!(obj, flippededge, ftolAbs, γcache) # don't delete a flipped edge with γ=0: to be able to undo the flip # but: no point in optimizing the length of such an edge. optimizelocalBL_LiNC won't. optimizelocalBL_LiNC!(obj, flippededge, lcache) if obj.loglik < currLik # then: undo the move fliphybrid!(obj.net, newhybridnode, !flippededge.isMajor, nohybridladder, constraints) obj.displayedtree = saveddisplayedtree # restore displayed trees and weights obj.priorltw = savedpriorltw obj.loglik = currLik # restore to loglik before move for (i,e) in enumerate(obj.net.edge) # restore edges and length (assumes same order) e.length = savedlen[i] e.gamma = savedgam[i] end return false # move was rejected: # rejections incremented else # keep hybrid flip move. If a γ became 0, optimizestructure will remove the edge return true # move was accepted: # rejections will be reset to zero end end """ updateSSM!(obj::SSM, renumber=false::Bool; constraints=TopologyConstraint[]::Vector{TopologyConstraint}) After adding or removing a hybrid, displayed trees will change. Updates the displayed tree list. Return SSM object. if `renumber`, reorder edge and internal node numbers. Only need to renumber after deleting a hybrid (which could remove edges and nodes from the middle of the edge and node lists). Assumptions: - The SSM object has cache arrays of size large enough, that is, the constructor [`StatisticalSubstitutionModel`](@ref) was previously called with maxhybrid equal or greater than in `obj.net`. `obj.priorltw` is not part of the "cache" arrays. Warning: Does not update the likelihood. ```jldoctest julia> net = readTopology("(((A:2.0,(B:1.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5,D:2.0);"); julia> fastafile = abspath(joinpath(dirname(Base.find_package("PhyloNetworks")), "..", "examples", "simple.aln")); julia> obj = PhyloNetworks.StatisticalSubstitutionModel(net, fastafile, :JC69; maxhybrid=3); julia> PhyloNetworks.checknetwork_LiNC!(obj.net, 3, true, true); julia> using Random; Random.seed!(432); julia> PhyloNetworks.addhybridedge!(obj.net, obj.net.edge[8], obj.net.edge[1], true, 0.0, 0.4); julia> writeTopology(obj.net) "(((B:1.0)#H1:0.1::0.9,(A:1.0)#H2:1.0::0.6):1.5,(C:0.6,#H1:1.0::0.1):1.0,(D:1.25,#H2:0.0::0.4):1.25);" julia> length(obj.displayedtree) # still as if 1 single reticulation 2 julia> PhyloNetworks.updateSSM!(obj); julia> length(obj.displayedtree) # now correct 4 displayed treess: 2 reticulations 4 ``` """ function updateSSM!(obj::SSM, renumber=false::Bool; constraints=TopologyConstraint[]::Vector{TopologyConstraint}) if renumber # traits are in leaf.number order, so leaf nodes not reordered resetNodeNumbers!(obj.net; checkPreorder=false, type=:internalonly) # preorder not used when type = internalonly resetEdgeNumbers!(obj.net, false) # verbose=false updateconstraintfields!(constraints, obj.net) end # extract displayed trees, with the default keeporiginalroot=false # because PhyLiNC assumes a reversible model and moves the root around: # displayed trees should not have any dangling node nor root of degree 1 # (which are equivalent via re-rooting) obj.displayedtree = displayedTrees(obj.net, 0.0; nofuse=true) for tree in obj.displayedtree preorder!(tree) # no need to call directEdges!: already correct in net end # log tree weights: sum log(γ) over edges, for each displayed tree updateSSM_priorltw!(obj) @debug begin all(!ismissing, obj.priorltw) ? "" : "one or more inheritance γ's are missing or negative. fix using setGamma!(network, edge)" end return obj end # ! requires correct displayed trees. If not, first call updatedisplayedtrees! function updateSSM_priorltw!(obj::SSM) pltw = obj.priorltw resize!(pltw, length(obj.displayedtree)) for (i,t) in enumerate(obj.displayedtree) @inbounds pltw[i] = inheritanceWeight(t) end return nothing end # updates displayed trees when one gamma changes function updatedisplayedtrees!(trees::Vector, enum::Int, pnum::Int, gammae::Float64, hase::Vector) gammap = 1.0 - gammae for (i,t) in enumerate(trees) h = hase[i] ismissing(h) && continue # tree doesn't have either e nor partner ei = (h ? findfirst(e -> e.number == enum, t.edge) : findfirst(e -> e.number == pnum, t.edge)) t.edge[ei].gamma = (h ? gammae : gammap) end end """ updateSSM_root!(obj::SSM) Update root and direction of edges in displayed trees to match the root in the network. """ function updateSSM_root!(obj::SSM) netroot = obj.net.node[obj.net.root] rnum = netroot.number rootabsent = false # The new root may have been a dangling node in one of the displayed trees, # so would be absent. Dangling nodes need to be deleted (no data to # initialize the tree traversal), so a root of degree 1 should be deleted # too. Otherwise: could become a dangling node after re-rooting. for tre in obj.displayedtree r = findfirst(n -> n.number == rnum, tre.node) if isnothing(r) rootabsent = true break end tre.root = r directEdges!(tre) preorder!(tre) end if rootabsent # then re-create all displayed trees: will be corrected rooted obj.displayedtree = displayedTrees(obj.net, 0.0; nofuse=true) for tree in obj.displayedtree preorder!(tree) # no need to call directEdges!: already correct in net end # After re-extracting, the displayed trees come in the same order as before: # no need to update the priorltw end end """ startingBL!(net::HybridNetwork, trait::AbstractVector{Vector{Union{Missings.Missing,Int}}}, siteweight=ones(length(trait[1]))::AbstractVector{Float64}) Calibrate branch lengths in `net` by minimizing the mean squared error between the JC-adjusted pairwise distance between taxa, and network-predicted pairwise distances, using [`calibrateFromPairwiseDistances!`](@ref). `siteweight[k]` gives the weight of site (or site pattern) `k` (default: all 1s). Note: the network is not "unzipped". PhyLiNC unzips reticulations later. Assumptions: - all species have the same number of traits (sites): `length(trait[i])` constant - `trait[i]` is for leaf with `node.number = i` in `net`, and `trait[i][j] = k` means that leaf number `i` has state index `k` for trait `j`. These indices are those used in a substitution model: kth value of `getlabels(model)`. - Hamming distances are < 0.75 with four states, or < (n-1)/n for n states. If not, all pairwise hamming distances are scaled by `.75/(m*1.01)` where `m` is the maximum observed hamming distance, to make them all < 0.75. """ function startingBL!(net::HybridNetwork, trait::AbstractVector{Vector{Union{Missings.Missing,Int}}}, siteweight=ones(length(trait[1]))::AbstractVector{Float64}) nspecies = net.numTaxa M = zeros(Float64, nspecies, nspecies) # pairwise distances initialized to 0 # count pairwise differences, then multiply by pattern weight ncols = length(trait[1]) # assumption: all species have same # columns length(siteweight) == ncols || error("$(length(siteweight)) site weights but $ncols columns in the data") for i in 2:nspecies species1 = trait[i] for j in 1:(i-1) species2 = trait[j] for col in 1:ncols if !(ismissing(species1[col]) || ismissing(species2[col])) && (species1[col] != species2[col]) M[i, j] += siteweight[col] end end M[j,i] = M[i,j] end end Mp = M ./ sum(siteweight) # to get proportion of sites, for each pair # estimate pairwise evolutionary distances using extended Jukes Cantor model nstates = mapreduce(x -> maximum(skipmissing(x)), max, trait) maxdist = (nstates-1)/nstates Mp[:] = Mp ./ max(maxdist, maximum(Mp*1.01)) # values in [0,0.9901]: log(1-Mp) well defined dhat = - maxdist .* log.( 1.0 .- Mp) taxonnames = [net.leaf[i].name for i in sortperm([n.number for n in net.leaf])] # taxon names: to tell the calibration that row i of dhat if for taxonnames[i] # ASSUMPTION: trait[i][j] = trait j for taxon at node number i: 'node.number' = i calibrateFromPairwiseDistances!(net, dhat, taxonnames, forceMinorLength0=true, ultrametric=false) # force minor length to 0 to avoid non-identifiability at zippers # works well if the true (or "the" best-fit) length of the minor parent # edge is less than the true length of the parent edge. # (zips all the way up instead of unzipping all the way down, as we do when the child edge = 0) for e in net.edge # avoid starting at the boundary if e.length < 1.0e-10 e.length = 0.0001 end end return net end #--------------- optimization of branch lengths --------------# """ CacheLengthLiNC(obj::SSM, ftolRel::Float64, ftolAbs::Float64, xtolRel::Float64, xtolAbs::Float64, maxeval::Int) Constructor from a `StatisticalSubstitutionModel` object, with tolerance values and parameters controlling the search. """ function CacheLengthLiNC(obj::SSM, ftolRel::Float64, ftolAbs::Float64, xtolRel::Float64, xtolAbs::Float64, maxeval::Int) k = nstates(obj.model) nt = size(obj._loglikcache, 3) # but: there might be fewer displayed trees nr = length(obj.ratemodel.ratemultiplier) ns = obj.nsites Prt = [MMatrix{k,k, Float64}(undef) for i in 1:nr] rQP = [MMatrix{k,k, Float64}(undef) for i in 1:nr] # defaultinstep = NLopt.initial_step(optBL, getlengths(edges)) # replace!(x -> min(x,0.1), defaultinstep) # 0.1 substitutions / site is kinda large # NLopt.initial_step!(optBL, defaultinstep) opt = NLopt.Opt(:LD_SLSQP, 1) # :LD_LBFGS would be another good choice NLopt.ftol_rel!(opt,ftolRel) # relative criterion NLopt.ftol_abs!(opt,ftolAbs) # absolute criterion NLopt.xtol_rel!(opt,xtolRel) NLopt.xtol_abs!(opt,xtolAbs) NLopt.maxeval!(opt, maxeval) # max number of iterations opt.lower_bounds = BLmin opt.upper_bounds = BLmax CacheLengthLiNC( Array{Float64}(undef, (k, ns, nr, nt)), # flike Array{Float64}(undef, (k, ns, nr, nt)), # dblike Vector{Bool}(undef, nt), # hase Prt, rQP, Vector{Float64}(undef, ns), opt, ) end """ updatecache_edge!(lcache::CacheLengthLiNC, obj::SSM, focusedge) Update fields in `lcache`, to correspond to the forward likelihood at the child node of the focus edge, backwards (at parent node) x directional (at sister edges) likelihoods, and keep track of which displayed trees do have the focus edge. These don't change if the length of the focus edge is modified. These quantities are then rescaled on the log scale (to get a max of 0) and exponentiated to get back to the probability scale. Assumptions: the following fields of `obj` are up-to-date: - displayed trees, with nodes preordered - prior log tree weights in `.priorltw` - log transition probabilities in `.logtrans` Output: - missing, if the edge length does not affect the likelihood, - constant used to rescale each site on the log scale, otherwise. """ function updatecache_edge!(lcache::CacheLengthLiNC, obj::SSM, focusedge) flike = lcache.flike dblike = lcache.dblike hase = lcache.hase tree = obj.displayedtree k, ns, nr, nt = size(flike) nt = length(tree) # could be less than dimensions in lcache # ! a sister edge in network may be absent in a displayed tree # but: edge & node numbers are the same in net and in trees v = getparent(focusedge) # ! focus edge needs same direction in displayed trees vnum = v.number unum = getchild(focusedge).number enum = focusedge.number snum = Int[] for e in v.edge if e !== focusedge && v == getparent(e) # then e sister to focus edge push!(snum, e.number) end end nsis = length(snum) # normally 1, 0 below hybrid node, 2 at root or at polytomies hassis = Array{Bool}(undef, (nsis,nt)) # is sister s in tree t? @inbounds for it in 1:nt hase[it] = any(x -> x.number == enum, tree[it].edge) for j in 1:nsis hassis[j,it] = any(x -> x.number == snum[j], tree[it].edge) end end # check if the edge affects the likelihood. It may not if: # the displayed trees that have the edge have a prior weight of 0. # Would pruning edges with weight 0 make the focus edge dangle? if all(i -> !hase[i] || obj.priorltw[i] == -Inf, 1:nt) # @debug "edge $(focusedge.number) does not affect the likelihood: skip optimization" return missing end lrw = obj.ratemodel.lograteweight ltw = obj.priorltw ftmp = obj.forwardlik btmp = obj.backwardlik dtmp = obj.directlik clik = obj._loglikcache # conditional likelihood: conditional on tree & rate fill!(flike, -Inf); fill!(dblike, -Inf) for it in 1:nt if hase[it] # we do need flike and dblike for ir in 1:nr ltrw = ltw[it] + lrw[ir] for is in 1:ns clik[is,ir,it] = discrete_corelikelihood_trait!(obj, it,is,ir) # ! +ltrw not needed discrete_backwardlikelihood_trait!(obj, it,ir) flike[:,is,ir,it] .= ftmp[:,unum] dblike[:,is,ir,it] .= btmp[:,vnum] .+ ltrw for isis in 1:nsis @inbounds if hassis[isis,it] dblike[:,is,ir,it] .+= dtmp[:,snum[isis]] # sum on log scale end end end; end else # tree does't have the focus edge: use clik only for ir in 1:nr ltrw = ltw[it] + lrw[ir] for is in 1:ns clik[is,ir,it] = discrete_corelikelihood_trait!(obj, it,is,ir) + ltrw end; end end end cf = maximum(flike) # unused values from trees without focus edge have -Inf cg = maximum(dblike) flike .= exp.(flike .- cf) dblike .= exp.(dblike .- cg) cfg = cf + cg # lcache.cadjust = cf + cg clik .= exp.(clik .- cfg) return cfg end """ optimizealllengths_LiNC!(obj::SSM, lcache::CacheLengthLiNC) Optimize all branch lengths, except those below hybrid edges (whose lengths are not identifiable). Same assumptions as in [`optimizelocalBL_LiNC!`](@ref). """ function optimizealllengths_LiNC!(obj::SSM, lcache::CacheLengthLiNC) edges = copy(obj.net.edge) # shallow copy # remove from edges # - constrained edges: to keep network unzipped, add # - and any hybrid edge with γ=0 if !isempty(obj.net.hybrid) @inbounds for i in length(edges):-1:1 e = edges[i] (getparent(e).hybrid || e.gamma == 0.0) && deleteat!(edges, i) end end # reduce edge lengths beyond upper bounds for e in edges if e.length > BLmax e.length = BLmax; end end update_logtrans(obj) qmat = Q(obj.model) Random.shuffle!(edges) for e in edges optimizelength_LiNC!(obj, e, lcache, qmat) end return edges # excludes constrained edges end """ optimizelocalBL_LiNC!(obj::SSM, edge::Edge, lcache::CacheLengthLiNC) Optimize branch lengths in `net` locally around `edge`. Update all edges that share a node with `edge` (including itself). Constrains branch lengths to zero below hybrid nodes. Return vector of updated `edges` (excluding constrained edges). The tolerance values and parameters controlling the search are set in `lcache`. Used after `nni!` or `addhybridedge!` moves to update local branch lengths. See [`phyLiNC!`](@ref). Assumptions: - displayed trees in `obj` are up-to-date with nodes preordered, and `obj.priorltw` are up-to-date. - branch lengths are at or above the lower bound, and definitely non-negative. ```jldoctest julia> net = readTopology("(((A:2.0,(B:0.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5,D:2.0);"); julia> fastafile = abspath(joinpath(dirname(Base.find_package("PhyloNetworks")), "..", "examples", "simple.aln")); julia> obj = PhyloNetworks.StatisticalSubstitutionModel(net, fastafile, :JC69); julia> obj.loglik = -Inf64; # not calculated yet julia> e = obj.net.edge[4]; julia> e.length 1.5 julia> using Random; Random.seed!(1234); julia> PhyloNetworks.optimizelocalBL_LiNC!(obj, e, PhyloNetworks.CacheLengthLiNC(obj, 1e-6,1e-6,1e-2,1e-2, 10)); julia> round(e.length, sigdigits=6) # we get the lower bound from PhyLiNC in this case 1.0e-8 julia> writeTopology(obj.net; round=true) "(((A:0.338,(B:0.0)#H1:0.04::0.9):0.0,(C:0.6,#H1:1.0::0.1):0.0):0.0,D:2.0);" ``` """ function optimizelocalBL_LiNC!(obj::SSM, focusedge::Edge, lcache::CacheLengthLiNC) neighboredges = adjacentedges(focusedge) # remove from neighboredges (shallow copy!) # - constrained edges: to keep network unzipped, and # - any hybrid edge with γ=0 if !isempty(obj.net.hybrid) @inbounds for i in length(neighboredges):-1:1 e = neighboredges[i] (getparent(e).hybrid || e.gamma == 0.0) && deleteat!(neighboredges, i) end end # reduce edge lengths beyond upper bounds: can appear from unzipping, for e in neighboredges # cycle shrinking, edges fused by deletehybridedge if e.length > BLmax e.length = BLmax; end end # assume: correct preordered displayed trees & tree weights update_logtrans(obj) # fixit: waste of time? avoid in some cases? qmat = Q(obj.model) for e in neighboredges optimizelength_LiNC!(obj, e, lcache, qmat) end return neighboredges # excludes constrained edges end """ optimizelength_LiNC!(obj::SSM, edge::Edge, cache::CacheLengthLiNC, Qmatrix) Optimize the length of a single `edge` using a gradient method, if `edge` is not below a reticulation (the unzipped canonical version should have a length of 0 below reticulations). Output: nothing. Warning: displayed trees are assumed up-to-date, with nodes preordered """ function optimizelength_LiNC!(obj::SSM, focusedge::Edge, lcache::CacheLengthLiNC, qmat) getparent(focusedge).hybrid && return nothing # keep the reticulation unzipped # the length of focus edge should be 0. stay as is. cfg = updatecache_edge!(lcache, obj, focusedge) ismissing(cfg) && return nothing flike = lcache.flike # P(descendants of e | state at child, rate, tree) dblike = lcache.dblike # P(non-descendants & state at parent, rate, tree) # if γ=0 then dblike starts as all -Inf because P(tree) = 0 -> problem # this problem is caught earlier: cfg would have been missing. hase = lcache.hase Prt = lcache.Prt # to hold exp(rtQ) matrices (one matrix for each r) rQP = lcache.rQP # d/dt of exp(rtQ) = rQ * Prt glik = lcache.glik # d/dt of site likelihoods ulik. length: # sites tree = obj.displayedtree k, ns, nr, nt = size(flike) nt = length(tree) # could be less than dimension in lcache (if network isn't tree-child) rates = obj.ratemodel.ratemultiplier ulik = obj._sitecache # will hold P(site): depends on length of e clik = obj._loglikcache # P(site & rate, tree) using old length of e adjustment = obj.totalsiteweight * cfg # use site weights, if any wsum = (isnothing(obj.siteweight) ? sum : x -> sum(x .* obj.siteweight)) # objective to maximize: overall log-likelihood function objective(t::Vector, grad::Vector) len = t[1] # candidate branch length @inbounds for ir in 1:nr P!(Prt[ir], obj.model, len * rates[ir]) lmul!(rates[ir], mul!(rQP[ir], qmat, Prt[ir])) # in-place multiplication end # integrate over trees & rates fill!(ulik, 0.0); fill!(glik, 0.0) for it in 1:nt if hase[it] # tree has edge: contributes to gradient for is in 1:ns for ir in 1:nr # dot(x,A,y) requires Julia 1.4, and fails with Optim v0.19.3 # u += dot(dblike[:,is,ir,it], Prt[ir], flike[:,is,ir,it]) # g += dot(dblike[:,is,ir,it], rQP[ir], flike[:,is,ir,it]) @inbounds for i in 1:k for j in 1:k ulik[is] += dblike[i,is,ir,it] * Prt[ir][i,j] * flike[j,is,ir,it] glik[is] += dblike[i,is,ir,it] * rQP[ir][i,j] * flike[j,is,ir,it] end; end end end else # tree doesn't have focus edge: use clik only, gradient=0 for is in 1:ns for ir in 1:nr ulik[is] += clik[is,ir,it] # already exp-ed inside updatecache_edge! end end end end # product over sites (or sum on log scale) loglik = wsum(log.(ulik)) if length(grad) > 0 # finish gradient calculation glik ./= ulik grad[1] = wsum(glik) #@show grad[1] end #@show loglik + adjustment return loglik end #= oldlik = objective([focusedge.length], [0.0]) + adjustment oldlik ≈ obj.loglik || @warn "oldlik $oldlik != stored lik $(obj.loglik): starting NNI?" # obj.loglik outdated at the start of an NNI move: # it is for the older, not the newly proposed topology =# optBL = lcache.opt NLopt.max_objective!(optBL, objective) fmax, xmax, ret = NLopt.optimize(optBL, [focusedge.length]) newlik = fmax + adjustment if ret == :FORCED_STOP # || oldlik > newlik @warn "failed optimization, edge $(focusedge.number): skipping branch length update." return nothing end focusedge.length = xmax[1] obj.loglik = newlik update_logtrans(obj, focusedge) # obj.logtrans updated according to new edge length return nothing end #= Note: This is an unused attempt to use the hessian and the Optim package. function optimizelength_LiNC!(obj::SSM, focusedge::Edge, lcache::CacheLengthLiNC) fun = objective(t) # returns vector [loglik,gradient,hessian] f = x::Vector -> -fun(x[1])[1] # minimize -loglik function g!(g,x::Vector) g = [-fun(x[1])[2]] end function h!(h,x::Vector) h = [-fun(x[1])[3]] end x0 = [focusedge.length] df = TwiceDifferentiable(f, g!, h!, x0) lx = [0.]; ux = [Inf]; dfc = TwiceDifferentiableConstraints(lx, ux) res = Optim.optimize(df, dfc, x0, IPNewton()) end =# #--------------- optimization of inheritance γ --------------# """ optimizeallgammas_LiNC!(obj::SSM, ftolAbs::Float64, γcache::CacheGammaLiNC, maxeval=1000::Int) Optimize all γ's in a network, one by one using [`optimizegamma_LiNC!`] until `maxeval` γ's have been optimized or until the difference in log-likelihood falls below `ftolAbs`. At the end: hybrid edges with γ=0 are deleted (if any). Output: true if reticulations have been deleted, false otherwise. If true, `updateSSM!` needs to be called afterwards, with constraints if any. (Constraints are not known here). Before updating the displayed trees in the SSM, [`shrink2cycles!`](@ref) or [`shrink3cycles!`](@ref) could be called, if desired, despite the (slight?) change in likelihood that this shrinking would cause. 2/3-cycles are *not* shrunk here. """ function optimizeallgammas_LiNC!(obj::SSM, ftolAbs::Float64, γcache::CacheGammaLiNC, maxeval::Int) hybnodes = obj.net.hybrid nh = length(hybnodes) # also = obj.net.numHybrids if nh==0 return false; end # no gammas to optimize hybs = [getparentedgeminor(h) for h in hybnodes] discrete_corelikelihood!(obj) # prerequisite for optimizegamma_LiNC! nevals = 0 ll = obj.loglik llnew = +Inf; lldiff = +Inf while nevals < maxeval && lldiff > ftolAbs for he in hybs llnew = optimizegamma_LiNC!(obj, he, ftolAbs, γcache) end lldiff = llnew - ll ll = llnew nevals += nh end ghosthybrid = false hi = nh while hi > 0 he = getparentedgeminor(hybnodes[hi]) if he.gamma == 0.0 deletehybridedge!(obj.net, he, false,true,false,false,false) ghosthybrid = true nh = length(hybnodes) # normally nh-1, but could be less: deleting # one hybrid may delete others indirectly, e.g. if hybrid ladder # or if generation of a 2-cycle end hi -= 1 if hi>nh hi=nh; end end return ghosthybrid end """ optimizelocalgammas_LiNC!(obj::SSM, edge::Edge, ftolAbs::Float64, γcache::CacheGammaLiNC, maxeval=1000::Int) Optimize γ's in `net` locally around `edge`. Update all edges adjacent to `edge` (including itself), one by one using [`optimizegamma_LiNC!`] until `maxeval` γ's have been optimized or until the difference in log-likelihood falls below `ftolAbs`. `nothing` is returned. Used after `nni!` or `addhybridedge!` moves to update local gammas. Assumptions: - correct `isChild1` field for `edge` and for hybrid edges - no in-coming polytomy: a node has 0, 1 or 2 parents, no more ```jldoctest julia> net = readTopology("(((A:2.0,(B:1.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5,D:2.0);"); julia> fastafile = abspath(joinpath(dirname(Base.find_package("PhyloNetworks")), "..", "examples", "simple.aln")); julia> obj = PhyloNetworks.StatisticalSubstitutionModel(net, fastafile, :JC69); julia> obj.net.edge[3].gamma 0.9 julia> using Random; Random.seed!(1234); julia> PhyloNetworks.optimizelocalgammas_LiNC!(obj, obj.net.edge[3], 1e-3, PhyloNetworks.CacheGammaLiNC(obj)); julia> obj.net.edge[3].gamma 0.0 ```` """ function optimizelocalgammas_LiNC!(obj::SSM, edge::Edge, ftolAbs::Float64, γcache::CacheGammaLiNC, maxeval=1000::Int) # get edges that are: hybrid and adjacent to edge neighborhybs = Edge[] for e in edge.node[1].edge e.hybrid || continue # below: e is a hybrid edge push!(neighborhybs, e) end for e in edge.node[2].edge e.hybrid || continue e === edge && continue push!(neighborhybs, e) end # next: keep minor edges, and replace major hybrid edges # by their minor partner if not already in the list for i in length(neighborhybs):-1:1 e = neighborhybs[i] e.isMajor || continue # skip below for minor edges p = getpartneredge(e) # minor partner j = findfirst(x -> x===p, neighborhybs) if isnothing(j) neighborhybs[i] = p # replace major e by its minor partner else deleteat!(neighborhybs,i) # delete e end end nh = length(neighborhybs) if nh==0 return nothing end discrete_corelikelihood!(obj) # prerequisite for optimizegamma_LiNC! nevals = 0 ll = obj.loglik llnew = +Inf; lldiff = +Inf while nevals < maxeval && lldiff > ftolAbs for he in neighborhybs llnew = optimizegamma_LiNC!(obj, he, ftolAbs, γcache) end lldiff = llnew - ll ll = llnew nevals += nh end return nothing end """ optimizegamma_LiNC!(obj::SSM, focusedge::Edge, ftolAbs::Float64, cache::CacheGammaLiNC, maxNR=10::Int) Optimize γ on a single hybrid `edge` using the Newton-Raphson method (the log-likelihood is concave). The new log-likelihood is returned after updating `obj` and its fields with the new γ. The search stops if the absolute difference in log-likelihood between two consecutive iterations is below `ftolAbs`, or after `maxNR` Newton-Raphson iterations. Warnings: - no check that `edge` is hybrid - `obj._loglikcache` and displayed trees (etc.) are assumed to be up-to-date, and is updated alongside the new γ. Used by [`optimizelocalgammas_LiNC!`](@ref) and [`optimizeallgammas_LiNC!`](@ref). """ function optimizegamma_LiNC!(obj::SSM, focusedge::Edge, ftolAbs::Float64, cache::CacheGammaLiNC, maxNR=10::Int) ## step 1: prepare vectors constant during the search edgenum = focusedge.number partner = getpartneredge(focusedge) partnernum = partner.number clike = cache.clike # conditional likelihood under focus edge clikp = cache.clikp # conditional likelihood under partner edge clikn = cache.clikn # conditional lik under no focus edge nor partner edge ulik = obj._sitecache # unconditional likelihood and more llca = obj._loglikcache fill!(clike, 0.0); fill!(clikp, 0.0) fill!(clikn, 0.0) nt, hase = updatecache_hase!(cache, obj, edgenum, partnernum) γ0 = focusedge.gamma visib = !any(ismissing, hase) # reticulation visible in *all* displayed trees? # check that the likelihood depends on the edge's γ: may not be the case # if displayed trees who have the edge or its partner have prior weight 0 # Would pruning edges with weight 0 make the focus edge dangle? if all(i -> ismissing(hase[i]) || obj.priorltw[i] == -Inf, 1:nt) # @debug "γ does not affect the likelihood: skip optimization" return obj.loglik end if γ0<1e-7 # then prior weight and loglikcachetoo small (-Inf if γ0=0) # @debug "γ0 too small ($γ0): was changed to 1e-7 prior to optimization" γ0 = 1e-7 setGamma!(focusedge, γ0) updatedisplayedtrees!(obj.displayedtree, edgenum, partnernum, γ0, hase) updateSSM_priorltw!(obj) discrete_corelikelihood!(obj) # to update obj._loglikcache elseif γ0>0.9999999 # @debug "γ0 too large ($γ0): was changed to 1 - 1e-7 prior to optimization" γ0 = 0.9999999 setGamma!(focusedge, γ0) updatedisplayedtrees!(obj.displayedtree, edgenum, partnernum, γ0, hase) updateSSM_priorltw!(obj) discrete_corelikelihood!(obj) # to update obj._loglikcache end # obj._loglikcache[site,rate,tree] = log P(site & tree,rate) cadjust = maximum(view(llca, :,:,1:nt)) # to avoid underflows nr = length(obj.ratemodel.ratemultiplier) for it in 1:nt # sum likelihood over all displayed trees @inbounds h = hase[it] if ismissing(h) # tree doesn't have e nor partner for ir in 1:nr # sum over all rate categories clikn .+= exp.(llca[:,ir,it] .- cadjust) end elseif h # tree has e for ir in 1:nr # sum over all rate categories clike .+= exp.(llca[:,ir,it] .- cadjust) end else # tree has partner edge for ir in 1:nr clikp .+= exp.(llca[:,ir,it] .- cadjust) end end end ## step 2: Newton-Raphson clike ./= γ0 clikp ./= 1.0 - γ0 adjustment = obj.totalsiteweight * cadjust ll = obj.loglik - adjustment wsum = (obj.siteweight === nothing ? sum : x -> sum(obj.siteweight .* x)) # evaluate if best γ is at the boundary: 0 or 1 if visib # true most of the time (all the time if tree-child) ulik .= (clike .- clikp) ./ clikp # avoids adding extra long vector of zeros else ulik .= (clike .- clikp) ./ (clikp .+ clikn); end # derivative of loglik at γ=0 llg0 = wsum(ulik) inside01 = true if llg0 <= 0.0 # if llg0 = 0, something fishy is happening or data has no variation γ = 0.0 inside01 = false ll = wsum((visib ? log.(clikp) : log.(clikp .+ clikn))) # @debug "γ = 0 best, skip Newton-Raphson" else # at γ=1 if visib ulik .= (clike .- clikp) ./ clike else ulik .= (clike .- clikp) ./ (clike .+ clikn); end llg1 = wsum(ulik) if llg1 >= 0.0 # if llg1 = 0.0, data has no variation γ = 1.0 inside01 = false ll = wsum((visib ? log.(clike) : log.(clike .+ clikn))) # @debug "γ = 1 best, skip Newton-Raphson" end end if inside01 # use interpolation to get a good starting point? γ = llg0 / (llg0 - llg1) in [0,1] γ = γ0 if visib ulik .= γ .* clike + (1.0-γ) .* clikp else ulik .= γ .* clike + (1.0-γ) .* clikp .+ clikn; end # ll: rescaled log likelihood. llg = gradient, llh = hessian below for istep in 1:maxNR # ll from above is also: sum(obj.siteweight .* log.(ulik))) ulik .= (clike .- clikp) ./ ulik # gradient of unconditional lik llg = wsum(ulik) map!(x -> x^2, ulik, ulik) # now ulik = -hessian contributions llh = - wsum(ulik) cγ = γ - llg/llh # candidate γ: will be new γ if inside (0,1) if cγ >= 1.0 γ = γ/2 + 0.5 elseif cγ <= 0.0 γ = γ/2 else γ = cγ end if visib ulik .= γ .* clike + (1.0-γ) .* clikp else ulik .= γ .* clike + (1.0-γ) .* clikp + clikn; end ll_new = wsum(log.(ulik)) lldiff = ll_new - ll ll = ll_new lldiff < ftolAbs && break end end ## step 3: update SSM object with new γ focusedge.gamma = γ partner.gamma = 1.0 - γ newmajor = γ > 0.5 if newmajor != focusedge.isMajor focusedge.isMajor = newmajor partner.isMajor = !newmajor # fixit: check clade constraints. perhaps at the start: # if this was problematic for constraints, restrict the search # to interval [0,0.5] or [0.5,1] as appropriate end ll += adjustment obj.loglik = ll lγdiff = log(γ) - log(γ0); l1mγdiff = log(1.0-γ) - log(1.0-γ0) for it in 1:nt @inbounds h = hase[it] ismissing(h) && continue # tree has unchanged weight: skip below obj.priorltw[it] += (h ? lγdiff : l1mγdiff) llca[:,:,it] .+= (h ? lγdiff : l1mγdiff) end return ll end function updatecache_hase!(cache::CacheGammaLiNC, obj::SSM, edgenum::Int, partnernum::Int) nt = length(obj.displayedtree) # could change if non-tree-child net hase = cache.hase resize!(hase, nt) for i in 1:nt @inbounds t = obj.displayedtree[i] @inbounds hase[i] = missing for e in t.edge if e.number == edgenum @inbounds hase[i] = true break elseif e.number == partnernum @inbounds hase[i] = false break end end end return nt, hase end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
62832
# functions to calculate the pseudolik function # originally in functions.jl # Claudia March 2015 # -------------------- delete Leaf------------------------------------- # aux function to make a hybrid node a tree node # used in deleteLeaf # input: hybrid node function makeNodeTree!(net::Network, hybrid::Node) hybrid.hybrid || error("cannot make node $(hybrid.number) tree node because it already is") @debug "we make node $(hybrid.number) a tree node, but it can still have hybrid edges pointing at it, hasHybEdge set to false" hybrid.gammaz = -1 hybrid.isBadDiamondI = false hybrid.isBadDiamondII = false hybrid.isBadTriangle = false hybrid.k = -1 removeHybrid!(net,hybrid) hybrid.hybrid = false hybrid.hasHybEdge = false hybrid.name = "" end # aux function to make a hybrid edge tree edge # used in deleteLeaf # input: edge and hybrid node it pointed to function makeEdgeTree!(edge::Edge, node::Node) edge.hybrid || error("cannot make edge $(edge.number) tree because it is tree already") node.hybrid || error("need the hybrid node at which edge $(edge.number) is pointing to, node $(node.number) is tree node") @debug "we make edge $(edge.number) a tree edge, but it will still point to hybrid node $(node.number)" edge.hybrid = false edge.isMajor = true edge.gamma = 1.0 edge.inCycle = -1 #warn:changed recently because I believe it does not affect the parameters function for bad diamond I other = getOtherNode(edge,node) hyb = false for e in other.edge #is it attached to other hybrid? if(e.hybrid) hyb = true end end other.hasHybEdge = hyb edge.istIdentifiable = isEdgeIdentifiable(edge) end # function to delete internal nodes until there is no # more internal node with only two edges # calls deleteIntLeaf! inside a while # returns middle node (see ipad drawing) # negative=true allows negative branch lengths function deleteIntLeafWhile!(net::Network, middle::Node, leaf::Node, negative::Bool) while(size(middle.edge,1) == 2) middle = deleteIntLeaf!(net,middle,leaf, negative) end return middle end deleteIntLeafWhile!(net::Network, middle::Node, leaf::Node) = deleteIntLeafWhile!(net, middle, leaf, false) # function to delete internal nodes until there is no # more internal node with only two edges # calls deleteIntLeaf! inside a while # negative=true allows negative branch lengths function deleteIntLeafWhile!(net::Network, leafedge::Edge, leaf::Node, negative::Bool) middle = getOtherNode(leafedge, leaf) while(size(middle.edge,1) == 2) middle = deleteIntLeaf!(net,middle,leaf, negative) end end deleteIntLeafWhile!(net::Network, leafedge::Edge, leaf::Node) = deleteIntLeafWhile!(net, leafedge, leaf, false) # function to delete an internal node in an external edge # input: network, internal node and leaf # returns the new middle # note: leafedge is the edge that survives # negative=true allows negative branch lengths function deleteIntLeaf!(net::Network, middle::Node, leaf::Node, negative::Bool) #println("calling deleteIntLeaf for middle $(middle.number) and leaf $(leaf.number)") if(size(middle.edge,1) == 2) if(isEqual(getOtherNode(middle.edge[1],middle),leaf)) leafedge = middle.edge[1] otheredge = middle.edge[2] elseif(isEqual(getOtherNode(middle.edge[2],middle),leaf)) leafedge = middle.edge[2] otheredge = middle.edge[1] else error("leaf $(leaf.number) is not attached to internal node $(middle.number) by any edge") end othernode = getOtherNode(otheredge,middle) setLength!(leafedge,leafedge.length + otheredge.length, negative) removeNode!(middle,leafedge) removeEdge!(othernode,otheredge) setNode!(leafedge,othernode) setEdge!(othernode,leafedge) deleteNode!(net,middle) deleteEdge!(net,otheredge) return othernode else @error "internal node $(middle.number) does not have two edges only, it has $(size(middle.edge,1))" end end deleteIntLeaf!(net::Network, middle::Node, leaf::Node) = deleteIntLeaf!(net, middle, leaf, false) # function to delete an internal node in an external edge # input: network, edge (from leaf.edge) to move in that direction and leaf # returns the new middle # note: leafedge is the edge that survives # negative=true allows negative branch lengths function deleteIntLeaf!(net::Network, leafedge::Edge, leaf::Node, negative::Bool) middle = getOtherNode(leafedge,leaf) if(size(middle.edge,1) == 2) if(isEqual(getOtherNode(middle.edge[1],middle),leaf)) otheredge = middle.edge[2] elseif(isEqual(getOtherNode(middle.edge[2],middle),leaf)) otheredge = middle.edge[1] else error("leaf $(leaf.number) is not attached to internal node $(middle.number) by any edge") end othernode = getOtherNode(otheredge,middle) setLength!(leafedge,leafedge.length + otheredge.length, negative) removeNode!(middle,leafedge) removeEdge!(othernode,otheredge) setNode!(leafedge,othernode) setEdge!(othernode,leafedge) deleteNode!(net,middle) deleteEdge!(net,otheredge) return othernode else @error "internal node $(middle.number) does not have two edges only, it has $(size(middle.edge,1))" end end deleteIntLeaf!(net::Network, leafedge::Edge, leaf::Node) = deleteIntLeaf!(net, leafedge, leaf, false) # fixit: still missing to test hybrid-> bad triangle II and # normal case (not bad triangle/diamond) of hasHybEdge # and normal case, delete not hybrid leaf bad triangle II function deleteLeaf!(net::Network, leaf::Node) leaf.leaf || error("node $(leaf.number) is not a leaf, cannot delete it") isNodeNumIn(leaf,net.leaf) || error("node $(leaf.number) is not in net.leaf, cannot delete it") size(leaf.edge,1) == 1 || error("strange leaf $(leaf.number) with $(size(leaf.edge,1)) edges instead of 1") other = getOtherNode(leaf.edge[1],leaf); DEBUGC && @debug "leaf is $(leaf.number) and other is $(other.number)" if(other.hybrid) DEBUGC && @debug "entra al caso other is hybrid node, other is $(other.number)" edge1,edge2 = hybridEdges(other,leaf.edge[1]); @debug "edge1 $(edge1.number), edge2 $(edge2.number)" (edge1.hybrid && edge2.hybrid) || error("hybrid node $(other.node) does not have two hybrid edges, they are tree edges: $(edge1.number), $(edge2.number)") other1 = getOtherNode(edge1,other); other2 = getOtherNode(edge2,other); @debug "in deleteLeaf, other hybrid node, other1 $(other1.number), other2 $(other2.number)" removeEdge!(other1,edge1) removeEdge!(other2,edge2) deleteEdge!(net,edge1) deleteEdge!(net,edge2) deleteEdge!(net,leaf.edge[1]) deleteNode!(net,other) deleteNode!(net,leaf) if(size(other1.edge,1) == 2 && isNodeNumIn(other1,net.node)) # need to delete internal nodes with only 2 edges (one of them external edge) node = getOtherNode(other1.edge[1],other1) leaf1 = node.leaf ? node : getOtherNode(other1.edge[2],other1) DEBUGC && @debug "other1 si tiene solo dos edges, y leaf1 es $(leaf1.number)" if(leaf1.leaf) deleteIntLeafWhile!(net,other1,leaf1); end end if(size(other2.edge,1) == 2 && isNodeNumIn(other2,net.node)) node = getOtherNode(other2.edge[1],other2) leaf1 = node.leaf ? node : getOtherNode(other2.edge[2],other2) DEBUGC && @debug "other2 si tiene solo dos edges, y leaf1 es $(leaf1.number)" if(leaf1.leaf) deleteIntLeafWhile!(net,other2,leaf1); end end if(length(other1.edge) == 1 && isNodeNumIn(other1,net.node)) #internal node with only one edge !other1.leaf || error("node $(other1.number) was attached no hybrid edge, cannot be a leaf") removeWeirdNodes!(net,other1) end if(length(other2.edge) == 1 && isNodeNumIn(other2,net.node)) !other2.leaf || error("node $(other2.number) was attached no hybrid edge, cannot be a leaf") removeWeirdNodes!(net,other2) end else if(other.hasHybEdge) @debug "entro a caso tree node has hyb edge" edge1,edge2 = hybridEdges(other,leaf.edge[1]); (edge1.hybrid || edge2.hybrid) || error("node $(other.number) has hybrid edge attribute true, but the edges $(edge1.number), $(edge2.number) are not hybrid (and the third edge has a leaf $(leaf.number)") other1 = getOtherNode(edge1,other); other2 = getOtherNode(edge2,other); # warning: if something changed for other1, also need to do for other2 if(other1.hybrid) if(other1.isBadDiamondI) edgemaj,edgemin,edgebla = hybridEdges(other1) edge4 = isEqual(edge1,edgemaj) ? edgemin : edgemaj other3 = getOtherNode(edge4,other1) ind = isEqual(getOtherNode(edgemaj,other1),other3) ? 1 : 2 edgebla,edge3,edge5 = hybridEdges(other3) leaf5 = getOtherNode(edge5,other3) DEBUGC && @debug "edge2 is $(edge2.number) and is identifiable $(edge2.istIdentifiable)" edge2.fromBadDiamondI = true # to keep track of edges from bad diamondI removeNode!(other,edge2) removeEdge!(other1,edge1) setNode!(edge2,other1) setEdge!(other1,edge2) other3.gammaz != -1 || error("hybrid node $(other1.number) is bad diamond, but for node $(other3.number), gammaz is not well updated, it is $(other3.gammaz)") DEBUGC && @debug "entro a cambiar length en edge $(edge2.number) con gammaz $(other3.gammaz)" setLength!(edge2,-log(1-other3.gammaz)) edge2.number = parse(Int,string(string(other1.number),string(ind))) DEBUGC && @debug "edge2 is $(edge2.number) should be not identifiable now $(edge2.istIdentifiable)" makeEdgeTree!(edge4,other1) makeNodeTree!(net,other1) removeEdge!(other2,edge3) removeEdge!(other3,edge3) deleteNode!(net,other) deleteEdge!(net,edge1) deleteEdge!(net,edge3) removeNode!(other3,edge4) removeEdge!(leaf5,edge5) setNode!(edge4,leaf5) setEdge!(leaf5,edge4) setLength!(edge4,edge5.length) deleteNode!(net,other3) deleteEdge!(net,edge5) other1.hasHybEdge = false @debug begin printEdges(net); "printed edged" end else removeEdge!(other,leaf.edge[1]) edgebla,edgebla,treeedge = hybridEdges(other1) if(getOtherNode(treeedge,other1).leaf) setLength!(edge1,edge2.length+edge1.length) removeEdge!(other2,edge2) removeNode!(other,edge1) setNode!(edge1,other2) setEdge!(other2,edge1) deleteEdge!(net,edge2) deleteNode!(net,other) end end deleteNode!(net,leaf) deleteEdge!(net,leaf.edge[1]) elseif(other2.hybrid) if(other2.isBadDiamondI) edgemaj,edgemin,edgebla = hybridEdges(other2) edge4 = isEqual(edge2,edgemaj) ? edgemin : edgemaj other3 = getOtherNode(edge4,other2) ind = isEqual(getOtherNode(edgemaj,other2),other3) ? 1 : 2 edgebla,edge3,edge5 = hybridEdges(other3) leaf5 = getOtherNode(edge5,other3) DEBUGC && @debug "edge1 is $(edge1.number) and is identifiable $(edge1.istIdentifiable)" edge1.fromBadDiamondI = true # to keep track of edges from bad diamondI removeNode!(other,edge1) removeEdge!(other2,edge2) setNode!(edge1,other2) setEdge!(other2,edge1) other3.gammaz != -1 || error("hybrid node $(other2.number) is bad diamond, but for node $(other3.number), gammaz is not well updated, it is $(other3.gammaz)") setLength!(edge1,-log(1-other3.gammaz)) edge1.number = parse(Int,string(string(other2.number),string(ind))) DEBUGC && @debug "edge1 is $(edge1.number) should be not identifiable now $(edge1.istIdentifiable)" makeEdgeTree!(edge4,other2) makeNodeTree!(net,other2) removeEdge!(other1,edge3) removeEdge!(other3,edge3) deleteNode!(net,other) deleteEdge!(net,edge2) deleteEdge!(net,edge3) removeNode!(other3,edge4) removeEdge!(leaf5,edge5) setNode!(edge4,leaf5) setEdge!(leaf5,edge4) setLength!(edge4,edge5.length) deleteNode!(net,other3) deleteEdge!(net,edge5) else removeEdge!(other,leaf.edge[1]) edgebla,edgebla,treeedge = hybridEdges(other2) if(getOtherNode(treeedge,other2).leaf) setLength!(edge2,edge2.length+edge1.length) removeEdge!(other1,edge1) removeNode!(other,edge2) setNode!(edge2,other1) setEdge!(other1,edge2) deleteEdge!(net,edge1) deleteNode!(net,other) end end deleteNode!(net,leaf) deleteEdge!(net,leaf.edge[1]) else error("node $(other.number) has hybrid edge, but neither of the other nodes $(other1.number), $(other2.number) are hybrid") end else # other is tree node without hybrid edges DEBUGC && @debug "entra al caso other is tree node no hyb edges" if(length(other.edge) == 2) edge1 = isEqual(other.edge[1],leaf.edge[1]) ? other.edge[2] : other.edge[1] other1 = getOtherNode(edge1,other) removeEdge!(other1,edge1) removeNode!(other1,edge1) deleteNode!(net,other) deleteNode!(net,leaf) deleteEdge!(net,leaf.edge[1]) deleteEdge!(net,edge1) DEBUGC && @debug "other1 is $(other1.number)" if(size(other1.edge,1) == 2 && isNodeNumIn(other1,net.node)) # need to delete internal nodes with only 2 edges (one of them external edge) node = getOtherNode(other1.edge[1],other1) leaf1 = node.leaf ? node : getOtherNode(other1.edge[2],other1) DEBUGC && @debug "other1 si tiene solo dos edges, y leaf1 es $(leaf1.number)" if(leaf1.leaf) other1 = deleteIntLeafWhile!(net,other1,leaf1); end end if(other1.hybrid && length(other1.edge) == 2) DEBUGC && @debug "entra a tratar de arreglar a other1 $(other1.number)" removeWeirdNodes!(net,other1) end if(length(other1.edge) == 1 && isNodeNumIn(other1,net.node)) #internal node with only one edge DEBUGC && @debug "entra a tratar de arreglar a other1 $(other1.number)" !other1.leaf || error("node $(other1.number) was attached no leaf edge, cannot be a leaf") removeWeirdNodes!(net,other1) end else edge1,edge2 = hybridEdges(other,leaf.edge[1]); other1 = getOtherNode(edge1,other); other2 = getOtherNode(edge2,other); removeEdge!(other,leaf.edge[1]) deleteNode!(net,leaf) deleteEdge!(net,leaf.edge[1]) if(other1.leaf || other2.leaf) (!other1.leaf || !other2.leaf) || error("just deleted a leaf $(leaf.number) and its two attached nodes are leaves also $(other1.number), $(other2.number)") newleaf = other1.leaf ? other1 : other2 middle = other DEBUGC && @debug "middle is $(middle.number), middle.hybrid $(middle.hybrid), middle.hasHybEdge $(middle.hasHybEdge)" middle = deleteIntLeafWhile!(net,middle,newleaf) DEBUGC && @debug "middle is $(middle.number), middle.hybrid $(middle.hybrid), middle.hasHybEdge $(middle.hasHybEdge)" if(middle.hybrid) edges = hybridEdges(middle) edges[1].istIdentifiable = false edges[2].istIdentifiable = false end end end end end end """ `deleteLeaf!(net::HybridNetwork, leaf::AbstractString)` `deleteLeaf!(net::Network, leaf::Node)` Deletes the leaf taxon from the network. The leaf argument is the name of the taxon to delete. Warnings: - requires a level-1 network with up-to-date attributes for snaq! (e.g. non-missing branch lengths, gammaz, etc.) - does not care where the root is and does not update it to a sensible location if the root is affected by the leaf removal. - does not merge edges, i.e. does not remove all nodes of degree 2. Within snaq!, this is used to extract quartets and to keep track of which edge lengths in the original network map to the quartet network. """ function deleteLeaf!(net::Network, leaf::AbstractString) found = false for l in net.leaf if(l.name == leaf) found = true deleteLeaf!(net,l) break end end found || error("cannot delete leaf $(leaf) because it was not found in the network") end # -------------------- extract quartet --------------------------------------- # function to update hasEdge attribute in a # QuartetNetwork after leaves deleted # with deleteLeaf! function updateHasEdge!(qnet::QuartetNetwork, net::HybridNetwork) #@warn "function to compare edges depends on edges number being unique" edges = Bool[] h = Bool[] hz = Bool[] for e in net.edge if(e.istIdentifiable) if(isEdgeNumIn(e,qnet.edge) && qnet.edge[getIndexEdge(e.number,qnet)].istIdentifiable) #println("found identifiable edge $(e.number) in net and qnet") push!(edges,true) else #println("not found identifiable edge $(e.number) in qnet but identifiable in net") push!(edges,false) end end if e.hybrid && !e.isMajor node = e.node[e.isChild1 ? 1 : 2] node.hybrid || error("strange thing, hybrid edge $(e.number) pointing at tree node $(node.number)") if(!node.isBadDiamondI) #println("found hybrid edge $(e.number) in net and qnet") push!(h,isNodeNumIn(node,qnet.hybrid)) else if(isNodeNumIn(node,qnet.hybrid)) push!(hz,true) push!(hz,true) else ind1 = parse(Int,string(string(node.number),"1")) ind2 = parse(Int,string(string(node.number),"2")) found1 = true found2 = true try getIndexEdge(ind1,qnet) catch found1 = false end try getIndexEdge(ind2,qnet) catch found2 = false end if(!found1 && !found2) push!(hz,false) push!(hz,false) elseif(found1 && !found2) index = getIndexEdge(ind1,qnet) if(!qnet.edge[index].istIdentifiable && all((n->!n.leaf), qnet.edge[index].node)) push!(hz,true) else push!(hz,false) end push!(hz,false) elseif(found2 && !found1) push!(hz,false) index = getIndexEdge(ind2,qnet) if(!qnet.edge[index].istIdentifiable && all((n->!n.leaf), qnet.edge[index].node)) push!(hz,true) else push!(hz,false) end else index1 = getIndexEdge(ind1,qnet) index2 = getIndexEdge(ind2,qnet) if(!qnet.edge[index1].istIdentifiable && all((n->!n.leaf), qnet.edge[index1].node) && !qnet.edge[index2].istIdentifiable && all((n->!n.leaf), qnet.edge[index2].node)) error("strange qnet when net has node $(node.number) Bad Diamond I: qnet should have only one of the gammaz if it does not have node, but it has two") end end end end end end # for in net.edge #println("edges $(edges), h $(h), hz $(hz)") qnet.hasEdge = vcat(h,edges,hz) end # function to extract a quartet from a network # input: QuartetNetwork (already created from HybridNetwork) # quartet: array with the 4 leaf nodes to keep # return: QuartetNetwork with only 4 tips # it updates qnet.hasEdge and qnet.indexht function extractQuartet(net::HybridNetwork,quartet::Array{Node,1}) size(quartet,1) == 4 || error("quartet array should have 4 nodes, it has $(size(quartet,1))") (quartet[1].leaf && quartet[2].leaf && quartet[3].leaf && quartet[4].leaf) || error("all four nodes to keep when extracting the quartet should be leaves: $([q.number for q in quartet])") qnet = QuartetNetwork(net) # fixit: try to re-use memory? quartetTaxon has not changed for instance. leaves = copy(qnet.leaf) for n in leaves if(!isNodeNumIn(n,quartet)) DEBUGC && @debug "delete leaf $(n.number)" deleteLeaf!(qnet,n) DEBUGC && printEdges(qnet) end end DEBUGC && @debug "deletion of leaves successful" return qnet end # function to extract a quartet from a Quartet object # it calls the previous extractQuartet # returns qnet (check: maybe not needed later) and assigns # quartet.qnet = qnet function extractQuartet!(net::HybridNetwork, quartet::Quartet) list = Node[] for q in quartet.taxon tax_in_net = findfirst(n -> n.name == q, net.node) tax_in_net != nothing || error("taxon $(q) not in network") push!(list, net.node[tax_in_net]) end qnet = extractQuartet(net,list) @debug "EXTRACT: extracted quartet $(quartet.taxon)" redundantCycle!(qnet) #removes no leaves, cleans external edges updateHasEdge!(qnet,net) parameters!(qnet,net) qnet.quartetTaxon = quartet.taxon quartet.qnet = qnet #return qnet end # function to extract all quartets from net according # to the array of quartets of a Data object # it updates expCF, hasEdge, indexht function extractQuartet!(net::HybridNetwork, quartet::Vector{Quartet}) @debug "EXTRACT: begins extract quartets for network" for q in quartet extractQuartet!(net,q) qnet = deepcopy(q.qnet); #there is a reason not to mess up with the original q.qnet, i believe to keep ht consistent calculateExpCFAll!(qnet); q.qnet.expCF[:] = qnet.expCF end end extractQuartet!(net::HybridNetwork, d::DataCF) = extractQuartet!(net, d.quartet) # function to check if there are potential redundant cycles in net # return the flag (true=redundant cycle found) and the hybrid node for the redundant cycle function hasRedundantCycle(net::Network) length(net.hybrid) == net.numHybrids || error("found net with length net.hybrid of $(length(net.hybrid)) and net.numHybrids of $(net.numHybrids)") if net.numHybrids > 0 for h in net.hybrid k = sum([(n.inCycle == h.number && length(n.edge) == 3) ? 1 : 0 for n in net.node]) if k < 2 return true,h end end end return false,nothing end # function to delete redundante cycles on all hybrid nodes in net function redundantCycle!(net::Network) length(net.hybrid) == net.numHybrids || error("found net with length net.hybrid of $(length(net.hybrid)) and net.numHybrids of $(net.numHybrids)") if(length(net.hybrid) > 0) redCycle, node = hasRedundantCycle(net) while(redCycle) !isa(node,Nothing) || error("redundant cycle found, but the hybrid node is set to nothing") redundantCycle!(net,node) DEBUGC && @debug "after redundante cycle for hybrid node $(n.number)" DEBUGC && printEdges(net) DEBUGC && printNodes(net) redCycle, node = hasRedundantCycle(net) end end cleanExtEdges!(net) end # function to delete redundant cycles (k=1,k=2), see ipad notes # warning: should not modify the quartet too much because we need to extract ht afterwards function redundantCycle!(net::Network,n::Node) n.hybrid || error("cannot clean a cycle on a tree node $(n.number)") edges = hybridEdges(n) edges[1].hybrid && edges[2].hybrid || error("hybrid node $(n.number) does not have two hybrid edges $(edges[1].number), $(edges[2].number)") @debug "search for redundantCycle for node $(n.number) with edges are $([e.number for e in edges])" other = getOtherNode(edges[1],n) if(length(other.edge) == 2) e = edges[1] while(length(other.edge) == 2) ind = isEqual(e,other.edge[1]) ? 2 : 1 e = other.edge[ind] other = getOtherNode(e,other) end if(isEqual(n,other)) n1 = getOtherNode(edges[1],n) n2 = getOtherNode(edges[2],n) @debug "redundant cycle found! n1 $(n1.number), n2 $(n2.number)" deleteIntLeafWhile!(net,n1,n) edge = n.edge[1].hybrid ? n.edge[1] : n.edge[2] @debug "edge is $(edge.number), should be the first (or only) edge in hybrid node $(n.number)" if(isEqual(edge.node[1],edge.node[2])) @debug "entra a q son iguales los nodes de edge" n3 = getOtherNode(edges[3],n) @debug "edges[3] is $(edges[3].number), n3 is $(n3.number)" removeEdge!(n3,edges[3]) deleteNode!(net,n) deleteEdge!(net,edge) deleteEdge!(net,edges[3]) if(!n3.leaf && length(n3.edge)==1) removeNoLeafWhile!(net,n3); end end end end end # function to delete an internal node with only one edge function removeNoLeaf!(net::Network,n::Node) !n.leaf || error("node $(n.number) is a leaf, so we cannot remove it") length(n.edge) == 1 || error("node $(n.number) has $(length(n.edge)) edges (not 1), so we do not have to remove it") node = getOtherNode(n.edge[1],n) removeEdge!(node,n.edge[1]) deleteNode!(net,n) deleteEdge!(net,n.edge[1]) return node end # function to do a while for removeNoLeaf # warning: we do not want to remove edges because we need to know # exactly which edges in qnet are affected by changes in net.ht function removeNoLeafWhile!(net::Network,n::Node) while(!n.leaf && length(n.edge)==1) n = removeNoLeaf!(net,n) end return n end # Function to check that external edges do not have nodes with only two edges function cleanExtEdges!(net::Network) # if(net.numHybrids > 0) for l in net.leaf length(l.edge) == 1 || error("leaf $(l.number) with $(length(l.edge)) edges, not 1") deleteIntLeafWhile!(net,getOtherNode(l.edge[1],l),l) end # end end # function to delete a hybrid node that has only two edges: the hybrid ones # it fixes other1,other2 for internal nodes with only 2 edges (one external), # returns other1, other2 if they are internal nodes with only one edge # returns array of nodes (to avoid treating o1,o2 as a tuple later) function removeLoneHybrid!(net::Network, n::Node) n.hybrid || error("cannot remove a lone hybrid if it is not hybrid: $(n.number)") length(n.edge) == 2 || error("hybrid node $(n.number) should have only 2 edges to be deleted, it has $(length(n.edge))") (n.edge[1].hybrid && n.edge[2].hybrid) || error("both edges have to be hybrid and they are not both: $(n.edge[1].number), $(n.edge[2].number)") other1 = getOtherNode(n.edge[1],n) other2 = getOtherNode(n.edge[2],n) removeEdge!(other1,n.edge[1]) removeEdge!(other2,n.edge[2]) deleteEdge!(net,n.edge[1]) deleteEdge!(net,n.edge[2]) deleteNode!(net,n) if(length(other1.edge) == 2 && isNodeNumIn(other1,net.node)) leaf1 = getOtherNode(other1.edge[1],other1) leaf = leaf1.leaf ? leaf1 : getOtherNode(other1.edge[2],other1) if(leaf.leaf) deleteIntLeafWhile!(net,other1,leaf) end end if(length(other2.edge) == 2 && isNodeNumIn(other2,net.node)) leaf1 = getOtherNode(other2.edge[1],other2) leaf = leaf1.leaf ? leaf1 : getOtherNode(other2.edge[2],other2) if(leaf.leaf) deleteIntLeafWhile!(net,other2,leaf) end end o1 = false o2 = false if(length(other1.edge) == 1) !other1.leaf || error("node $(other1.number) should not be a leaf because it was attached to hybrid edge") o1 = true end if(length(other2.edge) == 1) !other2.leaf || error("node $(other2.number) should not be a leaf because it was attached to hybrid edge") o2 = true end if(o1 && !o2) return [other1] elseif(!o1 && o2) return [other2] elseif(o1 && o2) return [other1,other2] else return nothing end end function removeWeirdNode!(net::Network,n::Node) other = nothing @debug "calling removeWeirdNode in node $(n.number)" if(length(n.edge) == 1 && !n.leaf) @debug "node $(n.number) is not a leaf and has one edge" n = removeNoLeafWhile!(net,n) end if(n.hybrid && length(n.edge) == 2) @debug "node $(n.number) is hybrid with only two edges" (n.edge[1].hybrid && n.edge[2].hybrid) || error("two edges for this hybrid node $(n.number) must be hybrid, and they are not") other = removeLoneHybrid!(net,n) #returns array of nodes (length 1 or 2) or nothing end return other end # function to remove internal nodes with only one edge # keep deleting those nodes, and hybrid nodes without descendants function removeWeirdNodes!(net::Network, n::Node) @debug "calling removeWeirdNodes in node $(n.number)" list = Node[] push!(list,n) while !isempty(list) n = pop!(list) if length(n.edge) == 1 && !n.leaf n = removeWeirdNode!(net,n) elseif n.hybrid && length(n.edge) == 2 (n.edge[1].hybrid && n.edge[2].hybrid) || error("hybrid node $(n.number) only has two edges and they must be hybrids") n = removeWeirdNode!(net,n) else @error "calling removeWeirdNode on normal node $(n.number)" n = nothing end if n !== nothing && !isa(n,Vector{Nothing}) @debug "typeof n $(typeof(n))" for l in n @debug "typeof l $(typeof(l))" push!(list,l) end end end end # ------------------------------- calculate expCF ------------------------------------- # ------- Identify Quartet # function to identify the type of hybridization of a given hybrid node # in a quartet network # sets node.k to the updated count # sets the node.typeHyb (1,2,3,4,5 see ipad notes) and pushes into qnet.typeHyb # sets node.prev = other to keep track of the "other" node # fixit: I think qnet.typeHyb is never used function identifyQuartet!(qnet::QuartetNetwork, node::Node) node.hybrid || error("cannot identify the hybridization around node $(node.number) because it is not hybrid node.") k = sum([(n.inCycle == node.number && size(n.edge,1) == 3) ? 1 : 0 for n in qnet.node]) node.k = k if k < 2 @debug begin printEdges(qnet) printNodes(qnet) "printed edges and nodes" end error("strange quartet network with a hybrid node $(node.number) but no cycle") elseif(k == 2) other = qnet.node[findfirst(n -> (n.inCycle == node.number && size(n.edge,1) == 3 && !isEqual(n,node)), qnet.node)] edgebla,edgebla,edge1 = hybridEdges(node) edgebla,edgebla,edge2 = hybridEdges(other) if(getOtherNode(edge1,node).leaf || getOtherNode(edge2,other).leaf) node.typeHyb = 1 node.prev = other push!(qnet.typeHyb,1) else node.typeHyb = 3 node.prev = other push!(qnet.typeHyb,3) end elseif(k == 3) #println("identifyQuartet: entra a k=3") edge1,edge2,edge3 = hybridEdges(node) #println("node is $(node.number), edge3 is $(edge3.number)") if(getOtherNode(edge3,node).leaf) node.typeHyb = 2 push!(qnet.typeHyb,2) for n in qnet.node if(n.inCycle == node.number && size(n.edge,1) == 3 && !isEqual(n,node)) #println("found a node $(n.number)") edge1,edge2,edge3 = hybridEdges(n) #println("edge1,egde2,edge3 are $(edge1.number), $(edge2.number), $(edge3.number)") if(getOtherNode(edge3,n).leaf) node.prev = n break end end end else node.typeHyb = 4 push!(qnet.typeHyb,4) for n in qnet.node if(n.inCycle == node.number && size(n.edge,1) == 3 && !isEqual(n,node)) node.prev = n break end end end elseif(k == 4) node.typeHyb = 5 push!(qnet.typeHyb,5) node.prev = nothing else @debug begin printEdges(qnet) printNodes(qnet) "printed edges and nodes" end error("strange quartet network with $(k) nodes in cycle, maximum should be 4") end DEBUGC && @debug "qnet identified as type $(node.typeHyb)" end # function to identify the Quartet network as # 1 (equivalent to tree), 2 (minor CF different) function identifyQuartet!(qnet::QuartetNetwork) #if(qnet.which == -1) if(qnet.numHybrids == 0) qnet.which = 1 elseif(qnet.numHybrids == 1) identifyQuartet!(qnet, qnet.hybrid[1]) if(qnet.typeHyb[1] == 5) qnet.which = 2 else qnet.which = 1 end else for n in qnet.hybrid cleanUpNode!(qnet,n) identifyQuartet!(qnet, n) end if(all((n->(n.typeHyb != 5)), qnet.hybrid)) qnet.which = 1 else if(all((n->(n.typeHyb == 5 || n.typeHyb == 1)), qnet.hybrid)) #@warn "hybridization of type 5 found in quartet network along with other hybridizations of type 1. there is the possibility of overlapping cycles." qnet.which = 2 else @debug begin printEdges(qnet) printNodes(qnet) "warning: found in the same quartet, two hybridizations with overlapping cycles: types of hybridizations are $([n.typeHyb for n in qnet.hybrid]), maybe this will cause problems if the hyb do not become all but one type 1" end qnet.which = 2 end end end #end end # function that will get rid of internal nodes with only # two edges for all three directions of a node function cleanUpNode!(net::Network,node::Node) edge1,edge2,edge3 = hybridEdges(node) deleteIntLeafWhile!(net,getOtherNode(edge1,node),node) deleteIntLeafWhile!(net,getOtherNode(edge2,node),node) deleteIntLeafWhile!(net,getOtherNode(edge3,node),node) end # ----------------------- Eliminate Hybridizations # aux function to eliminate hybridizations # in quartet # input: quartet network, # node correspond to the hybrid node # internal: true if loop is in internal edge function eliminateLoop!(qnet::QuartetNetwork, node::Node, internal::Bool) node.hybrid || error("cannot eliminate loop around node $(node.number) since it is not hybrid") edge1,edge2,edge3 = hybridEdges(node) deleteIntLeafWhile!(qnet, edge1, node) deleteIntLeafWhile!(qnet, edge2, node) other = getOtherNode(edge1,node) isEqual(getOtherNode(edge2,node),other) || error("node $(node.number) and other $(other.number) are not the two nodes in a cycle with k=2") other.number == node.prev.number || error("something strange, other node $(other.number) should be the same as the stored in node.prev $(node.prev.number)") removeEdge!(node,edge2) removeEdge!(other,edge2) deleteEdge!(qnet,edge2) if(internal) setLength!(edge1, -log(1-edge1.gamma*edge1.gamma*edge1.z-edge2.gamma*edge2.gamma*edge2.z)) else leaf = getOtherNode(edge3,node) #if(leaf.leaf) deleteIntLeafWhile!(qnet,node,leaf) #else # edge1,edge2,edge3 = hybridEdges(other) # deleteIntLeafWhile!(qnet,other,getOtherNode(edge3,other)) #end end end # aux function to identify intermediate edge between two nodes function intermediateEdge(node1::Node,node2::Node) edge = nothing for e in node1.edge if(isEqual(getOtherNode(e,node1),node2)) edge = e end end if(isa(edge, Nothing)) error("nodes $(node1.number), $(node2.number) are not connected by an edge") end return edge end # function to eliminate a triangle hybridization # input: quartet network, # node, other nodes in the hybridization # case: 1 (global case 2),2 (global case 4), 1 (global case 5) # warning: special treatment for bad diamond II function eliminateTriangle!(qnet::QuartetNetwork, node::Node, other::Node, case::Integer) #println("start eliminateTriangle----") node.hybrid || error("cannot eliminate triangle around node $(node.number) since it is not hybrid") #println("hybrid node is $(node.number), with edges $([e.number for e in node.edge]), with gammas $([e.gamma for e in node.edge])") edgemaj, edgemin, treeedge = hybridEdges(node) isa(edgemaj,Nothing) ? error("edge maj is nothing for node $(node.number), other $(other.number) and taxon $(qnet.quartetTaxon), $(printEdges(qnet))") : nothing isa(edgemin,Nothing) ? error("edge min is nothing for node $(node.number), other $(other.number) and taxon $(qnet.quartetTaxon), $(printEdges(qnet))") : nothing deleteIntLeafWhile!(qnet, edgemaj, node) deleteIntLeafWhile!(qnet, edgemin, node) if(isEqual(getOtherNode(edgemaj,node),other)) hybedge = edgemaj otheredge = edgemin elseif(isEqual(getOtherNode(edgemin,node),other)) hybedge = edgemin otheredge = edgemaj else error("node $(node.number) and other node $(other.number) are not connected by an edge") end #println("hybedge is $(hybedge.number), otheredge is $(otheredge.number)") middle = qnet.node[findfirst(n -> (n.inCycle == node.number && size(n.edge,1) == 3 && !isEqual(n,other) && !isEqual(n,node)), qnet.node)] #println("middle node is $(middle.number) in eliminateTriangle") ind = findfirst(e -> (e.inCycle == node.number && !isEqual(getOtherNode(e,middle),node)), middle.edge) ind != nothing || error("edge number not found in middle edge") edge = middle.edge[ind] #println("edge is $(edge.number) with length $(edge.length) in eliminateTriangle, will do deleteIntLeaf from middle through edge") deleteIntLeafWhile!(qnet,edge,middle) #println("after deleteIntLeaf, edge $(edge.number) has length $(edge.length)") isEqual(getOtherNode(edge,middle),other) || error("middle node $(middle.number) and other node $(other.number) are not connected by an edge") if(case == 1) setLength!(edge,-log(1 - hybedge.gamma*edge.z)) #println("Case 1: edge $(edge.number) length is $(edge.length) after updating") removeEdge!(middle,otheredge) removeEdge!(other,hybedge) removeEdge!(node,treeedge) removeNode!(node,treeedge) setEdge!(other, treeedge) setNode!(treeedge, other) deleteEdge!(qnet,otheredge) deleteEdge!(qnet,hybedge) deleteNode!(qnet,node) elseif(case == 2) (hybedge.hybrid && otheredge.hybrid) || error("hybedge $(hybedge.number) and otheredge $(otheredge.number) should by hybrid edges in eliminateTriangle Case 2") setLength!(hybedge, -log(otheredge.gamma*otheredge.gamma*otheredge.y + hybedge.gamma*otheredge.gamma*(3-edge.y) + hybedge.gamma*hybedge.gamma*hybedge.y), true) #println("Case 2: edge $(edge.number) length is $(edge.length) after updating") removeEdge!(middle,otheredge) removeEdge!(node,otheredge) deleteEdge!(qnet,otheredge) deleteIntLeafWhile!(qnet, node, getOtherNode(treeedge,node),true) deleteIntLeafWhile!(qnet, edge, other) else error("unknown case $(case), should be 1 or 2") end #println("end eliminateTriangle ---") end # function to polish quartet with hybridization type 5 # (2 minor CF different) and calculate the expCF # CF calculated in the order 12|34, 13|24, 14|23 of the qnet.quartet.taxon function quartetType5!(qnet::QuartetNetwork, node::Node) (node.hybrid && node.typeHyb == 5) || error("cannot polish the quartet type 5 hybridization since either the node is not hybrid: $(!node.hybrid) or it has type $(node.typeHyb), different than 5") edge1,edge2,edge3 = hybridEdges(node); if(!node.isBadDiamondI) deleteIntLeafWhile!(qnet,edge1,node) deleteIntLeafWhile!(qnet,edge2,node) end other1 = getOtherNode(edge1,node); other2 = getOtherNode(edge2,node); edgebla,edge5, edgetree1 = hybridEdges(other1); edgebla,edge6, edgetree2 = hybridEdges(other2); if(!node.isBadDiamondI) deleteIntLeafWhile!(qnet,edge5,other1) deleteIntLeafWhile!(qnet,edge6,other2) end if(node.isBadDiamondI) (other1.gammaz != -1 && other2.gammaz != -1) || error("node $(node.number) is bad diamond I but gammaz are -1") @debug "it will calculate the expCF in a bad diamond I case with gammaz: $(other1.gammaz) and $(other2.gammaz)" cf1 = (1 + 2*other1.gammaz - other2.gammaz)/3 cf2 = (1 + 2*other2.gammaz - other1.gammaz)/3 cf3 = (1 - other1.gammaz - other2.gammaz)/3 else cf1 = edge1.gamma*(1-2/3*edge5.y) + edge2.gamma*1/3*edge6.y cf2 = edge1.gamma*1/3*edge5.y + edge2.gamma*(1-2/3*edge6.y) cf3 = edge1.gamma*1/3*edge5.y + edge2.gamma*1/3*edge6.y end #println("cf1,cf2,cf3: $(cf1),$(cf2),$(cf3)") leaf1 = getOtherNode(edge3,node) if(isa(edgetree1,Nothing)) println("node $(node.number), edge3 $(edge3.number), other1 $(other1.number), leaf1 $(leaf1.number), other2 $(other2.number)") println("edge1 $(edge1.number), edge2 $(edge2.number), edge5 $(edge5.number), edge6 $(edge6.number)") printEdges(qnet) printNodes(qnet) end leaf2 = getOtherNode(edgetree1,other1) leaf3 = getOtherNode(edgetree2, other2) leaf4 = qnet.leaf[findfirst(n -> (!isEqual(n,leaf1) && !isEqual(n,leaf2) && !isEqual(n,leaf3)), qnet.leaf)] #println("leaf1 is $(leaf1.number)") #println("leaf2 is $(leaf2.number)") #println("leaf3 is $(leaf3.number)") #println("leaf4 is $(leaf4.number)") tx = whichLeaves(qnet,qnet.quartetTaxon[1],qnet.quartetTaxon[2], leaf1,leaf2,leaf3,leaf4) #println("tx is $(tx)") if(tx == (1,2) || tx == (2,1) || tx == (3,4) || tx == (4,3)) qnet.expCF[1] = cf1 tx = whichLeaves(qnet,qnet.quartetTaxon[1],qnet.quartetTaxon[3], leaf1,leaf2,leaf3,leaf4) if(tx == (1,3) || tx == (3,1) || tx == (2,4) || tx == (4,2)) qnet.expCF[2] = cf2 qnet.expCF[3] = cf3 elseif(tx == (1,4) || tx == (4,1) || tx == (3,2) || tx == (2,3)) qnet.expCF[2] = cf3 qnet.expCF[3] = cf2 else error("strange quartet network, could not find which leaves correspond to taxon1, taxon3") end elseif(tx == (1,3) || tx == (3,1) || tx == (2,4) || tx == (4,2)) qnet.expCF[1] = cf2 tx = whichLeaves(qnet,qnet.quartetTaxon[1],qnet.quartetTaxon[3], leaf1,leaf2,leaf3,leaf4) if(tx == (1,2) || tx == (2,1) || tx == (3,4) || tx == (4,3)) qnet.expCF[2] = cf1 qnet.expCF[3] = cf3 elseif(tx == (1,4) || tx == (4,1) || tx == (3,2) || tx == (2,3)) qnet.expCF[2] = cf3 qnet.expCF[3] = cf1 else error("strange quartet network, could not find which leaves correspond to taxon1, taxon3") end elseif(tx == (1,4) || tx == (4,1) || tx == (3,2) || tx == (2,3)) qnet.expCF[1] = cf3 tx = whichLeaves(qnet,qnet.quartetTaxon[1],qnet.quartetTaxon[3], leaf1,leaf2,leaf3,leaf4) if(tx == (1,3) || tx == (3,1) || tx == (2,4) || tx == (4,2)) qnet.expCF[2] = cf2 qnet.expCF[3] = cf1 elseif(tx == (1,2) || tx == (2,1) || tx == (3,4) || tx == (4,3)) qnet.expCF[2] = cf1 qnet.expCF[3] = cf2 else error("strange quartet network, could not find which leaves correspond to taxon1, taxon3") end else error("strange quartet network, could not find which leaves correspond to taxon1, taxon2") end if(!approxEq(sum(qnet.expCF),1.)) error("strange quartet network with hybridization in node $(node.number) of type 5: expCF do not add up to 1") end end # function to eliminate a hybridization around a given # hybrid node function eliminateHybridization!(qnet::QuartetNetwork, node::Node) node.hybrid || error("cannot eliminate hybridization around node $(node.number) since it is not hybrid node") if(node.typeHyb == 1) eliminateLoop!(qnet,node,false) elseif(node.typeHyb == 3) eliminateLoop!(qnet,node,true) elseif(node.typeHyb == 4) #println("node is $(node.number), other node is $(node.prev.number)") eliminateTriangle!(qnet,node,node.prev,2) elseif(node.typeHyb == 2) #println("node is $(node.number), other node is $(node.prev.number)") eliminateTriangle!(qnet,node,node.prev,1) elseif(node.typeHyb != 5) error("node type of hybridization should be 1,2,3,4 or 5, but for node $(node.number), it is $(node.typeHyb)") end end # aux function to eliminate all internal nodes with only # two edges in a quartet network with qnet.which=1 # eliminate internal nodes in every direction function internalLength!(qnet::QuartetNetwork) if qnet.which == 1 ind_3e = findfirst(n -> length(n.edge) == 3, qnet.node) if isnothing(ind_3e) printEdges(qnet) printNodes(qnet) error("not found internal node in qnet with 3 edges") end node = qnet.node[ind_3e] ind_3eo = findfirst(n -> (size(n.edge,1) == 3 && n !== node), qnet.node) if isnothing(ind_3eo) println("first node found with 3 edges $(node.number)") printEdges(qnet) printNodes(qnet) error("not found another internal node in qnet with 3 edges") end node2 = qnet.node[ind_3eo] for e in node.edge deleteIntLeafWhile!(qnet,e,node,true) end for e in node2.edge deleteIntLeafWhile!(qnet,e,node2,true) end edge = nothing for e in node.edge if(!getOtherNode(e,node).leaf) edge = e end end !isa(edge,Nothing) || error("cannot find internal edge attached to node $(node.number) in qnet") isEqual(getOtherNode(edge,node),node2) || error("strange internal edge $(edge.number) found in qnet, should have as nodes $(node.number), $(node2.number)") qnet.t1 = edge.length end end # function to eliminate hybridizations in a quartet network # first step to later calculate expCF # input: quartet network # fixit: need to add a loop, eliminate type1 until there are none, and then identify again function eliminateHybridization!(qnet::QuartetNetwork) qnet.which != -1 || error("qnet which has to be updated by now to 1 or 2, and it is $(qnet.which)") if(qnet.numHybrids == 1) eliminateHybridization!(qnet,qnet.hybrid[1]) elseif(qnet.numHybrids > 1) #eliminate in order: first type1 only DEBUGC && @debug "starting eliminateHyb for more than one hybrid with types $([n.typeHyb for n in qnet.hybrid])" while(qnet.numHybrids > 0 && any([n.typeHyb == 1 for n in qnet.hybrid])) hybrids = copy(qnet.hybrid) for n in hybrids if(n.typeHyb == 1) #only delete type 1 hybridizations (non identifiable ones) !isa(n.prev,Nothing) || error("hybrid node $(n.number) is type 1 hybridization, prev should be automatically set") eliminateHybridization!(qnet,n) end end qnet.typeHyb = Int[] if(qnet.numHybrids > 0) DEBUGC && @debug "need to identify hybridizations again after deleting type 1 hybridizations" identifyQuartet!(qnet) end end DEBUGC && @debug "now types are $([n.typeHyb for n in qnet.hybrid])" hybrids = copy(qnet.hybrid) for n in hybrids eliminateHybridization!(qnet,n) end end if(qnet.which == 1) internalLength!(qnet) end end # ------------------------- update qnet.formula # function to identify to which of the 4 leaves # two taxa correspond. this is to identify later # if the two taxa correspond to major/minor CF # input: qnet, taxon1,taxon2 # returns leaf for taxon1, leaf for taxon2 (i.e. 12) # warning: assumes that the numbers for the taxon in the output.csv table are the names function whichLeaves(qnet::QuartetNetwork, taxon1::String, taxon2::String, leaf1::Node, leaf2::Node, leaf3::Node, leaf4::Node) # danger: this quartet code assumes a particular correspondance between net.names and [n.name for n in net.node] if(taxon1 == qnet.names[leaf1.number]) if(taxon2 == qnet.names[leaf2.number]) return 1,2 elseif(taxon2 == qnet.names[leaf3.number]) return 1,3 elseif(taxon2 == qnet.names[leaf4.number]) return 1,4 else error("taxon2 $(taxon2) is not one of the three remaining leaves: $(leaf2.number), $(leaf3.number), $(leaf4.number)") end elseif(taxon1 == qnet.names[leaf2.number]) if(taxon2 == qnet.names[leaf1.number]) return 2,1 elseif(taxon2 == qnet.names[leaf3.number]) return 2,3 elseif(taxon2 == qnet.names[leaf4.number]) return 2,4 else error("taxon2 $(taxon2) is not one of the three remaining leaves: $(leaf1.number), $(leaf3.number), $(leaf4.number)") end elseif(taxon1 == qnet.names[leaf3.number]) if(taxon2 == qnet.names[leaf1.number]) return 3,1 elseif(taxon2 == qnet.names[leaf2.number]) return 3,2 elseif(taxon2 == qnet.names[leaf4.number]) return 3,4 else error("taxon2 $(taxon2) is not one of the three remaining leaves: $(leaf2.number), $(leaf1.number), $(leaf4.number)") end elseif(taxon1 == qnet.names[leaf4.number]) if(taxon2 == qnet.names[leaf2.number]) return 4,2 elseif(taxon2 == qnet.names[leaf3.number]) return 4,3 elseif(taxon2 == qnet.names[leaf1.number]) return 4,1 else error("taxon2 $(taxon2) is not one of the three remaining leaves: $(leaf2.number), $(leaf3.number), $(leaf4.number)") end else error("taxon1: $(taxon1) is not one of the 4 leaves in quartet: $(leaf1.number), $(leaf2.number), $(leaf3.number), $(leaf4.number)") end end # function to update the attribute split in qnet # qnet.leaf is a vector [x,y,z,w] and qnet.split is a vector # [1,1,2,2] that says in which side of the split is each leaf # warning: it needs to be run after eliminating hybridization and uniting # internal edge function updateSplit!(qnet::QuartetNetwork) if(qnet.which == 1) if(qnet.split == [-1,-1,-1,-1]) qnet.split = [2,2,2,2] middle = qnet.node[findfirst(n -> size(n.edge,1) == 3, qnet.node)] leaf1 = middle.edge[findfirst(e -> getOtherNode(e,middle).leaf, middle.edge)] leaf2 = middle.edge[findfirst(e -> getOtherNode(e,middle).leaf && !isEqual(leaf1,e), middle.edge)] leaf1 = getOtherNode(leaf1,middle) #leaf1 was edge, now it is node leaf2 = getOtherNode(leaf2,middle) ind1 = getIndex(leaf1,qnet.leaf) ind2 = getIndex(leaf2,qnet.leaf) qnet.split[ind1] = 1 qnet.split[ind2] = 1 end elseif(qnet.which == -1) error("cannot update split in quartet network if it has not been identified, and eliminated hybridizations") end end # function to know which formula (minor/major) to compute # for qnet.expCF[1,2,3] depending on the order of taxa in # qnet.quartet # warning: needs qnet.split updated already function updateFormula!(qnet::QuartetNetwork) if(qnet.which == 1) if(qnet.formula == [-1,-1,-1]) qnet.split != [-1,-1,-1,-1] || error("cannot update qnet.formula if qnet.split is not updated: $(qnet.split)") qnet.formula = [2,2,2] for i in 2:4 size(qnet.leaf,1) == 4 || error("strange quartet with $(size(qnet.leaf,1)) leaves instead of 4") tx1,tx2 = whichLeaves(qnet,qnet.quartetTaxon[1],qnet.quartetTaxon[i], qnet.leaf[1], qnet.leaf[2], qnet.leaf[3], qnet.leaf[4]) # index of leaf in qnet.leaf if(qnet.split[tx1] == qnet.split[tx2]) qnet.formula[i-1] = 1 break end end end elseif(qnet.which != 2) error("qnet.which should be updated already to 1 or 2, and it is $(qnet.which)") end end # --------------- calculate exp CF ---------------------- # function to calculate expCF for a quartet network # warning: needs qnet.formula and qnet.t1 already updated function calculateExpCF!(qnet::QuartetNetwork) if(qnet.which == 1) if(qnet.formula != [-1,-1,-1] && qnet.t1 != -1) for i in 1:3 qnet.expCF[i] = qnet.formula[i] == 1 ? 1-2/3*exp(-qnet.t1) : 1/3*exp(-qnet.t1) end else error("quartet network needs to have updated formula and t1 before computing the expCF") end elseif(qnet.which == 2) if(qnet.numHybrids == 1) if(qnet.hybrid[1].typeHyb == 5) quartetType5!(qnet,qnet.hybrid[1]) else error("strange quartet network type $(qnet.which) with one hybrid node $(qnet.hybrid[1].number) but it is not type 5, it is type $(qnet.hybrid[1].typeHyb)") end else error("quartet network with type $(qnet.which) but with $(qnet.numHybrids) hybrid nodes. all hybridizations type 1 (not identifiable) have been eliminated already, so there should only be one hybrid.") end end end # function to compute all the process of calculating the expCF # for a given qnet function calculateExpCFAll!(qnet::QuartetNetwork) identifyQuartet!(qnet) eliminateHybridization!(qnet) updateSplit!(qnet) updateFormula!(qnet) calculateExpCF!(qnet) end # function to calculate expCF for all the quartets in data # after extractQuartet(net,data) that updates quartet.qnet # warning: only updates expCF for quartet.changed=true function calculateExpCFAll!(data::DataCF) !all((q->(q.qnet.numTaxa != 0)), data.quartet) ? error("qnet in quartets on data are not correctly updated with extractQuartet") : nothing #@warn "assume the numbers for the taxon read from the observed CF table match the numbers given to the taxon when creating the object network" for q in data.quartet if(q.qnet.changed) qnet = deepcopy(q.qnet); calculateExpCFAll!(qnet); q.qnet.expCF[:] = qnet.expCF end end end # function to calculate expCF for all the quartets in data # after extractQuartet(net,data) that updates quartet.qnet # first updates the edge lengths according to x # warning: assumes qnet.indexht is updated already # warning: only updates expCF for quartet.qnet.changed=true function calculateExpCFAll!(data::DataCF, x::Vector{Float64},net::HybridNetwork) !all((q->(q.qnet.numTaxa != 0)), data.quartet) ? error("qnet in quartets on data are not correctly updated with extractQuartet") : nothing #println("calculateExpCFAll in x: $(x) with net.ht $(net.ht)") for q in data.quartet update!(q.qnet,x,net) if(q.qnet.changed) #println("enters to recalculate expCF for some quartet") qnet = deepcopy(q.qnet); calculateExpCFAll!(qnet); q.qnet.expCF[:] = qnet.expCF end end end # function to simply calculate the pseudolik of a given network """ `topologyQPseudolik!(net::HybridNetwork, d::DataCF)` Calculate the quartet pseudo-deviance of a given network/tree for DataCF `d`. This is the negative log pseudo-likelihood, up to an additive constant, such that a perfect fit corresponds to a deviance of 0.0. Be careful if the net object does not have all internal branch lengths specified because then the pseudolikelihood will be meaningless. The loglik attribute of the network is undated, and `d` is updated with the expected concordance factors under the input network. """ function topologyQPseudolik!(net0::HybridNetwork,d::DataCF; verbose=false::Bool) for ed in net0.edge !ed.hybrid || (ed.gamma >= 0.0) || error("hybrid edge has missing γ value. Cannot compute quartet pseudo-likelihood.\nTry `topologyMaxQPseudolik!` instead, to estimate these γ's.") end missingBL = any([e.length < 0.0 for e in net0.edge]) # at least one BL was missing net = readTopologyUpdate(writeTopologyLevel1(net0)) # update level-1 attributes. Changes <0 BL into 1.0 if(!isempty(d.repSpecies)) expandLeaves!(d.repSpecies, net) net = readTopologyLevel1(writeTopologyLevel1(net)) # dirty fix to multiple alleles problem with expandLeaves end missingBL && any([(e.length == 1.0 && e.istIdentifiable) for e in net.edge]) && @warn "identifiable edges lengths were originally missing, so assigned default value of 1.0" try checkNet(net) catch error("starting topology not a level 1 network") end extractQuartet!(net,d) # quartets are all updated: hasEdge, expCF, indexht all((q->(q.qnet.numTaxa != 0)), d.quartet) || error("qnet in quartets on data are not correctly updated with extractQuartet") for q in d.quartet if verbose println("computing expCF for quartet $(q.taxon)") # to stdout else @debug "computing expCF for quartet $(q.taxon)"; end # to logger if debug turned on by user qnet = deepcopy(q.qnet); calculateExpCFAll!(qnet); q.qnet.expCF[:] = qnet.expCF if verbose println("$(qnet.expCF)") # to stdout else @debug "$(qnet.expCF)"; end # to logger end val = logPseudoLik(d) if verbose println("$the value of pseudolikelihood is $(val)") # to stdout else @debug "$the value of pseudolikelihood is $(val)"; end # to logger net0.loglik = val return val end # ---------------------------- Pseudolik for a quartet ------------------------- # function to calculate the log pseudolikelihood function for a single # quartet # sum_i=1,2,3 (obsCF_i)*log(expCF_i/obsCF_i) # warning: assumes that quartet.qnet is already updated with extractQuartet and # calculateExpCF function logPseudoLik(quartet::Quartet) sum(quartet.qnet.expCF) != 0.0 || error("expCF not updated for quartet $(quartet.number)") #@debug "quartet= $(quartet.taxon), obsCF = $(quartet.obsCF), expCF = $(quartet.qnet.expCF)" suma = 0 for i in 1:3 if(quartet.qnet.expCF[i] < 0) @debug "found expCF negative $(quartet.qnet.expCF[i]), will set loglik=-1.e15" suma += -1.e15 else suma += quartet.obsCF[i] == 0 ? 0.0 : 100*quartet.obsCF[i]*log(quartet.qnet.expCF[i]/quartet.obsCF[i]) # WARNING: 100 should be replaced by -2*ngenes to get the deviance. # below: negative sign used below in logPseudoLik() when summing up across 4-taxon sets end end ## to account for missing data: ## if(quartet.ngenes > 0) ## suma = quartet.ngenes*suma ## end quartet.logPseudoLik = suma return suma end # function to calculate the -log pseudolikelihood function for array of # quartets # sum_q [sum_i=1,2,3 (obsCF_i)*log(expCF_i)] # warning: assumes that quartet.qnet is already updated with extractQuartet and # calculateExpCF for all quartets function logPseudoLik(quartet::Array{Quartet,1}) suma = 0 for q in quartet suma += logPseudoLik(q) end return -suma end logPseudoLik(d::DataCF) = logPseudoLik(d.quartet)
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
57301
# function to write a csv table from the expCF of an # array of quartets # warning: does not check if the expCF have been calculated function writeExpCF(quartets::Array{Quartet,1}) df = DataFrames.DataFrame(t1=String[],t2=String[],t3=String[],t4=String[], CF12_34=Float64[],CF13_24=Float64[],CF14_23=Float64[]) for q in quartets length(q.taxon) == 4 || error("quartet $(q.number) does not have 4 taxa") length(q.qnet.expCF) == 3 || error("quartet $(q.number) does have qnet with 3 expCF") push!(df, [q.taxon[1],q.taxon[2],q.taxon[3],q.taxon[4],q.qnet.expCF[1],q.qnet.expCF[2],q.qnet.expCF[3]]) end return df end writeExpCF(d::DataCF) = writeExpCF(d.quartet) """ writeTableCF(vector of Quartet objects) writeTableCF(DataCF) Build a DataFrame containing observed quartet concordance factors, with columns named: - `t1`, `t2`, `t3`, `t4` for the four taxon names in each quartet - `CF12_34`, `CF13_24`, `CF14_23` for the 3 quartets of a given four-taxon set - `ngenes` if this information is available for some quartets """ function writeTableCF(quartets::Array{Quartet,1}) df = DataFrames.DataFrame(t1=String[],t2=String[],t3=String[],t4=String[], CF12_34=Float64[],CF13_24=Float64[],CF14_23=Float64[], ngenes=Union{Missing, Float64}[]) for q in quartets length(q.taxon) == 4 || error("quartet $(q.number) does not have 4 taxa") length(q.obsCF) == 3 || error("quartet $(q.number) does have qnet with 3 expCF") push!(df, [q.taxon[1],q.taxon[2],q.taxon[3],q.taxon[4],q.obsCF[1],q.obsCF[2],q.obsCF[3], (q.ngenes==-1.0 ? missing : q.ngenes)]) end if all(ismissing, df[!,:ngenes]) select!(df, Not(:ngenes)) end return df end writeTableCF(d::DataCF) = writeTableCF(d.quartet) """ writeTableCF(quartetlist::Vector{QuartetT} [, taxonnames]; colnames) Convert a vector of [`QuartetT`](@ref) objects to a data frame, with 1 row for each four-taxon set in the list. Each four-taxon set contains quartet data of some type `T`, which determines the number of columns in the data frame. This data type `T` should be a vector of length 3 or 4, or a 3×n matrix. In the output data frame, the columns are, in this order: - `qind`: contains the quartet's `number` - `t1, t2, t3, t4`: contain the quartet's `taxonnumber`s if no `taxonnames` are given, or the taxon names otherwise. The name of taxon number `i` is taken to be `taxonnames[i]`. - 3 columns for each column in the quartet's `data`. The first 3 columns are named `CF12_34, CF13_24, CF14_23`. The next columns are named `V2_12_34, V2_13_24, V2_14_23` and contain the data in the second column of the quartet's data matrix. And so on. For the data frame to have non-default column names, provide the desired 3, 4, or 3×n names as a vector via the optional argument `colnames`. """ function writeTableCF(quartets::Vector{QuartetT{T}}, taxa::AbstractVector{<:AbstractString}=Vector{String}(); colnames=nothing) where T <: Union{StaticVector{3}, StaticVector{4}, StaticMatrix{3,N} where N} V = eltype(T) colnames_data = quartetdata_columnnames(T) if !isnothing(colnames) if length(colnames) == length(colnames_data) colnames_data = colnames else @error "'colnames' needs to be of length $(length(colnames_data)).\nwill use default column names." end end translate = !isempty(taxa) tnT = (translate ? eltype(taxa) : Int) # Type for taxon names if translate taxstring = x -> taxa[x] # will error if a taxonnumber > length(taxa): okay else taxstring = x -> x end df = DataFrames.DataFrame(qind=Int[], t1=tnT[],t2=tnT[],t3=tnT[],t4=tnT[]) for cn in colnames_data df[:,Symbol(cn)] = V[] end for q in quartets push!(df, (q.number, taxstring.(q.taxonnumber)..., q.data...) ) end return df end """ quartetdata_columnnames(T) where T <: StaticArray Vector of column names to hold the quartet data of type `T` in a data frame. If T is a length-3 vector type, they are "CF12_34","CF13_24","CF14_23". If T is a length-4 vector type, the 4th name is "ngenes". If T is a 3×n matrix type, the output vector contains 3×n names, 3 for each of "CF", "V2_", "V3_", ... "Vn_". Used by [`writeTableCF`](@ref) to build a data frame from a vector of [`QuartetT`](@ref) objects. """ function quartetdata_columnnames(::Type{T}) where T <: StaticArray{Tuple{3},S,1} where S return ["CF12_34","CF13_24","CF14_23"] end function quartetdata_columnnames(::Type{T}) where T <: StaticArray{Tuple{4},S,1} where S return ["CF12_34","CF13_24","CF14_23","ngenes"] end function quartetdata_columnnames(::Type{T}) where # for a 3×N matrix: N names T <: StaticArray{Tuple{3,N},S,2} where {N,S} N > 0 || error("expected at least 1 column of data") colnames_q = ["12_34","13_24","14_23"] colnames = "CF" .* colnames_q for i in 2:N append!(colnames, "V$(i)_" .* colnames_q); end return colnames end """ readTableCF(file) readTableCF(data frame) readTableCF!(data frame) Read a file or DataFrame object containing a table of concordance factors (CF), with one row per 4-taxon set. The first 4 columns are assumed to give the labels of the 4 taxa in each set (tx1, tx2, tx3, tx4). Columns containing the CFs are assumed to be named `CF12_34`, `CF13_24` and `CF14_23`; or `CF12.34`, `CF13.24` and `CF14.23`; or else are assumed to be columns 5,6,7. If present, a column named 'ngenes' will be used to get the number of loci used to estimate the CFs for each 4-taxon set. Output: [`DataCF`](@ref) object Optional arguments: - summaryfile: if specified, a summary file will be created with that name. - delim (for the first form only): to specify how columns are delimited, with single quotes: delim=';'. Default is a `csv` file, i.e. `delim=','`. - `mergerows`: false by default. When true, will attempt to merge multiple rows corresponding to the same four-taxon set (by averaging their quartet CFs) even if none of the species is repeated within any row (that is, in any set of 4 taxa) The last version modifies the input data frame, if species are represented by multiple alleles for instance (see [`readTableCF!`](@ref)(data frame, columns)). """ function readTableCF(file::AbstractString; delim=','::Char, summaryfile=""::AbstractString, kwargs...) df = DataFrame(CSV.File(file, delim=delim); copycols=false) readTableCF!(df; summaryfile=summaryfile, kwargs...) end function readTableCF(df0::DataFrames.DataFrame; summaryfile=""::AbstractString, kwargs...) df = deepcopy(df0) readTableCF!(df; summaryfile=summaryfile, kwargs...) end function readTableCF!(df::DataFrames.DataFrame; summaryfile=""::AbstractString, kwargs...) @debug "assume the numbers for the taxon read from the observed CF table match the numbers given to the taxon when creating the object network" taxoncolnames = [[:t1, :tx1, :tax1, :taxon1], [:t2, :tx2, :tax2, :taxon2], [:t3, :tx3, :tax3, :taxon3], [:t4, :tx4, :tax4, :taxon4] ] taxoncol = [findfirst(x-> x ∈ taxoncolnames[1], DataFrames.propertynames(df)), findfirst(x-> x ∈ taxoncolnames[2], DataFrames.propertynames(df)), findfirst(x-> x ∈ taxoncolnames[3], DataFrames.propertynames(df)), findfirst(x-> x ∈ taxoncolnames[4], DataFrames.propertynames(df))] alternativecolnames = [ # obsCF12 is as exported by fittedQuartetCF() [:CF12_34, Symbol("CF12.34"), :obsCF12, :CF1234], [:CF13_24, Symbol("CF13.24"), :obsCF13, :CF1324], [:CF14_23, Symbol("CF14.23"), :obsCF14, :CF1423] ] obsCFcol = [findfirst(x-> x ∈ alternativecolnames[1], DataFrames.propertynames(df)), findfirst(x-> x ∈ alternativecolnames[2], DataFrames.propertynames(df)), findfirst(x-> x ∈ alternativecolnames[3], DataFrames.propertynames(df))] ngenecol = findfirst(isequal(:ngenes), DataFrames.propertynames(df)) withngenes = ngenecol !== nothing nothing in taxoncol && error("columns for taxon names were not found") nothing in obsCFcol && error( """Could not identify columns with quartet concordance factors (qCFs). Was expecting CF12_34, CF13_24 and CF14_23 for the columns with CF values, or CF12.34 or obsCF12, etc.""") columns = [taxoncol; obsCFcol] if withngenes push!(columns, ngenecol) end d = readTableCF!(df, columns; kwargs...) if withngenes # && d.numTrees == -1 m1 = minimum([q.ngenes for q in d.quartet]) m2 = maximum([q.ngenes for q in d.quartet]) if m1<m2 print("between $m1 and ") end println("$m2 gene trees per 4-taxon set") # other info printed by show() on a DataCF object: num quartets and num gene trees end if(summaryfile != "") descData(d,summaryfile) end return d end # see docstring below, for readTableCF! # takes in df and 7 or 8 column numbers (4 labels + 3 CFs + ngenes possibly) function readTableCF!(df::DataFrames.DataFrame, co::Vector{Int}; mergerows=false) withngenes = (length(co)==8) # true if column :ngenes exists, false ow repSpecies = cleanAlleleDF!(df,co) # removes uninformative rows from df (not df0) # fixit: cleanAlleleDF! is time consuming but many times not needed # add option to skip it, if the user knows that each tip appears once only? if mergerows || !isempty(repSpecies) df = mergeRows(df,co) # warning: this 'df' is *not* changed externally co = collect(eachindex(co)) # 1:7 or 1:8 end # we cannot move to mapAllelesCFtable because we need repSpecies in here quartets = Quartet[] for i in 1:size(df,1) push!(quartets,Quartet(i,string(df[i,co[1]]),string(df[i,co[2]]),string(df[i,co[3]]),string(df[i,co[4]]), [df[i,co[5]],df[i,co[6]],df[i,co[7]]])) if withngenes quartets[end].ngenes = df[i,co[8]] end end d = DataCF(quartets) if(!isempty(repSpecies)) d.repSpecies = repSpecies end return d # return d, df ## to save memory & gc with readTableCF! for bootstrapping? end """ readTableCF!(data frame, columns; mergerows=false) Read in quartet CFs from data frame, assuming information is in columns numbered `columns`, of length **7 or 8**: 4 taxon labels then 3 CFs then ngenes possibly. If some species appears more than once in the same 4-taxon set (e.g. t1,t1,t2,t3), then the data frame is modified to remove rows (4-taxon sets) that are uninformative about between-species relationships. This situation may occur if multiple individuals are sampled from the same species. A 4-taxon set is uninformative (and its row is removed) if one taxon is repeated 3 or 4 times (like t1,t1,t1,t1 or t1,t2,t2,t2). The list of species appearing twice in some 4-taxon sets is stored in the output DataCF object. For these species, the length of their external edge is identifiable (in coalescent units). If multiple rows correspond to the same 4-taxon set, these rows are merged and their CF values (and number of genes) are averaged. If none of the species is repeated within any 4-taxon set, then this averaging is attempted only if `mergerows` is true. readTableCF!(DataCF, data frame, columns) Modify the `.quartet.obsCF` values in the `DataCF` object with those read from the data frame in columns numbered `columns`. `columns` should have **3** columns numbers for the 3 CFs in this order: `12_34`, `13_24` and `14_23`. Assumptions: - same 4-taxon sets in `DataCF` and in the data frame, and in the same order, but this assumption is *not checked* (for speed, e.g. during bootstrapping). - one single row per 4-taxon set (multiple individuals representatives of the same 4-taxon set should have been already merged); basically: the DataCF should have been created from the data frame by `readTableCF!(df, colums)` """ function readTableCF!(datcf::DataCF, df::DataFrame, cols::Vector{Int}) for i in 1:size(df,1) for j in 1:3 datcf.quartet[i].obsCF[j] = df[i,cols[j]] end end end # ---------------- read input gene trees and calculate obsCF ---------------------- """ readInputTrees(file) Read a text file with a list of trees/networks in parenthetical format (one tree per line) and transform them like [`readTopologyLevel1`](@ref) does: to be unrooted, with resolved polytomies, missing branch lengths set to 1.0, etc. See [`readMultiTopology`](@ref) to read multiple trees or networks with no modification. Output: array of HybridNetwork objects. Each line starting with "(" will be considered as describing one topology. The file can have extra lines that are ignored. """ function readInputTrees(file::AbstractString) try s = open(file) catch error("Could not find or open $(file) file"); end vnet = HybridNetwork[]; s = open(file) numl = 1 for line in eachline(s) line = strip(line) # remove spaces @debug "$(line)" c = isempty(line) ? "" : line[1] if(c == '(') try push!(vnet, readTopologyUpdate(line,false)) catch(err) error("could not read tree in line $(numl). The error is $(err)") end end numl += 1 end close(s) return vnet # consistent output type: HybridNetwork vector. might be of length 0. end # function to list all quartets for a set of taxa names # return a vector of quartet objects, and if writeFile=true, writes a file function allQuartets(taxon::Union{Vector{<:AbstractString},Vector{Int}}, writeFile::Bool) quartets = combinations(taxon,4) vquartet = Quartet[]; if(writeFile) #allName = "allQuartets$(string(integer(time()/1000))).txt" allName = "allQuartets.txt" f = open(allName,"w") end i = 1 for q in quartets if(writeFile) write(f,"$(q[1]),$(q[2]),$(q[3]),$(q[4])\n") end push!(vquartet,Quartet(i,string(q[1]),string(q[2]),string(q[3]),chomp(string(q[4])),[1.0,0.0,0.0])) i += 1 # overflow error if # quartets > typemax(Int), i.e. if 121,978+ taxa with Int64, 478+ taxa with Int32 end if(writeFile) close(f) end return vquartet end allQuartets(numTaxa::Integer, writeFile::Bool) = allQuartets(1:numTaxa, writeFile) # function to list num randomly selected quartets for a vector of all quartets # return a vector of Quartet randomly chosen (and a file if writeFile=true) function randQuartets(allquartets::Vector{Quartet},num::Integer, writeFile::Bool) randquartets = Quartet[] n = length(allquartets) if num == 0 num = Integer(floor(0.1*n)) end num <= n || error("you cannot choose a sample of $(num) quartets when there are $(n) in total") indx = [ones(Bool,num); zeros(Bool,n-num)] indx = indx[sortperm(randn(n))] if writeFile randName = "rand$(num)Quartets.txt" println("list of randomly selected quartets in file $(randName)") out = open(randName,"w") end for i in 1:n if indx[i] if writeFile q = allquartets[i].taxon write(out,"$(q[1]),$(q[2]),$(q[3]),$(q[4])\n") end push!(randquartets,allquartets[i]) end end if writeFile close(out) end return randquartets end # function that will not use randQuartets(list of quartets,...) # this function uses whichQuartet to avoid making the list of all quartets # fixit: writeFile is not used. remove the option? function randQuartets(taxon::Union{Vector{<:AbstractString},Vector{Int}},num::Integer, writeFile::Bool) randquartets = Quartet[] n = length(taxon) ntotal = binom(n,4) num <= ntotal || error("you cannot choose a sample of $(num) quartets when there are $(ntotal) in total") # indx = [rep(1,num);rep(0,ntotal-num)] # requires much more memory than necessary: # indx = indx[sortperm(randn(ntotal))] # several arrays of size ntotal !! # rq = findall(x -> x==1, indx) rq = sample(1:ntotal, num, replace=false, ordered=true) randName = "rand$(num)Quartets.txt" println("list of randomly selected quartets in file $(randName)") out = open(randName,"w") i = 1 for q in rq qind = whichQuartet(n,q) # vector of int quartet = createQuartet(taxon,qind,i) write(out,"$(quartet.taxon[1]), $(quartet.taxon[2]), $(quartet.taxon[3]), $(quartet.taxon[4])\n") push!(randquartets,quartet) i += 1 end close(out) return randquartets end randQuartets(numTaxa::Integer,num::Integer, writeFile::Bool) = randQuartets(1:numTaxa,num, writeFile) # function to read list of quartets from a file # and create Quartet type objects function readListQuartets(file::AbstractString) try f = open(file) catch error("could not open file $(file)") end f = open(file) quartets = Quartet[]; i = 1 for line in eachline(f) l = split(line,",") length(l) == 4 || error("quartet with $(length(l)) elements, should be 4: $(line)") push!(quartets,Quartet(i,string(l[1]),string(l[2]),string(l[3]),chomp(string(l[4])),[1.0,0.0,0.0])) i += 1 end return quartets end """ sameTaxa(Quartet, HybridNetwork) Return `true` if all taxa in the quartet are represented in the network, `false` if one or more taxa in the quartet does not appear in the network. warning: the name can cause confusion. A more appropriate name might be "in", or "taxain", or "taxonsubset", or etc. """ function sameTaxa(q::Quartet, t::HybridNetwork) for name in q.taxon in(name,t.names) || return false end return true end """ taxadiff(Vector{Quartet}, network; multiplealleles=true) taxadiff(DataCF, network; multiplealleles=true) Return 2 vectors: - taxa in at least 1 of the quartets but not in the network, and - taxa in the network but in none of the quartets. When `multiplealleles` is true, the taxon names that end with "__2" are ignored in the quartets: they are not expected to appear in the networks that users give as input, or get as output. """ function taxadiff(quartets::Vector{Quartet}, t::HybridNetwork; multiplealleles=true::Bool) tq = tipLabels(quartets) secondallele = occursin.(Ref(r"__2$"), tq) for i in length(secondallele):-1:1 secondallele[i] || continue basetax = match(r"(.*)__2$", tq[i]).captures[1] # if tq[i] = "mouse__2" for instance, then basetax = "mouse" if basetax in tq # some other taxon is "mouse" deleteat!(tq, i) # delete "mouse__2" from tq IF "mouse" is present end end tn = tipLabels(t) return (setdiff(tq,tn), setdiff(tn,tq)) end taxadiff(d::DataCF, t::HybridNetwork; multiplealleles=true::Bool) = taxadiff(d.quartet, t; multiplealleles=multiplealleles) # extract & sort the union of taxa of list of gene trees function unionTaxa(trees::Vector{HybridNetwork}) taxa = reduce(union, tipLabels(t) for t in trees) return sort_stringasinteger!(taxa) end """ sort_stringasinteger!(taxa) Sort a vector of strings `taxa`, numerically if elements can be parsed as an integer, alphabetically otherwise. """ function sort_stringasinteger!(taxa) sortby = x->parse(Int,x) try parse.(Int,taxa) catch sortby = identity end sort!(taxa, by=sortby) return taxa end # extract & sort the union of taxa of list of quartets function unionTaxa(quartets::Vector{Quartet}) taxa = reduce(union, q.taxon for q in quartets) return sort_stringasinteger!(taxa) end unionTaxaTree(file::AbstractString) = unionTaxa(readInputTrees(file)) tipLabels(t::Vector{HybridNetwork}) = unionTaxa(t) tipLabels(q::Vector{Quartet}) = unionTaxa(q) tipLabels(d::DataCF) = unionTaxa(d.quartet) """ calculateObsCFAll!(DataCF, taxa::Union{Vector{<:AbstractString}, Vector{Int}}) Calculate observed concordance factors: update the `.quartet[i].obsCF` values of the `DataCF` object based on its .tree vector. calculateObsCFAll!(vector of quartets, vector of trees, taxa) Calculate observed concordance factors: update the `.obsCF` values of the quartets, based on the trees, and returns a new `DataCF` object with these updated quartets and trees. calculateObsCFAll_noDataCF!(vector of quartets, vector of trees, taxa) update the `.obsCF` values of the quartets based on the trees, but returns nothing. Warning: all these functions need input trees (without any reticulations: h=0). See also: [`countquartetsintrees`](@ref), which uses a faster algorithm, processing each input tree only once. `calculateObsCFAll_noDataCF!` processes each input tree `# quartet` times. """ function calculateObsCFAll!(dat::DataCF, taxa::Union{Vector{<:AbstractString}, Vector{Int}}) calculateObsCFAll_noDataCF!(dat.quartet, dat.tree, taxa) end function calculateObsCFAll!(quartets::Vector{Quartet}, trees::Vector{HybridNetwork}, taxa::Union{Vector{<:AbstractString}, Vector{Int}}) calculateObsCFAll_noDataCF!(quartets, trees, taxa) d = DataCF(quartets,trees) return d end function calculateObsCFAll_noDataCF!(quartets::Vector{Quartet}, trees::Vector{HybridNetwork}, taxa::Union{Vector{<:AbstractString}, Vector{Int}}) println("calculating obsCF from $(length(trees)) gene trees and for $(length(quartets)) quartets") index = 1 totalq = length(quartets) println("Reading in quartets...") r = round(1/totalq, digits=2) numq = (r > 0.02 ? totalq : 50) print("0+") for i in 1:numq print("-") end print("+100%") println(" ") print(" ") for q in quartets if round(index/totalq, digits=2) > 0.02 print("*") index = 1 end suma = 0 sum12 = 0 sum13 = 0 sum14 = 0 for t in trees isTree(t) || error("gene tree found in file that is a network $(writeTopology(t))") if sameTaxa(q,t) M = tree2Matrix(t,taxa) #fixit: way to reuse M? length(t.edge) will be different across trees res = extractQuartetTree(q,M,taxa) @debug "res is $(res)" if(res == 1) sum12 += 1 elseif(res == 2) sum13 += 1 elseif(res == 3) sum14 += 1 end suma += (res == 0) ? 0 : 1 end end q.obsCF = [sum12/suma, sum13/suma, sum14/suma] q.ngenes = suma index += 1 end println(" ") return nothing end """ countquartetsintrees(trees [, taxonmap]; which=:all, weight_byallele=true) Calculate the quartet concordance factors (CF) observed in the `trees` vector. If present, `taxonmap` should be a dictionary that maps each allele name to it's species name. To save to a file, first convert to a data frame using [`writeTableCF`](@ref). When `which=:all`, quartet CFs are calculated for all 4-taxon sets. (Other options are not implemented yet.) The algorithm runs in O(mn⁴) where m is the number of trees and n is the number of tips in the trees. CFs are calculated at the species level only, that is, considering 4-taxon sets made of 4 distinct species, even if the gene trees may have multiple alleles from the same species. For 4 distinct species `a,b,c,d`, all alleles from each species (`a` etc.) will be considered to calculate the quartet CF. By default, each gene has a weight of 1. So if there are `n_a` alleles from `a`, `n_b` alleles from `b` etc. in a given gene, then each set of 4 alleles has a weight of `1/(n_a n_b b_c n_c)` in the calculation of the CF for `a,b,c,d`. With option `weight_byallele=true`, then each set of 4 alleles is given a weight of 1 instead. This inflates the total number of sets used to calculate the quartet CFs (to something larger than the number of genes). This may also affect the CF values if the number of alleles varies across genes: genes with more alleles will be given more weight. # examples ```jldoctest julia> tree1 = readTopology("(E,(A,B),(C,D),O);"); tree2 = readTopology("(((A,B),(C,D)),E);"); julia> q,t = countquartetsintrees([tree1, tree2]); Reading in trees, looking at 15 quartets in each... 0+--+100% ** julia> t # taxon order: t[i] = name of taxon number i 6-element Vector{String}: "A" "B" "C" "D" "E" "O" julia> length(q) # 15 four-taxon sets on 6 taxa 15 julia> q[1] # both trees agree on AB|CD: resolution 1 4-taxon set number 1; taxon numbers: 1,2,3,4 data: [1.0, 0.0, 0.0, 2.0] julia> q[8] # tree 2 is missing O (taxon 6), tree 1 wants resolution 3: AO|CD 4-taxon set number 8; taxon numbers: 1,3,4,6 data: [0.0, 0.0, 1.0, 1.0] julia> q[11] # tree 1 has ACEO unresolved, and tree 2 is missing O: no data for this quartet 4-taxon set number 11; taxon numbers: 1,3,5,6 data: [0.0, 0.0, 0.0, 0.0] julia> tree1 = readTopology("(E,(a1,B),(a2,D),O);"); tree2 = readTopology("(((a1,a2),(B,D)),E);"); julia> q,t = countquartetsintrees([tree1, tree2], Dict("a1"=>"A", "a2"=>"A"); showprogressbar=false); julia> t 5-element Vector{String}: "A" "B" "D" "E" "O" julia> q[1] # tree 1 has discordance: a1B|DE and a2D|BE. tree 2 has AE|BD for both alleles of A 4-taxon set number 1; taxon numbers: 1,2,3,4 data: [0.25, 0.25, 0.5, 2.0] julia> q[3] # tree 2 is missing O (taxon 5), and a2 is unresolved in tree 1. There's only a1B|EO 4-taxon set number 3; taxon numbers: 1,2,4,5 data: [1.0, 0.0, 0.0, 0.5] julia> df = writeTableCF(q,t); # to get a DataFrame that can be saved to a file later julia> show(df, allcols=true) 5×9 DataFrame Row │ qind t1 t2 t3 t4 CF12_34 CF13_24 CF14_23 ngenes │ Int64 String String String String Float64 Float64 Float64 Float64 ─────┼─────────────────────────────────────────────────────────────────────────── 1 │ 1 A B D E 0.25 0.25 0.5 2.0 2 │ 2 A B D O 0.5 0.5 0.0 1.0 3 │ 3 A B E O 1.0 0.0 0.0 0.5 4 │ 4 A D E O 1.0 0.0 0.0 0.5 5 │ 5 B D E O 0.0 0.0 0.0 0.0 julia> # using CSV; CSV.write(df, "filename.csv"); julia> tree2 = readTopology("((A,(B,D)),E);"); julia> q,t = countquartetsintrees([tree1, tree2], Dict("a1"=>"A", "a2"=>"A"); weight_byallele=true); Reading in trees, looking at 5 quartets in each... 0+--+100% ** julia> show(writeTableCF(q,t), allcols=true) 5×9 DataFrame Row │ qind t1 t2 t3 t4 CF12_34 CF13_24 CF14_23 ngenes │ Int64 String String String String Float64 Float64 Float64 Float64 ─────┼────────────────────────────────────────────────────────────────────────────── 1 │ 1 A B D E 0.333333 0.333333 0.333333 3.0 2 │ 2 A B D O 0.5 0.5 0.0 2.0 3 │ 3 A B E O 1.0 0.0 0.0 1.0 4 │ 4 A D E O 1.0 0.0 0.0 1.0 5 │ 5 B D E O 0.0 0.0 0.0 0.0 ``` """ function countquartetsintrees(tree::Vector{HybridNetwork}, taxonmap::Dict=Dict{String,String}(); whichQ::Symbol=:all, weight_byallele::Bool=false, showprogressbar::Bool=true) whichQ in [:all, :intrees] || error("whichQ must be either :all or :intrees, but got $whichQ") if isempty(taxonmap) taxa = unionTaxa(tree) else taxa = sort!(collect(Set(haskey(taxonmap, l.name) ? taxonmap[l.name] : l.name for t in tree for l in t.leaf))) end taxonnumber = Dict(taxa[i] => i for i in eachindex(taxa)) ntax = length(taxa) nCk = nchoose1234(ntax) # matrix used to ranks 4-taxon sets qtype = MVector{4,Float64} # 4 floats: CF12_34, CF13_24, CF14_23, ngenes; initialized at 0.0 if whichQ == :all numq = nCk[ntax+1,4] quartet = Vector{QuartetT{qtype}}(undef, numq) ts = [1,2,3,4] for qi in 1:numq quartet[qi] = QuartetT(qi, SVector{4}(ts), MVector(0.,0.,0.,0.)) # next: find the 4-taxon set with the next rank, # faster than using the direct mapping function ind = findfirst(x -> x>1, diff(ts)) if ind === nothing ind = 4; end ts[ind] += 1 for j in 1:(ind-1) ts[j] = j end end else error("whichQ = :intrees not implemented yet") # fixit: read all the trees, go through each edge, check if the current quartet list covers the edge, if not: add a quartet end totalt = length(tree) if showprogressbar nstars = (totalt < 50 ? totalt : 50) ntrees_perstar = (totalt/nstars) println("Reading in trees, looking at $numq quartets in each...") print("0+" * "-"^nstars * "+100%\n ") stars = 0 nextstar = Integer(ceil(ntrees_perstar)) end for i in 1:totalt # number of times each quartet resolution is seen in each tree countquartetsintrees!(quartet, tree[i], whichQ, weight_byallele, nCk, taxonnumber, taxonmap) if showprogressbar && i >= nextstar print("*") stars += 1 nextstar = Integer(ceil((stars+1) * ntrees_perstar)) end end showprogressbar && print("\n") # normalize counts to frequencies & number of genes for q in quartet d = q.data d[4] = d[1]+d[2]+d[3] # number of genes if d[4] > 0.0 d[1:3] /= d[4] end # otherwise: no genes with data on this quartet (missing taxa or polytomy): leave all zeros (NaN if /0) end return quartet, taxa end function countquartetsintrees!(quartet::Vector{QuartetT{MVector{4,Float64}}}, tree::HybridNetwork, whichQ::Symbol, weight_byallele::Bool, nCk::Matrix, taxonnumber::Dict{<:AbstractString,Int}, taxonmap::Dict{<:AbstractString,<:AbstractString}) tree.numHybrids == 0 || error("input phylogenies must be trees") # next: reset node & edge numbers so that they can be used as indices: 1,2,3,... resetNodeNumbers!(tree; checkPreorder=true, type=:postorder) # leaves first & post-order resetEdgeNumbers!(tree) # next: build list leaf number -> species ID, using the node name then taxon map nleaves = length(tree.leaf) nnodes = length(tree.node) taxID = Vector{Int}(undef, nleaves) for n in tree.leaf taxID[n.number] = haskey(taxonmap, n.name) ? taxonnumber[taxonmap[n.name]] : taxonnumber[n.name] end # number of individuals from each species: needed to weigh the quartets at the individual level # weight of t1,t2,t3,t4: 1/(taxcount[t1]*taxcount[t2]*taxcount[t3]*taxcount[t4]) taxcount = zeros(Int, length(taxonnumber)) for ti in taxID taxcount[ti] += 1; end # next: build data structure to get descendant / ancestor clades below,above = ladderpartition(tree) # re-checks that node numbers can be used as indices, with leaves first # below[n][1:2 ]: left & clades below node number n # above[n][1:end]: grade of clades above node n for n in (nleaves+1):nnodes # loop through internal nodes indices only bn = below[n] an = above[n] for c1 in 2:length(bn) # c = child clade, loop over all pairs of child clades for t1 in bn[c1] # pick 1 tip from each child clade s1 = taxID[t1] for c2 in 1:(c1-1) for t2 in bn[c2] s2 = taxID[t2] s1 != s2 || continue # skip quartets that have repeated species t12max = max(t1,t2) leftweight = 1/(taxcount[s1]*taxcount[s2]) for p1 in 1:length(an) # p = parent clade for t3i in 1:length(an[p1]) t3 = an[p1][t3i] s3 = taxID[t3] (s3 != s1 && s3 != s2) || continue for t4i in 1:(t3i-1) # pick 2 distinct tips from the same parent clade t4 = an[p1][t4i] t3 > t12max || t4 > t12max || continue # skip: would be counted twice otherwise s4 = taxID[t4] (s4 != s1 && s4 != s2 && s4 != s3) || continue rank,res = quartetRankResolution(s1, s2, s3, s4, nCk) weight = ( weight_byallele ? 1.0 : leftweight / (taxcount[s3]*taxcount[s4]) ) quartet[rank].data[res] += weight end for p2 in 1:(p1-1) # distinct parent clade: no risk of counting twice for t4 in an[p2] s4 = taxID[t4] (s4 != s1 && s4 != s2 && s4 != s3) || continue rank,res = quartetRankResolution(s1, s2, s3, s4, nCk) weight = ( weight_byallele ? 1.0 : leftweight / (taxcount[s3]*taxcount[s4]) ) quartet[rank].data[res] += weight end end end end end end end end end end function quartetRankResolution(t1::Int, t2::Int, t3::Int, t4::Int, nCk::Matrix) # quartet: t1 t2 | t3 t4, but indices have not yet been ordered: t1<t2, t3<t4, t1<min(t3,t4) if t3 > t4 # make t3 smallest of t3, t4 (t3,t4) = (t4,t3) end if t1 > t2 # make t1 smallest of t1, t2 (t1,t2) = (t2,t1) end if t1 > t3 # swap t1 with t3, t2 with t4 - makes t1 smallest (t1,t3) = (t3,t1) (t2,t4) = (t4,t2) end if t2 < t3 # t2 2nd smallest: order t1 < t2 < t3 < t4 resolution = 1; # 12|34 after ordering indices rank = quartetrank(t1, t2, t3, t4, nCk) else # t3 2nd smallest if t2 < t4 # order t1 < t3 < t2 < t4 resolution = 2; # 13|24 after ordering rank = quartetrank(t1, t3, t2, t4, nCk); else # order t1 < t3 < t4 < t2 resolution = 3; # 14|23 after ordering rank = quartetrank(t1, t3, t4, t2, nCk); end end return rank, resolution end """ readInputData(trees, quartetfile, whichQuartets, numQuartets, writetable, tablename, writeQfile, writesummary) readInputData(trees, whichQuartets, numQuartets, taxonlist, writetable, tablename, writeQfile, writesummary) Read gene trees and calculate the observed quartet concordance factors (CF), that is, the proportion of genes (and the number of genes) that display each quartet for a given list of four-taxon sets. Input: - `trees`: name of a file containing a list of input gene trees, or vector of trees (`HybridNetwork` objects) Optional arguments (defaults): - `quartetfile`: name of a file containing a list of quartets, or more precisely, a list of four-taxon sets - `whichQuartets` (`:all`): which quartets to sample. `:all` for all of them, `:rand` for a random sample. - `numQuartets`: number of quartets in the sample. default: total number of quartets if `whichQuartets=:all` and 10% of total if `whichQuartets=:rand` - `taxonlist` (all in the input gene trees): If `taxonlist` is used, `whichQuartets` will consist of *all* sets of 4 taxa in the `taxonlist`. - `writetable` (true): write the table of observed CF? - `tablename` ("tableCF.txt"): if `writetable` is true, the table of observed CFs is write to file `tablename` - `writeQfile` (false): write intermediate file with sampled quartets? - `writesummary` (true): write a summary file? if so, the summary will go in file "summaryTreesQuartets.txt". Uses [`calculateObsCFAll!`](@ref), which implements a slow algorithm. See also: [`countquartetsintrees`](@ref), which uses a much faster algorithm; [`readTrees2CF`](@ref), which is basically a re-naming of `readInputData`, and [`readTableCF`](@ref) to read a table of quartet CFs directly. """ function readInputData(treefile::AbstractString, quartetfile::AbstractString, whichQ::Symbol, numQ::Integer, writetab::Bool, filename::AbstractString, writeFile::Bool, writeSummary::Bool) if writetab if(filename == "none") filename = "tableCF.txt" # "tableCF$(string(integer(time()/1000))).txt" end if (isfile(filename) && filesize(filename) > 0) error("""file $(filename) already exists and is non-empty. Cannot risk to erase data. Choose a different CFfile name, use writeTab=false, or read the existing file with readTableCF(\"$(filename)\")""") end end println("read input trees from file $(treefile)\nand quartetfile $(quartetfile)") trees = readInputTrees(treefile) readInputData(trees, quartetfile, whichQ, numQ, writetab, filename, writeFile, writeSummary) end readInputData(treefile::AbstractString, quartetfile::AbstractString, whichQ::Symbol, numQ::Integer, writetab::Bool) = readInputData(treefile, quartetfile, whichQ, numQ, writetab, "none", false, true) readInputData(treefile::AbstractString, quartetfile::AbstractString, whichQ::Symbol, numQ::Integer) = readInputData(treefile, quartetfile, whichQ, numQ, true, "none", false, true) readInputData(treefile::AbstractString, quartetfile::AbstractString, writetab::Bool, filename::AbstractString) = readInputData(treefile, quartetfile, :all, 0, writetab, filename, false, true) function readInputData(trees::Vector{HybridNetwork}, quartetfile::AbstractString, whichQ::Symbol, numQ::Integer, writetab::Bool, filename::AbstractString, writeFile::Bool, writeSummary::Bool) if(whichQ == :all) numQ == 0 || @warn "set numQ=$(numQ) but whichQ is not rand, so all quartets will be used and numQ will be ignored. If you want a specific number of 4-taxon subsets not random, you can input with the quartetfile option" println("will use all quartets in file $(quartetfile)") quartets = readListQuartets(quartetfile) elseif(whichQ == :rand) if(numQ == 0) @warn "not specified numQ but whichQ=rand, so 10% of quartets will be sampled" #handled inside randQuartets else println("will take a random sample of $(numQ) 4-taxon sets from file $(quartetfile)") end allquartets = readListQuartets(quartetfile) quartets = randQuartets(allquartets,numQ,writeFile) else error("unknown symbol for whichQ $(whichQ), should be either all or rand") end d = calculateObsCFAll!(quartets,trees, unionTaxa(trees)) if(writetab) if(filename == "none") filename = "tableCF.txt" # "tableCF$(string(integer(time()/1000))).txt" end if (isfile(filename) && filesize(filename) > 0) error("""file $(filename) already exists and is non-empty. Cannot risk to erase data. Choose a different CFfile name, use writeTab=false, or read the existing file with readTableCF(\"$(filename)\")""") end println("\ntable of obsCF printed to file $(filename)") df = writeTableCF(d) CSV.write(filename,df) end #descData(d,"summaryTreesQuartets$(string(integer(time()/1000))).txt") writeSummary && descData(d,"summaryTreesQuartets.txt") return d end function readInputData(treefile::AbstractString, whichQ::Symbol=:all, numQ::Integer=0, taxa::Union{Vector{<:AbstractString}, Vector{Int}}=unionTaxaTree(treefile), writetab::Bool=true, filename::AbstractString="none", writeFile::Bool=false, writeSummary::Bool=true) if writetab if(filename == "none") filename = "tableCF.txt" # "tableCF$(string(integer(time()/1000))).txt" end if (isfile(filename) && filesize(filename) > 0) error("""file $(filename) already exists and is non-empty. Cannot risk to erase data. Choose a different CFfile name, use writeTab=false, or read the existing file with readTableCF(\"$(filename)\")""") end end println("read input trees from file $(treefile). no quartet file given.") trees = readInputTrees(treefile) readInputData(trees, whichQ, numQ, taxa, writetab, filename, writeFile, writeSummary) end readInputData(treefile::AbstractString, whichQ::Symbol, numQ::Integer, writetab::Bool) = readInputData(treefile, whichQ, numQ, unionTaxaTree(treefile), writetab, "none",false, true) readInputData(treefile::AbstractString, taxa::Union{Vector{<:AbstractString}, Vector{Int}}) = readInputData(treefile, :all, 0, taxa, true, "none",false, true) # above: the use of unionTaxaTree to set the taxon set # is not good: need to read the tree file twice: get the taxa, then get the trees # this inefficiency was fixed in readTrees2CF function readInputData(trees::Vector{HybridNetwork}, whichQ::Symbol, numQ::Integer, taxa::Union{Vector{<:AbstractString}, Vector{Int}}, writetab::Bool, filename::AbstractString, writeFile::Bool, writeSummary::Bool) if(whichQ == :all) numQ == 0 || @warn "set numQ=$(numQ) but whichQ=all, so all quartets will be used and numQ will be ignored. If you want a specific number of 4-taxon subsets not random, you can input with the quartetfile option" quartets = allQuartets(taxa,writeFile) println("will use all quartets on $(length(taxa)) taxa") elseif(whichQ == :rand) if(numQ == 0) @warn "not specified numQ with whichQ=rand, so 10% of quartets will be sampled" #handled inside randQuartets else println("will use a random sample of $(numQ) 4-taxon sets ($(round((100*numQ)/binomial(length(taxa),4), digits=2)) percent) on $(length(taxa)) taxa") end quartets = randQuartets(taxa,numQ, writeFile) else error("unknown symbol for whichQ $(whichQ), should be either all or rand") end d = calculateObsCFAll!(quartets,trees,taxa) if writetab if(filename == "none") filename = "tableCF.txt" end println("table of obsCF printed to file $(filename)") df = writeTableCF(d) CSV.write(filename,df) end #descData(d,"summaryTreesQuartets$(string(integer(time()/1000))).txt") writeSummary && descData(d,"summaryTreesQuartets.txt") return d end # rename the function readInputData to make it more user-friendly """ readTrees2CF(treefile) readTrees2CF(vector of trees) Read trees in parenthetical format from a file, or take a vector of trees already read, and calculate the proportion of these trees having a given quartet (concordance factor: CF), for all quartets or for a sample of quartets. Optional arguments include: - quartetfile: name of text file with list of 4-taxon subsets to be analyzed. If none is specified, the function will list all possible 4-taxon subsets. - whichQ="rand": to choose a random sample of 4-taxon subsets - numQ: size of random sample (ignored if whichQ is not set to "rand") - writeTab=false: does not write the observedCF to a table (default true) - CFfile: name of file to save the observedCF (default tableCF.txt) - writeQ=true: save intermediate files with the list of all 4-taxon subsets and chosen random sample (default false). - writeSummary: write descriptive stats of input data (default: true) - nexus: if true, it assumes the gene trees are written in nexus file (default: false) See also: [`countquartetsintrees`](@ref), which uses a much faster algorithm; [`readTableCF`](@ref) to read a table of quartet CFs directly. """ function readTrees2CF(treefile::AbstractString; quartetfile="none"::AbstractString, whichQ="all"::AbstractString, numQ=0::Integer, writeTab=true::Bool, CFfile="none"::AbstractString, taxa::AbstractVector=Vector{String}(), writeQ=false::Bool, writeSummary=true::Bool, nexus=false::Bool) trees = (nexus ? readnexus_treeblock(treefile, readTopologyUpdate, false, false; reticulate=false) : readInputTrees(treefile)) if length(taxa)==0 # unionTaxa(trees) NOT default argument: taxa = unionTaxa(trees) # otherwise: tree file is read twice end readTrees2CF(trees, quartetfile=quartetfile, whichQ=whichQ, numQ=numQ, writeTab=writeTab, CFfile=CFfile, taxa=taxa, writeQ=writeQ, writeSummary=writeSummary) end # same as before, but with input vector of HybridNetworks function readTrees2CF(trees::Vector{HybridNetwork}; quartetfile="none"::AbstractString, whichQ="all"::AbstractString, numQ=0::Integer, writeTab=true::Bool, CFfile="none"::AbstractString, taxa::AbstractVector=unionTaxa(trees), writeQ=false::Bool, writeSummary=true::Bool) whichQ == "all" || whichQ == "rand" || error("whichQ should be all or rand, not $(whichQ)") if(quartetfile == "none") readInputData(trees, Symbol(whichQ), numQ, taxa, writeTab, CFfile, writeQ, writeSummary) else readInputData(trees, quartetfile, Symbol(whichQ), numQ, writeTab, CFfile, writeQ, writeSummary) end end # ---------------------- descriptive stat for input data ---------------------------------- # function to check how taxa is represented in the input trees function taxaTreesQuartets(trees::Vector{HybridNetwork}, quartets::Vector{Quartet},s::IO) taxaT = unionTaxa(trees) taxaQ = unionTaxa(quartets) dif = symdiff(taxaT,taxaQ) isempty(dif) ? write(s,"\n same taxa in gene trees and quartets: $(taxaT)\n") : write(s,"\n $(length(dif)) different taxa found in gene trees and quartets. \n Taxa $(intersect(taxaT,dif)) in trees, not in quartets; and taxa $(intersect(taxaQ,dif)) in quartets, not in trees\n") u = union(taxaT,taxaQ) for taxon in u numT = taxonTrees(taxon,trees) #numQ = taxonQuartets(taxon,quartets) write(s,"Taxon $(taxon) appears in $(numT) input trees ($(round(100*numT/length(trees), digits=2)) %)\n") #and $(numQ) quartets ($(round(100*numQ/length(quartets), digits=2)) %)\n") end end taxaTreesQuartets(trees::Vector{HybridNetwork}, quartets::Vector{Quartet}) = taxaTreesQuartets(trees, quartets, stdout) # function that counts the number of trees in which taxon appears function taxonTrees(taxon::AbstractString, trees::Vector{HybridNetwork}) suma = 0 for t in trees suma += in(taxon,t.names) ? 1 : 0 end return suma end # function that counts the number of quartets in which taxon appears function taxonQuartets(taxon::AbstractString, quartets::Vector{Quartet}) suma = 0 for q in quartets suma += in(taxon,q.taxon) ? 1 : 0 end return suma end # function to create descriptive stat from input data, will save in stream sout # which can be a file or stdout # default: send to stdout # pc: only 4-taxon subsets with percentage of gene trees less than pc will be printed (default 70%) function descData(d::DataCF, sout::IO, pc::Float64) 0<=pc<=1 || error("percentage of missing genes should be between 0,1, not: $(pc)") if !isempty(d.tree) print(sout,"data consists of $(d.numTrees) gene trees and $(d.numQuartets) 4-taxon subsets\n") taxaTreesQuartets(d.tree,d.quartet,sout) print(sout,"----------------------------\n\n") print(sout,"will print below only the 4-taxon subsets with data from <= $(round((pc)*100, digits=2))% genes\n") for q in d.quartet percent = q.ngenes == -1.0 ? 0.0 : round(q.ngenes/d.numTrees*100, digits=2) if percent < pc print(sout,"4-taxon subset $(q.taxon) obsCF constructed with $(round(q.ngenes)) gene trees ($(percent)%)\n") end end print(sout,"----------------------------\n\n") else if !isempty(d.quartet) print(sout,"data consists of $(d.numQuartets) 4-taxon subsets") taxa=unionTaxa(d.quartet) print(sout,"\nTaxa: $(taxa)\n") print(sout,"Number of Taxa: $(length(taxa))\n") numQ = binomial(length(taxa),4); print(sout,"Maximum number of 4-taxon subsets: $(numQ). Thus, $(round(100*d.numQuartets/numQ, digits=2)) percent of 4-taxon subsets sampled\n") end end end function descData(d::DataCF, filename::AbstractString,pc::Float64) println("descriptive stat of input data printed to file $(filename)") s = open(filename, "w") descData(d,s,pc) close(s) end descData(d::DataCF, sout::IO=stdout) = descData(d, sout,0.7) descData(d::DataCF,pc::Float64) = descData(d, stdout,pc) descData(d::DataCF, filename::AbstractString) = descData(d, filename,0.7) """ `summarizeDataCF(d::DataCF)` function to summarize the information contained in a DataCF object. It has the following optional arguments: - filename: if provided, the summary will be saved in the filename, not to screen - pc (number between (0,1)): threshold of percentage of missing genes to identify 4-taxon subsets with fewer genes than the threshold """ function summarizeDataCF(d::DataCF; filename="none"::AbstractString, pc=0.7::Float64) 0<=pc<=1 || error("percentage of missing genes should be between 0,1, not: $(pc)") if filename == "none" descData(d,stdout,pc) else descData(d,filename,pc) end end # -------- branch length estimate in coalescent units on species tree ------ """ updateBL!(net::HybridNetwork, d::DataCF) Update internal branch lengths of `net` based on the average quartet concordance factor (CF) across all quartets that exactly correspond to a given branch: new branch length = `-log(3/2(1-mean(CF observed in d)))`. `net` is assumed to be a tree, such that the above equation holds. """ function updateBL!(net::HybridNetwork,d::DataCF) if !isTree(net) @error "updateBL! was created for a tree, and net here is not a tree, so no branch lengths updated" end parts = edgesParts(net) df = makeTable(net,parts,d) x = combine(groupby(df, :edge), nrow => :Nquartets, :CF => (x -> -log(3/2*(1. - mean(x)))) => :edgeL) edges = x[!,:edge] lengths = x[!,:edgeL] for i in 1:length(edges) ind = getIndexEdge(edges[i],net) # helpful error if not found if net.edge[ind].length < 0.0 || net.edge[ind].length==1.0 # readTopologyLevel1 changes missing branch length to 1.0 setLength!(net.edge[ind], (lengths[i] > 0 ? lengths[i] : 0.0)) end end for e in net.edge if e.length < 0.0 # some edges might have *no* quartet in the data setLength!(e, 1.0) end end return x end # function to get part1,part2,part3,part4 for each edge in net.edge # returns a EdgeParts object function edgesParts(net::HybridNetwork) parts = EdgeParts[] #vector to hold part1,...,part4 for each edge for e in net.edge if(isInternalEdge(e)) length(e.node) == 2 || error("strange edge with $(length(e.node)) nodes instead of 2") n1 = e.node[1] n2 = e.node[2] e11,e12 = hybridEdges(n1,e) e21,e22 = hybridEdges(n2,e) part1 = Node[] part2 = Node[] part3 = Node[] part4 = Node[] getDescendants!(getOtherNode(e11,n1),e11,part1) getDescendants!(getOtherNode(e12,n1),e12,part2) getDescendants!(getOtherNode(e21,n2),e21,part3) getDescendants!(getOtherNode(e22,n2),e22,part4) push!(parts, EdgeParts(e.number,part1,part2,part3,part4)) end end return parts end # aux function to traverse the network from a node and an edge # based on traverseContainRoot # warning: it does not go accross hybrid node, minor hybrid edge # there is another getDescendants in update.jl for updatePartition function getDescendants!(node::Node, edge::Edge, descendants::Array{Node,1}) if(node.leaf) push!(descendants, node) else for e in node.edge if(!isEqual(edge,e) && e.isMajor) other = getOtherNode(e,node); getDescendants!(other,e, descendants); end end end end # function to make table to later use in updateBL # uses vector parts obtained from edgeParts function function makeTable(net::HybridNetwork, parts::Vector{EdgeParts},d::DataCF) df = DataFrame(edge=Int[],t1=AbstractString[],t2=AbstractString[],t3=AbstractString[],t4=AbstractString[],resolution=AbstractString[],CF=Float64[]) sortedDataQ = [sort(q.taxon) for q in d.quartet] for p in parts #go over internal edges too for t1 in p.part1 for t2 in p.part2 for t3 in p.part3 for t4 in p.part4 tx1 = net.names[t1.number] tx2 = net.names[t2.number] tx3 = net.names[t3.number] tx4 = net.names[t4.number] nam = [tx1,tx2,tx3,tx4] snam = sort(nam) row = findall(isequal(snam), sortedDataQ) for r in row # nothing if tax set not found: length(row)=0 col,res = resolution(nam,d.quartet[r].taxon) push!(df, [p.edgenum,tx1,tx2,tx3,tx4,res,d.quartet[r].obsCF[col]]) end end end end end end return df end # function to determine the resolution of taxa picked from part1,2,3,4 and DataCF # names: taxa from part1,2,3,4 # rownames: taxa from table of obsCF function resolution(names::Vector{<:AbstractString},rownames::Vector{<:AbstractString}) length(names) == length(rownames) || error("names and rownames should have the same length") length(names) == 4 || error("names should have 4 entries, not $(length(names))") bin = [n == names[1] || n == names[2] ? 1 : 0 for n in rownames] if(bin == [1,1,0,0] || bin == [0,0,1,1]) return 1,"12|34" elseif(bin == [1,0,1,0] || bin == [0,1,0,1]) return 2,"13|24" elseif(bin == [1,0,0,1] || bin == [0,1,1,0]) return 3,"14|23" else error("strange resolution $(bin)") end end # function to extract a quartet from a matrix M # obtained from tree2Matrix (defined in file compareNetworks.jl) # this function is meant to replace extractQuartet! in calculateObsCFAll # input: Quartet, Matrix, vector of taxa names # returns 1 if quartet found is 12|34, 2 if 13|24, 3 if 14|23, and 0 if not found function extractQuartetTree(q::Quartet, M::Matrix{Int},S::Union{Vector{<:AbstractString},Vector{Int}}) @debug "extractQuartet: $(q.taxon)" @debug "matrix: $(M)" inds = indexin(q.taxon, S) if any(isnothing, inds) error("some taxon in quartet $(q.taxon) not found in list of all species $(S)") end subM = M[:, inds.+1] @debug "subM: $(subM)" for r in 1:size(subM,1) #rows in subM @debug "subM[r,:]: $(subM[r,:])" if subM[r,:] == [0,0,1,1] || subM[r,:] == [1,1,0,0] return 1 elseif subM[r,:] == [0,1,0,1] || subM[r,:] == [1,0,1,0] return 2 elseif subM[r,:] == [0,1,1,0] || subM[r,:] == [1,0,0,1] return 3 end end return 0 end # function that will give the qth quartet without making a list of all quartets # input: n number of taxa, q desired index of quartet # returns vector of int, e.g. 1234 function whichQuartet(n::Int, q::Int) p = 4 q <= binom(n,p) || error("the index for the quartet $(q) needs to be less than choose(n,4)=$(binom(n,p))") n > 4 || error("there must be at least 5 taxa, not $(n)") quartet = Int[] while(n > 1) abs = binom(n-1,p) #fixit: we don't want to compute this, we want to look for it in a table if(q > abs) push!(quartet,n) n -= 1 p -= 1 q = q-abs else n -= 1 end end if(length(quartet) == 3) push!(quartet,1) end quartet = quartet[[4,3,2,1]] #sort return quartet end # function to write a quartet on integer to taxon names # it creates a Quartet type # input: list of taxa names, vector of integers (each integer corresponds to a taxon name), # num is the number of the Quartet # assumes taxa is sorted already function createQuartet(taxa::Union{Vector{<:AbstractString},Vector{Int}}, qvec::Vector{Int}, num::Int) length(qvec) == 4 || error("a quartet should have only 4 taxa, not $(length(qvec))") names = String[] for i in qvec i <= length(taxa) || error("want taxon number $(i) in list of taxon names $(taxa) which has only $(length(taxa)) names") push!(names,string(taxa[i])) end return Quartet(num,names,[1.0,0.0,0.0]) end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
72989
# functions to read/write networks topologies # peek the next non-white-space char # removes white spaces from the IOStream/IOBuffer # see skipchars(predicate, io::IO; linecomment=nothing) in io.jl # https://github.com/JuliaLang/julia/blob/3b02991983dd47313776091720871201f75f644a/base/io.jl#L971 # replace "while !eof ... read(io, Char)" by readeach(io, Char) # when ready to require Julia v1.6 # https://docs.julialang.org/en/v1/base/io-network/#Base.skipchars function peekskip(io::IO, linecomment=nothing) c = missing while !eof(io) c = read(io, Char) if c === linecomment readline(io) elseif !isspace(c) skip(io, -ncodeunits(c)) break end end return c # skipchar returns io instead end # aux function to read the next non-white-symbol char in s, advances s # input: s IOStream/IOBuffer function readskip!(io::IO) c = missing while !eof(io) c = read(io, Char) if !isspace(c) break end end return c end # advance stream in readSubtree function advance!(s::IO, numLeft::Array{Int,1}) c = readskip!(s) if ismissing(c) error("Tree ends prematurely while reading subtree after left parenthesis $(numLeft[1]-1).") end return c end """ readnexuscomment(s::IO, c::Char) Read (and do nothing with) nexus-style comments: `[& ... ]` Assumption: 'c' is the next character to be read from s. Output: nothing. Comments can appear after (or instead of) a node or leaf name, before or after an edge length, and after another comment. """ function readnexuscomment(s::IO, c::Char) while c == '[' # a comment could be followed by another # [ should be followed by &, otherwise bad newick string # read [ and next character: don't skip spaces read(s, Char) == '[' || error("I was supposed to read '['") read(s, Char) == '&' || error("read '[' but not followed by &") skipchars(!isequal(']'), s) eof(s) && error("comment without ] to end it") read(s, Char) # to read ] and advance s c = peekskip(s) end return end """ readnodename(s::IO, c::Char, net, numLeft) Auxiliary function to read a taxon name during newick parsing. output: tuple (number, name, pound_boolean) Names may have numbers: numbers are treated as strings. Accepts `#` as part of the name (but excludes it from the name), in which case `pound_boolean` is true. `#` is used in extended newick to flag hybrid nodes. Nexus-style comments following the node name, if any, are read and ignored. """ function readnodename(s::IO, c::Char, net::HybridNetwork, numLeft::Array{Int,1}) pound = 0 name = "" while isValidSymbol(c) readskip!(s) # advance s past c (discard c, already read) if c == '#' pound += 1 c = readskip!(s) # read the character after the # if !isletter(c) a = read(s, String); error("Expected name after # but received $(c) in left parenthesis $(numLeft[1]-1). remaining: $(a).") end if c != 'L' && c != 'H' && c != 'R' @warn "Expected H, R or LGT after # but received $(c) in left parenthesis $(numLeft[1]-1)." end name = c * name # put the H, R or LGT first else name *= c # original c: put it last end c = peekskip(s); end if pound >1 a = read(s, String); error("strange node name with $(pound) # signs: $name. remaining: $(a).") end readnexuscomment(s,c) return size(net.names,1)+1, name, pound == 1 end # aux function to read floats like length or gamma values, to be read after a colon function readFloat(s::IO, c::Char) if !(isdigit(c) || c in ['.','e','-','E']) a = read(s, String); error("Expected float digit after ':' but found $(c). remaining is $(a)."); end num = "" while isdigit(c) || c in ['.','e','-', 'E'] d = read(s, Char) # reads c and advances IO num = string(num,d); c = peekskip(s); end f = 0.0 try f = parse(Float64, num) catch error("problem with number read $(num), not a float number") end return f end # aux function to identify if a symbol in taxon name is valid # allowed: letters, numbers, underscores, # (for hybrid name) # NOT allowed: white space () [] : ; ' , # according to richnewick.pdf # actually: ' is allowed. coded weirdly imo! function isValidSymbol(c::Char) return isletter(c) || isnumeric(c) || c=='_' || c=='#' || (!isspace(c) && c != '(' && c != ')' && c != '[' && c != ']' && c != ':' && c != ';' && c != ',') end """ parseRemainingSubtree!(s::IO, numLeft, net, hybrids) Create internal node. Helper for [`readSubtree!`](@ref), which creates the parent edge of the node created by `parseRemainingSubtree!`: `readSubtree!` calls `parseRemainingSubtree!`, and vice versa. Called once a `(` has been read in a tree topology and reads until the corresponding `)` has been found. This function performs the recursive step for `readSubtree!`. Advances `s` past the subtree, adds discovered nodes and edges to `net`, and `hybrids`. Does *not* read the node name and the edge information of the subtree root: this is done by [`readSubtree!`](@ref) """ @inline function parseRemainingSubtree!(s::IO, numLeft::Array{Int,1}, net::HybridNetwork, hybrids::Vector{String}) numLeft[1] += 1 # DEBUGC && @debug "" numLeft n = Node(-1*numLeft[1],false); # @debug "creating node $(n.number)" keepon = true; c = readskip!(s) while (keepon) bl = readSubtree!(s,n,numLeft,net,hybrids) c = advance!(s,numLeft) if c == ')' keepon = false elseif c != ',' a = read(s, String); error("Expected right parenthesis after left parenthesis $(numLeft[1]-1) but read $(c). The remainder of line is $(a).") end end return n end """ parseHybridNode!(node, parentNode, hybridName, net, hybrids) Helper function for `readSubtree!`. Create the parent edge for `node`. Return this edge, and the hybrid node retained (`node` or its clone in the newick string). Insert new edge and appropriate node into `net` and `hybrids` accordingly. Handles any type of given hybrid node. Called after a `#` has been found in a tree topology. """ @inline function parseHybridNode!(n::Node, parent::Node, name::String, net::HybridNetwork, hybrids::Vector{String}) # @debug "found pound in $(name)" n.hybrid = true; # DEBUGC && @debug "got hybrid $(name)" # DEBUGC && @debug "hybrids list has length $(length(hybrids))" ind = findfirst(isequal(name), hybrids) # index of 'name' in the list 'hybrid'. nothing if not found e = Edge(net.numEdges+1) # isMajor = true by default if n.leaf e.isMajor = false; end e.hybrid = true e.gamma = -1.0 if ind !== nothing # the hybrid name was seen before # @debug "$(name) was found in hybrids list" ni = findfirst(isequal(name), [no.name for no in net.node]) ni !== nothing || error("hybrid name $name was supposed to be in the network, but not found") other = net.node[ni] # @debug "other is $(other.number)" # DEBUGC && @debug "other is leaf? $(other.leaf), n is leaf? $(n.leaf)" if !n.leaf && !other.leaf error("both hybrid nodes are internal nodes: successors of the hybrid node must only be included in the node list of a single occurrence of the hybrid node.") elseif n.leaf # @debug "n is leaf" # @debug "creating hybrid edge $(e.number) attached to other $(other.number) and parent $(parent.number)" pushEdge!(net,e); setNode!(e,[other,parent]); # isChild1 = true by default constructor setEdge!(other,e); setEdge!(parent,e); n = other # original 'n' dropped, 'other' retained: 'n' output to modify 'n' outside # @debug "e $(e.number )istIdentifiable? $(e.istIdentifiable)" else # !n.leaf : delete 'other' from the network # @debug "n is not leaf, other is leaf" size(other.edge,1) == 1 || # other should be a leaf error("strange: node $(other.number) is a leaf hybrid node. should have only 1 edge but has $(size(other.edge,1))") # DEBUGC && @debug "other is $(other.number), n is $(n.number), edge of other is $(other.edge[1].number)" otheredge = other.edge[1]; otherparent = getOtherNode(otheredge,other); # @debug "otheredge is $(otheredge.number)" # @debug "parent of other is $(otherparent.number)" removeNode!(other,otheredge); deleteNode!(net,other); setNode!(otheredge,n); setEdge!(n,otheredge); ## otheredge.istIdentifiable = true ## setNode should catch this, but when fixed, causes a lot of problems # @debug "setting otheredge to n $(n.number)" # @debug "creating hybrid edge $(e.number) between n $(n.number) and parent $(parent.number)" setNode!(e,[n,parent]); setEdge!(n,e); setEdge!(parent,e); pushNode!(net,n); pushEdge!(net,e); n.number = other.number; # modifies original negative node number, to positive node # n.name = other.name; # @debug "edge $(e.number) istIdentifiable? $(e.istIdentifiable)" # @debug "otheredge $(otheredge.number) istIdentifiable? $(otheredge.istIdentifiable)" end else # ind==nothing: hybrid name not seen before # @debug "$(name) not found in hybrids list" # @debug "$(name) is leaf? $(n.leaf)" n.hybrid = true; nam = string(name) push!(net.names, nam); n.name = nam; # DEBUGC && @debug "put $(nam) in hybrids name list" push!(hybrids, nam); pushNode!(net,n); # @debug "creating hybrid edge $(e.number)" pushEdge!(net,e); setNode!(e,[n,parent]); setEdge!(n,e); setEdge!(parent,e); # @debug "edge $(e.number) istIdentifiable? $(e.istIdentifiable)" end e.containRoot = !e.hybrid # not good: but necessay for SNaQ functions return (e,n) end """ parseTreeNode!(node, parentNode, net) Helper function for `readSubtree!`. Insert the input tree node and associated edge (created here) into `net`. """ @inline function parseTreeNode!(n::Node, parent::Node, net::HybridNetwork) pushNode!(net,n); e = Edge(net.numEdges+1); pushEdge!(net,e); setNode!(e,[n,parent]); setEdge!(n,e); setEdge!(parent,e); return e end """ getdataValue!(s::IO, int, numLeft::Array{Int,1}) Helper function for `parseEdgeData!`. Read a single floating point edge data value in a tree topology. Ignore (and skip) nexus-style comments before & after the value (see [`readnexuscomment`](@ref)). Return -1.0 if no value exists before the next colon, return the value as a float otherwise. Modifies s by advancing past the next colon character. Only call this function to read a value when you know a numerical value exists! """ @inline function getDataValue!(s::IO, call::Int, numLeft::Array{Int,1}) errors = ["one colon read without double in left parenthesis $(numLeft[1]-1), ignored.", "second colon : read without any double in left parenthesis $(numLeft[1]-1), ignored.", "third colon : without gamma value after in $(numLeft[1]-1) left parenthesis, ignored"] c = peekskip(s) if c == '[' # e.g. comments only, no value, but : after readnexuscomment(s,c) c = peekskip(s) end if isdigit(c) || c == '.' || c == '-' # value is present: read it, and any following comment(s) val = readFloat(s, c) if val < 0.0 @error "expecting non-negative value but read '-', left parenthesis $(numLeft[1]-1). will set to 0." val = 0.0 end readnexuscomment(s,peekskip(s)) return val # No value elseif c == ':' return -1.0 else @warn errors[call] return -1.0 end end """ parseEdgeData!(s::IO, edge, numberOfLeftParentheses::Array{Int,1}) Helper function for readSubtree!. Modifies `e` according to the specified edge length and gamma values in the tree topology. Advances the stream `s` past any existing edge data. Edges in a topology may optionally be followed by ":edgeLen:bootstrap:gamma" where edgeLen, bootstrap, and gamma are decimal values. Nexus-style comments `[&...]`, if any, are ignored. """ @inline function parseEdgeData!(s::IO, e::Edge, numLeft::Array{Int,1}) read(s, Char); # to read the first ":" e.length = getDataValue!(s, 1, numLeft) bootstrap = nothing; if peekskip(s) == ':' readskip!(s) bootstrap = getDataValue!(s, 2, numLeft) end # e.gamma = -1.0 by default when e is created by parseHybridNode! if peekskip(s) == ':' readskip!(s) e.gamma = getDataValue!(s, 3, numLeft) end if e.gamma != -1.0 && !e.hybrid && e.gamma != 1.0 @warn "γ read for edge $(e.number) but it is not hybrid, so γ=$(e.gamma) ignored" e.gamma = 1.0 end end """ synchronizePartnersData!(e::Edge, n::Node) Synchronize γ and isMajor for edges `e` and its partner, both hybrid edges with the same child `n`: - if one γ is missing and the other is not: set the missing γ to 1 - the other - γ's should sum up to 1.0 - update `isMajor` to match the γ information: the major edge is the one with γ > 0.5. **Warnings**: does not check that `e` is a hybrid edge, nor that `n` is the child of `e`. """ @inline function synchronizePartnersData!(e::Edge, n::Node) partners = Edge[] # The edges having n as a child, other than e for e2 in n.edge if e2.hybrid && e2!=e && n==getchild(e2) push!(partners, e2) end end numPartners = length(partners) if numPartners == 0 return nothing end if numPartners > 1 # 3 or more hybrid parents error("γ value parsed but hybrid edge has $numPartners partners (should be 0 or 1)") end # numPartners == 1 then. partner edge has been read, may have gamma set partner = partners[1] if e.gamma == -1. && partner.gamma == -1. # exact -1.0 means missing return nothing end # γ non-missing for e and/or partner, then # update γ and isMajor of both edges, to be consistent with each other if e.gamma == -1. if partner.gamma < 0.0 @warn "partners: $(e.number) with no γ, $(partner.number) with γ<0. will turn to 1 and 0" partner.gamma = 0.0 e.gamma = 1.0 elseif partner.gamma > 1.0 @warn "partners: $(e.number) with no γ, $(partner.number) with γ>1. will turn to 0 and 1" partner.gamma = 1.0 e.gamma = 0.0 else # partner γ in [0,1] e.gamma = 1. - partner.gamma end elseif partner.gamma == -1. if e.gamma < 0.0 @warn "partners: $(partner.number) with no γ, $(e.number) with γ<0. will turn to 1 and 0" e.gamma = 0.0 partner.gamma = 1.0 elseif e.gamma > 1.0 @warn "partners: $(partner.number) with no γ, $(e.number) with γ>1. will turn to 0 and 1" e.gamma = 1.0 partner.gamma = 0.0 else # γ in [0,1] partner.gamma = 1. - e.gamma end else # both γ's are non-missing. won't check if negative gammasum = e.gamma + partner.gamma if !isapprox(gammasum, 1.0) e.gamma = e.gamma/gammasum partner.gamma = 1. - e.gamma end end # next: update isMajor, originally based on which node was a leaf and which was not # if both γ are 0.5: keep isMajor as is. Otherwise: γ's take precedence. if !isapprox(e.gamma, 0.5) emajor = e.gamma > 0.5 if e.isMajor != emajor # leaf status was inconsistent with γ info e.isMajor = emajor partner.isMajor = !emajor end end end """ readSubtree!(s::IO, parentNode, numLeft, net, hybrids) Recursive helper method for `readTopology`: read a subtree from an extended Newick topology. input `s`: IOStream/IOBuffer. Reads additional info formatted as: `:length:bootstrap:gamma`. Allows for name of internal nodes without # after closing parenthesis: (1,2)A. Warning if hybrid edge without γ, or if γ (ignored) without hybrid edge """ function readSubtree!(s::IO, parent::Node, numLeft::Array{Int,1}, net::HybridNetwork, hybrids::Vector{String}) c = peekskip(s) e = nothing; hasname = false; # to know if the current node has name pound = false; if c == '(' # read the rest of the subtree (perform the recursive step!) n = parseRemainingSubtree!(s, numLeft, net, hybrids) c = peekskip(s); # read potential internal node name (and skip comments) num, name, pound = readnodename(s, c, net, numLeft); if name != "" hasname = true; n.number = num; # n was given <0 number by parseRemainingSubtree!, now >0 end else # leaf, it should have a name hasname = true; num, name, pound = readnodename(s, c, net, numLeft) if name == "" a = read(s, String); error("Expected digit, alphanum or # at the start of taxon name, but received $(c). remaining: $(a)."); end n = Node(num, true); # positive node number to leaves in the newick-tree description # @debug "creating node $(n.number)" end if pound # found pound sign in name # merge the 2 nodes corresponding the hybrid: make n the node that is retained e,n = parseHybridNode!(n, parent, name, net, hybrids) # makes hybrid node number >0 else if hasname push!(net.names, name); n.name = name end e = parseTreeNode!(n, parent, net) end c = peekskip(s); e.length = -1.0 if c == ':' parseEdgeData!(s, e, numLeft) end if e.hybrid # if hybrid edge: 'e' might have no info, but its partner may have had info synchronizePartnersData!(e, n) # update γ and isMajor of e and/or its partner end return true end # function to read topology from parenthetical format # input: file name or tree in parenthetical format # calls readTopology(s::IO) # warning: crashes if file name starts with ( function readTopology(input::AbstractString,verbose::Bool) if(input[1] == '(') # input = parenthetical description s = IOBuffer(input) else # input = file name try s = open(input) catch error("Could not find or open $(input) file"); end s = open(input) end net = readTopology(s,verbose) return net end """ readTopology(file name) readTopology(parenthetical description) readTopology(IO) Read tree or network topology from parenthetical format (extended Newick). If the root node has a single child: ignore (i.e. delete from the topology) the root node and its child edge. Input: text file or parenthetical format directly. The file name may not start with a left parenthesis, otherwise the file name itself would be interpreted as the parenthetical description. Nexus-style comments (`[&...]`) are ignored, and may be placed after (or instead) of a node name, and before/after an edge length. A root edge, not enclosed within a pair a parentheses, is ignored. If the root node has a single edge, this one edge is removed. """ readTopology(input::AbstractString) = readTopology(input,true) function readTopology(s::IO,verbose::Bool) net = HybridNetwork() line = readuntil(s,";", keep=true); if(line[end] != ';') error("file does not end in ;") end seekstart(s) c = peekskip(s) numLeft = [1]; # made Array to make it mutable; start at 1 to avoid node -1 which breaks undirectedOtherNetworks hybrids = String[]; if(c == '(') numLeft[1] += 1; #println(numLeft) n = Node(-1*numLeft[1],false); c = readskip!(s) b = false; while(c != ';') b |= readSubtree!(s,n,numLeft,net,hybrids) c = readskip!(s); if eof(s) error("Tree ended while reading in subtree beginning with left parenthesis number $(numLeft[1]-1).") elseif c == ',' continue; elseif c == ')' # read potential root name (or comments) c = peekskip(s); num, name, pound = readnodename(s, c, net, numLeft) if name != "" n.name = name # log warning or error if pound > 0? end c = peekskip(s) if(c == ':') # skip information on the root edge, if it exists # @warn "root edge ignored" while c != ';' c = readskip!(s) end end end end # @debug "after readsubtree:" # @debug begin printEdges(net); "printed edges" end # delete the root edge, if present if size(n.edge,1) == 1 # root node n has only one edge edge = n.edge[1] child = getOtherNode(edge,n); removeEdge!(child,edge); net.root = getIndex(child,net); deleteEdge!(net,edge); else pushNode!(net,n); net.root = getIndex(n,net); end else a = read(s, String) error("Expected beginning of tree with ( but received $(c) instead, rest is $(a)") end storeHybrids!(net) checkNumHybEdges!(net) directEdges!(net; checkMajor=true) # to update edges containRoot: true until hybrid, false below hybrid net.isRooted = true return net end readTopology(s::IO) = readTopology(s,true) """ checkNumHybEdges!(net) Check for consistency between hybrid-related attributes in the network: - for each hybrid node: 2 or more hybrid edges - exception: allows for a leaf to be attached to a single hybrid edge - exactly 2 incoming parent hybrid edges Run after `storeHybrids!`. See also `check2HybEdges`. """ function checkNumHybEdges!(net::HybridNetwork) if isTree(net) return nothing; end !isempty(net.hybrid) || error("net.hybrid should not be empty for this network") for n in net.hybrid hyb = sum([e.hybrid for e in n.edge]); # number of hybrid edges attached to node if hyb == 1 if net.numHybrids == 1 error("only one hybrid node $(n.number) named $(n.name) found with one hybrid edge attached") else error("hybrid node $(n.number) named $(n.name) has only one hybrid edge attached. there are $(net.numHybrids-1) other hybrids out there but this one remained unmatched") end elseif hyb == 0 if length(n.edge) == 0 error("strange hybrid node $(n.number) attached to 0 edges") elseif length(n.edge) == 1 n.leaf || error("hybrid node $(n.number) has only one tree edge attached and it is not a leaf") elseif length(n.edge) >= 2 @warn "hybrid node $(n.number) not connected to any hybrid edges. Now transformed to tree node" n.hybrid = false; end elseif hyb >=2 # check: exactly 2 incoming, no more. nhybparents = 0 for e in n.edge if n == getchild(e) if e.hybrid nhybparents += 1 else @error "node $(n.number) has parent tree edge $(e.number): wrong isChild1 for this edge?" end end end if nhybparents < 2 error("hybrid node $(n.number) with $nhybparents = fewer than 2 hybrid parents") elseif nhybparents >2 error("hybrid node $(n.number) with $nhybparents: we don't allow such polytomies") end end end return nothing end # aux function to send an error if the number of hybrid attached to every # hybrid node is >2 function check2HybEdges(net::HybridNetwork) for n in net.hybrid hyb = sum([e.hybrid for e in n.edge]); if hyb > 2 error("hybrid node $(n.number) has more than two hybrid edges attached to it: polytomy that cannot be resolved without intersecting cycles.") end end end # aux function to solve a polytomy # warning: chooses one resolution at random function solvePolytomyRecursive!(net::HybridNetwork, n::Node) if(size(n.edge,1) == 4) edge1 = n.edge[1]; edge2 = n.edge[2]; edge3 = n.edge[3]; edge4 = n.edge[4]; removeEdge!(n,edge3); removeEdge!(n,edge4); removeNode!(n,edge3); removeNode!(n,edge4); ednew = Edge(net.numEdges+1,0.0); max_node = maximum([e.number for e in net.node]); n1 = Node(max_node+1,false,false,[edge3,edge4,ednew]); setEdge!(n,ednew); setNode!(edge3,n1); setNode!(edge4,n1); setNode!(ednew,[n,n1]); pushNode!(net,n1); pushEdge!(net,ednew); else edge1 = n.edge[1]; removeEdge!(n,edge1); solvePolytomyRecursive!(net,n); setEdge!(n,edge1); end end # function to solve a polytomy among tree edges recursively function solvePolytomy!(net::HybridNetwork, n::Node) !n.hybrid || error("cannot solve polytomy in a hybrid node $(n.number).") while(size(n.edge,1) > 3) solvePolytomyRecursive!(net,n); end end # aux function to add a child to a leaf hybrid function addChild!(net::HybridNetwork, n::Node) n.hybrid || error("cannot add child to tree node $(n.number).") ed1 = Edge(net.numEdges+1,0.0); n1 = Node(size(net.names,1)+1,true,false,[ed1]); setEdge!(n,ed1); setNode!(ed1,[n,n1]); pushNode!(net,n1); pushEdge!(net,ed1); end # aux function to expand the children of a hybrid node function expandChild!(net::HybridNetwork, n::Node) if n.hybrid suma = count([!e.hybrid for e in n.edge]); #println("create edge $(net.numEdges+1)") ed1 = Edge(net.numEdges+1,0.0); n1 = Node(size(net.names,1)+1,false,false,[ed1]); #println("create node $(n1.number)") hyb = Edge[]; for i in 1:size(n.edge,1) if !n.edge[i].hybrid push!(hyb,n.edge[i]); end end #println("hyb tiene $([e.number for e in hyb])") for e in hyb #println("se va a borrar a $(e.number)") removeEdge!(n,e); removeNode!(n,e); setEdge!(n1,e); setNode!(e,n1); end #println("now node $(n1.number) has the edges $([e.number for e in n1.edge])") setEdge!(n,ed1); setNode!(ed1,[n,n1]); pushNode!(net,n1); pushEdge!(net,ed1); if size(n1.edge,1) > 3 solvePolytomy!(net,n1); end else error("cannot expand children of a tree node.") end end # function to clean topology after readTopology # looks for: # TREE: # - all tree edges must have gamma=1. fixit: cannot point out which doesn't, # only shows error. # - internal nodes with only 2 edges and solves this case. # - polytomies and choose one resolution at random, issuing a warning # NETWORK: # - number of hybrid edges per hybrid node: # if 0,1: error (with warning in old functions) # if >2: error of hybrid polytomy # if 2: check number of tree edges # - number of tree edges per hybrid node: # if 0: leaf hybrid, add child # if >1: expand child # if 1: check values of gamma: # - gammas: need to sum to one and be present. # error if they do not sum up to one # default values of 0.1,0.9 if not present # leaveRoot=true: leaves the root even if it has only 2 edges (for plotting), default=false function cleanAfterRead!(net::HybridNetwork, leaveRoot::Bool) # set e.containRoot to !e.hybrid: updated later by updateAllReadTopology as required by snaq! for e in net.edge e.containRoot = !e.hybrid; end nodes = copy(net.node) for n in nodes if isNodeNumIn(n,net.node) # very important to check if size(n.edge,1) == 2 # delete n if: if (!n.hybrid && (!leaveRoot || !isEqual(net.node[net.root],n)) || (n.hybrid && sum(e.hybrid for e in n.edge) == 1)) deleteIntNode!(net,n) continue # n was deleted: skip the rest end end if !n.hybrid if size(n.edge,1) > 3 @debug "warning: polytomy found in node $(n.number), random resolution chosen" solvePolytomy!(net,n); end hyb = count([e.hybrid for e in n.edge]) if hyb == 1 n.hasHybEdge == true; elseif hyb > 1 @warn "strange tree node $(n.number) with more than one hybrid edge, intersecting cycles maybe" end else hyb = count([e.hybrid for e in n.edge]); tre = length(n.edge) - hyb if hyb > 2 error("hybrid node $(n.number) has more than two hybrid edges attached to it: polytomy that cannot be resolved without intersecting cycles.") elseif hyb == 1 hybnodes = count([n.hybrid for n in net.node]); if hybnodes == 1 error("only one hybrid node number $(n.number) with name $(net.names[n.number]) found with one hybrid edge attached") else error("current hybrid node $(n.number) with name $(net.names[n.number]) has only one hybrid edge attached. there are other $(hybnodes-1) hybrids out there but this one remained unmatched") end elseif hyb == 0 @warn "hybrid node $(n.number) is not connected to any hybrid edges, it was transformed to tree node" n.hybrid = false; else # 2 hybrid edges if tre == 0 #hybrid leaf @warn "hybrid node $(n.number) is a leaf, so we add an extra child" addChild!(net,n); elseif tre > 1 @warn "hybrid node $(n.number) has more than one child so we need to expand with another node" expandChild!(net,n); end suma = sum([e.hybrid ? e.gamma : 0.0 for e in n.edge]); # synchronizePartnersData! already made suma ≈ 1.0, when non-missing, # and already synchronized isMajor, even when γ's ≈ 0.5 if suma == -2.0 # hybrid edges have no gammas in newick description println("hybrid edges for hybrid node $(n.number) have missing gamma's, set default: 0.9,0.1") for e in n.edge if e.hybrid e.gamma = (e.isMajor ? 0.9 : 0.1) end end end end end end end for e in net.edge if e.hybrid if e.gamma < 0.0 || e.gamma > 1.0 # no -1.0 (missing) γ's by now error("hybrid edge $(e.number) with γ = $(e.gamma) outside of [0,1]") end else e.gamma == 1.0 || error("tree edge $(e.number) with γ = $(e.gamma) instead of 1.0") end end end cleanAfterRead!(net::HybridNetwork) = cleanAfterRead!(net,false) # function to search for the hybrid nodes in a read network after cleaning it # and store this information as a network's attribute function storeHybrids!(net::HybridNetwork) flag = true; hybrid = nothing try hybrid = searchHybridNode(net) catch #@warn "topology read is a tree as it has no hybrid nodes" flag = false; end if(flag) net.hybrid = hybrid; net.numHybrids = size(hybrid,1); end return nothing end # function to update the read topology after reading # it will go over the net.hybrid array and check each # of the hybridization events defined to update: # - in cycle # - contain root # - gammaz # it uses updateAllNewHybrid! function that # returns: success (bool), hybrid, flag, nocycle, flag2, flag3 # if tree read, also check that contain root is true for all, ishybrid and hashybedge is false # warning: needs to have run storeHybrids! before # warning: it will stop when finding one conflicting hybrid function updateAllReadTopology!(net::HybridNetwork) if(isTree(net)) #@warn "not a network read, but a tree as it does not have hybrid nodes" all((e->e.containRoot), net.edge) ? nothing : error("some tree edge has contain root as false") all((e->!e.hybrid), net.edge) ? nothing : error("some edge is hybrid and should be all tree edges in a tree") all((n->!n.hasHybEdge), net.node) ? nothing : error("some tree node has hybrid edge true, but it is a tree, there are no hybrid edges") else if(!net.cleaned) for n in net.hybrid success,hyb,flag,nocycle,flag2,flag3 = updateAllNewHybrid!(n,net,false,true,false) if(!success) @warn "current hybrid $(n.number) conflicts with previous hybrid by intersecting cycles: $(!flag), nonidentifiable topology: $(!flag2), empty space for contain root: $(!flag3), or does not create a cycle (probably problem with the root placement): $(nocycle)." #net.cleaned = false end end @debug "before update partition" @debug begin printPartitions(net); "printed partitions" end for n in net.hybrid #need to updatePartition after all inCycle nocycle, edgesInCycle, nodesInCycle = identifyInCycle(net,n); updatePartition!(net,nodesInCycle) @debug begin printPartitions(net); "partitions after updating partition for hybrid node $(n.number)" end end end end end # cleanAfterReadAll includes all the step to clean a network after read function cleanAfterReadAll!(net::HybridNetwork, leaveRoot::Bool) @debug "check for 2 hybrid edges at each hybrid node -----" check2HybEdges(net) @debug "cleanBL -----" cleanBL!(net) @debug "cleanAfterRead -----" cleanAfterRead!(net,leaveRoot) @debug "updateAllReadTopology -----" updateAllReadTopology!(net) #fixit: it could break if leaveRoot = true (have not checked it), but we need to updateContainRoot if(!leaveRoot) @debug "parameters -----" parameters!(net) end @debug "check root placement -----" checkRootPlace!(net) net.node[net.root].leaf && @warn "root node $(net.node[net.root].number) is a leaf, so when plotting net, it can look weird" net.cleaned = true #fixit: set to false inside updateAllReadTopology if problem encountered net.isRooted = false end cleanAfterReadAll!(net::HybridNetwork) = cleanAfterReadAll!(net,false) # function to read a topology from file name/tree directly and update it # by calling updateAllReadTopology after # leaveRoot=true if the root will not be deleted even if it has only 2 edges # used for plotting (default=false) # warning: if leaveRoot=true, net should not be used outside plotting, things will crash function readTopologyUpdate(file::AbstractString, leaveRoot::Bool,verbose::Bool) @debug "readTopology -----" net = readTopology(file,verbose) cleanAfterReadAll!(net,leaveRoot) return net end readTopologyUpdate(file::AbstractString) = readTopologyUpdate(file, false, true) readTopologyUpdate(file::AbstractString,verbose::Bool) = readTopologyUpdate(file, false, verbose) """ readTopologyLevel1(filename) readTopologyLevel1(parenthetical format) same as readTopology, reads a tree or network from parenthetical format, but this function enforces the necessary conditions for any starting topology in SNaQ: non-intersecting cycles, no polytomies, unrooted. It sets any missing branch length to 1.0. If the network has a bad diamond II (in which edge lengths are γ's are not identifiable) and if the edge below this diamond has a length `t` different from 0, then this length is set back to 0 and the major parent hybrid edge is lengthened by `t`. """ readTopologyLevel1(file::AbstractString) = readTopologyUpdate(file, false, true) # aux function to check if the root is placed correctly, and re root if not # warning: it needs updateContainRoot set function checkRootPlace!(net::HybridNetwork; verbose=false::Bool, outgroup="none"::AbstractString) if(outgroup == "none") if(!canBeRoot(net.node[net.root])) verbose && println("root node $(net.node[net.root].number) placement is not ok, we will change it to the first found node that agrees with the direction of the hybrid edges") for i in 1:length(net.node) if(canBeRoot(net.node[i])) net.root = i break end end end else # outgroup tmp = findall(n -> n.name == outgroup, net.leaf) if length(tmp)==0 error("leaf named $(outgroup) was not found in the network.") elseif length(tmp)>1 error("several leaves were found with name $(outgroup).") end leaf = net.leaf[tmp[1]] leaf.leaf || error("found outgroup not a leaf: $(leaf.number), $(outgroup)") length(leaf.edge) == 1 || error("found leaf with more than 1 edge: $(leaf.number)") other = getOtherNode(leaf.edge[1],leaf); if(canBeRoot(other)) net.root = getIndexNode(other.number,net) else throw(RootMismatch("outgroup $(outgroup) contradicts direction of hybrid edges")) end end canBeRoot(net.node[net.root]) || error("tried to place root, but couldn't. root is node $(net.node[net.root])") end """ writeSubTree!(IO, network, dendroscope::Bool, namelabel::Bool, round_branch_lengths::Bool, digits::Integer, internallabel::Bool) Write to IO the extended newick format (parenthetical description) of a network. If written for dendroscope, inheritance γ's are not written. If `namelabel` is true, taxa are labelled by their names; otherwise taxa are labelled by their number IDs. If unspecified, branch lengths and γ's are rounded to 3 digits. Use `internallabel=false` to suppress the labels of internal nodes. """ function writeSubTree!(s::IO, net::HybridNetwork, di::Bool, namelabel::Bool, roundBL::Bool, digits::Integer, internallabel::Bool) rootnode = getroot(net) if net.numNodes > 1 print(s,"(") degree = length(rootnode.edge) for e in rootnode.edge writeSubTree!(s,getOtherNode(e,rootnode),e,di,namelabel,roundBL,digits,internallabel) degree -= 1 degree == 0 || print(s,",") end print(s,")") end if internallabel || net.numNodes == 1 print(s, (namelabel ? rootnode.name : rootnode.number)) end print(s,";") return nothing end """ writeSubTree!(IO, node, edge, dendroscope::Bool, namelabel::Bool, round_branch_lengths::Bool, digits::Integer, internallabel::Bool) Write the extended newick format of the sub-network rooted at `node` and assuming that `edge` is a parent of `node`. If the parent `edge` is `nothing`, the edge attribute `isChild1` is used and assumed to be correct to write the subtree rooted at `node`. This is useful to write a subtree starting at a non-root node. Example: ```julia net = readTopology("(((A,(B)#H1:::0.9),(C,#H1:::0.1)),D);") directEdges!(net) s = IOBuffer() writeSubTree!(s, net.node[7], nothing, false, true) String(take!(s)) ``` Used by [`writeTopology`](@ref). """ writeSubTree!(s,n,parent,di,namelabel) = writeSubTree!(s,n,parent,di,namelabel, true,3,true) # "parent' is assumed to be adjancent to "node". not checked. # algorithm comes from "parent": do not traverse again. function writeSubTree!(s::IO, n::Node, parent::Union{Edge,Nothing}, di::Bool, namelabel::Bool, roundBL::Bool, digits::Integer, internallabel::Bool) # subtree below node n: if !n.leaf && (parent == nothing || parent.isMajor) # do not descent below a minor hybrid edge print(s,"(") firstchild = true for e in n.edge e != parent || continue # skip parent edge where we come from if parent == nothing # skip if n = child of e n != getchild(e) || continue end (e.hybrid && getchild(e)==n) && continue # no going up minor hybrid firstchild || print(s, ",") firstchild = false child = getOtherNode(e,n) writeSubTree!(s,child,e, di,namelabel, roundBL, digits, internallabel) end print(s,")") end # node label: if parent != nothing && parent.hybrid print(s, "#") print(s, (namelabel ? n.name : string("H", n.number))) n.name != "" || parent.isMajor || @warn "hybrid node $(n.number) has no name" elseif internallabel || n.leaf print(s, (namelabel ? n.name : n.number)) end # branch lengths and γ, if available: printBL = false if parent != nothing && parent.length != -1.0 # -1.0 means missing print(s,string(":",(roundBL ? round(parent.length, digits=digits) : parent.length))) printBL = true end if parent != nothing && parent.hybrid && !di # && (!printID || !n.isBadDiamondI)) if(parent.gamma != -1.0) if(!printBL) print(s,":"); end print(s,string("::",(roundBL ? round(parent.gamma, digits=digits) : parent.gamma))) end end if parent == nothing print(s, ";") end end # see full docstring below # Need HybridNetwork input, since QuartetNetwork does not have root. function writeTopologyLevel1(net0::HybridNetwork, di::Bool, str::Bool, namelabel::Bool,outgroup::AbstractString, printID::Bool, roundBL::Bool, digits::Integer, multall::Bool) s = IOBuffer() writeTopologyLevel1(net0,s,di,namelabel,outgroup,printID,roundBL,digits, multall) if str return String(take!(s)) else return s end end # warning: I do not want writeTopologyLevel1 to modify the network if outgroup is given! thus, we have updateRoot, and undoRoot # note that if printID is true, the function is modifying the network function writeTopologyLevel1(net0::HybridNetwork, s::IO, di::Bool, namelabel::Bool, outgroup::AbstractString, printID::Bool, roundBL::Bool, digits::Integer, multall::Bool) global CHECKNET net = deepcopy(net0) #writeTopologyLevel1 needs containRoot, but should not alter net0 # net.numBad == 0 || println("network with $(net.numBad) bad diamond I. Some γ and edge lengths t are not identifiable, although their γ * (1-exp(-t)) are.") if printID setNonIdBL!(net) # changes non identifiable BL to -1.0, except those in/below bad diamonds/triangles. end assignhybridnames!(net) if(net.numNodes == 1) print(s,string(net.node[net.root].number,";")) # error if 'string' is an argument name. else if(!isTree(net) && !net.cleaned) @debug "net not cleaned inside writeTopologyLevel1, need to run updateContainRoot" for n in net.hybrid flag,edges = updateContainRoot!(net,n) flag || error("hybrid node $(n.hybrid) has conflicting containRoot") end end updateRoot!(net,outgroup) #@debug begin printEverything(net); "printed everything" end CHECKNET && canBeRoot(net.node[net.root]) if(multall) mergeLeaves!(net) ## make sure the root is not on a leaf ## This is a band aid: need to check the order of write/root/merge leaves on multiple allele cases if outgroup != "none" try checkRootPlace!(net,outgroup=outgroup) ## keeps all attributes catch err if isa(err, RootMismatch) println("RootMismatch: ", err.msg, """\nThe estimated network has hybrid edges that are incompatible with the desired outgroup. Reverting to an admissible root position. """) else println("error trying to reroot: ", err.msg); end checkRootPlace!(net,verbose=false) # message about problem already printed above end else checkRootPlace!(net,verbose=false) #leave root in good place after snaq end end writeSubTree!(s, net, di,namelabel, roundBL,digits,true) end # outgroup != "none" && undoRoot!(net) # not needed because net is deepcopy of net0 # to delete 2-degree node, for snaq. end writeTopologyLevel1(net::HybridNetwork,di::Bool,str::Bool,namelabel::Bool,outgroup::AbstractString,printID::Bool) = writeTopologyLevel1(net,di,str,namelabel,outgroup,printID, false,3, false) # above: default roundBL=false (at unused digits=3 decimal places) writeTopologyLevel1(net::HybridNetwork,printID::Bool) = writeTopologyLevel1(net,false, true,true,"none",printID, false, 3, false) writeTopologyLevel1(net::HybridNetwork,outgroup::AbstractString) = writeTopologyLevel1(net,false, true,true,outgroup,true, false, 3, false) writeTopologyLevel1(net::HybridNetwork,di::Bool,outgroup::AbstractString) = writeTopologyLevel1(net,di, true,true,outgroup,true, false, 3, false) """ `writeTopologyLevel1(net::HybridNetwork)` Write the extended Newick parenthetical format of a level-1 network object with many optional arguments (see below). Makes a deep copy of net: does *not* modify `net`. - di=true: write in format for Dendroscope (default false) - namelabel=true: If `namelabel` is true, taxa are labelled by their names; otherwise taxa are labelled by their numbers (unique identifiers). - outgroup (string): name of outgroup to root the tree/network. if "none" is given, the root is placed wherever possible. - printID=true, only print branch lengths for identifiable egdes according to the snaq estimation procedure (default false) (true inside of `snaq!`.) - round: rounds branch lengths and heritabilities γ (default: true) - digits: digits after the decimal place for rounding (defult: 3) - string: if true (default), returns a string, otherwise returns an IOBuffer object. - multall: (default false). set to true when there are multiple alleles per population. The topology may be written using a root different than net.root, if net.root is incompatible with one of more hybrid node. Missing hybrid names are written as "#Hi" where "i" is the hybrid node number if possible. """ #" writeTopologyLevel1(net::HybridNetwork; di=false::Bool, string=true::Bool, namelabel=true::Bool, outgroup="none"::AbstractString, printID=false::Bool, round=false::Bool, digits=3::Integer, multall=false::Bool) = writeTopologyLevel1(net, di, string, namelabel, outgroup, printID, round, digits, multall) # function to check if root is well-placed # and look for a better place if not # searches on net.node because net.root is the index in net.node # if we search in net.edge, we then need to search in net.node # this function is only used inside writeTopologyLevel1 function updateRoot!(net::HybridNetwork, outgroup::AbstractString) checkroot = false if(outgroup == "none") @debug "no outgroup defined" checkroot = true else println("outgroup defined $(outgroup)") index = findfirst(n -> outgroup == n.name, net.node) index != nothing || error("outgroup $(outgroup) not in net.names $(net.names)") node = net.node[index] node.leaf || error("outgroup $(outgroup) is not a leaf in net") length(net.node[index].edge) == 1 || error("strange leaf $(outgroup), node number $(net.node[index].number) with $(length(net.node[index].edge)) edges instead of 1") edge = net.node[index].edge[1] if(edge.containRoot) DEBUGC && @debug "creating new node in the middle of the external edge $(edge.number) leading to outgroup $(node.number)" othernode = getOtherNode(edge,node) removeEdge!(othernode,edge) removeNode!(othernode,edge) max_edge = maximum([e.number for e in net.edge]); max_node = maximum([e.number for e in net.node]); newedge = Edge(max_edge+1) #fixit: maybe this edge not identifiable, need to add that check newnode = Node(max_node+1,false,false,[edge,newedge]) if(net.cleaned && !isTree(net) && !isempty(net.partition)) # fixit: this will crash if network estimated with snaq, and then manipulated part = whichPartition(net,edge) push!(net.partition[part].edges,newedge) end setNode!(edge,newnode) setNode!(newedge,newnode) setEdge!(othernode,newedge) setNode!(newedge,othernode) pushEdge!(net,newedge) pushNode!(net,newnode) t = edge.length if t == -1 edge.length = -1 newedge.length = -1 else setLength!(edge,t/2) setLength!(newedge,t/2) end net.root = length(net.node) #last node is root else @warn "external edge $(net.node[index].edge[1].number) leading to outgroup $(outgroup) cannot contain root, root placed wherever" checkroot = true end end if(checkroot && !isTree(net)) checkRootPlace!(net) end end # function to check if a node could be root # by the containRoot attribute of edges around it function canBeRoot(n::Node) !n.hybrid || return false #!n.hasHybEdge || return false #need to allow for some reason, check ipad notes !n.leaf || return false return any([e.containRoot for e in n.edge]) end # function to delete the extra node created in updateRoot # this extra node is needed to be able to compare networks with the distance function # but if left in the network, everything crashes (as everything assumes three edges per node) # fromUpdateRoot=true if called after updateRoot (in which case leaf has to be a leaf), ow it is used in readTopUpdate function undoRoot!(net::HybridNetwork, fromUpdateRoot::Bool) if(length(net.node[net.root].edge) == 2) root = net.node[net.root] leaf = getOtherNode(root.edge[1],root).leaf ? getOtherNode(root.edge[1],root) : getOtherNode(root.edge[2],root) (fromUpdateRoot && leaf.leaf) || error("root should have one neighbor leaf which has to be the outgroup defined") deleteIntLeafWhile!(net,root,leaf); end end undoRoot!(net::HybridNetwork) = undoRoot!(net, true) # .out file from snaq written by optTopRuns """ readSnaqNetwork(output file) Read the estimated network from a `.out` file generated by `snaq!`. The network score is read also, and stored in the network's field `.loglik`. Warning: despite the name "loglik", this score is only proportional to the network's pseudo-deviance: the lower, the better. Do NOT use this score to calculate an AIC or BIC (etc.) value. """ function readSnaqNetwork(file::AbstractString) open(file) do s line = readline(s) line[1] == '(' || error("output file $(file) does not contain a tree in the first line, instead it has $(line); or we had trouble finding ploglik.") # println("Estimated network from file $(file): $(line)") net = readTopology(line) # readTopologyUpdate is inadequate: would replace missing branch lengths, which are unidentifiable, by 1.0 values try vec = split(line,"-Ploglik = ") net.loglik = parse(Float64,vec[2]) catch e @warn "could not find the network score; the error was:" rethrow(e) end return net end end # function to change negative branch lengths to 1.0 for starting topology # and to change big branch lengths to 10.0 # also uses setLength for all edges function cleanBL!(net::HybridNetwork) ##println("missing branch lengths will be set to 1.0") for e in net.edge if(e.length < 0) setLength!(e,1.0) elseif(e.length > 10.0) setLength!(e,10.0) else setLength!(e,e.length) end end end # function to read multiple topologies # - calls readInputTrees in readData.jl, which # calls readTopologyUpdate here, for level 1 networks. # - read a file and create one object per line read # (each line starting with "(" will be considered a topology) # the file can have extra lines that are ignored # returns an array of HybridNetwork objects (that can be trees) function readMultiTopologyLevel1(file::AbstractString) readInputTrees(file) end """ readMultiTopology(filename::AbstractString, fast=true) readMultiTopology(newicktrees_list::Vector{<:AbstractString}) Read a list of networks in parenthetical format, either from a file (one network per line) if the input is a string giving the path to the file, or from a vector of strings with each string corresponding to a newick-formatted topology. By default (`fast=true`), `Functors.fmap` is used for repeatedly reading the newick trees into of HybridNetwork-type objects. The option `fast=false` corresponds to the behavior up until v0.14.3: with a file name as input, it prints a message (without failing) when a phylogeny cannot be parsed, and allows for empty lines. Each network is read with [`readTopology`](@ref). Return an array of HybridNetwork objects. # Examples ```julia julia> multitreepath = joinpath(dirname(Base.find_package("PhyloNetworks")), "..", "examples", "multitrees.newick"); julia> multitree = readMultiTopology(multitreepath) # vector of 25 HybridNetworks julia> multitree = readMultiTopology(multitreepath, false) # same but slower & safer julia> treestrings = readlines(multitreepath) # vector of 25 strings julia> multitree = readMultiTopology(treestrings) julia> readMultiTopology(treestrings, false) # same, but slower ``` """ function readMultiTopology(topologies::Vector{<:AbstractString}, fast::Bool=true) return (fast ? fmap(readTopology, topologies) : map(readTopology, topologies)) end function readMultiTopology(file::AbstractString, fast::Bool=true) if fast return readMultiTopology(readlines(file), true) end s = open(file) numl = 1 vnet = HybridNetwork[]; for line in eachline(s) line = strip(line) # remove spaces c = isempty(line) ? "" : line[1] if(c == '(') try push!(vnet, readTopology(line,false)) # false for non-verbose catch err print("skipped phylogeny on line $(numl) of file $file: ") if :msg in fieldnames(typeof(err)) println(err.msg); else println(typeof(err)); end end end numl += 1 end close(s) return vnet end @doc raw""" readnexus_treeblock(filename, treereader=readTopology, args...; reticulate=true, stringmodifier=[r"#(\d+)" => s"#H\1"]) Read the *first* "trees" block of a nexus-formatted file, using the translate table if present, and return a vector of `HybridNetwork`s. Information inside `[&...]` are interpreted as comments and are discarded by the default tree reader. Optional arguments `args` are passed to the tree reader. For the nexus format, see [Maddison, Swofford & Maddison (1997)](https://doi.org/10.1093/sysbio/46.4.590). Unless `reticulate` is false, the following is done to read networks with reticulations. Prior to reading each phylogeny, each instance of `#number` is replaced by `#Hnumber` to fit the standard extended Newick format at hybrid nodes. This behavior can be changed with option `stringmodifier`, which should be a vector of pairs accepted by `replace`. Inheritance γ values are assumed to be given within "comment" blocks at *minor* hybrid edges (cut as tips to form the extended Newick) like this for example, as output by bacter ([Vaughan et al. 2017](http://dx.doi.org/10.1534/genetics.116.193425)): #11[&conv=0, relSize=0.08, ... or like this, as output by SpeciesNetwork ([Zhang et al. 2018](https://doi.org/10.1093/molbev/msx307)): #H11[&gamma=0.08] In this example, the corresponding edge to hybrid H11 has γ=0.08. """ function readnexus_treeblock(file::AbstractString, treereader=readTopology::Function, args...; reticulate=true, stringmodifier=[r"#(\d+)\b" => s"#H\1"]) # add H vnet = HybridNetwork[] rx_start = r"^\s*begin\s+trees\s*;"i rx_end = r"^\s*end\s*;"i rx_tree = r"^\s*tree\s+[^(]+(\([^;]*;)"i treeblock = false translate = false id2name = nothing open(file) do s numl = 0 for line in eachline(s) numl += 1 if treeblock occursin(rx_end, line) && break # exit if end of tree block elseif occursin(rx_start, line) # start reading tree block treeblock = true line, translate, id2name = readnexus_translatetable(s) else continue end # now we are inside the treeblock m = match(rx_tree, line) isnothing(m) && continue phy = m.captures[1] if reticulate # fix #Hn and extract γ from #Hn[&conv=n, relSize=γ] phy = replace(phy, stringmodifier...) id2gamma = readnexus_extractgamma(phy) end net = nothing try net = treereader(phy, args...) catch err warnmsg = "skipped phylogeny on line $(numl) of file\n$file\n" * (:msg in fieldnames(typeof(err)) ? err.msg : string(typeof(err))) @warn warnmsg continue # don't push to vnet end reticulate && readnexus_assigngammas!(net, id2gamma) if translate for tip in net.leaf id = parse(Int, tip.name) tip.name = id2name[id] end end push!(vnet, net) end end return vnet end """ readnexus_translatetable(io) Read translate table from IO object `io`, whose first non-empty line should contain "translate". Then each line should have "number name" and the end of the table is indicated by a ;. Output tuple: - line that was last read, and is not part of the translate table, taken from `io` - translate: boolean, whether a table was successfully read - id2name: dictionary mapping number to name. """ function readnexus_translatetable(io) rx_translate = r"^\s*translate"i rx_emptyline = r"^\s*$" line = readline(io) translate = false id2name = Dict{Int,String}() while true if occursin(rx_translate, line) translate = true break elseif occursin(rx_emptyline, line) line = readline(io) else translate = false break end end if translate # then read the table rx_end = r"^\s*;" rx_idname = r"\s*(\d+)\s+(\w+)\s*([,;]?)" while true line = readline(io) occursin(rx_emptyline, line) && continue if occursin(rx_end, line) line = readline(io) break end m = match(rx_idname, line) if isnothing(m) @warn "problem reading the translate table at line $line.\nnumbers won't be translated to names" translate = false break end push!(id2name, parse(Int,m.captures[1]) => String(m.captures[2])) if m.captures[3] == ";" line = readline(io) break end end end return line, translate, id2name end """ readnexus_extractgamma(nexus_string) Extract γ from comments and return a dictionary hybrid number ID => γ, from one single phylogeny given as a string. The output from BEAST2 uses this format for reticulations at *minor* edges, as output by bacter ([Vaughan et al. 2017](http://dx.doi.org/10.1534/genetics.116.193425)): #11[&conv=0, relSize=0.08, ... or as output by SpeciesNetwork ([Zhang et al. 2018](https://doi.org/10.1093/molbev/msx307)): #H11[&gamma=0.08] The function below assumes that the "H" was already added back if not present already (from bacter), like this: #H11[&conv=0, relSize=0.19, ... The bacter format is tried first. If this format doesn't give any match, then the SpeciesNetwork format is tried next. See [`readnexus_assigngammas!`](@ref). """ function readnexus_extractgamma(nexstring) rx_gamma_v1 = r"#H(\d+)\[&conv=\d+,\s*relSize=(\d+\.\d+)" rx_gamma_v2 = r"#H(\d+)\[&gamma=(\d+\.\d+)" id2gamma = Dict{Int,Float64}() # first: try format v1 for m in eachmatch(rx_gamma_v1, nexstring) push!(id2gamma, parse(Int, m.captures[1]) => parse(Float64,m.captures[2])) end if isempty(id2gamma) # then try format v2 for m in eachmatch(rx_gamma_v2, nexstring) push!(id2gamma, parse(Int, m.captures[1]) => parse(Float64,m.captures[2])) end end return id2gamma end """ readnexus_assigngammas!(net, d::Dict) Assign d[i] as the `.gamma` value of the minor parent edge of hybrid "Hi", if this hybrid node name is found, and if its minor parent doesn't already have a non-missing γ. See [`readnexus_extractgamma`](@ref) """ function readnexus_assigngammas!(net::HybridNetwork, id2gamma::Dict) for (i,gam) in id2gamma nam = "H$i" j = findfirst(n -> n.name == nam, net.hybrid) if isnothing(j) @warn "didn't find any hybrid node named $nam." continue end hn = net.hybrid[j] he = getparentedgeminor(hn) if he.gamma == -1.0 setGamma!(he, gam) else @warn "hybrid edge number $(he.number) has γ=$(he.gamma). won't erase with $gam." end end return net end """ writeMultiTopology(nets, file_name; append=false) writeMultiTopology(nets, IO) Write an array of networks in parenthetical extended Newick format, one network per line. Use the option append=true to append to the file. Otherwise, the default is to create a new file or overwrite it, if it already existed. Each network is written with `writeTopology`. # Examples ```julia julia> net = [readTopology("(D,((A,(B)#H7:::0.864):2.069,(F,E):3.423):0.265,(C,#H7:::0.1361111):10);"), readTopology("(A,(B,C));"),readTopology("(E,F);"),readTopology("(G,H,F);")]; julia> writeMultiTopology(net, "fournets.net") # to (over)write to file "fournets.net" julia> writeMultiTopology(net, "fournets.net", append=true) # to append to this file julia> writeMultiTopology(net, stdout) # to write to the screen (standard out) (D,((A,(B)#H7:::0.864):2.069,(F,E):3.423):0.265,(C,#H7:::0.1361111):10.0); (A,(B,C)); (E,F); (G,H,F); ``` """ function writeMultiTopology(n::Vector{HybridNetwork},file::AbstractString; append::Bool=false) mode = (append ? "a" : "w") open(file, mode) do s writeMultiTopology(n,s) end # closes file safely end function writeMultiTopology(net::Vector{HybridNetwork},s::IO) for i in 1:length(net) try # writeTopologyLevel1(net[i],s,false,true,"none",false,false,3) writeTopology(net[i],s) # no rounding, not for dendroscope write(s,"\n") catch err if isa(err, RootMismatch) # continue writing other networks in list @error "\nError with topology $i:\n" * err.msg else rethrow(err); end end end end """ writeTopology(net) writeTopology(net, filename) writeTopology(net, IO) Write the parenthetical extended Newick format of a network, as a string, to a file or to an IO buffer / stream. Optional arguments (default values): - di (false): write in format for Dendroscope - round (false): rounds branch lengths and heritabilities γ - digits (3): digits after the decimal place for rounding - append (false): if true, appends to the file - internallabel (true): if true, writes internal node labels If the current root placement is not admissible, other placements are tried. The network is updated with this new root placement, if successful. Uses lower-level function [`writeSubTree!`](@ref). """ function writeTopology(n::HybridNetwork, file::AbstractString; append::Bool=false, round=false::Bool, digits=3::Integer, di=false::Bool, # keyword arguments internallabel=true::Bool) mode = (append ? "a" : "w") s = open(file, mode) writeTopology(n,s,round,digits,di,internallabel) write(s,"\n") close(s) end function writeTopology(n::HybridNetwork; round=false::Bool, digits=3::Integer, di=false::Bool, # keyword arguments internallabel=true::Bool) s = IOBuffer() writeTopology(n,s,round,digits,di,internallabel) return String(take!(s)) end function writeTopology(net::HybridNetwork, s::IO, round=false::Bool, digits=3::Integer, di=false::Bool, # optional arguments internallabel=true::Bool) # check/find admissible root: otherwise could be trapped in infinite loop rootsaved = net.root changeroot = false msg = "" try directEdges!(net) catch err if isa(err, RootMismatch) println(err.msg * "\nCannot write topology with current root.") changeroot = true else rethrow(err); end end while changeroot for e in net.edge # parents of hybrid edges should be sufficient, but gives weird look #if e.hybrid i = getIndex(getparent(e), net) net.root = i try directEdges!(net) print("Setting root at node $(net.node[i].number) (net.root = $i)\n\n") print(msg) changeroot = false break # stop loop over edges catch err if !isa(err, RootMismatch) rethrow(err); end end #end end if changeroot # none of hybrid edges worked net.root = rootsaved throw(RootMismatch("Could not find admissible root. Cannot write topology.")) changeroot=false # safety exit of while (but useless) end end if net.node[net.root].leaf @warn """Root is placed at a leaf node, so the parenthetical format will look strange. Use rootatnode! or rootonedge! to change the root position """ end # finally, write parenthetical format writeSubTree!(s,net,di,true,round,digits,internallabel) # namelabel = true: to print leaf & node names (labels), not numbers end """ hybridlambdaformat(net::HybridNetwork; prefix="I") Output `net` as a string in the format that the [Hybrid-Lambda](https://github.com/hybridLambda/hybrid-Lambda) simulator expects, namely: - all internal nodes are named, including the root, with names that are unique and start with a letter. - hybrid nodes are written as `H6#γ1:length1` and `H6#γ1:length2` instead of `#H6:length1::γ1` and `#H6:length2::γ2` (note the samme γ value expected by Hybrid-Lambda) This is a modified version of the [extended Newick](https://doi.org/10.1186/1471-2105-9-532) format. Optional keyword argument `prefix`: must start with a letter, other than "H". Internal nodes are given names like "I1", "I2", etc. Existing internal non-hybrid node names are **replaced**, which is crucial if some of them don't start with a letter (e.g. in case node names are bootstrap values). See [`nameinternalnodes!`](@ref) to add node names. # examples ```jldoctest julia> net = readTopology("((a:1,(b:1)#H1:1::0.8):5,(#H1:0::0.2,c:1):1);"); julia> hybridlambdaformat(net) # net is unchanged here "((a:1.0,(b:1.0)H1#0.8:1.0)I1:5.0,(H1#0.8:0.0,c:1.0)I2:1.0)I3;" julia> # using PhyloPlots; plot(net, shownodenumber=true) # shows that node -2 is the root julia> rotate!(net, -2) julia> writeTopology(net) # now the minor edge with γ=0.2 appears first "((#H1:0.0::0.2,c:1.0):1.0,(a:1.0,(b:1.0)#H1:1.0::0.8):5.0);" julia> hybridlambdaformat(net) "((H1#0.2:0.0,c:1.0)I2:1.0,(a:1.0,(b:1.0)H1#0.2:1.0)I1:5.0)I3;" julia> net = readTopology("((((B)#H1:::.6)#H2,((D,C,#H2:::0.8),(#H1,A))));"); # 2 reticulations, no branch lengths julia> writeTopology(net, round=true) "(#H2:::0.2,((D,C,((B)#H1:::0.6)#H2:::0.8),(#H1:::0.4,A)));" julia> hybridlambdaformat(net; prefix="int") "(H2#0.2,((D,C,((B)H1#0.6)H2#0.2)int1,(H1#0.6,A)int2)int3)int4;" ``` """ function hybridlambdaformat(net::HybridNetwork; prefix="I") startswith(prefix, r"[a-zA-GI-Z]") || error("unsafe prefix $prefix: please start with a letter, but not H") leafnames = tipLabels(net) length(Set(leafnames)) == length(leafnames) || error("taxon names must be unique: $(sort(leafnames))") net = deepcopy(net) # binding to new object for e in net.edge if e.hybrid && e.isMajor && e.gamma == -1.0 @error("edge number $(e.number) is missing gamma: will use 0.5") setGamma!(e, 0.5) end end for no in net.node (no.leaf || no.hybrid) && continue # skip leaves & hybrid nodes no.name = "" # erase any exisiting name: especially bootstrap values end nameinternalnodes!(net, prefix) str1 = writeTopology(net, round=true, digits=15) # internallabels=true by default rx_noBL = r"#(H[\w\d]+)::\d*\.?\d*(?:e[+-]?\d+)?:(\d*\.?\d*(?:e[+-]?\d+)?)" subst_noBL = s"\1#\2" rx_withBL = r"#(H[\w\d]+):(\d*\.?\d*(?:e[+-]?\d+)?):\d*\.?\d*(?:e[+-]?\d+)?:(\d*\.?\d*(?:e[+-]?\d+)?)" subst_withBL = s"\1#\3:\2" str2 = replace(replace(str1, rx_noBL => subst_noBL), rx_withBL => subst_withBL) ## next: replace the γ2 of the second occurrence by γ1 from the first occurrence: ## this is what Hybrid-Lambda wants... nh = length(net.hybrid) m = eachmatch(r"[)(,](H[^#)(,]*#)", str2) hboth = collect(h.captures[1] for h in m) hone = unique(hboth) length(hboth) == 2length(hone) || error("did not find Hname# twice for some one (or more) of the hybrid names.") str3 = str2 for hname in hone rx = Regex( hname * raw"(?<gamma1>\d*\.?\d*)(?<middle>.*)" * hname * raw"(?<gamma2>\d*\.?\d*)") subst = SubstitutionString(hname * raw"\g<gamma1>\g<middle>" * hname * raw"\g<gamma1>") str3 = replace(str3, rx => subst) end return str3 end """ nameinternalnodes!(net::HybridNetwork, prefix) Add names to nodes in `net` that don't already have a name. Leaves already have names; but if not, they will be given names as well. New node names will be of the form "prefixI" where I is an integer. # examples ```jldoctest julia> net = readTopology("((a:1,(b:1)#H1:1::0.8):5,(#H1:0::0.2,c:1):1);"); julia> PhyloNetworks.nameinternalnodes!(net, "I") # by default, shown without internal node names HybridNetwork, Rooted Network 7 edges 7 nodes: 3 tips, 1 hybrid nodes, 3 internal tree nodes. tip labels: a, b, c ((a:1.0,(b:1.0)#H1:1.0::0.8)I1:5.0,(#H1:0.0::0.2,c:1.0)I2:1.0)I3; julia> writeTopology(net; internallabel=false) # by default, writeTopology shows internal names if they exist "((a:1.0,(b:1.0)#H1:1.0::0.8):5.0,(#H1:0.0::0.2,c:1.0):1.0);" julia> net = readTopology("((int5:1,(b:1)#H1:1::0.8):5,(#H1:0::0.2,c:1):1);"); # one taxon name starts with "int" julia> PhyloNetworks.nameinternalnodes!(net, "int"); julia> writeTopology(net) "((int5:1.0,(b:1.0)#H1:1.0::0.8)int6:5.0,(#H1:0.0::0.2,c:1.0)int7:1.0)int8;" ``` """ function nameinternalnodes!(net::HybridNetwork, prefix) # get maximum index I of nodes whose names are already like: prefixI rx = Regex("^$(prefix)(\\d+)\$") nexti = 1 for node in net.node node.name != "" || continue # skip nodes with empty names m = match(rx, node.name) m !== nothing || continue nexti = max(nexti, parse(Int, m.captures[1])+1) end # assign names like: prefixI for I = nexti, nexti+1, etc. for node in net.node node.name == "" || continue # skip nodes with non-empty names node.name = prefix * string(nexti) nexti += 1 end return net end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
109552
# functions for numerical/heuristic optimization # originally in functions.jl # Claudia March 2015 const move2int = Dict{Symbol,Int}(:add=>1,:MVorigin=>2,:MVtarget=>3,:CHdir=>4,:delete=>5, :nni=>6) const int2move = Dict{Int,Symbol}(move2int[k]=>k for k in keys(move2int)) """ default values for tolerance parameters, used in the optimization of branch lengths (fAbs, fRel, xAbs, xRel) and in the acceptance of topologies (likAbs, numFails). if changes are made here, **make the same** in the docstring for snaq! below version | fAbs | fRel | xAbs | xRel | numFails | likAbs | multiplier --------|------|------|------|------|----------|--------|----------- v0.5.1 | 1e-6 | 1e-6 | 1e-3 | 1e-2 | 75 | 1e-6 | v0.3.0 | 1e-6 | 1e-5 | 1e-4 | 1e-3 | 100 | 0.01 | v0.0.1 | 1e-6 | 1e-5 | 1e-4 | 1e-3 | 100 | | 10000 older | 1e-10| 1e-12| 1e-10| 1e-10| v0.5.1: based on Nan Ji's work. same xAbs and xRel as in phylonet (as of 2015). earlier: multiplier was used; later: likAbs = multiplier*fAbs) "older": values from GLM.jl, Prof Bates default values used on a single topology, to optimize branch lengths and gammas, at the very end of snaq!, and by topologyMaxQPseudolik! since v0.5.1. version | fAbsBL | fRelBL | xAbsBL | xRelBL --------|--------|--------|--------|------- v0.0.1 | 1e-10 | 1e-12 | 1e-10 | 1e-10 """ const fAbs = 1e-6 const fRel = 1e-6 const xAbs = 1e-3 const xRel = 1e-2 const numFails = 75 # number of failed proposals allowed before stopping the procedure (like phylonet) const numMoves = Int[] #empty to be calculated inside based on coupon's collector const likAbs = 1e-6 # loglik absolute tolerance to accept new topology const fAbsBL = 1e-10 const fRelBL = 1e-12 const xAbsBL = 1e-10 const xRelBL = 1e-10 # ---------------------- branch length optimization --------------------------------- # function to get the branch lengths/gammas to optimize for a given network # warning: order of parameters (h,t,gammaz) # updates net.numht also with the number of hybrid nodes and number of identifiable edges (n2,n,hzn) function parameters(net::Network) t = Float64[] h = Float64[] n = Int[] n2 = Int[] hz = Float64[] hzn = Int[] indxt = Int[] indxh = Int[] indxhz = Int[] for e in net.edge if(e.istIdentifiable) push!(t,e.length) push!(n,e.number) push!(indxt, getIndex(e,net)) end if(e.hybrid && !e.isMajor) node = e.node[e.isChild1 ? 1 : 2] node.hybrid || error("strange thing, hybrid edge $(e.number) pointing at tree node $(node.number)") if(!node.isBadDiamondI) push!(h,e.gamma) push!(n2,e.number) push!(indxh, getIndex(e,net)) else if(node.isBadDiamondI) edges = hybridEdges(node) push!(hz,getOtherNode(edges[1],node).gammaz) push!(hz,getOtherNode(edges[2],node).gammaz) push!(hzn,parse(Int,string(string(node.number),"1"))) push!(hzn,parse(Int,string(string(node.number),"2"))) push!(indxhz,getIndex(getOtherNode(edges[1],node),net)) push!(indxhz,getIndex(getOtherNode(edges[2],node),net)) end end end end # size(t,1) > 0 || @warn "net does not have identifiable branch lengths" return vcat(h,t,hz),vcat(n2,n,hzn),vcat(indxh,indxt,indxhz) end function parameters!(net::Network) #@warn "deleting net.ht,net.numht and updating with current edge lengths (numbers)" net.ht,net.numht,net.index = parameters(net) return net.ht end # function to update qnet.indexht,qnet.index based on net.numht # warning: assumes net.numht is updated already with parameters!(net) function parameters!(qnet::QuartetNetwork, net::HybridNetwork) size(net.numht,1) > 0 || error("net.numht not correctly updated, need to run parameters first") @debug (size(qnet.indexht,1) == 0 ? "" : "deleting qnet.indexht to replace with info in net") nh = net.numht[1 : net.numHybrids - net.numBad] k = sum([e.istIdentifiable ? 1 : 0 for e in net.edge]) nt = net.numht[net.numHybrids - net.numBad + 1 : net.numHybrids - net.numBad + k] nhz = net.numht[net.numHybrids - net.numBad + k + 1 : length(net.numht)] qnh = Int[] qnt = Int[] qnhz = Int[] qindxh = Int[] qindxt = Int[] qindxhz = Int[] if(qnet.numHybrids == 1 && qnet.hybrid[1].isBadDiamondI) ind1 = parse(Int,string(string(qnet.hybrid[1].number),"1")) ind2 = parse(Int,string(string(qnet.hybrid[1].number),"2")) i = findfirst(isequal(ind1), nhz) i != nothing || error("ind1 not found in nhz") edges = hybridEdges(qnet.hybrid[1]) push!(qnhz,i+net.numHybrids-net.numBad+k) push!(qnhz,i+1+net.numHybrids-net.numBad+k) push!(qindxhz,getIndex(getOtherNode(edges[1],qnet.hybrid[1]),qnet)) push!(qindxhz,getIndex(getOtherNode(edges[2],qnet.hybrid[1]),qnet)) else found = false for n in qnet.hybrid if(n.isBadDiamondI) ind1 = parse(Int,string(string(n.number),"1")) ind2 = parse(Int,string(string(n.number),"2")) i = findfirst(isequal(ind1), nhz) i != nothing || error("ind1 not found in nhz") edges = hybridEdges(n) push!(qnhz,i+net.numHybrids-net.numBad+k) push!(qnhz,i+1+net.numHybrids-net.numBad+k) push!(qindxhz,getIndex(getOtherNode(edges[1],n),qnet)) push!(qindxhz,getIndex(getOtherNode(edges[2],n),qnet)) found = true break end end if(!found) all((n -> !n.isBadDiamondI),qnet.hybrid) || error("cannot have bad diamond I hybrid nodes in this qnet, case dealt separately before") for e in qnet.edge if(e.istIdentifiable) enum_in_nt = findfirst(isequal(e.number), nt) if isnothing(enum_in_nt) error("identifiable edge $(e.number) in qnet not found in net") end push!(qnt, enum_in_nt + net.numHybrids - net.numBad) push!(qindxt, getIndex(e,qnet)) end if(!e.istIdentifiable && all((n->!n.leaf),e.node) && !e.hybrid && e.fromBadDiamondI) # tree edge not identifiable but internal with length!=0 (not bad diamII nor bad triangle) enum_in_nhz = findfirst(isequal(e.number), nhz) if isnothing(enum_in_nhz) error("internal edge $(e.number) corresponding to gammaz in qnet not found in net.ht") end push!(qnhz, enum_in_nhz + net.numHybrids - net.numBad + k) push!(qindxhz, getIndex(e,qnet)) end if(e.hybrid && !e.isMajor) node = e.node[e.isChild1 ? 1 : 2] node.hybrid || error("strange hybrid edge $(e.number) poiting to tree node $(node.number)") enum_in_nh = findfirst(isequal(e.number), nh) found = (enum_in_nh != nothing) found ? push!(qnh, enum_in_nh) : nothing found ? push!(qindxh, getIndex(e,qnet)) : nothing end end # for qnet.edge end # not found end qnet.indexht = vcat(qnh,qnt,qnhz) qnet.index = vcat(qindxh,qindxt,qindxhz) length(qnet.indexht) == length(qnet.index) || error("strange in setting qnet.indexht and qnet.index, they do not have same length") end # function to compare a vector of parameters with the current vector in net.ht # to know which parameters were changed function changed(net::HybridNetwork, x::Vector{Float64}) if(length(net.ht) == length(x)) #@debug "inside changed with net.ht $(net.ht) and x $(x)" return [!approxEq(net.ht[i],x[i]) for i in 1:length(x)] else error("net.ht (length $(length(net.ht))) and vector x (length $(length(x))) need to have same length") end end # function to update a QuartetNetwork for a given # vector of parameters based on a boolean vector "changed" # which shows which parameters have changed function update!(qnet::QuartetNetwork,x::Vector{Float64}, net::HybridNetwork) ch = changed(net,x) length(x) == length(ch) || error("x (length $(length(x))) and changed $(length(changed)) should have the same length") length(ch) == length(qnet.hasEdge) || error("changed (length $(length(changed))) and qnet.hasEdge (length $(length(qnet.hasEdge))) should have same length") qnet.changed = false k = sum([e.istIdentifiable ? 1 : 0 for e in net.edge]) for i in 1:length(ch) qnet.changed |= (ch[i] & qnet.hasEdge[i]) end #DEBUGC && @debug "inside update!, qnet.changed is $(qnet.changed), ch $(ch) and qnet.hasEdge $(qnet.hasEdge), $(qnet.quartetTaxon), numHyb $(qnet.numHybrids)" if(qnet.changed) if(any([n.isBadDiamondI for n in qnet.hybrid])) # qnet.indexht is only two values: gammaz1,gammaz2 #FIXIT: this could crash if hybrid for bad diamond should disappear after cleaning qnet @debug "it is inside update! and identifies that ht changed and it is inside the bad diamond I case" length(qnet.indexht) == 2 || error("strange qnet from bad diamond I with hybrid node, it should have only 2 elements: gammaz1,gammaz2, not $(length(qnet.indexht))") for i in 1:2 0 <= x[qnet.indexht[i]] <= 1 || error("new gammaz value should be between 0,1: $(x[qnet.indexht[i]]).") @debug (x[qnet.indexht[1]] + x[qnet.indexht[2]] <= 1 ? "" : "warning: new gammaz should add to less than 1: $(x[qnet.indexht[1]] + x[qnet.indexht[2]])") qnet.node[qnet.index[i]].gammaz = x[qnet.indexht[i]] end else for i in 1:length(qnet.indexht) if(qnet.indexht[i] <= net.numHybrids - net.numBad) 0 <= x[qnet.indexht[i]] <= 1 || error("new gamma value should be between 0,1: $(x[qnet.indexht[i]]).") qnet.edge[qnet.index[i]].hybrid || error("something odd here, optimizing gamma for tree edge $(qnet.edge[qnet.index[i]].number)") setGamma!(qnet.edge[qnet.index[i]],x[qnet.indexht[i]], true) elseif(qnet.indexht[i] <= net.numHybrids - net.numBad + k) setLength!(qnet.edge[qnet.index[i]],x[qnet.indexht[i]]) else DEBUGC && @debug "updating qnet parameters, found gammaz case when hybridization has been removed" 0 <= x[qnet.indexht[i]] <= 1 || error("new gammaz value should be between 0,1: $(x[qnet.indexht[i]]).") #x[qnet.indexht[i]] + x[qnet.indexht[i]+1] <= 1 || @warn "new gammaz value should add to less than 1: $(x[qnet.indexht[i]]) $(x[qnet.indexht[i]+1])." if(approxEq(x[qnet.indexht[i]],1.0)) setLength!(qnet.edge[qnet.index[i]],10.0) else setLength!(qnet.edge[qnet.index[i]],-log(1-x[qnet.indexht[i]])) end end end end end end # function to update the branch lengths/gammas for a network # warning: order of parameters (h,t) function update!(net::HybridNetwork, x::Vector{Float64}) if(length(x) == length(net.ht)) net.ht = deepcopy(x) # to avoid linking them else error("net.ht (length $(length(net.ht))) and x (length $(length(x))) must have the same length") end end # function to update the branch lengths and gammas in a network after # the optimization # warning: optBL need to be run before, note that # xmin will not be in net.ht (net.ht is one step before) function updateParameters!(net::HybridNetwork, xmin::Vector{Float64}) length(xmin) == length(net.ht) || error("xmin vector should have same length as net.ht $(length(net.ht)), not $(length(xmin))") net.ht = xmin k = sum([e.istIdentifiable ? 1 : 0 for e in net.edge]) for i in 1:length(net.ht) if(i <= net.numHybrids - net.numBad) 0 <= net.ht[i] <= 1 || error("new gamma value should be between 0,1: $(net.ht[i]).") net.edge[net.index[i]].hybrid || error("something odd here, optimizing gamma for tree edge $(net.edge[net.index[i]].number)") setGamma!(net.edge[net.index[i]],net.ht[i], true) elseif(i <= net.numHybrids - net.numBad + k) setLength!(net.edge[net.index[i]],net.ht[i]) else 0 <= net.ht[i] <= 1 || error("new gammaz value should be between 0,1: $(net.ht[i]).") net.node[net.index[i]].gammaz = net.ht[i] end end end # function to update the attribute net.loglik function updateLik!(net::HybridNetwork, l::Float64) net.loglik = l end # function for the upper bound of ht function upper(net::HybridNetwork) k = sum([e.istIdentifiable ? 1 : 0 for e in net.edge]) return vcat(ones(net.numHybrids-net.numBad), repeat([10],inner=[k]), ones(length(net.ht)-k-net.numHybrids+net.numBad)) end # function to calculate the inequality gammaz1+gammaz2 <= 1 function calculateIneqGammaz(x::Vector{Float64}, net::HybridNetwork, ind::Integer, verbose::Bool) k = sum([e.istIdentifiable ? 1 : 0 for e in net.edge]) hz = x[net.numHybrids - net.numBad + k + 1 : length(x)] if verbose # goes to stdout println("enters calculateIneqGammaz with hz $(hz), and hz[ind*2] + hz[ind*2-1] - 1 = $(hz[ind*2] + hz[ind*2-1] - 1)") else # goes to logger (if debug messages are turned on by user) @debug "enters calculateIneqGammaz with hz $(hz), and hz[ind*2] + hz[ind*2-1] - 1 = $(hz[ind*2] + hz[ind*2-1] - 1)" end hz[ind*2] + hz[ind*2-1] - 1 end # numerical optimization of branch lengths given a network (or tree) # and data (set of quartets with obsCF) # using BOBYQA from NLopt package # warning: this function assumes that the network has all the good attributes set. It will not be efficient to re-read the network inside # to guarantee all the correct attributes, because this is done over and over inside snaq # also, net is modified inside to set its attribute net.loglik equal to the min """ `optBL` road map Function that optimizes the numerical parameters (branch lengths and inheritance probabilities) for a given network. This function is called multiple times inside `optTopLevel!`. - Input: network `net`, data `d` - Numerical tolerances: `ftolAbs, ftolRel, xtolAbs, xtolRel` - Function based on `MixedModels` `fit` function - The function assumes `net` has all the right attributes, and cannot check this inside because it would be inefficient Procedure: - `ht = parameters!(net)` extracts the vector of parameters to estimate `(h,t,gammaz)`, and sets as `net.ht`; identifies a bad diamond I, sets `net.numht` (vector of hybrid node numbers for h, edge numbers for t, hybrid node numbers for gammaz), and `net.index` to keep track of the vector of parameters to estimate - `extractQuartet!(net,d)` does the following for all quartets in `d.quartet`: - Extract quartet by deleting all leaves not in q -> create `QuartetNetwork` object saved in `q.qnet` - This network is ugly and does not have edges collapsed. This is done to keep a one-to-one correspondence between the edges in `q.qnet` and the edges in `net` (if we remove nodes with only two edges, we will lose this correspondence) - Calculate expected CF with `calculateExpCFAll` for a copy of `q.qnet`. We do this copy because we want to keep `q.qnet` as it is (without collapsed edges into one). The function will then save the `expCF` in `q.qnet.expCF` - `calculateExpCFAll!(qnet)` will - identify the type of quartet as type 1 (equivalent to a tree) or type 2 (minor CF different). Here the code will first clean up any hybrid node by removing nodes with only two edges before identifying the `qnet` (because identification depends on neighbor nodes to hybrid node); later, set `qnet.which` (1 or 2), `node.prev` (neighbor node to hybrid node), updates `node.k` (number of nodes in hybridization cycle, this can change after deleting the nodes with only two edges), `node.typeHyb` (1,2,3,4,5 depending on the number of nodes in the hybridization cycle and the origin/target of the minor hybrid edge; this attribute is never used). - eliminate hybridization: this will remove type 1 hybridizations first. If `qnet.which=1`, then the `qnet` is similar to a tree quartet, so it will calculate the internal length of the tree quartet: `qnet.t1`. - update split for `qnet.which=1`, to determine which taxa are together. For example, for the quartet 12|34, the split is [1,1,2,2] or [2,2,1,1], that is, taxon 1 and 2 are on the same side of the split. This will update `qnet.split` - update formula for `qnet.which=1` to know the order of minorCF and majorCF in the vector `qnet.expCF`. That is, if the quartet is 1342 (order in `qnet.quartet.taxon`), then the expected CF should match the observed CF in 13|42, 14|32, 12|34 and the `qnet` is 12|34 (given by `qnet.split`), `qnet.formula` will be [2,2,1] minor, minor, major - `calculateExpCF!(qnet)` for `qnet.which=1`, it will do `1-2/3exp(-qnet.t1)` if `qnet.formula[i]==1`, and `1/3exp(qnet.t1)` if `qnet.formula[i]==2`. For `qnet.which=2`, we need to make sure that there is only one hybrid node, and compute the major, minor1,minor2 expected CF in the order 12|34, 13|24, 14|23 of the taxa in `qnet.quartet.taxon` Then we create a `NLopt` object with algorithm BOBYQA and k parameters (length of ht). We define upper and lower bounds and define the objective function that should only depend on `x=(h,t,gz)` and g (gradient, which we do not have, but still need to put as argument). The objective function `obj(x,g)` calls - `calculateExpCFAll!(d,x,net)` needs to be run after `extractQuartet(net,d)` that will update `q.qnet` for all quartet. Assumes that `qnet.indexht` is updated already: we only need to do this at the beginning of `optBL!` because the topology is fixed at this point) - First it will update the edge lengths according to x - If the `q.qnet.changed=true` (that is, any of `qnet` branches changed value), we need to call `calculateExpCFAll!(qnet)` on a copy of `q.qnet` (again because we want to leave `q.qnet` with the edge correspondence to `net`) - `update!(net,x)` simply saves the new x in `net.ht` Finally, we call `NLopt.optimize`, and we update the `net.loglik` and `net.ht` at the end. After `optBL`, we want to call `afterOptBLAll` (or `afterOptBLAllMultipleAlleles`) to check if there are `h==0,1`; `t==0`; `hz==0,1`. """ function optBL!(net::HybridNetwork, d::DataCF, verbose::Bool, ftolRel::Float64, ftolAbs::Float64, xtolRel::Float64, xtolAbs::Float64) (ftolRel > 0 && ftolAbs > 0 && xtolAbs > 0 && xtolRel > 0) || error("tolerances have to be positive, ftol (rel,abs), xtol (rel,abs): $([ftolRel, ftolAbs, xtolRel, xtolAbs])") if verbose println("OPTBL: begin branch lengths and gammas optimization, ftolAbs $(ftolAbs), ftolRel $(ftolRel), xtolAbs $(xtolAbs), xtolRel $(xtolRel)"); else @debug "OPTBL: begin branch lengths and gammas optimization, ftolAbs $(ftolAbs), ftolRel $(ftolRel), xtolAbs $(xtolAbs), xtolRel $(xtolRel)"; end ht = parameters!(net); # branches/gammas to optimize: net.ht, net.numht extractQuartet!(net,d) # quartets are all updated: hasEdge, expCF, indexht k = length(net.ht) net.numBad >= 0 || error("network has negative number of bad hybrids") #opt = NLopt.Opt(net.numBad == 0 ? :LN_BOBYQA : :LN_COBYLA,k) # :LD_MMA if use gradient, :LN_COBYLA for nonlinear/linear constrained optimization derivative-free, :LN_BOBYQA for bound constrained derivative-free opt = NLopt.Opt(:LN_BOBYQA,k) # :LD_MMA if use gradient, :LN_COBYLA for nonlinear/linear constrained optimization derivative-free, :LN_BOBYQA for bound constrained derivative-free # criterion based on prof Bates code NLopt.ftol_rel!(opt,ftolRel) # relative criterion -12 NLopt.ftol_abs!(opt,ftolAbs) # absolute critetion -8, later changed to -10 NLopt.xtol_rel!(opt,xtolRel) # criterion on parameter value changes -10 NLopt.xtol_abs!(opt,xtolAbs) # criterion on parameter value changes -10 NLopt.maxeval!(opt,1000) # max number of iterations NLopt.lower_bounds!(opt, zeros(k)) NLopt.upper_bounds!(opt,upper(net)) count = 0 function obj(x::Vector{Float64},g::Vector{Float64}) # added g::Vector{Float64} for gradient, ow error if(verbose) #|| net.numBad > 0) #we want to see what happens with bad diamond I println("inside obj with x $(x)") end count += 1 calculateExpCFAll!(d,x,net) # update qnet branches and calculate expCF update!(net,x) # update net.ht val = logPseudoLik(d) if verbose #|| net.numBad > 0)#we want to see what happens with bad diamond I println("f_$count: $(round(val, digits=5)), x: $(x)") end return val end NLopt.min_objective!(opt,obj) ## if(net.numBad == 1) ## function inequalityGammaz(x::Vector{Float64},g::Vector{Float64}) ## val = calculateIneqGammaz(x,net,1,verbose) ## return val ## end ## NLopt.inequality_constraint!(opt,inequalityGammaz) ## elseif(net.numBad > 1) ## function inequalityGammaz(result::Vector{Float64},x::Vector{Float64},g::Matrix{Float64}) ## i = 1 ## while(i < net.numBad) ## result[i] = calculateIneqGammaz(x,net,i,verbose) ## i += 2 ## end ## end ## NLopt.inequality_constraint!(opt,inequalityGammaz) ## end if verbose println("OPTBL: starting point $(ht)") # to stdout else @debug "OPTBL: starting point $(ht)"; end # to logger if debug turned on by user fmin, xmin, ret = NLopt.optimize(opt,ht) if verbose println("got $(round(fmin, digits=5)) at $(round.(xmin, digits=5)) after $(count) iterations (returned $(ret))") else @debug "got $(round(fmin, digits=5)) at $(round.(xmin, digits=5)) after $(count) iterations (returned $(ret))"; end updateParameters!(net,xmin) net.loglik = fmin #return fmin,xmin end optBL!(net::HybridNetwork, d::DataCF) = optBL!(net, d, false, fRel, fAbs, xRel, xAbs) optBL!(net::HybridNetwork, d::DataCF, verbose::Bool) = optBL!(net, d,verbose, fRel, fAbs, xRel, xAbs) optBL!(net::HybridNetwork, d::DataCF, ftolRel::Float64, ftolAbs::Float64, xtolRel::Float64, xtolAbs::Float64) = optBL!(net, d, false, ftolRel, ftolAbs, xtolRel, xtolAbs) # rename optBL for a more user-friendly name """ `topologyMaxQPseudolik!(net::HybridNetwork, d::DataCF)` Estimate the branch lengths and inheritance probabilities (γ's) for a given network topology. The network is *not* modified, only the object `d` is, with updated expected concordance factors. Ouput: new network, with optimized parameters (branch lengths and gammas). The maximized quartet pseudo-deviance is the negative log pseudo-likelihood, up to an additive constant, such that a perfect fit corresponds to a deviance of 0.0. This is also an attribute of the network, which can be accessed with `net.loglik`. Optional arguments (default value): - verbose (false): if true, information on the numerical optimization is printed to screen - ftolRel (1e-5), ftolAbs (1e-6), xtolRel (1e-3), xtolAbs (1e-4): absolute and relative tolerance values for the pseudo-deviance function and the parameters """ function topologyMaxQPseudolik!(net::HybridNetwork, d::DataCF; verbose=false::Bool, ftolRel=fRel::Float64, ftolAbs=fAbs::Float64, xtolRel=xRel::Float64, xtolAbs=xAbs::Float64) tmp1, tmp2 = taxadiff(d,net) length(tmp1)==0 || error("these taxa appear in one or more quartets, but not in the starting topology: $tmp1") if length(tmp2)>0 s = "these taxa will be deleted from the starting topology, they have no quartet CF data:\n" for tax in tmp2 s *= " $tax"; end @warn s net = deepcopy(net) for tax in tmp2 deleteleaf!(net, tax) end end net = readTopologyUpdate(writeTopologyLevel1(net)) # update everything for level 1 try checkNet(net) catch err err.msg = "starting topology not a level 1 network:\n" * err.msg rethrow(err) end if(!isempty(d.repSpecies)) expandLeaves!(d.repSpecies, net) net = readTopologyLevel1(writeTopologyLevel1(net)) # dirty fix to multiple alleles problem with expandLeaves end optBL!(net, d, verbose, ftolRel, ftolAbs, xtolRel,xtolAbs) if(net.numBad > 0) # to keep gammaz info in parenthetical description of bad diamond I for n in net.hybrid setGammaBLfromGammaz!(n,net) # get t and γ that are compatible with estimated gammaz values end end setNonIdBL!(net) if(!isempty(d.repSpecies)) mergeLeaves!(net) end return net end # function to delete a hybrid, and then add a new hybrid: # deleteHybridizationUpdate and addHybridizationUpdate, # closeN=true will try move origin/target, if false, will delete/add new hybrid # default is closeN =true # origin=true, moves origin, if false, moves target. option added to control not keep coming # to the same network over and over # returns success # movesgama: vector of count of number of times each move is proposed to fix gamma zero situation:(add,mvorigin,mvtarget,chdir,delete,nni) # movesgamma[13]: total number of accepted moves by loglik """ `moveHybrid` road map Function that tries to fix a gamma zero problem (`h==0,1; t==0; hz==0,1`) after changing direction of hybrid edge failed. This function is called in `gammaZero`. Arguments: - `closeN=true` will try move origin/target on all neighbors (first choose minor/major edge at random, then make list of all neighbor edges and tries to put the hybrid node in all the neighbors until successful move); if false, will delete and add hybrid until successful move up to N times (this is never tested) Returns true if change was successful (not testing `optBL` again), and false if we could not move anything """ function moveHybrid!(net::HybridNetwork, edge::Edge, closeN ::Bool, origin::Bool,N::Integer, movesgamma::Vector{Int}) edge.hybrid || error("edge $(edge.number) cannot be deleted because it is not hybrid") node = edge.node[edge.isChild1 ? 1 : 2]; node.hybrid || error("hybrid edge $(edge.number) pointing at tree node $(node.number)") @debug "MOVE: moving hybrid for edge $(edge.number)" if(closeN ) if(origin) movesgamma[2] += 1 success = moveOriginUpdateRepeat!(net,node,true) movesgamma[8] += success ? 1 : 0 else movesgamma[3] += 1 success = moveTargetUpdateRepeat!(net,node,true) movesgamma[9] += success ? 1 : 0 end else movesgamma[1] += 1 deleteHybridizationUpdate!(net, node, true, true) success = addHybridizationUpdateSmart!(net,N) movesgamma[7] += success ? 1 : 0 end return success end # function to deal with h=0,1 case by: # - change direction of hybrid edge, do optBL again # - if failed, call moveHybrid # input: net (network to be altered) # closeN =true will try move origin/target, if false, will delete/add new hybrid # origin=true, moves origin, if false, moves target. option added to control not keep coming # to the same network over and over # returns success # movesgama: vector of count of number of times each move is proposed to fix gamma zero situation:(add,mvorigin,mvtarget,chdir,delete,nni) # movesgamma[13]: total number of accepted moves by loglik """ `gammaZero` road map Function that tries to fix a gamma zero problem (`h==0,1; t==0; hz==0,1`) 1) First tries to do `changeDirection` 2) If not successful from start, we call `moveHybrid` 3) If successful move (change direction), we call `optBL` and check if we fixed the problem 4) If problem fixed and we do not have worse pseudolik, we return `success=true` 5) If still problem or worse pseudolik, we call `moveHybrid` ** Important: ** Any function (`afterOptBL`) calling `gammaZero` is assuming that it only made a change, so if the returned value is true, then a change was made, and the other function needs to run `optBL` and check that all parameters are 'valid'. If the returned value is false, then no change was possible and we need to remove a hybridization if the problem is h==0,1; hz==0,1. If the problem is t==0, we ignore this problem. """ function gammaZero!(net::HybridNetwork, d::DataCF, edge::Edge, closeN ::Bool, origin::Bool, N::Integer, movesgamma::Vector{Int}) global CHECKNET currTloglik = net.loglik edge.hybrid || error("edge $(edge.number) should be hybrid edge because it corresponds to a gamma (or gammaz) in net.ht") @debug "gamma zero situation found for hybrid edge $(edge.number) with gamma $(edge.gamma)" node = edge.node[edge.isChild1 ? 1 : 2]; node.hybrid || error("hybrid edge $(edge.number) pointing at tree node $(node.number)") success = changeDirectionUpdate!(net,node) #changes dir of minor movesgamma[4] += 1 if(success) @debug begin printEverything(net); "printed everything" end CHECKNET && checkNet(net) movesgamma[10] += 1 optBL!(net,d,false) flags = isValid(net) if(net.loglik <= currTloglik && flags[1] && flags[3]) @debug "changing direction fixed the gamma zero situation" success2 = true else @debug "changing direction does not fix the gamma zero situation, need to undo change direction and move hybrid" success = changeDirectionUpdate!(net,node) success || error("strange thing, changed direction and success, but lower loglik; want to undo changeDirection, and success=false! Hybrid node is $(node.number)") @debug begin printEverything(net); "printed everything" end CHECKNET && checkNet(net) success2 = moveHybrid!(net,edge,closeN ,origin,N, movesgamma) end else @debug "changing direction was not possible to fix the gamma zero situation (success=false), need to move hybrid" @debug begin printEverything(net); "printed everything" end CHECKNET && checkNet(net) success2 = moveHybrid!(net,edge,closeN ,origin,N,movesgamma) end return success2 end # function to check if h or t (in currT.ht) are 0 (or 1 for h) # closeN =true will try move origin/target, if false, will delete/add new hybrid # origin=true, moves origin, if false, moves target. option added to control not keep coming # to the same network over and over # returns successchange=false if could not add new hybrid; true ow # returns successchange,flagh,flagt,flaghz (flag_=false if problem with gamma, t=0 or gammaz) # movesgama: vector of count of number of times each move is proposed to fix gamma zero situation:(add,mvorigin,mvtarget,chdir,delete,nni) # movesgamma[13]: total number of accepted moves by loglik """ `afterOptBL` road map Function that will check if there are `h==0,1;t==0,hz==0,1` cases in a network after calling `optBL!`. Arguments: - `closeN=true` will move origin/target, if false, add/delete N times before giving up (we have only tested `closeN=true`) - `origin=true` will move origin, false will move target. We added this to avoid going back and forth between the same networks - `movesgamma` vector of counts of number of times each move is proposed to fix a gamma zero problem: `(add,mvorigin,mvtarget,chdir,delete,nni)` Procedure: - First we split the `ht` vector in `nh,nt,nhz` (gammas, lengths, gammaz) - If we find a `h==0,1`, we loop through `nh` to find a hybrid edge with h==0 or 1 and want to try to fix this by doing: - `gammaZero!(currT,d,edge,closeN,origin,N,movesgamma)` which returns true if there was a successful change, and we stop the loop - If we find a `t==0`, we loop through all `nt` to find such edge, and do NNI move on this edge; return true if change successful and we stop the loop - If we find a `hz==0,1`, we loop through `nhz` to find such hybrid edge and call `gammaZero` again - If we did a successful change, we run `optBL` again, and recheck if there are no more problems. - Returns successchange, flagh, flagt,flaghz (flag=true means no problems) - If it is the multiple alleles case, it will not try to fix `h==0,1;hz==0,1` because it can reach a case that violates the multiple alleles condition. If we add a check here, things become horribly slow and inefficient, so we just delete a hybridization that has `h==0,1;hz==0,1` ** Important: ** `afterOptBL` is doing only one change, but we need to repeat multiple times to be sure that we fix all the gamma zero problems, which is why we call `afterOptBLRepeat` """ function afterOptBL!(currT::HybridNetwork, d::DataCF,closeN ::Bool, origin::Bool,verbose::Bool, N::Integer, movesgamma::Vector{Int}) global CHECKNET !isTree(currT) || return false,true,true,true nh = currT.ht[1 : currT.numHybrids - currT.numBad] k = sum([e.istIdentifiable ? 1 : 0 for e in currT.edge]) nt = currT.ht[currT.numHybrids - currT.numBad + 1 : currT.numHybrids - currT.numBad + k] nhz = currT.ht[currT.numHybrids - currT.numBad + k + 1 : length(currT.ht)] indh = currT.index[1 : currT.numHybrids - currT.numBad] indt = currT.index[currT.numHybrids - currT.numBad + 1 : currT.numHybrids - currT.numBad + k] indhz = currT.index[currT.numHybrids - currT.numBad + k + 1 : length(currT.ht)] flagh,flagt,flaghz = isValid(nh,nt,nhz) !reduce(&,[flagh,flagt,flaghz]) || return false,true,true,true @debug "begins afterOptBL because of conflicts: flagh,flagt,flaghz=$([flagh,flagt,flaghz])" successchange = true if(!flagh) for i in 1:length(nh) if(approxEq(nh[i],0.0) || approxEq(nh[i],1.0)) edge = currT.edge[indh[i]] approxEq(edge.gamma,nh[i]) || error("edge $(edge.number) gamma $(edge.gamma) should match the gamma in net.ht $(nh[i]) and it does not") successchange = gammaZero!(currT, d,edge,closeN ,origin,N,movesgamma) !successchange || break end end elseif(!flagt) for i in 1:length(nt) if(approxEq(nt[i],0.0)) edge = currT.edge[indt[i]] approxEq(edge.length,nt[i]) || error("edge $(edge.number) length $(edge.length) should match the length in net.ht $(nt[i]) and it does not") if(all((n->!n.hasHybEdge), edge.node)) movesgamma[6] += 1 successchange = NNI!(currT,edge) movesgamma[12] += successchange ? 1 : 0 !successchange || break else @debug "MOVE: need NNI on edge $(edge.number) because length is $(edge.length), but edge is attached to nodes that have hybrid edges" successchange = false end end end elseif(!flaghz) currT.numBad > 0 || error("not a bad diamond I and flaghz is $(flaghz), should be true") i = 1 while(i <= length(nhz)) if(approxEq(nhz[i],0.0)) nodehz = currT.node[indhz[i]] approxEq(nodehz.gammaz,nhz[i]) || error("nodehz $(nodehz.number) gammaz $(nodehz.gammaz) should match the gammaz in net.ht $(nhz[i]) and it does not") edges = hybridEdges(nodehz) edges[1].hybrid || error("bad diamond I situation, node $(nodehz.number) has gammaz $(nodehz.gammaz) so should be linked to hybrid edge, but it is not") successchange = gammaZero!(currT,d,edges[1],closeN ,origin,N,movesgamma) break elseif(approxEq(nhz[i],1.0)) approxEq(nhz[i+1],0.0) || error("gammaz for node $(currT.node[indhz[i]].number) is $(nhz[i]) but the other gammaz is $(nhz[i+1]), the sum should be less than 1.0 (afteroptbl)") nodehz = currT.node[indhz[i+1]] approxEq(nodehz.gammaz,nhz[i+1]) || error("nodehz $(nodehz.number) gammaz $(nodehz.gammaz) should match the gammaz in net.ht $(nhz[i+1]) and it does not") edges = hybridEdges(nodehz) edges[1].hybrid || error("bad diamond I situation, node $(nodehz.number) has gammaz $(nodehz.gammaz) so should be linked to hybrid edge, but it is not") successchange = gammaZero!(currT,d,edges[1],closeN ,origin,N,movesgamma) break else if(approxEq(nhz[i+1],0.0)) nodehz = currT.node[indhz[i+1]]; approxEq(nodehz.gammaz,nhz[i+1]) || error("nodehz $(nodehz.number) gammaz $(nodehz.gammaz) should match the gammaz in net.ht $(nhz[i+1]) and it does not") edges = hybridEdges(nodehz); edges[1].hybrid || error("bad diamond I situation, node $(nodehz.number) has gammaz $(nodehz.gammaz) so should be linked to hybrid edge, but it is not") successchange = gammaZero!(currT,d,edges[1],closeN ,origin,N,movesgamma) break elseif(approxEq(nhz[i+1],1.0)) error("gammaz for node $(currT.node[indhz[i]].number) is $(nhz[i]) but the other gammaz is $(nhz[i+1]), the sum should be less than 1.0 (afteroptbl)") end end i += 2 end end if successchange @debug begin printEverything(currT); "afterOptBL SUCCESSFUL change, need to run again to see if new topology is valid" end CHECKNET && checkNet(currT) optBL!(currT,d,verbose) flagh,flagt,flaghz = isValid(currT) @debug "new flags: flagh,flagt,flaghz $([flagh,flagt,flaghz])" end return successchange,flagh,flagt,flaghz end # function to repeat afterOptBL every time after changing something # N: number of times it will delete/add hybrid if closeN =false # origin=true, moves origin, if false, moves target. option added to control not keep coming # to the same network over and over # movesgama: vector of count of number of times each move is proposed to fix gamma zero situation:(add,mvorigin,mvtarget,chdir,delete,nni) # movesgamma[13]: total number of accepted moves by loglik """ `afterOptBLRepeat` road map `afterOptBL` is doing only one change, but we need to repeat multiple times to be sure that we fix all the gamma zero problems, which is why we call `afterOptBLRepeat`. This function will repeat `afterOptBL` every time a successful change happened; this is done only if `closeN=false`, because we would delete/add hybridizations and need to stop after tried N times. If `closeN=true` (default), then `afterOptBLRepeat` only does one `afterOptBL`, because in this case, only the neighbor edges need to be tested, and this would have been done already in `gammaZero`. """ function afterOptBLRepeat!(currT::HybridNetwork, d::DataCF, N::Integer,closeN ::Bool, origin::Bool, verbose::Bool, movesgamma::Vector{Int}) success,flagh,flagt,flaghz = afterOptBL!(currT,d,closeN ,origin,verbose,N, movesgamma) @debug "inside afterOptBLRepeat, after afterOptBL once, we get: success, flags: $([success,flagh,flagt,flaghz])" if !closeN @debug "closeN is $(closeN ), and gets inside the loop for repeating afterOptBL" i = 1 while(success && !reduce(&,[flagh,flagt,flaghz]) && i<N) #fixit: do we want to check loglik in this step also? success,flagh,flagt,flaghz = afterOptBL!(currT,d,closeN ,origin,verbose,N,movesgamma) i += 1 end @debug (i < N ? "" : "tried afterOptBL $(i) times") end return success,flagh,flagt,flaghz end # function to check if we have to keep checking loglik # returns true if we have to stop because loglik not changing much anymore, or it is close to 0.0 already ## function stopLoglik(currloglik::Float64, newloglik::Float64, ftolAbs::Float64, M::Number) ## return (abs(currloglik-newloglik) <= M*ftolAbs) || (newloglik <= M*ftolAbs) ## end # function similar to afterOptBLALl but for multiple alleles # it will not try as hard to fix gamma,t=0 problem # it will only call moveDownLevel if problem with gamma or gammaz # fixit: later we can modify this function so that it # will call the original afterOptBLAll if it is safe # (i.e. there is no chance the alleles will be involved in any change) function afterOptBLAllMultipleAlleles!(currT::HybridNetwork, d::DataCF, N::Integer,closeN ::Bool, ftolAbs::Float64, verbose::Bool, movesgamma::Vector{Int},ftolRel::Float64, xtolRel::Float64, xtolAbs::Float64) global CHECKNET !isempty(d.repSpecies) || error("calling afterOptBLAllMultipleAlleles but this is not a case with multple alleles") !isTree(currT) || return false,true,true,true nh = currT.ht[1 : currT.numHybrids - currT.numBad] k = sum([e.istIdentifiable ? 1 : 0 for e in currT.edge]) nt = currT.ht[currT.numHybrids - currT.numBad + 1 : currT.numHybrids - currT.numBad + k] nhz = currT.ht[currT.numHybrids - currT.numBad + k + 1 : length(currT.ht)] indh = currT.index[1 : currT.numHybrids - currT.numBad] indt = currT.index[currT.numHybrids - currT.numBad + 1 : currT.numHybrids - currT.numBad + k] indhz = currT.index[currT.numHybrids - currT.numBad + k + 1 : length(currT.ht)] flagh,flagt,flaghz = isValid(nh,nt,nhz) !reduce(&,[flagh,flagt,flaghz]) || return false,true,true,true @debug "begins afterOptBL because of conflicts: flagh,flagt,flaghz=$([flagh,flagt,flaghz])" ## fixit: we could check here currT and see if we can call the original afterOptBLAll if(!flagh || !flaghz) moveDownLevel!(currT) optBL!(currT,d,verbose,ftolRel, ftolAbs, xtolRel, xtolAbs) end if(CHECKNET) checkNet(currT) checkTop4multAllele(currT) || error("network after moveDownLevel does not satisfy multiple alleles condition") end end # function to repeat afterOptBL every time after changing something # closeN =true will try move origin/target, if false, will delete/add new hybrid # default is closeN =true # returns new approved currT (no gammas=0.0) # N: number of times failures of accepting loglik is allowed, liktolAbs: tolerance to stop the search for lik improvement # movesgama: vector of count of number of times each move is proposed to fix gamma zero situation:(add,mvorigin,mvtarget,chdir,delete,nni) # movesgamma[13]: total number of accepted moves by loglik """ `afterOptBLAll` road map After `optBL`, we want to call `afterOptBLAll` (or `afterOptBLAllMultipleAlleles`) to check if there are `h==0,1`; `t==0`; `hz==0,1`. This function will try to fix the gamma zero problem, but if it cannot, it will call `moveDownLevel`, to delete the hybridization from the network. Procedure: While `startover=true` and `tries<N` - While `badliks < N2` (number of bad pseudolikelihoods are less than `N2`) - Run `success = afterOptBLRepeat` - If `success = true` (it changed something): - If worse pseudolik, then go back to original topology `currT`, set `startover=true` and `badliks++` - If better pseudolik, then check flags. If all good, then `startover=false`; otherwise `startover = true` - If `success = false` (nothing changed), then set `badliks=N2+1` (to end the while on `currT`) - If all flags are ok, then `startover = false` - If bad h or hz, then call `moveDownLevel` (delete one hybridization), and set `startover = true` (maybe deleting that hybridization did not fix other gamma zero problems) - If bad t, then set `startover = false` - If left second while by back to original `currT`, and still bad h/hz, then move down one level, and `startover=true`; otherwise `startover=false` If first while ends by `tries>N`, then it checks one last time the flags, if bad h/hz will move down one level, and exit """ function afterOptBLAll!(currT::HybridNetwork, d::DataCF, N::Integer,closeN ::Bool, liktolAbs::Float64, ftolAbs::Float64, verbose::Bool, movesgamma::Vector{Int},ftolRel::Float64, xtolRel::Float64, xtolAbs::Float64) @debug "afterOptBLAll: checking if currT has gamma (gammaz) = 0.0(1.0): currT.ht $(currT.ht)" currloglik = currT.loglik currT.blacklist = Int[]; origin = (rand() > 0.5) #true=moveOrigin, false=moveTarget startover = true tries = 0 N2 = N > 10 ? N/10 : 1 #num of failures of badlik around a gamma=0.0, t=0.0 while(startover && tries < N) tries += 1 @debug "inside afterOptBLALL: number of tries $(tries) out of $(N) possible" badliks = 0 if(currT.loglik < liktolAbs) #curr loglik already close to 0.0 startover = false else backCurrT0 = false while(badliks < N2) #will try a few options around currT @debug "tried $(badliks) bad likelihood options so far out of $(N2)" currT0 = deepcopy(currT) origin = !origin #to guarantee not going back to previous topology success,flagh,flagt,flaghz = afterOptBLRepeat!(currT,d,N,closeN ,origin,verbose,movesgamma) all((e->!(e.hybrid && e.inCycle == -1)), currT.edge) || error("found hybrid edge with inCycle == -1") @debug "inside afterOptBLAll, after afterOptBLRepeat once we get: success, flags: $([success,flagh,flagt,flaghz])" if !success #tried to change something but failed @debug "did not change anything inside afterOptBL: could be nothing needed change or tried but couldn't anymore. flagh, flagt, flaghz = $([flagh,flagt,flaghz])" if reduce(&,[flagh,flagt,flaghz]) #currT was ok startover = false elseif !flagh || !flaghz #currT was bad but could not change it, need to go down a level !isTree(currT) || error("afterOptBL should not give reject=true for a tree") @debug "current topology has numerical parameters that are not valid: gamma=0(1), gammaz=0(1); need to move down a level h-1" moveDownLevel!(currT) optBL!(currT,d,verbose,ftolRel, ftolAbs, xtolRel, xtolAbs) startover = true elseif !flagt startover = false end else #changed something @debug "changed something inside afterOptBL: flagh, flagt, flaghz = $([flagh,flagt,flaghz]). oldloglik $(currloglik), newloglik $(currT.loglik)" if currT.loglik > currloglik #|| abs(currT.loglik-currloglik) <= liktolAbs) #fixit: allowed like this because of changeDir that does not change much the lik but can fix h=0 @debug "worse likelihood, back to currT" startover = true backCurrT0 = true else @debug "better likelihood, jump to new topology and startover" backCurrT0 = false movesgamma[13] += 1 if reduce(&,[flagh,flagt,flaghz]) startover = false else currloglik = currT.loglik startover = true end end end if backCurrT0 currT = currT0 startover = true badliks += 1 else badliks = N+1 ## exit second while end end if backCurrT0 # leaves while for failed loglik @debug "tried to fix gamma zero situation for $(badliks) times and could not" flagh,flagt,flaghz = isValid(currT) if(!flagh || !flaghz) !isTree(currT) || error("afterOptBL should not give reject=true for a tree") @debug "current topology has numerical parameters that are not valid: gamma=0(1), t=0, gammaz=0(1); need to move down a level h-1" movesgamma[5] += 1 movesgamma[11] += 1 moveDownLevel!(currT) optBL!(currT,d,verbose,ftolRel, ftolAbs, xtolRel, xtolAbs) startover = true else @debug "the only problem were lengths equal to zero, so we will keep them" startover = false end end end end if tries >= N @debug "afterOptBLAll ended because it tried $(tries) times with startover $(startover)" @debug writeTopologyLevel1(currT,true) flagh,flagt,flaghz = isValid(currT) if(!flagh || !flaghz) @debug "gammaz zero situation still in currT, need to move down one level to h-1" moveDownLevel!(currT) @debug begin printEdges(currT) printPartitions(currT) #printNodes(currT) writeTopologyLevel1(currT,true) end optBL!(currT,d,verbose,ftolRel, ftolAbs, xtolRel, xtolAbs) end end currT.blacklist = Int[]; return currT end # -------------- heuristic search for topology ----------------------- function isTree(net::HybridNetwork) net.numHybrids == length(net.hybrid) || error("numHybrids does not match to length of net.hybrid") net.numHybrids != 0 || return true return false end # function to adjust the weight of addHybrid if net is in a much lower layer # net.numHybrids<<hmax # takes as input the vector of weights for each move (add,mvorigin,mvtarget,chdir,delete,nni) function adjustWeight(net::HybridNetwork,hmax::Integer,w::Vector{Float64}) if(hmax - net.numHybrids > 0) hmax >= 0 || error("hmax must be non negative: $(hmax)") length(w) == 6 || error("length of w should be 6 as there are only 6 moves: $(w)") approxEq(sum(w),1.0) || error("vector of move weights should add up to 1: $(w),$(sum(w))") all((i->(0<=i<=1)), w) || error("weights must be nonnegative and less than one $(w)") suma = w[5]+w[2]+w[3]+w[4]+w[6] v = zeros(6) k = hmax - net.numHybrids for i in 1:6 if(i == 1) v[i] = w[1]*k/(suma + w[1]*k) else v[i] = w[i]/(suma + w[1]*k) end end return v end return w end # function to adjust weights (v) based on movesfail and Nmov, to # avoid proposing over and over moves that cannot work: (add,mvorigin, mvtarget, chdir, delete,nni) #returns false if sum(v)=0, no more moves available # needs the net and hmax to decide if there are available moves function adjustWeightMovesfail!(v::Vector{Float64}, movesfail::Vector{Int}, Nmov::Vector{Int}, net::HybridNetwork, hmax::Integer) length(v) ==length(movesfail) || error("v and movesfail must have same length") length(Nmov) ==length(movesfail) || error("Nmov and movesfail must have same length") for i in 1:length(v) v[i] = v[i]*(movesfail[i]<Nmov[i] ? 1 : 0) end if(hmax == 0) isTree(net) || error("hmax is $(hmax) but net is not a tree") v[6] == 0 && return false #nni else if(0 < net.numHybrids < hmax) sum(v) != 0 || return false #all moves elseif(net.numHybrids == 0) v[1] == 0 && v[6] == 0 && return false #nni or add elseif(net.numHybrids == hmax) sum(v[2:4]) + v[6] != 0 || return false #all moves except add/delete end end suma = sum(v) for i in 1:length(v) v[i] = v[i]/suma end return true end # function to decide what next move to do when searching # for topology that maximizes the P-loglik within the space of # topologies with the same number of hybridizations # possible moves: move origin/target, change direction hybrid edge, tree nni # needs the network to know the current numHybrids # takes as input the vector of weights for each move (add,mvorigin, mvtarget, chdir, delete,nni) # and dynamic=true, adjusts the weight for addHybrid if net is in a lower layer (net.numHybrids<<hmax) # movesfail and Nmov are to count number of fails in each move function whichMove(net::HybridNetwork,hmax::Integer,w::Vector{Float64}, dynamic::Bool, movesfail::Vector{Int}, Nmov::Vector{Int}) hmax >= 0 || error("hmax must be non negative: $(hmax)") length(w) == 6 || error("length of w should be 6 as there are only 6 moves: $(w)") approxEq(sum(w),1.0) || error("vector of move weights should add up to 1: $(w),$(sum(w))") all((i->(0<=i<=1)),w) || error("weights must be nonnegative and less than one $(w)") if(hmax == 0) isTree(net) || error("hmax is $(hmax) but net is not a tree") flag = adjustWeightMovesfail!(w,movesfail,Nmov,net,hmax) flag || return :none return :nni else r = rand() if(dynamic) v = adjustWeight(net,hmax,w) else v = w end @debug "weights before adjusting by movesfail $(v)" flag = adjustWeightMovesfail!(v,movesfail,Nmov,net,hmax) @debug "weights after adjusting by movesfail $(v)" flag || return :none if(0 < net.numHybrids < hmax) if(r < v[1]) return :add elseif(r < v[1]+v[2]) return :MVorigin elseif(r < v[1]+v[2]+v[3]) return :MVtarget elseif(r < v[1]+v[2]+v[3]+v[4]) return :CHdir elseif(r < v[1]+v[2]+v[3]+v[4]+v[5]) return :delete else return :nni end elseif(net.numHybrids == 0) suma = v[1]+v[6] if(r < (v[1])/suma) return :add else return :nni end else # net.numHybrids == hmax suma = v[5]+v[2]+v[3]+v[4]+v[6] if(r < v[2]/suma) return :MVorigin elseif(r < (v[3]+v[2])/suma) return :MVtarget elseif(r < (v[4]+v[2]+v[3])/suma) return :CHdir elseif(r < (v[5]+v[2]+v[3]+v[4])/suma) return :delete else return :nni end end end end whichMove(net::HybridNetwork,hmax::Integer,movesfail::Vector{Int}, Nmov::Vector{Int}) = whichMove(net,hmax,[1/5,1/5,1/5,1/5,0.0,1/5], true,movesfail, Nmov) whichMove(net::HybridNetwork,hmax::Integer,w::Vector{Float64},movesfail::Vector{Int}, Nmov::Vector{Int}) = whichMove(net,hmax,w, true,movesfail, Nmov) #function to choose a hybrid node for the given moves function chooseHybrid(net::HybridNetwork) !isTree(net) || error("net is a tree, cannot choose hybrid node") net.numHybrids > 1 || return net.hybrid[1] index1 = 0 while(index1 == 0 || index1 > size(net.hybrid,1)) index1 = round(Integer,rand()*size(net.hybrid,1)); end @debug "chosen hybrid node for network move: $(net.hybrid[index1].number)" return net.hybrid[index1] end # function to propose a new topology given a move # random = false uses the minor hybrid edge always # count to know in which step we are, N for NNI trials # order in movescount as in IF here (add,mvorigin,mvtarget,chdir,delete,nni) # multAll = true if d.repSpecies is not empty, checked outside """ `proposedTop!(move,newT,random,count,N,movescount,movesfail,multall)` road map Function to change the current network `newT` by a given `move`, and checks that the move was successful (correct attributes). If not successful, `newT` is changed back to its original state, except for the case of multiple alleles. **Note** that the update of attributes by each move is not done in all the network, but only in the local edges that were changed by the move. This is efficient (and makes a move easy to undo), but makes the code of each move function very clunky. Arguments: - move chosen from `whichMove` as described in `optTopLevel` - `newT` is the topology that will be modified inside with the move - `random=true`: chooses minor hybrid edge with prob 1-h, and major edge with prob h, if false, always chooses minor hybrid edge - `count`: simply which likelihood step we are in in the optimization at `optTopLevel` - `movescount` and `movesfail`: vector of counts of number of moves proposed - `multall=true` if multiple alleles case: we need to check if the move did not violate the multiple alleles condition (sister alleles together and no gene flow into the alleles). This is inefficient because we are proposing moves that we can reject later, instead of being smart about the moves we propose: for example, move origin/target could rule out some neighbors that move gene flow into the alleles, the same for add hybridization; nni move can check if it is trying to separate the alleles) Moves: - `addHybridizationUpdate(newT,N)`: will choose a partition first (to avoid choosing edges that will create a non level-1 network) will choose two edges from this partition randomly, will not allow two edges in a cherry (non-identifiable), or sister edges that are not identifiable (the blacklist was a way to keep track of "bad edges" were we should not waste time trying to put hybridizations, it has never been used nor tested). Also choose gamma from U(0,0.5). The "Update" in the function name means that it creates the new hybrid, and also updates all the attributes of `newT` - `node = chooseHybrid(newT)` choose a hybrid randomly for the next moves: - `moveOriginUpdateRepeat!(newT,node,random)` will choose randomly the minor/major hybrid edge to move (if `random=true`); will get the list of all neighbor edges where to move the origin, will move the origin and update all the attributes and check if the move was successful (not conflicting attributes); if not, will undo the move, and try with a different neighbor until it runs out of neighbors. Return true if the move was successful. - `moveTargetUpdateRepeat!(newT,node,random)` same as move origin but moving the target - `changeDirectionUpdate!(newT,node,random)` chooses minor/major hybrid edge at random (if `random=true), and changes the direction, and updates all the attributes. Checks if the move was successful (returns true), or undoes the change and returns false. - `deleteHybridizationUpdate!(newT,node)` removes the hybrid node, updates the attributes, no need to check any attributes, always successful move - NNIRepeat!(newT,N) choose an edge for nni that does not have a neighbor hybrid. It will try to find such an edge N times, and if it fails, it will return false (unsuccessful move). N=10 by default. If N=1, it rarely finds such an edge if the network is small or complex. The function cannot choose an external edge. it will update locally the attributes. ** Important: ** All the moves undo what they did if the move was not successful, so at the end you either have a `newT` with a new move and with all good attributes, or the same `newT` that started. This is important to avoid having to do deepcopy of the network before doing the move. Also, after each move, when we update the attributes, we do not update the attributes of the whole network, we only update the attributes of the edges that were affected by the move. This saves time, but makes the code quite clunky. Only the case of multiple alleles the moves does not undo what it did, because it finds out that it failed after the function is over, so just need to treat this case special. """ function proposedTop!(move::Integer, newT::HybridNetwork,random::Bool, count::Integer, N::Integer, movescount::Vector{Int}, movesfail::Vector{Int}, multall::Bool) global CHECKNET 1 <= move <= 6 || error("invalid move $(move)") #fixit: if previous move rejected, do not redo it! @debug "current move: $(int2move[move])" if(move == 1) success = addHybridizationUpdateSmart!(newT,N) elseif(move == 2) node = chooseHybrid(newT) success = moveOriginUpdateRepeat!(newT,node,random) CHECKNET && isBadTriangle(node) && success && error("success is $(success) in proposedTop, but node $(node.number) is very bad triangle") elseif(move == 3) node = chooseHybrid(newT) success = moveTargetUpdateRepeat!(newT,node,random) CHECKNET && isBadTriangle(node) && success && error("success is $(success) in proposedTop, but node $(node.number) is very bad triangle") elseif(move == 4) node = chooseHybrid(newT) success = changeDirectionUpdate!(newT,node, random) CHECKNET && isBadTriangle(node) && success && error("success is $(success) in proposedTop, but node $(node.number) is very bad triangle") elseif(move == 5) node = chooseHybrid(newT) deleteHybridizationUpdate!(newT,node) success = true elseif(move == 6) success = NNIRepeat!(newT,N) end if(multall) success2 = checkTop4multAllele(newT) @debug "entered to check topology for mult allele: $(success2)" success &= success2 end movescount[move] += 1 movescount[move+6] += success ? 1 : 0 movesfail[move] += success ? 0 : 1 @debug "success $(success), movescount (add,mvorigin,mvtarget,chdir,delete,nni) proposed: $(movescount[1:6]); successful: $(movescount[7:12]); movesfail: $(movesfail)" !success || return true @debug "new proposed topology failed in step $(count) for move $(int2move[move])" @debug begin printEverything(newT); "printed everything" end CHECKNET && checkNet(newT) return false end proposedTop!(move::Symbol, newT::HybridNetwork, random::Bool, count::Integer,N::Integer, movescount::Vector{Int},movesfail::Vector{Int}, multall::Bool) = proposedTop!( try move2int[move] catch; error("invalid move $(string(move))") end, newT, random,count,N, movescount,movesfail, multall) # function to calculate Nmov, number max of tries per move # order: (add,mvorigin,mvtarget,chdir,delete,nni) function calculateNmov!(net::HybridNetwork, N::Vector{Int}) if(isempty(N)) N = zeros(Int, 6) else length(N) == 6 || error("vector Nmov should have length 6: $(N)") end if(isTree(net)) N[1] = ceil(coupon(binom(numTreeEdges(net),2))) #add N[2] = 1 N[3] = 1 N[4] = 1 N[5] = 1 #delete N[6] = ceil(coupon(4*numIntTreeEdges(net))) #nni else N[1] = ceil(coupon(binom(numTreeEdges(net),2))) #add N[2] = ceil(coupon(2*4*net.numHybrids)) #mvorigin N[3] = ceil(coupon(2*4*net.numHybrids)) #mtarget N[4] = ceil(coupon(2*net.numHybrids)) #chdir N[5] = 10000 #delete N[6] = ceil(coupon(4*numIntTreeEdges(net))) #nni end end # function to optimize on the space of networks with the same (or fewer) numHyb # currT, the starting network will be modified inside # Nmov: vector with max number of tries per move (add,mvorigin,mvtarget,chdir,delete,nni) # Nfail: number of failure networks with lower loglik before aborting # liktolAbs: to stop the search if loglik close to liktolAbs, or if absDiff less than liktolAbs # hmax: max number of hybrids allowed # closeN =true if gamma=0.0 fixed only around neighbors with move origin/target # logfile=IOStream to capture the information on the heurisitc optimization, default stdout """ `optTopLevel` road map Function that does most of the heavy-lifting of `snaq`. It optimizes the pseudolikelihood for a given starting topology, and returns the best network. Assumes that the starting topology is level-1 network, and has all the attributes correctly updated. Input parameters: - Starting topology `currT`, input data `DataCF` `d`, maximum number of hybridizations `hmax` - Numerical optimization parameters: `liktolAbs, Nfail, ftolRel, ftolAbs, xtolRel, xtolAbs` - Print parameters: `verbose, logfile, writelog` - Parameters to tune the search in space of networks: `closeN=true` only propose move origin/target to neighbor edges (coded, but not tested with `closeN=false`), `Nmov0` vector with maximum number of trials allowed per type of move `(add, mvorigin, mvtarget, chdir, delete, nni)`, by default computed inside with coupon’s collector formulas The optimization procedure keeps track of - `movescount`: count of proposed moves, - `movesgamma`: count of proposed moves to fix a gamma zero situation (see below for definition of this situation), - `movesfail`: count of failed moves by violation of level-1 network (`inCycle` attribute) or worse pseudolikelihood than current, - `failures`: number of failed proposals that had a worse pseudolikelihood Optimization procedure: While the difference between current loglik and proposed loglik is greater than `liktolAbs`, or `failures<Nfail`, or `stillmoves=true`: - `Nmov` is updated based on `newT`. The type of move proposed will depend on `newT` (which is the same as `currT` at this point). For example, if `currT` is a tree, we cannot propose move origin/target. - `move = whichMove` selects randomly a type of move, depending on `Nmov,movesfail,hmax,newT` with weights 1/5 by default for all, and 0 for delete. These weights are adjusted depending on `newT.numHybrids` and `hmax`. If `newT.numHybrids` is far from `hmax`, we give higher probability to adding a new hybrid (we want to reach the `hmax` sooner, maybe not the best strategy, easy to change). Later, we adjust the weights by `movesfail` (first, give weight of 0 if `movesfail[i]>Nmov[i]`, that is, if we reached the maximum possible number of moves allowed for a certain type) and then increase the probability of the other moves. So, unless one move has `w=0`, nothing changes. This could be improved by using the outlier quartets to guide the proposal of moves. - `whichMove` will choose a move randomly from the weights, it will return `none` if no more moves allowed, in which case, the optimization ends - `flag=proposedTop!(move, newT)` will modify `newT` based on `move`. The function `proposedTop` will return `flag=true` if the move was successful (the move succeeded by `inCycle`, `containRoot`, available edge to make the move (more details in `proposedTop`)). If `flag=false`, then `newT` is cleaned, except for the case of multiple alleles. The function `proposedTop` keeps count of `movescount` (successful move), `movesfail` (unsuccessful move), Options: `random=true`: moves major/minor hybrid edge with prob h,1-h, respectively `N=10`: number of trials for NNI edge. - if(flag) Optimize branch lengths with `optBL` If `newT.loglik` is better than `currT.loglik` by `liktolAbs`, jump to `newT` (`accepted=true`) and fix `gamma=0, t=0` problems (more info on `afterOptBL`) If(accepted) `failures=0`, `movesfail=zeros`, `movescount` for successful move +1 end while After choosing the best network `newT`, we do one last more thorough optimization of branch lengths with `optBL`, we change non identifiable branch lengths to -1 (only in debug mode) and return `newT` """ function optTopLevel!(currT::HybridNetwork, liktolAbs::Float64, Nfail::Integer, d::DataCF, hmax::Integer, ftolRel::Float64, ftolAbs::Float64, xtolRel::Float64, xtolAbs::Float64, verbose::Bool, closeN ::Bool, Nmov0::Vector{Int}, logfile::IO, writelog::Bool) global CHECKNET @debug "OPT: begins optTopLevel with hmax $(hmax)" liktolAbs > 0 || error("liktolAbs must be greater than zero: $(liktolAbs)") Nfail > 0 || error("Nfail must be greater than zero: $(Nfail)") isempty(Nmov0) || all(Nmov0 .>= 0) || error("Nmov must be non-negative zero: $(Nmov0)") if(!isempty(d.repSpecies)) checkTop4multAllele(currT) || error("starting topology does not fit multiple alleles condition") end @debug begin printEverything(currT); "printed everything" end CHECKNET && checkNet(currT) count = 0 movescount = zeros(Int,18) #1:6 number of times moved proposed, 7:12 number of times success move (no intersecting cycles, etc.), 13:18 accepted by loglik movesgamma = zeros(Int,13) #number of moves to fix gamma zero: proposed, successful, movesgamma[13]: total accepted by loglik movesfail = zeros(Int,6) #count of failed moves for current topology failures = 0 stillmoves = true if(isempty(Nmov0)) Nmov = zeros(Int,6) else Nmov = deepcopy(Nmov0) end all((e->!(e.hybrid && e.inCycle == -1)), currT.edge) || error("found hybrid edge with inCycle == -1") optBL!(currT,d,verbose,ftolRel, ftolAbs, xtolRel, xtolAbs) if(!isempty(d.repSpecies)) ## muliple alleles case afterOptBLAllMultipleAlleles!(currT, d, Nfail,closeN , ftolAbs, verbose,movesgamma,ftolRel,xtolRel,xtolAbs) else currT = afterOptBLAll!(currT, d, Nfail,closeN , liktolAbs, ftolAbs, verbose,movesgamma,ftolRel,xtolRel,xtolAbs) #needed return because of deepcopy inside end absDiff = liktolAbs + 1 newT = deepcopy(currT) @debug begin printEdges(newT) printPartitions(newT) println("++++") writeTopologyLevel1(newT,true) end writelog && write(logfile, "\nBegins heuristic optimization of network------\n") loopcount = 0 while(absDiff > liktolAbs && failures < Nfail && currT.loglik > liktolAbs && stillmoves) #stops if close to zero because of new deviance form of the pseudolik if (loopcount % 50) == 0 GC.gc() end if CHECKNET && !isempty(d.repSpecies) checkTop4multAllele(currT) || error("currT is not good for multiple alleles") end count += 1 @debug "--------- loglik_$(count) = $(round(currT.loglik, digits=6)) -----------" if isempty(Nmov0) #if empty, not set by user calculateNmov!(newT,Nmov) end @debug "will propose move with movesfail $(movesfail), Nmov $(Nmov)" move = whichMove(newT,hmax,movesfail,Nmov) @debug "++++" if move != :none if !isempty(d.repSpecies) # need the original newT in case the proposed top fails by multiple alleles condition newT0 = deepcopy(newT) end flag = proposedTop!(move,newT,true, count,10, movescount,movesfail,!isempty(d.repSpecies)) #N=10 because with 1 it never finds an edge for nni if(flag) #no need else in general because newT always undone if failed, but needed for multiple alleles accepted = false all((e->!(e.hybrid && e.inCycle == -1)), newT.edge) || error("found hybrid edge with inCycle == -1") @debug "proposed new topology in step $(count) is ok to start optBL" @debug begin printEverything(newT); "printed everything" end CHECKNET && checkNet(newT) optBL!(newT,d,verbose,ftolRel, ftolAbs, xtolRel, xtolAbs) @debug "OPT: comparing newT.loglik $(newT.loglik), currT.loglik $(currT.loglik)" if(newT.loglik < currT.loglik && abs(newT.loglik-currT.loglik) > liktolAbs) #newT better loglik: need to check for error or keeps jumping back and forth newloglik = newT.loglik if(!isempty(d.repSpecies)) ## multiple alleles afterOptBLAllMultipleAlleles!(newT, d, Nfail,closeN , ftolAbs,verbose,movesgamma,ftolRel, xtolRel,xtolAbs) else newT = afterOptBLAll!(newT, d, Nfail,closeN , liktolAbs, ftolAbs,verbose,movesgamma,ftolRel, xtolRel,xtolAbs) #needed return because of deepcopy inside end @debug "loglik before afterOptBL $(newloglik), newT.loglik now $(newT.loglik), loss in loglik by fixing gamma (gammaz)=0.0(1.0): $(newloglik>newT.loglik ? 0 : abs(newloglik-newT.loglik))" accepted = true else accepted = false end if(accepted) absDiff = abs(newT.loglik - currT.loglik) @debug "proposed new topology with better loglik in step $(count): oldloglik=$(round(currT.loglik, digits=3)), newloglik=$(round(newT.loglik, digits=3)), after $(failures) failures" currT = deepcopy(newT) failures = 0 movescount[move2int[move]+12] += 1 movesfail = zeros(Int,6) #count of failed moves for current topology else @debug "rejected new topology with worse loglik in step $(count): currloglik=$(round(currT.loglik, digits=3)), newloglik=$(round(newT.loglik, digits=3)), with $(failures) failures" failures += 1 movesfail[move2int[move]] += 1 newT = deepcopy(currT) end @debug begin printEdges(newT) printPartitions(newT) #printNodes(newT) println("++++") println(writeTopologyLevel1(newT,true)) "ends step $(count) with absDiff $(accepted ? absDiff : 0.0) and failures $(failures)" end else if(!isempty(d.repSpecies)) newT = newT0 ## only need to go back with multiple alleles, bc other functions in proposedTop undo what they did end end else stillmoves = false end @debug "--------- loglik_$(count) end: earlier log can be discarded ----" loopcount += 1 end if ftolAbs > 1e-7 || ftolRel > 1e-7 || xtolAbs > 1e-7 || xtolRel > 1e-7 writelog && write(logfile,"\nfound best network, now we re-optimize branch lengths and gamma more precisely") optBL!(newT,d,verbose, fRelBL,fAbsBL,xRelBL,xAbsBL) end assignhybridnames!(newT) if(absDiff <= liktolAbs) writelog && write(logfile,"\nSTOPPED by absolute difference criteria") elseif(currT.loglik <= liktolAbs) writelog && write(logfile,"\nSTOPPED by loglik close to zero criteria") elseif(!stillmoves) writelog && write(logfile,"\nSTOPPED for not having more moves to propose: movesfail $(movesfail), Nmov $(Nmov)") else writelog && write(logfile,"\nSTOPPED by number of failures criteria") end ## if(newT.loglik > liktolAbs) #not really close to 0.0, based on absTol also ## write(logfile,"\nnewT.loglik $(newT.loglik) not really close to 0.0 based on loglik abs. tol. $(liktolAbs), you might need to redo with another starting point") ## end if(newT.numBad > 0) # if bad diamond I, need to keep gammaz info in parenthetical description for n in newT.hybrid setGammaBLfromGammaz!(n,newT) # get t and γ that are compatible with estimated gammaz values end end writelog && write(logfile,"\nEND optTopLevel: found minimizer topology at step $(count) (failures: $(failures)) with -loglik=$(round(newT.loglik, digits=5)) and ht_min=$(round.(newT.ht, digits=5))") writelog && printCounts(movescount,movesgamma,logfile) @debug begin printEdges(newT) printPartitions(newT) printNodes(newT) writeTopologyLevel1(newT,true) ## this changes non-identifiable BLs in newT to -1 end if CHECKNET && !isempty(d.repSpecies) checkTop4multAllele(newT) || error("newT not suitable for multiple alleles at the very end") end return newT end optTopLevel!(currT::HybridNetwork, d::DataCF, hmax::Integer) = optTopLevel!(currT, likAbs, numFails, d, hmax,fRel, fAbs, xRel, xAbs, false,true,numMoves, stdout,true) optTopLevel!(currT::HybridNetwork, d::DataCF, hmax::Integer, verbose::Bool) = optTopLevel!(currT, likAbs, numFails, d, hmax,fRel, fAbs, xRel, xAbs, verbose,true,numMoves,stdout,true) optTopLevel!(currT::HybridNetwork, liktolAbs::Float64, Nfail::Integer, d::DataCF, hmax::Integer,ftolRel::Float64, ftolAbs::Float64, xtolRel::Float64, xtolAbs::Float64, verbose::Bool, closeN ::Bool, Nmov0::Vector{Int}) = optTopLevel!(currT, liktolAbs, Nfail, d, hmax,ftolRel, ftolAbs, xtolRel, xtolAbs, verbose, closeN , Nmov0,stdout,true) # function to print count of number of moves after optTopLevel # s: IOStream to decide if you want to print to a file or to screen, by default to screen function printCounts(movescount::Vector{Int}, movesgamma::Vector{Int},s::Union{IOStream,Base.TTY}) length(movescount) == 18 || error("movescount should have length 18, not $(length(movescount))") length(movesgamma) == 13 || error("movesgamma should have length 13, not $(length(movescount))") print(s,"\nPERFORMANCE: total number of moves (proposed, successful, accepted) in general, and to fix gamma=0.0,t=0.0 cases\n") print(s,"\t--------moves general--------\t\t\t\t --------moves gamma,t------\t\n") print(s,"move\t Num.Proposed\t Num.Successful\t Num.Accepted\t | Num.Proposed\t Num.Successful\t Num.Accepted\n") names = ["add","mvorigin","mvtarget","chdir","delete","nni"] for i in 1:6 if(i == 2 || i == 3) print(s,"$(names[i])\t $(movescount[i])\t\t $(movescount[i+6])\t\t $(movescount[i+12])\t |\t $(movesgamma[i])\t\t $(movesgamma[i+6])\t\t --\n") elseif(i == 1) print(s,"$(names[i])\t\t $(movescount[i])\t\t $(movescount[i+6])\t\t $(movescount[i+12])\t |\t NA \t\t NA \t\t NA \n") else print(s,"$(names[i])\t\t $(movescount[i])\t\t $(movescount[i+6])\t\t $(movescount[i+12])\t |\t $(movesgamma[i])\t\t $(movesgamma[i+6])\t\t --\n") end end suma = sum(movescount[7:12]); suma2 = sum(movesgamma[7:12]) == 0 ? 1 : sum(movesgamma[7:12]) print(s,"Total\t\t $(sum(movescount[1:6]))\t\t $(sum(movescount[7:12]))\t\t $(sum(movescount[13:18]))\t |\t $(sum(movesgamma[1:6]))\t\t $(sum(movesgamma[7:12]))\t\t $(movesgamma[13])\n") print(s,"Proportion\t -- \t\t $(round(sum(movescount[7:12])/suma, digits=1))\t\t $(round(sum(movescount[13:18])/suma, digits=1))\t |\t -- \t\t $(round(sum(movesgamma[7:12])/suma2, digits=1))\t\t $(round(movesgamma[13]/suma2, digits=1))\n") end printCounts(movescount::Vector{Int}, movesgamma::Vector{Int}) = printCounts(movescount, movesgamma,stdout) # function to print count of number of moves to a file # file=name of file where to save function printCounts(movescount::Vector{Int}, movesgamma::Vector{Int},file::AbstractString) s = open(file,"w") printCounts(movescount,movesgamma,s) close(s) end # function to move down onw level to h-1 # caused by gamma=0,1 or gammaz=0,1 function moveDownLevel!(net::HybridNetwork) global CHECKNET !isTree(net) ||error("cannot delete hybridization in a tree") @debug "MOVE: need to go down one level to h-1=$(net.numHybrids-1) hybrids because of conflicts with gamma=0,1" @debug begin printEverything(net); "printed everything" end CHECKNET && checkNet(net) nh = net.ht[1 : net.numHybrids - net.numBad] k = sum([e.istIdentifiable ? 1 : 0 for e in net.edge]) nt = net.ht[net.numHybrids - net.numBad + 1 : net.numHybrids - net.numBad + k] nhz = net.ht[net.numHybrids - net.numBad + k + 1 : length(net.ht)] indh = net.index[1 : net.numHybrids - net.numBad] indhz = net.index[net.numHybrids - net.numBad + k + 1 : length(net.ht)] flagh,flagt,flaghz = isValid(nh,nt,nhz) if(!flagh) for i in 1:length(nh) if(approxEq(nh[i],0.0) || approxEq(nh[i],1.0)) edge = net.edge[indh[i]] node = edge.node[edge.isChild1 ? 1 : 2]; node.hybrid || error("hybrid edge $(edge.number) pointing at tree node $(node.number)") deleteHybridizationUpdate!(net,node) end break end elseif(!flaghz) net.numBad > 0 || error("not a bad diamond I and flaghz is $(flaghz), should be true") i = 1 while(i <= length(nhz)) if(approxEq(nhz[i],0.0)) nodehz = net.node[indhz[i]] approxEq(nodehz.gammaz,nhz[i]) || error("nodehz $(nodehz.number) gammaz $(nodehz.gammaz) should match the gammaz in net.ht $(nhz[i]) and it does not") edges = hybridEdges(nodehz) edges[1].hybrid || error("bad diamond I situation, node $(nodehz.number) has gammaz $(nodehz.gammaz) so should be linked to hybrid edge, but it is not") node = edges[1].node[edges[1].isChild1 ? 1 : 2]; node.hybrid || error("hybrid edge $(edge.number) pointing at tree node $(node.number)") deleteHybridizationUpdate!(net,node) break elseif(approxEq(nhz[i],1.0)) approxEq(nhz[i+1],0.0) || error("gammaz for node $(net.node[indhz[i]].number) is $(nhz[i]) but the other gammaz is $(nhz[i+1]), the sum should be less than 1.0 (movedownlevel)") nodehz = net.node[indhz[i+1]] approxEq(nodehz.gammaz,nhz[i+1]) || error("nodehz $(nodehz.number) gammaz $(nodehz.gammaz) should match the gammaz in net.ht $(nhz[i+1]) and it does not") edges = hybridEdges(nodehz) edges[1].hybrid || error("bad diamond I situation, node $(nodehz.number) has gammaz $(nodehz.gammaz) so should be linked to hybrid edge, but it is not") node = edges[1].node[edges[1].isChild1 ? 1 : 2]; node.hybrid || error("hybrid edge $(edge.number) pointing at tree node $(node.number)") deleteHybridizationUpdate!(net,node) break else if(approxEq(nhz[i+1],0.0)) nodehz = net.node[indhz[i+1]]; approxEq(nodehz.gammaz,nhz[i+1]) || error("nodehz $(nodehz.number) gammaz $(nodehz.gammaz) should match the gammaz in net.ht $(nhz[i+1]) and it does not") edges = hybridEdges(nodehz); edges[1].hybrid || error("bad diamond I situation, node $(nodehz.number) has gammaz $(nodehz.gammaz) so should be linked to hybrid edge, but it is not") node = edges[1].node[edges[1].isChild1 ? 1 : 2]; node.hybrid || error("hybrid edge $(edge.number) pointing at tree node $(node.number)") deleteHybridizationUpdate!(net,node) break elseif(approxEq(nhz[i+1],1.0)) error("gammaz for node $(net.node[indhz[i]].number) is $(nhz[i]) but the other gammaz is $(nhz[i+1]), the sum should be less than 1.0 (movedownlevel)") end end i += 2 end end @debug begin printEverything(net); "printed everything" end CHECKNET && checkNet(net) end # checks if there are problems in estimated net.ht: # returns flag for h, flag for t, flag for hz function isValid(net::HybridNetwork) nh = net.ht[1 : net.numHybrids - net.numBad] k = sum([e.istIdentifiable ? 1 : 0 for e in net.edge]) nt = net.ht[net.numHybrids - net.numBad + 1 : net.numHybrids - net.numBad + k] nhz = net.ht[net.numHybrids - net.numBad + k + 1 : length(net.ht)] #println("isValid on nh $(nh), nt $(nt), nhz $(nhz)") return all((n->(0<n<1 && !approxEq(n,0.0) && !approxEq(n,1.0))), nh), all((n->(n>0 && !approxEq(n,0.0))), nt), all((n->(0<n<1 && !approxEq(n,0.0) && !approxEq(n,1.0))), nhz) end # checks if there are problems in estimated net.ht: # returns flag for h, flag for t, flag for hz function isValid(nh::Vector{Float64},nt::Vector{Float64},nhz::Vector{Float64}) #println("isValid on nh $(nh), nt $(nt), nhz $(nhz)") return all((n->(0<n<1 && !approxEq(n,0.0) && !approxEq(n,1.0))), nh), all((n->(n>0 && !approxEq(n,0.0))), nt), all((n->(0<n<1 && !approxEq(n,0.0) && !approxEq(n,1.0))), nhz) end # optTopRuns! and optTopRun1! do *not* modify currT0 """ Road map for various functions behind [`snaq!`](@ref) snaq! optTopRuns! optTopRun1! optTopLevel! optBL! All return their optimized network. - [`snaq!`](@ref) calls `optTopRuns!` once, after a deep copy of the starting network. If the data contain multiple alleles from a given species, `snaq!` first expands the leaf for that species into 2 separate leaves, and merges them back into a single leaf after calling `optTopRuns!`. - `optTopRuns!` calls [`optTopRun1!`](@ref) several (`nrun`) times. assumes level-1 network with >0 branch lengths. assumes same tips in network as in data: i.e. 2 separate tips per species that has multiple alleles. each call to `optTopRun1!` gets the same starting network. - `optTopRun1!` calls `optTopLevel!` once, after deep copying + changing the starting network slightly. - `optTopLevel!` calls `optBL!` various times and proposes new network with various moves. """ function optTopRuns!(currT0::HybridNetwork, liktolAbs::Float64, Nfail::Integer, d::DataCF, hmax::Integer, ftolRel::Float64, ftolAbs::Float64, xtolRel::Float64, xtolAbs::Float64, verbose::Bool, closeN ::Bool, Nmov0::Vector{Int}, runs::Integer, outgroup::AbstractString, rootname::AbstractString, seed::Integer, probST::Float64) writelog = true writelog_1proc = false if (rootname != "") julialog = string(rootname,".log") logfile = open(julialog,"w") juliaout = string(rootname,".out") if Distributed.nprocs() == 1 writelog_1proc = true juliaerr = string(rootname,".err") errfile = open(juliaerr,"w") end else writelog = false logfile = stdout # used in call to optTopRun1! end str = """optimization of topology, BL and inheritance probabilities using: hmax = $(hmax), tolerance parameters: ftolRel=$(ftolRel), ftolAbs=$(ftolAbs), xtolAbs=$(xtolAbs), xtolRel=$(xtolRel). max number of failed proposals = $(Nfail), liktolAbs = $(liktolAbs). """ if outgroup != "none" str *= "Outgroup: $(outgroup) (for rooting at the final step)\n" end str *= (writelog ? "rootname for files: $(rootname)\n" : "no output files\n") str *= "BEGIN: $(runs) runs on starting tree $(writeTopologyLevel1(currT0,true))\n" if Distributed.nprocs()>1 str *= " using $(Distributed.nprocs()) processors\n" end if (writelog) write(logfile,str) flush(logfile) end print(stdout,str) print(stdout, Dates.format(Dates.now(), "yyyy-mm-dd H:M:S.s") * "\n") # if 1 proc: time printed to logfile at start of every run, not here. if(seed == 0) t = time()/1e9 a = split(string(t),".") seed = parse(Int,a[2][end-4:end]) #better seed based on clock end if (writelog) write(logfile,"\nmain seed $(seed)\n") flush(logfile) else print(stdout,"\nmain seed $(seed)\n"); end Random.seed!(seed) seeds = [seed;round.(Integer,floor.(rand(runs-1)*100000))] if writelog && !writelog_1proc for i in 1:runs # workers won't write to logfile write(logfile, "seed: $(seeds[i]) for run $(i)\n") end flush(logfile) end tstart = time_ns() bestnet = Distributed.pmap(1:runs) do i # for i in 1:runs logstr = "seed: $(seeds[i]) for run $(i), $(Dates.format(Dates.now(), "yyyy-mm-dd H:M:S.s"))\n" print(stdout, logstr) msg = "\nBEGIN SNaQ for run $(i), seed $(seeds[i]) and hmax $(hmax)" if writelog_1proc # workers can't write on streams opened by master write(logfile, logstr * msg) flush(logfile) end verbose && print(stdout, msg) GC.gc(); try best = optTopRun1!(currT0, liktolAbs, Nfail, d, hmax,ftolRel, ftolAbs, xtolRel, xtolAbs, verbose, closeN , Nmov0,seeds[i],logfile,writelog_1proc,probST); logstr *= "\nFINISHED SNaQ for run $(i), -loglik of best $(best.loglik)\n" verbose && print(stdout, logstr) if writelog_1proc logstr = writeTopologyLevel1(best,outgroup=outgroup, printID=true, multall=!isempty(d.repSpecies)) ## printID=true calls setNonIdBL logstr *= "\n---------------------\n" write(logfile, logstr) flush(logfile) end return best catch(err) msg = "\nERROR found on SNaQ for run $(i) seed $(seeds[i]): $(err)\n" logstr = msg * "\n---------------------\n" if writelog_1proc write(logfile, logstr) flush(logfile) write(errfile, msg) flush(errfile) end @warn msg # returns: nothing end end tend = time_ns() # in nanoseconds telapsed = round(convert(Int, tend-tstart) * 1e-9, digits=2) # in seconds writelog_1proc && close(errfile) msg = "\n" * Dates.format(Dates.now(), "yyyy-mm-dd H:M:S.s") if writelog write(logfile, msg) elseif verbose print(stdout, msg) end filter!(n -> n !== nothing, bestnet) # remove "nothing", failed runs if length(bestnet)>0 ind = sortperm([n.loglik for n in bestnet]) bestnet = bestnet[ind] maxNet = bestnet[1]::HybridNetwork # tell type to compiler else error("all runs failed") end ## need to do this before setting BL to -1 if (writelog && !isTree(maxNet)) ## only do networks file if maxNet is not tree println("best network and networks with different hybrid/gene flow directions printed to .networks file") julianet = string(rootname,".networks") s = open(julianet,"w") otherNet = [] try otherNet = undirectedOtherNetworks(maxNet, outgroup=outgroup, insideSnaq=true) # do not use rootMaxNet catch write(s,"""Bug found when trying to obtain networks with modified hybrid/gene flow direction. To help debug these cases and get other similar estimated networks for your analysis, please send the estimated network in parenthetical format to [email protected] with the subject BUG IN NETWORKS FILE. You can get this network from the .out file. You can also post this problem to the google group, or github issues. Thank you!\n""") end write(s,"$(writeTopologyLevel1(maxNet,printID=true, multall=!isempty(d.repSpecies))), with -loglik $(maxNet.loglik) (best network found, remaining sorted by log-pseudolik; the smaller, the better)\n") # best network is included first: for score comparison with other networks foundBad = false for n in otherNet try optBL!(n,d) ##optBL MUST have network with all the attributes, and undirectedOtherNetworks will return "good" networks that way if(n.numBad > 0) # to keep gammaz info in parenthetical description of bad diamond I for nod in n.hybrid setGammaBLfromGammaz!(nod,n) # get t and γ that are compatible with estimated gammaz values end end setNonIdBL!(n) catch n.loglik = -1 foundBad = true end end ## to sort otherNet by loglik value: ind = sortperm([n.loglik for n in otherNet]) otherNet = otherNet[ind] for n in otherNet write(s,"$(writeTopologyLevel1(n,printID=true, multall=!isempty(d.repSpecies))), with -loglik $(n.loglik)\n") end foundBad && write(s,"Problem found when optimizing branch lengths for some networks, left loglik as -1. Please report this issue on github. Thank you!") close(s) end setNonIdBL!(maxNet) if outgroup != "none" try checkRootPlace!(maxNet,outgroup=outgroup) ## keeps all attributes catch err if isa(err, RootMismatch) println("RootMismatch: ", err.msg, """\nThe estimated network has hybrid edges that are incompatible with the desired outgroup. Reverting to an admissible root position. """) else println("error trying to reroot: ", err.msg); end checkRootPlace!(maxNet,verbose=false) # message about problem already printed above end else checkRootPlace!(maxNet,verbose=false) #leave root in good place after snaq end writelog && write(logfile,"\nMaxNet is $(writeTopologyLevel1(maxNet,printID=true, multall=!isempty(d.repSpecies))) \nwith -loglik $(maxNet.loglik)\n") print(stdout,"\nMaxNet is $(writeTopologyLevel1(maxNet,printID=true, multall=!isempty(d.repSpecies))) \nwith -loglik $(maxNet.loglik)\n") s = writelog ? open(juliaout,"w") : stdout str = writeTopologyLevel1(maxNet, printID=true,multall=!isempty(d.repSpecies)) * """ -Ploglik = $(maxNet.loglik) Dendroscope: $(writeTopologyLevel1(maxNet,di=true, multall=!isempty(d.repSpecies))) Elapsed time: $(telapsed) seconds, $(runs) attempted runs ------- List of estimated networks for all runs (sorted by log-pseudolik; the smaller, the better): """ for n in bestnet str *= " " str *= (outgroup == "none" ? writeTopologyLevel1(n,printID=true, multall=!isempty(d.repSpecies)) : writeTopologyLevel1(n,outgroup=outgroup, printID=true, multall=!isempty(d.repSpecies))) str *= ", with -loglik $(n.loglik)\n" end str *= "-------\n" write(s,str); writelog && close(s) # to close juliaout file (but not stdout!) writelog && close(logfile) return maxNet end optTopRuns!(currT::HybridNetwork, d::DataCF, hmax::Integer, runs::Integer, outgroup::AbstractString, rootname::AbstractString) = optTopRuns!(currT, likAbs, numFails, d, hmax,fRel, fAbs, xRel, xAbs, false, true, numMoves, runs, outgroup,rootname,0,0.3) optTopRuns!(currT::HybridNetwork, d::DataCF, hmax::Integer, runs::Integer, outgroup::AbstractString) = optTopRuns!(currT, likAbs, numFails, d, hmax,fRel, fAbs, xRel, xAbs, false, true, numMoves, runs, outgroup,"optTopRuns",0,0.3) optTopRuns!(currT::HybridNetwork, d::DataCF, hmax::Integer, runs::Integer) = optTopRuns!(currT, likAbs, numFails, d, hmax,fRel, fAbs, xRel, xAbs, false, true, numMoves, runs, "none", "optTopRuns",0,0.3) optTopRuns!(currT::HybridNetwork, d::DataCF, hmax::Integer) = optTopRuns!(currT, likAbs, numFails, d, hmax,fRel, fAbs, xRel, xAbs, false, true, numMoves, 10, "none", "optTopRuns",0,0.3) # picks a modification of starting topology and calls optTopLevel # the seed is used as is # does *not* modify currT0. Modifies data d only. """ optTopRun1!(net, liktolAbs, Nfail, d::DataCF, hmax, etc.) The function will run 1 run by modifying the starting topology and calling `optTopLevel`. See [`optTopRuns!`](@ref) for a roadmap. `probST` (default in snaq is 0.3) is the probability of starting one run at the same input tree. So, with probability `1-probST`, we will change the topology by a NNI move on a tree edge without neighbor hybrid. If the starting topology is a network, then with probability `1-probST` it will also modify one randomly chosen hybrid edge: with prob 0.5, the function will move origin, with prob 0.5 will do move target. If there are multiple alleles (`d.repSpecies` not empty), then the function has to check that the starting topology does not violate the multiple alleles condition. After modifying the starting topology with NNI and/or move origin/target, `optTopLevel` is called. """ function optTopRun1!(currT0::HybridNetwork, liktolAbs, Nfail::Integer, d::DataCF, hmax::Integer, ftolRel::Float64, ftolAbs::Float64, xtolRel::Float64, xtolAbs::Float64, verbose::Bool, closeN ::Bool, Nmov0::Vector{Int},seed::Integer, logfile::IO, writelog::Bool, probST::Float64) Random.seed!(seed) currT = deepcopy(currT0); if(probST<1.0 && rand() < 1-probST) # modify starting tree by a nni move suc = NNIRepeat!(currT,10); #will try 10 attempts to do an nni move, if set to 1, hard to find it depending on currT if(!isempty(d.repSpecies)) suc2 = checkTop4multAllele(currT) suc &= suc2 if(!suc2) currT = deepcopy(currT0) end end writelog && suc && write(logfile," changed starting topology by NNI move\n") if(!isTree(currT)) if(rand() < 1-probST) # modify starting network by mvorigin, mvtarget with equal prob currT0 = deepcopy(currT) # to go back if new topology does not work for mult alleles if(currT.numHybrids == 1) ind = 1 else ind = 0 while(ind == 0 || ind > length(currT.hybrid)) ind = round(Integer,rand()*length(currT.hybrid)); end end if(rand()<0.5) suc = moveOriginUpdateRepeat!(currT,currT.hybrid[ind],true) if(!isempty(d.repSpecies)) suc2 = checkTop4multAllele(currT) suc &= suc2 if(!suc2) currT = deepcopy(currT0) end end writelog && suc && write(logfile,"\n changed starting network by move origin") else suc = moveTargetUpdateRepeat!(currT,currT.hybrid[ind],true) if(!isempty(d.repSpecies)) suc2 = checkTop4multAllele(currT) suc &= suc2 if(!suc2) currT = deepcopy(currT0) end end writelog && suc && write(logfile,"\n changed starting network by move target") end end end end GC.gc(); optTopLevel!(currT, liktolAbs, Nfail, d, hmax,ftolRel, ftolAbs, xtolRel, xtolAbs, verbose, closeN , Nmov0,logfile,writelog) end optTopRun1!(currT::HybridNetwork, d::DataCF, hmax::Integer) = optTopRun1!(currT, likAbs, numFails, d, hmax,fRel, fAbs, xRel, xAbs, false, true, numMoves, 0,stdout,true,0.3) optTopRun1!(currT::HybridNetwork, d::DataCF, hmax::Integer, seed::Integer) = optTopRun1!(currT, likAbs, numFails, d, hmax,fRel, fAbs, xRel, xAbs, false, true, numMoves,seed,stdout,true,0.3) # function SNaQ: it calls directly optTopRuns but has a prettier name # it differs from optTopRuns in that it creates a deepcopy of the starting topology, # check that it's of level 1 and updates its BL. # only currT and d are necessary, all others are optional and have default values """ snaq!(T::HybridNetwork, d::DataCF) Estimate the network (or tree) to fit observed quartet concordance factors (CFs) stored in a DataCF object, using maximum pseudo-likelihood. A level-1 network is assumed. The search starts from topology `T`, which can be a tree or a network with no more than `hmax` hybrid nodes. The function name ends with ! because it modifies the CF data `d` by updating its attributes `expCF`: CFs expected under the network model. It does *not* modify `T`. The quartet pseudo-deviance is the negative log pseudo-likelihood, up to an additive constant, such that a perfect fit corresponds to a deviance of 0.0. Output: - estimated network in file `.out` (also in `.log`): best network overall and list of networks from each individual run. - the best network and modifications of it, in file `.networks`. All networks in this file have the same undirected topology as the best network, but have different hybrid/gene flow directions. These other networks are reported with their pseudo-likelihood scores, because non-identifiability issues can cause them to have very similar scores, and because SNaQ was shown to estimate the undirected topology accurately but not the direction of hybridization in cases of near non-identifiability. - if any error occurred, file `.err` provides information (seed) to reproduce the error. There are many optional arguments, including - `hmax` (default 1): maximum number of hybridizations allowed - `verbose` (default false): if true, print information about the numerical optimization - `runs` (default 10): number of independent starting points for the search - `outgroup` (default none): outgroup taxon to root the estimated topology at the very end - `filename` (default "snaq"): root name for the output files (`.out`, `.err`). If empty (""), files are *not* created, progress log goes to the screen only (standard out). - `seed` (default 0 to get it from the clock): seed to replicate a given search - `probST` (default 0.3): probability to start from `T` at each given run. With problability 1-probST, the search is started from an NNI modification of `T` along a tree edge with no hybrid neighbor, with a possible modification of one reticulation if `T` has one. - `updateBL` (default true): If true and if `T` is a tree, the branch lengths in `T` are first optimized roughly with [`updateBL!`](@ref) by using the average CF of all quartets defining each branch and back-calculating the coalescent units. The following optional arguments control when to stop the optimization of branch lengths and γ's on each individual candidate network. Defaults are in parentheses: - `ftolRel` (1e-6) and `ftolAbs` (1e-6): relative and absolute differences of the network score between the current and proposed parameters, - `xtolRel` (1e-2) and `xtolAbs` (1e-3): relative and absolute differences between the current and proposed parameters. Greater values will result in a less thorough but faster search. These parameters are used when evaluating candidate networks only. The following optional arguments control when to stop proposing new network topologies: - `Nfail` (75): maximum number of times that new topologies are proposed and rejected (in a row). - `liktolAbs` (1e-6): the proposed network is accepted if its score is better than the current score by at least liktolAbs. Lower values of `Nfail` and greater values of `liktolAbs` and `ftolAbs` would result in a less thorough but faster search. At the end, branch lengths and γ's are optimized on the last "best" network with different and very thorough tolerance parameters: 1e-12 for ftolRel, 1e-10 for ftolAbs, xtolRel, xtolAbs. See also: [`topologyMaxQPseudolik!`](@ref) to optimize parameters on a fixed topology, and [`topologyQPseudolik!`](@ref) to get the deviance (pseudo log-likelihood up to a constant) of a fixed topology with fixed parameters. Reference: Claudia Solís-Lemus and Cécile Ané (2016). Inferring phylogenetic networks with maximum pseudolikelihood under incomplete lineage sorting. [PLoS Genetics](http://journals.plos.org/plosgenetics/article?id=10.1371/journal.pgen.1005896) 12(3):e1005896 """ function snaq!(currT0::HybridNetwork, d::DataCF; hmax=1::Integer, liktolAbs=likAbs::Float64, Nfail=numFails::Integer, ftolRel=fRel::Float64, ftolAbs=fAbs::Float64, xtolRel=xRel::Float64, xtolAbs=xAbs::Float64, verbose=false::Bool, closeN=true::Bool, Nmov0=numMoves::Vector{Int}, runs=10::Integer, outgroup="none"::AbstractString, filename="snaq"::AbstractString, seed=0::Integer, probST=0.3::Float64, updateBL=true::Bool) 0.0<=probST<=1.0 || error("probability to keep the same starting topology should be between 0 and 1: $(probST)") currT0.numTaxa >= 5 || error("cannot estimate hybridizations in topologies with fewer than 5 taxa, this topology has $(currT0.numTaxa) taxa") typemax(Int) > length(d.quartet) || @warn "the number of rows / 4-taxon sets exceeds the max integer of type $Int ($(typemax(Int))). High risk of overflow errors..." # need a clean starting net. fixit: maybe we need to be more thorough here # yes, need to check that everything is ok because it could have been cleaned and then modified tmp1, tmp2 = taxadiff(d,currT0) length(tmp1)==0 || error("these taxa appear in one or more quartets, but not in the starting topology: $tmp1") if length(tmp2)>0 s = "these taxa will be deleted from the starting topology, they have no quartet CF data:\n" for tax in tmp2 s *= " $tax"; end @warn s currT0 = deepcopy(currT0) for tax in tmp2 deleteleaf!(currT0, tax) end end startnet = readTopologyUpdate(writeTopologyLevel1(currT0)) # update all level-1 things flag = checkNet(startnet,true) # light checking only flag && error("starting topology suspected not level-1") try checkNet(startnet) catch err err.msg = "starting topology not a level 1 network:\n" * err.msg rethrow(err) end if updateBL && isTree(startnet) updateBL!(startnet,d) end # for the case of multiple alleles: expand into two leaves quartets like sp1 sp1 sp2 sp3. if !isempty(d.repSpecies) expandLeaves!(d.repSpecies,startnet) startnet = readTopologyLevel1(writeTopologyLevel1(startnet)) # dirty fix to multiple alleles problem with expandLeaves end net = optTopRuns!(startnet, liktolAbs, Nfail, d, hmax, ftolRel,ftolAbs, xtolRel,xtolAbs, verbose, closeN, Nmov0, runs, outgroup, filename,seed,probST) if(!isempty(d.repSpecies)) mergeLeaves!(net) end # checking root again after merging leaves. This is a band aid. # To-do: rethink order of check root and merge leaves inside optTopRuns if outgroup != "none" try checkRootPlace!(net,outgroup=outgroup) ## keeps all attributes catch err if isa(err, RootMismatch) println("RootMismatch: ", err.msg, """\nThe estimated network has hybrid edges that are incompatible with the desired outgroup. Reverting to an admissible root position. """) else println("error trying to reroot: ", err.msg); end checkRootPlace!(net,verbose=false) # message about problem already printed above end else checkRootPlace!(net,verbose=false) #leave root in good place after snaq end return net end ## function to modify the starting topology currT0 by an NNI move with probability 1-probST ## if starting topology is a network: also do move Origin/Target with prob 1-probST, each 50-50 chance ## if outgroup!="none" means that the root placement matters at the end (on outgroup), used for max parsimony function findStartingTopology!(currT0::HybridNetwork, probST::Float64, multAll::Bool, writelog::Bool, logfile::IO; outgroup="none"::Union{AbstractString,Integer}) currT = deepcopy(currT0); if probST<1.0 && rand() < 1-probST # modify starting tree by a nni move suc = NNIRepeat!(currT,10); #will try 10 attempts to do an nni move, if set to 1, hard to find it depending on currT if multAll suc2 = checkTop4multAllele(currT) suc &= suc2 if !suc2 currT = deepcopy(currT0) end end writelog && suc && write(logfile," changed starting topology by NNI move\n") if !isTree(currT) if rand() < 1-probST # modify starting network by mvorigin, mvtarget with equal prob currT0 = deepcopy(currT) # to go back if new topology does not work for mult alleles ind = rand(1:currT.numHybrids) mymove = ( rand()<0.5 ? "origin" : "target" ) mymove_fun! = (mymove=="origin" ? moveOriginUpdateRepeat! : moveTargetUpdateRepeat!) suc = mymove_fun!(currT,currT.hybrid[ind],true) if multAll suc2 = checkTop4multAllele(currT) suc &= suc2 if !suc2 currT = deepcopy(currT0) end end writelog && suc && write(logfile,"\n changed starting network by move $(mymove)") end end end GC.gc(); if outgroup != "none" currT1 = deepcopy(currT) ##just to check, but we do not want a rooted network at the end try rootatnode!(currT1,outgroup) catch err if isa(err, RootMismatch) println("RootMismatch: ", err.msg, """\nThe starting topology has hybrid edges that are incompatible with the desired outgroup. Reverting to original starting topology. """) else println("error trying to reroot: ", err.msg); end currT = deepcopy(currT0) end end return currT end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
47124
""" SubstitutionModel Abstract type for substitution models, using a continous time Markov model on a phylogeny. Adapted from [SubstitutionModels.jl](https://github.com/BioJulia/SubstitutionModels.jl/) in BioJulia. For variable rates, see [`RateVariationAcrossSites`](@ref) For sub types, see [`NucleicAcidSubstitutionModel`](@ref), [`TraitSubstitutionModel`](@ref) All these models are supposed to have fields `rate` and `eigeninfo`. """ abstract type SubstitutionModel end #ideally, we'd like this to be SubstitutionModels.SubstitionModel const SM = SubstitutionModel const Qmatrix = StaticArrays.SMatrix{4, 4, Float64} const Pmatrix = StaticArrays.MMatrix{4, 4, Float64} const Bmatrix = StaticArrays.MMatrix{2, 2, Float64} """ TraitSubstitutionModel For subtypes, see [`BinaryTraitSubstitutionModel`](@ref), [`EqualRatesSubstitutionModel`](@ref), [`TwoBinaryTraitSubstitutionModel`](@ref) """ abstract type TraitSubstitutionModel{T} <: SubstitutionModel end #this accepts labels const TSM = TraitSubstitutionModel{T} where T #T is type of labels """ NucleicAcidSubstitutionModel Adapted from [SubstitutionModels.jl](https://github.com/BioJulia/SubstitutionModels.jl/) in BioJulia. The same [`Q`](@ref) and [`P`](@ref) function names are used for the transition rates and probabilities. For subtypes, see [`JC69`](@ref), [`HKY85`](@ref) """ abstract type NucleicAcidSubstitutionModel <: SubstitutionModel end const NASM = NucleicAcidSubstitutionModel """ nparams(model) Number of parameters for a given trait evolution model (length of field `model.rate`). """ nparams(obj::SM) = error("nparams not defined for $(typeof(obj)).") """ setrates!(model, rates) update rates then call [`seteigeninfo!`](@ref) to update a model's eigeninfo """ function setrates!(obj::SM, rates::AbstractVector) obj.rate[:] = rates seteigeninfo!(obj) end """ seteigeninfo!(obj) Calculate eigenvalue & eigenfector information for a substitution model (SM) object (as needed to calculate transition rate matrices) and store this info within the object. """ function seteigeninfo!(obj::SM) error("seteigeninfo! not finalized yet for generic substitution models") # eig_vals, eig_vecs = eigen(Q(obj)) #this assumes that every SM has an eigeninfo and has # obj.eigeninfo[:] = eig_vals, eig_vecs, inv(eig_vecs) # then make P! use seteigeninfo! by for a generic SM end """ getlabels(model) State labels of a substitution model. """ function getlabels(obj::SM) error("Model must be of type TraitSubstitutionModel or NucleicAcidSubstitutionModel. Got $(typeof(obj))") end """ nstates(model) Number of character states for a given evolution model. """ nstates(obj::SM) = error("nstates not defined for $(typeof(obj)).") """ For example, this is 4 for a `NucleicAcidSubstitutionModel`. ```jldoctest julia> nstates(JC69([0.03], false)) 4 julia> nstates(HKY85([.5], [0.25, 0.25, 0.25, 0.25])) 4 ``` """ function nstates(obj::NASM) return 4::Int end function getlabels(obj::TSM) return obj.label end """ for a given [`NucleicAcidSubstitutionModel`](@ref), labels are symbols from [BioSymbols](https://github.com/BioJulia/BioSymbols.jl). For now, only ACGTs are allowed. (When fitting data, any ambiguity code in the data would be treated as missing value). # examples ```jldoctest julia> getlabels(JC69([0.03], false)) 4-element Vector{BioSymbols.DNA}: DNA_A DNA_C DNA_G DNA_T julia> getlabels(HKY85([.5], repeat([0.25], 4))) 4-element Vector{BioSymbols.DNA}: DNA_A DNA_C DNA_G DNA_T ``` """ function getlabels(::NASM) return [BioSymbols.DNA_A, BioSymbols.DNA_C, BioSymbols.DNA_G, BioSymbols.DNA_T] end """ Q(model) Substitution rate matrix for a given substitution model: Q[i,j] is the rate of transitioning from state i to state j. """ Q(obj::SM) = error("rate matrix Q not defined for $(typeof(obj)).") """ showQ(IO, model) Print the Q matrix to the screen, with trait states as labels on rows and columns. adapted from prettyprint function by mcreel, found 2017/10 at https://discourse.julialang.org/t/display-of-arrays-with-row-and-column-names/1961/6 """ function showQ(io::IO, obj::SM) M = Q(obj) pad = max(8,maximum(length(getlabels(obj))+1)) for i = 1:size(M,2) # print the header print(io, lpad(getlabels(obj)[i],(i==1 ? 2*pad : pad), " ")) end for i = 1:size(M,1) # print one row per state print(io, "\n") if getlabels(obj) != "" print(io, lpad(getlabels(obj)[i],pad," ")) end for j = 1:size(M,2) if j == i print(io, lpad("*",pad," ")) else fmt = "%$(pad).4f" @eval(@printf($io,$fmt,$(M[i,j]))) end end end end """ P(obj, t) Probability transition matrix for a [`TraitSubstitutionModel`](@ref), of the form P[1,1] ... P[1,k] . . . . P[k,1] ... P[k,k] where P[i,j] is the probability of ending in state j after time t, given that the process started in state i. see also: [`P!`](@ref). HKY example: ```jldoctest julia> m1 = HKY85([0.5], [0.20, 0.30, 0.30, 0.20]) HKY85 Substitution Model base frequencies: [0.2, 0.3, 0.3, 0.2] relative rate version with transition/tranversion ratio kappa = 0.5, scaled so that there is one substitution per unit time rate matrix Q: A C G T A * 0.4839 0.2419 0.3226 C 0.3226 * 0.4839 0.1613 G 0.1613 0.4839 * 0.3226 T 0.3226 0.2419 0.4839 * julia> PhyloNetworks.P(m1, 0.2) 4×4 StaticArraysCore.MMatrix{4, 4, Float64, 16} with indices SOneTo(4)×SOneTo(4): 0.81592 0.0827167 0.0462192 0.0551445 0.0551445 0.831326 0.0827167 0.0308128 0.0308128 0.0827167 0.831326 0.0551445 0.0551445 0.0462192 0.0827167 0.81592 ``` Juke-Cantor example: ```jldoctest julia> m1 = JC69([1.]); julia> PhyloNetworks.P(m1, 0.2) 4×4 StaticArraysCore.MMatrix{4, 4, Float64, 16} with indices SOneTo(4)×SOneTo(4): 0.824446 0.0585179 0.0585179 0.0585179 0.0585179 0.824446 0.0585179 0.0585179 0.0585179 0.0585179 0.824446 0.0585179 0.0585179 0.0585179 0.0585179 0.824446 ``` """ @inline function P(obj::SM, t::Float64) t >= 0.0 || error("substitution model: >=0 branch lengths are needed") k = nstates(obj) Pmat = MMatrix{k,k,Float64}(undef) return P!(Pmat, obj, t) end """ P!(Pmat::AbstractMatrix, obj::SM, t::Float64) Fill in the input matrix `Pmat` with the transition rates to go from each state to another in time `t`, according to rates in `Q`. see also: [`P`](@ref). ```jldoctest julia> m1 = BinaryTraitSubstitutionModel([1.0,2.0], ["low","high"]) Binary Trait Substitution Model: rate low→high α=1.0 rate high→low β=2.0 julia> PhyloNetworks.P!(Matrix{Float64}(undef,2,2), m1, 0.3) # fills an uninitialized 2x2 matrix of floats 2×2 Matrix{Float64}: 0.80219 0.19781 0.39562 0.60438 julia> m2 = JC69([1.]); julia> PhyloNetworks.P!(Matrix{Float64}(undef,4,4), m2, 0.2) 4×4 Matrix{Float64}: 0.824446 0.0585179 0.0585179 0.0585179 0.0585179 0.824446 0.0585179 0.0585179 0.0585179 0.0585179 0.824446 0.0585179 0.0585179 0.0585179 0.0585179 0.824446 ``` """ @inline function P!(Pmat::AbstractMatrix, obj::SM, t::Float64) Pmat[:] = exp(Q(obj) * t) return Pmat end """ BinaryTraitSubstitutionModel(α, β [, label]) Model for binary traits, that is, with 2 states. Default labels are "0" and "1". α is the rate of transition from "0" to "1", and β from "1" to "0". """ struct BinaryTraitSubstitutionModel{T} <: TraitSubstitutionModel{T} # fixit: back to mutable struct? rate::Vector{Float64} label::Vector{T} # most often: T = String, but could be BioSymbols.DNA eigeninfo::Vector{Float64} function BinaryTraitSubstitutionModel{T}(rate::Vector{Float64}, label::Vector{T}, eigeninfo::Vector{Float64}) where T #Warning: this constructor should not be used directly. Use it with the constructors below. @assert length(rate) == 2 "binary state: need 2 rates" rate[1] >= 0. || error("parameter α must be non-negative") rate[2] >= 0. || error("parameter β must be non-negative") @assert length(label) == 2 "need 2 labels exactly" new(rate, label, eigeninfo) end end const BTSM = BinaryTraitSubstitutionModel{T} where T function BinaryTraitSubstitutionModel(r::AbstractVector, label::AbstractVector) obj = BinaryTraitSubstitutionModel{eltype(label)}(r::AbstractVector, label::AbstractVector, zeros(3)) # Vector{Float64}(undef,3) for julia v1.0 seteigeninfo!(obj) return obj end BinaryTraitSubstitutionModel(α::Float64, β::Float64, label::AbstractVector) = BinaryTraitSubstitutionModel([α,β], label) BinaryTraitSubstitutionModel(α::Float64, β::Float64) = BinaryTraitSubstitutionModel(α, β, ["0", "1"]) """ for a [`BinaryTraitSubstitutionModel`]: store eigenvalue (q_01+q_10) and stationary distribution """ function seteigeninfo!(obj::BTSM) ab = obj.rate[1] + obj.rate[2] #eigenvalue = -(a+b) ab > 0. || error("α+β must be positive") p0 = obj.rate[2]/ab # asymptotic frequency of state "0" p1 = obj.rate[1]/ab # asymptotic frequency of state "1" obj.eigeninfo[1] = ab obj.eigeninfo[2] = p0 obj.eigeninfo[3] = p1 end """ for a `BinaryTraitSubstitutionModel`, this is 2: ```jldoctest julia> m1 = BinaryTraitSubstitutionModel([1.0,2.0], ["low","high"]) Binary Trait Substitution Model: rate low→high α=1.0 rate high→low β=2.0 julia> nstates(m1) 2 ``` """ function nstates(::BTSM) return 2::Int end nparams(::BTSM) = 2::Int """ For a BinaryTraitSubstitutionModel, the rate matrix Q is of the form: -α α β -β """ @inline function Q(obj::BTSM) return Bmatrix(-obj.rate[1], obj.rate[2], obj.rate[1], -obj.rate[2]) end function Base.show(io::IO, obj::BTSM) str = "Binary Trait Substitution Model:\n" str *= "rate $(obj.label[1])→$(obj.label[2]) α=$(round(obj.rate[1], digits=5))\n" str *= "rate $(obj.label[2])→$(obj.label[1]) β=$(round(obj.rate[2], digits=5))" print(io, str) end function P!(Pmat::AbstractMatrix, obj::BTSM, t::Float64) e1 = exp(-obj.eigeninfo[1]*t) a0= obj.eigeninfo[2]*e1 a1= obj.eigeninfo[3]*e1 Pmat[1,1] = obj.eigeninfo[2]+a1 Pmat[2,1] = obj.eigeninfo[2]-a0 Pmat[1,2] = obj.eigeninfo[3]-a1 Pmat[2,2] = obj.eigeninfo[3]+a0 return Pmat end """ TwoBinaryTraitSubstitutionModel(rate [, label]) [`TraitSubstitutionModel`](@ref) for two binary traits, possibly correlated. Default labels are "x0", "x1" for trait 1, and "y0", "y1" for trait 2. If provided, `label` should be a vector of size 4, listing labels for trait 1 first then labels for trait 2. `rate` should be a vector of substitution rates of size 8. rate[1],...,rate[4] describe rates of changes in trait 1. rate[5],...,rate[8] describe rates of changes in trait 2. In the transition matrix, trait combinations are listed in the following order: x0-y0, x0-y1, x1-y0, x1-y1. # example ```julia model = TwoBinaryTraitSubstitutionModel([2.0,1.2,1.1,2.2,1.0,3.1,2.0,1.1], ["carnivory", "noncarnivory", "wet", "dry"]); model using PhyloPlots plot(model) # to visualize states and rates ``` """ struct TwoBinaryTraitSubstitutionModel <: TraitSubstitutionModel{String} rate::Vector{Float64} label::Vector{String} function TwoBinaryTraitSubstitutionModel(α, label) all( x -> x >= 0., α) || error("rates must be non-negative") @assert length(α)==8 "need 8 rates" @assert length(label)==4 "need 4 labels for all combinations of 2 binary traits" new(α, [string(label[1], "-", label[3]), # warning: original type of 'label' lost here string(label[1], "-", label[4]), string(label[2], "-", label[3]), string(label[2], "-", label[4])]) end end const TBTSM = TwoBinaryTraitSubstitutionModel TwoBinaryTraitSubstitutionModel(α::Vector{Float64}) = TwoBinaryTraitSubstitutionModel(α, ["x0", "x1", "y0", "y1"]) nstates(::TBTSM) = 4::Int nparams(::TBTSM) = 8::Int function Q(obj::TBTSM) M = fill(0.0,(4,4)) a = obj.rate M[1,3] = a[1] M[3,1] = a[2] M[2,4] = a[3] M[4,2] = a[4] M[1,2] = a[5] M[2,1] = a[6] M[3,4] = a[7] M[4,3] = a[8] M[1,1] = -M[1,2] - M[1,3] M[2,2] = -M[2,1] - M[2,4] M[3,3] = -M[3,4] - M[3,1] M[4,4] = -M[4,3] - M[4,2] return M end function Base.show(io::IO, obj::TBTSM) print(io, "Substitution model for 2 binary traits, with rate matrix:\n") showQ(io, obj) end """ EqualRatesSubstitutionModel(numberStates, α, labels) [`TraitSubstitutionModel`](@ref) for traits with any number of states and equal substitution rates α between all states. Default labels are "1","2",... # example ```jldoctest julia> m1 = EqualRatesSubstitutionModel(2, [1.0], ["low","high"]) Equal Rates Substitution Model with k=2, all rates equal to α=1.0. rate matrix Q: low high low * 1.0000 high 1.0000 * ``` """ struct EqualRatesSubstitutionModel{T} <: TraitSubstitutionModel{T} k::Int rate::Vector{Float64} label::Vector{T} eigeninfo::Vector{Float64} function EqualRatesSubstitutionModel{T}(k::Int, rate::Vector{Float64}, label::Vector{T}, eigeninfo::Vector{Float64}) where T @assert length(label)==k "incorrect number of labels: k=$k, labels: $label" @assert k >= 2 "need k >= 2 category labels. labels: $label" @assert length(rate)==1 "rate must be a vector of length 1" rate[1] > 0 || error("parameter α (rate) must be positive") new(k, rate, label, eigeninfo) end end const ERSM = EqualRatesSubstitutionModel{T} where T function EqualRatesSubstitutionModel(k::Int, rate::Vector{Float64}, label::AbstractVector) obj = EqualRatesSubstitutionModel{eltype(label)}(k::Int, rate::Vector{Float64}, label::AbstractVector, zeros(1)) # Vector{Float64}(undef,3) for julia v1.0 seteigeninfo!(obj) return obj end EqualRatesSubstitutionModel(k::Int, α::Float64, label::AbstractVector) = EqualRatesSubstitutionModel(k,[α],label) EqualRatesSubstitutionModel(k::Int, α::Float64) = EqualRatesSubstitutionModel(k, [α], string.(1:k)) """ for a [`EqualRatesSubstitutionModel`]: store lambda = k/(k-1), where k is the number of states """ function seteigeninfo!(obj::ERSM) q = (obj.k/(obj.k-1.0)) obj.eigeninfo[1] = q end function nstates(obj::ERSM) return obj.k end nparams(::ERSM) = 1::Int function Base.show(io::IO, obj::ERSM) str = "Equal Rates Substitution Model with k=$(obj.k),\n" str *= "all rates equal to α=$(round(obj.rate[1], digits=5)).\n" str *= "rate matrix Q:\n" print(io, str) showQ(io, obj) end function Q(obj::ERSM) #this might be wrong, doesnt match ERSM proof α = obj.rate[1] M = fill(α, (obj.k,obj.k)) d = -(obj.k-1) * α for i in 1:obj.k M[i,i] = d end return M end """ randomTrait(model, t, start) randomTrait!(end, model, t, start) Simulate traits along one edge of length t. `start` must be a vector of integers, each representing the starting value of one trait. The bang version (ending with !) uses the vector `end` to store the simulated values. # Examples ```jldoctest julia> m1 = BinaryTraitSubstitutionModel(1.0, 2.0) Binary Trait Substitution Model: rate 0→1 α=1.0 rate 1→0 β=2.0 julia> using Random; Random.seed!(13); julia> randomTrait(m1, 0.2, [1,2,1,2,2]) 5-element Vector{Int64}: 1 2 1 1 2 ``` """ function randomTrait(obj::TSM, t::Float64, start::AbstractVector{Int}) res = Vector{Int}(undef, length(start)) randomTrait!(res, obj, t, start) end @doc (@doc randomTrait) randomTrait! function randomTrait!(endTrait::AbstractVector{Int}, obj::TSM, t::Float64, start::AbstractVector{Int}) Pt = P(obj, t) k = size(Pt, 1) # number of states w = [aweights(Pt[i,:]) for i in 1:k] for i in 1:length(start) endTrait[i] =sample(1:k, w[start[i]]) end return endTrait end """ randomTrait(model, net; ntraits=1, keepInternal=true, checkPreorder=true) Simulate evolution of discrete traits on a rooted evolutionary network based on the supplied evolutionary model. Trait sampling is uniform at the root. optional arguments: - `ntraits`: number of traits to be simulated (default: 1 trait). - `keepInternal`: if true, export character states at all nodes, including internal nodes. if false, export character states at tips only. output: - matrix of character states with one row per trait, one column per node; these states are *indices* in `model.label`, not the trait labels themselves. - vector of node labels (for tips) or node numbers (for internal nodes) in the same order as columns in the character state matrix # examples ```jldoctest julia> m1 = BinaryTraitSubstitutionModel(1.0, 2.0, ["low","high"]); julia> net = readTopology("(((A:4.0,(B:1.0)#H1:1.1::0.9):0.5,(C:0.6,#H1:1.0::0.1):1.0):3.0,D:5.0);"); julia> using Random; Random.seed!(95); julia> trait, lab = randomTrait(m1, net) ([1 2 … 1 1], ["-2", "D", "-3", "-6", "C", "-4", "H1", "B", "A"]) julia> trait 1×9 Matrix{Int64}: 1 2 1 1 2 2 1 1 1 julia> lab 9-element Vector{String}: "-2" "D" "-3" "-6" "C" "-4" "H1" "B" "A" ``` """ function randomTrait(obj::TSM, net::HybridNetwork; ntraits=1::Int, keepInternal=true::Bool, checkPreorder=true::Bool) net.isRooted || error("net needs to be rooted for preorder recursion") if(checkPreorder) preorder!(net) end nnodes = net.numNodes M = Matrix{Int}(undef, ntraits, nnodes) # M[i,j]= trait i for node j randomTrait!(M,obj,net) if !keepInternal M = getTipSubmatrix(M, net, indexation=:cols) # subset columns only. rows=traits nodeLabels = [n.name for n in net.nodes_changed if n.leaf] else nodeLabels = [n.name == "" ? string(n.number) : n.name for n in net.nodes_changed] end return M, nodeLabels end function randomTrait!(M::Matrix, obj::TSM, net::HybridNetwork) recursionPreOrder!(net.nodes_changed, M, # updates M in place updateRootRandomTrait!, updateTreeRandomTrait!, updateHybridRandomTrait!, obj) end function updateRootRandomTrait!(V::AbstractArray, i::Int, obj) sample!(1:nstates(obj), view(V, :, i)) # uniform at the root return end function updateTreeRandomTrait!(V::Matrix, i::Int,parentIndex::Int,edge::Edge, obj) randomTrait!(view(V, :, i), obj, edge.length, view(V, :, parentIndex)) end function updateHybridRandomTrait!(V::Matrix, i::Int, parentIndex1::Int, parentIndex2::Int, edge1::Edge, edge2::Edge, obj) randomTrait!(view(V, :, i), obj, edge1.length, view(V, :, parentIndex1)) tmp = randomTrait(obj, edge2.length, view(V, :, parentIndex2)) for j in 1:size(V,1) # loop over traits if V[j,i] == tmp[j] # both parents of the hybrid node have the same trait continue # skip the rest: go to next trait end if rand() > edge1.gamma V[j,i] = tmp[j] # switch to inherit trait of parent 2 end end end """ JC69(rate, relative) Jukes Cantor (1969) nucleic acid substitution model, which has a single rate parameter. `rate` corresponds to the absolute diagonal elements, that is, the rate of change (to any of the other 2 states). Individual rates are `rate`/3. If `relative` is true (default), the transition matrix [`Q`](@ref) is normalized to an average of 1 transition per unit of time: in which case `rate` is set to 1.0. # examples ```jldoctest julia> m1 = JC69([0.25], false) Jukes and Cantor 69 Substitution Model, absolute rate version off-diagonal rates equal to 0.25/3. rate matrix Q: A C G T A * 0.0833 0.0833 0.0833 C 0.0833 * 0.0833 0.0833 G 0.0833 0.0833 * 0.0833 T 0.0833 0.0833 0.0833 * julia> nstates(m1) 4 julia> nparams(m1) 1 julia> m2 = JC69([0.5]) Jukes and Cantor 69 Substitution Model, relative rate version off-diagonal rates equal to 1/3 rate matrix Q: A C G T A * 0.3333 0.3333 0.3333 C 0.3333 * 0.3333 0.3333 G 0.3333 0.3333 * 0.3333 T 0.3333 0.3333 0.3333 * julia> nparams(m2) 0 ``` """ struct JC69 <: NucleicAcidSubstitutionModel rate::Vector{Float64} relative::Bool eigeninfo::Vector{Float64} #TODO change to MVector, see if its faster function JC69(rate::Vector{Float64}, relative::Bool, eigeninfo::Vector{Float64}) #Warning: this constructor should not be used directly. Use the constructor below # which will call this. 0 <= length(rate) <= 1 || error("rate not a valid length for a JC69 model") all(rate .> 0.0) || error("All elements of rate must be positive for a JC69 model") new(rate, relative, eigeninfo) end end function JC69(rate::AbstractVector, relative=true::Bool) obj = JC69(rate, relative, zeros(1)) seteigeninfo!(obj) return obj end JC69(rate::Float64, relative=true::Bool) = JC69([rate], relative) """ for [`JC69`](@ref): store lambda = 4/3 (if relative) or rate * 4/3 (absolute). """ function seteigeninfo!(obj::JC69) if obj.relative lambda = (4.0/3.0) #eigen value of the Q matrix else lambda = (4.0/3.0)*obj.rate[1] #eigen value of the Q matrix end obj.eigeninfo[1] = lambda end function Base.show(io::IO, obj::JC69) str = "Jukes and Cantor 69 Substitution Model,\n" if obj.relative == true str *= "relative rate version\n" str *= "off-diagonal rates equal to 1/3\n" else str *= "absolute rate version\n" str *= "off-diagonal rates equal to $(round(obj.rate[1], digits=5))/3.\n" end str *= "rate matrix Q:\n" print(io, str) showQ(io, obj) end """ HKY85(rate, pi, relative) A nucleic acid substitution model based on Hasegawa et al. 1985 substitution model. `rate` should be a vector of 1 or 2 rates, and `pi` a vector of 4 probabilities summing to 1. If `relative` is false, the 2 rates represent the transition rate and the transversion rate, α and β. If `relative` is true (default), only the first rate is used and represents the transition/transversion ratio: κ=α/β. The rate transition matrix Q is normalized to have 1 change / unit of time on average, i.e. the absolute version of Q is divided by `2(piT*piC + piA*piG)α + 2(piY*piR)β`. `nparams` returns 1 or 2. In other words: the stationary distribution is not counted in the number of parameters (and `fitdiscrete` does not optimize the pi values at the moment). # examples ```jldoctest julia> m1 = HKY85([.5], [0.20, 0.30, 0.30, 0.20]) HKY85 Substitution Model base frequencies: [0.2, 0.3, 0.3, 0.2] relative rate version with transition/tranversion ratio kappa = 0.5, scaled so that there is one substitution per unit time rate matrix Q: A C G T A * 0.4839 0.2419 0.3226 C 0.3226 * 0.4839 0.1613 G 0.1613 0.4839 * 0.3226 T 0.3226 0.2419 0.4839 * julia> nstates(m1) 4 julia> m2 = HKY85([0.5, 0.5], [0.20, 0.30, 0.30, 0.20], false) HKY85 Substitution Model base frequencies: [0.2, 0.3, 0.3, 0.2] absolute rate version with transition/transversion ratio kappa = a/b = 1.0 with rates a = 0.5 and b = 0.5 rate matrix Q: A C G T A * 0.1500 0.1500 0.1000 C 0.1000 * 0.1500 0.1000 G 0.1000 0.1500 * 0.1000 T 0.1000 0.1500 0.1500 * ``` """ struct HKY85 <: NucleicAcidSubstitutionModel rate::Vector{Float64} pi::Vector{Float64} relative::Bool eigeninfo::Vector{Float64} function HKY85(rate::Vector{Float64}, pi::Vector{Float64}, relative::Bool, eigeninfo::Vector{Float64}) #Warning: this constructor should not be used directly. Use the constructor below, # which will call this. all(rate .> 0.) || error("All elements of rate must be positive") 1 <= length(rate) <= 2 || error("rate has invalid length for HKY85 model") if relative length(rate) == 1 || error("the relative version of HKY85 takes a single rate") else length(rate) == 2 || error("the absolute version of HKY85 takes 2 rates") end length(pi) == 4 || error("pi must be of length 4") all(0. .< pi.< 1.) || error("All base proportions must be between 0 and 1") isapprox(sum(pi), 1.; atol = 1e-12) || error("Base proportions must sum to 1.") new(rate, pi, relative, eigeninfo) end end function HKY85(rate::AbstractVector, pi::Vector{Float64}, relative=true::Bool) obj = HKY85(rate, pi, relative, zeros(5)) seteigeninfo!(obj) return obj end HKY85(rate::Float64, pi::Vector{Float64}) = HKY85([rate], pi, true) """ for [`HKY85`](@ref): store piR, piY, the 2 non-zero eigenvalues and a scaling factor """ function seteigeninfo!(obj::HKY85) piA = obj.pi[1]; piC = obj.pi[2]; piG = obj.pi[3]; piT = obj.pi[4] piR = piA + piG piY = piT + piC obj.eigeninfo[4] = piR obj.eigeninfo[5] = piY a = obj.rate[1] # relative: a = kappa. absolute: a = kappa*b if obj.relative # b=1/lambda: scaling factor to have branch lengths in substitutions/site b = 1.0 / (2*a*(piT*piC + piA*piG) + 2*(piY*piR)) obj.eigeninfo[2] = - (piR * a + piY) * b # lambda_R obj.eigeninfo[3] = - (piY * a + piR) * b # lambda_Y else b = obj.rate[2] obj.eigeninfo[2] = -((piR * a) + (piY * b)) obj.eigeninfo[3] = -((piY * a) + (piR * b)) end obj.eigeninfo[1] = -b end function Base.show(io::IO, obj::HKY85) str = "HKY85 Substitution Model base frequencies: $(obj.pi)\n" if obj.relative str *= "relative rate version with transition/tranversion ratio kappa = $(round(obj.rate[1], digits=5))," str *= "\n scaled so that there is one substitution per unit time\n" else str *= "absolute rate version with transition/transversion ratio kappa = a/b = " str *= "$(round(obj.rate[1]/obj.rate[2], digits=5))" str *= "\n with rates a = $(round(obj.rate[1], digits=5)) and b = $(round(obj.rate[2], digits=5))\n" end str *= "rate matrix Q:\n" print(io, str) showQ(io, obj) end """ for `JC69` model: 0 if relative, 1 if absolute """ function nparams(obj::JC69) return (obj.relative ? 0 : 1) end """ for `HKY85` model: 1 if relative, 2 if absolute """ function nparams(obj::HKY85) return (obj.relative ? 1 : 2) end @inline function Q(obj::JC69) if obj.relative Q0 = 1.0/3.0 #we multiply by 1/3 to make branch lengths interpretable as avg(#substitutions) (pi-weighted avg of diagonal is -1) else Q0 = (1.0/3.0)*obj.rate[1] end return Qmatrix(-3*Q0, Q0, Q0, Q0, Q0, -3*Q0, Q0, Q0, Q0, Q0, -3*Q0, Q0, Q0, Q0, Q0, -3*Q0) end @inline function Q(obj::HKY85) piA = obj.pi[1]; piC = obj.pi[2]; piG = obj.pi[3]; piT = obj.pi[4] piR = piA + piG piY = piT + piC if obj.relative k = obj.rate[1] lambda = (2*k*(piT*piC + piA*piG) + 2*(piY*piR)) # for sub/time interpretation. see HKY docstring Q₁ = piA/lambda Q₂ = k * Q₁ Q₃ = piC/lambda Q₄ = k * Q₃ Q₆ = piG/lambda Q₅ = k * Q₆ Q₇ = piT/lambda Q₈ = k * Q₇ Q₉ = -(Q₃ + Q₅ + Q₇) Q₁₀ = -(Q₁ + Q₆ + Q₈) Q₁₁ = -(Q₂ + Q₃ + Q₇) Q₁₂ = -(Q₁ + Q₄ + Q₆) else #GT, AT, CG, and AC are less likely (transversions) a = obj.rate[1]; b = obj.rate[2] Q₁ = b * piA Q₂ = a * piA Q₃ = b * piC Q₄ = a * piC Q₅ = a * piG Q₆ = b * piG Q₇ = b * piT Q₈ = a * piT Q₉ = -(Q₃ + Q₅ + Q₇) #AA Q₁₀ = -(Q₁ + Q₆ + Q₈) #CC Q₁₁ = -(Q₂ + Q₃ + Q₇) #GG Q₁₂ = -(Q₁ + Q₄ + Q₆) #TT end return Qmatrix(Q₉, Q₁, Q₂, Q₁, #ACGT Q₃, Q₁₀, Q₃, Q₄, Q₅, Q₆, Q₁₁, Q₆, Q₇, Q₈, Q₇, Q₁₂) end function P!(Pmat::AbstractMatrix, obj::JC69, t::Float64) P0 = 0.25 + 0.75 * exp(-t * obj.eigeninfo[1]) #lambda P1 = 0.25 - 0.25 * exp(-t * obj.eigeninfo[1]) # P1 off-diagonal and P0 on diagonal Pmat[1,1] = P0; Pmat[2,1] = P1; Pmat[3,1] = P1; Pmat[4,1] = P1 Pmat[1,2] = P1; Pmat[2,2] = P0; Pmat[3,2] = P1; Pmat[4,2] = P1 Pmat[1,3] = P1; Pmat[2,3] = P1; Pmat[3,3] = P0; Pmat[4,3] = P1 Pmat[1,4] = P1; Pmat[2,4] = P1; Pmat[3,4] = P1; Pmat[4,4] = P0 return Pmat end function P!(Pmat::AbstractMatrix, obj::HKY85, t::Float64) #returns ACGT piA = obj.pi[1]; piC = obj.pi[2]; piG = obj.pi[3]; piT = obj.pi[4] piR = obj.eigeninfo[4] piY = obj.eigeninfo[5] # expm1(x) = e^x-1 accurately. important when t is small ebm1 = expm1(obj.eigeninfo[1] * t) # -b eigevalue eRm1 = expm1(obj.eigeninfo[2] * t) # lambda_R eYm1 = expm1(obj.eigeninfo[3] * t) # lambda_Y # transversions P_TA_CA = - piA * ebm1 # C or T -> A: P{A|T} = P{A|C} P_AC_GC = - piC * ebm1 # P{C|A} = P{C|G} P_TG_CG = - piG * ebm1 # P{G|T} = P{G|C} P_AT_GT = - piT * ebm1 # P{T|A} = P{T|G} # transitions: A<->G (R) or C<->T (Y) tmp = (ebm1 * piY - eRm1) / piR P_GA = piA * tmp # P{A|G} P_AG = piG * tmp # P{G|A} tmp = (ebm1 * piR - eYm1) / piY P_TC = piC * tmp # P{C|T} P_CT = piT * tmp # P{T|C} # no change transv = P_AC_GC + P_AT_GT # transversion to Y: - piY * ebm1 P_AA = 1.0 - P_AG - transv P_GG = 1.0 - P_GA - transv transv = P_TA_CA + P_TG_CG # transversion to R P_CC = 1.0 - P_CT - transv P_TT = 1.0 - P_TC - transv # fill in the P matrix Pmat[1,1] = P_AA Pmat[2,2] = P_CC Pmat[3,3] = P_GG Pmat[4,4] = P_TT # to A: j=1 Pmat[2,1] = P_TA_CA Pmat[3,1] = P_GA Pmat[4,1] = P_TA_CA # to C: j=2 Pmat[1,2] = P_AC_GC Pmat[3,2] = P_AC_GC Pmat[4,2] = P_TC # to G: j=3 Pmat[1,3] = P_AG Pmat[2,3] = P_TG_CG Pmat[4,3] = P_TG_CG # to T: j=4 Pmat[1,4] = P_AT_GT Pmat[2,4] = P_CT Pmat[3,4] = P_AT_GT return Pmat end abstract type RateVariationAcrossSites end """ RateVariationAcrossSites(; pinv=0.0, alpha=Inf, ncat=4) Model for variable substitution rates across sites (or across traits) using the discrete Gamma model (+G, Yang 1994, Journal of Molecular Evolution) or the invariable-sites model (+I, Hasegawa, Kishino & Yano 1985 J Mol Evol). Both types of rate variation can be combined (+G+I, Gu, Fu & Li 1995, Mol Biol Evol) but this is discouraged (Jia, Lo & Ho 2014 PLOS One). Using rate variation increases the number of parameters by one (+G or +I) or by two (+G+I). Because the mean of the desired distribution or rates is 1, we use a Gamma distribution with shape α and scale θ=1/α (rate β=α) if no invariable sites, or scale θ=1/(α(1-pinv)), that is rate β=α(1-pinv) with a proportion pinv of invariable sites. The shape parameter is referred to as alpha here. The Gamma distribution is discretized into `ncat` categories. In each category, the category's rate multiplier is a normalized quantile of the gamma distribution. ```jldoctest julia> rv = RateVariationAcrossSites() Rate variation across sites: discretized Gamma categories for Gamma discretization: 1 rates: [1.0] julia> nparams(rv) 0 julia> typeof(rv) PhyloNetworks.RVASGamma{1} julia> rv = RateVariationAcrossSites(alpha=1.0, ncat=4) Rate variation across sites: discretized Gamma alpha: 1.0 categories for Gamma discretization: 4 rates: [0.146, 0.513, 1.071, 2.27] julia> typeof(rv) PhyloNetworks.RVASGamma{4} julia> PhyloNetworks.setalpha!(rv, 2.0) Rate variation across sites: discretized Gamma alpha: 2.0 categories for Gamma discretization: 4 rates: [0.319, 0.683, 1.109, 1.889] julia> nparams(rv) 1 julia> rv = RateVariationAcrossSites(pinv=0.3) Rate variation across sites: +I (invariable sites) pinv: 0.3 rates: [0.0, 1.429] julia> nparams(rv) 1 julia> typeof(rv) PhyloNetworks.RVASInv julia> PhyloNetworks.setpinv!(rv, 0.05) Rate variation across sites: +I (invariable sites) pinv: 0.05 rates: [0.0, 1.053] julia> rv = RateVariationAcrossSites(pinv=0.3, alpha=2.0, ncat=4) Rate variation across sites: discretized Gamma+I pinv: 0.3 alpha: 2.0 categories for Gamma discretization: 4 rates: [0.0, 0.456, 0.976, 1.584, 2.698] probabilities: [0.3, 0.175, 0.175, 0.175, 0.175] julia> nparams(rv) 2 julia> typeof(rv) PhyloNetworks.RVASGammaInv{5} julia> PhyloNetworks.setalpha!(rv, 3.0) Rate variation across sites: discretized Gamma+I pinv: 0.3 alpha: 3.0 categories for Gamma discretization: 4 rates: [0.0, 0.6, 1.077, 1.584, 2.454] probabilities: [0.3, 0.175, 0.175, 0.175, 0.175] julia> PhyloNetworks.setpinv!(rv, 0.05) Rate variation across sites: discretized Gamma+I pinv: 0.05 alpha: 3.0 categories for Gamma discretization: 4 rates: [0.0, 0.442, 0.793, 1.167, 1.808] probabilities: [0.05, 0.238, 0.238, 0.238, 0.238] julia> PhyloNetworks.setpinvalpha!(rv, 0.1, 5.0) Rate variation across sites: discretized Gamma+I pinv: 0.1 alpha: 5.0 categories for Gamma discretization: 4 rates: [0.0, 0.593, 0.91, 1.221, 1.721] probabilities: [0.1, 0.225, 0.225, 0.225, 0.225] ``` """ function RateVariationAcrossSites(; pinv=0.0::Float64, alpha=Inf64::Float64, ncat=1::Int) ncat>1 && alpha == Inf && error("please specify ncat=1 or alpha<Inf") # ncat is 1 or α is finite here if pinv==0.0 # if α is infinite: no rate variation, RVASGamma with ncat=1 return RVASGamma(alpha, ncat) end # pinv>0 here if ncat == 1 return RVASInv(pinv) end # pinv>0, ncat>1 and α is finite here return RVASGammaInv(pinv, alpha, ncat) end """ RateVariationAcrossSites(rvsymbol::Symbol, ncategories=4::Int) Default model for rate variation across site, specified by a symbol: - `:noRV` for no rate variation - `:G` or `:Gamma` for gamma-distributed rates - `:I` or `:Inv` for two categories: invariable and variable - `:GI` or `:GI` for both. """ function RateVariationAcrossSites(rvsymbol::Symbol, ncategories=4::Int) if rvsymbol == :noRV rvas = RateVariationAcrossSites() elseif rvsymbol == :Gamma || rvsymbol == :G rvas = RateVariationAcrossSites(alpha=1.0, ncat=ncategories) elseif rvsymbol == :GammaInv || rvsymbol == :GI rvas = RateVariationAcrossSites(pinv=0.05, alpha=1.0, ncat=ncategories) elseif rvsymbol == :Inv || rvsymbol == :I rvas = RateVariationAcrossSites(pinv=0.05) else error("model $rvsymbol unknown or not implemented yet:\nrate variation model needs to be :Gamma or :Inv or :GammaInv") end end struct RVASGamma{S} <: RateVariationAcrossSites # S = ncat, and size of vectors alpha::StaticArrays.MVector{1,Float64} # mutable ncat::Int ratemultiplier::StaticArrays.MVector{S,Float64} lograteweight::StaticArrays.SVector{S,Float64} # will be uniform: log(1/ncat) end function RVASGamma(alpha=1.0::Float64, ncat=4::Int) @assert ncat > 0 "ncat must be 1 or greater" uniflw = -log(ncat) # = log(1/ncat) obj = RVASGamma{ncat}( StaticArrays.MVector{1,Float64}(alpha), ncat, StaticArrays.MVector{ncat,Float64}(undef), # rates StaticArrays.SVector{ncat,Float64}([uniflw for i in 1:ncat])) if ncat == 1 obj.ratemultiplier[1] = 1.0 else setalpha!(obj, alpha) # checks for alpha >= 0 end return obj end struct RVASInv <: RateVariationAcrossSites pinv::StaticArrays.MVector{1,Float64} # mutable ratemultiplier::StaticArrays.MVector{2,Float64} lograteweight::StaticArrays.MVector{2,Float64} end function RVASInv(pinv=0.05::Float64) r = StaticArrays.MVector{2,Float64}(undef) # rates r[1] = 0.0 # invariable category obj = RVASInv(StaticArrays.MVector{1,Float64}(pinv), r, StaticArrays.MVector{2,Float64}(undef)) # log weights setpinv!(obj, pinv) # checks for 0 <= pinv < 1 return obj end struct RVASGammaInv{S} <: RateVariationAcrossSites # S = ncat+1, and size of vectors pinv::StaticArrays.MVector{1,Float64} # mutable alpha::StaticArrays.MVector{1,Float64} # mutable ncat::Int ratemultiplier::StaticArrays.MVector{S,Float64} lograteweight::StaticArrays.MVector{S,Float64} end function RVASGammaInv(pinv::Float64, alpha::Float64, ncat::Int) @assert ncat > 1 "ncat must be 2 or more for the Gamma+I model" s = 1+ncat r = StaticArrays.MVector{s,Float64}(undef) # rates r[1] = 0.0 # invariable category obj = RVASGammaInv{s}( StaticArrays.MVector{1,Float64}(pinv), StaticArrays.MVector{1,Float64}(alpha), ncat, r, StaticArrays.MVector{s,Float64}(undef)) # log weights setpinvalpha!(obj, pinv, alpha) # checks for α >= 0 and 0 <= pinv < 1 return obj end """ setalpha!(obj, alpha) Set the shape parameter `alpha` in a RateVariationAcrossSites model `obj`, and update the rate multipliers accordingly. Return the modified object. """ function setalpha!(obj::RVASGamma{S}, alpha::Float64) where S @assert alpha >= 0 "alpha must be >= 0" obj.alpha[1] = alpha gammadist = Distributions.Gamma(alpha, 1/alpha) cumprob = 1/(2obj.ncat) .+ (0:(obj.ncat-1))/obj.ncat # cumulative prob to discretize Gamma obj.ncat > 1 || return obj rv = obj.ratemultiplier for (i,cp) in enumerate(cumprob) @inbounds rv[i] = quantile(gammadist, cp) end rv ./= mean(rv) return obj end function setalpha!(obj::RVASGammaInv{S}, alpha::Float64) where S @assert alpha >= 0 "alpha must be >= 0" obj.alpha[1] = alpha ncat = obj.ncat pvar = 1.0 - obj.pinv[1] gammadist = Distributions.Gamma(alpha, 1/alpha) r0 = quantile.(gammadist, 1/(2ncat) .+ (0:(ncat-1))/ncat) r0 ./= mean(r0) for i in 2:(ncat+1) @inbounds obj.ratemultiplier[i] = r0[i-1]/pvar end return obj end """ setpinv!(obj, pinv) Set the proportion of invariable sites `pinv` in a RateVariationAcrossSites model `obj`, and update the rate multipliers & weights accordingly. For `RVASInvGamma` objects, the original rate multipliers are assumed correct, according to the original `pinv` value. Return the modified object. """ function setpinv!(obj::RVASInv, pinv::Float64) @assert 0.0 <= pinv < 1.0 "pinv must be in [0,1)" obj.pinv[1] = pinv pvar = 1.0-pinv # 0 not okay here: ratemultiplier would be infinite obj.lograteweight[1] = log(pinv) # -Inf is okay obj.lograteweight[2] = log(pvar) obj.ratemultiplier[2] = 1.0/pvar # to get an average rate = 1 return obj end function setpinv!(obj::RVASGammaInv{S}, pinv::Float64) where S @assert 0.0 <= pinv < 1.0 "pinv must be in [0,1)" ncat = obj.ncat pvar = 1.0-pinv # 0 not okay here: ratemultiplier would be infinite pvarratio = (1.0-obj.pinv[1])/pvar # old p_variable / new p_variable obj.pinv[1] = pinv obj.lograteweight[1] = log(pinv) # -Inf is okay uniflw = -log(ncat)+log(pvar) for i in 2:(ncat+1) @inbounds obj.lograteweight[i] = uniflw @inbounds obj.ratemultiplier[i] *= pvarratio # gamma rate / p_variable end return obj end """ setpinvalpha!(obj, pinv, alpha) Set the proportion of invariable sites `pinv` and the `alpha` parameter for the discretized gamma distribution in a model `obj` of type `RVASGammaInv{S}`. Update the rate multipliers & weights accordingly. The mean of the distribution is constrained to 1. Return the modified object. """ function setpinvalpha!(obj::RVASGammaInv{S}, pinv::Float64, alpha::Float64) where S @assert 0.0 <= pinv < 1.0 "pinv must be in [0,1)" @assert alpha >= 0 "alpha must be >= 0" obj.alpha[1] = alpha obj.pinv[1] = pinv obj.lograteweight[1] = log(pinv) # -Inf is okay ncat = obj.ncat gammadist = Distributions.Gamma(alpha, 1/alpha) r0 = quantile.(gammadist, 1/(2ncat) .+ (0:(ncat-1))/ncat) r0 ./= mean(r0) pvar = 1.0-pinv # 0 not okay here: ratemultiplier would be infinite uniflw = -log(ncat)+log(pvar) for i in 2:(ncat+1) @inbounds obj.lograteweight[i] = uniflw @inbounds obj.ratemultiplier[i] = r0[i-1]/pvar end return obj end function Base.show(io::IO, obj::RVASGamma{S}) where S str = "Rate variation across sites: discretized Gamma\n" if length(obj.ratemultiplier)>1 str *= "alpha: $(round(obj.alpha[1], digits=5))\n" end str *= "categories for Gamma discretization: $(obj.ncat)\n" str *= "rates: $(round.(obj.ratemultiplier, digits=3))" print(io, str) end function Base.show(io::IO, obj::RVASInv) str = "Rate variation across sites: +I (invariable sites)\n" str *= "pinv: $(round(obj.pinv[1], digits=5))\n" str *= "rates: $(round.(obj.ratemultiplier, digits=3))" print(io, str) end function Base.show(io::IO, obj::RVASGammaInv{S}) where S str = "Rate variation across sites: discretized Gamma+I\n" str *= "pinv: $(round(obj.pinv[1], digits=5))\n" str *= "alpha: $(round(obj.alpha[1], digits=5))\n" str *= "categories for Gamma discretization: $(obj.ncat)\n" str *= "rates: $(round.(obj.ratemultiplier, digits=3))\n" str *= "probabilities: $(round.(exp.(obj.lograteweight), digits=3))" print(io, str) end function nparams(obj::RVASGamma{S}) where S return (obj.ncat == 1 ? 0 : 1) end nparams(::RVASInv) = 1::Int nparams(::RVASGammaInv{S}) where S = 2::Int # ncat must be >1 """ getparameters(obj::RateVariationAcrossSites) Return a copy of the alpha and/or pinv parameters of model `obj`, in a single vector. """ getparameters(obj::RVASInv) = copy(obj.pinv) getparameters(obj::RVASGamma{S}) where S = copy(obj.alpha) getparameters(obj::RVASGammaInv{S}) where S = [obj.pinv[1], obj.alpha[1]] """ setparameters!(obj::RateVariationAcrossSites, par::AbstractVector) Set the values of the alpha and/or pinv parameters of model `obj`. See also [`setalpha!`](@ref), [`setpinv!`](@ref) and [`setpinvalpha!`](@ref) """ setparameters!(obj::RVASInv, par::AbstractVector) = setpinv!(obj, par[1]) setparameters!(obj::RVASGamma{S}, par::AbstractVector) where S = setalpha!(obj, par[1]) setparameters!(obj::RVASGammaInv{S}, par::AbstractVector) where S = setpinvalpha!(obj, par[1], par[2]) """ getparamindex(obj::RateVariationAcrossSites) Indices of parameters in (p_invariable, alpha). """ getparamindex(::RVASInv) = [1] getparamindex(::RVASGamma{S}) where S = [2] getparamindex(::RVASGammaInv{S}) where S = [1,2] """ empiricalDNAfrequencies(DNAdata::AbstractDataFrame, DNAweights, correction=true, useambiguous=true) Estimate base frequencies in DNA data `DNAdata`, ordered ACGT. - `DNAdata`: data frame. All columns are used. If the first column gives species names, find a way to ignore it before calculating empirical frequencies, e.g. `empiricalDNAfrequencies(view(DNAdata, :, 2:size(DNAdata, 2)))`. Data type must be `BioSymbols.DNA` or `Char` or `String`. WARNING: this is checked on the first column only. - `DNAweights`: vector of weights, to weigh each column in `DNAdata`. - `correction`: if `true`, add 1 to each count and 4 to the denominator for a more stable estimator, similar to Bayes prior of 1/4 and the Agresti-Coull interval in binomial estimation. - `useambiguous`: if `true`, ambiguous bases are used (except gaps and Ns). For example, `Y` adds 0.5 weight to `C` and 0.5 weight to `T`. """ function empiricalDNAfrequencies(dnaDat::AbstractDataFrame, dnaWeights::Vector, correctedestimate=true::Bool, useambiguous=true::Bool) # warning: checking first column and first row only dnadat1type = eltype(dnaDat[!,1]) dnadat1type == BioSymbols.DNA || dnadat1type == Char || dnaDat[1,1] ∈ string.(BioSymbols.alphabet(DNA)) || error("empiricalDNAfrequencies requires data of type String, Char, or BioSymbols.DNA") # initialize counts: keys same as BioSymbols.ACGT (which are ordered) prior = correctedestimate ? 1.0 : 0.0 dnacounts = Dict(DNA_A=>prior, DNA_C=>prior, DNA_G=>prior, DNA_T=>prior) convert2dna = dnadat1type != BioSymbols.DNA for j in 1:size(dnaDat, 2) # for each column col = dnaDat[!,j] wt = dnaWeights[j] for nuc in col # for each row if convert2dna nuc = convert(DNA, nuc[1]) # if nuc is a string, nuc[1] = 1st character end if nuc ∈ BioSymbols.ACGT dnacounts[nuc] += wt elseif nuc == DNA_Gap || nuc == DNA_N || !useambiguous continue # to next row # else: ambiguity, uses BioSequences definitions elseif nuc == DNA_M # A or C dnacounts[DNA_A] += 0.5*wt dnacounts[DNA_C] += 0.5*wt elseif nuc == DNA_R # A or G dnacounts[DNA_A] += 0.5*wt dnacounts[DNA_G] += 0.5*wt elseif nuc == DNA_W # A or T/U dnacounts[DNA_A] += 0.5*wt dnacounts[DNA_T] += 0.5*wt elseif nuc == DNA_S # C or G dnacounts[DNA_C] += 0.5*wt dnacounts[DNA_G] += 0.5*wt elseif nuc == DNA_Y # C or T/U dnacounts[DNA_C] += 0.5*wt dnacounts[DNA_T] += 0.5*wt elseif nuc == DNA_K # G or T/U dnacounts[DNA_G] += 0.5*wt dnacounts[DNA_T] += 0.5*wt elseif nuc == DNA_V # A or C or G dnacounts[DNA_A] += wt/3 dnacounts[DNA_C] += wt/3 dnacounts[DNA_G] += wt/3 elseif nuc == DNA_H # A or C or T dnacounts[DNA_A] += wt/3 dnacounts[DNA_C] += wt/3 dnacounts[DNA_T] += wt/3 elseif nuc == DNA_D # A or G or T/U dnacounts[DNA_A] += wt/3 dnacounts[DNA_G] += wt/3 dnacounts[DNA_T] += wt/3 elseif nuc == DNA_B # C or G or T/U dnacounts[DNA_C] += wt/3 dnacounts[DNA_G] += wt/3 dnacounts[DNA_T] += wt/3 end end end totalweight = sum(values(dnacounts)) res = [dnacounts[key]/totalweight for key in BioSymbols.ACGT] # to control the order all(0. .<= res .<= 1.) || error("""weird: empirical base frequency < 0 or > 1""") return res end """ stationary(substitutionmodel) Stationary distribution of a Markov model """ stationary(mod::SM) = error("stationary not defined for $(typeof(mod)).") function stationary(mod::JC69) #for JC, stationary = uniform return [0.25,0.25,0.25,0.25] end function stationary(mod::HKY85) return mod.pi end function stationary(mod::ERSM) #for ERSM, uniform = stationary return [1/mod.k for i in 1:mod.k] end function stationary(mod::BTSM) return [mod.eigeninfo[2], mod.eigeninfo[3]] end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
143654
# 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) error("The mean and variance do must have conforming dimensions.") end if randomRoot && size(sigma) != size(varRoot) error("The root variance and process variance must have the same dimensions.") end if !ismissing(shift) && size(shift.shift, 2) != dim error("The ShiftNet and diffusion process must have the same dimensions.") end return new(mu, sigma, randomRoot, varRoot, shift, L) end end ParamsMultiBM(mu::AbstractArray{Float64, 1}, sigma::AbstractArray{Float64, 2}) = ParamsMultiBM(mu, sigma, false, Diagonal([NaN]), missing, cholesky(sigma).L) function ParamsMultiBM(mu::AbstractArray{Float64, 1}, sigma::AbstractArray{Float64, 2}, shift::ShiftNet) ParamsMultiBM(mu, sigma, false, Diagonal([NaN]), shift, cholesky(sigma).L) end function ParamsMultiBM(mu::AbstractArray{Float64, 1}, sigma::AbstractArray{Float64, 2}, net::HybridNetwork) ParamsMultiBM(mu, sigma, ShiftNet(net, length(mu))) end function process_dim(params::ParamsMultiBM) return length(params.mu) end function Base.show(io::IO, obj::ParamsMultiBM) disp = "$(typeof(obj)):\n" pt = paramstable(obj) if obj.randomRoot disp = disp * "Parameters of a MBD with random root:\n" * pt else disp = disp * "Parameters of a MBD with fixed root:\n" * pt end println(io, disp) end function paramstable(obj::ParamsMultiBM) disp = "mu: $(obj.mu)\nSigma: $(obj.sigma)" 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 function partitionMBDMatrix(M::Matrix{Float64}, dim::Int) means = @view M[1:dim, :] vals = @view M[(dim + 1):(2 * dim), :] return means, vals end ############################################################################### ## Simulation of continuous traits ############################################################################### """ TraitSimulation Result of a trait simulation on an [`HybridNetwork`](@ref) with function [`simulate`](@ref). The following functions and extractors can be applied to it: [`tipLabels`](@ref), `obj[:Tips]`, `obj[:InternalNodes]` (see documentation for function [`getindex(::TraitSimulation, ::Symbol)`](@ref)). The `TraitSimulation` object has fields: `M`, `params`, `model`. """ struct TraitSimulation M::MatrixTopologicalOrder params::ParamsProcess evomodel::AbstractString end function Base.show(io::IO, obj::TraitSimulation) disp = "$(typeof(obj)):\n" disp = disp * "Trait simulation results on a network with $(length(obj.M.tipNames)) tips, using a $(obj.evomodel) model, with parameters:\n" disp = disp * paramstable(obj.params) println(io, disp) end # docstring already in descriptive.jl function tipLabels(obj::TraitSimulation) return tipLabels(obj.M) end """ simulate(net::HybridNetwork, params::ParamsProcess, checkPreorder=true::Bool) Simulate traits on `net` using the parameters `params`. For now, only parameters of type [`ParamsBM`](@ref) (univariate Brownian Motion) and [`ParamsMultiBM`](@ref) (multivariate Brownian motion) are accepted. The simulation using a recursion from the root to the tips of the network, therefore, a pre-ordering of nodes is needed. If `checkPreorder=true` (default), [`preorder!`](@ref) is called on the network beforehand. Otherwise, it is assumed that the preordering has already been calculated. Returns an object of type [`TraitSimulation`](@ref), which has a matrix with the trait expecations and simulated trait values at all the nodes. See examples below for accessing expectations and simulated trait values. # Examples ## Univariate ```jldoctest julia> phy = readTopology("(A:2.5,((U:1,#H1:0.5::0.4):1,(C:1,(D:0.5)#H1:0.5::0.6):1):0.5);"); julia> par = ParamsBM(1, 0.1) # BM with expectation 1 and variance 0.1. ParamsBM: Parameters of a BM with fixed root: mu: 1 Sigma2: 0.1 julia> using Random; Random.seed!(17920921); # for reproducibility julia> sim = simulate(phy, par) # Simulate on the tree. TraitSimulation: Trait simulation results on a network with 4 tips, using a BM model, with parameters: mu: 1 Sigma2: 0.1 julia> traits = sim[:Tips] # Extract simulated values at the tips. 4-element Vector{Float64}: 0.9664650558470932 0.4104321932336118 0.2796524923704289 0.7306692819731366 julia> sim.M.tipNames # name of tips, in the same order as values above 4-element Vector{String}: "A" "U" "C" "D" julia> traits = sim[:InternalNodes] # Extract simulated values at internal nodes. Order: as in sim.M.internalNodeNumbers 5-element Vector{Float64}: 0.5200361297500204 0.8088890626285765 0.9187604100796469 0.711921371091375 1.0 julia> traits = sim[:All] # simulated values at all nodes, ordered as in sim.M.nodeNumbersTopOrder 9-element Vector{Float64}: 1.0 0.711921371091375 0.9187604100796469 0.2796524923704289 0.5200361297500204 0.8088890626285765 0.7306692819731366 0.4104321932336118 0.9664650558470932 julia> traits = sim[:Tips, :Exp] # Extract expected values at the tips (also works for sim[:All, :Exp] and sim[:InternalNodes, :Exp]). 4-element Vector{Float64}: 1.0 1.0 1.0 1.0 ``` ## Multivariate ```jldoctest julia> phy = readTopology("(A:2.5,((B:1,#H1:0.5::0.4):1,(C:1,(V:0.5)#H1:0.5::0.6):1):0.5);"); julia> par = ParamsMultiBM([1.0, 2.0], [1.0 0.5; 0.5 1.0]) # BM with expectation [1.0, 2.0] and variance [1.0 0.5; 0.5 1.0]. ParamsMultiBM: Parameters of a MBD with fixed root: mu: [1.0, 2.0] Sigma: [1.0 0.5; 0.5 1.0] julia> using Random; Random.seed!(17920921); # for reproducibility julia> sim = simulate(phy, par) # simulate on the phylogeny TraitSimulation: Trait simulation results on a network with 4 tips, using a MBD model, with parameters: mu: [1.0, 2.0] Sigma: [1.0 0.5; 0.5 1.0] julia> traits = sim[:Tips] # Extract simulated values at the tips (each column contains the simulated traits for one node). 2×4 Matrix{Float64}: 2.99232 -0.548734 -1.79191 -0.773613 4.09575 0.712958 0.71848 2.00343 julia> traits = sim[:InternalNodes] # simulated values at internal nodes. order: same as in sim.M.internalNodeNumbers 2×5 Matrix{Float64}: -0.260794 -1.61135 -1.93202 0.0890154 1.0 1.46998 1.28614 0.409032 1.94505 2.0 julia> traits = sim[:All]; # 2×9 Matrix: values at all nodes, ordered as in sim.M.nodeNumbersTopOrder julia> sim[:Tips, :Exp] # Extract expected values (also works for sim[:All, :Exp] and sim[:InternalNodes, :Exp]) 2×4 Matrix{Float64}: 1.0 1.0 1.0 1.0 2.0 2.0 2.0 2.0 ``` """ function simulate(net::HybridNetwork, params::ParamsProcess, checkPreorder=true::Bool) if isa(params, ParamsBM) model = "BM" elseif isa(params, ParamsMultiBM) model = "MBD" else error("The 'simulate' function only works for a BM process (for now).") end !ismissing(params.shift) || (params.shift = ShiftNet(net, process_dim(params))) net.isRooted || error("The net needs to be rooted for trait simulation.") !anyShiftOnRootEdge(params.shift) || error("Shifts are not allowed above the root node. Please put all root specifications in the process parameter.") funcs = preorderFunctions(params) M = recursionPreOrder(net, checkPreorder, funcs["init"], funcs["root"], funcs["tree"], funcs["hybrid"], "c", params) TraitSimulation(M, params, model) end function preorderFunctions(::ParamsBM) return Dict("init" => initSimulateBM, "root" => updateRootSimulateBM!, "tree" => updateTreeSimulateBM!, "hybrid" => updateHybridSimulateBM!) end function preorderFunctions(::ParamsMultiBM) return Dict("init" => initSimulateMBD, "root" => updateRootSimulateMBD!, "tree" => updateTreeSimulateMBD!, "hybrid" => updateHybridSimulateMBD!) end function anyShiftOnRootEdge(shift::ShiftNet) nodInd = getShiftRowInds(shift) for n in shift.net.nodes_changed[nodInd] !(getMajorParentEdgeNumber(n) == -1) || return(true) end return(false) end # Initialization of the structure function initSimulateBM(nodes::Vector{Node}, ::Tuple{ParamsBM}) return(zeros(2, length(nodes))) end function initSimulateMBD(nodes::Vector{Node}, params::Tuple{ParamsMultiBM}) n = length(nodes) p = process_dim(params[1]) return zeros(2 * p, n) # [means vals] end # Initialization of the root function updateRootSimulateBM!(M::Matrix, i::Int, params::Tuple{ParamsBM}) params = params[1] if (params.randomRoot) M[1, i] = params.mu # expectation M[2, i] = params.mu + sqrt(params.varRoot) * randn() # random value else M[1, i] = params.mu # expectation M[2, i] = params.mu # random value (root fixed) end end function updateRootSimulateMBD!(M::Matrix{Float64}, i::Int, params::Tuple{ParamsMultiBM}) params = params[1] p = process_dim(params) means, vals = partitionMBDMatrix(M, p) if (params.randomRoot) means[:, i] .= params.mu # expectation vals[:, i] .= params.mu + cholesky(params.varRoot).L * randn(p) # random value else means[:, i] .= params.mu # expectation vals[:, i] .= params.mu # random value end end # Going down to a tree node function updateTreeSimulateBM!(M::Matrix, i::Int, parentIndex::Int, edge::Edge, params::Tuple{ParamsBM}) params = params[1] M[1, i] = M[1, parentIndex] + params.shift.shift[i] # expectation M[2, i] = M[2, parentIndex] + params.shift.shift[i] + sqrt(params.sigma2 * edge.length) * randn() # random value end function updateTreeSimulateMBD!(M::Matrix{Float64}, i::Int, parentIndex::Int, edge::Edge, params::Tuple{ParamsMultiBM}) params = params[1] p = process_dim(params) means, vals = partitionMBDMatrix(M, p) μ = @view means[:, i] val = @view vals[:, i] # μ .= means[:, parentIndex] + params.shift.shift[i, :] μ .= @view means[:, parentIndex] μ .+= @view params.shift.shift[i, :] # val .= sqrt(edge.length) * params.L * randn(p) + vals[:, parentIndex] + params.shift.shift[i, :] mul!(val, params.L, randn(p)) val .*= sqrt(edge.length) val .+= @view vals[:, parentIndex] val .+= params.shift.shift[i, :] end # Going down to an hybrid node function updateHybridSimulateBM!(M::Matrix, i::Int, parentIndex1::Int, parentIndex2::Int, edge1::Edge, edge2::Edge, params::Tuple{ParamsBM}) params = params[1] M[1, i] = edge1.gamma * M[1, parentIndex1] + edge2.gamma * M[1, parentIndex2] # expectation M[2, i] = edge1.gamma * (M[2, parentIndex1] + sqrt(params.sigma2 * edge1.length) * randn()) + edge2.gamma * (M[2, parentIndex2] + sqrt(params.sigma2 * edge2.length) * randn()) # random value end function updateHybridSimulateMBD!(M::Matrix{Float64}, i::Int, parentIndex1::Int, parentIndex2::Int, edge1::Edge, edge2::Edge, params::Tuple{ParamsMultiBM}) params = params[1] p = process_dim(params) means, vals = partitionMBDMatrix(M, p) μ = @view means[:, i] val = @view vals[:, i] μ1 = @view means[:, parentIndex1] μ2 = @view means[:, parentIndex2] v1 = @view vals[:, parentIndex1] v2 = @view vals[:, parentIndex2] # means[:, i] .= edge1.gamma * μ1 + edge2.gamma * μ2 mul!(μ, μ1, edge1.gamma) BLAS.axpy!(edge2.gamma, μ2, μ) # expectation # val .= edge1.gamma * (v1 + sqrt(edge1.length) * params.L * r1) + # edge2.gamma * (v2 + sqrt(edge2.length) * params.L * r2) # random value mul!(val, params.L, randn(p)) val .*= sqrt(edge1.length) val .+= v1 buffer = params.L * randn(p) buffer .*= sqrt(edge2.length) buffer .+= v2 BLAS.axpby!(edge2.gamma, buffer, edge1.gamma, val) # random value end # Extract the vector of simulated values at the tips """ getindex(obj, d) Getting submatrices of an object of type [`TraitSimulation`](@ref). # Arguments * `obj::TraitSimulation`: 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 """ function Base.getindex(obj::TraitSimulation, d::Symbol, w=:Sim::Symbol) inds = siminds(obj.params, w) return getindex(obj.M, d)[inds, :] end function siminds(::ParamsBM, w::Symbol) if w == :Sim return 2 elseif w == :Exp return 1 else error("The argument 'w' must be ':Sim' or ':Exp'. (':$w' was supplied)") end end function siminds(params::ParamsMultiBM, w::Symbol) p = process_dim(params) if w == :Sim return (p + 1):(2 * p) elseif w == :Exp return 1:p else error("The argument 'w' must be ':Sim' or ':Exp'. (':$w' was supplied)") end end ############################################################################### ## Type for models with within-species variation (including measurement error) ############################################################################### """ WithinSpeciesCTM CTM stands for "continuous trait model". Contains the estimated variance components (between-species phylogenetic variance rate and within-species variance) and output from the `NLopt` optimization used in the estimation. ## Fields - `wsp_var`: intra/within-species variance. - `bsp_var`: inter/between-species variance-rate. - `wsp_ninv`: vector of the inverse sample-sizes (e.g. [1/n₁, ..., 1/nₖ], where data from k species was used to fit the model and nᵢ is the no. of observations for the ith species). - `rss`: within-species sum of squares - `optsum`: an [`OptSummary`](@ref) object. """ struct WithinSpeciesCTM "within-species variance η*σ², assumes Normal distribution" wsp_var::Vector{Float64} # vector to make it mutable "between-species variance rate σ², such as from Brownian motion" bsp_var::Vector{Float64} "inverse sample sizes (or precision): 1/(no. of individuals) within each species" wsp_ninv::Vector{Float64} "within-species sum of squares" rss::Float64 "NLopt & NLopt summary object" optsum::OptSummary end """ ContinuousTraitEM Abstract type for evolutionary models for continuous traits, using a continuous-time stochastic process on a phylogeny. For subtypes, see [`BM`](@ref), [`PagelLambda`](@ref), [`ScalingHybrid`](@ref). Each of these subtypes/models has the field `lambda`, whose default value is 1.0. However, the interpretation of this field differs across models. """ abstract type ContinuousTraitEM end # current concrete subtypes: BM, PagelLambda, ScalingHybrid # possible future additions: OU (Ornstein-Uhlenbeck)? """ BM(λ) Brownian Motion, subtype of [`ContinuousTraitEM`](@ref), to model the population mean of a trait (or of the residuals from a linear model). Under the BM model, the population (or species) means have a multivariate normal distribution with covariance matrix = σ²λV, where σ² is the between-species variance-rate (to be estimated), and the matrix V is obtained from [`sharedPathMatrix`](@ref)(net)[:Tips]. λ is set to 1 by default, and is immutable. In future versions, λ may be used to control the scale for σ². On a tree, V is the length of shared ancestry. On a network, the BM model assumes that the trait at a hybrid node is the weighted average of its immediate parents (plus possibly a fixed shift). The weights are the proportion of genes inherited from each parent: the γ parameters of hybrid edges. """ struct BM <: ContinuousTraitEM lambda::Float64 # immutable end BM() = BM(1.0) evomodelname(::BM) = "Brownian motion" """ PagelLambda(λ) Pagel's λ model, subtype of [`ContinuousTraitEM`](@ref), with covariance matrix σ²V(λ). σ² is the between-species variance-rate (to be estimated), and V(λ) = λV + (1-λ)T, where V is the covariance under a Brownian motion [`BM`](@ref) and T is a diagonal matrix containing the total branch length elapsed from the root to each leaf (if the phylogeny is a tree, or more generally if the network is time consistent: the time from the root to a given node does not depend on the path). λ ∈ [0,1] is mutable and may be optimized. It is a measure of phylogenetic signal, that is, how important the given network is for explaining variation in the response. When λ=1, the `PagelLambda` model reduces to the `BM` model. """ mutable struct PagelLambda <: ContinuousTraitEM lambda::Float64 # mutable: can be optimized end PagelLambda() = PagelLambda(1.0) evomodelname(::PagelLambda) = "Pagel's lambda" """ ScalingHybrid(λ) Scaling Hybrid model, subtype of [`ContinuousTraitEM`](@ref), with covariance matrix σ²V(N(λ)). σ² is the between-species variance-rate (to be estimated), V(N) is the Brownian motion [`BM`](@ref) covariance obtained from network N, and N(λ) is a obtained from the input network by rescaling the inheritance parameter γ of all minor edges by the same λ: a minor edge has its original γ changed to λγ, using the same λ at all reticulations. Note that for a major edge with original inheritance γ, the partner minor edge has inheritance γ_minor = 1-γ, so the major edge's inheritance is changed to 1-λγ_minor = λγ+1-λ. For more information: see Bastide (2017) dissertation, section 4.3.2 p.175, available at https://tel.archives-ouvertes.fr/tel-01629648 λ ∈ [0,1] is mutable and may be optimized. It is a measure of how important the reticulations are for explaining variation in the response. When λ=1, the `ScalingHybrid` model reduces to the `BM` model. """ mutable struct ScalingHybrid <: ContinuousTraitEM lambda::Float64 end ScalingHybrid() = ScalingHybrid(1.0) evomodelname(::ScalingHybrid) = "Lambda's scaling hybrid" ############################################################################### ## phylogenetic network regression ############################################################################### """ PhyloNetworkLinearModel <: GLM.LinPredModel Phylogenetic linear model representation. ## Fields `lm`, `V`, `Vy`, `RL`, `Y`, `X`, `logdetVy`, `reml`, `ind`, `nonmissing`, `evomodel`, `model_within` and `formula`. The following syntax pattern can be used to get more information on a specific field: e.g. to find out about the `lm` field, do `?PhyloNetworkLinearModel.lm`. ## Methods applied to fitted models The following StatsBase functions can be applied: `coef`, `nobs`, `vcov`, `stderror`, `confint`, `coeftable`, `dof_residual`, `dof`, `deviance`, `residuals`, `response`, `predict`, `loglikelihood`, `nulldeviance`, `nullloglikelihood`, `r2`, `adjr2`, `aic`, `aicc`, `bic`, `ftest`, `lrtest` etc. The estimated variance-rate and estimated mean of the species-level trait model (see [`ContinuousTraitEM`](@ref)) can be retrieved using [`sigma2_phylo`](@ref) and [`mu_phylo`](@ref) respectively. If relevant, the estimated individual-level/within-species variance can be retrieved using [`sigma2_within`](@ref). The optimized λ parameter for Pagel's λ model (see [`PagelLambda`](@ref)) can be retrieved using [`lambda_estim`](@ref). An ancestral state reconstruction can be performed using [`ancestralStateReconstruction`](@ref). ## Within-species variation The true species/population means for the response trait/variable (or the residuals: conditional on the predictors) are jointly modeled as 𝒩(·, σ²ₛV) where V depends on the trait model (see [`ContinuousTraitEM`](@ref)) and on the species network. σ²ₛ is the between-species variance-rate. Within-species variation is modeled by assuming that the individual-level responses are iid 𝒩(0, σ²ₑ) about the true species means, so that the species-level sample means (conditional on the predictors) are jointly modeled as 𝒩(·, σ²ₛV + σ²ₑD⁻¹), where σ²ₑ is the within-species variance and D⁻¹ is a diagonal matrix whose entries are the inverse sample-sizes (see [`WithinSpeciesCTM`](@ref)). Although the above two models can be expressed in terms of a joint distribution for the species-level sample means (or residuals conditional on the predictors), more data are required to fit a model accounting for within-species variation, that is, a model recognizing that the sample means are estimates of the true population means. To fit a model *without* within-species variation, data on the species means are sufficient. To fit a model *with* within-species variation, we need to have the species means and the standard deviations of the response variable for each species. `phylolm` can fit a model with within-species variation either from species-level statistics ("mean response" and "standard deviation in response") or from individual-level data (in which case the species-level statistics are computed internally). See [`phylolm`](@ref) for more details on these two input choices. In the object, `obj.Y` and `obj.X` are the observed species means. `predict`, `residuals` and `response` return the values at the species level. """ mutable struct PhyloNetworkLinearModel <: GLM.LinPredModel "lm: a GLM.LinearModel object, fitted on the cholesky-tranformed problem" lm::GLM.LinearModel # result of a lm on a matrix "V: a MatrixTopologicalOrder object of the network-induced correlations" V::MatrixTopologicalOrder "Vy: the sub matrix corresponding to the tips and actually used for the correction" Vy::Matrix """RL: a LowerTriangular matrix, the lower Cholesky factor of Vy=RL*RL' obtained with `cholesky(Vy).L`. The data stored in `lm` are RL⁻¹Y and RL⁻¹X. """ RL::LowerTriangular "Y: the vector of data" Y::Vector "X: the matrix of regressors" X::Matrix "logdetVy: the log-determinant of Vy" logdetVy::Float64 "criterion: REML if reml is true, ML otherwise" reml::Bool "ind: vector matching the tips of the network against the names of the dataframe provided. 0 if the match could not be performed." ind::Vector{Int} "nonmissing: vector indicating which tips have non-missing data" nonmissing::BitArray{1} "evomodel: the model used for the fit" evomodel::ContinuousTraitEM # ContinuousTraitEM is abstract: not efficient. parametrize PhyloNetworkLinearModel? # but the types for Vy, Y and X are also abstract. "model_within: the model used for within-species variation (if needed)" model_within::Union{Nothing, WithinSpeciesCTM} "formula: a StatsModels.FormulaTerm formula" formula::Union{StatsModels.FormulaTerm,Nothing} end # default model_within=nothing PhyloNetworkLinearModel(lm, V,Vy,RL,Y,X,logdetVy, reml,ind,nonmissing, model) = PhyloNetworkLinearModel(lm,V,Vy,RL,Y,X,logdetVy, reml,ind,nonmissing, model,nothing,nothing) # default formula=nothing PhyloNetworkLinearModel(lm,V,Vy,RL,Y,X,logdetVy,reml,ind,nonmissing,model,model_within) = PhyloNetworkLinearModel(lm,V,Vy,RL,Y,X,logdetVy, reml,ind,nonmissing,model,model_within,nothing) #= ------ roadmap of phylolm methods -------------- with or without within-species variation: - phylolm(formula, dataframe, net; model="BM",...,withinspecies_var=false,...) - phylolm(X,Y,net, model::ContinuousTraitEM; kwargs...) calls a function with or without within-species variation. 1. no measurement error in species means: - phylolm(model, X,Y,net, reml; kwargs...) dispatches based on model type - phylolm_lambda(X,Y,V,reml, gammas,times; ...) - phylolm_scalingHybrid(X,Y,net,reml, gammas; ...) helpers: - pgls(X,Y,V; ...) for vanilla BM, but called by others with fixed V_theta - logLik_lam(lambda, X,Y,V,gammas,times; ...) - logLik_lam_hyb(lambda, X,Y,net,gammas; ...) 2. with measurement error (within-species variation): - phylolm_wsp(model, X,Y,net, reml; kwargs...) dispatch based on model implemented for model <: BM only - phylolm_wsp(X,Y,V,reml, nonmissing,ind, counts,ySD, model_within) - phylolm_wsp(Xsp,Ysp,Vsp,reml, d_inv,RSS, n,p,a, model_within) =# """ phylolm(X::Matrix, Y::Vector, net::HybridNetwork, model::ContinuousTraitEM=BM(); kwargs...) Return a [`PhyloNetworkLinearModel`](@ref) object. This method is called by `phylolm(formula, data, network; kwargs...)`. """ function phylolm(X::Matrix, Y::Vector, net::HybridNetwork, model::ContinuousTraitEM = BM(); reml::Bool=true, nonmissing=trues(length(Y))::BitArray{1}, ind=[0]::Vector{Int}, startingValue=0.5::Real, fixedValue=missing::Union{Real,Missing}, withinspecies_var::Bool=false, counts::Union{Nothing, Vector}=nothing, ySD::Union{Nothing, Vector}=nothing) if withinspecies_var phylolm_wsp(model, X,Y,net, reml; nonmissing=nonmissing, ind=ind, counts=counts, ySD=ySD) else phylolm(model, X,Y,net, reml; nonmissing=nonmissing, ind=ind, startingValue=startingValue, fixedValue=fixedValue) end end function phylolm(::BM, X::Matrix, Y::Vector, net::HybridNetwork,reml::Bool; nonmissing=trues(length(Y))::BitArray{1}, ind=[0]::Vector{Int}, kwargs...) # BM variance covariance: # V_ij = expected shared time for independent genes in i & j V = sharedPathMatrix(net) linmod, Vy, RL, logdetVy = pgls(X,Y,V; nonmissing=nonmissing, ind=ind) return PhyloNetworkLinearModel(linmod, V, Vy, RL, Y, X, logdetVy, reml, ind, nonmissing, BM()) end function phylolm(::PagelLambda, X::Matrix, Y::Vector, net::HybridNetwork, reml::Bool; nonmissing=trues(length(Y))::BitArray{1}, ind=[0]::Vector{Int}, startingValue=0.5::Real, fixedValue=missing::Union{Real,Missing}) # BM variance covariance V = sharedPathMatrix(net) gammas = getGammas(net) times = getHeights(net, false) # false: no need to preorder again phylolm_lambda(X,Y,V,reml, gammas, times; nonmissing=nonmissing, ind=ind, startingValue=startingValue, fixedValue=fixedValue) end #= ScalingHybrid = BM but with optimized weights of hybrid edges: minor edges have their original γ's changed to λγ. Same λ at all hybrids. see Bastide (2017) dissertation, section 4.3.2 p.175, at https://tel.archives-ouvertes.fr/tel-01629648 =# function phylolm(::ScalingHybrid, X::Matrix, Y::Vector, net::HybridNetwork, reml::Bool; nonmissing=trues(length(Y))::BitArray{1}, ind=[0]::Vector{Int}, startingValue=0.5::Real, fixedValue=missing::Union{Real,Missing}) preorder!(net) gammas = getGammas(net) phylolm_scalingHybrid(X, Y, net, reml, gammas; nonmissing=nonmissing, ind=ind, startingValue=startingValue, fixedValue=fixedValue) end ############################################################################### ## Fit BM # Vanilla BM using covariance V. used for other models: V calculated beforehand function pgls(X::Matrix, Y::Vector, V::MatrixTopologicalOrder; nonmissing=trues(length(Y))::BitArray{1}, # which tips are not missing? ind=[0]::Vector{Int}) # Extract tips matrix Vy = V[:Tips] # Re-order if necessary if (ind != [0]) Vy = Vy[ind, ind] end # Keep only not missing values Vy = Vy[nonmissing, nonmissing] # Cholesky decomposition R = cholesky(Vy) RL = R.L # Fit with GLM.lm, and return quantities needed downstream return lm(RL\X, RL\Y), Vy, RL, logdet(R) end ############################################################################### ## helper functions for lambda models """ getGammas(net) Vector of inheritance γ's of all major edges (tree edges and major hybrid edges), ordered according to the pre-order index of their child node, assuming this pre-order is already calculated (with up-to-date field `nodes_changed`). Here, a "major" edge is an edge with field `isMajor` set to true, regardless of its actual γ (below, at or above 0.5). See [`setGammas!`](@ref) """ function getGammas(net::HybridNetwork) gammas = ones(length(net.nodes_changed)) for (i,node) in enumerate(net.nodes_changed) node.hybrid || continue # skip tree nodes: their gamma is already set to 1 majorhybedge = getparentedge(node) # major gammas[i] = majorhybedge.gamma end return gammas end """ setGammas!(net, γ vector) Set inheritance γ's of hybrid edges, using input vector for *major* edges. Assume pre-order calculated already, with up-to-date field `nodes_changed`. See [`getGammas`](@ref). **Warning**: very different from [`setGamma!`](@ref), which focuses on a single hybrid event, updates the field `isMajor` according to the new γ, and is not used here. **Assumption**: each hybrid node has only 2 parents, a major and a minor parent (according to the edges' field `isMajor`). """ function setGammas!(net::HybridNetwork, gammas::Vector) for (i,nod) in enumerate(net.nodes_changed) nod.hybrid || continue # skip tree nodes: nothing to do majorhyb = getparentedge(nod) # major minorhyb = getparentedgeminor(nod) # error if doesn't exit majorhyb.gamma = gammas[i] minorhyb.gamma = 1 - gammas[i] end return nothing end """ getHeights(net, checkpreorder::Bool=true) Return the height (distance to the root) of all nodes, assuming a time-consistent network (where all paths from the root to a given hybrid node have the same length) but not necessarily ultrametric: tips need not all be at the same distance from the root. If `checkpreorder=false`, assumes the network has already been preordered with [`preorder!`](@ref), because it uses [`getGammas`](@ref) and [`setGammas!`](@ref)). Output: vector of node heights, one per node, in the same order as in `net.nodes_changed`. Examples: ```jldoctest julia> net = readTopology("(((C:1,(A:1)#H1:1.5::0.7):1,(#H1:0.3::0.3,E:2.0):2.2):1.0,O:5.2);"); julia> # using PhyloPlots; plot(net, useedgelength=true, showedgelength=true, shownodenumber=true); # to see julia> nodeheight = PhyloNetworks.getHeights(net) 9-element Vector{Float64}: 0.0 5.2 1.0 3.2 5.2 2.0 3.5 4.5 3.0 julia> [node.number => (nodeheight[i], node.name) for (i,node) in enumerate(net.nodes_changed)] 9-element Vector{Pair{Int64, Tuple{Float64, String}}}: -2 => (0.0, "") 5 => (5.2, "O") -3 => (1.0, "") -6 => (3.2, "") 4 => (5.2, "E") -4 => (2.0, "") 3 => (3.5, "H1") 2 => (4.5, "A") 1 => (3.0, "C") ``` """ function getHeights(net::HybridNetwork, checkpreorder::Bool=true) checkpreorder && preorder!(net) gammas = getGammas(net) # uses net.nodes_changed setGammas!(net, ones(net.numNodes)) V = sharedPathMatrix(net; checkPreorder=false) # no need to preorder again setGammas!(net, gammas) return(diag(V[:All])) end function maxLambda(times::Vector, V::MatrixTopologicalOrder) maskTips = indexin(V.tipNumbers, V.nodeNumbersTopOrder) maskNodes = indexin(V.internalNodeNumbers, V.nodeNumbersTopOrder) return minimum(times[maskTips]) / maximum(times[maskNodes]) # res = minimum(times[maskTips]) / maximum(times[maskNodes]) # res = res * (1 - 1/5/maximum(times[maskTips])) end function transform_matrix_lambda!(V::MatrixTopologicalOrder, lam::AbstractFloat, gammas::Vector, times::Vector) for i in 1:size(V.V, 1) for j in 1:size(V.V, 2) V.V[i,j] *= lam end end maskTips = indexin(V.tipNumbers, V.nodeNumbersTopOrder) for i in maskTips V.V[i, i] += (1-lam) * (gammas[i]^2 + (1-gammas[i])^2) * times[i] end # V_diag = Matrix(Diagonal(diag(V.V))) # V.V = lam * V.V .+ (1 - lam) .* V_diag end function logLik_lam(lam::AbstractFloat, X::Matrix, Y::Vector, V::MatrixTopologicalOrder, reml::Bool, gammas::Vector, times::Vector; nonmissing=trues(length(Y))::BitArray{1}, # Which tips are not missing ? ind=[0]::Vector{Int}) # Transform V according to lambda Vp = deepcopy(V) transform_matrix_lambda!(Vp, lam, gammas, times) # Fit and take likelihood linmod, Vy, RL, logdetVy = pgls(X,Y,Vp; nonmissing=nonmissing, ind=ind) n = (reml ? dof_residual(linmod) : nobs(linmod)) res = n*log(deviance(linmod)) + logdetVy if reml res += logdet(linmod.pp.chol); end return res end function phylolm_lambda(X::Matrix,Y::Vector, V::MatrixTopologicalOrder, reml::Bool, gammas::Vector, times::Vector; nonmissing=trues(length(Y))::BitArray{1}, # Which tips are not missing ? ind=[0]::Vector{Int}, ftolRel=fRelTr::AbstractFloat, xtolRel=xRelTr::AbstractFloat, ftolAbs=fAbsTr::AbstractFloat, xtolAbs=xAbsTr::AbstractFloat, startingValue=0.5::Real, fixedValue=missing::Union{Real,Missing}) if ismissing(fixedValue) # Find Best lambda using optimize from package NLopt opt = NLopt.Opt(:LN_BOBYQA, 1) NLopt.ftol_rel!(opt, ftolRel) # relative criterion NLopt.ftol_abs!(opt, ftolAbs) # absolute critetion NLopt.xtol_rel!(opt, xtolRel) # criterion on parameter value changes NLopt.xtol_abs!(opt, xtolAbs) # criterion on parameter value changes NLopt.maxeval!(opt, 1000) # max number of iterations NLopt.lower_bounds!(opt, 1e-100) # Lower bound # Upper Bound up = maxLambda(times, V) up = up-up/1000 NLopt.upper_bounds!(opt, up) @info "Maximum lambda value to maintain positive branch lengths: " * @sprintf("%.6g", up) count = 0 function fun(x::Vector{Float64}, g::Vector{Float64}) x = convert(AbstractFloat, x[1]) res = logLik_lam(x, X,Y,V, reml, gammas, times; nonmissing=nonmissing, ind=ind) count =+ 1 #println("f_$count: $(round(res, digits=5)), x: $(x)") return res end NLopt.min_objective!(opt, fun) fmin, xmin, ret = NLopt.optimize(opt, [startingValue]) # Best value dans result res_lam = xmin[1] else res_lam = fixedValue end transform_matrix_lambda!(V, res_lam, gammas, times) linmod, Vy, RL, logdetVy = pgls(X,Y,V; nonmissing=nonmissing, ind=ind) res = PhyloNetworkLinearModel(linmod, V, Vy, RL, Y, X, logdetVy, reml, ind, nonmissing, PagelLambda(res_lam)) return res end ############################################################################### ## Fit scaling hybrid function matrix_scalingHybrid(net::HybridNetwork, lam::AbstractFloat, gammas::Vector) setGammas!(net, 1.0 .- lam .* (1. .- gammas)) V = sharedPathMatrix(net) setGammas!(net, gammas) return V end function logLik_lam_hyb(lam::AbstractFloat, X::Matrix, Y::Vector, net::HybridNetwork, reml::Bool, gammas::Vector; nonmissing=trues(length(Y))::BitArray{1}, # Which tips are not missing ? ind=[0]::Vector{Int}) # Transform V according to lambda V = matrix_scalingHybrid(net, lam, gammas) # Fit and take likelihood linmod, Vy, RL, logdetVy = pgls(X,Y,V; nonmissing=nonmissing, ind=ind) n = (reml ? dof_residual(linmod) : nobs(linmod)) res = n*log(deviance(linmod)) + logdetVy if reml res += logdet(linmod.pp.chol); end return res end function phylolm_scalingHybrid(X::Matrix,Y::Vector, net::HybridNetwork, reml::Bool, gammas::Vector; nonmissing=trues(length(Y))::BitArray{1}, # Which tips are not missing ? ind=[0]::Vector{Int}, ftolRel=fRelTr::AbstractFloat, xtolRel=xRelTr::AbstractFloat, ftolAbs=fAbsTr::AbstractFloat, xtolAbs=xAbsTr::AbstractFloat, startingValue=0.5::Real, fixedValue=missing::Union{Real,Missing}) if ismissing(fixedValue) # Find Best lambda using optimize from package NLopt opt = NLopt.Opt(:LN_BOBYQA, 1) NLopt.ftol_rel!(opt, ftolRel) # relative criterion NLopt.ftol_abs!(opt, ftolAbs) # absolute critetion NLopt.xtol_rel!(opt, xtolRel) # criterion on parameter value changes NLopt.xtol_abs!(opt, xtolAbs) # criterion on parameter value changes NLopt.maxeval!(opt, 1000) # max number of iterations #NLopt.lower_bounds!(opt, 1e-100) # Lower bound #NLopt.upper_bounds!(opt, 1.0) count = 0 function fun(x::Vector{Float64}, g::Vector{Float64}) x = convert(AbstractFloat, x[1]) res = logLik_lam_hyb(x, X, Y, net, reml, gammas; nonmissing=nonmissing, ind=ind) #count =+ 1 #println("f_$count: $(round(res, digits=5)), x: $(x)") return res end NLopt.min_objective!(opt, fun) fmin, xmin, ret = NLopt.optimize(opt, [startingValue]) # Best value dans result res_lam = xmin[1] else res_lam = fixedValue end V = matrix_scalingHybrid(net, res_lam, gammas) linmod, Vy, RL, logdetVy = pgls(X,Y,V; nonmissing=nonmissing, ind=ind) res = PhyloNetworkLinearModel(linmod, V, Vy, RL, Y, X, logdetVy, reml, ind, nonmissing, ScalingHybrid(res_lam)) return res end """ phylolm(f::StatsModels.FormulaTerm, fr::AbstractDataFrame, net::HybridNetwork; kwargs...) Fit a phylogenetic linear regression model to data. Return an object of type [`PhyloNetworkLinearModel`](@ref). It contains a linear model from the GLM package, in `object.lm`, of type [GLM.LinearModel](https://juliastats.org/GLM.jl/stable/api/#GLM.LinearModel). ## Arguments * `f`: formula to use for the regression, see [StatsModels](https://juliastats.org/StatsModels.jl/stable/) * `fr`: DataFrame containing the response values, predictor values, species/tip labels for each observation/row. * `net`: phylogenetic network to use. Should have labelled tips. Keyword arguments * `model="BM"`: model for trait evolution (as a string) "lambda" (Pagel's lambda), "scalingHybrid" are other possible values (see [`ContinuousTraitEM`](@ref)) * `tipnames=:tipNames`: column name for species/tip-labels, represented as a symbol. For example, if the column containing the species/tip labels in `fr` is named "Species", then do `tipnames=:Species`. * `no_names=false`: If `true`, force the function to ignore the tips names. The data is then assumed to be in the same order as the tips of the network. Default is false, setting it to true is dangerous, and strongly discouraged. * `reml=true`: if `true`, use REML criterion ("restricted maximum likelihood") for estimating variance components, else use ML criterion. The following tolerance parameters control the optimization of lambda if `model="lambda"` or `model="scalingHybrid"`, and control the optimization of the variance components if `model="BM"` and `withinspecies_var=true`. * `fTolRel=1e-10`: relative tolerance on the likelihood value * `fTolAbs=1e-10`: absolute tolerance on the likelihood value * `xTolRel=1e-10`: relative tolerance on the parameter value * `xTolAbs=1e-10`: absolute tolerance on the parameter value * `startingValue=0.5`: If `model`="lambda" or "scalingHybrid", this provides the starting value for the optimization in lambda. * `fixedValue=missing`: If `model`="lambda" or "scalingHybrid", and `fixedValue` is a number, then lambda is set to this number and is not optimized. * `withinspecies_var=false`: If `true`, fits a within-species variation model. Currently only implemented for `model`="BM". * `y_mean_std::Bool=false`: If `true`, and `withinspecies_var=true`, then accounts for within-species variation, using species-level statistics provided in `fr`. ## Methods applied to fitted models To access the response values, do `response(object)`. To access the model matrix, do `modelmatrix(object)`. To access the model formula, do `formula(object)`. ## Within-species variation For a high-level description, see [`PhyloNetworkLinearModel`](@ref). To fit a model with within-species variation in the response variable, either of the following must be provided in the data frame `fr`: (1) Individual-level data: There should be columns for response, predictors, and species/tip-labels. Every row should correspond to an individual observation. At least one species must be represented by two or more individuals. (2) Species-level statistics: There should be columns for mean response, predictors, species/tip-labels, species sample-sizes (number of individuals for each species), and species standard deviations (standard deviations of the response values by species). Every row should correspond to a species: each species should be represented by a unique row. The column names for species sample-sizes and species standard deviations are expected to be "[response column name]\\_n" and "[response column name]\\_sd". For example, if the response column name is "y", then the column names should be "y\\_n" and "y\\_sd" for the sample-sizes and standard deviations. Regardless of whether the data provided follows (1) or (2), `withinspecies_var` should be set to true. If the data provided follows (2), then `y_mean_std` should be set to false. ## Within-species variation in predictors The model assumes *no* within-species variation in predictors, because it aims to capture the evolutionary (historical, phylogenetic) relationship between the predictors and the response, not the within-species (present-day, or phenotypic) relationship. If a within-species variation model is fitted on individual-level data, and if there are individuals within the same species with different values for the same predictor, these values are all replaced by the mean predictor value for all the individuals in that species. For example, suppose there are 3 individuals in a given species, and that their predictor values are (x₁=3, x₂=6), (x₁=4, x₂=8) and (x₁=2, x₂=1). Then the predictor values for these 3 individuals are each replaced by (x₁=(3+4+2)/3, x₂=(6+8+1)/3) before model fitting. If a fourth individual had data (x₁=10, x₂=missing), then that individual would be ignored for any model using x₂, and would not contribute any information to its species data for these models. ## Missing data Rows with missing data for either the response or the predictors are omitted from the model-fitting. There should minimally be columns for response, predictors, species/tip-labels. As detailed above, additional columns may be required for fitting within-species variation. Missing data in the columns for species names, species standard deviation / sample sizes (if used) will throw an error. ## See also [`simulate`](@ref), [`ancestralStateReconstruction`](@ref), [`vcv`](@ref) ## Examples: Without within-species variation ```jldoctest julia> phy = readTopology(joinpath(dirname(pathof(PhyloNetworks)), "..", "examples", "caudata_tree.txt")); julia> using DataFrames, CSV # to read data file, next julia> dat = CSV.File(joinpath(dirname(pathof(PhyloNetworks)), "..", "examples", "caudata_trait.txt")) |> DataFrame; julia> using StatsModels # for stat model formulas julia> fitBM = phylolm(@formula(trait ~ 1), dat, phy; reml=false); julia> fitBM # Shows a summary PhyloNetworkLinearModel Formula: trait ~ 1 Model: Brownian motion Parameter Estimates, using ML: phylogenetic variance rate: 0.00294521 Coefficients: ───────────────────────────────────────────────────────────────────── Coef. Std. Error t Pr(>|t|) Lower 95% Upper 95% ───────────────────────────────────────────────────────────────────── (Intercept) 4.679 0.330627 14.15 <1e-31 4.02696 5.33104 ───────────────────────────────────────────────────────────────────── Log Likelihood: -78.9611507833 AIC: 161.9223015666 julia> round(sigma2_phylo(fitBM), digits=6) # rounding for jldoctest convenience 0.002945 julia> round(mu_phylo(fitBM), digits=4) 4.679 julia> using StatsBase # for aic() stderror() loglikelihood() etc. julia> round(loglikelihood(fitBM), digits=10) -78.9611507833 julia> round(aic(fitBM), digits=10) 161.9223015666 julia> round(aicc(fitBM), digits=10) 161.9841572367 julia> round(bic(fitBM), digits=10) 168.4887090241 julia> round.(coef(fitBM), digits=4) 1-element Vector{Float64}: 4.679 julia> confint(fitBM) 1×2 Matrix{Float64}: 4.02696 5.33104 julia> abs(round(r2(fitBM), digits=10)) # absolute value for jldoctest convenience 0.0 julia> abs(round(adjr2(fitBM), digits=10)) 0.0 julia> round.(vcov(fitBM), digits=6) 1×1 Matrix{Float64}: 0.109314 julia> round.(residuals(fitBM), digits=6) 197-element Vector{Float64}: -0.237648 -0.357937 -0.159387 -0.691868 -0.323977 -0.270452 -0.673486 -0.584654 -0.279882 -0.302175 ⋮ -0.777026 -0.385121 -0.443444 -0.327303 -0.525953 -0.673486 -0.603158 -0.211712 -0.439833 julia> round.(response(fitBM), digits=5) 197-element Vector{Float64}: 4.44135 4.32106 4.51961 3.98713 4.35502 4.40855 4.00551 4.09434 4.39912 4.37682 ⋮ 3.90197 4.29388 4.23555 4.3517 4.15305 4.00551 4.07584 4.46729 4.23917 julia> round.(predict(fitBM), digits=5) 197-element Vector{Float64}: 4.679 4.679 4.679 4.679 4.679 4.679 4.679 4.679 4.679 4.679 ⋮ 4.679 4.679 4.679 4.679 4.679 4.679 4.679 4.679 4.679 ``` ## Examples: With within-species variation (two different input formats shown) ```jldoctest julia> using DataFrames, StatsModels # for statistical model formulas julia> net = readTopology("((((D:0.4,C:0.4):4.8,((A:0.8,B:0.8):2.2)#H1:2.2::0.7):4.0,(#H1:0::0.3,E:3.0):6.2):2.0,O:11.2);"); julia> df = DataFrame( # individual-level observations species = repeat(["D","C","A","B","E","O"],inner=3), trait1 = [4.08298,4.08298,4.08298,3.10782,3.10782,3.10782,2.17078,2.17078,2.17078,1.87333,1.87333, 1.87333,2.8445,2.8445,2.8445,5.88204,5.88204,5.88204], trait2 = [-7.34186,-7.34186,-7.34186,-7.45085,-7.45085,-7.45085,-3.32538,-3.32538,-3.32538,-4.26472, -4.26472,-4.26472,-5.96857,-5.96857,-5.96857,-1.99388,-1.99388,-1.99388], trait3 = [18.8101,18.934,18.9438,17.0687,17.0639,17.0732,14.4818,14.1112,14.2817,13.0842,12.9562, 12.9019,15.4373,15.4075,15.4317,24.2249,24.1449,24.1302]); julia> m1 = phylolm(@formula(trait3 ~ trait1), df, net; tipnames=:species, withinspecies_var=true) PhyloNetworkLinearModel Formula: trait3 ~ 1 + trait1 Model: Brownian motion Parameter Estimates, using REML: phylogenetic variance rate: 0.156188 within-species variance: 0.0086343 Coefficients: ────────────────────────────────────────────────────────────────────── Coef. Std. Error t Pr(>|t|) Lower 95% Upper 95% ────────────────────────────────────────────────────────────────────── (Intercept) 9.65347 1.3066 7.39 0.0018 6.02577 13.2812 trait1 2.30358 0.276163 8.34 0.0011 1.53683 3.07033 ────────────────────────────────────────────────────────────────────── Log Likelihood: 1.9446255188 AIC: 4.1107489623 julia> df_r = DataFrame( # species-level statistics (sample means, standard deviations) species = ["D","C","A","B","E","O"], trait1 = [4.08298,3.10782,2.17078,1.87333,2.8445,5.88204], trait2 = [-7.34186,-7.45085,-3.32538,-4.26472,-5.96857,-1.99388], trait3 = [18.896,17.0686,14.2916,12.9808,15.4255,24.1667], trait3_sd = [0.074524,0.00465081,0.185497,0.0936,0.0158379,0.0509643], trait3_n = [3, 3, 3, 3, 3, 3]); julia> m2 = phylolm(@formula(trait3 ~ trait1), df_r, net; tipnames=:species, withinspecies_var=true, y_mean_std=true) PhyloNetworkLinearModel Formula: trait3 ~ 1 + trait1 Model: Brownian motion Parameter Estimates, using REML: phylogenetic variance rate: 0.15618 within-species variance: 0.0086343 Coefficients: ────────────────────────────────────────────────────────────────────── Coef. Std. Error t Pr(>|t|) Lower 95% Upper 95% ────────────────────────────────────────────────────────────────────── (Intercept) 9.65342 1.30657 7.39 0.0018 6.02582 13.281 trait1 2.30359 0.276156 8.34 0.0011 1.53686 3.07032 ────────────────────────────────────────────────────────────────────── Log Likelihood: 1.9447243714 AIC: 4.1105512573 ``` """ function phylolm(f::StatsModels.FormulaTerm, fr::AbstractDataFrame, net::HybridNetwork; model::AbstractString="BM", tipnames::Symbol=:tipNames, no_names::Bool=false, reml::Bool=true, ftolRel::AbstractFloat=fRelTr, xtolRel::AbstractFloat=xRelTr, ftolAbs::AbstractFloat=fAbsTr, xtolAbs::AbstractFloat=xAbsTr, startingValue::Real=0.5, fixedValue::Union{Real,Missing}=missing, withinspecies_var::Bool=false, y_mean_std::Bool=false) # Match the tips names: make sure that the data provided by the user will # be in the same order as the ordered tips in matrix V. preorder!(net) if no_names # The names should not be taken into account. ind = [0] @info """As requested (no_names=true), I am ignoring the tips names in the network and in the dataframe.""" else nodatanames = !any(DataFrames.propertynames(fr) .== tipnames) nodatanames && any(tipLabels(net) == "") && error("""The network provided has no tip names, and the input dataframe has no column "$tipnames" for species names, so I can't match the data on the network unambiguously. If you are sure that the tips of the network are in the same order as the values of the dataframe provided, then please re-run this function with argument no_name=true.""") any(tipLabels(net) == "") && error("""The network provided has no tip names, so I can't match the data on the network unambiguously. If you are sure that the tips of the network are in the same order as the values of the dataframe provided, then please re-run this function with argument no_name=true.""") nodatanames && error("""The input dataframe has no column "$tipnames" for species names, so I can't match the data on the network unambiguously. If you are sure that the tips of the network are in the same order as the values of the dataframe provided, then please re-run this function with argument no_name=true.""") ind = indexin(fr[!, tipnames], tipLabels(net)) any(isnothing, ind) && error("""Tips with data are not in the network: $(fr[isnothing.(ind), tipnames]) please provide a larger network including these tips.""") ind = convert(Vector{Int}, ind) # Int, not Union{Nothing, Int} if length(unique(ind)) == length(ind) withinspecies_var && !y_mean_std && error("""for within-species variation, at least 1 species must have at least 2 individuals. did you mean to use option "y_mean_std=true" perhaps?""") else (!withinspecies_var || y_mean_std) && error("""Some tips have data on multiple rows.""") end end # Find the regression matrix and response vector data, nonmissing = StatsModels.missing_omit(StatsModels.columntable(fr), f) sch = StatsModels.schema(f, data) f = StatsModels.apply_schema(f, sch, PhyloNetworkLinearModel) mf = ModelFrame(f, sch, data, PhyloNetworkLinearModel) mm = StatsModels.ModelMatrix(mf) Y = StatsModels.response(mf) if withinspecies_var && y_mean_std # find columns in data frame for: # of individuals from each species colname = Symbol(String(mf.f.lhs.sym)*"_n") any(DataFrames.propertynames(fr) .== colname) || error("expected # of individuals in column $colname, but no such column was found") counts = fr[nonmissing,colname] all(!ismissing, counts) || error("some num_individuals values are missing, column $colname") all(x -> x>0, counts) || error("some species have 0 or <0 num_individuals, column $colname") all(isfinite.(counts))|| error("some species have infinite num_individuals, column $colname") # find sample SDs corresponding to the response mean in each species colname = Symbol(String(mf.f.lhs.sym)*"_sd") any(DataFrames.propertynames(fr) .== colname) || error("expected the response's SD (per species) in column $colname, but no such column was found") ySD = fr[nonmissing,colname] all(!ismissing, ySD) || error("some SD values are missing, column $colname") all(x -> x≥0, ySD) || error("some SD values are negative, column $colname") all(isfinite.(ySD))|| error("some SD values are infinite, column $colname") else counts = nothing ySD = nothing end withinspecies_var && model != "BM" && error("within-species variation is not implemented for non-BM models") modeldic = Dict("BM" => BM(), "lambda" => PagelLambda(), "scalingHybrid" => ScalingHybrid()) haskey(modeldic, model) || error("phylolm is not defined for model $model.") modelobj = modeldic[model] res = phylolm(mm.m, Y, net, modelobj; reml=reml, nonmissing=nonmissing, ind=ind, startingValue=startingValue, fixedValue=fixedValue, withinspecies_var=withinspecies_var, counts=counts, ySD=ySD) res.formula = f return res end ### Methods on type phyloNetworkRegression ## Un-changed Quantities # Coefficients of the regression StatsBase.coef(m::PhyloNetworkLinearModel) = coef(m.lm) StatsBase.coefnames(m::PhyloNetworkLinearModel) = (m.formula === nothing ? ["x$i" for i in 1:length(coef(m))] : coefnames(formula(m).rhs)) StatsModels.formula(obj::PhyloNetworkLinearModel) = obj.formula """ StatsBase.nobs(m::PhyloNetworkLinearModel) Number of observations: number of species with data, if the model assumes known species means, and number of individuals with data, if the model accounts for within-species variation. """ function StatsBase.nobs(m::PhyloNetworkLinearModel) if isnothing(m.model_within) return nobs(m.lm) else return sum(1.0 ./ m.model_within.wsp_ninv) end end """ vcov(m::PhyloNetworkLinearModel) Return the variance-covariance matrix of the coefficient estimates. For the continuous trait evolutionary models currently implemented, species-level mean response (conditional on the predictors), Y|X is modeled as: 1. Y|X ∼ 𝒩(Xβ, σ²ₛV) for models assuming known species mean values (no within-species variation) 2. Y|X ∼ 𝒩(Xβ, σ²ₛV + σ²ₑD⁻¹) for models with information from multiple individuals and assuming within-species variation The matrix V is inferred from the phylogeny, but may also depend on additional parameters to be estimated (e.g. `lambda` for Pagel's Lambda model). See [`ContinuousTraitEM`](@ref), [`PhyloNetworkLinearModel`](@ref) for more details. If (1), then return σ²ₛ(X'V⁻¹X)⁻¹, where σ²ₛ is estimated with REML, even if the model was fitted with `reml=false`. This follows the conventions of [`nlme::gls`](https://www.rdocumentation.org/packages/nlme/versions/3.1-152) and [`stats::glm`](https://www.rdocumentation.org/packages/stats/versions/3.6.2) in R. If (2), then return σ²ₛ(X'W⁻¹X)⁻¹, where W = V+(σ²ₑ/σ²ₛ)D⁻¹ is estimated, and σ²ₛ & σₑ are the estimates obtained with ML or REML, depending on the `reml` option used to fit the model `m`. This follows the convention of [`MixedModels.fit`](https://juliastats.org/MixedModels.jl/stable/) in Julia. """ function StatsBase.vcov(m::PhyloNetworkLinearModel) # GLM.vcov(x::LinPredModel) = rmul!(invchol(x.pp), dispersion(x, true)) # GLM.dispersion (sqrt=true): sqrt(sum of working residuals / dof_residual): forces "REML" (isnothing(m.model_within) ? vcov(m.lm) : rmul!(GLM.invchol(m.lm.pp), sigma2_phylo(m)) ) end """ stderror(m::PhyloNetworkLinearModel) Return the standard errors of the coefficient estimates. See [`vcov`](@ref) for related information on how these are computed. """ StatsBase.stderror(m::PhyloNetworkLinearModel) = sqrt.(diag(vcov(m))) # confidence Intervals for coefficients: GLM uses normal quantiles # Based on: https://github.com/JuliaStats/GLM.jl/blob/d1ccc9abcc9c7ca6f640c13ff535ee8383e8f808/src/lm.jl#L240-L243 """ confint(m::PhyloNetworkLinearModel; level::Real=0.95) Return confidence intervals for coefficients, with confidence level `level`, based on the t-distribution whose degree of freedom is determined by the number of species (as returned by `dof_residual`) """ function StatsBase.confint(m::PhyloNetworkLinearModel; level::Real=0.95) hcat(coef(m),coef(m)) + stderror(m) * quantile(TDist(dof_residual(m)), (1. - level)/2.) * [1. -1.] end # Table of estimated coefficients, standard errors, t-values, p-values, CIs # Based on: https://github.com/JuliaStats/GLM.jl/blob/d1ccc9abcc9c7ca6f640c13ff535ee8383e8f808/src/lm.jl#L193-L203 """ coeftable(m::PhyloNetworkLinearModel; level::Real=0.95) Return coefficient estimates, standard errors, t-values, p-values, and t-intervals as a `StatsBase.CoefTable`. """ function StatsBase.coeftable(m::PhyloNetworkLinearModel; level::Real=0.95) n_coef = size(m.lm.pp.X, 2) # no. of predictors if n_coef == 0 return CoefTable([0], ["Fixed Value"], ["(Intercept)"]) end cc = coef(m) se = stderror(m) tt = cc ./ se p = ccdf.(Ref(FDist(1, dof_residual(m))), abs2.(tt)) ci = se*quantile(TDist(dof_residual(m)), (1-level)/2) levstr = isinteger(level*100) ? string(Integer(level*100)) : string(level*100) cn = StatsModels.vectorize(coefnames(m)) CoefTable(hcat(cc,se,tt,p,cc+ci,cc-ci), ["Coef.","Std. Error","t","Pr(>|t|)","Lower $levstr%","Upper $levstr%"], cn, 4, 3) end # degrees of freedom for residuals: at the species level, for coefficients of # the phylogenetic regression, assuming known co-variance between species means. # used for F and T degrees of freedom, instead of more conservative Z StatsBase.dof_residual(m::PhyloNetworkLinearModel) = nobs(m.lm) - length(coef(m)) # degrees of freedom consumed by the species-level model function StatsBase.dof(m::PhyloNetworkLinearModel) res = length(coef(m)) + 1 # +1: phylogenetic variance if any(typeof(m.evomodel) .== [PagelLambda, ScalingHybrid]) res += 1 # lambda is one parameter end if !isnothing(m.model_within) res += 1 # within-species variance end return res end """ StatsBase.deviance(m::PhyloNetworkLinearModel) -2 loglikelihood of the fitted model. See also [`loglikelihood`](@ref). Note: this is not the residual-sum-of-squares deviance as output by GLM, such as one would get with `deviance(m.model)`. """ function StatsBase.deviance(m::PhyloNetworkLinearModel, ::Val{false}=Val(false)) -2*loglikelihood(m) end """ StatsBase.deviance(m::PhyloNetworkLinearModel, Val(true)) Residual sum of squares with metric V, the estimated phylogenetic covariance, if the model is appropriate. """ function StatsBase.deviance(m::PhyloNetworkLinearModel, ::Val{true}) isnothing(m.model_within) || error("deviance measured as SSR not implemented for within-species variation") deviance(m.lm) end ## Changed Quantities # Compute the residuals # (Rescaled by cholesky of variance between tips) StatsBase.residuals(m::PhyloNetworkLinearModel) = m.RL * residuals(m.lm) # Tip data: m.Y is different from response(m.lm) # and m.X is different from modelmatrix(m.lm) StatsBase.response(m::PhyloNetworkLinearModel) = m.Y StatsBase.modelmatrix(m::PhyloNetworkLinearModel) = m.X # Predicted values at the tips # (rescaled by cholesky of tips variances) StatsBase.predict(m::PhyloNetworkLinearModel) = m.RL * predict(m.lm) # log likelihood of the fitted linear model """ loglikelihood(m::PhyloNetworkLinearModel) Log likelihood, or log restricted likelihood (REML), depending on `m.reml`. For models with no within-species variation, the likelihood (or REML) is calculated based on the joint density for species-level mean responses. For within-species variation models, the likelihood is calculated based on the joint density for individual-level responses. This can be calculated from individual-level data, but also by providing species-level means and standard deviations which is accepted by [`phylolm`](@ref). **Warning**: many summaries are based on the species-level model, like "dof_residual", "residuals", "predict" or "deviance". So `deviance` is innapropriate to compare models with within-species variation. Use `loglikelihood` to compare models based on data at the individual level. Reminder: do not compare ML or REML values across models fit on different data. Do not compare REML values across models that do not have the same predictors (fixed effects): use ML instead, for that purpose. """ function StatsBase.loglikelihood(m::PhyloNetworkLinearModel) linmod = m.lm if isnothing(m.model_within) # not a msrerr model n = (m.reml ? dof_residual(linmod) : nobs(linmod) ) σ² = deviance(linmod)/n ll = - n * (1. + log2π + log(σ²))/2 - m.logdetVy/2 else # if msrerr model, return loglikelihood of individual-level data modwsp = m.model_within ntot = sum(1.0 ./ modwsp.wsp_ninv) # total number of individuals nsp = nobs(linmod) # number of species ncoef = length(coef(linmod)) bdof = (m.reml ? nsp - ncoef : nsp ) wdof = ntot - nsp N = wdof + bdof # ntot or ntot - ncoef σ² = modwsp.bsp_var[1] σw² = modwsp.wsp_var[1] ll = sum(log.(modwsp.wsp_ninv)) - (N + N * log2π + bdof * log(σ²) + wdof * log(σw²) + m.logdetVy) ll /= 2 end if m.reml ll -= logdet(linmod.pp.chol)/2 # -1/2 log|X'Vm^{-1}X| end return ll end # REMARK Not just the null deviance of the cholesky regression # Might be something better to do than this, though. """ StatsBase.nulldeviance(m::PhyloNetworkLinearModel) For appropriate phylogenetic linear models, the deviance of the null model is the total sum of square with respect to the metric V, the estimated phylogenetic covariance matrix. """ function StatsBase.nulldeviance(m::PhyloNetworkLinearModel) isnothing(m.model_within) || error("""null loglik / deviance not implemented for within-species variation (mixed model): please fit the model with an intercept only instead.""") ro = response(m.lm) if hasintercept(m) vo = ones(length(m.Y), 1) vo = m.RL \ vo bo = inv(vo'*vo)*vo'*ro ro = ro - vo*bo end return sum(ro.^2) end StatsModels.hasintercept(m::PhyloNetworkLinearModel) = any(i -> all(==(1), view(m.X , :, i)), 1:size(m.X, 2)) # Null Log likelihood (null model with only the intercept) # Same remark function StatsBase.nullloglikelihood(m::PhyloNetworkLinearModel) nulldev = nulldeviance(m) # error & exit if within-species variation m.reml && @warn "ML null loglik: do not compare with REML on model with predictors" n = length(m.Y) return -n/2 * (log(2*pi * nulldev/n) + 1) - 1/2 * m.logdetVy end # coefficient of determination (1 - SS_res/SS_null) # Copied from GLM.jl/src/lm.jl, line 139 function StatsBase.r2(m::PhyloNetworkLinearModel) isnothing(m.model_within) || error("r2 and adjusted r2 not implemented for within-species variation (mixed model)") 1 - deviance(m, Val(true))/nulldeviance(m) end # adjusted coefficient of determination # in GLM.jl/src/lm.jl: p = dof-1 and dof(x::LinearModel) = length(coef(x))+1, +1 for the dispersion parameter function StatsBase.adjr2(obj::PhyloNetworkLinearModel) n = nobs(obj) # dof() includes the dispersion parameter sigma2, and lambda if relevant p = dof(obj)-1 # like in GLM # one could argue to use this: p = length(coef(obj)), to ignore lambda or other parameters 1 - (1 - r2(obj))*(n-1)/(n-p) end ## REMARK # As PhyloNetworkLinearModel <: GLM.LinPredModel, the following functions are automatically defined: # aic, aicc, bic ## New quantities # ML estimate for variance of the BM """ sigma2_phylo(m::PhyloNetworkLinearModel) Estimated between-species variance-rate for a fitted object. """ function sigma2_phylo(m::PhyloNetworkLinearModel) linmod = m.lm if isnothing(m.model_within) n = (m.reml ? dof_residual(linmod) : nobs(linmod) ) σ² = deviance(linmod)/n else σ² = m.model_within.bsp_var[1] end return σ² end """ sigma2_within(m::PhyloNetworkLinearModel) Estimated within-species variance for a fitted object. """ sigma2_within(m::PhyloNetworkLinearModel) = (isnothing(m.model_within) ? nothing : m.model_within.wsp_var[1]) # ML estimate for ancestral state of the BM """ mu_phylo(m::PhyloNetworkLinearModel) Estimated root value for a fitted object. """ function mu_phylo(m::PhyloNetworkLinearModel) if m.formula === nothing @warn """You fitted the data against a custom matrix, so I have no way to know which column is your intercept (column of ones). I am using the first coefficient for ancestral mean mu by convention, but that might not be what you are looking for.""" size(m.lm.pp.X,2) == 0 && return 0 elseif m.formula.rhs.terms[1] != StatsModels.InterceptTerm{true}() error("The fit was done without intercept, so I cannot estimate mu") end return coef(m)[1] end """ lambda(m::PhyloNetworkLinearModel) lambda(m::ContinuousTraitEM) Value assigned to the lambda parameter, if appropriate. """ lambda(m::PhyloNetworkLinearModel) = lambda(m.evomodel) lambda(m::Union{BM,PagelLambda,ScalingHybrid}) = m.lambda """ lambda!(m::PhyloNetworkLinearModel, newlambda) lambda!(m::ContinuousTraitEM, newlambda) Assign a new value to the lambda parameter. """ lambda!(m::PhyloNetworkLinearModel, lambda_new) = lambda!(m.evomodel, lambda_new) lambda!(m::Union{BM,PagelLambda,ScalingHybrid}, lambda_new::Real) = (m.lambda = lambda_new) """ lambda_estim(m::PhyloNetworkLinearModel) Estimated lambda parameter for a fitted object. """ lambda_estim(m::PhyloNetworkLinearModel) = lambda(m) ### Print the results # Variance function paramstable(m::PhyloNetworkLinearModel) Sig = sigma2_phylo(m) res = "phylogenetic variance rate: " * @sprintf("%.6g", Sig) if any(typeof(m.evomodel) .== [PagelLambda, ScalingHybrid]) Lamb = lambda_estim(m) res = res*"\nLambda: " * @sprintf("%.6g", Lamb) end mw = m.model_within if !isnothing(mw) res = res*"\nwithin-species variance: " * @sprintf("%.6g", mw.wsp_var[1]) end return(res) end # For DataFrameModel. see also Base.show in # https://github.com/JuliaStats/StatsModels.jl/blob/master/src/statsmodel.jl function Base.show(io::IO, obj::PhyloNetworkLinearModel) ct = coeftable(obj) println(io, "$(typeof(obj))") if !(obj.formula === nothing) print(io, "\nFormula: ") println(io, string(obj.formula)) # formula end println(io) println(io, "Model: $(evomodelname(obj.evomodel))") println(io) println(io,"Parameter Estimates, using ", (obj.reml ? "REML" : "ML"),":") println(io, paramstable(obj)) println(io) println(io,"Coefficients:") show(io, ct) println(io) println(io, "Log Likelihood: "*"$(round(loglikelihood(obj), digits=10))") println(io, "AIC: "*"$(round(aic(obj), digits=10))") end ############################################################################### # within-species variation (including measurement error) ############################################################################### function phylolm_wsp(::BM, X::Matrix, Y::Vector, net::HybridNetwork, reml::Bool; nonmissing=trues(length(Y))::BitArray{1}, # which individuals have non-missing data? ind=[0]::Vector{Int}, counts::Union{Nothing, Vector}=nothing, ySD::Union{Nothing, Vector}=nothing) V = sharedPathMatrix(net) phylolm_wsp(X,Y,V, reml, nonmissing,ind, counts,ySD) end #= notes about missing data: after X and Y produced by stat formula: - individuals with missing data (in response or any predictor) already removed from both X and Y - V has all species: some not listed, some listed but without any data - nonmissing and ind correspond to the original rows in the data frame, including those with some missing data, so: * nonmissing has length >= length of Y * sum(nonmissing) = length of Y - V[:Tips][ind,ind][nonmissing,nonmissing] correspond to the data rows extra problems: - a species may be listed 1+ times in ind, but not in ind[nonmissing] - ind and nonmissing need to be converted to the species level, alongside Y =# function phylolm_wsp(X::Matrix, Y::Vector, V::MatrixTopologicalOrder, reml::Bool, nonmissing::BitArray{1}, ind::Vector{Int}, counts::Union{Nothing, Vector}, ySD::Union{Nothing, Vector}) n_coef = size(X, 2) # no. of predictors individualdata = isnothing(counts) xor(individualdata, isnothing(ySD)) && error("counts and ySD must be both nothing, or both vectors") if individualdata # get species means for Y and X, the within-species residual ss ind_nm = ind[nonmissing] # same length as Y ind_sp = unique(ind_nm) n_sp = length(ind_sp) # number of species with data n_tot = length(Y) # total number of individuals with data d_inv = zeros(n_sp) Ysp = Vector{Float64}(undef,n_sp) # species-level mean Y response Xsp = Matrix{Float64}(undef,n_sp,n_coef) RSS = 0.0 # residual sum-of-squares within-species for (i0,iV) in enumerate(ind_sp) iii = findall(isequal(iV), ind_nm) n_i = length(iii) # number of obs for species of index iV in V d_inv[i0] = 1/n_i Xsp[i0, :] = mean(X[iii, :], dims=1) # ideally, all have same Xs ymean = mean(Y[iii]) Ysp[i0] = ymean RSS += sum((Y[iii] .- ymean).^2) end Vsp = V[:Tips][ind_sp,ind_sp] # redefine "ind" and "nonmissing" at species level. ind = index of species # in tipLabels(net), in same order in which species come in means Ysp. # nonmissing: no need to list species with no data ind = ind_sp nonmissing = trues(n_sp) else # group means and sds for response variable were passed in n_sp = length(Y) n_tot = sum(counts) d_inv = 1.0 ./ counts Ysp = Y Xsp = X RSS = sum((ySD .^ 2) .* (counts .- 1.0)) ind_nm = ind[nonmissing] Vsp = V[:Tips][ind_nm,ind_nm] end model_within, RL = withinsp_varianceratio(Xsp,Ysp,Vsp, reml, d_inv,RSS, n_tot,n_coef,n_sp) η = model_within.optsum.final[1] Vm = Vsp + η * Diagonal(d_inv) m = PhyloNetworkLinearModel(lm(RL\Xsp, RL\Ysp), V, Vm, RL, Ysp, Xsp, 2*logdet(RL), reml, ind, nonmissing, BM(), model_within) return m end # the method below takes in "clean" X,Y,V: species-level means, no missing data, # matching order of species in X,Y and V, no extra species in V. # given V & η: analytical formula for σ² estimate # numerical optimization of η = σ²within / σ² function withinsp_varianceratio(X::Matrix, Y::Vector, V::Matrix, reml::Bool, d_inv::Vector, RSS::Float64, ntot::Real, ncoef::Int64, nsp::Int64, model_within::Union{Nothing, WithinSpeciesCTM}=nothing) RL = cholesky(V).L lm_sp = lm(RL\X, RL\Y) if model_within === nothing # create model_within with good starting values s2start = GLM.dispersion(lm_sp, false) # sqr=false: deviance/dof_residual # this is the REML, not ML estimate, which would be deviance/nobs s2withinstart = RSS/(ntot-nsp) ηstart = s2withinstart / s2start optsum = OptSummary([ηstart], [1e-100], :LN_BOBYQA; initial_step=[0.01], ftol_rel=fRelTr, ftol_abs=fAbsTr, xtol_rel=xRelTr, xtol_abs=[xAbsTr]) optsum.maxfeval = 1000 model_within = WithinSpeciesCTM([s2withinstart], [s2start], d_inv, RSS, optsum) else optsum = model_within.optsum # fixit: I find this option dangerous (and not used). what if the # current optsum has 2 parameters instead of 1, or innapropriate bounds, etc.? # We could remove the option to provide a pre-built model_within end opt = Opt(optsum) Ndof = (reml ? ntot - ncoef : ntot ) wdof = ntot - nsp Vm = similar(V) # scratch space for repeated usage function logliksigma(η) # returns: -2loglik, estimated sigma2, and more Vm .= V + η * Diagonal(d_inv) Vmchol = cholesky(Vm) # LL' = Vm RL = Vmchol.L lm_sp = lm(RL\X, RL\Y) σ² = (RSS/η + deviance(lm_sp))/Ndof # n2ll = -2 loglik except for Ndof*log(2pi) + sum log(di) + Ndof n2ll = Ndof * log(σ²) + wdof * log(η) + logdet(Vmchol) if reml n2ll += logdet(lm_sp.pp.chol) # log|X'Vm^{-1}X| end #= manual calculations without cholesky Q = X'*(Vm\X); β = Q\(X'*(Vm\Ysp)); r = Y-X*β val = Ndof*log(σ²) + ((RSS/η) + r'*(Vm\r))/σ² + (ntot-ncoef)*log(η) + logabsdet(Vm)[1] + logabsdet(Q)[1] =# return (n2ll, σ², Vmchol) end obj(x, g) = logliksigma(x[1])[1] # x = [η] NLopt.min_objective!(opt, obj) fmin, xmin, ret = NLopt.optimize(opt, optsum.initial) optsum.feval = opt.numevals optsum.final = xmin optsum.fmin = fmin optsum.returnvalue = ret # save the results η = xmin[1] (n2ll, σ², Vmchol) = logliksigma(η) model_within.wsp_var[1] = η*σ² model_within.bsp_var[1] = σ² return model_within, Vmchol.L end ############################################################################### #= Model comparisons isnested: borrowed from GLM.issubmodel (as of commit 504e5186c87) https://github.com/JuliaStats/GLM.jl/blob/master/src/ftest.jl#L11 To avoid comparing the coefnames and to be less restrictive, we compare the design matrices. For example: Xsmall = [x1-x2 x1-x3] is nested in Xbig = [x1 x2 x3]. We check that there exists B such that Xsmall = Xbig * B, or rather, that min_B norm(Xbig*B - Xsmall) ≈ 0 . For the math of this minimization problem, see https://github.com/JuliaStats/GLM.jl/pull/197#issuecomment-331136617 When isnested() exists in GLM, check to see if we should improve further. =# """ isnested(m1::PhyloNetworkLinearModel, m2::PhyloNetworkLinearModel) isnested(m1::ContinuousTraitEM, m2::ContinuousTraitEM) True if `m1` is nested in `m2`, false otherwise. Models fitted with different criteria (ML and REML) are not nested. Models with different predictors (fixed effects) must be fitted with ML to be considered nested. """ function StatsModels.isnested(m1m::PhyloNetworkLinearModel, m2m::PhyloNetworkLinearModel; atol::Real=0.0) if !(nobs(m1m) ≈ nobs(m2m)) @error "Models must have the same number of observations" return false end # exact same response? (before phylogenetic transformation) if m1m.Y != m2m.Y @error "Models must fit the same response" return false end # same criterion? if xor(m1m.reml, m2m.reml) @error "Models must be fitted with same criterion (both ML or both REML)" return false end # same within-species variation? e.g. same assumption of species means # this check should be useless, because same Y so same # species, and same # nobs so same # individuals. But 1 ind/species w/o within-species variation, # and at least 1 species with 2+ inds/species w/ within-species variation. xor(isnothing(m1m.model_within), isnothing(m2m.model_within)) && return false # nesting of fixed effects: is X1 = X2*B for some B? X1 = m1m.X np1 = size(X1, 2) X2 = m2m.X np2 = size(X2, 2) np1 > np2 && return false # if X1 has more predictors, can't be nested in X2 # is mininum_B norm X2*B - X1 ≈ 0 ? rtol = Base.rtoldefault(eltype(X1)) norm(view(qr(X2).Q' * X1, np2 + 1:size(X2,1), :)) < max(atol, rtol*norm(X1)) || return false # ML (not REML) if different fixed effects sameFE = (X1 == X2) # exact equality okay here if !sameFE && (m1m.reml || m2m.reml) @error "Models should be fitted with ML to do a likelihood ratio test with different predictors" return false end # nesting of phylogenetic variance models return isnested(m1m.evomodel, m2m.evomodel) end isnested(::T,::T) where T <: ContinuousTraitEM = true isnested(::BM,::Union{PagelLambda,ScalingHybrid}) = true isnested(::Union{PagelLambda,ScalingHybrid}, ::BM) = false isnested(::ScalingHybrid,::PagelLambda) = false isnested(::PagelLambda,::ScalingHybrid) = false #= ANOVA using ftest from GLM - need version 0.8.1 As of GLM v1.8, ftest throws a warning on typical BM models, one per model: "Starting from GLM.jl 1.8, null model is defined as having no predictor at all when a model without an intercept is passed." This is because after transforming the data to de-correlate the residuals, the transformed intercept vector is not proportional to the constant vector 1. The warning is from: ftest → r2(phylomodel.lm) → nulldeviance(phylomodel.lm) → warning. R² by GLM is wrong: assume *no* intercept, and are based on the transformed data. R² corrected them below: r2(phylomodel) reimplemented here. But nulldeviance(phylomodel) does *not* call nulldeviance(phylomodel.lm), instead re-implemented here to use the intercept properly. Keep the warnings: unless they can be suppressed with specificity Ideally: modify `ftest` here or in GLM. =# function GLM.ftest(objs::PhyloNetworkLinearModel...) if !all( isa(o.evomodel,BM) && isnothing(o.model_within) for o in objs) throw(ArgumentError("""F test is only valid for the vanilla BM model. Use a likelihood ratio test instead with function `lrtest`.""")) end objslm = [obj.lm for obj in objs] resGLM = ftest(objslm...) resGLM.r2 = r2.(objs) return resGLM end ## ANOVA: old version - kept for tests purposes - do not export """ anova(objs::PhyloNetworkLinearModel...) Takes several nested fits of the same data, and computes the F statistic for each pair of models. The fits must be results of function [`phylolm`](@ref) called on the same data, for models that have more and more effects. Returns a DataFrame object with the anova table. """ function anova(objs::PhyloNetworkLinearModel...) anovaTable = Array{Any}(undef, length(objs)-1, 6) ## Compute binary statistics for i in 1:(length(objs) - 1) anovaTable[i, :] = anovaBin(objs[i], objs[i+1]) end ## Transform into a DataFrame anovaTable = DataFrame(anovaTable, [:dof_res, :RSS, :dof, :SS, :F, Symbol("Pr(>F)")]) return(anovaTable) end function anovaBin(obj1::PhyloNetworkLinearModel, obj2::PhyloNetworkLinearModel) length(coef(obj1)) < length(coef(obj2)) || error("Models must be nested, from the smallest to the largest.") ## residuals dof2 = dof_residual(obj2) dev2 = deviance(obj2, Val(true)) ## reducted residuals dof1 = dof_residual(obj1) - dof2 dev1 = deviance(obj1, Val(true)) - dev2 ## Compute statistic F = (dev1 / dof1) / (dev2 / dof2) pval = GLM.ccdf.(GLM.FDist(dof1, dof2), F) # ccdf and FDist from Distributions, used by GLM return([dof2, dev2, dof1, dev1, F, pval]) end ############################################################################### ## Ancestral State Reconstruction ############################################################################### """ ReconstructedStates Type containing the inferred information about the law of the ancestral states given the observed tips values. The missing tips are considered as ancestral states. The following functions can be applied to it: [`expectations`](@ref) (vector of expectations at all nodes), `stderror` (the standard error), `predint` (the prediction interval). The `ReconstructedStates` object has fields: `traits_nodes`, `variances_nodes`, `NodeNumbers`, `traits_tips`, `tipNumbers`, `model`. Type in "?ReconstructedStates.field" to get help on a specific field. """ struct ReconstructedStates "traits_nodes: the infered expectation of 'missing' values (ancestral nodes and missing tips)" traits_nodes::Vector # Nodes are actually "missing" data (including tips) "variances_nodes: the variance covariance matrix between all the 'missing' nodes" variances_nodes::Matrix "NodeNumbers: vector of the nodes numbers, in the same order as `traits_nodes`" NodeNumbers::Vector{Int} "traits_tips: the observed traits values at the tips" traits_tips::Vector # Observed values at tips "TipNumbers: vector of tips numbers, in the same order as `traits_tips`" TipNumbers::Vector # Observed tips only "model: if not missing, the `PhyloNetworkLinearModel` used for the computations." model::Union{PhyloNetworkLinearModel, Missing} # if empirical, corresponding fitted object end """ expectations(obj::ReconstructedStates) Estimated reconstructed states at the nodes and tips. """ function expectations(obj::ReconstructedStates) return DataFrame(nodeNumber = [obj.NodeNumbers; obj.TipNumbers], condExpectation = [obj.traits_nodes; obj.traits_tips]) end """ expectationsPlot(obj::ReconstructedStates) Compute and format the expected reconstructed states for the plotting function. The resulting dataframe can be readily used as a `nodelabel` argument to `plot` from package [`PhyloPlots`](https://github.com/cecileane/PhyloPlots.jl). Keyword argument `markMissing` is a string that is appended to predicted tip values, so that they can be distinguished from the actual datapoints. Default to "*". Set to "" to remove any visual cue. """ function expectationsPlot(obj::ReconstructedStates; markMissing="*"::AbstractString) # Retrieve values expe = expectations(obj) # Format values for plot expetxt = Array{AbstractString}(undef, size(expe, 1)) for i=1:size(expe, 1) expetxt[i] = string(round(expe[i, 2], digits=2)) end # find tips absent from dataframe or with missing data: add a mark if !ismissing(obj.model) nonmissing = obj.model.nonmissing ind = obj.model.ind tipnumbers = obj.model.V.tipNumbers # all tips, even those absent from dataframe tipnumbers_data = tipnumbers[ind][nonmissing] # listed and data non-missing tipnumbers_imputed = setdiff(tipnumbers, tipnumbers_data) indexMissing = indexin(tipnumbers_imputed, expe[!,:nodeNumber]) expetxt[indexMissing] .*= markMissing end return DataFrame(nodeNumber = [obj.NodeNumbers; obj.TipNumbers], PredInt = expetxt) end StatsBase.stderror(obj::ReconstructedStates) = sqrt.(diag(obj.variances_nodes)) """ predint(obj::ReconstructedStates; level=0.95::Real) Prediction intervals with level `level` for internal nodes and missing tips. """ function predint(obj::ReconstructedStates; level=0.95::Real) if ismissing(obj.model) qq = quantile(Normal(), (1. - level)/2.) else qq = quantile(GLM.TDist(dof_residual(obj.model)), (1. - level)/2.) # TDist from Distributions # @warn "As the variance is estimated, the predictions intervals are not exact, and should probably be larger." end tmpnode = hcat(obj.traits_nodes, obj.traits_nodes) .+ (stderror(obj) * qq) .* [1. -1.] return vcat(tmpnode, hcat(obj.traits_tips, obj.traits_tips)) end function Base.show(io::IO, obj::ReconstructedStates) println(io, "$(typeof(obj)):\n", CoefTable(hcat(vcat(obj.NodeNumbers, obj.TipNumbers), vcat(obj.traits_nodes, obj.traits_tips), predint(obj)), ["Node index", "Pred.", "Min.", "Max. (95%)"], fill("", length(obj.NodeNumbers)+length(obj.TipNumbers)))) end """ predintPlot(obj::ReconstructedStates; level=0.95::Real, withExp=false::Bool) Compute and format the prediction intervals for the plotting function. The resulting dataframe can be readily used as a `nodelabel` argument to `plot` from package [`PhyloPlots`](https://github.com/cecileane/PhyloPlots.jl). Keyworks argument `level` control the confidence level of the prediction interval. If `withExp` is set to true, then the best predicted value is also shown along with the interval. """ function predintPlot(obj::ReconstructedStates; level=0.95::Real, withExp=false::Bool) # predInt pri = predint(obj; level=level) pritxt = Array{AbstractString}(undef, size(pri, 1)) # Exp withExp ? exptxt = expectationsPlot(obj, markMissing="") : exptxt = "" for i=1:length(obj.NodeNumbers) !withExp ? sep = ", " : sep = "; " * exptxt[i, 2] * "; " pritxt[i] = "[" * string(round(pri[i, 1], digits=2)) * sep * string(round(pri[i, 2], digits=2)) * "]" end for i=(length(obj.NodeNumbers)+1):size(pri, 1) pritxt[i] = string(round(pri[i, 1], digits=2)) end return DataFrame(nodeNumber = [obj.NodeNumbers; obj.TipNumbers], PredInt = pritxt) end #= ----- roadmap of ancestralStateReconstruction, continuous traits ------ all methods return a ReconstructedStates object. core method called by every other method: 1. ancestralStateReconstruction(Vzz, VzyVyinvchol, RL, Y, m_y, m_z, NodeNumbers, TipNumbers, sigma2, add_var, model) higher-level methods, for real data: 2. ancestralStateReconstruction(dataframe, net; tipnames=:tipNames, kwargs...) - dataframe: 2 columns only, species names & tip response values - fits an intercept-only model, then calls #3 - by default without kwargs: model = BM w/o within-species variation 3. ancestralStateReconstruction(PhyloNetworkLinearModel[, Matrix]) - takes a model already fitted - if no matrix given: the model must be intercept-only. An expanded intercept column is created with length = # nodes with *no* data - matrix: if given, must have same # of columns as the model matrix, and must contain the predictor(s) at nodes with *no* data, with nodes listed in the following order: * internal nodes first, in the same order in which they appear in net.node, i.e in V.internalNodeNumbers * then leaves with no data, in the same order in which they appear in tipLabels(net), i.e. in V.tipNumbers. - extracts the predicted values for all network nodes, and the unscaled 3 covariance matrices of interest (nodes with data, nodes w/o, crossed) - computes "universal" kriging (as opposed to "simple" kriging, which would simply plug-in estimates into the prediction variance formula): a term is added to the prediction variance, to account for the estimation of β. methods based on simulations with a ParamsProcess "params": 4. ancestralStateReconstruction(net, Y, params) which calls: ancestralStateReconstruction(V::MatrixTopologicalOrder, Y, params) - intercept-only: known β and known variance: "simple" kriging is correct - BM only: params must be of type ParamsBM =# """ ancestralStateReconstruction(net::HybridNetwork, Y::Vector, params::ParamsBM) Compute the conditional expectations and variances of the ancestral (un-observed) traits values at the internal nodes of the phylogenetic network (`net`), given the values of the traits at the tips of the network (`Y`) and some known parameters of the process used for trait evolution (`params`, only BM with fixed root works for now). This function assumes that the parameters of the process are known. For a more general function, see `ancestralStateReconstruction(obj::PhyloNetworkLinearModel[, X_n::Matrix])`. """ function ancestralStateReconstruction(net::HybridNetwork, Y::Vector, params::ParamsBM) V = sharedPathMatrix(net) ancestralStateReconstruction(V, Y, params) end function ancestralStateReconstruction(V::MatrixTopologicalOrder, Y::Vector, params::ParamsBM) # Variances matrices Vy = V[:Tips] Vz = V[:InternalNodes] Vyz = V[:TipsNodes] R = cholesky(Vy) RL = R.L VzyVyinvchol = (RL \ Vyz)' # Vectors of means m_y = ones(size(Vy)[1]) .* params.mu # !! correct only if no predictor. m_z = ones(size(Vz)[1]) .* params.mu # !! works if BM no shift. # Actual computation ancestralStateReconstruction(Vz, VzyVyinvchol, RL, Y, m_y, m_z, V.internalNodeNumbers, V.tipNumbers, params.sigma2) end # Reconstruction from all the needed quantities function ancestralStateReconstruction(Vz::Matrix, VzyVyinvchol::AbstractMatrix, RL::LowerTriangular, Y::Vector, m_y::Vector, m_z::Vector, NodeNumbers::Vector, TipNumbers::Vector, sigma2::Real, add_var=zeros(size(Vz))::Matrix, # Additional variance for BLUP model=missing::Union{PhyloNetworkLinearModel,Missing}) # E[z∣y] = E[z∣X] + Cov(z,y)⋅Var(y)⁻¹⋅(y-E[y∣X]) m_z_cond_y = m_z + VzyVyinvchol * (RL \ (Y - m_y)) V_z_cond_y = sigma2 .* (Vz - VzyVyinvchol * VzyVyinvchol') if !ismissing(model) && !isnothing(model.model_within) # y = last part of z Y = similar(Y, 0) # empty vector of similar type as Y end ReconstructedStates(m_z_cond_y, V_z_cond_y + add_var, NodeNumbers, Y, TipNumbers, model) end #= from a fitted object: see high-level docstring below X_n: matrix with as many columns as the number of predictors used, and as many rows as the number of unknown nodes or tips. TO DO: Handle the order of internal nodes and no-data tips for matrix X_n =# function ancestralStateReconstruction(obj::PhyloNetworkLinearModel, X_n::Matrix) if (size(X_n)[2] != length(coef(obj))) error("""The number of predictors for the ancestral states (number of columns of X_n) does not match the number of predictors at the tips.""") end if size(X_n)[1] != length(obj.V.internalNodeNumbers) + length(obj.V.tipNumbers)-length(obj.ind) + sum(.!obj.nonmissing) error("""The number of lines of the predictors does not match the number of nodes plus the number of missing tips.""") end #= y: observed species means at some tips z: trait (true species mean) at nodes to be predicted: - at nodes without data, i.e. internal nodes & no-data tips - at tips with data if within-species variation: y=ytrue+ϵ Vy,y = Vy,ytrue = Vytrue,y and Vytrue,z = Vyz =# m_y = predict(obj) m_z = X_n * coef(obj) # If the tips were re-organized, do the same for Vyz if obj.ind == [0] @warn """There were no indication for the position of the tips on the network. I am assuming that they are given in the same order. Please check that this is what you intended.""" ind = collect(1:length(obj.V.tipNumbers)) else ind = obj.ind end # Vyz: sharedpath. rows y: tips w/ data. cols z: internal nodes & tips w/o data Vyz = obj.V[:TipsNodes, ind, obj.nonmissing] Vzz = obj.V[:InternalNodes, ind, obj.nonmissing] nmTipNumbers = obj.V.tipNumbers[ind][obj.nonmissing] # tips w/ data # no-data node numbers: for nodes (internal or tips) with no data ndNodeNumbers = [obj.V.internalNodeNumbers; setdiff(obj.V.tipNumbers, nmTipNumbers)] if !isnothing(obj.model_within) # add tips with data to z Vtips = obj.V[:Tips, ind, obj.nonmissing] Vzz = [Vzz Vyz'; Vyz Vtips] Vyz = [Vyz Vtips] append!(m_z, m_y) append!(ndNodeNumbers, nmTipNumbers) empty!(nmTipNumbers) X_n = vcat(X_n, obj.X) end VzyVyinvchol = (obj.RL \ Vyz)' # add_var = zeros corresponds to "simple" kriging: E[Y∣X]=Xβ with known β & variance components # below: "universal" kriging: β estimated, variance components known U = X_n - VzyVyinvchol * (obj.RL \ obj.X) add_var = U * vcov(obj) * U' @warn """These prediction intervals show uncertainty in ancestral values, assuming that the estimated variance rate of evolution is correct. Additional uncertainty in the estimation of this variance rate is ignored, so prediction intervals should be larger.""" # Actual reconstruction ancestralStateReconstruction(Vzz, VzyVyinvchol, obj.RL, obj.Y, m_y, m_z, ndNodeNumbers, nmTipNumbers, sigma2_phylo(obj), add_var, obj) end @doc raw""" ancestralStateReconstruction(obj::PhyloNetworkLinearModel[, X_n::Matrix]) Function to find the ancestral traits reconstruction on a network, given an object fitted by function [`phylolm`](@ref). By default, the function assumes that the regressor is just an intercept. If the value of the regressor for all the ancestral states is known, it can be entered in X_n, a matrix with as many columns as the number of predictors used, and as many lines as the number of unknown nodes or tips. Returns an object of type [`ReconstructedStates`](@ref). # Examples ```jldoctest; filter = [r" PhyloNetworks .*:\d+", ] julia> using DataFrames, CSV # to read data file julia> phy = readTopology(joinpath(dirname(pathof(PhyloNetworks)), "..", "examples", "carnivores_tree.txt")); julia> dat = CSV.File(joinpath(dirname(pathof(PhyloNetworks)), "..", "examples", "carnivores_trait.txt")) |> DataFrame; julia> using StatsModels # for statistical model formulas julia> fitBM = phylolm(@formula(trait ~ 1), dat, phy); julia> ancStates = ancestralStateReconstruction(fitBM) # Should produce a warning, as variance is unknown. ┌ Warning: These prediction intervals show uncertainty in ancestral values, │ assuming that the estimated variance rate of evolution is correct. │ Additional uncertainty in the estimation of this variance rate is │ ignored, so prediction intervals should be larger. └ @ PhyloNetworks ~/build/crsl4/PhyloNetworks.jl/src/traits.jl:3359 ReconstructedStates: ─────────────────────────────────────────────── Node index Pred. Min. Max. (95%) ─────────────────────────────────────────────── -5.0 1.32139 -0.33824 2.98102 -8.0 1.03258 -0.589695 2.65485 -7.0 1.41575 -0.140705 2.97221 -6.0 1.39417 -0.107433 2.89577 -4.0 1.39961 -0.102501 2.90171 -3.0 1.51341 -0.220523 3.24733 -13.0 5.3192 3.92279 6.71561 -12.0 4.51176 2.89222 6.13131 -16.0 1.50947 -0.0186118 3.03755 -15.0 1.67425 0.196069 3.15242 -14.0 1.80309 0.309992 3.29618 -11.0 2.7351 1.17608 4.29412 -10.0 2.73217 1.12361 4.34073 -9.0 2.41132 0.603932 4.21871 -2.0 2.04138 -0.0340955 4.11686 14.0 1.64289 1.64289 1.64289 8.0 1.67724 1.67724 1.67724 5.0 0.331568 0.331568 0.331568 2.0 2.27395 2.27395 2.27395 4.0 0.275237 0.275237 0.275237 6.0 3.39094 3.39094 3.39094 13.0 0.355799 0.355799 0.355799 15.0 0.542565 0.542565 0.542565 7.0 0.773436 0.773436 0.773436 10.0 6.94985 6.94985 6.94985 11.0 4.78323 4.78323 4.78323 12.0 5.33016 5.33016 5.33016 1.0 -0.122604 -0.122604 -0.122604 16.0 0.73989 0.73989 0.73989 9.0 4.84236 4.84236 4.84236 3.0 1.0695 1.0695 1.0695 ─────────────────────────────────────────────── julia> expectations(ancStates) 31×2 DataFrame Row │ nodeNumber condExpectation │ Int64 Float64 ─────┼───────────────────────────── 1 │ -5 1.32139 2 │ -8 1.03258 3 │ -7 1.41575 4 │ -6 1.39417 5 │ -4 1.39961 6 │ -3 1.51341 7 │ -13 5.3192 8 │ -12 4.51176 ⋮ │ ⋮ ⋮ 25 │ 10 6.94985 26 │ 11 4.78323 27 │ 12 5.33016 28 │ 1 -0.122604 29 │ 16 0.73989 30 │ 9 4.84236 31 │ 3 1.0695 16 rows omitted julia> predint(ancStates) 31×2 Matrix{Float64}: -0.33824 2.98102 -0.589695 2.65485 -0.140705 2.97221 -0.107433 2.89577 -0.102501 2.90171 -0.220523 3.24733 3.92279 6.71561 2.89222 6.13131 -0.0186118 3.03755 0.196069 3.15242 ⋮ 0.542565 0.542565 0.773436 0.773436 6.94985 6.94985 4.78323 4.78323 5.33016 5.33016 -0.122604 -0.122604 0.73989 0.73989 4.84236 4.84236 1.0695 1.0695 julia> expectationsPlot(ancStates) # format the ancestral states 31×2 DataFrame Row │ nodeNumber PredInt │ Int64 Abstract… ─────┼─────────────────────── 1 │ -5 1.32 2 │ -8 1.03 3 │ -7 1.42 4 │ -6 1.39 5 │ -4 1.4 6 │ -3 1.51 7 │ -13 5.32 8 │ -12 4.51 ⋮ │ ⋮ ⋮ 25 │ 10 6.95 26 │ 11 4.78 27 │ 12 5.33 28 │ 1 -0.12 29 │ 16 0.74 30 │ 9 4.84 31 │ 3 1.07 16 rows omitted julia> using PhyloPlots # next: plot ancestral states on the tree julia> plot(phy, nodelabel = expectationsPlot(ancStates)); julia> predintPlot(ancStates) # prediction intervals, in data frame, useful to plot 31×2 DataFrame Row │ nodeNumber PredInt │ Int64 Abstract… ─────┼─────────────────────────── 1 │ -5 [-0.34, 2.98] 2 │ -8 [-0.59, 2.65] 3 │ -7 [-0.14, 2.97] 4 │ -6 [-0.11, 2.9] 5 │ -4 [-0.1, 2.9] 6 │ -3 [-0.22, 3.25] 7 │ -13 [3.92, 6.72] 8 │ -12 [2.89, 6.13] ⋮ │ ⋮ ⋮ 25 │ 10 6.95 26 │ 11 4.78 27 │ 12 5.33 28 │ 1 -0.12 29 │ 16 0.74 30 │ 9 4.84 31 │ 3 1.07 16 rows omitted julia> plot(phy, nodelabel = predintPlot(ancStates)); julia> allowmissing!(dat, :trait); julia> dat[[2, 5], :trait] .= missing; # missing values allowed to fit model julia> fitBM = phylolm(@formula(trait ~ 1), dat, phy); julia> ancStates = ancestralStateReconstruction(fitBM); ┌ Warning: These prediction intervals show uncertainty in ancestral values, │ assuming that the estimated variance rate of evolution is correct. │ Additional uncertainty in the estimation of this variance rate is │ ignored, so prediction intervals should be larger. └ @ PhyloNetworks ~/build/crsl4/PhyloNetworks.jl/src/traits.jl:3166 julia> first(expectations(ancStates), 3) # looking at first 3 nodes only 3×2 DataFrame Row │ nodeNumber condExpectation │ Int64 Float64 ─────┼───────────────────────────── 1 │ -5 1.42724 2 │ -8 1.35185 3 │ -7 1.61993 julia> predint(ancStates)[1:3,:] # just first 3 nodes again 3×2 Matrix{Float64}: -0.373749 3.22824 -0.698432 3.40214 -0.17179 3.41165 julia> first(expectationsPlot(ancStates),3) # format node <-> ancestral state 3×2 DataFrame Row │ nodeNumber PredInt │ Int64 Abstract… ─────┼─────────────────────── 1 │ -5 1.43 2 │ -8 1.35 3 │ -7 1.62 julia> plot(phy, nodelabel = expectationsPlot(ancStates)); julia> first(predintPlot(ancStates),3) # prediction intervals, useful to plot 3×2 DataFrame Row │ nodeNumber PredInt │ Int64 Abstract… ─────┼─────────────────────────── 1 │ -5 [-0.37, 3.23] 2 │ -8 [-0.7, 3.4] 3 │ -7 [-0.17, 3.41] julia> plot(phy, nodelabel = predintPlot(ancStates)); ``` """ function ancestralStateReconstruction(obj::PhyloNetworkLinearModel) # default reconstruction for known predictors if ((size(obj.X)[2] != 1) || !any(obj.X .== 1)) # Test if the regressor is just an intercept. error("""Predictor(s) other than a plain intercept are used in this `PhyloNetworkLinearModel` object. These predictors are unobserved at ancestral nodes, so they cannot be used for the ancestral state reconstruction. If these ancestral predictor values are known, please provide them as a matrix argument to the function. Otherwise, you might consider doing a multivariate linear regression (not implemented yet).""") end X_n = ones((length(obj.V.nodeNumbersTopOrder) - sum(obj.nonmissing), 1)) ancestralStateReconstruction(obj, X_n) end """ ancestralStateReconstruction(fr::AbstractDataFrame, net::HybridNetwork; kwargs...) Estimate the ancestral traits on a network, given some data at the tips. Uses function [`phylolm`](@ref) to perform a phylogenetic regression of the data against an intercept (amounts to fitting an evolutionary model on the network). See documentation on [`phylolm`](@ref) and `ancestralStateReconstruction(obj::PhyloNetworkLinearModel[, X_n::Matrix])` for further details. Returns an object of type [`ReconstructedStates`](@ref). """ function ancestralStateReconstruction(fr::AbstractDataFrame, net::HybridNetwork; tipnames::Symbol=:tipNames, kwargs...) nn = DataFrames.propertynames(fr) datpos = nn .!= tipnames if sum(datpos) > 1 error("""Besides one column labelled '$tipnames', the dataframe fr should have only one column, corresponding to the data at the tips of the network.""") end f = @eval(@formula($(nn[datpos][1]) ~ 1)) reg = phylolm(f, fr, net; tipnames=tipnames, kwargs...) return ancestralStateReconstruction(reg) end ################################################# ## Old version of phylolm (naive) ################################################# # function phylolmNaive(X::Matrix, Y::Vector, net::HybridNetwork, model="BM"::AbstractString) # # Geting variance covariance # V = sharedPathMatrix(net) # Vy = extractVarianceTips(V, net) # # Needed quantities (naive) # ntaxa = length(Y) # Vyinv = inv(Vy) # XtVyinv = X' * Vyinv # logdetVy = logdet(Vy) # # beta hat # betahat = inv(XtVyinv * X) * XtVyinv * Y # # sigma2 hat # fittedValues = X * betahat # residuals = Y - fittedValues # sigma2hat = 1/ntaxa * (residuals' * Vyinv * residuals) # # log likelihood # loglik = - 1 / 2 * (ntaxa + ntaxa * log(2 * pi) + ntaxa * log(sigma2hat) + logdetVy) # # Result # # res = phyloNetworkRegression(betahat, sigma2hat[1], loglik[1], V, Vy, fittedValues, residuals) # return((betahat, sigma2hat[1], loglik[1], V, Vy, logdetVy, fittedValues, residuals)) # end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
54465
""" StatisticalSubstitutionModel Subtype of `StatsBase.StatisticalModel`, to fit discrete data to a model of trait substitution along a network. See [`fitdiscrete`](@ref) to fit a trait substitution model to discrete data. It returns an object of type `StatisticalSubstitutionModel`, to which standard functions can be applied, like `loglikelihood(object)`, `aic(object)` etc. """ mutable struct StatisticalSubstitutionModel <: StatsBase.StatisticalModel model::SubstitutionModel ratemodel::RateVariationAcrossSites """stationary for NASM models (log(1/4)), uniform in all other cases""" prioratroot::Vector{Float64} net::HybridNetwork """ data: trait[i] for leaf with n.number = i type Int: for indices of trait labels in getlabels(model) allows missing, but not half-ambiguous and not multi-state""" trait::Vector{Vector{Union{Missing, Int}}} "number of columns in the data: should be equal to `length(trait[i])` for all i" nsites::Int "vector of weights, one for each column, taken as 1s if not provided" siteweight::Union{Nothing, Vector{Float64}} "total sum of site weights" totalsiteweight::Float64 """ log of transition probabilities: where e goes from X to Y logtrans[i,j,e,r] = P{Y=j|X=i} where i=start_state, j=end_state, e=edge.number, r = rate (if using RateVariationAcrossSites) all displayed trees use same edge numbers and same logtrans as in full network """ loglik::Union{Missings.Missing, Float64} """ log of transition probabilities. size: k,k, net.numEdges, r where k=nstates(model) """ logtrans::Array{Float64,4} # type based on extracting displayed trees displayedtree::Vector{HybridNetwork} """ prior log tree weight: log product of γ's. In fit!: priorltw = `inheritanceWeight.(trees)` (which returns missing for any negative γ and would cause an error here) """ priorltw::Vector{Float64} """ partial log-likelihoods for active trait(s) given a particular displayed tree and a particular rate category, at indices [i, n.number or e.number]: - forward likelihood: log P{data below node n (in tree t) given state i at n} - direct likelihood: log P{data below edge e (in tree t) given i at parent of e} - backward likelihood:log P{data at all non-descendants of n (in t) and state i at n} sizes: k, net.numNodes or net.numEdges. """ # reset for each trait and rate forwardlik::Array{Float64,2} # size: k, net.numNodes directlik::Array{Float64,2} # size: k, net.numEdges backwardlik::Array{Float64,2}# size: k, net.numNodes "log-likelihood of site k" _sitecache::Array{Float64,1} # size: nsites "log-likelihood of ith displayed tree t & rate category j, of site k" _loglikcache::Array{Float64, 3} # size: nsites, nrates, ntrees "inner (default) constructor: from model, rate model, network, trait and site weights" function StatisticalSubstitutionModel(model::SubstitutionModel, ratemodel::RateVariationAcrossSites, net::HybridNetwork, trait::AbstractVector, siteweight=nothing::Union{Nothing, Vector{Float64}}, maxhybrid=length(net.hybrid)::Int) length(trait) > 0 || error("no trait data!") nsites = length(trait[1]) siteweight === nothing || length(siteweight) == nsites || error("siteweight must be of same length as the number of traits") totalsiteweight = (siteweight === nothing ? float(nsites) : sum(siteweight)) k = nstates(model) if typeof(model) <: NASM prioratroot = log.(stationary(model)) #refactor to save in obj else # other trait models prioratroot = [-log(k) for i in 1:k] # uniform prior at root end # T = eltype(getlabels(model)) # extract displayed trees trees = displayedTrees(net, 0.0; nofuse=true, keeporiginalroot=true) for tree in trees preorder!(tree) # no need to call directEdges! before: already done on net end ntrees = 2^maxhybrid ntrees >= length(trees) || error("""maxhybrid is too low. Call using maxhybrid >= current number of hybrids""") # log tree weights: sum log(γ) over edges, for each displayed tree priorltw = inheritanceWeight.(trees) all(!ismissing, priorltw) || error("one or more inheritance γ's are missing or negative. fix using setGamma!(network, edge)") maxedges = length(net.edge) + 3*(maxhybrid-length(net.hybrid)) maxnodes = length(net.node) + 2*(maxhybrid-length(net.hybrid)) logtrans = zeros(Float64, k,k, maxedges, length(ratemodel.ratemultiplier)) forwardlik = zeros(Float64, k, maxnodes) directlik = zeros(Float64, k, maxedges) backwardlik= zeros(Float64, k, maxnodes) _sitecache = Vector{Float64}(undef, nsites) _loglikcache = zeros(Float64, nsites, length(ratemodel.ratemultiplier), ntrees) new(deepcopy(model), deepcopy(ratemodel), prioratroot, net, trait, nsites, siteweight, totalsiteweight, missing, # missing log likelihood logtrans, trees, priorltw, forwardlik, directlik, backwardlik,_sitecache,_loglikcache) end end const SSM = StatisticalSubstitutionModel # fasta constructor: from net, fasta filename, modsymbol, and maxhybrid # Works for DNA in fasta format. Probably need different versions for # different kinds of data (snp, amino acids). Similar to fitdiscrete() """ StatisticalSubstitutionModel(model::SubstitutionModel, ratemodel::RateVariationAcrossSites, net::HybridNetwork, trait::AbstractVector, siteweight=nothing::Union{Nothing, Vector{Float64}}, maxhybrid=length(net.hybrid)::Int) Inner constructor. Makes a deep copy of the input model, rate model. Warning: does *not* make a deep copy of the network: modification of the `object.net` would modify the input `net`. Assumes that the network has valid gamma values (to extract displayed trees). StatisticalSubstitutionModel(net::HybridNetwork, fastafile::String, modsymbol::Symbol, rvsymbol=:noRV::Symbol, ratecategories=4::Int; maxhybrid=length(net.hybrid)::Int) Constructor from a network and a fasta file. The model symbol should be one of `:JC69`, `:HKY85`, `:ERSM` or `:BTSM`. The `rvsymbol` should be as required by [`RateVariationAcrossSites`](@ref). The network's gamma values are modified if they are missing. After that, a deep copy of the network is passed to the inner constructor. """ function StatisticalSubstitutionModel(net::HybridNetwork, fastafile::AbstractString, modsymbol::Symbol, rvsymbol=:noRV::Symbol, ratecategories=4::Int; maxhybrid=length(net.hybrid)::Int) for e in net.edge # check for missing or inappropriate γ values if e.hybrid e.gamma > 0.0 && continue setGamma!(e, (e.isMajor ? 0.6 : 0.4)) # to maintain isMajor as is else e.gamma == 1.0 || error("tree edge number $(e.number) has γ not 1.0") end end data, siteweights = readfastatodna(fastafile, true) model = defaultsubstitutionmodel(net, modsymbol, data, siteweights) ratemodel = RateVariationAcrossSites(rvsymbol, ratecategories) dat2 = traitlabels2indices(view(data, :, 2:size(data,2)), model) # check_matchtaxonnames makes a deep copy of the network o, net = check_matchtaxonnames!(data[:,1], dat2, net) # calls resetNodeNumbers, which calls preorder! trait = dat2[o] obj = StatisticalSubstitutionModel(model, ratemodel, net, trait, siteweights, maxhybrid) end StatsBase.loglikelihood(obj::SSM) = obj.loglik StatsBase.islinear(SSM) = false StatsBase.dof(obj::SSM) = nparams(obj.model) + nparams(obj.ratemodel) function Base.show(io::IO, obj::SSM) disp = "$(typeof(obj)):\n" disp *= replace(string(obj.model), r"\n" => "\n ") * "\n" if nparams(obj.ratemodel) > 0 disp *= replace(string(obj.ratemodel), r"\n" => "\n ") * "\n" end disp *= "on a network with $(obj.net.numHybrids) reticulations\n" print(io, disp) showdata(io, obj) if !ismissing(obj.loglik) print(io, "\nlog-likelihood: $(round(obj.loglik, digits=5))") end end """ showdata(io::IO, obj::SSM, fullsiteinfo=false::Bool) Return information about the data in an SSM object: number of species, number or traits or sites, number of distinct patterns, and more information if `fullsiteinfo` is true: number sites with missing data only, number of invariant sites, number of sites with 2 distinct states, number of parsimony-informative sites (with 2+ states being observed in 2+ tips), number of sites with some missing data, and overall proportion of entries with missing data. Note: Missing is not considered an additional state. For example, if a site contains some missing data, but all non-missing values take the same state, then this site is counted in the category "invariant". """ function showdata(io::IO, obj::SSM, fullsiteinfo=false::Bool) disp = "data:\n $(length(obj.trait)) species" ns = obj.totalsiteweight ns = (isapprox(ns, round(ns), atol=1e-5) ? Int(round(ns)) : ns) disp *= (ns ≈ 1 ? "\n $ns trait" : "\n $ns sites") if !isapprox(obj.nsites, ns, atol=1e-5) disp *= "\n $(obj.nsites) distinct patterns" end print(io, disp) (fullsiteinfo && obj.nsites != 1) || return nothing # if more than 1 trait and if the user wants full information: nsv = MVector{6,Float64}(undef) # vector to count number of # sites with: 0, 1, 2 states, parsimony informative, with 1+ missing value, # missing values across all sites. fill!(nsv, 0.0) text = ["sites with no data", "invariant sites", "sites with 2 distinct states", "parsimony-informative sites", "sites with 1 or more missing values", "missing values overall"] trackstates = zeros(Int, nstates(obj.model)) # states seen at a given site ntaxa = length(obj.trait) for i in 1:(obj.nsites) # over sites sweight = (isnothing(obj.siteweight) ? 1.0 : obj.siteweight[i]) missone = false fill!(trackstates, 0) for j in 1:ntaxa # over taxa data = obj.trait[j][i] if ismissing(data) nsv[6] += sweight # total number of missing values missone && continue nsv[5] += sweight # sites with 1+ missing values missone = true else # mark state seen trackstates[data] += 1 # 1 more taxon end end # add site's weight to appropriate nstates nstates = sum(trackstates .> 0) if nstates < 3 nsv[nstates+1] += sweight end if nstates>1 # are there 2 states observed at 2+ taxa each? nstates_2taxa = sum(trackstates .> 1) if nstates_2taxa>1 nsv[4] += sweight end end end nsv_r = map(x -> begin y=round(x); (isapprox(y,x,atol=1e-5) ? Int(y) : x); end, nsv) for i in 1:5 print(io, "\n $(nsv_r[i]) $(text[i]) ($(round(100*nsv[i]/ns, digits=2))%)") end print(io, "\n $(round(100*nsv[6]/(ns*ntaxa), digits=2))% $(text[6])") end # nobs: nsites * nspecies, minus any missing, but ignores correlation between species # fixit: extend the StatsBase methods # coef, coefnames, coeftable, confint, # deviance (not from loglik in StatsBase), nulldeviance (from intercept only. here?) # nullloglikelihood (from intercept only. here?) # score (gradient of loglik) # informationmatrix: Fisher by default, observed info matrix if expected=false # stderror, vcov, params # weights """ fitdiscrete(net, model, tipdata) fitdiscrete(net, model, RateVariationAcrossSites, tipdata) fitdiscrete(net, model, species, traits) fitdiscrete(net, model, RateVariationAcrossSites, species, traits) fitdiscrete(net, model, dnadata, dnapatternweights) fitdiscrete(net, model, RateVariationAcrossSites, dnadata, dnapatternweights) fitdiscrete(net, modSymbol, species, traits) fitdiscrete(net, modSymbol, dnadata, dnapatternweights) Calculate the maximum likelihood (ML) score of a network or tree given one or more discrete characters at the tips. Along each edge, transitions are modelled with a continous time Markov `model`, whose parameters are estimated (by maximizing the likelihood). At each hybrid node, the trait is assumed to be inherited from either of the two immediate parents according to the parents' average genetic contributions (inheritance γ). The model ignores incomplete lineage sorting. The algorithm extracts all trees displayed in the network. Data can given in one of the following: - `tipdata`: dictionary taxon => state label, for a single trait. - `tipdata`: data frame for a single trait, in which case the taxon names are to appear in column 1 or in a column named "taxon" or "species", and trait *labels* are to appear in column 2 or in a column named "trait". Here, trait labels should be as they appear in `getlabels(model)`. - `species`: vector of strings, and `traits`: DataFrame of traits, with rows in the order corresponding to the order of species names. Again, trait labels should be as they appear in `getlabels(model)`. All traits are assumed to follow the same model, with same parameters. - `dnadata`: the first part of the output of readfastatodna, a dataframe of BioSequence DNA sequences, with taxon in column 1 and a column for each site. - `dnapatternweights`: the second part of the output of readfastatodna, an array of weights, one weights for each of the site columns. The length of the weight is equal to nsites. If using dnapatternweights, must provide dnadata. - RateVariationAcrossSites: model for rate variation (optional) Optional arguments (default): - `optimizeQ` (true): should model rate parameters be fixed, or should they be optimized? - `optimizeRVAS` (true): should the model optimize the parameters for the variability of rates across sites (α and/or p_invariable)? - `NLoptMethod` (`:LN_COBYLA`, derivative-free) for the optimization algorithm. For other options, see the [NLopt](https://nlopt.readthedocs.io/en/latest/NLopt_Algorithms/). - tolerance values to control when the optimization is stopped: `ftolRel` (1e-12), `ftolAbs` (1e-10) on the likelihood, and `xtolRel` (1e-10), `xtolAbs` (1e-10) on the model parameters. - bounds for the alpha parameter of the Gamma distribution of rates across sites: `alphamin=0.05`, `alphamax=50`. - `verbose` (false): if true, more information is output. # examples: ```jldoctest fitDiscrete_block julia> net = readTopology("(((A:2.0,(B:1.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5,D:2.0);"); julia> m1 = BinaryTraitSubstitutionModel([0.1, 0.1], ["lo", "hi"]); julia> using DataFrames julia> dat = DataFrame(species=["C","A","B","D"], trait=["hi","lo","lo","hi"]); julia> fit1 = fitdiscrete(net, m1, dat) PhyloNetworks.StatisticalSubstitutionModel: Binary Trait Substitution Model: rate lo→hi α=0.27222 rate hi→lo β=0.34981 on a network with 1 reticulations data: 4 species 1 trait log-likelihood: -2.7277 julia> tips = Dict("A" => "lo", "B" => "lo", "C" => "hi", "D" => "hi"); julia> fit2 = fitdiscrete(net, m1, tips; xtolRel=1e-16, xtolAbs=1e-16, ftolRel=1e-16) PhyloNetworks.StatisticalSubstitutionModel: Binary Trait Substitution Model: rate lo→hi α=0.27222 rate hi→lo β=0.34981 on a network with 1 reticulations data: 4 species 1 trait log-likelihood: -2.7277 ``` Note that a copy of the network is stored in the fitted object, but the internal representation of the network may be different in `fit1.net` and in the original network `net`: ```jldoctest fitDiscrete_block julia> net = readTopology("(sp1:3.0,(sp2:2.0,(sp3:1.0,sp4:1.0):1.0):1.0);"); julia> using BioSymbols julia> tips = Dict("sp1" => BioSymbols.DNA_A, "sp2" => BioSymbols.DNA_A, "sp3" => BioSymbols.DNA_G, "sp4" => BioSymbols.DNA_G); julia> mJC69 = JC69([0.25], false); julia> fitJC69 = fitdiscrete(net, mJC69, tips) PhyloNetworks.StatisticalSubstitutionModel: Jukes and Cantor 69 Substitution Model, absolute rate version off-diagonal rates equal to 0.29233/3. rate matrix Q: A C G T A * 0.0974 0.0974 0.0974 C 0.0974 * 0.0974 0.0974 G 0.0974 0.0974 * 0.0974 T 0.0974 0.0974 0.0974 * on a network with 0 reticulations data: 4 species 1 trait log-likelihood: -4.99274 julia> rv = RateVariationAcrossSites(alpha=1.0, ncat=4) Rate variation across sites: discretized Gamma alpha: 1.0 categories for Gamma discretization: 4 rates: [0.146, 0.513, 1.071, 2.27] julia> fitdiscrete(net, mJC69, rv, tips; optimizeQ=false, optimizeRVAS=false) PhyloNetworks.StatisticalSubstitutionModel: Jukes and Cantor 69 Substitution Model, absolute rate version off-diagonal rates equal to 0.25/3. rate matrix Q: A C G T A * 0.0833 0.0833 0.0833 C 0.0833 * 0.0833 0.0833 G 0.0833 0.0833 * 0.0833 T 0.0833 0.0833 0.0833 * Rate variation across sites: discretized Gamma alpha: 1.0 categories for Gamma discretization: 4 rates: [0.146, 0.513, 1.071, 2.27] on a network with 0 reticulations data: 4 species 1 trait log-likelihood: -5.2568 ``` fixit: add option to allow users to specify root prior, using either equal frequencies or stationary frequencies for trait models. """ function fitdiscrete(net::HybridNetwork, model::SubstitutionModel, tips::Dict; kwargs...) #tips::Dict no ratemodel version ratemodel = RateVariationAcrossSites(ncat=1) fitdiscrete(net, model, ratemodel, tips; kwargs...) end #tips::Dict version with ratemodel function fitdiscrete(net::HybridNetwork, model::SubstitutionModel, ratemodel::RateVariationAcrossSites, tips::Dict; kwargs...) species = String[] dat = Vector{Int}[] # indices of trait labels for (k,v) in tips !ismissing(v) || continue push!(species, k) vi = findfirst(isequal(v), getlabels(model)) vi !== nothing || error("trait $v not found in model") push!(dat, [vi]) end o, net = check_matchtaxonnames!(species, dat, net) # dat[o] would make a shallow copy only StatsBase.fit(StatisticalSubstitutionModel, net, model, ratemodel, view(dat, o); kwargs...) end #dat::DataFrame, no rate model version function fitdiscrete(net::HybridNetwork, model::SubstitutionModel, dat::DataFrame; kwargs...) ratemodel = RateVariationAcrossSites(ncat=1) fitdiscrete(net, model, ratemodel, dat; kwargs...) end #dat::DataFrame with rate model version function fitdiscrete(net::HybridNetwork, model::SubstitutionModel, ratemodel::RateVariationAcrossSites, dat::DataFrame; kwargs...) i = findfirst(isequal(:taxon), DataFrames.propertynames(dat)) if i===nothing i = findfirst(isequal(:species), DataFrames.propertynames(dat)); end if i===nothing i=1; end # first column if no column "taxon" or "species" j = findfirst(isequal(:trait), DataFrames.propertynames(dat)) if j===nothing j=2; end if i==j error("""expecting taxon names in column 'taxon', or 'species' or column 1, and trait values in column 'trait' or column 2.""") end species = dat[:,i] # modified in place later dat = traitlabels2indices(dat[!,j], model) # vec of vec, indices o, net = check_matchtaxonnames!(species, dat, net) StatsBase.fit(StatisticalSubstitutionModel, net, model, ratemodel, view(dat, o); kwargs...) end #species, dat version, no ratemodel function fitdiscrete(net::HybridNetwork, model::SubstitutionModel, species::Array{<:AbstractString}, dat::DataFrame; kwargs...) ratemodel = RateVariationAcrossSites(ncat=1) fitdiscrete(net, model, ratemodel, species, dat; kwargs...) end #species, dat version with ratemodel function fitdiscrete(net::HybridNetwork, model::SubstitutionModel, ratemodel::RateVariationAcrossSites, species::Array{<:AbstractString}, dat::DataFrame; kwargs...) dat2 = traitlabels2indices(dat, model) # vec of vec, indices o, net = check_matchtaxonnames!(copy(species), dat2, net) StatsBase.fit(StatisticalSubstitutionModel, net, model, ratemodel, view(dat2, o); kwargs...) end #wrapper: species, dat version with model symbol function fitdiscrete(net::HybridNetwork, modSymbol::Symbol, species::Array{<:AbstractString}, dat::DataFrame, rvSymbol=:noRV::Symbol; kwargs...) rate = startingrate(net) labels = learnlabels(modSymbol, dat) if modSymbol == :JC69 model = JC69([1.0], true) # 1.0 instead of rate because relative version elseif modSymbol == :HKY85 model = HKY85([1.0], # transition/transversion rate ratio empiricalDNAfrequencies(dat, repeat([1.], inner=size(dat, 2))), true) elseif modSymbol == :ERSM model = EqualRatesSubstitutionModel(length(labels), rate, labels); elseif modSymbol == :BTSM model = BinaryTraitSubstitutionModel([rate, rate], labels) elseif modSymbol == :TBTSM model = TwoBinaryTraitSubstitutionModel([rate, rate, rate, rate, rate, rate, rate, rate], labels) else error("model $modSymbol is unknown or not implemented yet") end rvas = RateVariationAcrossSites(rvSymbol) fitdiscrete(net, model, rvas, species, dat; kwargs...) end #dnadata with dnapatternweights version, no ratemodel function fitdiscrete(net::HybridNetwork, model::SubstitutionModel, dnadata::DataFrame, dnapatternweights::Array{Float64}; kwargs...) ratemodel = RateVariationAcrossSites(ncat=1) fitdiscrete(net, model, ratemodel, dnadata, dnapatternweights; kwargs...) end #dnadata with dnapatternweights version with ratemodel function fitdiscrete(net::HybridNetwork, model::SubstitutionModel, ratemodel::RateVariationAcrossSites,dnadata::DataFrame, dnapatternweights::Array{<:AbstractFloat}; kwargs...) dat2 = traitlabels2indices(dnadata[!,2:end], model) o, net = check_matchtaxonnames!(dnadata[:,1], dat2, net) kwargs = (:siteweights => dnapatternweights, kwargs...) StatsBase.fit(StatisticalSubstitutionModel, net, model, ratemodel, view(dat2, o); kwargs...) end #wrapper for dna data function fitdiscrete(net::HybridNetwork, modSymbol::Symbol, dnadata::DataFrame, dnapatternweights::Array{<:AbstractFloat}, rvSymbol=:noRV::Symbol; kwargs...) rate = startingrate(net) if modSymbol == :JC69 model = JC69([1.0], true) # 1.0 instead of rate because relative version elseif modSymbol == :HKY85 model = HKY85([1.0], # transition/transversion rate ratio empiricalDNAfrequencies(view(dnadata, :, 2:size(dnadata,2)), dnapatternweights), true) elseif modSymbol == :ERSM model = EqualRatesSubstitutionModel(4, rate, [BioSymbols.DNA_A, BioSymbols.DNA_C, BioSymbols.DNA_G, BioSymbols.DNA_T]); elseif modSymbol == :BTSM error("Binary Trait Substitution Model supports only two trait states, but dna data has four states.") elseif modSymbol == :TBTSM error("Two Binary Trait Substitution Model does not support dna data: it supports two sets of potentially correlated two trait states.") else error("model $modSymbol is unknown or not implemented yet") end rvas = RateVariationAcrossSites(rvSymbol) fitdiscrete(net, model, rvas, dnadata, dnapatternweights; kwargs...) end """ fit(StatisticalSubstitutionModel, net, model, traits; kwargs...) fit!(StatisticalSubstitutionModel; kwargs...) Internal function called by [`fitdiscrete`](@ref): with same key word arguments `kwargs`. But dangerous: `traits` should be a vector of vectors as for [`fitdiscrete`](@ref) **but** here `traits` need to contain the *indices* of trait values corresponding to the indices in `getlabels(model)`, and species should appear in `traits` in the order corresponding to the node numbers in `net`. See [`traitlabels2indices`](@ref) to convert trait labels to trait indices. **Warning**: does *not* perform checks. [`fitdiscrete`](@ref) calls this function after doing checks, preordering nodes in the network, making sure nodes have consecutive numbers, species are matched between data and network etc. """ function StatsBase.fit(::Type{SSM}, net::HybridNetwork, model::SubstitutionModel, ratemodel::RateVariationAcrossSites, trait::AbstractVector; kwargs...) sw = nothing if haskey(kwargs, :siteweights) sw = kwargs[:siteweights] kwargs = filter(p -> p.first != :siteweights, kwargs) end obj = StatisticalSubstitutionModel(model, ratemodel, net, trait, sw) fit!(obj; kwargs...) end function fit!(obj::SSM; optimizeQ=true::Bool, optimizeRVAS=true::Bool, closeoptim=false::Bool, verbose=false::Bool, maxeval=1000::Int, ftolRel=fRelBL::Float64, ftolAbs=fAbsBL::Float64, xtolRel=xRelBL::Float64, xtolAbs=xAbsBL::Float64, alphamin=alphaRASmin, alphamax=alphaRASmax, pinvmin=pinvRASmin, pinvmax=pinvRASmax) all(x -> x >= 0.0, [e.length for e in obj.net.edge]) || error("branch lengths should be >= 0") all(x -> x >= 0.0, [e.gamma for e in obj.net.edge]) || error("gammas should be >= 0") if optimizeQ && nparams(obj.model) <1 @debug "The Q matrix for this model is fixed, so there are no rate parameters to optimize. optimizeQ will be set to false." optimizeQ = false end if optimizeRVAS && (nparams(obj.ratemodel) == 0) @debug "Rate model has one rate category, so there are no parameters to optimize. optimizeRVAS will be set to false." optimizeRVAS = false end if !optimizeQ && !optimizeRVAS discrete_corelikelihood!(obj) verbose && println("loglik = $(loglikelihood(obj)) under fixed parameters, no optimization") return obj end if optimizeQ function loglikfun(x::Vector{<:AbstractFloat}, grad::Vector{<:AbstractFloat}) # modifies obj setrates!(obj.model, x) res = discrete_corelikelihood!(obj) verbose && println("loglik: $res, model rates: $x") length(grad) == 0 || error("gradient not implemented") return res end # optimize Q under fixed RVAS parameters # set-up optimization object for Q NLoptMethod=:LN_COBYLA # no gradient # :LN_COBYLA for (non)linear constraits, :LN_BOBYQA for bound constraints nparQ = nparams(obj.model) optQ = NLopt.Opt(NLoptMethod, nparQ) NLopt.ftol_rel!(optQ,ftolRel) # relative criterion NLopt.ftol_abs!(optQ,ftolAbs) # absolute criterion NLopt.xtol_rel!(optQ,xtolRel) NLopt.xtol_abs!(optQ,xtolAbs) NLopt.maxeval!(optQ, maxeval) # max number of iterations # NLopt.maxtime!(optQ, t::Real) NLopt.lower_bounds!(optQ, zeros(Float64, nparQ)) if typeof(obj.model) == HKY85 # set an upper bound on kappa values NLopt.upper_bounds!(optQ, fill(kappamax,nparQ)) end NLopt.max_objective!(optQ, loglikfun) fmax, xmax, ret = NLopt.optimize(optQ, obj.model.rate) setrates!(obj.model, xmax) obj.loglik = fmax verbose && println("got $(round(fmax, digits=5)) at $(round.(xmax, digits=5)) after $(optQ.numevals) iterations (return code $(ret))") end if optimizeRVAS function loglikfunRVAS(alpha::Vector{<:AbstractFloat}, grad::Vector{<:AbstractFloat}) setparameters!(obj.ratemodel, alpha) res = discrete_corelikelihood!(obj) verbose && println("loglik: $res, rate variation model shape parameter alpha: $(alpha[1])") length(grad) == 0 || error("gradient not implemented") return res end # set-up optimization object for RVAS parameter NLoptMethod=:LN_COBYLA # no gradient # :LN_COBYLA for (non)linear constraits, :LN_BOBYQA for bound constraints nparRVAS = nparams(obj.ratemodel) optRVAS = NLopt.Opt(NLoptMethod, nparRVAS) NLopt.ftol_rel!(optRVAS,ftolRel) # relative criterion NLopt.ftol_abs!(optRVAS,ftolAbs) # absolute criterion NLopt.xtol_rel!(optRVAS,xtolRel) NLopt.xtol_abs!(optRVAS,xtolAbs) NLopt.maxeval!(optRVAS,1000) # max number of iterations # NLopt.maxtime!(optRVAS, t::Real) rvind = getparamindex(obj.ratemodel) NLopt.lower_bounds!(optRVAS, [pinvmin,alphamin][rvind] ) NLopt.upper_bounds!(optRVAS, [pinvmax,alphamax][rvind] ) NLopt.max_objective!(optRVAS, loglikfunRVAS) fmax, xmax, ret = NLopt.optimize(optRVAS, getparameters(obj.ratemodel)) # optimization here! setparameters!(obj.ratemodel, xmax) obj.loglik = fmax verbose && println("RVAS: got $(round(fmax, digits=5)) at $(round.(xmax, digits=5)) after $(optRVAS.numevals) iterations (return code $(ret))") end if optimizeQ && optimizeRVAS && closeoptim # optimize Q under fixed RVAS parameters: a second time fmax, xmax, ret = NLopt.optimize(optQ, obj.model.rate) setrates!(obj.model, xmax) obj.loglik = fmax verbose && println("got $(round(fmax, digits=5)) at $(round.(xmax, digits=5)) after $(optQ.numevals) iterations (return code $(ret))") # optimize RVAS under fixed Q: a second time fmax, xmax, ret = NLopt.optimize(optRVAS, getparameters(obj.ratemodel)) setparameters!(obj.ratemodel, xmax) obj.loglik = fmax verbose && println("RVAS: got $(round(fmax, digits=5)) at $(round.(xmax, digits=5)) after $(optRVAS.numevals) iterations (return code $(ret))") end return obj end """ update_logtrans(obj::SSM) Initialize and update `obj.logtrans`, the log transition probabilities along each edge in the full network. They are re-used for each displayed tree, which is why edges are not fused around degree-2 nodes when extracting displayed trees. """ function update_logtrans(obj::SSM) rates = obj.ratemodel.ratemultiplier k = nstates(obj.model) Ptmp = MMatrix{k,k,Float64}(undef) # memory to be re-used for edge in obj.net.edge # update logtrans: same for all displayed trees, all traits enum = edge.number len = edge.length for i = 1:length(rates) obj.logtrans[:,:,enum, i] .= log.(P!(Ptmp, obj.model, len * rates[i])) end end end """ update_logtrans(obj::SSM, edge::Edge) Update the log-transition probabilities associates to one particular `edge` in the network. """ function update_logtrans(obj::SSM, edge::Edge) rates = obj.ratemodel.ratemultiplier enum = edge.number len = edge.length for i in 1:length(rates) pmat = view(obj.logtrans, :,:,enum,i) @inbounds pmat .= log.(P!(pmat, obj.model, len * rates[i])) end end """ discrete_corelikelihood!(obj::StatisticalSubstitutionModel; whichtrait::AbstractVector{Int} = 1:obj.nsites) Calculate the likelihood and update `obj.loglik` for discrete characters on a network, calling [`discrete_corelikelihood_trait!`](@ref). The algorithm extracts all displayed trees and weighs the likelihood under all these trees. The object's partial likelihoods are updated: - forward and direct partial likelihoods are re-used, one trait at a time, - overall likelihoods on each displayed tree, given each rate category and for each given site/trait: are cached in `_loglikcache`. """ function discrete_corelikelihood!(obj::SSM; whichtrait::AbstractVector{Int} = 1:obj.nsites) # fill _loglikcache nr = length(obj.ratemodel.ratemultiplier) nt = length(obj.displayedtree) update_logtrans(obj) for t in 1:nt for ri in 1:nr for ci in whichtrait obj._loglikcache[ci,ri,t] = discrete_corelikelihood_trait!(obj,t,ci,ri) # conditional: log P(site | rate & tree) # note: -Inf expected if 2 tips have different states, but separated by path of total length 0.0 end end end # aggregate over trees and rates lrw = obj.ratemodel.lograteweight for ti in 1:nt ltprior = obj.priorltw[ti] for ri in 1:nr obj._loglikcache[:,ri,ti] .+= ltprior + lrw[ri] # now unconditional: log P(site & rate & tree) end end for ci in whichtrait obj._sitecache[ci] = logsumexp(view(obj._loglikcache, ci,:,1:nt)) end if obj.siteweight !== nothing obj._sitecache .*= obj.siteweight end loglik = sum(obj._sitecache) obj.loglik = loglik return loglik end """ discrete_corelikelihood_trait!(obj::SSM, t::Integer, ci::Integer, ri::Integer) Return the likelihood for tree `t`, trait (character/site) index `ci` and rate category `ri`. Update & modify the forward & directional log-likelihoods `obj.forwardlik` and `obj.directlik`, which are indexed by [state, node_number or edge_number]. Used by [`discrete_corelikelihood!`](@ref). **Preconditions**: `obj.logtrans` updated, edges directed, nodes/edges preordered """ function discrete_corelikelihood_trait!(obj::SSM, t::Integer, ci::Integer, ri::Integer) forwardlik = obj.forwardlik directlik = obj.directlik tree = obj.displayedtree[t] k = nstates(obj.model) # also = size(logtrans,1) if not RateVariationAcrossSites fill!(forwardlik, 0.0) # re-initialize for each trait, each iteration fill!(directlik, 0.0) loglik = 0. for ni in reverse(1:length(tree.nodes_changed)) # post-order n = tree.nodes_changed[ni] nnum = n.number # same n.number across trees for a given node if n.leaf # need forwardlik initialized at 0: keep at 0 = log(1) if no data state = obj.trait[nnum][ci] # here: data assumed in a row n.number if !ismissing(state) for i in 1:k forwardlik[i,nnum] = -Inf64 # log(0) = -Inf if i != observed state end forwardlik[state, nnum] = 0. end else # forward likelihood = product of direct likelihood over all children edges for e in n.edge n == getparent(e) || continue # to next edge if n is not parent of e forwardlik[:,nnum] .+= view(directlik, :,e.number) end end if ni==1 # root is first index in nodes changed loglik = logsumexp(obj.prioratroot + view(forwardlik, :,nnum)) # log P{data for ci | tree t, rate ri} break # out of loop over nodes end # if we keep going, n is not the root # calculate direct likelihood on the parent edge of n for e in n.edge if n == getchild(e) lt = view(obj.logtrans, :,:,e.number, ri) for i in 1:k # state at parent node directlik[i,e.number] = logsumexp(view(lt,i,:) + view(forwardlik,:,nnum)) end break # we visited the parent edge: break out of for loop end end #loop over edges end # of loop over nodes return loglik end """ posterior_logtreeweight(obj::SSM, trait = 1) Array A of log-posterior probabilities for each tree displayed in the network: such that A[t] = log of P(tree `t` | trait `trait`) if a single `trait` is requested, or A[t,i]= log of P(tree `t` | trait `i`) if `trait` is a vector or range (e.g. `trait = 1:obj.nsites`). These probabilities are conditional on the model parameters in `obj`. Displayed trees are listed in the order in which they are stored in the fitted model object `obj`. **Precondition**: `_loglikcache` updated by [`discrete_corelikelihood!`](@ref) # examples ```jldoctest julia> net = readTopology("(((A:2.0,(B:1.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5,D:2.0);"); julia> m1 = BinaryTraitSubstitutionModel([0.1, 0.1], ["lo", "hi"]); # arbitrary rates julia> using DataFrames julia> dat = DataFrame(species=["C","A","B","D"], trait=["hi","lo","lo","hi"]); julia> fit = fitdiscrete(net, m1, dat); # optimized rates: α=0.27 and β=0.35 julia> pltw = PhyloNetworks.posterior_logtreeweight(fit); julia> round.(exp.(pltw), digits=5) # posterior trees probabilities (sum up to 1) 2-element Vector{Float64}: 0.91983 0.08017 julia> round.(exp.(fit.priorltw), digits=4) # the prior tree probabilities are similar here (tiny data set!) 2-element Vector{Float64}: 0.9 0.1 ``` """ function posterior_logtreeweight(obj::SSM, trait = 1) # ts[site,tree] = log P(data and tree) at site, integrated over rates d = length(size(trait)) # 0 if single trait, 1 if vector of several traits ts = dropdims(mapslices(logsumexp, view(obj._loglikcache, trait,:,:), dims=d+1); dims=1) if d>0 ts = permutedims(ts); end # now: ts[tree] or ts[tree,site] siteliks = mapslices(logsumexp, ts, dims=1) # 1 x ntraits array (or 1-element vector) ts .-= siteliks return ts end """ posterior_loghybridweight(obj::SSM, hybrid_name, trait = 1) posterior_loghybridweight(obj::SSM, edge_number, trait = 1) Log-posterior probability for all trees displaying the minor parent edge of hybrid node named `hybrid_name`, or displaying the edge number `edge_number`. That is: log of P(hybrid minor parent | trait) if a single `trait` is requested, or A[i]= log of P(hybrid minor parent | trait `i`) if `trait` is a vector or range (e.g. `trait = 1:obj.nsites`). These probabilities are conditional on the model parameters in `obj`. **Precondition**: `_loglikcache` updated by [`discrete_corelikelihood!`](@ref) # examples ```jldoctest julia> net = readTopology("(((A:2.0,(B:1.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5,D:2.0);"); julia> m1 = BinaryTraitSubstitutionModel([0.1, 0.1], ["lo", "hi"]); # arbitrary rates julia> using DataFrames julia> dat = DataFrame(species=["C","A","B","D"], trait=["hi","lo","lo","hi"]); julia> fit = fitdiscrete(net, m1, dat); # optimized rates: α=0.27 and β=0.35 julia> plhw = PhyloNetworks.posterior_loghybridweight(fit, "H1"); julia> round(exp(plhw), digits=5) # posterior probability of going through minor hybrid edge 0.08017 julia> hn = net.node[3]; getparentedgeminor(hn).gamma # prior probability 0.1 ``` """ function posterior_loghybridweight(obj::SSM, hybridname::String, trait = 1) hn_index = findfirst(n -> n.name == hybridname, obj.net.node) isnothing(hn_index) && error("node named $hybridname not found") hn = obj.net.node[hn_index] hn.hybrid || error("node named $hybridname is not a hybrid node") me = getparentedgeminor(hn) posterior_loghybridweight(obj, me.number, trait) end function posterior_loghybridweight(obj::SSM, edgenum::Integer, trait = 1) tpp = posterior_logtreeweight(obj, trait) # size: (ntree,) or (ntree,ntraits) hasedge = tree -> any(e.number == edgenum for e in tree.edge) tokeep = map(hasedge, obj.displayedtree) tppe = view(tpp, tokeep, :) # makes it a matrix epp = dropdims(mapslices(logsumexp, tppe, dims=1); dims=2) return (size(epp)==(1,) ? epp[1] : epp) # scalar or vector end """ traitlabels2indices(data, model::SubstitutionModel) Check that the character states in `data` are compatible with (i.e. subset of) the trait labels in `model`. All columns are used. `data` can be a DataFrame or a Matrix (multiple traits), or a Vector (one trait). Return a vector of vectors (one per species) with integer entries, where each state (label) is replaced by its index in `model`. For DNA data, any ambiguous site is treated as missing. """ function traitlabels2indices(data::AbstractVector, model::SubstitutionModel) A = Vector{Vector{Union{Missings.Missing,Int}}}(undef, 0) # indices of trait labels labs = getlabels(model) for l in data vi = missing if !ismissing(l) vi = findfirst(isequal(l), getlabels(model)) # value index in model labels vi !== nothing || error("trait $l not found in model") end push!(A, [vi]) end return A end function traitlabels2indices(data::Union{AbstractMatrix,AbstractDataFrame}, model::SubstitutionModel) A = Vector{Vector{Union{Missings.Missing,Int}}}(undef, 0) # indices of trait labels labs = getlabels(model) isDNA = typeof(labs) == Array{DNA,1} ntraits = size(data,2) #starting with spcies column for i in 1:size(data,1) # go row by row (which is species by species) V = Vector{Union{Missings.Missing,Int}}(undef, ntraits) for j in 1:ntraits vi = missing # value index @inbounds l = data[i,j] # value label if !isDNA && ismissing(l) vi = missing elseif isDNA #else if DNA if typeof(l) == String #takes string and converts to a Char so that we can convert to DNA l = Vector{Char}(l)[1] end l = convert(DNA, l) end if !ismissing(l) vi = findfirst(isequal(l), labs) if vi === nothing # ideally, handle ambiguous DNA types optimally if isDNA #&& BioSymbols.isambiguous(l) vi = missing else error("trait $l not found in model") end end end V[j] = vi end push!(A, V) end return A end """ check_matchtaxonnames!(species, data, net) Modify `species` and `dat` by removing the species (rows) absent from the network. Return a new network (`net` is *not* modified) with tips matching those in species: if some species in `net` have no data, these species are pruned from the network. The network also has its node names reset, such that leaves have nodes have consecutive numbers starting at 1, with leaves first. Used by [`fitdiscrete`](@ref) to build a new [`StatisticalSubstitutionModel`](@ref). """ function check_matchtaxonnames!(species::AbstractVector, dat::AbstractVector, net::HybridNetwork) # 1. basic checks for dimensions and types eltt = eltype(dat) @assert eltt <: AbstractVector "traits should be a vector of vectors" @assert nonmissingtype(eltype(eltt)) <: Integer "traits should be integers (label indices)" @assert !isempty(dat) "empty data vector!" ntraits = length(dat[1]) for d in dat @assert length(d)==ntraits "all species should have the same number of traits" end @assert length(dat) == length(species) "need as many species as rows in trait data" # 2. match taxon labels between data and network netlab = tipLabels(net) ind2notinnet = findall(x -> x ∉ netlab, species) # species not in network deleteat!(species, ind2notinnet) deleteat!(dat, ind2notinnet) nvalues = [sum(.!ismissing.(d)) for d in dat] # species with completely missing data indmissing = findall(x -> x==0, nvalues) deleteat!(species, indmissing) deleteat!(dat, indmissing) indnotindat = findall(x -> x ∉ species, netlab) # species not in data net = deepcopy(net) if !isempty(indnotindat) @warn "the network contains taxa with no data: those will be pruned" for i in indnotindat deleteleaf!(net, netlab[i]) end end # 3. calculate order of rows to have species with node.number i on ith row resetNodeNumbers!(net; checkPreorder=true, type=:ape) # tip species: now with numbers 1:n resetEdgeNumbers!(net, false) # to use edge as indices: 1:numEdges netlab = [n.name for n in sort(net.leaf, by = x -> x.number)] nspecies = length(netlab) o = Vector{Int}(undef, nspecies) for i in 1:nspecies @inbounds o[i] = something(findfirst(isequal(netlab[i]), species),0) end count(!iszero, o) == nspecies || # number of non-zeros should be total size error("weird: even after pruning, species in network have no data") return (o,net) end """ ancestralStateReconstruction(obj::SSM, trait::Integer = 1) Estimate the marginal probability of ancestral states for discrete character number `trait` (first trait by default). The parameters of the [`StatisticalSubstitutionModel`](@ref) object `obj` must first be fitted using [`fitdiscrete`](@ref), and ancestral state reconstruction is conditional on the estimated parameters. If these parameters were estimated using all traits, they are used as is, to do ancestral state reconstruction of the particular `trait` of interest. **output**: data frame with a first column for the node numbers, a second column for the node labels, and a column for each possible state: the entries in these columns give the marginal probability that a given node has a given state. warnings: - node numbers and node labels refer to those in `obj.net`, which might have a different internal representation of nodes than the original network used to build `obj`. - `obj` is modified: its likelihood fields (forward, directional & backward) are updated to make sure that they correspond to the current parameter values in `obj.model`, and to the `trait` of interest. limitations: the following are not checked. - Assumes that every node in the large network is also present (with descendant leaves) in each displayed tree. This is not true if the network is not tree-child... - Assumes that the root is also in each displayed tree, which may not be the case if the root had a hybrid child edge. See also [`posterior_logtreeweight`](@ref) and [`discrete_backwardlikelihood_trait!`](@ref) to update `obj.backwardlik`. # examples ```jldoctest julia> net = readTopology("(((A:2.0,(B:1.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5,D:2.0);"); julia> m1 = BinaryTraitSubstitutionModel([0.1, 0.1], ["lo", "hi"]); julia> using DataFrames julia> dat = DataFrame(species=["C","A","B","D"], trait=["hi","lo","lo","hi"]); julia> fit1 = fitdiscrete(net, m1, dat); julia> asr = ancestralStateReconstruction(fit1) 9×4 DataFrame Row │ nodenumber nodelabel lo hi │ Int64 String Float64 Float64 ─────┼─────────────────────────────────────────── 1 │ 1 A 1.0 0.0 2 │ 2 B 1.0 0.0 3 │ 3 C 0.0 1.0 4 │ 4 D 0.0 1.0 5 │ 5 5 0.286021 0.713979 6 │ 6 6 0.319456 0.680544 7 │ 7 7 0.16855 0.83145 8 │ 8 8 0.767359 0.232641 9 │ 9 H1 0.782776 0.217224 julia> using PhyloPlots julia> plot(fit1.net, nodelabel = asr[!,[:nodenumber, :lo]], tipoffset=0.2); # pp for "lo" state ``` """ function ancestralStateReconstruction(obj::SSM, trait::Integer = 1) # posterior probability of state i at node n: proportional to # sum_{tree t, rate r} exp( ltw[t] + backwardll[i,n] given t,r + forwardll[i,n] given t,r ) / nr trait <= obj.nsites || error("trait $trait is larger than the number of traits in the data") nnodes = length(obj.net.node) # may be smaller than 2nd size of bkd or frd update_logtrans(obj) bkd = view(obj.backwardlik, :, 1:nnodes) frd = view(obj.forwardlik, :, 1:nnodes) ltw = obj.priorltw res = similar(bkd) # first: hold the cumulative logsumexp of bkd + frd + ltw fill!(res, -Inf64) nr = length(obj.ratemodel.ratemultiplier) lrw = obj.ratemodel.lograteweight for t in 1:length(obj.displayedtree) ltprior = ltw[t] for ri in 1:nr # update forward & directional likelihoods discrete_corelikelihood_trait!(obj,t,trait,ri) # update backward likelihoods discrete_backwardlikelihood_trait!(obj,t,ri) # P{state i at node n} ∝ bkd[i,n] * frd[i,n] given tree & rate: # res = logaddexp(res, ltw[t] + lrw[ri] + bkd + frd) broadcast!(logaddexp, res, res, (ltprior + lrw[ri]) .+ bkd .+ frd) end end # normalize the results at each node: p_i / sum(p_j over all states j) traitloglik = logsumexp(res[:,1]) # sum p_j at node 1 or at any node = loglikelihood res .= exp.(res .- traitloglik) nodestringlabels = Vector{String}(undef, nnodes) for n in obj.net.node nodestringlabels[n.number] = (n.name == "" ? string(n.number) : n.name) end dat = DataFrame(transpose(res), Symbol.(getlabels(obj.model))) insertcols!(dat, 1, :nodenumber => collect(1:nnodes), makeunique=true) insertcols!(dat, 2, :nodelabel => nodestringlabels, makeunique=true) return dat end """ discrete_backwardlikelihood_trait!(obj::SSM, tree::Integer, ri::Integer) Update and return the backward likelihood (last argument `backwardlik`) assuming rate category `ri` and tree index `tree`, using current forward and backwards likelihoods in `obj`: these depend on the trait (or site) given to the last call to `discrete_corelikelihood_trait!`. Used by `ancestralStateReconstruction`. **warning**: assume correct transition probabilities. """ function discrete_backwardlikelihood_trait!(obj::SSM, t::Integer, ri::Integer) backwardlik = obj.backwardlik directlik = obj.directlik tree = obj.displayedtree[t] k = nstates(obj.model) fill!(backwardlik, 0.0) # re-initialize for each trait, each iteration bkwtmp = Vector{Float64}(undef, k) # to hold bkw lik without parent edge transition if typeof(obj.model) <: NASM logprior = log.(stationary(obj.model)) else #trait models logprior = [-log(k) for i in 1:k] # uniform prior at root end for ni in 1:length(tree.nodes_changed) # pre-order traversal to calculate backwardlik n = tree.nodes_changed[ni] nnum = n.number if ni == 1 # n is the root backwardlik[:,nnum] = logprior else pe = getparentedge(n) pn = getparent(pe) bkwtmp[:] = backwardlik[:,pn.number] # use bktmp's original memory for se in pn.edge if se != pe && pn == getparent(se) # then se is sister edge to pe bkwtmp .+= view(directlik, :,se.number) end end lt = view(obj.logtrans, :,:,pe.number,ri) for j in 1:k # state at node n backwardlik[j,nnum] = logsumexp(bkwtmp + view(lt,:,j)) end end end return backwardlik end """ learnlabels(model::Symbol, dat::DataFrame) Return unique non-missing values in `dat`, and check that these labels can be used to construct of substitution model of type `model`. # examples: ```jldoctest julia> using DataFrames julia> dat = DataFrame(trait1 = ["A", "C", "A", missing]); # 4×1 DataFrame julia> PhyloNetworks.learnlabels(:BTSM, dat) 2-element Vector{String}: "A" "C" julia> PhyloNetworks.learnlabels(:JC69, dat) 2-element Vector{String}: "A" "C" ``` """ function learnlabels(modSymbol::Symbol, dat::AbstractDataFrame) labels = mapreduce(x -> unique(skipmissing(x)), union, eachcol(dat)) if modSymbol == :BTSM length(labels) == 2 || error("Binary Trait Substitution Model supports traits with two states. These data have do not have two states.") elseif modSymbol == :TBTSM unique(skipmissing(dat[!,1])) == 2 && unique(skipmissing(dat[!,2]) == 2) || error("Two Binary Trait Substitution Model supports two traits with two states each.") elseif modSymbol in [:HKY85, :JC69] typeof(labels) == Array{DNA,1} || (typeof(labels) == Array{Char,1} && all(in.(uppercase.(labels), "-ABCDGHKMNRSTVWY"))) || (typeof(labels) == Array{String,1} && all(occursin.(uppercase.(labels), "-ABCDGHKMNRSTVWY"))) || # "ACGT" would dissallow ambiguous sites error("$modSymbol requires that trait data are dna bases A, C, G, and T") end return labels end """ startingrate(net) Estimate an evolutionary rate appropriate for the branch lengths in the network, which should be a good starting value before optimization in `fitdiscrete`, assuming approximately 1 change across the entire tree. If all edge lengths are missing, set starting rate to 1/(number of taxa). """ function startingrate(net::HybridNetwork) totaledgelength = 0.0 for e in net.edge if e.length > 0.0 totaledgelength += e.length end end if totaledgelength == 0.0 # as when all edge lengths are missing totaledgelength = net.numTaxa end return 1.0/totaledgelength end """ defaultsubstitutionmodel(network, modsymbol::Symbol, data::DataFrame, siteweights::Vector) Return a statistical substitution model (SSM) with appropriate state labels and a rate appropriate for the branch lengths in `net` (see [`startingrate`](@ref)). The `data` frame must have the actual trait/site data in columns 2 and up, as when the species names are in column 1. For DNA data, the relative rate model is returned, with a stationary distribution equal to the empirical frequencies. """ function defaultsubstitutionmodel(net::HybridNetwork, modsymbol::Symbol, data::DataFrame, siteweights=repeat([1.], inner=size(data,2))::AbstractVector) rate = startingrate(net) actualdat = view(data, :, 2:size(data,2)) labels = learnlabels(modsymbol, actualdat) if modsymbol == :JC69 return JC69([1.0], true) # 1.0 instead of rate because relative version elseif modsymbol == :HKY85 # transition/transversion rate ratio return HKY85([1.0], empiricalDNAfrequencies(actualdat, siteweights), true) elseif modsymbol == :ERSM return EqualRatesSubstitutionModel(length(labels), rate, labels); elseif modsymbol == :BTSM return BinaryTraitSubstitutionModel([rate, rate], labels) elseif modsymbol == :TBTSM return TwoBinaryTraitSubstitutionModel([rate, rate, rate, rate, rate, rate, rate, rate], labels) else error("model $modsymbol is unknown or not implemented yet") end end # fixit: new type for two (dependent) binary traits # need new algorithm for model at hybrid nodes: displayed trees aren't enough
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
27375
# circularity: a node has a vector of edges, and an edge has a vector of nodes """ ANode Abstract node. An object of type [`EdgeT`](@ref) has a `node` attribute, which is an vector of 2 objects of some subtype of `ANode`. The concrete type [`Node`](@ref) is a subtype of `ANode`, and has an `edge` attribute, which is vector of [`Edge`](@ref PhyloNetworks.EdgeT) objects (where Edge is an alias for EdgeT{Node}). """ abstract type ANode end """ EdgeT{node type} Edge = EdgeT{Node} Edge(number, length=1.0) Data structure for an edge and its various attributes. Most notably: - `number` (integer): serves as unique identifier; remains unchanged when the network is modified, with a nearest neighbor interchange for example - `node`: vector of [`Node`](@ref)s, normally just 2 of them - `isChild1` (boolean): `true` if `node[1]` is the child node of the edge, false if `node[1]` is the parent node of the edge - `length`: branch length - `hybrid` (boolean): whether the edge is a tree edge or a hybrid edge (in which case `isChild1` is important, even if the network is semi-directed) - `gamma`: proportion of genetic material inherited by the child node via the edge; 1.0 for a tree edge - `isMajor` (boolean): whether the edge is the major path to the child node; `true` for tree edges, since a tree edge is the only path to its child node; normally true if `gamma>0.5`. and other fields, used very internally """ mutable struct EdgeT{T<:ANode} number::Int length::Float64 #default 1.0 hybrid::Bool y::Float64 # exp(-t), cannot set in constructor for congruence z::Float64 # 1-y , cannot set in constructor for congruence gamma::Float64 # set to 1.0 for tree edges, hybrid?gamma:1.0 node::Vector{T} isChild1::Bool # used for hybrid edges to set the direction (default true) isMajor::Bool # major edge treated as tree edge for network traversal # true if gamma>.5, or if it is the original tree edge inCycle::Int # = Hybrid node number if this edge is part of a cycle created by such hybrid node # -1 if not part of cycle. used to add new hybrid edge. updated after edge is part of a network containRoot::Bool # true if this edge can contain a root given the direction of hybrid edges # used to add new hybrid edge. updated after edge is part of a network istIdentifiable::Bool # true if the parameter t (length) for this edge is identifiable as part of a network # updated after part of a network fromBadDiamondI::Bool # true if the edge came from deleting a bad diamond I hybridization end # outer constructors: ensure congruence among (length, y, z) and (gamma, hybrid, isMajor), and size(node)=2 function EdgeT{T}(number::Int, length::Float64=1.0) where {T<:ANode} y = exp(-length) EdgeT{T}(number,length,false,y,1.0-y,1.,T[],true,true,-1,true,true,false) end function EdgeT{T}(number::Int, length::Float64,hybrid::Bool,gamma::Float64,isMajor::Bool=(!hybrid || gamma>0.5)) where {T<:ANode} y = exp(-length) EdgeT{T}(number,length,hybrid,y,1.0-y, hybrid ? gamma : 1.,T[],true,isMajor,-1,!hybrid,true,false) end function EdgeT{T}(number::Int, length::Float64,hybrid::Bool,gamma::Float64,node::Vector{T}) where {T<:ANode} size(node,1) == 2 || error("vector of nodes must have exactly 2 values") y = exp(-length) Edge{T}(number,length,hybrid,y,1.0-y, hybrid ? gamma : 1., node,true, !hybrid || gamma>0.5, -1,!hybrid,true,false) end function EdgeT{T}(number::Int, length::Float64,hybrid::Bool,gamma::Float64,node::Vector{T},isChild1::Bool, inCycle::Int, containRoot::Bool, istIdentifiable::Bool) where {T<:ANode} size(node,1) == 2 || error("vector of nodes must have exactly 2 values") y = exp(-length) Edge{T}(number,length,hybrid,y,1.0-y, hybrid ? gamma : 1., node,isChild1, !hybrid || gamma>0.5, inCycle,containRoot,istIdentifiable,false) end # warning: gammaz, inCycle, isBadTriangle/Diamond updated until the node is part of a network """ Node(number, leaf) Node(number, leaf, hybrid) Data structure for a node and its various attributes. Most notably: - `number` (integer): serves as unique identifier; remains unchanged when the network is modified, with a nearest neighbor interchange for example - `leaf` (boolean): whether the node is a leaf (with data typically) or an internal node (no data typically) - `name` (string): taxon name for leaves; internal node may or may not have a name - `edge`: vector of [`Edge`](@ref PhyloNetworks.EdgeT)s that the node is attached to; 1 if the node is a leaf, 2 if the node is the root, 3 otherwise, and potentially more if the node has a polytomy - `hybrid` (boolean): whether the node is a hybrid node (with 2 or more parents) or a tree node (with a single parent) Other more internal attributes include: - `isBadDiamondI` and `isBadDiamondII` (booleans): whether the node is a hybrid node where the reticulation forms a cycle of 4 nodes (diamond), and where both parents of the hybrid nodes are connected to a leaf. In a bad diamond of type I, the hybrid node itself is also connected to a leaf but the common neighbor of the 2 hybrid's parents is not connected to a leaf. In a bad diamond of type II, the hybrid node has an internal node as child, and the common neighbor of the 2 hybrid's parents is connected to a leaf. - `isBadTriangle`, `isVeryBadTriangle` and `isExtBadTriangle` (booleans): true if the reticulation forms a cycle of 3 nodes (triangle) and depending on the number of leaves attached these 3 nodes. The triangle means that the 2 parents of the hybrid node are directly related: one is the child of the other. `isBadTriangle` is true if the triangle is "good", as per Solís-Lemus & Ané (2016), that is, if all 3 nodes in the cycle are not connected to any leaves (the reticulation is detectable from quartet concordance factors, even though all branch lengths are not identifiable). `isVeryBadTriangle` is true if 2 (or all) of the 3 nodes are connected to a leaf, in which case the reticulation is undetectable from unrooted gene tree topologies (thus it's best to exclude these reticulations from a search). `isBadTriangle` is true if exactly 1 of the 3 nodes is connected to a leaf. For details see Solís-Lemus & Ané (2016, doi:10.1371/journal.pgen.1005896) """ mutable struct Node <: ANode number::Int leaf::Bool hybrid::Bool gammaz::Float64 # notes file for explanation. gammaz if tree node, gamma2z if hybrid node. # updated after node is part of network with updateGammaz! edge::Vector{EdgeT{Node}} hasHybEdge::Bool #is there a hybrid edge in edge? only needed when hybrid=false (tree node) isBadDiamondI::Bool # for hybrid node, is it bad diamond case I, update in updateGammaz! isBadDiamondII::Bool # for hybrid node, is it bad diamond case II, update in updateGammaz! isExtBadTriangle::Bool # for hybrid node, is it extremely bad triangle, udpate in updateGammaz! isVeryBadTriangle::Bool # for hybrid node, is it very bad triangle, udpate in updateGammaz! isBadTriangle::Bool # for hybrid node, is it very bad triangle, udpate in updateGammaz! inCycle::Int # = hybrid node if this node is part of a cycle created by such hybrid node, -1 if not part of cycle prev::Union{Nothing,Node} # previous node in cycle, used in updateInCycle. set to "nothing" to begin with k::Int # num nodes in cycle, only stored in hybrid node, updated after node becomes part of network # default -1 typeHyb::Int8 # type of hybridization (1,2,3,4, or 5), needed for quartet network only. default -1 name::AbstractString end const Edge = EdgeT{Node} Node() = Node(-1,false,false,-1.,Edge[],false,false,false,false,false,false,-1,nothing,-1,-1,"") Node(number::Int, leaf::Bool, hybrid::Bool=false) = Node(number,leaf,hybrid,-1.,Edge[],hybrid,false,false,false,false,false,-1.,nothing,-1,-1,"") # set hasHybEdge depending on edge: Node(number::Int, leaf::Bool, hybrid::Bool, edge::Vector{Edge}) = Node(number,leaf,hybrid,-1.,edge,any(e->e.hybrid,edge),false,false,false,false,false,-1.,nothing,-1,-1,"") Node(number::Int, leaf::Bool, hybrid::Bool,gammaz::Float64, edge::Vector{Edge}) = Node(number,leaf,hybrid,gammaz,edge,any(e->e.hybrid, edge),false,false,false,false,false,-1.,nothing,-1,-1,"") # partition type mutable struct Partition cycle::Vector{Int} #hybrid node number for cycle (or cycles) edges::Vector{Edge} #edges in partition end abstract type Network end # warning: no attempt to make sure the direction of edges matches with the root # warning: no check if it is network or tree, node array can have no hybrids # warning: nodes and edges need to be defined and linked before adding to a network """ HybridNetwork Subtype of abstract `Network` type. Explicit network or tree with the following attributes: - numTaxa (taxa are tips, i.e. nodes attached to a single edge) - numNodes (total number of nodes: tips and internal nodes) - numEdges - numHybrids (number of hybrid nodes) - edge (array of Edges) - node (array of Nodes) - root (index of root in vector 'node'. May be artificial, for printing and traversal purposes only.) - hybrid (array of Nodes: those are are hybrid nodes) - leaf (array of Nodes: those that are leaves) - loglik (score after fitting network to data, i.e. negative log pseudolik for SNaQ) - isRooted (true or false) """ mutable struct HybridNetwork <: Network numTaxa::Int # cannot set in constructor for congruence numNodes::Int numEdges::Int node::Array{Node,1} edge::Array{Edge,1} root::Int # node[root] is the root node, default 1 names::Array{String,1} # translate table for taxon names --but also includes hybrid names... hybrid::Array{Node,1} # array of hybrid nodes in network numHybrids::Int # number of hybrid nodes cladewiseorder_nodeIndex::Vector{Int} # index in 'node' for "cladewise" preorder in main tree visited::Array{Bool,1} # reusable array of booleans edges_changed::Array{Edge,1} # reusable array of edges nodes_changed::Array{Node,1} # reusable array of nodes. used for preorder traversal leaf::Array{Node,1} # array of leaves ht::Vector{Float64} # vector of parameters to optimize numht::Vector{Int} # vector of number of the hybrid nodes and edges in ht e.g. [3,6,8,...], 2 hybrid nodes 3,6, and edge 8 is the 1st identifiable numBad::Int # number of bad diamond I hybrid nodes, set as 0 hasVeryBadTriangle::Bool # true if the network has extremely/very bad triangles that should be ignored index::Vector{Int} #index in net.edge, net.node of elements in net.ht to make updating easy loglik::Float64 # value of the min -loglik after optBL blacklist::Vector{Int} # reusable array of integers, used in afterOptBL partition::Vector{Partition} # to choose edges from a partition only to avoid intersecting cycles cleaned::Bool # attribute to know if the network has been cleaned after readm default false isRooted::Bool # to know if network is rooted, e.g. after directEdges! (which updates isChild1 of each edge) # inner constructor function HybridNetwork(node::Array{Node,1},edge::Array{Edge,1}) hybrid=Node[]; leaf=Node[]; for n in node if n.hybrid push!(hybrid,n); end if n.leaf push!(leaf, n); end end new(size(leaf,1),size(node,1),size(edge,1),node,edge,1,[],hybrid,size(hybrid,1), #numTaxa,...,numHybrids [],[],[],[],leaf,[],[], #cladewiseorder,...,numht 0,false,[],0,[],[],false,false) #numBad... end HybridNetwork() = new(0,0,0,[],[],0,[],[],0, # numTaxa ... numHybrid [],[],[],[],[],[],[], # cladewiseorder... 0,false,[],0,[],[],false,false); # numBad ... end # type created from a HybridNetwork only to extract a given quartet """ QuartetNetwork(net::HybridNetwork) Subtype of `Network` abstract type. A `QuartetNetwork` object is an internal type used to calculate the expected CFs of quartets on a given network. Attributes of the `QuartetNetwork` objects need not be updated at a given time (see below). The procedure to calculate expected CFs for a given network is as follows: 1. A `QuartetNetwork` object is created for each `Quartet` using `extractQuartet!(net,d)` for `net::HybridNetwork` and `d::DataCF` 2. The vector `d.quartet` has all the `Quartet` objects, each with a `QuartetNetwork` object (`q.qnet`). Attibutes in `QuartetNetwork` are not updated at this point 3. Attributes in `QuartetNetwork` are partially updated when calculating the expected CF (`calculateExpCFAll!`). To calculate the expected CF for this quartet, we need to update the attributes: `which`, `typeHyb`, `t1`, `split`, `formula`, `expCF`. To do this, we need to modify the `QuartetNetwork` object (i.e. merge edges,...). But we do not want to modify it directly because it is connected to the original `net` via a map of the edges and nodes, so we use a deep copy: `qnet=deepcopy(q.qnet)` and then `calculateExpCFAll!(qnet)`. Attributes that are updated on the original `QuartetNetwork` object `q.qnet` are: - `q.qnet.hasEdge`: array of booleans of length equal to `net.edge` that shows which identifiable edges and gammas of `net` (`net.ht`) are in `qnet` (and still identifiable). Note that the first elements of the vector correspond to the gammas. - `q.qnet.index`: length should match the number of trues in `qnet.hasEdge`. It has the indexes in `qnet.edge` from the edges in `qnet.hasEdge`. Note that the first elements of the vector correspond to the gammas. - `q.qnet.edge`: list of edges in `QuartetNetwork`. Note that external edges in `net` are collapsed when they appear in `QuartetNetwork`, so only internal edges map directly to edges in `net` - `q.qnet.expCF`: expected CF for this `Quartet` Why not modify the original `QuartetNetwork`? We wanted to keep the original `QuartetNetwork` stored in `DataCF` with all the identifiable edges, to be able to determine if this object had been changed or not after a certain optimization. The process is: 1. Deep copy of full network to create `q.qnet` for `Quartet q`. This `QuartetNetwork` object has only 4 leaves now, but does not have merged edges (the identifiable ones) so that we can correspond to the edges in net. This `QuartetNetwork` does not have other attributes updated. 2. For the current set of branch lengths and gammas, we can update the attributes in `q.qnet` to compute the expected CF. The functions that do this will "destroy" the `QuartetNetwork` object by merging edges, removing nodes, etc... So, we do this process in `qnet=deepcopy(q.qnet)`, and at the end, only update `q.qnet.expCF`. 3. After we optimize branch lengths in the full network, we want to update the branch lengths in `q.qnet`. The edges need to be there (which is why we do not want to modify this `QuartetNetwork` object by merging edges), and we do not do a deep-copy of the full network again. We only change the values of branch lengths and gammas in `q.qnet`, and we can re-calculate the expCF by creating a deep copy `qnet=deepcopy(q.qnet)` and run the other functions (which merge edges, etc) to get the `expCF`. Future work: there are definitely more efficient ways to do this (without the deep copies). In addition, currently edges that are no longer identifiable in `QuartetNetwork` do not appear in `hasEdge` nor `index`. Need to study this. ```jldoctest julia> net0 = readTopology("(s17:13.76,(((s3:10.98,(s4:8.99,s5:8.99)I1:1.99)I2:0.47,(((s6:2.31,s7:2.31)I3:4.02,(s8:4.97,#H24:0.0::0.279)I4:1.36)I5:3.64,((s9:8.29,((s10:2.37,s11:2.37)I6:3.02,(s12:2.67,s13:2.67)I7:2.72)I8:2.89)I9:0.21,((s14:2.83,(s15:1.06,s16:1.06)I10:1.78)I11:2.14)#H24:3.52::0.72)I12:1.47)I13:1.48)I14:1.26,(((s18:5.46,s19:5.46)I15:0.59,(s20:4.72,(s21:2.40,s22:2.40)I16:2.32)I17:1.32)I18:2.68,(s23:8.56,(s1:4.64,s2:4.64)I19:3.92)I20:0.16)I21:3.98)I22:1.05);"); julia> net = readTopologyLevel1(writeTopology(net0)) ## need level1 attributes for functions below HybridNetwork, Un-rooted Network 46 edges 46 nodes: 23 tips, 1 hybrid nodes, 22 internal tree nodes. tip labels: s17, s3, s4, s5, ... (s4:8.99,s5:8.99,(s3:10.0,((((s6:2.31,s7:2.31)I3:4.02,(s8:4.97,#H24:0.0::0.279)I4:1.36)I5:3.64,((s9:8.29,((s10:2.37,s11:2.37)I6:3.02,(s12:2.67,s13:2.67)I7:2.72)I8:2.89)I9:0.21,((s14:2.83,(s15:1.06,s16:1.06)I10:1.78)I11:2.14)#H24:3.52::0.721)I12:1.47)I13:1.48,((((s18:5.46,s19:5.46)I15:0.59,(s20:4.72,(s21:2.4,s22:2.4)I16:2.32)I17:1.32)I18:2.68,(s23:8.56,(s1:4.64,s2:4.64)I19:3.92)I20:0.16)I21:3.98,s17:10.0)I22:1.26)I14:0.47)I2:1.99)I1; julia> q1 = Quartet(1,["s1", "s16", "s18", "s23"],[0.296,0.306,0.398]) number: 1 taxon names: ["s1", "s16", "s18", "s23"] observed CF: [0.296, 0.306, 0.398] pseudo-deviance under last used network: 0.0 (meaningless before estimation) expected CF under last used network: Float64[] (meaningless before estimation) julia> qnet = PhyloNetworks.extractQuartet!(net,q1) taxa: ["s1", "s16", "s18", "s23"] number of hybrid nodes: 1 julia> sum([e.istIdentifiable for e in net.edge]) ## 23 identifiable edges in net 23 julia> idedges = [ee.number for ee in net.edge[[e.istIdentifiable for e in net.edge]]]; julia> print(idedges) [5, 6, 9, 11, 12, 13, 17, 20, 21, 22, 26, 27, 28, 29, 30, 31, 34, 38, 39, 40, 44, 45, 46] julia> length(qnet.hasEdge) ## 24 = 1 gamma + 23 identifiable edges 24 julia> sum(qnet.hasEdge) ## 8 = 1 gamma + 7 identifiable edges in qnet 8 julia> print(idedges[qnet.hasEdge[2:end]]) ## 7 id. edges: [12, 13, 29, 30, 31, 45, 46] [12, 13, 29, 30, 31, 45, 46] julia> qnet.edge[qnet.index[1]].number ## 11 = minor hybrid edge 11 ``` """ mutable struct QuartetNetwork <: Network numTaxa::Int numNodes::Int numEdges::Int node::Array{Node,1} edge::Array{Edge,1} hybrid::Array{Node,1} # array of hybrid nodes in network leaf::Array{Node,1} # array of leaves numHybrids::Int # number of hybrid nodes hasEdge::Array{Bool,1} # array of boolean with all the original identifiable edges of HybridNetwork and gammas (net.ht) quartetTaxon::Array{String,1} # the quartet taxa in the order it represents. Points to same array as its Quartet.taxon which::Int8 # 0 it tree quartet, 1 is equivalent to tree quartet and 2 if two minor CF different, default -1 typeHyb::Array{Int8,1} #array with the type of hybridization of each hybrid node in the quartet t1::Float64 # length of internal edge, used when qnet.which=1, default = -1 names::Array{String,1} # taxon and node names, same order as in network.node split::Array{Int8,1} # split that denotes to which side each leaf is from the split, i.e. [1,2,2,1] means that leaf1 and 4 are on the same side of the split, default -1,-1,-1,-1 formula::Array{Int8,1} # array for qnet.which=1 that indicates if the expCf is major (1) or minor (2) at qnet.expCF[i] depending on qnet.formula[i], default -1,-1,-1 expCF::Array{Float64,1} # three expected CF in order 12|34, 13|24, 14|23 (matching obsCF from qnet.quartet), default [0,0,0] indexht::Vector{Int} # index in net.ht for each edge in qnet.ht changed::Bool # true if the expCF would be changed with the current parameters in the optimization, to recalculate, default true index::Vector{Int} # index in qnet.edge (qnet.node for gammaz) of the members in qnet.indexht to know how to find quickly in qnet # inner constructor function QuartetNetwork(net::HybridNetwork) net2 = deepcopy(net); #fixit: maybe we dont need deepcopy of all, maybe only arrays new(net2.numTaxa,net2.numNodes,net2.numEdges,net2.node,net2.edge,net2.hybrid,net2.leaf,net2.numHybrids, [true for e in net2.edge],[],-1,[], -1.,net2.names,Int8[-1,-1,-1,-1],Int8[-1,-1,-1],[0,0,0],[],true,[]) end QuartetNetwork() = new(0,0,0,[],[],[],[],0,[],[],-1,[],-1.0,[],[],[],[],[],true,[]) end abstract type AQuartet end """ Quartet type that saves the information on a given 4-taxon subset. It contains the following attributes: - number: integer - taxon: vector of taxon names, like t1 t2 t3 t4 - obsCF: vector of observed CF, in order 12|34, 13|24, 14|23 - logPseudoLik - ngenes: number of gene trees used to compute the observed CF; -1.0 if unknown - qnet: [`QuartetNetwork`](@ref), which saves the expCF after snaq estimation to emphasize that the expCF depend on a specific network, not the data see also: [`QuartetT`](@ref) for quartet with data of user-defined type `T`, using a mapping between quartet indices and quartet taxa. """ mutable struct Quartet <: AQuartet number::Int taxon::Array{String,1} # taxa 1234. qnet.quartetTaxon points to the same array. obsCF::Array{Float64,1} # three observed CF in order 12|34, 13|24, 14|23 qnet::QuartetNetwork # quartet network for the current network (want to keep as if private attribute) logPseudoLik::Float64 # log pseudolik value for the quartet. 0.0 by default ngenes::Float64 # number of gene trees used to compute the obsCV, default -1.; Float in case ngenes is average # inner constructor: to guarantee obsCF are only three and add up to 1 function Quartet(number::Integer,t1::AbstractString,t2::AbstractString,t3::AbstractString,t4::AbstractString,obsCF::Array{Float64,1}) size(obsCF,1) != 3 ? error("observed CF vector should have size 3, not $(size(obsCF,1))") : nothing 0.99 < sum(obsCF) < 1.02 || @warn "observed CF should add up to 1, not $(sum(obsCF))" new(number,[t1,t2,t3,t4],obsCF,QuartetNetwork(),0.0,-1.0); end function Quartet(number::Integer,t1::Array{String,1},obsCF::Array{Float64,1}) size(obsCF,1) != 3 ? error("observed CF vector should have size 3, not $(size(obsCF,1))") : nothing 0.99< sum(obsCF) < 1.02 || @warn "observed CF should add up to 1, not $(sum(obsCF))" size(t1,1) != 4 ? error("array of taxa should have size 4, not $(size(t1,1))") : nothing 0.0 <= obsCF[1] <= 1.0 || error("obsCF must be between (0,1), but it is $(obsCF[1]) for $(t1)") 0.0 <= obsCF[2] <= 1.0 || error("obsCF must be between (0,1), but it is $(obsCF[2]) for $(t1)") 0.0 <= obsCF[3] <= 1.0 || error("obsCF must be between (0,1), but it is $(obsCF[3]) for $(t1)") new(number,t1,obsCF,QuartetNetwork(),0.0,-1.0); end Quartet() = new(0,[],[],QuartetNetwork(),0.0,-1.0) end """ QuartetT{T} Generic type for 4-taxon sets. Fields: - `number`: rank of the 4-taxon set - `taxonnumber`: static vector of 4 integers, assumed to be distinct and sorted - `data`: object of type `T` For easier look-up, a unique mapping is used between the rank (`number`) of a 4-taxon set and its 4 taxa (see [`quartetrank`](@ref) and [`nchoose1234`](@ref)): rank-1 = (t1-1) choose 1 + (t2-1) choose 2 + (t3-1) choose 3 + (t4-1) choose 4 # examples ```jldoctest julia> nCk = PhyloNetworks.nchoose1234(5) 6×4 Matrix{Int64}: 0 0 0 0 1 0 0 0 2 1 0 0 3 3 1 0 4 6 4 1 5 10 10 5 julia> PhyloNetworks.QuartetT(1,3,4,6, [.92,.04,.04, 100], nCk) 4-taxon set number 8; taxon numbers: 1,3,4,6 data: [0.92, 0.04, 0.04, 100.0] ``` """ struct QuartetT{T} <: AQuartet where T number::Int taxonnumber::StaticArrays.SVector{4,Int} data::T end function Base.show(io::IO, obj::QuartetT{T}) where T disp = "4-taxon set number $(obj.number); taxon numbers: " disp *= join(obj.taxonnumber,",") disp *= "\ndata: " print(io, disp) print(io, obj.data) end function QuartetT(tn1::Int,tn2::Int,tn3::Int,tn4::Int, data::T, nCk::Matrix, checksorted=true::Bool) where T if checksorted (tn1<tn2 && tn2<tn3 && tn3<tn4) || error("taxon numbers must be sorted") end QuartetT{T}(quartetrank(tn1,tn2,tn3,tn4,nCk), SVector(tn1,tn2,tn3,tn4), data) end """ quartetrank(t1,t2,t3,t4, nCk::Matrix) quartetrank([t1,t2,t3,t4], nCk) Return the rank of a four-taxon set with taxon numbers `t1,t2,t3,t4`, assuming that `ti`s are positive integers such that t1<t2, t2<t3 and t3<t4 (assumptions not checked!). `nCk` should be a matrix of "n choose k" binomial coefficients: see [`nchoose1234`](@ref). # examples ```jldoctest julia> nCk = PhyloNetworks.nchoose1234(5) 6×4 Matrix{Int64}: 0 0 0 0 1 0 0 0 2 1 0 0 3 3 1 0 4 6 4 1 5 10 10 5 julia> PhyloNetworks.quartetrank([1,2,3,4], nCk) 1 julia> PhyloNetworks.quartetrank([3,4,5,6], nCk) 15 ``` """ @inline function quartetrank(tnum::AbstractVector, nCk::Matrix) quartetrank(tnum..., nCk) end @inline function quartetrank(t1::Int, t2::Int, t3::Int, t4::Int, nCk::Matrix) # rank-1 = t1-1 choose 1 + t2-1 choose 2 + t3-1 choose 3 + t4-1 choose 4 return nCk[t1,1] + nCk[t2,2] + nCk[t3,3] + nCk[t4,4] + 1 end """ nchoose1234(nmax) `nmax+1 x 4` matrix containing the binomial coefficient "n choose k" in row `n+1` and column `k`. In other words, `M[i,k]` gives "i-1 choose k". It is useful to store these values and look them up to rank (a large number of) 4-taxon sets: see [`quartetrank`](@ref). """ function nchoose1234(nmax::Int) # compute nC1, nC2, nC3, nC4 for n in [0, nmax]: used for ranking quartets M = Matrix{Int}(undef, nmax+1, 4) for i in 1:(nmax+1) M[i,1] = i-1 # n choose 1 = n. row i is for n=i-1 end M[1,2:4] .= 0 # 0 choose 2,3,4 = 0 for i in 2:(nmax+1) for k in 2:4 # to choose k items in 1..n: the largest could be n, else <= n-1 M[i,k] = M[i-1,k-1] + M[i-1,k] end end return M end # Data on quartet concordance factors ------- """ DataCF type that contains the following attributes: - quartet (vector of Quartets) - numQuartets - tree (vector of trees: empty if a table of CF was input instead of list of trees) - numTrees (-1 if a table CF was input instead of list of trees) - repSpecies (taxon names that were repeated in table of CF or input gene trees: used inside snaq for multiple alleles case) The list of Quartet may be accessed with the attribute .quartet. If the input was a list of trees, the HybridNetwork's can be accessed with the attribute .tree. For example, if the DataCF object is named d, d.quartet[1] will show the first quartet and d.tree[1] will print the first input tree. """ mutable struct DataCF # fixit quartet::Array{Quartet,1} # array of quartets read from CF output table or list of quartets in file numQuartets::Integer # number of quartets tree::Vector{HybridNetwork} #array of input gene trees numTrees::Integer # number of gene trees repSpecies::Vector{String} #repeated species in the case of multiple alleles DataCF(quartet::Array{Quartet,1}) = new(quartet,length(quartet),[],-1,[]) DataCF(quartet::Array{Quartet,1},trees::Vector{HybridNetwork}) = new(quartet,length(quartet),trees,length(trees),[]) DataCF() = new([],0,[],-1,[]) end # aux type for the updateBL function mutable struct EdgeParts edgenum::Int part1::Vector{Node} part2::Vector{Node} part3::Vector{Node} part4::Vector{Node} end struct RootMismatch <: Exception msg::String end RootMismatch() = RootMismatch("") Base.showerror(io::IO, e::RootMismatch) = print(io, "RootMismatch: ", e.msg);
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
3611
# functions to undo incycle, containRoot, gammaz # originally in functions.jl # Claudia March 2015 # ---------------------------------------- undo update of new hybridization -------------------------------- # function to undo updateInCycle which returns an array # of edges/nodes changed function undoInCycle!(edges::Array{Edge,1},nodes::Array{Node,1}) for e in edges e.inCycle = -1; end for n in nodes n.inCycle = -1; end end # function to undo updateContainRoot (which returns an array # of edges changed) and gives value bool, by default true function undoContainRoot!(edges::Array{Edge,1}, bool::Bool) for e in edges e.containRoot = bool end end undoContainRoot!(edges::Vector{Edge}) = undoContainRoot!(edges,true) # function to undo updateGammaz which returns an array # of edges changed # it only changes the status of istIdentifiable to true function undoistIdentifiable!(edges::Array{Edge,1}) for e in edges !e.istIdentifiable ? e.istIdentifiable = true : e.istIdentifiable = false; end end """ undoGammaz!(node, network) Undo `updateGammaz!` for the 2 cases: bad diamond I,II. `node` should be a hybrid node. Set length to edges that were not identifiable and change edges' `gammaz` attribute to -1.0. Recalculate branch lengths in terms of `gammaz`. *warning*: needs to know `incycle` attributes """ function undoGammaz!(node::Node, net::HybridNetwork) node.hybrid || error("cannot undo gammaz if starting node is not hybrid") if(node.isBadDiamondI) edge_maj, edge_min, tree_edge2 = hybridEdges(node); other_maj = getOtherNode(edge_maj,node); other_min = getOtherNode(edge_min,node); edgebla,tree_edge_incycle1,tree_edge = hybridEdges(other_min); edgebla,tree_edge_incycle2,tree_edge = hybridEdges(other_maj); other_min.gammaz != -1 || error("bad diamond I in node $(node.number) but no gammaz updated correctly") setLength!(tree_edge_incycle1,-log(1-other_min.gammaz)) other_maj.gammaz != -1 || error("bad diamond I in node $(node.number) but no gammaz updated correctly") setLength!(tree_edge_incycle2,-log(1-other_maj.gammaz)) if approxEq(other_maj.gammaz,0.0) && approxEq(other_min.gammaz,0.0) setGamma!(edge_maj,0.0, true) # gamma could be anything if both gammaz are 0.0, but will set to 0.0 setLength!(edge_maj,0.0) setLength!(edge_min,0.0) else setGamma!(edge_maj,other_maj.gammaz / (other_maj.gammaz+other_min.gammaz), true) end other_min.gammaz = -1.0 other_maj.gammaz = -1.0 tree_edge_incycle1.istIdentifiable = true; tree_edge_incycle2.istIdentifiable = true; edge_maj.istIdentifiable = true; edge_min.istIdentifiable = true; node.isBadDiamondI = false net.numBad -= 1 elseif(node.isBadDiamondII) edge_maj, edge_min, tree_edge2 = hybridEdges(node); tree_edge2.istIdentifiable = true node.isBadDiamondII = false elseif(node.isBadTriangle) edge_maj, edge_min, tree_edge2 = hybridEdges(node); tree_edge2.istIdentifiable = true node.isBadTriangle = false elseif(node.isVeryBadTriangle || node.isExtBadTriangle) node.isVeryBadTriangle = false node.isExtBadTriangle = false net.hasVeryBadTriangle = false else edge_maj, edge_min, tree_edge2 = hybridEdges(node); edge_maj.istIdentifiable = isEdgeIdentifiable(edge_maj) edge_min.istIdentifiable = isEdgeIdentifiable(edge_min) end end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
17032
# functions to update incycle, containRoot, gammaz # Claudia March 2015 ##################### # --------------------------------------- update incycle, root, gammaz ------------------------------------------- # function to update inCycle (with priority queue) after becoming part of a network # based on program 3 CS367 with priority queue # expected to be much faster than the other two udpateInCycle (queue and recursive) # input: hybrid node around which we want to update inCycle # returns tuple: flag, nocycle, array of edges changed, array of nodes changed # flag: false if cycle intersects existing cycle or number of nodes in cycle < 3 # (there is the possibility of returning edges in intersection: path) # true if cycle does not intersect existing cycle # nocycle: true if there is no cycle (instead of error). it is used in addHybridization # calculates also the number of nodes in the cycle and put as hybrid node attribute "k" # warning: it is not checking if hybrid node or minor hybrid edge # were already part of a cycle (inCycle!= -1) # But it is checking so for the other edges in cycle # warning: it needs extra things: visited attribute, prev attribute # unlike updateInCycle recursive, but it is expected # to be much faster function updateInCycle!(net::HybridNetwork,node::Node) node.hybrid || error("node is not hybrid") start = node node.inCycle = node.number node.k = 1 hybedge = getparentedgeminor(node) hybedge.inCycle = node.number lastnode = getOtherNode(hybedge,node) dist = 0 queue = PriorityQueue() path = Node[] net.edges_changed = Edge[] net.nodes_changed = Node[] push!(net.edges_changed,hybedge) push!(net.nodes_changed,node) found = false net.visited = falses(length(net.node)) enqueue!(queue,node,dist) while !found if isempty(queue) return false, true, net.edges_changed, net.nodes_changed end curr = dequeue!(queue) if isEqual(curr,lastnode) found = true push!(path,curr) elseif !net.visited[getIndex(curr,net)] net.visited[getIndex(curr,net)] = true atstart = isEqual(curr,start) for e in curr.edge e.isMajor || continue other = getOtherNode(e,curr) if atstart || (!other.leaf && !net.visited[getIndex(other,net)]) other.prev = curr dist = dist+1 enqueue!(queue,other,dist) end end end end # end while curr = pop!(path) while !isEqual(curr, start) if curr.inCycle!= -1 push!(path,curr) curr = curr.prev else curr.inCycle = start.number push!(net.nodes_changed, curr) node.k = node.k + 1 edge = getConnectingEdge(curr,curr.prev) edge.inCycle = start.number push!(net.edges_changed, edge) curr = curr.prev end end flag = isempty(path) # || node.k<3 !flag && @debug "warning: new cycle intersects existing cycle" return flag, false, net.edges_changed, net.nodes_changed end """ updateContainRoot!(HybridNetwork, Node) traverseContainRoot!(Node, Edge, edges_changed::Array{Edge,1}, rightDir::Vector{Bool}) The input `node` to `updateContainRoot!` must be a hybrid node (can come from searchHybridNode). `updateContainRoot!` starts at the input node and calls `traverseContainRoot!`, which traverses the network recursively. By default, containRoot attributes of edges are true. Changes `containRoot` to false for all the visited edges: those below the input node, but not beyond any other hybrid node. `updateContainRoot!` Returns a `flag` and an array of edges whose containRoot has been changed from true to false. `flag` is false if the set of edges to place the root is empty In `traverseContainRoot!`, `rightDir` turns false if hybridizations have incompatible directions (vector of length 1, to be modified). Warning: - does *not* update `containRoot` of minor hybrid edges. - assumes correct `isMajor` attributes: to stop the recursion at minor hybrid edges. - assumes correct hybrid attributes of both nodes & edges: to check if various hybridizations have compatible directions. For each hybrid node that is encountered, checks if it was reached via a hybrid edge (ok) or tree edge (not ok). `rightDir`: vector of length 1 boolean, to be mutable and modified by the function """ function traverseContainRoot!(node::Node, edge::Edge, edges_changed::Array{Edge,1}, rightDir::Vector{Bool}) if node.hybrid if edge.hybrid edge.isMajor || error("hybrid edge $(edge.number) is minor and we should not traverse the graph through minor edges") DEBUGC && @debug "traverseContainRoot reaches hybrid node $(node.number) through major hybrid edge $(edge.number)" rightDir[1] &= true # This line has no effect: x && true = x else #approach hybrid node through tree edge => wrong direction rightDir[1] &= false # same as rightDir[1] = false: x && false = false DEBUGC && @debug "traverseContainRoot reaches hybrid node $(node.number) through tree edge $(edge.number), so rightDir $(rightDir[1])" end elseif !node.leaf for e in node.edge if !isEqual(edge,e) && e.isMajor # minor edges avoided-> their containRoot not updated other = getOtherNode(e,node); if e.containRoot # only considered changed those that were true and not hybrid DEBUGC && @debug "traverseContainRoot changing edge $(e.number) to false, at this moment, rightDir is $(rightDir[1])" e.containRoot = false; push!(edges_changed, e); end traverseContainRoot!(other,e, edges_changed, rightDir); end end end end # node: must be hybrid node (can come from searchHybridNode) # return flag, array of edges changed # flag: false if the set of edges to place the root is empty @doc (@doc traverseContainRoot!) updateContainRoot! function updateContainRoot!(net::HybridNetwork, node::Node) node.hybrid || error("node $(node.number )is not hybrid, cannot update containRoot") net.edges_changed = Edge[]; rightDir = [true] #assume good direction, only changed if found hybrid node through tree edge for e in node.edge if !e.hybrid other = getOtherNode(e,node); e.containRoot = false; push!(net.edges_changed,e); traverseContainRoot!(other,e, net.edges_changed,rightDir); end end if !rightDir[1] || all((e->!e.containRoot), net.edge) return false,net.edges_changed else return true,net.edges_changed end end # function to identify if the network is one of the pathological cases # see ipad notes: k = 0 (nonidentifiable), k = 1 (nonidentifiable # "extreme bad triangle", "very" bad triangle I,II) k = 2 (bad diamond # I,II) also checks if hybrid node has leaf child, in which case, # major edge is non identifiable # input: hybrid node around which to check (can come from searchHybridNode) # updates gammaz with whatever # edge lengths are originally in the network # allow = true, returns true always, used when reading topology # returns net.hasVeryBadTriangle, array of edges changed (istIdentifiable, except hybrid edges) # false if the network has extremely/very bad triangles # warning: needs to have updateInCycle already done as it needs inCycle, and k # check: assume any tree node that has hybrid Edge has only # one tree edge in cycle (true?) # updates net.numBad attribute when found a bad diamond I function updateGammaz!(net::HybridNetwork, node::Node, allow::Bool) node.hybrid || error("node $(node.number) is not hybrid, cannot updategammaz") node.k != -1 || error("update in cycle should have been run before: node.k not -1") node.isExtBadTriangle = false node.isVeryBadTriangle = false node.isBadTriangle = false node.isBadDiamondI = false node.isBadDiamondII = false net.edges_changed = Edge[]; edge_maj, edge_min, tree_edge2 = hybridEdges(node); other_maj = getOtherNode(edge_maj,node); other_min = getOtherNode(edge_min,node); node.k > 2 || error("cycle with only $(node.k) nodes: parallel edges") # return false, [] if(node.k == 4) # could be bad diamond I,II # net.numTaxa >= 5 || return false, [] #checked inside optTopRuns now edgebla,edge_min2,tree_edge3 = hybridEdges(other_min); edgebla,edge_maj2,tree_edge1 = hybridEdges(other_maj); other_min2 = getOtherNode(edge_min2,other_min); isLeaf1 = getOtherNode(tree_edge1,other_maj); isLeaf2 = getOtherNode(tree_edge2,node); isLeaf3 = getOtherNode(tree_edge3,other_min); tree_edge4 = nothing; for e in other_min2.edge if(isa(tree_edge4,Nothing) && e.inCycle == -1 && !e.hybrid) tree_edge4 = e; end end if(isEqual(other_min2,getOtherNode(edge_maj2,other_maj)) && isLeaf1.leaf && isLeaf2.leaf && isLeaf3.leaf) # bad diamond I @debug "bad diamond I found" net.numBad += 1 node.isBadDiamondI = true; other_min.gammaz = edge_min.gamma*edge_min2.z; other_maj.gammaz = edge_maj.gamma*edge_maj2.z; edge_min2.istIdentifiable = false; edge_maj2.istIdentifiable = false; edge_maj.istIdentifiable = false; edge_min.istIdentifiable = false; push!(net.edges_changed,edge_min2); push!(net.edges_changed,edge_min); push!(net.edges_changed,edge_maj2); push!(net.edges_changed,edge_maj); elseif(isEqual(other_min2,getOtherNode(edge_maj2,other_maj)) && isLeaf1.leaf && !isLeaf2.leaf && isLeaf3.leaf && getOtherNode(tree_edge4,other_min2).leaf) # bad diamond II @debug "bad diamond II found" node.isBadDiamondII = true; setLength!(edge_maj,edge_maj.length+tree_edge2.length) setLength!(tree_edge2,0.0) push!(net.edges_changed,tree_edge2) tree_edge2.istIdentifiable = false edge_maj.istIdentifiable = true edge_min.istIdentifiable = true end elseif(node.k == 3) # could be extreme/very bad triangle or just bad triangle if(net.numTaxa <= 5) @debug "extremely or very bad triangle found" node.isVeryBadTriangle = true net.hasVeryBadTriangle = true elseif(net.numTaxa >= 6) edgebla,tree_edge_incycle,tree_edge1 = hybridEdges(other_min); edgebla,edgebla,tree_edge3 = hybridEdges(other_maj); isLeaf1 = getOtherNode(tree_edge1,other_min); isLeaf2 = getOtherNode(tree_edge2,node); isLeaf3 = getOtherNode(tree_edge3,other_maj); if isLeaf1.leaf || isLeaf2.leaf || isLeaf3.leaf nl = count([l.leaf for l in [isLeaf1,isLeaf2,isLeaf3]]) if nl >= 2 @debug "warning: extremely bad triangle found" node.isExtBadTriangle = true; net.hasVeryBadTriangle = true elseif nl == 1 @debug "warning: bad triangle I or II found" node.isVeryBadTriangle = true; net.hasVeryBadTriangle = true end else node.isBadTriangle = true setLength!(edge_maj,edge_maj.length+tree_edge2.length) setLength!(tree_edge2,0.0) tree_edge2.istIdentifiable = false push!(net.edges_changed, tree_edge2); end end end #ends the search for bad things if(node.k > 3 && !node.isBadDiamondI && !node.isBadDiamondII) #println("si entra el ultimo if de k>3 y no bad diamondI,II") edgebla,tree_edge_incycle,tree_edge1 = hybridEdges(other_min); if(!tree_edge_incycle.istIdentifiable) tree_edge_incycle.istIdentifiable = true; push!(net.edges_changed,tree_edge_incycle); end edge_maj.istIdentifiable = isEdgeIdentifiable(edge_maj) edge_min.istIdentifiable = isEdgeIdentifiable(edge_min) end isBadTriangle(node) == net.hasVeryBadTriangle || error("node $(node.number) is very bad triangle but net.hasVeryBadTriangle is $(net.hasVeryBadTriangle)") if(allow) return true, net.edges_changed else return !net.hasVeryBadTriangle, net.edges_changed end end updateGammaz!(net::HybridNetwork, node::Node) = updateGammaz!(net, node, false) #function to check if edge should be identifiable #it is not only if followed by leaf, or if a newly converted tree edge function isEdgeIdentifiable(edge::Edge) if(edge.hybrid) node = edge.node[edge.isChild1 ? 1 : 2] #println("is edge $(edge.number) identifiable, node $(node.number)") node.hybrid || error("hybrid edge $(edge.number) pointing at tree node $(node.number)") major,minor,tree = hybridEdges(node) #println("major $(major.number), minor $(minor.number), tree $(tree.number)") if(getOtherNode(tree,node).leaf) return false else return true end else if(reduce(&,[!edge.node[1].leaf,!edge.node[2].leaf])) if(!edge.node[1].hybrid && !edge.node[2].hybrid && !edge.fromBadDiamondI) return true elseif(edge.node[1].hybrid || edge.node[2].hybrid) ind = edge.node[1].hybrid ? 1 : 2 if(!edge.node[ind].isBadDiamondII && !edge.node[ind].isBadTriangle) return true else return false end end else return false end end end # function to update the net.partition attribute along a cycle formed # by nodesChanged vector (obtained from updateInCycle) # warning: needs updateInCycle for all hybrids before running this function updatePartition!(net::HybridNetwork, nodesChanged::Vector{Node}) if(net.numHybrids == 0) net.partition = Partition[] end for n in nodesChanged if(length(n.edge) == 3) #because we are allowing the root to have only two edges when read from parenthetical format edge = nothing for e in n.edge if(e.inCycle == -1) edge = e end end !isa(edge,Nothing) || error("one edge in n.edge for node $(n.number) should not be in cycle") descendants = [edge] cycleNum = [nodesChanged[1].inCycle] getDescendants!(getOtherNode(edge,n),edge,descendants,cycleNum) !isempty(descendants) || error("descendants is empty for node $(n.number)") @debug "for node $(n.number), descendants are $([e.number for e in descendants]), and cycleNum is $(cycleNum)" partition = Partition(cycleNum,descendants) if(!isPartitionInNet(net,partition)) #need to check not already added by other hybrid nodes push!(net.partition, partition) end end end end function choosePartition(net::HybridNetwork) all((n->(length(n.edges) == 1)), net.partition) && return 0 #cannot put any hyb all((n->(length(n.edges) == 3)), net.partition) && return 0 #can only put very bad triangles partition = Int[] #good partitions for i in 1:length(net.partition) if(length(net.partition[i].edges) > 3) push!(partition,i) end end isempty(partition) && return 0 length(partition) == 1 && return partition[1] index1 = round(Integer,rand()*size(partition,1)); while(index1 == 0 || index1 > length(partition)) index1 = round(Integer,rand()*size(partition,1)); end @debug "chosen partition $([n.number for n in net.partition[partition[index1]].edges])" return partition[index1] end # based on getDescendants on readData.jl but with vector of edges, instead of nodes # finds the partition corresponding to the node and edge in the cycle # used in chooseEdgesGamma and to set net.partition # cycleNum is a variable that will save another hybrid node number if found function getDescendants!(node::Node, edge::Edge, descendants::Vector{Edge}, cycleNum::Vector{Int}) @debug "getDescendants of node $(node.number) and edge $(edge.number)" if(node.inCycle != -1) push!(cycleNum,node.inCycle) elseif(!node.leaf && node.inCycle == -1) for e in node.edge if(!isEqual(edge,e) && e.isMajor) push!(descendants,e) getDescendants!(getOtherNode(e,node),e,descendants,cycleNum) end end end end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
4278
# see readme file in tests/ for description of tests # Claudia July 2015 # modified to using PhyloNetworks always, all test files have commented out # the include(...) or the using PhyloNetworks part # Claudia May 2016 using Test using PhyloNetworks using CSV # for reading files using DataFrames using Distributed # parallel in test_correctLik.jl and test_bootstrap.jl using GLM # for coef, nobs, residuals etc. using LinearAlgebra: norm, diag, logdet, PosDefException # LinearAlgebra.rotate! not brought into scope using Random using StaticArrays # for rate substitution matrices using Statistics using StatsBase # for aic etc., stderr using BioSymbols PhyloNetworks.setCHECKNET(true) ## readTopology getIndexEdge = PhyloNetworks.getIndexEdge getIndexNode = PhyloNetworks.getIndexNode Edge = PhyloNetworks.Edge Node = PhyloNetworks.Node setNode! = PhyloNetworks.setNode! ## calculateExpCF approxEq = PhyloNetworks.approxEq Quartet = PhyloNetworks.Quartet extractQuartet! = PhyloNetworks.extractQuartet! identifyQuartet! = PhyloNetworks.identifyQuartet! eliminateHybridization! = PhyloNetworks.eliminateHybridization! updateSplit! = PhyloNetworks.updateSplit! updateFormula! = PhyloNetworks.updateFormula! calculateExpCF! = PhyloNetworks.calculateExpCF! parameters! = PhyloNetworks.parameters! searchHybridNode = PhyloNetworks.searchHybridNode updateInCycle! = PhyloNetworks.updateInCycle! updateContainRoot! = PhyloNetworks.updateContainRoot! updateGammaz! = PhyloNetworks.updateGammaz! ## correctLik calculateExpCFAll! = PhyloNetworks.calculateExpCFAll! logPseudoLik = PhyloNetworks.logPseudoLik optTopRun1! = PhyloNetworks.optTopRun1! ## partition addHybridizationUpdate! = PhyloNetworks.addHybridizationUpdate! deleteHybridizationUpdate! = PhyloNetworks.deleteHybridizationUpdate! ## partition2 writeTopologyLevel1 = PhyloNetworks.writeTopologyLevel1 printPartitions = PhyloNetworks.printPartitions cleanBL! = PhyloNetworks.cleanBL! cleanAfterRead! = PhyloNetworks.cleanAfterRead! identifyInCycle = PhyloNetworks.identifyInCycle updatePartition! = PhyloNetworks.updatePartition! ## deleteHybridizationUpdate checkNet = PhyloNetworks.checkNet ## add2hyb hybridEdges = PhyloNetworks.hybridEdges ## optBLparts update! = PhyloNetworks.update! ## orderings_plot RootMismatch = PhyloNetworks.RootMismatch fuseedgesat! = PhyloNetworks.fuseedgesat! ## compareNetworks deletehybridedge! = PhyloNetworks.deletehybridedge! displayedNetworks! = PhyloNetworks.displayedNetworks! ## perfect data writeExpCF = PhyloNetworks.writeExpCF optBL! = PhyloNetworks.optBL! ## traitLikDiscrete P = PhyloNetworks.P P! = PhyloNetworks.P! tests = [ "test_auxillary.jl", "test_generatetopology.jl", "test_addHybrid.jl", "test_5taxon_readTopology.jl", "test_calculateExpCF.jl", "test_calculateExpCF2.jl", "test_hasEdge.jl", "test_parameters.jl", "test_correctLik.jl", "test_partition.jl", "test_partition2.jl", "test_deleteHybridizationUpdate.jl", "test_add2hyb.jl", "test_optBLparts.jl", "test_undirectedOtherNetworks.jl", "test_graph_components.jl", "test_manipulateNet.jl", "test_compareNetworks.jl", "test_badDiamII.jl", "test_multipleAlleles.jl", "test_bootstrap.jl", "test_perfectData.jl", "test_moves_semidirected.jl", "test_lm.jl", "test_lm_tree.jl", "test_traits.jl", "test_simulate.jl", "test_simulate_mbd.jl", "test_lm_withinspecies.jl", "test_parsimony.jl", "test_calibratePairwise.jl", "test_relaxed_reading.jl", "test_isMajor.jl", "test_interop.jl", "test_traitLikDiscrete.jl", "test_phyLiNCoptimization.jl", "test_readInputData.jl", "test_nj.jl", ] @show PhyloNetworks.CHECKNET anyerrors = false for t in tests global anyerrors try @info "starting $t" include(t) println("\033[1m\033[32mPASSED\033[0m: $t") catch anyerrors = true println("\033[1m\033[31mFAILED\033[0m: $t") end end println("-------------------------------------") if anyerrors throw("Tests failed") else println("\033[1m\033[32mTests passed") end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
3620
include("test_functions_5taxon_read.jl") tests = ["F","G","H","J","I"]; wrong = AbstractString[]; function whichtree(t::String) if(t == "tree") tree = "(((6:0.1,4:1.5)1:0.2,7:0.2)5:0.1,8:0.1,10:0.1);" # normal tree elseif(t == "C") tree = "((((6:0.1,4:1.5),(7:0.2)11#H1),11#H1),8:0.1,10:0.1);" # Case C: bad triangle II elseif(t == "F") tree = "(((6:0.1,(4)11#H1)1:0.2,(11#H1,7))5:0.1,8:0.1,10:0.1);" # Case F: bad diamond I elseif(t == "G") tree = "((((6:0.1,4:1.5)1:0.2,(7)11#H1)5:0.1,(11#H1,8)),10:0.1);" # Case G elseif(t == "H") tree = "((((6,4),#H1),7),(8)#H1,10);" # Case H elseif(t == "J") tree = "((((6)#H1,4),7),8,(#H1,10));" # Case J elseif(t == "D") tree = "((((6,4))#H1,(#H1,7)),8,10);" # Case D Bad triangle I elseif(t == "E") tree = "(((((8,10))#H1,7),#H1),6,4);" # Case E Bad triangle I elseif(t == "I") tree = "((((8,10))#H1,7),6,(4,#H1));" # Case I Bad diamond II else error("not a known 5 taxon network case") end return tree end for t in tests #println("running $(t)") net = nothing; tree = whichtree(t) net = readTopologyLevel1(tree); if(t == "tree") try testTree(net) catch println("error in $(t)") push!(wrong,t); end elseif(t == "C") try testCaseC(net) catch println("error in $(t)") push!(wrong,t); end elseif(t == "F") try testCaseF(net) catch println("error in $(t)") push!(wrong,t); end elseif(t == "G") try testCaseG(net) catch println("error in $(t)") push!(wrong,t); end elseif(t == "H") try testCaseH(net) catch println("error in $(t)") push!(wrong,t); end elseif(t == "J") try testCaseJ(net) catch println("error in $(t)") push!(wrong,t); end elseif(t == "D") try testCaseD(net) catch println("error in $(t)") push!(wrong,t); end elseif(t == "E") try testCaseE(net) catch println("error in $(t)") push!(wrong,t); end elseif(t == "I") try testCaseI(net) catch println("error in $(t)") push!(wrong,t); end else error("not a known 5 taxon network case") end end ## if(!isempty(wrong)) ## for t in wrong ## println("running $(t)") ## net = nothing; ## tree = whichtree(t) ## f = open("prueba_tree.txt","w") ## write(f,tree) ## close(f) ## net = readTopologyUpdate("prueba_tree.txt"); ## if(t == "tree") ## testTree(net) ## elseif(t == "C") ## testCaseC(net) ## elseif(t == "F") ## testCaseF(net) ## elseif(t == "G") ## testCaseG(net) ## elseif(t == "H") ## testCaseH(net) ## elseif(t == "J") ## testCaseJ(net) ## elseif(t == "D") ## testCaseD(net) ## elseif(t == "E") ## testCaseE(net) ## elseif(t == "I") ## testCaseI(net) ## else ## error("not a known 5 taxon network case") ## end ## end ## else ## println("----------NO ERRORS!----------"); ## end @test isempty(wrong)
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
1204
# adding more than one hybrid # claudia may 2015 tree = "(((((((1,2),3),4),5),(6,7)),(8,9)),10);" currT0 = readTopologyLevel1(tree); #printEdges(currT0) besttree = deepcopy(currT0); Random.seed!(16); successful,hybrid,flag,nocycle,flag2,flag3 = PhyloNetworks.addHybridizationUpdate!(besttree); @test all([successful, flag, flag2, flag3, !nocycle, hybrid.hybrid]) @test hybrid.number == 11 @test sum(e.inCycle==11 for e in besttree.edge) == 4 @test hybrid.k == 4 @test !hybrid.isBadDiamondI @test !hybrid.isBadDiamondII successful,hybrid,flag,nocycle,flag2,flag3 = PhyloNetworks.addHybridizationUpdate!(besttree); #will add a bad triangle # seed was chosen such that we tried to add a bad triangle. We should notice. @test all([!successful, flag, !flag2, flag3, !nocycle]) @test hybrid.k == 3 @test hybrid.isVeryBadTriangle ed = hybridEdges(hybrid) @test ed[1].isMajor @test ed[1].gamma > 0.5 @test ed[1].hybrid # did not recognize as bad diamond II tree = "(6,(5,#H7:0.0):9.970714072991349,(3,(((2,1):0.2950382234364404,4):0.036924483697671304)#H7:0.00926495670648208):1.1071489442240392);" net = readTopologyLevel1(tree); net.node[10].isBadDiamondII || error("does not recognize as bad diamond II")
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
4436
#= # for local testing, need this: using Test using PhyloNetworks using Random =# @testset "addhybridedge! top function" begin # caution: this test has randomness in its choice of edges; may error sometimes and not others str_tree = "(A:3.0,(B:2.0,(C:1.0,D:1.0):1.0):1.0);"; tree = readTopology(str_tree) Random.seed!(5432); @test !isnothing(PhyloNetworks.addhybridedge!(tree, true, true)) @test tree.numHybrids == 1 @test !isnothing(PhyloNetworks.addhybridedge!(tree, true, true)) # should be able to add a hybrid @test tree.numHybrids == 2 @test !any([n.hybrid for n in PhyloNetworks.getparents(tree.hybrid[2])]) # tests if network is treechild str_level1 = "(((S8,S9),((((S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" netl1 = readTopology(str_level1) @test !isnothing(PhyloNetworks.addhybridedge!(netl1, true, true)) @test netl1.numHybrids == 3 @test !any([n.hybrid for n in PhyloNetworks.getparents(netl1.hybrid[3])]) # tests if network has no hybrid ladder netl1 = readTopology(str_level1) newhybridnode, newhybridedge = PhyloNetworks.addhybridedge!(netl1, false, true) @test !isnothing(newhybridnode) @test netl1.numHybrids == 3 PhyloNetworks.deletehybridedge!(netl1, PhyloNetworks.getparentedgeminor(newhybridnode)) @test hardwiredClusterDistance(netl1, readTopology(str_level1), true) == 0 end # of addhybridedge! top function @testset "addhybridedge! helper function" begin str_level1 = "(((S8,S9),((((S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" # allowed moves netl1 = readTopology(str_level1) newhybridnode, newhybridedge = PhyloNetworks.addhybridedge!(netl1, netl1.edge[3], netl1.edge[9], true, 0.0, 0.2) @test newhybridnode.hybrid @test PhyloNetworks.getparentedge(newhybridnode).gamma == 0.8 @test PhyloNetworks.getparentedgeminor(newhybridnode).gamma == 0.2 netl1 = readTopology(str_level1); @test !isnothing(PhyloNetworks.addhybridedge!(netl1, netl1.edge[15], netl1.edge[3], true)) @test writeTopology(netl1) == "(((((((S1,S4),(S5)#H1),(#H1,(S6,S7))),#H3))#H2,((S8,S9))#H3),(#H2,S10));" netl1 = readTopology(str_level1); @test !isnothing(PhyloNetworks.addhybridedge!(netl1, netl1.edge[2], netl1.edge[17], true)) @test writeTopology(netl1) == "((#H2,S10),(((S8,(S9,#H3)),((((S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2))#H3);" netl1 = readTopology(str_level1); @test !isnothing(PhyloNetworks.addhybridedge!(netl1, netl1.edge[20], netl1.edge[16], true)) @test writeTopology(netl1) == "(((S8,S9),(((((S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2)#H3),((#H2,S10),#H3));" netl1 = readTopology(str_level1); # good hybrid edge choice leads to a DAG when reverting the direction of edge2 @test !isnothing(PhyloNetworks.addhybridedge!(netl1, netl1.edge[6], netl1.edge[20], false)) @test netl1.root < 19 # the root must have been changed due to changing some edges' directions @test writeTopology(netl1) == "(#H2,S10,((((S8,S9),((((S5)#H1,((S1,S4),#H3)),(#H1,(S6,S7))))#H2)))#H3);" # new hybrid into an existing hybrid edge netl1 = readTopology(str_level1); @test !isnothing(PhyloNetworks.addhybridedge!(netl1, netl1.edge[9], netl1.edge[10], true)) @test writeTopology(netl1) == "(((S8,S9),((((S6,S7),(#H1)#H3),(((S1,S4),(S5)#H1),#H3)))#H2),(#H2,S10));" end # of addhybridedge! helper function @testset "edge checking functions" begin str_level1 = "(((S8,S9),((((S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" # 3-cycles: throws error if adding a hybrid edge would create a 3-cycle netl1 = readTopology(str_level1); @test PhyloNetworks.hybrid3cycle(netl1.edge[6], netl1.edge[9]) @test PhyloNetworks.hybrid3cycle(netl1.edge[3], netl1.edge[17]) @test PhyloNetworks.hybrid3cycle(netl1.edge[16], netl1.edge[17]) @test PhyloNetworks.hybrid3cycle(netl1.edge[16], netl1.edge[3]) @test PhyloNetworks.hybrid3cycle(netl1.edge[16], netl1.edge[18]) @test !PhyloNetworks.hybrid3cycle(netl1.edge[16], netl1.edge[20]) # directional: throws error if the new network would not be a DAG, e.g. if edge 1 is a directed descendant of edge 2 # case 6 nodeS145 = PhyloNetworks.getparent(netl1.edge[6]) @test PhyloNetworks.directionalconflict(nodeS145, netl1.edge[15], true) # case 2 @test PhyloNetworks.directionalconflict(nodeS145, netl1.edge[18], true) # case 3 (bad hybrid edge choice leads to a nonDAG) @test PhyloNetworks.directionalconflict(nodeS145, netl1.edge[20], true) @test PhyloNetworks.directionalconflict(nodeS145, netl1.edge[4], false) @test !PhyloNetworks.directionalconflict(nodeS145, netl1.edge[4], true) end # of edge checking functions
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
3806
#= # for local testing, need this: using Test using PhyloNetworks using PhyloPlots using CSV =# @testset "auxiliary" begin @testset "read level 1: hyb edge at root then 2-cycle" begin @test_throws "cycle with only 2 nodes" readTopologyLevel1("((t9,((t3,t2))#H12:::0.52),#H12:::0.48);") end @testset "setlengths and setgammas" begin originalstdout = stdout redirect_stdout(devnull) # requires julia v1.6 @test_nowarn PhyloNetworks.citation() redirect_stdout(originalstdout) str_level1_s = "(((S8,S9),((((S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" # indviduals S1A S1B S1C go on leaf 1 net = readTopology(str_level1_s) PhyloNetworks.setlengths!([net.edge[1]], [1.1]) @test net.edge[1].length == 1.1 PhyloNetworks.setlengths!([net.edge[3], net.edge[4]], [3.3, 4.4]) @test net.edge[3].length == 3.3 @test net.edge[4].length == 4.4 PhyloNetworks.setmultiplegammas!([net.edge[18]], [0.25]) @test net.edge[18].gamma == 0.25 @test net.edge[16].gamma == 0.75 @test PhyloNetworks.getlengths([net.edge[1]]) == [net.edge[1].length] @test PhyloNetworks.getlengths([net.edge[1], net.edge[5]]) == [net.edge[1].length, net.edge[5].length] end @testset "hashybridladder" begin tree = readTopology("(A:3.0,(B:2.0,(C:1.0,D:1.0):1.0):1.0);"); @test !PhyloNetworks.hashybridladder(tree) PhyloNetworks.addhybridedge!(tree, tree.edge[5], tree.edge[1], true) PhyloNetworks.addhybridedge!(tree, tree.edge[2], tree.edge[1], true) @test PhyloNetworks.hashybridladder(tree) end # of testing hashybridladder @testset "shrink edges and cycles" begin # shrink 1 edge, and hassinglechild net = readTopology("((A:2.0,(((B1,B2):1.0)0.01)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5);") @test !PhyloNetworks.shrinkedge!(net, net.edge[10]) @test_throws Exception PhyloNetworks.shrinkedge!(net, net.edge[6]) # hybrid edge @test_throws Exception PhyloNetworks.shrinkedge!(net, net.edge[3]) # external edge @test hassinglechild(net.hybrid[1]) @test hassinglechild(net.node[5]) && !net.node[5].hybrid # degree-2 tree node @test !PhyloNetworks.shrinkedge!(net, net.edge[5]) @test PhyloNetworks.shrinkedge!(net, net.edge[4]) @test !hassinglechild(net.hybrid[1]) # shrink cycles net = readTopology("(((A:2.0,(B:1.0)#H1:0.1::0.9):1.5,(C:0.6,#H1:1.0::0.1):1.0):0.5,D:2.0);") @test !shrink2cycles!(net) @test !shrink3cycles!(net) PhyloNetworks.addhybridedge!(net, net.edge[7], net.edge[4], true, 0.1, 0.2) @test !shrink2cycles!(net) @test shrink3cycles!(net) # tree case @test writeTopology(net) == "(((A:2.0,(B:1.0)#H1:0.1::0.9):1.37,(C:0.6,#H1:1.0::0.1):0.9):0.6,D:2.0);" PhyloNetworks.addhybridedge!(net, net.edge[3], net.edge[6], true, 0.3, 0.4) @test shrink3cycles!(net) # hybrid case @test writeTopology(net, round=true, digits=5) == "(((A:2.0,(B:1.0)#H1:0.13191::0.94):1.37,(C:0.6,#H1:1.0::0.06):0.9):0.6,D:2.0);" net0 = readTopology("((((((a:1)#H1:1::.9)#H2:1::.8)#H3:1::.7,#H3:0.5):1,#H2:1):1,(#H1:1,b:1):1,c:1);") net = deepcopy(net0) # new 2/3 cycles appear when some are shrunk @test shrink2cycles!(net) @test writeTopology(net, round=true) == "((#H1:1.0::0.1,b:1.0):1.0,c:1.0,(a:1.0)#H1:4.48::0.9);" @test shrink3cycles!(net0) writeTopology(net0, round=true) == "(c:1.1,a:5.132,b:1.9);" # non-tree-child network: w shape net0 = readTopology("((a:1,#H1:.1::.1):1,(((b:.5)#H3:1)#H1:1,(#H3:0.8::.4)#H2:1):1,(#H2:.2::.0,c:1):1);") PhyloNetworks.deletehybridedge!(net0, net0.edge[2], false,true,false,false) net = deepcopy(net0) # delete edge 10 (with γ=0) then shrink 2-cycle PhyloNetworks.deletehybridedge!(net, net.edge[7], false,true,false,false) @test shrink3cycles!(net) @test writeTopology(net) == "(a:2.0,c:2.0,b:3.42);" # shrink 3-cycle, which deletes edge 10 (with γ=0) : same result in the end @test shrink3cycles!(net0) @test writeTopology(net) == "(a:2.0,c:2.0,b:3.42);" end end # of set of auxiliary test sets
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
4022
# updateGammaz does not recognize this as bad diamond II # Claudia April 2015 PhyloNetworks.CHECKNET || error("need CHECKNET==true in PhyloNetworks to test snaq in test_correctLik.jl") @testset "test: bad diamond, max pseudo lik" begin global tree, net, df, d tree = "(6,(5,#H7:0.0):9.970714072991349,(3,(((2,1):0.2950382234364404,4):0.036924483697671304)#H7:0.00926495670648208):1.1071489442240392);" net = readTopologyLevel1(tree); checkNet(net) #printNodes(net) #printEdges(net) @test net.node[10].number == 3 # or: wrong hybrid @test net.node[10].hybrid # or: does not know it is hybrid @test net.node[10].isBadDiamondII # or: does not know it is bad diamond II ##plot(net,showedgenumber=true) @test [e.inCycle for e in net.edge] == [-1,-1,3,3,-1,-1,-1,-1,-1,-1,3,3] # or: error in incycle @test [e.containRoot for e in net.edge] == [true,true,false,true,true,false,false,false,false,false,false,true] # or: error in contain root @test [e.istIdentifiable for e in net.edge] == [false,false,true,true,false,false,false,true,false,false,true,true] # or: istIdentifiable not correct @test (net.edge[3].hybrid && net.edge[11].hybrid) # or: hybrid edges wrong") df=DataFrame(t1=["1","1","2","2","1","2","2","2","2","2","1","2","2","3","2"], t2=["3","3","3","3","3","1","5","1","1","1","5","1","1","5","3"], t3=["5","5","5","5","6","5","6","3","6","5","6","3","3","6","6"], t4=["6","4","4","6","4","6","4","5","4","4","4","6","4","4","4"], CF1234=[0.565,0.0005,0.0005,0.565,0.00003,0.99986,0.0410167,1,0.99987,1,0.040167,0.998667,1,0.073167,0.00003], CF1324=[0.0903,0.8599,0.8599,0.0903,0.8885,0.00006,0.263,0,0.00006,0,0.2630,0.00006,0,0.0424667,0.8885]) df[!,:CF1423] = 1.0 .- df[!,:CF1234] .- df[!,:CF1324] d = readTableCF(df) Random.seed!(345); net2 = topologyMaxQPseudolik!(net,d, ftolRel=1e-5,ftolAbs=1e-6,xtolRel=1e-3,xtolAbs=1e-4) @test net2.loglik < 340.5 # loglik ~ 339.95 @test net2.edge[3].istIdentifiable # or: wrong hybrid is t identifiable # @test 9.95 < net2.edge[3].length < 9.99 # why it's not a good idea to test the branch length estimate: # BL~4.92 when loglik~339.95 # BL>9.95 when loglik>340 # BL~0.0 when loglik~339.88 (using tolerances of 1e-8) @test net2.edge[11].istIdentifiable # or: wrong hybrid is t identifiable @test net2.edge[11].length < 0.01 # or: wrong bl estimated @test net2.edge[10].length == 0.0 # or: tree edge in bad diamond II not 0 #printEdges(net2) @test_logs show(devnull, net2) @test_logs [show(devnull, net2.node[i]) for i in [1,3,10]]; @test_logs [show(devnull, net2.edge[i]) for i in [1,3,11]]; @test_logs show(devnull, d) @test_logs show(devnull, d.quartet[1]) @test_logs show(devnull, d.quartet[1].qnet) @test tipLabels(d.quartet) == ["1","2","3","4","5","6"] a = (@test_logs fittedQuartetCF(d, :wide)); @test size(a) == (15,10) a = (@test_logs fittedQuartetCF(d, :long)); @test size(a) == (45,7) end ## testing readTopology---------------------------------------------------------------- ## will remove this from the test because readTopology should not have to worry about istIdentifiable ## we move into updateGammaz ## tree = "(6,(5,#H7:0.0):9.970714072991349,(3,(((2,1):0.2950382234364404,4):0.036924483697671304)#H7:0.00926495670648208):1.1071489442240392);" ## net2 = readTopology(tree) ## printEdges(net2) ## for e in net2.edge ## if(e.node[1].leaf || e.node[2].leaf) ## !e.istIdentifiable || error("ext edge should not identifiable") ## else ## e.istIdentifiable || error("int edge should not identifiable") ## end ## end ## ## this case works fine ## tree = "((((8,10))#H1,7),6,(4,#H1));" # Case I Bad diamond I ## net = readTopologyLevel1(tree) ## checkNet(net) ## net2 = readTopology(tree) ## printEdges(net2) ## for e in net2.edge ## if(e.node[1].leaf || e.node[2].leaf) ## !e.istIdentifiable || error("ext edge should not identifiable") ## else ## e.istIdentifiable || error("int edge should not identifiable") ## end ## end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
4711
# test the functions in src/bootstrap.jl exdir = joinpath(@__DIR__,"..","examples") # exdir = joinpath(dirname(pathof(PhyloNetworks)), "..","examples") @testset "testing hybridBootstrapSupport" begin bestnet = readTopology(joinpath(exdir,"fish2hyb.net")); bootnet = readMultiTopology(joinpath(exdir,"fish3hyb_20boostrap.net")); # issues with bootstrap networks 12, 21, 42, 96 # plot(bootnet[20], showedgenumber=true) # include(string(home, "bootstrap.jl")) resn, rese, resc, gam, edgenum = hybridBootstrapSupport(bootnet,bestnet); #@show resn; @show rese; showall(gam); @show edgenum; resc # plot(bestnet, shownodenumber=true); @test resn[1:2,:clade] == ["H26","H25"] @test resn[1:2,:BS_hybrid_samesisters] == [25.0,100.0] @test resn[!,:BS_hybrid] == [100.0,100,0,0,0,75,0,0,0,0,0,0,5,5,5,5,5,0,0,0] @test resn[!,:BS_minor_sister] == [0.0,0,100,0,0,5,10,70,75,25,5,5,0,0,0,0,0,0,0,5] @test resn[!,:BS_major_sister] == [0.0,0,0,100,100,0,70,10,0,0,5,5,0,0,0,0,0,5,5,0] @test rese[2,:BS_minor] == 25.0 # BS of introgression for H26 @test rese[4,:BS_minor] == 100.0 # BS of introgression for H25 @test resc[!,:taxa]==["Xgordoni","Xmeyeri","Xcouchianus","Xvariatus","Xevelynae","Xxiphidium", "Xmilleri","Xandersi","Xmaculatus","Xhellerii","Xalvarezi","Xmayae","Xsignum","Xclemenciae_F2", "Xmonticolus","Xmontezumae","Xnezahuacoyotl","Xbirchmanni_GARC","Xmalinche_CHIC2","Xcortezi", "Xcontinens","Xpygmaeus","Xnigrensis","Xmultilineatus"] @test resc[!,:taxa][resc[!,:H26]] == ["Xnezahuacoyotl"] @test resc[!,:taxa][resc[!,:H25]] == ["Xmontezumae","Xnezahuacoyotl","Xbirchmanni_GARC","Xmalinche_CHIC2","Xcortezi","Xcontinens","Xpygmaeus","Xnigrensis","Xmultilineatus"] @test resc[!,:taxa][resc[!,:c_minus27]] == ["Xnigrensis","Xmultilineatus"] # minor sis of H26 @test resc[!,:taxa][resc[!,:Xxiphidium]] == ["Xxiphidium"] # minor sis of H25 @test resc[!,:taxa][resc[!,:Xsignum]] == ["Xsignum"] # donor8 previously @test resc[!,:taxa][resc[!,:c_minus24]] == ["Xcontinens","Xpygmaeus","Xnigrensis","Xmultilineatus"] # donor7 @test resc[!,:taxa][resc[!,:Xmontezumae]] == ["Xmontezumae"] # major sis of H26. Below: major sis of H25 @test resc[!,:taxa][resc[!,:c_minus12]] == ["Xhellerii","Xalvarezi","Xmayae","Xsignum","Xclemenciae_F2","Xmonticolus"] @test gam[:,2] == [.0,.0,.192,.0,.0,.0,.0,.0,.193,.0,.184,.193,.0,.0,.0,.0,.0,.193,.0,.0] @test gam[:,4] == [.165,.166,.165,.166,.165,.165,.166,.165,.165,.166,.164,.166,.166,.165,.165,.165,.166,.165,.166,.166] @test edgenum ==[25,39,43,7] PhyloNetworks.addAlternativeHybridizations!(bestnet, rese, cutoff=4) @test rese[[5,10,11],:edge] == [54,57,60] @test ismissing(rese[6,:edge]) @test length(bestnet.hybrid) == 5 end # of testset, hybridBootstrapSupport @testset "bootsnaq from quartet CF intervals" begin T=readTopology(joinpath(exdir,"startTree.txt")) datf=DataFrame(CSV.File(joinpath(exdir,"tableCFCI.csv")); copycols=false) originalstdout = stdout redirect_stdout(devnull) # requires julia v1.6 bootnet = bootsnaq(T,datf,nrep=2,runs=1,seed=1234,filename="",Nfail=2, ftolAbs=1e-3,ftolRel=1e-3,xtolAbs=1e-4,xtolRel=1e-3,liktolAbs=0.01) redirect_stdout(originalstdout) @test size(bootnet)==(2,) @test writeTopology(bootnet[1], round=true) != writeTopology(bootnet[2], round=true) # "(2,((5,#H9:0.0::0.298):3.927,3):1.331,(((1,6):0.019,4):0.0)#H9:0.0::0.702);" # above: bad diamond 2, and both edges above the hybrid have estimated length of 0.0... end @testset "bootsnaq from bootstrap gene trees, multiple procs" begin treefile = joinpath(exdir,"treefile.txt") # pretending these are bootstrap trees, for all genes boottrees = Vector{HybridNetwork}[] T=readTopology(joinpath(exdir,"startTree.txt")) net1 = readTopology("(5,(((2,(1)#H7:::0.7143969494428192):1.5121337017411736,4):0.4894187322508883,3):0.519160762355313,(6,#H7:::0.2856030505571808):10.0);") for i=1:13 push!(boottrees, readMultiTopology(treefile)) end for i=1:13 @test size(boottrees[i])==(10,) end # 10 bootstrap trees for each of 13 "genes" addprocs(1) @everywhere using PhyloNetworks # using Distributed; @everywhere begin; using Pkg; Pkg.activate("."); using PhyloNetworks; end originalstdout = stdout redirect_stdout(devnull) bootnet = bootsnaq(T,boottrees,nrep=2,runs=2,otherNet=net1,seed=1234, prcnet=0.5,filename="",Nfail=2,ftolAbs=1e-3,ftolRel=1e-3) redirect_stdout(originalstdout) rmprocs(workers()) @test size(bootnet)==(2,) @test all(n -> n.numHybrids==1, bootnet) @test writeTopology(bootnet[1], round=true, digits=1) != writeTopology(bootnet[2], round=true, digits=1) filelist = joinpath(exdir, "treefilelist.txt") boottrees = readBootstrapTrees(filelist) @test length(boottrees) == 2 @test [length(b) for b in boottrees] == [10, 10] end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
18297
# test of calculateExpCF function # Claudia December 2014 # Case G ----------------- #println("------ Case G ----------") include("../examples/case_g_example.jl") # include(joinpath(dirname(pathof(PhyloNetworks)), "..","examples","case_g_example.jl")) error1 = false ind = 0 q1 = Quartet(1,["6","7","4","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q1); try identifyQuartet!(qnet) qnet.which != 1 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 3 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 2 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing qnet.hybrid[1].prev.number != -7 ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 0 || qnet.numHybrids != 0 ? error("qnet should not have hybrid nodes anymore") : nothing qnet.t1 != 0.2-log(1-0.1*(1-exp(-1.1))) ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [1,1,2,2] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [2,1,2] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [1/3*exp(-qnet.t1),1-2/3*exp(-qnet.t1),1/3*exp(-qnet.t1)] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 1") global error1 |= true global ind = 1 end q2 = Quartet(2,["6","7","10","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q2); try identifyQuartet!(qnet) qnet.which != 2 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 4 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 5 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing !isa(qnet.hybrid[1].prev,Nothing) ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 1 || qnet.numHybrids != 1 ? error("qnet should have 1 hybrid nodes") : nothing qnet.t1 != -1 ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [-1,-1,-1,-1] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [-1,-1,-1] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [0.9*(1-2/3*exp(-0.1))+0.1*1/3*exp(-1.0), 0.9*(1/3*exp(-0.1))+0.1*(1-2/3*exp(-1.0)), 0.9*(1/3*exp(-0.1))+0.1*(1/3*exp(-1.0))] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 2") global error1 |= true global ind = 2 end q3 = Quartet(3,["10","7","4","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q3); try identifyQuartet!(qnet) qnet.which != 2 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 4 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 5 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing !isa(qnet.hybrid[1].prev,Nothing) ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 1 || qnet.numHybrids != 1 ? error("qnet should have 1 hybrid nodes") : nothing qnet.t1 != -1 ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [-1,-1,-1,-1] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [-1,-1,-1] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [0.9*(1/3*exp(-0.1))+0.1*1/3*exp(-1.0), 0.9*(1/3*exp(-0.1))+0.1*(1-2/3*exp(-1.0)), 0.9*(1-2/3*exp(-0.1))+0.1*(1/3*exp(-1.0))] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 3") global error1 |= true global ind = 3 end q4 = Quartet(4,["6","10","4","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q4); try identifyQuartet!(qnet) qnet.which != 1 ? error("qnet which not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 0 || qnet.numHybrids != 0 ? error("qnet should not have hybrid nodes anymore") : nothing qnet.t1 > 0.30001 || qnet.t1 < 0.2999999999 ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [1,1,2,2] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [2,1,2] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [1/3*exp(-qnet.t1),1-2/3*exp(-qnet.t1),1/3*exp(-qnet.t1)] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 4") global error1 |= true global ind = 4 end q5 = Quartet(5,["6","7","4","10"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q5); try identifyQuartet!(qnet) qnet.which != 1 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 3 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 2 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing qnet.hybrid[1].prev.number != -3 ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 0 || qnet.numHybrids != 0 ? error("qnet should not have hybrid nodes anymore") : nothing qnet.t1 != 0.2-log(1-0.1*(1-exp(-0.1))) ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [1,1,2,2] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [2,1,2] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [1/3*exp(-qnet.t1),1-2/3*exp(-qnet.t1),1/3*exp(-qnet.t1)] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 5") global error1 |= true global ind = 5 end if error1 throw("error Case G in quartet $(ind)") end # Case F Bad Diamond I ----------------- #println("------ Case F Bad diamond I ----------") include("../examples/case_f_example.jl"); # include(joinpath(dirname(pathof(PhyloNetworks)), "..","examples","case_f_example.jl")) error1 = false ind = 0 parameters!(net) q1 = Quartet(1,["6","7","4","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q1); try identifyQuartet!(qnet) qnet.which != 2 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 4 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 5 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing !isa(qnet.hybrid[1].prev,Nothing) ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 1 || qnet.numHybrids != 1 ? error("qnet should not have hybrid nodes anymore") : nothing qnet.t1 != -1 ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [-1,-1,-1,-1] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [-1,-1,-1] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [(1-(0.7*(1-exp(-0.2)))-(0.3*(1-exp(-0.1))))/3, (1+2*(0.7*(1-exp(-0.2)))-(0.3*(1-exp(-0.1))))/3,(1-(0.7*(1-exp(-0.2)))+2*(0.3*(1-exp(-0.1))))/3] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 1") global error1 |= true global ind = 1 end q2 = Quartet(2,["6","7","10","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q2); try identifyQuartet!(qnet) qnet.which != 1 ? error("qnet which not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 0 || qnet.numHybrids != 0 ? error("qnet should have 0 hybrid nodes") : nothing qnet.t1 != 0.1 ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [1,1,2,2] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [1,2,2] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [1-2/3*(exp(-0.1)),1/3*(exp(-0.1)),1/3*(exp(-0.1))] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 2") global error1 |= true global ind = 2 end q3 = Quartet(3,["10","7","4","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q3); try identifyQuartet!(qnet) qnet.which != 1 ? error("qnet which not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 0 || qnet.numHybrids != 0 ? error("qnet should have 0 hybrid nodes") : nothing qnet.t1 != 0.1-log(1-(0.3*(1-exp(-0.1)))) ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [1,1,2,2] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [2,2,1] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [1/3*exp(-qnet.t1),1/3*exp(-qnet.t1),1-2/3*exp(-qnet.t1)] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 3") global error1 |= true global ind = 3 end q4 = Quartet(4,["6","10","4","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q4); try identifyQuartet!(qnet) qnet.which != 1 ? error("qnet which not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 0 || qnet.numHybrids != 0 ? error("qnet should have 0 hybrid nodes") : nothing qnet.t1 != 0.1-log(1-(0.7*(1-exp(-0.2)))) ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [1,1,2,2] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [2,1,2] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [1/3*exp(-qnet.t1),1-2/3*exp(-qnet.t1),1/3*exp(-qnet.t1)] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 4") global error1 |= true global ind = 4 end q5 = Quartet(5,["6","7","4","10"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q5); try identifyQuartet!(qnet) qnet.which != 2 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 4 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 5 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing !isa(qnet.hybrid[1].prev,Nothing) ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 1 || qnet.numHybrids != 1 ? error("qnet should not have hybrid nodes anymore") : nothing qnet.t1 != -1 ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [-1,-1,-1,-1] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [-1,-1,-1] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [(1-0.7*(1-exp(-0.2))-0.3*(1-exp(-0.1)))/3,(1+2*0.7*(1-exp(-0.2))-0.3*(1-exp(-0.1)))/3,(1-0.7*(1-exp(-0.2))+2*0.3*(1-exp(-0.1)))/3] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 5") global error1 |= true global ind = 5 end if error1 throw("error Case F in quartet $(ind)") end # Case I Bad Diamond II ----------------- #println("------ Case I Bad diamond II ----------") include("../examples/case_i_example.jl"); # include(joinpath(dirname(pathof(PhyloNetworks)), "..","examples","case_i_example.jl")) error1 = false ind = 0 q1 = Quartet(1,["6","7","4","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q1); try identifyQuartet!(qnet) qnet.which != 2 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 4 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 5 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing !isa(qnet.hybrid[1].prev,Nothing) ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 1 || qnet.numHybrids != 1 ? error("qnet should not have hybrid nodes anymore") : nothing qnet.t1 != -1 ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [-1,-1,-1,-1] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [-1,-1,-1] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [0.9*(1/3*exp(-1))+0.1*(1-2/3*exp(-1)),0.9*(1-2/3*exp(-1))+0.1*1/3*exp(-1),0.9*(1/3*exp(-1))+0.1*(1/3*exp(-1))] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 1") global error1 |= true global ind = 1 end q2 = Quartet(2,["6","7","10","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q2); try identifyQuartet!(qnet) qnet.which != 1 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 3 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 4 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing (qnet.hybrid[1].prev.number != -2 && qnet.hybrid[1].prev.number != -3) ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 0 || qnet.numHybrids != 0 ? error("qnet should have 0 hybrid nodes") : nothing !approxEq(qnet.t1,-log(1+0.1*(1-exp(-1))-0.1*0.1*(1-exp(-1-1))-0.1*0.1*(1-exp(-1))-0.9*0.9*(1-exp(-2.)))) ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [1,1,2,2] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [1,2,2] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [1-2/3*(exp(-qnet.t1)),1/3*(exp(-qnet.t1)),1/3*(exp(-qnet.t1))] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 2") global error1 |= true global ind = 2 end q3 = Quartet(3,["10","7","4","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q3); try identifyQuartet!(qnet) qnet.which != 1 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 3 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 4 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing (qnet.hybrid[1].prev.number != -6 && qnet.hybrid[1].prev.number != -3) ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 0 || qnet.numHybrids != 0 ? error("qnet should have 0 hybrid nodes") : nothing !approxEq(qnet.t1,-log(1+0.1*(1-exp(-2))-0.1*0.1*(1-exp(-1))-0.1*0.1*(1-exp(-2))-0.9*0.9*(1-exp(-2.)))) ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [1,1,2,2] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [2,2,1] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [1/3*exp(-qnet.t1),1/3*exp(-qnet.t1),1-2/3*exp(-qnet.t1)] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 3") global error1 |= true global ind = 3 end q4 = Quartet(4,["6","10","4","8"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q4); try identifyQuartet!(qnet) qnet.which != 1 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 3 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 4 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing (qnet.hybrid[1].prev.number != -6 && qnet.hybrid[1].prev.number != -3) ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 0 || qnet.numHybrids != 0 ? error("qnet should have 0 hybrid nodes") : nothing !approxEq(qnet.t1,-log(1+0.1*(1-exp(-1))-0.1*0.1*(1-exp(-1))-0.1*0.1*(1-exp(-1))-0.9*0.9*(1-exp(-3)))) ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [1,1,2,2] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [2,1,2] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [1/3*exp(-qnet.t1),1-2/3*exp(-qnet.t1),1/3*exp(-qnet.t1)] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 4") global error1 |= true global ind = 4 end q5 = Quartet(5,["6","7","4","10"],[0.5,0.4,0.1]); qnet = extractQuartet!(net,q5); try identifyQuartet!(qnet) qnet.which != 2 ? error("qnet which not correctly assigned") : nothing qnet.hybrid[1].k != 4 ? error("qnet.hybrid[1].k not correctly assigned") : nothing qnet.hybrid[1].typeHyb != 5 ? error("qnet.hybrid[1].typeHyb not correctly assigned") : nothing !isa(qnet.hybrid[1].prev,Nothing) ? error("qnet.hybrid[1].prev not correctly assigned") : nothing eliminateHybridization!(qnet) size(qnet.hybrid,1) != 1 || qnet.numHybrids != 1 ? error("qnet should not have hybrid nodes anymore") : nothing qnet.t1 != -1 ? error("internal edge length not correctly updated") : nothing updateSplit!(qnet) qnet.split != [-1,-1,-1,-1] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [-1,-1,-1] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF != [0.9*(1/3*exp(-1))+0.1*(1-2/3*exp(-1)),0.9*(1-2/3*exp(-1))+0.1*1/3*exp(-1),0.9*(1/3*exp(-1))+0.1*(1/3*exp(-1))] ? error("qnet.expCF wrongly calculated") : nothing catch println("errors in quartet 5") global error1 |= true global ind = 5 end if error1 throw("error Case I in quartet $(ind)") end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
1275
# test function from a debugging case in simScript.jl # in julia/debug/bigSimulation/n6/julia # seed 4545 # Claudia August 2015 # to debug problem tree="(3,(2,(((6,(5)#H9:0.91507):0.93066,(4,#H9:0.0):0.73688):0.0)#H7:1.79104::0.99498):0.11675,(1,#H7:0.04487::0.00502):0.4897);" net0=readTopologyLevel1(tree); #printEdges(net0) net0.node[6].gammaz =1.0 #-5 net0.node[8].gammaz =0.067 #-7 q1 = Quartet(1,["6","5","4","1"],[0.5,0.4,0.1]); qnet = extractQuartet!(net0,q1); #printEdges(qnet) identifyQuartet!(qnet) qnet.which != 2 ? error("qnet which not correctly assigned") : nothing #printEdges(qnet) eliminateHybridization!(qnet) qnet.which != 2 ? error("qnet which not correctly assigned") : nothing qnet.numHybrids == 1 || error("qnet not correctly eliminated hyb") qnet.hybrid[1].k == 4 || error("qnet not correclty identified") qnet.hybrid[1].typeHyb == 5 || error("qnet not correclty identified") qnet.hybrid[1].isBadDiamondI || error("qnet forgot it is a bad diamondI") updateSplit!(qnet) qnet.split != [-1,-1,-1,-1] ? error("qnet.split not correctly assigned") : nothing updateFormula!(qnet) qnet.formula != [-1,-1,-1] ? error("qnet.formula not correctly assigned") : nothing calculateExpCF!(qnet) qnet.expCF[2] < 0. || error("expCF not correctly calculated")
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
5638
@testset "calibrate with distances: 3-cycle, non-identifiable example" begin net2 = readTopology("((((D:0.1,C:0.2):1.5,(B:0.1)#H1:0.9::0.7):0.1,(#H1:0.01::0.3,A:0.3):0.8):0.1);") dAll = pairwiseTaxonDistanceMatrix(net2, keepInternal=true) @test dAll ≈ [0.0 .8 1.1 .1 .943 1.043 1.6 1.8 1.7 0.8 0.0 0.3 0.9 1.263 1.363 2.4 2.6 2.5 1.1 0.3 0.0 1.2 1.563 1.663 2.7 2.9 2.8 0.1 0.9 1.2 0.0 0.903 1.003 1.5 1.7 1.6 0.943 1.263 1.563 0.903 0.0 0.1 2.403 2.603 2.503 1.043 1.363 1.663 1.003 0.1 0.0 2.503 2.703 2.603 1.6 2.4 2.7 1.5 2.403 2.503 0.0 0.2 0.1 1.8 2.6 2.9 1.7 2.603 2.703 0.2 0.0 0.3 1.7 2.5 2.8 1.6 2.503 2.603 0.1 0.3 0.0] taxa = [l.name for l in net2.leaf] net2distances = pairwiseTaxonDistanceMatrix(net2) @test net2distances ≈ [.0 .3 2.603 2.8 0.3 0.0 2.703 2.9 2.603 2.703 0.0 1.663 2.8 2.9 1.663 0.0] g = PhyloNetworks.pairwiseTaxonDistanceGrad(net2); @test size(g) == (9,9,9) na = getNodeAges(net2); @test na ≈ [1.7,0.11,0.0,1.6,0.1,0.0,0.1,0.0,0.0] g = PhyloNetworks.pairwiseTaxonDistanceGrad(net2, nodeAges=na); @test size(g) == (9,9,9) @test g[:,:,1] ≈ [0 1 1 1 1 1 1 1 1;1 0 0 2 1.4 1.4 2 2 2; 1 0 0 2 1.4 1.4 2 2 2 1 2 2 0 .6 .6 0 0 0; 1 1.4 1.4 .6 0 0 .6 .6 .6; 1 1.4 1.4 .6 0 0 .6 .6 .6 1 2 2 0 .6 .6 0 0 0; 1 2 2 0 .6 .6 0 0 0; 1 2 2 0 .6 .6 0 0 0] global net net = readTopology("((#H1:0.06::0.3,A:0.6):1.3,(B:0.1)#H1:0.7::0.7,(C,D):1.4);"); # same topology, unrooted, different BL, leaves ordered differently # here: branch lengths not identifiable, even if minor fixed to 0 calibrateFromPairwiseDistances!(net, net2distances, taxa, #verbose=true, forceMinorLength0=true, ultrametric=false) est = pairwiseTaxonDistanceMatrix(net, checkPreorder=false) @test est ≈ [0 1.663 2.9 2.8; 1.663 0 2.703 2.603; 2.9 2.703 0 .3; 2.8 2.603 .3 0] atol=.00002 # deep LN_BOBYQA: 146 evaluations # got 0.0 at [0.00536, 1.32091, 0.14155, 0.84494, 0.2, 0.1, 1.37373] after 152 iterations (returned FTOL_REACHED) # shallow LN_BOBYQA: 79 evaluations # deep LD_MMA: 47 evaluations # got 0.0 at [0.20465, 1.03622, 0.19367, 0.77048, 0.2, 0.1, 1.45914] after 47 iterations (returned FTOL_REACHED) # second call, starting from solution: # got 0.0 at [0.00536, 1.32092, 0.14155, 0.84493, 0.2, 0.1, 1.37373] after 29 iterations (returned FTOL_REACHED) net = readTopology("((#H1:0.06::0.3,A:0.6):1.3,(B:0.1)#H1:0.7::0.7,(C,D):1.4);"); calibrateFromPairwiseDistances!(net, net2distances, taxa, verbose=false, forceMinorLength0=false, ultrametric=false) est = pairwiseTaxonDistanceMatrix(net) @test est ≈ [0 1.663 2.9 2.8; 1.663 0 2.703 2.603; 2.9 2.703 0 .3; 2.8 2.603 .3 0] atol=.00002 end @testset "calibrate with distances: 5-cycle example (when unrooted)" begin # most lengths identifiable when we force # minor hybrid to length 0 and ultrametric network # not identifiable otherwise global net net = readTopology("((Ag:3.0,(#H1:0.0::0.2,Ak:2.5):0.5):0.5,(((((Az:0.2,Ag2:0.2):1.3,As:1.5):1.0)#H1:0.3::0.8,Ap:2.8):0.2,Ar:3.0):0.5);"); taxa = [l.name for l in net.leaf]; netdist = pairwiseTaxonDistanceMatrix(net); @test getNodeAges(net) ≈ [3.5,3,0,2.8,0,3,2.5,0,2.5,1.5,0,.2,0,0,0] net = readTopology("((((((Ag2,Az),As))#H1:::0.8,Ap),Ar),(Ag,(#H1:::0.2,Ak)));"); # same topology, no BL, leaves ordered differently o = [4,3,5,6,7,1,2]; # to get leaves in same order as in taxa. inverse: [6,7,2,1,3,4,5] calibrateFromPairwiseDistances!(net, netdist, taxa, forceMinorLength0=true, ultrametric=false) # got 0.0 at [0.19998, 0.19998, 1.30003, 1.5, 0.6802, 0.69964, 2.79995, 0.20002, 2.99995, 0.50006, 2.9999, 2.49952, 0.50049, 0.50006] after 1000 iterations (returned MAXEVAL_REACHED) est = pairwiseTaxonDistanceMatrix(net, checkPreorder=false) @test est ≈ netdist[o,o] atol=.0005 # most edge lengths are correct, except for 5 edges: # - the 2 edges at the root: expected (the network should be unrooted) # when the optimization uses LN_BOBYQA # - the 3 edges connecting to the hybrid node: lack of identifiability? net = readTopology("((((((Ag2,Az),As))#H1:::0.8,Ap),Ar),(Ag,(#H1:::0.2,Ak)));"); # same topology, no BL, leaf ordered differently for e in net.edge e.length=1.0; end preorder!(net) na = getNodeAges(net); @test na ≈ [6.,1,4,0,0,5,0,4,0,3,2,0,1,0,0] pairwiseTaxonDistanceMatrix(net, nodeAges=na); # update edge lengths in net @test [e.length for e in net.edge] ≈ [1.,1,1,2,1,1,4,1,5,1,1,1,4,-3,5] g = PhyloNetworks.pairwiseTaxonDistanceGrad(net, nodeAges=na); net.edge[11].length = 4.; # to respect constraints net.edge[14].length = 0.; net.edge[15].length = 2.; net1 = deepcopy(net); fmin, na = calibrateFromPairwiseDistances!(net1, netdist, taxa, #verbose=true, forceMinorLength0=false, ultrametric=true) # got 0.0 at [3.5, 3.0, 2.50001, 3.0, 2.8, 1.95797, 1.5, 0.2] after 58 iterations (returned FTOL_REACHED) est = pairwiseTaxonDistanceMatrix(net1) @test est ≈ netdist[o,o] atol=.0005 # still not identifiable: all good but the 3 edges adjacent to hybrid node # only the age of the hybrid node is wrong: zipped down nearer tips calibrateFromPairwiseDistances!(net, netdist, taxa, #verbose=true, forceMinorLength0=true, ultrametric=true, NLoptMethod=:LN_COBYLA) est = pairwiseTaxonDistanceMatrix(net) @test est ≈ netdist[o,o] atol=.06 # hard problem? reached max # iterations calibrateFromPairwiseDistances!(net, netdist, taxa, #verbose=true, forceMinorLength0=true, ultrametric=true) est = pairwiseTaxonDistanceMatrix(net) @test est ≈ netdist[o,o] atol=.06 est = [e.length for e in net.edge] el = [.2,.2,1.3,1.5,1,.3,2.8,.2,3,.5,3,0,2.5,.5,.5] @test est ≈ el atol=0.06 end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
24798
# test of deletehybridedge!, functions to extract displayed trees/subnetworks, # used to compare networks with the hardwired cluster distance. # Cecile March 2016 if !(@isdefined doalltests) doalltests = false; end @testset "test sets: compareNetworks" begin global net, tree #----------------------------------------------------------# # testing functions to delete edges and nodes # #----------------------------------------------------------# @testset "testing deletehybridedge!" begin # with nofuse=true netstr = "(((A:4.0,(B:1.0)#H1:1.1::0.9):0.5,(C:0.6,#H1:1.0::0.1):1.0):3.0,D:5.0);" net = readTopology(netstr) @test_logs PhyloNetworks.deletehybridedge!(net, net.edge[6], true); @test writeTopology(net) == "(((A:4.0,(B:1.0)H1:1.1):0.5,(C:0.6):1.0):3.0,D:5.0);" @test net.edge[3].gamma == 0.9 @test net.node[3].name == "H1" net = readTopology(netstr) @test_logs PhyloNetworks.deletehybridedge!(net, net.edge[3], true); @test writeTopology(net) == "(((A:4.0):0.5,(C:0.6,(B:1.0)H1:1.0):1.0):3.0,D:5.0);" @test net.edge[5].gamma == 0.1 @test !net.edge[5].hybrid @test net.edge[5].isMajor @test net.node[3].name == "H1" @test !net.node[3].hybrid # example of network with one hybrid edge connected to the root # 3 edges below the root (1 of them hybrid): netstr = "((Adif:1.0,(Aech:0.122,#H6:10.0::0.047):10.0):1.614,Aten:1.0,((Asub:1.0,Agem:1.0):0.0)#H6:5.062::0.953);"; net = readTopology(netstr); @test_logs PhyloNetworks.deletehybridedge!(net, net.edge[10]); # will be rooted @test writeTopology(net) == "((Adif:1.0,(Aech:0.122,(Asub:1.0,Agem:1.0):10.0):10.0):1.614,Aten:1.0);" net = readTopology(netstr); @test_logs PhyloNetworks.deletehybridedge!(net, net.edge[10], false, true); # unrooted @test writeTopology(net) == "(Adif:1.0,(Aech:0.122,(Asub:1.0,Agem:1.0):10.0):10.0,Aten:2.614);" net = readTopology(netstr); @test_logs PhyloNetworks.deletehybridedge!(net, net.edge[3]); @test writeTopology(net) == "((Adif:1.0,Aech:10.122):1.614,Aten:1.0,(Asub:1.0,Agem:1.0):5.062);" # 2 edges below the root (1 of them hybrid): netstr = "((Adif:1.0,(Aech:0.122,#H6:10.0::0.047):10.0):1.614,((Asub:1.0,Agem:1.0):0.0)#H6:5.062::0.953);"; net = readTopology(netstr); @test_logs PhyloNetworks.deletehybridedge!(net, net.edge[9]); @test writeTopology(net) == "(Adif:1.0,(Aech:0.122,(Asub:1.0,Agem:1.0):10.0):10.0);" net = readTopology(netstr); @test_logs PhyloNetworks.deletehybridedge!(net, net.edge[9], true); @test writeTopology(net) == "(Adif:1.0,(Aech:0.122,((Asub:1.0,Agem:1.0):0.0)H6:10.0):10.0);" net = readTopology(netstr); @test_logs PhyloNetworks.deletehybridedge!(net, net.edge[9], true, false, false, true, true); # last: keeporiginalroot=true to keep the root of degree 1 @test writeTopology(net) == "((Adif:1.0,(Aech:0.122,((Asub:1.0,Agem:1.0):0.0)H6:10.0):10.0):1.614);" if doalltests net=readTopology("(4,((1,(2)#H7:::0.864):2.069,(6,5):3.423):0.265,(3,#H7:::0.1361111):10.0);"); deletehybridedge!(net, net.edge[11]); writeTopologyLevel1(net) == "(4,((1,2):2.069,(6,5):3.423):0.265,3);" || error("deletehybridedge! didn't work on 11th edge") net=readTopology("(4,((1,(2)#H7:::0.864):2.069,(6,5):3.423):0.265,(3,#H7:::0.1361111):10.0);"); deletehybridedge!(net, net.edge[4]); writeTopologyLevel1(net) == "(4,((6,5):3.423,1):0.265,(3,2):10.0);" || error("deletehybridedge! didn't work on 4th edge") end # example with wrong attributed inChild1 net=readTopology("(4,((1,(2)#H7:::0.864):2.069,(6,5):3.423):0.265,(3,#H7:::0.1361111):10.0);"); net.edge[5].isChild1 = false; @test_logs deletehybridedge!(net, net.edge[4]); @test writeTopologyLevel1(net) == "(4,((6,5):3.423,1):0.265,(3,2):10.0);" # or: deletehybridedge! didn't work on 4th edge when isChild1 was outdated if doalltests net = readTopology("((Adif:1.0,(Aech:0.122,#H6:10.0::0.047):10.0):1.614,Aten:1.0,((Asub:1.0,Agem:1.0):0.0)#H6:5.062::0.953);"); net.edge[5].isChild1 = false # edge 5 from -1 to -2 deletehybridedge!(net, net.edge[10]); println("a warning is expected: \"node -1 being the root is contradicted by isChild1 of its edges.\"") writeTopologyLevel1(net) == "(Adif:1.0,(Aech:0.122,(Asub:1.0,Agem:1.0):10.0):10.0,Aten:2.614);" || error("deletehybridedge! didn't work on 10th edge after isChild1 was changed") end # example with simplify=false net0 = readTopology("((((((a:1)#H1:1::.9)#H2:1::.8)#H3:1::.7,#H3:0.5):1,#H2:1):1,(#H1:1,b:1):1,c:1);") net = deepcopy(net0) @test writeTopology(deletehybridedge!(net, net.edge[5]), round=true) == "((#H1:1.0::0.1,b:1.0):1.0,c:1.0,(a:1.0)#H1:3.0::0.9);" @test writeTopology(deletehybridedge!(net0, net0.edge[5],false,true,false,false), round=true) == "((#H2:1.0::0.2,((a:1.0)#H1:1.0::0.9)#H2:3.0::0.8):1.0,(#H1:1.0::0.1,b:1.0):1.0,c:1.0);" # level-2 degree-2 blob simplifying to parallel edges, + polytomy below net0 = readTopology("(africa_east:0.003,((#H3:0::0.003,(non_africa_west:0.2,non_africa_east:0.2)#H1:0.3::1):0.3,(#H1:0::0)#H3:0::0.997)H2:0);"); PhyloNetworks.deletehybridedge!(net0, net0.edge[2], false, false, false, true, false) @test all(!n.hybrid for n in net0.node) @test all(e.containRoot for e in net0.edge) @test writeTopology(net0) == "(africa_east:0.003,(non_africa_west:0.2,non_africa_east:0.2)H1:0.0);" end # of testing deletehybridedge! @testset "testing deleteleaf! and hardwiredClusterDistance" begin cui2str = "(Xgordoni,Xmeyeri,(Xcouchianus,(Xvariatus,(Xevelynae,((Xxiphidium,#H25:9.992::0.167):1.383,(Xmilleri,(Xandersi,(Xmaculatus,((((Xhellerii,(Xalvarezi,Xmayae):0.327):0.259,Xsignum):1.866,(Xclemenciae_F2,Xmonticolus):1.461):0.786,((((Xmontezumae,(Xnezahuacoyotl)#H26:0.247::0.807):0.372,((Xbirchmanni_GARC,Xmalinche_CHIC2):1.003,Xcortezi):0.454):0.63,((Xcontinens,Xpygmaeus):1.927,((Xnigrensis,Xmultilineatus):1.304,#H26:0.0::0.193):0.059):2.492):2.034)#H25:0.707::0.833):1.029):0.654):0.469):0.295):0.41):0.646):3.509):0.263);" cui3str = "(Xmayae,((Xhellerii,(((Xclemenciae_F2,Xmonticolus):1.458,(((((Xmontezumae,(Xnezahuacoyotl)#H26:0.247::0.804):0.375,((Xbirchmanni_GARC,Xmalinche_CHIC2):0.997,Xcortezi):0.455):0.63,(#H26:0.0::0.196,((Xcontinens,Xpygmaeus):1.932,(Xnigrensis,Xmultilineatus):1.401):0.042):2.439):2.0)#H7:0.787::0.835,(Xmaculatus,(Xandersi,(Xmilleri,((Xxiphidium,#H7:9.563::0.165):1.409,(Xevelynae,(Xvariatus,(Xcouchianus,(Xgordoni,Xmeyeri):0.263):3.532):0.642):0.411):0.295):0.468):0.654):1.022):0.788):1.917)#H27:0.149::0.572):0.668,Xalvarezi):0.257,(Xsignum,#H27:1.381::0.428):4.669);" if doalltests net3 = readTopology(cui3str); net2 = readTopology(cui2str); # major tree, root with outgroup then delete 2 leaves: tree2 = majorTree(net2); tree3 = majorTree(net3); rootatnode!(tree2,"Xmayae"); rootatnode!(tree3,"Xmayae"); deleteleaf!(tree2,"Xhellerii"); deleteleaf!(tree3,"Xhellerii"); deleteleaf!(tree2,"Xsignum"); deleteleaf!(tree3,"Xsignum"); hardwiredClusterDistance(tree2, tree3, false) == 0 || error("HWDist not 0, major tree, root then prune"); # major tree, delete 2 leaves then root with outgroup: tree2 = majorTree(net2); tree3 = majorTree(net3); deleteleaf!(tree2,"Xhellerii"); deleteleaf!(tree3,"Xhellerii"); deleteleaf!(tree2,"Xsignum"); deleteleaf!(tree3,"Xsignum"); hardwiredClusterDistance(tree2, tree3, false) == 0 || error("HWD not 0, major tree - 2 taxa"); @test hardwiredClusterDistance(tree2, tree3, true) == 21 rootatnode!(tree3,"Xmaculatus"); hardwiredClusterDistance(tree2, tree3, true) == 15 || error("rooted RF dist not 15"); rootatnode!(tree2,"Xgordoni"); hardwiredClusterDistance(tree2, tree3, true) == 16 || error("rooted RF dist not 16"); hardwiredClusterDistance(tree2, tree3, false) == 0 || error("HWD not 0, major tree - 2 taxa"); end # network: delete 2 leaves net2 = readTopology(cui2str); @test_logs deleteleaf!(net2,"Xhellerii"); @test_logs deleteleaf!(net2,"Xsignum"); @test_logs rootatnode!(net2,"Xmayae"); net3 = readTopology(cui3str); @test_logs deleteleaf!(net3,"Xhellerii"); @test_logs deleteleaf!(net3,"Xsignum"); @test hardwiredClusterDistance(net2, net3, true) == 3 @test_logs rootatnode!(net3,"Xmayae"); @test hardwiredClusterDistance(net2, net3, true) == 4 @test hardwiredClusterDistance(net2, net3, false) == 4 @test_logs deleteleaf!(net3,"Xmayae"; unroot=true); #plot(net3); @test net3.numHybrids == 2 # using simplify=false in deleteleaf! net3 = readTopology(cui3str); deleteleaf!(net3,"Xhellerii"); deleteleaf!(net3,"Xsignum"); deleteleaf!(net3,"Xmayae", simplify=false); @test net3.numHybrids==3 @test net3.numNodes == 47 net3 = readTopology(cui3str); deleteleaf!(net3,"Xhellerii"); deleteleaf!(net3,"Xsignum"); deleteleaf!(net3,"Xmayae", simplify=false, unroot=true); @test net3.numHybrids==3 @test net3.numNodes == 46 end # of testset for deleteleaf! and hardwiredClusterDistance #----------------------------------------------------------# # testing functions to display trees / subnetworks # #----------------------------------------------------------# @testset "testing deleteHybridThreshold!" begin if doalltests net21 = readTopology("(A,((B,#H1:::0.5),(C,(D)#H1)));"); deleteHybridThreshold!(net21,0.2); writeTopology(net21) == "(A,((B,#H1:::0.5),(C,(D)#H1:::0.5)));" || error("deleteHybridThreshold! didn't work on net21, gamma=0.2") deleteHybridThreshold!(net21,0.5); writeTopologyLevel1(net21) == "(A,((C,D),B));" || error("deleteHybridThreshold! didn't work on net21, gamma=0.5") net22 = readTopology("(A,((B,#H1:::0.2),(C,(D)#H1:::0.8)));"); deleteHybridThreshold!(net22,0.3); writeTopologyLevel1(net22) == "(A,((C,D),B));" || error("deleteHybridThreshold! didn't work on net22, gamma=0.3") net31 = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(C:0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); net32 = deepcopy(net31); for e in net32.edge e.length=-1.0; end # plot(net31) deleteHybridThreshold!(net31,0.3); writeTopologyLevel1(net31) == "(A:1.0,((C:0.9,D:1.1):1.3,B:2.3):0.7);" || error("deleteHybridThreshold! didn't work on net31, gamma=0.3") deleteHybridThreshold!(net32,0.3) writeTopologyLevel1(net32) == "(A,((C,D),B));" || error("deleteHybridThreshold! didn't work on net32, gamma=0.3") net42 = readTopology("(A:1.0,((B:1.1,#H1:0.2):1.2,(C:0.9,(D:0.8)#H1:0.3):1.3):0.7):0.1;"); deleteHybridThreshold!(net42,0.5); writeTopologyLevel1(net42) == "(A:1.0,((C:0.9,D:1.1):1.3,B:2.3):0.7);" || error("deleteHybridThreshold! didn't work on net42, gamma=0.5") end net5 = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); # plot(net5) @test_logs deleteHybridThreshold!(net5,0.5); # both H1 and H2 eliminated @test writeTopologyLevel1(net5) == "(A:1.0,((((C:0.52,E:0.52):0.6,F:1.5):0.9,D:1.1):1.3,B:2.3):0.7);" # or: deleteHybridThreshold! didn't work on net5, gamma=0.5 net5 = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); @test_logs deleteHybridThreshold!(net5,0.3); # H2 remains @test writeTopologyLevel1(net5) == "(A:1.0,((((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,D:1.1):1.3,B:2.3):0.7);" # or: deleteHybridThreshold! didn't work on net5, gamma=0.3 end # of testset, deleteHybridThreshold! @testset "testing displayedNetworks! and displayedTrees" begin net3 = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(C:0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); net31 = displayedNetworks!(net3, net3.node[6]); #H1 = 6th node @test writeTopologyLevel1(net31) == "(A:1.0,((B:1.1,D:1.0):1.2,C:2.2):0.7);" # or: displayedNetworks! didn't work on net3, minor at 6th node @test writeTopologyLevel1(net3) == "(A:1.0,((C:0.9,D:1.1):1.3,B:2.3):0.7);" # or: displayedNetworks! didn't work on net3, major at 6th node if doalltests net3 = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(C:0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); a = displayedTrees(net3, 0.2); length(a) == 2 || error("displayedTrees didn't work on net3, gamma=0.2: output not of length 2") writeTopologyLevel1(a[1]) == "(A:1.0,((C:0.9,D:1.1):1.3,B:2.3):0.7);" || error("displayedTrees didn't work on net3, gamma=0.2: 1st tree wrong") writeTopologyLevel1(a[2]) == "(A:1.0,((B:1.1,D:1.0):1.2,C:2.2):0.7);" || error("displayedTrees didn't work on net3, gamma=0.2: 2nd tree wrong") end net5 = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); a = displayedTrees(net5, 0.5); @test length(a) == 1 # or: displayedTrees didn't work on net5, gamma=0.5 @test writeTopologyLevel1(a[1]) == "(A:1.0,((((C:0.52,E:0.52):0.6,F:1.5):0.9,D:1.1):1.3,B:2.3):0.7);" # or: displayedTrees didn't work on net5, gamma=0.5 a = displayedTrees(net5, 0.1); @test length(a) == 4 # or: displayedTrees didn't work on net5, gamma=0.1 @test writeTopologyLevel1(a[1]) == "(A:1.0,((((C:0.52,E:0.52):0.6,F:1.5):0.9,D:1.1):1.3,B:2.3):0.7);" @test writeTopologyLevel1(a[2]) == "(A:1.0,((B:1.1,D:1.0):1.2,((C:0.52,E:0.52):0.6,F:1.5):2.2):0.7);" @test writeTopologyLevel1(a[3]) == "(A:1.0,((((F:0.7,E:0.51):0.8,C:1.12):0.9,D:1.1):1.3,B:2.3):0.7);" @test writeTopologyLevel1(a[4]) == "(A:1.0,((B:1.1,D:1.0):1.2,((F:0.7,E:0.51):0.8,C:1.12):2.2):0.7);" net = readTopology("(((A:4.0,(B:1.0)#H1:1.1::0.9):0.5,(C:0.6,#H1:1.0::0.1):1.0):3.0,D:5.0);") trees = (@test_logs displayedTrees(net,0.0; nofuse=true)); @test writeTopology(trees[1])=="(((A:4.0,(B:1.0)H1:1.1):0.5,(C:0.6):1.0):3.0,D:5.0);" @test writeTopology(trees[2])=="(((A:4.0):0.5,(C:0.6,(B:1.0)H1:1.0):1.0):3.0,D:5.0);" @test PhyloNetworks.inheritanceWeight.(trees) ≈ [log(0.9), log(0.1)] end # of testset, displayedNetworks! & displayedTrees @testset "testing majorTree and displayedNetworkAt!" begin net5 = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); @test writeTopology(majorTree(net5)) == "(A:1.0,((((C:0.52,E:0.52):0.6,F:1.5):0.9,D:1.1):1.3,B:2.3):0.7);" @test_logs displayedNetworkAt!(net5, net5.hybrid[1]); @test writeTopology(net5) == "(A:1.0,((((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,D:1.1):1.3,B:2.3):0.7);" net = readTopology("((((B)#H1)#H2,((D,C,#H2)S1,(#H1,A)S2)S3)S4);") # missing γ's, level 2 @test writeTopology(majorTree(net)) == "(((D,C)S1,A)S3,B)S4;" @test writeTopology(majorTree(net; nofuse=true)) == "(((B)H1)H2,((D,C)S1,(A)S2)S3)S4;" setGamma!(net.edge[8], 0.8) @test writeTopology(majorTree(net)) == "((D,C)S1,(A,B)S2)S3;" @test writeTopology(majorTree(net; nofuse=true)) == "((D,C)S1,((B)H1,A)S2)S3;" @test writeTopology(majorTree(net; nofuse=true, keeporiginalroot=true)) == "(((D,C)S1,((B)H1,A)S2)S3)S4;" @test writeTopology(majorTree(net; keeporiginalroot=true)) == "(((D,C)S1,(A,B)S2)S3)S4;" # net6 below: hybrid ladder H2 -> H1; and H2 child of root # using multgammas=true, to test multiplygammas and how it is used net6 = readTopology("(#H2:::0.2,((C,((B)#H1:::0.6)#H2:::0.8),(#H1,(A1,A2))),O);") tre6 = displayedTrees(net6, 0.5; nofuse=false, multgammas=true)[1] @test tre6.edge[2].gamma ≈ 0.48 displayedNetworkAt!(net6, net6.node[4], false, false, true) # nofuse, unroot=false, multgammas=true @test net6.edge[3].gamma ≈ 0.6 net6 = readTopology("(#H2:::0.2,((C,((B)#H1:::0.6)#H2:::0.8),(#H1,(A1,A2))),O);") displayedNetworkAt!(net6, net6.node[3], false, false, true) # nofuse, unroot=false, multgammas=true @test net6.edge[5].gamma ≈ 0.4 @test net6.edge[3].gamma ≈ 0.48 end # of testset, majorTree & displayedNetworkAt! #----------------------------------------------------------# # testing functions to compare trees # #----------------------------------------------------------# @testset "testing tree2Matrix" begin if doalltests net5 = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); tree = displayedTrees(net5, 0.0); taxa = tipLabels(net5); M1 = tree2Matrix(tree[1], taxa, rooted=false); M2 = tree2Matrix(tree[2], taxa, rooted=false); M1 == [15 0 0 1 1 1 1; 12 0 0 1 1 1 0; 8 0 0 1 1 0 0] || error("bad M1, from net5") M2 == [ 4 0 1 0 0 0 1; 12 0 0 1 1 1 0; 8 0 0 1 1 0 0] || error("bad M2, from net5") hardwiredClusterDistance(tree[1], tree[2], true) == 2 || error("wrong dist between rooted trees 1 and 2"); hardwiredClusterDistance(tree[1], tree[2], false)== 2 || error("wrong dist between unrooted trees 1 and 2"); hardwiredClusters(net5, taxa) == [16 0 1 1 1 1 1 10; 4 0 1 0 0 0 1 10; 3 0 0 0 0 0 1 11; 15 0 0 1 1 1 1 10; 12 0 0 1 1 1 0 10; 8 0 0 1 1 0 0 10; 7 0 0 0 1 0 0 11; 11 0 0 0 1 1 0 10] || error("wrong matrix of hardwired clusters for net5"); hardwiredClusterDistance(net5, tree[2], true) == 4 || error("wrong dist between net5 and tree 2"); end ## check things with R # library(ape); set.seed(15); phy <- rmtree(10,8); write.tree(phy,"tenRtrees.tre") # library(phangorn); RF.dist(phy,rooted=F) # 1 2 3 4 5 6 7 8 9 # 2 8 # 3 10 10 # 4 10 10 10 # 5 10 8 8 10 # 6 10 10 8 10 8 # 7 10 10 10 10 10 10 # 8 10 8 8 10 10 8 10 # 9 10 10 8 8 10 10 10 10 # 10 8 6 10 8 8 10 10 10 8 # i=10; j=1; RF.dist(phy[[i]],phy[[j]],rooted=T) # 10 # i=10; j=2; RF.dist(phy[[i]],phy[[j]],rooted=T) # 8 ## now checking if we get the same results in julia # phy = readInputTrees("tenRtrees.tre") # or phy1 = readTopology("((t8:0.8623136566,(((t6:0.141187073,t2:0.7767125128):0.9646669542,t4:0.8037273993):0.447443719,t5:0.7933459524):0.8417851452):0.7066285675,(t1:0.0580010619,(t7:0.6590069213,t3:0.1069735419):0.5657461432):0.3575631182);"); phy2 = readTopology("((t3:0.9152618761,t4:0.4574306419):0.7603277895,(((t1:0.4291725352,t8:0.3302786439):0.3437780738,(t5:0.8438980761,(t6:0.6667000714,t2:0.7141199473):0.01087239943):0.752832541):0.2591188031,t7:0.7685037958):0.9210739341);"); phy3 = readTopology("(((t7:0.3309174306,t6:0.8330178803):0.7741786113,(((t2:0.4048132468,t8:0.6809111023):0.6810255498,(t4:0.6540613638,t5:0.2610215396):0.8490990005):0.6802781771,t3:0.2325445588):0.911911567):0.94644987,t1:0.09404937108);"); phy10= readTopology("((t4:0.1083955287,((t1:0.8376079942,t8:0.1745392387):0.6178579947,((t6:0.3196466176,t2:0.9228881211):0.3112748025,t7:0.05162345758):0.7137957355):0.5162231021):0.06693460606,(t5:0.005652675638,t3:0.2584615161):0.7333540542);"); @test hardwiredClusterDistance(phy1, phy10, false)== 8 @test hardwiredClusterDistance(phy2, phy10, false)== 6 @test hardwiredClusterDistance(phy3, phy10, false)==10 @test hardwiredClusterDistance(phy1, phy2, false)== 8 @test hardwiredClusterDistance(phy1, phy3, false)==10 @test hardwiredClusterDistance(phy2, phy3, false)==10 @test hardwiredClusterDistance(phy1, phy10, true) ==10 @test hardwiredClusterDistance(phy2, phy10, true) == 8 # or: wrong RF distance between some of the trees end # of testset, tree2Matrix #----------------------------------------------------------# # testing function to compare networks # # with hardwired clusters # # used for detection of given hybridization event # #----------------------------------------------------------# @testset "test displayedTrees, hardwiredClusters, hardwiredClusterDistance, displayedNetworkAt!" begin estnet = readTopology("(6,((5,#H7:0.0::0.402):8.735,((1,2):6.107,((3,4):1.069)#H7:9.509::0.598):6.029):0.752);") # originally from "../msSNaQ/simulations/estimatedNetworks/baseline/nloci10/1_julia.out" trunet = readTopology("((((1,2),((3,4))#H1),(#H1,5)),6);"); @test hardwiredClusterDistance(majorTree(trunet), majorTree(estnet),false) == 0 # false: unrooted truminor = minorTreeAt(trunet, 1); # (1:1.0,2:1.0,((5:1.0,(3:1.0,4:1.0):2.0):1.0,6:1.0):2.0); estminor = minorTreeAt(estnet, 1); # (5:1.0,(3:1.0,4:1.0):1.069,(6:1.0,(1:1.0,2:1.0):10.0):8.735); @test writeTopology(truminor) == "(((5,(3,4)),(1,2)),6);" @test writeTopology(estminor) == "(6,((5,(3,4):1.069):8.735,(1,2):12.136):0.752);" @test hardwiredClusterDistance(truminor, estminor, false) == 0 # false: unrooted # so the hybrid edge was estimated correctly!! rootatnode!(trunet, -8) @test hardwiredClusterDistance(estnet, trunet, true) == 3 # next: testing hardwiredClusterDistance_unrooted, via the option rooted=false @test hardwiredClusterDistance(estnet, trunet, false) == 0 h0est = readTopology("(((2:0.01,1:0.01):0.033,(3:0.0154,4:0.0149):0.0186):0.0113,6:0.0742,5:0.0465);") truenet = readTopology("((((1,2),((3,4))#H1),(#H1,5)),6);") h1est = readTopology("(5:0.0,6:0.0,(((2:0.0)#H1:0.0::0.95,1:0.0):0.0,((4:0.0,3:0.0):0.0,#H1:0.0::0.05):0.0):0.0);") @test hardwiredClusterDistance(h0est, truenet, false) == 2 @test hardwiredClusterDistance(truenet, h0est, false) == 2 @test hardwiredClusterDistance(h1est, truenet, false) == 4 @test hardwiredClusterDistance(truenet, h1est, false) == 4 net5 = readTopology("(A,((B,#H1:::0.2),(((C,(E)#H2:::0.7),(#H2:::0.3,F)),(D)#H1:::0.8)));"); tree = displayedTrees(net5, 0.0); taxa = tipLabels(net5); @test hardwiredClusters(tree[1], taxa) == [16 0 1 1 1 1 1 10; 15 0 0 1 1 1 1 10; 12 0 0 1 1 1 0 10; 8 0 0 1 1 0 0 10] @test hardwiredClusters(tree[2], taxa) == [16 0 1 1 1 1 1 10; 4 0 1 0 0 0 1 10; 12 0 0 1 1 1 0 10; 8 0 0 1 1 0 0 10] @test hardwiredClusters(net5, taxa) == [16 0 1 1 1 1 1 10; 4 0 1 0 0 0 1 10; 3 0 0 0 0 0 1 11; 15 0 0 1 1 1 1 10; 12 0 0 1 1 1 0 10; 8 0 0 1 1 0 0 10; 7 0 0 0 1 0 0 11; 11 0 0 0 1 1 0 10] if doalltests trunet = readTopology("(((1,2),((3,4))#H1),(#H1,5),6);"); # unrooted taxa = tipLabels(trunet); hardwiredClusters(trunet, taxa) == [8 1 1 1 1 0 0 10 3 1 1 0 0 0 0 10 7 0 0 1 1 0 0 11 6 0 0 1 1 0 0 10 11 0 0 1 1 1 0 10] || error("wrong hardwired cluster matrix for unrooted trunet"); trunet = readTopology("((((1,2),((3,4))#H1),(#H1,5)),6);"); # rooted: good! hardwiredClusters(trunet, taxa) == [12 1 1 1 1 1 0 10; 8 1 1 1 1 0 0 10; 3 1 1 0 0 0 0 10; 7 0 0 1 1 0 0 11; 6 0 0 1 1 0 0 10; 11 0 0 1 1 1 0 10] || error("wrong hardwired cluster matrix for trunet"); hardwiredClusters(estnet, taxa) == [13 1 1 1 1 1 0 10 4 0 0 1 1 1 0 10 3 0 0 1 1 0 0 11 10 0 0 1 1 0 0 10 12 1 1 1 1 0 0 10 7 1 1 0 0 0 0 10] || error("wrong hardwired cluster matrix for estnet") hardwiredClusterDistance(trunet,estnet,true) == 0 || error("trunet and estnet should be found to be at HWDist 0"); net51 = readTopologyLevel1("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;") directEdges!(net51); # doing this avoids a warning on the next line: displayedNetworkAt!(net51, net51.hybrid[1]) # H2 # "WARNING: node -3 being the root is contradicted by isChild1 of its edges." rootatnode!(net51, "A"); writeTopologyLevel1(net51) == "(A:0.5,((((C:0.52,(E:0.5)#H2:0.02):0.6,(#H2:0.01,F:0.7):0.8):0.9,D:1.1):1.3,B:2.3):0.5);" || error("wrong net51 after displayedNetworkAt!"); net52 = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); displayedNetworkAt!(net52, net52.hybrid[2]) writeTopologyLevel1(net52) == "(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,E:0.52):0.6,F:1.5):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7);" || error("wrong net52 after displayedNetworkAt!"); taxa = tipLabels(net52); # order: A B C E F D hardwiredClusters(net51, taxa) == [16 0 1 1 1 1 1 10; 15 0 0 1 1 1 1 10; 12 0 0 1 1 1 0 10; 8 0 0 1 1 0 0 10; 7 0 0 0 1 0 0 11; 11 0 0 0 1 1 0 10] || error("wrong hardwired clusters for net51"); hardwiredClusters(net52, taxa) == [16 0 1 1 1 1 1 10; 4 0 1 0 0 0 1 10; 3 0 0 0 0 0 1 11; 15 0 0 1 1 1 1 10; 12 0 0 1 1 1 0 10; 8 0 0 1 1 0 0 10] || error("wrong hardwired clusters for net52"); hardwiredClusterDistance(net51,net52,true) == 4 || error("wrong HWDist between net51 and net52"); end end # of testset: displayedTrees, hardwiredClusters, hardwiredClusterDistance, displayedNetworkAt! @testset "testing hardwiredCluster! on single nodes" begin net5 = "(A,((B,#H1),(((C,(E)#H2),(#H2,F)),(D)#H1)));" |> readTopology |> directEdges! ; taxa = net5 |> tipLabels # ABC EF D m = hcat([true,false,false,false,false,false], [false,true,false,false,false,false], [false,false,false,false,false,true], [false,true,false,false,false,true], [false,false,true,false,false,false], [false,false,false,true,false,false], [false,false,false,true,false,false], [false,false,true,true,false,false], [false,false,false,true,false,false], [false,false,false,false,true,false], [false,false,false,true,true,false], [false,false,true,true,true,false], [false,false,false,false,false,true], [false,false,false,false,false,true], [false,false,true,true,true,true], [false,true,true,true,true,true]) for i = 1:16 @test hardwiredCluster(net5.edge[i], taxa) == m[:,i] end end # of testset, hardwiredCluster! on single nodes end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
4545
# test to see if the likelihood is correctly calculated # and if the networks are correctly estimated # Claudia August 2015 # -------------------5taxon tree------------------ PhyloNetworks.CHECKNET || error("need CHECKNET==true in PhyloNetworks to test snaq in test_correctLik.jl") df=DataFrame(t1=["6","6","10","6","6"], t2=["7","7","7","10","7"], t3=["4","10","4","4","4"], t4=["8","8","8","8","10"], obsCF12=[0.2729102510259939, 0.3967750546426937, 0.30161247267865315, 0.24693940689390592, 0.2729102510259939], obsCF13=[0.45417949794801216, 0.30161247267865315, 0.30161247267865315, 0.5061211862121882, 0.45417949794801216], obsCF14=[0.2729102510259939, 0.30161247267865315, 0.3967750546426937, 0.24693940689390592, 0.2729102510259939]) d = readTableCF(df) @test_throws ErrorException PhyloNetworks.writeExpCF(d) @test writeTableCF(d) == rename(df, [:obsCF12 => :CF12_34, :obsCF13 => :CF13_24, :obsCF14 => :CF14_23]) @test tipLabels(d) == ["4","6","7","8","10"] @test_logs PhyloNetworks.descData(d, devnull) df[!,:ngenes] = [10,10,10,10,20] allowmissing!(df, :ngenes) d = readTableCF(df) df[1,:ngenes] = missing; d.quartet[1].ngenes = -1.0 newdf = writeTableCF(d) @test newdf[!,1:7] == rename(df, [:obsCF12 => :CF12_34, :obsCF13 => :CF13_24, :obsCF14 => :CF14_23])[!,1:7] @test ismissing(newdf[1,:ngenes]) @test newdf[2:end,:ngenes] == df[2:end,:ngenes] # starting tree: tree = "((6,4),(7,8),10);" currT = readTopologyLevel1(tree); #printEdges(currT) @testset "correct pseudo likelihood and snaq" begin @testset "lik on tree" begin extractQuartet!(currT,d) calculateExpCFAll!(d) tmp = (@test_logs PhyloNetworks.writeExpCF(d)) for i in [5,7] for j in 2:5 @test tmp[j,i] ≈ 0.12262648039048077; end end for j in 2:5 @test tmp[j,6] ≈ 0.7547470392190385; end lik = logPseudoLik(d) @test lik ≈ 193.7812623319291 #estTree = optTopRun1!(currT,d,0,5454) # issue with printCounts, TravisCI? #@test estTree.loglik ≈ 0.0 atol=1e-8 #println("passed optTopRun1! on tree") end # ------------------5taxon network 1 hybridization: Case H----------------- # starting topology: Case G global tree = "((((6:0.1,4:1.5)1:0.2,(7)11#H1)5:0.1,(11#H1,8)),10:0.1);" # Case G global currT = readTopologyLevel1(tree); # real network: Case H global df=DataFrame(t1=["6","6","10","6","6"],t2=["7","7","7","10","7"],t3=["4","10","4","4","4"],t4=["8","8","8","8","10"],CF1234=[0.13002257237728915, 0.36936019721747243, 0.34692592933269173, 0.12051951084152591, 0.11095702789935982], CF1324=[0.7399548552454217, 0.28371387344983595, 0.28371387344983595, 0.7589609783169482, 0.7780859442012804],CF1423=[0.13002257237728915, 0.34692592933269173, 0.36936019721747243, 0.12051951084152591, 0.11095702789935982]) global d = readTableCF(df) @testset "lik of network" begin extractQuartet!(currT,d) calculateExpCFAll!(d) lik = logPseudoLik(d) @test lik ≈ 50.17161079450669 end @testset "network estimation h=1" begin estNet = optTopRun1!(currT, 0.01,75, d,1, 1e-5,1e-6,1e-3,1e-4, false,true,Int[], 54, stdout,false,0.3) # topology, likAbs,Nfail, data,hmax, fRel,fAbs,xRel,xAbs, # verbose,closeN,numMoves, seed, logfile,writelog,probST,sout) @test estNet.loglik < 0.00217 end @testset "snaq! in serial and in parallel" begin global tree = readTopology("((((6:0.1,4:1.5),9)1:0.1,8),10:0.1);") @test_throws ErrorException snaq!(tree, d) # some taxa are in quartets, not in tree originalstdout = stdout redirect_stdout(devnull) global net = readTopology("((((6:0.1,4:1.5)1:0.2,((7,60))11#H1)5:0.1,(11#H1,8)),10:0.1);") @test_logs (:warn, r"^these taxa will be deleted") snaq!(net, d, # taxon "60" in net: not in quartets hmax=1, runs=1, Nfail=1, seed=1234, ftolRel=1e-2,ftolAbs=1e-2,xtolAbs=1e-2,xtolRel=1e-2) global n1 = snaq!(currT, d, hmax=1, runs=1, Nfail=1, seed=123, ftolRel=1e-2,ftolAbs=1e-2,xtolAbs=1e-2,xtolRel=1e-2, verbose=true) addprocs(1) @everywhere using PhyloNetworks global n2 = snaq!(currT, d, hmax=1, runs=2, Nfail=1, seed=123, ftolRel=1e-2,ftolAbs=1e-2,xtolAbs=1e-2,xtolRel=1e-2) redirect_stdout(originalstdout) rmprocs(workers()) @test writeTopology(n1, round=true)==writeTopology(n2, round=true) @test n1.loglik == n2.loglik n3 = readSnaqNetwork("snaq.out") @test writeTopology(n3, round=true)==writeTopology(n2, round=true) @test n3.loglik > 0.0 rm("snaq.out") rm("snaq.networks") rm("snaq.log") # .log and .err should be git-ignored, but still rm("snaq.err") end end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
3807
# test to see that deleteHybridizationUpdate undoes all attributes # prompted by Cecile finding cases when containRoot was not updated # Claudia December 2015 PhyloNetworks.CHECKNET || error("need CHECKNET==true in PhyloNetworks to test snaq in test_correctLik.jl") @testset "test: delete hybridization" begin global seed, currT0, besttree, net, successful,hybrid,flag,nocycle,flag2,flag3 seed = 485 # 2738 at v0.14.2 currT0 = readTopologyLevel1("(((((((1,2),3),4),5),(6,7)),(8,9)),10);"); # warning: the random number generator has a local scope: # with subsets of tests, the same seed would be re-used over and over. Random.seed!(seed); besttree = deepcopy(currT0); # ===== first hybridization ========================== successful,_ = PhyloNetworks.addHybridizationUpdate!(besttree); @test successful net = deepcopy(besttree); @test sum(!e.containRoot for e in net.edge) == 3 # 3 edges can't contain the root @test sum(e.inCycle==11 for e in net.edge) == 6 @test sum(n.inCycle==11 for n in net.node) == 6 @test length(net.partition) == 6 @test Set([e.number for e in p.edges] for p in net.partition) == Set([[14], [11], [10], [9,7,5,3,1,2,4,6,8], [17], [15]]) # ===== second hybridization ========================== successful = false successful,_ = PhyloNetworks.addHybridizationUpdate!(besttree); @test successful net = deepcopy(besttree); @test sum(!e.containRoot for e in net.edge) == 8 @test sum(e.inCycle==11 for e in net.edge) == 6 # edges 12, 13, 16, 18, 19, 20 @test sum(n.inCycle==11 for n in net.node) == 6 @test sum(e.inCycle==13 for e in net.edge) == 4 # edges 5, 7, 22, 23 @test sum(n.inCycle==13 for n in net.node) == 4 # test partition @test length(net.partition) == 9 @test Set([e.number for e in p.edges] for p in net.partition) == Set([[15], [10], [11], [17], [14], [3,1,2], [21,8,9], [6], [4]]) ## # ===== identify containRoot for net.node[21] ## net0=deepcopy(net); ## hybrid = net.node[21]; ## hybrid.isBadDiamondI ## nocycle, edgesInCycle, nodesInCycle = identifyInCycle(net,hybrid); ## [n.number for n in edgesInCycle] == [23,9,7,5,22] || error("wrong identified cycle") ## [n.number for n in nodesInCycle] == [13,14,-4,-5,-6] || error("wrong identified cycle") ## edgesRoot = identifyContainRoot(net,hybrid); ## [n.number for n in edgesRoot] == [3,1,2] || error("wrong identified contain root") ## [e.containRoot for e in edgesRoot] == [false,false,false] || error("edges root should be false contain root") ## edges = hybridEdges(hybrid); ## [e.number for e in edges] == [22,23,3] || error("wrong identified edges") ## undoGammaz!(hybrid,net); ## othermaj = getOtherNode(edges[1],hybrid); ## othermaj.number == -6 || error("wrong othermaj") ## edgesmaj = hybridEdges(othermaj); ## [e.number for e in edgesmaj] == [22,5,4] || error("wrong identified edges") ## edgesmaj[3].containRoot || error("wrong edgesmaj[3] contain root") ## undoContainRoot!(edgesRoot); ## [e.containRoot for e in edgesRoot] == [true,true,true] || error("edges root should be false contain root") ## deleteHybrid!(hybrid,net,true, false) ## [e.containRoot for e in edgesRoot] == [true,true,true] || error("edges root should be false contain root") ## printEdges(net) # ================= delete second hybridization ============================= deleteHybridizationUpdate!(net,net.node[21], false,false); @test length(net.partition) == 6 @test Set([e.number for e in p.edges] for p in net.partition) == Set([[15], [10], [11], [17], [14], [3,1,2,8,9,6,4,7,5]]) @test sum(!e.containRoot for e in net.edge) == 3 @test sum(e.inCycle==11 for e in net.edge) == 6 @test sum(e.inCycle==13 for e in net.edge) == 0 # =============== delete first hybridization =================== deleteHybridizationUpdate!(net,net.node[19]); checkNet(net) @test length(net.partition) == 0 #printEdges(net) end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
12121
# test functions for the 5taxon networks # functions used in tests_5taxon_readTopology.jl # fixit: it would be better that within each function, it would look # for the needed edges/nodes starting from the hybrid node # so that it would be a general function (not bounded to the specific indeces) # Claudia November 2014 # Case C bad triangle II function testCaseC(net::HybridNetwork) n=searchHybridNode(net); node = n[1]; node.k != 3 ? error("k diff than 3") : nothing node.isVeryBadTriangle ? nothing : error("does not know it is very bad triangle") node.isExtBadTriangle ? error("thinks it is extremely bad triangle") : nothing net.hasVeryBadTriangle ? nothing : error("net does not know it has very bad triangle") net.numBad == 0 ? nothing : error("net.numBad should be 0") net.numHybrids != 1 ? error("should have 1 hybrid, but net.numHybrids is $(net.numHybrids): $([n.number for n in net.hybrid])") : nothing end # Case F bad diamond I function testCaseF(net::HybridNetwork) net.visited = [e.istIdentifiable for e in net.edge]; net.numHybrids == 1 ? nothing : error("networks should have one hybrid node and it has $(net.numHybrids)") node=net.hybrid[1]; node.k != 4 ? error("k diff than 4") : nothing (net.edge[3].inCycle != node.number || net.edge[4].inCycle != node.number || net.edge[5].inCycle != node.number || net.edge[7].inCycle != node.number ) ? error("edges not correctly in cycle") : nothing (net.node[3].inCycle != node.number || net.node[4].inCycle != node.number || net.node[6].inCycle != node.number || net.node[7].inCycle != node.number) ? error("nodes not correctly in cycle") : nothing !node.isBadDiamondI ? error("does not know it is bad diamond I") : nothing node.isBadDiamondII ? error("thinks it is bad diamond II") : nothing net.edge[2].containRoot ? error("edge can contain root") : nothing (!net.edge[3].hybrid || !net.edge[3].isMajor) ? error("edge 3 is not hybrid or major") : nothing (!net.edge[5].hybrid || net.edge[5].isMajor) ? error("edge 5 is not hybrid or is major") : nothing net.node[4].gammaz != net.edge[3].gamma*net.edge[4].z ? error("node 4 gammaz not correctly calculated") : nothing net.node[6].gammaz != net.edge[5].gamma*net.edge[7].z ? error("node 6 gammaz not correctly calculated") : nothing (net.edge[4].istIdentifiable || net.edge[7].istIdentifiable) ? error("edges identifiable that should not") : nothing !net.edge[8].istIdentifiable ? error("edge 8 not identifiable") : nothing net.visited[8] = false; !all([!id for id in net.visited]) ? error("edges not identifiable as identifiable") : nothing [n.number for n in net.leaf] == [1,2,5,7,8] ? nothing : error("net.leaf is wrong") end # Case G function testCaseG(net::HybridNetwork) net.visited = [e.istIdentifiable for e in net.edge]; net.numHybrids == 1 ? nothing : error("networks should have one hybrid node and it has $(net.numHybrids)") node=net.hybrid[1]; node.k != 4 ? error("k diff than 4") : nothing (net.edge[5].inCycle != node.number || net.edge[6].inCycle != node.number || net.edge[7].inCycle != node.number || net.edge[9].inCycle != node.number ) ? error("edges not correctly in cycle") : nothing (net.node[5].inCycle != node.number || net.node[6].inCycle != node.number || net.node[8].inCycle != node.number || net.node[9].inCycle != node.number) ? error("nodes not correctly in cycle") : nothing (node.isBadDiamondI || node.isBadDiamondII ) ? error("thinks it is bad diamond") : nothing net.edge[4].containRoot ? error("edge can contain root") : nothing (!net.edge[5].hybrid || !net.edge[5].isMajor) ? error("edge 5 is not hybrid or major") : nothing (!net.edge[7].hybrid || net.edge[7].isMajor) ? error("edge 7 is not hybrid or is major") : nothing net.node[5].gammaz != -1 ? error("node 5 gammaz should be -1") : nothing (!net.edge[6].istIdentifiable || !net.edge[3].istIdentifiable || !net.edge[9].istIdentifiable) ? error("edges identifiable as not identifiable") : nothing net.visited[6] = false; net.visited[3] = false; net.visited[9] = false; !all([!id for id in net.visited]) ? error("edges not identifiable as identifiable") : nothing [n.number for n in net.leaf] == [1,2,4,7,8] ? nothing : error("net.leaf is wrong") end # Case H function testCaseH(net::HybridNetwork) net.visited = [e.istIdentifiable for e in net.edge]; net.numHybrids == 1 ? nothing : error("networks should have one hybrid node and it has $(net.numHybrids)") node=net.hybrid[1]; node.k != 4 ? error("k diff than 4") : nothing (net.edge[4].inCycle != node.number || net.edge[5].inCycle != node.number || net.edge[7].inCycle != node.number || net.edge[9].inCycle != node.number ) ? error("edges not correctly in cycle") : nothing (net.node[4].inCycle != node.number || net.node[6].inCycle != node.number || net.node[8].inCycle != node.number || net.node[10].inCycle != node.number) ? error("nodes not correctly in cycle") : nothing (node.isBadDiamondI || node.isBadDiamondII) ? error("thinks it is bad diamond") : nothing net.edge[8].containRoot ? error("8 can contain root") : nothing (!net.edge[9].hybrid || !net.edge[9].isMajor) ? error("edge 9 is not hybrid or major") : nothing (!net.edge[4].hybrid || net.edge[4].isMajor) ? error("edge 4 is not hybrid or is major") : nothing node.gammaz != -1 ? error("hybrid node gammaz should be -1") : nothing (!net.edge[3].istIdentifiable || !net.edge[5].istIdentifiable || !net.edge[7].istIdentifiable) ? error("edge9,5,13not identifiable") : nothing net.visited[3] = false; net.visited[5] = false; net.visited[7] = false; !all([!id for id in net.visited]) ? error("edges not identifiable as identifiable") : nothing [n.number for n in net.leaf] == [1,2,4,5,6] ? nothing : error("net.leaf is wrong") end # Case J function testCaseJ(net::HybridNetwork) net.visited = [e.istIdentifiable for e in net.edge]; net.numHybrids == 1 ? nothing : error("networks should have one hybrid node and it has $(net.numHybrids)") node=net.hybrid[1]; node.k != 5 ? error("k diff than 5") : nothing (net.edge[2].inCycle != node.number || net.edge[4].inCycle != node.number || net.edge[6].inCycle != node.number || net.edge[10].inCycle != node.number || net.edge[8].inCycle != node.number) ? error("edges not correctly in cycle") : nothing (net.node[2].inCycle != node.number || net.node[4].inCycle != node.number || net.node[6].inCycle != node.number || net.node[10].inCycle != node.number || net.node[9].inCycle) != node.number ? error("nodes not correctly in cycle") : nothing net.edge[1].containRoot ? error("edge can contain root") : nothing (!net.edge[2].hybrid || !net.edge[2].isMajor) ? error("edge 2 is not hybrid or major") : nothing node.gammaz != -1 ? error("hybrid node gammaz should be -1") : nothing (!net.edge[4].istIdentifiable || !net.edge[6].istIdentifiable || !net.edge[10].istIdentifiable) ? error("edge9,5,10not identifiable") : nothing net.visited[4] = false; net.visited[6] = false; net.visited[10] = false; !all([!id for id in net.visited]) ? error("edges not identifiable as identifiable") : nothing [n.number for n in net.leaf] == [1,3,4,5,6] ? nothing : error("net.leaf is wrong") end # Case D bad triangle I function testCaseD(net::HybridNetwork) net.visited = [e.istIdentifiable for e in net.edge]; n = searchHybridNode(net); node = n[1]; node.k != 3 ? error("k diff than 3") : nothing node.isVeryBadTriangle ? nothing : error("does not know it is very bad triangle") node.isExtBadTriangle ? error("thinks it is extremely bad triangle") : nothing net.hasVeryBadTriangle ? nothing : error("net does not know it has very bad triangle") net.numBad == 0 ? nothing : error("net.numBad should be 0") net.numHybrids != 1 ? error("should have 1 hybrid, but net.numHybrids is $(net.numHybrids): $([n.number for n in net.hybrid])") : nothing end # Case E bad triangle I function testCaseE(net::HybridNetwork) net.visited = [e.istIdentifiable for e in net.edge]; n = searchHybridNode(net); node = n[1]; node.k != 3 ? error("k diff than 3") : nothing node.isVeryBadTriangle ? nothing : error("does not know it is very bad triangle") node.isExtBadTriangle ? error("thinks it is extremely bad triangle") : nothing net.hasVeryBadTriangle ? nothing : error("net does not know it has very bad triangle") net.numBad == 0 ? nothing : error("net.numBad should be 0") net.numHybrids != 1 ? error("should have 1 hybrid, but net.numHybrids is $(net.numHybrids): $([n.number for n in net.hybrid])") : nothing end # Case I bad diamond II function testCaseI(net::HybridNetwork) net.numHybrids == 1 ? nothing : error("networks should have one hybrid node and it has $(net.numHybrids)") node = net.hybrid[1]; node.isBadDiamondII ? nothing : error("does not know it is bad diamond II") node.isBadDiamondI ? error("thinks it is bad diamond I") : nothing node.k == 4 ? nothing : error("k should be 4") net.visited = [e.istIdentifiable for e in net.edge]; edge4 = getIndexEdge(4,net); edge1 = getIndexEdge(1,net); edge2 = getIndexEdge(2,net); edge3 = getIndexEdge(3,net); edge9 = getIndexEdge(9,net); edge10 = getIndexEdge(10,net); edge6 = getIndexEdge(6,net); node1 = getIndexNode(-2,net); node2 = getIndexNode(-3,net); node5 = getIndexNode(-6,net); node3 = getIndexNode(3,net); (net.edge[edge4].inCycle != node.number || net.edge[edge9].inCycle != node.number || net.edge[edge6].inCycle != node.number || net.edge[edge10].inCycle != node.number ) ? error("edges not correctly in cycle") : nothing (net.node[node1].inCycle != node.number || net.node[node2].inCycle != node.number || net.node[node5].inCycle != node.number || net.node[node3].inCycle != node.number) ? error("nodes 1,5,11,12 not correctly in cycle") : nothing (net.edge[edge1].containRoot || net.edge[edge2].containRoot || net.edge[edge3].containRoot) ? error("edges can contain root and shouldn't") : nothing (!net.edge[edge4].hybrid || !net.edge[edge4].isMajor) ? error("edge 4 is not hybrid or major") : nothing net.edge[edge3].length != 0 ? error("edges should have length 0") : nothing net.edge[edge3].istIdentifiable ? error("edge9,4 identifiable and should not") : nothing (net.edge[edge4].istIdentifiable && net.edge[edge9].istIdentifiable && net.edge[edge6].istIdentifiable && net.edge[edge10].istIdentifiable) || error("edges that should be identifiable, are not") net.visited[edge4] = false; net.visited[edge9] = false; net.visited[edge6] = false; net.visited[edge10] = false; !all([!id for id in net.visited]) ? error("edges not identifiable as identifiable") : nothing [n.number for n in net.leaf] == [1,2,4,5,6] ? nothing : error("net.leaf is wrong") end # tree example function testTree(net::HybridNetwork) !all([!e.hybrid for e in net.edge]) ? error("some edge is still hybrid") : nothing !all([!e.hybrid for e in net.node]) ? error("some node is still hybrid") : nothing !all([!e.hasHybEdge for e in net.node]) ? error("some node has hybrid edge") : nothing !all([e.isMajor for e in net.edge]) ? error("some edge is not major") : nothing !all([e.containRoot for e in net.edge]) ? error("some edge cannot contain root") : nothing edge9 = getIndexNumEdge(9,net); edge5 = getIndexNumEdge(5,net); (!net.edge[5].istIdentifiable || !net.edge[3].istIdentifiable) ? error("edge3,5 not identifiable") : nothing net.visited = [e.istIdentifiable for e in net.edge]; net.visited[3] = false; net.visited[5] = false; !all([!id for id in net.visited]) ? error("edges not identifiable as identifiable") : nothing net.edge[2].length != 1.5 ? error("edge length for 2 is wrong") : nothing net.edge[4].length != 0.2 ? error("edge length for 4 is wrong") : nothing [n.number for n in net.leaf] == [1,2,4,6,7] ? nothing : error("net.leaf is wrong") end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
1002
@testset "deterministic topologies" begin @test PhyloNetworks.startree_newick(3) == "(t1:1.0,t2:1.0,t3:1.0);" @test PhyloNetworks.symmetrictree_newick(2, 0.1, 2) == "((A2:0.1,A3:0.1):0.1,(A4:0.1,A5:0.1):0.1);" @test PhyloNetworks.symmetricnet_newick(3, 2, 1, 0.1, 1) == "(((#H:1::0.1,(A1:1,A2:1):0.5):0.5,((A3:0.5)#H:0.5::0.9,A4:1):1):1,((A5:1,A6:1):1,(A7:1,A8:1):1):1);" @test PhyloNetworks.symmetricnet_newick(3, 3, 3, 0.1, 1) == "((#H:1::0.1,((A1:1,A2:1):1,(A3:1,A4:1):1):0.5):0.5,(((A5:1,A6:1):1,(A7:1,A8:1):1):0.5)#H:0.5::0.9);" @test PhyloNetworks.symmetricnet_newick(4, 2, 0.1) == "((((#H1:0.25::0.1,(A1:0.25,A2:0.25):0.125):0.125,((A3:0.125)#H1:0.125::0.9,A4:0.25):0.25):0.25,((#H2:0.25::0.1,(A5:0.25,A6:0.25):0.125):0.125,((A7:0.125)#H2:0.125::0.9,A8:0.25):0.25):0.25):0.25,(((#H3:0.25::0.1,(A9:0.25,A10:0.25):0.125):0.125,((A11:0.125)#H3:0.125::0.9,A12:0.25):0.25):0.25,((#H4:0.25::0.1,(A13:0.25,A14:0.25):0.125):0.125,((A15:0.125)#H4:0.125::0.9,A16:0.25):0.25):0.25):0.25);" end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
7247
# using Test, PhyloNetworks # using PhyloPlots # using Debugger @testset "Testing Tarjan's biconnected components" begin net = readTopology("(A,(B,(C,D)));"); a = biconnectedComponents(net); @test [[e.number for e in b] for b in a] == [[1],[2],[3],[4],[5],[6],] net = readTopology("(((A,(((C,(D)#H2),(E,#H2)))#H1),(B,#H1)),F);"); a = biconnectedComponents(net); @test [[e.number for e in b] for b in a] == [[1],[2],[3],[6], [8, 7, 4, 5],[9],[12],[14, 13, 10, 11],[15],[16]] net = readTopology("(((A,(B)#H1),((C,(E)#H2),#H1)),(D,#H2));"); a = biconnectedComponents(net); @test [[e.number for e in b] for b in a] == [[1], [2],[5],[6],[12],[10, 14, 13, 7, 8, 9, 3, 4, 11]] net = readTopology("((((A,(B)#H1),((C,(E)#H2),#H1)),(D,#H2)),(((F)#H3,G),(H,#H3)));"); a = biconnectedComponents(net); @test [[e.number for e in b] for b in a] == [[1],[2],[5],[6],[12], [10, 14, 13, 7, 8, 9, 3, 4, 11],[15],[16],[20],[18], [22, 21, 17, 19],[23]] a = biconnectedComponents(net, true); @test [[e.number for e in b] for b in a] == [[10, 14, 13, 7, 8, 9, 3, 4, 11], [22, 21, 17, 19]] # net with hybrid ladder; 3 degree-2 nodes; root edge above LSA net = readTopology("((((((((((((Ae_caudata))#H1,#H2),(Ae_umbellulata,#H1)),Ae_comosa),((((Ae_searsii)#H2,#H3),#H4)))),(((Ae_speltoides_Tr223,Ae_speltoides_Tr251))#H3,(Ae_mutica)#H4))),S_vavilovii)));") a = biconnectedComponents(net, false); a = [sort!([e.number for e in b]) for b in a] @test length(a) == 14 @test a[14] == [31] # root edge @test a[10] == [3,4,5, 7,8,9, 11, 13,14,15,16,17,18,19,20, 24, 26,27] net = readTopology("((((A,(B)#H1),((C,(E)#H2),#H1)),(D,#H2)),(((F)#H3,G),(H,#H3)));"); r,major,minor = PhyloNetworks.blobInfo(net, false); @test [n.number for n in r] == [-5, 3, -8, 6, -10, -3, -2, 9, -14, -12, -11, -2] r,major,minor = PhyloNetworks.blobInfo(net); @test [n.number for n in r] == [-3,-11,-2] @test [[e.number for e in h] for h in major] == [[7, 3],[17],[]] @test [[e.number for e in h] for h in minor] == [[13,9],[21],[]] forest, blobs = blobDecomposition(net); @test length(blobs)==3 @test writeTopology(forest) == "(dummy -3,dummy -11);" s = IOBuffer() writeSubTree!(s, blobs[1], nothing, false, true) @test String(take!(s)) == "(((A,(B)#H1),((C,(E)#H2),#H1)),(D,#H2));" writeSubTree!(s, blobs[2], nothing, false, true) @test String(take!(s)) == "(((F)#H3,G),(H,#H3));" writeSubTree!(s, blobs[3], nothing, false, true) @test String(take!(s)) == "(dummy -3,dummy -11);" # h=2, 2 non-trivial blobs above the LSA, LSA = the single tip net = readTopology("((((t1)#H22:::0.8,#H22))#H10:::0.7,#H10);") a = biconnectedComponents(net,true); @test [[e.number for e in b] for b in a] == [[3,2], [6,5]] lsa, lsaind = PhyloNetworks.leaststableancestor(net) @test (lsa.number,lsaind) == (2,4) # h=3, one level-1 blob above the LSA, one level-2 blob below including a 2-cycle net = readTopology("((((((t2,#H25:::0.3))#H22:::0.8,#H22),(t1)#H25:::0.7))#H10:::0.6,#H10);") a = biconnectedComponents(net,true); [[e.number for e in b] for b in a] == [ [5,8,2,3,4,6], [11,10]] aentry = PhyloNetworks.biconnectedcomponent_entrynodes(net, a) @test [n.number for n in aentry] == [-4,-2] aexit = PhyloNetworks.biconnectedcomponent_exitnodes(net, a) @test [[n.number for n in ae] for ae in aexit] == [[2,-7],[5]] # balanced tree + extra root edge net = readTopology("((((t1,t2),(t3,t4))));") _, lsaindex = PhyloNetworks.leaststableancestor(net) @test net.nodes_changed[lsaindex].number == -4 # LSA = root & entry to non-trivial blob lsa, _ = PhyloNetworks.leaststableancestor(readTopology("(#H2:::0.2,((b)#H2,a));")) @test lsa.number == -2 end @testset "tree component" begin treestr = "(A:3.0,(B:2.0,(C:1.0,D:1.0):1.0):1.0);" tree = readTopology(treestr) for e in tree.edge e.containRoot=false; end # wrong, on purpose @test collect(values(treeedgecomponents(tree))) == repeat([1], inner=7) rcomp = checkroot!(tree) @test rcomp == 1 @test all([e.containRoot for e = tree.edge]) netstr = "(#H1:::0.1,#H2:::0.2,(((b)#H1)#H2,a));" net = readTopology(netstr) for e in net.edge e.containRoot=false; end # wrong, on purpose node2comp = treeedgecomponents(net) # e.g. [1,1,1,2,2,3] or [2,2,2,1,1,3] compsize = [count(isequal(i), values(node2comp)) for i in 1:3] @test sort(compsize) == [1,2,3] rcompID = checkroot!(net, node2comp) @test compsize[rcompID] == 3 rcomp = keys(filter(p -> p.second == rcompID, node2comp)) @test Set(n.number for n in rcomp) == Set([-2 -3 4]) @test Set(e.number for e in net.edge if e.containRoot) == Set([7 6 5 2 1]) for e in net.edge e.containRoot=true; end # wrong, on purpose net.root = 2 # node number 1, also H1: not in the root component on purpose checkroot!(net) @test [e.number for e in net.edge if e.containRoot] == [1,2,5,6,7] @test net.root == 5 # i.e. node number -3. only 1 other option: 6, i.e. nn -2 # test semidirected cycle case net.edge[1].isChild1 = !net.edge[1].isChild1 net.edge[7].isChild1 = !net.edge[7].isChild1 net.edge[7].hybrid = true net.edge[7].gamma = net.edge[4].gamma net.edge[4].gamma = 1.0 net.edge[4].hybrid = false net.root = 5 net.node[6].hybrid = true net.node[6].name = "H3" net.node[2].hybrid = false net.hybrid[1] = net.node[6] mem = treeedgecomponents(net) nnum2comp = Dict(n.number => uc for (n,uc) in mem) @test nnum2comp[4] == nnum2comp[-3] @test nnum2comp[1] == nnum2comp[2] == nnum2comp[3] @test length(unique(nnum2comp[nn] for nn in [4,1,-2])) == 3 @test_throws PhyloNetworks.RootMismatch checkroot!(net, mem) try checkroot!(net, mem) catch e @test occursin("Semidirected cycle", sprint(showerror, e)) end # test multiple entry points case str_level1 = "(((S8,S9),((((S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" netl1 = readTopology(str_level1) P = PhyloNetworks # binding P: local to test set root = netl1.node[19] # 19 = findfirst(n -> n.number == -2, netl1.node) e1 = netl1.edge[20] # 20 = findfirst(e -> e.number == 20, netl1.edge) e2 = netl1.edge[17] # 17 = findfirst(e -> e.number == 17, netl1.edge) P.deleteEdge!(netl1, e1) P.deleteEdge!(netl1, e2) P.deleteNode!(netl1, root) P.removeEdge!(netl1.node[18], e1) # 18 = P.getIndexNode(-12, netl1) P.removeEdge!(netl1.node[16], e2) # 16 = P.getIndexNode(-3, netl1) # nodenumber2UC = Dict(n.number => uc for (n,uc) in treeedgecomponents(netl1)) mem = treeedgecomponents(netl1) @test_throws PhyloNetworks.RootMismatch checkroot!(netl1, mem) try checkroot!(netl1, mem) catch e @test occursin("no common ancestor", sprint(showerror, e)) end # test undirected cycle case netl1 = readTopology(str_level1) n1 = netl1.node[14] # 14 = P.getIndexNode(-6, netl1) n2 = netl1.node[6] # 6 = P.getIndexNode(-8, netl1) e = P.Edge(21,1.0,false,1.0) # 21 = length(netl1.edge) + 1 P.setNode!(e, n1) P.setNode!(e, n2) push!(n1.edge, e) push!(n2.edge, e) push!(net.edge, e) @test_throws PhyloNetworks.RootMismatch treeedgecomponents(netl1) try treeedgecomponents(netl1) catch e @test occursin("Undirected cycle", sprint(showerror, e)) end end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
5917
# test for hasEdge of a QuartetNetwork # Claudia January 2015 # Also, tests for net.ht, net.numht, qnet.indexht #println("----- Case G ------") include("../examples/case_g_example.jl"); # include(joinpath(dirname(pathof(PhyloNetworks)), "..","examples","case_g_example.jl")) q1 = Quartet(1,["6","7","4","8"],[0.5,0.4,0.1]); q2 = Quartet(2,["6","7","10","8"],[0.5,0.4,0.1]); q3 = Quartet(3,["10","7","4","8"],[0.5,0.4,0.1]); q4 = Quartet(4,["6","10","4","8"],[0.5,0.4,0.1]); q5 = Quartet(5,["6","7","4","10"],[0.5,0.4,0.1]); d = DataCF([q1,q2,q3,q4,q5]); #parameters!(net) extractQuartet!(net,d) error1 = false try q1.qnet.hasEdge == [true,true,true,true] ? nothing : error("q1 wrong hasEdge") q2.qnet.hasEdge == [true,false,true,true] ? nothing : error("q2 wrong hasEdge") q3.qnet.hasEdge == [true,false,true,true] ? nothing : error("q3 wrong hasEdge") q4.qnet.hasEdge == [false,true,true,false] ? nothing : error("q4 wrong hasEdge") q5.qnet.hasEdge == [true, true,true,false] ? nothing : error("q5 wrong hasEdge") net.ht == [0.1,0.2,0.1,1.0] ? nothing : error("net.ht not correct") net.numht == [7,3,6,9] ? nothing : error("net.numth not correct") q1.qnet.indexht == [1,2,3,4] ? nothing : error("q1.qnet.indexht not correct") q2.qnet.indexht == [1,3,4] ? nothing : error("q2.qnet.indexht not correct") q3.qnet.indexht == [1,3,4] ? nothing : error("q3.qnet.indexht not correct") q4.qnet.indexht == [2,3] ? nothing : error("q4.qnet.indexht not correct") q5.qnet.indexht == [1,2,3] ? nothing : error("q5.qnet.indexht not correct") q1.qnet.index == [7,3,6,9] ? nothing : error("q1.qnet.index not correct") q2.qnet.index == [5,4,7] ? nothing : error("q2.qnet.index not correct") q3.qnet.index == [5,4,7] ? nothing : error("q3.qnet.index not correct") q4.qnet.index == [3,4] ? nothing : error("q4.qnet.index not correct") q5.qnet.index == [7,3,6] ? nothing : error("q5.qnet.index not correct") catch println("---- error in case G -----") global error1 = true end #println("----- Case F: bad diamond ------") include("../examples/case_f_example.jl"); # include(joinpath(dirname(pathof(PhyloNetworks)), "..","examples","case_f_example.jl")) q1 = Quartet(1,["6","7","4","8"],[0.5,0.4,0.1]); q2 = Quartet(2,["6","7","10","8"],[0.5,0.4,0.1]); q3 = Quartet(3,["10","7","4","8"],[0.5,0.4,0.1]); q4 = Quartet(4,["6","10","4","8"],[0.5,0.4,0.1]); q5 = Quartet(5,["6","7","4","10"],[0.5,0.4,0.1]); d = DataCF([q1,q2,q3,q4,q5]); parameters!(net) extractQuartet!(net,d) error1 = false try q1.qnet.hasEdge == [false,true,true] ? nothing : error("q1 wrong hasEdge") q2.qnet.hasEdge == [true,false,false] ? nothing : error("q2 wrong hasEdge") q3.qnet.hasEdge == [true,false,true] ? nothing : error("q3 wrong hasEdge") q4.qnet.hasEdge == [true,true,false] ? nothing : error("q4 wrong hasEdge") q5.qnet.hasEdge == [false, true,true] ? nothing : error("q5 wrong hasEdge") all(map(approxEq,net.ht,[0.1,0.7*(1-exp(-0.2)),0.3*(1-exp(-0.1))])) ? nothing : error("net.ht not correct") net.numht == [9,21,22] ? nothing : error("net.numth not correct") q1.qnet.indexht == [2,3] ? nothing : error("q1.qnet.indexht not correct") q2.qnet.indexht == [1] ? nothing : error("q2.qnet.indexht not correct") q3.qnet.indexht == [1,3] ? nothing : error("q3.qnet.indexht not correct") q4.qnet.indexht == [1,2] ? nothing : error("q4.qnet.indexht not correct") q5.qnet.indexht == [2,3] ? nothing : error("q5.qnet.indexht not correct") q1.qnet.index == [1,3] ? nothing : error("q1.qnet.index not correct") q2.qnet.index == [4] ? nothing : error("q2.qnet.index not correct") q3.qnet.index == [5,3] ? nothing : error("q3.qnet.index not correct") q4.qnet.index == [5,3] ? nothing : error("q4.qnet.index not correct") q5.qnet.index == [1,3] ? nothing : error("q5.qnet.index not correct") catch println("---- error in case F -----") global error1 = true end #println("----- Case I: bad diamondII ------") include("../examples/case_i_example.jl"); q1 = Quartet(1,["6","7","4","8"],[0.5,0.4,0.1]); q2 = Quartet(2,["6","7","10","8"],[0.5,0.4,0.1]); q3 = Quartet(3,["10","7","4","8"],[0.5,0.4,0.1]); q4 = Quartet(4,["6","10","4","8"],[0.5,0.4,0.1]); q5 = Quartet(5,["6","7","4","10"],[0.5,0.4,0.1]); d = DataCF([q1,q2,q3,q4,q5]); extractQuartet!(net,d) error1 = false try q1.qnet.hasEdge == [true,false,true,false,true] ? nothing : error("q1 wrong hasEdge") q2.qnet.hasEdge == [true,true,true,true,true] ? nothing : error("q2 wrong hasEdge") q3.qnet.hasEdge == [true,true,true,true,true] ? nothing : error("q3 wrong hasEdge") q4.qnet.hasEdge == [true,true,true,true,true] ? nothing : error("q4 wrong hasEdge") q5.qnet.hasEdge == [true,false,true,false,true] ? nothing : error("q5 wrong hasEdge") net.ht == [0.1,2.,1.,1.,1.] ? nothing : error("net.ht not correct") net.numht == [9,4,6,9,10] ? nothing : error("net.numth not correct") q1.qnet.indexht == [1,3,5] ? nothing : error("q1.qnet.indexht not correct") q2.qnet.indexht == [1,2,3,4,5] ? nothing : error("q2.qnet.indexht not correct") q3.qnet.indexht == [1,2,3,4,5] ? nothing : error("q3.qnet.indexht not correct") q4.qnet.indexht == [1,2,3,4,5] ? nothing : error("q4.qnet.indexht not correct") q5.qnet.indexht == [1,3,5] ? nothing : error("q5.qnet.indexht not correct") q1.qnet.index == [7,4,8] ? nothing : error("q1.qnet.index not correct") q2.qnet.index == [8,4,6,8,9] ? nothing : error("q2.qnet.index not correct") q3.qnet.index == [8,4,6,8,9] ? nothing : error("q3.qnet.index not correct") q4.qnet.index == [8,4,5,8,9] ? nothing : error("q4.qnet.index not correct") q5.qnet.index == [7,4,8] ? nothing : error("q5.qnet.index not correct") catch println("---- error in case I -----") global error1 = true end if error1 throw("errors in has edge") end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
2528
@testset "testing interoperability, matrix-based net" begin # tree, some edge lengths missing tree1 = readTopology("(A,(B:1.0,(C:1.0,D:1.0):1.0):1.0);"); @test_logs PhyloNetworks.resetNodeNumbers!(tree1); tree1.edge[3].number = 50 @test_logs (:warn, r"^resetting edge numbers") PhyloNetworks.resetEdgeNumbers!(tree1); @test tree1.edge[3].number == 3 @test PhyloNetworks.majoredgematrix(tree1) == [5 1; 5 6; 6 2; 6 7; 7 3; 7 4] @test all(PhyloNetworks.majoredgelength(tree1) .=== [missing, 1.0,1.0,1.0,1.0,1.0]) @test PhyloNetworks.minorreticulationmatrix(tree1) == Array{Int64,2}(undef, 0,2) @test size(PhyloNetworks.minorreticulationlength(tree1)) == (0,) @test size(PhyloNetworks.minorreticulationgamma(tree1)) == (0,) # network, h=1, some missing gamma values net1 = (@test_logs (:warn, r"^third colon : without gamma value") readTopology("(((A:4.0,(B:1.0)#H1:1.1::):0.5,(C:0.6,#H1:1.0):1.0):3.0,D:5.0);")); @test_logs PhyloNetworks.resetNodeNumbers!(net1); @test PhyloNetworks.majoredgematrix(net1) == [5 6; 5 4; 6 8; 6 7; 7 3; 8 1; 8 9; 9 2] @test PhyloNetworks.majoredgelength(net1) == [3.,5.,.5,1.,.6,4.,1.1,1.] @test PhyloNetworks.minorreticulationmatrix(net1) == [7 9] @test PhyloNetworks.minorreticulationlength(net1) == [1.] @test all(PhyloNetworks.minorreticulationgamma(net1) .=== [missing]) # network, h=2 hybridizations s = "(((Ag,(#H1:7.159::0.056,((Ak,(E:0.08,#H2:0.0::0.004):0.023):0.078,(M:0.0)#H2:::0.996):2.49):2.214):0.026, (((((Az:0.002,Ag2:0.023):2.11,As:2.027):1.697)#H1:0.0::0.944,Ap):0.187,Ar):0.723):5.943,(P,20):1.863,165);"; net2 = readTopology(s); @test_logs PhyloNetworks.resetNodeNumbers!(net2); @test PhyloNetworks.majoredgematrix(net2) == [13 15; 13 14; 13 12; 14 10; 14 11; 15 18; 15 16; 16 17; 16 9; 17 24; 17 8; 18 1; 18 19; 19 20; 20 21; 20 23; 21 2; 21 22; 22 3; 23 4; 24 25; 25 26; 25 7; 26 5; 26 6] @test all(PhyloNetworks.majoredgelength(net2) .=== [5.943,1.863,missing,missing,missing,.026,.723,.187,missing,0,missing,missing, 2.214,2.490,.078,missing,missing,.023,.08,0,1.697,2.11,2.027,.002,.023]) #a.isnull[[3,4,5,9,11,12,16,17]] == [true for i in 1:8] #@test convert(Array, a[[1,2,6,7,8,10,13,14,15]]) == [5.943,1.863, .026,.723,.187, 0, 2.214,2.490,.078] #@test convert(Array, a[18:end]) == [.023,.08,0,1.697,2.11,2.027,.002,.023] @test PhyloNetworks.minorreticulationmatrix(net2) == [19 24; 22 23] @test PhyloNetworks.minorreticulationlength(net2) == [7.159,0.] @test PhyloNetworks.minorreticulationgamma(net2) == [0.056,0.004] end # of testset for interop
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
2309
@testset "readTopology Hybrid Node isMajor Tests" begin global n1, n2, n3 # n1: see issue #44, both hybrid parent edges were minor n1 = readTopology("(A,((B,#H1),(C,(D)#H1:::0.2)));") @test writeTopology(n1) == "(A,((B,(D)#H1:::0.8),(C,#H1:::0.2)));" hybridParents = [x for x in n1.hybrid[1].edge if x.hybrid] # Exclusive or to check exactly one parent edge is major @test hybridParents[1].isMajor ⊻ hybridParents[2].isMajor # Gammas must sum to 1 and be non-negative for hybrids @test hybridParents[1].gamma + hybridParents[2].gamma == 1.0 @test hybridParents[1].gamma >= 0.0 @test hybridParents[2].gamma >= 0.0 # n2 previously failed: both hybrid parent edges were major n2 = readTopology("(A,((B,#H1:::0.5),(C,(D)#H1:::0.5)));") @test writeTopology(n2) == "(A,((B,#H1:::0.5),(C,(D)#H1:::0.5)));" hybridParents = [x for x in n2.hybrid[1].edge if x.hybrid] # Exclusive or to check exactly one parent edge is major @test hybridParents[1].isMajor ⊻ hybridParents[2].isMajor # Gammas must sum to 1 and be non-negative for hybrids @test hybridParents[1].gamma + hybridParents[2].gamma == 1.0 @test hybridParents[1].gamma >= 0.0 @test hybridParents[2].gamma >= 0.0 n3 = readTopology("(A,((C,(D)#H1:::0.5),(B,#H1:::0.5)));") @test writeTopology(n3) =="(A,((C,(D)#H1:::0.5),(B,#H1:::0.5)));" end @testset "parsing extended newick" begin # second reticulation has minor before major, issue #70: net1 = (@test_logs readTopology("(((lo,#H3),#H4),((sp)#H3,(mu)#H4));")); net3 = (@test_logs readTopology("(((sp)#H3,(mu)#H4),((lo,#H3),#H4));")); @test hardwiredClusterDistance(net1, net3, true) == 0 @test_logs readTopology("((((((((((((((Ae_ca1,Ae_ca2),Ae_ca3))#H1,#H2),(((Ae_um1,Ae_um2),Ae_um3),#H1)),((Ae_co1,Ae_co),(((Ae_un1,Ae_un2),Ae_un3),Ae_un4))),(((Ae_ta1,Ae_ta2),(Ae_ta3,Ae_ta4)),((((((((Ae_lo1,Ae_lo2),Ae_lo3),(Ae_sh1,Ae_sh2)),((Ae_bi1,Ae_bi2),Ae_bi3)),((Ae_se1,Ae_se2),Ae_se3)))#H2,#H3),#H4))),(((T_bo1,(T_bo2,T_bo3)),T_bo4),((T_ur1,T_ur2),(T_ur3,T_ur4)))),(((((Ae_sp1,Ae_sp2),Ae_sp3),Ae_sp4))#H3,((((Ae_mu1,Ae_mu2),Ae_mu3),Ae_mu4))#H4))),Ta_ca),S_va),Er_bo),H_vu);"); @test_throws ErrorException readTopology("(((lo,#H3),#H4);") # "Tree ended while reading in subtree ..." @test_throws ErrorException readTopology("((lo,#H3),);") # "Expected beginning of subtree but read ..." end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
34598
## tests of phylolm @testset "phylolm on small network" begin global net tree_str= "(A:2.5,((B:1,#H1:0.5::0.1):1,(C:1,(D:0.5)#H1:0.5::0.9):1):0.5);" net = readTopology(tree_str) preorder!(net) # Rk: Is there a way to check that the branch length are coherent with # one another (Especialy for hybrids) ? # see QuartetNetworkGoodnessFit.ultrametrize! which can detect if the network is # time-consistent: all paths from the root to a given node have the same length # https://github.com/cecileane/QuartetNetworkGoodnessFit.jl # Ancestral state reconstruction with ready-made matrices params = ParamsBM(10, 1) Random.seed!(2468); # simulates the Y values below under julia v1.6 sim = simulate(net, params) # tests that the simulation runs, but results not used Y = [11.239539657364706,8.600423079191044,10.559841251147608,9.965748423156297] # sim[:Tips] X = ones(4, 1) phynetlm = phylolm(X, Y, net; reml=false) @test_logs show(devnull, phynetlm) # Naive version (GLS) ntaxa = length(Y) Vy = phynetlm.Vy Vyinv = inv(Vy) XtVyinv = X' * Vyinv logdetVy = logdet(Vy) betahat = inv(XtVyinv * X) * XtVyinv * Y fittedValues = X * betahat resids = Y - fittedValues sigma2hat = 1/ntaxa * (resids' * Vyinv * resids) # log likelihood loglik = - 1 / 2 * (ntaxa + ntaxa * log(2 * pi) + ntaxa * log(sigma2hat) + logdetVy) # null version nullX = ones(ntaxa, 1) nullXtVyinv = nullX' * Vyinv nullresids = Y - nullX * inv(nullXtVyinv * nullX) * nullXtVyinv * Y nullsigma2hat = 1/ntaxa * (nullresids' * Vyinv * nullresids) nullloglik = - 1 / 2 * (ntaxa + ntaxa * log(2 * pi) + ntaxa * log(nullsigma2hat) + logdetVy) @test coef(phynetlm) ≈ betahat @test nobs(phynetlm) ≈ ntaxa @test residuals(phynetlm) ≈ resids @test response(phynetlm) ≈ Y @test predict(phynetlm) ≈ fittedValues @test dof_residual(phynetlm) ≈ ntaxa-length(betahat) @test sigma2_phylo(phynetlm) ≈ sigma2hat @test loglikelihood(phynetlm) ≈ loglik @test vcov(phynetlm) ≈ sigma2hat*ntaxa/(ntaxa-length(betahat))*inv(XtVyinv * X) @test stderror(phynetlm) ≈ sqrt.(diag(sigma2hat*ntaxa/(ntaxa-length(betahat))*inv(XtVyinv * X))) @test dof(phynetlm) ≈ length(betahat)+1 @test deviance(phynetlm, Val(true)) ≈ sigma2hat * ntaxa @test nulldeviance(phynetlm) ≈ nullsigma2hat * ntaxa @test nullloglikelihood(phynetlm) ≈ nullloglik @test loglikelihood(phynetlm) ≈ nullloglikelihood(phynetlm) @test deviance(phynetlm, Val(true)) ≈ nulldeviance(phynetlm) @test r2(phynetlm) ≈ 1-sigma2hat / nullsigma2hat atol=1e-15 @test adjr2(phynetlm) ≈ 1 - (1 - (1-sigma2hat/nullsigma2hat))*(ntaxa-1)/(ntaxa-length(betahat)) atol=1e-15 @test aic(phynetlm) ≈ -2*loglik+2*(length(betahat)+1) @test aicc(phynetlm) ≈ -2*loglik+2*(length(betahat)+1)+2(length(betahat)+1)*((length(betahat)+1)+1)/(ntaxa-(length(betahat)+1)-1) @test bic(phynetlm) ≈ -2*loglik+(length(betahat)+1)*log(ntaxa) @test hasintercept(phynetlm) # with data frames dfr = DataFrame(trait = Y, tipNames = ["A","B","C","D"]) # sim.M.tipNames fitbis = phylolm(@formula(trait ~ 1), dfr, net; reml=false) #@show fitbis @test coef(phynetlm) ≈ coef(fitbis) @test vcov(phynetlm) ≈ vcov(fitbis) @test nobs(phynetlm) ≈ nobs(fitbis) @test residuals(phynetlm)[fitbis.ind] ≈ residuals(fitbis) @test response(phynetlm)[fitbis.ind] ≈ response(fitbis) @test predict(phynetlm)[fitbis.ind] ≈ predict(fitbis) @test dof_residual(phynetlm) ≈ dof_residual(fitbis) @test sigma2_phylo(phynetlm) ≈ sigma2_phylo(fitbis) @test stderror(phynetlm) ≈ stderror(fitbis) @test confint(phynetlm) ≈ confint(fitbis) @test loglikelihood(phynetlm) ≈ loglikelihood(fitbis) @test dof(phynetlm) ≈ dof(fitbis) @test deviance(phynetlm, Val(true)) ≈ deviance(fitbis, Val(true)) @test nulldeviance(phynetlm) ≈ nulldeviance(fitbis) @test nullloglikelihood(phynetlm) ≈ nullloglikelihood(fitbis) @test r2(phynetlm) ≈ r2(fitbis) atol=1e-15 @test adjr2(phynetlm) ≈ adjr2(fitbis) atol=1e-15 @test aic(phynetlm) ≈ aic(fitbis) @test aicc(phynetlm) ≈ aicc(fitbis) @test bic(phynetlm) ≈ bic(fitbis) tmp = (@test_logs (:warn, r"^You fitted the data against a custom matrix") mu_phylo(phynetlm)) @test tmp ≈ mu_phylo(fitbis) @test hasintercept(phynetlm) ## fixed values parameters fitlam = phylolm(@formula(trait ~ 1), dfr, net, model = "lambda", fixedValue=1.0, reml=false) @test_logs show(devnull, fitlam) @test lambda_estim(fitlam) ≈ 1.0 @test coef(fitlam) ≈ coef(fitbis) @test vcov(fitlam) ≈ vcov(fitbis) @test nobs(fitlam) ≈ nobs(fitbis) @test residuals(fitlam)[fitbis.ind] ≈ residuals(fitbis) @test response(fitlam)[fitbis.ind] ≈ response(fitbis) @test predict(fitlam)[fitbis.ind] ≈ predict(fitbis) @test dof_residual(fitlam) ≈ dof_residual(fitbis) @test sigma2_phylo(fitlam) ≈ sigma2_phylo(fitbis) @test stderror(fitlam) ≈ stderror(fitbis) @test confint(fitlam) ≈ confint(fitbis) @test loglikelihood(fitlam) ≈ loglikelihood(fitbis) @test dof(fitlam) ≈ dof(fitbis) + 1 @test deviance(fitlam, Val(true)) ≈ deviance(fitbis, Val(true)) @test nulldeviance(fitlam) ≈ nulldeviance(fitbis) @test nullloglikelihood(fitlam) ≈ nullloglikelihood(fitbis) @test r2(fitlam) ≈ r2(fitbis) atol=1e-15 @test adjr2(fitlam) ≈ adjr2(fitbis) - 0.5 atol=1e-15 @test aic(fitlam) ≈ aic(fitbis) + 2 #@test aicc(fitlam) ≈ aicc(fitbis) @test bic(fitlam) ≈ bic(fitbis) + log(nobs(fitbis)) @test mu_phylo(fitlam) ≈ mu_phylo(fitbis) @test hasintercept(fitlam) fitSH = phylolm(@formula(trait ~ 1), dfr, net, model="scalingHybrid", fixedValue=1.0, reml=false) @test loglikelihood(fitlam) ≈ loglikelihood(fitSH) @test aic(fitlam) ≈ aic(fitSH) @test modelmatrix(fitlam) == reshape(ones(4), (4,1)) s = IOBuffer(); show(s, formula(fitlam)) @test String(take!(s)) == "trait ~ 1" PhyloNetworks.lambda!(fitlam, 0.5) @test PhyloNetworks.lambda(fitlam) == 0.5 ## Pagel's Lambda fitlam = (@test_logs (:info, r"^Maximum lambda value") match_mode=:any phylolm(@formula(trait ~ 1), dfr, net, model="lambda", reml=false)) @test lambda_estim(fitlam) ≈ 1.24875 ## Scaling Hybrid fitSH = phylolm(@formula(trait ~ 1), dfr, net, model="scalingHybrid", reml=false) @test lambda_estim(fitSH) ≈ 4.057891910001937 atol=1e-5 end ############################################################################### ### With shifts ############################################################################### @testset "Shifts and Transgressive Evolution" begin global net net = readTopology("(((Ag:5,(#H1:1::0.056,((Ak:2,(E:1,#H2:1::0.004):1):1,(M:2)#H2:1::0.996):1):1):1,(((((Az:1,Ag2:1):1,As:2):1)#H1:1::0.944,Ap:4):1,Ar:5):1):1,(P:4,20:4):3,165:7);"); preorder!(net) ## Simulate params = ParamsBM(10, 0.1, shiftHybrid([3.0, -3.0], net)) Random.seed!(2468); # sets the seed for reproducibility, to debug potential error sim = simulate(net, params) # checks for no error, but not used. # values simulated using julia v1.6.4's RNG hardcoded below. # Y = sim[:Tips] Y = [11.640085037749985, 9.498284887480622, 9.568813792749083, 13.036916724865296, 6.873936265709946, 6.536647349405742, 5.95771939864956, 10.517318306450647, 9.34927049737206, 10.176238483133424, 10.760099940744308, 8.955543827353837] ## Construct regression matrix dfr_shift = regressorShift(net.edge[[8,17]], net) dfr_shift[!,:sum] = vec(sum(Matrix(dfr_shift[:,findall(DataFrames.propertynames(dfr_shift) .!= :tipNames)]), dims=2)) dfr_hybrid = regressorHybrid(net) @test dfr_shift[!,:shift_8] ≈ dfr_hybrid[!,:shift_8] @test dfr_shift[!,:shift_17] ≈ dfr_hybrid[!,:shift_17] @test dfr_shift[!,:sum] ≈ dfr_hybrid[!,:sum] ## Data dfr = DataFrame(trait = Y, tipNames = ["Ag","Ak","E","M","Az","Ag2","As","Ap","Ar","P","20","165"]) # sim.M.tipNames dfr = innerjoin(dfr, dfr_hybrid, on=:tipNames) ## Simple BM fitShift = phylolm(@formula(trait ~ shift_8 + shift_17), dfr, net; reml=false) @test_logs show(devnull, fitShift) ## Test against fixed values lambda models fitlam = phylolm(@formula(trait ~ shift_8 + shift_17), dfr, net, model="lambda", fixedValue=1.0, reml=false) @test lambda_estim(fitlam) ≈ 1.0 @test coef(fitlam) ≈ coef(fitShift) @test vcov(fitlam) ≈ vcov(fitShift) @test nobs(fitlam) ≈ nobs(fitShift) @test residuals(fitlam) ≈ residuals(fitShift) @test response(fitlam) ≈ response(fitShift) @test predict(fitlam) ≈ predict(fitShift) @test dof_residual(fitlam) ≈ dof_residual(fitShift) @test sigma2_phylo(fitlam) ≈ sigma2_phylo(fitShift) @test stderror(fitlam) ≈ stderror(fitShift) @test confint(fitlam) ≈ confint(fitShift) @test loglikelihood(fitlam) ≈ loglikelihood(fitShift) @test dof(fitlam) ≈ dof(fitShift) + 1 @test deviance(fitlam, Val(true)) ≈ deviance(fitShift, Val(true)) @test nulldeviance(fitlam) ≈ nulldeviance(fitShift) @test nullloglikelihood(fitlam) ≈ nullloglikelihood(fitShift) @test r2(fitlam) ≈ r2(fitShift) atol=1e-15 #@test adjr2(fitlam) ≈ adjr2(fitShift) - 0.5 atol=1e-15 @test aic(fitlam) ≈ aic(fitShift) + 2 #@test aicc(fitlam) ≈ aicc(fitShift) @test bic(fitlam) ≈ bic(fitShift) + log(nobs(fitShift)) @test mu_phylo(fitlam) ≈ mu_phylo(fitShift) @test hasintercept(fitlam) fitSH = phylolm(@formula(trait ~ shift_8 + shift_17), dfr, net, model="scalingHybrid", fixedValue=1.0, reml=false) @test loglikelihood(fitlam) ≈ loglikelihood(fitSH) @test aic(fitlam) ≈ aic(fitSH) ## ftest against own naive implementation modnull = phylolm(@formula(trait ~ 1), dfr, net) @test sigma2_phylo(modnull) ≈ 0.6517876326943942 atol=1e-6 # using REML modhom = phylolm(@formula(trait ~ sum), dfr, net) modhet = phylolm(@formula(trait ~ sum + shift_8), dfr, net) #= 3 warnings thrown by ftest, one for each model, because after transforming the data to de-correlate the results, the intercept vector is not ∝ 1. Keep the warnings: because incorrect R² values in the ftest output =# table1 = redirect_stdio(stderr=devnull) do # to avoid seeing the warnings ftest(modhet, modhom, modnull) end table2 = PhyloNetworks.anova(modnull, modhom, modhet) @test table1.fstat[2] ≈ table2[2,:F] @test table1.fstat[3] ≈ table2[1,:F] @test table1.pval[2] ≈ table2[2,Symbol("Pr(>F)")] @test table1.pval[3] ≈ table2[1,Symbol("Pr(>F)")] @test hasintercept(modnull) && hasintercept(modhom) && hasintercept(modhet) @test all(isapprox.(table1.r2, (0.8398130376214782, 0.006032952123011026, 0), atol=1e-15)) # Check that it is the same as doing shift_8 + shift_17 modhetbis = phylolm(@formula(trait ~ shift_8 + shift_17), dfr, net) table2bis = PhyloNetworks.anova(modnull, modhom, modhetbis) @test table2[!,:F] ≈ table2bis[!,:F] @test table2[!,Symbol("Pr(>F)")] ≈ table2bis[!,Symbol("Pr(>F)")] @test table2[!,:dof_res] ≈ table2bis[!,:dof_res] @test table2[!,:RSS] ≈ table2bis[!,:RSS] @test table2[!,:dof] ≈ table2bis[!,:dof] @test table2[!,:SS] ≈ table2bis[!,:SS] # re-fit with ML to do likelihood ratio test modnull = phylolm(@formula(trait ~ 1), dfr, net; reml=false) modhom = phylolm(@formula(trait ~ sum), dfr, net; reml=false) modhet = phylolm(@formula(trait ~ sum + shift_8), dfr, net; reml=false) table3 = (@test_logs lrtest(modhet, modhom, modnull)) @test all(isapprox.(table3.deviance, (25.10067039653046,47.00501928245542,47.0776339693065), atol=1e-6)) @test table3.dof == (4, 3, 2) @test all(isapprox.(table3.pval[2:end], (2.865837220526082e-6,0.7875671600772386), atol=1e-6)) end ################# ### No intercept ################# @testset "No Intercept" begin global net net = readTopology("(((Ag:5,(#H1:1::0.056,((Ak:2,(E:1,#H2:1::0.004):1):1,(M:2)#H2:1::0.996):1):1):1,(((((Az:1,Ag2:1):1,As:2):1)#H1:1::0.944,Ap:4):1,Ar:5):1):1,(P:4,20:4):3,165:7);"); preorder!(net) ## data Y = [11.640085037749985, 9.498284887480622, 9.568813792749083, 13.036916724865296, 6.873936265709946, 6.536647349405742, 5.95771939864956, 10.517318306450647, 9.34927049737206, 10.176238483133424, 10.760099940744308, 8.955543827353837] X = [9.199418112245104, 8.641506886650749, 8.827105915999073, 11.198420342332025, 5.8212242346434655, 6.130520100788492, 5.846098148463377, 9.125593652542882, 10.575371612483897, 9.198463833849347, 9.090317561636194, 9.603570747653789] dfr = DataFrame(trait = Y, reg = X, tipNames = ["Ag","Ak","E","M","Az","Ag2","As","Ap","Ar","P","20","165"]) # sim.M.tipNames phynetlm = phylolm(@formula(trait ~ -1 + reg), dfr, net; reml=false) # Naive version (GLS): most of it hard-coded, but code shown below ntaxa = length(Y) X = phynetlm.X # Vy = phynetlm.Vy; Vyinv = inv(Vy); XtVyinv = X' * Vyinv; logdetVy = logdet(Vy) betahat = [1.073805579608655] # inv(XtVyinv * X) * XtVyinv * Y fittedValues = X * betahat resids = Y - fittedValues # sigma2hat = 1/ntaxa * (resids' * Vyinv * resids) # loglik = - 1 / 2 * (ntaxa + ntaxa * log(2 * pi) + ntaxa * log(sigma2hat) + logdetVy) #= null model: no X, and not even an intercept nullX = zeros(ntaxa, 1); nullresids = Y; nullXtVyinv = nullX' * Vyinv nullsigma2hat = 1/ntaxa * (nullresids' * Vyinv * nullresids) # 6.666261935713196 nullloglik = - 1 / 2 * (ntaxa + ntaxa * log(2 * pi) + ntaxa * log(nullsigma2hat) + logdetVy) # -38.01145980802529 =# @test coef(phynetlm) ≈ betahat @test nobs(phynetlm) ≈ 12 # ntaxa @test residuals(phynetlm) ≈ resids @test response(phynetlm) ≈ Y @test predict(phynetlm) ≈ fittedValues @test dof_residual(phynetlm) ≈ 11 # ntaxa-length(betahat) @test sigma2_phylo(phynetlm) ≈ 0.1887449836519979 # sigma2hat @test loglikelihood(phynetlm) ≈ -16.6249533603196 # loglik @test vcov(phynetlm) ≈ [0.003054397019042955;;] # sigma2hat*ntaxa/(ntaxa-length(betahat))*inv(XtVyinv * X) @test stderror(phynetlm) ≈ [0.05526659948868715] # sqrt.(diag(sigma2hat*ntaxa/(ntaxa-length(betahat))*inv(XtVyinv * X))) @test dof(phynetlm) ≈ 2 # length(betahat)+1 @test deviance(phynetlm, Val(true)) ≈ 2.264939803823975 # sigma2hat * ntaxa @test nulldeviance(phynetlm) ≈ 79.99514322855836 # nullsigma2hat * ntaxa @test nullloglikelihood(phynetlm) ≈ -38.01145980802529 # nullloglik @test r2(phynetlm) ≈ 0.9716865335517596 # 1-sigma2hat / nullsigma2hat @test adjr2(phynetlm) ≈ 0.9716865335517596 atol=1e-15 # 1 - (1 - (1-sigma2hat/nullsigma2hat))*(ntaxa-1)/(ntaxa-length(betahat)) @test aic(phynetlm) ≈ 37.2499067206392 # -2*loglik+2*(length(betahat)+1) @test aicc(phynetlm) ≈ 38.58324005397254 # -2*loglik+2*(length(betahat)+1)+2(length(betahat)+1)*((length(betahat)+1)+1)/(ntaxa-(length(betahat)+1)-1) @test bic(phynetlm) ≈ 38.219720020215206 # -2*loglik+(length(betahat)+1)*log(ntaxa) @test !hasintercept(phynetlm) end ############################################################################### #### Other Network ############################################################################### @testset "phylolm and ancestralStateReconstruction" begin global net # originally: "(((Ag,(#H1:7.159::0.056,((Ak,(E:0.08,#H2:0.0::0.004):0.023):0.078,(M:0.0)#H2:::0.996):2.49):2.214):0.026,(((((Az:0.002,Ag2:0.023):2.11,As:2.027):1.697)#H1:0.0::0.944,Ap):0.187,Ar):0.723):5.943,(P,20):1.863,165);" # followed by changes in net.edge[?].length values to make the network ultrametric net = readTopology("(((Ag:5,(#H1:1::0.056,((Ak:2,(E:1,#H2:1::0.004):1):1,(M:2)#H2:1::0.996):1):1):1,(((((Az:1,Ag2:1):1,As:2):1)#H1:1::0.944,Ap:4):1,Ar:5):1):1,(P:4,20:4):3,165:7);"); #= Simulate correlated data in data frames b0 = 1 b1 = 10 Random.seed!(5678) sim = simulate(net, ParamsBM(1, 1)) A = sim[:Tips] B = b0 .+ b1 * A .+ simulate(net, ParamsBM(0, 0.1))[:Tips] tipnam = sim.M.tipNames =# A = [2.626609842049044,0.6334773804400937,3.0577676668430476,0.8570052897626761,3.3415290038076875,2.7038939422417467,1.8694860778492748,3.354373836136418,7.436775409527188,2.6659127435884318,3.2298992674067417,-2.2323810599565013] B = [27.60133970558981,8.228820310098914,32.42043423853238,10.249417359958978,33.52061781961048,27.008691929589997,19.11541648307886,35.38758567184537,75.04861071222199,27.68624399802581,33.03778377357321,-20.4001107607967] tipnam = ["Ag","Ak","E","M","Az","Ag2","As","Ap","Ar","P","20","165"] # With Matrices X = hcat(ones(12), A) fit_mat = phylolm(X, B, net; reml=false) #@show fit_mat # Naive version (GLS) ntaxa = length(B) Vy = fit_mat.Vy Vyinv = inv(Vy) XtVyinv = X' * Vyinv logdetVy = logdet(Vy) betahat = inv(XtVyinv * X) * XtVyinv * B fittedValues = X * betahat resids = B - fittedValues sigma2hat = 1/ntaxa * (resids' * Vyinv * resids) # log likelihood loglik = - 1 / 2 * (ntaxa + ntaxa * log(2 * pi) + ntaxa * log(sigma2hat) + logdetVy) # null version nullX = ones(ntaxa, 1) nullXtVyinv = nullX' * Vyinv nullresids = B - nullX * inv(nullXtVyinv * nullX) * nullXtVyinv * B nullsigma2hat = 1/ntaxa * (nullresids' * Vyinv * nullresids) nullloglik = - 1 / 2 * (ntaxa + ntaxa * log(2 * pi) + ntaxa * log(nullsigma2hat) + logdetVy) @test coef(fit_mat) ≈ betahat @test nobs(fit_mat) ≈ ntaxa @test residuals(fit_mat) ≈ resids @test response(fit_mat) ≈ B @test predict(fit_mat) ≈ fittedValues @test dof_residual(fit_mat) ≈ ntaxa-length(betahat) @test sigma2_phylo(fit_mat) ≈ sigma2hat @test loglikelihood(fit_mat) ≈ loglik @test vcov(fit_mat) ≈ sigma2hat*ntaxa/(ntaxa-length(betahat)).*inv(XtVyinv * X) @test stderror(fit_mat) ≈ sqrt.(diag(sigma2hat*ntaxa/(ntaxa-length(betahat)).*inv(XtVyinv * X))) @test dof(fit_mat) ≈ length(betahat)+1 @test deviance(fit_mat, Val(true)) ≈ sigma2hat * ntaxa @test nulldeviance(fit_mat) ≈ nullsigma2hat * ntaxa @test nullloglikelihood(fit_mat) ≈ nullloglik @test r2(fit_mat) ≈ 1-sigma2hat / nullsigma2hat atol=1e-15 @test adjr2(fit_mat) ≈ 1 - (1 - (1-sigma2hat/nullsigma2hat))*(ntaxa-1)/(ntaxa-length(betahat)) atol=1e-15 @test aic(fit_mat) ≈ -2*loglik+2*(length(betahat)+1) @test aicc(fit_mat) ≈ -2*loglik+2*(length(betahat)+1)+2(length(betahat)+1)*((length(betahat)+1)+1)/(ntaxa-(length(betahat)+1)-1) @test bic(fit_mat) ≈ -2*loglik+(length(betahat)+1)*log(ntaxa) ## perfect user using right format and formula dfr = DataFrame(trait=B, pred=A, tipNames=tipnam) phynetlm = phylolm(@formula(trait ~ pred), dfr, net; reml=false) #@show phynetlm @test coef(phynetlm) ≈ coef(fit_mat) @test vcov(phynetlm) ≈ vcov(fit_mat) @test nobs(phynetlm) ≈ nobs(fit_mat) @test residuals(phynetlm) ≈ residuals(fit_mat) @test response(phynetlm) ≈ response(fit_mat) @test predict(phynetlm) ≈ predict(fit_mat) @test dof_residual(phynetlm) ≈ dof_residual(fit_mat) @test sigma2_phylo(phynetlm) ≈ sigma2_phylo(fit_mat) @test stderror(phynetlm) ≈ stderror(fit_mat) @test confint(phynetlm) ≈ confint(fit_mat) @test loglikelihood(phynetlm) ≈ loglikelihood(fit_mat) @test dof(phynetlm) ≈ dof(fit_mat) @test deviance(phynetlm, Val(true)) ≈ deviance(fit_mat, Val(true)) @test nulldeviance(phynetlm) ≈ nulldeviance(fit_mat) @test nullloglikelihood(phynetlm) ≈ nullloglikelihood(fit_mat) @test r2(phynetlm) ≈ r2(fit_mat) @test adjr2(phynetlm) ≈ adjr2(fit_mat) @test aic(phynetlm) ≈ aic(fit_mat) @test aicc(phynetlm) ≈ aicc(fit_mat) @test bic(phynetlm) ≈ bic(fit_mat) # Deprecated methods @test (@test_logs (:warn,r"^accessing") phynetlm.model) === phynetlm @test (@test_logs (:warn,r"^accessing") phynetlm.mf.f) == formula(phynetlm) @test (@test_logs (:warn,r"^accessing") phynetlm.mm.m) == modelmatrix(phynetlm) # unordered data dfr = dfr[[2,6,10,5,12,7,4,11,1,8,3,9], :] fitbis = phylolm(@formula(trait ~ pred), dfr, net; reml=false) @test coef(phynetlm) ≈ coef(fitbis) @test vcov(phynetlm) ≈ vcov(fitbis) @test nobs(phynetlm) ≈ nobs(fitbis) @test residuals(phynetlm)[fitbis.ind] ≈ residuals(fitbis) @test response(phynetlm)[fitbis.ind] ≈ response(fitbis) @test predict(phynetlm)[fitbis.ind] ≈ predict(fitbis) @test dof_residual(phynetlm) ≈ dof_residual(fitbis) @test sigma2_phylo(phynetlm) ≈ sigma2_phylo(fitbis) @test stderror(phynetlm) ≈ stderror(fitbis) @test confint(phynetlm) ≈ confint(fitbis) @test loglikelihood(phynetlm) ≈ loglikelihood(fitbis) @test dof(phynetlm) ≈ dof(fitbis) @test deviance(phynetlm, Val(true)) ≈ deviance(fitbis, Val(true)) @test nulldeviance(phynetlm) ≈ nulldeviance(fitbis) @test nullloglikelihood(phynetlm) ≈ nullloglikelihood(fitbis) @test r2(phynetlm) ≈ r2(fitbis) @test adjr2(phynetlm) ≈ adjr2(fitbis) @test aic(phynetlm) ≈ aic(fitbis) @test aicc(phynetlm) ≈ aicc(fitbis) @test bic(phynetlm) ≈ bic(fitbis) @test mu_phylo(phynetlm) ≈ mu_phylo(fitbis) # unnamed ordered data dfr = DataFrame(trait = B, pred = A) fitter = (@test_logs (:info, r"^As requested \(no_names=true\)") match_mode=:any phylolm(@formula(trait ~ pred), dfr, net, no_names=true, reml=false)) @test coef(phynetlm) ≈ coef(fitter) @test vcov(phynetlm) ≈ vcov(fitter) @test nobs(phynetlm) ≈ nobs(fitter) @test residuals(phynetlm) ≈ residuals(fitter) @test response(phynetlm) ≈ response(fitter) @test predict(phynetlm) ≈ predict(fitter) @test dof_residual(phynetlm) ≈ dof_residual(fitter) @test sigma2_phylo(phynetlm) ≈ sigma2_phylo(fitter) @test stderror(phynetlm) ≈ stderror(fitter) @test confint(phynetlm) ≈ confint(fitter) @test loglikelihood(phynetlm) ≈ loglikelihood(fitter) @test dof(phynetlm) ≈ dof(fitter) @test deviance(phynetlm, Val(true)) ≈ deviance(fitter, Val(true)) @test nulldeviance(phynetlm) ≈ nulldeviance(fitter) @test nullloglikelihood(phynetlm) ≈ nullloglikelihood(fitter) @test r2(phynetlm) ≈ r2(fitter) @test adjr2(phynetlm) ≈ adjr2(fitter) @test aic(phynetlm) ≈ aic(fitter) @test aicc(phynetlm) ≈ aicc(fitter) @test bic(phynetlm) ≈ bic(fitter) # unnamed un-ordered data dfr = dfr[[9,6,5,10,1,11,12,7,2,3,8,4], :] @test_throws ErrorException phylolm(@formula(trait ~ pred), dfr, net) # Wrong pred ### Add NAs dfr = DataFrame(trait=B, pred=A, tipNames=tipnam) allowmissing!(dfr, :pred) dfr[[2, 8, 11], :pred] .= missing fitna = phylolm(@formula(trait ~ pred), dfr, net) #@show fitna dfr = dfr[[8,2,3,4,6,10,9,1,11,12,7,5], :] fitnabis = phylolm(@formula(trait ~ pred), dfr, net) @test coef(fitna) ≈ coef(fitnabis) @test vcov(fitna) ≈ vcov(fitnabis) @test nobs(fitna) ≈ nobs(fitnabis) @test sort(residuals(fitna)) ≈ sort(residuals(fitnabis)) @test sort(response(fitna)) ≈ sort(response(fitnabis)) @test sort(predict(fitna)) ≈ sort(predict(fitnabis)) @test dof_residual(fitna) ≈ dof_residual(fitnabis) @test sigma2_phylo(fitna) ≈ sigma2_phylo(fitnabis) @test stderror(fitna) ≈ stderror(fitnabis) @test confint(fitna) ≈ confint(fitnabis) @test loglikelihood(fitna) ≈ loglikelihood(fitnabis) @test dof(fitna) ≈ dof(fitnabis) @test deviance(fitna, Val(true)) ≈ deviance(fitnabis, Val(true)) @test nulldeviance(fitna) ≈ nulldeviance(fitnabis) @test (@test_logs (:warn, r"^ML") nullloglikelihood(fitna)) ≈ (@test_logs (:warn, r"^ML") nullloglikelihood(fitnabis)) @test r2(fitna) ≈ r2(fitnabis) @test adjr2(fitna) ≈ adjr2(fitnabis) @test aic(fitna) ≈ aic(fitnabis) @test aicc(fitna) ≈ aicc(fitnabis) @test bic(fitna) ≈ bic(fitnabis) ## Tests against fixed values parameters fitlam = phylolm(@formula(trait ~ pred), dfr, net, model="lambda", fixedValue=1.0) #@show fitlam @test lambda_estim(fitlam) ≈ 1.0 @test coef(fitlam) ≈ coef(fitnabis) @test vcov(fitlam) ≈ vcov(fitnabis) @test nobs(fitlam) ≈ nobs(fitnabis) @test residuals(fitlam) ≈ residuals(fitnabis) @test response(fitlam) ≈ response(fitnabis) @test predict(fitlam) ≈ predict(fitnabis) @test dof_residual(fitlam) ≈ dof_residual(fitnabis) @test sigma2_phylo(fitlam) ≈ sigma2_phylo(fitnabis) @test stderror(fitlam) ≈ stderror(fitnabis) @test confint(fitlam) ≈ confint(fitnabis) @test loglikelihood(fitlam) ≈ loglikelihood(fitnabis) @test dof(fitlam) ≈ dof(fitnabis) + 1 @test deviance(fitlam, Val(true)) ≈ deviance(fitnabis, Val(true)) @test nulldeviance(fitlam) ≈ nulldeviance(fitnabis) @test (@test_logs (:warn, r"^ML") nullloglikelihood(fitlam)) ≈ (@test_logs (:warn, r"^ML") nullloglikelihood(fitnabis)) @test r2(fitlam) ≈ r2(fitnabis) atol=1e-15 @test adjr2(fitlam)-1 ≈ (adjr2(fitnabis)-1)*(nobs(fitnabis)-dof(fitnabis)+1)/(nobs(fitnabis)-dof(fitlam)+1) atol=1e-15 @test aic(fitlam) ≈ aic(fitnabis) + 2 #@test aicc(fitlam) ≈ aicc(fitnabis) @test bic(fitlam) ≈ bic(fitnabis) + log(nobs(fitnabis)) @test mu_phylo(fitlam) ≈ mu_phylo(fitnabis) fitSH = phylolm(@formula(trait ~ pred), dfr, net, model="scalingHybrid", fixedValue=1.0) @test loglikelihood(fitlam) ≈ loglikelihood(fitSH) @test aic(fitlam) ≈ aic(fitSH) ## Pagel's Lambda fitlam = (@test_logs (:info, r"^Maximum lambda value") match_mode=:any phylolm(@formula(trait ~ pred), dfr, net, model="lambda", reml=false)) #@show fitlam @test lambda_estim(fitlam) ≈ 1.1135518305 atol=1e-6 ## scaling Hybrid fitSH = phylolm(@formula(trait ~ pred), dfr, net, model="scalingHybrid", reml=false) @test_logs show(devnull, fitSH) @test lambda_estim(fitSH) ≈ -52.81305448333567 atol=1e-6 ### Ancestral State Reconstruction params = ParamsBM(3, 1) # sim = simulate(net, params); Y = sim[:Tips]; tipnam=tipLabels(sim) Y = [7.49814057852738,7.713232061975018,7.4314117011628795,0.9850885689559203,4.970152778471174,5.384066549416034,4.326644522544125,0.6079385242666691,4.084254785718834,5.501648315448596,3.8732700346136597,4.790127215808698] tipnam = ["Ag","Ak","E","M","Az","Ag2","As","Ap","Ar","P","20","165"] # From known parameters ancestral_traits = ancestralStateReconstruction(net, Y, params) # BLUP dfr = DataFrame(trait=Y, tipNames=tipnam) phynetlm = phylolm(@formula(trait~1), dfr, net) # prediction intervals larger with reml=true than with reml=false blup = (@test_logs (:warn, r"^These prediction intervals show uncertainty in ancestral values") ancestralStateReconstruction(phynetlm)); # plot(net, blup) @test_logs show(devnull, blup) # BLUP same, using the function directly blup_bis = (@test_logs (:warn, r"^These prediction intervals show uncertainty in ancestral values") match_mode=:any ancestralStateReconstruction(dfr, net)); @test expectations(blup)[!,:condExpectation] ≈ expectations(blup_bis)[!,:condExpectation] @test expectations(blup)[!,:nodeNumber] ≈ expectations(blup_bis)[!,:nodeNumber] @test blup.traits_tips ≈ blup_bis.traits_tips @test blup.TipNumbers ≈ blup_bis.TipNumbers @test predint(blup) ≈ predint(blup_bis) @test predintPlot(blup)[!,:PredInt] == predintPlot(blup_bis)[!,:PredInt] @test predintPlot(blup, withExp=true)[!,:PredInt] == predintPlot(blup_bis, withExp=true)[!,:PredInt] @test expectationsPlot(blup)[!,:PredInt] == expectationsPlot(blup_bis)[!,:PredInt] dfr = DataFrame(trait=Y, tipNames=tipnam, reg=Y) @test_throws ErrorException ancestralStateReconstruction(dfr, net) # cannot handle a predictor # Unordered dfr2 = dfr[[5,4,9,2,6,12,8,11,7,1,3,10], :] phynetlm = phylolm(@formula(trait~1), dfr2, net) blup2 = (@test_logs (:warn, r"^These prediction intervals show uncertainty in ancestral values") ancestralStateReconstruction(phynetlm)) @test expectations(blup)[1:length(blup.NodeNumbers),:condExpectation] ≈ expectations(blup2)[1:length(blup.NodeNumbers),:condExpectation] @test blup.traits_tips[phynetlm.ind] ≈ blup2.traits_tips @test blup.TipNumbers[phynetlm.ind] ≈ blup2.TipNumbers @test predint(blup)[1:length(blup.NodeNumbers), :] ≈ predint(blup2)[1:length(blup.NodeNumbers), :] # With unknown tips allowmissing!(dfr, :trait) dfr[[2, 4], :trait] .= missing phynetlm = phylolm(@formula(trait~1), dfr, net) blup = (@test_logs (:warn, r"^These prediction intervals show uncertainty in ancestral values") ancestralStateReconstruction(phynetlm)) # plot(net, blup) # Unordered dfr2 = dfr[[1, 2, 5, 3, 4, 6, 7, 8, 9, 10, 11, 12], :] phynetlm = phylolm(@formula(trait~1), dfr, net) blup2 = (@test_logs (:warn, r"^These prediction intervals show uncertainty in ancestral values") ancestralStateReconstruction(phynetlm)) @test expectations(blup)[!,:condExpectation] ≈ expectations(blup2)[!,:condExpectation] @test predint(blup) ≈ predint(blup2) @test predintPlot(blup)[!,:PredInt] == predintPlot(blup2)[!,:PredInt] @test predintPlot(blup, withExp=true)[!,:PredInt] == predintPlot(blup2, withExp=true)[!,:PredInt] # Test mark on missing ee = expectationsPlot(blup) predMiss = ee[indexin([n.number for n in net.leaf][[2,4]], ee[!,:nodeNumber]),:PredInt] for pp = predMiss @test pp[end] == '*' end end ################# ## Data with no phylogenetic signal ################# @testset "lambda when no signal" begin global net net = readTopology("(((Ag:5,(#H1:1::0.056,((Ak:2,(E:1,#H2:1::0.004):1):1,(M:2)#H2:1::0.996):1):1):1,(((((Az:1,Ag2:1):1,As:2):1)#H1:1::0.944,Ap:4):1,Ar:5):1):1,(P:4,20:4):3,165:7);"); #= Simulate correlated data in data frames b0 = 1 b1 = 10 Random.seed!(5678); A = randn(size(tipLabels(net), 1)) B = b0 .+ (b1 .* A + randn(size(tipLabels(net), 1))) =# A = [-1.2217252038914663, 0.8431411538631137, 0.3847679754817904, 0.10277471357263539, 1.0944221266744778, 2.053347250198844, 1.4708882134841876, 1.1056475371071361, -0.94952153892202, -0.3477162381565148, -0.2742415177451819, 0.25034046948064764] B = [-9.849415384443805, 10.765309004952346, 4.8269904926118565, 1.7279441642635127, 11.535570136728504, 20.16670120778599, 13.971404727143286, 13.019084912634444, -8.278125099304921, -4.784290010378141, -2.537139017477904, 2.9460706727827755] dfr = DataFrame(trait = B, pred = A, tipNames = tipLabels(net)) ## Network phynetlm = (@test_logs (:info, r"^Maximum lambda value") match_mode=:any phylolm(@formula(trait ~ pred), dfr, net, model="lambda", reml=false)) @test lambda_estim(phynetlm) ≈ 0.5894200143 atol=1e-8 # using REML phynetlm = (@test_logs (:info, r"^Max") phylolm(@formula(trait ~ pred), dfr, net, model="lambda")) @test lambda_estim(phynetlm) ≈ 0.8356905283 atol=1e-8 ## Major Tree global tree tree = majorTree(net) phynetlm = (@test_logs (:info, r"^Maximum lambda value") match_mode=:any phylolm(@formula(trait ~ pred), dfr, tree, model="lambda", reml=false)) @test lambda_estim(phynetlm) ≈ 0.5903394415 atol=1e-6 ## scaling Hybrid lmtree = phylolm(@formula(trait ~ pred), dfr, tree, model = "BM") lmnet = phylolm(@formula(trait ~ pred), dfr, net, model = "BM") lmSHzero = phylolm(@formula(trait ~ pred), dfr, net, model = "scalingHybrid", fixedValue = 0.0) lmSHone = phylolm(@formula(trait ~ pred), dfr, net, model = "scalingHybrid", fixedValue = 1.0) @test loglikelihood(lmtree) ≈ loglikelihood(lmSHzero) @test loglikelihood(lmnet) ≈ loglikelihood(lmSHone) lmSH = phylolm(@formula(trait ~ pred), dfr, net, model="scalingHybrid", reml=false) @test lambda_estim(lmSH) ≈ 23.46668204551696 atol=1e-5 lmSH = phylolm(@formula(trait ~ pred), dfr, net, model="scalingHybrid") @test lambda_estim(lmSH) ≈ 24.61373831478016 atol=1e-5 # λ so large?? largest γ = 0.056, so λγ = 1.34 is > 1... end ############################################################################### ### Undefined branch lengths ############################################################################### @testset "Undefined branch length" begin ## No branch length net = readTopology("(A:2.5,((B,#H1:1::0.1):1,(C:1,(D:1)#H1:1::0.9):1):0.5);"); dfr = DataFrame(trait = [11.6,8.1,10.3,9.1], tipNames = ["A","B","C","D"]); @test_throws ErrorException("""Branch(es) number 2 have no length. The variance-covariance matrix of the network is not defined. A phylogenetic regression cannot be done.""") phylolm(@formula(trait ~ 1), dfr, net); ## Negative branch length net.edge[2].length = -0.5; @test_throws ErrorException("""Branch(es) number 2 have negative length. The variance-covariance matrix of the network is not defined. A phylogenetic regression cannot be done.""") phylolm(@formula(trait ~ 1), dfr, net); ## Zero branch length: allowed net.edge[2].length = 0.0; fit = phylolm(@formula(trait ~ 1), dfr, net); @test loglikelihood(fit) ≈ -6.245746681512051 net.edge[2].length = 0.1; # back to non-zero ## Illicit zero length for 1st edge: from root to single "outgroup" taxon net.edge[1].length = 0.0; @test_throws PosDefException phylolm(@formula(trait ~ 1), dfr, net); end ############################ ## Against no regressor ########################### #= fixit: passes with GML up to v1.3, fails with GLM v1.4. `lm()` has by default # `allowrankdeficient=false` in v1.3, but `dropcollinear=true` in v1.4 # We would need `dropcollinear=false` in this test. fixit later: pass kwargs... ? # no predictors, so REML = ML in this case @testset "phylolm with no regressor" begin global net net = readTopology("(((Ag:5,(#H1:1::0.056,((Ak:2,(E:1,#H2:1::0.004):1):1,(M:2)#H2:1::0.996):1):1):1,(((((Az:1,Ag2:1):1,As:2):1)#H1:1::0.944,Ap:4):1,Ar:5):1):1,(P:4,20:4):3,165:7);"); params = ParamsBM(10, 1) Random.seed!(2468) # sets the seed for reproducibility, to debug potential error sim = simulate(net, params) Y = sim[:Tips] phynetlm = phylolm(zeros(length(Y),0), Y, net) #@show phynetlm # Naive version (GLS) ntaxa = length(Y) Vy = phynetlm.Vy Vyinv = inv(Vy) logdetVy = logdet(Vy) fittedValues = zeros(length(Y)) resids = Y - fittedValues sigma2hat = 1/ntaxa * (resids' * Vyinv * resids) # log likelihood loglik = - 1 / 2 * (ntaxa + ntaxa * log(2 * pi) + ntaxa * log(sigma2hat) + logdetVy) # null version nullX = ones(ntaxa, 1) nullXtVyinv = nullX' * Vyinv nullresids = Y - nullX * inv(nullXtVyinv * nullX) * nullXtVyinv * Y nullsigma2hat = 1/ntaxa * (nullresids' * Vyinv * nullresids) nullloglik = - 1 / 2 * (ntaxa + ntaxa * log(2 * pi) + ntaxa * log(nullsigma2hat) + logdetVy) @test nobs(phynetlm) ≈ ntaxa @test residuals(phynetlm) ≈ resids @test response(phynetlm) ≈ Y @test predict(phynetlm) ≈ fittedValues @test dof_residual(phynetlm) ≈ ntaxa @test sigma2_phylo(phynetlm) ≈ sigma2hat @test loglikelihood(phynetlm) ≈ loglik @test deviance(phynetlm, Val(true)) ≈ sigma2hat * ntaxa @test nulldeviance(phynetlm) ≈ nullsigma2hat * ntaxa @test nullloglikelihood(phynetlm) ≈ nullloglik @test r2(phynetlm) ≈ 1-sigma2hat / nullsigma2hat atol=1e-14 @test adjr2(phynetlm) ≈ 1 - (1 - (1-sigma2hat/nullsigma2hat))*(ntaxa-1)/(ntaxa) atol=1e-14 @test aic(phynetlm) ≈ -2*loglik+2*(1) @test aicc(phynetlm) ≈ -2*loglik+2*(1)+2(1)*((1)+1)/(ntaxa-(1)-1) @test bic(phynetlm) ≈ -2*loglik+(1)*log(ntaxa) # with data frames dfr = DataFrame(trait = Y, tipNames = sim.M.tipNames) fitbis = phylolm(@formula(trait ~ -1), dfr, net) @test_logs show(devnull, fitbis) #@test coef(phynetlm) ≈ coef(fitbis) #@test vcov(phynetlm) ≈ vcov(fitbis) @test nobs(phynetlm) ≈ nobs(fitbis) @test residuals(phynetlm)[fitbis.ind] ≈ residuals(fitbis) @test response(phynetlm)[fitbis.ind] ≈ response(fitbis) @test predict(phynetlm)[fitbis.ind] ≈ predict(fitbis) @test dof_residual(phynetlm) ≈ dof_residual(fitbis) @test sigma2_phylo(phynetlm) ≈ sigma2_phylo(fitbis) #@test stderror(phynetlm) ≈ stderror(fitbis) #@test confint(phynetlm) ≈ confint(fitbis) @test loglikelihood(phynetlm) ≈ loglikelihood(fitbis) #@test dof(phynetlm) ≈ dof(fitbis) @test deviance(phynetlm, Val(true)) ≈ deviance(fitbis, Val(true)) @test nulldeviance(phynetlm) ≈ nulldeviance(fitbis) @test nullloglikelihood(phynetlm) ≈ nullloglikelihood(fitbis) @test r2(phynetlm) ≈ r2(fitbis) atol=1e-15 @test adjr2(phynetlm) ≈ adjr2(fitbis) atol=1e-15 @test aic(phynetlm) ≈ aic(fitbis) @test aicc(phynetlm) ≈ aicc(fitbis) @test bic(phynetlm) ≈ bic(fitbis) #@test mu_phylo(phynetlm) mu_phylo(fitbis) end =#
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
26218
# Test of phylolm on trees ############################################################################### ## Caudata dataset - shared paths matrix ############################################################################### @testset "phylolm: Caudata Dataset" begin ## Export "caudata" dataset (from geiger) phy = readTopology(joinpath(@__DIR__, "..", "examples", "caudata_tree.txt")); V = sharedPathMatrix(phy); VR = DataFrame(CSV.File(joinpath(@__DIR__,"..","examples","caudata_shared_paths.txt")); copycols=false) VR = Matrix(VR); # Tips @test V[:Tips] ≈ VR[1:197, 1:197] # Internal nodes intnodes_in_VR = -V.internalNodeNumbers .+ 196 @test V[:InternalNodes] ≈ VR[intnodes_in_VR, intnodes_in_VR] # tips in rows, internal nodes in columns @test V[:TipsNodes] ≈ VR[1:197, intnodes_in_VR] ### R Code to get those results # library(geiger) # ## Load data caudata (salamanders) # data("caudata") # ## Save tree # write.tree(caudata$phy, file = "caudata_tree.txt", append = FALSE, # digits = 10, tree.names = FALSE) # # ## Times shared # V <- node.depth.edgelength(caudata$phy) # prac <- mrca(caudata$phy, full = TRUE) # V <- matrix(V[prac], dim(prac)) # write.table(V, # file = "caudata_shared_paths.txt", # sep = ",", row.names = FALSE, # col.names = TRUE) ############################################################################### ## Caudata dataset - BM ############################################################################### ## Export "caudata" dataset (from geiger) phy = readTopology(joinpath(@__DIR__, "..", "examples", "caudata_tree.txt")); dat = DataFrame(CSV.File(joinpath(@__DIR__,"..","examples","caudata_trait.txt")); copycols=false); ## Fit a BM fitBM = phylolm(@formula(trait ~ 1), dat, phy; reml=false) # Tests against results obtained with geiger::fitContinuous or phylolm::phylolm @test loglikelihood(fitBM) ≈ -78.9611507833 atol=1e-10 @test dof(fitBM) ≈ 2.0 atol=1e-10 @test aic(fitBM) ≈ 161.9223015666 atol=1e-10 @test aicc(fitBM) ≈ 161.9841572367 atol=1e-10 @test coef(fitBM) ≈ [4.6789989001] atol=1e-8 @test vcov(fitBM) ≈ [0.1093144100] atol=1e-10 @test nobs(fitBM) ≈ 197.0 atol=1e-10 @test sum(residuals(fitBM)) ≈ -115.5767321312 atol=1e-8 @test dof_residual(fitBM) ≈ 196.0 atol=1e-10 @test sigma2_phylo(fitBM) ≈ 0.0029452097 atol=1e-10 @test stderror(fitBM) ≈ [0.3306272978] atol=1e-10 @test confint(fitBM)[1] ≈ 4.0269551772 atol=1e-10 @test confint(fitBM)[2] ≈ 5.3310426231 atol=1e-10 @test predict(fitBM) ≈ [4.6789989001 for i in 1:197] atol=1e-8 ### Ancestral state reconstruction (with Rphylopars) anc = (@test_logs (:warn, r"^These prediction intervals show uncertainty in ancestral values") ancestralStateReconstruction(fitBM)); ancR = DataFrame(CSV.File(joinpath(@__DIR__,"..","examples","caudata_Rphylopars.txt")); copycols=false) ## Expectations expe = expectations(anc) expeR = ancR[!,:trait] # Matching tips ? tipsR = expeR[expe[197:393, :nodeNumber]] tipsJulia = expe[197:393, :condExpectation] @test tipsR ≈ tipsJulia # Matching nodes ? nodesR = expeR[-expe[1:196, :nodeNumber] .+ 196] nodesJulia = expe[1:196, :condExpectation] # below: print for when the test was broken #@show nodesR[1:6], nodesR[190:end] #@show nodesJulia[1:6],nodesJulia[190:end] @test isapprox(nodesR, nodesJulia) ## Variances vars = diag(anc.variances_nodes) # Rphylopars varsR = ancR[!,:var] # Matching nodes ? nodesR = varsR[-expe[1:196, :nodeNumber] .+ 196] @test nodesR ≈ vars atol=1e-3 ## RK: Small tol !! ### Ancestral state reconstruction (with Phytools) ancRt = DataFrame(CSV.File(joinpath(@__DIR__,"..","examples","caudata_Phytools.txt")); copycols=false); ## Expectations expe = expectations(anc) expeRt = ancRt[!,:trait] # Matching nodes ? nodesRt = expeRt[-expe[1:196, :nodeNumber] .+ (196 - 197)] nodesJulia = expe[1:196, :condExpectation] # below: print for when the test was broken #@show nodesRt[1:6], nodesRt[190:end] #@show nodesJulia[1:6],nodesJulia[190:end] @test isapprox(nodesRt, nodesJulia) ## Variances vars = diag(anc.variances_nodes) # Rphylopars varsRt = ancRt[!,:var] # Matching nodes ? nodesRt = varsRt[-expe[1:196, :nodeNumber] .+ (196 - 197)] @test nodesRt ≈ vars atol=2e-3 ## RK: Small tol !! ### Comparison between Rphylopars and Phytools: @test nodesRt ≈ nodesR atol=0.003 ## RK: Small tol !! ### R script to get the above values: # library(geiger) # # ## Load data caudata (salamanders) # data("caudata") # # ## Save tree and data # write.tree(caudata$phy, file = "caudata_tree.txt", append = FALSE, # digits = 10, tree.names = FALSE) # # write.table(data.frame(tipsNames = names(caudata$dat), # trait = unname(caudata$dat)), # file = "caudata_trait.txt", # sep = ",", row.names = FALSE) # # ## Fit using Geiger # fitgeiger <- fitContinuous(caudata$phy, caudata$dat, model = "BM") # # ## Fit using phylolm # library(phylolm) # fitphylolm <- phylolm(trait ~ 1, # data.frame(trait = caudata$dat), # caudata$phy, model = "BM") # # ## Fit using Rphylopars # library(Rphylopars) # fitphylopars <- phylopars(data.frame(species = names(caudata$dat), # trait = unname(caudata$dat)), # caudata$phy, # pheno_error = FALSE, # pheno_correlated = FALSE, # REML = FALSE) # # # Save results of Rphylopars for ancestral trait reconstruction # write.table(data.frame(trait = unname(fitphylopars$anc_recon), # var = unname(fitphylopars$anc_var)), # file = "caudata_Rphylopars.txt", # sep = ",", row.names = FALSE) # # ## Ancestral State reconstruction using phytools # library(phytools) # fitphytools <- fastAnc(caudata$phy, caudata$dat, vars = TRUE) # # # Save results of Rphylopars for ancestral trait reconstruction # write.table(data.frame(trait = unname(fitphytools$ace), # var = unname(fitphytools$var)), # file = "caudata_Phytools.txt", # sep = ",", row.names = FALSE) # # ## Quantities to compare # sprintf("%.10f", fitgeiger$opt$ln) # log likelihood # sprintf("%.10f", fitphylolm$logLik) # sprintf("%.10f", fitphylopars$logLik) # sprintf("%.10f", fitgeiger$opt$aic) # aic # sprintf("%.10f", fitphylolm$aic) # sprintf("%.10f", fitgeiger$opt$aicc) # aicc # sprintf("%.10f", fitphylolm$coefficients) # coef # sprintf("%.10f", fitgeiger$opt$z0) # sprintf("%.10f", fitphylopars$mu) # sprintf("%.10f", fitphylolm$vcov) # vcov # sprintf("%.10f", fitphylolm$n) # nobs # sprintf("%.10f", sum(fitphylolm$residuals)) # residuals (sum) # sprintf("%.10f", fitphylolm$n - fitphylolm$d) # df residuals # sprintf("%.10f", fitphylolm$sigma2) # sigma 2 # sprintf("%.10f", fitgeiger$opt$sigsq) # sprintf("%.10f", fitphylopars$pars$phylocov) # sprintf("%.10f", summary(fitphylolm)$coefficients[2]) # std error # sprintf("%.10f", summary(fitphylolm)$df) # df # sprintf("%.10f", fitgeiger$opt$k) # sprintf("%.10f", coef(fitphylolm) + summary(fitphylolm)$coefficients[2] * qt(0.025, 196)) # sprintf("%.10f", coef(fitphylolm) + summary(fitphylolm)$coefficients[2] * qt(0.975, 196)) # sprintf("%.10f", predict(fitphylolm)) # df ############################################################################### ## Caudata dataset - Pagel's lambda ############################################################################### ## Fit Pagel's lambda fitLambda = (@test_logs (:info, r"^Maximum lambda value") match_mode=:any phylolm(@formula(trait ~ 1), dat, phy, model = "lambda", reml=false)); @test lambda_estim(fitLambda) ≈ 0.9193 atol=1e-4 # Due to convergence issues, tolerance is lower. @test loglikelihood(fitLambda) ≈ -51.684379 atol=1e-6 @test dof(fitLambda) ≈ 3.0 atol=1e-10 @test aic(fitLambda) ≈ 109.368759 atol=1e-6 @test aicc(fitLambda) ≈ 109.493111 atol=1e-6 @test coef(fitLambda) ≈ [4.66893] atol=1e-5 @test vcov(fitLambda) ≈ [0.05111] atol=1e-5 @test nobs(fitLambda) ≈ 197.0 atol=1e-10 # below: print for when the test was broken #@show sum(residuals(fitLambda)) # locally: -115.91591040367894 #println("is this -113.594?") @test isapprox(sum(residuals(fitLambda)), -113.594, atol=1e-2) ## Low Tolerance !! @test dof_residual(fitLambda) ≈ 196.0 atol=1e-10 ## Correct Definition ? @test sigma2_phylo(fitLambda) ≈ 0.0014756 atol=1e-7 @test stderror(fitLambda) ≈ [0.22608] atol=1e-5 @test confint(fitLambda)[1] ≈ 4.2230 atol=1e-4 @test confint(fitLambda)[2] ≈ 5.114 atol=1e-3 tmp = predict(fitLambda); # below: print for when the test was broken #@show length(tmp) #@show tmp[1:6], tmp[190:end] # all 4.66893 except for last 5: 8.42676, 8.44585, etc. #println("are they all 4.66893?") # next: looks random. sometimes passes, most times fails @test predict(fitLambda) ≈ [4.66893 for i in 1:197] atol=1e-5 norm=x->norm(x,Inf) ### R script to get the above values: # library(geiger) # # ## Load data caudata (salamanders) # data("caudata") # # ## Fit using Geiger # fitgeiger <- fitContinuous(caudata$phy, caudata$dat, model = "lambda") # # ## Fit using phylolm # library(phylolm) # fitphylolm <- phylolm(trait ~ 1, # data.frame(trait = caudata$dat), # caudata$phy, model = "lambda", # starting.value = 0.9) # # ## Fit using Rphylopars # library(Rphylopars) # fitphylopars <- phylopars(data.frame(species = names(caudata$dat), # trait = unname(caudata$dat)), # caudata$phy, # model = "lambda", # model_par_start = 0.9, # pheno_error = FALSE, # pheno_correlated = FALSE, # REML = FALSE) # # ## Quantities to compare # sprintf("%.10f", fitgeiger$opt$ln) # log likelihood # sprintf("%.10f", fitphylolm$logLik) # sprintf("%.10f", fitphylopars$logLik) # sprintf("%.10f", fitgeiger$opt$aic) # aic # sprintf("%.10f", fitphylolm$aic) # sprintf("%.10f", fitgeiger$opt$aicc) # aicc # sprintf("%.10f", fitphylolm$coefficients) # coef # sprintf("%.10f", fitgeiger$opt$z0) # sprintf("%.10f", fitphylopars$mu) # sprintf("%.10f", fitphylolm$vcov) # vcov # sprintf("%.10f", fitphylolm$n) # nobs # sprintf("%.10f", sum(fitphylolm$residuals)) # residuals (sum) # sprintf("%.10f", fitphylolm$n - fitphylolm$d) # df residuals # sprintf("%.10f", fitphylolm$sigma2) # sigma 2 # sprintf("%.10f", fitgeiger$opt$sigsq) # sprintf("%.10f", fitphylopars$pars$phylocov) # sprintf("%.10f", summary(fitphylolm)$coefficients[2]) # std error # sprintf("%.10f", summary(fitphylolm)$df) # df # sprintf("%.10f", fitgeiger$opt$k) # sprintf("%.10f", coef(fitphylolm) + summary(fitphylolm)$coefficients[2] * qt(0.025, 196)) # sprintf("%.10f", coef(fitphylolm) + summary(fitphylolm)$coefficients[2] * qt(0.975, 196)) # sprintf("%.10f", predict(fitphylolm)) # df ############################################################################### ## Caudata dataset - BM with shifts ############################################################################### ## Export "caudata" dataset (from geiger) phy = readTopology(joinpath(@__DIR__, "..", "examples", "caudata_tree.txt")); dat = DataFrame(CSV.File(joinpath(@__DIR__,"..","examples","caudata_trait.txt")); copycols=false); ## Add some shifts in the model df_shift = regressorShift(phy.edge[[98, 326, 287]], phy) dat = innerjoin(dat, df_shift, on=:tipNames) ## Fit a BM fitBM = phylolm(@formula(trait ~ shift_98 + shift_326 + shift_287), dat, phy; reml=false) # Tests against results obtained with geiger::fitContinuous or phylolm::phylolm @test loglikelihood(fitBM) ≈ -76.1541605207 atol=1e-10 @test dof(fitBM) ≈ 5.0 atol=1e-10 @test aic(fitBM) ≈ 162.3083210414 atol=1e-10 @test coef(fitBM) ≈ [4.8773804547 -0.6664678924 -1.0692950215 -0.0159349201]' atol=1e-10 vcovR = [ 0.1165148753 -0.0431446679 -0.0305707092 0.0000000000 -0.0431446679 0.3212796435 0.0340202694 -0.0000000000 -0.0305707092 0.0340202694 0.2472613252 -0.0236868278 0.0000000000 -0.0000000000 -0.0236868278 0.1263794810] @test vcov(fitBM) ≈ vcovR atol=1e-8 @test nobs(fitBM) ≈ 197.0 atol=1e-10 @test sum(residuals(fitBM)) ≈ -10.1752334428 atol=1e-10 @test dof_residual(fitBM) ≈ 193.0 atol=1e-10 @test sigma2_phylo(fitBM) ≈ 0.0028624636 atol=1e-10 @test stderror(fitBM) ≈ [0.3413427535 0.5668153522 0.4972537835 0.3554989184]' atol=1e-10 @test confint(fitBM)[:,1] ≈ [4.2041393297 -1.7844157659 -2.0500444097 -0.7170966977]' atol=1e-10 @test confint(fitBM)[:,2] ≈ [5.5506215797 0.4514799811 -0.0885456333 0.6852268574]' atol=1e-10 predictR = [4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 4.2109125624, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.7921505131, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 3.8080854332, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547, 4.8773804547] tmp = predict(fitBM) tmp2 = predictR[fitBM.ind] # below: print for when the test was broken #@show tmp[1:6], tmp[190:end] #@show tmp2[1:6],tmp2[190:end] # the last 5 values are different @test isapprox(predict(fitBM), predictR[fitBM.ind], atol=1e-8) # ## R code to get those results # library(geiger) # ## Load data caudata (salamanders) # data("caudata") # ## Re-order with the tree # dat <- caudata$dat[match(caudata$phy$tip.label, names(caudata$dat))] # ## Incidence matrix # Tm = PhylogeneticEM::incidence.matrix(caudata$phy) + 0 # ## Fit using phylolm # library(phylolm) # fitphylolm <- phylolm(trait ~ shift_37 + shift_105 + shift_222, # data.frame(trait = dat, # shift_37 = Tm[, 37], # shift_105 = Tm[, 105], # shift_222 = Tm[, 222]), # caudata$phy, model = "BM") # ## Quantities to compare # sprintf("%.10f", fitphylolm$logLik) # sprintf("%.10f", fitphylolm$aic) # sprintf("%.10f", fitphylolm$coefficients) # coef # sprintf("%.10f", fitphylolm$vcov) # vcov # sprintf("%.10f", fitphylolm$n) # nobs # sprintf("%.10f", sum(fitphylolm$residuals)) # residuals (sum) # sprintf("%.10f", fitphylolm$n - fitphylolm$d) # df residuals # sprintf("%.10f", fitphylolm$sigma2) # sigma 2 # sprintf("%.10f", summary(fitphylolm)$coefficients[,2]) # std error # sprintf("%.10f", summary(fitphylolm)$df) # df # sprintf("%.10f", coef(fitphylolm) + summary(fitphylolm)$coefficients[,2] * qt(0.025, 193)) # sprintf("%.10f", coef(fitphylolm) + summary(fitphylolm)$coefficients[,2] * qt(0.975, 193)) # sprintf("%.10f", predict(fitphylolm)) end ############################################################################### ## Lizard dataset - BM ############################################################################### @testset "phylolm: Lizard Dataset" begin ## Export "lizard" dataset (Mahler et al 2013) phy = readTopology(joinpath(@__DIR__, "..", "examples", "lizard_tree.txt")); dat = DataFrame(CSV.File(joinpath(@__DIR__,"..","examples","lizard_trait.txt")); copycols=false); dat[!,:region] = string.(dat[:,:region]) # avoid CategoricalArrays.categorical dependency ## Fit a BM fitBM = phylolm(@formula(AVG_SVL ~ AVG_ltoe_IV + AVG_lfing_IV * region), dat, phy; reml=false) # Tests against results obtained with geiger::fitContinuous or phylolm::phylolm @test loglikelihood(fitBM) ≈ 105.17337853473711 atol=1e-10 @test dof(fitBM) ≈ 10.0 atol=1e-10 @test aic(fitBM) ≈ -190.3467570695 atol=1e-10 # @test aicc(fitBM) @test coef(fitBM) ≈ [2.7925712673 -0.2010704391 0.9832555589 -0.1021226296 -0.3703658712 0.1557471731 0.0374549036 0.1805667675 -0.0495767233]' atol=1e-10 vcovR = [0.0200086273 -0.0136717540 0.0084815090 -0.0093192029 -0.0114417825 -0.0113346813 0.0041102304 0.0053787287 0.0050521693 -0.0136717540 0.0185396965 -0.0169114682 0.0020645005 0.0036352899 0.0026227856 -0.0012281620 -0.0018838231 -0.0014800242 0.0084815090 -0.0169114682 0.0174647413 0.0016403871 0.0005624488 0.0015003301 -0.0005714235 -0.0003201257 -0.0005423354 -0.0093192029 0.0020645005 0.0016403871 0.0167953394 0.0078012534 0.0086329399 -0.0080782771 -0.0037333495 -0.0039327836 -0.0114417825 0.0036352899 0.0005624488 0.0078012534 0.0490482083 0.0092203882 -0.0033670465 -0.0191567265 -0.0040068947 -0.0113346813 0.0026227856 0.0015003301 0.0086329399 0.0092203882 0.0331395502 -0.0037513830 -0.0041592743 -0.0146108207 0.0041102304 -0.0012281620 -0.0005714235 -0.0080782771 -0.0033670465 -0.0037513830 0.0045172675 0.0018165174 0.0020857846 0.0053787287 -0.0018838231 -0.0003201257 -0.0037333495 -0.0191567265 -0.0041592743 0.0018165174 0.0093292284 0.0020427637 0.0050521693 -0.0014800242 -0.0005423354 -0.0039327836 -0.0040068947 -0.0146108207 0.0020857846 0.0020427637 0.0074817942] @test vcov(fitBM) ≈ vcovR atol=1e-8 @test nobs(fitBM) ≈ 100.0 atol=1e-10 # below: print for when the test was broken (with @test_skip) #@show sum(residuals(fitBM)) # looks random, e.g. 1.6091413520064477, or 0.8338189090359597 #println("is this equal to 0.6352899255?") # sometimes NO, yet the test passes below!! @test sum(residuals(fitBM)) ≈ 0.6352899255 atol=1e-10 @test dof_residual(fitBM) ≈ 91.0 atol=1e-10 @test sigma2_phylo(fitBM) ≈ 0.0003025014 atol=1e-10 @test stderror(fitBM) ≈ [0.1414518551,0.1361605540,0.1321542330,0.1295968341,0.2214683008,0.1820427154,0.0672106202,0.0965879311,0.0864973651] atol=1e-10 @test confint(fitBM)[:,1] ≈ [2.5115945339,-0.4715366529,0.7207474097,-0.3595508202,-0.8102854443,-0.2058583178,-0.0960507369,-0.0112932922,-0.2213931131] atol=1e-10 norm=x->norm(x,Inf) @test confint(fitBM)[:,2] ≈ [3.0735480006,0.0693957746,1.2457637082,0.1553055609,0.0695537019,0.5173526640,0.1709605441,0.3724268272,0.1222396666] atol=1e-10 ### R script to get the above values # ## Data # dat <- read.csv(file = "GA_Anolis_traits.csv") # geo <- read.csv(file = "GA_Anolis_biogeography.csv") # # dat <- merge(dat, geo, by = "species") # # keep only toe and hand length # dat <- dat[, c("species", "AVG.SVL", "AVG.ltoe.IV", "AVG.lfing.IV", "region")] # colnames(dat)[1] <- "tipsNames" # # write.table(dat, # file = "lizard_trait.txt", # sep = ",", row.names = FALSE) # # ## Tree # phy <- read.tree(file = "GA_Anolis_MCC.tre") # # write.tree(phy, file = "lizards_tree.txt", append = FALSE, # digits = 10, tree.names = FALSE) # # rownames(dat) <- dat$tipsNames # dat <- dat[, -1] # dat$region <- as.factor(dat$region) # # ## Fit # fitphylolm <- phylolm(AVG.SVL ~ 1 + AVG.ltoe.IV + AVG.lfing.IV * region, dat, phy, model = "BM") # ## Quantities to compare # sprintf("%.10f", fitphylolm$logLik) # sprintf("%.10f", summary(fitphylolm)$df) # df # sprintf("%.10f", fitphylolm$aic) # sprintf("%.10f", fitphylolm$coefficients) # coef # matrix(sprintf("%.10f", fitphylolm$vcov), 9, 9) # vcov # sprintf("%.10f", fitphylolm$n) # nobs # sprintf("%.10f", sum(fitphylolm$residuals)) # residuals (sum) # sprintf("%.10f", fitphylolm$n - fitphylolm$d) # df residuals # sprintf("%.10f", fitphylolm$sigma2) # sigma 2 # sprintf("%.10f", summary(fitphylolm)$coefficients[,2]) # std error # sprintf("%.10f", coef(fitphylolm) + summary(fitphylolm)$coefficients[, 2] * qt(0.025, 91)) # sprintf("%.10f", coef(fitphylolm) + summary(fitphylolm)$coefficients[, 2] * qt(0.975, 91)) ############################################################################### ## Lizard dataset - lambda ############################################################################### ## Fit lambda fitLambda = (@test_logs (:info, r"^Maximum lambda value") match_mode=:any phylolm(@formula(AVG_SVL ~ AVG_ltoe_IV + AVG_lfing_IV * region), dat, phy, model = "lambda", reml=false)) # Tests against results obtained with geiger::fitContinuous or phylolm::phylolm @test lambda_estim(fitLambda) ≈ 0.9982715594 atol=1e-5 @test loglikelihood(fitLambda) ≈ 105.1769275564 atol=1e-8 @test dof(fitLambda) ≈ 11.0 atol=1e-10 @test aic(fitLambda) ≈ -188.3538551128 atol=1e-8 # @test aicc(fitBM) @test coef(fitLambda) ≈ [2.7940573420 -0.2066584606 0.9897083949 -0.1004840950 -0.3677991157 0.1576743022 0.0367633665 0.1792502383 -0.0505291142]' atol=1e-5 vcovR = [0.0200251600 -0.0137474015 0.0085637021 -0.0092973836 -0.0114259722 -0.0113056243 0.0041037877 0.0053740100 0.0050429112 -0.0137474015 0.0186885224 -0.0170645512 0.0020509207 0.0036334103 0.0026066694 -0.0012237488 -0.0018826836 -0.0014743137 0.0085637021 -0.0170645512 0.0176200143 0.0016494733 0.0005604169 0.0015116125 -0.0005735573 -0.0003192320 -0.0005457420 -0.0092973836 0.0020509207 0.0016494733 0.0167461876 0.0077885115 0.0086173037 -0.0080563819 -0.0037287856 -0.0039275469 -0.0114259722 0.0036334103 0.0005604169 0.0077885115 0.0490092393 0.0092036032 -0.0033631662 -0.0191657329 -0.0040017905 -0.0113056243 0.0026066694 0.0015116125 0.0086173037 0.0092036032 0.0330248707 -0.0037465110 -0.0041543671 -0.0145663751 0.0041037877 -0.0012237488 -0.0005735573 -0.0080563819 -0.0033631662 -0.0037465110 0.0045042057 0.0018142470 0.0020823721 0.0053740100 -0.0018826836 -0.0003192320 -0.0037287856 -0.0191657329 -0.0041543671 0.0018142470 0.0093334212 0.0020404652 0.0050429112 -0.0014743137 -0.0005457420 -0.0039275469 -0.0040017905 -0.0145663751 0.0020823721 0.0020404652 0.0074600880] @test vcov(fitLambda) ≈ vcovR atol=3e-7 @test nobs(fitLambda) ≈ 100.0 atol=1e-10 @test sum(residuals(fitLambda)) ≈ 0.6369008979 atol=1e-5 @test dof_residual(fitLambda) ≈ 91.0 atol=1e-10 @test sigma2_phylo(fitLambda) ≈ 0.0003009914 atol=1e-9 @test stderror(fitLambda) ≈ [0.1415102824,0.1367059706,0.1327404019,0.1294070617,0.2213803048,0.1817274626,0.0671133793,0.0966096332,0.0863718011] atol=1e-6 @test confint(fitLambda)[:,1] ≈ [2.5129645499,-0.4782080775,0.7260358930,-0.3575353260,-0.8075438955,-0.2033049779,-0.0965491169,-0.0126529301,-0.2220960868] atol=1e-5 @test confint(fitLambda)[:,2] ≈ [3.0751501341,0.0648911562,1.2533808968,0.1565671360,0.0719456641,0.5186535822,0.1700758500,0.3711534067,0.1210378584] atol=1e-5 ### R script to get the above values # ## Data # dat <- read.csv(file = "GA_Anolis_traits.csv") # geo <- read.csv(file = "GA_Anolis_biogeography.csv") # # dat <- merge(dat, geo, by = "species") # # keep only toe and hand length # dat <- dat[, c("species", "AVG.SVL", "AVG.ltoe.IV", "AVG.lfing.IV", "region")] # colnames(dat)[1] <- "tipsNames" # # write.table(dat, # file = "lizard_trait.txt", # sep = ",", row.names = FALSE) # # ## Tree # phy <- read.tree(file = "GA_Anolis_MCC.tre") # # write.tree(phy, file = "lizards_tree.txt", append = FALSE, # digits = 10, tree.names = FALSE) # # rownames(dat) <- dat$tipsNames # dat <- dat[, -1] # dat$region <- as.factor(dat$region) # # ## Fit # fitphylolm <- phylolm(AVG.SVL ~ 1 + AVG.ltoe.IV + AVG.lfing.IV * region, dat, phy, model = "lambda") # ## Quantities to compare # sprintf("%.10f", fitphylolm$logLik) # sprintf("%.10f", summary(fitphylolm)$df) # df # sprintf("%.10f", fitphylolm$aic) # sprintf("%.10f", fitphylolm$coefficients) # coef # matrix(sprintf("%.10f", fitphylolm$vcov), 9, 9) # vcov # sprintf("%.10f", fitphylolm$n) # nobs # sprintf("%.10f", sum(fitphylolm$residuals)) # residuals (sum) # sprintf("%.10f", fitphylolm$n - fitphylolm$d) # df residuals # sprintf("%.10f", fitphylolm$sigma2) # sigma 2 # sprintf("%.10f", summary(fitphylolm)$coefficients[,2]) # std error # sprintf("%.10f", coef(fitphylolm) + summary(fitphylolm)$coefficients[, 2] * qt(0.025, 91)) # sprintf("%.10f", coef(fitphylolm) + summary(fitphylolm)$coefficients[, 2] * qt(0.975, 91)) end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
34893
## traits.jl : phylolm for within-species variation, continuous traits @testset "phylolm: within-species variation, star" begin #= simulation of data used below (test more reproducible when using fixed data) # simulate traits at the species-level, then # repeat identical trait values across m individuals function simTraits(net, m, paramsprocess) sim = simulate(net, paramsprocess) trait = sim[:Tips] # simple vector now return repeat(trait, inner=m) end n = 4; m = 3 starnet = readTopology(PhyloNetworks.startree_newick(n)) Random.seed!(6591) trait1 = simTraits(starnet, m, ParamsBM(2, 0.5)) # var: 0.5 trait2 = simTraits(starnet, m, ParamsBM(-2, 1)) phylo_noise_var = 2; meas_noise_var = 1 phylo_noise = simTraits(starnet, m, ParamsBM(0, phylo_noise_var)) meas_noise = randn(n*m) * sqrt(meas_noise_var) trait3 = 10 .+ 2*trait1 + phylo_noise + meas_noise print(round.(trait1, digits=4)) # etc labels = repeat(starnet.names, inner=m) df = DataFrame(trait1=trait1, trait2=trait2, trait3=trait3,tipNames=labels) =# n = 4; m = 3 starnet = readTopology(PhyloNetworks.startree_newick(n)) netnames = ["t1","t2","t3","t4"] # = tipLabels(starnet) # was generated to have length n df = DataFrame( species = repeat(netnames, inner=m), trait1 = [2.8564, missing, 2.8564, 2.8457, 2.8457, 2.8457, 0.4197, 0.4197, 0.4197, 2.2359, 2.2359, 2.2359], trait2 = [-2.0935, -2.0935, -2.0935, 0.4955, 0.4955, 0.4955, -2.1977, -2.1977, -2.1977, -2.618, -2.618, -2.618], trait3 = [missing, 15.7869, 14.0615, 14.3547, 13.3721, 15.7062, 9.2764, 8.8553, 8.7627, 15.0298, 15.8258, 15.3248] # missing replaced 14.0467 ) Y = df[!,:trait3] # nm vector X = fill(1.0, (n,2)); X[:,2] = df[1:m:n*m,:trait1] # nx2 matrix #= reduced data: one row per species, extra columns for SD and n of trait 3 gdf = groupby(df, :species) df_r = combine(gdf, :trait1 => (x -> mean(skipmissing(x))) => :trait1, :trait2 => (x -> mean(skipmissing(x))) => :trait2, :trait3 => (x -> mean(skipmissing(x))) => :trait3, :trait3 => (x -> std(skipmissing(x))) => :trait3_sd, :trait3 => (x -> sum(.!ismissing.(x))) => :trait3_n) =# df_r = DataFrame( species = ["t1","t2","t3","t4"], trait1 = [2.8564,2.8457,.4197,2.2359], trait2 = [-2.0935,0.4955,-2.1977,-2.618], trait3 = [14.0615, 14.477666666666666, 8.9648, 15.393466666666667], # [14.9242,... if we include ind 2 trait3_sd = [0,1.1718985891848046,.2737966581242371,.4024181076111425], # [1.2200420402592675,... if we include ind 2 trait3_n = [1,3,3,3]) # [2,3,3,3] #= star tree: R code to check df = data.frame(species = rep(c("t1","t2","t3","t4"), each=3), trait1 = c(2.8564,NA,2.8564,2.8457,2.8457,2.8457,.4197,.4197,.4197,2.2359,2.2359,2.2359), trait2 = c(-2.0935,-2.0935,-2.0935,.4955,.4955,.4955,-2.1977,-2.1977,-2.1977, -2.618,-2.618,-2.618), trait3 = c(NA,15.7869,14.0615,14.3547,13.3721,15.7062,9.2764,8.8553,8.7627,15.0298,15.8258,15.3248)) mR = lmer(trait3 ~ trait1 + (1|species), df) fixef(mR) # 8.457020 2.296978 print(mR, digits=7, ranef.comp="Var") # variances: 2.1216068,0.5332865 logLik(mR) # -13.37294 logLik(mR, REML=FALSE) # -14.57265 vcov(mR) # matrix(c(3.111307,-1.219935,-1.219935,0.5913808), nrow=2) mR = lmer(trait3 ~ trait1 + (1|species), df, REML=FALSE) fixef(mR) # 8.439909 2.318488 print(mR, digits=7, ranef.comp="Var") # variances: 0.9470427,0.5299540 logLik(mR) # -14.30235 vcov(mR) # matrix(c(1.5237486,-0.6002803,-0.6002803,0.2941625), nrow=2) =# #= Alternatively: Julia code to check using MixedModels mm1 = fit(MixedModel, @formula(trait3 ~ trait1 + (1|species)), df, REML=true) # compare with m1 mm3 = fit(MixedModel, @formula(trait3 ~ trait1 + (1|species)), df) # compare with m3 fixef(mm1) # fixed-effect param estimates: 8.45702,2.29698 VarCorr(mm1) # estimated variance-components: species-variance=2.121607, residual-variance=0.533287 # `objective(m)` returns -2 * (log-likelihood of model m) objective(mm1)/(-2) # -13.3729434, `loglikelihood` not available for models fit by REML loglikelihood(mm3) # -14.3023458 vcov(mm1) # var-cov matrix for fixef coeffs: [3.11131 -1.21993; -1.21993 0.591381] =# m1 = phylolm(@formula(trait3 ~ trait1), df, starnet; reml=true, tipnames=:species, withinspecies_var=true) m2 = phylolm(@formula(trait3 ~ trait1), df_r, starnet; reml=true, tipnames=:species, withinspecies_var=true, y_mean_std=true) @test m1.reml && m2.reml @test coef(m1) ≈ [8.457020,2.296978] rtol=1e-5 # fixef(mR) @test coef(m2) ≈ [8.457020,2.296978] rtol=1e-5 @test sigma2_phylo(m1) ≈ 2.1216068 rtol=1e-5 # print(mR, digits=7, ranef.comp="Var") @test sigma2_phylo(m2) ≈ 2.1216068 rtol=1e-5 @test sigma2_within(m1) ≈ 0.5332865 rtol=1e-5 @test sigma2_within(m2) ≈ 0.5332865 rtol=1e-5 @test loglikelihood(m1) ≈ -13.37294 rtol=1e-5 @test loglikelihood(m2) ≈ -13.37294 rtol=1e-5 @test vcov(m1) ≈ [3.111307 -1.219935; -1.219935 0.5913808] rtol=1e-5 @test vcov(m2) ≈ [3.111307 -1.219935; -1.219935 0.5913808] rtol=1e-5 m3 = phylolm(@formula(trait3 ~ trait1), df_r, starnet; reml=false, tipnames=:species, withinspecies_var=true, y_mean_std=true) @test !m3.reml @test coef(m3) ≈ [8.439909,2.318488] rtol=1e-5 @test sigma2_phylo(m3) ≈ 0.9470427 rtol=1e-5 @test sigma2_within(m3) ≈ 0.5299540 rtol=1e-5 @test loglikelihood(m3) ≈ -14.30235 rtol=1e-5 @test vcov(m3) ≈ [1.5237486 -0.6002803; -0.6002803 0.2941625] rtol=1e-5 end @testset "phylolm: binary tree, no withinspecies var" begin #= Rcode to generate the newick string and dataset: library(phytools) set.seed(1) tree <- pbtree(n=5,scale=1) # topology and branch lengths tree.newick <- write.tree(tree) # newick format # tree.newick <- "((t1:0.8121974445,(t2:0.4806586387,t3:0.4806586387):0.3315388057):0.1878025555,(t4:0.1206907041,t5:0.1206907041):0.8793092959);" X <- fastBM(tree,sig2=2,nsim=2); colnames(X) <- c("x1","x2") # non-intercept predictors # X <- matrix(c(-0.5503706,-0.7503593,-0.7599224,-0.4217977,-0.9839226,-1.3102488,0.4544195,0.2151272,1.0384023,1.3138847),nrow=5) # colnames(X) <- c("x1","x2"); rownames(X) <- c("t1","t2","t3","t4","t5") bsperr <- fastBM(tree) # phylogenetic variation, true BM variance-rate is 1 y <- cbind(rep(1,5),X)%*%(1:3)+bsperr # response, true beta vector is c(1,2,3) # y <- matrix(c(-4.1836578,0.6258014,-0.3070109,2.6120026,2.2391044),nrow=5) # rownames(y) <- c("t1","t2","t3","t4","t5") df <- data.frame(y,X,species=tree$tip.label) =# net = readTopology("((t1:0.8121974445,(t2:0.4806586387,t3:0.4806586387):0.3315388057):0.1878025555,(t4:0.1206907041,t5:0.1206907041):0.8793092959);") df = DataFrame( y = [-4.18366,0.625801,-0.307011,2.612,2.2391], x1 = [-0.550371,-0.750359,-0.759922,-0.421798,-0.983923], x2 = [-1.31025,0.45442,0.215127,1.0384,1.31388], species = net.names # ["t1","t2","t3","t4","t5"] ) #= Rcode to check model fit: library(nlme) m1 <- gls(y~x1+x2,data=df, correlation=corBrownian(1,tree,form=~species),method="REML") coef(m1) # coefficients estimates: c(0.6469652,2.0420889,2.8285257) sigma(m1)^2 # reml BM variance-rate estimate: 0.0438973 logLik(m1) # restricted log-likelihood: -0.07529961 vcov(m1) # cov mat for coef estimates # matrix(c(0.030948901,0.024782246,0.003569513,0.024782246,0.039001092,0.009137043,0.003569513,0.009137043,0.013366014),nrow=3) summary(m1)$tTable[,"t-value"] # t-values for coef estimates: c(3.677548,10.340374,24.465786) summary(m1)$tTable[,"p-value"] # p-values for coef estimates: c(0.066635016,0.009223303,0.001666460) coef(m1) + qt(p=0.025,df=5-3)*sqrt(diag(vcov(m1))) # lower limit 95%-CI: c(-0.1099703,1.1923712,2.3310897) coef(m1) + qt(p=0.975,df=5-3)*sqrt(diag(vcov(m1))) # upper limit 95%-CI: c(1.403901,2.891807,3.325962) m2 <- gls(y~x1+x2,data=df, correlation=corBrownian(1,tree,form=~species),method="ML") coef(m2) # coefficients estimates: c(0.6469652,2.0420889,2.8285257) sigma(m2)^2 # ml BM variance-rate estimate: 0.01755892 logLik(m2) # log-likelihood: 3.933531 vcov(m2) # cov mat for coef estimates, this evaluates to the same value as vcov(m1) # Note: vcov(gls(...,method="REML)) == vcov(gls(...,method="ML")) # The same holds for t/p-values and CIs for the coef estimates summary(m2)$tTable[,"t-value"] # t-values for coef estimates: c(3.677548,10.340374,24.465786) summary(m2)$tTable[,"p-value"] # p-values for coef estimates: c(0.066635016,0.009223303,0.001666460) coef(m2) + qt(p=0.025,df=5-3)*sqrt(diag(vcov(m2))) # lower limit 95%-CI: c(-0.1099703,1.1923712,2.3310897) coef(m2) + qt(p=0.975,df=5-3)*sqrt(diag(vcov(m2))) # upper limit 95%-CI: c(1.403901,2.891807,3.325962) =# m1 = phylolm(@formula(y~x1+x2),df,net; tipnames=:species, reml=true) m2 = phylolm(@formula(y~x1+x2),df,net; tipnames=:species, reml=false) @test m1.reml @test coef(m1) ≈ [0.6469652,2.0420889,2.8285257] rtol=1e-5 @test sigma2_phylo(m1) ≈ 0.0438973 rtol=1e-4 @test isnothing(sigma2_within(m1)) @test loglikelihood(m1) ≈ -0.07529961 rtol=1e-3 @test vcov(m1) ≈ [0.030948901 0.024782246 0.003569513;0.024782246 0.039001092 0.009137043;0.003569513 0.009137043 0.013366014] rtol=1e-4 @test coeftable(m1).cols[coeftable(m1).teststatcol] ≈ [3.677548,10.340374,24.465786] rtol=1e-4 @test coeftable(m1).cols[coeftable(m1).pvalcol] ≈ [0.066635016,0.009223303,0.001666460] rtol=1e-4 @test coeftable(m1).cols[findall(coeftable(m1).colnms .== "Lower 95%")[1]] ≈ [-0.1099703,1.1923712,2.3310897] rtol=1e-5 @test coeftable(m1).cols[findall(coeftable(m1).colnms .== "Upper 95%")[1]] ≈ [1.403901,2.891807,3.325962] rtol=1e-5 @test !m2.reml @test coef(m2) ≈ [0.6469652,2.0420889,2.8285257] rtol=1e-5 @test sigma2_phylo(m2) ≈ 0.01755892 rtol=1e-4 @test isnothing(sigma2_within(m2)) @test loglikelihood(m2) ≈ 3.933531 rtol=1e-4 @test vcov(m2) ≈ [0.030948901 0.024782246 0.003569513;0.024782246 0.039001092 0.009137043;0.003569513 0.009137043 0.013366014] rtol=1e-4 @test coeftable(m2).cols[coeftable(m2).teststatcol] ≈ [3.677548,10.340374,24.465786] rtol=1e-4 @test coeftable(m2).cols[coeftable(m2).pvalcol] ≈ [0.066635016,0.009223303,0.001666460] rtol=1e-4 @test coeftable(m2).cols[findall(coeftable(m2).colnms .== "Lower 95%")[1]] ≈ [-0.1099703,1.1923712,2.3310897] rtol=1e-5 @test coeftable(m2).cols[findall(coeftable(m2).colnms .== "Upper 95%")[1]] ≈ [1.403901,2.891807,3.325962] rtol=1e-5 end @testset "phylolm: binary tree, withinspecies var" begin #= NOTE: This testset DOES NOT check for similarity of the variance-components estimates from 'pgls.SEy' (phytools) and 'phylolm' (PhyloNetworks). In fact, 'pgls.SEy' and 'phylolm' solve different problems! ML/REML variance-component estimates are obtained by running 'phylolm'. The code for 'pgls.SEy' is adapted to calculate coef estimates, cov matrix for coef estimates, t/p-values for coef estimates, and full/restricted-loglikelihood, given these variance-components estimates. These values are then compared against those extracted from the output of 'phylolm'. =# #= Rcode to generate the newick string and dataset: library(phytools) set.seed(2) m <- 5 # sample-size per taxa n <- 5 # no. of taxa p <- 3 # no. of predictors (including intercept) tree <- pbtree(n=n,scale=1) # topology and branch lengths tree.newick <- write.tree(tree) # newick format # tree.newick <- "(((t4:0.2537636499,t5:0.2537636499):0.2103870459,t3:0.4641506959):0.5358493041,(t1:0.4807642475,t2:0.4807642475):0.5192357525);" X <- fastBM(tree,sig2=2,nsim=2); colnames(X) <- c("x1","x2") # non-intercept predictors # X <- matrix(c(0.7894387,0.3285286,2.1495131,-1.4935665,-2.3199935,2.8184268,0.4740687,2.5801004,1.9967379,-0.4121874),nrow=5) # colnames(X) <- c("x1","x2"); rownames(X) <- c("t4","t5","t3","t1","t2") bsperr <- fastBM(tree) # phylogenetic variation, true BM variance-rate is 1 wspvar <- 0.1 # within-species variance is 0.1 msrerr <- rnorm(n=n,sd=sqrt(wspvar/m)) # msr error in species-level mean responses y_sd <- sqrt(wspvar*rchisq(n=n,df=m-1)/(m-1)) # sd in individual responses per species # y_sd <- c(0.2463003,0.3236629,0.2458547,0.4866844,0.3434582); y <- cbind(rep(1,5),X)%*%(1:3)+bsperr+msrerr # response, true beta vector is c(1,2,3) # y <- matrix(c(11.399108,3.216645,13.648011,4.851454,-4.922803),nrow=5); rownames(y) <- c("t4","t5","t3","t1","t2") df <- data.frame(y,y_sd,X,species=tree$tip.label) =# net = readTopology("(((t4:0.2537636499,t5:0.2537636499):0.2103870459,t3:0.4641506959):0.5358493041,(t1:0.4807642475,t2:0.4807642475):0.5192357525);") df = DataFrame( y=[11.399108,3.216645,13.648011,4.851454,-4.922803], y_sd=[0.2463003,0.3236629,0.2458547,0.4866844,0.3434582], y_n=fill(5,5), x1=[0.7894387,0.3285286,2.1495131,-1.4935665,-2.3199935], x2=[2.8184268,0.4740687,2.5801004,1.9967379,-0.4121874], species=net.names ) #= R/Julia code to check model fit: (1) Julia code: ## To extract reml/ml msrerr variance estimates fitted by phylolm m1 |> sigma2_within |> x -> round(x,sigdigits=6) # reml est msrerr var: 0.116721 m2 |> sigma2_within |> x -> round(x,sigdigits=6) # ml est msrerr var: 0.125628 m1 |> sigma2_phylo |> x -> round(x,sigdigits=6) # reml est BM var: 0.120746 m2 |> sigma2_phylo |> x -> round(x,sigdigits=6) # ml est BM var: 0.000399783 (2) R code: ## To check phylolm REML fit library(nlme) T1 <- tree wspvar1 <- 0.116721 # reml est msrerr var of indiv-lvl rsps bspvar1 <- 0.120746 # reml est BM var se1 <- setNames(rep(sqrt(wspvar1/m),n),T1$tip.label) # msrerr sd of species-lvl mean rsp T1$edge.length <- T1$edge.length*bspvar1 # scale all edges by est BM var ii <- sapply(1:Ntip(T1),function(x,e) which(e==x),e=T1$edge[,2]) # indices of pendant edges # extend pendant edges by msrerr sd T1$edge.length[ii] <- T1$edge.length[ii]+se1[T1$tip.label]^2 covmat1 <- vcv(T1) # extract est vars of species-lvl mean rsp m1 <- gls(y~x1+x2,data=cbind(df,vf=diag(covmat1)), correlation=corBrownian(1,T1,form=~species), method="REML", weights=varFixed(~vf)) coef(m1) # reml coefficient estimates: c(1.079839,1.976719,3.217391) Xp <- model.matrix(m1,df) # predictor matrix vcov1 <- solve(t(Xp)%*%solve(covmat1)%*%Xp) # cov mat for coef estimates # matrix(c(0.09386431,0.02273458,-0.02602937,0.02273458,0.02172123,-0.01133032,-0.02602937,-0.01133032,0.01584198),nrow=3) teststat1 <- coef(m1)/sqrt(diag(vcov1)) # test stat for coef estimates: c(3.524591,13.412285,25.562252) pval1 <- sapply(X=pt(teststat1,n-p),FUN=function(p) 2*min(p,1-p)) # pval for coef est: # c(0.071921276,0.005513044,0.001526885) lowerci1 <- coef(m1) + qt(p=0.025,df=n-p)*sqrt(diag(vcov1)) # lower limit 95%-CI: c(-0.2383769,1.3425890,2.6758379) upperci1 <- coef(m1) + qt(p=0.975,df=n-p)*sqrt(diag(vcov1)) # upper limit 95%-CI: c(2.398055,2.610850,3.758944) RSS <- sum((m-1)*(df$y_sd^2)) # residual sum-of-squares wrt to the species means logLik(m1) # species-lvl cond restricted-ll: -3.26788 sigm1 <- sigma(m1) # this is not bspvar1!, but rather the best "scaling" for covmat1 # indiv-lvl cond restricted ll # "+ (n-p)*(2*log(sigm1)-sigm1^2+1)/2" un-scales the species-lvl rll returned by logLik # "- n*(m-1)*(log(wspvar1)+log(2*pi))/2 - (n*log(m)+RSS/wspvar1)/2" corrects to indiv-lvl rll rll.species <- logLik(m1) rll.indiv <- (rll.species + (n-p)*(2*log(sigm1)-sigm1^2+1)/2 - n*(m-1)*(log(wspvar1)+log(2*pi))/2 - (n*log(m)+RSS/wspvar1)/2 ) round(rll.indiv,digits=6) # indiv-lvl rll of remles: -14.14184 ## To check phylolm ML fit T2 <- tree wspvar2 <- 0.125628 # ml est msrerr var of indiv-lvl rsps bspvar2 <- 0.000399783 # ml est BM var se2 <- setNames(rep(sqrt(wspvar2/m),n),T2$tip.label) T2$edge.length <- T2$edge.length*bspvar2 ii <- sapply(1:Ntip(T2),function(x,e) which(e==x),e=T2$edge[,2]) T2$edge.length[ii] <- T2$edge.length[ii]+se2[T2$tip.label]^2 covmat2 <- vcv(T2) m2 <- gls(y~x1+x2,data=cbind(df,vf=diag(covmat2)), correlation=corBrownian(1,T2,form=~species), method="ML", weights=varFixed(~vf)) coef(m2) # ml coefficient estimates: c(0.9767352,1.9155142,3.2661862) Xp <- model.matrix(m2,df) # predictor matrix vcov2 <- solve(t(Xp)%*%solve(covmat2)%*%Xp) # cov mat for coef estimates # matrix(c(0.019118171,0.004924625,-0.008977541,0.004924625,0.003577654,-0.003028413,-0.008977541,-0.003028413,0.005793475),nrow=3) teststat2 <- coef(m2)/sqrt(diag(vcov2)) # test stat for coef est: c(7.064049,32.024784,42.911270) pval2 <- sapply(X=pt(teststat2,n-p),FUN=function(p) 2*min(p,1-p)) # pval for coef est: # c(0.0194568147,0.0009736278,0.0005426298) lowerci2 <- coef(m2) + qt(p=0.025,df=n-p)*sqrt(diag(vcov2)) # lower limit 95%-CI: c(0.381814,1.658158,2.938690) upperci2 <- coef(m2) + qt(p=0.975,df=n-p)*sqrt(diag(vcov2)) # upper limit 95%-CI: c(1.571656,2.172871,3.593682) ll.species <- logLik(m2) # species-lvl cond ll: 1.415653 sigm2 <- sigma(m2) # this is not bspvar2!, but rather the best "scaling" for covmat2 RSS <- sum((m-1)*(df$y_sd^2)) # residual sum-of-squares wrt to the species means # indiv-lvl cond ll # "+ n*(2*log(sigm2)-sigm2^2+1)/2" un-scales the species-lvl ll returned by logLik # "- n*(m-1)*(log(wspvar2)+log(2*pi))/2 - (n*log(m)+RSS/wspvar2)/2" corrects to indiv-lvl ll ll.indiv <- (ll.species + n*(2*log(sigm2)-sigm2^2+1)/2 - n*(m-1)*(log(wspvar2)+log(2*pi))/2 - (n*log(m)+RSS/wspvar2)/2 ) round(ll.indiv,digits=6) # indiv-lvl ll of mles: -9.582357 =# m1 = phylolm(@formula(y~x1+x2),df,net; tipnames=:species, reml=true, withinspecies_var=true, y_mean_std=true) m2 = phylolm(@formula(y~x1+x2),df,net; tipnames=:species, reml=false, withinspecies_var=true, y_mean_std=true) @test coef(m1) ≈ [1.079839,1.976719,3.217391] rtol=1e-4 @test coef(m2) ≈ [0.9767352,1.9155142,3.2661862] rtol=1e-4 @test loglikelihood(m1) ≈ -14.14184 rtol=1e-4 @test loglikelihood(m2) ≈ -9.582357 rtol=1e-4 @test vcov(m1) ≈ [0.09386431 0.02273458 -0.02602937;0.02273458 0.02172123 -0.01133032;-0.02602937 -0.01133032 0.01584198] rtol=1e-3 @test vcov(m2) ≈ [0.019118171 0.004924625 -0.008977541;0.004924625 0.003577654 -0.003028413;-0.008977541 -0.003028413 0.005793475] rtol=1e-3 @test coeftable(m1).cols[coeftable(m1).teststatcol] ≈ [3.524591,13.412285,25.562252] rtol=1e-4 @test coeftable(m2).cols[coeftable(m2).teststatcol] ≈ [7.064049,32.024784,42.911270] rtol=1e-4 @test coeftable(m1).cols[coeftable(m1).pvalcol] ≈ [0.071921276,0.005513044,0.001526885] rtol=1e-3 @test coeftable(m2).cols[coeftable(m2).pvalcol] ≈ [0.0194568147,0.0009736278,0.0005426298] rtol=1e-3 @test coeftable(m1).cols[findall(coeftable(m1).colnms .== "Lower 95%")[1]] ≈ [-0.2383769,1.3425890,2.6758379] rtol=1e-4 @test coeftable(m2).cols[findall(coeftable(m2).colnms .== "Lower 95%")[1]] ≈ [0.381814,1.658158,2.938690] rtol=1e-4 @test coeftable(m1).cols[findall(coeftable(m1).colnms .== "Upper 95%")[1]] ≈ [2.398055,2.610850,3.758944] rtol=1e-4 @test coeftable(m2).cols[findall(coeftable(m2).colnms .== "Upper 95%")[1]] ≈ [1.571656,2.172871,3.593682] rtol=1e-4 # missing y (but y_n/SD present); missing/infinite sample size; missing/infinite y_SD df = df[[1,2,3,4],:] # delete t2 allowmissing!(df, [:y,:y_n,:y_sd]) # m0 = phylolm(@formula(y~1),df,net; tipnames=:species, withinspecies_var=true, y_mean_std=true) df1 = DataFrame(df) # makes a copy push!(df1, (missing,0.,0,0.,0.,"t2")) m1 = phylolm(@formula(y~1),df1,net; tipnames=:species, withinspecies_var=true, y_mean_std=true) @test coef(m1) ≈ [7.8116494901242195] atol=1e-6 # same as m0 @test sigma2_within(m1) ≈ 0.11568962074173368 atol=1e-6 @test nobs(m1) == 20 # 4 species x 5 indiv/species @test dof_residual(m1) == 3 # sample sizes y_n: 1, 0, infinite @test dof(m1) == 3 # intercept, s2phylo, s2within df1[5,:] .= (0.,0.,1,0.,0.,"t2") # then almost same within-sp variation m1 = phylolm(@formula(y~1),df1,net; tipnames=:species, withinspecies_var=true, y_mean_std=true) @test sigma2_within(m1) ≈ 0.11569 atol=1e-4 @test nobs(m1) == 21 @test dof_residual(m1) == 4 df1[5,:] .= (0.,0.,0,0.,0.,"t2") # some species have 0 or <0 num_individuals, column y_n @test_throws ErrorException phylolm(@formula(y~1),df1,net; tipnames=:species, withinspecies_var=true, y_mean_std=true) df1[!,:y_n] = Float64.(df1[!,:y_n]) df1[5,:] .= (0.,0.,Inf,0.,0.,"t2")#some species have infinite num_individuals, column y_n @test_throws ErrorException phylolm(@formula(y~1),df1,net; tipnames=:species, withinspecies_var=true, y_mean_std=true) df1[5,:] .= (0.,missing,1,0.,0.,"t2") # some SD values are missing, column y_sd @test_throws ErrorException phylolm(@formula(y~1),df1,net; tipnames=:species, withinspecies_var=true, y_mean_std=true) df1[5,:] .= (0.0,Inf,1,0.,0.,"t2") # some SD values are infinite, column y_sd @test_throws ErrorException phylolm(@formula(y~1),df1,net; tipnames=:species, withinspecies_var=true, y_mean_std=true) end @testset "phylolm: within-species var, network h=1" begin #= Simulation of data used below: (1) Individual-level data function simTraits(net, m, paramsprocess) sim = simulate(net, paramsprocess) trait = sim[:Tips] return repeat(trait, inner=m) end n = 6; m = 3 # 6 species, 3 individuals per species net = readTopology("((((D:0.4,C:0.4):4.8,((A:0.8,B:0.8):2.2)#H1:2.2::0.7):4.0,(#H1:0::0.3,E:3.0):6.2):2.0,O:11.2);"); Random.seed!(18480224); trait1 = simTraits(net, m, ParamsBM(2, 0.5)) # simulate a BM with mean 2 and variance 0.5 on net trait2 = simTraits(net, m, ParamsBM(-2, 1.0)) # simulate a BM with mean -2 and variance 1.0 on net phylo_noise_var = 0.1 # BM variance-rate meas_noise_var = 0.01 # individual-level msrerr variance phylo_noise = simTraits(net, m, ParamsBM(0, phylo_noise_var)) meas_noise = randn(n*m)*sqrt(meas_noise_var) trait3 = 10 .+ 2 * trait1 + phylo_noise + meas_noise labels = repeat(names(vcv(net)), inner=m) df = DataFrame(trait1=trait1, trait2=trait2, trait3=trait3, tipNames=labels) (2) Species-level data (extra columns for SD and n of trait3) gdf = groupby(df, :species) df_r = combine(gdf, :trait1 => (x -> mean(x)) => :trait1, :trait2 => (x -> mean(x)) => :trait2, :trait3 => (x -> mean(x)) => :trait3, :trait3 => (x -> std(x)) => :trait3_sd, :trait3 => (x -> length(x)) => :trait3_n) =# n = 6; m = 3 net = readTopology("((((D:0.4,C:0.4):4.8,((A:0.8,B:0.8):2.2)#H1:2.2::0.7):4.0,(#H1:0::0.3,E:3.0):6.2):2.0,O:11.2);"); df = DataFrame( species = repeat(["D","C","A","B","E","O"],inner=m), trait1 = [4.08298,4.08298,4.08298,3.10782,3.10782,3.10782,2.17078,2.17078,2.17078,1.87333,1.87333,1.87333,2.8445, 2.8445,2.8445,5.88204,5.88204,5.88204], trait2 = [-7.34186,-7.34186,-7.34186,-7.45085,-7.45085,-7.45085,-3.32538,-3.32538,-3.32538,-4.26472,-4.26472, -4.26472,-5.96857,-5.96857,-5.96857,-1.99388,-1.99388,-1.99388], trait3 = [18.8101,18.934,18.9438,17.0687,17.0639,17.0732,14.4818,14.1112,14.2817,13.0842,12.9562,12.9019,15.4373, 15.4075,15.4317,24.2249,24.1449,24.1302] ) df_r = DataFrame( species = ["D","C","A","B","E","O"], trait1 = [4.08298,3.10782,2.17078,1.87333,2.8445,5.88204], trait2 = [-7.34186,-7.45085,-3.32538,-4.26472,-5.96857,-1.99388], trait3 = [18.895966666666666,17.0686,14.291566666666668,12.980766666666666,15.4255,24.166666666666668], trait3_sd = [0.07452397824414288,0.004650806381693211,0.18549690922851855,0.09360001780626576,0.01583792915756317,0.05096433393397276], trait3_n = [3, 3, 3, 3, 3, 3] ) m1 = phylolm(@formula(trait3 ~ trait1), df, net; reml=true, tipnames=:species, withinspecies_var=true) m2 = phylolm(@formula(trait3 ~ trait1), df_r, net; reml=true, tipnames=:species, withinspecies_var=true, y_mean_std=true) m3 = phylolm(@formula(trait3 ~ trait1), df, net; reml=false, tipnames=:species, withinspecies_var=true) m4 = phylolm(@formula(trait3 ~ trait1), df_r, net; reml=false, tipnames=:species, withinspecies_var=true, y_mean_std=true) @testset "agreement across data input" begin # nested test set #= - individual-level data vs when the species-level data: see m1, m2, m3, m4 - permuted data rows: see m1permute, m2permute - w/o withinspecies var: when a species has missing entries vs when the species is completely absent from the data (see m3missingentry, m4missingrow). =# m1permute = phylolm(@formula(trait3 ~ trait1), df[[1,6,11,17,16,18,8,5,9,3,12,7,13,10,2,14,4,15],:], # permute predictor rows net; reml=true,tipnames=:species, withinspecies_var=true) m2permute = phylolm(@formula(trait3 ~ trait1), df_r[[5,2,3,1,6,4],:], net; reml=true, # permute predictor rows tipnames=:species, withinspecies_var=true, y_mean_std=true) @test coef(m1) ≈ [9.65347,2.30357] rtol=1e-4 @test coef(m1permute) ≈ [9.65347,2.30357] rtol=1e-4 @test coef(m2) ≈ [9.65347,2.30357] rtol=1e-4 @test coef(m2permute) ≈ [9.65347,2.30357] rtol=1e-4 @test sigma2_phylo(m1) ≈ 0.156188 rtol=1e-4 @test sigma2_phylo(m1permute) ≈ 0.156188 rtol=1e-4 @test sigma2_phylo(m2) ≈ 0.156188 rtol=1e-4 @test sigma2_phylo(m2permute) ≈ 0.156188 rtol=1e-4 @test sigma2_within(m1) ≈ 0.008634 rtol=1e-4 @test sigma2_within(m1permute) ≈ 0.008634 rtol=1e-4 @test sigma2_within(m2) ≈ 0.008634 rtol=1e-4 @test sigma2_within(m2permute) ≈ 0.008634 rtol=1e-4 @test loglikelihood(m1) ≈ 1.944626 rtol=1e-4 @test loglikelihood(m1permute) ≈ 1.944626 rtol=1e-4 @test loglikelihood(m2) ≈ 1.944626 rtol=1e-4 @test loglikelihood(m2permute) ≈ 1.944626 rtol=1e-4 @test stderror(m1) ≈ [1.3065987324433421,0.27616258597477233] atol=1e-6 @test stderror(m1permute) ≈ [1.3065987324433421,0.27616258597477233] atol=1e-6 @test stderror(m2) ≈ [1.3065987324433421,0.27616258597477233] atol=1e-6 @test stderror(m2permute) ≈ [1.3065987324433421,0.27616258597477233] atol=1e-6 @test nobs(m1) == 18 # 6 species, 18 ind @test nobs(m1permute) == 18 @test residuals(m1) ≈ [-0.16295769587309603,0.2560302141911026,-0.36246083625543507,-0.9880623366773218,-0.78049231427113,0.9634719640663754] atol=1e-6 # indexin(df[[1,6,11,17,16,18,8,5,9,3,12,7,13,10,2,14,4,15],:].species |> unique, df.species |> unique) == [1,2,4,6,3,5] @test residuals(m1permute) ≈ [-0.16295769587309603,0.2560302141911026,-0.36246083625543507, -0.9880623366773218,-0.78049231427113,0.9634719640663754][[1,2,4,6,3,5]] atol=1e-6 @test residuals(m2) ≈ [-0.16295769587309603,0.2560302141911026,-0.36246083625543507,-0.9880623366773218,-0.78049231427113,0.9634719640663754] atol=1e-6 @test residuals(m2permute) ≈ [-0.16295769587309603,0.2560302141911026,-0.36246083625543507, -0.9880623366773218,-0.78049231427113,0.9634719640663754][[5,2,3,1,6,4]] atol=1e-6 @test dof_residual(m1) == 4 @test dof_residual(m1permute) == 4 @test dof(m1) == 4 dfmissingentry = allowmissing(df); dfmissingentry.trait1[1:3] .= missing # remove entire trait1 col for species D m3missingentry = phylolm(@formula(trait3 ~ trait1), dfmissingentry, net; reml=false, # not using data from species D tipnames=:species, withinspecies_var=true) df_rmissingrow = copy(df_r); df_rmissingrow = df_rmissingrow[2:6,:] # remove entire row for species D m4missingrow = phylolm(@formula(trait3 ~ trait1), df_rmissingrow, net; reml=false, # not using data from species D tipnames=:species, withinspecies_var=true, y_mean_std=true) @test coef(m3) ≈ [9.63523,2.30832] rtol=1e-4 @test coef(m4) ≈ [9.63523,2.30832] rtol=1e-4 @test coef(m3missingentry) ≈ coef(m4missingrow) rtol=1e-4 @test sigma2_phylo(m3) ≈ 0.102255 rtol=1e-4 @test sigma2_phylo(m4) ≈ 0.102255 rtol=1e-4 @test sigma2_phylo(m3missingentry) ≈ sigma2_phylo(m4missingrow) rtol=1e-4 @test sigma2_within(m3) ≈ 0.008677 rtol=1e-4 @test sigma2_within(m4) ≈ 0.008677 rtol=1e-4 @test sigma2_within(m3missingentry) ≈ sigma2_within(m4missingrow) rtol=1e-4 @test loglikelihood(m3) ≈ 1.876606 rtol=1e-4 @test loglikelihood(m4) ≈ 1.876606 rtol=1e-4 @test loglikelihood(m3missingentry) ≈ loglikelihood(m4missingrow) rtol=1e-4 @test stderror(m3) ≈ [1.0619360781577734, 0.22496955609230126] atol=1e-6 @test stderror(m4) ≈ [1.0619360781577734, 0.22496955609230126] atol=1e-6 @test stderror(m3missingentry) ≈ stderror(m4missingrow) atol=1e-6 @test residuals(m3missingentry) ≈ residuals(m4missingrow) atol=1e-6 end # agreement test subset @testset "model comparison & likelihood ratio test" begin m3null = phylolm(@formula(trait3 ~ 1), df, net; reml=false, tipnames=:species, withinspecies_var=true) m3full = phylolm(@formula(trait3 ~ trait1 + trait2), df, net; reml=false, tipnames=:species, withinspecies_var=true) @test StatsModels.isnested(m3null, m3full) tab = (@test_logs lrtest(m3null, m3, m3full)) @test all(isapprox.(tab.deviance, (13.720216379785523,-3.75321128763398,-4.243488375445074), atol=1e-6)) @test tab.dof == (3, 4, 5) @test all(isapprox.(tab.pval[2:end], (2.9135155795020905e-5,0.4838037279625203), atol=1e-6)) m1null = phylolm(@formula(trait3 ~ 1), df, net; tipnames=:species, withinspecies_var=true) # REML @test !(@test_logs (:error, r"fitted with ML") StatsModels.isnested(m1null, m1)) # REML, different FEs @test_logs (:error, r"same criterion") (@test_throws ArgumentError lrtest(m3null, m1)) # ML and REML m2w = phylolm(@formula(trait3 ~ trait1), df_r, net; tipnames=:species) m5w = phylolm(@formula(trait3 ~ trait1), df[[1,2,4,7,13,18],:], net; tipnames=:species, withinspecies_var=true) @test !(@test_logs (:error, r"same number of obs") StatsModels.isnested(m2, m2w)) @test !(@test_logs (:error, r"same response") StatsModels.isnested(m5w,m2w)) m6w = (@test_logs (:info,r"^Maximum lambda") phylolm(@formula(trait3 ~ trait1), df_r, net; tipnames=:species, model="lambda")) tab = lrtest(m2w, m6w) # both REML, but same predictors @test tab.pval[2] ≈ 0.03928341265297505 atol=1e-6 @test !PhyloNetworks.isnested(PhyloNetworks.PagelLambda(0.1),PhyloNetworks.BM()) @test !PhyloNetworks.isnested(PhyloNetworks.PagelLambda(),PhyloNetworks.ScalingHybrid()) @test !PhyloNetworks.isnested(PhyloNetworks.ScalingHybrid(2.0),PhyloNetworks.PagelLambda()) @test_throws ArgumentError ftest(m3null, m3, m3full) # not the same Y after transformation end # lrt test subset @testset "equivalence with Pagel's lambda on expanded net" begin # find a given named tip or node function getNode(name::String, net::HybridNetwork) i = findfirst(n -> n.name == name, net.node) isnothing(i) && error("Node $(name) was not found in the network.") return net.node[i] end # new column with tip ids, initialized to species names dfbig = deepcopy(df) insertcols!(dfbig, 1, :speciesIds => dfbig[!,:species]) # add tips with zero length branches on the network netbig = deepcopy(net) for i in 1:nrow(dfbig) sp_name = dfbig[i, :species]; tip_name = sp_name * string(i) PhyloNetworks.addleaf!(netbig, getNode(sp_name, netbig), tip_name, 0.0) dfbig[i, :speciesIds] = tip_name end # (((((D1:0.0,D2:0.0,D3:0.0)D:0.4,(C4:0.0,C5:0.0,C6:0.0)C:0.4):4.8,(((A7:0.0,A8:0.0,A9:0.0)A:0.8,(B10:0.0,B11:0.0,B12:0.0)B:0.8):2.2)#H1:2.2::0.7):4.0,(#H1:0.0::0.3,(E13:0.0,E14:0.0,E15:0.0)E:3.0):6.2):2.0,(O16:0.0,O17:0.0,O18:0.0)O:11.2); # fit lambda on bigger network m1big = (@test_logs (:info, r"^M") phylolm(@formula(trait3 ~ trait1), dfbig, netbig, model="lambda"; tipnames=:speciesIds)) # equivalent phylo and within variances net_height = maximum(PhyloNetworks.getHeights(net)); sig_phy_2 = sigma2_phylo(m1big) * lambda_estim(m1big); sig_err_2 = sigma2_phylo(m1big) * (1 - lambda_estim(m1big)) * net_height; @test sigma2_phylo(m1) ≈ sig_phy_2 atol=1e-7 @test sigma2_within(m1) ≈ sig_err_2 atol=1e-9 # equivalent lambda value; equivalent coefficients and other w_var_lambda = sigma2_phylo(m1) / (sigma2_within(m1) / net_height + sigma2_phylo(m1)); @test w_var_lambda ≈ lambda_estim(m1big) atol=1e-8 @test coef(m1) ≈ coef(m1big) atol=1e-7 @test mu_phylo(m1) ≈ mu_phylo(m1big) atol=1e-7 @test vcov(m1) ≈ vcov(m1big) atol=1e-6 @test stderror(m1) ≈ stderror(m1big) atol=1e-6 @test nobs(m1) ≈ nobs(m1big) atol=1e-10 @test dof(m1) ≈ dof(m1big) atol=1e-10 @test deviance(m1) ≈ deviance(m1big) atol=1e-10 @test loglikelihood(m1) ≈ loglikelihood(m1big) atol=1e-10 # what differs: residuals, response, predict (not same length) # also differs: dof_residuals (18-2=16 vs 6-2=4), and so predint end allowmissing!(df, [:trait3]); df[4:6,:trait3] .= missing # species C missing allowmissing!(df_r,[:trait3]); df_r[2,:trait3] = missing # to check imputation @testset "ancestral state prediction, intercept only" begin m1 = phylolm(@formula(trait3 ~ 1), df_r, net; tipnames=:species, withinspecies_var=true, y_mean_std=true) ar1 = (@test_logs (:warn, r"^T") ancestralStateReconstruction(m1)) # ar.NodeNumbers[8] == 2 (looking at node #2), m1.V.tipNames[indexin([2],m1.V.tipNumbers)[1]] == "C" (looking at tip "C") @test ar1.traits_nodes[8] ≈ 18.74416393519304 rtol=1e-5 # masked sampled C_bar was 17.0686 @test predint(ar1)[8,:] ≈ [15.24005506417728,22.2482728062088] rtol=1e-5 # on dataframe with model passed as keyword args. must be individual data. ar2 = (@test_logs (:warn, r"^T") ancestralStateReconstruction(df[!,[:species,:trait3]], net; tipnames=:species, withinspecies_var=true)) @test ar2.traits_nodes ≈ ar1.traits_nodes rtol=1e-5 @test predint(ar2) ≈ predint(ar1) rtol=1e-5 # When withinspecies_var=true, predicted values at the tips are part of # "traits_nodes", not "traits_tips", and differ from the observed sample means. @test length(ar1.traits_tips) == 0 @test length(ar2.traits_tips) == 0 @test length(ar1.traits_nodes) == 13 @test length(ar2.traits_nodes) == 13 @test ar1.traits_nodes[9] ≈ 18.895327175656757 # for tip D: observed 18.896 @test predint(ar1)[9,:] ≈ [18.73255168713768,19.058102664175834] # narrow end @testset "ancestral state prediction, more than intercept" begin m3 = phylolm(@formula(trait3 ~ trait1 + trait2), df[[1,6,11,17,16,18,8,5,9,3,12,7,13,10,2,14,4,15],:], net; tipnames=:species, withinspecies_var=true) X_n = [m3.X;m3.X[1:3,:]] # 8x3 Array ar3 = (@test_logs (:warn, r"^T") ancestralStateReconstruction(m3, X_n)) m4 = phylolm(@formula(trait3 ~ trait1 + trait2), df_r[[1,4,6,3,2,5],:], net; tipnames=:species, withinspecies_var=true, y_mean_std=true) ar4 = (@test_logs (:warn, r"^T") ancestralStateReconstruction(m4, X_n)) @test ar3.NodeNumbers == ar4.NodeNumbers @test ar3.traits_nodes ≈ ar4.traits_nodes rtol=1e-5 @test ar3.variances_nodes ≈ ar4.variances_nodes rtol=1e-5 @test size(expectations(ar4)) == (13, 2) @test expectationsPlot(ar4)[8,2] == "24.84*" @test expectationsPlot(ar3)[8,2] == "24.84*" @test predint(ar3)[13,:] ≈ [15.173280800793783,15.677786825808212] rtol=1e-5 # narrow at tip with data @test predint(ar3)[7,:] ≈ [10.668220499837211,15.322037065478693] rtol=1e-5 # wide at a root p3 = predintPlot(ar3) p4 = predintPlot(ar4) @test p3[!,:nodeNumber] == p4[!,:nodeNumber] @test p3[13,2] == "[15.17, 15.68]" @test p4[13,2] == "[15.17, 15.68]" @test p3[7,2] == "[10.67, 15.32]" @test p4[7,2] == "[10.67, 15.32]" end # test subset end # test set: withinspecies_var on network h=1
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
13290
if !(@isdefined doalltests) doalltests = false; end @testset "manipulateNet" begin @testset "test: auxiliary" begin global net net = readTopology("((((B:102.3456789)#H1)#H2,((D:0.00123456789,C,#H2:::0.123456789)S1,(#H1,A_coolname)S2)S3)S4);") s = IOBuffer() @test_logs printEdges(s, net) @test String(take!(s)) == """ edge parent child length hybrid isMajor gamma containRoot inCycle istIdentitiable 1 2 1 102.346 false true 1 false -1 false 2 3 2 true true false -1 true 3 10 3 true true 0.8765 true -1 true 4 6 4 0.001 false true 1 true -1 false 5 6 5 false true 1 true -1 false 6 6 3 true false 0.1235 true -1 true 7 9 6 false true 1 true -1 true 8 8 2 true false true -1 true 9 8 7 false true 1 true -1 false 10 9 8 false true 1 true -1 true 11 10 9 false true 1 true -1 true """ close(s); s = IOBuffer() @test_logs printNodes(s, net) @test String(take!(s)) == """ node leaf hybrid hasHybEdge name inCycle edges'numbers 1 true false false B -1 1 2 false true true H1 -1 1 2 8 3 false true true H2 -1 2 3 6 4 true false false D -1 4 5 true false false C -1 5 6 false false true S1 -1 4 5 6 7 7 true false false A_coolname -1 9 8 false false true S2 -1 8 9 10 9 false false false S3 -1 7 10 11 10 false false true S4 -1 3 11 """ close(s); originalstdout = stdout redirect_stdout(devnull) printEdges(net) # method without io argument printNodes(net) redirect_stdout(originalstdout) @test_throws ErrorException getparent(net.node[net.root]) @test_throws ErrorException getparentedge(net.node[net.root]) @test_throws ErrorException getparentedgeminor(net.node[net.root]) @test_throws ErrorException getparentminor(net.node[1]) @test getparent(net.node[1]).number == 2 @test getparentminor(net.node[3]).number == 6 @test getparent(net.node[3]).number == 10 @test getparentedge(net.node[6]).number == 7 @test_throws ErrorException getparentedgeminor(net.node[6]) @test getparentedge(net.node[2]).number == 2 @test getparentedgeminor(net.node[2]).number == 8 @test [n.number for n in getchildren(net.node[4])] == [] # leaf @test [n.number for n in getchildren(net.node[2])] == [1] # hybrid node @test [n.number for n in getchildren(net.node[9])] == [6,8] # tree node @test [n.number for n in getchildren(net.node[10])] == [3,9] # at root @test [n.number for n in getchildren(net.node[6])] == [4,5,3] # polytomy @test getparent(net.edge[8]).number == 8 @test [n.number for n in getparents(net.node[3])] == [10, 6] @test [n.number for n in getparents(net.node[6])] == [9] @test_throws ErrorException deleteleaf!(net, net.node[9]) n = deepcopy(net) @test_logs deleteleaf!(n, n.node[7]) @test n.numNodes == 8; @test n.numEdges == 9; @test_logs deleteleaf!(net, net.node[7], simplify=false) deleteleaf!(net, 4, simplify=false); deleteleaf!(net, 5, simplify=false) @test net.numNodes == 5; @test net.numEdges == 6; # below: 3 taxa, h=2, hybrid ladder but no 2-cycle. pruning t9 removes both hybrids. nwkstring = "((t7:0.23,#H19:0.29::0.47):0.15,(((#H23:0.02::0.34)#H19:0.15::0.53,(t9:0.06)#H23:0.02::0.66):0.09,t6:0.17):0.21);" net = readTopology(nwkstring) @test_throws Exception deleteleaf!(net, "t1") # no leaf named t1 net.node[1].name = "t9" @test_throws Exception deleteleaf!(net, "t9") # 2+ leaves named t1 @test_throws Exception deleteleaf!(net, 10, index=true) # <10 nodes net.node[1].name = "t7" # back to original name deleteleaf!(net, "t9", nofuse=true) @test writeTopology(net) == "((t7:0.23):0.15,(t6:0.17):0.21);" deleteleaf!(net, "t7") @test writeTopology(net) == "(t6:0.17);" @test_logs (:warn, r"^Only 1 node") deleteleaf!(net, "t6") @test isempty(net.edge) @test isempty(net.node) end @testset "testing directEdges! and re-rootings" begin # on a tree, then on a network with h=2" if doalltests tre = readTopology("(((((((1,2),3),4),5),(6,7)),(8,9)),10);"); tre.edge[1].isChild1=false; tre.edge[17].isChild1=false directEdges!(tre) tre.edge[1].isChild1 || error("directEdges! didn't correct the direction of 1st edge") tre.edge[17].isChild1 || error("directEdges! didn't correct the direction of 17th edge") for i=1:18 tre.edge[i].containRoot=false; end; tre.root = 9; directEdges!(tre); !tre.edge[9].isChild1 || error("directEdges! didn't correct the direction of 9th edge") for i=1:18 tre.edge[i].containRoot || error("directEdges! didn't correct containRoot of $(i)th edge.") end tre = readTopology("(((((((1,2),3),4),5),(6,7)),(8,9)),10);"); rootatnode!(tre, -9); ## clau: previously -8 end global net net = readTopology("(((Ag,(#H1:7.159::0.056,((Ak,(E:0.08,#H2:0.0::0.004):0.023):0.078,(M:0.0)#H2:::0.996):2.49):2.214):0.026,(((((Az:0.002,Ag2:0.023):2.11,As:2.027):1.697)#H1:0.0::0.944,Ap):0.187,Ar):0.723):5.943,(P,20):1.863,165);"); # 5th node = node number -7 (clau: previously -6). net.root = 5 @test_logs directEdges!(net); @test !net.edge[12].isChild1 # or: directEdges! didn't correct the direction of 12th edge @test !net.edge[23].isChild1 # or: directEdges! didn't correct the direction of 23th edge" @test [!net.edge[i].containRoot for i in [8;collect(13:17)]] == [true for i in 1:6] # or: "directEdges! didn't correct containRoot below a hyb node, $(i)th edge." @test [net.edge[i].containRoot for i in [9,5,18,2]] == [true for i in 1:4] # or: "directEdges! didn't correct containRoot of hyb edges." @test_logs rootatnode!(net, -10); # or: rootatnode! complained, node -10 @test_throws PhyloNetworks.RootMismatch rootatnode!(net, "M"); # println("the rootmismatch about node 5 is good and expected.") @test_logs rootonedge!(net, 9); # or: rootonedge! complained, edge 9 @test_logs PhyloNetworks.fuseedgesat!(27, net); # earlier warning: """node 1 is a leaf. Will create a new node if needed, to set taxon "Ag" as outgroup.""" @test_logs rootatnode!(net, "Ag"); # need for new node # earlier: """node 1 is a leaf. Will create a new node if needed, to set taxon "Ag" as outgroup.""" @test_logs rootatnode!(net, "Ag"); # no need this time @test length(net.node) == 27 # or: wrong # of nodes after rootatnode! twice on same outgroup # earlier: """node 10 is a leaf. Will create a new node if needed, to set taxon "Ap" as outgroup.""" @test_logs rootatnode!(net, "Ap"); @test length(net.node) == 27 # or: wrong # of nodes, after 3rd rooting with outgroup @test_logs rootonedge!(net, 5); # example with one hybridization below another if doalltests net = readTopology("((((((((1,2),3),4),(5)#H1),(#H1,(6,7))))#H2,(8,9)),(#H2,10));"); # sum([!e.containRoot for e in net.edge]) # only 4. directEdges!(net); # or error("directEdges! says that the root position is incompatible with hybrids") sum([!e.containRoot for e in net.edge]) == 16 || error("directEdges! wrong on net with 2 stacked hybrids"); plot(net, showedgenumber=true, showedgelength=false, shownodenumber=true); net = readTopology("((((((((1,2),3),4),(5)#H1),(#H1,(6,7))))#H2,(8,9)),(#H2,10));"); net.root=19; # node number -13 (clau: previously -12) directEdges!(net); # or error("directEdges! says that the root position is incompatible with hybrids"); end net = readTopology("((((((((1,2),3),4),(5)#H1),(#H1,(6,7))))#H2,(8,9)),(#H2,10));"); net.root=15; # node number -5 (clau: previously -4) @test_throws PhyloNetworks.RootMismatch directEdges!(net); # occursin(r"non-leaf node 9 had 0 children",e.msg)) @test_logs rootatnode!(net, -13); # or: rootatnode complained... @test_throws PhyloNetworks.RootMismatch rootatnode!(net, -5); # occursin(r"non-leaf node 9 had 0 children", e.msg)) @test_throws PhyloNetworks.RootMismatch rootatnode!(net,"H2"); #try rethrow(); # occursin(r"hybrid edge 17 conflicts", e.msg)) # earlier: """node 12 is a leaf. Will create a new node if needed, to set taxon "10" as outgroup.""" @test_logs rootatnode!(net,"10"); end # of testset for directEdges! and re-rootings @testset "testing preorder!" begin # on a tree, then on a network with h=2 global net tre = readTopology("(((((((1,2),3),4),5),(6,7)),(8,9)),10);"); net = readTopology("(((Ag,(#H1:7.159::0.056,((Ak,(E:0.08,#H2:0.0::0.004):0.023):0.078,(M:0.0)#H2:::0.996):2.49):2.214):0.026,(((((Az:0.002,Ag2:0.023):2.11,As:2.027):1.697)#H1:0.0::0.944,Ap):0.187,Ar):0.723):5.943,(P,20):1.863,165);"); if doalltests preorder!(tre) ## clau: previously [-1,10,-2,-9,9,8,-3,-8,7,6,-4,5,-5,4,-6,3,-7,2,1]; nodeN = [-2,10,-3,-10,9,8,-4,-9,7,6,-5,5,-6,4,-7,3,-8,2,1]; for i=1:length(tre.node) tre.nodes_changed[i].number==nodeN[i] || error("node pre-ordered $i is node number $(tre.nodes_changed[i].number) instead of $(nodeN[i])") end end @test_logs preorder!(net) ## clau previously: [-1,14,-14,13,12,-2,-9,11,-10,10,-3,-4,-5,-6,-7,5,6,4,3,2,-12,9,-13,8,7,1]; nodeN = [-2,14,-15,13,12,-3,-10,11,-11,10,-4,-5,-6,-7,-8,5,6,4,3,2,-13,9,-14,8,7,1]; @test [n.number for n in net.nodes_changed] == nodeN cui3str = "(Xmayae,((Xhellerii,(((Xclemenciae_F2,Xmonticolus):1.458,(((((Xmontezumae,(Xnezahuacoyotl)#H26:0.247::0.804):0.375,((Xbirchmanni_GARC,Xmalinche_CHIC2):0.997,Xcortezi):0.455):0.63,(#H26:0.0::0.196,((Xcontinens,Xpygmaeus):1.932,(Xnigrensis,Xmultilineatus):1.401):0.042):2.439):2.0)#H7:0.787::0.835,(Xmaculatus,(Xandersi,(Xmilleri,((Xxiphidium,#H7:9.563::0.165):1.409,(Xevelynae,(Xvariatus,(Xcouchianus,(Xgordoni,Xmeyeri):0.263):3.532):0.642):0.411):0.295):0.468):0.654):1.022):0.788):1.917)#H27:0.149::0.572):0.668,Xalvarezi):0.257,(Xsignum,#H27:1.381::0.428):4.669);" net3 = readTopology(cui3str); deleteleaf!(net3,"Xhellerii"); deleteleaf!(net3,"Xsignum"); deleteleaf!(net3,"Xmayae", simplify=false, unroot=true); # now: net3 has a 2-cycle directEdges!(net3) preorder!(net3) @test [n.number for n in net3.nodes_changed] == [-3,25,-6,-8,-20,-21,-22,-23,-25,-26,-27,-28,24,23,22,21,20,-24,15,-10,-16,-17,-19,14,13,-18,12,11,-11,-14,10,-15,9,8,-12,7,6,5,19,18,17,16,-7,4,3,26] end # of testset for preorder! @testset "testing cladewiseorder!" begin # on a tree then network with h=2 # cladewiseorder! is used for plotting: to avoid crossing edges in main tree if doalltests cladewiseorder!(tre) nodeN = collect(19:-1:1); for i=1:length(tre.node) tre.cladewiseorder_nodeIndex[i]==nodeN[i] || error("node clade-wise ordered $i is $(tre.cladewiseorder_nodeIndex[i])th node instead of $(nodeN[i])th") end end @test_logs cladewiseorder!(net) nodeN = collect(26:-1:1); @test net.cladewiseorder_nodeIndex == nodeN end # of testset for cladewiseorder! @testset "testing rotate!" begin # to change the order of children edges at a given node if doalltests net = readTopology("(A:1.0,((B:1.1,#H1:0.2::0.2):1.2,(((C:0.52,(E:0.5)#H2:0.02::0.7):0.6,(#H2:0.01::0.3,F:0.7):0.8):0.9,(D:0.8)#H1:0.3::0.8):1.3):0.7):0.1;"); rotate!(net, -5) ## clau: previously -4 [e.number for e in net.node[13].edge] == [14,12,15] || error("rotate didn't work at node -5"); ## clau: previously -4 plot(net); # just to check no error. end global net net=readTopology("(4,((1,(2)#H7:::0.864):2.069,(6,5):3.423):0.265,(3,#H7:::0.136):10.0);"); @test_logs rotate!(net, -2, orderedEdgeNum=[1,12,9]) @test [e.number for e in net.node[12].edge] == [1,12,9] # or: rotate didn't work at node -2 end # of testset for rotate @testset "other in manipulateNet" begin net0 = readTopology("((((C:0.9)I1:0.1)I3:0.1,((A:1.0)I2:0.4)I3:0.6):1.4,(((B:0.2)H1:0.6)I2:0.5)I3:2.1);"); removedegree2nodes!(net0, true) # true: to keep the root of degree-2 @test writeTopology(net0, round=true) == "((C:1.1,A:2.0):1.4,B:3.4);" #--- delete above least stable ancestor ---# # 3 blobs above LSA: cut edge + level-2 blob + cut edge. net = readTopology("(((((#H25)#H22:::0.8,#H22),((t2:0.1,t1))#H25:::0.7)));") PhyloNetworks.deleteaboveLSA!(net) @test writeTopology(net) == "(t2:0.1,t1);" # 2 separate non-trivial clades + root edge net = readTopology("((((t1,t2):0.1,(t3:0.3,t4)):0.4));") PhyloNetworks.deleteaboveLSA!(net) @test writeTopology(net) == "((t1,t2):0.1,(t3:0.3,t4));" # 1 tip + 2-cycle above it, no extra root edge above, hybrid LSA net = readTopology("((t1)#H22:::0.8,#H22);") PhyloNetworks.deleteaboveLSA!(net) @test writeTopology(net) == "(t1)H22;" @test isempty(net.hybrid) @test [n.name for n in net.nodes_changed] == ["H22","t1"] # deleteleaf! and removedegree2nodes! when the root starts a 2-cycle net = readTopology("((a,(((b)#H1,#H1))#H2),(#H2));") deleteleaf!(net, "a") @test writeTopology(net) == "((#H2),(((b)#H1,#H1))#H2);" removedegree2nodes!(net) @test writeTopology(net) == "((((b)#H1,#H1))#H2,#H2);" net = readTopology("((a,(((b)#H1,#H1))#H2),#H2);") # no degree-2 node adjacent to root this time deleteleaf!(net, "a", unroot=true) @test writeTopology(net) == "(b)H1;" end # of testset for other functions in manipulateNet end # of overall testset for this file
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
32085
#= # for local testing, need this: using Test using PhyloNetworks using Random =# @testset "moveTargetUpdate! reject 2-cycle proposal" begin net3c_newick = "(1,2,(((3,4))#H1:::0.6,(#H1:::0.4,(5,6))));" # 3-cycle adjacent to 3 cherries net3 = readTopologyLevel1(net3c_newick) # net3.node[6].isBadTriangle : not isVeryBadTriangle nor isExtBadTriangle hn = net3.hybrid[1] # more robust than net3.node[6] tmp = PhyloNetworks.moveTargetUpdate!(net3, hn, getparentedge(hn), net3.edge[11]) @test !any(tmp) end @testset "unconstrained NNI moves" begin str_level1 = "(((S8,S9),(((((S1,S2,S3),S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" net_level1 = readTopology(str_level1); # this network has a polytomy at node -9 # same topology as: rootatnode!(net_level1, -3). edges 1:22 str_nontreechild = "((((Ag,E))#H3,(#H1:7.159::0.056,((M:0.0)#H2:::0.996,(Ak,(#H3:0.08,#H2:0.0::0.004):0.023):0.078):2.49):2.214):0.026,((Az:2.13,As:2.027):1.697)#H1:0.0::0.944,Ap);" net_nontreechild = readTopology(str_nontreechild); # problem: the plot has an extra vertical segment, for a clade that's not in the major tree # --> fix that in PhyloPlots (fixit) str_hybridladder = "(#H2:::0.2,((C,((B)#H1)#H2:::0.8),(#H1,(A1,A2))),O);" net_hybridladder = readTopology(str_hybridladder); @test isnothing(nni!(net_level1, net_level1.edge[1], 0x01, true, true)) # external edge @testset "level1 edge 3: BB undirected move $move" for move in 0x01:0x08 undoinfo = nni!(net_level1, net_level1.edge[3], move, true, true); #location of v node (number -4) nodes = [n.number for n in net_level1.edge[20].node] #α's connections if move in [1, 2, 6, 8] #check that edge α connected to v @test -4 in nodes else @test !(-4 in nodes) end #location of u node (number -3) nodes = [n.number for n in net_level1.edge[1].node] if move in [2, 4, 5, 6] #check that edge γ connected to u @test -3 in nodes else @test !(-3 in nodes) end # check directionality if move in [3, 4, 5, 7] # keeping α, β or flipping uv keeps node -4 as child of edge 3 @test PhyloNetworks.getchild(net_level1.edge[3]).number == -4 else # switching α, β AND flipping uv or doing neither makes node -3 child of edge 3 @test PhyloNetworks.getchild(net_level1.edge[3]).number == -3 end # undo move nni!(undoinfo...); # confirm we're back to original topology @test writeTopology(net_level1) == str_level1 end # of level1 edge 3: BB undirected @testset "level1 test edge 13: BR directed move $move" for move in 0x01:0x03 # e.hybrid and tree parent: BR case, 3 moves because e cannot contain the root # 3cycle test: α connected to γ so move 1 will create 3 cycles. if move == 0x01 @test isnothing(nni!(net_level1, net_level1.edge[13], move, true, true)) # would create a 3cycle # move 1 would create a 3 cycle, but should work if we don't forbid 3cycles undoinfo = nni!(net_level1, net_level1.edge[13], move, true, false); #no3cycle=false nodes = [n.number for n in net_level1.edge[17].node] @test 8 in nodes # check that edge α connected to v nodes = [n.number for n in net_level1.edge[11].node] @test !(-11 in nodes) @test PhyloNetworks.getchild(net_level1.edge[13]).number == -11 nni!(undoinfo...); # undo move @test writeTopology(net_level1) == "(((S8,S9),(((((S1,S2,S3),S4),(S5:0.0)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" # confirm we're back to original topology (but now with 0.0 branch lengths) else undoinfo = nni!(net_level1, net_level1.edge[13], move, true, false); # test that move was made nodes = [n.number for n in net_level1.edge[17].node] if move == 0x03 @test 8 in nodes # check that edge α connected to v else @test !(8 in nodes) end #location of u node (number -11) nodes = [n.number for n in net_level1.edge[11].node] if move == 0x03 # check that edge γ connected to u @test -11 in nodes else # check that edge δ connected to u @test !(-11 in nodes) end # check directionality @test PhyloNetworks.getchild(net_level1.edge[13]).number == 8 nni!(undoinfo...); # undo move @test writeTopology(net_level1) == "(((S8,S9),(((((S1,S2,S3),S4),(S5:0.0)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));"# confirm we're back to original topology end end # of level1 edge 13: BR directed @testset "level1 edge 16: BB directed move $move" for move in 0x01:0x02 # e not hybrid, tree parent: BB case, 2 NNIs if directed, 8 if undirected undoinfo = nni!(net_level1, net_level1.edge[16], move, true, true); nodes = [n.number for n in net_level1.edge[13].node] #β's connections @test -11 in nodes #check β connected to u node (number -11) nodes = [n.number for n in net_level1.edge[14].node] #γ's connections if move == 1 #check that edge γ connected to v @test -12 in nodes else #check that edge γ connected to u @test -11 in nodes end # check directionality node -11 child of edge 16 in both cases @test PhyloNetworks.getchild(net_level1.edge[16]).number == -11 nni!(undoinfo...); # undo move @test writeTopology(net_level1) == "(((S8,S9),(((((S1,S2,S3),S4),(S5:0.0)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" # confirm we're back to original topology end #of level1 edge 16: BB directed # BB directed has two allowed moves, so 0x03 should throw an exception @test_throws Exception nni!(net_level1, net_level1.edge[16], 0x03); @testset "level1 edge 17: BB directed with 4cycle move $move" for move in 0x01:0x02 # no3cycle test # move 2 should fail because of 3cycle problems # β is connected in a 4 cycle with γ so a move that makes γ and β a pair # would create a 3 cycle if move == 0x01 undoinfo = nni!(net_level1, net_level1.edge[17], move, true, true); nodes = [n.number for n in net_level1.edge[12].node] #β's connections @test -6 in nodes #check β connected to u node (number -6) nodes = [n.number for n in net_level1.edge[13].node] #γ's connections #check that edge γ connected to v @test -11 in nodes # check directionality node -6 child of edge 17 in both cases @test PhyloNetworks.getchild(net_level1.edge[17]).number == -6 nni!(undoinfo...); # undo move @test writeTopology(net_level1) == "(((S8,S9),(((((S1,S2,S3),S4),(S5:0.0)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" else @test isnothing(nni!(net_level1, net_level1.edge[17], move, true, true)) undoinfo = nni!(net_level1, net_level1.edge[17], move, true, false) #should work if we dont check for 3cycles nodes = [n.number for n in net_level1.edge[12].node] #β's connections @test -6 in nodes #check β connected to u node (number -6) nodes = [n.number for n in net_level1.edge[13].node] #γ's connections #check that edge γ connected to u @test -6 in nodes # check directionality node -11 child of edge 17 in both cases @test PhyloNetworks.getchild(net_level1.edge[17]).number == -6 nni!(undoinfo...); # undo move @test writeTopology(net_level1) == "(((S8,S9),(((((S1,S2,S3),S4),(S5:0.0)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" end end # of level1 edge 17: BB directed @testset "level1 edge 18: RR (directed) move $move" for move in 0x01:0x04 # RB case, 4 moves. uv edge cannot contain the root (always directed) undoinfo = nni!(net_level1, net_level1.edge[18], move, true, true); #test that move was made nodes = [n.number for n in net_level1.edge[19].node] #α's connections if move in [0x01, 0x03] @test -6 in nodes #check that edge α connected to v elseif move in [0x02, 0x04] @test !(-6 in nodes) end nodes = [n.number for n in net_level1.edge[12].node] #γ's connections if move in [0x03, 0x04] #check that edge γ connected to u (11) @test 11 in nodes elseif move in [0x01, 0x02] #check that edge δ connected to u, not γ @test !(11 in nodes) end #check directionality (should point toward u, node 11) @test PhyloNetworks.getchild(net_level1.edge[18]).number == 11 nni!(undoinfo...); # edge constrained at 0.0 now @test writeTopology(net_level1) == "(((S8,S9),(((((S1,S2,S3),S4),(S5:0.0)#H1),(#H1,(S6,S7))):0.0)#H2),(#H2,S10));" end # of level1 edge 18: RR (directed) @testset "non tree child net edge 3: RB (directed) move $move" for move in 0x01:0x04 # RB case, 4 moves. uv edge cannot contain the root undoinfo = nni!(net_nontreechild, net_nontreechild.edge[3], move, true, true); #test that move was made #location of v node (node -5) nodes = [n.number for n in net_nontreechild.edge[4].node] #α's connections if move in [0x01, 0x03] #check that edge α connected to v @test -5 in nodes else #check that edge β connected to v, not u @test !(-5 in nodes) end nodes = [n.number for n in net_nontreechild.edge[2].node] #δ's connections if move in [0x01, 0x02] #check that edge δ connected to u @test 3 in nodes else @test !(3 in nodes) end #check directionality (should point toward u, node 3) @test PhyloNetworks.getchild(net_nontreechild.edge[3]).number == 3 #undo move nni!(undoinfo...); # keep constrained edges at 0.0, but otherwise topology completely restored @test writeTopology(net_nontreechild) == "((((Ag,E):0.0)#H3,(#H1:7.159::0.056,((M:0.0)#H2:::0.996,(Ak,(#H3:0.08,#H2:0.0::0.004):0.023):0.078):2.49):2.214):0.026,((Az:2.13,As:2.027):1.697)#H1:0.0::0.944,Ap);" end #of non tree child net edge 5: RB (directed) @testset "hybrid ladder net edge 1: BR undirected (u at root, potential nonDAG, 3cycle) move $move" for move in 0x01:0x06 # BR case, 6 moves. uv edge can contain the root. u at root # DAG check: u is root, so if α -> γ, moves 1 and 3 will create a nonDAG # α -> γ so moves 1 and 3 will fail. # moves 1 and 3 in the notes correspond to 1, 1' and 3, 3' (1, 4 and 3, 6) # 3cycle check: could create 3 cycle (α connected to γ) so moves 1 and 5 forbidden if move in [0x01, 0x03, 0x05, 0x06] # DAG check @test isnothing(nni!(net_hybridladder, net_hybridladder.edge[1], move, false, true)) end if move in [0x01, 0x05] # 3cycle check @test isnothing(nni!(net_hybridladder, net_hybridladder.edge[1], move, true, true)) end if move == 0x04 undoinfo = nni!(net_hybridladder, net_hybridladder.edge[1], move, false, true); nodes = [n.number for n in net_hybridladder.edge[12].node] # α @test !(1 in nodes) # check that edge α is connected to v nodes = [n.number for n in net_hybridladder.edge[4].node] # δ's connections @test -2 in nodes # check that edge δ is connected to u # check directionality (edge should point toward u, node -2) @test PhyloNetworks.getchild(net_hybridladder.edge[1]).number == 1 nni!(undoinfo...); @test writeTopology(net_hybridladder)== "(#H2:::0.2,((C,((B)#H1:0.0)#H2:::0.8),(#H1,(A1,A2))),O);" # restored but edge below hybrid node constrained at 0.0 elseif move == 0x02 undoinfo = nni!(net_hybridladder, net_hybridladder.edge[1], move, true, true); nodes = [n.number for n in net_hybridladder.edge[12].node] # α @test !(1 in nodes) # check that edge α not connected to v nodes = [n.number for n in net_hybridladder.edge[4].node] # δ's connections @test -2 in nodes # δ connected to u # check directionality (edge should point toward u, node -2) @test PhyloNetworks.getchild(net_hybridladder.edge[1]).number == 1 nni!(undoinfo...); @test writeTopology(net_hybridladder) == "(#H2:::0.2,((C,((B)#H1:0.0)#H2:::0.8),(#H1,(A1,A2))),O);" # restored but edge below hybrid node constrained at 0.0 end end # of hybrid ladder net edge 1: BR undirected @testset "hybrid ladder net edge 4: RR (directed) move $move" for move in 0x01:0x02 # RR case, 2 moves. uv edge cannot contain the root (always directed) undoinfo = nni!(net_hybridladder, net_hybridladder.edge[4], move, false, true); #test that move was made nodes = [n.number for n in net_hybridladder.edge[5].node] #α's connections if move == 0x01 #check that edge α connected to v @test 4 in nodes else move == 0x02 #check that edge β connected to v, not α @test !(4 in nodes) end #check that edge δ connected to u, not γ nodes = [n.number for n in net_hybridladder.edge[3].node] @test 1 in nodes #check directionality (should point toward u, node 1) @test PhyloNetworks.getchild(net_hybridladder.edge[4]).number == 1 #undo move nni!(undoinfo...); @test writeTopology(net_hybridladder) == "(#H2:::0.2,((C,((B)#H1:0.0)#H2:::0.8),(#H1,(A1,A2))),O);" # restored but edge below hybrid node constrained at 0.0 end #of hybrid ladder net edge 4: RR (directed) @testset "hybrid ladder net edge 5: BR undirected move $move" for move in 0x01:0x06 # BR case, 6 moves. uv edge can contain the root # 3 cycle test: α connected to γ, α -> u # moves 1, 5 forbidden # DAG test: # no path from α -> γ or β -> γ so all moves should work if move in [0x01, 0x05] @test isnothing(nni!(net_hybridladder, net_hybridladder.edge[5], move, false, true)) # 3-cycles forbidden undoinfo = nni!(net_hybridladder, net_hybridladder.edge[5], move, false, false) # 3-cycles allowed else undoinfo = nni!(net_hybridladder, net_hybridladder.edge[5], move, false, true); end #tests for all moves: nodes = [n.number for n in net_hybridladder.edge[6].node] #α if move in [0x01, 0x03, 0x05, 0x06] @test 1 in nodes #check that edge α connected to v else @test !(1 in nodes) #check that edge α not connected to v end nodes = [n.number for n in net_hybridladder.edge[4].node] #δ's connections if move in [0x01, 0x02, 0x04, 0x05] @test -4 in nodes #δ connected to u else @test !(-4 in nodes) end #check directionality if move in [0x01, 0x05] #(edge should point toward u, node -4) @test PhyloNetworks.getchild(net_hybridladder.edge[5]).number == -4 else @test PhyloNetworks.getchild(net_hybridladder.edge[5]).number == 1 end #undo move nni!(undoinfo...); @test writeTopology(net_hybridladder) == "(#H2:::0.2,((C,((B)#H1:0.0)#H2:::0.8),(#H1,(A1,A2))),O);" # restored but edge below hybrid node constrained at 0.0 end #of hybrid ladder net edge 5: BR undirected @testset "hybrid ladder net edge 12: BB undirected (edge below root) move $move" for move in 0x01:0x08 # BB case, 8 moves. uv edge can contain the root. no flip. # no3cycle: moves 1, 4, 5, 8 would create a 3 cycle because α is connected to γ if move in [0x01, 0x04, 0x05, 0x08] @test isnothing(nni!(net_hybridladder, net_hybridladder.edge[12], move, true, true)) undoinfo = nni!(net_hybridladder, net_hybridladder.edge[12], move, true, false); else undoinfo = nni!(net_hybridladder, net_hybridladder.edge[12], move, true, true); end nodes = [n.number for n in net_hybridladder.edge[1].node] #α if move in [0x01, 0x02, 0x06, 0x08] @test -3 in nodes #check that edge α connected to v else @test !(-3 in nodes) #check that edge α not connected to v end nodes = [n.number for n in net_hybridladder.edge[11].node] #δ's connections if move in [0x01, 0x03, 0x07, 0x08] @test -2 in nodes #δ connected to u else @test !(-2 in nodes) end #check directionality @test PhyloNetworks.getchild(net_hybridladder.edge[12]).number == -3 #undo move nni!(undoinfo...); @test writeTopology(net_hybridladder) == "(#H2:::0.2,((C,((B)#H1:0.0)#H2:::0.8),(#H1,(A1,A2))),O);" # restored but edge below hybrid node constrained at 0.0 end # of hybrid ladder net edge 12: BB undirected (edge below root) @testset "test isdescendant and isconnected functions" begin net_level1 = readTopology(str_level1); @test PhyloNetworks.isdescendant(net_level1.node[7], net_level1.node[17]) # nodes -9, -6 @test !PhyloNetworks.isdescendant(net_level1.node[7], net_level1.node[3]) # nodes -9, -4 @test PhyloNetworks.isdescendant(net_level1.node[15], net_level1.node[17]) # nodes -12, -6 @test !PhyloNetworks.isdescendant(net_level1.node[12], net_level1.node[12]) @test PhyloNetworks.isconnected(net_level1.node[12], net_level1.node[17]) # nodes -7, -6 @test !PhyloNetworks.isconnected(net_level1.node[12], net_level1.node[19]) # nodes -7, -3 # mess up the direction of some tree edges, then check descendence relationships with isdescendant_undirected for i in [4,5,6,7,9,10,12,17,3,20] net_level1.edge[i].isChild1 = !net_level1.edge[i].isChild1; end @test PhyloNetworks.isdescendant_undirected(net_level1.node[7], net_level1.node[17], net_level1.edge[18]) @test !PhyloNetworks.isdescendant_undirected(net_level1.node[7], net_level1.node[3], net_level1.edge[3]) @test PhyloNetworks.isdescendant_undirected(net_level1.node[15], net_level1.node[17], net_level1.edge[18]) @test !PhyloNetworks.isdescendant_undirected(net_level1.node[12], net_level1.node[12], net_level1.edge[12]) end end # of testset on unconstrained NNIs @testset "constrained NNI moves" begin # subsets for: species constraints; move root (species & clade constraints); # clade constraints (not yet: TODO) @testset "species constraints" begin # multiple individuals from each species str_level1_s = "(((S8,S9),((((S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" # indviduals S1A S1B S1C go on leaf 1 net_level1_s = readTopology(str_level1_s) # test breakedge! function newnode, newedge = PhyloNetworks.breakedge!(net_level1_s.edge[4], net_level1_s); @test length(net_level1_s.node) == 20 @test length(net_level1_s.edge) == 21 @test newnode.edge[1].number == 4 @test newnode.edge[2].number == 21 @test PhyloNetworks.getparent(net_level1_s.edge[4]) === newnode @test PhyloNetworks.getchild(newedge) === newnode # test addleaf! function net_level1_s = readTopology(str_level1_s) PhyloNetworks.addleaf!(net_level1_s, net_level1_s.node[4], "S1A"); @test !net_level1_s.node[findfirst([n.number == 3 for n in net_level1_s.node])].leaf PhyloNetworks.addleaf!(net_level1_s, net_level1_s.node[4], "S1B"); PhyloNetworks.addleaf!(net_level1_s, net_level1_s.node[4], "S1C"); @test net_level1_s.edge[21].containRoot == false # check containRoot on edge 4 and exterior edges @test net_level1_s.edge[22].containRoot == false @test PhyloNetworks.getchild(net_level1_s.edge[21]).name == "S1A" @test PhyloNetworks.getchild(net_level1_s.edge[22]).name == "S1B" # test addleaf! on edge net_level1_s = readTopology(str_level1_s) PhyloNetworks.addleaf!(net_level1_s, net_level1_s.edge[4], "S1A"); @test length(net_level1_s.node) == 21 @test net_level1_s.node[21].leaf # test addindividuals! function net_level1_s = readTopology(str_level1_s) PhyloNetworks.addindividuals!(net_level1_s, "S1", ["S1A", "S1B", "S1C"]) @test !net_level1_s.node[findfirst([n.number == 3 for n in net_level1_s.node])].leaf @test length(net_level1_s.node[findfirst([n.number == 3 for n in net_level1_s.node])].edge) == 4 # spaces in name net_level1_s = readTopology(str_level1_s) @test_logs (:warn, r"^species S 1 not") PhyloNetworks.addindividuals!(net_level1_s, "S 1", ["S1A", "S1B", "S1C"]) @test writeTopology(net_level1_s) == str_level1_s # network unchanged @test_logs (:warn, r"^Spaces in \"S1 A\" may cause errors") PhyloNetworks.addindividuals!(net_level1_s, "S1", ["S1 A", "S1B", "S1C"]) @test writeTopology(net_level1_s) == "(((S8,S9),(((((S1_A,S1B,S1C)S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" # test mapindividuals function net_level1_s = readTopology(str_level1_s) # in net env filename = joinpath(@__DIR__, "..","examples","mappingIndividuals.csv") # filename = abspath(joinpath(dirname(Base.find_package("PhyloNetworks")), "..", "examples", "mappingIndividuals.csv")) net_level1_i, c_species = PhyloNetworks.mapindividuals(net_level1_s, filename) @test string(c_species[1]) == "Species constraint, on tips: S1A, S1B, S1C\n stem edge number 4\n crown node number 3" @test c_species[1].taxonnames == ["S1A","S1B","S1C"] @test c_species[1].taxonnums == Set([11,12,13]) @test writeTopology(net_level1_i) == "(((S8,S9),(((((S1A,S1B,S1C)S1,S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" # test clade constraint contructor c_clade = PhyloNetworks.TopologyConstraint(0x02, ["S1A","S1B","S1C","S4"], net_level1_i) @test string(c_clade) == "Clade constraint, on tips: S1A, S1B, S1C, S4\n stem edge number 6\n crown node number -8" # test errors in species constructor @test_throws ErrorException PhyloNetworks.TopologyConstraint(0x02, ["S1A"], net_level1_i) # only 1 tip @test_throws ErrorException PhyloNetworks.TopologyConstraint(0x02, ["S1A", "TypoTaxa"], net_level1_i) # typo @test_throws ErrorException PhyloNetworks.TopologyConstraint(0x02, ["S1A", "S8"], net_level1_i) # not a clade # NNIs under species constraints Random.seed!(1234); # no nni on stem edge for species example @test isnothing(nni!(net_level1_i , net_level1_i.edge[4], true, true, c_species)) @testset "NNI, 1 species constraint, net level 1, edge $ei" for ei in [8,3,9] # 8: BR directed, 3: BB undirected, 9: BB directed, 15: RB directed # note: there are no cases of RR directed in net_level1_i undoinfo = nni!(net_level1_i , net_level1_i.edge[ei], true, true, c_species); @test undoinfo !== nothing nni!(undoinfo...); # restored to original network, except that edges below hybrid nodes will now have length 0.0 @test writeTopology(net_level1_i) == "(((S8,S9),(((((S1A,S1B,S1C)S1,S4),(S5:0.0)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" end # TODO: BR case edge 8: nni move 3 causes problems. hybrid node 6 has 0 or 2+ major hybrid parents end # of species constraints @testset "test move root & constraint checking under species & clade constraints" begin # "(((S8,S9),(((((S1A,S1B,S1C)S1,S4),#H1),((S5)#H1,(S6,S7))))#H2),(#H2,S10));" netl1_i = readTopology("(((((S1A,S1B,S1C)S1,S4),#H1),((S5)#H1,(S6,S7))));") con = [PhyloNetworks.TopologyConstraint(0x01, ["S1A","S1B","S1C"], netl1_i), PhyloNetworks.TopologyConstraint(0x02, ["S5","S6","S7"], netl1_i)] Random.seed!(765); @test PhyloNetworks.moveroot!(netl1_i, con) # only 2 options writeTopology(netl1_i) == "(((S1A,S1B,S1C)S1,S4),#H1,(((S5)#H1,(S6,S7))));" # now unrooted @test PhyloNetworks.moveroot!(netl1_i, con) # only 1 option writeTopology(netl1_i) == "((S1A,S1B,S1C)S1,S4,(#H1,(((S5)#H1,(S6,S7)))));" netl1_i.root = 14 # back to original rooted network. This node is still of degree 2 @test !PhyloNetworks.checkspeciesnetwork!(netl1_i, con) # false: root *at* clade crown @test netl1_i.root == 13 # now unrooted (via removedegree2nodes!), root was moved, con[2] stem edge was deleted too... netl1_i.root = 7; directEdges!(netl1_i) # move root strictly above clade crown con[2] = PhyloNetworks.TopologyConstraint(0x02, ["S5","S6","S7"], netl1_i) @test PhyloNetworks.checkspeciesnetwork!(netl1_i, con) # now fine: root *above* clade crown undoinfo = nni!(netl1_i,netl1_i.edge[8],0x01,false,false); @test !PhyloNetworks.checkspeciesnetwork!(netl1_i, con) nni!(undoinfo...); @test PhyloNetworks.checkspeciesnetwork!(netl1_i, con) undoinfo = nni!(netl1_i,netl1_i.edge[8],0x03,false,false) # creates a 2-cycle @test netl1_i.numEdges == 13 PhyloNetworks.deletehybridedge!(netl1_i, netl1_i.edge[10]) @test netl1_i.numEdges == 10 # 2-cycle removed netl1_i = readTopology("(((S1A,S1B,S1C),S4),#H1,((S5)#H1,(S6,S7)));") undoinfo = nni!(netl1_i,netl1_i.edge[12],0x03,false,false) # 4-cycle now @test nni!(netl1_i,netl1_i.edge[12],0x02,true,true) === nothing # would create a 3-cycle end #= str_level1 = "(((S8,S9),(((((S1,S2,S3),S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" net_level1 = readTopology(str_level1); #polytomy at node -9 for leaves 3, 4, 5 str_nontreechild = "((((Ag,E))#H3,(#H1:7.159::0.056,((M:0.0)#H2:::0.996,(Ak,(#H3:0.08,#H2:0.0::0.004):0.023):0.078):2.49):2.214):0.026,((Az:2.13,As:2.027):1.697)#H1:0.0::0.944,Ap);" net_nontreechild = readTopology(str_nontreechild); str_polytomy_species = "(((S8,S9),(((((S1,S2,S3),S4),(S5)#H1),(#H1,(S6,S7))))#H2),(#H2,S10));" net_species = readTopology(str_polytomy_species); =# #= @testset "clade contraints" begin c_nontree_cladebelowhybrid = PhyloNetworks.TopologyConstraint(0x02, ["Az", "As"], net_nontreechild) c_level1_clade = PhyloNetworks.TopologyConstraint(0x02, ["S1", "S2", "S3"], net_level1) # this test below returns nothing but shouldn't nni!(net_nontreechild, net_nontreechild.edge[20], true, [c_nontree_cladebelowhybrid]) # this test errors @test isnothing(nni!(net_nontreechild, net_nontreechild.edge[18], true, [c_nontree_cladebelowhybrid])) @test PhyloNetworks.checkspeciesnetwork!(net_nontreechild, [c_nontree_cladebelowhybrid]) PhyloNetworks.addindividuals!(net_level1_s, "S1", ["S1A", "S1B", "S1C"]) @test_throws ErrorException PhyloNetworks.checkspeciesnetwork!(net_level1_i, [c_species]) @test PhyloNetworks.cladesviolated(net_level1_i, c_species) @test_throws ErrorException PhyloNetworks.checkspeciesnetwork!(net_level1_s, [c_level1_species]) @test PhyloNetworks.checknetwork(net_level1_i, c_species) #TODO will want to remove if we remove this function end # of testset on checknetwork functions for species constraints =# end # of constrained NNI moves @testset "test fliphybrid!" begin # simple network n6h1 = readTopology("((((1:0.2,2:0.2):2.4,((3:0.4,4:0.4):1.1)#H1:1.1):2.0,(#H1:0.0::0.3,5:1.5):3.1):1.0,6:5.6);") n6h1d = deepcopy(n6h1) # hybrid node = node number 5 @test !isnothing(PhyloNetworks.fliphybrid!(n6h1, n6h1.hybrid[1])) # flips minor by default @test n6h1.hybrid[1].number == -8 @test !isnothing(PhyloNetworks.fliphybrid!(n6h1d, n6h1d.hybrid[1], false)) # flips major edge @test n6h1d.hybrid[1].number == -4 @test n6h1d.hybrid[1].name == "H1" @test writeTopology(n6h1d) == "((#H1:2.0::0.3,(((3:0.4,4:0.4):1.1,((1:0.2,2:0.2):2.4)#H1:1.1::0.7):0.0,5:1.5):3.1):1.0,6:5.6);" # hybrid ladder network hybridladderstring = "(#H2:::0.2,((C,((B)#H1)#H2:::0.8),(#H1,(A1,A2))),O);" net_hl = readTopology(hybridladderstring); # hybrid 1 = H1, node number 4 # fails because newhybridnode is already a hybrid node @test isnothing(PhyloNetworks.fliphybrid!(net_hl, net_hl.hybrid[1], false, false)) @test net_hl.hybrid[1].number == 4 # unchanged # flipping H2's major hybrid edge creates a W structure: allowed even if hybrid ladders are not # hybrid 2 = H2, node number 1 @test !isnothing(PhyloNetworks.fliphybrid!(net_hl, net_hl.hybrid[2], false, true)) @test net_hl.hybrid[2].number == -4 @test net_hl.hybrid[2].name == "H2" @test writeTopology(net_hl) == "(((B)#H1,(C)#H2:::0.8),(#H2:::0.2,(#H1,(A1,A2))),O);" # W structure network wstring = "(C:0.0262,(B:0.0)#H2:0.03::0.9756,(((D:0.1,A:0.1274):0.0)#H1:0.0::0.6,(#H2:0.0001::0.0244,#H1:0.151::0.4):0.0274):0.4812);" net_W = readTopology(wstring) # hybrid 1: H2, node number 3, hybrid 2: H1, number 6 @test isnothing(PhyloNetworks.fliphybrid!(net_W, net_W.hybrid[1], true, true)) # not allowed, creates a hybrid ladder @test isnothing(PhyloNetworks.fliphybrid!(net_W, net_W.hybrid[2], true, true)) # same @test !isnothing(PhyloNetworks.fliphybrid!(net_W, net_W.hybrid[2])) # hybrid ladders allowed @test net_W.hybrid[2].number == -7 @test writeTopology(net_W) == "(C:0.0262,(B:0.0)#H2:0.03::0.9756,(((D:0.1,A:0.1274):0.0,#H1:0.151::0.4):0.0,(#H2:0.0001::0.0244)#H1:0.0274::0.6):0.4812);" ## cases when the root needs to be reset (to former hybrid node) # newhybridnode < current root net_W = readTopology(wstring) @test !isnothing(PhyloNetworks.fliphybrid!(net_W, net_W.hybrid[2], false)) # root was reset @test net_W.root == 7 @test writeTopology(net_W) == "((D:0.1,A:0.1274):0.0,((C:0.0262,(B:0.0)#H2:0.03::0.9756):0.4812)#H1:0.0::0.6,(#H2:0.0001::0.0244,#H1:0.0274::0.4):0.151);" # newhybridnode = current root # new root will have 2 children hybrid edges, because of former hybrid ladder net_hl = readTopology(hybridladderstring) # hybrid 2 = H2, node number 1 @test !isnothing(PhyloNetworks.fliphybrid!(net_hl, net_hl.hybrid[2], true, false)) @test net_hl.hybrid[2].number == -2 # this is the former root @test net_hl.root == 4 # new root index is as expected @test writeTopology(net_hl) == "((B)#H1,#H2:::0.2,(C,((#H1,(A1,A2)),(O)#H2:::0.8)));" #= other examples in which newhybridnode = current root n6h1 = readTopology("((((1:0.2,2:0.2):2.4,((3:0.4,4:0.4):1.1)#H1:1.1):2.0,(#H1:0.0::0.3,5:1.5):3.1):1.0,6:5.6);") n6h1.root = 10 directEdges!(n6h1) @test n6h1.hybrid[1].number == 5 @test !isnothing(PhyloNetworks.fliphybrid!(n6h1, n6h1.hybrid[1])) # flips minor by default @test n6h1.hybrid[1].number == -8 @test writeTopology(n6h1) == "((3:0.4,4:0.4):1.1,((1:0.2,2:0.2):2.4,((5:1.5)#H1:3.1::0.7,(6:5.6):1.0):2.0):1.1,#H1:0.0::0.3);" net_W = readTopology(wstring) @test !isnothing(PhyloNetworks.fliphybrid!(net_W, net_W.hybrid[1], false)) # move major edge # this moves root to node number -4 @test net_W.root == 3 # index @test writeTopology(net_W) == "(B:0.0,(C:0.0262)#H2:0.03::0.9756,(#H1:0.151::0.4,(((D:0.1,A:0.1274):0.0)#H1:0.0::0.6,#H2:0.4812::0.0244):0.0274):0.0001);" =# # flip hybrid would create a directed cycle tangledstring = "((a:0.01,((b:0.01,(c:0.005)#H2:0.005):0.01)#H1:0.01::0.8):0.01,e:0.01,((#H1:0.01::0.2,d:0.01):0.005,#H2):0.005);" # untangledstring = "((a:0.01,((b:0.01,(c:0.005)#H2:0.005::0.8):0.01)#H1:0.01::0.8):0.01,((#H2:0.01::0.2,d:0.01):0.005,#H1:::0.2):0.005);" netc = readTopology(tangledstring) # hybrid 1: H2, number 4 @test isnothing(PhyloNetworks.fliphybrid!(netc, netc.hybrid[1], true)) # would create cycle, away from root # flip edge cannot contain root, yet flip admissible, and has hybrid ladder: edgetoflip = bottom rung @test isnothing(PhyloNetworks.fliphybrid!(netc, netc.hybrid[1],false, true)) @test !isnothing(PhyloNetworks.fliphybrid!(netc, netc.hybrid[1],false)) @test writeTopology(netc) == "((a:0.01,(#H2:0.01)#H1:0.01::0.8):0.01,e:0.01,((#H1:0.01::0.2,d:0.01):0.005,(c:0.005,(b:0.01)#H2:0.005)):0.005);" # case when the new hybrid edge = child edge of the new hybrid node net_ex = readTopology("(((c:0.01,(a:0.005,#H1):0.005):0.01,(b:0.005)#H1:0.005):0.01,d:0.01);") @test !isnothing(PhyloNetworks.fliphybrid!(net_ex, net_ex.hybrid[1], false)) # flip major edge @test net_ex.root == 6 # index @test net_ex.hybrid[1].number == -3 # @test writeTopology(net_ex) == "(b:0.005,(a:0.005,(c:0.01,#H1:0.01):0.005),((d:0.01):0.01)#H1:0.005);" PhyloNetworks.fliphybrid!(net_ex, net_ex.hybrid[1], false) # undo: except that different root @test writeTopology(net_ex) == "((c:0.01,(a:0.005,#H1):0.005):0.01,(b:0.005)#H1:0.005,(d:0.01):0.01);" # degree-2 node exists, but not rooted at that node # case when sum_isdesc is 1, but corresponds to a hybrid edge level3string = "(b,(((#H1:::0.01,#H2:::0.02))#H3,((a)#H1)#H2),#H3:::0.03);" netl3 = readTopology(level3string) # hybrid 2: H1. only has edge has isdesc = true, but hybrid edge @test isnothing(PhyloNetworks.fliphybrid!(netl3, netl3.hybrid[2])) # hybrid 3 = H2: can flip its minor parent but creates hybrid ladder # cannot flip major parent: creates a cycle end @testset "test fliphybrid! randomly choose node function" begin Random.seed!(123) n6h1 = readTopology("((((1:0.2,2:0.2):2.4,((3:0.4,4:0.4):1.1)#H1:1.1):2.0,(#H1:0.0::0.3,5:1.5):3.1):1.0,6:5.6);") @test n6h1.hybrid[1].number == 5 @test !isnothing(PhyloNetworks.fliphybrid!(n6h1)) @test n6h1.hybrid[1].number == -8 net_W = readTopology("(C:0.0262,(B:0.0)#H2:0.03::0.9756,(((D:0.1,A:0.1274):0.0)#H1:0.0::0.6,(#H2:0.0001::0.0244,#H1:0.151::0.4):0.0274):0.4812);") @test isnothing(PhyloNetworks.fliphybrid!(net_W, true, true)) # all minor edge flips create a hybridladder @test net_W.hybrid[1].number == 3 # unchanged end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
7511
@testset "multiple alleles" begin global tree, df, d, net, currT @testset "test: map alleles to species" begin tree = readTopology("(6,(5,(7,(3,4))));"); PhyloNetworks.expandLeaves!(["7"],tree) @test writeTopology(tree) == "(6,(5,((7:0.0,7__2:0.0):1.0,(3,4))));" PhyloNetworks.mergeLeaves!(tree) @test writeTopology(tree) == "(6,(5,(7:1.0,(3,4))));" alleleDF=DataFrame(allele=["1","2"], species=["7","7"]) CSV.write("tmp.csv", alleleDF); df = (@test_logs (:warn, r"^not all alleles were mapped") mapAllelesCFtable("tmp.csv", joinpath(@__DIR__, "..", "examples", "tableCFCI.csv"), # joinpath(dirname(pathof(PhyloNetworks)), "..", "examples", "tableCFCI.csv"), filename="CFmapped.csv")) rm("CFmapped.csv") rm("tmp.csv") @test df[!,:t4] == ["4","7","3","7","3","3","7","3","3","3","7","3","3","3","3"] end #----------------------------------------------------------# # testing sorting of taxa and CFs # #----------------------------------------------------------# @testset "sorttaxa!" begin letters = ["a","b","c","d"]; cfvalues = [0.6, 0.39, 0.01] # for ab_cd, ac_bd, ad_bc d = DataFrame(t1=Array{String}(undef,24),t2=Array{String}(undef,24),t3=Array{String}(undef,24),t4=Array{String}(undef,24), CF12_34=Array{Float64}(undef,24), CF13_24=Array{Float64}(undef,24), CF14_23=Array{Float64}(undef,24)); irow=1 # d will contain 6!=24 rows: for all permutations on 4 letters for i1 in 1:4 ind234 = deleteat!(collect(1:4),i1) for i2 in ind234 ind34 = deepcopy(ind234) deleteat!(ind34, findfirst(isequal(i2), ind34)) for j in 1:2 i3=ind34[j]; i4=ind34[3-j] d[irow,:t1]=letters[i1]; d[irow,:t2]=letters[i2]; d[irow,:t3]=letters[i3]; d[irow,:t4]=letters[i4] # CF12_34 corresponds to CFi1i2_i3i4 if (i1,i2)∈[(1,2),(2,1),(3,4),(4,3)] d[irow,:CF12_34] = cfvalues[1] elseif (i1,i2)∈[(1,3),(3,1),(2,4),(4,2)] d[irow,:CF12_34] = cfvalues[2] elseif (i1,i2)∈[(1,4),(4,1),(2,3),(3,2)] d[irow,:CF12_34] = cfvalues[3] end # next: set CF13_24 if (i1,i3)∈[(1,2),(2,1),(3,4),(4,3)] d[irow,:CF13_24] = cfvalues[1] elseif (i1,i3)∈[(1,3),(3,1),(2,4),(4,2)] d[irow,:CF13_24] = cfvalues[2] elseif (i1,i3)∈[(1,4),(4,1),(2,3),(3,2)] d[irow,:CF13_24] = cfvalues[3] end # nest: set CF14_23 if (i1,i4)∈[(1,2),(2,1),(3,4),(4,3)] d[irow,:CF14_23] = cfvalues[1] elseif (i1,i4)∈[(1,3),(3,1),(2,4),(4,2)] d[irow,:CF14_23] = cfvalues[2] elseif (i1,i4)∈[(1,4),(4,1),(2,3),(3,2)] d[irow,:CF14_23] = cfvalues[3] end irow += 1 end end end # d d2 = deepcopy(d); sorttaxa!(d2); d3 = DataFrame(t1=repeat([letters[1]],outer=[24]),t2=repeat([letters[2]],outer=[24]), t3=repeat([letters[3]],outer=[24]),t4=repeat([letters[4]],outer=[24]), CF12_34=repeat([cfvalues[1]],outer=[24]),CF13_24=repeat([cfvalues[2]],outer=[24]),CF14_23=repeat([cfvalues[3]],outer=[24])); @test d2==d3 dat = readTableCF(d); net = (@test_logs readTopologyLevel1("(a,((b)#H1,((#H1,c),d)));")); # earlier warning: "net does not have identifiable branch lengths" @test_logs topologyQPseudolik!(net, dat); sorttaxa!(dat) @test [q.obsCF for q in dat.quartet] == [[0.6,0.39,0.01] for i in 1:24] @test [q.qnet.expCF for q in dat.quartet] == [[0.6915349833361827,0.12262648039048075,0.1858385362733365] for i in 1:24] @test [q.taxon for q in dat.quartet] == [letters for i in 1:24] @test [q.qnet.quartetTaxon for q in dat.quartet] == [letters for i in 1:24] end # of testset: sorttaxa! @testset "snaq on multiple alleles" begin df = DataFrame(t1=["6","7"], t2=["7","6"], t3=["4","4"], t4=["8","8"], a=[true,true], # to test recognition of columns CF12_34=[0.25, 0.15], ngenes=[10,20], CF13_24=[0.3,0.55], b=[false,false], CF14_23=[0.45,0.3]) @test length(readTableCF(df).quartet) == 2 d = readTableCF(df, mergerows=true) @test isempty(d.repSpecies) @test length(d.quartet) == 1 @test d.quartet[1].obsCF ≈ [0.3, 0.5, 0.2] @test d.quartet[1].ngenes ≈ 15 PhyloNetworks.descData(d, devnull) PhyloNetworks.descData(d, "tmp.log") summarizeDataCF(d, filename="tmp.log") rm("tmp.log") df=DataFrame(t1=["6","6","10","6","6","7","7","7","7","7", "3", "7", "7"], # rows 11 & 13 (last & third to last): non-informative t2=["7","7","7","10","7","7","7","7","7","7", "7", "7", "7"], t3=["4","10","4","4","4","8","8","8","10","10","7", "6", "7"], t4=["8","8","8","8","10","10","4","6","4","6", "7", "4", "4"], CF1234=[0.2729102510259939, 0.3967750546426937, 0.30161247267865315, 0.24693940689390592, 0.2729102510259939, 0.155181, 0.792153, 0.486702, 0.962734, 0.202531, 0.3, 0.486886, 0.3], CF1324=[0.45417949794801216, 0.30161247267865315, 0.30161247267865315, 0.5061211862121882, 0.45417949794801216, 0.673426 ,0.145408, 0.391103, 0.023078, 0.714826, 0.3, 0.419015, 0.3], CF1423=[0.2729102510259939, 0.30161247267865315, 0.3967750546426937, 0.24693940689390592, 0.2729102510259939, 0.171393, 0.062439, 0.122195, 0.014188, 0.082643, 0.4, 0.094099, 0.4]) d = readTableCF(df) @test !isempty(d.repSpecies) @test d.repSpecies == ["7"] tree = "((6,4),(7,8),10);" currT = readTopology(tree); originalstdout = stdout redirect_stdout(devnull) # requires julia v1.6 estNet = snaq!(currT,d,hmax=1,seed=7, runs=1, filename="", Nfail=10) redirect_stdout(originalstdout) @test 180.0 < estNet.loglik < 185.29 @test estNet.hybrid[1].k >= 4 @test estNet.numTaxa == 5 #= redirect_stdout(devnull) # requires julia v1.6 estNet = snaq!(currT,d,hmax=1,seed=8306, runs=1, filename="", Nfail=10, ftolAbs=1e-6,ftolRel=1e-5,xtolAbs=1e-4,xtolRel=1e-3) redirect_stdout(originalstdout) @test estNet.hybrid[1].k == 5 # or: wrong k in hybrid @test estNet.numTaxa == 5 # or: wrong # taxa =# # net = snaq!(currT,d,hmax=1,seed=8378,filename="") net = readTopology("(((4,#H7:::0.47411636966376686):0.6360197250223204,10):0.09464128563363322,(7:0.0,(6)#H7:::0.5258836303362331):0.36355727108454877,8);") @test topologyQPseudolik!(net, d) ≈ 174.58674796123705 @test net.loglik ≈ 174.58674796123705 net = readTopology("(((4,#H1),10),(7,(6)#H1),8);") net = topologyMaxQPseudolik!(net,d, # loose tolerance for faster test ftolRel=1e-2,ftolAbs=1e-2,xtolAbs=1e-2,xtolRel=1e-2) @test net.loglik > 174.5 # testing root checks at the end when outgroup!="none" redirect_stdout(devnull) estNet = snaq!(currT,d,hmax=1,seed=6355, runs=1, filename="", Nfail=10, ftolAbs=1e-6,ftolRel=1e-5,xtolAbs=1e-4,xtolRel=1e-3, outgroup="10") redirect_stdout(originalstdout) # below, mostly check for 1 reticulation and "10" as outgroup. exact net depends on RNG :( netstring = writeTopology(estNet; round=true, digits=1) @test occursin(r"^\(\(7:0.0,#H\d:::.*,10\);", netstring) || occursin(r"^\(10,\(.*,#H\d:::0.\d\);", netstring) || occursin(r",10,#H\d:::0.\d\);", netstring) end # test of snaq on multiple alleles #----------------------------------------------------------# # testing writeTopologyLevel1 with multiple alleles # #----------------------------------------------------------# @testset "writeTopologyLevel1 multiall=true" begin net = readTopologyLevel1("(A,(((B,B__2),E),(C,D)));") @test writeTopologyLevel1(net, false, true, true,"D", false, true, 2, true) == "(D:0.5,(C:1.0,((B:1.0,E:1.0):1.0,A:1.0):1.0):0.5);" end # test of writeTopologyLevel1 end # overall multiple allele sets of testests
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
1187
@testset "Neighbour joining implementation" begin D = DataFrame(CSV.File(joinpath(@__DIR__,"..","examples","caudata_dist.txt")); copycols=false) tree = nj(D) # read results from ape implementation of nj apetree = readTopology(joinpath(@__DIR__, "..", "examples", "caudata_dist_nj.txt")) @test hardwiredClusterDistance(tree, apetree, false) == 0 # also check branch lengths (more or less) @test sort!([e.length for e in tree.edge]) ≈ sort!([e.length for e in apetree.edge]) # example where Ints are converted to Floats, and there's a < 0 edge length df = DataFrame(s1=[0, 5,9,9,5], s2=[5,0,10,10,6], s3=[9,10,0,8,4], s4=[9,10,8,0,0], s5=[5,6, 4, 0,0]) tree = (@test_logs (:info, r"have negative lengths") nj(df)) @test writeTopology(tree) == "(((s1:2.0,s2:3.0):3.0,s3:4.0):2.0,s4:2.0,s5:-2.0);" # example with no names argument, force_nonnegative_edges D = [0 5 9 9 6.5; 5 0 10 10 7.5; 9 10 0 8 5.5; 9 10 8 0 1.5; 6.5 7.5 5.5 1.5 0] tree = (@test_logs (:info, r"reset to 0") PhyloNetworks.nj!(D, force_nonnegative_edges=true)) @test writeTopology(tree) == "(((1:2.0,2:3.0):3.0,3:4.0):2.0,4:2.0,5:0.0);" end
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git
[ "MIT" ]
0.16.4
66c2a637bd4d4e7064b60c0e5a0e6db2db3116a1
code
16380
# test the components in optBL separately # Claudia January 2015 globalerror = false #println("--------- Case G --------------") include("../examples/case_g_example.jl"); q1 = Quartet(1,["6","7","4","8"],[0.5,0.4,0.1]); q2 = Quartet(2,["6","7","10","8"],[0.5,0.4,0.1]); q3 = Quartet(3,["10","7","4","8"],[0.5,0.4,0.1]); q4 = Quartet(4,["6","10","4","8"],[0.5,0.4,0.1]); q5 = Quartet(5,["6","7","4","10"],[0.5,0.4,0.1]); d = DataCF([q1,q2,q3,q4,q5]); extractQuartet!(net,d) oldht = net.ht x = [0.3,1.0,1.5,2.0] err = false #println("x is $(x) all changed-----------") try update!(q1.qnet,x,net) q1.qnet.edge[3].length !=x[2] || q1.qnet.edge[6].length !=x[3] || q1.qnet.edge[9].length !=x[4] ? error("qnet edges lengths not correct") : nothing q1.qnet.edge[5].gamma !=1-x[1] || q1.qnet.edge[7].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing update!(q2.qnet,x,net) q2.qnet.edge[4].length !=x[3] || q2.qnet.edge[7].length !=x[4] ? error("qnet edges lengths not correct") : nothing q2.qnet.edge[3].gamma !=1-x[1] || q2.qnet.edge[5].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing update!(q3.qnet,x,net) q3.qnet.edge[4].length !=x[3] || q3.qnet.edge[7].length !=x[4] ? error("qnet edges lengths not correct") : nothing q3.qnet.edge[3].gamma !=1-x[1] || q3.qnet.edge[5].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing update!(q4.qnet,x,net) q4.qnet.edge[3].length !=x[2] || q4.qnet.edge[4].length !=x[3] ? error("qnet edges lengths not correct") : nothing update!(q5.qnet,x,net) q5.qnet.edge[3].length !=x[2] || q5.qnet.edge[6].length !=x[3] ? error("qnet edges lengths not correct") : nothing q5.qnet.edge[5].gamma !=1-x[1] || q5.qnet.edge[7].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing reduce(&,[q.qnet.changed for q in d.quartet]) || error("all qnet should be changed") update!(net,x) net.ht == x || ("net.ht not correctly changed to x with update") catch global err = true end for q in d.quartet update!(q.qnet,oldht,net) end update!(net,oldht) x = [0.1,0.2,0.1,2.0] # changing t9 only #println("x is $(x) changing t9 only-----------") try update!(q1.qnet,x,net) q1.qnet.edge[3].length !=x[2] || q1.qnet.edge[6].length !=x[3] || q1.qnet.edge[9].length !=x[4] ? error("qnet edges lengths not correct") : nothing q1.qnet.edge[5].gamma !=1-x[1] || q1.qnet.edge[7].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing update!(q2.qnet,x,net) q2.qnet.edge[4].length !=x[3] || q2.qnet.edge[7].length !=x[4] ? error("qnet edges lengths not correct") : nothing q2.qnet.edge[3].gamma !=1-x[1] || q2.qnet.edge[5].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing update!(q3.qnet,x,net) q3.qnet.edge[4].length !=x[3] || q3.qnet.edge[7].length !=x[4] ? error("qnet edges lengths not correct") : nothing q3.qnet.edge[3].gamma !=1-x[1] || q3.qnet.edge[5].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing update!(q4.qnet,x,net) q4.qnet.edge[3].length !=x[2] || q4.qnet.edge[4].length !=x[3] ? error("qnet edges lengths not correct") : nothing update!(q5.qnet,x,net) q5.qnet.edge[3].length !=x[2] || q5.qnet.edge[6].length !=x[3] ? error("qnet edges lengths not correct") : nothing q5.qnet.edge[5].gamma !=1-x[1] || q5.qnet.edge[7].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing [q.qnet.changed for q in d.quartet] == [true,true,true,false,false] || error("q.qnet.changed not correct for all quartets") update!(net,x) net.ht == x || error("net.ht not correctly changed to x with update") catch global err = true end for q in d.quartet update!(q.qnet,oldht,net) end update!(net,oldht) x = [0.3,0.2,0.1,2.0] # changing gamma and t9 only #println("x is $(x) changing gamma and t9 only-----------") try update!(q1.qnet,x,net) q1.qnet.edge[3].length !=x[2] || q1.qnet.edge[6].length !=x[3] || q1.qnet.edge[9].length !=x[4] ? error("qnet edges lengths not correct") : nothing q1.qnet.edge[5].gamma !=1-x[1] || q1.qnet.edge[7].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing update!(q2.qnet,x,net) q2.qnet.edge[4].length !=x[3] || q2.qnet.edge[7].length !=x[4] ? error("qnet edges lengths not correct") : nothing q2.qnet.edge[3].gamma !=1-x[1] || q2.qnet.edge[5].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing update!(q3.qnet,x,net) q3.qnet.edge[4].length !=x[3] || q3.qnet.edge[7].length !=x[4] ? error("qnet edges lengths not correct") : nothing q3.qnet.edge[3].gamma !=1-x[1] || q3.qnet.edge[5].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing update!(q4.qnet,x,net) q4.qnet.edge[3].length !=x[2] || q4.qnet.edge[4].length !=x[3] ? error("qnet edges lengths not correct") : nothing update!(q5.qnet,x,net) q5.qnet.edge[3].length !=x[2] || q5.qnet.edge[6].length !=x[3] ? error("qnet edges lengths not correct") : nothing q5.qnet.edge[5].gamma !=1-x[1] || q5.qnet.edge[7].gamma !=x[1] ? error("qnet edges gammas not correct") : nothing [q.qnet.changed for q in d.quartet] == [true,true,true,false,true] || error("q.qnet.changed not correct for all quartets") update!(net,x) net.ht == x || error("net.ht not correctly changed to x with update") catch global err = true end for q in d.quartet update!(q.qnet,oldht,net) end update!(net,oldht) # ---- calculateExpCF x = [0.3,0.2,0.1,2.0] # changing gamma and t9 only #println("---- calculate expCF for $(x)") try calculateExpCFAll!(d,x,net) reduce(&,map(approxEq,q1.qnet.expCF,[(1-x[1])/3*exp(-x[2])+x[1]/3*exp(-x[2]-x[3]-x[4]),(1-x[1])*(1-2/3*exp(-x[2]))+x[1]*(1-2/3*exp(-x[2]-x[3]-x[4])), (1-x[1])/3*exp(-x[2])+x[1]/3*exp(-x[2]-x[3]-x[4])])) || error("q1 expCF wrong") reduce(&,map(approxEq,q2.qnet.expCF, [(1-x[1])*(1-2/3*exp(-x[3]))+x[1]*(1/3*exp(-x[4])),(1-x[1])*(1/3*exp(-x[3]))+x[1]*(1-2/3*exp(-x[4])), (1-x[1])/3*exp(-x[3])+x[1]/3*exp(-x[4])])) || error("q2 expCF wrong") reduce(&,map(approxEq,q3.qnet.expCF, [(1-x[1])/3*exp(-x[3])+x[1]/3*exp(-x[4]),(1-x[1])*(1/3*exp(-x[3]))+x[1]*(1-2/3*exp(-x[4])),(1-x[1])*(1-2/3*exp(-x[3]))+x[1]*(1/3*exp(-x[4]))])) || error("q3 expCF wrong") reduce(&,map(approxEq,q4.qnet.expCF,[1/3*exp(-x[2]-x[3]),1-2/3*exp(-x[2]-x[3]),1/3*exp(-x[2]-x[3])])) || error("q4 expCF wrong") reduce(&,map(approxEq,q5.qnet.expCF,[(1-x[1])/3*exp(-x[2])+x[1]/3*exp(-x[2]-x[3]),(1-x[1])*(1-2/3*exp(-x[2]))+x[1]*(1-2/3*exp(-x[2]-x[3])), (1-x[1])/3*exp(-x[2])+x[1]/3*exp(-x[2]-x[3])])) || error("q5 expCF wrong") catch global err = true end #logPseudoLik(d) if !err #println("-------------Case G: NO ERRORS!------------") else globalerror = true end #println("--------- Case F Bad Diamond I --------------") include("../examples/case_f_example.jl"); parameters!(net) q1 = Quartet(1,["6","7","4","8"],[0.5,0.4,0.1]); q2 = Quartet(2,["6","7","10","8"],[0.5,0.4,0.1]); q3 = Quartet(3,["10","7","4","8"],[0.5,0.4,0.1]); q4 = Quartet(4,["6","10","4","8"],[0.5,0.4,0.1]); q5 = Quartet(5,["6","7","4","10"],[0.5,0.4,0.1]); d = DataCF([q1,q2,q3,q4,q5]); extractQuartet!(net,d) oldht = net.ht x = [0.4,0.2,0.1] err = false #println("x is $(x) all changed-----------") try update!(q1.qnet,x,net) q1.qnet.node[1].gammaz !=x[2] || q1.qnet.node[3].gammaz !=x[3] ? error("qnet gammaz not correct") : nothing update!(q2.qnet,x,net) q2.qnet.edge[4].length !=x[1] ? error("qnet edges lengths not correct") : nothing update!(q3.qnet,x,net) q3.qnet.edge[5].length !=x[1] ? error("qnet edges lengths not correct") : nothing q3.qnet.edge[3].length !=-log(1-x[3]) ? error("qnet edges gammaz not correct") : nothing update!(q4.qnet,x,net) q4.qnet.edge[5].length !=x[1] ? error("qnet edges lengths not correct") : nothing q4.qnet.edge[3].length !=-log(1-x[2]) ? error("qnet edges gammaz not correct") : nothing update!(q5.qnet,x,net) q1.qnet.node[1].gammaz !=x[2] || q1.qnet.node[3].gammaz !=x[3] ? error("qnet gammaz not correct") : nothing reduce(&,[q.qnet.changed for q in d.quartet]) || error("all qnet should be changed") update!(net,x) net.ht == x || ("net.ht not correctly changed to x with update") catch global err = true end for q in d.quartet update!(q.qnet,oldht,net) end update!(net,oldht) x = [0.1,0.2,0.1] # changing gammaz1, gammaz2 only #println("x is $(x) changing gammaz1, gammaz2 only-----------") try update!(q1.qnet,x,net) q1.qnet.node[1].gammaz !=x[2] || q1.qnet.node[3].gammaz !=x[3] ? error("qnet gammaz not correct") : nothing update!(q2.qnet,x,net) q2.qnet.edge[4].length !=x[1] ? error("qnet edges lengths not correct") : nothing update!(q3.qnet,x,net) q3.qnet.edge[5].length !=x[1] ? error("qnet edges lengths not correct") : nothing q3.qnet.edge[3].length !=-log(1-x[3]) ? error("qnet edges gammaz not correct") : nothing update!(q4.qnet,x,net) q4.qnet.edge[5].length !=x[1] ? error("qnet edges lengths not correct") : nothing q4.qnet.edge[3].length !=-log(1-x[2]) ? error("qnet edges gammaz not correct") : nothing update!(q5.qnet,x,net) q1.qnet.node[1].gammaz !=x[2] || q1.qnet.node[3].gammaz !=x[3] ? error("qnet gammaz not correct") : nothing [q.qnet.changed for q in d.quartet] == [true,false,true,true,true] || error("q.qnet.changed not correct for all quartets") update!(net,x) net.ht == x || error("net.ht not correctly changed to x with update") catch global err = true end for q in d.quartet update!(q.qnet,oldht,net) end update!(net,oldht) # ---- calculateExpCF x = [0.3,0.2,0.1] #println("---- calculate expCF for $(x)") try calculateExpCFAll!(d,x,net) reduce(&,map(approxEq,q1.qnet.expCF,[(1-x[2]-x[3])/3,(1+2*x[2]-x[3])/3,(1-x[2]+2*x[3])/3])) || error("q1 expCF wrong") reduce(&,map(approxEq,q2.qnet.expCF, [1-2/3*exp(-x[1]),1/3*exp(-x[1]),1/3*exp(-x[1])])) || error("q2 expCF wrong") reduce(&,map(approxEq,q3.qnet.expCF, [1/3*exp(-x[1]+log(1-x[3])),1/3*exp(-x[1]+log(1-x[3])),1-2/3*exp(-x[1]+log(1-x[3]))])) || error("q3 expCF wrong") reduce(&,map(approxEq,q4.qnet.expCF,[1/3*exp(-x[1]+log(1-x[2])),1-2/3*exp(-x[1]+log(1-x[2])),1/3*exp(-x[1]+log(1-x[2]))])) || error("q4 expCF wrong") reduce(&,map(approxEq,q5.qnet.expCF,[(1-x[2]-x[3])/3,(1+2*x[2]-x[3])/3,(1-x[2]+2*x[3])/3])) || error("q5 expCF wrong") catch global err = true end #logPseudoLik(d) if !err #println("-------------Case F: NO ERRORS!------------") else globalerror = true end #println("--------- Case I Bad Diamond II --------------") include("../examples/case_i_example.jl"); q1 = Quartet(1,["6","7","4","8"],[0.5,0.4,0.1]); q2 = Quartet(2,["6","7","10","8"],[0.5,0.4,0.1]); q3 = Quartet(3,["10","7","4","8"],[0.5,0.4,0.1]); q4 = Quartet(4,["6","10","4","8"],[0.5,0.4,0.1]); q5 = Quartet(5,["6","7","4","10"],[0.5,0.4,0.1]); d = DataCF([q1,q2,q3,q4,q5]); extractQuartet!(net,d) oldht = net.ht x = [0.2,0.2,0.1,0.1,0.1] err = false #println("x is $(x) all changed-----------") try update!(q1.qnet,x,net) q1.qnet.edge[7].gamma != x[1] || q1.qnet.edge[2].gamma != 1-x[1] ? error("qnet gamma not correct") : nothing q1.qnet.edge[4].length != x[3] || q1.qnet.edge[8].length != x[4] ? error("qnet edge lengths not correct") : nothing update!(q2.qnet,x,net) q2.qnet.edge[8].gamma != x[1] || q2.qnet.edge[4].gamma != 1-x[1] ? error("qnet gamma not correct") : nothing (q2.qnet.edge[4].length !=x[2] || q2.qnet.edge[6].length !=x[3] || q2.qnet.edge[8].length !=x[4] || q2.qnet.edge[9].length !=x[5]) ? error("qnet edges lengths not correct") : nothing update!(q3.qnet,x,net) q3.qnet.edge[8].gamma != x[1] || q3.qnet.edge[4].gamma != 1-x[1] ? error("qnet gamma not correct") : nothing (q2.qnet.edge[4].length !=x[2] || q2.qnet.edge[6].length !=x[3] || q2.qnet.edge[8].length !=x[4] || q2.qnet.edge[9].length !=x[5]) ? error("qnet edges lengths not correct") : nothing update!(q4.qnet,x,net) q4.qnet.edge[8].gamma != x[1] || q4.qnet.edge[4].gamma != 1-x[1] ? error("qnet gamma not correct") : nothing (q2.qnet.edge[4].length !=x[2] || q2.qnet.edge[6].length !=x[3] || q2.qnet.edge[8].length !=x[4] || q2.qnet.edge[9].length !=x[5]) ? error("qnet edges lengths not correct") : nothing update!(q5.qnet,x,net) q5.qnet.edge[7].gamma != x[1] || q5.qnet.edge[2].gamma != 1-x[1] ? error("qnet gamma not correct") : nothing q5.qnet.edge[4].length != x[3] || q5.qnet.edge[8].length != x[4] ? error("qnet edge lengths not correct") : nothing reduce(&,[q.qnet.changed for q in d.quartet]) || error("all qnet should be changed") update!(net,x) net.ht == x || ("net.ht not correctly changed to x with update") catch global err = true end for q in d.quartet update!(q.qnet,oldht,net) end update!(net,oldht) x = [0.1,0.2,1.,1.,1.] # changing t3 only err = false #println("x is $(x) changing t3 only-----------") try update!(q1.qnet,x,net) q1.qnet.edge[7].gamma != x[1] || q1.qnet.edge[2].gamma != 1-x[1] ? error("qnet gamma not correct") : nothing q1.qnet.edge[4].length != x[3] || q1.qnet.edge[8].length != x[4] ? error("qnet edge lengths not correct") : nothing update!(q2.qnet,x,net) q2.qnet.edge[8].gamma != x[1] || q2.qnet.edge[4].gamma != 1-x[1] ? error("qnet gamma not correct") : nothing (q2.qnet.edge[4].length !=x[2] || q2.qnet.edge[6].length !=x[3] || q2.qnet.edge[8].length !=x[4] || q2.qnet.edge[9].length !=x[5]) ? error("qnet edges lengths not correct") : nothing update!(q3.qnet,x,net) q3.qnet.edge[8].gamma != x[1] || q3.qnet.edge[4].gamma != 1-x[1] ? error("qnet gamma not correct") : nothing (q2.qnet.edge[4].length !=x[2] || q2.qnet.edge[6].length !=x[3] || q2.qnet.edge[8].length !=x[4] || q2.qnet.edge[9].length !=x[5]) ? error("qnet edges lengths not correct") : nothing update!(q4.qnet,x,net) q4.qnet.edge[8].gamma != x[1] || q4.qnet.edge[4].gamma != 1-x[1] ? error("qnet gamma not correct") : nothing (q2.qnet.edge[4].length !=x[2] || q2.qnet.edge[6].length !=x[3] || q2.qnet.edge[8].length !=x[4] || q2.qnet.edge[9].length !=x[5]) ? error("qnet edges lengths not correct") : nothing update!(q5.qnet,x,net) q5.qnet.edge[7].gamma != x[1] || q5.qnet.edge[2].gamma != 1-x[1] ? error("qnet gamma not correct") : nothing q5.qnet.edge[4].length != x[3] || q5.qnet.edge[8].length != x[4] ? error("qnet edge lengths not correct") : nothing [q.qnet.changed for q in d.quartet] == [false, true, true, true, false] || error("not all qnet should be changed") update!(net,x) net.ht == x || ("net.ht not correctly changed to x with update") catch global err = true end for q in d.quartet update!(q.qnet,oldht,net) end update!(net,oldht) # ---- calculateExpCF x = [0.2,0.2,0.1,0.1,0.1] #println("---- calculate expCF for $(x)") try calculateExpCFAll!(d,x,net) reduce(&,map(approxEq,q1.qnet.expCF,[(1-x[1])*(1/3*exp(-x[3]))+x[1]*(1-2/3*exp(-x[4])),(1-x[1])*(1-2/3*exp(-x[3]))+x[1]*(1/3*exp(-x[4])),(1-x[1])*(1/3*exp(-x[3]))+x[1]*(1/3*exp(-x[4]))])) || error("q1 expCF wrong") t=-log(1+x[1]*(1-exp(-x[3]))-x[1]*x[1]*(1-exp(-x[5]-x[4]))-x[1]*x[1]*(1-exp(-x[3]))-(1-x[1])*(1-x[1])*(1-exp(-x[2]))) reduce(&,map(approxEq,q2.qnet.expCF, [1-2/3*exp(-t),1/3*exp(-t),1/3*exp(-t)])) || error("q2 expCF wrong") t=-log(1+x[1]*(1-exp(-x[3]-x[5]))-x[1]*x[1]*(1-exp(-x[4]))-x[1]*x[1]*(1-exp(-x[3]-x[5]))-(1-x[1])*(1-x[1])*(1-exp(-x[2]))) reduce(&,map(approxEq,q3.qnet.expCF, [1/3*exp(-t),1/3*exp(-t),1-2/3*exp(-t)])) || error("q3 expCF wrong") t=-log(1+x[1]*(1-exp(-x[5]))-x[1]*x[1]*(1-exp(-x[5]))-x[1]*x[1]*(1-exp(-x[4]))-(1-x[1])*(1-x[1])*(1-exp(-x[3]-x[2]))) reduce(&,map(approxEq,q4.qnet.expCF, [1/3*exp(-t),1-2/3*exp(-t),1/3*exp(-t)])) || error("q4 expCF wrong") reduce(&,map(approxEq,q5.qnet.expCF,[(1-x[1])*(1/3*exp(-x[3]))+x[1]*(1-2/3*exp(-x[4])),(1-x[1])*(1-2/3*exp(-x[3]))+x[1]*(1/3*exp(-x[4])),(1-x[1])*(1/3*exp(-x[3]))+x[1]*(1/3*exp(-x[4]))])) || error("q5 expCF wrong") catch global err = true end #logPseudoLik(d) if !err #println("-------------Case I: NO ERRORS!------------") else globalerror = true end @test !globalerror
PhyloNetworks
https://github.com/JuliaPhylo/PhyloNetworks.jl.git