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.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 8179 |
# Tests the routine ah18 jacobian:
#include("../src/ttv.jl")
# Next, try computing three-body Keplerian Jacobian:
@testset "ah18" begin
#n = 8
n = 3
H = [3,1,1]
#n = 2
t0 = 7257.93115525
h = 0.05
hbig = big(h)
tmax = 600.0
dlnq = big(1e-20)
#nstep = 8000
#nstep = 5000
nstep = 100
#nstep = 1
elements = readdlm("elements.txt",',')[1:n,:]
# Increase mass of inner planets:
elements[2,1] *= 100.
elements[3,1] *= 100.
m =zeros(n)
x0=zeros(3,n)
v0=zeros(3,n)
# Define which pairs will have impulse rather than -drift+Kepler:
pair = zeros(Bool,n,n)
# Initialize with identity matrix:
jac_step = Matrix{Float64}(I,7*n,7*n)
for k=1:n
m[k] = elements[k,1]
end
m0 = copy(m)
init = ElementsIC(t0,H,elements)
x0,v0,_ = init_nbody(init)
# Tilt the orbits a bit:
x0[2,1] = 5e-1*sqrt(x0[1,1]^2+x0[3,1]^2)
x0[2,2] = -5e-1*sqrt(x0[1,2]^2+x0[3,2]^2)
x0[2,3] = -5e-1*sqrt(x0[1,2]^2+x0[3,2]^2)
v0[2,1] = 5e-1*sqrt(v0[1,1]^2+v0[3,1]^2)
v0[2,2] = -5e-1*sqrt(v0[1,2]^2+v0[3,2]^2)
v0[2,3] = -5e-1*sqrt(v0[1,2]^2+v0[3,2]^2)
xbig = big.(x0); vbig = big.(v0)
xtest = copy(x0); vtest=copy(v0)
# Take a single step (so that we aren't at initial coordinates):
x = copy(x0); v = copy(v0)
xerror = zeros(3,n); verror = zeros(3,n)
big_xerror = zeros(BigFloat,3,n)
big_verror = zeros(BigFloat,3,n)
for i=1:nstep; ah18!(x,v,xerror,verror,h,m,n,pair); end
# Take a step with big precision:
ah18!(xbig,vbig,big_xerror,big_verror,big(h),big.(m),n,pair)
# Take a single DH17 step:
xerror = zeros(3,n); verror = zeros(3,n)
#@time for i=1:nstep; dh17!(xtest,vtest,xerror,verror,h,m,n,pair);end
#println("AH18 vs. DH17 x/v difference: ",x-xtest,v-vtest)
# Compute x & v in BigFloat precision:
xbig = big.(x0)
vbig = big.(v0)
mbig = big.(m0)
xerr_big = zeros(BigFloat,3,n); verr_big = zeros(BigFloat,3,n)
jac_step_big = Matrix{BigFloat}(I,7*n,7*n)
jac_err_big = zeros(BigFloat,7*n,7*n)
for i=1:nstep; ah18!(xbig,vbig,xerr_big,verr_big,hbig,mbig,n,jac_step_big,jac_err_big,pair);end
#println("AH18 vs. AH18 BigFloat x/v difference: ",x-convert(Array{Float64,2},xbig),v-convert(Array{Float64,2},vbig))
# Now, copy these to compute Jacobian (so that I don't step
# x0 & v0 forward in time):
x = copy(x0)
v = copy(v0)
m = copy(m0)
xerror = zeros(3,n); verror = zeros(3,n); jac_error = zeros(7*n,7*n)
# Compute jacobian exactly over nstep steps:
for istep=1:nstep
ah18!(x,v,xerror,verror,h,m,n,jac_step,jac_error,pair)
end
#println("AH18 vs. AH18 BigFloat jac_step difference: ",jac_step-convert(Array{Float64,2},jac_step_big))
#println(typeof(h)," ",jac_step)
#read(STDIN,Char)
# The following lines have a Julia bug - jac_big gets
# misaligned or shifted when returned. If I modify ah18! to output
# jac_step, then it works.
# Initialize with identity matrix:
## Compute jacobian exactly over nstep steps:
#for istep=1:nstep
# jac_copy = ah18!(xbig,vbig,hbig,mbig,n,jac_big,pair)
#end
#println(typeof(hbig)," ",convert(Array{Float64,2},jac_copy))
#println("Comparing x & xbig: ",maximum(abs,x-xbig))
#println("Comparing v & vbig: ",maximum(abs,v-vbig))
#println("Comparing jac_step and jac_big: ",maxabs(jac_step-jac_copy))
#println("Comparing jac_step and jac_big: ",jac_step./convert(Array{Float64,2},jac_big))
# Test that both versions of ah18 give the same answer:
#xtest = copy(x0)
#vtest = copy(v0)
#m = copy(m0)
#for istep=1:nstep
# ah18!(xtest,vtest,h,m,n,pair)
#end
#println("x/v difference: ",x-xtest,v-vtest)
# Now compute numerical derivatives:
jac_step_num = zeros(BigFloat,7*n,7*n)
# Vary the initial parameters of planet j:
for j=1:n
# Vary the initial phase-space elements:
for jj=1:3
# Initial positions, velocities & masses:
xm = big.(x0)
vm = big.(v0)
mm = big.(m0)
fill!(big_xerror,0.0)
fill!(big_verror,0.0)
dq = dlnq * xm[jj,j]
if xm[jj,j] != 0.0
xm[jj,j] -= dq
else
dq = dlnq
xm[jj,j] = -dq
end
for istep=1:nstep
ah18!(xm,vm,big_xerror,big_verror,hbig,mm,n,pair)
end
xp = big.(x0)
vp = big.(v0)
mp = big.(m0)
fill!(big_xerror,0.0)
fill!(big_verror,0.0)
dq = dlnq * xp[jj,j]
if xp[jj,j] != 0.0
xp[jj,j] += dq
else
dq = dlnq
xp[jj,j] = dq
end
for istep=1:nstep
ah18!(xp,vp,big_xerror,big_verror,hbig,mp,n,pair)
end
# Now x & v are final positions & velocities after time step
for i=1:n
for k=1:3
jac_step_num[(i-1)*7+ k,(j-1)*7+ jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_step_num[(i-1)*7+3+k,(j-1)*7+ jj] = .5*(vp[k,i]-vm[k,i])/dq
end
end
# Next velocity derivatives:
xm= big.(x0)
vm= big.(v0)
mm= big.(m0)
fill!(big_xerror,0.0)
fill!(big_verror,0.0)
dq = dlnq * vm[jj,j]
if vm[jj,j] != 0.0
vm[jj,j] -= dq
else
dq = dlnq
vm[jj,j] = -dq
end
for istep=1:nstep
ah18!(xm,vm,big_xerror,big_verror,hbig,mm,n,pair)
end
xp= big.(x0)
vp= big.(v0)
mp= big.(m0)
fill!(big_xerror,0.0)
fill!(big_verror,0.0)
dq = dlnq * vp[jj,j]
if vp[jj,j] != 0.0
vp[jj,j] += dq
else
dq = dlnq
vp[jj,j] = dq
end
for istep=1:nstep
ah18!(xp,vp,big_xerror,big_verror,hbig,mp,n,pair)
end
for i=1:n
for k=1:3
jac_step_num[(i-1)*7+ k,(j-1)*7+3+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_step_num[(i-1)*7+3+k,(j-1)*7+3+jj] = .5*(vp[k,i]-vm[k,i])/dq
end
end
end
# Now vary mass of planet:
xm= big.(x0)
vm= big.(v0)
mm= big.(m0)
fill!(big_xerror,0.0)
fill!(big_verror,0.0)
dq = mm[j]*dlnq
mm[j] -= dq
for istep=1:nstep
ah18!(xm,vm,big_xerror,big_verror,hbig,mm,n,pair)
end
xp= big.(x0)
vp= big.(v0)
mp= big.(m0)
fill!(big_xerror,0.0)
fill!(big_verror,0.0)
dq = mp[j]*dlnq
mp[j] += dq
for istep=1:nstep
ah18!(xp,vp,big_xerror,big_verror,hbig,mp,n,pair)
end
for i=1:n
for k=1:3
jac_step_num[(i-1)*7+ k,j*7] = .5*(xp[k,i]-xm[k,i])/dq
jac_step_num[(i-1)*7+3+k,j*7] = .5*(vp[k,i]-vm[k,i])/dq
end
end
# Mass unchanged -> identity
jac_step_num[j*7,j*7] = 1.0
end
# Now, compare the results:
#println(jac_step)
#println(jac_step_num)
#for j=1:n
# for i=1:7
# for k=1:n
# println(i," ",j," ",k," ",jac_step[(j-1)*7+i,(k-1)*7+1:k*7]," ",jac_step_num[(j-1)*7+i,(k-1)*7+1:k*7]," ",jac_step[(j-1)*7+i,(k-1)*7+1:7*k]./jac_step_num[(j-1)*7+i,(k-1)*7+1:7*k]-1.)
# end
# end
#end
jacmax = 0.0; jac_diff = 0.0
imax = 0; jmax = 0; kmax = 0; lmax = 0
for i=1:7, j=1:3, k=1:7, l=1:3
if jac_step[(j-1)*7+i,(l-1)*7+k] != 0
diff = abs(jac_step_num[(j-1)*7+i,(l-1)*7+k]/jac_step[(j-1)*7+i,(l-1)*7+k]-1.0)
if diff > jacmax
jac_diff = diff; imax = i; jmax = j; kmax = k; lmax = l; jacmax = jac_step[(j-1)*7+i,(l-1)*7+k]
end
end
end
#println("Maximum fractional error: ",jac_diff," ",imax," ",jmax," ",kmax," ",lmax," ",jacmax)
#println(jac_step./jac_step_num)
#println("Maximum error jac_step: ",maximum(abs.(jac_step-jac_step_num)))
#println("Maximum error jac_step_big vs. jac_step_num: ",maximum(abs.(asinh.(jac_step_big)-asinh.(jac_step_num))))
#println("Maximum diff asinh(jac_step): ",maximum(abs.(asinh.(jac_step)-asinh.(jac_step_num))))
# Compute dqdt:
dqdt = zeros(7*n)
dqdt_num = zeros(BigFloat,7*n)
x = copy(x0)
v = copy(v0)
m = copy(m0)
xerror = zeros(3,n); verror = zeros(3,n)
ah18!(x,v,xerror,verror,h,m,n,dqdt,pair)
xm= big.(x0)
vm= big.(v0)
mm= big.(m0)
fill!(big_xerror,0.0)
fill!(big_verror,0.0)
dq = hbig*dlnq
hbig -= dq
ah18!(xm,vm,big_xerror,big_verror,hbig,mm,n,pair)
xp= big.(x0)
vp= big.(v0)
mp= big.(m0)
fill!(big_xerror,0.0)
fill!(big_verror,0.0)
hbig += 2dq
ah18!(xp,vp,big_xerror,big_verror,hbig,mp,n,pair)
for i=1:n, k=1:3
dqdt_num[(i-1)*7+ k] = .5*(xp[k,i]-xm[k,i])/dq
dqdt_num[(i-1)*7+3+k] = .5*(vp[k,i]-vm[k,i])/dq
end
dqdt_num = convert(Array{Float64,1},dqdt_num)
#println("dqdt: ",dqdt); println("dqdt_num: ",dqdt_num); println(" diff: ",dqdt-dqdt_num)
#println("dqdt-dqdt_num: ",maxabs(dqdt-convert(Array{Float64,1},dqdt_num)))
#@test isapprox(jac_step,jac_step_num)
#@test isapprox(jac_step,jac_step_num;norm=maxabs)
@test isapprox(asinh.(jac_step),asinh.(jac_step_num);norm=maxabs)
@test isapprox(dqdt,dqdt_num;norm=maxabs)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 1896 |
function NeumaierSum(input)
sum = 0.0
c = 0.0 # A running compensation for lost low-order bits.
for i = 1:size(input)[1]
t = sum + input[i]
if abs(sum) >= abs(input[i])
c += (sum - t) + input[i] # If sum is bigger, low-order digits of input[i] are lost.
else
c += (input[i] - t) + sum # Else low-order digits of sum are lost.
end
sum = t
end
return sum,c # Correction only applied once in the very end.
end
#include("../src/ttv.jl")
include("../src/utils.jl")
# Testing compensated summation:
#Base.rand(::Type{BigFloat}) = get(tryparse(BigFloat, "0." .* join(rand(['0','1'], precision(BigFloat)));base= 2))
function test_comp_sum()
# Create random numbers in BigFloat precision:
nrand = 1000000
summand_big = zeros(BigFloat,nrand)
for i=1:nrand
summand_big[i] = (rand(BigFloat)-big(0.5))*10^(rand(BigFloat)*2)
end
# Convert summands to Float64:
summand = convert(Array{Float64,1},summand_big)
# So, now sum with Kahan compensated summation:
err = 0.0
sum_comp = 0.0
for i=1:nrand
sum_comp,err = comp_sum(sum_comp,err,summand[i])
end
# Next with Neumaier compensated summation:
sum_neum,corr_neum = NeumaierSum(summand)
# Sum without compensated summation:
sum_flt = sum(summand)
# Sum with BigFloat precision:
sum_big = sum(summand_big)
# Now compare the difference:
println("Float - Big sum: ",sum_flt-sum_big)
println("Comp - Big sum: ",sum_comp-sum_big)
diff = sum_comp-sum_big+err
println("Error: ",err," Comp - Big +err: ",sum_comp-sum_big-err," Big - (Comp + err): ",sum_big-sum_comp+err)
diff_neum = sum_neum-sum_big+corr_neum
println("Error: ",corr_neum," Neum - Big +err: ",sum_neum-sum_big+corr_neum," Big - (Comp + err): ",sum_big-sum_neum-corr_neum)
println("Improve Kahan: ",abs(diff)/abs(sum_flt-sum_big))
println("Improve Neum: ",abs(diff_neum)/abs(sum_flt-sum_big))
end
test_comp_sum()
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 245 | using NbodyGradient, DelimitedFiles
include("../src/integrator/convert.jl")
fname = "elements.txt"
el = readdlm(fname,',')
ic = ElementsIC(el,8,0.0)
s = State(ic)
elements = get_orbital_elements(s,ic)
println(isapprox(elements,ic.elements))
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 2721 |
#include("../src/ttv.jl")
#include("/Users/ericagol/Computer/Julia/regress.jl")
run(`rm -f coord_jac_double.txt`)
run(`rm -f coord_jac_bigfloat.txt`)
#@testset "test_coordinates" begin
# This routine takes derivative of coordinates with respect
# to the initial cartesian coordinates of bodies, output to a *large* file.
#n = 8
n = 3
t0 = 7257.93115525-7300.0
#h = 0.12
h = 0.04
#h = 0.02
#tmax = 600.0
#tmax = 1000.0
tmax = 100.0
#tmax = 10.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
ntt = zeros(Int64,n)
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
println("ntt: ",ntt)
tt = zeros(n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
# Call the ttv function & compute derivatives (with respect to initial cartesian positions/masses):
rstar = 1e12
dtdq0 = zeros(n,maximum(ntt),7,n)
@time dtdelements = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq0,rstar;fout="coord_jac_double.txt",iout=10)
# Compute the derivatives in BigFloat precision to see whether finite difference
# derivatives or Float64 derivatives are imprecise at the start:
hbig = big(h); t0big = big(t0); tmaxbig=big(tmax); tt_big = big.(tt); elementsbig = big.(elements); rstarbig = big(rstar)
dtdq0_big = zeros(BigFloat,n,maximum(ntt),7,n)
@time dtdelements_big = ttv_elements!(n,t0big,hbig,tmaxbig,elementsbig,tt_big,count,dtdq0_big,rstarbig;fout="coord_jac_bigfloat.txt",iout=10)
using PyPlot
clf()
# Plot the difference in the TTVs:
for i=2:3
diff1 = abs.(tt[i,2:count[i]].-tt_big[i,2:count[i]])/elements[i,2];
loglog(tt[i,2:count[i]]-tt[i,1],diff1);
end
loglog([1.0,1024.0],2e-15*[1,2^15],":")
for i=2:3, k=1:7, l=1:3
if maximum(abs.(dtdq0[i,2:count[i],k,l])) > 0
diff3 = abs.(asinh.(dtdq0_big[i,2:count[i],k,l])-asinh.(dtdq0[i,2:count[i],k,l]));
loglog(tt[i,2:count[i]]-tt[i,1],diff3,linestyle=":");
println(i," ",k," ",l," asinh error: ",convert(Float64,maximum(diff3))); read(STDIN,Char);
end
end
mederror = zeros(size(tt))
# Plot a line that scales as time^{3/2}:
loglog([1.0,1024.0],1e-12*[1,2^15],":",linewidth=3)
println("Max diff asinh(dtdq0): ",maximum(abs.(asinh.(dtdq0_big)-asinh.(dtdq0))))
@test isapprox(asinh.(dtdq0),asinh.(convert(Array{Float64,4},dtdq0_big));norm=maxabs)
#end
read(STDIN,Char)
# Now read in coordinate Jacobians:
data_dbl = readdlm("coord_jac_double.txt")
data_big = readdlm("coord_jac_bigfloat.txt")
# And plot the results
ncol = 49*n^2+6*n+1
nt = size(data_dbl)[1]
for i=1:ncol
loglog(data_dbl[2:nt,1]-data_dbl[1,1],abs.(asinh.(data_big[2:nt,i])-asinh.(data_dbl[2:nt,i])))
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 7108 | # Tests the routine dh17 jacobian2
#include("../src/ttv.jl")
# Next, try computing three-body Keplerian Jacobian:
@testset "dh17" begin
#n = 8
n = 3
H = [3,1,1]
#n = 2
t0 = 7257.93115525
h = 0.05
hbig = big(h)
tmax = 600.0
dlnq = big(1e-20)
#nstep = 8000
nstep = 500
#nstep = 1
elements = readdlm("elements.txt",',')
# Increase mass of inner planets:
elements[2,1] *= 100.
elements[3,1] *= 100.
m =zeros(n)
x0=zeros(3,n)
v0=zeros(3,n)
# Define which pairs will have impulse rather than -drift+Kepler:
pair = zeros(Bool,n,n)
# We want Keplerian between star & planets, and impulses between
# planets. Impulse is indicated with 'true', -drift+Kepler with 'false':
#for i=2:n
# pair[1,i] = false
# # We don't need to define this, but let's anyways:
# pair[i,1] = false
#end
# Initialize with identity matrix:
jac_step = Matrix{Float64}(I,7*n,7*n)
jac_error = zeros(7*n,7*n)
for k=1:n
m[k] = elements[k,1]
end
m0 = copy(m)
init = ElementsIC(elements,H,t0)
x0,v0,_ = init_nbody(init)
# Tilt the orbits a bit:
x0[2,1] = 5e-1*sqrt(x0[1,1]^2+x0[3,1]^2)
x0[2,2] = -5e-1*sqrt(x0[1,2]^2+x0[3,2]^2)
x0[2,3] = -5e-1*sqrt(x0[1,2]^2+x0[3,2]^2)
v0[2,1] = 5e-1*sqrt(v0[1,1]^2+v0[3,1]^2)
v0[2,2] = -5e-1*sqrt(v0[1,2]^2+v0[3,2]^2)
v0[2,3] = -5e-1*sqrt(v0[1,2]^2+v0[3,2]^2)
xtest = copy(x0); vtest=copy(v0)
xbig = big.(x0); vbig = big.(v0)
# Take a single step (so that we aren't at initial coordinates):
@time for i=1:nstep; dh17!(x0,v0,h,m,n,pair); end
# Take a step with big precision:
ah18!(xbig,vbig,big(h),big.(m),n,pair)
# Take a single AH18 step:
@time for i=1:nstep; ah18!(xtest,vtest,h,m,n,pair);end
println("AH18 vs. DH17 x/v difference: ",x0-xtest,v0-vtest)
# Now, copy these to compute Jacobian (so that I don't step
# x0 & v0 forward in time):
x = copy(x0)
v = copy(v0)
m = copy(m0)
xerror = zeros(3,n); verror = zeros(3,n)
xbig = big.(x0)
vbig = big.(v0)
mbig = big.(m0)
xerr_big = zeros(BigFloat,3,n); verr_big=zeros(BigFloat,3,n);
# Compute jacobian exactly over nstep steps:
for istep=1:nstep
dh17!(x,v,xerror,verror,h,m,n,jac_step,pair)
end
#println(typeof(h)," ",jac_step)
#read(STDIN,Char)
# The following lines have a Julia bug - jac_big gets
# misaligned or shifted when returned. If I modify dh17! to output
# jac_step, then it works.
# Initialize with identity matrix:
## Compute jacobian exactly over nstep steps:
#for istep=1:nstep
# jac_copy = dh17!(xbig,vbig,hbig,mbig,n,jac_big,pair)
#end
#println(typeof(hbig)," ",convert(Array{Float64,2},jac_copy))
#println("Comparing x & xbig: ",maximum(abs,x-xbig))
#println("Comparing v & vbig: ",maximum(abs,v-vbig))
#println("Comparing jac_step and jac_big: ",maxabs(jac_step-jac_copy))
#println("Comparing jac_step and jac_big: ",jac_step./convert(Array{Float64,2},jac_big))
# Test that both versions of dh17 give the same answer:
#xtest = copy(x0)
#vtest = copy(v0)
#m = copy(m0)
#for istep=1:nstep
# dh17!(xtest,vtest,h,m,n,pair)
#end
#println("x/v difference: ",x-xtest,v-vtest)
# Now compute numerical derivatives:
jac_step_num = zeros(BigFloat,7*n,7*n)
# Vary the initial parameters of planet j:
for j=1:n
# Vary the initial phase-space elements:
for jj=1:3
# Initial positions, velocities & masses:
xm = big.(x0)
vm = big.(v0)
mm = big.(m0)
dq = dlnq * xm[jj,j]
if xm[jj,j] != 0.0
xm[jj,j] -= dq
else
dq = dlnq
xm[jj,j] = -dq
end
for istep=1:nstep
dh17!(xm,vm,hbig,mm,n,pair)
end
xp = big.(x0)
vp = big.(v0)
mp = big.(m0)
dq = dlnq * xp[jj,j]
if xp[jj,j] != 0.0
xp[jj,j] += dq
else
dq = dlnq
xp[jj,j] = dq
end
for istep=1:nstep
dh17!(xp,vp,hbig,mp,n,pair)
end
# Now x & v are final positions & velocities after time step
for i=1:n
for k=1:3
jac_step_num[(i-1)*7+ k,(j-1)*7+ jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_step_num[(i-1)*7+3+k,(j-1)*7+ jj] = .5*(vp[k,i]-vm[k,i])/dq
end
end
# Next velocity derivatives:
xm= big.(x0)
vm= big.(v0)
mm= big.(m0)
dq = dlnq * vm[jj,j]
if vm[jj,j] != 0.0
vm[jj,j] -= dq
else
dq = dlnq
vm[jj,j] = -dq
end
for istep=1:nstep
dh17!(xm,vm,hbig,mm,n,pair)
end
xp= big.(x0)
vp= big.(v0)
mp= big.(m0)
dq = dlnq * vp[jj,j]
if vp[jj,j] != 0.0
vp[jj,j] += dq
else
dq = dlnq
vp[jj,j] = dq
end
for istep=1:nstep
dh17!(xp,vp,hbig,mp,n,pair)
end
for i=1:n
for k=1:3
jac_step_num[(i-1)*7+ k,(j-1)*7+3+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_step_num[(i-1)*7+3+k,(j-1)*7+3+jj] = .5*(vp[k,i]-vm[k,i])/dq
end
end
end
# Now vary mass of planet:
xm= big.(x0)
vm= big.(v0)
mm= big.(m0)
dq = mm[j]*dlnq
mm[j] -= dq
for istep=1:nstep
dh17!(xm,vm,hbig,mm,n,pair)
end
xp= big.(x0)
vp= big.(v0)
mp= big.(m0)
dq = mp[j]*dlnq
mp[j] += dq
for istep=1:nstep
dh17!(xp,vp,hbig,mp,n,pair)
end
for i=1:n
for k=1:3
jac_step_num[(i-1)*7+ k,j*7] = .5*(xp[k,i]-xm[k,i])/dq
jac_step_num[(i-1)*7+3+k,j*7] = .5*(vp[k,i]-vm[k,i])/dq
end
end
# Mass unchanged -> identity
jac_step_num[j*7,j*7] = 1.0
end
# Now, compare the results:
#println(jac_step)
#println(jac_step_num)
#for j=1:n
# for i=1:7
# for k=1:n
# println(i," ",j," ",k," ",jac_step[(j-1)*7+i,(k-1)*7+1:k*7]," ",jac_step_num[(j-1)*7+i,(k-1)*7+1:k*7]," ",jac_step[(j-1)*7+i,(k-1)*7+1:7*k]./jac_step_num[(j-1)*7+i,(k-1)*7+1:7*k]-1.)
# end
# end
#end
jacmax = 0.0; jac_diff = 0.0
imax = 0; jmax = 0; kmax = 0; lmax = 0
for i=1:7, j=1:3, k=1:7, l=1:3
if jac_step[(j-1)*7+i,(l-1)*7+k] != 0
diff = abs(jac_step_num[(j-1)*7+i,(l-1)*7+k]/jac_step[(j-1)*7+i,(l-1)*7+k]-1.0)
if diff > jacmax
jac_diff = diff; imax = i; jmax = j; kmax = k; lmax = l; jacmax = jac_step[(j-1)*7+i,(l-1)*7+k]
end
end
end
println("Maximum fractional error: ",jac_diff," ",imax," ",jmax," ",kmax," ",lmax," ",jacmax)
#println(jac_step./jac_step_num)
println("Maximum error jac_step: ",maximum(abs.(jac_step-jac_step_num)))
println("Maximum diff asinh(jac_step): ",maximum(abs.(asinh.(jac_step)-asinh.(jac_step_num))))
# Compute dqdt:
# Set a short timestep so that particles will drift:
h = 0.001; hbig = big(h)
dqdt = zeros(7*n)
dqdt_num = zeros(BigFloat,7*n)
x = copy(x0)
v = copy(v0)
m = copy(m0)
xerror = zeros(3,n); verror = zeros(3,n)
dh17!(x,v,xerror,verror,h,m,n,dqdt,pair)
xm= big.(x0)
vm= big.(v0)
mm= big.(m0)
dq = hbig*dlnq
hbig -= dq
dh17!(xm,vm,hbig,mm,n,pair)
xp= big.(x0)
vp= big.(v0)
mp= big.(m0)
hbig += 2dq
dh17!(xp,vp,hbig,mp,n,pair)
for i=1:n, k=1:3
dqdt_num[(i-1)*7+ k] = (xp[k,i]-xm[k,i])/dq/2
dqdt_num[(i-1)*7+3+k] = (vp[k,i]-vm[k,i])/dq/2
end
dqdt_num = convert(Array{Float64,1},dqdt_num)
println("dqdt: ",dqdt," dqdt_num: ",dqdt_num," diff: ",dqdt-dqdt_num)
println("dqdt-dqdt_num: ",maxabs(dqdt-convert(Array{Float64,1},dqdt_num)))
#@test isapprox(jac_step,jac_step_num)
#@test isapprox(jac_step,jac_step_num;norm=maxabs)
@test isapprox(asinh.(jac_step),asinh.(jac_step_num);norm=maxabs)
@test isapprox(dqdt,dqdt_num;norm=maxabs)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 895 | @testset "Elements" begin
# Get known 'good' elements
fname = "elements.txt"
t0 = 7257.93115525-7300.0
H = [3,1,1]
init0 = ElementsIC(fname,H,t0)
# Fill new methods with pre-calculated elements
# See if we get back the proper array
elems_arr = readdlm(fname,',',comments=true)
# Convert ecosϖ/esinϖ to ϖ and e
elems_a = copy(elems_arr[1,:])
elems_b = copy(elems_arr[2,:])
elems_c = copy(elems_arr[3,:])
function convert_back!(elems::Vector{<:Real})
e = sqrt(elems[4]^2 + elems[5]^2)
ϖ = atan(elems[5],elems[4])
elems .= [elems[1:3];e;ϖ;elems[6:end]]
return
end
convert_back!.([elems_b,elems_c])
a = Elements(elems_a...)
b = Elements(elems_b...)
c = Elements(elems_c...)
init_test = ElementsIC(t0,a,b,c,H=H)
@test isapprox(init0.elements[1:3,:],init_test.elements);
end;
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 1912 | using PyPlot
include("../src/kepler_solver.jl")
# Define a constant of 1/3:
const third = 1.0/3.0
function test_elliptic()
# This routine runs a test of the kep_elliptic function in kepler_solver_elliptic.jl
# Define the central force constant in terms of AU and days:
k = (2.0*pi/365.25)^2
# Initial position at 1 AU:
x0 = [0.0,1.0,0.0]
#r0 = norm(x0)
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
# Circular velocity:
vcirc = sqrt(k/r0)
# Define initial velocity at apastron:
v0 = [0.98*vcirc,0.0,0.0] # The eccentricity is about ~2(1-v0/vcirc).
h = 18.0 # 18-day timesteps
s0::Float64 = 0.0
x = zeros(Float64,3)
v = zeros(Float64,3)
s::Float64 = 0.0
t = 0.0
ssave = zeros(2)
#nsteps = 10000000
nsteps = 1000000
#nsteps = 1000
xsave=zeros(Float64,12,nsteps) # First is time (1,:); next three are position (2-4,:); next three velocity (5-7,:); then r (8,:), drdt (9,:); then beta (10,:); finally s & ds (11:12,:)
# Create a variable to store the state at the end of a step:
state=zeros(Float64,12)
xsave[1,1]=0.0
for j=1:3
xsave[j+1,1]=x0[j]
xsave[j+4,1]=v0[j]
end
# Save beta:
xsave[8,1]=r0
beta0 = 2.0*k/r0-dot(v0,v0)
xsave[10,1]=beta0
#@inbounds for i=2:nsteps
for i=2:nsteps
# x,v,r,drdt,s,beta,iter=kep_elliptic(x0,v0,r0,k,h,beta0,s0)
# iter = kep_elliptic!(x0,v0,r0,k,h,beta0,s0,state)
iter = kep_ell_hyp!(x0,v0,r0,k,h,beta0,s0,state)
s = state[11]
ds = state[12]
if iter > 2
println("iter: ",iter," ds: ",ds)
end
# Increment time by h:
state[1] += h
for j=1:12
xsave[j,i]=state[j]
end
if i >= 4
# Quadratic prediction for s of next step:
s0 = 3.0*s - 3.0*ssave[1] + ssave[2]
ssave[2] = ssave[1]
ssave[1] = s
else
s0 = s
ssave[2]=ssave[1]
ssave[1]=s
end
# Now, proceed to next step:
for j=1:3
x0[j]=state[1+j]
v0[j]=state[4+j]
end
r0=state[8]
beta0=state[10]
# println(i,x,v)
end
#plot(xsave[1],xsave[2])
return xsave
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 5301 | # This code tests two functions: keplerij! and kep_elliptic!
#using PyPlot
#include("../src/kepler_solver_derivative.jl")
#include("../src/ttv.jl")
@testset "kep_elliptic" begin
# Define a constant of 1/3:
#const third = 1.0/3.0
function test_elliptic_derivative(dlnq::BigFloat)
# Call as: save,jac_num,jacobian=test_elliptic_derivative(1e-4)
# This routine runs a test of the kep_elliptic_jacobian function in kepler_solver.jl
# Define the central force constant in terms of AU and days:
k = (2.0*pi/365.25)^2
# Initial position at 1 AU:
x0 = [0.01,1.0,0.01]
#r0 = norm(x0)
# Circular velocity:
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
vcirc = sqrt(k/r0)
# Define initial velocity at apastron:
v0 = [.9*vcirc,0.01*vcirc,0.01*vcirc] # The eccentricity is about ~2(1-v0/vcirc).
h = 18.0 # 18-day timesteps
hbig = big(h)
s0::Float64 = 0.0
x = zeros(Float64,3)
v = zeros(Float64,3)
s::Float64 = 0.0
t = 0.0
ssave = zeros(2)
nsteps = 1
xsave=zeros(Float64,12,nsteps) # First is time (1,:); next three are position (2-4,:); next three velocity (5-7,:); then r (8,:), drdt (9,:); then beta (10,:); finally s & ds (11:12,:)
# Create a variable to store the state at the end of a step:
state=zeros(Float64,12)
state_diffbig=zeros(BigFloat,12)
xsave[1,1]=0.0
for jj=1:3
xsave[jj+1,1]=x0[jj]
xsave[jj+4,1]=v0[jj]
end
# Save beta:
xsave[8,1]=r0
beta0 = 2.0*k/r0-dot(v0,v0)
xsave[10,1]=beta0
jacobian=zeros(Float64,7,7)
d = Derivatives(Float64)
#iter = kep_elliptic!(x0,v0,r0,k,h,beta0,s0,state,jacobian)
iter = kep_ell_hyp!(x0,v0,r0,k,h,beta0,s0,state,jacobian,d)
#println("Initial conditions: ",x0,v0)
#println("Final state: ",state)
#println("Differnce : ",state[2:4]-x0,state[5:7]-v0)
#read(STDIN,Char)
# Now, do finite differences at higher precision:
kbig = big(k); s0big = big(0.0); statebig = big.(state)
x0big = big.(x0); v0big = big.(v0)
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
jacobian_big =zeros(BigFloat,7,7)
dBig = Derivatives(BigFloat)
#iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,statebig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,statebig,jacobian_big,dBig)
#println("Final state: ",statebig[2:7])
jac_frac = jacobian./convert(Array{Float64,2},jacobian_big).-1.0
println("Fractional Jacobian difference: ",maxabs(jac_frac[.~isnan.(jac_frac)]))
#println(jacobian)
#println(jac_frac)
#read(STDIN,Char)
#s = statebig[11]
# Now, compute the Jacobian numerically:
#jac_num = zeros(Float64,7,7)
jac_num = zeros(BigFloat,7,7)
# jac_num[i,j]: derivative of (x_i,v_i,k) with respect to (x_{0,j},v_{0,j},k):
for j=1:3
x0save = copy(x0big)
dq = dlnq * x0big[j]
if x0big[j] != 0.0
x0big[j] += dq
else
dq = dlnq
x0big[j] = dq
end
# Recompute quantities:
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
# iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
x0big = copy(x0save)
for i=1:3
jac_num[ i, j] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i, j] = (state_diffbig[4+i]-statebig[4+i])/dq
end
v0save = copy(v0big)
dq = dlnq * v0big[j]
if v0big[j] != 0.0
v0big[j] += dq
else
dq = dlnq
v0big[j] = dq
end
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
# iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
v0big = copy(v0save)
for i=1:3
jac_num[ i,3+j] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i,3+j] = (state_diffbig[4+i]-statebig[4+i])/dq
end
# Now vary mass:
ksave = copy(kbig)
dq = kbig*dlnq
kbig += dq
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
# iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
for i=1:3
jac_num[ i,7] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i,7] = (state_diffbig[4+i]-statebig[4+i])/dq
end
kbig = copy(ksave)
jac_num[7, 7] = 1.0
end
println("Maximum jac_big-jac_num: ",maxabs(convert(Array{Float64,2},jacobian_big-jac_num)))
#println(convert(Array{Float64,2},jacobian_big))
#println(convert(Array{Float64,2},jacobian_big./jac_num-1.0))
return xsave,jac_num,jacobian
end
# First try:
xsave,jac_num1,jacobian=test_elliptic_derivative(big(1e-20))
# Second try:
#xsave,jac_num2,jacobian=test_elliptic_derivative(1e-6)
#jacobian
#jac_num1-jac_num2
#println("Fraction errors on Jacobian: ",jac_num1./jacobian-1.0)
#println("jac_num1: ",jac_num1)
emax = 0.0; imax = 0; jmax = 0
for i=1:7, j=1:7
if jacobian[i,j] != 0.0
diff = abs(convert(Float64,jac_num1[i,j])/jacobian[i,j]-1.0)
if diff > emax
emax = diff; imax = i; jmax = j
end
end
end
println("Maximum fractional error: ",emax," ",imax," ",jmax)
println("Maximum jacobian-jac_num: ",maxabs(jacobian-convert(Array{Float64,2},jac_num1)))
#@test isapprox(jacobian,jac_num1)
@test isapprox(jacobian,jac_num1;norm=maxabs)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4881 | # This code tests two functions: keplerij! and kep_elliptic!
#using PyPlot
#include("../src/kepler_solver_derivative.jl")
#include("../src/ttv.jl")
@testset "kep_elliptic" begin
# Define a constant of 1/3:
#const third = 1.0/3.0
function test_elliptic_derivative(dlnq::BigFloat)
# Call as: save,jac_num,jacobian=test_elliptic_derivative(1e-4)
# This routine runs a test of the kep_elliptic_jacobian function in kepler_solver.jl
# Define the central force constant in terms of AU and days:
k = (2.0*pi/365.25)^2
# Initial position at 1 AU:
x0 = [0.01,1.0,0.01]
#r0 = norm(x0)
# Circular velocity:
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
vcirc = sqrt(k/r0)
# Define initial velocity at apastron:
v0 = [.9*vcirc,0.01*vcirc,0.01*vcirc] # The eccentricity is about ~2(1-v0/vcirc).
h = 100.0 # 18-day timesteps
hbig = big(h)
s0::Float64 = 0.0
x = zeros(Float64,3)
v = zeros(Float64,3)
s::Float64 = 0.0
t = 0.0
ssave = zeros(2)
nsteps = 1
xsave=zeros(Float64,12,nsteps) # First is time (1,:); next three are position (2-4,:); next three velocity (5-7,:); then r (8,:), drdt (9,:); then beta (10,:); finally s & ds (11:12,:)
# Create a variable to store the state at the end of a step:
state=zeros(Float64,12)
state_diffbig=zeros(BigFloat,12)
xsave[1,1]=0.0
for jj=1:3
xsave[jj+1,1]=x0[jj]
xsave[jj+4,1]=v0[jj]
end
# Save beta:
xsave[8,1]=r0
beta0 = 2.0*k/r0-dot(v0,v0)
xsave[10,1]=beta0
jacobian=zeros(Float64,7,7)
#iter = kep_elliptic!(x0,v0,r0,k,h,beta0,s0,state,jacobian)
iter = kep_ell_hyp!(x0,v0,r0,k,h,beta0,s0,state,jacobian)
#println("Initial conditions: ",x0,v0)
#println("Final state: ",state)
#println("Differnce : ",state[2:4]-x0,state[5:7]-v0)
#read(STDIN,Char)
# Now, do finite differences at higher precision:
kbig = big(k); s0big = big(0.0); statebig = big.(state)
x0big = big.(x0); v0big = big.(v0)
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
#iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,statebig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,statebig)
#println("Final state: ",statebig[2:7])
#read(STDIN,Char)
#s = statebig[11]
# Now, compute the Jacobian numerically:
#jac_num = zeros(Float64,7,7)
jac_num = zeros(BigFloat,7,7)
#dlnq = 1e-4
# jac_num[i,j]: derivative of (x_i,v_i,k) with respect to (x_{0,j},v_{0,j},k):
for j=1:3
x0save = copy(x0big)
dq = dlnq * x0big[j]
if x0big[j] != 0.0
x0big[j] += dq
else
dq = dlnq
x0big[j] = dq
end
# Recompute quantities:
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
# iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
x0big = copy(x0save)
for i=1:3
jac_num[ i, j] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i, j] = (state_diffbig[4+i]-statebig[4+i])/dq
end
v0save = copy(v0big)
dq = dlnq * v0big[j]
if v0big[j] != 0.0
v0big[j] += dq
else
dq = dlnq
v0big[j] = dq
end
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
# iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
v0big = copy(v0save)
for i=1:3
jac_num[ i,3+j] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i,3+j] = (state_diffbig[4+i]-statebig[4+i])/dq
end
# Now vary mass:
ksave = copy(kbig)
dq = kbig*dlnq
kbig += dq
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
# iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
for i=1:3
jac_num[ i,7] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i,7] = (state_diffbig[4+i]-statebig[4+i])/dq
end
kbig = copy(ksave)
jac_num[7, 7] = 1.0
end
return xsave,jac_num,jacobian
end
# First try:
const KEPLER_TOL = 1e-12
xsave,jac_num1,jacobian=test_elliptic_derivative(big(1e-15))
# Second try:
#xsave,jac_num2,jacobian=test_elliptic_derivative(1e-6)
#println("Jac dlnq=1e-7 ")
#jac_num1
#println("Jac dlnq=1e-6 ")
#jac_num2
#jacobian
#jac_num1-jac_num2
#println("Fraction errors on Jacobian: ",jac_num1./jacobian-1.0)
#println("jac_num1: ",jac_num1)
emax = 0.0; imax = 0; jmax = 0
for i=1:7, j=1:7
if jacobian[i,j] != 0.0
diff = abs(jac_num1[i,j]/jacobian[i,j]-1.0)
if diff > emax
emax = diff; imax = i; jmax = j
end
end
end
println("Maximum fractional error: ",emax," ",imax," ",jmax)
println("Maximum error jacobian: ",maximum(abs.(jacobian-jac_num1)))
#@test isapprox(jacobian,jac_num1)
@test isapprox(jacobian,jac_num1;norm=maxabs)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 2050 | #include("../src/ttv.jl")
#include("/Users/ericagol/Computer/Julia/regress.jl")
#maxabs(x) = maximum(abs.(x))
#using Base.Test
#KEPLER_TOL = 1e-15
#TRANSIT_TOL = 1e-15
@testset "findtransit3" begin
#n = 8
n = 3
H = [3,1,1]
t0 = 7257.93115525
#h = 0.12
h = 0.05
#tmax = 600.0
#tmax = 100.0
tmax = 10.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
# Increase masses for debugging:
elements[2,1] *= 10.0
elements[3,1] *= 10.0
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
ntt = zeros(Int64,n)
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
tt = zeros(n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
# Now, compute derivatives (with respect to initial cartesian positions/masses at
# beginning of each step):
dtdq0 = zeros(n,maximum(ntt),7,n)
dtdq0_num = zeros(BigFloat,n,maximum(ntt),7,n)
dlnq = big(1e-10)
# Make radius of star large:
rstar = 1e12
# Not sure why this call is here.
#dtdelements_num = ttv_elements!(H,t0,h,tmax,elements,tt,count,dtdq0,dtdq0_num,dlnq,rstar)
# Now do computation in BigFloat precision:
dtdq0_big = big.(dtdq0)
dtdelements_num = ttv_elements!(H,big(t0),big(h),big(tmax),big.(elements),big.(tt),count,dtdq0_big,big(rstar))
dtdq0_num = convert(Array{Float64,4},dtdq0_num)
dtdq0_big = convert(Array{Float64,4},dtdq0_big)
mask = zeros(Bool, size(dtdq0))
for i=2:n, j=1:count[i], k=1:5, l=1:n
mask[i,j,k,l] = true
end
#println("Max diff log(dtdq0): ",maximum(abs.(dtdq0_num[mask]./dtdq0[mask]-1.0)))
#println("Max diff asinh(dtdq0): ",maximum(abs.(asinh.(dtdq0_num[mask])-asinh.(dtdq0[mask]))))
#println("Max diff dtdq0 : ",maximum((dtdq0_num[mask]-dtdq0[mask])))
#@test isapprox(dtdq0[mask],convert(Array{Float64,4},dtdq0_num)[mask];norm=maxabs)
@test isapprox(asinh.(dtdq0[mask]),asinh.(convert(Array{Float64,4},dtdq0_num)[mask]);norm=maxabs)
#unit = ones(dtdq0[mask])
#@test isapprox(dtdq0[mask]./convert(Array{Float64,4},dtdq0_num)[mask],unit;norm=maxabs)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 1705 |
include("../src/g3.jl")
using PyPlot
@testset "g3_hn" begin
gamma = logspace(-10.0,0.0,1000)
gbig = big.(gamma)
for beta in [-1.5,-0.75,-0.1,-0.01,-0.001,-0.0001,-0.00001,-0.000001,0.000001,0.00001,0.0001,0.001,0.01,0.1,0.75,1.5]
clf()
betabig=big(beta)
zbig = big(0.0)
g3b = convert(Array{Float64,1},G3.(gbig,betabig;gc = zbig))
h1b = convert(Array{Float64,1},H1.(gbig,betabig;gc = zbig))
h2b = convert(Array{Float64,1},H2.(gbig,betabig;gc = zbig))
h3b = convert(Array{Float64,1},H3.(gbig,betabig;gc = zbig))
h5b = convert(Array{Float64,1},H5.(gbig,betabig;gc = zbig))
h6b = convert(Array{Float64,1},H6.(gbig,betabig;gc = zbig))
h7b = convert(Array{Float64,1},H7.(gbig,betabig;gc = zbig))
h8b = convert(Array{Float64,1},H8.(gbig,betabig;gc = zbig))
g3 = G3.(gamma,beta)
h1 = H1.(gamma,beta)
h2 = H2.(gamma,beta)
h3 = H3.(gamma,beta)
h5 = H5.(gamma,beta)
h6 = H6.(gamma,beta)
h7 = H7.(gamma,beta)
h8 = H8.(gamma,beta)
semilogy(gamma,abs.(g3./g3b-1),label="G3")
plot(gamma,abs.(h1./h1b-1),label="H1")
plot(gamma,abs.(h2./h2b-1),label="H2")
plot(gamma,abs.(h3./h3b-1),label="H3")
plot(gamma,abs.(h5./h5b-1),label="H5")
plot(gamma,abs.(h6./h6b-1),label="H6")
plot(gamma,abs.(h7./h7b-1),label="H7")
plot(gamma,abs.(h8./h8b-1),label="H8")
@test isapprox(g3b,g3;norm=maxabs)
@test isapprox(h1b,h1;norm=maxabs)
@test isapprox(h2b,h2;norm=maxabs)
@test isapprox(h3b,h3;norm=maxabs)
@test isapprox(h5b,h5;norm=maxabs)
@test isapprox(h6b,h6;norm=maxabs)
@test isapprox(h7b,h7;norm=maxabs)
@test isapprox(h8b,h8;norm=maxabs)
println("beta: ",beta)
axis([0.0,1.0,1e-16,0.1])
legend(loc="upper left")
read(STDIN,Char)
end
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 950 | # Writing a test for a new Hamiltonian formulation:
n = 4
x = zeros(3,n)
v = zeros(3,n)
vcom = zeros(3)
m = zeros(n)
h_cartesian = 0.0
# Compute Hamiltonian in Cartesian coordinates:
for i=1:n
x[:,i] = randn(3)
v[:,i] = randn(3)
m[i] = exp(rand())
h_cartesian += 0.5*m[i]*dot(v[:,i],v[:,i])
vcom .+= m[i]*v[:,i]
end
# Center of mass velocity:
mtot = sum(m)
vcom ./= mtot
# Kinetic energy of the system:
h_sakura = h_cartesian
h_keplerian = 0.5*mtot*dot(vcom,vcom)
for i=1:n-1
for j=i+1:n
xij = x[:,j].-x[:,i]
vij = v[:,j].-v[:,i]
rij = norm(xij)
h_cartesian -= m[i]*m[j]/rij
mij = m[i]+m[j]
mred = m[i]*m[j]/mij
v2 = dot(vij,vij)
h_sakura += mred*(0.5*v2-mij/rij) - 0.5*mred*v2
h_keplerian += mred*(0.5*v2-mij/rij) - 0.5*(1.0-mij/mtot)*mred*v2
end
end
println("h_cartesian: ",h_cartesian)
println("h_sakura: ",h_sakura)
println("h_keplerian: ",h_keplerian," ",h_keplerian/h_cartesian-1.)
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 2048 | # Check whether the test is being run as standalone
if ~@isdefined Test
using Test
end
include("../src/setup_hierarchy.jl")
@testset "hierarchy matrix" begin
# Makes sure the hierarchy matrix generator is working as expected for a select set of orbital systems.
# Fully nested Keplerians
ϵ_nested::Matrix{Float64} = [-1 1 0 0;
-1 -1 1 0;
-1 -1 -1 1;
-1 -1 -1 -1;]
@test hierarchy([4,1,1,1]) == ϵ_nested
# Double Binary
ϵ_double::Matrix{Float64} = [-1 1 0 0;
0 0 -1 1;
-1 -1 1 1;
-1 -1 -1 -1;]
@test hierarchy([4,2,1]) == ϵ_double
# Double binary + top level body
ϵ_asym::Matrix{Float64} = [-1 1 0 0 0;
0 0 -1 1 0;
-1 -1 1 1 0;
-1 -1 -1 -1 1;
-1 -1 -1 -1 -1;]
@test hierarchy([5,2,1,1]) == ϵ_asym
# Test of specific ambiguous initialization case of a 'symmetric fully-nested' (top) and the double binary + tertiary binary (bottom)
ϵ_sym_full::Matrix{Float64} = [-1 1 0 0 0 0;
0 0 0 -1 1 0;
-1 -1 1 0 0 0;
0 0 0 -1 -1 1;
-1 -1 -1 1 1 1;
-1 -1 -1 -1 -1 -1;]
ϵ_asym_multi::Matrix{Float64}=[-1 1 0 0 0 0;
0 0 -1 1 0 0;
-1 -1 1 1 0 0;
0 0 0 0 -1 1;
-1 -1 -1 -1 1 1;
-1 -1 -1 -1 -1 -1;]
h_sym_full,h_asym_multi = hierarchy.([[6,2,2,1,2],[6,2,2,1]])
@test ϵ_sym_full == h_sym_full
@test ϵ_asym_multi == h_asym_multi
end | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 1857 | using PyPlot
include("../src/kepler_solver.jl")
# Define a constant of 1/3:
const third = 1.0/3.0
function test_hyperbolic()
# This routine runs a test of the kep_hyperbolic function in kepler_solver_hyperbolic.jl
# Define the central force constant in terms of AU and days:
k = (2.0*pi/365.25)^2
# Initial position at 1 AU:
x0 = [0.0,1.0,0.0]
#r0 = norm(x0)
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
# Circular velocity:
vcirc = sqrt(k/r0)
# Define initial velocity at apastron:
v0 = [1.5*vcirc,0.0,0.0] # The eccentricity is about ~2(1-v0/vcirc).
h = 18.0 # 18-day timesteps
s0::Float64 = 0.0
x = zeros(Float64,3)
v = zeros(Float64,3)
s::Float64 = 0.0
t = 0.0
ssave = zeros(2)
#nsteps = 10000000
nsteps = 1000000
#nsteps = 1000
xsave=zeros(Float64,12,nsteps) # First is time (1,:); next three are position (2-4,:); next three velocity (5-7,:); then r (8,:), drdt (9,:); then beta (10,:); finally s & ds (11:12,:)
# Create a variable to store the state at the end of a step:
state=zeros(Float64,12)
xsave[1,1]=0.0
for j=1:3
xsave[j+1,1]=x0[j]
xsave[j+4,1]=v0[j]
end
# Save beta:
xsave[8,1]=r0
beta0 = 2.0*k/r0-dot(v0,v0)
xsave[10,1]=beta0
#@inbounds for i=2:nsteps
for i=2:nsteps
# iter = kep_hyperbolic!(x0,v0,r0,k,h,beta0,s0,state)
iter = kep_ell_hyp!(x0,v0,r0,k,h,beta0,s0,state)
s = state[11]
ds = state[12]
if iter > 2
println("iter: ",iter," ds: ",ds)
end
# Increment time by h:
state[1] += h
for j=1:12
xsave[j,i]=state[j]
end
if i >= 4
# Quadratic prediction for s of next step:
s0 = 3.0*s - 3.0*ssave[1] + ssave[2]
ssave[2] = ssave[1]
ssave[1] = s
else
s0 = s
ssave[2]=ssave[1]
ssave[1]=s
end
# Now, proceed to next step:
for j=1:3
x0[j]=state[1+j]
v0[j]=state[4+j]
end
r0=state[8]
beta0=state[10]
# println(i,x,v)
end
#plot(xsave[1],xsave[2])
return xsave
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4906 | # This code tests two functions: keplerij! and kep_elliptic!
#using PyPlot
#include("../src/kepler_solver_derivative.jl")
#include("../src/ttv.jl")
@testset "kep_elliptic" begin
# Define a constant of 1/3:
#const third = 1.0/3.0
function test_elliptic_derivative(dlnq::BigFloat)
# Call as: save,jac_num,jacobian=test_elliptic_derivative(1e-4)
# This routine runs a test of the kep_elliptic_jacobian function in kepler_solver.jl
# Define the central force constant in terms of AU and days:
k = (2.0*pi/365.25)^2
# Initial position at 1 AU:
x0 = [0.01,1.0,0.01]
#r0 = norm(x0)
# Circular velocity:
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
vcirc = sqrt(k/r0)
# Define initial velocity at apastron:
v0 = [2.0*vcirc,0.01*vcirc,0.01*vcirc] # The eccentricity is about ~2(1-v0/vcirc).
h = 100.0 # 18-day timesteps
hbig = big(h)
s0::Float64 = 0.0
x = zeros(Float64,3)
v = zeros(Float64,3)
s::Float64 = 0.0
t = 0.0
ssave = zeros(2)
nsteps = 1
xsave=zeros(Float64,12,nsteps) # First is time (1,:); next three are position (2-4,:); next three velocity (5-7,:); then r (8,:), drdt (9,:); then beta (10,:); finally s & ds (11:12,:)
# Create a variable to store the state at the end of a step:
state=zeros(Float64,12)
state_diffbig=zeros(BigFloat,12)
xsave[1,1]=0.0
for jj=1:3
xsave[jj+1,1]=x0[jj]
xsave[jj+4,1]=v0[jj]
end
# Save beta:
xsave[8,1]=r0
beta0 = 2.0*k/r0-dot(v0,v0)
println("beta: ",beta0)
xsave[10,1]=beta0
jacobian=zeros(Float64,7,7)
#iter = kep_elliptic!(x0,v0,r0,k,h,beta0,s0,state,jacobian)
iter = kep_ell_hyp!(x0,v0,r0,k,h,beta0,s0,state,jacobian)
#println("Initial conditions: ",x0,v0)
#println("Final state: ",state)
#println("Differnce : ",state[2:4]-x0,state[5:7]-v0)
#read(STDIN,Char)
# Now, do finite differences at higher precision:
kbig = big(k); s0big = big(0.0); statebig = big.(state)
x0big = big.(x0); v0big = big.(v0)
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
#iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,statebig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,statebig)
#println("Final state: ",statebig[2:7])
#read(STDIN,Char)
#s = statebig[11]
# Now, compute the Jacobian numerically:
#jac_num = zeros(Float64,7,7)
jac_num = zeros(BigFloat,7,7)
#dlnq = 1e-4
# jac_num[i,j]: derivative of (x_i,v_i,k) with respect to (x_{0,j},v_{0,j},k):
for j=1:3
x0save = copy(x0big)
dq = dlnq * x0big[j]
if x0big[j] != 0.0
x0big[j] += dq
else
dq = dlnq
x0big[j] = dq
end
# Recompute quantities:
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
# iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
x0big = copy(x0save)
for i=1:3
jac_num[ i, j] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i, j] = (state_diffbig[4+i]-statebig[4+i])/dq
end
v0save = copy(v0big)
dq = dlnq * v0big[j]
if v0big[j] != 0.0
v0big[j] += dq
else
dq = dlnq
v0big[j] = dq
end
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
# iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
v0big = copy(v0save)
for i=1:3
jac_num[ i,3+j] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i,3+j] = (state_diffbig[4+i]-statebig[4+i])/dq
end
# Now vary mass:
ksave = copy(kbig)
dq = kbig*dlnq
kbig += dq
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
# iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
iter = kep_ell_hyp!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
for i=1:3
jac_num[ i,7] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i,7] = (state_diffbig[4+i]-statebig[4+i])/dq
end
kbig = copy(ksave)
jac_num[7, 7] = 1.0
end
return xsave,jac_num,jacobian
end
# First try:
const KEPLER_TOL = 1e-12
xsave,jac_num1,jacobian=test_elliptic_derivative(big(1e-15))
# Second try:
#xsave,jac_num2,jacobian=test_elliptic_derivative(1e-6)
#println("Jac dlnq=1e-7 ")
#jac_num1
#println("Jac dlnq=1e-6 ")
#jac_num2
#jacobian
#jac_num1-jac_num2
#println("Fraction errors on Jacobian: ",jac_num1./jacobian-1.0)
#println("jac_num1: ",jac_num1)
emax = 0.0; imax = 0; jmax = 0
for i=1:7, j=1:7
if jacobian[i,j] != 0.0
diff = abs(jac_num1[i,j]/jacobian[i,j]-1.0)
if diff > emax
emax = diff; imax = i; jmax = j
end
end
end
println("Maximum fractional error: ",emax," ",imax," ",jmax)
println("Maximum error jacobian: ",maximum(abs.(jacobian-jac_num1)))
#@test isapprox(jacobian,jac_num1)
@test isapprox(jacobian,jac_num1;norm=maxabs)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4402 | # This code tests two functions: keplerij! and kep_elliptic!
#using PyPlot
#include("../src/kepler_solver_derivative.jl")
#include("../src/ttv.jl")
@testset "kep_elliptic" begin
# Define a constant of 1/3:
#const third = 1.0/3.0
function test_elliptic_derivative(dlnq::BigFloat)
# Call as: save,jac_num,jacobian=test_elliptic_derivative(1e-4)
# This routine runs a test of the kep_elliptic_jacobian function in kepler_solver.jl
# Define the central force constant in terms of AU and days:
k = (2.0*pi/365.25)^2
# Initial position at 1 AU:
x0 = [0.01,1.0,0.01]
#r0 = norm(x0)
# Circular velocity:
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
vcirc = sqrt(k/r0)
# Define initial velocity at apastron:
v0 = [.9*vcirc,0.01*vcirc,0.01*vcirc] # The eccentricity is about ~2(1-v0/vcirc).
h = 100.0 # 18-day timesteps
hbig = big(h)
s0::Float64 = 0.0
x = zeros(Float64,3)
v = zeros(Float64,3)
s::Float64 = 0.0
t = 0.0
ssave = zeros(2)
nsteps = 1
xsave=zeros(Float64,12,nsteps) # First is time (1,:); next three are position (2-4,:); next three velocity (5-7,:); then r (8,:), drdt (9,:); then beta (10,:); finally s & ds (11:12,:)
# Create a variable to store the state at the end of a step:
state=zeros(Float64,12)
state_diffbig=zeros(BigFloat,12)
xsave[1,1]=0.0
for jj=1:3
xsave[jj+1,1]=x0[jj]
xsave[jj+4,1]=v0[jj]
end
# Save beta:
xsave[8,1]=r0
beta0 = 2.0*k/r0-dot(v0,v0)
xsave[10,1]=beta0
jacobian=zeros(Float64,7,7)
iter = kep_elliptic!(x0,v0,r0,k,h,beta0,s0,state,jacobian)
#println("Initial conditions: ",x0,v0)
# Now, do finite differences at higher precision:
kbig = big(k); s0big = big(0.0); statebig = big.(state)
x0big = big.(x0); v0big = big.(v0)
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,statebig)
#println("Final state: ",statebig[2:7])
#read(STDIN,Char)
#s = statebig[11]
# Now, compute the Jacobian numerically:
#jac_num = zeros(Float64,7,7)
jac_num = zeros(BigFloat,7,7)
#dlnq = 1e-4
# jac_num[i,j]: derivative of (x_i,v_i,k) with respect to (x_{0,j},v_{0,j},k):
for j=1:3
x0save = copy(x0big)
dq = dlnq * x0big[j]
if x0big[j] != 0.0
x0big[j] += dq
else
dq = dlnq
x0big[j] = dq
end
# Recompute quantities:
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
x0big = copy(x0save)
for i=1:3
jac_num[ i, j] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i, j] = (state_diffbig[4+i]-statebig[4+i])/dq
end
v0save = copy(v0big)
dq = dlnq * v0big[j]
if v0big[j] != 0.0
v0big[j] += dq
else
dq = dlnq
v0big[j] = dq
end
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
v0big = copy(v0save)
for i=1:3
jac_num[ i,3+j] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i,3+j] = (state_diffbig[4+i]-statebig[4+i])/dq
end
# Now vary mass:
ksave = copy(kbig)
dq = kbig*dlnq
kbig += dq
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
iter = kep_elliptic!(x0big,v0big,r0big,kbig,hbig,beta0big,s0big,state_diffbig)
for i=1:3
jac_num[ i,7] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i,7] = (state_diffbig[4+i]-statebig[4+i])/dq
end
kbig = copy(ksave)
jac_num[7, 7] = 1.0
end
return xsave,jac_num,jacobian
end
# First try:
const KEPLER_TOL = 1e-12
xsave,jac_num1,jacobian=test_elliptic_derivative(big(1e-15))
# Second try:
#xsave,jac_num2,jacobian=test_elliptic_derivative(1e-6)
#println("Jac dlnq=1e-7 ")
#jac_num1
#println("Jac dlnq=1e-6 ")
#jac_num2
#jacobian
#jac_num1-jac_num2
#println("Fraction errors on Jacobian: ",jac_num1./jacobian-1.0)
#println("jac_num1: ",jac_num1)
emax = 0.0; imax = 0; jmax = 0
for i=1:7, j=1:7
if jacobian[i,j] != 0.0
diff = abs(jac_num1[i,j]/jacobian[i,j]-1.0)
if diff > emax
emax = diff; imax = i; jmax = j
end
end
end
println("Maximum fractional error: ",emax," ",imax," ",jmax)
println("Maximum error jacobian: ",maximum(abs.(jacobian-jac_num1)))
#@test isapprox(jacobian,jac_num1)
@test isapprox(jacobian,jac_num1;norm=maxabs)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4311 | # This code tests kep_drift_ell_hyp!
@testset "kepler_drift" begin
function test_kepler_drift(dlnq::BigFloat,drift_first::Bool)
# Call as: save,jac_num,jacobian=test_kepler_drift(1e-4,true)
# This routine runs a test of the kep_elliptic_jacobian function in kepler_solver.jl
# Define the central force constant in terms of AU and days:
k = (2.0*pi/365.25)^2
# Initial position at 1 AU:
x0 = [0.01,1.0,0.01]
# Circular velocity:
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
vcirc = sqrt(k/r0)
# Define initial velocity at apastron:
v0 = [.9*vcirc,0.01*vcirc,0.01*vcirc] # The eccentricity is about ~2(1-v0/vcirc).
h = 18.0 # 18-day timesteps
hbig = big(h)
s0::Float64 = 0.0
x = zeros(Float64,3)
v = zeros(Float64,3)
s::Float64 = 0.0
t = 0.0
nsteps = 1
xsave=zeros(Float64,12,nsteps) # First is time (1,:); next three are position (2-4,:); next three velocity (5-7,:); then r (8,:), drdt (9,:); then beta (10,:); finally s & ds (11:12,:)
# Create a variable to store the state at the end of a step:
state=zeros(Float64,12)
state_diffbig=zeros(BigFloat,12)
xsave[1,1]=0.0
for jj=1:3
xsave[jj+1,1]=x0[jj]
xsave[jj+4,1]=v0[jj]
end
# Save beta:
xsave[8,1]=r0
beta0 = 2.0*k/r0-dot(v0,v0)
xsave[10,1]=beta0
jacobian=zeros(Float64,7,7)
d = Derivatives(Float64)
iter = kep_drift_ell_hyp!(x0,v0,k,h,s0,state,jacobian,drift_first,d)
# Now, do finite differences at higher precision:
kbig = big(k); s0big = big(0.0); statebig = big.(state)
x0big = big.(x0); v0big = big.(v0)
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
jacobian_big =zeros(BigFloat,7,7)
dBig = Derivatives(BigFloat)
iter = kep_drift_ell_hyp!(x0big,v0big,kbig,hbig,s0big,statebig,jacobian_big,drift_first,dBig)
jac_frac = jacobian./convert(Array{Float64,2},jacobian_big).-1.0
println("Fractional Jacobian difference: ",maxabs(jac_frac[.~isnan.(jac_frac)]))
# Now, compute the Jacobian numerically:
jac_num = zeros(BigFloat,7,7)
# jac_num[i,j]: derivative of (x_i,v_i,k) with respect to (x_{0,j},v_{0,j},k):
for j=1:3
x0save = copy(x0big)
dq = dlnq * x0big[j]
if x0big[j] != 0.0
x0big[j] += dq
else
dq = dlnq
x0big[j] = dq
end
# Recompute quantities:
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
iter = kep_drift_ell_hyp!(x0big,v0big,kbig,hbig,s0big,state_diffbig,drift_first)
x0big = copy(x0save)
for i=1:3
jac_num[ i, j] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i, j] = (state_diffbig[4+i]-statebig[4+i])/dq
end
v0save = copy(v0big)
dq = dlnq * v0big[j]
if v0big[j] != 0.0
v0big[j] += dq
else
dq = dlnq
v0big[j] = dq
end
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
iter = kep_drift_ell_hyp!(x0big,v0big,kbig,hbig,s0big,state_diffbig,drift_first)
v0big = copy(v0save)
for i=1:3
jac_num[ i,3+j] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i,3+j] = (state_diffbig[4+i]-statebig[4+i])/dq
end
# Now vary mass:
ksave = copy(kbig)
dq = kbig*dlnq
kbig += dq
r0big = sqrt(x0big[1]*x0big[1]+x0big[2]*x0big[2]+x0big[3]*x0big[3])
beta0big = 2*kbig/r0big-dot(v0big,v0big)
iter = kep_drift_ell_hyp!(x0big,v0big,kbig,hbig,s0big,state_diffbig,drift_first)
for i=1:3
jac_num[ i,7] = (state_diffbig[1+i]-statebig[1+i])/dq
jac_num[3+i,7] = (state_diffbig[4+i]-statebig[4+i])/dq
end
kbig = copy(ksave)
jac_num[7, 7] = 1.0
end
println("Maximum jac_big-jac_num: ",maxabs(convert(Array{Float64,2},jacobian_big-jac_num)))
#println(convert(Array{Float64,2},jacobian_big))
#println(convert(Array{Float64,2},jacobian_big./jac_num.-1.0))
return xsave,jac_num,jacobian
end
# First try:
xsave,jac_num1,jacobian=test_kepler_drift(big(1e-20),true)
# Second try:
xsave,jac_num1,jacobian=test_kepler_drift(big(1e-20),false)
emax = 0.0; imax = 0; jmax = 0
for i=1:7, j=1:7
if jacobian[i,j] != 0.0
diff = abs(convert(Float64,jac_num1[i,j])/jacobian[i,j]-1.0)
if diff > emax
emax = diff; imax = i; jmax = j
end
end
end
println("Maximum fractional error: ",emax," ",imax," ",jmax)
println("Maximum jacobian-jac_num: ",maxabs(jacobian-convert(Array{Float64,2},jac_num1)))
@test isapprox(jacobian,jac_num1;norm=maxabs)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 5686 |
# This code tests the autodiffed Drift/Kepler step
include("../src/kepler_drift_gamma.jl")
@testset "kepler_drift_gamma" begin
function test_kepler_drift(dlnq::BigFloat,drift_first::Bool)
# Call as: save,jac_num,jacobian=test_kepler_drift(1e-4,true)
# This routine runs a test of the kep_elliptic_jacobian function in kepler_solver.jl
# Define the central force constant in terms of AU and days:
k = (2.0*pi/365.25)^2
# Initial position at 1 AU:
x0 = [0.01,1.0,0.01]
# Circular velocity:
r0 = sqrt(x0[1]*x0[1]+x0[2]*x0[2]+x0[3]*x0[3])
vcirc = sqrt(k/r0)
# Define initial velocity at apastron:
v0 = [.9*vcirc,0.01*vcirc,0.01*vcirc] # The eccentricity is about ~2(1-v0/vcirc).
#h = 18.0 # 18-day timesteps
h = 0.000005 # 18-day timesteps
#h = 0.05 # 18-day timesteps
hbig = big(h)
s0::Float64 = 0.0
x = zeros(Float64,3)
v = zeros(Float64,3)
t = 0.0
nsteps = 1
xsave=zeros(Float64,12,nsteps) # First is time (1,:); next three are position (2-4,:); next three velocity (5-7,:); then r (8,:), drdt (9,:); then beta (10,:); finally s & ds (11:12,:)
# Create a variable to store the state at the end of a step:
state=zeros(Float64,12)
state_diffbig=zeros(BigFloat,12)
xsave[1,1]=0.0
for jj=1:3
xsave[jj+1,1]=x0[jj]
xsave[jj+4,1]=v0[jj]
end
# Save beta:
xsave[8,1]=r0
beta0 = 2.0*k/r0-dot(v0,v0)
xsave[10,1]=beta0
# First, compute it with the old version:
jacobian_old =zeros(Float64,7,7)
d_old = Derivatives(Float64)
iter = kep_drift_ell_hyp!(x0,v0,k,h,s0,state,jacobian_old,drift_first,d_old)
#println("s old: ",state[11])
# Check that old and new are giving the same answer:
delxv = jac_delxv_gamma!(x0,v0,k,h,drift_first;debug=true)
println("state: ",state)
println("delxv: ",delxv)
println("Old-new: ",state[2:7]-delxv[1:6])
# Now compute algebraic Jacobian:
delxv,jac_alg = jac_delxv_gamma!(x0,v0,k,h,drift_first;grad=true,auto=false,debug=true)
# Next, compute autodiff Jacobian:
delxv,jacobian = jac_delxv_gamma!(x0,v0,k,h,drift_first;grad=true,auto=true,debug=true)
# Now, do finite differences at higher precision:
kbig = big(k)
x0big = big.(x0); v0big = big.(v0)
# Now compute big-float precision autodiff Jacobian:
delxv_big,jacobian_big = jac_delxv_gamma!(x0big,v0big,kbig,hbig,drift_first;grad=true,auto=true,debug=true)
#println("Auto diff Jacobian: ",jacobian)
jac_frac = jac_alg[1:6,:]./convert(Array{Float64,2},jacobian_big[1:6,:]).-1.0
println("Fractional Jacobian difference: ",maxabs(jac_frac[.~isnan.(jac_frac)]))
# Now compute finite-difference Jacobian:
delxv,jac_num = jac_delxv_gamma!(x0big,v0big,kbig,hbig,drift_first;grad=true,auto=false,dlnq=dlnq,debug=true)
name = ["x01","x02","x03","v01","v02","v03","gamma","r","fm1","fdot","gmhgdot","gdotm1"]
for i=1:12
println(i," ",name[i])
println("Fini diff Jacobian: ",convert(Array{Float64,1},jac_num[i,:]))
println("Algebraic Jacobian: ",convert(Array{Float64,1},jac_alg[i,:]))
println("Auto diff Jacobian: ",convert(Array{Float64,1},jacobian_big[i,:]))
println("Frac diff Jacobian: ",jac_alg[i,:]./convert(Array{Float64,1},jacobian_big[i,:]).-1.0)
end
println("gamma alg gradient: ",jac_alg[7,:])
println("gamma auto gradient: ",convert(Array{Float64,1},jacobian_big[7,:]))
println("gamma diff gradient: ",convert(Array{Float64,1},jac_num[7,:]))
println("r alg gradient: ",jac_alg[8,:])
println("r auto gradient: ",convert(Array{Float64,1},jacobian_big[8,:]))
println("r diff gradient: ",convert(Array{Float64,1},jac_num[8,:]))
println("fm1 gradient alg: ",jac_alg[9,:])
println("fm1 gradient auto: ",convert(Array{Float64,1},jacobian_big[9,:]))
println("fm1 gradient diff: ",convert(Array{Float64,1},jac_num[9,:]))
println("fdot gradient alg: ",jac_alg[10,:])
println("fdot gradient auto: ",convert(Array{Float64,1},jacobian_big[10,:]))
println("fdot gradient diff: ",convert(Array{Float64,1},jac_num[10,:]))
println("g-h gdot gradient alg: ",jac_alg[11,:])
println("g-h gdot gradient auto: ",convert(Array{Float64,1},jacobian_big[11,:]))
println("g-h gdot gradient diff: ",convert(Array{Float64,1},jac_num[11,:]))
println("gdot-1 gradient alg: ",jac_alg[12,:])
println("gdot-1 gradient auto: ",convert(Array{Float64,1},jacobian_big[12,:]))
println("gdot-1 gradient diff: ",convert(Array{Float64,1},jac_num[12,:]))
println("Dim of jacobian_big: ",size(jacobian_big)," dim of jac_num: ",size(jac_num))
println("Maximum jac_big-jac_num: ",maxabs(convert(Array{Float64,2},jacobian_big-jac_num)))
println("Maximum jac_big-jac_alg: ",maxabs(convert(Array{Float64,2},jacobian_big-jac_alg)))
return xsave,jac_num,jac_alg
end
# First try:
xsave,jac_num1,jacobian=test_kepler_drift(big(1e-20),true)
emax = 0.0; imax = 0; jmax = 0
#for i=1:6, j=1:8
for i=1:12, j=1:8
if jacobian[i,j] != 0.0
diff = abs(convert(Float64,jac_num1[i,j])/jacobian[i,j]-1.0)
if diff > emax
emax = diff; imax = i; jmax = j
# println("i ",i," j ",j," jac_num1: ",convert(Float64,jac_num1[i,j])," jacobian: ",jacobian[i,j])
end
end
end
println("Maximum fractional error: ",emax," ",imax," ",jmax)
println("Maximum jacobian-jac_num: ",maxabs(jacobian-convert(Array{Float64,2},jac_num1)))
# Second try:
xsave,jac_num1,jacobian=test_kepler_drift(big(1e-20),false)
emax = 0.0; imax = 0; jmax = 0
for i=1:6, j=1:8
if jacobian[i,j] != 0.0
diff = abs(convert(Float64,jac_num1[i,j])/jacobian[i,j]-1.0)
if diff > emax
emax = diff; imax = i; jmax = j
# println("i ",i," j ",j," jac_num1: ",convert(Float64,jac_num1[i,j])," jacobian: ",jacobian[i,j])
end
end
end
println("Maximum fractional error: ",emax," ",imax," ",jmax)
println("Maximum jacobian-jac_num: ",maxabs(jacobian-convert(Array{Float64,2},jac_num1)))
@test isapprox(jacobian,jac_num1;norm=maxabs)
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 7548 | # This code tests the function kepler_driftij2
@testset "kepler_driftij" begin
for drift_first in [true,false]
# Next, try computing two-body Keplerian Jacobian:
n = 3
H = [3,1,1]
t0 = 7257.93115525
#t0 = -300.0
h = 0.0000005
hbig = big(h)
tmax = 600.0
#dlnq = 1e-8
dlnq = big(1e-20)
elements = readdlm("elements.txt",',')
#elements[2,1] = 0.75
elements[2,1] = 1.0
elements[3,1] = 1.0
m =zeros(n)
x0=zeros(NDIM,n)
v0=zeros(NDIM,n)
for k=1:n
m[k] = elements[k,1]
end
for iter = 1:2
init = ElementsIC(elements,H,t0)
x0,v0,_ = init_nbody(init)
if iter == 2
# Reduce masses to trigger hyperbolic routine:
m[1:n] *= 1e-1
h = 0.0000005
hbig = big(h)
end
# Tilt the orbits a bit:
x0[2,1] = 5e-1*sqrt(x0[1,1]^2+x0[3,1]^2)
x0[2,2] = -5e-1*sqrt(x0[1,2]^2+x0[3,2]^2)
v0[2,1] = 5e-1*sqrt(v0[1,1]^2+v0[3,1]^2)
v0[2,2] = -5e-1*sqrt(v0[1,2]^2+v0[3,2]^2)
jac_ij = zeros(Float64,14,14)
dqdt_ij = zeros(Float64,14)
dqdt_num = zeros(BigFloat,14)
println("Initial values: ",x0,v0)
println("masses: ",m)
i=1 ; j=2
x = copy(x0) ; v=copy(v0)
xerror = zeros(NDIM,n); verror = zeros(NDIM,n)
d = Derivatives(Float64)
# Predict values of s:
kepler_driftij!(m,x,v,xerror,verror,i,j,h,jac_ij,dqdt_ij,drift_first,d)
x0 = copy(x) ; v0 = copy(v)
xerror = zeros(NDIM,n); verror = zeros(NDIM,n)
xbig = big.(x) ; vbig=big.(v); mbig = big.(m)
xerr_big = zeros(BigFloat,NDIM,n); verr_big = zeros(BigFloat,NDIM,n)
kepler_driftij!(m,x,v,xerror,verror,i,j,h,jac_ij,dqdt_ij,drift_first,d)
# Now compute Jacobian with BigFloat precision:
jac_ij_big = zeros(BigFloat,14,14)
dqdt_ij_big = zeros(BigFloat,14)
KEPLER_TOL = sqrt(eps(big(1.0)))
dBig = Derivatives(BigFloat)
kepler_driftij!(mbig,xbig,vbig,xerr_big,verr_big,i,j,hbig,jac_ij_big,dqdt_ij_big,drift_first,dBig)
#println("jac_ij: ",convert(Array{Float64,2},jac_ij_big))
#println("jac_ij - jac_ij_big: ",convert(Array{Float64,2},jac_ij_big)-jac_ij)
println("max(jac_ij - jac_ij_big): ",maxabs(convert(Array{Float64,2},jac_ij_big)-jac_ij))
# Now, compute the derivatives numerically:
jac_ij_num = zeros(BigFloat,14,14)
xsave = big.(x)
vsave = big.(v)
msave = big.(m)
# Compute the time derivatives:
# Initial positions, velocities & masses:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * hbig
hbig -= dq
kepler_driftij!(mm,xm,vm,i,j,hbig,drift_first)
xp = big.(x0)
vp = big.(v0)
hbig += 2dq
kepler_driftij!(mm,xp,vp,i,j,hbig,drift_first)
# Now x & v are final positions & velocities after time step
for k=1:3
dqdt_num[ k] = .5*(xp[k,i]-xm[k,i])/dq
dqdt_num[ 3+k] = .5*(vp[k,i]-vm[k,i])/dq
dqdt_num[ 7+k] = .5*(xp[k,j]-xm[k,j])/dq
dqdt_num[10+k] = .5*(vp[k,j]-vm[k,j])/dq
end
hbig = big(h)
# Compute position, velocity & mass derivatives:
for jj=1:3
# Initial positions, velocities & masses:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * xm[jj,i]
if xm[jj,i] != 0.0
xm[jj,i] -= dq
else
dq = dlnq
xm[jj,i] = -dq
end
kepler_driftij!(mm,xm,vm,i,j,hbig,drift_first)
xp = big.(x0)
vp = big.(v0)
if xm[jj,i] != 0.0
xp[jj,i] += dq
else
dq = dlnq
xp[jj,i] = dq
end
kepler_driftij!(mm,xp,vp,i,j,hbig,drift_first)
# Now x & v are final positions & velocities after time step
for k=1:3
jac_ij_num[ k, jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k, jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k, jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k, jj] = .5*(vp[k,j]-vm[k,j])/dq
end
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * vm[jj,i]
if vm[jj,i] != 0.0
vm[jj,i] -= dq
else
dq = dlnq
vm[jj,i] = -dq
end
kepler_driftij!(mm,xm,vm,i,j,hbig,drift_first)
xp = big.(x0)
vp = big.(v0)
mm = big.(msave)
if vp[jj,i] != 0.0
vp[jj,i] += dq
else
dq = dlnq
vp[jj,i] = dq
end
kepler_driftij!(mm,xp,vp,i,j,hbig,drift_first)
for k=1:3
jac_ij_num[ k,3+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,3+jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,3+jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,3+jj] = .5*(vp[k,j]-vm[k,j])/dq
end
end
# Now vary mass of inner planet:
xm= big.(x0)
vm= big.(v0)
mm= big.(msave)
dq = mm[i]*dlnq
mm[i] -= dq
kepler_driftij!(mm,xm,vm,i,j,hbig,drift_first)
xp= big.(x0)
vp= big.(v0)
mp= big.(msave)
dq = mp[i]*dlnq
mp[i] += dq
kepler_driftij!(mp,xp,vp,i,j,hbig,drift_first)
for k=1:3
jac_ij_num[ k,7] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,7] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,7] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,7] = .5*(vp[k,j]-vm[k,j])/dq
end
# The mass doesn't change:
jac_ij_num[7,7] = 1.0
for jj=1:3
# Now vary parameters of outer planet:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * xm[jj,j]
if xm[jj,j] != 0.0
xm[jj,j] -= dq
else
dq = dlnq
xm[jj,j] = -dq
end
kepler_driftij!(mm,xm,vm,i,j,hbig,drift_first)
xp = big.(x0)
vp = big.(v0)
if xp[jj,j] != 0.0
xp[jj,j] += dq
else
dq = dlnq
xp[jj,j] = dq
end
kepler_driftij!(mm,xp,vp,i,j,hbig,drift_first)
for k=1:3
jac_ij_num[ k,7+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,7+jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,7+jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,7+jj] = .5*(vp[k,j]-vm[k,j])/dq
end
xm= big.(x0)
vm= big.(v0)
mm = big.(msave)
dq = dlnq * vm[jj,j]
if vm[jj,j] != 0.0
vm[jj,j] -= dq
else
dq = dlnq
vm[jj,j] = -dq
end
kepler_driftij!(mm,xm,vm,i,j,hbig,drift_first)
xp= big.(x0)
vp= big.(v0)
if vp[jj,j] != 0.0
vp[jj,j] += dq
else
dq = dlnq
vp[jj,j] = dq
end
kepler_driftij!(mm,xp,vp,i,j,hbig,drift_first)
for k=1:3
jac_ij_num[ k,10+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,10+jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,10+jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,10+jj] = .5*(vp[k,j]-vm[k,j])/dq
end
end
# Now vary mass of outer planet:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = mm[j]*dlnq
mm[j] -= dq
kepler_driftij!(mm,xm,vm,i,j,hbig,drift_first)
xp = big.(x0)
vp = big.(v0)
mp = big.(msave)
dq = mp[j]*dlnq
mp[j] += dq
kepler_driftij!(mp,xp,vp,i,j,hbig,drift_first)
for k=1:3
jac_ij_num[ k,14] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,14] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,14] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,14] = .5*(vp[k,j]-vm[k,j])/dq
end
# The mass doesn't change:
jac_ij_num[14,14] = 1.0
#println(jac_ij)
#println(jac_ij_num)
#println(jac_ij./jac_ij_num)
emax = 0.0; imax = 0; jmax = 0
emax_big = big(0.0); imax_big = 0; jmax_big = 0
for i=1:14
jac_ij[i,i] += 1
jac_ij_big[i,i] += 1
end
for i=1:14, j=1:14
if jac_ij[i,j] != 0.0
diff = abs(convert(Float64,jac_ij_num[i,j])/jac_ij[i,j]-1.0)
if diff > emax
emax = diff; imax = i; jmax = j
end
diff_big = abs(convert(Float64,jac_ij_num[i,j])/jac_ij_big[i,j]-1.0)
if diff_big > emax_big
emax_big = diff; imax_big = i; jmax_big = j
end
end
end
println("Maximum fractional error: ",emax," ",imax," ",jmax)
println("Maximum fractional error big: ",emax_big," ",imax_big," ",jmax_big)
#println(jac_ij)
#println(convert(Array{Float64,2},jac_ij_num))
println("Maximum jac_ij error: ",maxabs(convert(Array{Float64,2},asinh.(jac_ij_num))-asinh.(jac_ij)))
println("Maximum jac_ij_big-jac_ij_num: ",maxabs(convert(Array{Float64,2},asinh.(jac_ij_num)-asinh.(jac_ij_big))))
println("Max dqdt error: ",maxabs(dqdt_ij-convert(Array{Float64,1},dqdt_num)))
@test isapprox(jac_ij_num,jac_ij;norm=maxabs)
#@test isapprox(dqdt_ij,convert(Array{Float64,1},dqdt_num);norm=maxabs)
end
end
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 8892 | # This code tests the function kepler_driftij_gamma
import NbodyGradient: kepler_driftij_gamma!
@testset "kepler_driftij_gamma" begin
for drift_first in [true,false]
# Next, try computing two-body Keplerian Jacobian:
NDIM = 3
n = 3
H = [3,1,1]
t0 = 7257.93115525
#t0 = -300.0
#h = 0.0000005
#h = 0.05
h = 0.25
hbig = big(h)
tmax = 600.0
#dlnq = 1e-8
dlnq = big(1e-15)
elements = readdlm("elements.txt",',')
#elements[2,1] = 0.75
#elements[2,1] = 1.0
#elements[3,1] = 1.0
m =zeros(n)
x0=zeros(NDIM,n)
v0=zeros(NDIM,n)
for k=1:n
m[k] = elements[k,1]
end
for iter = 1:2
init = ElementsIC(t0,H,elements)
x0,v0,_ = init_nbody(init)
if iter == 2
# Reduce masses to trigger hyperbolic routine:
m[1:n] *= 1e-3
hbig = big(h)
end
# Tilt the orbits a bit:
x0[2,1] = 5e-1*sqrt(x0[1,1]^2+x0[3,1]^2)
x0[2,2] = -5e-1*sqrt(x0[1,2]^2+x0[3,2]^2)
v0[2,1] = 5e-1*sqrt(v0[1,1]^2+v0[3,1]^2)
v0[2,2] = -5e-1*sqrt(v0[1,2]^2+v0[3,2]^2)
jac_ij = zeros(Float64,14,14)
dqdt_ij = zeros(Float64,14)
dqdt_num = zeros(BigFloat,14)
#println("Initial values: ",x0,v0)
#println("masses: ",m)
i=1 ; j=2
x = copy(x0) ; v=copy(v0)
xerror = zeros(NDIM,n); verror = zeros(NDIM,n)
# Predict values of s:
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h,jac_ij,dqdt_ij,drift_first)
x0 = copy(x) ; v0 = copy(v)
xerror = zeros(NDIM,n); verror = zeros(NDIM,n)
xbig = big.(x) ; vbig=big.(v); mbig = big.(m)
xerr_big = zeros(BigFloat,NDIM,n); verr_big = zeros(BigFloat,NDIM,n)
kepler_driftij_gamma!(m,x,v,xerror,verror,i,j,h,jac_ij,dqdt_ij,drift_first)
# Now compute Jacobian with BigFloat precision:
jac_ij_big = zeros(BigFloat,14,14)
dqdt_ij_big = zeros(BigFloat,14)
KEPLER_TOL = sqrt(eps(big(1.0)))
kepler_driftij_gamma!(mbig,xbig,vbig,xerr_big,verr_big,i,j,hbig,jac_ij_big,dqdt_ij_big,drift_first)
#println("jac_ij: ",convert(Array{Float64,2},jac_ij_big))
#println("jac_ij - jac_ij_big: ",convert(Array{Float64,2},jac_ij_big)-jac_ij)
#println("max(jac_ij - jac_ij_big): ",maxabs(convert(Array{Float64,2},jac_ij_big)-jac_ij))
# Now, compute the derivatives numerically:
jac_ij_num = zeros(BigFloat,14,14)
xsave = big.(x)
vsave = big.(v)
msave = big.(m)
# Compute the time derivatives:
# Initial positions, velocities & masses:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * hbig
hbig -= dq
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xm,vm,xerr_big,verr_big,i,j,hbig,drift_first)
xp = big.(x0)
vp = big.(v0)
hbig += 2dq
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xp,vp,xerr_big,verr_big,i,j,hbig,drift_first)
# Now x & v are final positions & velocities after time step
for k=1:3
dqdt_num[ k] = .5*(xp[k,i]-xm[k,i])/dq
dqdt_num[ 3+k] = .5*(vp[k,i]-vm[k,i])/dq
dqdt_num[ 7+k] = .5*(xp[k,j]-xm[k,j])/dq
dqdt_num[10+k] = .5*(vp[k,j]-vm[k,j])/dq
end
hbig = big(h)
# Compute position, velocity & mass derivatives:
for jj=1:3
# Initial positions, velocities & masses:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * xm[jj,i]
if xm[jj,i] != 0.0
xm[jj,i] -= dq
else
dq = dlnq
xm[jj,i] = -dq
end
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xm,vm,xerr_big,verr_big,i,j,hbig,drift_first)
xp = big.(x0)
vp = big.(v0)
if xm[jj,i] != 0.0
xp[jj,i] += dq
else
dq = dlnq
xp[jj,i] = dq
end
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xp,vp,xerr_big,verr_big,i,j,hbig,drift_first)
# Now x & v are final positions & velocities after time step
for k=1:3
jac_ij_num[ k, jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k, jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k, jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k, jj] = .5*(vp[k,j]-vm[k,j])/dq
end
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * vm[jj,i]
if vm[jj,i] != 0.0
vm[jj,i] -= dq
else
dq = dlnq
vm[jj,i] = -dq
end
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xm,vm,xerr_big,verr_big,i,j,hbig,drift_first)
xp = big.(x0)
vp = big.(v0)
mm = big.(msave)
if vp[jj,i] != 0.0
vp[jj,i] += dq
else
dq = dlnq
vp[jj,i] = dq
end
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xp,vp,xerr_big,verr_big,i,j,hbig,drift_first)
for k=1:3
jac_ij_num[ k,3+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,3+jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,3+jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,3+jj] = .5*(vp[k,j]-vm[k,j])/dq
end
end
# Now vary mass of inner planet:
xm= big.(x0)
vm= big.(v0)
mm= big.(msave)
dq = mm[i]*dlnq
mm[i] -= dq
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xm,vm,xerr_big,verr_big,i,j,hbig,drift_first)
xp= big.(x0)
vp= big.(v0)
mp= big.(msave)
dq = mp[i]*dlnq
mp[i] += dq
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mp,xp,vp,xerr_big,verr_big,i,j,hbig,drift_first)
for k=1:3
jac_ij_num[ k,7] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,7] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,7] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,7] = .5*(vp[k,j]-vm[k,j])/dq
end
# The mass doesn't change:
jac_ij_num[7,7] = 1.0
for jj=1:3
# Now vary parameters of outer planet:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * xm[jj,j]
if xm[jj,j] != 0.0
xm[jj,j] -= dq
else
dq = dlnq
xm[jj,j] = -dq
end
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xm,vm,xerr_big,verr_big,i,j,hbig,drift_first)
xp = big.(x0)
vp = big.(v0)
if xp[jj,j] != 0.0
xp[jj,j] += dq
else
dq = dlnq
xp[jj,j] = dq
end
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xp,vp,xerr_big,verr_big,i,j,hbig,drift_first)
for k=1:3
jac_ij_num[ k,7+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,7+jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,7+jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,7+jj] = .5*(vp[k,j]-vm[k,j])/dq
end
xm= big.(x0)
vm= big.(v0)
mm = big.(msave)
dq = dlnq * vm[jj,j]
if vm[jj,j] != 0.0
vm[jj,j] -= dq
else
dq = dlnq
vm[jj,j] = -dq
end
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xm,vm,xerr_big,verr_big,i,j,hbig,drift_first)
xp= big.(x0)
vp= big.(v0)
if vp[jj,j] != 0.0
vp[jj,j] += dq
else
dq = dlnq
vp[jj,j] = dq
end
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xp,vp,xerr_big,verr_big,i,j,hbig,drift_first)
for k=1:3
jac_ij_num[ k,10+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,10+jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,10+jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,10+jj] = .5*(vp[k,j]-vm[k,j])/dq
end
end
# Now vary mass of outer planet:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = mm[j]*dlnq
mm[j] -= dq
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mm,xm,vm,xerr_big,verr_big,i,j,hbig,drift_first)
xp = big.(x0)
vp = big.(v0)
mp = big.(msave)
dq = mp[j]*dlnq
mp[j] += dq
fill!(xerr_big,0.0) ; fill!(verr_big,0.0)
kepler_driftij_gamma!(mp,xp,vp,xerr_big,verr_big,i,j,hbig,drift_first)
for k=1:3
jac_ij_num[ k,14] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,14] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,14] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,14] = .5*(vp[k,j]-vm[k,j])/dq
end
# The mass doesn't change:
jac_ij_num[14,14] = 1.0
#println(jac_ij)
#println(jac_ij_num)
#println(jac_ij./jac_ij_num)
emax = 0.0; imax = 0; jmax = 0
emax_big = big(0.0); imax_big = 0; jmax_big = 0
for i=1:14
jac_ij[i,i] += 1
jac_ij_big[i,i] += 1
end
for i=1:14, j=1:14
if jac_ij[i,j] != 0.0
diff = abs(convert(Float64,jac_ij_num[i,j])/jac_ij[i,j]-1.0)
if diff > emax
emax = diff; imax = i; jmax = j
end
diff_big = abs(convert(Float64,jac_ij_num[i,j])/jac_ij_big[i,j]-1.0)
if diff_big > emax_big
emax_big = diff; imax_big = i; jmax_big = j
end
end
end
# Dont need for CI
#=println("Maximum fractional error: ",emax," ",imax," ",jmax)
for i=1:14
println("jac_ij: i ",i," ",jac_ij[i,:])
println("jac_ij_num: i ",i," ",convert(Array{Float64,1},jac_ij_num[i,:]))
println("difference: i ",i," ",jac_ij[i,:].-convert(Array{Float64,1},jac_ij_num[i,:]))
if i != 7 && i != 14
println("frac diff : i ",i," ",jac_ij[i,:]./convert(Array{Float64,1},jac_ij_num[i,:]).-1.0)
end
end
println("Maximum fractional error big: ",emax_big," ",imax_big," ",jmax_big)
#println(jac_ij)
#println(convert(Array{Float64,2},jac_ij_num))
println("Maximum jac_ij error: ",maxabs(convert(Array{Float64,2},asinh.(jac_ij_num))-asinh.(jac_ij)))
println("Maximum jac_ij_big-jac_ij_num: ",maxabs(convert(Array{Float64,2},asinh.(jac_ij_num)-asinh.(jac_ij_big))))
println("Max dqdt error: ",maxabs(dqdt_ij-convert(Array{Float64,1},dqdt_num)))
=#
@test isapprox(jac_ij_num,jac_ij;norm=maxabs)
@test isapprox(dqdt_ij,convert(Array{Float64,1},dqdt_num);norm=maxabs)
end
end
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 7114 | # This code tests two functions: keplerij! and kep_elliptic!
#using PyPlot
#include("../src/kepler_solver_derivative.jl")
#include("../src/ttv.jl")
@testset "keplerij" begin
# Next, try computing two-body Keplerian Jacobian:
n = 3
t0 = 7257.93115525
h = 0.05
hbig = big(h)
tmax = 600.0
#dlnq = 1e-8
dlnq = 1e-20
H = [3,1,1]
elements = readdlm("elements.txt",',')
#elements[2,1] = 0.75
elements[2,1] = 1.0
elements[3,1] = 1.0
m =zeros(n)
x0=zeros(NDIM,n)
v0=zeros(NDIM,n)
for k=1:n
m[k] = elements[k,1]
end
for iter = 1:2
init = ElementsIC(elements,H,t0)
x0,v0,_ = init_nbody(init)
if iter == 2
# Reduce masses to trigger hyperbolic routine:
m[1:n] *= 1e-1
h = 0.05
hbig = big(h)
end
# Tilt the orbits a bit:
x0[2,1] = 5e-1*sqrt(x0[1,1]^2+x0[3,1]^2)
x0[2,2] = -5e-1*sqrt(x0[1,2]^2+x0[3,2]^2)
v0[2,1] = 5e-1*sqrt(v0[1,1]^2+v0[3,1]^2)
v0[2,2] = -5e-1*sqrt(v0[1,2]^2+v0[3,2]^2)
jac_ij = zeros(Float64,14,14)
dqdt_ij = zeros(Float64,14)
dqdt_num = zeros(BigFloat,14)
i=1 ; j=2
x = copy(x0) ; v=copy(v0)
# Predict values of s:
#println("Before first step: ",x," ",v)
xerror = zeros(NDIM,n); verror = zeros(NDIM,n)
d = Derivatives(Float64)
keplerij!(m,x,v,xerror,verror,i,j,h,jac_ij,dqdt_ij,d)
#println("After first step: ",x," ",v)
x0 = copy(x) ; v0 = copy(v)
xbig = big.(x) ; vbig=big.(v); mbig = big.(m)
xerr_big = zeros(BigFloat,NDIM,n) ; verr_big= zeros(BigFloat,NDIM,n)
xerror = zeros(NDIM,n); verror = zeros(NDIM,n)
keplerij!(m,x,v,xerror,verror,i,j,h,jac_ij,dqdt_ij,d)
# Now compute Jacobian with BigFloat precision:
jac_ij_big = zeros(BigFloat,14,14)
dqdt_ij_big = zeros(BigFloat,14)
KEPLER_TOL = sqrt(eps(big(1.0)))
dBig = Derivatives(BigFloat)
keplerij!(mbig,xbig,vbig,xerr_big,verr_big,i,j,hbig,jac_ij_big,dqdt_ij_big,dBig)
#println("jac_ij: ",convert(Array{Float64,2},jac_ij_big))
#println("jac_ij - jac_ij_big: ",convert(Array{Float64,2},jac_ij_big)-jac_ij)
println("max(jac_ij - jac_ij_big): ",maxabs(convert(Array{Float64,2},jac_ij_big)-jac_ij))
# xtest = copy(x0) ; vtest=copy(v0)
# keplerij!(m,xtest,vtest,i,j,h,jac_ij)
# println("Test of jacobian vs. none: ",maximum(abs(x-xtest)),maximum(abs(v-vtest)))
# Now, compute the derivatives numerically:
jac_ij_num = zeros(BigFloat,14,14)
xsave = big.(x)
vsave = big.(v)
msave = big.(m)
# Compute the time derivatives:
# Initial positions, velocities & masses:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * hbig
hbig -= dq
keplerij!(mm,xm,vm,i,j,hbig)
xp = big.(x0)
vp = big.(v0)
hbig += 2dq
keplerij!(mm,xp,vp,i,j,hbig)
# Now x & v are final positions & velocities after time step
for k=1:3
dqdt_num[ k] = .5*(xp[k,i]-xm[k,i])/dq
dqdt_num[ 3+k] = .5*(vp[k,i]-vm[k,i])/dq
dqdt_num[ 7+k] = .5*(xp[k,j]-xm[k,j])/dq
dqdt_num[10+k] = .5*(vp[k,j]-vm[k,j])/dq
end
hbig = big(h)
for jj=1:3
# Initial positions, velocities & masses:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * xm[jj,i]
if xm[jj,i] != 0.0
xm[jj,i] -= dq
else
dq = dlnq
xm[jj,i] = -dq
end
keplerij!(mm,xm,vm,i,j,hbig)
xp = big.(x0)
vp = big.(v0)
if xm[jj,i] != 0.0
xp[jj,i] += dq
else
dq = dlnq
xp[jj,i] = dq
end
keplerij!(mm,xp,vp,i,j,hbig)
# now x & v are final positions & velocities after time step
for k=1:3
jac_ij_num[ k, jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k, jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k, jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k, jj] = .5*(vp[k,j]-vm[k,j])/dq
end
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * vm[jj,i]
if vm[jj,i] != 0.0
vm[jj,i] -= dq
else
dq = dlnq
vm[jj,i] = -dq
end
keplerij!(mm,xm,vm,i,j,hbig)
xp = big.(x0)
vp = big.(v0)
mm = big.(msave)
if vp[jj,i] != 0.0
vp[jj,i] += dq
else
dq = dlnq
vp[jj,i] = dq
end
keplerij!(mm,xp,vp,i,j,hbig)
for k=1:3
jac_ij_num[ k,3+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,3+jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,3+jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,3+jj] = .5*(vp[k,j]-vm[k,j])/dq
end
end
# Now vary mass of inner planet:
xm= big.(x0)
vm= big.(v0)
mm= big.(msave)
dq = mm[i]*dlnq
mm[i] -= dq
keplerij!(mm,xm,vm,i,j,hbig)
xp= big.(x0)
vp= big.(v0)
mp= big.(msave)
dq = mp[i]*dlnq
mp[i] += dq
keplerij!(mp,xp,vp,i,j,hbig)
for k=1:3
jac_ij_num[ k,7] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,7] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,7] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,7] = .5*(vp[k,j]-vm[k,j])/dq
end
# The mass doesn't change:
jac_ij_num[7,7] = 1.0
for jj=1:3
# Now vary parameters of outer planet:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = dlnq * xm[jj,j]
if xm[jj,j] != 0.0
xm[jj,j] -= dq
else
dq = dlnq
xm[jj,j] = -dq
end
keplerij!(mm,xm,vm,i,j,hbig)
xp = big.(x0)
vp = big.(v0)
if xp[jj,j] != 0.0
xp[jj,j] += dq
else
dq = dlnq
xp[jj,j] = dq
end
keplerij!(mm,xp,vp,i,j,hbig)
for k=1:3
jac_ij_num[ k,7+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,7+jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,7+jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,7+jj] = .5*(vp[k,j]-vm[k,j])/dq
end
xm= big.(x0)
vm= big.(v0)
mm = big.(msave)
dq = dlnq * vm[jj,j]
if vm[jj,j] != 0.0
vm[jj,j] -= dq
else
dq = dlnq
vm[jj,j] = -dq
end
keplerij!(mm,xm,vm,i,j,hbig)
xp= big.(x0)
vp= big.(v0)
if vp[jj,j] != 0.0
vp[jj,j] += dq
else
dq = dlnq
vp[jj,j] = dq
end
keplerij!(mm,xp,vp,i,j,hbig)
for k=1:3
jac_ij_num[ k,10+jj] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,10+jj] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,10+jj] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,10+jj] = .5*(vp[k,j]-vm[k,j])/dq
end
end
# Now vary mass of outer planet:
xm = big.(x0)
vm = big.(v0)
mm = big.(msave)
dq = mm[j]*dlnq
mm[j] -= dq
keplerij!(mm,xm,vm,i,j,hbig)
xp = big.(x0)
vp = big.(v0)
mp = big.(msave)
dq = mp[j]*dlnq
mp[j] += dq
keplerij!(mp,xp,vp,i,j,hbig)
for k=1:3
jac_ij_num[ k,14] = .5*(xp[k,i]-xm[k,i])/dq
jac_ij_num[ 3+k,14] = .5*(vp[k,i]-vm[k,i])/dq
jac_ij_num[ 7+k,14] = .5*(xp[k,j]-xm[k,j])/dq
jac_ij_num[10+k,14] = .5*(vp[k,j]-vm[k,j])/dq
end
# The mass doesn't change:
jac_ij_num[14,14] = 1.0
#println(jac_ij)
#println(jac_ij_num)
#println(jac_ij./jac_ij_num)
emax = 0.0; imax = 0; jmax = 0
for i=1:14, j=1:14
if jac_ij[i,j] != 0.0
diff = abs(convert(Float64,jac_ij_num[i,j])/jac_ij[i,j]-1.0)
if diff > emax
emax = diff; imax = i; jmax = j
end
end
end
println("Maximum fractional error: ",emax," ",imax," ",jmax)
#println(jac_ij)
#println(convert(Array{Float64,2},jac_ij_num))
println("Maximum jac_ij error: ",maxabs(convert(Array{Float64,2},jac_ij_num)-jac_ij))
println("Maximum jac_ij_big-jac_ij_num: ",maxabs(convert(Array{Float64,2},jac_ij_num-jac_ij_big)))
println("Max dqdt error: ",maxabs(dqdt_ij-convert(Array{Float64,1},dqdt_num)))
@test isapprox(jac_ij_num,jac_ij;norm=maxabs)
@test isapprox(dqdt_ij,convert(Array{Float64,1},dqdt_num);norm=maxabs)
#println("dqdt: ",dqdt_ij," ",dqdt_num," Max error: ",maximum(dqdt_ij-dqdt_num))
end
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4438 | # Tests the routine phic jacobian. This routine
# computes the force gradient correction after Dehnen & Hernandez (2017).
# Next, try computing three-body Keplerian Jacobian:
#@testset "phic" begin
n = 3
t0 = 7257.93115525
h = 0.05
tmax = 600.0
dlnq = big(1e-15)
elements = readdlm("elements.txt",',')
elements[2,1] = 1.0
elements[3,1] = 1.0
m =zeros(n)
x0=zeros(3,n)
v0=zeros(3,n)
# Define which pairs will have impulse rather than -drift+Kepler:
pair = ones(Bool,n,n)
# We want Keplerian between star & planets, and impulses between
# planets. Impulse is indicated with 'true', -drift+Kepler with 'false':
for i=2:n
pair[1,i] = false
# We don't need to define this, but let's anyways:
pair[i,1] = false
end
println("pair: ",pair)
jac_step = zeros(7*n,7*n)
for k=1:n
m[k] = elements[k,1]
end
m0 = copy(m)
x0,v0 = init_nbody(elements,t0,n)
# Tilt the orbits a bit:
x0[2,1] = 5e-1*sqrt(x0[1,1]^2+x0[3,1]^2)
x0[2,2] = -5e-1*sqrt(x0[1,2]^2+x0[3,2]^2)
x0[2,3] = -5e-1*sqrt(x0[1,2]^2+x0[3,2]^2)
v0[2,1] = 5e-1*sqrt(v0[1,1]^2+v0[3,1]^2)
v0[2,2] = -5e-1*sqrt(v0[1,2]^2+v0[3,2]^2)
v0[2,3] = -5e-1*sqrt(v0[1,2]^2+v0[3,2]^2)
# Take a step:
dh17!(x0,v0,h,m,n,pair)
# Now, copy these to compute Jacobian (so that I don't step
# x0 & v0 forward in time):
x = copy(x0); v = copy(v0); m = copy(m0)
# Compute jacobian exactly:
phic!(x,v,h,m,n,jac_step,pair)
# Now compute numerical derivatives, using BigFloat to avoid
# round-off errors:
jac_step_num = zeros(BigFloat,7*n,7*n)
# Save these so that I can compute derivatives numerically:
xsave = big.(x0)
vsave = big.(v0)
msave = big.(m0)
hbig = big(h)
# Carry out step using BigFloat for extra precision:
phic!(xsave,vsave,hbig,msave,n,pair)
xbig = big.(x0)
vbig = big.(v0)
mbig = big.(m0)
# Vary time:
phic!(xbig,vbig,hbig,mbig,n,pair)
# Initial positions, velocities & masses:
xbig .= big.(x0)
vbig .= big.(v0)
mbig .= big.(m0)
hbig = big(h)
dq = dlnq * hbig
hbig += dq
phic!(xbig,vbig,hbig,mbig,n,pair)
# Now x & v are final positions & velocities after time step
hbig = big(h)
# Vary the initial parameters of planet j:
for j=1:n
# Vary the initial phase-space elements:
for jj=1:3
# Initial positions, velocities & masses:
xbig .= big.(x0)
vbig .= big.(v0)
mbig .= big.(m0)
dq = dlnq * xbig[jj,j]
if xbig[jj,j] != 0.0
xbig[jj,j] += dq
else
dq = dlnq
xbig[jj,j] = dq
end
phic!(xbig,vbig,hbig,mbig,n,pair)
# Now x & v are final positions & velocities after time step
for i=1:n
for k=1:3
jac_step_num[(i-1)*7+ k,(j-1)*7+jj] = (xbig[k,i]-xsave[k,i])/dq
jac_step_num[(i-1)*7+3+k,(j-1)*7+jj] = (vbig[k,i]-vsave[k,i])/dq
end
end
xbig .= big.(x0)
vbig .= big.(v0)
mbig .= big.(m0)
dq = dlnq * vbig[jj,j]
if vbig[jj,j] != 0.0
vbig[jj,j] += dq
else
dq = dlnq
vbig[jj,j] = dq
end
phic!(xbig,vbig,hbig,mbig,n,pair)
for i=1:n
for k=1:3
jac_step_num[(i-1)*7+ k,(j-1)*7+3+jj] = (xbig[k,i]-xsave[k,i])/dq
jac_step_num[(i-1)*7+3+k,(j-1)*7+3+jj] = (vbig[k,i]-vsave[k,i])/dq
end
end
end
# Now vary mass of planet:
xbig .= big.(x0)
vbig .= big.(v0)
mbig .= big.(m0)
dq = mbig[j]*dlnq
mbig[j] += dq
phic!(xbig,vbig,hbig,mbig,n,pair)
for i=1:n
for k=1:3
jac_step_num[(i-1)*7+ k,j*7] = (xbig[k,i]-xsave[k,i])/dq
jac_step_num[(i-1)*7+3+k,j*7] = (vbig[k,i]-vsave[k,i])/dq
end
# Mass unchanged -> identity
jac_step_num[7*i,7*i] = big(1.0)
end
end
# Now, compare the results:
#println(jac_step)
#println(convert(Array{Float64,2},jac_step_num))
#for j=1:3
# for i=1:7
# for k=1:3
# println(jac_step[(j-1)*7+i,(k-1)*7+1:7*k]," ",jac_step_num[(j-1)*7+i,(k-1)*7+1:7*k]," ",jac_step_num[(j-1)*7+i,(k-1)*7+1:7*k]./jac_step[(j-1)*7+i,(k-1)*7+1:7*k]-1.)
# end
# end
#end
jacmax = 0.0
for i=1:7, j=1:3, k=1:7, l=1:3
if jac_step[(j-1)*7+i,(l-1)*7+k] != 0
# Compute the fractional error and absolute error, and take the minimum of the two:
diff = minimum([abs(float(jac_step_num[(j-1)*7+i,(l-1)*7+k])/jac_step[(j-1)*7+i,(l-1)*7+k]-1.0);float(jac_step_num[(j-1)*7+i,(l-1)*7+k])-jac_step[(j-1)*7+i,(l-1)*7+k]])
if diff > jacmax
jacmax = diff
end
end
end
println(jac_step)
println(convert(Array{Float64,2},jac_step_num))
println("Maximum jac_step phic error: ",convert(Float64,jacmax))
@test isapprox(jac_step,jac_step_num;norm=maxabs)
#end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 1001 |
using PyPlot
# Tests different ways of keeping track of time.
# Looks like multiplication is just as accurate as
# compensated summation, yet is much faster. Not
# that this is a limiting factor.
function test_time(nt)
#nt = 10000000
T = Float64
s2 = zero(T)
h = 0.04
hbig = big(h)
t = zeros(T,nt)
tb = zeros(BigFloat,nt)
tc = zeros(T,nt)
tm = zeros(T,nt)
for i=2:nt
tc[i],s2 = comp_sum(tc[i-1],s2,h)
t[i] = t[i-1] + h
tm[i] = (i-1)*h
tb[i] = tb[i-1] + hbig
end
# Add compensated error at the end:
println("Compensated: ",tc[nt]," big: ",tb[nt]," diff: ",tc[nt]-tb[nt]," diff+err: ",big(tc[nt])+big(s2)-tb[nt])
#tref = convert(Array{Float64,1},tb)
#semilogy(abs.(t-tref),label="Added")
println("Maximum difference added: ",maximum(abs.(t-tref)))
#plot(abs.(tc-tref),":",label="Compensated")
println("Maximum difference compensated: ",maximum(abs.(tc-tref)))
#plot(abs.(tm-tref),"--",label="Multiplied")
println("Maximum difference multiplied: ",maximum(abs.(tm-tref)))
#legend()
return
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 2157 |
include("../src/ttv.jl")
include("/Users/ericagol/Computer/Julia/regress.jl")
n = 8
t0 = 7257.93115525
#h = 0.12
#h = 0.075
h = 0.05
tmax = 600.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
ntt = zeros(Int64,n)
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+2
end
println("ntt: ",ntt)
tt1 = zeros(n,maximum(ntt))
tt2 = zeros(n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count1 = zeros(Int64,n)
# Call the ttv function:
rstar = 1e12
@time ttv_elements!(n,t0,h,tmax,elements,tt1,count1,0.0,0,0,rstar)
@time ttv_elements!(n,t0,h,tmax,elements,tt1,count1,0.0,0,0,rstar)
# Write out every 10th step to a file:
@time ttv_elements!(n,t0,h,tmax,elements,tt1,count1,0.0,0,0,rstar,"test_out.txt",10)
# Now call with half the timestep:
count2 = zeros(Int64,n)
ttv_elements!(n,t0,h/10.,tmax,elements,tt2,count2,0.0,0,0,rstar)
println("Timing error: ",maximum(abs.(tt1-tt2))*24.*3600.," sec")
# Check type stabilty:
dtdq0 = zeros(n,maximum(ntt),7,n)
dtdelements0 = @code_warntype ttv_elements!(n,t0,h,tmax,elements,tt1,count1,dtdq0,rstar)
using PyPlot
# Make a plot of some TTVs:
fig,axes = subplots(4,2)
for i=2:8
ax = axes[i-1]
fn = zeros(Float64,2,count1[i])
sig = ones(count1[i])
tti1 = tt1[i,1:count1[i]]
tti2 = tt2[i,1:count2[i]]
for j=1:count1[i]
fn[1,j] = 1.0
fn[2,j] = round(Int64,(tti1[j]-elements[i,3])/elements[i,2])
end
coeff,cov = regress(fn,tti1,sig)
tt_ref1 = coeff[1]+coeff[2]*fn[2,:]
ttv1 = (tti1-tt_ref1)*24.*60.
# coeff,cov = regress(fn,tti2,sig)
tt_ref2 = coeff[1]+coeff[2]*fn[2,:]
ttv2 = (tti2-tt_ref2)*24.*60.
ax[:plot](tti1,ttv1)
ax[:plot](tti2,ttv2)
# ax[:plot](tti2,((ttv1-ttv2)-mean(ttv1-ttv2)))
ax[:plot](tti2,ttv1-ttv2)
println(i," ",coeff," ",elements[i,2:3]," ",coeff[1]-elements[i,3]," ",coeff[2]-elements[i,2])
# println(i," ",maximum(ttv1-ttv2-mean(ttv1-ttv2))*60.," sec ", minimum(ttv1-ttv2-mean(ttv1-ttv2))*60.," sec" )
println(i," ",maximum(ttv1-ttv2)*60.," sec ", minimum(ttv1-ttv2)*60.," sec")
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 7285 | #include("../src/ttv.jl")
#include("/Users/ericagol/Computer/Julia/regress.jl")
@testset "ttv_cartesian" begin
# This routine takes derivative of transit times with respect
# to the initial cartesian coordinates of bodies. [x]
#n = 8
n = 3
H = [3,1,1]
t0 = 7257.93115525-7300.0
#h = 0.12
h = 0.04
#h = 0.02
#tmax = 600.0
#tmax = 1000.0
#tmax = 100.0
tmax = 10.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
elements[:,3] .-= 7300.0
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
ntt = zeros(Int64,n)
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
#println("ntt: ",ntt)
tt = zeros(n,maximum(ntt))
tt1 = zeros(n,maximum(ntt))
tt2 = zeros(n,maximum(ntt))
tt3 = zeros(n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
count1 = zeros(Int64,n)
# Call the ttv function:
rstar = 1e12
#dq = ttv_elements!(H,t0,h,tmax,elements,tt1,count1,0.0,0,0,rstar)
# Now call with half the timestep:
count2 = zeros(Int64,n)
count3 = zeros(Int64,n)
dq = ttv_elements!(H,t0,h/2,tmax,elements,tt2,count2,0.0,0,0,rstar)
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtdq0 = zeros(n,maximum(ntt),7,n)
dtdelements = ttv_elements!(H,t0,h,tmax,elements,tt,count,dtdq0,rstar)
#read(STDIN,Char)
# Check that this is working properly:
for i=1:n
for j=1:count2[i]
# println(i," ",j," ",tt[i,j]," ",tt2[i,j]," ",tt[i,j]-tt2[i,j]," ",tt1[i,j]-tt2[i,j])
end
end
#read(STDIN,Char)
# Compute derivatives numerically:
# Compute the numerical derivative:
dtdq0_num = zeros(BigFloat,n,maximum(ntt),7,n)
itdq0 = zeros(Int64,n,maximum(ntt),7,n)
dlnq = big(1e-15)
hbig = big(h); t0big = big(t0); tmaxbig=big(tmax); tt2big = big.(tt2); tt3big = big.(tt3)
for jq=1:n
for iq=1:7
elements2 = big.(elements)
dq_plus = ttv_elements!(H,t0big,hbig,tmaxbig,elements2,tt2big,count2,dlnq,iq,jq,big(rstar))
elements3 = big.(elements)
dq_minus = ttv_elements!(H,t0big,hbig,tmaxbig,elements3,tt3big,count3,-dlnq,iq,jq,big(rstar))
for i=1:n
for k=1:count2[i]
# Compute double-sided derivative for more accuracy:
dtdq0_num[i,k,iq,jq] = (tt2big[i,k]-tt3big[i,k])/(dq_plus-dq_minus)
# println(i," ",k," ",iq," ",jq," ",tt2big[i,k]," ",tt3big[i,k]," ")
end
end
end
end
nbad = 0
ntot = 0
diff_dtdq0 = zeros(n,maximum(ntt),7,n)
mask = zeros(Bool, size(dtdq0))
for i=2:n, j=1:count[i], k=1:7, l=1:n
if abs(dtdq0[i,j,k,l]-dtdq0_num[i,j,k,l]) > 0.1*abs(dtdq0[i,j,k,l]) && ~(abs(dtdq0[i,j,k,l]) == 0.0 && abs(dtdq0_num[i,j,k,l]) < 1e-3)
# println(i," ",j," ",k," ",l," ",dtdq0[i,j,k,l]," ",dtdq0_num[i,j,k,l]," ",itdq0[i,j,k,l])
nbad +=1
end
diff_dtdq0[i,j,k,l] = abs(dtdq0[i,j,k,l]-dtdq0_num[i,j,k,l])
if k != 2 && k != 5
mask[i,j,k,l] = true
end
ntot +=1
end
tt_big = big.(tt); elementsbig = big.(elements); rstarbig = big(rstar)
dqbig = ttv_elements!(H,t0big,hbig,tmaxbig,elementsbig,tt_big,count,big(0.0),0,0,rstarbig)
# Now halve the time steps:
tt_big_half = copy(tt_big)
dqbig = ttv_elements!(H,t0big,hbig/2,tmaxbig,elementsbig,tt_big_half,count1,big(0.0),0,0,rstarbig)
# Compute the derivatives in BigFloat precision to see whether finite difference
# derivatives or Float64 derivatives are imprecise at the start:
dtdq0_big = zeros(BigFloat,n,maximum(ntt),7,n)
hbig = big(h); tt_big = big.(tt); elementsbig = big.(elements); rstarbig = big(rstar)
dtdelements_big = ttv_elements!(H,t0big,hbig,tmaxbig,elementsbig,tt_big,count,dtdq0_big,rstarbig)
#=
using PyPlot
clf()
# Plot the difference in the TTVs:
for i=2:3
# diff1 = abs.(tt1[i,2:count1[i]]./tt_big[i,2:count1[i]]-1.0);
diff1 = convert(Array{Float64,1},abs.(tt1[i,2:count1[i]].-tt_big[i,2:count1[i]])/elements[i,2]);
dtt=tt[i,2:count1[i]].-tt[i,1]
loglog(dtt,diff1);
# diff2 = abs.(tt2[i,2:count1[i]]./tt_big_half[i,2:count1[i]]-1.0);
# diff2 = abs.(tt2[i,2:count1[i]].-tt_big_half[i,2:count1[i]])/elements[i,2];
# loglog(tt[i,2:count[i]]-tt[i,1],diff2);
end
loglog([1.0,1024.0],2e-15*[1,2^15],":")
for i=2:3, k=1:7, l=1:3
if maximum(abs.(dtdelements_big[i,2:count[i],k,l])) > 0
diff1 = convert(Array{Float64,1},abs.(dtdelements_big[i,2:count[i],k,l]./dtdelements[i,2:count[i],k,l].-1));
diff3 = convert(Array{Float64,1},abs.(asinh.(dtdelements_big[i,2:count[i],k,l])-asinh.(dtdelements[i,2:count[i],k,l])));
# loglog(tt[i,2:count[i]]-tt[i,1],diff1);
dtt = tt[i,2:count[i]].-tt[i,1]
loglog(dtt,diff3);
println(i," ",k," ",l," frac error: ",convert(Float64,maximum(diff1))," asinh error: ",convert(Float64,maximum(diff3))); #read(STDIN,Char);
end
if maximum(abs.(dtdq0_big[i,2:count[i],k,l])) > 0
diff1 = convert(Array{Float64,1},abs.(dtdq0[i,2:count[i],k,l]./dtdq0_big[i,2:count[i],k,l].-1.0));
# diff2 = abs.(asinh.(dtdq0_big[i,2:count[i],k,l]).-asinh.(dtdq0_num[i,2:count[i],k,l]));
diff3 = convert(Array{Float64,1},abs.(asinh.(dtdq0_big[i,2:count[i],k,l]).-asinh.(dtdq0[i,2:count[i],k,l])));
# loglog(tt[i,2:count[i]].-tt[i,1],diff1);
dtt = tt[i,2:count[i]].-tt[i,1]
loglog(dtt,diff3,linestyle=":");
# loglog(tt[i,2:count[i]].-tt[i,1],diff2,".");
println(i," ",k," ",l," frac error: ",convert(Float64,maximum(diff1))," asinh error: ",convert(Float64,maximum(diff3))); #read(STDIN,Char);
end
end
mederror = zeros(size(tt))
for i=2:3
for j=1:count1[i]
data_list = Float64[]
for k=1:7, l=1:3
if abs(dtdq0_num[i,j,k,l]) > 0
push!(data_list,abs(dtdq0[i,j,k,l]/dtdq0_num[i,j,k,l]-1.0))
end
end
mederror[i,j] = median(data_list)
end
end
# Plot a line that scales as time^{3/2}:
loglog([1.0,1024.0],1e-12*[1,2^15],":",linewidth=3)
=#
#println("Max diff log(dtdq0): ",maximum(abs.(dtdq0_num[mask]./dtdq0[mask].-1.0)))
#println("Max diff asinh(dtdq0): ",maximum(abs.(asinh.(dtdq0_num[mask]).-asinh.(dtdq0[mask]))))
#unit = ones(dtdq0[mask])
#@test isapprox(dtdq0[mask]./convert(Array{Float64,4},dtdq0_num)[mask],unit;norm=maxabs)
#@test isapprox(dtdq0[mask],convert(Array{Float64,4},dtdq0_num)[mask];norm=maxabs)
@test isapprox(asinh.(dtdq0[mask]),asinh.(convert(Array{Float64,4},dtdq0_num)[mask]);norm=maxabs)
#end
#
#nderiv = n^2*7*maximum(ntt)
#loglog(abs.(reshape(dtdq0,nderiv)),abs.(reshape(convert(Array{Float64,4},dtdq0_num),nderiv)),".")
#loglog(abs.(reshape(dtdq0,nderiv)),abs.(reshape(convert(Array{Float64,4},diff_dtdq0),nderiv)),".")
## Make a plot of some TTVs:
#
#fig,axes = subplots(4,2)
#
#for i=2:8
# ax = axes[i-1]
# fn = zeros(Float64,2,count1[i])
# sig = ones(count1[i])
# tti1 = tt1[i,1:count1[i]]
# tti2 = tt2[i,1:count2[i]]
# for j=1:count1[i]
# fn[1,j] = 1.0
# fn[2,j] = round(Int64,(tti1[j]-elements[i,3])/elements[i,2])
# end
# coeff,cov = regress(fn,tti1,sig)
# tt_ref1 = coeff[1]+coeff[2]*fn[2,:]
# ttv1 = (tti1-tt_ref1)*24.*60.
# coeff,cov = regress(fn,tti2,sig)
# tt_ref2 = coeff[1]+coeff[2]*fn[2,:]
# ttv2 = (tti2-tt_ref2)*24.*60.
# ax[:plot](tti1,ttv1)
## ax[:plot](tti2,ttv2)
# ax[:plot](tti2,((ttv1-ttv2)-mean(ttv1-ttv2)))
# println(i," ",coeff," ",elements[i,2:3]," ",coeff[1]-elements[i,3]," ",coeff[2]-elements[i,2])
# println(i," ",maximum(ttv1-ttv2-mean(ttv1-ttv2))*60.," sec ", minimum(ttv1-ttv2-mean(ttv1-ttv2))*60.," sec" )
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4597 |
#include("../src/ttv.jl")
#include("/Users/ericagol/Computer/Julia/regress.jl")
#@testset "ttv_cartesian" begin
# This routine takes derivative of transit times with respect
# to the initial cartesian coordinates of bodies. [x]
#n = 8
n = 3
t0 = 7257.93115525-7300.0
#h = 0.12
h = 0.04
#h = 0.02
#tmax = 600.0
tmax = 40000.0
#tmax = 100.0
#tmax = 10.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
ntt = zeros(Int64,n)
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
println("ntt: ",ntt)
tt = zeros(n,maximum(ntt))
tt2 = zeros(n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
# Call the ttv function:
rstar = 1e12
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtdq0 = zeros(n,maximum(ntt),7,n)
@time dtdelements = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq0,rstar)
# Now with half the timestep:
#dtdq2 = zeros(n,maximum(ntt),7,n)
#@time dtdelements = ttv_elements!(n,t0,h/2,tmax,elements,tt2,count,dtdq2,rstar)
tt_big = big.(tt); elementsbig = big.(elements); rstarbig = big(rstar)
tmaxbig = big(tmax); t0big = big(t0); hbig = big(h)
# Compute the derivatives in BigFloat precision to see whether finite difference
# derivatives or Float64 derivatives are imprecise at the start:
dtdq0_big = zeros(BigFloat,n,maximum(ntt),7,n)
hbig = big(h); tt_big = big.(tt); elementsbig = big.(elements); rstarbig = big(rstar)
@time dtdelements_big = ttv_elements!(n,t0big,hbig,tmaxbig,elementsbig,tt_big,count,dtdq0_big,rstarbig)
# Now with half the timestep:
dtdq2_big = zeros(BigFloat,n,maximum(ntt),7,n)
tt2_big = big.(tt2)
#@time dtdelements_big = ttv_elements!(n,t0big,hbig/2,tmaxbig,elementsbig,tt2_big,count,dtdq2_big,rstarbig)
using PyPlot
clf()
# Plot the difference in the TTVs:
for i=2:3
diff1 = abs.(tt[i,2:count[i]].-tt_big[i,2:count[i]])/h;
loglog(tt[i,2:count[i]]-tt[i,1],diff1);
# diff2 = abs.(tt2[i,2:count[i]].-tt2_big[i,2:count[i]])/elements[i,2];
# loglog(tt[i,2:count[i]]-tt[i,1],diff2);
end
xlabel("Time since start")
ylabel(L"(time_{dbl}-time_{big})/timestep")
#loglog([1.0,1024.0],2e-15*[1,2^15],":")
loglog([1.0,40000.0],0.5e-16*([1.0,40000.0]/h).^1.5,":")
clf()
nmed = 10
for i=2:3, k=1:7, l=1:3
if maximum(abs.(dtdq0[i,2:count[i],k,l])) > 0
# diff1 = abs.(asinh.(dtdq0_big[i,2:count[i],k,l])-asinh.(dtdq0[i,2:count[i],k,l]));
# diff1 = abs.(dtdq0_big[i,2:count[i],k,l]-dtdq0[i,2:count[i],k,l])/maximum(dtdq0[i,2:count[i],k,l]);
diff1 = abs.(dtdq0_big[i,2:count[i],k,l]-dtdq0[i,2:count[i],k,l])
diff2 = copy(diff1);
diff3 = abs.(dtdelements_big[i,2:count[i],k,l]-dtdelements[i,2:count[i],k,l])
# diff3 = abs.(asinh.(dtdelements_big[i,2:count[i],k,l])-asinh.(dtdelements[i,2:count[i],k,l]))
diff4 = copy(diff3);
ntt1 = size(diff1)[1];
for it=nmed:ntt1-nmed
# Divide by a median smoothed dtdq0:
diff2[it] = diff1[it]/maximum(abs.(dtdq0[i,it+1-nmed+1:it+1+nmed,k,l]))
maxit = maximum(abs.(dtdelements[i,it+1-nmed+1:it+1+nmed,k,l]))
if maxit > 0
diff4[it] = diff3[it]/maximum(abs.(dtdelements[i,it+1-nmed+1:it+1+nmed,k,l]))
end
end;
diff2[1:nmed-1] .= diff2[nmed]; diff2[ntt1-nmed+1:ntt1] .= diff2[ntt1-nmed];
diff4[1:nmed-1] .= diff4[nmed]; diff4[ntt1-nmed+1:ntt1] .= diff4[ntt1-nmed];
# diff3 = abs.(asinh.(dtdq2_big[i,2:count[i],k,l])-asinh.(dtdq2[i,2:count[i],k,l]));
loglog(tt[i,2:count[i]]-tt[i,1],diff2,linestyle=":");
loglog(tt[i,2:count[i]]-tt[i,1],diff4,linestyle="--");
# loglog(tt[i,2:count[i]]-tt[i,1],diff3);
println("xvs: ",i," ",k," ",l," asinh error h : ",convert(Float64,maximum(diff2))); #read(STDIN,Char);
println("els: ",i," ",k," ",l," asinh error h : ",convert(Float64,maximum(diff4))); #read(STDIN,Char);
# println(i," ",k," ",l," asinh error h/2: ",convert(Float64,maximum(diff3))); #read(STDIN,Char);
end
end
loglog([1.0,40000.0],0.5e-16*([1.0,40000.0]/h).^1.5)
#axis([1,1024,1e-19,1e-9])
axis([1,31600,1e-19,2.5e-7])
xlabel("Time since start")
#ylabel("median(asinh(dt/dq)_dbl - asinh(dt/dq)_big,20)")
ylabel("(dt/dq_{dbl}-dt/dq_{big})/maximum(dt/dq_{dbl}[i-9:i+10])")
# Plot a line that scales as time^{3/2}:
# loglog([1.0,1024.0],1e-12*[1,2^15],":",linewidth=3)
# loglog([1.0,1024.0],1e-12*[1,2^15],":",linewidth=3)
println("Max diff asinh(dtdq0): ",maximum(abs.(asinh.(dtdq0_big)-asinh.(dtdq0))))
@test isapprox(asinh.(dtdq0),asinh.(convert(Array{Float64,4},dtdq0_big));norm=maxabs)
#end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 4621 |
#include("../src/ttv.jl")
#include("/Users/ericagol/Computer/Julia/regress.jl")
#@testset "ttv_cartesian" begin
# This routine takes derivative of transit times with respect
# to the initial cartesian coordinates of bodies. [x]
#n = 8
n = 2
t0 = 7257.93115525-7300.0
#h = 0.12
h = 0.04
#h = 0.02
#tmax = 600.0
tmax = 40000.0
#tmax = 100.0
#tmax = 10.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
elements[:,3] -= 7300.0
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
ntt = zeros(Int64,n)
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
println("ntt: ",ntt)
tt = zeros(n,maximum(ntt))
tt2 = zeros(n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
# Call the ttv function:
rstar = 1e12
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtdq0 = zeros(n,maximum(ntt),7,n)
@time dtdelements = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq0,rstar)
# Now with half the timestep:
#dtdq2 = zeros(n,maximum(ntt),7,n)
#@time dtdelements = ttv_elements!(n,t0,h/2,tmax,elements,tt2,count,dtdq2,rstar)
tt_big = big.(tt); elementsbig = big.(elements); rstarbig = big(rstar)
tmaxbig = big(tmax); t0big = big(t0); hbig = big(h)
# Compute the derivatives in BigFloat precision to see whether finite difference
# derivatives or Float64 derivatives are imprecise at the start:
dtdq0_big = zeros(BigFloat,n,maximum(ntt),7,n)
hbig = big(h); tt_big = big.(tt); elementsbig = big.(elements); rstarbig = big(rstar)
@time dtdelements_big = ttv_elements!(n,t0big,hbig,tmaxbig,elementsbig,tt_big,count,dtdq0_big,rstarbig)
# Now with half the timestep:
dtdq2_big = zeros(BigFloat,n,maximum(ntt),7,n)
tt2_big = big.(tt2)
#@time dtdelements_big = ttv_elements!(n,t0big,hbig/2,tmaxbig,elementsbig,tt2_big,count,dtdq2_big,rstarbig)
using PyPlot
clf()
# Plot the difference in the TTVs:
for i=2:n
diff1 = abs.(tt[i,2:count[i]].-tt_big[i,2:count[i]])/h;
loglog(tt[i,2:count[i]]-tt[i,1],diff1);
# diff2 = abs.(tt2[i,2:count[i]].-tt2_big[i,2:count[i]])/elements[i,2];
# loglog(tt[i,2:count[i]]-tt[i,1],diff2);
end
xlabel("Time since start")
ylabel(L"(time_{dbl}-time_{big})/timestep")
#loglog([1.0,1024.0],2e-15*[1,2^15],":")
loglog([1.0,40000.0],0.5e-16*([1.0,40000.0]/h).^1.5,":")
clf()
nmed = 10
for i=2:n, k=1:7, l=1:n
if maximum(abs.(dtdq0[i,2:count[i],k,l])) > 0
# diff1 = abs.(asinh.(dtdq0_big[i,2:count[i],k,l])-asinh.(dtdq0[i,2:count[i],k,l]));
# diff1 = abs.(dtdq0_big[i,2:count[i],k,l]-dtdq0[i,2:count[i],k,l])/maximum(dtdq0[i,2:count[i],k,l]);
diff1 = abs.(dtdq0_big[i,2:count[i],k,l]-dtdq0[i,2:count[i],k,l])
diff2 = copy(diff1);
diff3 = abs.(dtdelements_big[i,2:count[i],k,l]-dtdelements[i,2:count[i],k,l])
# diff3 = abs.(asinh.(dtdelements_big[i,2:count[i],k,l])-asinh.(dtdelements[i,2:count[i],k,l]))
diff4 = copy(diff3);
ntt1 = size(diff1)[1];
for it=nmed:ntt1-nmed
# Divide by a median smoothed dtdq0:
diff2[it] = diff1[it]/maximum(abs.(dtdq0[i,it+1-nmed+1:it+1+nmed,k,l]))
maxit = maximum(abs.(dtdelements[i,it+1-nmed+1:it+1+nmed,k,l]))
if maxit > 0
diff4[it] = diff3[it]/maximum(abs.(dtdelements[i,it+1-nmed+1:it+1+nmed,k,l]))
end
end;
diff2[1:nmed-1] .= diff2[nmed]; diff2[ntt1-nmed+1:ntt1] .= diff2[ntt1-nmed];
diff4[1:nmed-1] .= diff4[nmed]; diff4[ntt1-nmed+1:ntt1] .= diff4[ntt1-nmed];
# diff3 = abs.(asinh.(dtdq2_big[i,2:count[i],k,l])-asinh.(dtdq2[i,2:count[i],k,l]));
loglog(tt[i,2:count[i]]-tt[i,1],diff2,linestyle=":");
loglog(tt[i,2:count[i]]-tt[i,1],diff4,linestyle="--");
# loglog(tt[i,2:count[i]]-tt[i,1],diff3);
println("xvs: ",i," ",k," ",l," asinh error h : ",convert(Float64,maximum(diff2))); #read(STDIN,Char);
println("els: ",i," ",k," ",l," asinh error h : ",convert(Float64,maximum(diff4))); #read(STDIN,Char);
# println(i," ",k," ",l," asinh error h/2: ",convert(Float64,maximum(diff3))); #read(STDIN,Char);
end
end
loglog([1.0,40000.0],0.5e-16*([1.0,40000.0]/h).^1.5)
#axis([1,1024,1e-19,1e-9])
axis([1,31600,1e-19,2.5e-7])
xlabel("Time since start")
#ylabel("median(asinh(dt/dq)_dbl - asinh(dt/dq)_big,20)")
ylabel("(dt/dq_{dbl}-dt/dq_{big})/maximum(dt/dq_{dbl}[i-9:i+10])")
# Plot a line that scales as time^{3/2}:
# loglog([1.0,1024.0],1e-12*[1,2^15],":",linewidth=3)
# loglog([1.0,1024.0],1e-12*[1,2^15],":",linewidth=3)
println("Max diff asinh(dtdq0): ",maximum(abs.(asinh.(dtdq0_big)-asinh.(dtdq0))))
@test isapprox(asinh.(dtdq0),asinh.(convert(Array{Float64,4},dtdq0_big));norm=maxabs)
#end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 10739 |
#include("../src/ttv.jl")
#include("/Users/ericagol/Computer/Julia/regress.jl")
@testset "ttv_elements" begin
# This routine takes derivative of transit times with respect
# to the initial orbital elements.
#n = 8
n = 3
H = [3,1,1]
n_body = n
t0 = 7257.93115525-7300.0
#h = 0.12
h = 0.04
#tmax = 600.0
#tmax = 800.0
#tmax = 1000.0
tmax = 10.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
elements[:,3] .-= 7300.0
# Make masses of planets bigger
#elements[2,1] *= 10.0
#elements[3,1] *= 10.0
ntt = zeros(Int64,n)
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
dtdq0 = zeros(n,maximum(ntt),7,n)
tt = zeros(n,maximum(ntt))
tt1 = zeros(n,maximum(ntt))
tt2 = zeros(n,maximum(ntt))
tt3 = zeros(n,maximum(ntt))
tt4 = zeros(n,maximum(ntt))
tt8 = zeros(n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
count1 = zeros(Int64,n)
# Call the ttv function:
rstar = 1e12
dq = ttv_elements!(H,t0,h,tmax,elements,tt1,count1,0.0,0,0,rstar)
# Now call with half the timestep:
count2 = zeros(Int64,n)
count3 = zeros(Int64,n)
dq = ttv_elements!(H,t0,h/10.,tmax,elements,tt2,count2,0.0,0,0,rstar)
mask = zeros(Bool, size(dtdq0))
for jq=1:n_body
for iq=1:7
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
for i=2:n
for k=1:count2[i]
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[i,k,iq,jq] = true
end
end
end
end
end
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtdelements0 = zeros(n,maximum(ntt),7,n)
dtdelements0 = ttv_elements!(H,t0,h,tmax,elements,tt,count,dtdq0,rstar)
dtdq2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = ttv_elements!(H,t0,h/2.,tmax,elements,tt2,count,dtdq2,rstar)
dtdq4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = ttv_elements!(H,t0,h/4.,tmax,elements,tt4,count,dtdq4,rstar)
dtdq8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = ttv_elements!(H,t0,h/8.,tmax,elements,tt8,count,dtdq8,rstar)
#println("Maximum error on derivative: ",maximum(abs.(dtdelements0-dtdelements2)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements2-dtdelements4)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements4-dtdelements8)))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements0[mask])-asinh.(dtdelements2[mask]))))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq0)-asinh.(dtdq2))))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements2[mask])-asinh.(dtdelements4[mask]))))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq2)-asinh.(dtdq4))))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements4[mask])-asinh.(dtdelements8[mask]))))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq4)-asinh.(dtdq8))))
#read(STDIN,Char)
# Check that this is working properly:
#for i=1:n
# for j=1:count2[i]
# println(i," ",j," ",tt[i,j]," ",tt2[i,j]," ",tt[i,j]-tt2[i,j]," ",tt1[i,j]-tt2[i,j])
# end
#end
#read(STDIN,Char)
# Compute derivatives numerically:
#nq = 15
# This "summarizes" best numerical derivative:
dtdelements0_num = zeros(BigFloat,n,maximum(ntt),7,n)
# Compute derivatives with BigFloat for additional precision:
elements0 = copy(elements)
#delement = big.([1e-15,1e-15,1e-15,1e-15,1e-15,1e-15,1e-15])
#dq0 = big(1e-20)
dq0 = big(1e-10)
t0big = big(t0); tmaxbig = big(tmax); hbig = big(h)
zilch = big(0.0)
# Compute the transit times in BigFloat precision:
tt_big = big.(tt); elementsbig = big.(elements0); rstarbig = big(rstar)
dqbig = ttv_elements!(H,t0big,hbig,tmaxbig,elementsbig,tt_big,count,big(0.0),0,0,rstarbig)
mask = zeros(Bool, size(dtdq0))
for jq=1:n_body
for iq=1:7
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
for i=2:n
for k=1:count2[i]
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[i,k,iq,jq] = true
end
end
end
end
end
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtdelements0 = zeros(n,maximum(ntt),7,n)
dtdelements0 = ttv_elements!(H,t0,h,tmax,elements,tt,count,dtdq0,rstar)
dtdq2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = ttv_elements!(H,t0,h/2.,tmax,elements,tt2,count,dtdq2,rstar)
dtdq4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = ttv_elements!(H,t0,h/4.,tmax,elements,tt4,count,dtdq4,rstar)
dtdq8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = ttv_elements!(H,t0,h/8.,tmax,elements,tt8,count,dtdq8,rstar)
#println("Maximum error on derivative: ",maximum(abs.(dtdelements0-dtdelements2)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements2-dtdelements4)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements4-dtdelements8)))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements0[mask])-asinh.(dtdelements2[mask]))))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq0)-asinh.(dtdq2))))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements2[mask])-asinh.(dtdelements4[mask]))))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq2)-asinh.(dtdq4))))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements4[mask])-asinh.(dtdelements8[mask]))))
#println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq4)-asinh.(dtdq8))))
#read(STDIN,Char)
# Check that this is working properly:
#for i=1:n
# for j=1:count2[i]
# println(i," ",j," ",tt[i,j]," ",tt2[i,j]," ",tt[i,j]-tt2[i,j]," ",tt1[i,j]-tt2[i,j])
# end
#end
#read(STDIN,Char)
# Compute derivatives numerically:
#nq = 15
# This "summarizes" best numerical derivative:
dtdelements0_num = zeros(BigFloat,n,maximum(ntt),7,n)
# Compute derivatives with BigFloat for additional precision:
elements0 = copy(elements)
#delement = big.([1e-15,1e-15,1e-15,1e-15,1e-15,1e-15,1e-15])
#dq0 = big(1e-20)
dq0 = big(1e-10)
tt2 = big.(tt2)
tt3 = big.(tt3)
t0big = big(t0); tmaxbig = big(tmax); hbig = big(h)
zilch = big(0.0)
# Compute the transit times in BigFloat precision:
tt_big = big.(tt); elementsbig = big.(elements0)
# Now, compute derivatives numerically:
for jq=1:n_body
for iq=1:7
elementsbig = big.(elements0)
# dq0 = delement[iq]; if jq==1 && iq==7 ; dq0 = big(1e-10); end # Vary mass of star by a larger factor
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
elementsbig[jq,ivary] += dq0
dq_plus = ttv_elements!(H,t0big,hbig,tmaxbig,elementsbig,tt2,count2,zilch,0,0,big(rstar))
elementsbig[jq,ivary] -= 2dq0
dq_minus = ttv_elements!(H,t0big,hbig,tmaxbig,elementsbig,tt3,count2,zilch,0,0,big(rstar))
#xm,vm = init_nbody(elements,t0,n_body)
for i=2:n
for k=1:count2[i]
# Compute double-sided derivative for more accuracy:
dtdelements0_num[i,k,iq,jq] = (tt2[i,k]-tt3[i,k])/(2dq0)
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[i,k,iq,jq] = true
end
end
end
end
end
#println("Max diff dtdelements: ",maximum(abs.(dtdelements0[mask]./dtdelements0_num[mask].-1.0)))
#println("Max diff asinh(dtdelements): ",maximum(abs.(asinh.(dtdelements0[mask])-asinh.(dtdelements0_num[mask]))))
#ntot = 0
#diff_dtdelements0 = zeros(n,maximum(ntt),7,n)
#for i=1:n, j=1:count[i], k=1:7, l=2:n
# diff_dtdelements0[i,j,k,l] = abs(dtdelements0[i,j,k,l]-convert(Float64,dtdelements0_num[i,j,k,l]))
# ntot +=1
#end
#using PyPlot
#
#nderiv = n^2*7*maximum(ntt)
##mask[:,:,2,:] = false
#loglog(abs.(reshape(dtdelements0,nderiv)),abs.(reshape(convert(Array{Float64,4},dtdelements0_num),nderiv)),".")
#axis([1e-6,1e2,1e-12,1e2])
#loglog(abs.(reshape(dtdelements0,nderiv)),abs.(reshape(diff_dtdelements0,nderiv)),".")
#println("Maximum error: ",maximum(diff_dtdelements0))
#=
using PyPlot
# Make a plot of the fractional errors:
for i=2:3, k=1:7, l=1:3
if maximum(abs.(dtdelements0_num[i,2:count1[i],k,l])) > 0
loglog(tt[i,2:count1[i]].-tt[i,1],convert(Array{Float64,1},abs.(dtdelements0[i,2:count1[i],k,l]./dtdelements0_num[i,2:count1[i],k,l].-1.)))
end
end
clf()
# Plot the difference in the TTVs:
for i=2:3
diff1 = convert(Array{Float64,1},abs.(tt1[i,2:count1[i]]./tt_big[i,2:count1[i]].-1.0));
loglog(tt[i,2:count1[i]].-tt[i,1],diff1);
end
for i=2:3, k=1:7, l=1:3
if maximum(abs.(dtdelements0_num[i,2:count1[i],k,l])) > 0 && k != 5 && k != 6
diff1 = convert(Array{Float64,1},abs.(dtdelements0[i,2:count1[i],k,l]./dtdelements0_num[i,2:count1[i],k,l].-1));
diff2 = convert(Array{Float64,1},abs.(asinh.(dtdelements0[i,2:count1[i],k,l])-asinh.(dtdelements0_num[i,2:count1[i],k,l])));
loglog(tt[i,2:count1[i]].-tt[i,1],diff1);
# loglog(tt[i,2:count1[i]].-tt[i,1],diff2,".");
println(i," ",k," ",l," frac error: ",convert(Float64,maximum(diff1))," asinh error: ",convert(Float64,maximum(diff2))); #read(STDIN,Char);
end
end
# Plot a line that scales as time^{3/2}:
loglog([1.0,1024.0],1e-09*[1,2^15],":")
loglog([1.0,1024.0],1e-12*[1,2^15],":")
loglog([1.0,1024.0],1e-15*[1,2^15],":")
=#
#@test isapprox(dtdelements0[mask],dtdelements0_num[mask];norm=maxabs)
@test isapprox(asinh.(dtdelements0[mask]),asinh.(dtdelements0_num[mask]);norm=maxabs)
#unit = ones(dtdelements0[mask])
#@test isapprox(dtdelements0[mask]./dtdelements0_num[mask],unit;norm=maxabs)
#end
## Make a plot of some TTVs:
#
#fig,axes = subplots(4,2)
#
#for i=2:8
# ax = axes[i-1]
# fn = zeros(Float64,2,count1[i])
# sig = ones(count1[i])
# tti1 = tt1[i,1:count1[i]]
# tti2 = tt2[i,1:count2[i]]
# for j=1:count1[i]
# fn[1,j] = 1.0
# fn[2,j] = round(Int64,(tti1[j]-elements[i,3])/elements[i,2])
# end
# coeff,cov = regress(fn,tti1,sig)
# tt_ref1 = coeff[1]+coeff[2]*fn[2,:]
# ttv1 = (tti1.-tt_ref1)*24.*60.
# coeff,cov = regress(fn,tti2,sig)
# tt_ref2 = coeff[1]+coeff[2]*fn[2,:]
# ttv2 = (tti2.-tt_ref2)*24.*60.
# ax[:plot](tti1,ttv1)
## ax[:plot](tti2,ttv2)
# ax[:plot](tti2,((ttv1.-ttv2)-mean(ttv1.-ttv2)))
# println(i," ",coeff," ",elements[i,2:3]," ",coeff[1]-elements[i,3]," ",coeff[2]-elements[i,2])
# println(i," ",maximum(ttv1-ttv2-mean(ttv1-ttv2))*60.," sec ", minimum(ttv1-ttv2-mean(ttv1-ttv2))*60.," sec" )
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 10613 | 2
#include("../src/ttv.jl")
#include("/Users/ericagol/Computer/Julia/regress.jl")
#@testset "ttv_elements" begin
# This routine takes derivative of transit times with respect
# to the initial orbital elements.
#n = 8
n = 2
n_body = n
t0 = 7257.93115525-7300.0
#h = 0.12
h = 0.04
#tmax = 600.0
#tmax = 800.0
#tmax = 1000.0
tmax = 10.0
#tmax = 40000.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
elements[:,3] -= 7300.0
# Make masses of planets bigger
#elements[2,1] *= 10.0
#elements[3,1] *= 10.0
ntt = zeros(Int64,n)
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
dtdq0 = zeros(n,maximum(ntt),7,n)
tt = zeros(n,maximum(ntt))
tt1 = zeros(n,maximum(ntt))
tt2 = zeros(n,maximum(ntt))
tt3 = zeros(n,maximum(ntt))
tt4 = zeros(n,maximum(ntt))
tt8 = zeros(n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
count1 = zeros(Int64,n)
# Call the ttv function:
rstar = 1e12
dq = ttv_elements!(n,t0,h,tmax,elements,tt1,count1,0.0,0,0,rstar)
# Now call with half the timestep:
count2 = zeros(Int64,n)
count3 = zeros(Int64,n)
dq = ttv_elements!(n,t0,h/10.,tmax,elements,tt2,count2,0.0,0,0,rstar)
mask = zeros(Bool, size(dtdq0))
for jq=1:n_body
for iq=1:7
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
for i=2:n
for k=1:count2[i]
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[i,k,iq,jq] = true
end
end
end
end
end
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtdelements0 = zeros(n,maximum(ntt),7,n)
dtdelements0 = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq0,rstar)
dtdq2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = ttv_elements!(n,t0,h/2.,tmax,elements,tt2,count,dtdq2,rstar)
dtdq4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = ttv_elements!(n,t0,h/4.,tmax,elements,tt4,count,dtdq4,rstar)
dtdq8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = ttv_elements!(n,t0,h/8.,tmax,elements,tt8,count,dtdq8,rstar)
#println("Maximum error on derivative: ",maximum(abs.(dtdelements0-dtdelements2)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements2-dtdelements4)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements4-dtdelements8)))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements0[mask])-asinh.(dtdelements2[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq0)-asinh.(dtdq2))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements2[mask])-asinh.(dtdelements4[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq2)-asinh.(dtdq4))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements4[mask])-asinh.(dtdelements8[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq4)-asinh.(dtdq8))))
#read(STDIN,Char)
# Check that this is working properly:
#for i=1:n
# for j=1:count2[i]
# println(i," ",j," ",tt[i,j]," ",tt2[i,j]," ",tt[i,j]-tt2[i,j]," ",tt1[i,j]-tt2[i,j])
# end
#end
#read(STDIN,Char)
# Compute derivatives numerically:
#nq = 15
# This "summarizes" best numerical derivative:
dtdelements0_num = zeros(BigFloat,n,maximum(ntt),7,n)
# Compute derivatives with BigFloat for additional precision:
elements0 = copy(elements)
#delement = big.([1e-15,1e-15,1e-15,1e-15,1e-15,1e-15,1e-15])
#dq0 = big(1e-20)
dq0 = big(1e-10)
t0big = big(t0); tmaxbig = big(tmax); hbig = big(h)
zilch = big(0.0)
# Compute the transit times in BigFloat precision:
tt_big = big.(tt); elementsbig = big.(elements0); rstarbig = big(rstar)
dqbig = ttv_elements!(n,t0big,hbig,tmaxbig,elementsbig,tt_big,count,big(0.0),0,0,rstarbig)
mask = zeros(Bool, size(dtdq0))
for jq=1:n_body
for iq=1:7
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
for i=2:n
for k=1:count2[i]
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[i,k,iq,jq] = true
end
end
end
end
end
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtdelements0 = zeros(n,maximum(ntt),7,n)
dtdelements0 = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq0,rstar)
dtdq2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = ttv_elements!(n,t0,h/2.,tmax,elements,tt2,count,dtdq2,rstar)
dtdq4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = ttv_elements!(n,t0,h/4.,tmax,elements,tt4,count,dtdq4,rstar)
dtdq8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = ttv_elements!(n,t0,h/8.,tmax,elements,tt8,count,dtdq8,rstar)
#println("Maximum error on derivative: ",maximum(abs.(dtdelements0-dtdelements2)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements2-dtdelements4)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements4-dtdelements8)))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements0[mask])-asinh.(dtdelements2[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq0)-asinh.(dtdq2))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements2[mask])-asinh.(dtdelements4[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq2)-asinh.(dtdq4))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements4[mask])-asinh.(dtdelements8[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq4)-asinh.(dtdq8))))
#read(STDIN,Char)
# Check that this is working properly:
#for i=1:n
# for j=1:count2[i]
# println(i," ",j," ",tt[i,j]," ",tt2[i,j]," ",tt[i,j]-tt2[i,j]," ",tt1[i,j]-tt2[i,j])
# end
#end
#read(STDIN,Char)
# Compute derivatives numerically:
#nq = 15
# This "summarizes" best numerical derivative:
dtdelements0_num = zeros(BigFloat,n,maximum(ntt),7,n)
# Compute derivatives with BigFloat for additional precision:
elements0 = copy(elements)
#delement = big.([1e-15,1e-15,1e-15,1e-15,1e-15,1e-15,1e-15])
#dq0 = big(1e-20)
dq0 = big(1e-10)
tt2 = big.(tt2)
tt3 = big.(tt3)
t0big = big(t0); tmaxbig = big(tmax); hbig = big(h)
zilch = big(0.0)
# Compute the transit times in BigFloat precision:
tt_big = big.(tt); elementsbig = big.(elements0)
# Now, compute derivatives numerically:
for jq=1:n_body
for iq=1:7
elementsbig = big.(elements0)
# dq0 = delement[iq]; if jq==1 && iq==7 ; dq0 = big(1e-10); end # Vary mass of star by a larger factor
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
elementsbig[jq,ivary] += dq0
dq_plus = ttv_elements!(n,t0big,hbig,tmaxbig,elementsbig,tt2,count2,zilch,0,0,big(rstar))
elementsbig[jq,ivary] -= 2dq0
dq_minus = ttv_elements!(n,t0big,hbig,tmaxbig,elementsbig,tt3,count2,zilch,0,0,big(rstar))
#xm,vm = init_nbody(elements,t0,n_body)
for i=2:n
for k=1:count2[i]
# Compute double-sided derivative for more accuracy:
dtdelements0_num[i,k,iq,jq] = (tt2[i,k]-tt3[i,k])/(2.*dq0)
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[i,k,iq,jq] = true
end
end
end
end
end
#println("Max diff dtdelements: ",maximum(abs.(dtdelements0[mask]./dtdelements0_num[mask]-1.0)))
println("Max diff asinh(dtdelements): ",maximum(abs.(asinh.(dtdelements0[mask])-asinh.(dtdelements0_num[mask]))))
#ntot = 0
#diff_dtdelements0 = zeros(n,maximum(ntt),7,n)
#for i=1:n, j=1:count[i], k=1:7, l=2:n
# diff_dtdelements0[i,j,k,l] = abs(dtdelements0[i,j,k,l]-convert(Float64,dtdelements0_num[i,j,k,l]))
# ntot +=1
#end
#using PyPlot
#
#nderiv = n^2*7*maximum(ntt)
##mask[:,:,2,:] = false
#loglog(abs.(reshape(dtdelements0,nderiv)),abs.(reshape(convert(Array{Float64,4},dtdelements0_num),nderiv)),".")
#axis([1e-6,1e2,1e-12,1e2])
#loglog(abs.(reshape(dtdelements0,nderiv)),abs.(reshape(diff_dtdelements0,nderiv)),".")
#println("Maximum error: ",maximum(diff_dtdelements0))
using PyPlot
# Make a plot of the fractional errors:
for i=2:n, k=1:7, l=1:n
if maximum(abs.(dtdelements0_num[i,2:count1[i],k,l])) > 0
loglog(tt[i,2:count1[i]]-tt[i,1],abs.(dtdelements0[i,2:count1[i],k,l]./dtdelements0_num[i,2:count1[i],k,l]-1.))
end
end
clf()
# Plot the difference in the TTVs:
for i=2:n
diff1 = abs.(tt1[i,2:count1[i]]./tt_big[i,2:count1[i]]-1.0);
loglog(tt[i,2:count1[i]]-tt[i,1],diff1);
end
for i=2:n, k=1:7, l=1:n
if maximum(abs.(dtdelements0_num[i,2:count1[i],k,l])) > 0 && k != 5 && k != 6
diff1 = abs.(dtdelements0[i,2:count1[i],k,l]./dtdelements0_num[i,2:count1[i],k,l]-1.);
diff2 = abs.(asinh.(dtdelements0[i,2:count1[i],k,l])-asinh.(dtdelements0_num[i,2:count1[i],k,l]));
loglog(tt[i,2:count1[i]]-tt[i,1],diff1);
# loglog(tt[i,2:count1[i]]-tt[i,1],diff2,".");
println(i," ",k," ",l," frac error: ",convert(Float64,maximum(diff1))," asinh error: ",convert(Float64,maximum(diff2))); #read(STDIN,Char);
end
end
# Plot a line that scales as time^{3/2}:
loglog([1.0,1024.0],1e-09*[1,2^15],":")
loglog([1.0,1024.0],1e-12*[1,2^15],":")
loglog([1.0,1024.0],1e-15*[1,2^15],":")
#@test isapprox(dtdelements0[mask],dtdelements0_num[mask];norm=maxabs)
@test isapprox(asinh.(dtdelements0[mask]),asinh.(dtdelements0_num[mask]);norm=maxabs)
#unit = ones(dtdelements0[mask])
#@test isapprox(dtdelements0[mask]./dtdelements0_num[mask],unit;norm=maxabs)
#end
## Make a plot of some TTVs:
#
#fig,axes = subplots(4,2)
#
#for i=2:8
# ax = axes[i-1]
# fn = zeros(Float64,2,count1[i])
# sig = ones(count1[i])
# tti1 = tt1[i,1:count1[i]]
# tti2 = tt2[i,1:count2[i]]
# for j=1:count1[i]
# fn[1,j] = 1.0
# fn[2,j] = round(Int64,(tti1[j]-elements[i,3])/elements[i,2])
# end
# coeff,cov = regress(fn,tti1,sig)
# tt_ref1 = coeff[1]+coeff[2]*fn[2,:]
# ttv1 = (tti1-tt_ref1)*24.*60.
# coeff,cov = regress(fn,tti2,sig)
# tt_ref2 = coeff[1]+coeff[2]*fn[2,:]
# ttv2 = (tti2-tt_ref2)*24.*60.
# ax[:plot](tti1,ttv1)
## ax[:plot](tti2,ttv2)
# ax[:plot](tti2,((ttv1-ttv2)-mean(ttv1-ttv2)))
# println(i," ",coeff," ",elements[i,2:3]," ",coeff[1]-elements[i,3]," ",coeff[2]-elements[i,2])
# println(i," ",maximum(ttv1-ttv2-mean(ttv1-ttv2))*60.," sec ", minimum(ttv1-ttv2-mean(ttv1-ttv2))*60.," sec" )
#end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 10682 |
#include("../src/ttv.jl")
#include("/Users/ericagol/Computer/Julia/regress.jl")
#@testset "ttv_elements" begin
# This routine takes derivative of transit times with respect
# to the initial orbital elements.
#n = 8
n = 2
n_body = n
t0 = 7257.93115525-7300.0
#h = 0.12
h = 0.04
#tmax = 600.0
#tmax = 800.0
#tmax = 1000.0
tmax = 10.0
#tmax = 40000.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
elements[:,3] -= 7300.0
# Make initial conditions (nearly) circular:
elements[2:3,4:5] = 1e-9
# Make masses of planets bigger
#elements[2,1] *= 10.0
#elements[3,1] *= 10.0
ntt = zeros(Int64,n)
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
dtdq0 = zeros(n,maximum(ntt),7,n)
tt = zeros(n,maximum(ntt))
tt1 = zeros(n,maximum(ntt))
tt2 = zeros(n,maximum(ntt))
tt3 = zeros(n,maximum(ntt))
tt4 = zeros(n,maximum(ntt))
tt8 = zeros(n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
count1 = zeros(Int64,n)
# Call the ttv function:
rstar = 1e12
dq = ttv_elements!(n,t0,h,tmax,elements,tt1,count1,0.0,0,0,rstar)
# Now call with half the timestep:
count2 = zeros(Int64,n)
count3 = zeros(Int64,n)
dq = ttv_elements!(n,t0,h/10.,tmax,elements,tt2,count2,0.0,0,0,rstar)
mask = zeros(Bool, size(dtdq0))
for jq=1:n_body
for iq=1:7
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
for i=2:n
for k=1:count2[i]
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[i,k,iq,jq] = true
end
end
end
end
end
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtdelements0 = zeros(n,maximum(ntt),7,n)
dtdelements0 = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq0,rstar)
dtdq2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = ttv_elements!(n,t0,h/2.,tmax,elements,tt2,count,dtdq2,rstar)
dtdq4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = ttv_elements!(n,t0,h/4.,tmax,elements,tt4,count,dtdq4,rstar)
dtdq8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = ttv_elements!(n,t0,h/8.,tmax,elements,tt8,count,dtdq8,rstar)
#println("Maximum error on derivative: ",maximum(abs.(dtdelements0-dtdelements2)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements2-dtdelements4)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements4-dtdelements8)))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements0[mask])-asinh.(dtdelements2[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq0)-asinh.(dtdq2))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements2[mask])-asinh.(dtdelements4[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq2)-asinh.(dtdq4))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements4[mask])-asinh.(dtdelements8[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq4)-asinh.(dtdq8))))
#read(STDIN,Char)
# Check that this is working properly:
#for i=1:n
# for j=1:count2[i]
# println(i," ",j," ",tt[i,j]," ",tt2[i,j]," ",tt[i,j]-tt2[i,j]," ",tt1[i,j]-tt2[i,j])
# end
#end
#read(STDIN,Char)
# Compute derivatives numerically:
#nq = 15
# This "summarizes" best numerical derivative:
dtdelements0_num = zeros(BigFloat,n,maximum(ntt),7,n)
# Compute derivatives with BigFloat for additional precision:
elements0 = copy(elements)
#delement = big.([1e-15,1e-15,1e-15,1e-15,1e-15,1e-15,1e-15])
#dq0 = big(1e-20)
dq0 = big(1e-10)
t0big = big(t0); tmaxbig = big(tmax); hbig = big(h)
zilch = big(0.0)
# Compute the transit times in BigFloat precision:
tt_big = big.(tt); elementsbig = big.(elements0); rstarbig = big(rstar)
dqbig = ttv_elements!(n,t0big,hbig,tmaxbig,elementsbig,tt_big,count,big(0.0),0,0,rstarbig)
mask = zeros(Bool, size(dtdq0))
for jq=1:n_body
for iq=1:7
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
for i=2:n
for k=1:count2[i]
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[i,k,iq,jq] = true
end
end
end
end
end
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtdelements0 = zeros(n,maximum(ntt),7,n)
dtdelements0 = ttv_elements!(n,t0,h,tmax,elements,tt,count,dtdq0,rstar)
dtdq2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = zeros(n,maximum(ntt),7,n)
dtdelements2 = ttv_elements!(n,t0,h/2.,tmax,elements,tt2,count,dtdq2,rstar)
dtdq4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = zeros(n,maximum(ntt),7,n)
dtdelements4 = ttv_elements!(n,t0,h/4.,tmax,elements,tt4,count,dtdq4,rstar)
dtdq8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = zeros(n,maximum(ntt),7,n)
dtdelements8 = ttv_elements!(n,t0,h/8.,tmax,elements,tt8,count,dtdq8,rstar)
#println("Maximum error on derivative: ",maximum(abs.(dtdelements0-dtdelements2)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements2-dtdelements4)))
#println("Maximum error on derivative: ",maximum(abs.(dtdelements4-dtdelements8)))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements0[mask])-asinh.(dtdelements2[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq0)-asinh.(dtdq2))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements2[mask])-asinh.(dtdelements4[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq2)-asinh.(dtdq4))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdelements4[mask])-asinh.(dtdelements8[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtdq4)-asinh.(dtdq8))))
#read(STDIN,Char)
# Check that this is working properly:
#for i=1:n
# for j=1:count2[i]
# println(i," ",j," ",tt[i,j]," ",tt2[i,j]," ",tt[i,j]-tt2[i,j]," ",tt1[i,j]-tt2[i,j])
# end
#end
#read(STDIN,Char)
# Compute derivatives numerically:
#nq = 15
# This "summarizes" best numerical derivative:
dtdelements0_num = zeros(BigFloat,n,maximum(ntt),7,n)
# Compute derivatives with BigFloat for additional precision:
elements0 = copy(elements)
#delement = big.([1e-15,1e-15,1e-15,1e-15,1e-15,1e-15,1e-15])
#dq0 = big(1e-20)
dq0 = big(1e-10)
tt2 = big.(tt2)
tt3 = big.(tt3)
t0big = big(t0); tmaxbig = big(tmax); hbig = big(h)
zilch = big(0.0)
# Compute the transit times in BigFloat precision:
tt_big = big.(tt); elementsbig = big.(elements0)
# Now, compute derivatives numerically:
for jq=1:n_body
for iq=1:7
elementsbig = big.(elements0)
# dq0 = delement[iq]; if jq==1 && iq==7 ; dq0 = big(1e-10); end # Vary mass of star by a larger factor
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
elementsbig[jq,ivary] += dq0
dq_plus = ttv_elements!(n,t0big,hbig,tmaxbig,elementsbig,tt2,count2,zilch,0,0,big(rstar))
elementsbig[jq,ivary] -= 2dq0
dq_minus = ttv_elements!(n,t0big,hbig,tmaxbig,elementsbig,tt3,count2,zilch,0,0,big(rstar))
#xm,vm = init_nbody(elements,t0,n_body)
for i=2:n
for k=1:count2[i]
# Compute double-sided derivative for more accuracy:
dtdelements0_num[i,k,iq,jq] = (tt2[i,k]-tt3[i,k])/(2.*dq0)
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[i,k,iq,jq] = true
end
end
end
end
end
#println("Max diff dtdelements: ",maximum(abs.(dtdelements0[mask]./dtdelements0_num[mask]-1.0)))
println("Max diff asinh(dtdelements): ",maximum(abs.(asinh.(dtdelements0[mask])-asinh.(dtdelements0_num[mask]))))
#ntot = 0
#diff_dtdelements0 = zeros(n,maximum(ntt),7,n)
#for i=1:n, j=1:count[i], k=1:7, l=2:n
# diff_dtdelements0[i,j,k,l] = abs(dtdelements0[i,j,k,l]-convert(Float64,dtdelements0_num[i,j,k,l]))
# ntot +=1
#end
#using PyPlot
#
#nderiv = n^2*7*maximum(ntt)
##mask[:,:,2,:] = false
#loglog(abs.(reshape(dtdelements0,nderiv)),abs.(reshape(convert(Array{Float64,4},dtdelements0_num),nderiv)),".")
#axis([1e-6,1e2,1e-12,1e2])
#loglog(abs.(reshape(dtdelements0,nderiv)),abs.(reshape(diff_dtdelements0,nderiv)),".")
#println("Maximum error: ",maximum(diff_dtdelements0))
using PyPlot
# Make a plot of the fractional errors:
for i=2:n, k=1:7, l=1:n
if maximum(abs.(dtdelements0_num[i,2:count1[i],k,l])) > 0
loglog(tt[i,2:count1[i]]-tt[i,1],abs.(dtdelements0[i,2:count1[i],k,l]./dtdelements0_num[i,2:count1[i],k,l]-1.))
end
end
clf()
# Plot the difference in the TTVs:
for i=2:n
diff1 = abs.(tt1[i,2:count1[i]]./tt_big[i,2:count1[i]]-1.0);
loglog(tt[i,2:count1[i]]-tt[i,1],diff1);
end
for i=2:n, k=1:7, l=1:n
if maximum(abs.(dtdelements0_num[i,2:count1[i],k,l])) > 0 && k != 5 && k != 6
diff1 = abs.(dtdelements0[i,2:count1[i],k,l]./dtdelements0_num[i,2:count1[i],k,l]-1.);
diff2 = abs.(asinh.(dtdelements0[i,2:count1[i],k,l])-asinh.(dtdelements0_num[i,2:count1[i],k,l]));
loglog(tt[i,2:count1[i]]-tt[i,1],diff1);
# loglog(tt[i,2:count1[i]]-tt[i,1],diff2,".");
println(i," ",k," ",l," frac error: ",convert(Float64,maximum(diff1))," asinh error: ",convert(Float64,maximum(diff2))); #read(STDIN,Char);
end
end
# Plot a line that scales as time^{3/2}:
loglog([1.0,1024.0],1e-09*[1,2^15],":")
loglog([1.0,1024.0],1e-12*[1,2^15],":")
loglog([1.0,1024.0],1e-15*[1,2^15],":")
#@test isapprox(dtdelements0[mask],dtdelements0_num[mask];norm=maxabs)
@test isapprox(asinh.(dtdelements0[mask]),asinh.(dtdelements0_num[mask]);norm=maxabs)
#unit = ones(dtdelements0[mask])
#@test isapprox(dtdelements0[mask]./dtdelements0_num[mask],unit;norm=maxabs)
#end
## Make a plot of some TTVs:
#
#fig,axes = subplots(4,2)
#
#for i=2:8
# ax = axes[i-1]
# fn = zeros(Float64,2,count1[i])
# sig = ones(count1[i])
# tti1 = tt1[i,1:count1[i]]
# tti2 = tt2[i,1:count2[i]]
# for j=1:count1[i]
# fn[1,j] = 1.0
# fn[2,j] = round(Int64,(tti1[j]-elements[i,3])/elements[i,2])
# end
# coeff,cov = regress(fn,tti1,sig)
# tt_ref1 = coeff[1]+coeff[2]*fn[2,:]
# ttv1 = (tti1-tt_ref1)*24.*60.
# coeff,cov = regress(fn,tti2,sig)
# tt_ref2 = coeff[1]+coeff[2]*fn[2,:]
# ttv2 = (tti2-tt_ref2)*24.*60.
# ax[:plot](tti1,ttv1)
## ax[:plot](tti2,ttv2)
# ax[:plot](tti2,((ttv1-ttv2)-mean(ttv1-ttv2)))
# println(i," ",coeff," ",elements[i,2:3]," ",coeff[1]-elements[i,3]," ",coeff[2]-elements[i,2])
# println(i," ",maximum(ttv1-ttv2-mean(ttv1-ttv2))*60.," sec ", minimum(ttv1-ttv2-mean(ttv1-ttv2))*60.," sec" )
#end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 6022 |
using JLD2
#include("../src/ttv.jl")
#include("/Users/ericagol/Computer/Julia/regress.jl")
@testset "ttvbv_cartesian" begin
# This routine takes derivative of transit times, sky velocity &
# impact parameter squared with respect to the initial cartesian coordinates of bodies. [x]
#n = 8
n = 3
H =[3,1,1]
t0 = 7257.93115525-7300.0
#h = 0.12
h = 0.04
#h = 0.02
#tmax = 600.0
#tmax = 1000.0
#tmax = 100.0
tmax = 10.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
elements[:,3] .-= 7300.0
# Make an array, tt, to hold transit times:
# First, though, make sure it is large enough:
ntt = zeros(Int64,n)
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
println("ntt: ",ntt)
ntbv = 3
ttbv = zeros(ntbv,n,maximum(ntt))
ttbv1 = zeros(ntbv,n,maximum(ntt))
ttbv2 = zeros(ntbv,n,maximum(ntt))
ttbv3 = zeros(ntbv,n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
count1 = zeros(Int64,n)
# Call the ttv function:
rstar = 1e12
dq = ttvbv_elements!(H,t0,h,tmax,elements,ttbv1,count1,0.0,0,0,rstar)
# Now call with half the timestep:
count2 = zeros(Int64,n)
count3 = zeros(Int64,n)
dq = ttvbv_elements!(H,t0,h/2,tmax,elements,ttbv2,count2,0.0,0,0,rstar)
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtbvdq0 = zeros(ntbv,n,maximum(ntt),7,n)
dtbvdelements = ttvbv_elements!(H,t0,h,tmax,elements,ttbv,count,dtbvdq0,rstar)
# Compute derivatives numerically:
# Compute the numerical derivative:
dtbvdq0_num = zeros(BigFloat,ntbv,n,maximum(ntt),7,n)
dlnq = big(1e-15)
hbig = big(h); t0big = big(t0); tmaxbig=big(tmax); ttbv2big = big.(ttbv2); ttbv3big = big.(ttbv3)
for jq=1:n
for iq=1:7
elements2 = big.(elements)
dq_plus = ttvbv_elements!(H,t0big,hbig,tmaxbig,elements2,ttbv2big,count2,dlnq,iq,jq,big(rstar))
elements3 = big.(elements)
dq_minus = ttvbv_elements!(H,t0big,hbig,tmaxbig,elements3,ttbv3big,count3,-dlnq,iq,jq,big(rstar))
for i=1:n
for k=1:count2[i]
# Compute double-sided derivative for more accuracy:
for itbv=1:ntbv
dtbvdq0_num[itbv,i,k,iq,jq] = (ttbv2big[itbv,i,k]-ttbv3big[itbv,i,k])/(dq_plus-dq_minus)
end
# println(i," ",k," ",iq," ",jq," ",tt2big[i,k]," ",tt3big[i,k]," ")
end
end
end
end
nbad = 0
ntot = 0
diff_dtbvdq0 = zeros(ntbv,n,maximum(ntt),7,n)
mask = zeros(Bool, size(dtbvdq0))
for i=2:n, j=1:count[i], k=1:7, l=1:n
for itbv=1:ntbv
if abs(dtbvdq0[itbv,i,j,k,l]-dtbvdq0_num[itbv,i,j,k,l]) > 0.1*abs(dtbvdq0[itbv,i,j,k,l]) && ~(abs(dtbvdq0[itbv,i,j,k,l]) == 0.0 && abs(dtbvdq0_num[itbv,i,j,k,l]) < 1e-3)
nbad +=1
end
diff_dtbvdq0[itbv,i,j,k,l] = abs(dtbvdq0[itbv,i,j,k,l]-dtbvdq0_num[itbv,i,j,k,l])
if k != 2 && k != 5
mask[itbv,i,j,k,l] = true
end
ntot +=1
end
end
ttbv_big = big.(ttbv); elementsbig = big.(elements); rstarbig = big(rstar)
dqbig = ttvbv_elements!(H,t0big,hbig,tmaxbig,elementsbig,ttbv_big,count,big(0.0),0,0,rstarbig)
# Now halve the time steps:
ttbv_big_half = copy(ttbv_big)
dqbig = ttvbv_elements!(H,t0big,hbig/2,tmaxbig,elementsbig,ttbv_big_half,count1,big(0.0),0,0,rstarbig)
# Compute the derivatives in BigFloat precision to see whether finite difference
# derivatives or Float64 derivatives are imprecise at the start:
dtbvdq0_big = zeros(BigFloat,ntbv,n,maximum(ntt),7,n)
hbig = big(h); ttbv_big = big.(ttbv); elementsbig = big.(elements); rstarbig = big(rstar)
dtbvdelements_big = ttvbv_elements!(H,t0big,hbig,tmaxbig,elementsbig,ttbv_big,count,dtbvdq0_big,rstarbig)
#=
using PyPlot
clf()
# Plot the difference in the TTVs:
for i=2:3
# diff1 = abs.(tt1[i,2:count1[i]]./tt_big[i,2:count1[i]]-1.0);
for itbv=1:ntbv
diff1 = convert(Array{Float64,1},abs.(ttbv1[itbv,i,2:count1[i]].-ttbv_big[itbv,i,2:count1[i]])/elements[i,2]);
dtt=ttbv[itbv,i,2:count1[i]].-ttbv[itbv,i,1]
loglog(dtt,diff1);
end
# diff2 = abs.(tt2[i,2:count1[i]]./tt_big_half[i,2:count1[i]]-1.0);
# diff2 = abs.(tt2[i,2:count1[i]].-tt_big_half[i,2:count1[i]])/elements[i,2];
# loglog(tt[i,2:count[i]]-tt[i,1],diff2);
end
loglog([1.0,1024.0],2e-15*[1,2^15],":")
for i=2:3, k=1:7, l=1:3
for itbv=1:ntbv
if maximum(abs.(dtbvdelements_big[itbv,i,2:count[i],k,l])) > 0
diff1 = convert(Array{Float64,1},abs.(dtbvdelements_big[itbv,i,2:count[i],k,l]./dtbvdelements[itbv,i,2:count[i],k,l].-1));
diff3 = convert(Array{Float64,1},abs.(asinh.(dtbvdelements_big[itbv,i,2:count[i],k,l])-asinh.(dtbvdelements[itbv,i,2:count[i],k,l])));
dtt = ttbv[itbv,i,2:count[i]].-ttbv[itbv,i,1]
loglog(dtt,diff3);
println(itbv," ",i," ",k," ",l," frac error: ",convert(Float64,maximum(diff1))," asinh error: ",convert(Float64,maximum(diff3))); #read(STDIN,Char);
end
if maximum(abs.(dtbvdq0_big[itbv,i,2:count[i],k,l])) > 0
diff1 = convert(Array{Float64,1},abs.(dtbvdq0[itbv,i,2:count[i],k,l]./dtbvdq0_big[itbv,i,2:count[i],k,l].-1.0));
diff3 = convert(Array{Float64,1},abs.(asinh.(dtbvdq0_big[itbv,i,2:count[i],k,l]).-asinh.(dtbvdq0[itbv,i,2:count[i],k,l])));
dtt = ttbv[itbv,i,2:count[i]].-ttbv[itbv,i,1]
loglog(dtt,diff3,linestyle=":");
println(itbv," ",i," ",k," ",l," frac error: ",convert(Float64,maximum(diff1))," asinh error: ",convert(Float64,maximum(diff3))); #read(STDIN,Char);
end
end
end
#mederror = zeros(size(ttbv))
#for i=2:3
# for j=1:count1[i]
# data_list = Float64[]
# for itbv=1:ntbv, k=1:7, l=1:3
# if abs(dtbvdq0_num[itbv,i,j,k,l]) > 0
# push!(data_list,abs(dtbvdq0[itbv,i,j,k,l]/dtbvdq0_num[itbv,i,j,k,l]-1.0))
# end
# mederror[itbv,i,j] = median(data_list)
# end
# end
#end
# Plot a line that scales as time^{3/2}:
loglog([1.0,1024.0],1e-12*[1,2^15],":",linewidth=3)
=#
println("Max diff asinh(dtbvdq0): ",maximum(abs.(asinh.(dtbvdq0_num[mask]).-asinh.(dtbvdq0[mask]))))
@test isapprox(asinh.(dtbvdq0[mask]),asinh.(convert(Array{Float64,5},dtbvdq0_num)[mask]);norm=maxabs)
#@save "test_ttbv.jld2" dtbvdq0 dtbvdq0_num
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 8446 |
#include("../src/ttv.jl")
#include("/Users/ericagol/Computer/Julia/regress.jl")
@testset "ttvbv_elements" begin
# This routine takes derivative of transit times, vsky & bsky^2 with respect
# to the initial orbital elements.
#n = 8
n = 3
H = [3,1,1]
n_body = n
t0 = 7257.93115525-7300.0
#h = 0.12
h = 0.04
#tmax = 600.0
#tmax = 800.0
#tmax = 1000.0
tmax = 10.0
# Read in initial conditions:
elements = readdlm("elements.txt",',')
elements[:,3] .-= 7300.0
# Make masses of planets bigger
#elements[2,1] *= 10.0
#elements[3,1] *= 10.0
ntt = zeros(Int64,n)
# Make an array, ttbv, to hold transit times, vsky & b^2:
# First, though, make sure it is large enough:
for i=2:n
ntt[i] = ceil(Int64,tmax/elements[i,2])+3
end
dtbvdq0 = zeros(3,n,maximum(ntt),7,n)
ttbv = zeros(3,n,maximum(ntt))
ttbv1 = zeros(3,n,maximum(ntt))
ttbv2 = zeros(3,n,maximum(ntt))
ttbv3 = zeros(3,n,maximum(ntt))
ttbv4 = zeros(3,n,maximum(ntt))
ttbv8 = zeros(3,n,maximum(ntt))
# Save a counter for the actual number of transit times of each planet:
count = zeros(Int64,n)
count1 = zeros(Int64,n)
# Call the ttv function:
rstar = 1e12
dq = ttvbv_elements!(H,t0,h,tmax,elements,ttbv1,count1,0.0,0,0,rstar)
# Now call with half the timestep:
count2 = zeros(Int64,n)
count3 = zeros(Int64,n)
dq = ttvbv_elements!(H,t0,h/10.,tmax,elements,ttbv2,count2,0.0,0,0,rstar)
mask = zeros(Bool, size(dtbvdq0))
for itbv=1:3, jq=1:n_body
for iq=1:7
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
for i=2:n
for k=1:count2[i]
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[itbv,i,k,iq,jq] = true
end
end
end
end
end
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtbvdelements0 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements0 = ttvbv_elements!(H,t0,h,tmax,elements,ttbv,count,dtbvdq0,rstar)
dtbvdq2 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements2 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements2 = ttvbv_elements!(H,t0,h/2.,tmax,elements,ttbv2,count,dtbvdq2,rstar)
dtbvdq4 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements4 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements4 = ttvbv_elements!(H,t0,h/4.,tmax,elements,ttbv4,count,dtbvdq4,rstar)
dtbvdq8 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements8 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements8 = ttvbv_elements!(H,t0,h/8.,tmax,elements,ttbv8,count,dtbvdq8,rstar)
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdelements0[mask])-asinh.(dtbvdelements2[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdq0)-asinh.(dtbvdq2))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdelements2[mask])-asinh.(dtbvdelements4[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdq2)-asinh.(dtbvdq4))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdelements4[mask])-asinh.(dtbvdelements8[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdq4)-asinh.(dtbvdq8))))
# Compute derivatives numerically:
#nq = 15
# This "summarizes" best numerical derivative:
dtbvdelements0_num = zeros(BigFloat,3,n,maximum(ntt),7,n)
# Compute derivatives with BigFloat for additional precision:
elements0 = copy(elements)
dq0 = big(1e-10)
t0big = big(t0); tmaxbig = big(tmax); hbig = big(h)
zilch = big(0.0)
# Compute the transit times in BigFloat precision:
ttbv_big = big.(ttbv); elementsbig = big.(elements0); rstarbig = big(rstar)
dqbig = ttvbv_elements!(H,t0big,hbig,tmaxbig,elementsbig,ttbv_big,count,big(0.0),0,0,rstarbig)
mask = zeros(Bool, size(dtbvdq0))
for itbv=1:3, jq=1:n_body
for iq=1:7
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
for i=2:n
for k=1:count2[i]
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[itbv,i,k,iq,jq] = true
end
end
end
end
end
# Now, compute derivatives (with respect to initial cartesian positions/masses):
dtbvdelements0 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements0 = ttvbv_elements!(H,t0,h,tmax,elements,ttbv,count,dtbvdq0,rstar)
dtbvdq2 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements2 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements2 = ttvbv_elements!(H,t0,h/2.,tmax,elements,ttbv2,count,dtbvdq2,rstar)
dtbvdq4 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements4 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements4 = ttvbv_elements!(H,t0,h/4.,tmax,elements,ttbv4,count,dtbvdq4,rstar)
dtbvdq8 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements8 = zeros(3,n,maximum(ntt),7,n)
dtbvdelements8 = ttvbv_elements!(H,t0,h/8.,tmax,elements,ttbv8,count,dtbvdq8,rstar)
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdelements0[mask])-asinh.(dtbvdelements2[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdq0)-asinh.(dtbvdq2))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdelements2[mask])-asinh.(dtbvdelements4[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdq2)-asinh.(dtbvdq4))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdelements4[mask])-asinh.(dtbvdelements8[mask]))))
println("Maximum error on derivative: ",maximum(abs.(asinh.(dtbvdq4)-asinh.(dtbvdq8))))
# Compute derivatives numerically:
#nq = 15
# This "summarizes" best numerical derivative:
dtbvdelements0_num = zeros(BigFloat,3,n,maximum(ntt),7,n)
# Compute derivatives with BigFloat for additional precision:
elements0 = copy(elements)
dq0 = big(1e-10)
ttbv2 = big.(ttbv2)
ttbv3 = big.(ttbv3)
t0big = big(t0); tmaxbig = big(tmax); hbig = big(h)
zilch = big(0.0)
# Compute the transit times in BigFloat precision:
ttbv_big = big.(ttbv); elementsbig = big.(elements0)
# Now, compute derivatives numerically:
for jq=1:n_body
for iq=1:7
elementsbig = big.(elements0)
if iq == 7; ivary = 1; else; ivary = iq+1; end # Shift mass variation to end
elementsbig[jq,ivary] += dq0
dq_plus = ttvbv_elements!(H,t0big,hbig,tmaxbig,elementsbig,ttbv2,count2,zilch,0,0,big(rstar))
elementsbig[jq,ivary] -= 2dq0
dq_minus = ttvbv_elements!(H,t0big,hbig,tmaxbig,elementsbig,ttbv3,count2,zilch,0,0,big(rstar))
#xm,vm = init_nbody(elements,t0,n_body)
for i=2:n
for k=1:count2[i]
# Compute double-sided derivative for more accuracy:
for itbv=1:3
dtbvdelements0_num[itbv,i,k,iq,jq] = (ttbv2[itbv,i,k]-ttbv3[itbv,i,k])/(2dq0)
# Ignore inclination & longitude of nodes variations:
if iq != 5 && iq != 6 && ~(jq == 1 && iq < 7) && ~(jq == i && iq == 7)
mask[itbv,i,k,iq,jq] = true
end
end
end
end
end
end
println("Max diff asinh(dtbvdelements): ",maximum(abs.(asinh.(dtbvdelements0[mask])-asinh.(dtbvdelements0_num[mask]))))
#=
using PyPlot
# Make a plot of the fractional errors:
for itbv=1:3, i=2:3, k=1:7, l=1:3
if maximum(abs.(dtbvdelements0_num[itbv,i,2:count1[i],k,l])) > 0
loglog(ttbv[itbv,i,2:count1[i]].-ttbv[itbv,i,1],convert(Array{Float64,1},abs.(dtbvdelements0[itbv,i,2:count1[i],k,l]./dtbvdelements0_num[itbv,i,2:count1[i],k,l].-1.)))
end
end
clf()
# Plot the difference in the TTVs:
for itbv=1:3, i=2:3
diff1 = convert(Array{Float64,1},abs.(ttbv1[itbv,i,2:count1[i]]./ttbv_big[itbv,i,2:count1[i]].-1.0));
loglog(ttbv[itbv,i,2:count1[i]].-ttbv[itbv,i,1],diff1);
end
for itbv=1:3, i=2:3, k=1:7, l=1:3
if maximum(abs.(dtbvdelements0_num[itbv,i,2:count1[i],k,l])) > 0 && k != 5 && k != 6
diff1 = convert(Array{Float64,1},abs.(dtbvdelements0[itbv,i,2:count1[i],k,l]./dtbvdelements0_num[itbv,i,2:count1[i],k,l].-1));
diff2 = convert(Array{Float64,1},abs.(asinh.(dtbvdelements0[itbv,i,2:count1[i],k,l])-asinh.(dtbvdelements0_num[itbv,i,2:count1[i],k,l])));
loglog(ttbv[itbv,i,2:count1[i]].-ttbv[itbv,i,1],diff1);
println(i," ",k," ",l," frac error: ",convert(Float64,maximum(diff1))," asinh error: ",convert(Float64,maximum(diff2))); #read(STDIN,Char);
end
end
# Plot a line that scales as time^{3/2}:
loglog([1.0,1024.0],1e-09*[1,2^15],":")
loglog([1.0,1024.0],1e-12*[1,2^15],":")
loglog([1.0,1024.0],1e-15*[1,2^15],":")
=#
@test isapprox(asinh.(dtbvdelements0[mask]),asinh.(dtbvdelements0_num[mask]);norm=maxabs)
dtbvdelements0_num = convert(Array{Float64,5},dtbvdelements0_num)
#@save "ttvbv_elements.jld2" dtbvdelements0 dtbvdelements0_num ttbv
end
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | code | 3763 |
clf()
nmed = 10
for i=2:3, k=1:7, l=1:3
if maximum(abs.(dtdq0[i,2:count[i],k,l])) > 0
# diff1 = abs.(asinh.(dtdq0_big[i,2:count[i],k,l])-asinh.(dtdq0[i,2:count[i],k,l]));
# diff1 = abs.(dtdq0_big[i,2:count[i],k,l]-dtdq0[i,2:count[i],k,l])/maximum(dtdq0[i,2:count[i],k,l]);
diff1 = abs.(dtdq0_big[i,2:count[i],k,l]-dtdq0[i,2:count[i],k,l])
diff2 = copy(diff1);
diff3 = abs.(dtdelements_big[i,2:count[i],k,l]-dtdelements_mixed[i,2:count[i],k,l])
# diff3 = abs.(asinh.(dtdelements_big[i,2:count[i],k,l])-asinh.(dtdelements_mixed[i,2:count[i],k,l]))
diff4 = copy(diff3);
ntt1 = size(diff1)[1];
for it=nmed:ntt1-nmed
# Divide by a median smoothed dtdq0:
diff2[it] = diff1[it]/maximum(abs.(dtdq0[i,it+1-nmed+1:it+1+nmed,k,l]))
maxit = maximum(abs.(dtdelements_mixed[i,it+1-nmed+1:it+1+nmed,k,l]))
if maxit > 0
diff4[it] = diff3[it]/maximum(abs.(dtdelements_mixed[i,it+1-nmed+1:it+1+nmed,k,l]))
end
end;
diff2[1:nmed-1] .= diff2[nmed]; diff2[ntt1-nmed+1:ntt1] .= diff2[ntt1-nmed];
diff4[1:nmed-1] .= diff4[nmed]; diff4[ntt1-nmed+1:ntt1] .= diff4[ntt1-nmed];
# diff3 = abs.(asinh.(dtdq2_big[i,2:count[i],k,l])-asinh.(dtdq2[i,2:count[i],k,l]));
loglog(tt[i,2:count[i]]-tt[i,1],diff2,linestyle=":");
loglog(tt[i,2:count[i]]-tt[i,1],diff4,linestyle="--");
# loglog(tt[i,2:count[i]]-tt[i,1],diff3);
println("xvs: ",i," ",k," ",l," asinh error h : ",convert(Float64,maximum(diff2))); #read(STDIN,Char);
println("els: ",i," ",k," ",l," asinh error h : ",convert(Float64,maximum(diff4))); #read(STDIN,Char);
# println(i," ",k," ",l," asinh error h/2: ",convert(Float64,maximum(diff3))); #read(STDIN,Char);
end
end
loglog([1.0,40000.0],0.5e-16*([1.0,40000.0]/h).^1.5)
clf()
nmed = 10
for i=2:3, k=1:7, l=1:3
if maximum(abs.(dtdq0[i,2:count[i],k,l])) > 0
diff1 = abs.(asinh.(dtdq0_big[i,2:count[i],k,l])-asinh.(dtdq0[i,2:count[i],k,l]));
diff3 = abs.(asinh.(dtdelements_big[i,2:count[i],k,l])-asinh.(dtdelements_mixed[i,2:count[i],k,l]))
loglog(tt[i,2:count[i]]-tt[i,1],diff1,linestyle=":");
loglog(tt[i,2:count[i]]-tt[i,1],diff3,linestyle="--");
println("xvs: ",i," ",k," ",l," asinh error h : ",convert(Float64,maximum(diff1))); #read(STDIN,Char);
println("els: ",i," ",k," ",l," asinh error h : ",convert(Float64,maximum(diff3))); #read(STDIN,Char);
end
end
loglog([1.0,40000.0],0.5e-16*([1.0,40000.0]/h).^1.5)
@inbounds for i=1:n, j=1:count[i]
@inbounds for k=1:n, l=1:7; dtdelements_mixed[i,j,l,k] = 0.0
@inbounds for p=1:n, q=1:7
dtdelements_mixed[i,j,l,k] += dtdq0[i,j,q,p]*convert(Float64,jac_init_big[(p-1)*7+q,(k-1)*7+l])
end
end
end
dtdelements_mixed_big = copy(dtdelements_big)
@inbounds for i=1:n, j=1:count[i]
@inbounds for k=1:n, l=1:7; dtdelements_mixed_big[i,j,l,k] = 0.0
@inbounds for p=1:n, q=1:7
dtdelements_mixed_big[i,j,l,k] += dtdq0_big[i,j,q,p]*jac_init_big[(p-1)*7+q,(k-1)*7+l]
end
end
end
clf()
nmed = 10
for i=2:3, k=1:7, l=1:3
if maximum(abs.(dtdq0[i,2:count[i],k,l])) > 0
diff1 = abs.(dtdq0_big[i,2:count[i],k,l]-dtdq0[i,2:count[i],k,l])/median(abs.(dtdq0[i,2:count[i],k,l]))
loglog(tt[i,2:count[i]]-tt[i,1],diff1,linestyle=":");
println("xvs: ",i," ",k," ",l," asinh error h : ",convert(Float64,maximum(diff1))); #read(STDIN,Char);
end
if maximum(abs.(dtdelements[i,2:count[i],k,l])) > 0
diff3 = abs.(dtdelements_big[i,2:count[i],k,l]-dtdelements[i,2:count[i],k,l])/median(abs.(dtdelements[i,2:count[i],k,l]));
loglog(tt[i,2:count[i]]-tt[i,1],diff3,linestyle="--");
println("els: ",i," ",k," ",l," asinh error h : ",convert(Float64,maximum(diff3))); #read(STDIN,Char);
end
end
loglog([1.0,40000.0],0.5e-16*([1.0,40000.0]/h).^1.5)
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | docs | 1019 | # NbodyGradient
[](https://github.com/ericagol/NbodyGradient.jl/actions/workflows/NbodyGradient.yml)
[](https://arxiv.org/abs/2106.02188)
[](https://ericagol.github.io/NbodyGradient.jl/dev)
A set of Julia routines for computing gradients of N-body integrations.
Under development by Eric Agol, David Hernandez and Zach Langford
License: If using in publications, please cite [Agol, Hernandez & Langford (2021)](https://arxiv.org/abs/2106.02188).
Paper: See orange button above or go to the [paper repository](https://github.com/langfzac/nbg-papers).
Documentation: See blue button above.
Thanks to NASA, NSF and the Guggenheim Foundation for supporting this work.
Here is an introduction at the NASA Exoplanet Modeling and Analysis Center (EMAC):
https://www.youtube.com/watch?v=VXnxDnIBHog
| NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | docs | 652 | # API
## Types
### Initial Conditions
```@docs
CartesianIC
Elements
Elements(m::T,P::T,t0::T,ecosϖ::T,esinϖ::T,I::T,Ω::T) where T<:Real
ElementsIC
ElementsIC(t0::T, H::Matrix{<:Real}, elems::Elements{T}...) where T<:AbstractFloat
```
### State
```@docs
State{T<:AbstractFloat}
State(ic::InitialConditions{T}) where T<:AbstractFloat
```
### Integrator
```@docs
Integrator{T<:AbstractFloat}
```
### TransitTiming
```@docs
TransitParameters{T<:AbstractFloat}
TransitParameters(tmax::T,ic::ElementsIC{T},ti::Int64=1) where T<:AbstractFloat
TransitTiming{T<:AbstractFloat}
TransitTiming(tmax::T,ic::ElementsIC{T},ti::Int64=1) where T<:AbstractFloat
``` | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | docs | 4182 | # Basic Usage
Here we'll walk through an example of integrating a 3-body system.
##### Units
A quick note on the units used throughout the code.
- Distance: AU
- Time: Days
- Mass: Solar Masses
- Angles: Radians
### Initial Conditions
First, we define the orbital elements of the system. This can be done by creating [`Elements`](@ref) for each body in the system.
Start with a 1 solar mass star
```@example 1
using NbodyGradient
a = Elements(m = 1.0);
nothing # hide
```
We then define the orbital elements for second body, say an Earth analogue.
```@example 1
b = Elements(
m = 3e-6, # Mass [Solar masses]
t0 = 0.0, # Initial time of transit [days]
P = 365.256, # Period [days]
ecosω = 0.01, # Eccentricity * cos(Argument of Periastron)
esinω = 0.0, # Eccentricity * sin(Argument of Periastron)
I = π/2, # Inclination [Radians]
Ω = 0.0 # Longitude of Ascending Node [Radians]
);
nothing # hide
```
(`ecosω` can be typed as `ecos\omega` and then hitting tab)
Next we'll create a Jupiter analogue for the final body. Here the orbital elements are specified for the Keplerian ((a,b),c), or c orbiting the center of mass of a and b. (While this might not need to be stated explicitly here, this convention is useful for more complicated hierarchical systems).
```@example 1
c = Elements(
m = 9.54e-4,
P = 4332.59,
ecosω = 0.05,
I = π/2
);
nothing # hide
```
Here, we can simply omit any orbital elements which are zero. Unspecified elements are set to zero by default.
Now we need to pass our [`Elements`](@ref) to [`ElementsIC`](@ref).
```@example 1
t0 = 0.0 # Initial time
N = 3 # Number of bodies
ic = ElementsIC(t0,N,a,b,c)
```
Finally, we can pass the initial conditions to [`State`](@ref), which converts orbital elements to cartesian coordinates (and calculates the derivatives with respect to the initial conditions).
```@example 1
s = State(ic);
nothing # hide
```
The positions and velocities can be accessed by `s.x` and `s.v`, respectively. Each matrix contains the vector component (rows) for a particular body (columns).
```@example 1
s.x
```
### Integration
Now that we have initial conditions, we can construct and run the integrator. First, define an [`Integrator`](@ref), specifying the integration scheme, the time step, and final time. We'll use the `ahl21!` mapping.
```@example 1
h = b.P/30.0 # We want at most 1/20th of the smallest period for a time step
tmax = 5*c.P # Integrate for 5 orbital periods of the outer body
intr = Integrator(ahl21!,h,tmax);
nothing # hide
```
!!! note "A quick aside on constructors"
The types in NbodyGradient.jl have a number of constructors that enable to user to write as terse or as verbose code as they would like. For example, the above `Integrator` construction could specify each field as `Integrator(scheme, h, t0, tmax)` (see [`Integrator`](@ref) for argument definitions), or only the time step and integration time as `Integrator(h,tmax)`. In the latter case, the default value for `scheme` and `t0` are `ahl21!` and `0`, respectively. If you're coming from [Agol, Hernandez, and Langford (2021)](https://ui.adsabs.harvard.edu/abs/2021arXiv210602188A/abstract) you'll notice some discrepancy in the examples due to this.
Finally, run the [`Integrator`](@ref) by passing it the [`State`](@ref).
```@example 1
intr(s)
s.x # Show final positions
```
This integrates from `s.t` to `s.t+tmax`, steping by `h`. If you'd rather step a certain number of time steps:
```@example 1
N = 1000
intr(s,N)
```
!!! note "Re-running simulations"
If you want to run the integration from the initial condtions again, you must 'reset' the [`State`](@ref). I.e. run `s = State(ic)`. Otherwise, the integration will begin from what ever `s.t` is currently equal to, and with those coordinates.
### Transit Timing
If we wish to compute transit times, we need only to pass a [`TransitTiming`](@ref)structure to the [`Integrator`](@ref).
```@example 1
s = State(ic) # Reset to the initial conditions
tt = TransitTiming(tmax, ic)
intr(s,tt)
```
To see the first 5 transit times of our second body about the first body, run:
```@example 1
tt.tt[2,1:5]
``` | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | docs | 2259 | # Gradients
The main purpose of developing NbodyGradient.jl is to provide a differentiable N-body model for gradient-based optimization. Here, we walk though computing and accessing the jacobian of the transit times with respect to the initial orbital elements and masses.
We assume you've taken a look at the [Basic Usage](@ref) tutorial, and are familiar with the orbital elements and units used in NbodyGradient.jl.
!!! note "No gradient support for exactly circular orbits"
This package supports specifying initial conditions for circular orbits (ie. eccentricity=0). However, the derivative computations contain 1/e terms -- requiring a non-zero eccentricity to be computed correctly. We expect the need for derivatives for exactly circular initial orbits to be minimal, and intend to implement them in the future.
Here, we will specify the orbital elements using the 'elements matrix' option (See [`ElementsIC`](@ref)).
```@example 2
using NbodyGradient
# Initial Conditions
elements = [
# m P t0 ecosω esinω I Ω
1.0 0.0 0.0 0.0 0.0 0.0 0.0; # Star
3e-6 365.256 0.0 0.01 0.0 π/2 0.0; # Earth analogue
]
ic = ElementsIC(0.0, 2, elements);
nothing # hide
```
Let's integrate for 5 periods of the planet and record the transit times.
```@example 2
s = State(ic)
P = elements[2,2] # Get the period from the elements matrix
tmax = 5 * P
tt = TransitTiming(5 * P, ic)
h = P/30.0
Integrator(h, tmax)(s, tt) # Run without creating an `Integrator` variable.
# Computed transit times
tt.tt
```
The derivatives of the transit times with respect to the initial orbitial elements and masses are held in the `dtdelements` field of the [`TransitTiming`](@ref) structure -- an `Array{T<:AbstractFloat,4}`. The indices correspond to the transiting body, transit number, orbital element, and body the orbital element is describing. For example, this is how to access the 'gradient' of the first transit time of the orbiting body:
```@example 2
tt.dtdelements[2,1,:,:]
```
Here, the first column is the derivative of the transit time with respect to the stars 'orbital elements', which are all zero except for the mass in the last row. The second column is the derivatives with respect to the orbital elements of the system. | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | docs | 1075 | # NbodyGradient
A fast, differentiable N-body integrator for modeling transiting exoplanets, and more.
This package provides a simple user-interface to carry out N-body simulations and compute the derivatives of the outputs with respect to the initial conditions. The current version of the code implements the following:
- Integrators:
- AHL21 (4th-order Symplectic; [Agol, Hernandez, & Langford 2021](https://github.com/langfzac/nbg-papers))
- Initial Conditions:
- Cartesian coordinates ([`CartesianIC`](@ref))
- Orbital elements ([`ElementsIC`](@ref))
- Output Models:
- Transit times ([`TransitTiming`](@ref))
- Transit times, impact parameter, and sky-plane velocity ([`TransitParameters`](@ref))
## Getting Started
First, you'll need to add the package. Using the Julia REPL, run:
```julia
pkg> add NbodyGradient
```
If you'd like to use the developement version of the code, run:
```julia
pkg> add NbodyGradient#master
```
Then, use like any other Julia package
```julia
using NbodyGradient
```
See the [Tutorials](@ref) page for basic usage. | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"MIT"
] | 0.2.1 | c335d4bf34bbdff2253cd0071e5a26dbf586d098 | docs | 66 | # Tutorials
```@contents
Pages = ["basic.md", "gradients.md"]
``` | NbodyGradient | https://github.com/ericagol/NbodyGradient.jl.git |
|
[
"CC0-1.0"
] | 0.1.1 | 8d72b728dacbe28ca31deeea9edfafd081c77010 | code | 144 | using Documenter, MixFit
makedocs(sitename="MixFit Documentation", modules = [MixFit])
deploydocs(repo = "github.com/the-sushi/MixFit.jl.git")
| MixFit | https://github.com/the-sushi/MixFit.jl.git |
|
[
"CC0-1.0"
] | 0.1.1 | 8d72b728dacbe28ca31deeea9edfafd081c77010 | code | 145 | module MixFit
using Statistics
include("special.jl")
include("distributions.jl")
include("mixutils.jl")
include("em.jl")
end
| MixFit | https://github.com/the-sushi/MixFit.jl.git |
|
[
"CC0-1.0"
] | 0.1.1 | 8d72b728dacbe28ca31deeea9edfafd081c77010 | code | 947 | export dnorm, dgumbel, dgamma, dlognorm
"""
dnorm(x::Real, μ::Real, σ::Real)
Normal distribution density function
"""
dnorm(x::Real, μ::Real, σ::Real) = exp(-0.5 * ((x - μ)/σ)^2)/(σ*sqrt2π)
"""
dgumbel(x::Real, μ::Real, σ::Real)
Gumbel density, parameterized by mean (μ) and SD (σ) of x.
"""
function dgumbel(x::Real, μ::Real, σ::Real)
β = (√6 * σ) / π
α = μ - (β*γ)
z = (x - α) / β
exp(-(z + exp(-z)))
end
"""
dgamma(x::Real, μ::Real, σ::Real)
Gamma density, parameterized by mean (μ) and sigma(σ) of x.
"""
function dgamma(x::Real, μ::Real, σ::Real)
α = μ^2 / σ^2
β = μ / σ^2
(x^(α - 1) * exp(-β * x)) * (β^α / Γ(α))
end
"""
dlognorm(x::Real, μ::Real, σ::Real)
Lognormal density, parameterized by mean (μ) and SD (σ) of x, NOT of log(x).
"""
function dlognorm(x::Real, μ::Real, σ::Real)
lμ = log(μ^2 / sqrt(1 + σ^2 / μ^2))
lσ = √(log(1 + σ^2 / μ^2))
dnorm(log(x), lμ, lσ) / x
end
| MixFit | https://github.com/the-sushi/MixFit.jl.git |
|
[
"CC0-1.0"
] | 0.1.1 | 8d72b728dacbe28ca31deeea9edfafd081c77010 | code | 6212 | export em_step!, em_run!, mixfit, densfit
"""
em_step!(est::MixModel, x::Vector{<:Real})
Run a single EM step.
See also: [`em_run!`](@ref), [`mixfit`](@ref)
"""
function em_step!(est::MixModel, x::Vector{<:Real})
p = Matrix{Float32}(undef, length(est.μ), length(x))
for i = 1:length(est.μ)
p[i,:] = est.α[i] * dnorm.(x, est.μ[i], est.σ[i]) ./
sum(est.α[j] * dnorm.(x, est.μ[j], est.σ[j]) for j=1:length(est.μ))
end
for i = 1:length(est.μ)
est.μ[i] = sum(p[i,:] .* x) / sum(p[i,:])
est.σ[i] = √(sum(p[i,:] .* (x .- est.μ[i,:]).^2) / sum(p[i,:]))
est.α[i] = mean(p[i,:])
end
end
"""
em_run!(est::MixModel, x::Vector{<:Real}, rtol::AbstractFloat = 0.00001, maxiter::Int = 0)
Run EM steps until the percent increase in log-likelihood is below `rtol` or the number of iterations is greater than `maxiter`.
If `maxiter` is set to zero, EM steps will continue until the increase is below `rtol` regardless of the number of iterations.
See also: [`em_run!`](@ref), [`mixfit`](@ref)
"""
function em_run!(est::MixModel, x::Vector{<:Real}, rtol::AbstractFloat = 0.00001, maxiter::Int = 0)
ll::Float32 = LL(x, est)
oll::Float32 = -ll
i::Int = 1
while true
em_step!(est, x)
oll = ll
ll = LL(x, est)
if abs((oll - ll) / oll) < rtol
break
end
if i == maxiter
@warn "Hit maximum number of iterations"
end
i += 1
end
end
"""
mixfit(x::Vector{<:Real},
m::Int;
rtol::AbstractFloat = 0.00001,
α::Vector{<:Real} = fill(1/m, m),
μ::Vector{<:Real} = quantile!(x, (1:m)/m),
σ::Vector{<:Real} = fill(std(x) / √(m), m),
maxswap::Int = 5 * m^2,
maxiter_inner::Int = 0,
maxiter::Int = 0,
silent::Bool = false,
kernel::Function = dnorm)
Get the maximum likelihood estimate of an `m`-component mixture model
using random-swap EM. Random-swap EM avoids local optimums by randomly
replacing components and using the result with the maximum likelihood [^1].
The component distributions are given by `kernel`. The maximum number of swaps
is given by `maxswap`. If results vary across runs, then `maxswap` is too low -
the default is ``5m^2``. maxiter_inner is the maximum number of iterations for
the estimates that go through the swapping process, and maxiter is the maximum
for the final estimate. Similarly, `rtol` is for the final estimate, while the
inner estimates use 0.1. To supress output, simply set `silent` to true.
Starting values can be provided via the α, μ, and σ arguments, but this
shouldn't be necassary due to the use of random swapping.
[^1]: Zhao, Q., Hautamäki, V., Kärkkäinen, I., & Fränti, P. (2012). Random swap EM algorithm for Gaussian mixture models. Pattern Recognition Letters, 33(16), 2120-2126.
See also: [`densfit`](@ref), [`em_run!`](@ref)
"""
function mixfit(x::Vector{<:Real},
m::Int;
rtol::AbstractFloat = 0.00001,
t::Int = 0,
α::Union{Vector{<:Real}, Nothing} = nothing,
μ::Union{Vector{<:Real}, Nothing} = nothing,
σ::Union{Vector{<:Real}, Nothing} = nothing,
maxswap::Int = 0,
maxiter_inner::Int = 0,
maxiter::Int = 0,
silent::Bool = false,
kernel::Function = dnorm)
if maxswap == 0
maxswap = 5 * m^2
end
est = MixModel(fill(1/m, m), quantile!(x, (1:m)/m), fill(std(x) / √(m), m), kernel)
if μ != nothing
est.μ = μ
end
if σ != nothing
est.σ = σ
end
if α != nothing
est.α = α
end
em_run!(est, x, 0.1, maxiter_inner)
for i ∈ 1:maxswap
est_s = copy(est)
choice = rand(1:m)
est_s.μ[choice] = rand(x)
est_s.α = fill(1/m, m)
est_s.σ[choice] = std(x) / √(m)
em_run!(est_s, x, 0.1, maxiter_inner)
if LL(x, est_s) > LL(x, est)
est = est_s
end
end
em_run!(est, x, rtol, maxiter)
if silent == false
describe(est, data = x)
end
return est
end
"""
densfit(x::Vector{<:Real};
wait::Int = 3,
rtol_em::AbstractFloat = 0.00001,
criterion::Function = AIC,
silent::Bool = false,
maxiter::Int = 0,
maxiter_inner::Int = 0,
maxswap::Int = 0,
kernel::Function = dnorm)
Estimate the density of `x` by a mixture model. Successive mixture model estimates
are done via random swap EM with increasing number of clusters until `criterion`
decreases for 3 iterations. By default, `criterion` uses AIC, which performs
well for density estimation [^2]. However, AIC2 should be used instead if one
wants to actually estimate the number of clusters in a true mixture model.
The relative tolerance for EM convergence is given by `rtol_em`. To disable output, set `silent` to true.
[^2]: Wang, Y., & Chee, C. S. (2012). Density estimation using non-parametric and semi-parametric mixtures. Statistical Modelling, 12(1), 67-92.
See also: [`densfit`](@ref), [`em_run!`](@ref)
"""
function densfit(x::Vector{<:Real};
wait::Int = 3,
rtol_em::AbstractFloat = 0.00001,
criterion::Function = AIC,
silent::Bool = false,
maxiter::Int = 0,
maxiter_inner::Int = 0,
maxswap::Int = 0,
kernel::Function = dnorm)
new::MixModel = mixfit(x, 1, silent = true)
current::MixModel = new
m::Int = 2
nbad::Int = 0
while nbad < wait
new = mixfit(x, m,
silent = true,
maxiter = maxiter,
maxiter_inner = maxiter_inner,
maxswap = maxswap,
kernel = kernel)
if (criterion(x, new) >= criterion(x, current))
nbad += 1
else
nbad = 0
current = new
end
m += 1
end
if silent == false
describe(current, data = x)
end
return current
end
| MixFit | https://github.com/the-sushi/MixFit.jl.git |
|
[
"CC0-1.0"
] | 0.1.1 | 8d72b728dacbe28ca31deeea9edfafd081c77010 | code | 3274 | export MixModel, copy, LL, AIC, AIC3, BIC, describe
"""
Structure of mixture model parameters.
# Variables
- `α::Vector{Float32}`: Weights of the components
- `μ::Vector{Float32}`: Means of the components
- `σ::Vector{Float32}`: SDs of the components
"""
mutable struct MixModel
α::Vector{Float32}
μ::Vector{Float32}
σ::Vector{Float32}
kernel::Function
end
Base.copy(est::MixModel) = MixModel(est.α, est.μ, est.σ, est.kernel)
"""
LL(x::Vector{<:Real}, est::MixModel)
Get the log-likelihood of a mixture model detailed in `est`, using the data `x`.
See also: [`AIC`](@ref), [`AIC3`](@ref), [`BIC`](@ref)
"""
LL(x::Vector{<:Real}, est::MixModel) = sum(
log(sum(est.α .* est.kernel.(x[i], est.μ, est.σ)))
for i=1:length(x))
"""
AIC(x::Vector{<:Real}, est::MixModel)
Get the AIC of a mixture model, using the data `x`.
The AIC for a model ``M`` is given by:
`` AIC(M) = 2k - 2l(M)``
Where ``k`` is the number of parameters and ``l(M)`` is the log-likelihood.
See also: [`AIC3`](@ref), [`BIC`](@ref), [`LL`](@ref)
"""
AIC(x::Vector{<:Real}, est::MixModel) = 2*(3 * length(est.μ) - 1) - 2*LL(x, est)
"""
AIC3(x::Vector{<:Real}, est::MixModel)
Get the modified AIC, "AIC3", of a mixture model using the data `x`.
The AIC3 for a model ``M`` is given by [^3]:
`` AIC(M) = 3k - 2l(M)``
Where ``k`` is the number of parameters and ``l(M)`` is the log-likelihood.
[^3]: Bozdogan, H. (1994). Mixture-model cluster analysis using model selection criteria and a new informational measure of complexity. In Proceedings of the first US/Japan conference on the frontiers of statistical modeling: An informational approach (pp. 69-113). Springer, Dordrecht.
See also: [`AIC`](@ref), [`BIC`](@ref), [`LL`](@ref)
"""
AIC3(x::Vector{<:Real}, est::MixModel) = 3*(3 * length(est.μ) - 1) - 2*LL(x, est)
"""
BIC(x::Vector{<:Real}, est::MixModel)
Get the Bayesian Information Criterion of a mixture model using the data `x`.
The BIC for a model ``M`` is given by:
`` BIC(M) = log(n)k - 2l(M) ``
Where ``n`` is the sample size and ``l(M)`` is the log-likelihood
See also: [`AIC`](@ref), [`AIC3`](@ref), [`LL`](@ref)
"""
BIC(x::Vector{<:Real}, est::MixModel) = log(length(x))*(3 * length(est.μ) - 1) - 2*LL(x, est)
"""
describe(est::MixModel; data::Vector{<:Real})
Pretty-print the parameters and fit indicies for the mixture model `est`.
If `data` is not specified, fit indicies will not be printed.
"""
function describe(est::MixModel; data::Union{Vector{<:Real}, Nothing} = nothing)
if (data != nothing)
println(repeat('-', length("Log-likelihood: $(LL(data, est))")))
println("\nLog-likelihood: $(LL(data, est))")
println("AIC: $(AIC(data, est))")
println("AIC3: $(AIC3(data, est))")
println("BIC: $(BIC(data, est))\n")
else
println("------------------\n")
end
for i ∈ 1:length(est.α)
println("Component $i:")
println("\tα: $(est.α[i])")
println("\tμ: $(est.μ[i])")
println("\tσ: $(est.σ[i])\n")
end
if (data != nothing)
println(repeat('-', length("Log-likelihood: $(LL(data, est))")))
else
println("------------------")
end
end
| MixFit | https://github.com/the-sushi/MixFit.jl.git |
|
[
"CC0-1.0"
] | 0.1.1 | 8d72b728dacbe28ca31deeea9edfafd081c77010 | code | 247 | const log2π = log(2*π)
const sqrt2π = √(2*π)
const sqrtπ = √π
# Euler–Mascheroni constant
const γ = 0.577215665
# Ramanujan's approximation to the Γ function:
Γ(x::Real) = sqrtπ*((x-1)/exp(1))^(x-1) * (8*(x-1)^3 + 4*(x-1)^2 + (x-1) + 1/30)^(1/6)
| MixFit | https://github.com/the-sushi/MixFit.jl.git |
|
[
"CC0-1.0"
] | 0.1.1 | 8d72b728dacbe28ca31deeea9edfafd081c77010 | docs | 1941 | # MixFit.jl
[](http://creativecommons.org/publicdomain/zero/1.0/)
[](http://joshuapritsker.com/MixFit.jl/stable)
MixFit.jl is a Julia package for fitting finite mixture models, and for nonparametric density estimation via finite mixture models ([Wang & Chee, 2012](https://doi.org/10.1177/1471082X1001200104)). Models are fitted using random-swap expectation maximization ([Zhao, Hautamäki, Kärkkäinen, & Fränti, 2012](https://doi.org/10.1016/j.patrec.2012.06.017)), which avoids the problem of local optimums by randomly replacing components and using the final maximum. By default, MixFit.jl supports normal, gamma, lognormal, and gumbel mixtures, but it is easy to use your own density function instead. If you use this, it *would be nice* if you cited me, but I'm putting it under public domain so you can do whatever you want with it.
## Example
```
julia> using MixFit
julia> x = [randn(500); (randn(500).+3).*2]
1000-element Array{Float64,1}:
-0.3872542393168341
0.44218146773613404
-1.140006685489404
-0.11093365262262657
0.917287805330094
1.3997276699755827
⋮
3.860428712486353
4.924743765884938
4.767237225983121
3.6111782228201013
5.498455397469906
julia> densfit(x, criterion = AIC3)
----------------------------------
Log-likelihood: -2408.562390297034
AIC: 4827.124780594068
AIC3: 4832.124780594068
BIC: 4851.6635569889795
Component 1:
α: 0.5093992
μ: 0.07551261
σ: 1.0396444
Component 2:
α: 0.49060085
μ: 6.004384
σ: 2.0322912
----------------------------------
MixModel(Float32[0.5093992, 0.49060085], Float32[0.07551261, 6.004384], Float32[1.0396444, 2.0322912], MixFit.dnorm)
julia>
```
| MixFit | https://github.com/the-sushi/MixFit.jl.git |
|
[
"CC0-1.0"
] | 0.1.1 | 8d72b728dacbe28ca31deeea9edfafd081c77010 | docs | 219 | # MixFit.jl Documentation
## Model estimation
```@docs
MixModel
mixfit
densfit
em_run!
em_step!
```
## Model methods
```@docs
LL
AIC
AIC3
BIC
describe
```
## Distributions
```@docs
dnorm
dgumbel
dgamma
dlognorm
```
| MixFit | https://github.com/the-sushi/MixFit.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 303 | using BenchmarkTools
using Random
using MIToS.Utils
using MIToS.MSA
using MIToS.Information
const SUITE = BenchmarkGroup()
include("Utils/GeneralUtils.jl")
include("MSA/Residues.jl")
include("MSA/Annotations.jl")
include("Information/CorrectedMutualInformation.jl")
include("Information/Counters.jl")
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 506 | let msa = rand(Random.MersenneTwister(1), res"ARNDCQEGHILKMFPSTWYV-", 50, 50),
msa_large = msa[:, 1:10],
msa_wide = msa[1:10, :]
SUITE["Information"]["CorrectedMutualInformation"]["buslje09"]["msa"] =
@benchmarkable buslje09($msa)
SUITE["Information"]["CorrectedMutualInformation"]["buslje09"]["msa_large"] =
@benchmarkable buslje09($msa_large)
SUITE["Information"]["CorrectedMutualInformation"]["buslje09"]["msa_wide"] =
@benchmarkable buslje09($msa_wide)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 486 | let seq_a = rand(Random.MersenneTwister(37), res"ARNDCQEGHILKMFPSTWYV-", 500),
seq_b = rand(Random.MersenneTwister(73), res"ARNDCQEGHILKMFPSTWYV-", 500),
Na = ContingencyTable(Float64, Val{1}, UngappedAlphabet()),
Nab = ContingencyTable(Float64, Val{2}, UngappedAlphabet())
SUITE["Information"]["frequencies!"]["1"] = @benchmarkable frequencies!($Na, $seq_a)
SUITE["Information"]["frequencies!"]["2"] =
@benchmarkable frequencies!($Nab, $seq_a, $seq_b)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 4199 | # PF00501 in Pfam 30.0 has 3560 columns, 423 sin inserts
let seq = replace(
"""
........................................................................................
........................................................................................
.m-----.----...--.---..--..........................-------....-..-..-.....-....-....-...
......-....-....-....-.....-.......-........-..........-........-..............-....-...
............-........G..............V......E.............K.............G.........D.I....
...............I.G.......L....K..........G...................R....N........V............
.P......E..............W.....L.........I..A......D.L.......G..V...Q.........M.....A.....
..........G...G......C....S.....L.....N......L.P.Y......................................
........Q.Q..K.E..................E...I.....M...V...D.......L.....L....H......E.....I...
....G.......T.......-....-....--..........................--..........................-.
-.--..-..-.......--..-....-.....-.....-.....-......-......-.........-......-........-...
....-.....-........-......-........-.......-.......-.......-.........-......-......-....
....-....-........-..........-......-........-....-...-..-..-.-.-..-.--.---........---..
........................................................................................
.........................................----.-.--.-......-.-.-.-...-....-.....-...-....
..-............-...............-...........-.......-...........-......-.........-.......
...-............-...............-.................-.......-.....-.....-...---...........
...........--.-.--.-.--.........----.......--..-.--.....................................
...--...-.-....--..-....-..-...-...-....-..-....-..-..................-....-....-.-...-.
...-....-............-..........-.....-..........-.........-......-............-......-.
...-.....-.......-............-.......-...........-......-......-....--..........----...
..........................-..-.-..-.........-...........-.........-...........-.........
-......-.......-.........-......-...-...-..........-...-....-..--..--...................
..........--..-.-.---..-.............-----..............................................
.....................................................................................---
...................................-...--..-............................................
........................................................................................
.............................................-.....-...........................-.......-
-..-...-...-....-....-......-.........-..-...-...-..-..-..-.----........................
...................--.-..-..-.-....-..........-.....-.-.-----........--.................
...............................................................---.---.-...-...-.-.-....
.-...-.....-........................--.....-....................................-....-..
-...-...-..-......-....-..............-.....-.......-........-.......-...-..-.-......-..
......................................................--.--..........-.-.............-..
-..........-....-.....-..-.............-.................-..-............-.............-
......-....-.........-...-..................-...--...................-...-..-..-...--..-
.......................................................-....--..-.-...-...-...-..-..---.
...-..-..............-..........-...-................................-...-....-.-..-..-.
-.-...-..-..-----vvys...................................................................
........................................................................................
........................................
""",
'\n' => "",
),
mask = convert(BitArray, Bool[isuppercase(char) || char == '-' for char in seq]),
indexes = collect(eachindex(seq))[mask],
annot = Annotations()
setannotresidue!(annot, "K1PKS6_CRAGI/1-58", "SEQ", seq)
SUITE["MSA"]["Annotations"]["filtercolumns"]["boolean mask"] =
@benchmarkable filtercolumns!(copy($annot), $mask)
SUITE["MSA"]["Annotations"]["filtercolumns"]["index array"] =
@benchmarkable filtercolumns!(copy($annot), $indexes)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 570 | # En Pfam 30.0 PF00400 has 268378 sequences
let chars = rand(Random.MersenneTwister(1), ['.', '-', 'a':'z'..., 'A':'Z'...], 268378 * 2),
residues = Residue[char for char in chars],
ints = Int[res for res in residues]
SUITE["MSA"]["Residue conversions"]["char2res"] = @benchmarkable Residue.($chars)
SUITE["MSA"]["Residue conversions"]["res2char"] = @benchmarkable Char.($residues)
SUITE["MSA"]["Residue conversions"]["int2res"] = @benchmarkable Residue.($ints)
SUITE["MSA"]["Residue conversions"]["res2int"] = @benchmarkable Int.($residues)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 341 | let ascii_str = "#=GR O31698/18-71 SS CCCHHHHHHHHHHHHHHHEEEEEEEEEEEEEEEEHHH\n",
utf8_str = "#=GF CC (Römling U. and Galperin M.Y. “Bacterial cellulose\n"
SUITE["Utils"]["get_n_words"]["ascii"] = @benchmarkable get_n_words($ascii_str, 3)
SUITE["Utils"]["get_n_words"]["utf8"] = @benchmarkable get_n_words($utf8_str, 3)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 571 | using Literate, MIToS
COOKBOOK = joinpath(@__DIR__, "src", "cookbook")
MD_OUTPUT = joinpath(@__DIR__, "src")
NB_OUTPUT = joinpath(@__DIR__, "src", "cookbook", "notebooks")
for file in [
"01_Change_B_factors.jl",
"02_Linking_structural_and_evolutionary_information.jl",
"03_RMSF.jl",
]
Literate.markdown(
joinpath(COOKBOOK, file),
MD_OUTPUT,
execute = false,
documenter = true,
)
Literate.notebook(
joinpath(COOKBOOK, file),
NB_OUTPUT,
execute = false,
documenter = true,
)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 1463 | using Documenter
using DocumenterCitations
using MIToS
const BIB = CitationBibliography(joinpath(@__DIR__, "src", "refs.bib"))
const WARNONLY = [:missing_docs]
if get(ENV, "CI", nothing) === nothing
@info "Running locally, adding :cross_references to WARNONLY"
push!(WARNONLY, :cross_references)
end
DocMeta.setdocmeta!(MIToS, :DocTestSetup, :(using MIToS); recursive = true)
include("literate.jl")
makedocs(
doctest = true,
format = Documenter.HTML(
prettyurls = get(ENV, "CI", nothing) == "true",
assets = String["assets/extra_styles.css", "assets/citations.css"],
),
sitename = "MIToS",
authors = "Diego Javier Zea",
modules = [MIToS],
pages = [
"Home" => "index.md",
"Installation.md",
"Example.md",
"Modules" => ["MSA.md", "Information.md", "SIFTS.md", "PDB.md", "Pfam.md"],
"Cookbook" => [
"01_Change_B_factors.md",
"02_Linking_structural_and_evolutionary_information.md",
"03_RMSF.md",
],
"API" => [
"MSA_API.md",
"Information_API.md",
"SIFTS_API.md",
"PDB_API.md",
"Pfam_API.md",
"Utils_API.md",
],
"Scripts.md",
"References.md",
],
warnonly = WARNONLY,
plugins = [BIB],
)
deploydocs(
repo = "github.com/diegozea/MIToS.jl.git",
target = "build",
deps = nothing,
make = nothing,
)
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 5007 | # # Change B-factors
#
#md # [](@__BINDER_ROOT_URL__/cookbook/notebooks/01_Change_B_factors.ipynb)
#md # [](@__NBVIEWER_ROOT_URL__/cookbook/notebooks/01_Change_B_factors.ipynb)
#
#
# ## Problem description
#
# It is a common practice to change the B-factors of a PDB to store information
# about atoms or residues to be used by other programs. In particular, values
# in the B-factor column can be easily used to colour residues with
# [PyMOL](https://pymolwiki.org/index.php/Color#B-Factors) or
# [Chimera](https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/tutorials/bfactor.html).
#
# We cannot simply assign a new value to the `B` field of a `PDBAtom` because
# this type is immutable. However, we can make use of the `@set` macro of the
# [Setfield](https://github.com/jw3126/Setfield.jl) package to create a new
# `PDBAtom` with a different B-factor value.
#
# In a PDB file, B-factors are stored from the column 61 to 66. Therefore, new
# B-factors should be a `String` with 6 or fewer characters, normally using two
# characters for decimal values. We can use `pyfmt` and `FormatSpec` from the
# [Format](https://github.com/JuliaString/Format.jl) package to create a
# proper B-factor string.
#
# ## MIToS solution
#
# For this example we are going to use the small heat shock protein AgsA from
# *Salmonella typhimurium* (PDB code: *4ZJ9*) available in MIToS docs data:
using MIToS
pdbfile = abspath(pathof(MIToS), "..", "..", "docs", "data", "4zj9.pdb")
#md nothing # hide
# First, we need to read the PDB file using the `MIToS.PDB` module:
using MIToS.PDB
pdb_residues = read_file(pdbfile, PDBFile)
#md nothing # hide
# For this example, we are going to replace the B-factor of the alpha-carbons
# by the residue hydrophobicity according to the hydrophobicity scale of
# [Kyte and Doolittle](https://doi.org/10.1016/0022-2836(82)90515-0) used by
# [Chimera](https://www.cgl.ucsf.edu/chimera/docs/UsersGuide/midas/hydrophob.html):
hydrophobicity = Dict(
"ILE" => 4.5,
"VAL" => 4.2,
"LEU" => 3.8,
"PHE" => 2.8,
"CYS" => 2.5,
"MET" => 1.9,
"ALA" => 1.8,
"GLY" => -0.4,
"THR" => -0.7,
"SER" => -0.8,
"TRP" => -0.9,
"TYR" => -1.3,
"PRO" => -1.6,
"HIS" => -3.2,
"GLU" => -3.5,
"GLN" => -3.5,
"ASP" => -3.5,
"ASN" => -3.5,
"LYS" => -3.9,
"ARG" => -4.5,
)
#md nothing # hide
# First, we define a helper function using `Format` to create a proper
# B-factor string with the PDB format; 6 characters and 2 digits after the
# decimal point.
# The [PDB format description](https://www.wwpdb.org/documentation/file-format-content/format23/sect9.html)
# describe this field as:
# ```
# COLUMNS DATA TYPE FIELD DEFINITION
# ------------------------------------------------------
# 61 - 66 Real(6.2) tempFactor Temperature factor.
# ```
using Format
"""
Return value as a string with the B factor format described in PDB. # e.g. 1.5 -> " 1.50"
"""
format_b_factor(value) = pyfmt(FormatSpec("6.2f"), value) # e.g. 1.5 -> " 1.50"
#md nothing # hide
# Then, where are using that helper function to define a function that returns
# a new `PDBAtom` by changing the `B` factor field using the `Setfield` package.
using Setfield
"""
Return a new PDBAtom with the B-factor changed to value.
"""
function change_b_factor(atom::PDBAtom, value)
b_factor_string = format_b_factor(value)
b_factor_string = strip(b_factor_string) # e.g. " 1.50" -> "1.50"
if length(b_factor_string) > 6
throw(ErrorException("$b_factor_string has more than 6 characters."))
end
@set atom.B = b_factor_string
end
#md nothing # hide
# Now, we can use the `change_b_factor` function to change the B-factor of each
# `"CA"` atom:
for res in pdb_residues
for i in eachindex(res.atoms)
atom = res.atoms[i]
if atom.atom == "CA"
res.atoms[i] = change_b_factor(atom, hydrophobicity[res.id.name])
end
end
end
# Finally, we can save the changed residues in a new PDB file.
#
# ```julia
# write_file("4zj9_hydrophobicity.pdb", pdb_residues, PDBFile)
# ```
#
# ## Discussion
#
# While we have focused on changing the B-factor field of a `PDBAtom`, you can
# use the same approach to change other fields. However, if you want to change
# atom coordinates, it is better to use the `change_coordinates` function from
# the PDB module of MIToS.
#
# MIToS atoms and residues generally stores the string present in the input
# file without surrounding spaces. You can use the `Format` module to
# create these strings and `strip` to get rid of the spaces. You can see the
# [PDB format description](https://www.wwpdb.org/documentation/file-format-content/format23/sect9.html)
# to know what is the format of the expected string or see the
# [MIToS PDB print_file source code](https://github.com/diegozea/MIToS.jl/blob/master/src/PDB/PDBParser.j)
# to get a quick idea.
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 10036 | # # Linking structural and evolutionary information
#
#md # [](@__BINDER_ROOT_URL__/cookbook/notebooks/02_Linking_structural_and_evolutionary_information.ipynb)
#md # [](@__NBVIEWER_ROOT_URL__/cookbook/notebooks/02_Linking_structural_and_evolutionary_information.ipynb)
#
#
# ## Problem description
#
# It is a very common task to map sequence to structure residue number. For
# example, to link structural information coming from *PDB* and evolutionary
# information calculated from multiple sequence alignments.
#
# The naive way of mapping sequence and structure is to perform global pairwise
# alignment between the sequence and the *PDB* sequence (using the residues in
# *ATOM*). The problem with this approach is that the sequences can have
# missing regions and standard pairwise alignment algorithms often yield
# incorrect assignations around those regions
# [(Velankar et.al. 2013)](https://doi.org/10.1093/nar/gks1258). This is
# particularly important when aligning *PDB* sequences, that can have missing
# residues, and sequences coming from multiple sequence alignments, that can be
# incomplete or have unaligned regions (e.g. insert states).
#
# The [SIFTS](https://www.ebi.ac.uk/pdbe/docs/sifts/index.html)
# (Structure Integration with Function, Taxonomy and Sequences) database solves
# this problem and provides residue level mapping between PDB and other
# databases (e.g. *UniProt* and *Pfam*).
#
# The `SIFTS` module of MIToS has functions to access this residue level mapping
# between *PDB* and other databases. Also, MIToS keeps track of the residue
# number of each residue in a multiple sequence alignment (MSA) using its annotations.
# Both things together, allow the correct mapping of sequence and structure
# without performing error-prone pairwise alignments.
#
# Particular solutions depend on problem details, here we show some common ways
# to use MIToS and *SIFTS* to map evolutionary information calculated in an MSA
# (e.g. Shannon entropy) with structural information (e.g. B-factors).
#
# ## PDB and Pfam alignment mapping
#
# This is the easiest problem to solve with the
# [MIToS `Pfam` module](@ref Module-Pfam) because *SIFTS* already has a residue
# level mapping between *PDB* and *Pfam*.
#
# For this example, we are going to map the columns in the multiple sequence
# alignment of the *PF09645* Pfam family and the residues in the chain *A* from
# the *2VQC* *PDB* file. The needed files are available in the MIToS test suite:
using MIToS
pdb_file = abspath(pathof(MIToS), "..", "..", "test", "data", "2VQC.pdb")
pfam_file = abspath(pathof(MIToS), "..", "..", "test", "data", "PF09645_full.stockholm")
sifts_file = abspath(pathof(MIToS), "..", "..", "test", "data", "2vqc.xml.gz")
#md nothing # hide
# You can also use `downloadpdb` from `MIToS.PDB`, `downloadpfam` from
# `MIToS.Pfam` and `downloadsifts` from `MIToS.SIFTS` to get the corresponding
# files from those databases.
#
# It is important to read the Pfam MSA file using `generatemapping=true` and
# `useidcoordinates=true` because that allows keeping track of the residue
# number using the MSA annotations.
using MIToS.Pfam
msa = read_file(pfam_file, Stockholm, generatemapping = true, useidcoordinates = true)
# First, we need to know what is the sequence in the MSA that correspond to the
# PDB we want to link. Luckily, Pfam Stockholm files store the mapping between
# sequences and PDB chains. You can access that mapping using the `getseq2pdb`
# function from `MIToS.Pfam`
seq2pdbs = getseq2pdb(msa)
# The returned dictionary gives you all the PDB chains associated with a
# determined sequence in the MSA. But, in this case, we want to go in the other
# direction to find all the sequences associated with a determined *PDB* chain.
# We are going to use a list comprehension because it is possible for a single
# chain to be associated with more than one sequence in the *Pfam* MSA (e.g.
# domain repeats).
pdb_code = "2VQC"
pdb_chain = "A"
seq_ids = [seq for (seq, pdbs) in seq2pdbs if (pdb_code, pdb_chain) in pdbs]
# In this example, we are going to use the only sequence we found for the *A*
# of *2VQC*.
seq_id = seq_ids[1]
# Finally, we can use the `msacolumn2pdbresidue` function from the Pfam module
# to get a dictionary from the MSA column index to the *PDB* residue number:
pfam_id = "PF09645"
msacol2pdbres = msacolumn2pdbresidue(msa, seq_id, pdb_code, pdb_chain, pfam_id, sifts_file)
# This dictionary has the mapping between MSA column and PDB residue that allows
# the mapping between evolutionary and structural information. For example, to
# measure the correlation between entropy (related to residue variation in an
# MSA column) and the mean B factor of the residue:
using MIToS.Information
Hx = mapcolfreq!(
shannon_entropy,
msa,
Frequencies(ContingencyTable(Int, Val{1}, UngappedAlphabet())),
)
# To get quick access to each PDB residue based on its residue number, we can
# read the PDB file into a dictionary using the `read_file` and `residuesdict`
# functions from the MIToS `PDB` module:
using MIToS.PDB
res_dict = residuesdict(
read_file(pdb_file, PDBFile, occupancyfilter = true),
model = "1",
chain = "A",
)
# Then, we can iterate the mapping dictionary to link the MSA and PDB based
# values:
using Statistics
x = Float64[]
y = Float64[]
for (col_index, res_number) in msacol2pdbres
if res_number != "" # i.e. MSA column has an associated PDB residue
push!(x, Hx[col_index])
push!(y, mean(parse(Float64, atom.B) for atom in res_dict[res_number].atoms))
end
end
cor(x, y)
# ## Unknown sequence coordinates
#
# While *Pfam* alignments have the start and end of the aligned region indicated
# in the sequence name, other multiple sequence alignments don't give any hint
# about that. In those cases, we should use pairwise alignments. However,
# instead of aligning the sequence coming from the MSA and the *PDB* sequence,
# we can align the MSA sequence to the *UniProt* sequence to reduce the
# possibility of mapping errors. Once we have the mapping of the MSA sequence
# to the *UniProt* sequence, we can use *SIFTS* to map the *PDB* sequence to
# the MSA sequence using the *UniProt* numeration.
#
# For this example, we are going to use the following files included in MIToS
# documentation:
using MIToS
pdb_file = abspath(pathof(MIToS), "..", "..", "docs", "data", "1dur.pdb")
msa_file = abspath(pathof(MIToS), "..", "..", "docs", "data", "blast_alignment.fa")
sifts_file = abspath(pathof(MIToS), "..", "..", "docs", "data", "1dur.xml.gz")
uniprot_file = abspath(pathof(MIToS), "..", "..", "docs", "data", "P00193.fasta")
#md nothing # hide
# First, we are going to read the MSA file. In this case, we can not use
# `useidcoordinates=true` because the sequence names don't have the sequence
# coordinates in the Pfam format. However, we are going to use
# `generatemapping=true` to get the default mapping for each sequence in the
# alignment (from `1` to the length of the aligned region):
using MIToS.MSA
msa = read_file(msa_file, FASTA, generatemapping = true)
# After that, we get the first sequence of the MSA, the one we know that
# corresponds to the PDB of interest. We need the sequence as a `String`
# without gaps (unaligned), so we use the `MIToS.MSA` `stringsequence` function
# together with `replace`:
msa_seq = replace(stringsequence(msa, 1), '-' => "")
# Also, we are going to read the *UniProt* sequence. You can easily download the
# sequence from UniProt by doing:
# ```julia
# using MIToS.Utils
# download_file("https://www.uniprot.org/uniprot/P00193.fasta", "P00193.fasta")
# ```
# To read the FASTA file we are going to use the `FastaIO` package:
using FastaIO
uniprot_sequences = readfasta(uniprot_file)
# And get the unique sequence:
uniprot_seq = uniprot_sequences[1][2]
# We can perform a pairwise sequence alignment between both sequences by using
# the [`BioAlignments` package](https://github.com/BioJulia/BioAlignments.jl)
# from the *BioJulia* suite. In this case, we use a semi-global alignment
# (no start/end gap penalty) because we know that the MSA sequence is a region
# of the *UniProt* sequence.
using BioAlignments
costmodel = AffineGapScoreModel(BLOSUM62, gap_open = -10, gap_extend = -1)
aln = pairalign(SemiGlobalAlignment(), msa_seq, uniprot_seq, costmodel)
# Then, we only need to iterate the alignment to designate the positions and
# store the equivalences in a dictionary:
function seq2refnumber(aln)
seq_pos = 0
ref_pos = 0
last_seq_pos = 0
seq2ref = Dict{Int,Int}()
for (seq_res, ref_res) in alignment(aln)
if seq_res != '-'
seq_pos += 1
end
if ref_res != '-'
ref_pos += 1
end
if seq_pos != last_seq_pos
seq2ref[seq_pos] = ref_pos
last_seq_pos = seq_pos
end
end
seq2ref
end
seqnum2uniprotnum = seq2refnumber(aln)
# Then, we can use `getsequencemapping` to go from MSA column number to
# *UniProt* residue, and `siftsmapping` to go from *UniProt* to *PDB*:
seqmap = getsequencemapping(msa, 1)
# -
colnum2uniprotnum = Dict{Int,Int}()
for (colnum, seqnum) in enumerate(seqmap)
if seqnum != 0 # getsequencemapping returns 0 where there is a gap
colnum2uniprotnum[colnum] = seqnum2uniprotnum[seqnum]
end
end
colnum2uniprotnum
# -
using MIToS.SIFTS
uniprotnum2pdbnum = siftsmapping(
sifts_file,
dbUniProt,
"P00193",
dbPDB,
"1dur", # SIFTS stores PDB identifiers in lowercase
chain = "A",
missings = false,
) # residues without coordinates aren't used in the mapping
# To finally get the dictionary from MSA column index to PDB residue number
colnum2pdbnum = Dict{Int,String}()
for (colnum, uniprotnum) in colnum2uniprotnum
pdbresnum = get(uniprotnum2pdbnum, string(uniprotnum), "")
if pdbresnum != ""
colnum2pdbnum[colnum] = pdbresnum
end
end
colnum2pdbnum
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 3348 | # # Root Mean Squared Fluctuation (RMSF)
#
# md # [](@__BINDER_ROOT_URL__/cookbook/notebooks/03_RMSF.ipynb)
# md # [](@__NBVIEWER_ROOT_URL__/cookbook/notebooks/03_RMSF.ipynb)
#
#
# ## Problem description
#
# The [Root Mean Squared Fluctuation (RMSF)](https://en.wikipedia.org/wiki/Mean_squared_displacement)
# is a common way to measure residue flexibility in a structural ensemble.
# It is a measure of how far is the residue moving from its average position
# in the group of structures. Usually, we represent a residue position with
# the spatial coordinates of its alpha carbon.
#
# The protein structures should be previously superimposed to calculate the
# RMSF, for example, by using the `superimpose` function of the
# [`PDB` module of `MIToS`](@ref Module-PDB). In this example, we are going
# to measure the RMSF of each residue from an NMR ensemble using the
# `rmsf` function.
#
# The structure superimposition could be the most complicated step of the
# process, depending on the input data. In particular, it structures come
# from different PDB structures or homologous proteins can require the use
# of external programs,
# as [MAMMOTH-mult](https://ub.cbm.uam.es/software/online/mamothmult.php) or
# [MUSTANG](https://lcb.infotech.monash.edu/mustang/) among others,
# tailored for this task.
#
# In this case, we are going to use an NMR ensemble. Therefore, we are not
# going to need to superimpose the structures as NMR models have the
# same protein sequence and are, usually, well-aligned.
#
#
# ## MIToS solution
import MIToS
using MIToS.PDB
using Plots
# Lets read the NMR ensemble:
pdb_file = abspath(pathof(MIToS), "..", "..", "test", "data", "1AS5.pdb")
pdb_res = read_file(pdb_file, PDBFile, occupancyfilter = true)
#md nothing # hide
# We set `occupancyfilter` to `true` to ensure that we have one single set of
# coordinates for each atom. That filter isn't essential for NMR structures,
# but It can avoid multiple alpha carbons in crystallographic structures with
# disordered atoms.
# We can get an idea of the alpha carbon positions by plotting these residues:
scatter(pdb_res, legend = false)
# As we saw in the previous plot, the structure doesn't need to be
# superimposed. Now, we are going to separate each model into different
# vectors, storing each vector into a `Dict`:
models = Dict{String,Vector{PDBResidue}}()
for res in pdb_res
push!(get!(models, res.id.model, []), res)
end
# Then, we simply need to collect all the PDB models in the values
# of the `Dict`, to get the vector of `PDBResidues` vectors required
# to calculate the RMSF.
pdb_models = collect(values(models))
#md nothing # hide
# And, finally, call the `rmsf` function on the list of structures. It is
# important that all the vectors has the same number of `PDBResidue`s. This
# function assumes that the nth element of each vector corresponds to the same
# residue:
RMSF = rmsf(pdb_models)
# This return the vector of RMSF values for each residue, calculated using
# the coordinates of the alpha carbons.
# You can plot this vector to get an idea of the which are the most flexible
# position in your structure:
plot(RMSF, legend = false, xlab = "Residue", ylab = "RMSF [Å]")
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 1078 | module MIToSClusteringExt
using MIToS.MSA
using Clustering
using StatsBase
"""
Get the number of clusters in a `Clusters` object.
"""
Clustering.nclusters(cl::Clusters) = length(cl.clustersize)
"""
Get sample counts of clusters as a `Vector`. Each `k` value is the number of samples
assigned to the k-th cluster.
"""
Clustering.counts(cl::Clusters) = cl.clustersize
"""
Get a vector of assignments, where the `i` value is the index/number of the cluster to
which the i-th sequence is assigned.
"""
Clustering.assignments(cl::Clusters) = cl.clusters
# Convert from ClusteringResult to Clusters
# needs tests
function Base.convert(::Type{Clusters}, cl::ClusteringResult)
clustersize = counts(cl)
clusters = assignments(cl)
weights = StatsBase.Weights(
Float64[1.0 / clustersize[k] for k in clusters],
Float64(length(clustersize)),
)
Clusters(clustersize, clusters, weights)
end
# getweight(cl::ClusteringResult) = getweight(convert(Clusters, cl))
# getweight(cl::ClusteringResult, seq::Int) = getweight(convert(Clusters, cl), seq)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 1182 | module MIToSROCAnalysisExt
using MIToS.Pfam
using MIToS.Utils
using ROCAnalysis
using PairwiseListMatrices
using NamedArrays
"""
AUC(scores::PairwiseListMatrix, msacontacts::PairwiseListMatrix)
Returns the Area Under a ROC (Receiver Operating Characteristic) Curve (AUC) of the
`scores` for `msacontact` prediction. `score` and `msacontact` lists are vinculated
(inner join) by their labels (i.e. column number in the file). `msacontact` should have
1.0 for true contacts and 0.0 for not contacts (NaN or other numbers for missing
values). You need to do `using ROCAnalysis` before using this function.
"""
function ROCAnalysis.AUC(
scores::NamedArray{L,2,PairwiseListMatrix{L,false,VL},NL},
msacontacts::NamedArray{R,2,PairwiseListMatrix{L,false,VR},NR},
) where {L<:AbstractFloat,R<:AbstractFloat,VL,VR,NL,NR}
sco, con = join(scores, msacontacts, kind = :inner)
true_contacts, false_contacts = getcontactmasks(con)
scores_list = getlist(getarray(sco))
ROCAnalysis.AUC(
ROCAnalysis.roc(
scores_list[true_contacts.&.!isnan.(scores_list)],
scores_list[false_contacts.&.!isnan.(scores_list)],
),
)
end
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 236 | module MIToS
export Utils, MSA, Information, PDB, SIFTS, Pfam
include("Utils/Utils.jl")
include("MSA/MSA.jl")
include("Information/Information.jl")
include("PDB/PDB.jl")
include("SIFTS/SIFTS.jl")
include("Pfam/Pfam.jl")
end # module
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 3977 | # BLOSUM Clustered Target Frequencies=qij
# Blocks Database = /data/blocks_5.0/blocks.dat
# Cluster Percentage: >= 62
"""
BLOSUM62 probabilities *P(aa)* for each residue on the `UngappedAlphabet`.
SUM: 0.9987
"""
const BLOSUM62_Pi = ContingencyTable(
Float64[
0.0741,
0.0516,
0.0445,
0.0536,
0.0246,
0.034,
0.0543,
0.0741,
0.0262,
0.0679,
0.0988,
0.0579,
0.0249,
0.0473,
0.0387,
0.0573,
0.0507,
0.0132,
0.0321,
0.0729,
],
UngappedAlphabet(),
)
"""
Table with conditional probabilities of residues based on BLOSUM62. The normalization is
done row based. The firts row contains the *P(aa|A)* and so one.
"""
const BLOSUM62_Pij = ContingencyTable(
Float64[
# A R N D C Q E G H I L K M F P S T W Y V
0.2901 0.0310 0.0256 0.0297 0.0216 0.0256 0.0405 0.0783 0.0148 0.0432 0.0594 0.0445 0.0175 0.0216 0.0297 0.0850 0.0499 0.0054 0.0175 0.0688
0.0446 0.3450 0.0388 0.0310 0.0078 0.0484 0.0523 0.0329 0.0233 0.0233 0.0465 0.1202 0.0155 0.0174 0.0194 0.0446 0.0349 0.0058 0.0174 0.0310
0.0427 0.0449 0.3169 0.0831 0.0090 0.0337 0.0494 0.0652 0.0315 0.0225 0.0315 0.0539 0.0112 0.0180 0.0202 0.0697 0.0494 0.0045 0.0157 0.0270
0.0410 0.0299 0.0690 0.3974 0.0075 0.0299 0.0914 0.0466 0.0187 0.0224 0.0280 0.0448 0.0093 0.0149 0.0224 0.0522 0.0354 0.0037 0.0112 0.0243
0.0650 0.0163 0.0163 0.0163 0.4837 0.0122 0.0163 0.0325 0.0081 0.0447 0.0650 0.0203 0.0163 0.0203 0.0163 0.0407 0.0366 0.0041 0.0122 0.0569
0.0559 0.0735 0.0441 0.0471 0.0088 0.2147 0.1029 0.0412 0.0294 0.0265 0.0471 0.0912 0.0206 0.0147 0.0235 0.0559 0.0412 0.0059 0.0206 0.0353
0.0552 0.0497 0.0405 0.0902 0.0074 0.0645 0.2965 0.0350 0.0258 0.0221 0.0368 0.0755 0.0129 0.0166 0.0258 0.0552 0.0368 0.0055 0.0166 0.0313
0.0783 0.0229 0.0391 0.0337 0.0108 0.0189 0.0256 0.5101 0.0135 0.0189 0.0283 0.0337 0.0094 0.0162 0.0189 0.0513 0.0297 0.0054 0.0108 0.0243
0.0420 0.0458 0.0534 0.0382 0.0076 0.0382 0.0534 0.0382 0.3550 0.0229 0.0382 0.0458 0.0153 0.0305 0.0191 0.0420 0.0267 0.0076 0.0573 0.0229
0.0471 0.0177 0.0147 0.0177 0.0162 0.0133 0.0177 0.0206 0.0088 0.2710 0.1679 0.0236 0.0368 0.0442 0.0147 0.0250 0.0398 0.0059 0.0206 0.1767
0.0445 0.0243 0.0142 0.0152 0.0162 0.0162 0.0202 0.0213 0.0101 0.1154 0.3755 0.0253 0.0496 0.0547 0.0142 0.0243 0.0334 0.0071 0.0223 0.0962
0.0570 0.1071 0.0415 0.0415 0.0086 0.0535 0.0708 0.0432 0.0207 0.0276 0.0432 0.2781 0.0155 0.0155 0.0276 0.0535 0.0397 0.0052 0.0173 0.0328
0.0522 0.0321 0.0201 0.0201 0.0161 0.0281 0.0281 0.0281 0.0161 0.1004 0.1968 0.0361 0.1606 0.0482 0.0161 0.0361 0.0402 0.0080 0.0241 0.0924
0.0338 0.0190 0.0169 0.0169 0.0106 0.0106 0.0190 0.0254 0.0169 0.0634 0.1142 0.0190 0.0254 0.3869 0.0106 0.0254 0.0254 0.0169 0.0888 0.0550
0.0568 0.0258 0.0233 0.0310 0.0103 0.0207 0.0362 0.0362 0.0129 0.0258 0.0362 0.0413 0.0103 0.0129 0.4935 0.0439 0.0362 0.0026 0.0129 0.0310
0.1099 0.0401 0.0541 0.0489 0.0175 0.0332 0.0524 0.0663 0.0192 0.0297 0.0419 0.0541 0.0157 0.0209 0.0297 0.2199 0.0820 0.0052 0.0175 0.0419
0.0730 0.0355 0.0434 0.0375 0.0178 0.0276 0.0394 0.0434 0.0138 0.0533 0.0651 0.0454 0.0197 0.0237 0.0276 0.0927 0.2465 0.0059 0.0178 0.0710
0.0303 0.0227 0.0152 0.0152 0.0076 0.0152 0.0227 0.0303 0.0152 0.0303 0.0530 0.0227 0.0152 0.0606 0.0076 0.0227 0.0227 0.4924 0.0682 0.0303
0.0405 0.0280 0.0218 0.0187 0.0093 0.0218 0.0280 0.0249 0.0467 0.0436 0.0685 0.0312 0.0187 0.1308 0.0156 0.0312 0.0280 0.0280 0.3178 0.0467
0.0700 0.0219 0.0165 0.0178 0.0192 0.0165 0.0233 0.0247 0.0082 0.1646 0.1303 0.0261 0.0316 0.0357 0.0165 0.0329 0.0494 0.0055 0.0206 0.2689
],
UngappedAlphabet(),
)
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 15378 | # Contingency Tables
# ==================
"""
A `ContingencyTable` is a multidimensional array. It stores the contingency matrix, its
marginal values and total. The type also has an internal and private temporal array and an
alphabet object. It's a parametric type, taking three ordered parameters:
- `T` : The element type of the multidimensional array.
- `N` : It's the dimension of the array and should be an `Int`.
- `A` : This should be a type, subtype of `ResidueAlphabet`, i.e.: `UngappedAlphabet`,
`GappedAlphabet` or `ReducedAlphabet`.
A `ContingencyTable` can be created from an alphabet if all the parameters are given.
Otherwise, you need to give a type, a number (`Val`) and an alphabet. You can also create a
`ContingencyTable` using a matrix and a alphabet. For example:
```julia
ContingencyTable{Float64,2,UngappedAlphabet}(UngappedAlphabet())
ContingencyTable(Float64, Val{2}, UngappedAlphabet())
ContingencyTable(zeros(Float64, 20, 20), UngappedAlphabet())
```
"""
mutable struct ContingencyTable{T,N,A} <: AbstractArray{T,N}
alphabet::A
temporal::Array{T,N}
table::NamedArray{T,N,Array{T,N},NTuple{N,OrderedDict{String,Int}}}
marginals::NamedArray{T,2,Array{T,2},NTuple{2,OrderedDict{String,Int}}}
total::T
end
# Probability and Frequencies
# ----------------------
"""
A `Probabilities` object wraps a `ContingencyTable` storing probabilities. It doesn't
perform any check. If the total isn't one, you must use `normalize` or `normalize!`on the
`ContingencyTable` before wrapping it to make the sum of the probabilities equal to one.
"""
mutable struct Probabilities{T,N,A} <: AbstractArray{T,N}
table::ContingencyTable{T,N,A}
end
"""
A `Frequencies` object wraps a `ContingencyTable` storing counts/frequencies.
"""
mutable struct Frequencies{T,N,A} <: AbstractArray{T,N}
table::ContingencyTable{T,N,A}
end
# DEPRECATED: Deprecation warning for Counts type
mutable struct Counts{T,N,A} <: AbstractArray{T,N}
table::ContingencyTable{T,N,A}
end
function Counts{T,N,A}(table::ContingencyTable{T,N,A}) where {T,N,A}
Base.depwarn(
"The `Counts` type is deprecated. Please use `Frequencies` instead.",
:Counts,
force = true,
)
Frequencies{T,N,A}(table)
end
# Getters
"""
`getcontingencytable` allows to access the wrapped `ContingencyTable` in a `Probabilities`
or `Frequencies` object.
"""
@inline getcontingencytable(p::Probabilities{T,N,A}) where {T,N,A} = p.table
@inline getcontingencytable(n::Frequencies{T,N,A}) where {T,N,A} = n.table
for f in
(:getalphabet, :gettable, :getmarginals, :gettotal, :gettablearray, :getmarginalsarray)
@eval $(f)(p::Probabilities{T,N,A}) where {T,N,A} = $(f)(getcontingencytable(p))
@eval $(f)(n::Frequencies{T,N,A}) where {T,N,A} = $(f)(getcontingencytable(n))
end
# AbstractArray
for f in (:size, :getindex, :setindex!)
@eval Base.$(f)(p::Probabilities{T,N,A}, args...) where {T,N,A} =
$(f)(getcontingencytable(p), args...)
@eval Base.$(f)(n::Frequencies{T,N,A}, args...) where {T,N,A} =
$(f)(getcontingencytable(n), args...)
end
# Getters
# -------
"""
`getalphabet` allows to access the stored alphabet object.
"""
@inline getalphabet(table::ContingencyTable) = table.alphabet
"""
`gettable` allows to access the table (`NamedArray`).
"""
@inline gettable(table::ContingencyTable) = table.table
"""
`getmarginals` allows to access the array with the marginal values (`NamedArray`).
"""
@inline getmarginals(table::ContingencyTable) = table.marginals
"""
`gettotal` allows to access the stored total value.
"""
@inline gettotal(table::ContingencyTable) = table.total
Base.sum(table::ContingencyTable) = gettotal(table)
"""
`gettablearray` allows to access the table (`Array` without names).
"""
@inline gettablearray(table::ContingencyTable) = getarray(table.table)
"""
`getmarginalsarray` allows to access the array with the marginal values
(`Array` without names).
"""
@inline getmarginalsarray(table::ContingencyTable) = getarray(table.marginals)
# Cartesian (helper functions)
# ----------------------------
"""
`_marginal(1,:A,:i,:value)` generates the expression: `A[i_1, 1] += value`
"""
function _marginal(N::Int, marginal::Symbol, index::Symbol, value::Symbol)
aexprs = [
Expr(:escape, Expr(:(+=), Expr(:ref, marginal, Symbol(index, '_', i), i), value)) for i = 1:N
]
Expr(:block, aexprs...)
end
macro _marginal(N, marginal, index, value)
_marginal(N, marginal, index, value)
end
"""
`_test_index(1, i, continue)` generates the expression: `i_1 >= 22 && continue`
"""
function _test_index(N::Int, index::Symbol, expr::Expr)
aexprs = Expr[]
for i = 1:N
push!(
aexprs,
Expr(:escape, Expr(:&&, Expr(:call, :>=, Symbol(index, "_", i), 22), expr)),
)
end
Expr(:block, aexprs...)
end
macro _test_index(N, index, expr)
_test_index(N, index, expr)
end
# AbstractArray Interface
# -----------------------
Base.size(table::ContingencyTable) = size(table.table)
Base.getindex(table::ContingencyTable, i...) = getindex(table.table, i...)
@generated function Base.getindex(table::ContingencyTable, I::Residue...)
N = length(I)
quote
alphabet = getalphabet(table)
matrix = getarray(gettable(table))
# index_1 = alphabet[I[1]]
# index_2 ...
@nextract $N index d -> alphabet[I[d]]
# index_1 >= 22 error("There is a Residue outside the alphabet")
# index_2 ...
@_test_index $N index error("There is a Residue outside the alphabet")
# getindex(matrix, index_1, index_2...
@nref $N matrix index
end
end
function Base.setindex!(table::ContingencyTable, value, i...)
setindex!(table.table, value, i...)
update_marginals!(table)
end
@generated function Base.setindex!(table::ContingencyTable, value, I::Residue...)
N = length(I)
quote
alphabet = getalphabet(table)
matrix = getarray(gettable(table))
@nextract $N index d -> alphabet[I[d]]
@_test_index $N index error("There is a Residue outside the alphabet")
@nref($N, matrix, index) = value
update_marginals!(table)
end
end
# Similar
# -------
Base.similar(table::ContingencyTable{T,N,A}) where {T,N,A} =
ContingencyTable(T, Val{N}, table.alphabet)
function Base.similar(table::ContingencyTable{T,N,A}, ::Type{S}) where {T,S,N,A}
ContingencyTable(S, Val{N}, table.alphabet)
end
# Show
# ====
function Base.show(io::IO, ::MIME"text/plain", table::ContingencyTable{T,N,A}) where {T,N,A}
println(io, typeof(table), " : ")
print(io, "\ntable : ")
show(io, MIME"text/plain"(), gettable(table))
if length(size(table)) != 1
print(io, "\n\nmarginals : ")
show(io, MIME"text/plain"(), getmarginals(table))
end
print(io, "\n\ntotal : $(gettotal(table))")
end
function Base.show(
io::IO,
::MIME"text/plain",
table::Union{Probabilities{T,N,A},Frequencies{T,N,A}},
) where {T,N,A}
print(io, typeof(table), " wrapping a ")
show(io, MIME"text/plain"(), getcontingencytable(table))
end
# Creation
# --------
@generated function (::Type{ContingencyTable{T,N,A}})(alphabet::A) where {T,N,A}
@assert N > 0 "The dimension should be a natural number"
quote
n = length(alphabet)
# residue_names = names(alphabet)
# namedict = OrderedDict{String,Int}(residue_names[i] => i for i in 1:n)
namedict = getnamedict(alphabet)
dimtable = @ntuple $N k -> n # (n, n, ...)
dimtemporal = @ntuple $N k -> 22 # (22, 22, ...)
table = NamedArray(
zeros($T, dimtable),
@ntuple($N, k -> namedict), # (namedict, namedict, ...)
@ntuple($N, k -> "Dim_k")
) # ("Dim_1", "Dim_2", ...)
marginals = NamedArray(
zeros($T, n, $N),
# OrderedDict{String,Int}("Dim_$i" => i for i in 1:N)
(namedict, OrderedDict{String,Int}(@ntuple $N k -> "Dim_k" => k)),
("Residue", "Dim"),
)
ContingencyTable{T,N,A}(alphabet, zeros(T, dimtemporal), table, marginals, zero(T))
end
end
function ContingencyTable(::Type{T}, ::Type{Val{N}}, alphabet::A) where {T,A,N}
ContingencyTable{T,N,A}(alphabet)
end
function ContingencyTable(matrix::AbstractArray{T,N}, alphabet::A) where {T,N,A}
n = length(alphabet)
@assert size(matrix) == ((n for i = 1:N)...,) "Matrix size doesn't match alphabet length"
table = ContingencyTable(T, Val{N}, alphabet)
getarray(table.table)[:] = matrix
_update_marginals!(table)
_update_total!(table)
end
# Update!
# -------
# Update the table, marginal and total using temporal
@generated function _update_table!(table::ContingencyTable{T,N,A}) where {T,N,A}
if A <: ReducedAlphabet
quote
temporal = table.temporal::Array{T,N}
alphabet = getalphabet(table)::A
freqtable = getarray(table.table)::Array{T,N}
@inbounds @nloops $N i temporal begin
@_test_index $N i continue
@nextract $N a d -> alphabet[i_d]
@_test_index $N a continue
@nref($N, freqtable, a) += @nref($N, temporal, i)
end
table
end
elseif (A === UngappedAlphabet) || (A === GappedAlphabet)
quote
temporal = table.temporal::Array{T,N}
freqtable = getarray(table.table)::Array{T,N}
@inbounds @nloops $N i freqtable begin
@nref($N, freqtable, i) += @nref($N, temporal, i)
end
table
end
end
end
@generated function _update_marginals!(table::ContingencyTable{T,N,A}) where {T,N,A}
quote
freqtable = getarray(table.table)::Array{T,N}
marginal = getarray(table.marginals)::Matrix{T}
@inbounds @nloops $N i freqtable begin
value = @nref $N freqtable i
@_marginal($N, marginal, i, value)
end
table
end
end
function _update_total!(table::ContingencyTable{T,N,A}) where {T,N,A}
marginals = getarray(table.marginals)::Matrix{T}
n = size(marginals, 1)
total = zero(T)
@inbounds @simd for i = 1:n
total += marginals[i] # marginals[i,1]
end
table.total = total
table
end
"""
`update_marginals!` updates the marginal and total values using the table.
"""
function update_marginals!(table::ContingencyTable{T,N,A}) where {T,N,A}
fill!(getarray(table.marginals)::Matrix{T}, zero(T))
_update_marginals!(table)
_update_total!(table)
table
end
function _update!(table::ContingencyTable{T,N,A}) where {T,N,A}
_update_table!(table)
update_marginals!(table)
end
function _cleanup_table!(table::ContingencyTable{T,N,A}) where {T,N,A}
fill!(getarray(table.table)::Array{T,N}, zero(T))
end
function _cleanup_temporal!(table::ContingencyTable{T,N,A}) where {T,N,A}
fill!(table.temporal, zero(T))
end
"""
`cleanup!` fills the temporal, table and marginals arrays with zeros.
It also sets total to zero.
"""
function cleanup!(table::ContingencyTable{T,N,A}) where {T,N,A}
_cleanup_temporal!(table)
_cleanup_table!(table)
fill!(getarray(table.marginals)::Matrix{T}, zero(T))
table.total = zero(T)
table
end
# Fill
# ====
function Base.fill!(table::ContingencyTable{T,N,A}, value::T) where {T,N,A}
fill!(getarray(table.table)::Array{T,N}, value)
update_marginals!(table)
end
Base.fill!(table::ContingencyTable{T,N,A}, p::AdditiveSmoothing{T}) where {T,N,A} =
fill!(table, p.λ)
@inline Base.fill!(table::ContingencyTable{T,N,A}, p::NoPseudocount) where {T,N,A} = table
# Apply pseudocount
# =================
# This is faster than array[:] += value
function _sum!(matrix::NamedArray, value)
matrix_array = getarray(matrix)
@inbounds for i in eachindex(matrix_array)
matrix_array[i] += value
end
matrix
end
"""
It adds the `pseudocount` value to the table cells.
"""
function apply_pseudocount!(table::ContingencyTable{T,N,A}, pseudocount::T) where {T,N,A}
_sum!(table.table, pseudocount)
update_marginals!(table)
end
function apply_pseudocount!(
table::ContingencyTable{T,N,A},
p::AdditiveSmoothing{T},
) where {T,N,A}
apply_pseudocount!(table, p.λ)
end
@inline apply_pseudocount!(table::ContingencyTable, p::NoPseudocount) = table
# Normalize
# =========
# This is faster than array[:] /= value
function _div!(matrix::NamedArray, value)
matrix_array = getarray(matrix)
@inbounds for i in eachindex(matrix_array)
matrix_array[i] /= value
end
matrix
end
"""
`normalize!` makes the sum of the frequencies to be one, in place.
"""
function LinearAlgebra.normalize!(table::ContingencyTable{T,N,A}) where {T,N,A}
if table.total != one(T)
_div!(table.table, table.total)
update_marginals!(table)
end
table
end
"""
`normalize` returns another table where the sum of the frequencies is one.
"""
LinearAlgebra.normalize(table::ContingencyTable{T,N,A}) where {T,N,A} =
normalize!(deepcopy(table))
# Delete Dimensions
# =================
function _list_without_dimensions(len::Int, output_len::Int, dimensions::Int...)
ndim = length(dimensions)
@assert (len - ndim) == output_len "$output_len should be = $(len-ndim)"
index_list = Array{Int}(undef, output_len)
j = 1
@inbounds for i = 1:len
if !(i in dimensions)
index_list[j] = i
j += 1
end
end
index_list
end
"""
`delete_dimensions!(out::ContingencyTable, in::ContingencyTable, dimensions::Int...)`
This function fills a ContingencyTable with the counts/probabilities on `in` after the
deletion of `dimensions`. i.e. This is useful for getting Pxy from Pxyz.
"""
function delete_dimensions!(
output::ContingencyTable{T,S,A},
input::ContingencyTable{T,N,A},
dimensions::Int...,
) where {T,N,S,A}
output_marginals = getarray(output.marginals)
output_table = getarray(output.table)
input_marginals = getarray(input.marginals)
input_table = getarray(input.table)
output_marginals[:] = input_marginals[:, _list_without_dimensions(N, S, dimensions...)]
output_table[:] = sum(input_table, dims = dimensions)
output.total = input.total
output
end
"""
`delete_dimensions(in::ContingencyTable, dimensions::Int...)`
This function creates a ContingencyTable with the counts/probabilities on `in` after the
deletion of `dimensions`. i.e. This is useful for getting Pxy from Pxyz.
"""
function delete_dimensions(
input::ContingencyTable{T,N,A},
dims::Vararg{Int,I},
) where {T,N,A,I}
delete_dimensions!(ContingencyTable(T, Val{N - I}, input.alphabet), input, dims...)
end
for tp in (:Probabilities, :Frequencies)
@eval begin
function delete_dimensions!(
output::$(tp){T,S,A},
input::$(tp){T,N,A},
dimensions::Int...,
) where {T,N,S,A}
delete_dimensions!(
getcontingencytable(output),
getcontingencytable(input),
dimensions...,
)
output
end
function delete_dimensions(input::$(tp){T,N,A}, dims::Vararg{Int,I}) where {T,N,A,I}
output = delete_dimensions(getcontingencytable(input), dims...)
$(tp)(output)
end
end
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 5695 | # Busjle et. al. 2009
# ===================
const _MI_MAT_TYPE = NamedArray{
Float64,
2,
PairwiseListMatrix{Float64,false,Vector{Float64}},
NTuple{2,OrderedDict{String,Int}},
}
function _buslje09(aln, alphabet::A, clusters, lambda, apc) where {A}
mi = mapcolpairfreq!(
_mutual_information,
aln,
Frequencies{Float64,2,A}(ContingencyTable(Float64, Val{2}, alphabet)),
usediagonal = false,
pseudocounts = AdditiveSmoothing{Float64}(lambda),
weights = clusters,
diagonalvalue = NaN,
)
if apc
APC!(mi)
end
mi
end
"""
`buslje09` takes a MSA and calculates a Z score and a corrected MI/MIp as described
on **Busjle et. al. 2009**.
keyword argument, type, default value and descriptions:
```
- lambda Float64 0.05 Low count value
- clustering Bool true Sequence clustering (Hobohm I)
- threshold 62 Percent identity threshold for clustering
- maxgap Float64 0.5 Maximum fraction of gaps in positions included in calculation
- apc Bool true Use APC correction (MIp)
- samples Int 100 Number of samples for Z-score
- fixedgaps Bool true Fix gaps positions for the random samples
- alphabet ResidueAlphabet UngappedAlphabet() Residue alphabet to be used
```
This function returns:
```
- Z score
- MI or MIp
```
"""
function buslje09(
aln::AbstractMatrix{Residue};
lambda::Float64 = 0.05,
clustering::Bool = true,
threshold = 62,
maxgap::Float64 = 0.5,
apc::Bool = true,
samples::Int = 100,
alphabet::ResidueAlphabet = UngappedAlphabet(),
fixedgaps::Bool = true,
)::NTuple{2,_MI_MAT_TYPE}
aln = filtercolumns(aln, gapfraction(aln, 1) .<= maxgap)
clusters = clustering ? hobohmI(aln, threshold) : NoClustering()
mi = _buslje09(aln, alphabet, clusters, lambda, apc)
if samples > 0
rand_mi = Array{PairwiseListMatrix{Float64,false,Vector{Float64}}}(undef, samples)
zmi = copy(mi)
residuematrix = getresidues(aln)
for ns = 1:samples
shuffle_msa!(residuematrix, dims = 1, fixedgaps = fixedgaps)
rand_mi[ns] = getarray(_buslje09(aln, alphabet, clusters, lambda, apc))
end
PairwiseListMatrices.zscore!(rand_mi, getarray(zmi))
return (zmi, mi)
else
return (fill!(copy(mi), 0.0), mi)
end
end
function buslje09(filename::String, format::Type{T}; kargs...) where {T<:FileFormat}
Base.depwarn(
"Using a file name and format with `buslje09` is deprecated. Use `read_file` to read an MSA object and call `buslje09` on it.",
:buslje09,
force = true,
)
aln = read_file(filename, T, AnnotatedMultipleSequenceAlignment, generatemapping = true)
buslje09(aln; kargs...)
end
# MIToS BLMI: Blosum MI
# =====================
function _BLMI(aln, clusters, alpha, beta, apc, lambda::Float64 = 0.0)
mi = mapcolpairfreq!(
_mutual_information,
aln,
Probabilities{Float64,2,UngappedAlphabet}(
ContingencyTable(Float64, Val{2}, UngappedAlphabet()),
),
usediagonal = false,
pseudocounts = AdditiveSmoothing{Float64}(lambda),
weights = clusters,
diagonalvalue = NaN,
pseudofrequencies = BLOSUM_Pseudofrequencies(alpha, beta),
)
if apc
APC!(mi)
end
mi
end
"""
`BLMI` takes an MSA and calculates a Z score (ZBLMI) and a corrected MI/MIp as described
on **Busjle et. al. 2009** but using using BLOSUM62 pseudo frequencies instead of a
fixed pseudocount.
Keyword argument, type, default value and descriptions:
```
- beta Float64 8.512 β for BLOSUM62 pseudo frequencies
- lambda Float64 0.0 Low count value
- threshold 62 Percent identity threshold for sequence clustering (Hobohm I)
- maxgap Float64 0.5 Maximum fraction of gaps in positions included in calculation
- apc Bool true Use APC correction (MIp)
- samples Int 50 Number of samples for Z-score
- fixedgaps Bool true Fix gaps positions for the random samples
```
This function returns:
```
- Z score (ZBLMI)
- MI or MIp using BLOSUM62 pseudo frequencies (BLMI/BLMIp)
```
"""
function BLMI(
aln::AbstractMatrix{Residue};
beta::Float64 = 8.512,
threshold = 62,
maxgap::Float64 = 0.5,
apc::Bool = true,
samples::Int = 50,
fixedgaps::Bool = true,
lambda::Float64 = 0.0,
)::NTuple{2,_MI_MAT_TYPE}
aln = filtercolumns(aln, gapfraction(aln, 1) .<= maxgap)
clusters = hobohmI(aln, threshold)
numbercl = Float64(length(clusters.clustersize))
mi = _BLMI(aln, clusters, numbercl, beta, apc, lambda)
if samples > 0
rand_mi = Array{PairwiseListMatrix{Float64,false,Vector{Float64}}}(undef, samples)
zmi = copy(mi)
residuematrix = getresidues(aln)
for ns = 1:samples
shuffle_msa!(residuematrix, dims = 1, fixedgaps = fixedgaps)
rand_mi[ns] = getarray(_BLMI(aln, clusters, numbercl, beta, apc, lambda))
end
PairwiseListMatrices.zscore(rand_mi, getarray(zmi))
return (zmi, mi)
else
return (fill!(copy(mi), 0.0), mi)
end
end
function BLMI(filename::String, format::Type{T}; kargs...) where {T<:FileFormat}
Base.depwarn(
"Using a file name and format with `BLMI` is deprecated. Use `read_file` to read an MSA object and call `BLMI` on it.",
:BLMI,
force = true,
)
aln = read_file(filename, T, AnnotatedMultipleSequenceAlignment, generatemapping = true)
BLMI(aln; kargs...)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 2549 | """
Mean mutual information of column a (Dunn et. al. 2008).
Summation is over j=1 to N, j ≠ a. Total is N-1.
"""
function _mean_column(mi::Matrix{T}) where {T}
(dropdims(sum(mi, dims = 1), dims = 1) .- diag(mi)) ./ (size(mi, 1) - 1)
end
"""
Mean mutual information of column a (Dunn et. al. 2008).
Summation is over j=1 to N, j ≠ a. Total is N-1.
Overall mean mutual information (Dunn et. al. 2008).
2/(N*(N-1)) by the sum of MI where the indices run i=1 to N-1, j=i+1 to N (triu).
"""
function _mean_total(mi::Matrix{T}) where {T}
values = matrix2list(mi)
sum(values) / length(values)
end
"""
APC
# References
- [Dunn, Stanley D., Lindi M. Wahl, and Gregory B. Gloor. "Mutual information without
the influence of phylogeny or entropy dramatically improves residue contact prediction."
Bioinformatics 24.3 (2008): 333-340.](@cite dunn2008mutual)
"""
function APC!(MI::Matrix{T}) where {T}
nrow, ncol = size(MI)
MI_mean = _mean_total(MI)
# if MI_mean == 0.0
# return(fill!(MI, zero(T)))
# end
MI_res_mean = _mean_column(MI)
@inbounds for j = 1:ncol
for i = 1:nrow
if i != j
MI[i, j] -= ((MI_res_mean[i] * MI_res_mean[j]) / MI_mean)
else
MI[i, j] = NaN
end
end
end
MI
end
function APC!(MI::PairwiseListMatrix{T,true,Vector{T}}) where {T<:AbstractFloat}
ncol = MI.nelements
MI_col_sum = vec(sum_nodiag(MI, dims = 1))
MI_mean = sum(MI_col_sum) / (length(MI) - ncol)
MI_col_mean = MI_col_sum ./ (ncol - 1)
k = 0
list = MI.list
@inbounds for i = 1:ncol
for j = i:ncol
k += 1
if i != j
list[k] -= ((MI_col_mean[i] * MI_col_mean[j]) / MI_mean)
else
list[k] = NaN
end
end
end
MI
end
function APC!(MI::PairwiseListMatrix{T,false,Vector{T}}) where {T<:AbstractFloat}
ncol = MI.nelements
MI_col_sum = vec(sum_nodiag(MI, dims = 1))
MI_mean = sum(MI_col_sum) / (length(MI) - ncol)
MI_col_mean = MI_col_sum ./ (ncol - 1)
k = 0
list = MI.list
@inbounds for i = 1:(ncol-1)
for j = (i+1):ncol
k += 1
list[k] -= ((MI_col_mean[i] * MI_col_mean[j]) / MI_mean)
end
end
MI.diag[:] .= NaN
MI
end
function APC!(
MI::NamedArray{T,2,PairwiseListMatrix{T,D,Vector{T}},NTuple{2,OrderedDict{String,Int}}},
) where {T,D}
plm = getarray(MI)::PairwiseListMatrix{T,D,Vector{T}}
APC!(plm)
MI
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 9107 | # Counting
# ========
@generated function _temporal_counts!(
counts::ContingencyTable{T,N,A},
weights,
seqs::Vararg{AbstractArray{Residue},N},
) where {T,N,A}
quote
@assert N == length(seqs) "Number of residue arrays and table dimension doesn't match."
# seq_1 = seqs[1]
# seq_2 = ...
@nextract $N seq d -> seqs[d]
len = length(seq_1)
# @assert len == length(seq_1) "Residue arrays have different lengths"
# @assert len == length(seq_2) ...
@nexprs $N d ->
@assert len == length(seq_d) "Residue arrays have different lengths."
if isa(weights, AbstractArray)
@assert len == length(weights) "Residue array and weights sizes doesn't match."
end
_cleanup_temporal!(counts)
temporal = counts.temporal
@inbounds @simd for index in eachindex(seq_1)
# temporal[Int(seq_1[index]), Int(seq_2... += getweight(weights, index)
@nref($N, temporal, d -> Int(seq_d[index])) += getweight(weights, index)
end
counts
end
end
"""
It populates a `ContingencyTable` (first argument) using the frequencies in the sequences
(last positional arguments). The dimension of the table must match the number of sequences
and all the sequences must have the same length. You must indicate the used weights and
pseudocounts as second and third positional arguments respectively. You can use
`NoPseudofrequencies()` and `NoClustering()` to avoid the use of sequence weighting and
pseudocounts, respectively.
**DEPRECATED**: Use [`frequencies!`](@ref) instead. Note that `frequencies!` defines the weigths and
pseudocounts using keyword arguments instead of positional arguments.
"""
function count!(
table::ContingencyTable{T,N,A},
weights,
pseudocounts::Pseudocount,
seqs::Vararg{AbstractArray{Residue},N},
) where {T,N,A}
Base.depwarn(
"count! using a ContingencyTable or Frequencies is deprecated. Use frequencies! instead.",
:count!,
force = true,
)
frequencies!(table, seqs..., weights = weights, pseudocounts = pseudocounts)
end
function count!(table::Frequencies{T,N,A}, args...) where {T,N,A}
count!(getcontingencytable(table), args...)
end
# frequencies! is like count! but using keyword arguments
"""
frequencies!(table, seqs...; weights::WeightTypes, pseudocounts::Pseudocount)
It populates a `ContingencyTable` or `Frequencies` table (first argument) using the frequencies
in the given sequences (last positional arguments). The dimension of the table must match
the number of sequences and all the sequences must have the same length. You must indicate
the used `weights` and `pseudocounts` as keyword arguments. Those arguments default to
`NoClustering()` and `NoPseudocount()` respectively, to avoid the use of sequence
weighting and pseudocounts.
"""
function frequencies!(
table::ContingencyTable{T,N,A},
seqs::Vararg{AbstractArray{Residue},N};
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
) where {T,N,A}
_temporal_counts!(table, weights, seqs...)
apply_pseudocount!(table, pseudocounts)
_update!(table)
table
end
frequencies!(table::Frequencies{T,N,A}, args...; kwargs...) where {T,N,A} =
frequencies!(getcontingencytable(table), args...; kwargs...)
# Default counters
# ================
function _count(
alphabet::A,
weights,
pseudocounts,
seqs::Vararg{AbstractArray{Residue},N},
)::ContingencyTable{Float64,N,A} where {N,A<:ResidueAlphabet}
table = ContingencyTable(Float64, Val{N}, alphabet)::ContingencyTable{Float64,N,A}
frequencies!(table, seqs..., weights = weights, pseudocounts = pseudocounts)
table
end
"""
It returns a `ContingencyTable` wrapped in a `Frequencies` type with the frequencies of residues
in the sequences that takes as arguments. The dimension of the table is equal to the number
of sequences. You can use the keyword arguments `alphabet`, `weights` and `pseudocounts`
to indicate the alphabet of the table (default to `UngappedAlphabet()`), a clustering
result (default to `NoClustering()`) and the pseudocounts (default to `NoPseudocount()`)
to be used during the estimation of the frequencies.
**DEPRECATED**: Use [`frequencies`](@ref) instead. Note that `frequencies` defines the
alphabet, weigths and pseudocounts using keyword arguments instead of positional arguments.
"""
function Base.count(
seqs::Vararg{AbstractArray{Residue},N};
alphabet::ResidueAlphabet = UngappedAlphabet(),
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
) where {N}
Base.depwarn(
"`count` on sequences is deprecated in favor of `frequencies`.",
:count,
force = true,
)
frequencies(
seqs...;
alphabet = alphabet,
weights = weights,
pseudocounts = pseudocounts,
)
end
"""
frequencies(seqs...; alphabet=UngappedAlphabet(), weights=NoClustering(), pseudocounts=NoPseudocount()
This function returns a `Frequencies` object wrapping a `ContingencyTable` with the frequencies
of residues in the sequences that takes as arguments. The dimension of the table is equal
to the number of sequences. You can use the keyword arguments `alphabet`, `weights` and
`pseudocounts` to indicate the alphabet of the table, a clustering result and the
pseudocounts to be used during the estimation of the frequencies.
"""
function frequencies(
seqs::Vararg{AbstractArray{Residue},N};
alphabet::ResidueAlphabet = UngappedAlphabet(),
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
) where {N}
Frequencies(_count(alphabet, weights, pseudocounts, seqs...))
end
# Probabilities
# =============
"""
It populates a `ContingencyTable` (first argument) using the probabilities in the sequences
(last positional arguments). The dimension of the table must match the number of sequences
and all the sequences must have the same length. You must indicate the used weights,
pseudocounts and pseudofrequencies as second, third and fourth positional arguments
respectively. You can use `NoClustering()`, `NoPseudocount()` and `NoPseudofrequencies()`
to avoid the use of sequence weighting, pseudocounts and pseudofrequencies, respectively.
"""
function probabilities!(
table::ContingencyTable{T,N,A},
weights,
pseudocounts::Pseudocount,
pseudofrequencies::Pseudofrequencies,
seqs::Vararg{AbstractArray{Residue},N},
) where {T,N,A}
Base.depwarn(
"The probabilities! method indicating weights, pseudocounts and pseudofrequencies using positional arguments is deprecated; use keyword arguments instead.",
:probabilities!,
force = true,
)
probabilities!(
table,
seqs...,
weights = weights,
pseudocounts = pseudocounts,
pseudofrequencies = pseudofrequencies,
)
end
function probabilities!(
table::ContingencyTable{T,N,A},
seqs::Vararg{AbstractArray{Residue},N};
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
pseudofrequencies::Pseudofrequencies = NoPseudofrequencies(),
) where {T,N,A}
frequencies!(table, seqs..., weights = weights, pseudocounts = pseudocounts)
normalize!(table)
apply_pseudofrequencies!(table, pseudofrequencies)
table
end
function probabilities!(table::Probabilities{T,N,A}, args...; kargs...) where {T,N,A}
probabilities!(getcontingencytable(table), args...; kargs...)
end
# Default probabilities
# =====================
function _probabilities(
alphabet::A,
weights,
pseudocounts,
pseudofrequencies,
seqs::Vararg{AbstractArray{Residue},N},
)::ContingencyTable{Float64,N,A} where {N,A<:ResidueAlphabet}
table = ContingencyTable(Float64, Val{N}, alphabet)::ContingencyTable{Float64,N,A}
probabilities!(
table,
seqs...;
weights = weights,
pseudocounts = pseudocounts,
pseudofrequencies = pseudofrequencies,
)
table
end
"""
It returns a `ContingencyTable` wrapped in a `Probabilities` type with the probabilities of
residues in the sequences that takes as arguments. The dimension of the table is equal to
the number of sequences. You can use the keyword arguments `alphabet`, `weights`,
`pseudocounts` and `pseudofrequencies` to indicate the alphabet of the table
(default to `UngappedAlphabet()`), a clustering result (default to `NoClustering()`),
the pseudocounts (default to `NoPseudocount()`) and the pseudofrequencies
(default to `NoPseudofrequencies()`) to be used during the estimation of the probabilities.
"""
function probabilities(
seqs::Vararg{AbstractArray{Residue},N};
alphabet::ResidueAlphabet = UngappedAlphabet(),
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
pseudofrequencies::Pseudofrequencies = NoPseudofrequencies(),
) where {N}
Probabilities(
_probabilities(alphabet, weights, pseudocounts, pseudofrequencies, seqs...),
)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 2690 | # GaussDCA
# ========
"""
Wrapper function to `GaussDCA.gDCA`.
You need to install GaussDCA:
```julia
using Pkg
Pkg.add(PackageSpec(url = "https://github.com/carlobaldassi/GaussDCA.jl", rev = "master"))
```
Look into [GaussDCA.jl README](https://github.com/carlobaldassi/GaussDCA.jl) for further information.
If you use this wrapper, **please cite the GaussDCA publication and the package's doi**.
It's possible to indicate the path to the julia binary where GaussDCA is installed.
However, it's recommended to use the same version where MIToS is installed. That is
because this function use `serialize`/`deserialize` to transfer data between the processes.
**GaussDCA Publication:**
Baldassi, Carlo, Marco Zamparo, Christoph Feinauer, Andrea Procaccini, Riccardo Zecchina, Martin Weigt, and Andrea Pagnani.
"Fast and accurate multivariate Gaussian modeling of protein families: predicting residue contacts and protein-interaction partners."
PloS one 9, no. 3 (2014): e92721.
"""
function gaussdca(
msa;
juliapath::String = joinpath(Sys.BINDIR, Base.julia_exename()),
project::String = Base.active_project(),
kargs...,
)
base_name = tempname()
if Sys.iswindows()
base_name = escape_string(base_name)
juliapath = escape_string(juliapath)
if !endswith(juliapath, ".exe")
juliapath = juliapath * ".exe"
end
end
script_file = base_name * ".jl"
msa_file = base_name * ".fasta"
jdl_file = base_name * ".jls"
plm = fill!(columnpairsmatrix(msa), NaN)
write_file(msa_file, msa, FASTA)
try
_create_script(script_file, msa_file, jdl_file; kargs...)
run(`$juliapath --project=$project $script_file`)
pairedvalues = open(deserialize, jdl_file, "r")
for (i, j, value) in pairedvalues
plm[i, j] = value
end
finally
isfile(script_file) && rm(script_file)
isfile(msa_file) && rm(msa_file)
isfile(jdl_file) && rm(jdl_file)
end
plm
end
function _create_script(script_file::String, msa_file::String, jdl_file::String; kargs...)
if length(kargs) > 0
for (k, v) in kargs
@assert isa(v, Number) || isa(v, Symbol) "Argument values must be numbers or symbols"
end
str_kargs =
"," * join([isa(v, Symbol) ? "$k=:$v" : "$k=$v" for (k, v) in kargs], ',')
else
str_kargs = ""
end
open(script_file, "w") do fh
println(fh, "using Serialization;")
println(fh, "using GaussDCA;")
println(fh, "values = GaussDCA.gDCA(\"$msa_file\"$str_kargs);")
println(fh, "open(fh -> serialize(fh, values), \"$(jdl_file)\", \"w\")")
end
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 1879 | # Pairwise Gap Percentage
# =======================
"""
It calculates the gap intersection as percentage from a table of `Frequencies`.
"""
function gap_intersection_percentage(nxy::Frequencies{T,2,GappedAlphabet}) where {T}
T(100.0) * gettablearray(nxy)[21, 21] / gettotal(nxy)
end
"""
It calculates the gap union as percentage from a table of `Frequencies`.
"""
function gap_union_percentage(nxy::Frequencies{T,2,GappedAlphabet}) where {T}
marginals = getmarginalsarray(nxy)
T(100.0) * (marginals[21, 1] + marginals[21, 2] - gettablearray(nxy)[21, 21]) /
gettotal(nxy)
end
# MIToS Pairwise Gap Percentage
# =============================
"""
It takes a MSA or a file and a `FileFormat` as first arguments. It calculates the percentage
of gaps on columns pairs (union and intersection) using sequence clustering (Hobohm I).
Argument, type, default value and descriptions:
```
- clustering Bool true Sequence clustering (Hobohm I)
- threshold 62 Percent identity threshold for sequence clustering (Hobohm I)
```
This function returns:
```
- pairwise gap union as percentage
- pairwise gap intersection as percentage
```
"""
function pairwisegapfraction(
aln::AbstractMatrix{Residue};
clustering::Bool = true,
threshold = 62,
)
clusters = clustering ? hobohmI(aln, threshold) : NoClustering()
table = Frequencies(ContingencyTable(Float64, Val{2}, GappedAlphabet()))
gu = mapcolpairfreq!(gap_union_percentage, aln, table, weights = clusters)
gi = mapcolpairfreq!(gap_intersection_percentage, aln, table, weights = clusters)
gu, gi
end
function pairwisegapfraction(
filename::String,
format::Type{T};
kargs...,
) where {T<:FileFormat}
aln = read_file(filename, T, AnnotatedMultipleSequenceAlignment, generatemapping = true)
pairwisegapfraction(aln; kargs...)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 3144 | """
The `Information` module of MIToS defines types and functions useful to calculate
information measures (e.g. *Mutual Information* (MI) and *Entropy*) over a Multiple
Sequence Alignment (MSA). This module was designed to count `Residue`s
(defined in the `MSA` module) in special contingency tables (as fast as possible) and
to derive probabilities from this counts. Also, includes methods for applying corrections
to that tables, e.g. pseudocounts and pseudo frequencies. Finally, `Information` allows to
use this probabilities and counts to estimate information measures and other
frequency based values.
**Features**
- Estimate multi dimensional frequencies and probabilities tables from sequences, MSAs, etc...
- Correction for small number of observations
- Correction for data redundancy on a MSA
- Estimate information measures
- Calculate corrected mutual information between residues
```julia
using MIToS.Information
```
"""
module Information
using MIToS.Utils
using MIToS.MSA
using Serialization # GaussDCA
using Base.Cartesian # nloops for ContingencyTables
using NamedArrays # ContingencyTables have NamedArrays
using OrderedCollections # OrderedDicts for NamedArrays
using StatsBase # entropy
using LinearAlgebra # normalize
using PairwiseListMatrices
if isdefined(Base, :count!)
import Base: count!
end
export # MIToS.MSA
GappedAlphabet,
UngappedAlphabet,
ReducedAlphabet,
# Pseudocounts
Pseudocount,
NoPseudocount,
AdditiveSmoothing,
# ContingencyTables
ContingencyTable,
Probabilities,
Frequencies,
Counts, # deprecated
getcontingencytable,
getalphabet,
gettable,
gettablearray,
getmarginals,
getmarginalsarray,
gettotal,
# update_marginals!,
apply_pseudocount!,
delete_dimensions!,
delete_dimensions,
# BLOSUM62
BLOSUM62_Pi,
BLOSUM62_Pij,
# Pseudofrequencies
Pseudofrequencies,
NoPseudofrequencies,
BLOSUM_Pseudofrequencies,
apply_pseudofrequencies!,
# Counters
count!,
frequencies,
frequencies!,
probabilities,
probabilities!,
# Iterations
mapcolfreq!,
mapseqfreq!,
mapcolpairfreq!,
mapseqpairfreq!,
mapfreq,
cumulative,
# InformationMeasures
entropy,
shannon_entropy,
marginal_entropy,
kullback_leibler,
mutual_information,
normalized_mutual_information,
# Corrections
APC!,
# CorrectedMutualInformation
buslje09,
BLMI,
# Gaps
gap_union_percentage,
gap_intersection_percentage,
pairwisegapfraction,
# Externals
gaussdca,
# Formats from MIToS.MSA
Raw,
Stockholm,
FASTA,
# Imported from Base (and exported for docs)
normalize,
normalize!,
count
include("Pseudocounts.jl")
include("ContingencyTables.jl")
include("BLOSUM62.jl")
include("Pseudofrequencies.jl")
include("Counters.jl")
include("Iterations.jl") # TO DO: Docs
include("InformationMeasures.jl")
include("Corrections.jl")
include("CorrectedMutualInformation.jl")
include("Gaps.jl")
include("Externals.jl")
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 15951 | # Entropy
# =======
const _DOC_LOG_BASE = """
The default base for the log is ℯ (`base=ℯ`), so the result is in nats. You can use
`base = 2` to get the result in bits.
"""
"""
shannon_entropy(table::Union{Frequencies{T,N,A},Probabilities{T,N,A}}; base::Number=ℯ)
It calculates the Shannon entropy (H) from a table of `Frequencies` or `Probabilities`.
Use last and optional positional argument to change the base of the log. $_DOC_LOG_BASE
"""
function shannon_entropy(table::Probabilities{T,N,A}; base::Number = ℯ) where {T,N,A}
H = zero(T)
p = gettablearray(table)
@inbounds for pᵢ in p
if pᵢ > zero(T)
H -= pᵢ * log(pᵢ)
end
end
base === ℯ ? H : (H / log(base))
end
function shannon_entropy(table::Frequencies{T,N,A}; base::Number = ℯ) where {T,N,A}
H = zero(T)
total = gettotal(table)
n = gettablearray(table)
@inbounds for nᵢ in n
if nᵢ > zero(T)
H -= nᵢ * log(nᵢ / total)
end
end
if base === ℯ
H / total # Default base: e
else
(H / total) / log(base)
end
end
function StatsBase.entropy(
table::Union{Frequencies{T,N,A},Probabilities{T,N,A}},
) where {T,N,A}
Base.depwarn(
"entropy(table::Union{Frequencies,Probabilities}) is deprecated. Use shannon_entropy(table) instead.",
:entropy,
force = true,
)
shannon_entropy(table)
end
function StatsBase.entropy(
table::Union{Frequencies{T,N,A},Probabilities{T,N,A}},
base::Real,
) where {T,N,A}
Base.depwarn(
"entropy(table::Union{Frequencies,Probabilities}, base::Real) is deprecated. Use shannon_entropy(table; base=base) instead.",
:entropy,
force = true,
)
shannon_entropy(table, base = base)
end
# using mapfreq to define the method for multiple sequence alignments
"""
shannon_entropy(msa::AbstractArray{Residue}; base::Number=ℯ,
probabilities::Bool=false, usediagonal::Bool=true, kargs...)
It calculates the Shannon entropy (H) on a MSA. You can use the keyword argument `base` to
change the base of the log. $_DOC_LOG_BASE It uses [`mapfreq`](@ref) under the hood,
so it takes the same keyword arguments. By default, it measures the entropy of each column
in the MSA. You can use `dims = 1` to measure the entropy of each sequence. You can also
set `rank = 2`to measure the joint entropy of each pair of sequences or columns. This
function sets by default the `probabilities` keyword argument to `false` because it's
faster to calculate the entropy from counts/frequencies. It also sets `usediagonal = true`
to also calculate the entropy of the individual variables (sequences or columns).
```jldoctest
julia> using MIToS.MSA, MIToS.Information
julia> msa = Residue['C' 'G'; 'C' 'L'; 'C' 'I']
3×2 Matrix{Residue}:
C G
C L
C I
julia> shannon_entropy(msa)
1×2 Named Matrix{Float64}
Function ╲ Col │ 1 2
────────────────┼─────────────────
shannon_entropy │ 0.0 1.09861
"""
function shannon_entropy(
msa::AbstractArray{Residue};
probabilities::Bool = false,
usediagonal = true,
kargs...,
)
mapfreq(
shannon_entropy,
msa;
probabilities = probabilities,
usediagonal = usediagonal,
kargs...,
)
end
# Marginal Entropy
# ----------------
function _marginal_entropy(table::Probabilities{T,N,A}, margin::Int) where {T,N,A}
H = zero(T)
marginals = getmarginalsarray(table)
@inbounds for pi in view(marginals, :, margin)
if pi > zero(T)
H += pi * log(pi)
end
end
-H # Default base: e
end
function _marginal_entropy(table::Frequencies{T,N,A}, margin::Int) where {T,N,A}
H = zero(T)
total = gettotal(table)
marginals = getmarginalsarray(table)
@inbounds for ni in view(marginals, :, margin)
if ni > zero(T)
H += ni * log(ni / total)
end
end
-H / total # Default base: e
end
"""
marginal_entropy(table::Union{Frequencies{T,N,A},Probabilities{T,N,A}}; margin::Int=1,
base::Number=ℯ)
It calculates marginal entropy (H) from a table of `Frequencies` or `Probabilities`. It takes
two keyword arguments: `margin` and `base`. The first one is used to indicate the margin
used to calculate the entropy, e.g. it estimates the entropy H(X) if margin is 1, H(Y)
for 2, etc. The default value of `margin` is 1. The second keyword argument is used to
change the base of the log. $_DOC_LOG_BASE
"""
function marginal_entropy(
table::Union{Frequencies{T,N,A},Probabilities{T,N,A}};
margin::Int = 1,
base::Number = ℯ,
) where {T,N,A}
H = _marginal_entropy(table, margin)
if base === ℯ
H # Default base: e
else
H / log(base)
end
end
# Deprecate the marginal_entropy methods taking positional arguments
function marginal_entropy(
table::Union{Frequencies{T,N,A},Probabilities{T,N,A}},
margin::Int,
) where {T,N,A}
Base.depwarn(
"marginal_entropy(table, margin) is deprecated. Use marginal_entropy(table; margin=margin) instead.",
:marginal_entropy,
force = true,
)
marginal_entropy(table, margin = margin)
end
function marginal_entropy(
table::Union{Frequencies{T,N,A},Probabilities{T,N,A}},
margin::Int,
base::Real,
) where {T,N,A}
Base.depwarn(
"marginal_entropy(table, margin, base) is deprecated. Use marginal_entropy(table; margin=margin, base=base) instead.",
:marginal_entropy,
force = true,
)
marginal_entropy(table, margin = margin, base = base)
end
# Kullback-Leibler
# ================
function _gettablearray(
table::Union{Probabilities{T,N,A},Frequencies{T,N,A},ContingencyTable{T,N,A}},
) where {T,N,A}
gettablearray(table)
end
_gettablearray(table::Array{T,N}) where {T,N} = table
const _DOC_KL_KARG = """
You can use the keyword argument `background` to set the background distribution. This
argument can take an `Array`, `Probabilities`, or `ContingencyTable` object. The background
distribution must have the same size and alphabet as the probabilities. The default is the
`BLOSUM62_Pi` table. $_DOC_LOG_BASE
"""
"""
kullback_leibler(probabilities::Probabilities{T,N,A}, background::Union{
AbstractArray{T,N}, Probabilities{T,N,A}, ContingencyTable{T,N,A}}=BLOSUM62_Pi,
base::Number=ℯ)
It calculates the Kullback-Leibler (KL) divergence from a table of `Probabilities`.
$_DOC_KL_KARG
"""
function kullback_leibler(
probabilities::Probabilities{T,N,A};
background::Union{AbstractArray{T,N},Probabilities{T,N,A},ContingencyTable{T,N,A}} = BLOSUM62_Pi,
base::Number = ℯ,
) where {T<:Number,N,A<:ResidueAlphabet}
p = getcontingencytable(probabilities)
bg = _gettablearray(background)
@assert size(background) == size(p) "probabilities and background must have the same size."
KL = zero(T)
@inbounds for i in eachindex(p)
pᵢ = p[i]
if pᵢ > zero(T)
KL += pᵢ * log(pᵢ / bg[i])
end
end
if base === ℯ
KL # Default base: e
else
KL / log(base)
end
end
# Kullback-Leibler for MSA
"""
kullback_leibler(msa::AbstractArray{Residue}; background::Union{Array{T,N}, Probabilities{T,N,A}, ContingencyTable{T,N,A}}=BLOSUM62_Pi, base::Number=ℯ, kargs...)
It calculates the Kullback-Leibler (KL) divergence from a multiple sequence alignment (MSA).
$_DOC_KL_KARG The other keyword arguments are passed to the [`mapfreq`](@ref) function.
"""
function kullback_leibler(
msa::AbstractArray{Residue};
background::AbstractArray = BLOSUM62_Pi,
base::Number = ℯ,
rank::Int = 1,
kargs...,
)
@assert rank == 1 "rank must be 1 for kullback_leibler"
mapfreq(
kullback_leibler,
msa;
rank = rank,
background = background,
base = base,
kargs...,
)
end
# Deprecate the old methods
# Method with positional arguments for background and base
function kullback_leibler(
p::Probabilities{T,N,A},
q::AbstractArray{T,N},
base::Real,
) where {T<:Number,N,A<:ResidueAlphabet}
Base.depwarn(
"kullback_leibler(p, q, base) is deprecated. Use kullback_leibler(p; background=q, base=base) instead.",
:kullback_leibler,
force = true,
)
kullback_leibler(p; background = q, base = base)
end
# Method with positional argument for background
function kullback_leibler(p::Probabilities{T,N,A}, q::AbstractArray{T,N}) where {T,N,A}
Base.depwarn(
"kullback_leibler(p, q) is deprecated. Use kullback_leibler(p; background=q) instead.",
:kullback_leibler,
force = true,
)
kullback_leibler(p; background = q)
end
# Method with positional argument for base
function kullback_leibler(p::Probabilities{T,N,A}, base::Real) where {T,N,A}
Base.depwarn(
"kullback_leibler(p, base) is deprecated. Use kullback_leibler(p; base=base) instead.",
:kullback_leibler,
force = true,
)
kullback_leibler(p; base = base)
end
# Mutual Information
# ==================
# It avoids ifelse() because log is expensive (https://github.com/JuliaLang/julia/issues/8869)
@inline function _mi(::Type{T}, pij, pi, pj) where {T}
(pij > zero(T)) && (pi > zero(T)) ? T(pij * log(pij / (pi * pj))) : zero(T)
end
"""
Information._mutual_information(table::Union{Frequencies{T,2,A},Probabilities{T,2,A}}) where {T,A}
It calculates Mutual Information (MI) from a table of `Frequencies` or `Probabilities` using ℯ as
the base of the log. This function is the kernel of the `mutual_information` function. It is
also used to calculate the MI values of different MIToS functions that do not require the
base of the log as an argument. In particular, the `buslje09` and `BLMI` functions use this
function.
"""
function _mutual_information(table::Probabilities{T,2,A}) where {T,A}
MI = zero(T)
marginals = getmarginalsarray(table)
p = gettablearray(table)
N = size(marginals, 1)
@inbounds for j = 1:N
pj = marginals[j, 2]
if pj > zero(T)
@inbounds @simd for i = 1:N
MI += _mi(T, p[i, j], marginals[i, 1], pj)
end
end
end
MI
end
"""
mutual_information(table::Union{Frequencies{T,2,A},Probabilities{T,2,A}}; base::Number=ℯ)
It calculates Mutual Information (MI) from a table of `Frequencies` or `Probabilities`.
$_DOC_LOG_BASE Note that calculating MI from `Frequencies` is faster than from `Probabilities`.
"""
function mutual_information(table::Probabilities{T,2,A}; base::Number = ℯ) where {T,A}
mi = _mutual_information(table)
base === ℯ ? mi : (mi / log(base)) # Default base: e
end
# It avoids ifelse() because log is expensive (https://github.com/JuliaLang/julia/issues/8869)
@inline function _mi(total::T, nij, ni, nj) where {T}
(nij > zero(T)) && (ni > zero(T)) ? T(nij * log((total * nij) / (ni * nj))) : zero(T)
end
function _mutual_information(table::Frequencies{T,2,A}) where {T,A}
mi = zero(T)
marginals = getmarginalsarray(table)
n = gettablearray(table)
total = gettotal(table)
N = size(marginals, 1)
@inbounds for j = 1:N
nj = marginals[j, 2]
if nj > zero(T)
@inbounds @simd for i = 1:N
mi += _mi(total, n[i, j], marginals[i, 1], nj)
end
end
end
mi / total
end
function mutual_information(table::Frequencies{T,2,A}; base::Number = ℯ) where {T,A}
mi = _mutual_information(table)
base === ℯ ? mi : (mi / log(base)) # Default base: e
end
function mutual_information(
table::Union{Frequencies{T,N,A},Probabilities{T,N,A}},
base::Real,
) where {T,N,A}
Base.depwarn(
"mutual_information(table, base) is deprecated. Use mutual_information(table; base=base) instead.",
:mutual_information,
force = true,
)
mutual_information(table, base = base)
end
"""
mutual_information(table::Union{Frequencies{T,3,A},Probabilities{T,3,A}}; base::Number=ℯ)
It calculates Mutual Information (MI) from a table of `Frequencies` or `Probabilities` with three
dimensions. $_DOC_LOG_BASE
```jldoctest
julia> using Random, MIToS.MSA, MIToS.Information
julia> msa = rand(Random.MersenneTwister(37), Residue, 3, 4)
3×4 Matrix{Residue}:
T R F K
S H C I
G G R V
julia> Nxyz = frequencies(msa[:, 1], msa[:, 2], msa[:, 3]);
julia> mutual_information(Nxyz)
1.0986122886681093
```
"""
function mutual_information(
pxyz::Union{Frequencies{T,3,A},Probabilities{T,3,A}};
base::Number = ℯ,
) where {T,A}
pxy = delete_dimensions(pxyz, 3)
mi = (
marginal_entropy(pxyz, margin = 1) + # H(X) +
marginal_entropy(pxyz, margin = 2) + # H(Y) +
marginal_entropy(pxyz, margin = 3) - # H(Z) -
shannon_entropy(pxy) - # H(X,Y) -
shannon_entropy(delete_dimensions!(pxy, pxyz, 2)) - # H(X,Z) -
shannon_entropy(delete_dimensions!(pxy, pxyz, 2)) + # H(Y,Z) +
shannon_entropy(pxyz) # H(X,Y,Z)
)
base === ℯ ? mi : (mi / log(base))
end
"""
mutual_information(msa::AbstractArray{Residue}; base::Number=ℯ, kargs...)
It calculates Mutual Information (MI) from a multiple sequence alignment (MSA).
$_DOC_LOG_BASE The minimum value for `rank` is 2 (the default value). By defualt, it
uses counts/frequencies to calculate the MI, as it's faster. You can use the keyword
argument `probabilities = true` to calculate the MI from probabilities.
```jldoctest
julia> using Random, MIToS.MSA, MIToS.Information
julia> msa = rand(Random.MersenneTwister(37), Residue, 3, 4)
3×4 Matrix{Residue}:
T R F K
S H C I
G G R V
julia> mutual_information(msa)
4×4 Named PairwiseListMatrices.PairwiseListMatrix{Float64, false, Vector{Float64}}
Col1 ╲ Col2 │ 1 2 3 4
────────────┼───────────────────────────────────
1 │ NaN 1.09861 1.09861 1.09861
2 │ 1.09861 NaN 1.09861 1.09861
3 │ 1.09861 1.09861 NaN 1.09861
4 │ 1.09861 1.09861 1.09861 NaN
````
"""
function mutual_information(
msa::AbstractArray{Residue};
rank::Int = 2,
probabilities::Bool = false,
base::Number = ℯ,
kargs...,
)
@assert rank > 1 "rank must be greater than 1 for mutual_information"
mapfreq(
mutual_information,
msa;
rank = rank,
probabilities = probabilities,
base = base,
kargs...,
)
end
# Normalized Mutual Information by Entropy
# ----------------------------------------
const _DOC_NMI = """
The mutual information score is normalized by the joint entropy of the
two variables: \$nMI(X, Y) = MI(X, Y) / H(X, Y)\$
"""
"""
It calculates a Normalized Mutual Information (nMI) from a table of `Frequencies` or
`Probabilities`. $_DOC_NMI
"""
function normalized_mutual_information(
table::Union{Frequencies{T,N,A},Probabilities{T,N,A}},
) where {T,N,A}
H = shannon_entropy(table)
if H != zero(T)
MI = _mutual_information(table)
return (T(MI / H))
else
return (zero(T))
end
end
"""
normalized_mutual_information(msa::AbstractArray{Residue}; kargs...)
This function calculates the Normalized Mutual Information (nMI) from a multiple sequence
alignment using the [`mapfreq`](@ref) function—all the keyword arguments are passed to
`mapfreq`. $_DOC_NMI By default, it uses counts/frequencies to estimate the nMI, as it's
faster than using probabilities.
"""
function normalized_mutual_information(
msa::AbstractArray{Residue};
rank::Int = 2,
probabilities::Bool = false,
kargs...,
)
@assert rank > 1 "rank must be greater than 1 for normalized_mutual_information"
mapfreq(
normalized_mutual_information,
msa,
rank = rank,
probabilities = probabilities,
kargs...,
)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 15140 | function _get_matrix_residue(msa::AbstractMultipleSequenceAlignment)::Matrix{Residue}
getarray(namedmatrix(msa))
end
_get_matrix_residue(msa::NamedArray)::Matrix{Residue} = getarray(msa)
_get_matrix_residue(msa::Matrix{Residue})::Matrix{Residue} = msa
# Kernel function to fill ContingencyTable based on residues
function _mapfreq_kernel!(
f::Function,
freqtable::Union{Probabilities{T,N,A},Frequencies{T,N,A}},
weights,
pseudocounts,
pseudofrequencies,
res::Vararg{AbstractVector{Residue},N};
kargs...,
) where {T,N,A}
table = freqtable.table
_cleanup_table!(table) # frequencies! calls _cleanup_temporal! and cleans marginals
frequencies!(table, res..., weights = weights, pseudocounts = pseudocounts) # frequencies! calls apply_pseudocount! and _update!
if isa(freqtable, Probabilities{T,N,A})
normalize!(table)
apply_pseudofrequencies!(table, pseudofrequencies)
end
f(freqtable; kargs...)
end
_mapfreq_kargs_doc = """
- `weights` (default: `NoClustering()`): Weights to be used for table counting.
- `pseudocounts` (default: `NoPseudocount()`): `Pseudocount` object to be applied to table.
- `pseudofrequencies` (default: `NoPseudofrequencies()`): `Pseudofrequencies` to be applied to the normalized (probabilities) table.
"""
_mappairfreq_kargs_doc = """
- `usediagonal` (default: `true`): If `true`, the function will be also applied to the diagonal elements.
- `diagonalvalue` (default: `zero`): Value to fill diagonal elements if `usediagonal` is `false`.
"""
# Residues: The output is a Named Vector
# --------------------------------------
function _mapfreq!(
f::Function,
res_list::Vector{V}, # sequences or columns
table::Union{Probabilities{T,1,A},Frequencies{T,1,A}};
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
pseudofrequencies::Pseudofrequencies = NoPseudofrequencies(),
kargs...,
) where {T,A,V<:AbstractArray{Residue}}
scores = map(res_list) do res
_mapfreq_kernel!(f, table, weights, pseudocounts, pseudofrequencies, res; kargs...)
end
scores
end
# Map to each column
"""
It efficiently map a function (first argument) that takes a table of `Frequencies` or
`Probabilities` (third argument). The table is filled in place with the counts or
probabilities of each column from the `msa` (second argument).
$_mapfreq_kargs_doc
"""
function mapcolfreq!(
f::Function,
msa::AbstractMatrix{Residue},
table::Union{Probabilities{T,1,A},Frequencies{T,1,A}};
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
pseudofrequencies::Pseudofrequencies = NoPseudofrequencies(),
kargs...,
) where {T,A}
N = ncolumns(msa)
residues = _get_matrix_residue(msa)
ncol = size(residues, 2)
columns = map(i -> view(residues, :, i), 1:ncol) # 2x faster than calling view inside the loop
scores = _mapfreq!(
f,
columns,
table;
weights = weights,
pseudocounts = pseudocounts,
pseudofrequencies = pseudofrequencies,
kargs...,
)
name_list = columnnames(msa)
NamedArray(
reshape(scores, (1, N)),
(
OrderedDict{String,Int}(string(f) => 1),
OrderedDict{String,Int}(name_list[i] => i for i = 1:N),
),
("Function", "Col"),
)
end
# Map to each sequence
"""
It efficiently map a function (first argument) that takes a table of `Frequencies` or
`Probabilities` (third argument). The table is filled in place with the counts or
probabilities of each sequence from the `msa` (second argument).
$_mapfreq_kargs_doc
"""
function mapseqfreq!(
f::Function,
msa::AbstractMatrix{Residue},
table::Union{Probabilities{T,1,A},Frequencies{T,1,A}};
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
pseudofrequencies::Pseudofrequencies = NoPseudofrequencies(),
kargs...,
) where {T,A}
N = nsequences(msa)
sequences = getresiduesequences(msa)
name_list = sequencenames(msa)
scores = _mapfreq!(
f,
sequences,
table;
weights = weights,
pseudocounts = pseudocounts,
pseudofrequencies = pseudofrequencies,
kargs...,
)
NamedArray(
reshape(scores, (N, 1)),
(
OrderedDict{String,Int}(name_list[i] => i for i = 1:N),
OrderedDict{String,Int}(string(f) => 1),
),
("Seq", "Function"),
)
end
# Residue pairs: The output is a Named PairwiseListMatrix
# -------------------------------------------------------
function _mappairfreq!(
f::Function,
res_list::Vector{V}, # sequences or columns
plm::PairwiseListMatrix{T,D,TV}, # output
table::Union{Probabilities{T,2,A},Frequencies{T,2,A}},
usediagonal::Type{Val{D}} = Val{true};
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
pseudofrequencies::Pseudofrequencies = NoPseudofrequencies(),
kargs...,
) where {T,D,TV,A,V<:AbstractArray{Residue}}
@inbounds @iterateupper plm D begin
list[k] = _mapfreq_kernel!(
f,
table,
weights,
pseudocounts,
pseudofrequencies,
res_list[i],
res_list[j];
kargs...,
)
end
plm
end
# Map to column pairs
"""
It efficiently map a function (first argument) that takes a table of `Frequencies` or
`Probabilities` (third argument). The table is filled in place with the counts or
probabilities of each pair of columns from the `msa` (second argument).
$_mapfreq_kargs_doc
$_mappairfreq_kargs_doc
"""
function mapcolpairfreq!(
f::Function,
msa::AbstractMatrix{Residue},
table::Union{Probabilities{T,2,A},Frequencies{T,2,A}};
usediagonal::Bool = true,
diagonalvalue::T = zero(T),
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
pseudofrequencies::Pseudofrequencies = NoPseudofrequencies(),
kargs...,
) where {T,A}
ncol = ncolumns(msa)
residues = _get_matrix_residue(msa)
columns = map(i -> view(residues, :, i), 1:ncol) # 2x faster than calling view inside the loop
scores = columnpairsmatrix(msa, T, Val{usediagonal}, diagonalvalue) # Named PairwiseListMatrix
plm = getarray(scores)
_mappairfreq!(
f,
columns,
plm,
table,
Val{usediagonal};
weights = weights,
pseudocounts = pseudocounts,
pseudofrequencies = pseudofrequencies,
kargs...,
)
scores
end
# DEPRECATED, usediagonal is now a boolean keyword argument
function mapcolpairfreq!(f, msa, table, usediagonal::Type{Val{D}}; kargs...) where {D}
Base.depwarn(
"The `usediagonal` positional argument of `mapcolpairfreq!` taking `Val{true}` or `Val{false}` is deprecated. Use `usediagonal = true` or `usediagonal = false` instead.",
:mapcolpairfreq!,
force = true,
)
mapcolpairfreq!(f, msa, table; usediagonal = D, kargs...)
end
# Map to sequence pairs
"""
It efficiently map a function (first argument) that takes a table of `Frequencies` or
`Probabilities` (third argument). The table is filled in place with the counts or
probabilities of each pair of sequences from the `msa` (second argument).
$_mapfreq_kargs_doc
$_mappairfreq_kargs_doc
"""
function mapseqpairfreq!(
f::Function,
msa::AbstractMatrix{Residue},
table::Union{Probabilities{T,2,A},Frequencies{T,2,A}};
usediagonal::Bool = true,
diagonalvalue::T = zero(T),
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
pseudofrequencies::Pseudofrequencies = NoPseudofrequencies(),
kargs...,
) where {T,A}
sequences = getresiduesequences(msa)
scores = sequencepairsmatrix(msa, T, Val{usediagonal}, diagonalvalue) # Named PairwiseListMatrix
plm = getarray(scores)
_mappairfreq!(
f,
sequences,
plm,
table,
Val{usediagonal};
weights = weights,
pseudocounts = pseudocounts,
pseudofrequencies = pseudofrequencies,
kargs...,
)
scores
end
# DEPRECATED, usediagonal is now a boolean keyword argument
function mapseqpairfreq!(f, msa, table, usediagonal::Type{Val{D}}; kargs...) where {D}
Base.depwarn(
"The `usediagonal` positional argument of mapseqpairfreq! taking `Val{true}` or `Val{false}` is deprecated. Use `usediagonal = true` or `usediagonal = false` instead.",
:mapseqpairfreq!,
force = true,
)
mapseqpairfreq!(f, msa, table; usediagonal = D, kargs...)
end
# General mapfreq methods
# =======================
# The doctest for rank=2 can not be supported simultaneously for Julia 1.6 and 1.10
# because of the different behavior when printing the matrix headers.
# Therefore, the following docstest could be added once we drop support for Julia 1.6:
# mapfreq(sum, msa, rank=2)
# mapfreq(sum, msa, dims=1, rank=2)
"""
mapfreq(f, msa; rank = 1, dims = 2, alphabet = UngappedAlphabet(),
weights = NoClustering(), pseudocounts = NoPseudocount(),
pseudofrequencies = NoPseudofrequencies(), probabilities = true,
usediagonal = false, diagonalvalue = NaN, kargs...)
It efficiently map a function (first argument) that takes a table of `Frequencies` or
`Probabilities` (depending on the `probabilities` keyword argument) calculated on
sequences (`dims = 1`) or columns (`dims = 2`, the default) of an `msa` (second argument).
If `rank = 1`, the default, the function is applied to each sequence or column. If
`rank = 2`, the function is applied to each pair of sequences or columns. In that case,
we can set the `usediagonal` keyword argument to `true` to apply the function to pairs
of the same sequence or column. The `diagonalvalue` keyword argument is used to set the
value of the diagonal elements if `usediagonal` is `false`. By default, the function is not
applied to the diagonal elements (i.e. `usediagonal = false`) and the `diagonalvalue` is
set to `NaN`. The `alphabet` keyword argument can be used to set the alphabet used to
construct the contingency table. The function also accepts the following keyword arguments:
$_mapfreq_kargs_doc
Note that the `pseudofrequencies` argument is only valid if `probabilities = true`. All the
other keyword arguments are passed to the function `f`.
```jldoctest
julia> using Random, MIToS.MSA, MIToS.Information
julia> msa = rand(Random.MersenneTwister(1), Residue, 3, 6) # random MSA as an example
3×6 Matrix{Residue}:
F A F D E V
T R R G F I
N V S W Q T
julia> mapfreq(sum, msa) # default: rank=1, dims=2, probabilities=true
1×6 Named Matrix{Float64}
Function ╲ Col │ 1 2 3 4 5 6
───────────────┼─────────────────────────────
sum │ 1.0 1.0 1.0 1.0 1.0 1.0
julia> mapfreq(sum, msa, probabilities=false)
1×6 Named Matrix{Float64}
Function ╲ Col │ 1 2 3 4 5 6
───────────────┼─────────────────────────────
sum │ 3.0 3.0 3.0 3.0 3.0 3.0
julia> mapfreq(sum, msa, dims=1)
3×1 Named Matrix{Float64}
Seq ╲ Function │ sum
───────────────┼────
1 │ 1.0
2 │ 1.0
3 │ 1.0
```
"""
function mapfreq(
f::Function,
msa::AbstractArray{Residue};
rank::Int = 1,
dims::Int = 2,
alphabet::ResidueAlphabet = UngappedAlphabet(),
weights::WeightTypes = NoClustering(),
pseudocounts::Pseudocount = NoPseudocount(),
pseudofrequencies::Pseudofrequencies = NoPseudofrequencies(),
probabilities::Bool = true,
usediagonal::Bool = false,
diagonalvalue::Float64 = NaN,
kargs...,
)
# Ensure that the keyword arguments are correct
@assert dims == 1 || dims == 2 "The dimension must be 1 (sequences) or 2 (columns)."
@assert rank == 1 || rank == 2 "The rank must be 1 (single sequences or columns) or 2 (pairs)."
if pseudofrequencies !== NoPseudofrequencies()
@assert probabilities "Set `probabilities = true` to use pseudofrequencies."
end
# Define the table to apply the function
_table = ContingencyTable(Float64, Val{rank}, alphabet)
table = probabilities ? Probabilities(_table) : Frequencies(_table)
if rank == 1
if dims == 1
mapseqfreq!(
f,
msa,
table;
weights = weights,
pseudocounts = pseudocounts,
pseudofrequencies = pseudofrequencies,
kargs...,
)
else
mapcolfreq!(
f,
msa,
table;
weights = weights,
pseudocounts = pseudocounts,
pseudofrequencies = pseudofrequencies,
kargs...,
)
end
else
if dims == 1
mapseqpairfreq!(
f,
msa,
table;
usediagonal = usediagonal,
diagonalvalue = diagonalvalue,
weights = weights,
pseudocounts = pseudocounts,
pseudofrequencies = pseudofrequencies,
kargs...,
)
else
mapcolpairfreq!(
f,
msa,
table;
usediagonal = usediagonal,
diagonalvalue = diagonalvalue,
weights = weights,
pseudocounts = pseudocounts,
pseudofrequencies = pseudofrequencies,
kargs...,
)
end
end
end
# cMI
# ===
"""
`cumulative` allows to calculate cumulative scores (i.e. cMI) as defined
in *Marino Buslje et al. 2010*:
> "We calculated a cumulative mutual information score (cMI) for each residue as the
> sum of MI values above a certain threshold for every amino acid pair where the particular
> residue appears. This value defines to what degree a given amino acid takes part in a
> mutual information network."
# References
- [Marino Buslje, Cristina, et al. "Networks of high mutual information define the
structural proximity of catalytic sites: implications for catalytic residue
identification." PLoS computational biology 6.11 (2010):
e1000978.](@cite marino2010networks)
"""
function cumulative(plm::PairwiseListMatrix{T,D,VT}, threshold::T) where {T,D,VT}
N = size(plm, 1)
out = zeros(T, N)
@iterateupper plm false begin
elem = list[k]
if !isnan(elem) && elem >= threshold
out[i] += elem
out[j] += elem
end
end
reshape(out, (1, N))
end
function cumulative(
nplm::NamedArray{T,2,PairwiseListMatrix{T,D,TV},DN},
threshold::T,
) where {T,D,TV,DN}
N = size(nplm, 2)
name_list = names(nplm, 2)
NamedArray(
cumulative(getarray(nplm), threshold),
(
OrderedDict{String,Int}("cumulative" => 1),
OrderedDict{String,Int}(name_list[i] => i for i = 1:N),
),
("Function", dimnames(nplm, 2)),
)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 1864 | # Pseudocounts
# ============
"""
Parametric abstract type to define pseudocount types
"""
abstract type Pseudocount{T<:Real} end
"""
You can use `NoPseudocount()` to avoid pseudocount corrections where a
`Pseudocount` type is needed.
"""
struct NoPseudocount <: Pseudocount{Float64} end
"""
**Additive Smoothing** or fixed pseudocount `λ` for `ResidueCount`
(in order to estimate probabilities when the number of samples is low).
Common values of `λ` are:
- `0` : No cell frequency prior, gives you the maximum likelihood estimator.
- `0.05` is the optimum value for `λ` found in *Buslje et. al. 2009*, similar results was obtained for `λ` in the range [0.025, 0.075].
- `1 / p` : Perks prior (Perks, 1947) where `p` the number of parameters (i.e. residues, pairs of residues) to estimate. If `p` is the number of residues (`20` without counting gaps), this gives you `0.05`.
- `sqrt(n) / p` : Minimax prior (Trybula, 1958) where `n` is the number of samples and `p` the number of parameters to estimate. If the number of samples `n` is 400 (minimum number of sequence clusters for achieve good performance in *Buslje et. al. 2009*) for estimating 400 parameters (pairs of residues without counting gaps) this gives you `0.05`.
- `0.5` : Jeffreys prior (Jeffreys, 1946).
- `1` : Bayes-Laplace uniform prior, aka. Laplace smoothing.
# References
- [Buslje, Cristina Marino, et al. "Correction for phylogeny, small number of
observations and data redundancy improves the identification of coevolving
amino acid pairs using mutual information."
Bioinformatics 25.9 (2009): 1125-1131.](@cite buslje2009correction)
"""
struct AdditiveSmoothing{T} <: Pseudocount{T}
λ::T
end
Base.zero(::Type{AdditiveSmoothing{T}}) where {T} = AdditiveSmoothing(zero(T))
Base.one(::Type{AdditiveSmoothing{T}}) where {T} = AdditiveSmoothing(one(T))
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 3332 | # Pseudofrequencies
# =================
"""
Parametric abstract type to define pseudofrequencies types
"""
abstract type Pseudofrequencies end
"""
You can use `NoPseudofrequencies()` to avoid pseudocount corrections where a
`Pseudofrequencies` type is needed.
"""
struct NoPseudofrequencies <: Pseudofrequencies end
# BLOSUM based pseudofrequencies
# ==============================
"""
`BLOSUM_Pseudofrequencies` type. It takes to arguments/fields:
- `α` : Usually the number of sequences or sequence clusters in the MSA.
- `β` : The weight of the pseudofrequencies, a value close to 8.512 when `α` is the number of sequence clusters.
"""
struct BLOSUM_Pseudofrequencies <: Pseudofrequencies
α::Float64
β::Float64
end
"""
`_calculate_blosum_pseudofrequencies!{T}(Pab::ContingencyTable{T,2,UngappedAlphabet})`
This function uses the conditional probability matrix `BLOSUM62_Pij` to fill the temporal
array field of `Pab` with pseudo frequencies (`Gab`). This function needs the real
frequencies/probabilities `Pab` because they are used to estimate the pseudofrequencies.
`Gab = Σcd Pcd ⋅ BLOSUM62( a | c ) ⋅ BLOSUM62( b | d )`
"""
function _calculate_blosum_pseudofrequencies!(
Pab::ContingencyTable{T,2,UngappedAlphabet},
) where {T}
@assert gettotal(Pab) ≈ one(T) "The input should be a probability table (normalized)"
pab = getarray(gettable(Pab))
gab = Pab.temporal
bl62 = getarray(gettable(BLOSUM62_Pij))
total = zero(T)
@inbounds for b = 1:20, a = 1:20
gab[a, b] = zero(T)
for d = 1:20
bl62_db = bl62[d, b]
for c = 1:20
P = pab[c, d]
if P != 0
# BLOSUM62_Pij[c,a] is p(a|c)
gab[a, b] += (P * bl62[c, a] * bl62_db)
end
end
end
total += gab[a, b]
end
if total ≉ one(T)
@inbounds for col = 1:20
@simd for row = 1:20
gab[row, col] /= total
end
end
end
Pab
end
"""
`apply_pseudofrequencies!{T}(Pab::ContingencyTable{T,2,UngappedAlphabet}, pseudofrequencies::BLOSUM_Pseudofrequencies)`
When a `BLOSUM_Pseudofrequencies(α,β)` is used, this function applies pseudofrequencies
`Gab` over `Pab`, as a weighted mean of both. It uses the conditional probability
matrix `BLOSUM62_Pij` and the real frequencies/probabilities `Pab` to estimate the
pseudofrequencies `Gab`. α is the weight of the real frequencies `Pab` and β the weight
of the pseudofrequencies.
`Gab = Σcd Pcd ⋅ BLOSUM62( a | c ) ⋅ BLOSUM62( b | d )`
`Pab = (α ⋅ Pab + β ⋅ Gab )/(α + β)`
"""
function apply_pseudofrequencies!(
Pab::ContingencyTable{T,2,UngappedAlphabet},
pseudofrequencies::BLOSUM_Pseudofrequencies,
) where {T}
α = T(pseudofrequencies.α)
β = T(pseudofrequencies.β)
if β == 0.0
return (Pab)
end
_calculate_blosum_pseudofrequencies!(Pab)
pab = getarray(gettable(Pab))
gab = Pab.temporal
frac = one(T) / (α + β)
@inbounds for col = 1:20
@simd for row = 1:20
pab[row, col] = (α * pab[row, col] + β * gab[row, col]) * frac
end
end
update_marginals!(Pab)
normalize!(Pab)
end
@inline apply_pseudofrequencies!(
Pab::ContingencyTable,
pseudofrequencies::NoPseudofrequencies,
) = Pab
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 2359 | struct A3M <: MSAFormat end
struct A2M <: MSAFormat end
function _add_insert_gaps!(SEQS)
seq_len = length.(SEQS)
ncol = maximum(seq_len)
j = 1
is_insert = false
while j <= ncol
for i = 1:length(SEQS)
if j <= seq_len[i]
res = SEQS[i][j]
if islowercase(res) || res == '.'
is_insert = true
break
end
end
end
if is_insert
for i = 1:length(SEQS)
seq = SEQS[i]
if j > seq_len[i]
SEQS[i] = seq * "."
seq_len[i] += 1
else
res = seq[j]
if isuppercase(res) || res == '-'
SEQS[i] = seq[1:j-1] * "." * seq[j:end]
seq_len[i] += 1
end
end
end
ncol = maximum(seq_len)
end
is_insert = false
j += 1
end
SEQS
end
function _load_sequences(
io::Union{IO,AbstractString},
format::Type{A3M};
create_annotations::Bool = false,
)
IDS, SEQS = _pre_readfasta(io)
_check_seq_and_id_number(IDS, SEQS)
try
_check_seq_len(IDS, SEQS)
catch
SEQS = _add_insert_gaps!(SEQS)
end
return IDS, SEQS, Annotations()
end
# A2M is similar to FASTA but uses lowercase letters and dots for inserts. In the A2M
# format, all sequences have the same length. Since MIToS handles the inserts, we can load
# it as FASTA. However, I will use the A3M parser instead of the FASTA parser to ensure
# the file can be read correctly if the user confuses A2M with A3M.
_load_sequences(io::Union{IO,AbstractString}, format::Type{A2M}) = _load_sequences(io, A3M)
# Print A3M
# =========
function Utils.print_file(
io::IO,
msa::AbstractMatrix{Residue},
format::Union{Type{A3M},Type{A2M}},
)
seqnames = sequencenames(msa)
aligned = _get_aligned_columns(msa)
for i = 1:nsequences(msa)
seq = stringsequence(msa, i)
# A2M uses dots for gaps aligned to insertions, but A3M can avoid them
keep_insert_gaps = format === A2M
formatted_seq = _format_inserts(seq, aligned, keep_insert_gaps)
println(io, ">", seqnames[i])
println(io, formatted_seq)
end
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 5552 | """
Abstract type to define residue alphabet types.
"""
abstract type ResidueAlphabet end
"""
This type defines the usual alphabet of the 20 natural residues and a gap character.
```jldoctest
julia> using MIToS.MSA
julia> GappedAlphabet()
GappedAlphabet of length 21. Residues : res"ARNDCQEGHILKMFPSTWYV-"
```
"""
struct GappedAlphabet <: ResidueAlphabet end
"""
This type defines the usual alphabet of the 20 natural residues, without the gap character.
```jldoctest
julia> using MIToS.MSA
julia> UngappedAlphabet()
UngappedAlphabet of length 20. Residues : res"ARNDCQEGHILKMFPSTWYV"
```
"""
struct UngappedAlphabet <: ResidueAlphabet end
"""
`ReducedAlphabet` allows the construction of reduced residue alphabets, where residues
inside parenthesis belong to the same group.
```jldoctest
julia> using MIToS.MSA
julia> ab = ReducedAlphabet("(AILMV)(RHK)(NQST)(DE)(FWY)CGP")
ReducedAlphabet of length 8 : "(AILMV)(RHK)(NQST)(DE)(FWY)CGP"
julia> ab[Residue('K')]
2
```
"""
struct ReducedAlphabet <: ResidueAlphabet
mapping::Array{Int,1} # Residue -> Int
named::NamedArray{Int,1,Array{Int,1},Tuple{OrderedDict{String,Int}}}
len::Int
end
# Creation
# --------
function ReducedAlphabet(str::AbstractString)
N = Int(XAA)
mapping = fill!(Array{Int}(undef, N), N)
ingroup = false
pos = 0
group_names = fill!(Array{String}(undef, N), "")
for char in str
if char == '('
ingroup = true
pos += 1
continue
end
if char == ')'
ingroup = false
continue
end
if !ingroup
pos += 1
end
int_residue = Int(Residue(char))
@assert int_residue != 22 "$char isn't valid for a residue alphabet." # N == 22
group_names[pos] = string(group_names[pos], char)
mapping[int_residue] = pos
end
named = NamedArray(
collect(1:pos),
(OrderedDict{String,Int}(group_names[i] => i for i = 1:pos),),
("Groups",),
)
ReducedAlphabet(mapping, named, pos)
end
# Iteration Interface
# -------------------
Base.length(ab::UngappedAlphabet) = 20
Base.length(ab::GappedAlphabet) = 21
Base.length(ab::ReducedAlphabet) = ab.len
Base.eltype(::ResidueAlphabet) = Int
function Base.iterate(ab::ResidueAlphabet, state = 0)
if state ≥ length(ab)
return nothing
else
next_state = state + 1
return (next_state, next_state)
end
end
# Show
# ----
function Base.show(io::IO, ab::ResidueAlphabet)
print(
io,
typeof(ab),
" of length ",
length(ab),
". Residues : res\"",
join(_to_char[1:length(ab)]),
"\"",
)
end
function Base.show(io::IO, ab::ReducedAlphabet)
groups = names(ab.named, 1)
print(io, "ReducedAlphabet of length ", length(ab), " : \"")
for i in ab
chars = groups[i]
if length(chars) == 1
print(io, chars[1])
elseif length(chars) > 1
print(io, "(", join(chars), ")")
end
end
print(io, "\"")
end
# getindex
# --------
@inline function Base.getindex(ab::ResidueAlphabet, res::Int)::Int
ifelse(res <= length(ab), res, 22)
end
@inline function Base.getindex(ab::ReducedAlphabet, res::Int)::Int
@inbounds value = ab.mapping[res]
value
end
@inline function Base.getindex(ab::ResidueAlphabet, res::Residue)::Int
ab[Int(res)]
end
@inline function Base.getindex(ab::ResidueAlphabet, res::String)::Int
@assert length(res) == 1 "The string with the residue should have only one character."
i = Int(Residue(res[1]))
ifelse(i <= length(ab), i, 22)
end
@inline function Base.getindex(ab::ReducedAlphabet, res::String)::Int
@inbounds value = ab.named[res]
value
end
# In Alphabet
# -----------
Base.in(res::Residue, alphabet::ResidueAlphabet) = Int(res) <= length(alphabet)
Base.in(res::Residue, alphabet::ReducedAlphabet) = alphabet[res] != 22
# Names
# -----
"""
It returns the name of each group. The name is a string with the one letter code of each
residue that belong to the group.
```jldoctest
julia> using MIToS.MSA
julia> ab = ReducedAlphabet("(AILMV)(RHK)(NQST)(DE)(FWY)CGP")
ReducedAlphabet of length 8 : "(AILMV)(RHK)(NQST)(DE)(FWY)CGP"
julia> names(ab)
8-element Vector{String}:
"AILMV"
"RHK"
"NQST"
"DE"
"FWY"
"C"
"G"
"P"
```
"""
Base.names(alphabet::ReducedAlphabet) = names(alphabet.named, 1)
Base.names(alphabet::ResidueAlphabet) = String[string(Residue(i)) for i in alphabet]
# Dict of names to indexes
# ------------------------
@inline _getdict(n::NamedArray{Int,1,Array{Int,1},Tuple{OrderedDict{String,Int}}}) =
n.dicts[1]
const _UngappedAlphabet_Names =
OrderedDict{String,Int}(string(Residue(i)) => i for i = 1:20)
const _GappedAlphabet_Names = OrderedDict{String,Int}(string(Residue(i)) => i for i = 1:21)
@inline getnamedict(alphabet::UngappedAlphabet) = _UngappedAlphabet_Names
@inline getnamedict(alphabet::GappedAlphabet) = _GappedAlphabet_Names
"""
It takes a `ResidueAlphabet` and returns a dictionary from group name to group position.
```jldoctest
julia> using MIToS.MSA
julia> ab = ReducedAlphabet("(AILMV)(RHK)(NQST)(DE)(FWY)CGP")
ReducedAlphabet of length 8 : "(AILMV)(RHK)(NQST)(DE)(FWY)CGP"
julia> getnamedict(ab)
OrderedCollections.OrderedDict{String, Int64} with 8 entries:
"AILMV" => 1
"RHK" => 2
"NQST" => 3
"DE" => 4
"FWY" => 5
"C" => 6
"G" => 7
"P" => 8
```
"""
@inline getnamedict(alphabet::ReducedAlphabet) = _getdict(copy(alphabet.named))
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 13896 | # Annotations
# ===========
"""
The `Annotations` type is basically a container for `Dict`s with the annotations of a
multiple sequence alignment. `Annotations` was designed for storage of annotations of
the **Stockholm format**.
MIToS also uses MSA annotations to keep track of:
- **Modifications** of the MSA (`MIToS_...`) as deletion of sequences or columns.
- Positions numbers in the original MSA file (**column mapping:** `ColMap`)
- Position of the residues in the sequence (**sequence mapping:** `SeqMap`)
"""
@auto_hash_equals mutable struct Annotations
file::OrderedDict{String,String}
sequences::Dict{Tuple{String,String},String}
columns::Dict{String,String}
residues::Dict{Tuple{String,String},String}
end
Annotations() = Annotations(
OrderedDict{String,String}(),
Dict{Tuple{String,String},String}(),
Dict{String,String}(),
Dict{Tuple{String,String},String}(),
)
# Length
# ------
function Base.length(a::Annotations)
length(a.file) + length(a.sequences) + length(a.columns) + length(a.residues)
end
# Filters
# -------
# This function is useful because of the Julia issue #12495
function _filter(str::String, mask::AbstractArray{Bool})
@assert length(str) == length(mask) "The string and the mask must have the same length"
# data readable writable
buffer = IOBuffer(Array{UInt8}(undef, lastindex(str)), read = true, write = true)
# To start at the beginning of the buffer:
truncate(buffer, 0)
i = 1
for char in str
@inbounds if mask[i]
write(buffer, char)
end
i += 1
end
String(take!(buffer))
end
_filter(str::String, indexes::AbstractArray{Int}) = String(collect(str)[indexes])
"""
For filter column and sequence mapping of the format: ",,,,10,11,,12"
"""
_filter_mapping(str_map::String, mask) = join(split(str_map, ',')[mask], ',')
"""
`filtersequences!(data::Annotations, ids::Vector{String}, mask::AbstractArray{Bool,1})`
It is useful for deleting sequence annotations. `ids` should be a list of the sequence
names and `mask` should be a logical vector.
"""
function filtersequences!(
data::Annotations,
ids::Vector{String},
mask::AbstractVector{Bool},
)
@assert length(ids) == length(mask) "It's needed one sequence id per element in the mask."
nresannot = length(data.residues)
nseqannot = length(data.sequences)
if nresannot > 0 || nseqannot > 0
del = Set(ids[.!mask])
end
if nresannot > 0
for key in keys(data.residues)
if key[1] in del
delete!(data.residues, key)
end
end
data.residues = sizehint!(data.residues, length(data.residues))
end
if nseqannot > 0
for key in keys(data.sequences)
if key[1] in del
delete!(data.sequences, key)
end
end
data.sequences = sizehint!(data.sequences, length(data.sequences))
end
data
end
"""
`filtercolumns!(data::Annotations, mask)`
It is useful for deleting column annotations (creating a subset in place).
"""
function filtercolumns!(data::Annotations, mask)
if length(data.residues) > 0
for (key, value) in data.residues
data.residues[key] = _filter(value, mask)
end
end
if length(data.columns) > 0
for (key, value) in data.columns
data.columns[key] = _filter(value, mask)
end
end
if length(data.sequences) > 0
for (key, value) in data.sequences
if key[2] == "SeqMap"
data.sequences[key] = _filter_mapping(value, mask)
end
end
end
# vcat can create multiple ColMap annotations in a single MSA; update all of them
colmap_keys = filter(endswith("ColMap"), keys(data.file))
for key in colmap_keys
data.file[key] = _filter_mapping(data.file[key], mask)
end
data
end
# Copy, deepcopy and empty!
# -------------------------
for fun in [:copy, :deepcopy]
@eval begin
Base.$(fun)(ann::Annotations) = Annotations(
$(fun)(ann.file),
$(fun)(ann.sequences),
$(fun)(ann.columns),
$(fun)(ann.residues),
)
end
end
function Base.empty!(ann::Annotations)
empty!(ann.file)
empty!(ann.sequences)
empty!(ann.columns)
empty!(ann.residues)
ann
end
Base.isempty(ann::Annotations) =
isempty(ann.file) &&
isempty(ann.sequences) &&
isempty(ann.columns) &&
isempty(ann.residues)
# merge! and merge
# ----------------
const _MERGE_NOTE = md"""
NOTE: This function does not check for consistency among the various `Annotations`.
For example, it does not verify that `SeqMap` annotations have consistent lengths.
"""
"""
merge!(target::Annotations, sources::Annotations...)
Merge one or more source `Annotations` into a target `Annotations`. This function calls
`Base.merge!` on each of the four dictionaries in the `Annotations` type: `file`,
`sequences`, `columns`, and `residues`. Consequently, it behaves like `Base.merge!` for
dictionaries; if the same key exists in different `Annotations` objects, the value from the
last one is used.
$_MERGE_NOTE
"""
function Base.merge!(target::Annotations, sources::Annotations...)
for source in sources
merge!(target.file, source.file)
merge!(target.sequences, source.sequences)
merge!(target.columns, source.columns)
merge!(target.residues, source.residues)
end
target
end
"""
merge(target::Annotations, sources::Annotations...)
Create a new `Annotations` object by merging two or more `Annotations`. If the same
annotation exists in different `Annotations` objects, the value from the last one is used.
See also `merge!`.
$_MERGE_NOTE
"""
Base.merge(target::Annotations, sources::Annotations...) =
merge!(deepcopy(target), sources...)
# ncolumns
# --------
"""
`ncolumns(ann::Annotations)` returns the number of columns/residues with annotations.
This function returns `-1` if there is not annotations per column/residue.
"""
function ncolumns(ann::Annotations)
for value in values(ann.columns)
return (length(value))
end
for value in values(ann.residues)
return (length(value))
end
-1
end
# Getters
# -------
for (fun, field) in [(:getannotfile, :(ann.file)), (:getannotcolumn, :(ann.columns))]
@eval begin
$(fun)(ann::Annotations) = $(field)
$(fun)(ann::Annotations, feature::String) = getindex($(field), feature)
$(fun)(ann::Annotations, feature::String, default::String) =
get($(field), feature, default)
end
end
for (fun, field) in
[(:getannotsequence, :(ann.sequences)), (:getannotresidue, :(ann.residues))]
@eval begin
$(fun)(ann::Annotations) = $(field)
$(fun)(ann::Annotations, seqname::String, feature::String) =
getindex($(field), (seqname, feature))
$(fun)(ann::Annotations, seqname::String, feature::String, default::String) =
get($(field), (seqname, feature), default)
end
end
@doc """`getannotfile(ann[, feature[,default]])`
It returns per file annotation for `feature`
""" getannotfile
@doc """`getannotcolumn(ann[, feature[,default]])`
It returns per column annotation for `feature`
""" getannotcolumn
@doc """`getannotsequence(ann[, seqname, feature[,default]])`
It returns per sequence annotation for `(seqname, feature)`
""" getannotsequence
@doc """`getannotresidue(ann[, seqname, feature[,default]])`
It returns per residue annotation for `(seqname, feature)`
""" getannotresidue
# Setters
# -------
function _test_feature_name(feature::String)
@assert length(feature) <= 50 "Feature name has a limit of 50 characters."
@assert !occursin(r"\s", feature) "Feature name must not have spaces."
end
function setannotfile!(ann::Annotations, feature::String, annotation::String)
_test_feature_name(feature)
previous = get(ann.file, feature, "")
ann.file[feature] = previous != "" ? string(previous, '\n', annotation) : annotation
end
function setannotsequence!(
ann::Annotations,
seqname::String,
feature::String,
annotation::String,
)
_test_feature_name(feature)
previous = get(ann.sequences, (seqname, feature), "")
ann.sequences[(seqname, feature)] =
previous != "" ? string(previous, '\n', annotation) : annotation
end
function setannotcolumn!(ann::Annotations, feature::String, annotation::String)
_test_feature_name(feature)
len = ncolumns(ann)
if (len == -1) || (len == length(annotation))
setindex!(ann.columns, annotation, feature)
else
throw(
DimensionMismatch(
string(
"You should have exactly 1 char per column (",
len,
" columns/residues)",
),
),
)
end
end
function setannotresidue!(
ann::Annotations,
seqname::String,
feature::String,
annotation::String,
)
_test_feature_name(feature)
len = ncolumns(ann)
if (len == -1) || (len == length(annotation))
setindex!(ann.residues, annotation, (seqname, feature))
else
throw(
DimensionMismatch(
string(
"You should have exactly 1 char per residue (",
len,
" columns/residues)",
),
),
)
end
end
@doc """`setannotfile!(ann, feature, annotation)`
It stores per file `annotation` for `feature`
""" setannotfile!
@doc """`setannotcolumn!(ann, feature, annotation)`
It stores per column `annotation` (1 char per column) for `feature`
""" setannotcolumn!
@doc """`setannotsequence!(ann, seqname, feature, annotation)`
It stores per sequence `annotation` for `(seqname, feature)`
""" setannotsequence!
@doc """`setannotresidue!(ann, seqname, feature, annotation)`
It stores per residue `annotation` (1 char per residue) for `(seqname, feature)`
""" setannotresidue!
# MIToS modification annotations
# ===============================
"""
Annotates on file annotations the modifications realized by MIToS on the MSA. It always
returns `true`, so It can be used in a boolean context.
"""
function annotate_modification!(ann::Annotations, modification::String)
setannotfile!(ann, string("MIToS_", Dates.now()), modification)
true # generally used in a boolean context: annotate && annotate_modification!(...
end
"""
Deletes all the MIToS annotated modifications
"""
function delete_annotated_modifications!(ann::Annotations)
for key in keys(ann.file)
if startswith(key, "MIToS_")
delete!(ann.file, key)
end
end
end
"""
Prints MIToS annotated modifications
"""
function printmodifications(ann::Annotations)
for (key, value) in ann.file
if startswith(key, "MIToS_")
list_k = split(key, '_')
println("-------------------")
println(list_k[2])
println('\n', value)
end
end
end
# Show & Print Annotations
# ========================
function _printfileannotations(io::IO, ann::Annotations)
if !isempty(ann.file)
for (key, value) in ann.file
for val in split(value, '\n')
println(io, string("#=GF ", key, '\t', val))
end
end
end
end
function _printcolumnsannotations(io::IO, ann::Annotations)
if !isempty(ann.columns)
for (key, value) in ann.columns
println(io, string("#=GC ", key, "\t\t\t", value))
end
end
end
function _printsequencesannotations(io::IO, ann::Annotations)
if !isempty(ann.sequences)
for (key, value) in ann.sequences
for val in split(value, '\n')
println(io, string("#=GS ", key[1], '\t', key[2], '\t', val))
end
end
end
end
function _printresiduesannotations(io::IO, ann::Annotations)
if !isempty(ann.residues)
for (key, value) in ann.residues
println(io, string("#=GR ", key[1], '\t', key[2], '\t', value))
end
end
end
function Base.print(io::IO, ann::Annotations)
_printfileannotations(io, ann)
_printsequencesannotations(io, ann)
_printresiduesannotations(io, ann)
_printcolumnsannotations(io, ann)
end
Base.show(io::IO, ann::Annotations) = print(io, ann)
# Rename sequences
# ================
# This private function is used by rename sequences during MSA concatenation,
# but it could be useful for other purposes
"""
_rename_sequences(annotations::Annotations, old2new::Dict{String,String})
Renames sequences in a given `Annotations` object based on a mapping provided in `old2new`.
This function iterates through residue-level and sequence-level annotations in the
provided `Annotations` object. For each annotation, it checks if the sequence name exists
in the `old2new` dictionary. If so, the sequence name is updated to the new name from
`old2new`; otherwise, the original sequence name is retained.
The function then returns a new `Annotations` object with updated sequence names.
"""
function _rename_sequences(annotations::Annotations, old2new::Dict{String,String})
res_annotations = Dict{Tuple{String,String},String}()
for ((seqname, annot_name), value) in getannotresidue(annotations)
seqname = get(old2new, seqname, seqname)
res_annotations[(seqname, annot_name)] = value
end
seq_annotations = Dict{Tuple{String,String},String}()
for ((seqname, annot_name), value) in getannotsequence(annotations)
seqname = get(old2new, seqname, seqname)
seq_annotations[(seqname, annot_name)] = value
end
Annotations(
copy(getannotfile(annotations)),
seq_annotations,
copy(getannotcolumn(annotations)),
res_annotations,
)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 1398 | # Clusters
# ========
abstract type AbstractCluster end
"""
Use `NoClustering()` to avoid the use of clustering where a `Clusters` type is needed.
"""
struct NoClustering <: AbstractCluster end
"""
Data structure to represent sequence clusters. The sequence data itself is not included.
"""
@auto_hash_equals struct Clusters <: AbstractCluster
clustersize::Vector{Int}
clusters::Vector{Int}
weights::StatsBase.Weights{Float64,Float64,Array{Float64,1}}
end
nelements(cl::Clusters) = length(cl.clusters)
@inline Base.convert(::Type{Clusters}, cl::Clusters) = cl # no-op
# weights
# -------
"""
The `WeightTypes` type is the same as `Union{Weights,NoClustering,Clusters}`. This type is
used to represent weights. Most of the functions taking the `weights` kerword argument in
the `Information` module accept instances of `WeightTypes`.
"""
const WeightTypes = Union{Weights,NoClustering,Clusters}
"""
`getweight(c[, i::Int])`
This function returns the weight of the sequence number `i`. getweight should be defined for
any type used for `frequencies!`/`frequencies` in order to use his weigths. If `i` isn't
used, this function returns a vector with the weight of each sequence.
"""
@inline getweight(weight::NoClustering, seq::Int) = 1.0
getweight(cl::Clusters) = cl.weights
getweight(cl::Clusters, seq::Int) = cl.weights[seq]
@inline getweight(cl::Weights, i::Int) = cl[i]
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 41925 | ## hcat (horizontal concatenation)
function _hcat_seqnames_kernel!(concatenated_names, msa, delim)
for (i, seq) in enumerate(sequencename_iterator(msa))
if seq == concatenated_names[i]
continue
end
concatenated_names[i] *= delim * seq
end
concatenated_names
end
function _h_concatenated_seq_names(msas...; delim::String = "_&_")
concatenated_names = sequencenames(msas[1])
for msa in msas[2:end]
_hcat_seqnames_kernel!(concatenated_names, msa, delim)
end
concatenated_names
end
function _hcat_colnames_kernel!(colnames, columns, msa_number::Int)::Int
first_col = first(columns)
check_msa_change = '_' in first_col
previous = ""
msa_number += 1
for col in columns
if check_msa_change
fields = split(col, '_')
current = first(fields)
if current != previous
if previous != ""
msa_number += 1
end
previous = string(current)
end
col = last(fields)
end
push!(colnames, "$(msa_number)_$col")
end
msa_number
end
function _h_concatenated_col_names(msas...)
colnames = String[]
msa_number = 0
for msa in msas
columns = columnname_iterator(msa)
msa_number = _hcat_colnames_kernel!(colnames, columns, msa_number)
end
colnames
end
_get_seq_lengths(msas...) = Int[ncolumns(msa) for msa in msas]
function _h_concatenate_annotfile(data::Annotations...)
N = length(data)
annotfile = copy(getannotfile(data[1]))
for i = 2:N
ann = data[i]::Annotations
for (k, v) in getannotfile(ann)
if haskey(annotfile, k)
if endswith(k, "ColMap") # to also use ColMap annotations from vcat
annotfile[k] = string(annotfile[k], ",", v)
else
annotfile[k] = string(annotfile[k], "_&_", v)
end
else
if endswith(k, "ColMap")
# that means that the ColMap annotation probably comes from vcat
# in one of the source MSAs and there is no match between keys.
@warn "There was no possible to match the ColMap annotations."
end
push!(annotfile, k => v)
end
end
end
annotfile
end
"""
It returns a Dict mapping the MSA number and sequence name to the horizontally
concatenated sequence name.
"""
function _get_seqname_mapping_hcat(concatenated_seqnames, msas...)
mapping = Dict{Tuple{Int,String},String}()
nmsa = length(msas)
nseq = length(concatenated_seqnames)
for j = 1:nmsa
seq_names = sequencenames(msas[j])
@assert nseq == length(seq_names)
for i = 1:nseq
mapping[(j, seq_names[i])] = concatenated_seqnames[i]
end
end
mapping
end
"""
At this moment, the _concatenate_annotsequence function does no check for SeqMap
annotations. Therefore, if an MSA does not have a SeqMap annotation, the concatenated
SeqMap annotation is corrupted. To avoid this, we will delete the SeqMap annotation
whose length is not equal to the length of the concatenated MSA.
"""
function _clean_sequence_mapping!(msa::AnnotatedAlignedObject)
N = ncolumns(msa)
to_delete = Tuple{String,String}[]
annotsequence = getannotsequence(msa)
for (key, value) in annotsequence
if key[2] == "SeqMap"
n_delim = count(==(','), value)
if n_delim != N - 1
push!(to_delete, key)
end
end
end
for key in to_delete
delete!(annotsequence, key)
end
msa
end
function _concatenate_annotsequence(seqname_mapping, data::Annotations...)
annotsequence = Dict{Tuple{String,String},String}()
for (i, ann::Annotations) in enumerate(data)
for ((seqname, annot_name), value) in getannotsequence(ann)
concatenated_seqname = get(seqname_mapping, (i, seqname), seqname)
new_key = (concatenated_seqname, annot_name)
# if we used :vcat, new_key will not be present in the dict as the
# sequence names are disambiguated first
if haskey(annotsequence, new_key)
# so, we execute the following code only if we used :hcat
if annot_name == "SeqMap"
sep = ","
else
sep = "_&_"
end
annotsequence[new_key] = string(annotsequence[new_key], sep, value)
else
push!(annotsequence, new_key => value)
end
end
end
annotsequence
end
function _fill_and_update!(dict, last, key, i, value, seq_lengths)
if haskey(dict, key)
if last[key] == i - 1
dict[key] = string(dict[key], value)
else
previous = sum(seq_lengths[(last[key]+1):(i-1)])
dict[key] = string(dict[key], repeat(" ", previous), value)
end
last[key] = i
else
if i == 1
push!(dict, key => value)
else
previous = sum(seq_lengths[1:(i-1)])
push!(dict, key => string(repeat(" ", previous), value))
end
push!(last, key => i)
end
end
function _fill_end!(dict, seq_lengths, entity)
total_length = sum(seq_lengths)
for (key, value) in dict
current_length = length(value)
if current_length < total_length
dict[key] *= " "^(total_length - current_length)
elseif current_length > total_length
throw(
ErrorException(
"There are $current_length $entity annotated instead of $total_length.",
),
)
end
end
dict
end
function _h_concatenate_annotcolumn(
seq_lengths::Vector{Int},
data::Annotations...,
)::Dict{String,String}
annotcolumn = Dict{String,String}()
last = Dict{String,Int}()
for (i, ann::Annotations) in enumerate(data)
for (annot_name, value) in getannotcolumn(ann)
_fill_and_update!(annotcolumn, last, annot_name, i, value, seq_lengths)
end
end
_fill_end!(annotcolumn, seq_lengths, "columns")
end
function _h_concatenate_annotresidue(seq_lengths, seqname_mapping, data::Annotations...)
annotresidue = Dict{Tuple{String,String},String}()
last = Dict{Tuple{String,String},Int}()
for (i, ann) in enumerate(data)
for ((seqname, annot_name), value) in getannotresidue(ann)
concatenated_seqname = get(seqname_mapping, (i, seqname), seqname)
new_key = (concatenated_seqname, annot_name)
_fill_and_update!(annotresidue, last, new_key, i, value, seq_lengths)
end
end
_fill_end!(annotresidue, seq_lengths, "residues")
end
function _delete_hcat_annotfile!(annot::Annotations)
if haskey(annot.file, "HCat")
delete!(annot.file, "HCat")
end
annot
end
function _set_hcat_annotfile!(annot::Annotations, colnames)
_delete_hcat_annotfile!(annot)
setannotfile!(
annot,
"HCat",
join((replace(col, r"_[0-9]+$" => "") for col in colnames), ','),
)
annot
end
function Base.hcat(msa::T...) where {T<:AnnotatedAlignedObject}
seqnames = _h_concatenated_seq_names(msa...)
colnames = _h_concatenated_col_names(msa...)
concatenated_matrix = reduce(hcat, getresidues.(msa))
concatenated_msa = _namedresiduematrix(concatenated_matrix, seqnames, colnames)
seqname_mapping = _get_seqname_mapping_hcat(seqnames, msa...)
seq_lengths = _get_seq_lengths(msa...)
old_annot = annotations.([msa...])
new_annot = Annotations(
_h_concatenate_annotfile(old_annot...),
_concatenate_annotsequence(seqname_mapping, old_annot...),
_h_concatenate_annotcolumn(seq_lengths, old_annot...),
_h_concatenate_annotresidue(seq_lengths, seqname_mapping, old_annot...),
)
_set_hcat_annotfile!(new_annot, colnames)
new_msa = T(concatenated_msa, new_annot)
_clean_sequence_mapping!(new_msa)
end
function Base.hcat(msa::T...) where {T<:UnannotatedAlignedObject}
concatenated_matrix = reduce(hcat, getresidues.(msa))
seqnames = _h_concatenated_seq_names(msa...)
colnames = _h_concatenated_col_names(msa...)
concatenated_msa = _namedresiduematrix(concatenated_matrix, seqnames, colnames)
T(concatenated_msa)
end
"""
It returns a vector of numbers from `1` to N for each column that indicates the source MSA.
The mapping is annotated in the `"HCat"` file annotation of an
`AnnotatedMultipleSequenceAlignment` or in the column names of an `NamedArray` or
`MultipleSequenceAlignment`.
NOTE: When the MSA results from vertically concatenating MSAs using `vcat`,
the `"HCat"` annotations from the constituent MSAs are renamed as `"1_HCat"`, `"2_HCat"`,
etc. In that case, the MSA numbers referenced in the column names are provided.
To access the original annotations, utilize the `getannotfile` function.
"""
function gethcatmapping(msa::AnnotatedMultipleSequenceAlignment)
annot = getannotfile(msa)
if haskey(annot, "HCat")
return _str2int_mapping(annot["HCat"])
else
return gethcatmapping(namedmatrix(msa))
end
end
function gethcatmapping(msa::NamedResidueMatrix{AT}) where {AT<:AbstractMatrix}
colnames = columnname_iterator(msa)
if !isempty(colnames)
if !occursin('_', first(colnames))
throw(ErrorException("Column names have not been generated by `hcat`."))
end
Int[parse(Int, replace(col, r"_[0-9]+$" => "")) for col in colnames]
else
throw(ErrorException("There are not column names!"))
end
end
gethcatmapping(msa::MultipleSequenceAlignment) = gethcatmapping(namedmatrix(msa))
## vcat (vertical concatenation)
"""
If returns a vector of sequence names for the vertically concatenated MSA. The prefix
is the number associated to the source MSA. If the sequence name has already a number
as prefix, the MSA number is increased accordingly.
"""
function _v_concatenated_seq_names(msas...; fill_mapping::Bool = false)
label_mapping = Dict{String,Int}()
concatenated_names = String[]
msa_number = 0
previous_msa_number = 0
for msa in msas
msa_label = ""
msa_number += 1
for seqname in sequencename_iterator(msa)
m = match(r"^([0-9]+)_(.*)$", seqname)
if m === nothing
msa_label = ""
new_seqname = "$(msa_number)_$seqname"
else
# if the sequence name has already a number as prefix, we increase the
# MSA number every time the prefix number changes
current_msa_label = string(m.captures[1])
if current_msa_label == msa_label
new_seqname = "$(msa_number)_$(m.captures[2])"
else
# avoid increasing the MSA number two times in a row the first time
# we find a sequence name with a number as prefix
if msa_label != ""
msa_number += 1
end
msa_label = current_msa_label
fill_mapping && push!(label_mapping, msa_label => msa_number)
new_seqname = "$(msa_number)_$(m.captures[2])"
end
end
previous_msa_number = msa_number
push!(concatenated_names, new_seqname)
end
end
concatenated_names, label_mapping
end
"""
It returns a Dict mapping the MSA number and sequence name to the vertically
concatenated sequence name.
"""
function _get_seqname_mapping_vcat(concatenated_seqnames, msas...)
mapping = Dict{Tuple{Int,String},String}()
sequence_number = 0
for (i, msa) in enumerate(msas)
for seq in sequencename_iterator(msa)
sequence_number += 1
mapping[(i, seq)] = concatenated_seqnames[sequence_number]
end
end
mapping
end
function _update_annotation_name(annot_name, msa_number, label_mapping)
m = match(r"^([0-9]+)_(.*)$", annot_name)
if m !== nothing
# The annotation name has already a number as prefix, so we use the mapping
# to determine the corresponding MSA number
if haskey(label_mapping, m.captures[1])
# we avoid taking the MSA number from the name if it is not in the mapping
# to avoid taking a prefix that was alredy there but related to vcat
msa_number = label_mapping[m.captures[1]]
end
new_annot_name = "$(msa_number)_$(m.captures[2])"
else
new_annot_name = "$(msa_number)_$annot_name"
end
msa_number, new_annot_name
end
function _v_concatenate_annotfile(label_mapping::Dict{String,Int}, data::Annotations...)
annotfile = OrderedDict{String,String}()
msa_number = 0
for ann::Annotations in data
msa_number += 1
for (name, annotation) in getannotfile(ann)
msa_number, new_name = _update_annotation_name(name, msa_number, label_mapping)
push!(annotfile, new_name => annotation)
end
end
annotfile
end
"""
Column annotations are disambiguated by adding a prefix to the annotation name as
we do for the sequence names.
"""
function _v_concatenate_annotcolumn(label_mapping::Dict{String,Int}, data::Annotations...)
annotcolumn = Dict{String,String}()
msa_number = 0
for ann::Annotations in data
msa_number += 1
for (name, annotation) in getannotcolumn(ann)
msa_number, new_name = _update_annotation_name(name, msa_number, label_mapping)
push!(annotcolumn, new_name => annotation)
end
end
annotcolumn
end
"""
Residue annotations are disambiguated by adding a prefix to the sequence name holding
the annotation as we do for the sequence names.
"""
function _v_concatenate_annotresidue(concatenated_seqnames, data::Annotations...)
annotresidue = Dict{Tuple{String,String},String}()
for (i, ann::Annotations) in enumerate(data)
for ((seqname, annot_name), value) in getannotresidue(ann)
concatenated_seqname = get(concatenated_seqnames, (i, seqname), seqname)
new_key = (concatenated_seqname, annot_name)
push!(annotresidue, new_key => value)
end
end
annotresidue
end
function Base.vcat(msa::T...) where {T<:AnnotatedAlignedObject}
seqnames, label_mapping = _v_concatenated_seq_names(msa...; fill_mapping = true)
colnames = columnname_iterator(msa[1])
concatenated_matrix = reduce(vcat, getresidues.(msa))
concatenated_msa = _namedresiduematrix(concatenated_matrix, seqnames, colnames)
seqname_mapping = _get_seqname_mapping_vcat(seqnames, msa...)
old_annot = annotations.([msa...])
new_annot = Annotations(
_v_concatenate_annotfile(label_mapping, old_annot...),
_concatenate_annotsequence(seqname_mapping, old_annot...),
_v_concatenate_annotcolumn(label_mapping, old_annot...),
_v_concatenate_annotresidue(seqname_mapping, old_annot...),
)
# There is no need for a VCat annotation as the source MSA number is already
# annotated as a prefix in the sequence names
T(concatenated_msa, new_annot)
end
function Base.vcat(msa::T...) where {T<:UnannotatedAlignedObject}
concatenated_matrix = reduce(vcat, getresidues.(msa))
seqnames, _ = _v_concatenated_seq_names(msa...)
colnames = columnname_iterator(msa[1])
concatenated_msa = _namedresiduematrix(concatenated_matrix, seqnames, colnames)
T(concatenated_msa)
end
#
# Functions to join, merge or pair MSAs
#
# Currently, these functions will utilize hcat and vcat functions as much as possible.
# If this approach proves to be too slow, we may consider preallocating the result matrices.
# helper functions to name columns in gap blocks
function _get_last_gap_number(name_iterator)
numbers = (
parse(Int, replace(name, "gap:" => "")) for
name in name_iterator if startswith(name, "gap:")
)
# as `maximum(numbers, init=0)` doesn't work in Julia versions < 1.6
# we use `foldl` instead
foldl(max, numbers, init = 0)
end
function _gapblock_columnnames(msa, ncol)
last_gap_number = _get_last_gap_number(columnname_iterator(msa))
["gap:$(i)" for i = (last_gap_number+1):(last_gap_number+ncol)]
end
# Since gaps are used for padding, the following function creates an MSA that contains
# only gaps but the proper annotations and names to be used in hcat and vcat.
function _gap_columns(msa, ncol)
nseq = nsequences(msa)
empty_mapping = repeat(",", ncol - 1)
matrix = fill(GAP, nseq, ncol)
seqnames = sequencenames(msa)
colnames = _gapblock_columnnames(msa, ncol)
named_matrix = _namedresiduematrix(matrix, seqnames, colnames)
block = AnnotatedMultipleSequenceAlignment(named_matrix)
for seq in seqnames
setannotsequence!(block, seq, "SeqMap", empty_mapping)
end
setannotfile!(block, "ColMap", empty_mapping)
block
end
function _disambiguate_sequence_names(msa, seqnames)
disambiguous_seqnames = deepcopy(seqnames)
last_gap_number = _get_last_gap_number(sequencename_iterator(msa))
for (i, seqname) in enumerate(seqnames)
# Check for redundancy and rename if necessary
if seqname in sequencename_iterator(msa)
last_gap_number += 1
disambiguous_seqnames[i] = "gap:$(last_gap_number)"
end
end
disambiguous_seqnames
end
"""
_renumber_sequence_gaps(msa::AnnotatedMultipleSequenceAlignment)
Renumbers the gap sequences in a given multiple sequence alignment (MSA) object and
returns a new MSA object with updated sequence names.
This function specifically targets sequences within the MSA that are named with the
prefix "gap:". It assigns a new sequential number to each gap sequence, ensuring a unique
and ordered naming convention (e.g., "gap:1", "gap:2", etc.).
Therefore, this function is useful for renumbering gap sequences in an MSA where gap
blocks have been inserted from the end to the beginning. This insertion order can lead to
non-sequential numbering of the gap sequences. For example, in the case of two gap blocks,
where one block contains a single sequence and the other contains two, the sequences
might originally be numbered as "gap:3", "gap:1", "gap:2". This function renumbers them
sequentially so that they are numbered as "gap:1", "gap:2", "gap:3".
"""
function _renumber_sequence_gaps(msa::AnnotatedMultipleSequenceAlignment)
seqnames = collect(sequencename_iterator(msa))
gap_number = 0
old2new = Dict{String,String}()
for (i, old_seqname) in enumerate(seqnames)
if startswith(old_seqname, "gap:")
gap_number += 1
new_seqname = "gap:$(gap_number)"
if old_seqname != new_seqname
old2new[old_seqname] = new_seqname
seqnames[i] = new_seqname
end
end
end
annot = _rename_sequences(annotations(msa), old2new)
named_matrix = _namedresiduematrix(getresidues(msa), seqnames, columnnames(msa))
AnnotatedMultipleSequenceAlignment(named_matrix, annot)
end
function _renumber_column_gaps(col_names::Vector{String})
new_colnames = copy(col_names)
gap_number = 0
for (i, old_colname) in enumerate(col_names)
if startswith(old_colname, "gap:")
gap_number += 1
new_colnames[i] = "gap:$(gap_number)"
end
end
new_colnames
end
function _renumber_column_gaps(msa::AnnotatedMultipleSequenceAlignment)
new_colnames = _renumber_column_gaps(columnnames(msa))
named_matrix = _namedresiduematrix(getresidues(msa), sequencenames(msa), new_colnames)
AnnotatedMultipleSequenceAlignment(named_matrix, annotations(msa))
end
function _gap_sequences(msa, seqnames)
nseq = length(seqnames)
ncol = ncolumns(msa)
empty_mapping = repeat(",", ncol - 1)
matrix = fill(GAP, nseq, ncol)
colnames = columnname_iterator(msa)
# Names are disambiguated to prevent the "Inconsistent dictionary sizes" error during
# vcat. This error arises when the same sequence name appears in different MSAs,
# as sequence names are utilised as keys in a dictionary.
disambiguous_seqnames = _disambiguate_sequence_names(msa, seqnames)
named_matrix = _namedresiduematrix(matrix, disambiguous_seqnames, colnames)
block = AnnotatedMultipleSequenceAlignment(named_matrix)
for seq in disambiguous_seqnames
setannotsequence!(block, string(seq), "SeqMap", empty_mapping)
end
block
end
# This functions are used to insert a gap block in a given position in the MSA
# without altering the annotations too much. The idea is the gap blocks are
# no real MSAs, but things inserted into a previously existing MSA.
# Insert gap sequences.
function _get_position(max_pos, position::Int)
if position < 1
throw(ArgumentError("The gap block position must be equal or greater than 1."))
elseif position > max_pos
max_pos + 1 # to insert the gap block at the end
else
position # in the MSA
end
position
end
function _vcat_gap_block(msa_a, msa_b)
matrix_a = getresidues(msa_a)
matrix_b = getresidues(msa_b)
concatenated_matrix = vcat(matrix_a, matrix_b)
seqnames_a = sequencenames(msa_a)
seqnames_b = sequencenames(msa_b)
seqnames = vcat(seqnames_a, seqnames_b)
colnames = columnnames(msa_a)
named_matrix = _namedresiduematrix(concatenated_matrix, seqnames, colnames)
annot = merge(annotations(msa_a), annotations(msa_b))
AnnotatedMultipleSequenceAlignment(named_matrix, annot)
end
function _insert_gap_sequences(msa, seqnames, position)
gap_block = _gap_sequences(msa, seqnames)
nseq = nsequences(msa)
int_position = _get_position(nseq, position)
if int_position == 1 # at start
_vcat_gap_block(gap_block, msa)
elseif int_position == nseq + 1 # after end
_vcat_gap_block(msa, gap_block)
else
_vcat_gap_block(
_vcat_gap_block(msa[1:(int_position-1), :], gap_block),
msa[int_position:end, :],
)
end
end
# Insert gap columns.
function _get_msa_number(colnames, position)
fields = split(colnames[position], '_')
if length(fields) == 1
0 # the column does not have a MSA number as prefix
else
parse(Int, first(fields))
end
end
# rely on hcat to do the job, then correct the annotations
# to avoid changing the MSA index number.
function _fix_msa_numbers(original_msa, int_position, gap_block_columns, gapped_msa)
# 1. get the MSA number that will be used for the gap block
original_msa_column_names = columnnames(original_msa)
ncol = length(original_msa_column_names)
gap_block_colnames = ["gap:$i" for i = 1:gap_block_columns]
# 3. conserve the annotations outside the gap block
new_colnames = if int_position == 1 # at start
vcat(gap_block_colnames, original_msa_column_names)
elseif int_position == ncol + 1 # after end
vcat(original_msa_column_names, gap_block_colnames)
else
vcat(
original_msa_column_names[1:(int_position-1)],
gap_block_colnames,
original_msa_column_names[int_position:end],
)
end::Vector{String}
# 4. update the names and annotations
# NOTE: We call _renumber_column_gaps to avoid the problem of duplicated names where
# more than one gap block is inserted
renamed_colnames = _renumber_column_gaps(new_colnames)
setnames!(namedmatrix(gapped_msa), renamed_colnames, 2)
prev_file_annotations = annotations(original_msa).file
if haskey(prev_file_annotations, "HCat")
_set_hcat_annotfile!(annotations(gapped_msa), renamed_colnames)
else
# do not add the HCat annotation if it was not present in the original MSA
delete!(annotations(gapped_msa).file, "HCat")
end
new_file_annotations = annotations(gapped_msa).file
for key in keys(new_file_annotations)
if startswith(key, "MIToS_") && !haskey(prev_file_annotations, key)
# delete new MIToS annotated modifications
delete!(new_file_annotations, key)
end
end
if haskey(prev_file_annotations, "NCol")
# do not change the NCol annotation
new_file_annotations["NCol"] = prev_file_annotations["NCol"]
end
gapped_msa
end
function _insert_gap_columns(input_msa, gap_block_columns::Int, position)
@assert gap_block_columns ≥ 0 "The number of gap columns must be greater than 0."
msa = AnnotatedMultipleSequenceAlignment(input_msa)
gap_block_columns == 0 && return msa
gap_block = _gap_columns(msa, gap_block_columns)
ncol = ncolumns(msa)
int_position = _get_position(ncol, position)
gapped_msa = if int_position == 1 # at start
hcat(gap_block, msa)
elseif int_position == ncol + 1 # after end
hcat(msa, gap_block)
else
hcat(msa[:, 1:(int_position-1)], gap_block, msa[:, int_position:end])
end
_fix_msa_numbers(msa, int_position, gap_block_columns, gapped_msa)
end
# join for MSAs
"""
_add_gaps_in_b(msa_a, msa_b, positions_a, positions_b, axis::Int=1)
This is an helper function for the `:left` and `:right` joins. It aligns `msa_b` with
`msa_a` by adding gaps to `msa_b`. Only the sequences or columns in `msa_b` that match
the positions in `msa_a` are kept. Gaps are inserted in `msa_b` at positions where `msa_a`
has sequences or columns that are not matched in `msa_b`. Therefore, we can think of
`msa_a` as the reference MSA and `msa_b` as the MSA to be aligned with the reference.
The `positions_a` and `positions_b` arguments define corresponding positions in `msa_a`
and `msa_b`, respectively, for accurate gap insertion. The function returns a modified
`msa_b` with gaps inserted to align with `msa_a`.
The axis argument (`1` for sequences, `2` for columns) determines whether gaps are
inserted as sequences or columns.
# Example
```julia
aligned_msa_b = _add_gaps_in_b(msa_a, msa_b, [1, 2, 3], [2, 3, 4], 2) # axis = 2
```
"""
function _add_gaps_in_b(msa_a, msa_b, positions_a, positions_b, axis::Int = 1)
@assert axis == 1 || axis == 2 "The axis must be 1 (sequences) or 2 (columns)."
# sort the positions to keep the order in msa_a
order_a = sortperm(positions_a)
sorted_b = positions_b[order_a]
# keep only the matching positions in msa_b
matching_b = if axis == 1
AnnotatedMultipleSequenceAlignment(msa_b[sorted_b, :])
else
AnnotatedMultipleSequenceAlignment(msa_b[:, sorted_b])
end
# find the positions were we need to add gaps in msa_b
N_a = axis == 1 ? nsequences(msa_a) : ncolumns(msa_a)
names_a = axis == 1 ? sequencenames(msa_a) : columnnames(msa_a)
positions_a_set = Set{Int}(positions_a)
last_b = 0
gap_positions = Int[]
gap_names = String[]
for i = 1:N_a
if i in positions_a_set # we have seen a matched position in msa_b
last_b += 1
else # if the msa_a position is not matched, add gaps in msa_b
push!(gap_positions, last_b)
push!(gap_names, names_a[i])
end
end
# compress the list of gap positions to later add full gap blocks
for pos in Iterators.reverse(unique(gap_positions))
block_names = gap_names[gap_positions.==pos]
if axis == 1
matching_b = _renumber_sequence_gaps(
_insert_gap_sequences(matching_b, block_names, pos + 1),
)
else
matching_b = _renumber_column_gaps(
_insert_gap_columns(matching_b, length(block_names), pos + 1),
)
end
end
matching_b
end
function _find_pairing_positions(index_function::Function, msa_a, msa_b, pairing)
n = length(pairing)
positions_a = Vector{Int}(undef, n)
positions_b = Vector{Int}(undef, n)
for (i, (a, b)) in enumerate(pairing)
positions_a[i] = index_function(msa_a, a)
positions_b[i] = index_function(msa_b, b)
end
positions_a, positions_b
end
function _find_pairing_positions(axis::Int, msa_a, msa_b, pairing)
@assert axis == 1 || axis == 2 "The axis must be 1 (sequences) or 2 (columns)."
index_function = axis == 1 ? sequence_index : column_index
_find_pairing_positions(index_function, msa_a, msa_b, pairing)
end
"""
_find_gaps(positions, n)
Calculate gaps in a sorted sequence of positions given also a maximum value `n` that would
be added at the end as `n+1` if `n` it is not already present.
This function returns a list of tuples, where each tuple represents a gap in the sequence.
The first element of the tuple indicates the position after which the gap will be inserted,
and the second element is the position that comes just after the gap. The function accounts
for gaps at both the beginning and end of the sequence. A gap is identified as a difference
greater than 1 between consecutive positions. To account for gaps at the end, the end
position of a gap matching the last position of the sequence is set to `n+1`.
"""
function _find_gaps(positions, n)
_positions = if positions[end] == n
((0,), positions)
else
((0,), positions, (n + 1,))
end
pos_iterator = Iterators.flatten(_positions)
[(x, y) for (x, y) in zip(Iterators.drop(pos_iterator, 1), pos_iterator) if x - y > 1]
end
"""
_insert_sorted_gaps(msa_target, msa_reference, positions_target, positions_reference,
block_position::Symbol=:before, axis::Int=1)
Inserts gap blocks into `msa_target` to match the alignment pattern of `msa_reference`.
This function is utilized for aligning two MSAs based on specific alignment positions. The
`positions_target` and `positions_reference` parameters dictate the corresponding
positions in both MSAs for accurate gap insertion.
The function returns the modified `msa_target` with inserted gaps, aligned according
to `msa_reference`.
The `block_position` keyword argument determines whether the gap blocks are inserted
`:before` (the default) or `:after` the unmatched sequences or columns. The `axis` keyword
argument determines whether the gap blocks are inserted as sequences (`1`, the default) or
columns (`2`).
# Example
```julia
gapped_msa_a = _insert_sorted_gaps(msa_a, msa_b, positions_a, positions_b)
```
"""
function _insert_sorted_gaps(
msa_target,
msa_reference,
positions_target,
positions_reference;
block_position::Symbol = :before,
axis::Int = 1,
)
@assert block_position in [:before, :after] "block_position must be :before or :after."
@assert axis == 1 || axis == 2 "The axis must be 1 (sequences) or 2 (columns)."
# Obtain the positions that will be aligned to gaps in the reference
N_reference = axis == 1 ? nsequences(msa_reference) : ncolumns(msa_reference)
gaps_reference = _find_gaps(positions_reference, N_reference)
# We need the sequence names from the reference that will be aligned to gaps
names_reference = axis == 1 ? sequencenames(msa_reference) : columnnames(msa_reference)
# Create a dictionary to find the matching position in `msa_target` for adding the gap blocks
reference2target = Dict{Int,Int}(positions_reference .=> positions_target)
N_target = axis == 1 ? nsequences(msa_target) : ncolumns(msa_target)
# Add the gap blocks to `msa_target` as found when looking at `positions_reference`
blocks_target = Tuple{Int,Vector{String}}[]
for (stop, start) in gaps_reference
# Found the matching position in `msa_target`
start_target = start == 0 ? 1 : reference2target[start] + 1
stop_target = stop > N_reference ? N_target + 1 : reference2target[stop]
# This should work fine, even if `start` is 0 and `stop` is n+1
unmatched_names = names_reference[start+1:stop-1]
# Determine whether the gap block should be inserted before or after the sequences
if block_position == :before
push!(blocks_target, (start_target, unmatched_names))
else
push!(blocks_target, (stop_target, unmatched_names))
end
end
gapped_msa_target = AnnotatedMultipleSequenceAlignment(msa_target)
if axis == 1
for (position, seqnames) in Iterators.reverse(blocks_target)
gapped_msa_target = _insert_gap_sequences(gapped_msa_target, seqnames, position)
end
_renumber_sequence_gaps(gapped_msa_target)
else
for (position, colnames) in Iterators.reverse(blocks_target)
gapped_msa_target =
_insert_gap_columns(gapped_msa_target, length(colnames), position)
end
_renumber_column_gaps(gapped_msa_target)
end
end
function _reorder_and_extract_unmatched_names(msa, positions, axis::Int)
N = size(msa, axis)
unmatched_positions = setdiff(1:N, positions)
if axis == 1
reordered_msa = msa[vcat(positions, unmatched_positions), :]
reordered_names = sequencenames(reordered_msa)
else
reordered_msa = msa[:, vcat(positions, unmatched_positions)]
reordered_names = columnnames(reordered_msa)
end
unmatched_names = reordered_names[length(positions)+1:end]
return reordered_msa, unmatched_names
end
"""
join_msas(msa_a::AnnotatedMultipleSequenceAlignment,
msa_b::AnnotatedMultipleSequenceAlignment,
pairing;
kind::Symbol=:outer,
axis::Int=1)::AnnotatedMultipleSequenceAlignment
join_msas(msa_a::AnnotatedMultipleSequenceAlignment,
msa_b::AnnotatedMultipleSequenceAlignment,
positions_a,
positions_b;
kind::Symbol=:outer,
axis::Int=1)::AnnotatedMultipleSequenceAlignment
Join two Multiple Sequence Alignments (MSAs), `msa_a` and `msa_b`, based on specified
matching positions or names. The function supports two formats: one takes a `pairing`
argument as a list of correspondences, and the other takes `positions_a` and
`positions_b` as separate lists indicating matching positions or names in each MSA.
This function allows for various types of join operations (`:inner`, `:outer`, `:left`,
`:right`) and can merge MSAs by sequences (`axis` `1`) or by columns (`axis` `2`).
**Parameters:**
- `msa_a::AnnotatedMultipleSequenceAlignment`: The first MSA.
- `msa_b::AnnotatedMultipleSequenceAlignment`: The second MSA.
- `pairing`: An iterable where each element is a pair of sequence or column
positions (`Int`s) or names (`String`s) to match between `msa_a` and `msa_b`. For example,
it can be a list of two-element tuples or pairs, or and `OrderedDict`.
- `positions_a`, `positions_b`: Separate lists of positions or names in `msa_a` and `msa_b`,
respectively.
- `kind::Symbol`: Type of join operation. Default is `:outer`.
- `axis::Int`: The axis along which to join (`1` to match sequences, `2` to match columns).
**Returns:**
- `AnnotatedMultipleSequenceAlignment`: A new MSA resulting from the join operation.
**Behavior and Sequence Ordering:**
The order of sequences or columns in the resulting MSA depends on the `kind` of join
operation and the order of elements in the `pairing` or `positions_a` and `positions_b` lists.
- For `:inner` joins, the function returns an MSA containing only those sequences/columns
that are paired in both `msa_a` and `msa_b`. The order of elements in the output MSA
follows the order in the `pairing` or position lists.
- For `:outer` joins, the output MSA includes all sequences/columns from both `msa_a` and
`msa_b`. Unpaired sequences/columns are filled with gaps as needed. The sequences/columns
from `msa_a` are placed first. If the `pairing` or position lists are sorted, the output
MSA columns and sequences will keep the same order as in the inputs. That's nice for
situations such as profile alignments where the order of columns is important. If the
`pairing` or position lists are not sorted, then the order of sequences/columns in the
output MSA is not guaranteed to be the same as in the inputs. In particular, the matched
sequences or columns will be placed first, followed by the unmatched ones.
- For `:left` joins, all sequences/columns from `msa_a` are included in the output MSA
keeping the same order as in `msa_a`. Sequences/columns from `msa_b` are added where
matches are found, with gaps filling the unmatched positions.
- For `:right` joins, the output MSA behaves like `:left` joins but with roles of
`msa_a` and `msa_b` reversed.
**Warning:** When using `Dict` for pairing, the order of elements might not be preserved as
expected. `Dict` in Julia does not maintain the order of its elements, which might lead to
unpredictable order of sequences/columns in the output MSA. To preserve order, it is
recommended to use an `OrderedDict` or a list of `Pair`s objects.
"""
function join_msas(
msa_a::AnnotatedMultipleSequenceAlignment,
msa_b::AnnotatedMultipleSequenceAlignment,
pairing;
kind::Symbol = :outer,
axis::Int = 1,
)
# Check that input arguments and throw explicit ArgumentErrors if necessary
if isempty(pairing)
throw(
ArgumentError(
"The pairing argument indicating the matching positions is empty.",
),
)
end
if length(first(pairing)) != 2
throw(
ArgumentError(
string(
"pairing must consist of pairs where the first element ",
"corresponds to a position in the first MSA and the second to the second MSA. ",
"Otherwise, utilize two distinct position lists.",
),
),
)
end
if kind != :inner && kind != :outer && kind != :left && kind != :right
throw(
ArgumentError(
"The kind of join must be one of :inner, :outer, :left or :right.",
),
)
end
if axis != 1 && axis != 2
throw(ArgumentError("The axis must be 1 (sequences) or 2 (columns)."))
end
# Get the matching positions as integer vectors
positions_a, positions_b = _find_pairing_positions(axis, msa_a, msa_b, pairing)
# Perform the join
if kind == :inner
if axis == 1
return hcat(msa_a[positions_a, :], msa_b[positions_b, :])
else
return vcat(msa_a[:, positions_a], msa_b[:, positions_b])
end
elseif kind == :outer
if issorted(positions_a) && issorted(positions_b)
gapped_a = _insert_sorted_gaps(
msa_a,
msa_b,
positions_a,
positions_b,
block_position = :after,
axis = axis,
)
gapped_b =
_insert_sorted_gaps(msa_b, msa_a, positions_b, positions_a, axis = axis)
return axis == 1 ? hcat(gapped_a, gapped_b) : vcat(gapped_a, gapped_b)
else
# do as the inner join for the matching positions, and add the unmatched
# positions at the end, using gap blocks
reordered_a, unmatched_names_a =
_reorder_and_extract_unmatched_names(msa_a, positions_a, axis)
reordered_b, unmatched_names_b =
_reorder_and_extract_unmatched_names(msa_b, positions_b, axis)
if axis == 1
@warn "Sequence order may not be preserved due to unsorted matching positions."
a_block = _insert_gap_sequences(
reordered_a,
unmatched_names_b,
nsequences(reordered_a) + 1,
)
b_block = _insert_gap_sequences(
reordered_b,
unmatched_names_a,
length(positions_b) + 1,
)
return hcat(a_block, b_block)
else
@warn "Column order may not be preserved due to unsorted matching positions."
a_block = _insert_gap_columns(
reordered_a,
length(unmatched_names_b),
ncolumns(reordered_a) + 1,
)
b_block = _insert_gap_columns(
reordered_b,
length(unmatched_names_a),
length(positions_b) + 1,
)
return vcat(a_block, b_block)
end
end
elseif kind == :left
gapped_b = _add_gaps_in_b(msa_a, msa_b, positions_a, positions_b, axis)
return axis == 1 ? hcat(msa_a, gapped_b) : vcat(msa_a, gapped_b)
elseif kind == :right
gapped_a = _add_gaps_in_b(msa_b, msa_a, positions_b, positions_a, axis)
return axis == 1 ? hcat(gapped_a, msa_b) : vcat(gapped_a, msa_b)
else
throw(
ArgumentError(
"The kind of join must be one of :inner, :outer, :left or :right.",
),
)
end
end
function join_msas(
msa_a::AnnotatedMultipleSequenceAlignment,
msa_b::AnnotatedMultipleSequenceAlignment,
positions_a,
positions_b;
kind::Symbol = :outer,
axis::Int = 1,
)
if length(positions_a) != length(positions_b)
throw(ArgumentError("positions_a and positions_b must have the same length."))
end
pairing = zip(positions_a, positions_b)
join_msas(msa_a, msa_b, pairing, kind = kind, axis = axis)
end
function Base.join(
msa_a::AnnotatedMultipleSequenceAlignment,
msa_b::AnnotatedMultipleSequenceAlignment,
args...;
kwargs...,
)
Base.depwarn(
"The function `join` using AnnotatedMultipleSequenceAlignment objects is deprecated. Use `join_msas` instead.",
:join,
force = true,
)
join_msas(msa_a, msa_b, args...; kwargs...)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 1248 | struct FASTA <: MSAFormat end
# FASTA Parser
# ============
function _pre_readfasta(string::AbstractString)
seqs = split(string, '>')
N = length(seqs) - 1
IDS = Array{String}(undef, N)
SEQS = Array{String}(undef, N)
for i = 1:N
fields = split(seqs[i+1], '\n')
IDS[i] = fields[1]
SEQS[i] = replace(join(fields[2:end]), r"\s+" => "")
end
(IDS, SEQS)
end
# MethodError: no method matching seek(::TranscodingStreams.TranscodingStream, ::Int)
_pre_readfasta(io::TranscodingStreams.TranscodingStream) = _pre_readfasta(read(io, String))
function _pre_readfasta(io)
IDS = String[]
SEQS = String[]
for (name, seq) in FastaReader{String}(io) # FastaIO
push!(IDS, name)
push!(SEQS, seq)
end
(IDS, SEQS)
end
function _load_sequences(
io::Union{IO,AbstractString},
format::Type{FASTA};
create_annotations::Bool = false,
)
IDS, SEQS = _pre_readfasta(io)
return IDS, SEQS, Annotations()
end
# Print FASTA
# ===========
function Utils.print_file(io::IO, msa::AbstractMatrix{Residue}, format::Type{FASTA})
seqnames = sequencenames(msa)
for i = 1:nsequences(msa)
println(io, ">", seqnames[i], "\n", stringsequence(msa, i))
end
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 14793 | # File Formats
# ============
abstract type AbstractSequenceFormat <: FileFormat end
abstract type MSAFormat <: AbstractSequenceFormat end
abstract type SequenceFormat <: AbstractSequenceFormat end
# Mappings
# ========
# It checks sequence lengths
function _fill_aln_seq_ann!(
aln,
seq_ann::Vector{String},
seq::String,
init::Int,
nres::Int,
i,
)
if length(seq) != nres
throw(
ErrorException(
string(
"There is an aligned sequence with different number of columns [ ",
length(seq),
" != ",
nres,
" ]:\n",
seq,
),
),
)
end
j = 1
@inbounds for res in seq
aln[j, i] = res
if res != '-' && res != '.'
seq_ann[j] = string(init)
init += 1
else
seq_ann[j] = ""
end
j += 1
end
join(seq_ann, ','), init - 1
end
function _to_msa_mapping(sequences::Array{String,1})
nseq = size(sequences, 1)
nres = length(sequences[1])
aln = Array{Residue}(undef, nres, nseq)
mapp = Array{String}(undef, nseq)
seq_ann = Array{String}(undef, nres)
for i = 1:nseq
# It checks sequence lengths
mapp[i], last = _fill_aln_seq_ann!(aln, seq_ann, sequences[i], 1, nres, i)
end
msa = NamedArray(permutedims(aln, [2, 1]))
# MSA constructors adds dimension names
# setdimnames!(msa, ("Seq","Col"))
(msa, mapp)
end
function _to_msa_mapping(sequences::Array{String,1}, ids)
nseq = size(sequences, 1)
nres = length(sequences[1])
aln = Array{Residue}(undef, nres, nseq)
mapp = Array{String}(undef, nseq)
seq_ann = Array{String}(undef, nres)
sep = r"/|-"
for i = 1:nseq
fields = split(ids[i], sep)
init = length(fields) == 3 ? parse(Int, fields[2]) : 1
mapp[i], last = _fill_aln_seq_ann!(aln, seq_ann, sequences[i], init, nres, i)
if length(fields) == 3
end_coordinate = parse(Int, fields[3])
if last != end_coordinate
throw(
ErrorException(
string(
"The last residue in sequence ",
i,
" (residue number ",
last,
") doesn't match the sequence coordinate indicated on sequence name (",
end_coordinate,
").",
),
),
)
end
end
end
msa = NamedArray(
permutedims(aln, [2, 1]),
(
OrderedDict{String,Int}(zip(ids, 1:nseq)),
OrderedDict{String,Int}(string(i) => i for i = 1:nres),
),
("Seq", "Col"),
)
msa, mapp
end
# Check sequence length
# ---------------------
#
# Functions to be used in _pre_read... functions
# This checks that all the sequences have the same length,
# Use _convert_to_matrix_residues(SEQS, _get_msa_size(SEQS))
# instead of convert(Matrix{Residue},SEQS)
# if SEQS was generated by pre_read... calling _check_seq_...
function _check_seq_and_id_number(IDS, SEQS)
if length(SEQS) != length(IDS)
throw(
ErrorException(
"The number of sequences is different from the number of names.",
),
)
end
end
function _check_seq_len(IDS, SEQS)
N = length(SEQS)
_check_seq_and_id_number(IDS, SEQS)
if N > 1
first_length = length(SEQS[1])
for i = 2:N
len = length(SEQS[i])
if len != first_length
throw(
ErrorException(
"The sequence $(IDS[i]) has $len residues. " *
"$first_length residues are expected.",
),
)
end
end
end
end
# Disambiguate Sequences
# ----------------------
function _disambiguate_sequences(IDS::Vector{String})
old2new = Dict{String,Vector{String}}()
seen = OrderedSet{String}()
for original in IDS
current_name = original
count = length(get(old2new, current_name, []))
new_name = current_name
if count > 0
new_name = _propose_name(current_name, count)
end
while new_name in seen
count += 1
new_name = _propose_name(current_name, count)
end
push!(seen, new_name)
if haskey(old2new, original)
push!(old2new[original], new_name)
else
old2new[original] = [new_name]
end
end
return old2new, collect(seen)
end
_propose_name(base::String, count::Int)::String = "$(base)($(count))"
# NamedArray{Residue,2} and AnnotatedMultipleSequenceAlignment generation
# -----------------------------------------------------------------------
function _ids_ordered_dict(ids, nseq::Int)
dict = OrderedDict{String,Int}()
sizehint!(dict, length(ids))
for (i, id) in enumerate(ids)
dict[id] = i
end
if length(dict) < nseq
throw(ArgumentError("There are less unique sequence identifiers than sequences."))
end
return dict
end
function _colnumber_ordered_dict(nres::Int)
dict = OrderedDict{String,Int}()
sizehint!(dict, nres)
for i = 1:nres
dict[string(i)] = i
end
return dict
end
function _generate_named_array(SEQS, IDS)::NamedResidueMatrix{Array{Residue,2}}
nseq, nres = _get_msa_size(SEQS)
msa = _convert_to_matrix_residues(SEQS, (nseq, nres))
NamedResidueMatrix{Array{Residue,2}}(
msa,
(_ids_ordered_dict(IDS, nseq), _colnumber_ordered_dict(nres)),
("Seq", "Col"),
)
end
function _generate_annotated_msa(
annot::Annotations,
IDS::Vector{String},
SEQS,
keepinserts,
generatemapping,
useidcoordinates,
deletefullgaps,
)
if keepinserts
_keepinserts!(SEQS, annot)
end
from_hcat = getannotfile(annot, "HCat", "") != ""
if generatemapping
N = length(IDS)
N > 0 || throw(ErrorException("There are no sequence in the alingment!"))
first_seq_name = IDS[1]
if getannotsequence(annot, first_seq_name, "SeqMap", "") != ""
@warn("""
The file already has sequence mappings annotations.
MIToS will replace those annotations as you have set generatemapping to true.
Set generatemapping to false to use the mapping annotations of the file.
""")
end
if useidcoordinates && hascoordinates(first_seq_name)
MSA, MAP = _to_msa_mapping(SEQS, IDS)
else
MSA, MAP = _to_msa_mapping(SEQS)
setnames!(MSA, IDS, 1)
end
# vcat prefixed ColMap annotations won't cause problems here
if getannotfile(annot, "ColMap", "") != ""
mssg = if from_hcat
"""
The file came from an MSA concatenation and has column annotations.
The information about the column numbers before concatenation will be lost
because of the generatemapping keyword argument.
"""
else
"The file already has column annotations. ColMap will be replaced."
end
@warn """
$mssg You can use generatemapping=false to keep the file mapping annotations.
"""
end
setannotfile!(annot, "NCol", string(size(MSA, 2)))
setannotfile!(annot, "ColMap", join(vcat(1:size(MSA, 2)), ','))
for i = 1:N
setannotsequence!(annot, IDS[i], "SeqMap", MAP[i])
end
else
MSA = _generate_named_array(SEQS, IDS)
# we do not deal with vcat prefixed ColMap or HCat annotations to avoid that
# the column names reflect only one of the concatenated alignments
colmap = getannotfile(annot, "ColMap", "")
cols = if colmap != ""
map(String, split(colmap, ','))
else
String[]
end
if !isempty(cols)
if from_hcat
msas = map(String, split(getannotfile(annot, "HCat"), ','))
setnames!(MSA, String["$(m)_$c" for (m, c) in zip(msas, cols)], 2)
else
setnames!(MSA, cols, 2)
end
end
end
msa = AnnotatedMultipleSequenceAlignment(MSA, annot)
if deletefullgaps
deletefullgapcolumns!(msa)
end
msa
end
# Matrix{Residue} and NamedArray{Residue,2}
# -----------------------------------------
#
# This checks that all the sequences have the same length
#
function _strings_to_msa(
::Type{NamedArray{Residue,2}},
seqs::Vector{String},
deletefullgaps::Bool,
)
msa = NamedArray(convert(Matrix{Residue}, seqs))
setdimnames!(msa, ("Seq", "Col"))
if deletefullgaps
return (deletefullgapcolumns(msa))
end
msa
end
function _strings_to_msa(
::Type{Matrix{Residue}},
seqs::Vector{String},
deletefullgaps::Bool,
)
msa = convert(Matrix{Residue}, seqs)
if deletefullgaps
return (deletefullgapcolumns(msa))
end
msa
end
# Unsafe: It doesn't check sequence lengths
# Use it after _pre_read... calling _check_seq_...
function _strings_to_matrix_residue_unsafe(seqs::Vector{String}, deletefullgaps::Bool)
msa = _convert_to_matrix_residues(seqs, _get_msa_size(seqs))
if deletefullgaps
return (deletefullgapcolumns(msa))
end
msa
end
# Delete Full of Gap Columns
# ==========================
"""
Deletes columns with 100% gaps, this columns are generated by inserts.
"""
function deletefullgapcolumns!(
msa::AbstractMultipleSequenceAlignment,
annotate::Bool = true,
)
mask = columngapfraction(msa) .!= one(Float64)
number = sum(.~mask)
if number != 0
annotate && annotate_modification!(
msa,
string(
"deletefullgaps! : Deletes ",
number,
" columns full of gaps (inserts generate full gap columns on MIToS ",
"because lowercase and dots are not allowed)",
),
)
filtercolumns!(msa, mask, annotate)
end
msa
end
function deletefullgapcolumns(msa::AbstractMatrix{Residue})
mask = columngapfraction(msa) .!= one(Float64)
number = sum(.~mask)
if number != 0
return (filtercolumns(msa, mask))
end
msa
end
function deletefullgapcolumns(msa::AbstractMultipleSequenceAlignment, annotate::Bool = true)
deletefullgapcolumns!(copy(msa)::AbstractMultipleSequenceAlignment, annotate)
end
@doc """
`parse_file(io, format[, output; generatemapping, useidcoordinates, deletefullgaps])`
The keyword argument `generatemapping` (`false` by default) indicates if the mapping of the
sequences ("SeqMap") and columns ("ColMap") and the number of columns in the original MSA
("NCol") should be generated and saved in the annotations. If `useidcoordinates` is `true`
(default: `false`) the sequence IDs of the form "ID/start-end" are parsed and used for
determining the start and end positions when the mappings are generated. `deletefullgaps`
(`true` by default) indicates if columns 100% gaps (generally inserts from a HMM) must be
removed from the MSA.
""" parse_file
# Keepinserts
# ===========
"""
Function to keep insert columns in `parse_file`. It uses the first sequence to generate the
"Aligned" annotation, and after that, convert all the characters to uppercase.
"""
function _keepinserts!(SEQS, annot)
aligned = map(SEQS[1]) do char
isuppercase(char) || char == '-' ? '1' : '0'
end
setannotcolumn!(annot, "Aligned", aligned)
map!(uppercase, SEQS, SEQS)
end
# Print inserts
# =============
_get_aligned_columns(msa::AnnotatedAlignedObject) = getannotcolumn(msa, "Aligned", "")
_get_aligned_columns(msa::AbstractMatrix{Residue}) = ""
function _format_inserts(seq::String, aligned::String, keep_insert_gaps::Bool = true)
if isempty(aligned)
return seq
end
formatted = Char[]
for (aln, res) in zip(aligned, seq)
if aln == '1'
push!(formatted, res)
else
if res == '-'
keep_insert_gaps && push!(formatted, '.')
else
push!(formatted, lowercase(res))
end
end
end
join(formatted)
end
# Parse for MSA formats
# =====================
function Utils.parse_file(
io::Union{IO,AbstractString},
format::Type{T},
output::Type{AnnotatedMultipleSequenceAlignment};
generatemapping::Bool = false,
useidcoordinates::Bool = false,
deletefullgaps::Bool = true,
keepinserts::Bool = false,
) where {T<:MSAFormat}
IDS, SEQS, annot = _load_sequences(io, format; create_annotations = true)
_check_seq_len(IDS, SEQS)
_generate_annotated_msa(
annot,
IDS,
SEQS,
keepinserts,
generatemapping,
useidcoordinates,
deletefullgaps,
)
end
function Utils.parse_file(
io::Union{IO,AbstractString},
format::Type{T},
output::Type{NamedResidueMatrix{Array{Residue,2}}};
deletefullgaps::Bool = true,
) where {T<:MSAFormat}
IDS, SEQS, _ = _load_sequences(io, format; create_annotations = false)
_check_seq_len(IDS, SEQS)
msa = _generate_named_array(SEQS, IDS)
if deletefullgaps
return deletefullgapcolumns(msa)
end
msa
end
function Utils.parse_file(
io::Union{IO,AbstractString},
format::Type{T},
output::Type{MultipleSequenceAlignment};
deletefullgaps::Bool = true,
) where {T<:MSAFormat}
msa = parse_file(
io,
format,
NamedResidueMatrix{Array{Residue,2}},
deletefullgaps = deletefullgaps,
)
MultipleSequenceAlignment(msa)
end
function Utils.parse_file(
io::Union{IO,AbstractString},
format::Type{T},
output::Type{Matrix{Residue}};
deletefullgaps::Bool = true,
) where {T<:MSAFormat}
IDS, SEQS, _ = _load_sequences(io, format; create_annotations = false)
_check_seq_len(IDS, SEQS)
_strings_to_matrix_residue_unsafe(SEQS, deletefullgaps)
end
function Utils.parse_file(
io::Union{IO,AbstractString},
format::Type{T};
generatemapping::Bool = false,
useidcoordinates::Bool = false,
deletefullgaps::Bool = true,
keepinserts::Bool = false,
) where {T<:MSAFormat}
parse_file(
io,
format,
AnnotatedMultipleSequenceAlignment;
generatemapping = generatemapping,
useidcoordinates = useidcoordinates,
deletefullgaps = deletefullgaps,
keepinserts = keepinserts,
)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 5565 | for T in (
:(AlignedSequence),
:(AnnotatedSequence),
:(AnnotatedAlignedSequence),
:(MultipleSequenceAlignment),
:(AnnotatedMultipleSequenceAlignment),
)
@eval Base.IndexStyle(::Type{$(T)}) = Base.IndexLinear()
end
# ---
# Performant lookup of the sequence and column positions.
# CAUTION: This relies on the NamedArrays internal representation.
# This is a bit hacky, but it's the fastest way to get the index.
"""
sequence_index(msa, seq_name)
Return the index (integer position) of the sequence with name `seq_name` in the MSA `msa`.
A `KeyError` is thrown if the sequence name does not exist. If `seq_name` is an integer,
the same integer is returned without checking if it is a valid index.
"""
sequence_index(msa::NamedResidueMatrix, seq_name::AbstractString) = msa.dicts[1][seq_name]
"""
column_index(msa, col_name)
Return the index (integer position) of the column with name `col_name` in the MSA `msa`.
A `KeyError` is thrown if the column name does not exist. If `col_name` is an integer,
the same integer is returned without checking if it is a valid index.
"""
column_index(msa::NamedResidueMatrix, col_name::AbstractString) = msa.dicts[2][col_name]
function sequence_index(msa::AbstractResidueMatrix, seq_name::AbstractString)
sequence_index(msa.matrix, seq_name)
end
function column_index(msa::AbstractResidueMatrix, column_name::AbstractString)
column_index(msa.matrix, column_name)
end
# Do not allow indexing Matrix{Residue} with AbstractString
function sequence_index(msa::Matrix{Residue}, seq_name::AbstractString)
throw(
ErrorException(
"There are no sequence names in a Matrix{Residue} object, use an integer index instead.",
),
)
end
function column_index(msa::Matrix{Residue}, column_name::AbstractString)
throw(
ErrorException(
"There are no column names in a Matrix{Residue} object, use an integer index instead.",
),
)
end
# If the user already gives a position, return the same position.
sequence_index(msa, sequence_index::Int) = sequence_index
column_index(msa, column_index::Int) = column_index
# ---
@inline Base.getindex(x::AbstractResidueMatrix, args...) = getindex(namedmatrix(x), args...)
@inline function Base.setindex!(x::AbstractResidueMatrix, value, args...)
setindex!(namedmatrix(x), value, args...)
end
# Special getindex/setindex! for sequences to avoid `seq["seqname","colname"]`
@inline function Base.getindex(
x::Union{AbstractSequence,AbstractAlignedSequence},
i::Union{Int,AbstractString},
)
getindex(namedmatrix(x), 1, i)
end
@inline function Base.setindex!(
x::Union{AbstractSequence,AbstractAlignedSequence},
value,
i::Union{Int,AbstractString},
)
setindex!(namedmatrix(x), value, 1, i)
end
# ## Special getindex to conserve annotations and types
"""
Helper function to create a boolean mask to select sequences.
"""
function _get_selected_sequences(msa, selector)
type = eltype(selector)
if type == Bool
return selector
else
to_select = Set(selector)
if type <: Number
Bool[i in to_select for i = 1:nsequences(msa)]
elseif type <: AbstractString
Bool[i in to_select for i in sequencenames(msa)]
else
throw(ArgumentError("$type is not a valid element type for the selector."))
end
end
end
function _column_indices(msa, selector)
if eltype(selector) <: AbstractString
return Int[column_index(msa, i) for i in selector]
end
selector
end
function Base.getindex(
msa::AnnotatedMultipleSequenceAlignment,
seqs::AbstractArray,
cols::AbstractArray,
)
annot = copy(annotations(msa))
seq_selector = _get_selected_sequences(msa, seqs)
filtersequences!(annot, sequencenames(msa), seq_selector)
_annotate_seq_modification!(annot, seq_selector)
col_selector = _column_indices(msa, cols)
filtercolumns!(annot, col_selector)
_annotate_col_modification!(annot, col_selector)
AnnotatedMultipleSequenceAlignment(msa.matrix[seqs, cols], annot)
end
function Base.getindex(
msa::AnnotatedMultipleSequenceAlignment,
seqs::AbstractArray,
cols::Colon,
)
annot = copy(annotations(msa))
seq_selector = _get_selected_sequences(msa, seqs)
filtersequences!(annot, sequencenames(msa), seq_selector)
_annotate_seq_modification!(annot, seq_selector)
AnnotatedMultipleSequenceAlignment(msa.matrix[seqs, cols], annot)
end
function Base.getindex(
msa::AnnotatedMultipleSequenceAlignment,
seqs::Colon,
cols::AbstractArray,
)
annot = copy(annotations(msa))
col_selector = _column_indices(msa, cols)
filtercolumns!(annot, col_selector)
_annotate_col_modification!(annot, col_selector)
AnnotatedMultipleSequenceAlignment(msa.matrix[seqs, cols], annot)
end
Base.getindex(msa::AnnotatedMultipleSequenceAlignment, seqs::Colon, cols::Colon) = copy(msa)
function Base.getindex(
msa::MultipleSequenceAlignment,
seqs::Union{AbstractArray,Colon},
cols::Union{AbstractArray,Colon},
)
MultipleSequenceAlignment(msa.matrix[seqs, cols])
end
function Base.getindex(seq::AnnotatedAlignedSequence, cols::AbstractArray)
seq_copy = copy(seq)
col_selector = _column_indices(seq, cols)
filtercolumns!(seq_copy, col_selector)
_annotate_col_modification!(seq_copy, col_selector)
seq_copy
end
# TODO: AnnotatedSequence
function Base.getindex(seq::AlignedSequence, cols::Union{AbstractArray,Colon})
AlignedSequence(seq.matrix[cols])
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 2105 | # Hobohm I
# ========
"""
Fill `cluster` and `clustersize` matrices. These matrices are assumed to be empty
(only zeroes) and their length is assumed to be equal to the number of sequences in the
alignment (`aln`). `threshold` is the minimum identity value between two sequences
to be in the same cluster.
"""
function _fill_hobohmI!(
cluster::Vector{Int},
clustersize::Vector{Int},
aln::Vector{Vector{Residue}},
threshold,
)
cluster_id = 0
nseq = length(aln)
@inbounds for i = 1:(nseq-1)
if cluster[i] == 0
cluster_id += 1
cluster[i] = cluster_id
clustersize[cluster_id] += 1
ref_seq = aln[i]
for j = (i+1):nseq
if cluster[j] == 0 && percentidentity(ref_seq, aln[j], threshold)
cluster[j] = cluster_id
clustersize[cluster_id] += 1
end
end
end
end
@inbounds if cluster[nseq] == 0
cluster_id += 1
cluster[nseq] = cluster_id
clustersize[cluster_id] += 1
end
resize!(clustersize, cluster_id)
end
"""
Calculates the weight of each sequence in a cluster. The weight is equal to one divided
by the number of sequences in the cluster.
"""
function _get_sequence_weight(clustersize, cluster)
nseq = length(cluster)
sequence_weight = Array{Float64}(undef, nseq)
for i = 1:nseq
@inbounds sequence_weight[i] = 1.0 / clustersize[cluster[i]]
end
Weights(sequence_weight, Float64(length(clustersize)))
end
"""
Sequence clustering using the Hobohm I method from Hobohm et. al.
# References
- [Hobohm, Uwe, et al. "Selection of representative protein data sets."
Protein Science 1.3 (1992): 409-417.](@cite hobohm1992selection)
"""
function hobohmI(msa::AbstractMatrix{Residue}, threshold)
aln = getresiduesequences(msa)
nseq = length(aln)
cluster = zeros(Int, nseq)
clustersize = zeros(Int, nseq)
_fill_hobohmI!(cluster, clustersize, aln, threshold)
Clusters(clustersize, cluster, _get_sequence_weight(clustersize, cluster))
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 8503 | # Calculates percent identity of two aligned sequences
# No account of the positions with gaps in both sequences in the length
"""
seq1 and seq2 should have the same len
"""
function _percentidentity(seq1, seq2, len)
count = 0
notcount = 0
for i = 1:len
@inbounds aa1 = seq1[i]
@inbounds aa2 = seq2[i]
if aa1 == aa2
if aa1 == GAP || aa1 == XAA
notcount += 1
else
count += 1
end
else
if aa1 == XAA || aa2 == XAA
notcount += 1
end
end
end
100.0 * count / (len - notcount)
end
"""
`percentidentity(seq1, seq2)`
Calculates the fraction of identities between two aligned sequences. The identity value is
calculated as the number of identical characters in the i-th position of both sequences
divided by the length of both sequences. Positions with gaps in both sequences doesn't
count to the length of the sequences. Positions with a `XAA` in at least one sequence
aren't counted.
"""
function percentidentity(seq1, seq2)
len = length(seq1)
if len != length(seq2)
throw(
ErrorException("""
Sequences of different length, they aren't aligned or don't come from the same MSA.
"""),
)
end
_percentidentity(seq1, seq2, len)
end
"""
`percentidentity(seq1, seq2, threshold)`
Computes quickly if two aligned sequences have a identity value greater than a given
`threshold` value. Returns a boolean value. Positions with gaps in both sequences
doesn't count to the length of the sequences. Positions with a `XAA` in at least one
sequence aren't counted.
"""
function percentidentity(seq1, seq2, threshold)
fraction = threshold / 100.0
len = length(seq1)
if len != length(seq2)
throw(
ErrorException("""
Sequences of different length, they aren't aligned or don't come from the same MSA.
"""),
)
end
n = len
limit_count = n * fraction
diff = 0
count = 0
@inbounds for i = 1:len
aa1 = seq1[i]
aa2 = seq2[i]
if aa1 == XAA || aa2 == XAA
n -= 1
continue
end
if aa1 == aa2
if aa1 != GAP
count += 1
if count >= limit_count
return (true)
end
else
n -= 1
limit_count = n * fraction
end
else
diff += 1
if diff > n - limit_count
return (false)
end
end
end
(count / n) >= fraction
end
# percentidentity for a MSA
# =========================
function _percentidentity_kernel!(scores, aln::Vector{Vector{Residue}}, nseq, len)
k = 0
list = getlist(scores)
@inbounds for i = 1:(nseq-1)
a = aln[i]
for j = (i+1):nseq
list[k+=1] = _percentidentity(a, aln[j], len)
end
end
scores
end
"""
`percentidentity(msa[, out::Type=Float64])`
Calculates the identity between all the sequences on a MSA. You can indicate the output
element type with the last optional parameter (`Float64` by default). For a MSA with a lot
of sequences, you can use `Float32` or `Flot16` in order to avoid the `OutOfMemoryError()`.
"""
function percentidentity(msa::AbstractMatrix{Residue}, out::Type{T} = Float64) where {T}
aln = getresiduesequences(msa)
nseq = length(aln)
len = length(aln[1])
scores = sequencepairsmatrix(msa, T, Val{false}, T(100.0))
_percentidentity_kernel!(getarray(scores), aln, nseq, len)
scores
end
# Mean Percent Identity of an MSA
# ===============================
"""
Returns the mean of the percent identity between the sequences of a MSA. If the MSA has 300
sequences or less, the mean is exact. If the MSA has more sequences and the `exact` keyword
is `false` (defualt), 44850 random pairs of sequences are used for the estimation. The
number of samples can be changed using the second argument. Use `exact=true` to perform all
the pairwise comparison (the calculation could be slow).
"""
function meanpercentidentity(msa, nsamples::Int = 44850; exact::Bool = false)
# lengthlist(300, false) == 44850
nseq, ncol = size(msa)
@assert nsamples > 2 "At least 2 samples are needed."
nvalues = lengthlist(nseq, Val{false})
sum = 0.0
if !exact && nvalues >= nsamples
samples = Set{Tuple{Int,Int}}()
sizehint!(samples, nsamples)
while length(samples) < nsamples
i = rand(1:(nseq-1))
j = rand((i+1):nseq)
if !in((i, j), samples)
push!(samples, (i, j))
sum += percentidentity(msa[i, :], msa[j, :])
end
end
return ((sum / nsamples))
else # exact and/or few sequences
for i = 1:(nseq-1)
@inbounds @simd for j = (i+1):nseq
sum += percentidentity(msa[i, :], msa[j, :])
end
end
return ((sum / nvalues))
end
end
# Similarity percent
# ==================
"""
Calculates the similarity percent between two aligned sequences. The 100% is the length of
the aligned sequences minus the number of columns with gaps in both sequences and the number
of columns with at least one residue outside the alphabet. So, columns with residues outside
the alphabet (other than the specially treated `GAP`) aren't counted to the protein length.
Two residues are considered similar if they below to the same group in a `ReducedAlphabet`.
The `alphabet` (third positional argument) by default is:
```julia
ReducedAlphabet("(AILMV)(NQST)(RHK)(DE)(FWY)CGP")
```
The first group is composed of the non polar residues `(AILMV)`, the second group is composed
of polar residues, the third group are positive residues, the fourth group are negative
residues, the fifth group is composed by the aromatic residues `(FWY)`. `C`, `G` and `P`
are considered unique residues.
**Other residue groups/alphabets:**
**SMS (Sequence Manipulation Suite)** Ident and Sim *(Stothard Paul. 2000)*:
```julia
ReducedAlphabet("(GAVLI)(FYW)(ST)(KRH)(DENQ)P(CM)")
```
*Stothard P (2000) The Sequence Manipulation Suite: JavaScript programs for analyzing and
formatting protein and DNA sequences. Biotechniques 28:1102-1104.*
**Bio3D 2.2** seqidentity *(Grant, Barry J., et al. 2006)*:
```julia
ReducedAlphabet("(GA)(MVLI)(FYW)(ST)(KRH)(DE)(NQ)PC")
```
# References
- [Stothard, Paul. "The sequence manipulation suite: JavaScript programs for analyzing
and formatting protein and DNA sequences."
Biotechniques 28.6 (2000): 1102-1104.](@cite stothard2000sequence)
- [Grant, Barry J., et al. "Bio3d: an R package for the comparative analysis of protein
structures." Bioinformatics 22.21 (2006): 2695-2696.](@cite grant2006bio3d)
"""
function percentsimilarity(
seq1::Vector{Residue},
seq2::Vector{Residue},
alphabet::ResidueAlphabet = ReducedAlphabet("(AILMV)(RHK)(NQST)(DE)(FWY)CGP"),
)
len = length(seq1)
if len != length(seq2)
throw(
ErrorException(
"""
Sequences of different lengths, they aren't aligned or don't come from the same MSA.
""",
),
)
end
count = 0
colgap = 0
colout = 0 # Columns with residues outside the alphabet aren't used
@inbounds for i = 1:len
res1 = seq1[i]
res2 = seq2[i]
isgap1 = res1 == GAP
isgap2 = res2 == GAP
if isgap1 && isgap2
colgap += 1
continue
end
if (!isgap1 && !in(res1, alphabet)) || (!isgap2 && !in(res2, alphabet))
colout += 1
continue
end
if !isgap1 && !isgap2
count += Int(alphabet[res1] == alphabet[res2])
end
end
alnlen = len - colgap - colout
(100.0 * count) / alnlen
end
"""
Calculates the similarity percent between all the sequences on a MSA. You can indicate
the output element type with the `out` keyword argument (`Float64` by default). For an
MSA with a lot of sequences, you can use `out=Float32` or `out=Flot16` in order to
avoid the `OutOfMemoryError()`.
"""
function percentsimilarity(msa::AbstractMatrix{Residue}, A...; out::Type = Float64)
M = getresiduesequences(msa)
P = sequencepairsmatrix(msa, out, Val{false}, out(100.0))
@inbounds @iterateupper getarray(P) false begin
list[k] = percentsimilarity(M[i], M[j], A...)
end
P
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 4338 | """
The MSA module of MIToS has utilities for working with Multiple Sequence Alignments of protein Sequences (MSA).
**Features**
- Read and write MSAs in `Stockholm`, `FASTA`, `A3M`, `PIR`, or `Raw` format
- Handle MSA annotations
- Edit the MSA, e.g. delete columns or sequences, change sequence order, shuffling...
- Keep track of positions and annotations after modifications on the MSA
- Describe a MSA, e.g. mean percent identity, sequence coverage, gap percentage...
```julia
using MIToS.MSA
```
"""
module MSA
using OrderedCollections # OrderedDicts for Annotations
using AutoHashEquals # Annotations, Clusters
using NamedArrays # Col and Seq names, basic sequence/MSA object
using FastaIO # FastaReader (fast)
using Random # default_rng, shuffle!, rand, Sampler, randstring
using Dates # Dates.now()
using PairwiseListMatrices # Percent Identity Matrices
using StatsBase # Weights for clustering
using RecipesBase # Plots for MSAs
using TranscodingStreams # To solve MethodError seek(::TranscodingStream, ::Int)
using MIToS.Utils
import Markdown: @md_str # for docstrings
export # Residue
Residue,
GAP,
XAA,
@res_str,
# Alphabet
ResidueAlphabet,
GappedAlphabet,
UngappedAlphabet,
ReducedAlphabet,
getnamedict,
# ThreeLetters
residue2three,
three2residue,
# Annotations
Annotations,
# filtersequences!,
ncolumns,
filtercolumns!,
getannotfile,
getannotcolumn,
getannotsequence,
getannotresidue,
setannotfile!,
setannotcolumn!,
setannotsequence!,
setannotresidue!,
annotate_modification!,
delete_annotated_modifications!,
printmodifications,
# MultipleSequenceAlignment
AbstractResidueMatrix,
AbstractAlignedObject,
AbstractMultipleSequenceAlignment,
AbstractAlignedSequence,
MultipleSequenceAlignment,
AnnotatedMultipleSequenceAlignment,
AlignedSequence,
AnnotatedAlignedSequence,
AnnotatedAlignedObject,
UnannotatedAlignedObject,
AbstractSequence,
AnnotatedSequence,
NamedResidueMatrix,
annotations,
namedmatrix,
nsequences,
getresidues,
getsequence,
sequence_id,
getresiduesequences,
stringsequence,
getcolumnmapping,
getsequencemapping,
sequencenames,
columnnames,
sequencename_iterator,
columnname_iterator,
rename_sequences!,
rename_sequences, # TODO: rename_columns!
# MSAStats
gapfraction,
residuefraction,
coverage,
columngapfraction,
# MSAEditing
filtersequences,
filtersequences!,
filtercolumns,
filtercolumns!,
swapsequences!,
setreference!,
adjustreference,
adjustreference!,
gapstrip,
gapstrip!,
# GetIndex
sequence_index,
column_index,
# GeneralParserMethods
SequenceFormat,
MSAFormat,
deletefullgapcolumns,
deletefullgapcolumns!,
# Raw
Raw,
# Stockholm
Stockholm,
# FASTA
FASTA,
# NBRF/PIR
PIR,
# A3M
A3M,
A2M,
# Sequences
FASTASequences,
PIRSequences,
RawSequences,
# Shuffle
shuffle_msa!,
shuffle_msa,
# PLM
sequencepairsmatrix,
columnpairsmatrix,
# Identity
percentidentity,
meanpercentidentity,
percentsimilarity,
# Clusters
WeightTypes,
NoClustering,
Clusters,
AbstractCluster,
counts,
getweight,
nelements,
# Hobohm
hobohmI,
# Imported from Utils
read_file,
parse_file,
write_file,
print_file,
# Imported from Base or StdLib (and exported for docs)
names,
parse,
isvalid,
rand,
shuffle,
shuffle!,
# Concatenation
gethcatmapping,
join_msas
include("Residues.jl")
include("Alphabet.jl")
include("ThreeLetters.jl")
include("Annotations.jl")
include("MultipleSequenceAlignment.jl")
include("MSAEditing.jl")
include("GetIndex.jl")
include("MSAStats.jl")
include("GeneralParserMethods.jl")
include("Raw.jl")
include("Stockholm.jl")
include("FASTA.jl")
include("PIR.jl")
include("A3M.jl")
include("Sequences.jl")
include("Shuffle.jl")
include("PLM.jl")
include("Identity.jl")
include("Clusters.jl")
include("Hobohm.jl")
include("Plots.jl")
include("Concatenation.jl")
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 12350 | # Filters
# =======
# Creation of a boolean mask array
# --------------------------------
# If the input is a matrix, dropdims the singleton dimension
function _column_mask(mask::AbstractMatrix{Bool}, msa)
@assert size(mask, 1) == 1 "The mask should be a vector or a matrix of size (1,ncol)"
@assert size(mask, 2) == ncolumns(msa) "One boolean value per column is needed."
dropdims(mask, dims = 1)
end
function _sequence_mask(mask::AbstractMatrix{Bool}, msa)
@assert size(mask, 2) == 1 "The mask should be a vector or a matrix of size (nseq,1)"
@assert size(mask, 1) == nsequences(msa) "One boolean value per sequence is needed."
dropdims(mask, dims = 2)
end
# If the input is a function, apply it to the respective slice
function _column_mask(mask::Function, msa)
out = mapslices(mask, msa, dims = 1)
if size(out) != (1, ncolumns(msa)) || eltype(out) != Bool
error("The function must return a Bool element per column.")
end
dropdims(out, dims = 1)
end
function _sequence_mask(mask::Function, msa)
out = mapslices(mask, msa, dims = 2)
if size(out) != (nsequences(msa), 1) || eltype(out) != Bool
error("The function must return a Bool element per column.")
end
dropdims(out, dims = 2)
end
# If the mask is an AbstractVector{Bool}, return it without changes
function _column_mask(mask::AbstractVector{Bool}, msa)
@assert length(mask) == ncolumns(msa) "One boolean value per column is needed."
mask
end
function _sequence_mask(mask::AbstractVector{Bool}, msa)
@assert length(mask) == nsequences(msa) "One boolean value per sequence is needed."
mask
end
# If the mask is list of indexes, return it without changes
_column_mask(mask::Union{AbstractArray,Colon}, msa) = mask
# Annotate modifications
# ----------------------
_annotate_modification!(x, selector::Colon, fun::String, column::Bool) = nothing
function _annotate_modification!(x, selector::AbstractArray, fun::String, column::Bool)
entity = column ? "column" : "sequence"
verb = "has"
if eltype(selector) <: Bool
n_deleted = sum(.~selector)
if n_deleted > 0
if n_deleted > 1
entity *= "s"
verb = "have"
end
str = string("$fun : $n_deleted $entity $verb been deleted.")
annotate_modification!(x, str)
end
else
cleaned_selector = unique(selector)
n_selected = length(cleaned_selector)
if n_selected > 0
if n_selected > 1
entity *= "s"
verb = "have"
end
str = string("$fun : $n_selected $entity $verb been selected.")
annotate_modification!(x, str)
if column && n_selected > 1 && !issorted(selector) # do not store sequence order changes
annotate_modification!(x, "$fun : column order has changed!")
end
end
end
end
function _annotate_col_modification!(x, selector)
_annotate_modification!(x, selector, "filtercolumns!", true)
end
function _annotate_seq_modification!(x, selector)
_annotate_modification!(x, selector, "filtersequences!", false)
end
# Filter sequences
# ----------------
"""
It's similar to `filtersequences!` but for an `AbstractMatrix{Residue}`
"""
filtersequences(msa::AbstractMatrix{Residue}, mask) = msa[_sequence_mask(mask, msa), :]
"""
`filtersequences!(msa, mask[, annotate::Bool=true])`
It allows to filter `msa` sequences using a `AbstractVector{Bool}` `mask`
(It removes sequences with `false` values). `AnnotatedMultipleSequenceAlignment` annotations
are updated if `annotate` is `true` (default).
"""
function filtersequences!(
msa::AnnotatedMultipleSequenceAlignment,
mask,
annotate::Bool = true,
)
boolean_vector = _sequence_mask(mask, msa)
filtersequences!(annotations(msa), sequencenames(msa), boolean_vector)
# Filter annotations first, names will be changed by filtersequences:
msa.matrix = filtersequences(namedmatrix(msa), boolean_vector)
if annotate
_annotate_seq_modification!(msa, boolean_vector)
end
msa
end
function filtersequences!(msa::MultipleSequenceAlignment, mask, annotate::Bool = false) # annotate is useful for calling this
# inside other functions
msa.matrix = filtersequences(namedmatrix(msa), _sequence_mask(mask, msa))
msa
end
function filtersequences(
msa::Union{AnnotatedMultipleSequenceAlignment,MultipleSequenceAlignment},
args...,
)
filtersequences!(deepcopy(msa), args...)
end
# Filter columns
# --------------
"""
It's similar to `filtercolumns!` but for an `AbstractMatrix{Residue}`
"""
function filtercolumns(msa::AbstractMatrix{Residue}, mask)
msa[:, _column_mask(mask, msa)]
end
"""
`filtercolumns!(msa, mask[, annotate::Bool=true])`
It allows to filter MSA or aligned sequence columns/positions using a
`AbstractVector{Bool}` `mask`. Annotations are updated if `annotate` is `true` (default).
"""
function filtercolumns!(
x::Union{AnnotatedMultipleSequenceAlignment,AnnotatedAlignedSequence,AnnotatedSequence},
mask,
annotate::Bool = true,
)
selector = _column_mask(mask, x)
filtercolumns!(annotations(x), selector)
x.matrix = filtercolumns(namedmatrix(x), selector)
if annotate
_annotate_col_modification!(x, selector)
end
x
end
function filtercolumns!(x::UnannotatedAlignedObject, mask, annotate::Bool = false) # annotate is useful for calling this
# inside other functions
x.matrix = filtercolumns(namedmatrix(x), _column_mask(mask, x))
x
end
filtercolumns(x::AbstractResidueMatrix, args...) = filtercolumns!(deepcopy(x), args...)
# Util function
# -------------
"""
This function takes a vector of sequence names and a sequence id.
It returns the position of that id in the vector.
If the id isn't in the vector, It throws an error.
"""
function _get_seqid_index(names::Vector{String}, sequence_id::String)
id_index = something(findfirst(isequal(sequence_id), names), 0)
if id_index == 0
throw(ErrorException("$sequence_id is not in the list of sequence names."))
end
id_index
end
# Reference
# ---------
"""
It swaps the names on the positions `i` and `j` of a `Vector{String}`
"""
function _swap!(names::Vector{String}, i::Int, j::Int)
name = names[i, :]
names[i, :] = names[j, :]
names[j, :] = name
names
end
"""
It swaps the sequences on the positions `i` and `j` of an MSA. Also it's possible to swap
sequences using their sequence names/identifiers when the MSA object as names.
"""
function swapsequences!(matrix::Matrix{Residue}, i::Int, j::Int)
seq = matrix[i, :]
matrix[i, :] = matrix[j, :]
matrix[j, :] = seq
return matrix
end
function swapsequences!(matrix::NamedArray, i::Int, j::Int)
swapsequences!(getarray(matrix), i, j)
setnames!(matrix, _swap!(sequencenames(matrix), i, j), 1)
return matrix
end
function swapsequences!(matrix::NamedArray, i::String, j::String)
seqnames = sequencenames(matrix)
swapsequences!(matrix, _get_seqid_index(seqnames, i), _get_seqid_index(seqnames, j))
end
"""
It puts the sequence `i` (name or position) as reference (first sequence) of the MSA. This
function swaps the sequences 1 and `i`.
"""
function setreference!(
msa::AnnotatedMultipleSequenceAlignment,
i::Int,
annotate::Bool = true,
)
swapsequences!(namedmatrix(msa), 1, i)
if annotate
seqnames = sequencenames(msa)
annotate_modification!(
msa,
string(
"setreference! : Using ",
seqnames[1],
" instead of ",
seqnames[i],
" as reference.",
),
)
end
msa
end
function setreference!(msa::MultipleSequenceAlignment, i::Int, annotate::Bool = false)
# The annotate argument is useful for calling this inside other functions
swapsequences!(namedmatrix(msa), 1, i)
msa
end
function setreference!(
msa::NamedResidueMatrix{T},
i::Int,
annotate::Bool = false,
) where {T<:AbstractArray}
swapsequences!(msa, 1, i)
end
function setreference!(
msa::NamedResidueMatrix{T},
id::String,
annotate::Bool = false,
) where {T<:AbstractArray}
swapsequences!(msa, names(msa, 1)[1], id)
end
function setreference!(
msa::AbstractMultipleSequenceAlignment,
id::String,
annotate::Bool = true,
)
setreference!(msa, _get_seqid_index(sequencenames(msa), id), annotate)
end
function setreference!(msa::Matrix{Residue}, i::Int, annotate::Bool = false)
# The annotate argument is useful for calling this inside other functions
swapsequences!(msa, 1, i)
end
"""
Creates a new matrix of residues. This function deletes positions/columns of the MSA with
gaps in the reference (first) sequence.
"""
function adjustreference(msa::AbstractMatrix{Residue}, annotate::Bool = false)
# The annotate argument is useful for calling this inside other functions
msa[:, msa[1, :].!=GAP]
end
"""
It removes positions/columns of the MSA with gaps in the reference (first) sequence.
"""
function adjustreference!(msa::AbstractMultipleSequenceAlignment, annotate::Bool = true)
filtercolumns!(msa, vec(getresidues(getsequence(msa, 1))) .!= GAP, annotate)
end
"""
Creates a new matrix of `Residue`s (MSA) with deleted sequences and columns/positions. The
MSA is edited in the following way:
1. Removes all the columns/position on the MSA with gaps on the reference (first) sequence
2. Removes all the sequences with a coverage with respect to the number of
columns/positions on the MSA **less** than a `coveragelimit`
(default to `0.75`: sequences with 25% of gaps)
3. Removes all the columns/position on the MSA with **more** than a `gaplimit`
(default to `0.5`: 50% of gaps)
"""
function gapstrip(
msa::AbstractMatrix{Residue};
coveragelimit::Float64 = 0.75,
gaplimit::Float64 = 0.5,
)
msa = adjustreference(msa)
# Remove sequences with pour coverage of the reference sequence
if ncolumns(msa) != 0
msa = filtersequences(msa, vec(coverage(msa) .>= coveragelimit))
else
throw("There are not columns in the MSA after the gap trimming")
end
if nsequences(msa) != 0
msa = filtercolumns(msa, vec(columngapfraction(msa) .<= gaplimit))
else
throw("There are not sequences in the MSA after coverage filter")
end
msa
end
"""
This functions deletes/filters sequences and columns/positions on the MSA on the following
order:
1. Removes all the columns/position on the MSA with gaps on the reference (first) sequence.
2. Removes all the sequences with a coverage with respect to the number of
columns/positions on the MSA **less** than a `coveragelimit`
(default to `0.75`: sequences with 25% of gaps).
3. Removes all the columns/position on the MSA with **more** than a `gaplimit`
(default to `0.5`: 50% of gaps).
"""
function gapstrip!(
msa::AbstractMultipleSequenceAlignment,
annotate::Bool = isa(msa, AnnotatedAlignedObject);
coveragelimit::Float64 = 0.75,
gaplimit::Float64 = 0.5,
)
if annotate
annotate_modification!(
msa,
string("gapstrip! : Deletes columns with gaps in the first sequence."),
)
end
adjustreference!(msa, annotate)
# Remove sequences with pour coverage of the reference sequence
if ncolumns(msa) != 0
if annotate
annotate_modification!(
msa,
string(
"gapstrip! : Deletes sequences with a coverage less than ",
coveragelimit,
),
)
end
filtersequences!(msa, vec(coverage(msa) .>= coveragelimit), annotate)
else
throw("There are not columns in the MSA after the gap trimming")
end
# Remove columns with a porcentage of gap greater than gaplimit
if nsequences(msa) != 0
if annotate
annotate_modification!(
msa,
string("gapstrip! : Deletes columns with more than ", gaplimit, " gaps."),
)
end
filtercolumns!(msa, vec(columngapfraction(msa) .<= gaplimit), annotate)
else
throw("There are not sequences in the MSA after coverage filter")
end
msa
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 3396 |
# Counting Gaps and Coverage
# --------------------------
"""
It calculates the fraction of gaps on the `Array` (alignment, sequence, column, etc.). This
function can take an extra `dimension` argument for calculation of the gap fraction over the
given dimension.
"""
function gapfraction(x::AbstractArray{Residue})
counter = 0
len = 0
for res in x
counter += ifelse(res == GAP, 1, 0)
len += 1
end
float(counter) / float(len)
end
function gapfraction(x::AbstractArray{Residue}, dimension::Int)
mapslices(gapfraction, x, dims = dimension)
end
"""
It calculates the fraction of residues (no gaps) on the `Array`
(alignment, sequence, column, etc.). This function can take an extra `dimension` argument
for calculation of the residue fraction over the given dimension
"""
residuefraction(x::AbstractArray{Residue}) = 1.0 - gapfraction(x)
function residuefraction(x::AbstractArray{Residue}, dimension::Int)
mapslices(residuefraction, x, dims = dimension)
end
macro keep_names_dimension(functions)
function_names = functions.args
n = length(function_names)
definitions = Array{Any}(undef, n)
for i = 1:n
f = esc(function_names[i])
definitions[i] = quote
function ($f)(msa::NamedResidueMatrix{T}, dimension::Int) where {T}
result = ($f)(getarray(msa), dimension)
if dimension == 1
name_list = names(msa, 2)
N = length(name_list)
NamedArray(
result,
(
OrderedDict{String,Int}(
Utils._get_function_name(string($f)) => 1,
),
OrderedDict{String,Int}(name_list[i] => i for i = 1:N),
),
("Function", "Col"),
)
elseif dimension == 2
name_list = names(msa, 1)
N = length(name_list)
NamedArray(
result,
(
OrderedDict{String,Int}(name_list[i] => i for i = 1:N),
OrderedDict{String,Int}(
Utils._get_function_name(string($f)) => 1,
),
),
("Seq", "Function"),
)
else
throw(ArgumentError("Dimension must be 1 or 2."))
end
end
($f)(a::AbstractResidueMatrix, dimension::Int) =
($f)(namedmatrix(a), dimension)
end
end
return Expr(:block, definitions...)
end
@keep_names_dimension([gapfraction, residuefraction])
"""
Coverage of the sequences with respect of the number of positions on the MSA
"""
function coverage(msa::AbstractMatrix{Residue})
result = residuefraction(msa, 2)
if isa(result, NamedArray) && ndims(result) == 2
setnames!(result, ["coverage"], 2)
end
result
end
coverage(msa::AbstractAlignedObject) = coverage(namedmatrix(msa))
"""
Fraction of gaps per column/position on the MSA
"""
columngapfraction(msa::AbstractMatrix{Residue}) = gapfraction(msa, 1)
columngapfraction(msa::AbstractAlignedObject) = columngapfraction(namedmatrix(msa))
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 29676 | # import Base: length, getindex, setindex!, size, copy, deepcopy, empty!,
# convert, transpose, names
abstract type AbstractResidueMatrix <: AbstractMatrix{Residue} end
"""
MIToS MSA and aligned sequences (aligned objects) are subtypes of `AbstractMatrix{Residue}`,
because MSAs and sequences are stored as `Matrix` of `Residue`s.
"""
abstract type AbstractAlignedObject <: AbstractResidueMatrix end
"""
MSAs are stored as `Matrix{Residue}`. It's possible to use a
`NamedResidueMatrix{Array{Residue,2}}` as the most simple MSA with sequence
identifiers and column names.
"""
abstract type AbstractMultipleSequenceAlignment <: AbstractAlignedObject end
"""
A MIToS aligned sequence is an `AbstractMatrix{Residue}` with only 1 row/sequence.
"""
abstract type AbstractAlignedSequence <: AbstractAlignedObject end
"""
A MIToS (unaligned) sequence is an `AbstractMatrix{Residue}` with only 1 row/sequence.
"""
abstract type AbstractSequence <: AbstractResidueMatrix end
# Multiple Sequence Alignment
# ===========================
const NamedResidueMatrix{AT} =
NamedArray{Residue,2,AT,Tuple{OrderedDict{String,Int},OrderedDict{String,Int}}}
"""
This MSA type include a `NamedArray` wrapping a `Matrix` of `Residue`s. The use of
`NamedArray` allows to store sequence names and original column numbers as `String`s, and
fast indexing using them.
"""
mutable struct MultipleSequenceAlignment <: AbstractMultipleSequenceAlignment
matrix::NamedResidueMatrix{Array{Residue,2}}
function (::Type{MultipleSequenceAlignment})(
matrix::NamedResidueMatrix{Array{Residue,2}},
)
setdimnames!(matrix, ("Seq", "Col"))
new(matrix)
end
end
"""
This type represent an MSA, similar to `MultipleSequenceAlignment`, but It also stores
`Annotations`. This annotations are used to store residue coordinates (i.e. mapping
to UniProt residue numbers).
"""
mutable struct AnnotatedMultipleSequenceAlignment <: AbstractMultipleSequenceAlignment
matrix::NamedArray{
Residue,
2,
Array{Residue,2},
Tuple{OrderedDict{String,Int},OrderedDict{String,Int}},
}
annotations::Annotations
function (::Type{AnnotatedMultipleSequenceAlignment})(
matrix::NamedResidueMatrix{Array{Residue,2}},
annotations::Annotations,
)
setdimnames!(matrix, ("Seq", "Col"))
new(matrix, annotations)
end
end
# Helper constructor for NamedResidueMatrix{Array{Residue,2}}
function _namedresiduematrix(
matrix::Matrix{Residue},
seqnames::OrderedDict{String,Int},
colnames::OrderedDict{String,Int},
)::NamedResidueMatrix{Array{Residue,2}}
NamedArray(matrix, (seqnames, colnames), ("Seq", "Col"))
end
function _namedresiduematrix(matrix::Matrix{Residue}, seqnames, colnames)
_namedresiduematrix(
matrix,
OrderedDict{String,Int}(string(k) => i for (i, k) in enumerate(seqnames)),
OrderedDict{String,Int}(string(k) => i for (i, k) in enumerate(colnames)),
)
end
# Aligned Sequences
# -----------------
"""
An `AlignedSequence` wraps a `NamedResidueMatrix{Array{Residue,2}}` with only 1 row/sequence. The
`NamedArray` stores the sequence name and original column numbers as `String`s.
"""
mutable struct AlignedSequence <: AbstractAlignedSequence
matrix::NamedResidueMatrix{Array{Residue,2}}
function (::Type{AlignedSequence})(matrix::NamedResidueMatrix{Array{Residue,2}})
@assert size(matrix, 1) == 1 "There are more than one sequence."
setdimnames!(matrix, ("Seq", "Col"))
new(matrix)
end
end
"""
This type represent an aligned sequence, similar to `AlignedSequence`, but It also stores
its `Annotations`.
"""
mutable struct AnnotatedAlignedSequence <: AbstractAlignedSequence
matrix::NamedResidueMatrix{Array{Residue,2}}
annotations::Annotations
function (::Type{AnnotatedAlignedSequence})(
matrix::NamedResidueMatrix{Array{Residue,2}},
annotations::Annotations,
)
@assert size(matrix, 1) == 1 "There are more than one sequence."
setdimnames!(matrix, ("Seq", "Col"))
new(matrix, annotations)
end
end
# Unaligned Sequences
# -------------------
"""
An `AnnotationSequence` wraps a `NamedResidueMatrix{Array{Residue,2}}` with only 1
row/sequence and its `Annotations`. The `NamedArray` stores the sequence name and
original position numbers as `String`s.
"""
mutable struct AnnotatedSequence <: AbstractSequence
matrix::NamedResidueMatrix{Array{Residue,2}}
annotations::Annotations
function (::Type{AnnotatedSequence})(
matrix::NamedResidueMatrix{Array{Residue,2}},
annotations::Annotations,
)
@assert size(matrix, 1) == 1 "There should be only one sequence—i.e. one row."
if dimnames(matrix, 2) != "Pos"
setdimnames!(matrix, ("Seq", "Pos")) # Unaligned sequences have positions instead of columns
end
clean_matrix = adjustreference(matrix) # ensure that the sequence has no gaps
new(clean_matrix, annotations)
end
end
# Constructors
# ------------
# AnnotatedMultipleSequenceAlignment
function AnnotatedMultipleSequenceAlignment(msa::NamedResidueMatrix{Array{Residue,2}})
AnnotatedMultipleSequenceAlignment(msa, Annotations())
end
function AnnotatedMultipleSequenceAlignment(msa::Matrix{Residue})
AnnotatedMultipleSequenceAlignment(NamedArray(msa))
end
function AnnotatedMultipleSequenceAlignment(msa::AbstractMatrix{Residue})
AnnotatedMultipleSequenceAlignment(Matrix{Residue}(msa))
end
function AnnotatedMultipleSequenceAlignment(msa::MultipleSequenceAlignment)
AnnotatedMultipleSequenceAlignment(namedmatrix(msa), Annotations())
end
AnnotatedMultipleSequenceAlignment(msa::AnnotatedMultipleSequenceAlignment) = msa
# MultipleSequenceAlignment
function MultipleSequenceAlignment(msa::Matrix{Residue})
MultipleSequenceAlignment(NamedArray(msa))
end
function MultipleSequenceAlignment(msa::AbstractMatrix{Residue})
MultipleSequenceAlignment(Matrix{Residue}(msa))
end
function MultipleSequenceAlignment(msa::AnnotatedMultipleSequenceAlignment)
MultipleSequenceAlignment(namedmatrix(msa))
end
MultipleSequenceAlignment(msa::MultipleSequenceAlignment) = msa
# AnnotatedAlignedSequence
function AnnotatedAlignedSequence(seq::NamedResidueMatrix{Array{Residue,2}})
AnnotatedAlignedSequence(seq, Annotations())
end
function AnnotatedAlignedSequence(seq::Matrix{Residue})
AnnotatedAlignedSequence(NamedArray(seq))
end
function AnnotatedAlignedSequence(seq::AbstractMatrix{Residue})
AnnotatedAlignedSequence(Matrix{Residue}(seq))
end
function AnnotatedAlignedSequence(seq::AlignedSequence)
AnnotatedAlignedSequence(namedmatrix(seq), Annotations())
end
AnnotatedAlignedSequence(seq::AnnotatedAlignedSequence) = seq
# AlignedSequence
AlignedSequence(seq::Matrix{Residue}) = AlignedSequence(NamedArray(seq))
AlignedSequence(seq::AbstractMatrix{Residue}) = AlignedSequence(Matrix{Residue}(seq))
AlignedSequence(seq::AnnotatedAlignedSequence) = AlignedSequence(namedmatrix(seq))
AlignedSequence(seq::AlignedSequence) = seq
# Annotated Unaligned Sequence
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Constructors from strings or vectors
function _clean_sequence(seq::AbstractString)
seq = uppercase(seq) # to avoid converting lowercase to GAP
replace(seq, r"[^A-Z]" => "") # remove non-alphabetic characters
end
function AnnotatedSequence(
id::AbstractString,
seq::AbstractString,
annot::Annotations = Annotations(),
)
clean_seq = _clean_sequence(seq)
vector_res = convert(Vector{Residue}, clean_seq) # string -> vector
AnnotatedSequence(id, vector_res, annot)
end
# ⬇
function AnnotatedSequence(
id::AbstractString,
seq::AbstractVector{Residue},
annot::Annotations = Annotations(),
)
matrix = permutedims(seq) # vector -> matrix
named_matrix = NamedArray(
matrix,
(
OrderedDict{String,Int}(id => 1),
OrderedDict{String,Int}(string(i) => i for i = 1:length(matrix)),
),
("Seq", "Pos"),
)
AnnotatedSequence(named_matrix, annot)
end
# The default id is an empty string
AnnotatedSequence(seq::AbstractString, annot::Annotations = Annotations()) =
AnnotatedSequence("", seq, annot)
AnnotatedSequence(seq::AbstractVector{Residue}, annot::Annotations = Annotations()) =
AnnotatedSequence("", seq, annot)
# From matrices
function AnnotatedSequence(seq::AbstractMatrix{Residue}, annot::Annotations = Annotations())
AnnotatedSequence(NamedArray(seq), annot)
end
# Form aligned sequences
function AnnotatedSequence(seq::AlignedSequence)
AnnotatedSequence(namedmatrix(seq), Annotations())
end
function AnnotatedSequence(seq::AnnotatedAlignedSequence)
AnnotatedSequence(namedmatrix(seq), deepcopy(seq.annotations))
end
# no-op
AnnotatedSequence(seq::AnnotatedSequence) = seq
# AnnotatedAlignedObject
# ----------------------
const AnnotatedAlignedObject =
Union{AnnotatedMultipleSequenceAlignment,AnnotatedAlignedSequence}
const UnannotatedAlignedObject = Union{MultipleSequenceAlignment,AlignedSequence}
# Matrices
# --------
const MSAMatrix = Union{Matrix{Residue},NamedResidueMatrix{Array{Residue,2}}}
# Getters
# -------
"""
The `annotations` function returns the `Annotations` of an annotated MSA or aligned
sequence. If the object is not annotated, it returns an empty `Annotations` object.
"""
@inline annotations(msa::AnnotatedMultipleSequenceAlignment) = msa.annotations
@inline annotations(seq::AnnotatedAlignedSequence) = seq.annotations
@inline annotations(seq::AnnotatedSequence) = seq.annotations
@inline annotations(x::UnannotatedAlignedObject) = Annotations()
@inline annotations(x::MSAMatrix) = Annotations()
"""
The `namedmatrix` function returns the `NamedResidueMatrix{Array{Residue,2}}` stored in an
MSA or aligned sequence.
"""
@inline function namedmatrix(x::AbstractResidueMatrix)
x.matrix::NamedResidueMatrix{Array{Residue,2}}
end
NamedArrays.dimnames(x::AbstractResidueMatrix) = dimnames(namedmatrix(x))
# Sequence equality
# -----------------
# By default, the sequences objects use the AbstractArray implementations of the equality
# operators. This means that only the matrices are compared, i.e. the sequence residues.
# Therefore, we define the following methods to compare the whole object, including the
# sequence identifier. This doesn't compare the annotations, as they are not part of the
# sequence itself.
function Base.:(==)(
seq_a::Union{AbstractSequence,AbstractAlignedSequence},
seq_b::Union{AbstractSequence,AbstractAlignedSequence},
)
sequence_id(seq_a) == sequence_id(seq_b) && namedmatrix(seq_a) == namedmatrix(seq_b)
end
function Base.isequal(
seq_a::Union{AbstractSequence,AbstractAlignedSequence},
seq_b::Union{AbstractSequence,AbstractAlignedSequence},
)
isequal(sequence_id(seq_a), sequence_id(seq_b)) &&
isequal(namedmatrix(seq_a), namedmatrix(seq_b))
end
function Base.hash(seq::Union{AbstractSequence,AbstractAlignedSequence}, h::UInt)
h = hash(sequence_id(seq), h)
hash(namedmatrix(seq), h)
end
# Convert
# -------
function Base.convert(
::Type{MultipleSequenceAlignment},
msa::AnnotatedMultipleSequenceAlignment,
)
Base.depwarn(
"`convert(::Type{MultipleSequenceAlignment}, msa)` has been deprecated. Use `MultipleSequenceAlignment(msa)`",
:convert,
force = true,
)
MultipleSequenceAlignment(namedmatrix(msa))
end
function Base.convert(::Type{AlignedSequence}, seq::AnnotatedAlignedSequence)
Base.depwarn(
"`convert(::Type{AlignedSequence}, seq)` has been deprecated. Use `AlignedSequence(seq)`",
:convert,
force = true,
)
AlignedSequence(namedmatrix(seq))
end
function Base.convert(
::Type{AnnotatedMultipleSequenceAlignment},
msa::MultipleSequenceAlignment,
)
Base.depwarn(
"`convert(::Type{AnnotatedMultipleSequenceAlignment}, msa)` has been deprecated. Use `AnnotatedMultipleSequenceAlignment(msa)`",
:convert,
force = true,
)
AnnotatedMultipleSequenceAlignment(namedmatrix(msa), Annotations())
end
function Base.convert(::Type{AnnotatedAlignedSequence}, seq::AlignedSequence)
Base.depwarn(
"`convert(::Type{AnnotatedAlignedSequence}, seq)` has been deprecated. Use `AnnotatedAlignedSequence(seq)`",
:convert,
force = true,
)
AnnotatedAlignedSequence(namedmatrix(seq), Annotations())
end
# AbstractArray Interface
# -----------------------
for f in (:size, :length)
@eval Base.$(f)(x::AbstractResidueMatrix) = $(f)(namedmatrix(x))
end
# Show
# ----
for T in (
:(AnnotatedSequence),
:(AlignedSequence),
:(AnnotatedAlignedSequence),
:(MultipleSequenceAlignment),
:(AnnotatedMultipleSequenceAlignment),
)
@eval begin
function Base.show(io::IO, ::MIME"text/plain", x::$(T))
type_name = split(string($T), '.')[end]
if isa(
x,
Union{
AnnotatedMultipleSequenceAlignment,
AnnotatedAlignedSequence,
AnnotatedSequence,
},
)
print(io, type_name, " with ", length(annotations(x)), " annotations : ")
else
print(io, type_name, " : ")
end
show(io, MIME"text/plain"(), namedmatrix(x))
end
end
end
# Transpose (permutedims)
# -----------------------
function Base.transpose(x::AbstractAlignedObject)
Base.depwarn(
"`transpose(x::AbstractAlignedObject)` has been deprecated, use `permutedims(x)` instead.",
:transpose,
force = true,
)
permutedims(namedmatrix(x))
end
Base.permutedims(x::AbstractResidueMatrix, args...) = permutedims(namedmatrix(x), args...)
# Selection without Mappings
# --------------------------
"""
`getresidues` allows you to access the residues stored inside an MSA or aligned sequence
as a `Matrix{Residue}` without annotations nor column/row names.
"""
getresidues(x::Matrix{Residue}) = x
getresidues(x::NamedResidueMatrix{Array{Residue,2}}) = getarray(x)
getresidues(x::AbstractResidueMatrix) = getresidues(namedmatrix(x))
"""
`nsequences` returns the number of sequences on the MSA.
"""
nsequences(x::AbstractMatrix{Residue}) = size(x, 1)
"""
`ncolumns` returns the number of MSA columns or positions.
"""
ncolumns(x::AbstractMatrix{Residue}) = size(x, 2)
"""
`getresiduesequences` returns a `Vector{Vector{Residue}}` with all the MSA sequences without
annotations nor column/sequence names.
"""
function getresiduesequences(msa::Matrix{Residue})
nseq = nsequences(msa)
tmsa = permutedims(msa, [2, 1])
sequences = Array{Vector{Residue}}(undef, nseq)
for i = 1:nseq
@inbounds sequences[i] = tmsa[:, i]
end
sequences
end
getresiduesequences(x::NamedResidueMatrix{Array{Residue,2}}) =
getresiduesequences(getresidues(x))
getresiduesequences(x::AbstractResidueMatrix) = getresiduesequences(getresidues(x))
# Select sequence
# ---------------
# Gives you the annotations of the Sequence
function getsequence(data::Annotations, id::String)
GS = Dict{Tuple{String,String},String}()
GR = Dict{Tuple{String,String},String}()
if length(data.sequences) > 0
for (key, value) in data.sequences
if key[1] == id
GS[key] = value
end
end
sizehint!(GS, length(GS))
end
if length(data.residues) > 0
for (key, value) in data.residues
if key[1] == id
GR[key] = value
end
end
sizehint!(GR, length(GR))
end
Annotations(data.file, GS, data.columns, GR)
end
@doc """
`getsequence` takes an MSA and a sequence number or identifier and returns an aligned
sequence object. If the MSA is an `AnnotatedMultipleSequenceAlignment`, it returns an
`AnnotatedAlignedSequence` with the sequence annotations. From a
`MultipleSequenceAlignment`, It returns an `AlignedSequence` object. If an `Annotations`
object and a sequence identifier are used, this function returns the annotations related
to the sequence.
""" getsequence
getsequence(msa::AbstractMatrix{Residue}, i::Int) = msa[i:i, :]
getsequence(msa::NamedResidueMatrix{Array{Residue,2}}, i::Int) = msa[i:i, :]
getsequence(msa::NamedResidueMatrix{Array{Residue,2}}, id::String) = msa[String[id], :]
function getsequence(msa::AnnotatedMultipleSequenceAlignment, i::Int)
seq = namedmatrix(msa)[i:i, :]
annot = getsequence(annotations(msa), names(seq, 1)[1])
AnnotatedAlignedSequence(seq, annot)
end
function getsequence(msa::AnnotatedMultipleSequenceAlignment, id::String)
seq = namedmatrix(msa)[String[id], :]
annot = getsequence(annotations(msa), id)
AnnotatedAlignedSequence(seq, annot)
end
function getsequence(msa::MultipleSequenceAlignment, seq::String)
AlignedSequence(getsequence(namedmatrix(msa), seq))
end
function getsequence(msa::MultipleSequenceAlignment, seq::Int)
AlignedSequence(getsequence(namedmatrix(msa), seq))
end
# Names
# -----
"""
`sequencenames(msa)`
It returns a `Vector{String}` with the sequence names/identifiers.
"""
function sequencenames(x::NamedResidueMatrix{AT})::Vector{String} where {AT<:AbstractArray}
names(x, 1)
end
sequencenames(x::AbstractResidueMatrix)::Vector{String} = sequencenames(namedmatrix(x))
sequencenames(msa::AbstractMatrix{Residue})::Vector{String} = map(string, 1:size(msa, 1))
"""
`columnnames(msa)`
It returns a `Vector{String}` with the sequence names/identifiers. If the `msa` is a
`Matrix{Residue}` this function returns the actual column numbers as strings. Otherwise it
returns the column number of the original MSA through the wrapped `NamedArray` column names.
"""
function columnnames(x::NamedResidueMatrix{AT})::Vector{String} where {AT}
names(x, 2)
end
columnnames(x::AbstractResidueMatrix)::Vector{String} = columnnames(namedmatrix(x))
columnnames(msa::AbstractMatrix{Residue})::Vector{String} = map(string, 1:size(msa, 2))
"""
sequence_id(seq::Union{AbstractSequence,AbstractAlignedSequence})
It returns the sequence identifier of a sequence object.
"""
sequence_id(seq::Union{AbstractSequence,AbstractAlignedSequence}) = only(sequencenames(seq))
# Name Iterators
# --------------
# These function relies on the internal implementation of NamedArrays
# to return the key iterator of the OrderedDict containing the row or column names.
# That should help reduce allocations in places where a vector of names is not needed.
"""
`sequencename_iterator(msa)`
It returns an iterator that returns the sequence names/identifiers of the `msa`.
"""
function sequencename_iterator(x::NamedResidueMatrix{AT}) where {AT}
keys(x.dicts[1])::Base.KeySet{String,OrderedDict{String,Int64}}
end
sequencename_iterator(x::AbstractResidueMatrix) = sequencename_iterator(namedmatrix(x))
sequencename_iterator(msa::AbstractMatrix{Residue}) = (string(i) for i = 1:size(msa, 1))
"""
`columnname_iterator(msa)`
It returns an iterator that returns the column names of the `msa`. If the `msa` is a
`Matrix{Residue}` this function returns the actual column numbers as strings. Otherwise it
returns the column number of the original MSA through the wrapped `NamedArray` column names.
"""
function columnname_iterator(x::NamedResidueMatrix{AT}) where {AT}
keys(x.dicts[2])
end
columnname_iterator(x::AbstractResidueMatrix) = columnname_iterator(namedmatrix(x))
columnname_iterator(msa::AbstractMatrix{Residue}) = (string(i) for i = 1:size(msa, 2))
# Copy, deepcopy
# --------------
for f in (:copy, :deepcopy)
@eval begin
function Base.$(f)(msa::AnnotatedMultipleSequenceAlignment)
AnnotatedMultipleSequenceAlignment(
$(f)(namedmatrix(msa)),
$(f)(annotations(msa)),
)
end
function Base.$(f)(msa::MultipleSequenceAlignment)
MultipleSequenceAlignment($(f)(namedmatrix(msa)))
end
function Base.$(f)(seq::AnnotatedAlignedSequence)
AnnotatedAlignedSequence($(f)(seq.matrix), $(f)(seq.annotations))
end
function Base.$(f)(seq::AnnotatedSequence)
AnnotatedSequence($(f)(seq.matrix), $(f)(seq.annotations))
end
Base.$(f)(seq::AlignedSequence) = AlignedSequence($(f)(seq.matrix))
end
end
# Get annotations
# ---------------
# MSA
for getter in (:getannotcolumn, :getannotfile, :getannotresidue, :getannotsequence)
@eval $(getter)(x::AnnotatedMultipleSequenceAlignment, args...) =
$(getter)(annotations(x), args...)
end
# Sequence
function _check_feature(
seq::Union{AnnotatedAlignedSequence,AnnotatedSequence},
feature::String,
)
if feature == sequence_id(seq)
annot = annotations(seq)
sequence_features = last.(keys(annot.sequences))
residue_features = last.(keys(annot.residues))
if feature ∉ sequence_features && feature ∉ residue_features
sequence_features_str =
isempty(sequence_features) ? "" :
"Possible sequence features: " * join(sequence_features, ", ", " and ")
residue_features_str =
isempty(residue_features) ? "" :
"Possible residue features: " * join(residue_features, ", ", " and ")
@warn """The second argument should be a feature name, not the sequence identifier: $(feature).
$sequence_features_str
$residue_features_str"""
end
end
feature
end
for getter in (:getannotcolumn, :getannotfile)
@eval $(getter)(x::Union{AnnotatedSequence,AnnotatedAlignedSequence}, args...) =
$(getter)(annotations(x), args...)
end
for getter in (:getannotresidue, :getannotsequence)
@eval begin
function $(getter)(x::Union{AnnotatedSequence,AnnotatedAlignedSequence})
return $(getter)(annotations(x)) # get all the annotations
end
function $(getter)(
x::Union{AnnotatedSequence,AnnotatedAlignedSequence},
feature::String,
)
return $(getter)(annotations(x), sequence_id(x), _check_feature(x, feature))
end
function $(getter)(
x::Union{AnnotatedSequence,AnnotatedAlignedSequence},
feature::String,
default::String,
)
return $(getter)(
annotations(x),
sequence_id(x),
_check_feature(x, feature),
default,
)
end
end
end
# Set annotations
# ---------------
for setter in (
:setannotcolumn!,
:setannotfile!,
:annotate_modification!,
:delete_annotated_modifications!,
:printmodifications,
)
@eval $(setter)(
x::Union{
AnnotatedMultipleSequenceAlignment,
AnnotatedAlignedSequence,
AnnotatedSequence,
},
args...,
) = $(setter)(annotations(x), args...)
end
for setter in (:setannotresidue!, :setannotsequence!)
@eval $(setter)(x::AnnotatedMultipleSequenceAlignment, args...) =
$(setter)(annotations(x), args...)
end
for setter in (:setannotresidue!, :setannotsequence!)
@eval begin
function $(setter)(
x::Union{AnnotatedAlignedSequence,AnnotatedSequence},
feature::String,
annotation::String,
)
return $(setter)(
annotations(x),
sequence_id(x),
_check_feature(x, feature),
annotation,
)
end
end
end
# To be used on AbstractMultipleSequenceAlignment methods
@inline function annotate_modification!(msa::MultipleSequenceAlignment, str::String)
# It's generally used in a boolean context: annotate && annotate_modification!(...
false
end
# Mapping annotations
# ===================
"""
Converts a string of mappings into a vector of `Int`s
```jldoctest
julia> using MIToS.MSA
julia> MSA._str2int_mapping(",,2,,4,5")
6-element Vector{Int64}:
0
0
2
0
4
5
```
"""
function _str2int_mapping(mapping::String)
values = split(mapping, ',')
len = length(values)
intmap = Array{Int}(undef, len)
@inbounds for i = 1:len
value = values[i]
intmap[i] = value == "" ? 0 : parse(Int, value)
end
intmap
end
"""
It returns a `Vector{Int}` with the original column number of each column on the actual MSA.
The mapping is annotated in the `ColMap` file annotation of an
`AnnotatedMultipleSequenceAlignment` or in the column names of an `NamedArray` or
`MultipleSequenceAlignment`.
NOTE: When the MSA results from vertically concatenating MSAs using `vcat`,
the column map annotations from the constituent MSAs (such as `1_ColMap`, `2_ColMap`, etc.)
are not returned. Instead, the column numbers referenced in the column names are provided.
To access the original annotations, utilize the `getannotfile` function.
"""
function getcolumnmapping(msa::AnnotatedMultipleSequenceAlignment)
annot = getannotfile(msa)
if haskey(annot, "ColMap")
return _str2int_mapping(annot["ColMap"])
else
if haskey(annot, "1_ColMap")
@warn """
The MSA is the result of a vertical concatenation of MSAs. The column mapping
annotations from the sub-MSAs are not returned. Instead, the column numbers
referenced in the column names are provided. To access the original
annotations, utilize the getannotfile function. For example:
`getannotfile(msa, "1_ColMap")`
"""
end
return getcolumnmapping(namedmatrix(msa))
end
end
function getcolumnmapping(msa::NamedResidueMatrix{AT}) where {AT<:AbstractMatrix}
# replace to clean names from hcat
Int[parse(Int, replace(col, r"^[0-9]+_" => "")) for col in names(msa, 2)]
end
getcolumnmapping(msa::MultipleSequenceAlignment) = getcolumnmapping(namedmatrix(msa))
"""
It returns the sequence coordinates as a `Vector{Int}` for an MSA sequence. That vector has
one element for each MSA column. If the number if `0` in the mapping, there is a gap in
that column for that sequence.
"""
function getsequencemapping(msa::AnnotatedMultipleSequenceAlignment, seq_id::String)
_str2int_mapping(getannotsequence(msa, seq_id, "SeqMap"))
end
function getsequencemapping(msa::AnnotatedMultipleSequenceAlignment, seq_num::Int)
getsequencemapping(msa, sequencenames(msa)[seq_num])
end
function getsequencemapping(seq::Union{AnnotatedAlignedSequence,AnnotatedSequence})
_str2int_mapping(getannotsequence(seq, "SeqMap"))
end
# Sequences as strings
# --------------------
"""
```
stringsequence(seq)
stringsequence(msa, i::Int)
stringsequence(msa, id::String)
```
It returns the selected sequence as a `String`.
"""
stringsequence(msa::AbstractMatrix{Residue}, i) = String(vec(msa[i, :]))
function stringsequence(msa::AbstractMultipleSequenceAlignment, i)
stringsequence(namedmatrix(msa), i)
end
function stringsequence(seq::AbstractMatrix{Residue})
@assert size(seq, 1) == 1 "There are more than one sequence/row."
String(vec(seq))
end
stringsequence(seq::Union{AbstractSequence,AbstractAlignedSequence}) =
stringsequence(namedmatrix(seq))
# Rename sequences
# ----------------
const RENAME_SEQUENCES_DOC = md"""
Rename the sequences of an MSA given a vector of new names, a dictionary mapping old names
to new names, or one or more pairs going from old to new names. If the `msa` is an
`AnnotatedMultipleSequenceAlignment`, the annotations are also updated.
"""
"""
rename_sequences!(msa, newnames::Vector{T}) where {T<:AbstractString}
rename_sequences!(msa, old2new::AbstractDict)
rename_sequences!(msa, old2new::Pair...)
$RENAME_SEQUENCES_DOC The function modifies the `msa` in place and returns it.
"""
function rename_sequences!(
msa::NamedResidueMatrix{AT},
newnames::Vector{T},
) where {AT,T<:AbstractString}
@assert length(newnames) == size(msa, 1) "The number of new names must match the number of sequences."
setnames!(msa, newnames, 1)
msa
end
function rename_sequences!(
msa::MultipleSequenceAlignment,
newnames::Vector{T},
) where {T<:AbstractString}
rename_sequences!(namedmatrix(msa), newnames)
msa
end
function rename_sequences!(
msa::AnnotatedMultipleSequenceAlignment,
newnames::Vector{T},
) where {T<:AbstractString}
name_mapping = Dict{String,String}(
old => new for
(old, new) in zip(sequencename_iterator(msa), newnames) if old != new
)
new_annotations = _rename_sequences(annotations(msa), name_mapping)
rename_sequences!(namedmatrix(msa), newnames)
msa.annotations = new_annotations
msa
end
"""
rename_sequences(msa, newnames::Vector{T}) where {T<:AbstractString}
rename_sequences(msa, old2new::AbstractDict)
rename_sequences(msa, old2new::Pair...)
$RENAME_SEQUENCES_DOC The function returns a new MSA with the sequences renamed without
modifying the original MSA.
"""
rename_sequences(msa, newnames) = rename_sequences!(deepcopy(msa), newnames)
# Rename a single sequence or a set of sequences
function _newnames(msa, old2new::AbstractDict)
String[get(old2new, name, name) for name in sequencename_iterator(msa)]
end
_newnames(msa, old2new::Pair...) = _newnames(msa, Dict(old2new))
function rename_sequences!(msa, old2new::AbstractDict)
rename_sequences!(msa, _newnames(msa, old2new))
end
function rename_sequences!(msa, old2new::Pair...)
rename_sequences!(msa, _newnames(msa, old2new...))
end
rename_sequences(msa, old2new::Pair...) = rename_sequences(msa, _newnames(msa, old2new...))
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 4273 | struct PIR <: MSAFormat end
# PIR Parser
# ==========
# Description of PIR/NBRF format in :
# - https://salilab.org/modeller/9v7/manual/node445.html
# - http://iubio.bio.indiana.edu/soft/molbio/readseq/classic/src/Formats
# - http://www.bioinformatics.nl/tools/crab_pir.html
# - http://emboss.sourceforge.net/docs/themes/seqformats/NbrfFormat.html
# They could be annotations/comments after the sequence, we are ignoring that at the moment.
function _pre_readpir(io::Union{IO,AbstractString})
IDS = String[]
SEQS = String[]
GS = Dict{Tuple{String,String},String}()
# Sequence types from http://iubio.bio.indiana.edu/soft/molbio/readseq/classic/src/Formats
nucleic_types = Set([
"DL", # DNA, linear
"DC", # DNA, circular
"RL", # RNA, linear
"RC", # RNA, circular
"N1", # functional RNA, other than tRNA
"N3",
]) # tRNA
nonres = r"[^A-Za-z-\.]+" # large negated character class becuase seqs are free text
finished = false
line_number = 0
seq_number = 0
for line::String in lineiterator(io)
line_number += 1
if startswith(line, '>')
line_number = 1
seq_number += 1
finished = false
m = match(r"^>([A-Z][A-Z0-9]);(.+)$", line) # e.g. >P1;5fd1
if m !== nothing
seq_type = m[1] === nothing ? "" : m[1]
seq_id = m[2] === nothing ? "" : rstrip(m[2]::SubString)
push!(IDS, seq_id)
push!(GS, (seq_id, "Type") => seq_type)
if seq_type in nucleic_types
@warn("Type $seq_type indicates that $seq_id is a nucleic acid.")
end
else
throw(ErrorException("Identifier doesn't match the PIR format: $line"))
end
elseif line_number == 2 && !isempty(IDS)
push!(GS, (IDS[seq_number], "Title") => line)
elseif line_number == 3
if endswith(line, '*')
finished = true
end
push!(SEQS, replace(line, nonres => ""))
elseif !finished && length(SEQS) == seq_number && seq_number != 0
if endswith(line, '*')
finished = true
end
@inbounds SEQS[seq_number] = SEQS[seq_number] * replace(line, nonres => "")
end
end
(IDS, SEQS, GS)
end
function _load_sequences(
io::Union{IO,AbstractString},
format::Type{PIR};
create_annotations::Bool = false,
)
IDS, SEQS, GS = _pre_readpir(io)
annot = Annotations()
if create_annotations
annot.sequences = GS
end
return IDS, SEQS, annot
end
# Print Pfam
# ==========
function _print_pir_seq(io::IO, seq_type, seq_id, seq_title, seq)
println(io, ">", seq_type, ';', seq_id)
println(io, seq_title)
char_counter = 0
for char in seq
print(io, char)
char_counter += 1
if char_counter % 80 == 0
println(io)
end
end
println(io, '*')
end
function _get_pir_annotations(sequence_annotations, seq_id::String)
if haskey(sequence_annotations, (seq_id, "Type"))
seq_type = sequence_annotations[(seq_id, "Type")]
else
@warn("There is not sequence Type annotation for $seq_id, using XX (Unknown).")
seq_type = "XX"
end
if haskey(sequence_annotations, (seq_id, "Title"))
seq_title = sequence_annotations[(seq_id, "Title")]
else
@warn("There is not sequence Title annotation for $seq_id.")
seq_title = ""
end
seq_type, seq_title
end
function Utils.print_file(
io::IO,
msa::AnnotatedMultipleSequenceAlignment,
format::Type{PIR},
)
sequence_annotations = getannotsequence(msa)
seqnames = sequencenames(msa)
for i = 1:nsequences(msa)
seq_id = seqnames[i]
seq_type, seq_title = _get_pir_annotations(sequence_annotations, seq_id)
seq = stringsequence(msa, i)
_print_pir_seq(io, seq_type, seq_id, seq_title, seq)
end
end
function Utils.print_file(io::IO, msa::AbstractMatrix{Residue}, format::Type{PIR})
seqnames = sequencenames(msa)
for i = 1:nsequences(msa)
_print_pir_seq(io, "XX", seqnames[i], "", stringsequence(msa, i))
end
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 2161 | # Initialize an empty PairwiseListMatrix (PLM) for a pairwise measure in column or
# sequence pairs. These functions take care of the labels.
"""
Initialize an empty `PairwiseListMatrix` for a pairwise measure in column pairs. It uses the
column mapping (column number in the input MSA file) if it’s available, otherwise it uses
the actual column numbers. You can use the positional argument to indicate the number
`Type` (default: `Float64`), if the `PairwiseListMatrix` should store the diagonal values
on the list (default: `false`) and a default value for the diagonal (default: `NaN`).
"""
function sequencepairsmatrix(
msa::AbstractMatrix{Residue},
::Type{T},
::Type{Val{diagonal}},
diagonalvalue::T,
) where {T,diagonal}
plm = PairwiseListMatrix(T, nsequences(msa), diagonal, diagonalvalue)
nplm = setlabels(plm, sequencenames(msa))
setdimnames!(nplm, ["Seq1", "Seq2"])
nplm::NamedArray{
T,
2,
PairwiseListMatrix{T,diagonal,Vector{T}},
NTuple{2,OrderedDict{String,Int}},
}
end
function sequencepairsmatrix(msa::AbstractMatrix{Residue})
sequencepairsmatrix(msa, Float64, Val{false}, NaN)
end
"""
Initialize an empty `PairwiseListMatrix` for a pairwise measure in sequence pairs. It uses
the sequence names if they are available, otherwise it uses the actual sequence numbers.
You can use the positional argument to indicate the number `Type` (default: `Float64`),
if the `PairwiseListMatrix` should store the diagonal values on the list (default: `false`)
and a default value for the diagonal (default: `NaN`).
"""
function columnpairsmatrix(
msa::AbstractMatrix{Residue},
::Type{T},
::Type{Val{diagonal}},
diagonalvalue::T,
) where {T,diagonal}
plm = PairwiseListMatrix(T, ncolumns(msa), diagonal, diagonalvalue)
nplm = setlabels(plm, columnnames(msa))
setdimnames!(nplm, ["Col1", "Col2"])
nplm::NamedArray{
T,
2,
PairwiseListMatrix{T,diagonal,Vector{T}},
NTuple{2,OrderedDict{String,Int}},
}
end
function columnpairsmatrix(msa::AbstractMatrix{Residue})
columnpairsmatrix(msa, Float64, Val{false}, NaN)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 591 | const _residue_labels = map(string, reverse!(res"ARNDCQEGHILKMFPSTWYV-"))
@recipe function plot(msa::AbstractMultipleSequenceAlignment)
seriestype --> :heatmap
yflip --> true
grid --> false
foreground_color_border --> nothing
foreground_color_axis --> nothing
linewidth --> 0
zdiscrete_values --> _residue_labels
nseq = nsequences(msa)
names = sequencenames(msa)
if nseq > 20
step = div(nseq, 20)
yticks --> (1:step:nseq, names)
html_output_format := :png
end
1:ncolumns(msa), names, map(string, getresidues(msa))
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 574 | struct Raw <: MSAFormat end
# Raw Parser
# ==========
function _load_sequences(
io::Union{IO,AbstractString},
format::Type{Raw};
create_annotations::Bool = false,
)
SEQS = String[]
IDS = String[]
for (i, line::String) in enumerate(lineiterator(io))
push!(SEQS, line)
push!(IDS, string(i))
end
return IDS, SEQS, Annotations()
end
# Print Raw
# =========
function Utils.print_file(io::IO, msa::AbstractMatrix{Residue}, format::Type{Raw})
for i = 1:nsequences(msa)
println(io, stringsequence(msa, i))
end
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 9153 | # Residues
# ========
if Int === Int64
primitive type Residue 64 end
else
primitive type Residue 32 end
end
@doc """
Most of the **MIToS** design is created around the `Residue` bitstype. It has
representations for the 20 natural amino acids, a value representing insertions and
deletions (`GAP`, `'-'`) and one representing unknown, ambiguous and non standard residues
(`XAA`, `'X'`).
Each `Residue` is encoded as an integer number, with the same bit representation and size
than a `Int`. This allows fast indexing operation of probability or frequency matrices.
**Residue creation and conversion**
Creation and conversion of `Residue`s should be treated carefully. `Residue` is encoded
as a 32 or 64 bits type similar to `Int`, to get fast indexing using `Int(x::Residue)`.
`Int` simply calls `reinterpret` without checking if the residue is valid.
Valid residues have integer values in the closed interval [1,22]. `convert` from `Int` and
`Char` always returns valid residues, however it's possible to find invalid residues
(they are shown using the character `'�'`) after the creation of uninitialized `Residue`
arrays (i.e. using `Array`). You can use `zeros`, `ones` or `rand` to get initialized
`Residue` arrays with valid residues.
Conversions to and from `Char`s changes the bit representation and allows the use of the
usual character representation of residues and amino acids. This conversions are used in IO
operations and always return valid residues. In conversions from `Char`, lowercase letters,
`'*'`, `'-'` and `'.'` are translated to `GAP`, letters representing the 20 natural amino
(ARNDCQEGHILKMFPSTWYV) acids are translated to their corresponding `Residue` and any other
character is translated to `XAA`. Since lowercase letters and dots are translated to gaps,
Pfam MSA insert columns are converted to columns full of gaps.
```jldoctest
julia> using MIToS.MSA
julia> alanine = Residue('A')
A
julia> Char(alanine)
'A': ASCII/Unicode U+0041 (category Lu: Letter, uppercase)
julia> for residue in res"ARNDCQEGHILKMFPSTWYV-X"
println(residue, " ", Int(residue))
end
A 1
R 2
N 3
D 4
C 5
Q 6
E 7
G 8
H 9
I 10
L 11
K 12
M 13
F 14
P 15
S 16
T 17
W 18
Y 19
V 20
- 21
X 22
```
""" Residue
# Conversion from/to integers
# ---------------------------
#
# This conversions are used for indexing, comparison and operations
"""
It takes an `Int` and returns the `Int` value used to represent a valid `Residue`.
Invalid residues are encoded as the integer 23.
"""
@inline _valid_residue_integer(x::Int) = ifelse(1 <= x <= 22, x, 22)
# XAA
Base.convert(::Type{Residue}, x::Int) = reinterpret(Residue, _valid_residue_integer(x))
# Conversion to `Int` doesn’t check if the residue is valid
@inline Base.convert(::Type{Int}, x::Residue) = reinterpret(Int, x)
Residue(i::Int) = convert(Residue, i)
Base.Int(res::Residue) = convert(Int, res)
# ndims
# -----
Base.ndims(r::Residue) = 0
Base.ndims(::Type{Residue}) = 0
# Scalar
# ------
Base.broadcastable(x::Residue) = Ref(x)
# Gaps
# ----
"""
`GAP` is the `Residue` representation on MIToS for gaps (`'-'`, insertions and
deletions). Lowercase residue characters, dots and `'*'` are encoded as `GAP` in conversion
from `String`s and `Char`s. This `Residue` constant is encoded as `Residue(21)`.
"""
const GAP = Residue(21) # - .
"""
`XAA` is the `Residue` representation for unknown, ambiguous and non standard residues.
This `Residue` constant is encoded as `Residue(22)`.
"""
const XAA = Residue(22) # X
# Check for valid residues
# ------------------------
"""
`isvalid(res::Residue)`
It returns `true` if the encoded integer is in the closed interval [1,22].
"""
Base.isvalid(::Type{Residue}, res::Residue) = 1 <= reinterpret(Int, res) <= 22
Base.isvalid(res::Residue) = isvalid(Residue, res)
# Type boundaries
# ---------------
Base.typemin(::Type{Residue}) = Residue(1)
Base.typemax(::Type{Residue}) = Residue(22)
# zeros and ones
# --------------
Base.zero(::Type{Residue}) = GAP
Base.one(::Type{Residue}) = XAA
# Conversion from/to Char/Uint8
# -----------------------------
#
# Conversions for input and output.
const _to_char = Char[
'A',
'R',
'N',
'D',
'C',
'Q',
'E',
'G',
'H',
'I',
'L',
'K',
'M',
'F',
'P',
'S',
'T',
'W',
'Y',
'V',
'-',
'X',
]
function Base.convert(::Type{Char}, res::Residue)
@inbounds char = _to_char[_valid_residue_integer(Int(res))]
char
end
"""
'z' is the maximum between 'A':'Z', 'a':'z', '.', '-' and '*'.
'z' is 'GAP' but the next character to 'z' is '{', i.e. `XAA`.
"""
const _max_char = Int('z') + 1
const _to_residue = fill(XAA, _max_char)
# Residues
for index = 1:22
_to_residue[Int(_to_char[index])] = Residue(index)
end
# A lowercase Char is translated to GAP
for char = 'a':'z'
_to_residue[Int(char)] = GAP
end
_to_residue[Int('.')] = GAP # Gap in insert columns
_to_residue[Int('-')] = GAP # Usual GAP character
_to_residue[Int('*')] = GAP # Usual representation of a translated stop codon
@inline Base.@pure function Base.convert(::Type{Residue}, char::Char)::Residue
@inbounds if char < '{'
_to_residue[Int(char)]
else
XAA
end
end
Base.Char(res::Residue) = convert(Char, res)
Residue(char::Char) = convert(Residue, char)
# Bits
# ----
Base.bitstring(res::Residue) = bitstring(reinterpret(Int, res))
# Show
# ----
# Invalid residues are shown with the '�' character
function _write(io::IO, res::Residue)
if isvalid(res)
@inbounds char = _to_char[Int(res)]
write(io, char)
else
write(io, '�')
end
nothing
end
Base.show(io::IO, res::Residue) = _write(io, res)
# Print
# -----
# Invalid residues are printed with the 'X' character
function Base.print(io::IO, res::Residue)
write(io, Char(res))
nothing
end
# Conversion from/to String
# ------------------------------
#
# They are useful for IO and creation of Vector{Residue}
Base.convert(::Type{Vector{Residue}}, str::AbstractString) = Residue[char for char in str]
function Base.convert(::Type{String}, seq::Vector{Residue})
# Buffer length can be length(seq) since Char(res) is always ASCII
buffer = IOBuffer(Array{UInt8}(undef, length(seq)), read = true, write = true)
# To start at the beginning of the buffer:
truncate(buffer, 0)
for res in seq
write(buffer, Char(res))
end
String(take!(buffer))
end
Base.String(seq::Vector{Residue}) = convert(String, seq)
function _get_msa_size(sequences::Array{String,1})
nseq = length(sequences)
if nseq == 0
throw(ErrorException("There are not sequences."))
end
nres = length(sequences[1])
nseq, nres
end
function _convert_to_matrix_residues(sequences::Array{String,1}, size::Tuple{Int,Int})
nseq, nres = size
aln = Array{Residue}(undef, nseq, nres)
@inbounds for (i, str) in enumerate(sequences)
for (j, char) in enumerate(str)
aln[CartesianIndex(i, j)] = Residue(char)
end
end
aln
end
# For convert a MSA stored as Vector{String} to Matrix{Residue}
# This checks that all the sequences have the same length
function Base.convert(::Type{Matrix{Residue}}, sequences::Array{String,1})
nseq, nres = _get_msa_size(sequences)
# throw() can be used with @threads : https://github.com/JuliaLang/julia/issues/17532
for seq in sequences
if length(seq) != nres
throw(
ErrorException(
string(
"There is an aligned sequence with different number of columns",
"[ ",
length(seq),
" != ",
nres,
" ]: ",
String(seq),
),
),
)
end
end
_convert_to_matrix_residues(sequences, (nseq, nres))
end
# Non-Standard String Literal
# ---------------------------
"""
The MIToS macro `@res_str` takes a string and returns a `Vector` of `Residues` (sequence).
```jldoctest
julia> using MIToS.MSA
julia> res"MIToS"
5-element Vector{Residue}:
M
I
T
-
S
```
"""
macro res_str(str)
convert(Vector{Residue}, str)
end
# Comparisons
# -----------
Base.:(==)(x::Residue, y::Residue) = x === y
Base.:(!=)(x::Residue, y::Residue) = x !== y
Base.length(res::Residue) = length(Int(res))
# Random
# ------
"""
It chooses from the 20 natural residues (it doesn't generate gaps).
```jldoctest
julia> using MIToS.MSA
julia> using Random
julia> Random.seed!(1); # Reseed the random number generator.
julia> rand(Residue)
R
julia> rand(Residue, 4, 4)
4×4 Matrix{Residue}:
E D D A
F S K K
M S I M
Y F E D
```
"""
Random.rand(rng::AbstractRNG, ::Random.SamplerType{Residue}) = Residue(rand(rng, 1:20))
function Random.Sampler(RNG::Type{<:AbstractRNG}, res::Residue, r::Random.Repetition)
Random.SamplerSimple(res, Random.Sampler(RNG, 1:20, r))
end
Random.rand(rng::AbstractRNG, sp::Random.SamplerSimple{Residue}) = rand(rng, sp.data)
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 2051 | # Sequence File Formats
# =====================
struct FASTASequences <: SequenceFormat end
struct PIRSequences <: SequenceFormat end
struct RawSequences <: SequenceFormat end
_format_fallback(::Type{FASTASequences}) = FASTA
_format_fallback(::Type{PIRSequences}) = PIR
_format_fallback(::Type{RawSequences}) = Raw
function _generate_sequences(ids, seqs, annot)
n = length(ids)
@assert n == length(seqs)
output = AnnotatedSequence[]
sizehint!(output, n)
for (id, seq) in zip(ids, seqs)
seq_annot = getsequence(annot, id)
push!(output, AnnotatedSequence(id, seq, seq_annot))
end
output
end
# Parse File
# ==========
function Utils.parse_file(
io::Union{IO,AbstractString},
format::Type{T};
generatemapping::Bool = false,
useidcoordinates::Bool = false,
deletefullgaps::Bool = true,
keepinserts::Bool = false,
) where {T<:SequenceFormat}
pre_parser_format = _format_fallback(T)
ids, seqs, annot = _load_sequences(io, pre_parser_format; create_annotations = true)
_generate_sequences(ids, seqs, annot)
end
# Print File
# ==========
# PIRSequences
# ------------
# It uses _get_pir_annotations and _print_pir_seq from src/MSA/PIR.jl
function Utils.print_file(
io::IO,
seqs::Vector{AnnotatedSequence},
format::Type{PIRSequences},
)
for seq in seqs
seqann = getannotsequence(seq)
seq_id = sequence_id(seq)
seq_type, seq_title = _get_pir_annotations(seqann, seq_id)
seq_str = join(seq)
_print_pir_seq(io, seq_type, seq_id, seq_title, seq_str)
end
end
# RawSequences
# ------------
function Utils.print_file(
io::IO,
seqs::Vector{AnnotatedSequence},
format::Type{RawSequences},
)
for seq in seqs
println(io, join(seq))
end
end
# FASTASequences
# --------------
function Utils.print_file(
io::IO,
seqs::Vector{AnnotatedSequence},
format::Type{FASTASequences},
)
for seq in seqs
println(io, ">", sequence_id(seq))
println(io, join(seq))
end
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 7061 | function _subset_indices(msa::Matrix{Residue}, dims::Int, subset, fixed_reference)
_indices = if subset === Colon()
nseq, ncol = size(msa)
if dims == 1
1:nseq
else
1:ncol
end
else
if eltype(subset) !== Int
throw(
ArgumentError(
"For a Matrix{Residue}, subset must be an iterator of Int values or Colon()",
),
)
end
if isa(subset, AbstractRange)
collect(subset)
elseif isa(subset, Int)
[subset]
else
subset
end
end
indices = convert(Vector{Int}, _indices)
if fixed_reference && dims == 1
filter!(!=(1), indices)
end
indices
end
function _subset_indices(msa::NamedResidueMatrix, dims::Int, subset, fixed_reference)
dict = dims == 1 ? msa.dicts[1] : msa.dicts[2]
_indices = NamedArrays.indices(dict, subset)
indices = convert(Vector{Int}, isa(_indices, Int) ? [_indices] : _indices)
if fixed_reference && dims == 1
filter!(!=(1), indices)
end
indices
end
function _subset_indices(
msa::AbstractMultipleSequenceAlignment,
dims,
subset,
fixed_reference,
)::Vector{Int}
_subset_indices(msa.matrix, dims, subset, fixed_reference)
end
function shuffle_msa!(
r::AbstractRNG,
msa::AbstractMatrix{Residue},
subset = Colon();
dims::Int = 2,
fixedgaps::Bool = true,
fixed_reference::Bool = false,
)
@assert dims == 1 || dims == 2 "dims must be 1 for shuffling along sequences or 2 for columns"
subset_indices = _subset_indices(msa, dims, subset, fixed_reference)
msa_matrix = getresidues(msa)
nseq, ncol = size(msa_matrix)
mask = fixedgaps ? msa_matrix .!= GAP : trues(nseq, ncol)
if fixed_reference
mask[1, :] .= 0
end
for i in subset_indices
to_shuffle =
dims == 1 ? view(msa_matrix, i, mask[i, :]) : view(msa_matrix, mask[:, i], i)
shuffle!(r, to_shuffle)
end
msa
end
function shuffle_msa!(r::AbstractRNG, msa::MultipleSequenceAlignment, args...; kwargs...)
shuffle_msa!(r, msa.matrix, args...; kwargs...)
msa
end
function shuffle_msa!(
r::AbstractRNG,
msa::AnnotatedMultipleSequenceAlignment,
subset = Colon();
dims::Int = 2,
fixedgaps::Bool = true,
fixed_reference::Bool = false,
)
shuffle_msa!(r, msa.matrix, subset; dims, fixedgaps, fixed_reference)
# Annotate the modifications
subset_indices = _subset_indices(msa, dims, subset, fixed_reference)
n = length(subset_indices)
entities = dims == 1 ? "sequences" : "columns"
message = "$n $entities shuffled."
fixed = if fixedgaps && fixed_reference
" Gaps and residues in the first sequence"
elseif fixedgaps
" Gaps"
elseif fixed_reference
" Residues in the first sequence"
else
""
end
if !isempty(fixed)
message *= fixed
message *= " were kept in their positions."
end
annotate_modification!(msa.annotations, message)
if dims == 1
seqnames = sequencenames(msa)
for i in subset_indices
seqname = seqnames[i]
setannotsequence!(msa, seqname, "Shuffled", "true")
# Delete SeqMap of the shuffled sequences
delete!(msa.annotations.sequences, (seqname, "SeqMap"))
end
else
shuffled = zeros(Int, ncolumns(msa))
shuffled[subset_indices] .= 1
setannotcolumn!(msa, "Shuffled", join(shuffled))
end
msa
end
shuffle_msa_doc = md"""
It randomly permute residues in the MSA `msa` along sequences (`dims=1`) or columns
(`dims=2`, the default). The optional positional argument `subset` allows to shuffle only
a subset of the sequences or columns. The optional keyword argument `fixedgaps` indicates
if the gaps should remain their positions (`true` by default). The optional keyword
argument `fixed_reference` indicates if the residues in the first sequence should remain
in their positions (`false` by default).
"""
"""
shuffle_msa!([rng=default_rng(),] msa::AbstractMatrix{Residue}, subset=Colon(); dims=2, fixedgaps=true, fixed_reference=false)
In-place version of [`shuffle_msa`](@ref). $shuffle_msa_doc
"""
function shuffle_msa!(msa::AbstractMatrix{Residue}, args...; kwargs...)
shuffle_msa!(Random.default_rng(), msa, args...; kwargs...)
end
function shuffle_msa(r::AbstractRNG, msa::AbstractMatrix{Residue}, args...; kwargs...)
shuffle_msa!(r, deepcopy(msa), args...; kwargs...)
end
"""
shuffle_msa([rng=default_rng(),] msa::AbstractMatrix{Residue}, subset=Colon(); dims=2, fixedgaps=true, fixed_reference=false)
$shuffle_msa_doc To shuffle in-place, see [`shuffle_msa!`](@ref).
```jldoctest
julia> using MIToS.MSA
julia> using Random
julia> msa = hcat(res"RRE",res"DDK", res"G--")
3×3 Matrix{Residue}:
R D G
R D -
E K -
julia> Random.seed!(42);
julia> shuffle_msa(msa, dims=1, fixedgaps=true)
3×3 Matrix{Residue}:
G D R
R D -
E K -
julia> Random.seed!(42);
julia> shuffle_msa(msa, dims=1, fixedgaps=false)
3×3 Matrix{Residue}:
G D R
R - D
E K -
```
"""
function shuffle_msa(msa::AbstractMatrix{Residue}, args...; kwargs...)
shuffle_msa(Random.default_rng(), msa, args...; kwargs...)
end
"""
It's like `Random.shuffle`. When a `Matrix{Residue}` is used, you can indicate if the gaps
should remain their positions using the last boolean argument. The previous argument should
be the dimension to shuffle, 1 for shuffling residues in a sequence (row) or 2 for shuffling
residues in a column.
**DEPRECATED:** This method is deprecated. Use [`shuffle_msa!`](@ref) instead.
"""
function Random.shuffle!(
r::AbstractRNG,
msa::AbstractMatrix{Residue},
dim::Int,
fixedgaps::Bool = true,
)
Base.depwarn(
"The function `shuffle!(r, msa, dim, fixedgaps)` is deprecated. Use `shuffle_msa!(r, msa; dims, fixedgaps)` instead.",
:shuffle!,
force = true,
)
shuffle_msa!(r, msa, Colon(); dims = dim, fixedgaps = fixedgaps) |> getresidues
end
function Random.shuffle!(msa::AbstractMatrix{Residue}, args...)
shuffle!(Random.default_rng(), msa, args...)
end
"""
It's like `shuffle` but in-place. When a `Matrix{Residue}` or a `AbstractAlignedObject`
(sequence or MSA) is used, you can indicate if the gaps should remain their positions
using the last boolean argument.
**DEPRECATED:** This method is deprecated. Use [`shuffle_msa`](@ref) instead.
"""
function Random.shuffle(
r::AbstractRNG,
msa::AbstractMatrix{Residue},
dim::Int,
fixedgaps::Bool = true,
)
Base.depwarn(
"The function `shuffle(r, msa, dim, fixedgaps)` is deprecated. Use `shuffle_msa(r, msa; dims, fixedgaps)` instead.",
:shuffle,
force = true,
)
shuffle_msa(r, msa, Colon(); dims = dim, fixedgaps = fixedgaps) |> getresidues
end
function Random.shuffle(msa::AbstractMatrix{Residue}, args...)
shuffle(Random.GLOBAL_RNG, msa, args...)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 4158 | struct Stockholm <: MSAFormat end
@inline function _fill_with_sequence_line!(IDS, SEQS, line)
if !startswith(line, '#') && !startswith(line, "//")
words = get_n_words(line, 2)
@inbounds id = words[1]
if id in IDS
# It's useful when sequences are split into several lines
# It can be a problem with duplicated IDs
i = something(findfirst(isequal(id), IDS), 0)
SEQS[i] = SEQS[i] * words[2]
else
push!(IDS, id)
push!(SEQS, words[2])
end
end
end
function _fill_with_line!(IDS, SEQS, GF, GS, GC, GR, line)
if startswith(line, "#=GF")
words = get_n_words(line, 3)
id = words[2]
if id in keys(GF)
GF[id] = GF[id] * "\n" * words[3]
else
GF[id] = words[3]
end
elseif startswith(line, "#=GS")
words = get_n_words(line, 4)
idtuple = (words[2], words[3])
if idtuple in keys(GS)
GS[idtuple] = GS[idtuple] * "\n" * words[4]
else
GS[idtuple] = words[4]
end
elseif startswith(line, "#=GC")
words = get_n_words(line, 3)
GC[words[2]] = words[3]
elseif startswith(line, "#=GR")
words = get_n_words(line, 4)
GR[(words[2], words[3])] = words[4]
else
_fill_with_sequence_line!(IDS, SEQS, line)
end
end
function _pre_readstockholm(io::Union{IO,AbstractString})
IDS = OrderedSet{String}()
SEQS = String[]
GF = OrderedDict{String,String}()
GC = Dict{String,String}()
GS = Dict{Tuple{String,String},String}()
GR = Dict{Tuple{String,String},String}()
@inbounds for line::String in lineiterator(io)
isempty(line) && continue
startswith(line, "//") && break
_fill_with_line!(IDS, SEQS, GF, GS, GC, GR, line)
end
GF = sizehint!(GF, length(GF))
GC = sizehint!(GC, length(GC))
GS = sizehint!(GS, length(GS))
GR = sizehint!(GR, length(GR))
(IDS, SEQS, GF, GS, GC, GR)
end
function _pre_readstockholm_sequences(io::Union{IO,AbstractString})
IDS = OrderedSet{String}()
SEQS = String[]
@inbounds for line::String in lineiterator(io)
isempty(line) && continue
startswith(line, "//") && break
_fill_with_sequence_line!(IDS, SEQS, line)
end
(IDS, SEQS)
end
function _load_sequences(
io::Union{IO,AbstractString},
format::Type{Stockholm};
create_annotations::Bool = false,
)
if create_annotations
IDS, SEQS, GF, GS, GC, GR = _pre_readstockholm(io)
annot = Annotations(GF, GS, GC, GR)
else
IDS, SEQS = _pre_readstockholm_sequences(io)
annot = Annotations()
end
return collect(IDS), SEQS, annot
end
# Print Pfam
# ==========
function _to_sequence_dict(annotation::Dict{Tuple{String,String},String})
seq_dict = Dict{String,Vector{String}}()
for (key, value) in annotation
seq_id = key[1]
if haskey(seq_dict, seq_id)
push!(seq_dict[seq_id], string(seq_id, '\t', key[2], '\t', value))
else
seq_dict[seq_id] = [string(seq_id, '\t', key[2], '\t', value)]
end
end
sizehint!(seq_dict, length(seq_dict))
end
function Utils.print_file(io::IO, msa::AbstractMatrix{Residue}, format::Type{Stockholm})
has_annotations = isa(msa, AnnotatedAlignedObject) && !isempty(msa.annotations)
if has_annotations
_printfileannotations(io, msa.annotations)
_printsequencesannotations(io, msa.annotations)
res_annotations = _to_sequence_dict(msa.annotations.residues)
end
seqnames = sequencenames(msa)
aligned = _get_aligned_columns(msa)
for i = 1:nsequences(msa)
id = seqnames[i]
seq = stringsequence(msa, i)
formatted_seq = _format_inserts(seq, aligned)
println(io, id, "\t\t\t", formatted_seq)
if has_annotations && haskey(res_annotations, id)
for line in res_annotations[id]
println(io, "#=GR ", line)
end
end
end
has_annotations && _printcolumnsannotations(io, msa.annotations)
println(io, "//")
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 1167 | const _res2three = [
"ALA",
"ARG",
"ASN",
"ASP",
"CYS",
"GLN",
"GLU",
"GLY",
"HIS",
"ILE",
"LEU",
"LYS",
"MET",
"PHE",
"PRO",
"SER",
"THR",
"TRP",
"TYR",
"VAL",
" ",
"XAA",
]
"""
This function returns the three letter name of the `Residue`.
```jldoctest
julia> using MIToS.MSA
julia> residue2three(Residue('G'))
"GLY"
```
"""
function residue2three(res::Residue)
int_res = Int(res)
if int_res == 21 || !isvalid(res)
# GAP
throw(ErrorException("Residue($(int_res)) has not three letter name."))
end
_res2three[int_res]
end
"""
It takes a three letter residue name and returns the corresponding `Residue`.
If the name isn't in the MIToS dictionary, a `XAA` is returned.
```jldoctest
julia> using MIToS.MSA
julia> three2residue("ALA")
A
```
"""
function three2residue(res::String)
if length(res) == 3
get(_three2res, uppercase(res), XAA)
else
throw(ErrorException("The residue name should have 3 letters."))
end
end
const _three2res = convert(Dict{String,Residue}, THREE2ONE) # THREE2ONE from MIToS.Utils
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 2443 | """
query_alphafolddb(uniprot_accession::String)
This function queries the AlphaFoldDB API to retrieve structure information for
a given `uniprot_accession`, e.g. `"P00520"`. This function returns the structure
information as a `JSON3.Object`.
"""
function query_alphafolddb(uniprot_accession::String)
# Construct the URL for the AlphaFoldDB API request
url = "https://alphafold.ebi.ac.uk/api/prediction/$uniprot_accession"
body = IOBuffer()
response = Downloads.request(url, method = "GET", output = body)
if response.status == 200
# Use only to get the unique EntrySummary object in the Root list
only(JSON3.read(String(take!(body))))
else
error_type = response.status == 422 ? "Validation Error" : "Error"
throw(
ErrorException(
"$error_type ($(response.status)) fetching UniProt Accession $uniprot_accession from AlphaFoldDB.",
),
)
end
end
# This function extracts the filename from a given URL.
function _extract_filename_from_url(url::String)
return split(url, "/")[end]
end
# Function to download the PDB or CIF file based on the UniProt Accession
"""
download_alphafold_structure(uniprot_accession::String; format::Type{T}=MMCIFFile) where T<:FileFormat
This function downloads the structure file (PDB or mmCIF) for a given UniProt Accession
from AlphaFoldDB. The `uniprot_accession` parameter specifies the UniProt Accession of the
protein, e.g. `"P00520"`. The `format` parameter specifies the file format to download,
with the default being mmCIF, i.e. `MMCIFFile`. You can set `format` to `PDBFile` if you
want to download a PDB file.
"""
function download_alphafold_structure(
uniprot_accession::String;
format::Type{T} = MMCIFFile,
) where {T<:FileFormat}
structure_info = query_alphafolddb(uniprot_accession)
# Initialize the model URL based on the requested format
if format === PDBFile
model_url = structure_info["pdbUrl"]
elseif format === MMCIFFile
model_url = structure_info["cifUrl"]
else
throw(ArgumentError("Unsupported format: $format"))
end
file_name = _extract_filename_from_url(model_url)
try
download_file(model_url, file_name)
catch
throw(
ErrorException(
"Error downloading AlphaFold model for UniProt Accession $uniprot_accession",
),
)
end
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 18488 | """
Covalent radius in Å of each element from the Additional file 1 of PICCOLO [1].
Hydrogen was updated using the value on Table 2 from Cordero et. al. [2].
1. Bickerton, G. R., Higueruelo, A. P., & Blundell, T. L. (2011).
Comprehensive, atomic-level characterization of structurally
characterized protein-protein interactions: the PICCOLO database.
BMC bioinformatics, 12(1), 313.
2. Cordero, B., Gómez, V., Platero-Prats, A. E., Revés, M.,
Echeverría, J., Cremades, E., ... & Alvarez, S. (2008).
Covalent radii revisited. Dalton Transactions, (21), 2832-2838.
"""
const covalentradius =
Dict{String,Float64}("C" => 0.77, "N" => 0.70, "O" => 0.66, "S" => 1.04, "H" => 0.31)
const _3_letter_aa = String[
"ALA",
"ARG",
"ASN",
"ASP",
"CYS",
"GLN",
"GLU",
"GLY",
"HIS",
"ILE",
"LEU",
"LYS",
"MET",
"PHE",
"PRO",
"SER",
"THR",
"TRP",
"TYR",
"VAL",
]
"""
van der Waals radius in Å from the Additional file 1 of Bickerton et. al. 2011
- Bickerton, G. R., Higueruelo, A. P., & Blundell, T. L. (2011).
Comprehensive, atomic-level characterization of structurally characterized protein-protein interactions: the PICCOLO database.
BMC bioinformatics, 12(1), 313.
"""
const vanderwaalsradius = Dict{Tuple{String,String},Float64}(
("ALA", "C") => 1.61,
("ALA", "CA") => 1.88,
("ALA", "CB") => 1.88,
("ALA", "N") => 1.64,
("ALA", "O") => 1.42,
("ARG", "C") => 1.61,
("ARG", "CA") => 1.88,
("ARG", "CB") => 1.88,
("ARG", "CD") => 1.88,
("ARG", "CG") => 1.88,
("ARG", "CZ") => 1.61,
("ARG", "N") => 1.64,
("ARG", "NE") => 1.64,
("ARG", "NH1") => 1.64,
("ARG", "NH2") => 1.64,
("ARG", "O") => 1.42,
("ASN", "C") => 1.61,
("ASN", "CA") => 1.88,
("ASN", "CB") => 1.88,
("ASN", "CG") => 1.61,
("ASN", "N") => 1.64,
("ASN", "ND2") => 1.64,
("ASN", "O") => 1.42,
("ASN", "OD1") => 1.42,
("ASP", "C") => 1.61,
("ASP", "CA") => 1.88,
("ASP", "CB") => 1.88,
("ASP", "CG") => 1.61,
("ASP", "N") => 1.64,
("ASP", "O") => 1.42,
("ASP", "OD1") => 1.42,
("ASP", "OD2") => 1.42,
("CYS", "C") => 1.61,
("CYS", "CA") => 1.88,
("CYS", "CB") => 1.88,
("CYS", "N") => 1.64,
("CYS", "O") => 1.42,
("CYS", "SG") => 1.77,
("GLN", "C") => 1.61,
("GLN", "CA") => 1.88,
("GLN", "CB") => 1.88,
("GLN", "CD") => 1.61,
("GLN", "CG") => 1.88,
("GLN", "N") => 1.64,
("GLN", "NE2") => 1.64,
("GLN", "O") => 1.42,
("GLN", "OE1") => 1.42,
("GLU", "C") => 1.61,
("GLU", "CA") => 1.88,
("GLU", "CB") => 1.88,
("GLU", "CD") => 1.61,
("GLU", "CG") => 1.88,
("GLU", "N") => 1.64,
("GLU", "O") => 1.42,
("GLU", "OE1") => 1.42,
("GLU", "OE2") => 1.42,
("GLY", "C") => 1.61,
("GLY", "CA") => 1.88,
("GLY", "N") => 1.64,
("GLY", "O") => 1.42,
("HIS", "C") => 1.61,
("HIS", "CA") => 1.88,
("HIS", "CB") => 1.88,
("HIS", "CD2") => 1.76,
("HIS", "CE1") => 1.76,
("HIS", "CG") => 1.61,
("HIS", "N") => 1.64,
("HIS", "ND1") => 1.64,
("HIS", "NE2") => 1.64,
("HIS", "O") => 1.42,
("ILE", "C") => 1.61,
("ILE", "CA") => 1.88,
("ILE", "CB") => 1.88,
("ILE", "CD1") => 1.88,
("ILE", "CG1") => 1.88,
("ILE", "CG2") => 1.88,
("ILE", "N") => 1.64,
("ILE", "O") => 1.42,
("LEU", "C") => 1.61,
("LEU", "CA") => 1.88,
("LEU", "CB") => 1.88,
("LEU", "CD1") => 1.88,
("LEU", "CD2") => 1.88,
("LEU", "CG") => 1.88,
("LEU", "N") => 1.64,
("LEU", "O") => 1.42,
("LYS", "C") => 1.61,
("LYS", "CA") => 1.88,
("LYS", "CB") => 1.88,
("LYS", "CD") => 1.88,
("LYS", "CE") => 1.88,
("LYS", "CG") => 1.88,
("LYS", "N") => 1.64,
("LYS", "NZ") => 1.64,
("LYS", "O") => 1.42,
("MET", "C") => 1.61,
("MET", "CA") => 1.88,
("MET", "CB") => 1.88,
("MET", "CE") => 1.88,
("MET", "CG") => 1.88,
("MET", "N") => 1.64,
("MET", "O") => 1.42,
("MET", "SD") => 1.77,
("PHE", "C") => 1.61,
("PHE", "CA") => 1.88,
("PHE", "CB") => 1.88,
("PHE", "CD1") => 1.76,
("PHE", "CD2") => 1.76,
("PHE", "CE1") => 1.76,
("PHE", "CE2") => 1.76,
("PHE", "CG") => 1.61,
("PHE", "CZ") => 1.76,
("PHE", "N") => 1.64,
("PHE", "O") => 1.42,
("PRO", "C") => 1.61,
("PRO", "CA") => 1.88,
("PRO", "CB") => 1.88,
("PRO", "CD") => 1.88,
("PRO", "CG") => 1.88,
("PRO", "N") => 1.64,
("PRO", "O") => 1.42,
("SER", "C") => 1.61,
("SER", "CA") => 1.88,
("SER", "CB") => 1.88,
("SER", "N") => 1.64,
("SER", "O") => 1.42,
("SER", "OG") => 1.46,
("THR", "C") => 1.61,
("THR", "CA") => 1.88,
("THR", "CB") => 1.88,
("THR", "CG2") => 1.88,
("THR", "N") => 1.64,
("THR", "O") => 1.42,
("THR", "OG1") => 1.46,
("TRP", "C") => 1.61,
("TRP", "CA") => 1.88,
("TRP", "CB") => 1.88,
("TRP", "CD1") => 1.76,
("TRP", "CD2") => 1.61,
("TRP", "CE2") => 1.61,
("TRP", "CE3") => 1.76,
("TRP", "CG") => 1.61,
("TRP", "CH2") => 1.76,
("TRP", "CZ2") => 1.76,
("TRP", "CZ3") => 1.76,
("TRP", "N") => 1.64,
("TRP", "NE1") => 1.64,
("TRP", "O") => 1.42,
("TYR", "C") => 1.61,
("TYR", "CA") => 1.88,
("TYR", "CB") => 1.88,
("TYR", "CD1") => 1.76,
("TYR", "CD2") => 1.76,
("TYR", "CE1") => 1.76,
("TYR", "CE2") => 1.76,
("TYR", "CG") => 1.61,
("TYR", "CZ") => 1.61,
("TYR", "N") => 1.64,
("TYR", "O") => 1.42,
("TYR", "OH") => 1.46,
("VAL", "C") => 1.61,
("VAL", "CA") => 1.88,
("VAL", "CB") => 1.88,
("VAL", "CG1") => 1.88,
("VAL", "CG2") => 1.88,
("VAL", "N") => 1.64,
("VAL", "O") => 1.42,
)
function _add_CTER_O!(dict)
for aa in _3_letter_aa
push!(dict, (aa, "OXT"))
push!(dict, (aa, "OT2"))
push!(dict, (aa, "OT1"))
end
dict
end
function _add_CTER_O!(dict, value)
for aa in _3_letter_aa
push!(dict, (aa, "OXT") => value)
push!(dict, (aa, "OT2") => value)
push!(dict, (aa, "OT1") => value)
end
dict
end
_add_CTER_O!(vanderwaalsradius, 1.42) # Using 1.42 because OXT is the terminal oxigen I assume same vdw radii than O
const _hydrophobic = Set{Tuple{String,String}}([
("ALA", "CB"),
("ARG", "CB"),
("ARG", "CG"),
("ASN", "CB"),
("ASP", "CB"),
("CYS", "CB"),
("GLN", "CB"),
("GLN", "CG"),
("GLU", "CB"),
("GLU", "CG"),
("HIS", "CB"),
("ILE", "CB"),
("ILE", "CD1"),
("ILE", "CG1"),
("ILE", "CG2"),
("LEU", "CB"),
("LEU", "CD1"),
("LEU", "CD2"),
("LEU", "CG"),
("LYS", "CB"),
("LYS", "CD"),
("LYS", "CG"),
("MET", "CB"),
("MET", "CE"),
("MET", "CG"),
("MET", "SD"),
("PHE", "CB"),
("PHE", "CD1"),
("PHE", "CD2"),
("PHE", "CE1"),
("PHE", "CE2"),
("PHE", "CG"),
("PHE", "CZ"),
("PRO", "CB"),
("PRO", "CG"),
("THR", "CG2"),
("TRP", "CB"),
("TRP", "CD2"),
("TRP", "CE3"),
("TRP", "CG"),
("TRP", "CH2"),
("TRP", "CZ2"),
("TRP", "CZ3"),
("TYR", "CB"),
("TYR", "CD1"),
("TYR", "CD2"),
("TYR", "CE1"),
("TYR", "CE2"),
("TYR", "CG"),
("VAL", "CB"),
("VAL", "CG1"),
("VAL", "CG2"),
])
const _aromatic_res = Set{String}(["HIS", "PHE", "TRP", "TYR"])
const _aromatic = Set{Tuple{String,String}}([
("HIS", "CD2"),
("HIS", "CE1"),
("HIS", "CG"),
("HIS", "ND1"),
("HIS", "NE2"),
("PHE", "CD1"),
("PHE", "CD2"),
("PHE", "CE1"),
("PHE", "CE2"),
("PHE", "CG"),
("PHE", "CZ"),
("TRP", "CD1"),
("TRP", "CD2"),
("TRP", "CE2"),
("TRP", "CE3"),
("TRP", "CG"),
("TRP", "CH2"),
("TRP", "CZ2"),
("TRP", "CZ3"),
("TRP", "NE1"),
("TYR", "CD1"),
("TYR", "CD2"),
("TYR", "CE1"),
("TYR", "CE2"),
("TYR", "CG"),
("TYR", "CZ"),
])
const _cationic = Set{Tuple{String,String}}([
("ARG", "CZ"),
("ARG", "NE"),
("ARG", "NH1"),
("ARG", "NH2"),
("HIS", "CD2"),
("HIS", "CE1"),
("HIS", "CG"),
("HIS", "ND1"),
("HIS", "NE2"),
("LYS", "NZ"),
])
const _anionic = Set{Tuple{String,String}}([
("ASP", "CG"),
("ASP", "OD1"),
("ASP", "OD2"),
("GLU", "CD"),
("GLU", "OE1"),
("GLU", "OE2"),
])
_add_CTER_O!(_anionic)
"""
Keys come from Table 1 of Bickerton et. al. 2011,
The hydrogen names of the donor comes from: http://biomachina.org/courses/modeling/download/topallh22x.pro
Synonyms come from: http://www.bmrb.wisc.edu/ref_info/atom_nom.tbl
"""
const _hbond_donor = Dict{Tuple{String,String},Vector{String}}(
("ALA", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("ARG", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("ARG", "NE") => ["HE", "HNE"],
("ARG", "NH1") => ["HH11", "HH12", "1HH1", "2HH1"],
("ARG", "NH2") => ["HH22", "HH21", "2HH1", "1HH2"],
("ASN", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("ASN", "ND2") => ["HD21", "HD22", "HN21", "HN22", "1HD2", "2HD2"],
("ASP", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("CYS", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("CYS", "SG") => ["HG1", "HG", "HSG"],
("GLN", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("GLN", "NE2") => ["HE21", "HE22", "1HE2", "2HE2", "HN21", "HN22"],
("GLU", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("GLY", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("HIS", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("HIS", "ND1") => ["HD1"],
("HIS", "NE2") => ["HE2", "HNE2"],
("ILE", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("LEU", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("LYS", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("LYS", "NZ") => ["HZ1", "HZ2", "HZ3", "1HZ", "2HZ", "3HZ", "HNZ1", "HNZ2", "HNZ3"],
("MET", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("PHE", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("SER", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("SER", "OG") => ["HG1", "HG", "HOG"],
("THR", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("THR", "OG1") => ["HG1", "HOG1"],
("TRP", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("TRP", "NE1") => ["HE1", "HNE1"],
("TYR", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("TYR", "OH") => ["HH", "HOH"],
("VAL", "N") => [
"HN",
"H",
"HN1",
"H1",
"1H",
"HN2",
"H2",
"2H",
"HN3",
"H3",
"3H",
"HT1",
"HT2",
"HT3",
],
("PRO", "N") => ["HN1", "H1", "1H", "HN2", "H2", "2H", "HT1", "HT2"],
)
# Proline N-Terminal (RESIDUE PROP)
"""
Keys come from Table 1 of Bickerton et. al. 2011,
Antecedents come from come from: http://biomachina.org/courses/modeling/download/topallh22x.pro
Synonyms come from: http://www.bmrb.wisc.edu/ref_info/atom_nom.tbl
"""
const _hbond_acceptor = Dict{Tuple{String,String},Vector{String}}(
("ALA", "O") => ["C"],
("ALA", "OT1") => ["C"],
("ALA", "OXT") => ["C"],
("ALA", "OT2") => ["C"],
("ARG", "O") => ["C"],
("ARG", "OT1") => ["C"],
("ARG", "OXT") => ["C"],
("ARG", "OT2") => ["C"],
("ASN", "O") => ["C"],
("ASN", "OT1") => ["C"],
("ASN", "OXT") => ["C"],
("ASN", "OT2") => ["C"],
("ASN", "OD1") => ["CG"],
("ASP", "O") => ["C"],
("ASP", "OT1") => ["C"],
("ASP", "OXT") => ["C"],
("ASP", "OT2") => ["C"],
("ASP", "OD1") => ["CG"],
("ASP", "OD2") => ["CG"],
("CYS", "O") => ["C"],
("CYS", "OT1") => ["C"],
("CYS", "OXT") => ["C"],
("CYS", "OT2") => ["C"],
("CYS", "SG") => ["CB"],
("GLN", "O") => ["C"],
("GLN", "OT1") => ["C"],
("GLN", "OXT") => ["C"],
("GLN", "OT2") => ["C"],
("GLN", "OE1") => ["CD"],
("GLU", "O") => ["C"],
("GLU", "OT1") => ["C"],
("GLU", "OXT") => ["C"],
("GLU", "OT2") => ["C"],
("GLU", "OE1") => ["CD"],
("GLU", "OE2") => ["CD"],
("GLY", "O") => ["C"],
("GLY", "OT1") => ["C"],
("GLY", "OXT") => ["C"],
("GLY", "OT2") => ["C"],
("HIS", "ND1") => ["CG", "CE1"],
("HIS", "NE2") => ["CD2", "CE1"],
("HIS", "O") => ["C"],
("HIS", "OT1") => ["C"],
("HIS", "OXT") => ["C"],
("HIS", "OT2") => ["C"],
("ILE", "O") => ["C"],
("ILE", "OT1") => ["C"],
("ILE", "OXT") => ["C"],
("ILE", "OT2") => ["C"],
("LEU", "O") => ["C"],
("LEU", "OT1") => ["C"],
("LEU", "OXT") => ["C"],
("LEU", "OT2") => ["C"],
("LYS", "O") => ["C"],
("LYS", "OT1") => ["C"],
("LYS", "OXT") => ["C"],
("LYS", "OT2") => ["C"],
("MET", "O") => ["C"],
("MET", "OT1") => ["C"],
("MET", "OXT") => ["C"],
("MET", "OT2") => ["C"],
("MET", "SD") => ["CG", "CE"],
("PHE", "O") => ["C"],
("PHE", "OT1") => ["C"],
("PHE", "OXT") => ["C"],
("PHE", "OT2") => ["C"],
("PRO", "O") => ["C"],
("PRO", "OT1") => ["C"],
("PRO", "OXT") => ["C"],
("PRO", "OT2") => ["C"],
("SER", "O") => ["C"],
("SER", "OT1") => ["C"],
("SER", "OXT") => ["C"],
("SER", "OT2") => ["C"],
("SER", "OG") => ["CB"],
("THR", "O") => ["C"],
("THR", "OT1") => ["C"],
("THR", "OXT") => ["C"],
("THR", "OT2") => ["C"],
("THR", "OG1") => ["CB"],
("TRP", "O") => ["C"],
("TRP", "OT1") => ["C"],
("TRP", "OXT") => ["C"],
("TRP", "OT2") => ["C"],
("TYR", "O") => ["C"],
("TYR", "OT1") => ["C"],
("TYR", "OXT") => ["C"],
("TYR", "OT2") => ["C"],
("VAL", "O") => ["C"],
("VAL", "OT1") => ["C"],
("VAL", "OXT") => ["C"],
("VAL", "OT2") => ["C"],
)
function _generate_dict!(dict, input_dict)
for (res, atom) in keys(input_dict)
if haskey(dict, res)
push!(dict[res], atom)
else
dict[res] = Set{String}(String[atom])
end
end
dict
end
function _generate_dict!(dict, input_set::Set{Tuple{String,String}})
for (res, atom) in input_set
if haskey(dict, res)
push!(dict[res], atom)
else
dict[res] = Set{String}(String[atom])
end
end
dict
end
function _generate_interaction_keys(vdw, hyd, aro, cat, ani)
dict = Dict{String,Set{String}}()
_generate_dict!(dict, vdw)
_generate_dict!(dict, hyd)
_generate_dict!(dict, aro)
_generate_dict!(dict, cat)
_generate_dict!(dict, ani)
dict
end
const _interaction_keys = _generate_interaction_keys(
vanderwaalsradius,
_hydrophobic,
_aromatic,
_cationic,
_anionic,
)
_generate_atoms_set(res::PDBResidue) =
String[atom.atom for atom in res.atoms[findheavy(res)]]
"""
This function takes a `PDBResidue` and returns `true` only if all the atoms can be used
for checking interactions.
"""
function check_atoms_for_interactions(res::PDBResidue)
atoms = _generate_atoms_set(res)
if haskey(_interaction_keys, res.id.name)
used = _interaction_keys[res.id.name]
else
@warn "RESIDUE $(res.id.name) is unknown to MIToS.PDB (AtomsData.jl)"
return (false)
end
for atom in atoms
if !(atom in used)
@warn "RESIDUE $(res.id.name) ATOM $(atom) is unknown to MIToS.PDB (AtomsData.jl)"
return (false)
end
end
true
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 2007 | # This file defines the functions to convert between MIToS.PDB and BioStructures types.
function BioStructures.MolecularStructure(residues::Vector{PDBResidue})
mmcifdict = _pdbresidues_to_mmcifdict(residues, molecular_structures = true)
MolecularStructure(mmcifdict)
end
function Base.convert(::Type{Vector{PDBResidue}}, struc::MolecularStructure)
_molecularstructure_to_pdbresidues(struc)
end
function _molecularstructure_to_pdbresidues(struc::MolecularStructure)
vector_res = PDBResidue[]
for model in values(models(struc))
for chain in values(chains(model))
for res in values(BioStructures.residues(chain))
# Check if the residue is a DisorderedResidue
if isdisorderedres(res)
for res_name in resnames(res)
dis_res = disorderedres(res, res_name)
push!(vector_res, _create_pdbresidue(dis_res, model, chain))
end
else
push!(vector_res, _create_pdbresidue(res, model, chain))
end
end
end
end
vector_res
end
function _create_pdbresidue(res, model::Model, chain::Chain)
residue_id = PDBResidueIdentifier(
"", # PDBe_number not available
string(resnumber(res)) * inscode(res),
resname(res),
ishetero(res) ? "HETATM" : "ATOM",
string(modelnumber(model)),
chainid(chain),
)
atoms = PDBAtom[]
for atom in collectatoms(res)
atom_obj = PDBAtom(
Coordinates(
BioStructures.x(atom),
BioStructures.y(atom),
BioStructures.z(atom),
),
atomname(atom),
element(atom),
occupancy(atom),
string(tempfactor(atom)),
string(altlocid(atom)),
strip(charge(atom, strip = false)),
)
push!(atoms, atom_obj)
end
PDBResidue(residue_id, atoms)
end
| MIToS | https://github.com/diegozea/MIToS.jl.git |
|
[
"MIT"
] | 3.0.6 | 8995effa332b70686f53d0dca35a29950f418df7 | code | 9604 | _with_vdw(a::PDBAtom, resname_a::String) = (resname_a, a.atom) in keys(vanderwaalsradius)
_with_cov(a::PDBAtom, resname_a::String) = a.element in keys(covalentradius)
ishydrophobic(a::PDBAtom, resname_a::String) = (resname_a, a.atom) in _hydrophobic
"""
Returns true if the atom, e.g. `("HIS","CG")`, is an aromatic atom in the residue.
"""
isaromatic(a::PDBAtom, resname_a::String) = (resname_a, a.atom) in _aromatic
"""
Returns true if the atom, e.g. `("ARG","NE")`, is a cationic atom in the residue.
"""
iscationic(a::PDBAtom, resname_a::String) = (resname_a, a.atom) in _cationic
"""
Returns true if the atom, e.g. `("GLU","CD")`, is an anionic atom in the residue.
"""
isanionic(a::PDBAtom, resname_a::String) = (resname_a, a.atom) in _anionic
"""
Returns true if the atom, e.g. `("ARG","N")`, is a donor in H bonds.
"""
ishbonddonor(a::PDBAtom, resname_a::String) = (resname_a, a.atom) in keys(_hbond_donor)
"""
Returns true if the atom, e.g. `("ARG","O")`, is an acceptor in H bonds.
"""
ishbondacceptor(a::PDBAtom, resname_a::String) =
(resname_a, a.atom) in keys(_hbond_acceptor)
"""
`any(f::Function, a::PDBResidue, b::PDBResidue, criteria::Function)`
Test if the function `f` is true for any pair of atoms between the residues `a` and `b`.
This function only test atoms that returns `true` for the fuction `criteria`.
"""
function Base.any(f::Function, a::PDBResidue, b::PDBResidue, criteria::Function)
resname_a, resname_b = a.id.name, b.id.name
a_atoms = a.atoms
b_atoms = b.atoms
indices_a = _find(x -> criteria(x, resname_a), a_atoms)
indices_b = _find(x -> criteria(x, resname_b), b_atoms)
if length(indices_a) != 0 && length(indices_b) != 0
@inbounds for i in indices_a
for j in indices_b
if f(a_atoms[i], b_atoms[j], resname_a, resname_b)
return (true)
end
end
end
end
return (false)
end
# Interaction types
# =================
# van der Waals
# -------------
"""
Test if two atoms or residues are in van der Waals contact using:
`distance(a,b) <= 0.5 + vanderwaalsradius[a] + vanderwaalsradius[b]`.
It returns distance `<= 0.5` if the atoms aren't in `vanderwaalsradius`.
"""
function vanderwaals(a::PDBAtom, b::PDBAtom, resname_a, resname_b)
return (
distance(a, b) <=
0.5 +
get(vanderwaalsradius, (resname_a, a.atom), 0.0) +
get(vanderwaalsradius, (resname_b, b.atom), 0.0)
)
end
vanderwaals(a::PDBResidue, b::PDBResidue) = any(vanderwaals, a, b, _with_vdw)
# van der Waals clash
# -------------------
"""
Returns `true` if the distance between the atoms is less than the sum of the
`vanderwaalsradius` of the atoms. If the atoms aren't on the list (i.e. `OXT`), the
`vanderwaalsradius` of the element is used. If there is not data in the dict,
distance `0.0` is used.
"""
function vanderwaalsclash(a::PDBAtom, b::PDBAtom, resname_a, resname_b)
return (
distance(a, b) <=
get(
vanderwaalsradius,
(resname_a, a.atom),
get(vanderwaalsradius, (resname_a, a.element), 0.0),
) + get(
vanderwaalsradius,
(resname_b, b.atom),
get(vanderwaalsradius, (resname_b, b.element), 0.0),
)
)
end
vanderwaalsclash(a::PDBResidue, b::PDBResidue) = any(vanderwaalsclash, a, b, _with_vdw)
# Covalent
# --------
"""
Returns `true` if the distance between atoms is less than the sum of the `covalentradius`
of each atom.
"""
function covalent(a::PDBAtom, b::PDBAtom, resname_a, resname_b) # any(... calls it with the res names
return (
distance(a, b) <=
get(covalentradius, a.element, 0.0) + get(covalentradius, b.element, 0.0)
)
end
covalent(a::PDBAtom, b::PDBAtom) = covalent(a, b, "", "")
covalent(a::PDBResidue, b::PDBResidue) = any(covalent, a, b, _with_cov)
# Disulphide
# ----------
_issulphurcys(a::PDBAtom, resname_a) = resname_a == "CYS" && a.element == "S"
"""
Returns `true` if two `CYS`'s `S` are at 2.08 Å or less
"""
function disulphide(a::PDBAtom, b::PDBAtom, resname_a, resname_b)
if _issulphurcys(a, resname_a) && _issulphurcys(b, resname_b)
return (squared_distance(a, b) <= (2.08^2))
end
return (false)
end
disulphide(a::PDBResidue, b::PDBResidue) = any(disulphide, a, b, _issulphurcys)
# Aromatic-Sulphur
# ----------------
_issulphur(a::PDBAtom) = a.element == "S"
"""
Returns `true` if an sulphur and an aromatic atoms are 5.3 Å or less"
"""
function aromaticsulphur(a::PDBAtom, b::PDBAtom, resname_a, resname_b)
if (_issulphur(a) && isaromatic(b, resname_b)) ||
(_issulphur(b) && isaromatic(a, resname_a))
return (squared_distance(a, b) <= 28.09) # 28.09 == 5.3 ^ 2
end
return (false)
end
_issulphuroraromatic(a::PDBAtom, resname_a) = _issulphur(a) || isaromatic(a, resname_a)
aromaticsulphur(a::PDBResidue, b::PDBResidue) =
any(aromaticsulphur, a, b, _issulphuroraromatic)
# Π-Cation
# --------
"""
There's a Π-Cation interaction if a cationic and an aromatic atoms are at 6.0 Å or less
"""
function pication(a::PDBAtom, b::PDBAtom, resname_a, resname_b)
if (iscationic(a, resname_a) && isaromatic(b, resname_b)) ||
(iscationic(b, resname_b) && isaromatic(a, resname_a))
return (squared_distance(a, b) <= 36.0) # 36.0 == 6.0 ^ 2
end
return (false)
end
_iscationicoraromatic(a::PDBAtom, resname_a) =
iscationic(a, resname_a) || isaromatic(a, resname_a)
pication(a::PDBResidue, b::PDBResidue) = any(pication, a, b, _iscationicoraromatic)
# Aromatic
# --------
"""
There's an aromatic interaction if centriods are at 6.0 Å or less.
"""
function aromatic(a::PDBResidue, b::PDBResidue)
threshold = 36.0 # 6.0 ^ 2
if (a.id.name in _aromatic_res) &&
(b.id.name in _aromatic_res) &&
(squared_distance(a, b) <= threshold)
centres_a = _centre(_get_plane(a))
centres_b = _centre(_get_plane(b))
return (any(
squared_distance(centroid_a, centroid_b) <= threshold for
centroid_a in centres_a, centroid_b in centres_b
))
end
return (false)
end
# Ionic
# -----
"""
There's an ionic interaction if a cationic and an anionic atoms are at 6.0 Å or less.
"""
function ionic(a::PDBAtom, b::PDBAtom, resname_a, resname_b)
if (iscationic(a, resname_a) && isanionic(b, resname_b)) ||
(iscationic(b, resname_b) && isanionic(a, resname_a))
return (squared_distance(a, b) <= 36.0) # 36.0 == 6.0 ^ 2
end
return (false)
end
_iscationicoranionic(a::PDBAtom, resname_a) =
iscationic(a, resname_a) || isanionic(a, resname_a)
ionic(a::PDBResidue, b::PDBResidue) = any(ionic, a, b, _iscationicoranionic)
# Hydrophobic contact
# -------------------
"""
There's an hydrophobic interaction if two hydrophobic atoms are at 5.0 Å or less.
"""
function hydrophobic(a::PDBAtom, b::PDBAtom, resname_a, resname_b)
if ishydrophobic(a, resname_a) && ishydrophobic(b, resname_b)
return (squared_distance(a, b) <= 25.0) # 5.0 ^ 2
end
return (false)
end
hydrophobic(a::PDBResidue, b::PDBResidue) = any(hydrophobic, a, b, ishydrophobic)
# Hydrogen bonds
# --------------
function _find_antecedent(res::PDBResidue, a::PDBAtom)
ids = _hbond_acceptor[(res.id.name, a.atom)]
_find(a -> a.atom in ids, res.atoms)
end
function _find_h(res::PDBResidue, a::PDBAtom)
ids = _hbond_donor[(res.id.name, a.atom)]
_find(a -> a.atom in ids, res.atoms)
end
function _hbond_kernel(donor, acceptor, indices_donor, indices_acceptor)
@inbounds for i in indices_donor
don = donor.atoms[i]
indices_h = _find_h(donor, don)
if length(indices_h) == 0
continue
end
for j in indices_acceptor
acc = acceptor.atoms[j]
indices_ant = _find_antecedent(acceptor, acc)
if squared_distance(don, acc) <= (3.9^2) && length(indices_ant) != 0
for k in indices_h
hyd = donor.atoms[k]
if squared_distance(hyd, acc) <= 6.25 && angle(don, hyd, acc) >= 90.0 # 6.25 == 2.5²
for ant in indices_ant
if angle(don, acc, acceptor.atoms[ant]) >= 90.0 &&
angle(hyd, acc, acceptor.atoms[ant]) >= 90.0
return (true)
end
end
end
end
end
end
end
return (false)
end
function _hydrogenbond_don_acc(donor::PDBResidue, acceptor::PDBResidue)
if donor != acceptor
indices_donor = findall(x -> ishbonddonor(x, donor.id.name), donor.atoms)
indices_acceptor =
findall(x -> ishbondacceptor(x, acceptor.id.name), acceptor.atoms)
if length(indices_donor) != 0 && length(indices_acceptor) != 0
return (_hbond_kernel(donor, acceptor, indices_donor, indices_acceptor))
end
end
return (false)
end
"""
This function only works if there are hydrogens in the structure.
The criteria for a hydrogen bond are:
- d(Ai, Aj) < 3.9Å
- d(Ah, Aacc) < 2.5Å
- θ(Adon, Ah, Aacc) > 90°
- θ(Adon, Aacc, Aacc-antecedent) > 90°
- θ(Ah, Aacc, Aacc-antecedent) > 90°
Where Ah is the donated hydrogen atom, Adon is the hydrogen bond donor atom,
Aacc is the hydrogen bond acceptor atom and Aacc-antecednt is the atom antecedent to the
hydrogen bond acceptor atom.
"""
hydrogenbond(a::PDBResidue, b::PDBResidue) =
_hydrogenbond_don_acc(a, b) || _hydrogenbond_don_acc(b, a)
| MIToS | https://github.com/diegozea/MIToS.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.