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" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
255
# Example of vOptSpecific, for the 2LAP # when the numerical instance is read on a file, according to the LAP format # July 2017 using vOptSpecific m = load2LAP("2ap03.dat") # comment: set up the path to the file if required z1, z2, S = vSolve( m )
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
361
using vOptSpecific n = 3 C1 = [ 3 9 7 ; 16 10 6 ; 2 7 11] C2 = [16 15 6 ; 5 7 13 ; 1 2 13] myInstance = set2LAP( n , C1 , C2 ) algorithm = LAP_Przybylski2008( ) z1, z2, S = vSolve( myInstance , algorithm ) id = set2LAP(n, C1, C2) z1,z2,solutions = vSolve(id) for i = 1:length(z1) println("(" , z1[i], " | ", z2[i], ") : ", solutions[i,:]) end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
279
# Example of vOptSpecific, for the 2OSP # July 2017 using vOptSpecific n =4 p = [2, 4, 3, 1] d = [1, 2, 4, 6] id = set2OSP(n, p, d) z1, z2 , S = vSolve(id) #Default solver is OSP_Van_Wassenhove1980() for i = 1:length(S) println("(", z1[i], ", ", z2[i], ") : ", S[i]) end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
221
n = 4 p = [ 2 , 4 , 3 , 1 ] d = [ 1 , 2 , 4 , 6 ] r = [ 0 , 0 , 0 , 0 ] w = [ 1 , 1 , 1 , 1 ] using vOptSpecific id = set2OSP( n , p , d , r , w ) solver = OSP_VanWassenhove1980( ) z1, z2 , S = vSolve( id , solver )
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
121
using vOptSpecific id = load2OSP( "2osp04.dat" ) solver = OSP_VanWassenhove1980( ) z1, z2 , S = vSolve( id , solver )
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
371
# ======================================================================= # 2KP using vOptSpecific # ========================================== # instance id = load2UKP("../examples/2KP500-1A.DAT") # ========================================== z1, z2, w, solutions = vSolve(id) for i = 1:length(z1) println("(" , z1[i], " | ", z2[i], ") : ", solutions[i,:]) end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
474
# ======================================================================= # 2KP using vOptSpecific # ========================================== # instance n = 3 p1 = [ 3, 9 , 7] p2 = [16, 15 , 6] w = [ 2, 3 , 4] c = 8 # ========================================== myInstance = set2UKP( n , p1 , p2 , w , c ) algorithm = UKP_Jorge2010() z1, z2, r, x = vSolve( myInstance , algorithm ) for i = 1:length(z1) println("(" , z1[i], " | ", z2[i], ") : ", x[i,:]) end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
391
# ======================================================================= # 2UMFLP using vOptSpecific # ========================================== # instance id = load2UMFLP("../examples/F50-51.txt") # ========================================== # vOptSpecific : UMFLP_Delmee2017 Z1, Z2, Y, X, isEdge = vSolve(id) for i = 1:length(z1) println("(" , Z1[i], " | ", Z2[i], ") ") end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
690
# ======================================================================= # 2UMFLP using vOptSpecific # ========================================== # instance n = 3 # facilities m = 7 # customers ca1 = [9 27 24; 34 9 34; 11 12 17; 14 9 13; 16 26 28; 82 95 49; 20 17 9] ca2 = [34 9 34; 14 9 13; 20 17 9; 9 27 24; 11 12 17; 16 26 28; 82 95 49] cr1 = [30, 30, 30] cr2 = [12, 45, 25] # ========================================== # vOptSpecific : test 0 : UMFLP_Delmee2017 myInstance = set2UMFLP( m , n, ca1, ca2, cr1, cr2 ) algorithm = UMFLP_Delmee2017() Z1, Z2, Y, X, isEdge = vSolve( myInstance , algorithm ) for i = 1:length(z1) println("(" , Z1[i], " | ", Z2[i], ") ") end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
1292
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. struct _2UKP nSize::Int P1::Vector{Int} P2::Vector{Int} W::Vector{Int} C::Int end Base.show(io::IO, id::_2UKP) = print("Bi-Objective Knapsack Problem with $(id.nSize) variables.") set2UKP(n::Int, p1::Vector{Int}, p2::Vector{Int}, w::Vector{Int}, c::Int) = begin @assert n == length(p1) == length(p2) == length(w) _2UKP(n, p1, p2, w, c) end set2UKP(p1::Vector{Int}, p2::Vector{Int}, w::Vector{Int}, c::Int) = set2UKP(length(p1), p1, p2, w, c) struct UKPsolver solve::Function #::Function(id::_2LAP) -> ... end function vSolve(id::_2UKP, solver::UKPsolver = UKP_Jorge2010()) solver.solve(id) end function UKP_Jorge2010(output::Bool = true)::UKPsolver f = (id::_2UKP) -> begin pb = Bi01KP.problem(id.P1, id.P2, id.W, id.C) return Bi01KP.solve(pb, output) end return UKPsolver(f) end function load2UKP(fname) f = open(fname) n = parse(Int, readline(f)) P = parse(Int, readline(f)) nbC = parse(Int, readline(f)) p1 = parse.(Int, split(readline(f))) p2 = parse.(Int, split(readline(f))) w = parse.(Int, split(readline(f))) c = parse(Int, readline(f)) _2UKP(n, p1, p2, w, c) end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
2313
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. struct _2LAP nSize::Int C1::Matrix{Int} C2::Matrix{Int} end Base.show(io::IO, id::_2LAP) = print("Bi-Objective Linear Affectation Problem with $(id.nSize) variables.") set2LAP(n::Int, c1::Matrix{Int}, c2::Matrix{Int}) = begin if !(size(c1,1) == size(c1, 2) == size(c2,1) == size(c2 , 2) == n) error("dimensions incorrectes") end _2LAP(n, c1, c2) end set2LAP(c1::Matrix{Int}, c2::Matrix{Int}) = _2LAP(size(c1,1), c1, c2) struct LAPsolver parameters solve::Function #::Function(id::_2LAP) -> ... end function vSolve(id::_2LAP, solver::LAPsolver = LAP_Przybylski2008()) solver.solve(id) end function LAP_Przybylski2008()::LAPsolver f = (id::_2LAP) -> begin nSize, C1, C2 = Cint(id.nSize), vec(convert(Matrix{Cint}, id.C1)), vec(convert(Matrix{Cint}, id.C2)) p_z1,p_z2,p_solutions,p_nbsolutions = Ref{Ptr{Cint}}() , Ref{Ptr{Cint}}(), Ref{Ptr{Cint}}(), Ref{Cint}() ccall( (:solve_bilap_exact, libLAPpath), Nothing, (Ref{Cint},Ref{Cint}, Cint, Ref{Ptr{Cint}}, Ref{Ptr{Cint}}, Ref{Ptr{Cint}}, Ref{Cint}), C1, C2, nSize, p_z1, p_z2, p_solutions, p_nbsolutions) nbSol = p_nbsolutions.x z1,z2 = convert(Array{Int,1},_unsafe_wrap(Array, p_z1.x, nbSol, own=true)), convert(Array{Int,1},_unsafe_wrap(Array, p_z2.x, nbSol, own=true)) solutions = convert(Array{Int,2},reshape(_unsafe_wrap(Array, p_solutions.x, nbSol*id.nSize, own=true), (id.nSize, nbSol))) return z1, z2, permutedims(solutions, [2,1]).+1 end return LAPsolver(nothing, f) end function load2LAP(fname::AbstractString) f = open(fname) n = parse(Int,readline(f)) C1 = zeros(Int,n,n) C2 = zeros(Int,n,n) for i = 1:n @static if VERSION > v"0.7-" C1[i,:] = parse.(Int, split(chomp(readline(f)), ' ', keepempty=false)) else C1[i,:] = parse.(Int, split(chomp(readline(f)), ' ', keep=false)) end end for i=1:n @static if VERSION > v"0.7-" C2[i,:] = parse.(Int, split(chomp(readline(f)), ' ', keepempty=false)) else C2[i,:] = parse.(Int, split(chomp(readline(f)), ' ', keep=false)) end end return _2LAP(n, C1, C2) end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
4334
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. struct _2UMFLP m::Int #nbCustomers n::Int #nbFacilities A1::Matrix{Float64} #Assignment costs of clients to facilities A2::Matrix{Float64} #Assignment costs of clients to facilities R1::Vector{Float64} #Running cost of facilities R2::Vector{Float64} #Running cost of facilities end Base.show(io::IO, id::_2UMFLP) = println("Bi-Objective Facility Location Problem with $(id.m) customers and $(id.n) facilities.") set2UMFLP(m,n,A1,A2,R1,R2) = begin @assert size(A1,2) == length(R1) @assert n == size(A1, 2) == size(A2, 2) == length(R1) == length(R2) @assert m == size(A1, 1) == size(A2, 1) return _2UMFLP(m,n,A1,A2,R1,R2) end set2UMFLP(A1,A2,R1,R2) = set2UMFLP(size(A1,1), size(A1,2), A1, A2, R1, R2) struct UMFLPsolver solve::Function end function vSolve(id::_2UMFLP, solver::UMFLPsolver = UMFLP_Delmee2017()) solver.solve(id) end function load2UMFLP(fname) f = open(fname) nbC = parse(Int, readline(f)) nbF = parse(Int, readline(f)) d = readdlm(f) c_alloc1 = convert(Matrix{Float64}, d[1:nbC, 1:nbF]) c_alloc2 = convert(Matrix{Float64}, d[nbC+1:2nbC, 1:nbF]) c_loc1 = convert(Vector{Float64}, d[2nbC+1, 1:nbF]) c_loc2 = convert(Vector{Float64}, d[2nbC+2, 1:nbF]) return _2UMFLP(nbC, nbF, c_alloc1, c_alloc2, c_loc1, c_loc2) end function UMFLP_Delmee2017(; modeVerbose = false, modeUpperBound = true, modeLowerBound = true, modeImprovedLB = false, modeParam = true)::UMFLPsolver f = (id::_2UMFLP) -> begin n, m = id.n, id.m #n facilities, m customers A1, A2 = vec(permutedims(id.A1, [2,1])), vec(permutedims(id.A2, [2,1])) R1, R2 = id.R1, id.R2 p_z1,p_z2 = Ref{Ptr{Cdouble}}() ,Ref{Ptr{Cdouble}}() p_facility, p_isEdge, p_isExtremityDominated = Ref{Ptr{Cuchar}}(), Ref{Ptr{Cuchar}}(), Ref{Ptr{Cuchar}}() p_nbAlloc, p_customerAlloc, p_correspondingFac = Ref{Ptr{Cint}}(), Ref{Ptr{Cint}}(), Ref{Ptr{Cint}}() p_percentageAlloc = Ref{Ptr{Cdouble}}() nbSol = ccall((:solve, libUMFLPpath), Int, (Cint, Cint, Ref{Cdouble}, Ref{Cdouble}, Ref{Cdouble}, Ref{Cdouble}, #Inputs Cuchar, Cuchar, Cuchar, Cuchar, Cuchar, Cuchar, Cuchar, Cuchar, #Parameters # Outputs : Ref{Ptr{Cdouble}}, Ref{Ptr{Cdouble}}, #z1, z2 Ref{Ptr{Cuchar}}, Ref{Ptr{Cuchar}}, Ref{Ptr{Cuchar}},#facility, isEdge, isExtremityDominated, Ref{Ptr{Cint}}, Ref{Ptr{Cint}}, Ref{Ptr{Cint}}, Ref{Ptr{Cdouble}}), #nb Alloc, SparseMatrix : i,j,k m, n, A1, A2, R1, R2, modeVerbose, modeLowerBound, false, false, modeImprovedLB, modeUpperBound, modeParam, false, p_z1, p_z2, p_facility, p_isEdge, p_isExtremityDominated, p_nbAlloc, p_customerAlloc, p_correspondingFac, p_percentageAlloc) z1 = _unsafe_wrap(Array, p_z1.x, nbSol, own=true) z2 = _unsafe_wrap(Array, p_z2.x, nbSol, own=true) facility = convert(BitArray, _unsafe_wrap(Array, p_facility.x, nbSol*n, own=true)) facility_res = [facility[i:i+n-1] for i = 1:n:nbSol*n] isEdge = convert(BitArray, _unsafe_wrap(Array, p_isEdge.x, nbSol, own=true)) isExtremityDominated = convert(BitArray, _unsafe_wrap(Array, p_isExtremityDominated.x, nbSol, own=true)) nbAlloc = _unsafe_wrap(Array, p_nbAlloc.x, nbSol, own=true) totalAlloc = sum(nbAlloc) customerAlloc = 1 .+ _unsafe_wrap(Array, p_customerAlloc.x, totalAlloc, own=true) correspondingFac = 1 .+ _unsafe_wrap(Array, p_correspondingFac.x, totalAlloc, own=true) percentageAlloc = _unsafe_wrap(Array, p_percentageAlloc.x, totalAlloc, own=true) ind = 1 X = SparseMatrixCSC{Float64, Int}[] for i= 1:nbSol sm = sparse(customerAlloc[ind:ind+nbAlloc[i]-1], correspondingFac[ind:ind+nbAlloc[i]-1], percentageAlloc[ind:ind+nbAlloc[i]-1]) ind += nbAlloc[i] push!(X, sm) end return z1, z2, facility_res, X, isEdge, isExtremityDominated end return UMFLPsolver(f) end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
16879
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. # ========================================================================== # vOpt solver # Part of the open source prototype issued from the ANR-DFG research project # Coordinator: # [email protected] # -------------------------------------------------------------------------- # Content of this package: # Exact algorithm for solving the 1/./(sumCi , Tmax) scheduling problem # Contributor(s): # Pauline Chatellier-Bertin # Xavier Gandibleux # Version and Release date: # V0.1 - April 28, 2017 # ========================================================================== # ========================================================================== # Types and structures # ========================================================================== # Environment variables struct t_environment # for display's options: false => mute, true => verbose displayYN :: Bool # display the generation of all efficient solutions and non-dominated points displayPrint :: Bool # display all the prints to follow the algorithm's activity displayGraphic :: Bool # display the results on a graphic end # ========================================================================== # Type of a instance for the scheduling problem presented in the paper Morita et al., 2001 (FCDS) struct _2OSP n ::Int # number of tasks (positive integer value) p ::Vector{Int}# vector of processing time (positive integer values) d ::Vector{Int}# vector of due dates (non-negative integer values) r ::Vector{Int}#vector of release dates (non-negative integer values) w ::Vector{Int}# vector of weights (non-negative integer values) end Base.show(io::IO, id::_2OSP) = begin print(io, "Bi-Objective Scheduling Problem with $(id.n) tasks.") print(io, "\nProcessing times : ") ; show(IOContext(io, :limit=>true), id.p) print(io, "\nDue dates : ") ; show(IOContext(io, :limit=>true), id.d) if any(x->x!=0, id.r) print(io, "\nRelease dates : ") ; show(IOContext(io, :limit=>true), id.r) end if any(x->x!=1, id.w) print(io, "\nWeights : ") ; show(IOContext(io, :limit=>true), id.w) end end # ========================================================================== # Type of a solution for the scheduling problem presented in the paper Morita et al., 2001 (FCDS) mutable struct t_solution x ::Vector{Int}# vector of index of jobs in the solution z1::Int # performance objective 1 (integer) z2::Int # performance objective 2 (integer) end # ========================================================================== # Instance's Generators # ========================================================================== # Generate a didactic instance function generateDidacticInstance(idInstance::String)::_2OSP if idInstance == "2001" # From the paper: # Hiroyuki Morita, Xavier Gandibleux, Naoki Katoh. # Experimental feedback on biobjective permutation scheduling problems solved with a population heuristic. # Foundations of Computing and Decision Sciences 26 (1), 23-50. # http://fcds.cs.put.poznan.pl/FCDS2/PastIssues.aspx nTasks = 4 data = _2OSP(nTasks, [3, 4, 5, 6], [20, 16, 11, 5], [1, 1, 1, 1], ones(nTasks)) return data elseif idInstance == "1980_4" # From the paper: # Luc Van Wassenhove and Ludo Gelders # Solving a bicriterion scheduling problem. # European Journal of Operational Research 4 (1980) 42-48. nTasks = 4 data = _2OSP(nTasks, [2, 4, 3, 1], [1, 2, 4, 6], [1, 1, 1, 1], ones(nTasks)) # data = _2OSP(nTasks, [2, 3, 1, 2], [3, 4, 5, 6], [1, 1, 1, 1], ones(nTasks)) return data elseif idInstance == "1980_10" # From the paper: # Luc Van Wassenhove and Ludo Gelders # Solving a bicriterion scheduling problem. # European Journal of Operational Research 4 (1980) 42-48. nTasks = 10 data = _2OSP(nTasks, [9, 9, 6, 7, 2, 4, 7, 2, 7, 8], [32, 49, 7, 25, 55, 9, 54, 40, 52, 51], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], ones(nTasks)) return data end end # ========================================================================== # Generate a parameterized random instance function generateRandomInstance(nTasks::Int, pMax::Int, dMax::Int, wMax::Int)::_2OSP data = _2OSP(nTasks, rand(1:pMax, nTasks), rand(1:dMax, nTasks), rand(1:wMax, nTasks), ones(nTasks)) return data end # ========================================================================== # Generate a parameterized instance according to (Yagiura and Ibaraki, 1996) function generateHardInstance(nTasks::Int; pMax::Int = 30, LF::Float64 = 0.3, RDD::Float64 = 0.9)::_2OSP # The generator follows the rules provided in the paper: # Mutsunori Yagiura, Toshihide Ibaraki. # Genetic and local search algorithms as robust and simple optimization tools. # In "Meta-Heuristics: Theory and Applications" (I. Osman and J. Kelly Edts). Kluwer, pp.63-82, 1996. # -------------------------------------------------------------------------- # The parameters are: # nTasks : number of tasks for the scheduling problem # nTasks > 0 # pMax : upper value of p_i # 1 <= pMax <= 30 # LF : Average Lateness Factor (facteur de retard moyen) # 0.1 <= LF <= 0.5 # RDD : Relative Range of Duedate (interval relatif des dates echues) # 0.8 <= RDD <= 1.0 data_p = rand(1:pMax, nTasks) MP = sum(data_p) data_d = max.(0 , rand( floor(Int, (1-LF-RDD/2)*MP) : floor(Int, (1-LF+RDD/2)*MP) , nTasks)) data = _2OSP(nTasks, data_p, data_d, ones(Int,nTasks), ones(nTasks)) return data end # ========================================================================== # Optimization algorithmsmax.(0 , rand( floor(Int, (1-LF-RDD/2)*MP) : floor(Int, (1-LF+RDD/2)*MP) , nTasks)) # ========================================================================== # minimize the flowtime on a single machine (Smith's rule) function computeMinFlowtime(env::t_environment, data::_2OSP)::Tuple{Vector{Int}, Int} # minimise f1 : flowtime (SPT-rule) SPT = sortperm(data.p) somCi = 0 somPi = 0 c = zeros(Int,data.n) for i=1:data.n c[SPT[i]] = somPi + data.p[SPT[i]] somPi = somPi + data.p[SPT[i]] somCi = somCi + c[SPT[i]] end if env.displayPrint == true println("minimum f1 (min flowtime) = ", somCi) end return SPT, somCi end # ========================================================================== # minimize the maximum tardiness on a single machine function computeMinMaxTardiness(env::t_environment, data::_2OSP)::Tuple{Vector{Int}, Int} # minimise f2 : maximum tardiness (EDD-rule) EDD = sortperm(data.d) maxT = 0 somPi = 0 c = zeros(Int,data.n) for i=1:data.n c[EDD[i]] = somPi + data.p[EDD[i]] somPi = somPi + data.p[EDD[i]] maxT = max(maxT, c[EDD[i]]-data.d[EDD[i]]) end if env.displayPrint == true println("minimum f2 (max tardiness) = ", maxT) end return EDD, maxT end # ========================================================================== # minimize the flowtime on a single machine (modified Smith's backward scheduling rule) function smith_modifie(env::t_environment, data::_2OSP, I::Matrix{Int}, R::Int, D::Vector{Int})::Tuple{Vector{Int}, Bool} sol = zeros(Int,data.n) k = data.n trouve = true # Ensemble des taches triees par ordre lexicographique de leur processing time puis de leur due date N = [I[i,3] for i = 1:data.n] # Assignation des taches a chaque position en partant de la fin (on decremente k) # jusqu'a les avoir toutes assignees ou lorsqu'il n'y a plus de tache i respectant D_i >= R while 0 < k && trouve i = length(N) trouve = false # Parcours des taches de l'ensemble N, # en partant de celle ayant le plus grand p_i, en cas de p_i egaux celle ayant le plus grand d_i while 0 < i && !trouve # Si la tache i respecte la conditon D_i >= R if D[N[i]] >= R sol[k] = N[i] # on l'assigne à la position k R = R - data.p[N[i]] # R = R - p_i deleteat!(N, i) # on supprime i de l'ensemble N k = k-1 trouve = true else i = i-1 end end end return sol, trouve end # ========================================================================== # minimize both flowtime and maximum tardiness on a single machine function computeExactFlowtimeMaxTardiness(env::t_environment, data::_2OSP)::Vector{t_solution} # The algorithm implemented is presented in the paper: # Luc Van Wassenhove and Ludo Gelders # Solving a bicriterion scheduling problem. # European Journal of Operational Research 4 (1980) 42-48. # -------------------------------------------------------------------------- # YN est un tableau contenant tous les points non-domines YN = t_solution[] # -------------------------------------------------------------------------- # Trie des taches par ordre lexicographique # sur leur processing time puis leur due date I = [data.p data.d 1:data.n] I = @static if VERSION > v"0.7-" sortslices(I, dims=1) else sortrows(I) end # -------------------------------------------------------------------------- # Initialisation de R avec la somme des processing time R = sum(data.p) # -------------------------------------------------------------------------- # Initialisation de delta avec la somme des processing time, puis des D_i = d_i - delta delta = sum(data.p) D = [data.d[i] + delta for i = 1:data.n] # -------------------------------------------------------------------------- # Recherche d'une 1ere solution X avec les R et D_i initiaux X, existeX = smith_modifie(env, data, I, R, D) # -------------------------------------------------------------------------- # Recherche de l'ensemble des solutions efficaces while existeX sol = t_solution(X, 0, 0) evaluateSolution!(env, data, sol) # (re)evalue la solution sur les 2 objectifs push!(YN, sol) # ajoute le point non-domine a l'ensemble YN # Affichage de la solution trouvée if env.displayYN == true println("") println(" X (scheduling) = ", sol.x) println(" z1 (total flow time) = ", sol.z1) println(" z2 (maximum tardiness) = ", sol.z2) println("") end # plotEfficientGraphicY(env, sol) # Si z2 peut être amélioré on cherche de nouvelle solution sinon on arrête if sol.z2 != 0 # Mise à jour de delta et D_i delta = sol.z2 - 1 for j = 1:data.n D[j] = data.d[j] + delta end X, existeX = smith_modifie(env, data, I, R, D) else existeX = false end #if end #while return YN end # ========================================================================== # Bi-objective evaluation of a solution function evaluateSolution!(env::t_environment, data::_2OSP, sol::t_solution) # a solution here is a feasible scheduling of tasks c = 0; sol.z1 = 0; sol.z2 = 0 for i=1:data.n # completion time de la tache i c = c + data.p[sol.x[i]] # calcule la somme des c_i (total flow time)) sol.z1 = sol.z1 + c # calcule le retard maximum (maximum tardiness) sol.z2 = max(sol.z2, c - data.d[sol.x[i]] ) end end # ========================================================================== # Output on screen # ========================================================================== # display the values of the instance function displayInstance(env::t_environment, data::_2OSP) if env.displayPrint == true println("Instance :") println(" n = ", data.n) println(" p = ", data.p) println(" d = ", data.d) end end # ========================================================================== # display the points corresponding to optimal solutions for objectives separately function displayOptimal(env::t_environment, optf1::t_solution, optf2::t_solution) if env.displayPrint == true println("") println(" X optimal f1 = ", optf1.x) println(" z1 (total flowtime) = ", optf1.z1) println(" z2 (maximum tardiness) = ", optf1.z2) println("") println(" X optimal f2 = ", optf2.x) println(" z1 (total flowtime) = ", optf2.z1) println(" z2 (maximum tardiness) = ", optf2.z2) println("") println("------------------------------------------------------------------") end end # ========================================================================== # display on screen a summary of the solving process function displaySummary(env::t_environment, YN, elapsedTime) if env.displayPrint == true println("") println(" Number of non-dominated points = ", length(YN)) println(" Elapsed time (seconds) = ", elapsedTime) println("") end end # ========================================================================== # Output on graphics # ========================================================================== # initiate the legends of the graphic in the objective space # function setupGraphicY(env::t_environment, titleFigure, axisX, axisY) # if env.displayGraphic == true # title(titleFigure) # xlabel(axisX) # ylabel(axisY) # end # end # ========================================================================== # plot the optimal points corresponding to optimal solutions for both objectives separately # function plotOptimalGraphicY(env::t_environment, optf1::t_solution, optf2::t_solution) # if env.displayGraphic == true # plot(optf1.z1,optf1.z2, color="green",linestyle="",marker="D", label="opt") # plot(optf2.z1,optf2.z2, color="green",linestyle="",marker="D", label="opt") # end # end # ========================================================================== # plot one non-dominated point # function plotEfficientGraphicY(env::t_environment, sol::t_solution) # if env.displayGraphic == true # plot(sol.z1,sol.z2, color="cyan",linestyle="",marker="o", label="YN") # end # end function solveOSP(data::_2OSP, displayYN, displayPrint) # -------------------------------------------------------------------------- env = t_environment(displayYN, displayPrint, false) # display the values of the instance displayInstance(env, data) # -------------------------------------------------------------------------- # Elements pour la representation graphique de l'espace des objectifs # setupGraphicY(env, "Y (objective space)", "z1 (total flow time)", "z2 (Maximum tardiness)") # -------------------------------------------------------------------------- # Initialise le timer tstart = time_ns() # -------------------------------------------------------------------------- # Calcul des solutions optimales pour les 2 objectifs pris separement optf1 = t_solution(zeros(data.n), 0, 0) optf1.x, optf1.z1 = computeMinFlowtime(env, data) evaluateSolution!(env, data, optf1) # (re)evalue la solution sur les 2 objectifs optf2 = t_solution(zeros(data.n), 0, 0) optf2.x, optf2.z2 = computeMinMaxTardiness(env, data) evaluateSolution!(env, data, optf2) # (re)evalue la solution sur les 2 objectifs # -------------------------------------------------------------------------- # plot on graphic the optimal points corresponding to optimal solutions for both objectives separately # plotOptimalGraphicY(env, optf1, optf2) # -------------------------------------------------------------------------- # display on screen the optimal solutions for both objectives separately displayOptimal(env, optf1, optf2) # -------------------------------------------------------------------------- # Calcul des points non-domines pour les 2 objectifs pris simultanement YN = computeExactFlowtimeMaxTardiness(env, data) # Releve le timer et donne le temps utilise par la resolution elapsedTime = (time_ns() - tstart) * 1e-9 # -------------------------------------------------------------------------- # display on screen a summary of the solving process displaySummary(env, YN, elapsedTime) return map(x -> x.z1, YN), map(x -> x.z2, YN), map(x -> x.x, YN) # ========================================================================== end function set2OSP(n::Int, p::Vector{Int}, d::Vector{Int}, r::Vector{Int}=zeros(Int,n), w::Vector{Int}=ones(Int,n)) @assert n==length(p)==length(d)==length(w) @assert all(x->x>0, p) @assert all(x->x>=0, d) @assert all(x->x>=0, r) @assert all(x->x>=0, w) _2OSP(n,p,d,r,w) end set2OSP(p::Vector{Int},d::Vector{Int},r::Vector{Int}=zeros(Int,length(p)),w::Vector{Int}=ones(Int, length(p))) = set2OSP(length(p),p,d,r,w) struct OSPSolver solve::Function end function OSP_VanWassenhove1980(;displayYN=false, displayPrint=false)::OSPSolver return OSPSolver((id::_2OSP) -> solveOSP(id,displayYN,displayPrint)) end function vSolve(id::_2OSP, solver::OSPSolver = OSP_VanWassenhove1980()) solver.solve(id) end function load2OSP(fname::AbstractString) f = open(fname) n = parse(Int, readline(f)) data = convert(Matrix{Int}, readdlm(f)) p = data[1,:] d = data[2,:] r = data[3,:] w = data[4,:] close(f) return set2OSP(p,d,r,w) end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
1097
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. module vOptSpecific const libLAPpath = joinpath(@__DIR__, "..", "deps", "libLAP.so") const libUMFLPpath = joinpath(@__DIR__, "..", "deps", "libUMFLP.so") const libcomboPath = joinpath(@__DIR__,"..","deps","libcombo.so") include("LAP.jl") include("UMFLP.jl") include("jMOScheduling.jl") include("Bi01KP/Bi01KP.jl") include("KP.jl") @static if VERSION > v"0.7-" using DelimitedFiles using SparseArrays _unsafe_wrap(Atype, p, dims ; own=false) = unsafe_wrap(Atype, p, dims, own=own) end @static if VERSION < v"0.7-" _unsafe_wrap(Atype, p, dims ; own=false) = unsafe_wrap(Atype, p, dims, own) end export vSolve, load2LAP, set2LAP, LAP_Przybylski2008, load2OSP, set2OSP, OSP_VanWassenhove1980, generateHardInstance, load2UMFLP, set2UMFLP, UMFLP_Delmee2017, load2UKP, set2UKP, UKP_Jorge2010 __init__() = (!isfile(libLAPpath) || !isfile(libUMFLPpath)) || !isfile(libcomboPath) && warn("""Some libraries are missing, run Pkg.build("vOptSpecific")""") end # module
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
2135
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. module Bi01KP using DataStructures include("problem.jl") #Defines problems and reduce_problem!() include("mono_problem.jl") #Defines mono_problems include("solution.jl") #Defines solutions include("mono_solution.jl") #Defines mono_solutions include("combo.jl") #API to call Combo to solve mono-objective problems include("first_phase.jl") #first_phase(pb::problem) -> XSE1m include("vertex.jl") #Defines vertices include("arc.jl") #Defines arcs, paths(arclists) and partitions include("second_phase.jl") include("graph.jl") # include("BoundSetReduction.jl") const libcomboPath = joinpath(@__DIR__,"..","..","deps","libcombo.so") function solve(pb::problem, output=true) reduce_problem!(pb, output) XSE1m = first_phase(pb) if length(XSE1m) == 1 X = XSE1m else X = second_phase(XSE1m, output) end z1, z2 = map(obj_1, X), map(obj_2, X) w = map(weight, X) x = map(full_variable_vector, X) z1, z2, w, x end function parseKP(fname::AbstractString) if fname[end-2:end] == "KNP" f = open(fname) while !(readline(f)[1]=='n') end readline(f) x = readdlm(f) p1 = convert(Vector{Int},x[1:findfirst(x[:,3], "")-1 , 3]) p2 = convert(Vector{Int},x[1:findfirst(x[:,4], "")-1 , 4]) w = convert(Vector{Int},x[1:findfirst(x[:,2], "")-1 , 2]) c = Int(x[findfirst(x[:,1], "W"), 2]) elseif any(contains.(fname, ["TA","TB","TC","TD"])) f = open(fname) x = readdlm(f, skipstart=4) p1 = convert(Vector{Int},x[1:findfirst(x[:,3], "")-1 , 3]) p2 = convert(Vector{Int},x[1:findfirst(x[:,4], "")-1 , 4]) w = convert(Vector{Int},x[1:findfirst(x[:,2], "")-1 , 2]) c = Int(x[findfirst(x[:,1], "W"), 2]) else f = open(fname) x = convert(Array{Int},readdlm(f, skipstart=11))[:,1] close(f) n = (length(x)-1) ÷ 3 c = x[end] p1 = x[1:n] p2 = x[n+1:2n] w = x[2n+1:3n] end return problem(p1,p2,w,c) end end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
2868
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. const Arc = Pair{vertex,vertex} struct List{T} head::T tail::List{T} List{T}() where T = new{T}() List(a, l::List{T}) where T = new{T}(a, l) end List(T) = List{T}() List() = List(Any) Base.isempty(x::List) = !isdefined(x,2) head(a::List) = a.head tail(a::List) = a.tail @static if VERSION > v"0.7-" function Base.iterate(l::List, state::List = l) isempty(state) && return nothing state.head, state.tail end end @static if VERSION < v"0.7-" Base.start(l::List) = l Base.done(l::List, state::List) = isempty(state) Base.next(l::List, state::List) = (state.head, state.tail) end function reverse(l::List{T}) where T l2 = List(T) for h in l l2 = List(h, l2) end l2 end struct Partition v::vertex arcs::List{Arc} nbArcs::UInt16 zλ::Int z1::Int z2::Int end <(a::Partition, b::Partition) = a.zλ < b.zλ || a.zλ == b.zλ && a.nbArcs < b.nbArcs #Used to sort the binary heap of Partitions Base.isless(a::Partition, b::Partition) = a.zλ < b.zλ || a.zλ == b.zλ && a.nbArcs < b.nbArcs #Used to sort the binary heap of Partitions # Base.isless(a::Partition, b::Partition) = a.zλ < b.zλ || (a.zλ == b.zλ && a.z1 <= b.z1 && a.z2 <= b.z2) #Used to sort the binary heap of Partitions # <(a::Partition, b::Partition) = a.zλ < b.zλ || (a.zλ == b.zλ && a.z1 <= b.z1 && a.z2 <= b.z2) #Used to sort the binary heap of Partitions zλ(p::Partition) = p.zλ z1(p::Partition) = p.z1 z2(p::Partition) = p.z2 Partition(v::vertex) = Partition(v, List(Arc), 0, v.zλ, v.z1, v.z2) #Reconstruct a solution from a Partition function solution(l, pb::problem, mono_pb::mono_problem) vars = falses(size(pb)) obj1, obj2, w = mono_pb.min_profit_1, mono_pb.min_profit_2, mono_pb.ω #TODO : #variables in l are sorted by decreasing profit of the mono_problem, #the first pass should be doable in O(n) instead of O(n^2) #Variables in C1 could be sorted after the reduction to make the second pass in O(n) too for i = 1:length(l) if l[i] ind_var = mono_pb.variables[i] vars[findfirst(isequal(ind_var), pb.variables)] = true obj1 += pb.p1[ind_var] obj2 += pb.p2[ind_var] w += pb.w[ind_var] end end for v in mono_pb.C1 vars[findfirst(isequal(v), pb.variables)] = true end res = solution(pb, vars, obj1 - pb.min_profit_1, obj2 - pb.min_profit_2, w - pb.ω) # @assert dot(pb.p1, res.x, pb.variables) + pb.min_profit_1 == obj_1(res) # @assert dot(pb.p2, res.x, pb.variables) + pb.min_profit_2 == obj_2(res) return res end zλ(s, t, mpb) = s.w == t.w ? 0 : mpb.p[s.i] z1(s, t, pb) = s.w == t.w ? 0 : pb.p1[s.i] z2(s, t, pb) = s.w == t.w ? 0 : pb.p2[s.i] weight(s, t) = t.w - s.w
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
1485
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. struct combo_item p::Clonglong w::Clonglong x::Cint i::Cint end function solve_mono(pb::mono_problem,lb=0,ub=0) if isempty(variables(pb)) return mono_solution(pb, BitArray(0), 0, 0) end #If all items fit in the KP (which happens sometimes when doing variable reductions), #combo throws a ReadOnlyMemoryError() if sum(x -> pb.w[x], variables(pb)) + pb.ω <= pb.c return mono_solution(pb, trues(size(pb)), sum(x -> pb.p[x], variables(pb)), sum(x -> pb.w[x], variables(pb))) end #@assert all(x -> x>=0, pb.p) "$(pb.p)" #@assert all(x -> x>0, pb.w) items = [combo_item(pb.p[j], pb.w[j], 0, i) for (i,j) in enumerate(variables(pb))] z = ccall((:solve,libcomboPath), Clonglong, (Ref{combo_item}, Cint, Clonglong, Clonglong, Clonglong), items, size(pb), pb.c - pb.ω, lb, ub) # #@assert lb <= z <= ub vars = falses(size(pb)) for it in items it.x==1 && (vars[it.i]=true) end #If combo can't find a solution better than the lower bound, #it returns z = lb with an empty solution... #in that case, we recalculate z if z == lb z = dot(pb.p, vars, pb.variables) end #@assert z == dot(pb.p, vars, pb.variables) "$z != $(dot(pb.p, vars, pb.variables)) $lb $ub" return mono_solution(pb, vars, z, dot(pb.w, vars, pb.variables)) end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
1103
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. function solveWeightedSum(pb::problem, λ1::Int, λ2::Int, lb::Int=0) mono_p = mono_problem(pb, λ1, λ2, false) mono_s = solve_mono(mono_p,lb) return solution(mono_s) end #Calcul de X_SE1m par dichotomie function solveRecursion(xr::solution, xs::solution, X::Vector{solution}) λ1 = obj_2(xr) - obj_2(xs) λ2 = obj_1(xs) - obj_1(xr) lb = λ1*xr.obj_1 + λ2*xr.obj_2 x = solveWeightedSum(xr.pb, λ1, λ2, lb) if λ1*x.obj_1 + λ2*x.obj_2 > lb push!(X, x) solveRecursion(xr, x, X) solveRecursion(x, xs, X) end nothing end function first_phase(pb::problem) xr = solveWeightedSum(pb, 0, 1) xs = solveWeightedSum(pb, 1, 0) X = [xr,xs] solveRecursion(xr, xs, X) sort!(X, by = obj, lt = isless, alg=QuickSort) del_inds = Int[] for i = 1:length(X)-1 X[i] >= X[i+1] && push!(del_inds, i+1) X[i] <= X[i+1] && push!(del_inds, i) end deleteat!(X, del_inds) return unique(obj, X) end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
3607
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. struct graph pb::problem mono_pb::mono_problem layer::Vector{vertex} #last layer of the graph end Base.isempty(g::graph) = isempty(g.layer) function build_graph(Δ::Triangle, output::Bool) xr = Δ.xr xs = Δ.xs pb = xr.pb λ1, λ2 = Δ.λ mono_pb = mono_problem(pb, λ1, λ2) # @assert obj(solve_mono(mono_pb)) == Δ.ub "$xr => $xs isn't a supporting edge of Y ($(solution(pb,solve_mono(mono_pb))))" reduce!(mono_pb, Δ, output) size(mono_pb) == 0 && return graph(pb, mono_pb, vertex[]) s = source(mono_pb) current_layer = [s] for l = 1:size(mono_pb) # @assert mono_pb.variables[l] == current_layer[1].i # @assert l == current_layer[1].layer previous_layer = current_layer current_layer = vertex[] #Adds all vertices in the next layer obtained without picking the object for v in previous_layer if relax(v, mono_pb) >= Δ.lb #&& relax_z1(v, sortperm_z1) >= obj_1(xr) || relax_z2(v, sortperm_z2) >= obj_2(xs) push!(current_layer, vertex_skip(v, mono_pb)) end end #Adds all vertices in the next layer obtained by picking the object (if possible) for v in previous_layer let wplus1 = v.w + pb.w[v.i] #Calculate the weight of the solution when we pick item i wplus1 > mono_pb.c && continue #If the solution is too heavy for the knapsack, skip it. child = vertex_keep(v, mono_pb) #else, create the vertex # Check if a node with that weight already exists so we can merge them. # The nodes in the layer are sorted by their weight so we can use a dichotomic search range = searchsorted(current_layer, wplus1, lt = weight_lt) # (weight_lt compares a vertex to an Integer weight) if isempty(range) # ∄ node with that weight, we can add it (at the right place) to the current layer insert!(current_layer, range.start , child) else # a node with this weight already exists, we merge them merge!(current_layer[range.start], child) end end end end return graph(pb, mono_pb, current_layer) end #Calculates the relaxation for the combined problem function relax(v::vertex, mpb::mono_problem) #we assume the items are already sorted by utility #we only consider picking items which come after v.i vars = view(variables(mpb), v.layer+1:size(mpb))::SubArray{Int} zλ= v.zλ w = v.w c = mpb.c i = 1 while i <= length(vars) && w + mpb.w[vars[i]] <= c var = vars[i] w += mpb.w[var] zλ += mpb.p[var] i += 1 end if i <= length(vars) && length(vars) > 1 cleft = mpb.c - w if i == 1 varplus1 = vars[i+1] zλ += floor(Int, cleft * mpb.p[varplus1]/mpb.w[varplus1]) elseif i == length(vars) varminus1 = vars[i-1] zλ += floor(Int, mpb.p[var] - (mpb.w[var] - cleft)*(mpb.p[varminus1]/mpb.w[varminus1])) else var = vars[i] varplus1 = vars[i+1] varminus1 = vars[i-1] U0 = zλ + floor(Int, cleft * mpb.p[varplus1]/mpb.w[varplus1]) U1 = zλ + floor(Int, mpb.p[var] - (mpb.w[var] - cleft)*(mpb.p[varminus1]/mpb.w[varminus1])) zλ = max(U0,U1) end end return zλ end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
7227
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. mutable struct mono_problem pb::problem psize::Int p::Vector{Int} #combined profit vector p1::Vector{Int} p2::Vector{Int} w::Vector{Int} c::Int C0::Vector{Int} #Variables that have been fixed to 0 for the mono_problem only C1::Vector{Int} #Variables that have been fixed to 1 for the mono_problem only ω::Int #Minimum weight min_profit_λ::Int min_profit_1::Int min_profit_2::Int eff::Vector{Float64} variables::Vector{Int} #Order of variables with decreasing utiliy wrt to the combined objective ub_z1_i0::Vector{Int} #Upper bound on z1 for each variable i fixed to 0 ub_z1_i1::Vector{Int} #Upper bound on z1 for each variable i fixed to 1 ub_z2_i0::Vector{Int} #Upper bound on z2 for each variable i fixed to 0 ub_z2_i1::Vector{Int} #Upper bound on z2 for each variable i fixed to 1 end #Printer Base.show(io::IO, pb::mono_problem) = print(io, "Mono-objective Knapsack Problem with $(size(pb))($(pb.psize)) variables : \tω=$(pb.ω)\n\tc=$(pb.c)\n\tvars=$(pb.variables)\n\tp=$(pb.p[pb.variables])\n\tw=$(pb.w[pb.variables])") size(pb::mono_problem)::Int = length(pb.variables) variables(pb::mono_problem)::Vector{Int} = pb.variables function fix!(mp::mono_problem, C0::Vector{Int}, C1::Vector{Int}) for i in C0 v = mp.variables[i] push!(mp.C0, v) end for i in C1 v = mp.variables[i] push!(mp.C1, v) mp.min_profit_λ += mp.p[v] mp.min_profit_1 += mp.p1[v] mp.min_profit_2 += mp.p2[v] mp.ω += mp.w[v] end deleteat!(mp.variables, sort(vcat(C0,C1))) end #Constructor from a bi_problem function mono_problem(p::problem, λ1::Int, λ2::Int, calculate_efficiency::Bool = true) profits = λ1*p.p1 + λ2*p.p2 eff = calculate_efficiency ? profits ./ p.w : Float64[] vars = variables(p)[:] calculate_efficiency && sort!(vars, by = x -> eff[x], rev=true) return mono_problem( p, size(p), #Number of variables profits, #Combined profit vector p.p1, p.p2, p.w, #Weight vector p.c, #Capacity Int[], #C0 Int[], #C1 p.ω, #ω λ1*p.min_profit_1 + λ2*p.min_profit_2,#min_profit p.min_profit_1, p.min_profit_2, eff, #Utility vector vars, #variables p.ub_z1_i0, p.ub_z1_i1, p.ub_z2_i0, p.ub_z2_i1 ) end function reduce!(mp::mono_problem, Δ, output::Bool) #Here, C0 and C1 will contain not the variables to be fixed to 0/1 but their indices in mp.variables #It makes their removal faster : we don't have to use findfirst(...) to find the values we have to remove from mp.variables lb_zλ, lb_z1, lb_z2 = Δ.lb, obj_1(Δ.xr), obj_2(Δ.xs) vars = variables(mp) ### Reduction with lb_z1 C0,C1 = Vector{Int}(), Vector{Int}() for i = 1:size(mp) if mp.ub_z1_i0[vars[i]] <= lb_z1 push!(C1, i) elseif mp.ub_z1_i1[vars[i]] <= lb_z1 push!(C0, i) end end ##@assert isempty(intersect(C1,C0)) # @show C0 # @show C1 fix!(mp, C0, C1) empty!(C0) ; empty!(C1) #Reduction with lb_z2 for i = 1:size(mp) if mp.ub_z2_i0[vars[i]] <= lb_z2 push!(C1, i) end if mp.ub_z2_i1[vars[i]] <= lb_z2 push!(C0, i) end end ##@assert isempty(intersect(C1,C0)) fix!(mp, C0, C1) empty!(C0) ; empty!(C1) #TODO : find the break_item and only calculate C0 for variables before the break_item and C1 for those after. #Reduction with lb_zλ for i=1:size(mp) #Calculate relaxation with variable i set to 0 w = mp.ω ub = mp.min_profit_λ j = 1 while j <= size(mp) && (i==j || w + mp.w[vars[j]] <= mp.c) v = vars[j] if j != i w += mp.w[v] ub += mp.p[v] end j += 1 end if j <= size(mp) v = vars[j] cleft = mp.c - w if j+1 == i || j == size(mp) if j+2 <= size(mp) U0 = ub + floor(Int, cleft * mp.p[vars[j+2]]/mp.w[vars[j+2]]) else U0 = ub end else U0 = ub + floor(Int, cleft * mp.p[vars[j+1]]/mp.w[vars[j+1]]) end if j-1 == i || j == 1 if j-2 >= 1 U1 = ub + floor(Int, mp.p[v] - (mp.w[v] - cleft)*(mp.p[vars[j-2]]/mp.w[vars[j-2]])) else U1 = 0 end else U1 = ub + floor(Int, mp.p[v] - (mp.w[v] - cleft)*(mp.p[vars[j-1]]/mp.w[vars[j-1]])) end ub = max(U0,U1) end if ub < lb_zλ push!(C1, i) end end for i=1:size(mp) #Calculate relaxation with variable i set to 1 w = mp.ω + mp.w[vars[i]] ub = mp.min_profit_λ + mp.p[vars[i]] j = 1 while j <= size(mp) && (i==j || w + mp.w[vars[j]] <= mp.c) v = vars[j] if j != i w += mp.w[v] ub += mp.p[v] end j += 1 end if j <= size(mp) v = vars[j] cleft = mp.c - w if j+1 == i || j == size(mp) if j+2 <= size(mp) U0 = ub + floor(Int, cleft * mp.p[vars[j+2]]/mp.w[vars[j+2]]) else U0 = ub end else U0 = ub + floor(Int, cleft * mp.p[vars[j+1]]/mp.w[vars[j+1]]) end if j-1==i || j == 1 if j-2 >= 1 U1 = ub + floor(Int, mp.p[v] - (mp.w[v] - cleft)*(mp.p[vars[j-2]]/mp.w[vars[j-2]])) else U1 = 0 end else U1 = ub + floor(Int, mp.p[v] - (mp.w[v] - cleft)*(mp.p[vars[j-1]]/mp.w[vars[j-1]])) end ub = max(U0,U1) end if ub < lb_zλ push!(C0, i) end end fix!(mp, C0, C1) reduce_again!(mp, Δ) output && mp.psize != size(mp) && println("Problem reduced from $(mp.psize) to $(size(mp)) variables") nothing end function reduce_again!(mp::mono_problem, Δ) size0 = size(mp) lb_zλ = Δ.lb vars = variables(mp) C0,C1 = Vector{Int}(), Vector{Int}() M = 500000 for i = 1:length(vars) v = vars[i] p_old = mp.p[v] ; mp.p[v] = 0 #fix_0!(p, v) ms = solve_mono(mp) if obj(ms) < lb_zλ push!(C1, i) end mp.p[v] = p_old end for i = 1:length(vars) v = vars[i] if mp.ω + mp.w[v] > mp.c push!(C0, i) continue end mp.p[v] += M ; mp.min_profit_λ -= M # fix_1!(mp, v) ms = solve_mono(mp) if obj(ms) < lb_zλ push!(C0, i) end mp.p[v] -= M ; mp.min_profit_λ += M #unfix_0 end fix!(mp, C0, C1) return nothing end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
1143
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. struct mono_solution mpb::mono_problem x::BitArray obj::Int weight::Int end #Constructur : empty solution # mono_solution(p::mono_problem) = mono_solution(p, falses(size(p)), 0, 0) obj(s::mono_solution) = s.obj + s.mpb.min_profit_λ weight(s::mono_solution) = s.weight + s.mpb.ω #Print function Base.show(io::IO, s::mono_solution) = print(io, "mono_sol(p=$(obj(s)), w=$(weight(s)))") #Convert a mono_solution to a solution solution(s::mono_solution) = begin #@assert dot(s.pb.w, s.x, s.pb.variables) + s.pb.ω == weight(s) p = s.mpb.pb C1 = s.mpb.C1 x = falses(size(p)) for (i,v) = enumerate(s.mpb.variables) s.x[i] && (x[findfirst(isequal(v), p.variables)] = true) end for v in s.mpb.C1 x[findfirst(isequal(v), p.variables)] = true end res = solution( p, x, dot(p.p1, x, p.variables), dot(p.p2, x, p.variables), weight(s) - p.ω) #@assert weight(res) == dot(p.w, res.x, p.variables) + p.ω return res end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
9004
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. mutable struct problem psize::Int #Number of variables p1::Vector{Int} #Objective vector 1 p2::Vector{Int} #Objective vector 1 w::Vector{Int} #Weights vector c::Int #Knapsack Capacity C0::Vector{Int} #Indices of variables always set to 0 C1::Vector{Int} #Indices of variables always set to 1 ω::Int #Weight of items always picked min_profit_1::Int #Guaranteed profit on first objective by picking the items in C1 min_profit_2::Int #Guaranteed profit on second objective by picking the items in C1 eff1::Vector{Float64} #Variables efficiency wrt objective 1 eff2::Vector{Float64} #Variables efficiency wrt objective 2 variables::Vector{Int} #Remaining variables of the problem after reduction ub_z1_i0::Vector{Int} #Upper bound on z1 for each variable i fixed to 0 ub_z1_i1::Vector{Int} #Upper bound on z1 for each variable i fixed to 1 ub_z2_i0::Vector{Int} #Upper bound on z2 for each variable i fixed to 0 ub_z2_i1::Vector{Int} #Upper bound on z2 for each variable i fixed to 1 end Base.copy(pb::problem) = problem(pb.psize, pb.p1, pb.p2, pb.w, pb.c, copy(pb.C0), copy(pb.C1), pb.ω, pb.min_profit_1, pb.min_profit_2, pb.eff1, pb.eff2, copy(pb.variables), pb.ub_z1_i0, pb.ub_z1_i1, pb.ub_z2_i0, pb.ub_z2_i1) #Printer Base.show(io::IO, pb::problem) = print(io, "Bi-objective Knapsack Problem with $(size(pb))($(pb.psize)) variables :\n p1=$(pb.p1)\np2=$(pb.p2)\nw=$(pb.w)\nc=$(pb.c)\nC0=$(pb.C0)\nC1=$(pb.C1)\n") #Constructor problem(p1, p2, w, c) = problem(length(w), p1, p2, w, c, Int[], Int[], 0, 0, 0, p1 ./ w, p2 ./ w, collect(1:length(w)), zeros(Int, length(w)), zeros(Int, length(w)), zeros(Int, length(w)), zeros(Int, length(w))) size(pb::problem)::Int = length(pb.variables) variables(pb::problem)::Vector{Int} = pb.variables function reduce_problem!(pb::problem, output::Bool) n = size(pb) #Compute Pref(vi) and Dom(vi) ∀i = 1..n Pref = [Int[] for i = 1:size(pb)] Dom = [Int[] for i = 1:size(pb)] for i = 1:n-1, j = i+1:n i1, i2, j1, j2 = pb.p1[i], pb.p2[i], pb.p1[j], pb.p2[j] wi, wj = pb.w[i], pb.w[j] if ((i1 > j1 && i2 >= j2) || (i1 >= j1 && i2 > j2)) && wi <= wj push!(Pref[j], i) push!(Dom[i], j) end if ((j1 > i1 && j2 >= i2) || (j1 >= i1 && j2 > i2)) && wj <= wi push!(Pref[i], j) push!(Dom[j], i) end end #Compute LB and UB : bounds on the cardinality of an efficient solution c = pb.c w = sort(pb.w, rev=true) sum_weight = 0 LB = 0 while LB < n && w[LB+1] + sum_weight <= c LB += 1 sum_weight += w[LB] end reverse!(w) sum_weight = 0 UB = 0 while UB < n && w[UB+1] + sum_weight <= c UB += 1 sum_weight += w[UB] end #Compute C0 and C1 : sets of variables always set to 0 / 1 in an efficient solution C0 = pb.C0 C1 = pb.C1 for i = 1:n if length(Pref[i]) >= UB push!(C0, i) elseif n - length(Dom[i]) <= LB push!(C1, i) elseif !isempty(Pref[i]) && sum(j -> pb.w[j], Pref[i]) + pb.w[i] > c push!(C0, i) elseif sum(j -> j ∉ Dom[i] ? pb.w[j] : 0 , 1:n) <= c push!(C1, i) end end if !isempty(C1) pb.ω = sum(i -> pb.w[i], C1) pb.min_profit_1 = sum(i -> pb.p1[i], C1) pb.min_profit_2 = sum(i -> pb.p2[i], C1) end deleteat!(pb.variables, sort(union(C0,C1))) if output && pb.psize != size(pb) println("Global reduction from $(pb.psize) to $(size(pb)) variables") end calculate_upper_bounds!(pb) nothing end function calculate_upper_bounds!(pb::problem) vars = sort(variables(pb), by = v -> pb.eff1[v], rev=true) for i=1:size(pb) #Calculate relaxation with variable i set to 0 w = pb.ω ub = pb.min_profit_1 j = 1 while j <= size(pb) && (i==j || w + pb.w[vars[j]] <= pb.c) v = vars[j] if j != i w += pb.w[v] ub += pb.p1[v] end j += 1 end if j <= size(pb) v = vars[j] cleft = pb.c - w if j+1 == i || j == size(pb) if j+2 <= size(pb) U0 = ub + floor(Int, cleft * pb.p1[vars[j+2]]/pb.w[vars[j+2]]) else U0 = ub end else U0 = ub + floor(Int, cleft * pb.p1[vars[j+1]]/pb.w[vars[j+1]]) end if j-1==i || j == 1 if j-2 >= 1 U1 = ub + floor(Int, pb.p1[v] - (pb.w[v] - cleft)*(pb.p1[vars[j-2]]/pb.w[vars[j-2]])) else U1 = 0 end else U1 = ub + floor(Int, pb.p1[v] - (pb.w[v] - cleft)*(pb.p1[vars[j-1]]/pb.w[vars[j-1]])) end ub = max(U0,U1) end pb.ub_z1_i0[vars[i]] = ub end for i=1:size(pb) #Calculate relaxation with variable i set to 1 w = pb.ω + pb.w[vars[i]] ub = pb.min_profit_1 + pb.p1[vars[i]] j = 1 while j <= size(pb) && (i==j || w + pb.w[vars[j]] <= pb.c) v = vars[j] if j != i w += pb.w[v] ub += pb.p1[v] end j += 1 end if j <= size(pb) v = vars[j] cleft = pb.c - w if j+1 == i || j == size(pb) if j+2 <= size(pb) U0 = ub + floor(Int, cleft * pb.p1[vars[j+2]]/pb.w[vars[j+2]]) else U0 = ub end else U0 = ub + floor(Int, cleft * pb.p1[vars[j+1]]/pb.w[vars[j+1]]) end if j-1==i || j == 1 if j-2 >= 1 U1 = ub + floor(Int, pb.p1[v] - (pb.w[v] - cleft)*(pb.p1[vars[j-2]]/pb.w[vars[j-2]])) else U1 = 0 end else U1 = ub + floor(Int, pb.p1[v] - (pb.w[v] - cleft)*(pb.p1[vars[j-1]]/pb.w[vars[j-1]])) end ub = max(U0,U1) end pb.ub_z1_i1[vars[i]] = ub end vars = sort(variables(pb), by = v -> pb.eff2[v], rev=true) for i=1:size(pb) #Calculate relaxation with variable i set to 0 w = pb.ω ub = pb.min_profit_2 j = 1 ; v = vars[j] j = 1 while j <= size(pb) && (i==j || w + pb.w[vars[j]] <= pb.c) v = vars[j] if j != i w += pb.w[v] ub += pb.p2[v] end j += 1 end if j <= size(pb) v = vars[j] cleft = pb.c - w if j+1 == i || j == size(pb) if j+2 <= size(pb) U0 = ub + floor(Int, cleft * pb.p2[vars[j+2]]/pb.w[vars[j+2]]) else U0 = ub end else U0 = ub + floor(Int, cleft * pb.p2[vars[j+1]]/pb.w[vars[j+1]]) end if j-1==i || j == 1 if j-2 >= 1 U1 = ub + floor(Int, pb.p2[v] - (pb.w[v] - cleft)*(pb.p2[vars[j-2]]/pb.w[vars[j-2]])) else U1 = 0 end else U1 = ub + floor(Int, pb.p2[v] - (pb.w[v] - cleft)*(pb.p2[vars[j-1]]/pb.w[vars[j-1]])) end ub = max(U0,U1) end pb.ub_z2_i0[vars[i]] = ub end for i=1:size(pb) #Calculate relaxation with variable i set to 1 w = pb.ω + pb.w[vars[i]] ub = pb.min_profit_2 + pb.p2[vars[i]] j = 1 while j <= size(pb) && (i==j || w + pb.w[vars[j]] <= pb.c) v = vars[j] if j != i w += pb.w[v] ub += pb.p2[v] end j += 1 end if j <= size(pb) v = vars[j] cleft = pb.c - w if j+1 == i || j == size(pb) if j+2 <= size(pb) U0 = ub + floor(Int, cleft * pb.p2[vars[j+2]]/pb.w[vars[j+2]]) else U0 = ub end else U0 = ub + floor(Int, cleft * pb.p2[vars[j+1]]/pb.w[vars[j+1]]) end if j-1==i || j == 1 if j-2 >= 1 U1 = ub + floor(Int, pb.p2[v] - (pb.w[v] - cleft)*(pb.p2[vars[j-2]]/pb.w[vars[j-2]])) else U1 = 0 end else U1 = ub + floor(Int, pb.p2[v] - (pb.w[v] - cleft)*(pb.p2[vars[j-1]]/pb.w[vars[j-1]])) end ub = max(U0,U1) end pb.ub_z2_i1[vars[i]] = ub end end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
7011
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. mutable struct Triangle xr::solution xs::solution XΔ::Vector{solution} λ::Tuple{Int,Int} ub::Int lb::Int pending::Bool end Triangle(xr::solution,xs::solution) = begin λ1,λ2 = obj_2(xr) - obj_2(xs), obj_1(xs) - obj_1(xr) Triangle(xr,xs,solution[xr,xs],(λ1,λ2),λ1*obj_1(xr) + λ2*obj_2(xr),λ1*obj_1(xr) + λ2*obj_2(xs), true) end #const PartitionHeap = BinaryHeap{Partition, DataStructures.GreaterThan} # update 22-07-2021 const PartitionHeap = BinaryMaxHeap{Partition} #Returns the partition p in τ maximizing p.zλ function parent_partition!(τ::PartitionHeap) pop!(τ) end function clean!(τ::PartitionHeap, lb::Int) deleteat!(τ.valtree, findall(elt -> elt.zλ < lb, τ.valtree)) heapify!(τ.valtree, Base.Order.Reverse) # @assert all(top(τ).zλ .>= zλ.(τ.valtree[2:end])) end #constructs the optimal path for a partition p=<v, U> #new partitions are added to τ if their value for zλ is >= lb function const_Path_New_Partition(p::Partition, τ::PartitionHeap, lb::Int, mono_pb::mono_problem)::BitArray t = p.v #The vertex from which we're constructing the path U = p.arcs #The imposed arcs U_prime = reverse(U) ϕ = falses(size(mono_pb)) #The path that will be returned while t.layer != 1 if !isempty(U_prime) && last(head(U_prime)) == t #if an arc (s=>t) is imposed s = first(head(U_prime)) U_prime = tail(U_prime) elseif inner_degree(t) == 1 #elseif the vertex only has one parent s = parent(t) else s1,s2 = parents(t) #(s => t) is the optimal arc, (s' => t) is the secondary arc, not imposed yet if s2.zλ + zλ(s2, t, mono_pb) == t.zλ s = s2 s_prime = s1 else s = s1 s_prime = s2 end if isempty(U_prime) #Create a partition imposing the secondary arc (s' => t) ϕ_zλ = zλ(p) - zλ(t) + zλ(s_prime) + zλ(s_prime, t, mono_pb) if ϕ_zλ >= lb #Add it only if it's interesting ϕ_z1 = z1(p) - z1(t) + z1(s_prime) + z1(s_prime, t, mono_pb) ϕ_z2 = z2(p) - z2(t) + z2(s_prime) + z2(s_prime, t, mono_pb) #@assert ϕ_zλ <= p.zλ ♇ = Partition(p.v, List(s_prime=>t, U), p.nbArcs+1, ϕ_zλ, ϕ_z1, ϕ_z2 ) push!(τ,♇) end end end #If the weight of the arc isn't 0 (-> if we picked the item) if weight(s, t) != 0 ϕ[s.layer] = true #We add s.i to the list of items picked end t = s end ϕ end in_triangle(y::Tuple{Int,Int}, yr::Tuple{Int,Int}, ys::Tuple{Int,Int}) = yr[1] <= y[1] <= ys[1] && ys[2] <= y[2] <= yr[2] in_triangle(y::Tuple{Int,Int}, xr::solution, xs::solution) = in_triangle(y, obj(xr), obj(xs)) in_triangle(xt::solution, xr::solution, xs::solution) = in_triangle(obj(xt), obj(xr), obj(xs)) in_triangle(y::solution, Δ::Triangle) = in_triangle(y, Δ.XΔ[1], Δ.XΔ[end]) in_triangle(y::Tuple{Int,Int}, Δ::Triangle) = in_triangle(y, Δ.XΔ[1], Δ.XΔ[end]) function update_lb!(Δ::Triangle) # @assert issorted(Δ.XΔ, by = x -> obj_1(x)) XΔ = Δ.XΔ λ1, λ2 = Δ.λ lb = λ1*obj_1(XΔ[1]) + λ2*obj_2(XΔ[1]) for i = 2:length(XΔ) zλ = λ1*obj_1(XΔ[i]) + λ2*obj_2(XΔ[i]) lb = min(lb,zλ) end for i = 1:length(XΔ)-1 xr = XΔ[i] xs = XΔ[i+1] zλ = λ1*(obj_1(xr)+1) + λ2*(obj_2(xs)+1) lb = min(lb,zλ) end Δ.lb = lb end function explore_triangle(Δ::Triangle, output::Bool) Δ.pending = false XΔ = Δ.XΔ OΔ = solution[] #Nondominated points located outside of Δ(yr, ys) GKP = build_graph(Δ, output) isempty(GKP) && return OΔ mono_pb = GKP.mono_pb # τ = binary_maxheap([Partition(v) for v in GKP.layer]) # updated 23-07-2021 τ = BinaryMaxHeap([Partition(v) for v in GKP.layer]) Tk = parent_partition!(τ) while Tk.zλ >= Δ.lb ϕk = const_Path_New_Partition(Tk, τ, Δ.lb, mono_pb) let yk = (Tk.z1, Tk.z2) if in_triangle(yk, Δ)#If the solution is in the triangle if !any(x -> dominates(obj(x), yk), XΔ) #and no other solution in the triangle dominates it s = solution(ϕk, GKP.pb, GKP.mono_pb) #Create the solution( O(n) ) deleteat!(XΔ, findall(x -> s>=x, XΔ))#Delete solutions dominated by this one #Add the solution to the list indinsert = searchsortedfirst(XΔ, s, by = obj_1) insert!(XΔ, indinsert, s) if Δ.lb != update_lb!(Δ)#And update the lower bound clean!(τ, Δ.lb) #If the lower bound has been updated, we can remove some partitions from τ end end else if !any(y -> dominates(obj(y), yk), OΔ)#If the solution isn't in the triangle and isn't dominated by any other in OΔ deleteat!(OΔ, findall(y -> dominates(yk, obj(y)), OΔ))#Delete solutions dominated by this one push!(OΔ, solution(ϕk, GKP.pb, GKP.mono_pb))#push it in OΔ end end end length(τ)==0 && break #If there are no more partitions to explore, stop Tk = parent_partition!(τ)#Else, pick the one with the better zλ end OΔ end function second_phase(XSE::Vector{solution}, output::Bool) res = solution[] Δlist = [Triangle(XSE[i], XSE[i+1]) for i = 1:length(XSE)-1] for i = 1:length(Δlist) Δ = select_triangle(Δlist) output && println("exploring triangle $i/$(length(Δlist)) : Δ$(obj(Δ.xr))$(obj(Δ.xs)) ($((Δ.ub-Δ.lb)/2))") # output && plot_triangle(Δ) OΔ = explore_triangle(Δ, output) append!(res, Δ.XΔ) for sol in OΔ for j = 1:length(Δlist) Δj = Δlist[j] if in_triangle(sol,Δj) let sol=sol #15938 !(Δj.pending) && break any(x -> x>=sol, Δj.XΔ) && break deleteat!(Δj.XΔ, findall(x -> sol>=x, Δj.XΔ)) indinsert = searchsortedfirst(Δj.XΔ, sol, by = obj_1) insert!(Δj.XΔ, indinsert, sol) end update_lb!(Δj) break end end end end sort!(res, by = obj_1, alg=QuickSort) return unique(elt -> elt.x, res) end function select_triangle(Δlist::Vector{Triangle}) res = Δlist[findfirst(x->x.pending, Δlist)] val_min = res.ub - res.lb for i in findall(x -> x.pending, Δlist) val = Δlist[i].ub - Δlist[i].lb if val < val_min val_min = val res = Δlist[i] end end return res end
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
2290
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. struct solution pb::problem #The problem for which it's a solution x::BitArray #Variable states obj_1::Int #Value on first objective obj_2::Int #Value on second objective weight::Int #Weight of the solution end #Constructor : empty solution solution(p::problem) = solution(p, falses(size(p)), 0, 0, 0) #Getters obj_1(s::solution) = s.obj_1 + s.pb.min_profit_1 obj_2(s::solution) = s.obj_2 + s.pb.min_profit_2 obj(s::solution) = obj_1(s), obj_2(s) weight(s::solution) = s.weight + s.pb.ω full_variable_vector(s::solution) = begin res = zeros(Int,s.pb.psize) for i in s.pb.C1 res[i] = 1 end for i = 1:size(s.pb) if s.x[i] == true res[s.pb.variables[i]] = 1 end end return res end print_vars(s::solution) = String([i==1 ? '1' : '0' for i in full_variable_vector(s)]) #Print function Base.show(io::IO, s::solution) = # print(io, "sol(p1=$(obj_1(s)), p2=$(obj_2(s)), w=$(weight(s)))") print(io, "sol(p1=",obj_1(s),", p2=",obj_2(s),") w=",weight(s)," : " ,print_vars(s)) #Helper function to calculate an objective value or an accumulated weight function dot(v::Vector{Int}, status::BitArray, indices::AbstractArray{Int,1}) #@assert length(v) >= length(status) == length(indices) res = 0 for i = 1:length(status) @inbounds res += status[i] * v[indices[i]] end res end #Relation operators dominates(a1::Int,a2::Int,b1::Int,b2::Int) = (a1 > b1 && a2 >= b2) || (a1 >= b1 && a2 > b2) dominates(yr::Tuple{Int,Int}, ys::Tuple{Int,Int}) = dominates(yr[1], yr[2], ys[1], ys[2]) ideal(yr::Tuple{Int,Int}, ys::Tuple{Int,Int}) = max(yr[1],ys[1]), max(yr[2],ys[2]) nadir(yr::Tuple{Int,Int}, ys::Tuple{Int,Int}) = min(yr[1],ys[1]), min(yr[2],ys[2]) import Base.== ==(a::solution, b::solution) = a.obj_1==b.obj_1 && a.obj_2==b.obj_2 && a.weight==b.weight && a.x==b.x import Base.< import Base.<= <=(a::solution,b::solution) = dominates(obj(b),obj(a)) <=(a, b::solution) = dominates(obj(b), a) <=(a::solution, b) = dominates(b, obj(a)) ideal(a::solution,b::solution) = max(obj_1(a), obj_1(b)) , max(obj_2(a), obj_2(b)) nadir(a::solution,b::solution) = nadir(obj(a), obj(b))
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
2537
# MIT License # Copyright (c) 2017: Xavier Gandibleux, Anthony Przybylski, Gauthier Soleilhac, and contributors. mutable struct vertex layer::Int #index of the layer in the graph i::Int #index of the variable w::Int #accumulated weight zλ::Int #best profit possible for zλ z1::Int #best profit possible for z1 z2::Int #best profit possible for z2 has_parent_0::Bool has_parent_1::Bool parent_0::vertex #parent node, with an edge having a profit == 0 parent_1::vertex #parent node, with an edge having a profit > 0 vertex(l,i,w,zλ,z1,z2,hp0,hp1) = new(l,i,w,zλ,z1,z2,hp0,hp1) vertex(l,i,w,zλ,z1,z2,hp0,hp1,p) = new(l,i,w,zλ,z1,z2,hp0,hp1,p,p) end # Base.show(io::IO, v::vertex) = print(io, "v_",v.i,"_",v.w,"(",v.zλ,")(",v.layer,")") Base.show(io::IO, v::vertex) = print(io, "v_",v.i,"_",v.w,"(",v.z1,",",v.z2,")(",v.layer,")") #v_i_0 source(mono_pb::mono_problem) = vertex(1,mono_pb.variables[1],mono_pb.ω,mono_pb.min_profit_λ,mono_pb.min_profit_1,mono_pb.min_profit_2,false,false) #inner degree of a vertex inner_degree(v::vertex) = v.has_parent_0 + v.has_parent_1 #Creates a vertex v_i+1_w from a vertex v_i_w assuming we decided not to pick item i function vertex_skip(v::vertex, mono_pb::mono_problem) varplus1 = v.layer == size(mono_pb) ? v.layer + 1 : mono_pb.variables[v.layer+1] return vertex(v.layer+1, varplus1, v.w, v.zλ, v.z1, v.z2, true, false, v) end #Creates a vertex v_i+1_w' from a vertex v_i_w assuming we decided to pick item i function vertex_keep(v::vertex, mono_pb::mono_problem) #@assert v.mono_pb.variables[v.layer] == v.i var = v.i varplus1 = v.layer == size(mono_pb) ? v.layer + 1 : mono_pb.variables[v.layer+1] return vertex(v.layer+1, varplus1, v.w+mono_pb.w[var], v.zλ+mono_pb.p[var], v.z1+mono_pb.p1[var], v.z2+mono_pb.p2[var], false, true, v) end #merge two vertices function merge!(a::vertex, b::vertex) if b.zλ >= a.zλ a.zλ, a.z1, a.z2 = b.zλ, b.z1, b.z2 end a.has_parent_1 = true a.parent_1 = b.parent_1 end #Comparison functions for searchsorted() weight_lt(v::vertex, w::Int) = v.w < w weight_lt(w::Int, v::vertex) = w < v.w #Returns the unique parent of a vertex function parent(v::vertex) return v.has_parent_0 ? v.parent_0 : v.parent_1 end #Returns both parents of a vertex function parents(v::vertex) return v.parent_0, v.parent_1 end zλ(v::vertex) = v.zλ z1(v::vertex) = v.z1 z2(v::vertex) = v.z2
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
code
1807
using vOptSpecific using Test println("Testing 2LAP...") C1 = [3 9 0 0 6 10 7 5 16 11 ; 16 0 6 12 19 8 17 10 9 18 ; 2 7 11 15 8 10 10 12 8 6 ; 4 11 7 16 3 13 18 11 11 7 ; 14 19 7 0 4 19 8 13 9 10 ; 11 4 17 14 19 5 16 2 17 4 ; 8 14 7 15 2 11 0 1 14 11 ; 8 8 3 15 8 7 14 9 0 16 ; 11 3 12 8 9 11 6 5 5 15 ; 2 5 1 9 0 4 12 13 5 6 ] C2 = [16 5 6 19 12 7 18 19 16 10 ; 15 7 13 7 7 2 10 5 0 8 ; 1 2 13 2 3 6 6 16 19 3 ; 14 7 8 1 7 13 8 17 12 16 ; 8 19 15 1 18 14 16 8 0 8 ; 8 1 10 14 15 5 0 14 1 11 ; 9 16 10 10 9 17 3 17 15 15 ; 5 15 14 0 16 12 14 4 12 6 ; 12 1 19 14 15 15 0 7 1 13 ; 10 10 1 0 0 10 10 3 19 17 ] id = set2LAP(10, C1, C2) z1,z2,solutions = vSolve(id) @test z1 == [18,19,28,35,43,54,66,22,26,34,51] @test solutions[1,:] == [3, 2, 1, 5, 4, 10, 7, 9, 8, 6] id = load2LAP("../examples/2AP10-1A100.dat") z1,z2,solutions = vSolve(id) @test z1 == [146, 155, 185, 271, 363, 478, 572, 149, 220, 267, 307, 402, 433] @test solutions[1,:] == [6, 3, 7, 9, 2, 10, 1, 5, 4, 8] println("\nTesting 2UKP...") id = set2UKP([1,2,3], [4,5,6], [7,8,9], 16) z1, z2, w, solutions = vSolve(id) @test z1 == [4] @test w == [16] @test solutions == [[1, 0, 1]] id = load2UKP("../examples/2KP500-1A.DAT") z1, z2, w, solutions = vSolve(id) @assert length(z1) == 1682 @assert extrema(z1) == (16028, 20360) @assert allunique(solutions) println("\nTesting 2UMFLP...") id = load2UMFLP("../examples/F50-51.txt") z1, z2, facility_res, X, isEdge = vSolve(id) @test length(z1) == 198 @test count(!iszero, X[21]) == 91 @test count(isEdge) == 188 println("\nTesting 2OSP...") id = set2OSP(4, [2, 4, 3, 1], [1, 2, 4, 6]) z1, z2 , S = vSolve(id) for i = 1:length(S) println("(", z1[i], ", ", z2[i], ") : ", S[i]) end @test z1 == [20, 21, 27] @test z2 == [8, 6, 5] @test S == [[4, 1, 3, 2], [4, 1, 2, 3], [1, 2, 3, 4]]
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
1.1.0
c5ce2a59e213e5bb3de8bcbb9a9f600ba3c4487f
docs
3605
# vOptSpecific: part of vOptSolver for structured problems [![Build Status](https://travis-ci.org/vOptSolver/vOptSpecific.jl.svg?branch=master)](https://travis-ci.org/vOptSolver/vOptSpecific.jl) [![codecov.io](http://codecov.io/github/vOptSolver/vOptSpecific.jl/coverage.svg?branch=master)](http://codecov.io/github/vOptSolver/vOptSpecific.jl?branch=master) **vOptSolver** is a solver of multiobjective linear optimization problems (MOMIP, MOLP, MOIP, MOCO). This repository concerns **vOptSpecific**, the part of vOptSolver devoted to **multiobjective structured problems** (currently available: 2LAP, 2OSP, 2UKP, 2UMFLP). With vOptSpecific, the problem is expressed using an Application Programming Interface. vOptSpecific runs on macOS, and linux-ubuntu. We suppose you are familiar with vOptSolver; if not, read first this [presentation](https://voptsolver.github.io/vOptSolver/). ## !!! Warning !!! vOptSpecific calls C/C++ codes through julia wrappers. Compilation, configuration, and installation are done automatically when the package is added to your own julia environment. These steps require none action from the user. However, some issues with the C/C++ compilation scripts on the latest versions of macOS and Linux have been reported to us recently. You may have to manually compile codes with commands set in the scripts and install the resulting shared libraries in the ad hoc folders for executing vOptSpecific. Sorry for these inconveniences, we will examine and fix this soon. ## Instructions For an use, a working version of: - Julia must be ready; instructions for the installation are available [here](https://julialang.org/downloads/) - your favorite C/C++ compiler must be ready (GCC is suggested) ### Run Julia On macOS: - locate the application `julia` and - click on the icon, the julia console comes to the screen On linux: - open a console on your computer or in the cloud - when the prompt is ready, type in the console `julia` ### Installation Instructions Before your first use, 1. run Julia and when the terminal is ready with the prompt `julia` on screen, 2. add and build as follow the mandatory package to your Julia distribution: ``` julia> using Pkg julia> Pkg.add("vOptSpecific") julia> Pkg.build("vOptSpecific") ``` That's all folk; at this point, vOptSpecific is properly installed. ### Usage Instructions When vOptSpecific is properly installed, 1. run Julia and when the terminal is ready with the prompt `julia` on screen, 2. invoke vOptSpecific in typing in the console: ``` julia> using vOptSpecific ``` vOptSpecific is ready. See examples for further informations and have fun with the solver! ## Problems available: | Problem | Description | API | src | Reference | |:--------|:-----------------------------------|:-------------:| --------:| --------------:| | LAP | Linear Assignment Problem | **2LAP2008** | C | Przybylski2008 | | OSP | One machine Scheduling Problem | **2OSP1980** | Julia | Wassenhove1980 | | UKP | 01 Unidimensional knapsack problem | **2UKP2010** | Julia + C | Jorge2010 | | UMFLP | Uncapacitated Mixed variables Facility Location Problem |**2UMFLP2016**| C++ | Delmee2017| ## Examples The folder `examples` provides (1) source code of problems ready to be solved and (2) selected datafiles into different formats. ## Limitations - The problem size for 2LAP is limited to 100x100. ## Validation Tested the - 22-Jul-2021 with - Julia 1.6.2 on - macOS 11.4 (Big Sur) - Linux ubuntu 18.04.5 LTS
vOptSpecific
https://github.com/vOptSolver/vOptSpecific.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
1448
# Stricker Klaus 2020 - License is MIT: http://julialang.org/license # ReadWriteDlm2 - https://github.com/strickek/ReadWriteDlm2.jl """ ## ReadWriteDlm2 `ReadWriteDlm2` functions `readdlm2()`, `writedlm2()`, `readcsv2()` and `writecsv2()` are similar to those of stdlib.DelimitedFiles, but with additional support for `Date`, `DateTime`, `Time`, `Complex`, `Rational`, `Missing` types and special decimal marks. `ReadWriteDlm2` supports the `Tables` interface. ### `readcsv2(), writecsv2()`: For "decimal dot" users the functions `readcsv2()` and `writecsv2()` have the respective defaults: Delimiter is `','` (fixed) and `decimal='.'`. ### `readdlm2(), writedlm2()`: The basic idea of these functions is to support the "decimal comma countries". They use `';'` as default delimiter and `','` as default decimal mark. "Decimal dot" users of these functions need to define `decimal='.'` ### Detailed Documentation: For more information about functionality and (keyword) arguments see `?help` for `readdlm2()`, `writedlm2()`, `readcsv2()` and `writecsv2()`. """ module ReadWriteDlm2 using Dates using DelimitedFiles using DelimitedFiles: readdlm_string, val_opts import Tables export readdlm2, writedlm2, readcsv2, writecsv2 include("rwd2_dateregex.jl") include("rwd2_readutils.jl") include("rwd2_read.jl") include("rwd2_writeutils.jl") include("rwd2_write.jl") include("rwd2_csv.jl") include("rwd2_tables.jl") end # End module ReadWriteDlm2
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
1206
# Stricker Klaus 2020 - License is MIT: http://julialang.org/license # ReadWriteDlm2 - rwd2_csv.jl - https://github.com/strickek/ReadWriteDlm2.jl """ readcsv2(source, T::Type=Any; opts...) Equivalent to `readdlm2()` with delimiter `','` and `decimal='.'`. Default Type `Any` activates parsing of `Bool`, `Int`, `Float64`, `Complex`, `Rational`, `Missing`, `DateTime`, `Date` and `Time`. # Code Example ```jldoctest julia> using ReadWriteDlm2 julia> B = Any[1 complex(1.5,2.7);1.0 1//3]; julia> writecsv2("test.csv", B) julia> readcsv2("test.csv") 2×2 Array{Any,2}: 1 1.5+2.7im 1.0 1//3 ``` """ readcsv2(input; opts...) = readdlm2auto(input, ',', Nothing, '\n', false; decimal='.', opts...) readcsv2(input, T::Type; opts...) = readdlm2auto(input, ',', T, '\n', false; decimal='.', opts...) """ writecsv2(f, A; opts...) Equivalent to `writedlm2()` with fixed delimiter `','` and `decimal='.'`. # Code Example ```jldoctest julia> using ReadWriteDlm2 julia> B = Any[1 complex(1.5,2.7);1.0 1//3]; julia> writecsv2("test.csv", B) julia> read("test.csv", String) "1,1.5+2.7im\\n1.0,1//3\\n" ``` """ writecsv2(f, a; opts...) = writedlm2auto(f, a, ','; decimal='.', opts...)
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
4622
# Stricker Klaus 2020 - License is MIT: http://julialang.org/license # ReadWriteDlm2 - rwd2_dateregex - https://github.com/strickek/ReadWriteDlm2.jl """ dfregex(df::AbstractString, locale::AbstractString=\"english\") Create a regex string `r\"^...\$\"` for the given `Date` or `DateTime` `format`string `df`. The regex groups are named according to the `format`string codes. `locale` is used to calculate min and max length of month and day names (for codes: UuEe). """ function dfregex(df::AbstractString, locale::AbstractString="english") # calculate min and max string lengths of months and day_of_weeks names Ule = try extrema([length(Dates.monthname(i;locale=locale)) for i in 1:12])catch; (3, 9) end ule = try extrema([length(Dates.monthabbr(i;locale=locale)) for i in 1:12])catch; (3, 3) end Ele = try extrema([length(Dates.dayname(i;locale=locale)) for i in 1:7])catch; (6, 9) end ele = try extrema([length(Dates.dayabbr(i;locale=locale)) for i in 1:7])catch; (3, 3) end codechars = 'y', 'Y', 'm', 'u', 'e', 'U', 'E', 'd', 'H', 'M', 'S', 's', 'Z', 'z', '\\' r = "^ *"; repeat_count = 1; ldf = length(df); dotsec = false for i = 1:ldf repeat_next = ((i < ldf) && (df[(i + 1)] == df[i])) ? true : false ((df[i] == '.') && (i < ldf) && (df[(i + 1)] == 's')) && (dotsec = true) repeat_count = (((i > 2) && (df[(i - 2)] != '\\') && (df[(i - 1)] == df[i])) || ((i == 2) && (df[1] == df[2]))) ? (repeat_count + 1) : 1 r = r * ( ((i > 1) && (df[(i - 1)] == '\\')) ? string(df[i]) : ((df[i] == 'y') && (repeat_count < 5) && !repeat_next) ? "(?<y>\\d{1,4})" : ((df[i] == 'y') && (repeat_count > 4) && !repeat_next) ? "(?<y>\\d{1,$repeat_count})" : ((df[i] == 'Y') && (repeat_count < 5) && !repeat_next) ? "(?<y>\\d{1,4})" : ((df[i] == 'Y') && (repeat_count > 4) && !repeat_next) ? "(?<y>\\d{1,$repeat_count})" : ((df[i] == 'm') && (repeat_count == 1) && !repeat_next) ? "(?<m>0?[1-9]|1[012])" : ((df[i] == 'm') && (repeat_count == 2) && !repeat_next) ? "(?<m>0[1-9]|1[012])" : ((df[i] == 'm') && (repeat_count > 2) && !repeat_next) ? "0{$(repeat_count-2)}(?<m>0[1-9]|1[012])" : ((df[i] == 'u') && (repeat_count == 1)) ? "(?<u>[A-Za-z\u00C0-\u017F]{$(ule[1]),$(ule[2])})" : ((df[i] == 'U') && (repeat_count == 1)) ? "(?<U>[A-Za-z\u00C0-\u017F]{$(Ule[1]),$(Ule[2])})" : ((df[i] == 'e') && (repeat_count == 1)) ? "(?<e>[A-Za-z\u00C0-\u017F]{$(ele[1]),$(ele[2])})" : ((df[i] == 'E') && (repeat_count == 1)) ? "(?<E>[A-Za-z\u00C0-\u017F]{$(Ele[1]),$(Ele[2])})" : ((df[i] == 'd') && (repeat_count == 1) && !repeat_next) ? "(?<d>0?[1-9]|[12]\\d|3[01])" : ((df[i] == 'd') && (repeat_count == 2) && !repeat_next) ? "(?<d>0[1-9]|[12]\\d|3[01])" : ((df[i] == 'd') && (repeat_count > 2) && !repeat_next) ? "0{$(repeat_count-2)}(?<d>0[1-9]|[12]\\d|3[01])" : ((df[i] == 'H') && (repeat_count == 1) && !repeat_next) ? "(?<H>0?\\d|1\\d|2[0-3])" : ((df[i] == 'H') && (repeat_count == 2) && !repeat_next) ? "(?<H>0\\d|1\\d|2[0-3])" : ((df[i] == 'H') && (repeat_count > 2) && !repeat_next) ? "0{$(repeat_count-2)}(?<H>0\\d|1\\d|2[0-3])" : ((df[i] == 'M') && (repeat_count == 1) && !repeat_next) ? "(?<M>\\d|[0-5]\\d)" : ((df[i] == 'M') && (repeat_count == 2) && !repeat_next) ? "(?<M>[0-5]\\d)" : ((df[i] == 'M') && (repeat_count > 2) && !repeat_next) ? "0{$(repeat_count-2)}(?<M>[0-5]\\d)" : ((df[i] == 'S') && (repeat_count == 1) && !repeat_next) ? "(?<S>\\d|[0-5]\\d)" : ((df[i] == 'S') && (repeat_count == 2) && !repeat_next) ? "(?<S>[0-5]\\d)" : ((df[i] == 'S') && (repeat_count > 2) && !repeat_next) ? "0{$(repeat_count-2)}(?<S>[0-5]\\d)" : ((df[i] == '.') && dotsec) ? "" : ((df[i] == '.')) ? "\\." : ((df[i] == 's') && (dotsec == true) && (repeat_count < 4) && !repeat_next) ? "(\\.(?<s>\\d{0,3}0{0,6}))?" : ((df[i] == 's') && (dotsec == true) && (repeat_count > 3) && !repeat_next) ? "(\\.(?<s>\\d{$(repeat_count)}))?" : ((df[i] == 's') && (dotsec == false) && (repeat_count < 4) && !repeat_next) ? "(?<s>\\d{3})?" : ((df[i] == 's') && (dotsec == false) && (repeat_count > 3) && !repeat_next) ? "(?<s>\\d{$(repeat_count)})?" : ((df[i] == 'z') && !repeat_next) ? "(?<z>[\\+|\\-]?(0\\d|1\\d|2[0-3]):?[0-5]\\d)" : ((df[i] == 'Z') && !repeat_next) ? "(?<Z>[A-Z]{3,14})" : in(df[i], codechars) ? "" : string(df[i]) ) end return Regex(r * " *" * string('$')) end
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
11260
# Stricker Klaus 2020 - License is MIT: http://julialang.org/license # ReadWriteDlm2 - rwd2_read.jl - https://github.com/strickek/ReadWriteDlm2.jl """ readdlm2(source; options...) readdlm2(source, T::Type; options...) readdlm2(source, delim::AbstractChar; options...) readdlm2(source, delim::AbstractChar, T::Type; options...) readdlm2(source, delim::AbstractChar, eol::AbstractChar; options...) readdlm2(source, delim::AbstractChar, T::Type, eol::AbstractChar; options...) Read a matrix from `source`. The `source` can be a text file, stream or byte array. Each line (separated by `eol`, this is `'\\n'` by default) gives one row. The columns are separated by `';'`, another `delim` can be defined. Pre-processing of `source` with regex substitution changes the decimal marks from `d,d` to `d.d`. For default `rs` the keyword argument `decimal=','` sets the decimal Char in the `r`-string of `rs`. When a special regex substitution tuple `rs=(r.., s..)` is defined, the argument `decimal` is not used. Pre-processing can be switched off with: `rs=()`. In addition to stdlib readdlm(), data is also parsed for `Dates` formats, the `Time` format `\"HH:MM[:SS[.s{1,9}]]\"` and for complex and rational numbers. To deactivate parsing dates/time set: `dfs=\"\", dtfs=\"\"`. `locale` defines the language of day (`E`, `e`) and month (`U`, `u`) names. The result will be a (heterogeneous) array of default element type `Any`. If `header=true` it will be a tuple containing the data array and a vector for the columnnames. Other (abstract) types for the data array elements could be defined. If data is empty, a `0×0 Array{T,2}` is returned. With `tables=true`[, `header=true`] option[s] a `Tables` interface compatible `MatrixTable` with individual column types is returned, which for example can be used as Argument for `DataFrame()`. # Additional Keyword Arguments * `decimal=','`: Decimal mark Char used by default `rs`, irrelevant if `rs`-tuple is not the default one * `rs=(r\"(\\d),(\\d)\", s\"\\1.\\2\")`: Regex (r,s)-tuple, the default change d,d to d.d if `decimal=','` * `dtfs=\"yyyy-mm-ddTHH:MM:SS.s\"`: Format string for DateTime parsing * `dfs=\"yyyy-mm-dd\"`: Format string for Date parsing * `locale=\"english\"`: Language for parsing dates names * `tables=false`: Return `Tables` interface compatible MatrixTable if `true` * `dfheader=false`: 'dfheader=true' is shortform for `tables=true, header=true` * `missingstring=\"na\"`: How missing values are represented Find more information about `readdlm()` functionality and (keyword) arguments - which are also supported by `readdlm2()` - in `help` for `readdlm()`. # Code Example ```jldoctest julia> using ReadWriteDlm2 julia> A = Any[1 1.2; "text" missing]; julia> writedlm2("test.csv", A) julia> readdlm2("test.csv") 2×2 Array{Any,2}: 1 1.2 "text" missing ``` """ readdlm2(input; opts...) = readdlm2auto(input, ';', Nothing, '\n', true; opts...) readdlm2(input, T::Type; opts...) = readdlm2auto(input, ';', T, '\n', false; opts...) readdlm2(input, dlm::AbstractChar; opts...) = readdlm2auto(input, dlm, Nothing, '\n', true; opts...) readdlm2(input, dlm::AbstractChar, T::Type; opts...) = readdlm2auto(input, dlm, T, '\n', false; opts...) readdlm2(input, dlm::AbstractChar, eol::AbstractChar; opts...) = readdlm2auto(input, dlm, Nothing, eol, true; opts...) readdlm2(input, dlm::AbstractChar, T::Type, eol::AbstractChar; opts...) = readdlm2auto(input, dlm, T, eol, false; opts...) function readdlm2auto(input, dlm, T, eol, auto; decimal::AbstractChar=',', rs::Tuple=(r"(\d),(\d)", s"\1.\2"), dtfs::AbstractString="yyyy-mm-ddTHH:MM:SS.s", dfs::AbstractString="yyyy-mm-dd", locale::AbstractString="english", tables::Bool=false, dfheader::Bool=false, missingstring::AbstractString="na", opts...) if dfheader == true tables = true opts = [opts...] push!(opts, :header => true) end ((!isempty(dtfs) && !occursin(Regex("[^YymdHMSs]"), dtfs)) || (!isempty(dfs) && !occursin(Regex("[^YymdHMSs]"), dfs))) && info( """ Format string for DateTime(`$dtfs`) or Date(`$dfs`) contains numeric code elements only. At least one non-numeric code element or character is needed for parsing dates. """) # "parsing-logic" - defaults doparsedatetime = !isempty(dtfs) doparsedate = !isempty(dfs) doparsetime = false doparsecomplex = true doparserational = true doparsemissing = false doparsenothing = false convertarray = true T2 = Any if T == Nothing # to know wether T ist Any by default T = Any anybydefault = true else anybydefault = false end # "parsing-logic" for different T::Types ((typeintersect(DateTime, T)) == Union{}) && (doparsedatetime = false) ((typeintersect(Date, T)) == Union{}) && (doparsedate = false) doparsetime = ((doparsedatetime && doparsedate) || ((Time <: T) && !(Any <:T))) T <: Union{AbstractFloat, AbstractString, Char} && (T2 = T; convertarray = false) ((typeintersect(Complex, T)) == Union{}) && (doparsecomplex = false) ((typeintersect(Rational, T)) == Union{}) && (doparserational = false) Missing <: T && (doparsemissing = true) Nothing <: T && (doparsenothing = true) (Any <: T) && (convertarray = false) if tables == true T2 = Any convertarray = false !anybydefault && (convertarray = true) T <: Union{AbstractString, Char} && (T2 = T; convertarray = false) end s = read(input, String) # empty input data - return empty array if (isempty(s) || (s == string(eol))) return Array{T2}(undef, 0, 0) end if (!isempty(rs) && (decimal != '.')) # do pre-processing of decimal mark # adopt dfs if decimal between two digits of formatstring if (rs == (r"(\d),(\d)", s"\1.\2")) && doparsedate drs = (Regex("([YymdHM])$decimal([YymdHM])"), s"\1.\2") dfs = replace(dfs, drs[1] => drs[2]) end # adopt dtfs if decimal between two digits of formatstring if (rs == (r"(\d),(\d)", s"\1.\2")) && doparsedatetime drs = (Regex("([YymdHMSs])$decimal([YymdHMSs])"), s"\1.\2") dtfs = replace(dtfs, drs[1] => drs[2]) end # Change default regex substitution Tuple if decimal != ',' if ((rs == (r"(\d),(\d)", s"\1.\2")) && (decimal != ',')) rs = (Regex("(\\d)$decimal(\\d)"), s"\1.\2") end # Error if decimal mark to replace is also the delim Char "1"*string(dlm)*"1" != replace("1"*string(dlm)*"1", rs[1] => rs[2]) && error( """ Error: Decimal mark to replace is also the delim Char. Pre-processing with decimal mark Regex substitution for `$(dlm)` (= delim!!) is not allowed - change rs/decimal or delim! """) # Regex substitution decimal s = replace(s, rs[1] => rs[2]) end # Using stdlib DelimitedFiles internal function to read dlm-string z = readdlm_string(s, dlm, T2, eol, auto, val_opts(opts)) # Formats, Regex for Date/DateTime parsing doparsedatetime && (dtdf = DateFormat(dtfs, locale); rdt = dfregex(dtfs, locale)) doparsedate && (ddf = DateFormat(dfs, locale); rd = dfregex(dfs, locale)) if tables == true # return MatrixTable for Tables Interface if isa(z, Tuple) y, h = z headerexist = true cn = Symbol.(reshape(h, :)) else y = z headerexist = false end rows, cols = size(y) coltypes = Array{Type, 1}(undef, cols) Tn = typeintersect(T, Number) for c in 1:cols # iterate columns colcontainmissing = false colcontainnothing = false coltype = Union{} for r in 1:rows # iterate rows in columns if isa(y[r,c], AbstractString) if doparsedatetime && occursin(rdt, y[r,c]) # parse DateTime try y[r,c] = DateTime(y[r,c], dtdf) catch; end elseif doparsedate && occursin(rd, y[r,c]) # parse Date try y[r,c] = Date(y[r,c], ddf) catch; end elseif doparsemissing && y[r,c] == missingstring # parse Missing try y[r,c] = missing catch; end elseif doparsenothing && y[r,c] == "nothing" # parse Nothing try y[r,c] = nothing catch; end else # parse Time, Complex and Rational try y[r,c] = parseothers(y[r,c], doparsetime, doparsecomplex, doparserational) catch; end if isa(y[r,c], AbstractString) #Substring to String try y[r,c] = String.(split(y[r,c]))[1] catch; end end end elseif convertarray && !(typeof(y[r,c]) <: Tn) try y[r,c] = convert(Tn, y[r,c]) catch; end end if typeof(y[r,c]) == Missing colcontainmissing = true elseif typeof(y[r,c]) == Nothing colcontainnothing = true else coltype = typejoin(coltype, typeof(y[r,c])) end end # end for - iterate rows in columns if colcontainmissing && colcontainnothing coltypes[c] = Union{Missing, Nothing, coltype} elseif colcontainmissing coltypes[c] = Union{Missing, coltype} elseif colcontainnothing coltypes[c] = Union{Nothing, coltype} else coltypes[c] = coltype end if convertarray && (coltypes[c] <: T) coltypes[c] = T end end # end for - iterate columns vdata = vecofvec(y, coltypes) if headerexist return Tables.table(vdata, header=cn) else return Tables.table(vdata) end else # return standard Format (Arry or Tuple(data, header)) if isa(z, Tuple) y, h = z else y = z end for i in eachindex(y) if isa(y[i], AbstractString) if doparsedatetime && occursin(rdt, y[i]) # parse DateTime try y[i] = DateTime(y[i], dtdf) catch; end elseif doparsedate && occursin(rd, y[i]) # parse Date try y[i] = Date(y[i], ddf) catch; end elseif doparsemissing && y[i] == missingstring # parse Missing try y[i] = missing catch; end elseif doparsenothing && y[i] == "nothing" # parse Nothing try y[i] = nothing catch; end else # parse Time, Complex and Rational try y[i] = parseothers(y[i], doparsetime, doparsecomplex, doparserational) catch; end end end end end if convertarray isa(z, Tuple) ? z = (convert(Array{T}, y), h) : z = convert(Array{T}, z) end return z end # End function readdlm2auto()
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
2188
# Stricker Klaus 2020 - License is MIT: http://julialang.org/license # ReadWriteDlm2 - rwd2_readutils.jl- https://github.com/strickek/ReadWriteDlm2.jl """ parseothers(y::AbstractString, doparsetime::Bool, doparsecomplex::Bool, doparserational::Bool) Parse string `y` for `Time`, `Complex` and `Rational` format and if match return the value. Otherwise return the input string `y`. """ function parseothers(y, doparsetime, doparsecomplex, doparserational) if doparsetime # parse Time mt = match(r"^ *(0?\d|1\d|2[0-3])[:Hh]([0-5]?\d)(:([0-5]?\d)([\.,](\d{1,3})(\d{1,3})?(\d{1,3})?)?)? *$", y) if mt != nothing h = parse(Int, mt[1]) mi = parse(Int, mt[2]) (mt[4] == nothing) ? s = ms = us = ns = 0 : s = parse(Int, lpad(string(mt[4]), 2, string(0))); (mt[6] == nothing) ? ms = us = ns = 0 : ms = parse(Int, rpad(string(mt[6]), 3, string(0))); (mt[7] == nothing) ? us = ns = 0 : us = parse(Int, rpad(string(mt[7]), 3, string(0))); (mt[8] == nothing) ? ns = 0 : ns = parse(Int, rpad(string(mt[8]), 3, string(0))) return Dates.Time(h, mi, s, ms, us, ns) end end if doparsecomplex # parse Complex mc = match(r"^ *(-?\d+(\.\d+)?([eE]-?\d+)?|(-?\d+)//(\d+)) ?([\+-]) ?(\d+(\.\d+)?([eE]-?\d+)?|(\d+)//(\d+))(\*im|\*i|\*j|im|i|j) *$", y) if mc != nothing real = ((mc[4] != nothing) && (mc[5] != nothing)) ? //(parse(Int, mc[4]), parse(Int, mc[5])) : ((mc[2] == nothing) && (mc[3] == nothing)) ? parse(Int, mc[1]) : parse(Float64, mc[1]) imag = ((mc[10] != nothing) && (mc[11] != nothing)) ? //(parse(Int, mc[6]*mc[10]), parse(Int, mc[11])) : ((mc[8] == nothing) && (mc[9] == nothing)) ? parse(Int, mc[6]*mc[7]) : parse(Float64, mc[6]*mc[7]) return complex(real, imag) end end if doparserational # parse Rational mr = match(r"^ *(-?\d+)//(-?\d+) *$", y) if mr != nothing nu = parse(Int, mr[1]) de = parse(Int, mr[2]) return //(nu, de) end end return y end
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
4964
# Stricker Klaus 2020 - License is MIT: http://julialang.org/license # ReadWriteDlm2 - rwd2_tables.jl - https://github.com/strickek/ReadWriteDlm2.jl """ ReadWriteDlm2.matrix2(table) Materialize any table source input as a `Matrix{Any}`. Column names - in Symbol type - are written in first row. """ function matrix2(table) cols = Tables.Columns(table) cnames = Tables.columnnames(table) nr = Tables.rowcount(cols) + 1 nc = length(cnames) matrix = Matrix{Any}(undef, nr, nc) for (i, col) in enumerate(cols) matrix[1, i] = cnames[i] matrix[2:end, i] = col end return matrix end """ vecofvec(a::Matrix, ct::Vector{Type}) Take the columns of Matrix `a`, convert each column to `Array{T,1} where T` (`ct` provides Type), and return the columns as `Vector{Array{T,1} where T}`. """ function vecofvec(a::Matrix, ct::Vector{<:Type}) cols = size(a, 2) cols == length(ct) || throw(ArgumentError( "`ct` length ($(length(ct))) must match number of columns in matrix ($(size(a, 2)))" )) vov = Vector{Array{T,1} where T}(undef, cols) for i = 1:cols vov[i] = convert(Vector{ct[i]}, view(a, :,i)) end return vov end # MatrixTable - ReadWriteDlm2 outputformat for Tables interface struct MatrixTable <: Tables.AbstractColumns names::Vector{Symbol} lookup::Dict{Symbol, Int} matrix::Vector{Array{T,1} where T} end # Overload Table.table for m::Vector{Vector} """ Tables.table(m::Vector{Array{T,1} where T; [header::Vector{Symbol}]) Wrap an vector containing columns as vectors (`Array{T,1} where T`) in a `MatrixTable`, which satisfies the Tables.jl interface. This allows accesing the matrix via `Tables.rows` and `Tables.columns`. An optional keyword argument `header` can be passed as a `Vector{Symbol}` to be used as the column names. """ function Tables.table(m::Vector{Array{T,1} where T}; header::Vector{Symbol} = [Symbol("Column$i") for i = 1:length(m)] ) length(header) == length(m) || throw(ArgumentError( "`header` length must match number of columns in matrix ($(length(m)))")) lookup = Dict(nm=>i for (i, nm) in enumerate(header)) return MatrixTable(header, lookup, m) end """ mttoarray(m::ReadWriteDlm2.MatrixTable; elt::Type=Union{}) Take Vectors of field matrix in MatrixTable `m` and return data as Array{T,2}. With given `elt` T=elt, otherwise T is the union of element types in matrix. """ function mttoarray(m::ReadWriteDlm2.MatrixTable; elt::Type=Union{}) ma = ReadWriteDlm2.matrix(m) nc = length(ma) nr = length(ma[1]) elt == Union{} ? T1 = Any : T1 = elt a = Array{T1}(undef, (nr,nc)) T = elt for i in eachindex(ma) T = Union{T, eltype(m[i])} a[:,i] = m[i] end elt != Union{} && return a return convert(Array{T,2}, a) end # declare that MatrixTable is a table Tables.istable(::Type{<:MatrixTable}) = true # getter methods to avoid getproperty clash names(m::MatrixTable) = getfield(m, :names) matrix(m::MatrixTable) = getfield(m, :matrix) lookup(m::MatrixTable) = getfield(m, :lookup) # schema is column names and types Tables.schema(m::MatrixTable) = Tables.Schema(names(m), eltype.(matrix(m))) # column interface Tables.columnaccess(::Type{<:MatrixTable}) = true Tables.columns(m::MatrixTable) = m # required Tables.AbstractColumns object methods Tables.getcolumn(m::MatrixTable, ::Type{T}, col::Int, nm::Symbol) where {T} = matrix(m)[col] Tables.getcolumn(m::MatrixTable, nm::Symbol) = matrix(m)[lookup(m)[nm]] Tables.getcolumn(m::MatrixTable, i::Int) = matrix(m)[i] Tables.columnnames(m::MatrixTable) = names(m) # declare that any MatrixTable defines its own `Tables.rows` method Tables.rowaccess(::Type{<:MatrixTable}) = true # just return itself, which means MatrixTable must iterate `Tables.AbstractRow`-compatible objects Tables.rows(m::MatrixTable) = m # the iteration interface, at a minimum, requires `eltype`, `length`, and `iterate` # for `MatrixTable` `eltype`, we're going to provide a custom row type Base.eltype(m::MatrixTable) = MatrixRow Base.length(m::MatrixTable) = length(matrix(m)[1]) Base.iterate(m::MatrixTable, st=1) = st > length(m) ? nothing : (MatrixRow(st, m), st + 1) # a custom row type; acts as a "view" into a row of an AbstractMatrix struct MatrixRow <: Tables.AbstractRow row::Int source::MatrixTable end # required `Tables.AbstractRow` interface methods (same as for `Tables.AbstractColumns` object before) # but this time, on our custom row type Tables.getcolumn(m::MatrixRow, ::Type, col::Int, nm::Symbol) = getfield(getfield(m, :source), :matrix)[col][getfield(m, :row)] Tables.getcolumn(m::MatrixRow, i::Int) = getfield(getfield(m, :source), :matrix)[i][getfield(m, :row)] Tables.getcolumn(m::MatrixRow, nm::Symbol) = getfield(getfield(m, :source), :matrix)[getfield(getfield(m, :source), :lookup)[nm]][getfield(m, :row)] Tables.columnnames(m::MatrixRow) = names(getfield(m, :source))
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
4107
# Stricker Klaus 2020 - License is MIT: http://julialang.org/license # ReadWriteDlm2 - rwd2_write.jl - https://github.com/strickek/ReadWriteDlm2.jl """ writedlm2(f, A; opts...) writedlm2(f, A, delim; opts...) Write `A` (a vector, matrix, or an iterable collection of iterable rows, a `Tables` source) as text to `f` (either a filename or an IO stream). The columns are separated by `';'`, another `delim` (Char or String) can be defined. By default, a pre-processing of values takes place. Before writing as strings, decimal marks are changed from `'.'` to `','`. With the keyword argument `decimal=` another decimal mark can be defined. To switch off this pre-processing set: `decimal='.'`. In `writedlm2()` the output format for `Date` and `DateTime` data can be defined with format strings. Defaults are the ISO formats. Day (`E`, `e`) and month (`U`, `u`) names are written in the `locale` language. For writing `Complex` numbers the imaginary component suffix can be selected with the `imsuffix=` keyword argument. # Additional Keyword Arguments * `decimal=','`: Character for writing decimal marks * `dtfs=\"yyyy-mm-ddTHH:MM:SS.s\"`: DateTime write format * `dfs=\"yyyy-mm-dd\"`: Date write format * `locale=\"english\"`: Language for DateTime writing * `imsuffix=\"im\"`: Complex Imag suffix `\"im\"`, `\"i\"` or `\"j\"` * `missingstring=\"na\"`: How missing values are written # Code Example ```jldoctest julia> using ReadWriteDlm2, Dates julia> A = Any[1 1.2; "text" Date(2017)]; julia> writedlm2("test.csv", A) julia> read("test.csv", String) "1;1,2\\ntext;2017-01-01\\n" ``` """ writedlm2(io::IO, a; opts...) = writedlm2auto(io, a, ';'; opts...) writedlm2(io::IO, a, dlm; opts...) = writedlm2auto(io, a, dlm; opts...) writedlm2(f::AbstractString, a; opts...) = writedlm2auto(f, a, ';'; opts...) writedlm2(f::AbstractString, a, dlm; opts...) = writedlm2auto(f, a, dlm; opts...) function writedlm2auto(f, a, dlm; decimal::AbstractChar=',', dtfs::AbstractString="yyyy-mm-ddTHH:MM:SS.s", dfs::AbstractString="yyyy-mm-dd", locale::AbstractString="english", imsuffix::AbstractString="im", missingstring::AbstractString="na", opts...) ((!isempty(dtfs) && !occursin(Regex("[^YymdHMSs]"), dtfs)) || (!isempty(dfs) && !occursin(Regex("[^YymdHMSs]"), dfs))) && info( """ Format string for DateTime(`$dtfs`) or Date(`$dfs`) contains numeric code elements only. At least one non-numeric code element or character is needed for parsing dates. """) (string(dlm) == string(decimal)) && error( "Error: decimal = delim = ´$(dlm)´ - change decimal or delim!") ((imsuffix != "im") && (imsuffix != "i") && (imsuffix != "j")) && error( "Only `\"im\"`, `\"i\"` or `\"j\"` are valid for `imsuffix`.") if isa(a, Union{Nothing, Missing, Number, TimeType}) a = [a] # create 1 element Array elseif Tables.istable(a) == true # Tables interface a = matrix2(a) # Matrix{Any}, first row columnnames, row 2:end -> data end if isa(a, AbstractArray) fdt = !isempty(dtfs) # Bool: format DateTime dtdf = DateFormat(dtfs, locale) fd = !isempty(dfs) # Bool: format Date ddf = DateFormat(dfs, locale) ft = (decimal != '.') # Bool: format Time (change decimal) # create b for manipulation/write - keep a unchanged b = similar(a, Any) for i in eachindex(a) b[i] = isa(a[i], AbstractFloat) ? floatformat(a[i], decimal) : isa(a[i], Missing) ? missingstring : isa(a[i], Nothing) ? "nothing" : isa(a[i], DateTime) && fdt ? Dates.format(a[i], dtdf) : isa(a[i], Date) && fd ? Dates.format(a[i], ddf) : isa(a[i], Time) && ft ? timeformat(a[i], decimal) : isa(a[i], Complex) ? complexformat(a[i], decimal, imsuffix) : string(a[i]) end else # a is not a Number, TimeType or Array -> no preprocessing b = a end writedlm(f, b, dlm; opts...) end # End function writedlm2auto()
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
1065
# Stricker Klaus 2020 - License is MIT: http://julialang.org/license # ReadWriteDlm2 - rwd2_writeutils.jl - https://github.com/strickek/ReadWriteDlm2.jl """ floatformat(a, decimal::AbstractChar) Convert Int or Float64 numbers to String and change decimal mark. """ function floatformat(a, decimal) a = string(a) (decimal != '.') && (a = replace(a, '.' => decimal)) return a end """ timeformat(a, decimal::AbstractChar) Convert Time to String, optional with change of decimal mark for seconds. """ function timeformat(a, decimal) a = string(a) (decimal != '.') && (a = replace(a, '.' => decimal)) return a end """ Complexformat(a, decimal::AbstractChar, imsuffix::AbstractString) Convert Complex number to String, optional change of decimal and/or imsuffix. """ function complexformat(a, decimal, imsuffix) a = string(a) a = replace(a, " " => "" ) #"1 + 3im" => "1+3im" (imsuffix != "im") && (a = string(split(a, "im")[1], imsuffix)) (decimal != '.') && (a = replace(a, '.' => decimal)) return a end
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
387
#2020 Klaus Stricker - Tests for ReadWriteDlm2 #License is MIT: http://julialang.org/license # runtests.jl using DelimitedFiles using ReadWriteDlm2 using Test using Random using Dates import Tables import ReadWriteDlm2.dfregex include("rwd2tests_1.jl") include("rwd2tests_2.jl") include("rwd2tests_3.jl") include("rwd2tests_4.jl") include("rwd2tests_5.jl") include("rwd2tests_6.jl")
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
15341
#2020 Klaus Stricker - Tests for ReadWriteDlm2 #License is MIT: http://julialang.org/license # rwd2tests_1.jl # 1st block modified standardtests isequaldlm(m1, m2, t) = isequal(m1, m2) && (eltype(m1) == eltype(m2) == t) @testset "1_ readdlm2" begin @test isequaldlm(readdlm2(IOBuffer("1;2\n3;4\n5;6\n"), Float64), [1. 2; 3 4; 5 6], Float64) @test isequaldlm(readdlm2(IOBuffer("1;2\n3;4\n5;6\n"), Int), [1 2; 3 4; 5 6], Int) @test isequaldlm(readdlm2(IOBuffer("1 2\n3 4\n5 6\n"),' ', Float64), [1. 2; 3 4; 5 6], Float64) @test isequaldlm(readdlm2(IOBuffer("1 2\n3 4\n5 6\n"), ' ', Int), [1 2; 3 4; 5 6], Int) @test size(readdlm2(IOBuffer("1;2;3;4\n1;2;3"))) == (2,4) @test size(readdlm2(IOBuffer("1; 2;3;4\n1;2;3"))) == (2,4) @test size(readdlm2(IOBuffer("1; 2;3;4\n1;2;3\n"))) == (2,4) @test size(readdlm2(IOBuffer("1;;2;3;4\n1;2;3\n"))) == (2,5) let result1 = reshape(Any["", "", "", "", "", "", 1.0, 1.0, "", "", "", "", "", 1.0, 2.0, "", 3.0, "", "", "", "", "", 4.0, "", "", ""], 2, 13), result2 = reshape(Any[1.0, 1.0, 2.0, 1.0, 3.0, "", 4.0, ""], 2, 4) @test isequaldlm(readdlm2(IOBuffer(";;;1;;;;2;3;;;4;\n;;;1;;;1\n")), result1, Any) @test isequaldlm(readdlm2(IOBuffer(" 1 2 3 4 \n 1 1\n"), ' '), result1, Any) @test isequaldlm(readdlm2(IOBuffer(" 1 2 3 4 \n 1 1\n"), ' '), result1, Any) @test isequaldlm(readdlm2(IOBuffer("1;2\n3;4 \n"), Float64), [[1.0, 3.0] [2.0, 4.0]], Float64) end let result1 = reshape(Any["", "", "", "", "", "", "भारत", 1.0, "", "", "", "", "", 1.0, 2.0, "", 3.0, "", "", "", "", "", 4.0, "", "", ""], 2, 13) @test isequaldlm(readdlm2(IOBuffer(",,,भारत,,,,2,3,,,4,\n,,,1,,,1\n"), ',', rs=()) , result1, Any) end let result1 = reshape(Any[1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, ""], 2, 4) @test isequaldlm(readdlm2(IOBuffer("1;2;3;4\n1;2;3")), result1, Any) @test isequaldlm(readdlm2(IOBuffer("1;2;3;4\n1;2;3;"),';'), result1, Any) @test isequaldlm(readdlm2(IOBuffer("1,2,3,4\n1,2,3"), ',', rs=()), result1, Any) @test isequaldlm(readdlm2(IOBuffer("1,2,3,4\r\n1,2,3\r\n"), ',', rs=()), result1, Any) @test isequaldlm(readdlm2(IOBuffer("1,2,3,\"4\"\r\n1,2,3\r\n"), ',', rs=()), result1, Any) end let result1 = reshape(Any["abc", "hello", "def,ghi", " \"quote\" ", "new\nline", "world"], 2, 3), result2 = reshape(Any["abc", "line\"", "\"hello\"", "\"def", "", "\" \"\"quote\"\" \"", "ghi\"", "", "world", "\"new", "", ""], 3, 4) @test isequaldlm(readdlm2(IOBuffer("abc,\"def,ghi\",\"new\nline\"\n\"hello\",\" \"\"quote\"\" \",world"), ',', rs=()), result1, Any) @test isequaldlm(readdlm2(IOBuffer("abc,\"def,ghi\",\"new\nline\"\n\"hello\",\" \"\"quote\"\" \",world"), ',', rs=(), quotes=false), result2, Any) @test isequaldlm(readdlm2(IOBuffer("abc,\"def,ghi\",\"new\nline\"\n\"hello\",\" \"\"quote\"\" \",world"), ',', rs=()), result1, Any) @test isequaldlm(readdlm2(IOBuffer("abc,\"def,ghi\",\"new\nline\"\n\"hello\",\" \"\"quote\"\" \",world"), ',', rs=(), quotes=false), result2, Any) @test isequaldlm(readdlm2(IOBuffer("abc;\"def,ghi\";\"new\nline\"\n\"hello\";\" \"\"quote\"\" \";world")), result1, Any) @test isequaldlm(readdlm2(IOBuffer("abc;\"def;ghi\";\"new\nline\"\n\"hello\";\" \"\"quote\"\" \";world"), quotes=false), result2, Any) @test isequaldlm(readdlm2(IOBuffer("abc;\"def,ghi\";\"new\nline\"\n\"hello\";\" \"\"quote\"\" \";world"), rs=()), result1, Any) @test isequaldlm(readdlm2(IOBuffer("abc;\"def;ghi\";\"new\nline\"\n\"hello\";\" \"\"quote\"\" \";world"), rs=(), quotes=false), result2, Any) end let result1 = reshape(Any["t", "c", "", "c"], 2, 2), result2 = reshape(Any["t", "\"c", "t", "c"], 2, 2) @test isequaldlm(readdlm2(IOBuffer("t;\n\"c\";c")), result1, Any) @test isequaldlm(readdlm2(IOBuffer("t;t\n\"\"\"c\";c")), result2, Any) @test isequaldlm(readdlm2(IOBuffer("t;\n\"c\";c"), rs=()), result1, Any) @test isequaldlm(readdlm2(IOBuffer("t;t\n\"\"\"c\";c"), rs=()), result2, Any) end @test isequaldlm(readdlm2(IOBuffer("\n1;2;3\n4;5;6\n\n\n"), skipblanks=false), reshape(Any["",1.0,4.0,"","","",2.0,5.0,"","","",3.0,6.0,"",""], 5, 3), Any) @test isequaldlm(readdlm2(IOBuffer("\n1;2;3\n4;5;6\n\n\n"), Float64, skipblanks=true), reshape([1.0,4.0,2.0,5.0,3.0,6.0], 2, 3), Float64) @test isequaldlm(readdlm2(IOBuffer("1;2\n\n4;5"), skipblanks=false), reshape(Any[1.0,"",4.0,2.0,"",5.0], 3, 2), Any) @test isequaldlm(readdlm2(IOBuffer("1;2\n\n4;5"), Float64, skipblanks=true), reshape([1.0,4.0,2.0,5.0], 2, 2), Float64) end @testset "1_ writedlm2" begin let x = bitrand(5, 10), io = IOBuffer() writedlm2(io, x) seek(io, 0) @test readdlm2(io, Bool) == x end let x = bitrand(5, 10) writedlm2("test.csv", x, ";") @test readdlm2("test.csv", ';', Bool, '\n') == x @test readdlm2("test.csv", ';', '\n') == x end let x = bitrand(5, 10) writedlm2("test.csv", x, ";") @test readdlm2("test.csv", ';', Bool) == x @test readdlm2("test.csv", ';') == x end let x = bitrand(5, 10) writedlm2("test.csv", x) @test readdlm2("test.csv", Bool) == x @test readdlm2("test.csv") == x end let x = [1,2,3], y = [4,5,6], io = IOBuffer() writedlm2(io, zip(x,y), ", ") seek(io, 0) @test readdlm2(io, ',', rs=()) == [x y] end let x = [0.1 0.3 0.5], io = IOBuffer() writedlm2(io, x, ", ") seek(io, 0) @test read(io, String) == "0,1, 0,3, 0,5\n" end let x = [0.1 0.3 0.5], io = IOBuffer() writedlm2(io, x, "; ") seek(io, 0) @test read(io, String) == "0,1; 0,3; 0,5\n" end let x = [0.1 0.3 0.5], io = IOBuffer() writedlm2(io, x) seek(io, 0) @test readdlm2(io) == [0.1 0.3 0.5] end let x = [0.1 0.3 0.5], io = IOBuffer() writedlm2(io, x, decimal='€') seek(io, 0) @test readdlm2(io, rs=(r"(\d)€(\d)", s"\1.\2")) == [0.1 0.3 0.5] end let x = [0.1 0.3 0.5], io = IOBuffer() writedlm2(io, x, ':', decimal='€') seek(io, 0) @test readdlm2(io, ':', rs=(r"(\d)€(\d)", s"\1.\2")) == [0.1 0.3 0.5] end let x = ["abc", "def\"ghi", "jk\nl"], y = [1, ",", "\"quoted\""], io = IOBuffer() writedlm2(io, zip(x,y)) seek(io, 0) @test readdlm2(io) == [x y] end let x = ["abc", "def\"ghi", "jk\nl"], y = [1, ",", "\"quoted\""], io = IOBuffer() writedlm2(io, zip(x,y)) seek(io, 0) @test readdlm2(io, Any) == [x y] end let x = ["a" "b"; "d" ""], io = IOBuffer() writedlm2(io, x) seek(io, 0) @test readdlm2(io) == x end let x = ["\"hello\"", "world\""], io = IOBuffer() writedlm2(io, x, quotes=false) @test String(take!(io)) == "\"hello\"\nworld\"\n" writedlm2(io, x) @test String(take!(io)) == "\"\"\"hello\"\"\"\n\"world\"\"\"\n" end end @testset "1_ comments" begin @test isequaldlm(readdlm2(IOBuffer("#this is comment\n1;2;3\n#one more comment\n4;5;6"), Float64, comments=true), [1. 2. 3.;4. 5. 6.], Float64) @test isequaldlm(readdlm2(IOBuffer("#this is \n#comment\n1;2;3\n#one more \n#comment\n4;5;6"), Float64, comments=true), [1. 2. 3.;4. 5. 6.], Float64) @test isequaldlm(readdlm2(IOBuffer("1;2;#3\n4;5;6"), comments=true), [1. 2. "";4. 5. 6.], Any) @test isequaldlm(readdlm2(IOBuffer("1#;2;3\n4;5;6"), comments=true), [1. "" "";4. 5. 6.], Any) @test isequaldlm(readdlm2(IOBuffer("1;2;\"#3\"\n4;5;6"), comments=true), [1. 2. "#3";4. 5. 6.], Any) @test isequaldlm(readdlm2(IOBuffer("1;2;3\n #with leading whitespace\n4;5;6"), comments=true), [1. 2. 3.;" " "" "";4. 5. 6.], Any) end @testset "1_ skipstart" begin x = ["a" "b" "c"; "d" "e" "f"; "g" "h" "i"; "A" "B" "C"; 1 2 3; 4 5 6; 7 8 9] io = IOBuffer() writedlm2(io, x, quotes=false) seek(io, 0) (data, hdr) = readdlm2(io, header=true, skipstart=3) @test data == [1 2 3; 4 5 6; 7 8 9] @test hdr == ["A" "B" "C"] x = ["a" "b" "\nc"; "d" "\ne" "f"; "g" "h" "i\n"; "A" "B" "C"; 1 2 3; 4 5 6; 7 8 9] io = IOBuffer() writedlm2(io, x, quotes=true) seek(io, 0) (data, hdr) = readdlm2(io, header=true, skipstart=6) @test data == [1 2 3; 4 5 6; 7 8 9] @test hdr == ["A" "B" "C"] io = IOBuffer() writedlm2(io, x, quotes=false) seek(io, 0) (data, hdr) = readdlm2(io, header=true, skipstart=6) @test data == [1 2 3; 4 5 6; 7 8 9] @test hdr == ["A" "B" "C"] end @testset "1_ i18n" begin # source: http://www.i18nguy.com/unicode/unicode-example-utf8.zip let i18n_data = ["Origin (English)", "Name (English)", "Origin (Native)", "Name (Native)", "Australia", "Nicole Kidman", "Australia", "Nicole Kidman", "Austria", "Johann Strauss", "Österreich", "Johann Strauß", "Belgium (Flemish)", "Rene Magritte", "België", "René Magritte", "Belgium (French)", "Rene Magritte", "Belgique", "René Magritte", "Belgium (German)", "Rene Magritte", "Belgien", "René Magritte", "Bhutan", "Gonpo Dorji", "འབྲུག་ཡུལ།", "མགོན་པོ་རྡོ་རྗེ།", "Canada", "Celine Dion", "Canada", "Céline Dion", "Canada - Nunavut (Inuktitut)", "Susan Aglukark", "ᓄᓇᕗᒻᒥᐅᑦ", "ᓱᓴᓐ ᐊᒡᓗᒃᑲᖅ", "Democratic People's Rep. of Korea", "LEE Sol-Hee", "조선 민주주의 인민 공화국", "이설희", "Denmark", "Soren Hauch-Fausboll", "Danmark", "Søren Hauch-Fausbøll", "Denmark", "Soren Kierkegaard", "Danmark", "Søren Kierkegård", "Egypt", "Abdel Halim Hafez", "ﻣﺼﺮ", "ﻋﺑﺪﺍﻠﺣﻟﻳﻢ ﺤﺎﻓﻅ", "Egypt", "Om Kolthoum", "ﻣﺼﺮ", "ﺃﻡ ﻛﻟﺛﻭﻡ", "Eritrea", "Berhane Zeray", "ብርሃነ ዘርኣይ", "ኤርትራ", "Ethiopia", "Haile Gebreselassie", "ኃይሌ ገብረሥላሴ", "ኢትዮጵያ", "France", "Gerard Depardieu", "France", "Gérard Depardieu", "France", "Jean Reno", "France", "Jean Réno", "France", "Camille Saint-Saens", "France", "Camille Saint-Saëns", "France", "Mylene Demongeot", "France", "Mylène Demongeot", "France", "Francois Truffaut", "France", "François Truffaut", "France (Braille)", "Louis Braille", "⠋⠗⠁⠝⠉⠑", "⠇⠕⠥⠊⠎⠀<BR>⠃⠗⠁⠊⠇⠇⠑", "Georgia", "Eduard Shevardnadze", "საქართველო", "ედუარდ შევარდნაძე", "Germany", "Rudi Voeller", "Deutschland", "Rudi Völler", "Germany", "Walter Schultheiss", "Deutschland", "Walter Schultheiß", "Greece", "Giorgos Dalaras", "Ελλάς", "Γιώργος Νταλάρας", "Iceland", "Bjork Gudmundsdottir", "Ísland", "Björk Guðmundsdóttir", "India (Hindi)", "Madhuri Dixit", "भारत", "माधुरी दिछित", "Ireland", "Sinead O'Connor", "Éire", "Sinéad O'Connor", "Israel", "Yehoram Gaon", "ישראל", "יהורם גאון", "Italy", "Fabrizio DeAndre", "Italia", "Fabrizio De André", "Japan", "KUBOTA Toshinobu", "日本", "久保田 利伸", "Japan", "HAYASHIBARA Megumi", "日本", "林原 めぐみ", "Japan", "Mori Ogai", "日本", "森鷗外", "Japan", "Tex Texin", "日本", "テクス テクサン", "Norway", "Tor Age Bringsvaerd", "Noreg", "Tor Åge Bringsværd", "Pakistan (Urdu)", "Nusrat Fatah Ali Khan", "پاکستان", "نصرت فتح علی خان", "People's Rep. of China", "ZHANG Ziyi", "中国", "章子怡", "People's Rep. of China", "WONG Faye", "中国", "王菲", "Poland", "Lech Walesa", "Polska", "Lech Wałęsa", "Puerto Rico", "Olga Tanon", "Puerto Rico", "Olga Tañón", "Rep. of China", "Hsu Chi", "臺灣", "舒淇", "Rep. of China", "Ang Lee", "臺灣", "李安", "Rep. of Korea", "AHN Sung-Gi", "한민국", "안성기", "Rep. of Korea", "SHIM Eun-Ha", "한민국", "심은하", "Russia", "Mikhail Gorbachev", "Россия", "Михаил Горбачёв", "Russia", "Boris Grebenshchikov", "Россия", "Борис Гребенщиков", "Slovenia", "\"Frane \"\"Jezek\"\" Milcinski", "Slovenija", "Frane Milčinski - Ježek", "Syracuse (Sicily)", "Archimedes", "Συρακούσα", "Ἀρχιμήδης", "Thailand", "Thongchai McIntai", "ประเทศไทย", "ธงไชย แม็คอินไตย์", "U.S.A.", "Brad Pitt", "U.S.A.", "Brad Pitt", "Yugoslavia (Cyrillic)", "Djordje Balasevic", "Југославија", "Ђорђе Балашевић", "Yugoslavia (Latin)", "Djordje Balasevic", "Jugoslavija", "Đorđe Balašević"] i18n_arr = permutedims(reshape(i18n_data, 4, Int(floor(length(i18n_data)/4))), [2, 1]) i18n_buff = PipeBuffer() writedlm2(i18n_buff, i18n_arr, ',', decimal='.') @test i18n_arr == readdlm2(i18n_buff, ',', rs=()) writedlm2(i18n_buff, i18n_arr) @test i18n_arr == readdlm2(i18n_buff) hdr = i18n_arr[1:1, :] data = i18n_arr[2:end, :] writedlm2(i18n_buff, i18n_arr) @test (data, hdr) == readdlm2(i18n_buff, header=true) end end @testset "1_ issue #13028" begin for data in ["A B C", "A B C\n"] data,hdr = readdlm2(IOBuffer(data), ' ', header=true) @test hdr == AbstractString["A" "B" "C"] @test data == Array{Float64}(undef, 0, 3) end end @testset "1_ issue #13179" begin # fix #13179 parsing unicode lines with default delmiters @test isequaldlm(readdlm2(IOBuffer("# Should ignore this π\n1\tα\n2\tβ\n"), '\t', comments=true), Any[1 "α"; 2 "β"], Any) @test isequaldlm(readdlm2(IOBuffer("# Should ignore this π\n1;α\n2;β\n"), comments=true), Any[1 "α"; 2 "β"], Any) @test isequaldlm(readdlm2(IOBuffer("# Should ignore this π\n1\tα\n2\tβ\n"), '\t', rs=(), comments=true), Any[1 "α"; 2 "β"], Any) @test isequaldlm(readdlm2(IOBuffer("# Should ignore this π\n1;α\n2;β\n"), rs=(), comments=true), Any[1 "α"; 2 "β"], Any) end @testset "1_ other issues" begin # BigInt parser let data = "1;2;3" @test readdlm2(IOBuffer(data), BigInt) == BigInt[1 2 3] @test readdlm2(IOBuffer(data), BigInt, rs=()) == BigInt[1 2 3] end let data = "1 2 3" @test readdlm2(IOBuffer(data), ' ', BigInt) == BigInt[1 2 3] @test readdlm2(IOBuffer(data), ' ', BigInt, rs=()) == BigInt[1 2 3] end # Test that we can read a write protected file let fn = tempname() open(fn, "w") do f write(f, "Julia") end chmod(fn, 0o444) @test readdlm2(fn)[] == "Julia" rm(fn) end # issue #21180 let data = "\"721\",\"1438\",\"1439\",\"…\",\"1\"" @test readdlm2(IOBuffer(data), ',', rs=()) == Any[721 1438 1439 "…" 1] end let data = "\"721\";\"1438\";\"1439\";\"…\";\"1\"" @test readdlm2(IOBuffer(data)) == Any[721 1438 1439 "…" 1] end # issue #21207 let data = "\"1\";\"灣\"\"灣灣灣灣\";\"3\"" @test readdlm2(IOBuffer(data)) == Any[1 "灣\"灣灣灣灣" 3] end # issue #11484: useful error message for invalid readdlm filepath arguments # not implemented in ReadWriteDlm2 end @testset "1_ complex" begin @test readdlm2(IOBuffer("3+4im; 4+5im"), Complex{Int}) == [3+4im 4+5im] end
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
10121
#2020 Klaus Stricker - Tests for ReadWriteDlm2 #License is MIT: http://julialang.org/license # rwd2tests_2.jl # 2nd block # Test the new functions of ReadWriteDlm2 @testset "2_ dfregex" begin @test true == occursin(dfregex("HH:MM"), "22:00") @test true == occursin(dfregex("H:M"), "1:30") @test true == occursin(dfregex("H:M"), "10:30") @test false == occursin(dfregex("H:M"), "10:62") @test true == occursin(dfregex("HHhMM"), "22h00") @test false == occursin(dfregex("HHhMM"), "22h") @test true == occursin(dfregex("Hh"), "22h") @test true == occursin(dfregex("HhM\\min"), "22h15min") @test true == occursin(dfregex("yyyy-mm-dd"), "2018-01-23") @test true == occursin(dfregex("yyyy.mm.dd"), "2018.01.23") @test false == occursin(dfregex("yyyy-mm-dd"), "2018.01.23") @test true == occursin(dfregex("yyyy-mm-ddTHH:MM:SS"), "2018-01-23T23:52:00") @test false == occursin(dfregex("yyyy-mm-ddTHH:MM:SS"), "2018-01-23T23:72:00") @test true == occursin(dfregex("yyyy-mm-ddTHH:MMz"), "2018-01-23T23:52+01:00") @test true == occursin(dfregex("yyyy-mm-ddTHH:MMz"), "2018-01-23T23:52+0100") @test true == occursin(dfregex("yyyy-mm-ddTHH:MMz"), "2018-01-23T23:52-10:00") @test false == occursin(dfregex("yyyy-mm-ddTHH:MM z"), "2018-01-23T23:52+01:00") @test false == occursin(dfregex("yyyy-mm-ddTHH:MM z"), "2018-01-23T23:52 ") @test true == occursin(dfregex("yyyy-mm-ddTHH:MM z"), "2018-01-23T23:52 10:00") @test true == occursin(dfregex("yyyy-mm-ddTHH:MMZ"), "2018-01-23T23:52UTC") @test true == occursin(dfregex("yyyy-mm-ddTHH:MMZ"), "2018-01-23T23:52CET") @test true == occursin(dfregex("yyyy-mm-ddTHH:MMZ"), "2018-01-23T23:52CEST") @test false == occursin(dfregex("yyyy-mm-ddTHH:MM Z"), "2018-01-23T23:52CET") @test true == occursin(dfregex("yyyy-mm-ddTHH:MM Z"), "2018-01-23T23:52 CEST") @test false == occursin(dfregex("yyyy-mm-ddTHH:MM Z"), "2018-01-23T23:52CEST") @test false == occursin(dfregex("yyyy-mm-ddTHH:MMZ"), "2018-01-23T23:52CE") @test true == occursin(dfregex("yyyy-mm-ddTHH:MMZZZZZZ"), "2018-01-23T23:52CEST") @test true == occursin(dfregex("yyyy-mm-ddTHH:MM ZZZZ"), "2018-01-23T23:52 CET") @test true == occursin(dfregex("yyyy-mm-ddTHH:MM zzzzzz"), "2018-01-23T23:52 +11:00") @test true == occursin(dfregex("yyyy-mm-ddTHH:MM zzzz"), "2018-01-23T23:52 -09:00") @test true == occursin(dfregex("yyyy-mm-ddTHH:MM\\Z"), "2018-01-23T23:52Z") end @testset "2_new functions" begin let data = "2015-01-01;5,1;Text1\n10;19e6;4\n" @test isequaldlm(readdlm2(IOBuffer(data)), [Date(2015) 5.1 "Text1";10 190.0e5 4.0], Any) @test isequaldlm(readdlm2(IOBuffer(data)), [Date(2015) 5.1 "Text1";10 190.0e5 4.0], Any) end a = [Date(2015) 5.1 "Text1";10 190.0e5 4.0] writedlm2("test.csv", a, decimal='€') @test read("test.csv", String) == "2015-01-01;5€1;Text1\n10;1€9e7;4€0\n" b = readdlm2("test.csv", rs=(r"(\d)€(\d)", s"\1.\2")) rm("test.csv") @test b[1] == Date(2015) a = DateTime(2017) writedlm2("test.csv", a) @test read("test.csv", String) == "2017-01-01T00:00:00.0\n" b = readdlm2("test.csv") rm("test.csv") @test b[1] == DateTime(2017) a = Any[Date(2017,1,14) DateTime(2017,2,15,23,40,59)] writedlm2("test.csv", a) @test read("test.csv", String) == "2017-01-14;2017-02-15T23:40:59.0\n" b = readdlm2("test.csv") rm("test.csv") @test isequaldlm(a, b, Any) a = Any[Date(2017, 1, 1) DateTime(2017, 2, 15, 23, 0, 0)] writedlm2("test.csv", a, dfs="mm/yyyy", dtfs="dd.mm.yyyy/HH.h") @test read("test.csv", String) == "01/2017;15.02.2017/23.h\n" writedlm2("test.csv", a, dfs="", dtfs="") @test read("test.csv", String) == "2017-01-01;2017-02-15T23:00:00\n" writedlm2("test.csv", a, decimal='.') @test read("test.csv", String) == "2017-01-01;2017-02-15T23:00:00.0\n" writedlm2("test.csv", a, decimal='.', dfs="\\Y\\ear: yyyy", dtfs="\\Y\\ear: yyyy") @test read("test.csv", String) == "Year: 2017;Year: 2017\n" writedlm2("test.csv", a, dfs="mm/yyyy", dtfs="dd.mm.yyyy/HH.h") @test read("test.csv", String) == "01/2017;15.02.2017/23.h\n" b = readdlm2("test.csv", dfs="mm/yyyy", dtfs="dd.mm.yyyy/HH.h") @test isequaldlm(a, b, Any) b = readdlm2("test.csv", rs=(), dfs="mm/yyyy", dtfs="dd.mm.yyyy/HH.h") rm("test.csv") @test isequaldlm(a, b, Any) a = Date(2017,5,1) writedlm2("test.csv", a, dfs="dd.mm.yyyy") @test read("test.csv", String) == "01.05.2017\n" b = readdlm2("test.csv", dfs="dd.mm.yyyy") rm("test.csv") @test b[1] == a a = "ABC" writedlm2("test.csv", a) @test read("test.csv", String) == "A\nB\nC\n" b = readdlm2("test.csv") rm("test.csv") @test b[1] == "A" && b[3] == "C" D = rand(1:9, 10, 5) writedlm2("test.csv", D) @test length(read("test.csv", String)) == 100 b = readdlm2("test.csv") rm("test.csv") @test D == b a = 10.9 writedlm2("test.csv", a, decimal='€') @test read("test.csv", String) == "10€9\n" b = readdlm2("test.csv") rm("test.csv") @test b[1] == "10€9" a = 10.9 writedlm2("test.csv", a, decimal='.') @test read("test.csv", String) == "10.9\n" b = readdlm2("test.csv") rm("test.csv") @test b[1] == 10.9 a = [10.9 12.5; Date(2017) DateTime(2017)] writedlm2("test.csv", a, ',', decimal='€') b = readdlm2("test.csv", ',', decimal='€') rm("test.csv") @test a == b a = [10.9 12.5; Date(2017) DateTime(2017)] writedlm2("test.csv", a, ',', decimal='.') b = readdlm2("test.csv", ',', decimal='.') rm("test.csv") @test a == b a = [10.9 12.5; Date(2017) DateTime(2017)] writedlm2("test.csv", a) b = readdlm2("test.csv") rm("test.csv") @test a == b end @testset "2_ date format" begin # test date format strings with variable length a = DateTime(2017,5,1,5,59,1) writedlm2("test.csv", a, dtfs="E, dd.mm.yyyy H:M:S") @test read("test.csv", String) == "Monday, 01.05.2017 5:59:1\n" b = readdlm2("test.csv", dtfs="E, dd.mm.yyyy H:M:S") rm("test.csv") @test a == b[1] a = DateTime(2017,5,1,5,59,1,898) writedlm2("test.csv", a, dtfs="E, d.u yyyy H:M:S,s") @test read("test.csv", String) == "Monday, 1.May 2017 5:59:1,898\n" b = readdlm2("test.csv", dtfs="E, d.u yyyy H:M:S.s") @test a == b[1] b = readdlm2("test.csv", dtfs="E, d.u yyyy H:M:S,s") @test a == b[1] rm("test.csv") # test date format strings with fix length a = [DateTime(2017,5,1,5,59,1,898) 1.0 1.1 1.222e7 1 true] writedlm2("test.csv", a, dtfs="yyyyymmmdddTHHHMMMSSSsss") @test read("test.csv", String) == "02017005001T005059001898;1,0;1,1;1,222e7;1;true\n" b = readdlm2("test.csv", dtfs="yyyyymmmdddTHHHMMMSSSsss") rm("test.csv") @test b == a end @testset "2_ Time parsing" begin a = [Dates.Time(23,55,56,123,456,789) Dates.Time(23,55,56,123,456) Dates.Time(23,55,56,123) Dates.Time(12,45) Dates.Time(11,23,11)] writedlm2("test.csv", a) @test read("test.csv", String) == "23:55:56,123456789;23:55:56,123456;23:55:56,123;12:45:00;11:23:11\n" b = readdlm2("test.csv") @test b == a write("test.csv", "23:55:56.123456789;23:55:56,123456;23:55:56,123;12:45;11:23:11\n") b = readdlm2("test.csv") rm("test.csv") @test b == a a = [Dates.Time(23,55,56,123,456) Dates.Time(12,45) Dates.Time(11,23,11)] writedlm2("test.csv", a, decimal='.') @test read("test.csv", String) == "23:55:56.123456;12:45:00;11:23:11\n" @test readdlm2("test.csv", dtfs="", dfs="") == ["23:55:56.123456" "12:45:00" "11:23:11"] @test readdlm2("test.csv") == a rm("test.csv") end @testset "2_ DateLocale" begin # Test locale for french and german Dates.LOCALES["french"] = Dates.DateLocale( ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], ["janv", "févr", "mars", "avril", "mai", "juin", "juil", "août", "sept", "oct", "nov", "déc"], ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"], ["lu", "ma", "me", "je", "ve", "sa", "di"], ) Dates.LOCALES["german"] = Dates.DateLocale( ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"], ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"], ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"], ) a = DateTime(2017,5,1,5,59,1) writedlm2("test.csv", a, dtfs="E, dd.mm.yyyy H:M:S", locale="french") @test read("test.csv", String) == "lundi, 01.05.2017 5:59:1\n" b = readdlm2("test.csv", dtfs="E, dd.mm.yyyy H:M:S", locale="french") rm("test.csv") @test b[1] == a a = DateTime(2017,1,1,5,59,1,898) writedlm2("test.csv", a, dtfs="E, d.u yyyy H:M:S,s", locale="french") @test read("test.csv", String) == "dimanche, 1.janv 2017 5:59:1,898\n" b = readdlm2("test.csv", dtfs="E, d.u yyyy H:M:S.s", locale="french") @test b[1] == a b = readdlm2("test.csv", dtfs="E, d.u yyyy H:M:S,s", locale="french") @test b[1] == a rm("test.csv") a = DateTime(2017,8,1,5,59,1) writedlm2("test.csv", a, dtfs="E, dd.mm.yyyy H:M:S", locale="german") @test read("test.csv", String) == "Dienstag, 01.08.2017 5:59:1\n" b = readdlm2("test.csv", dtfs="E, dd.mm.yyyy H:M:S", locale="german") rm("test.csv") @test b[1] == a a = DateTime(2017,11,1,5,59,1,898) writedlm2("test.csv", a, dtfs="E, d. U yyyy H:M:S,s", locale="german") @test read("test.csv", String) == "Mittwoch, 1. November 2017 5:59:1,898\n" b = readdlm2("test.csv", dtfs="E, d. U yyyy H:M:S.s", locale="german") @test b[1] == a b = readdlm2("test.csv", dtfs="E, d. U yyyy H:M:S,s", locale="german") @test b[1] == a rm("test.csv") end
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
7729
#2020 Klaus Stricker - Tests for ReadWriteDlm2 #License is MIT: http://julialang.org/license # rwd2tests_3.jl @testset "3_ other types" begin # Test Complex and Rational parsing a = Any[complex(-1,-2) complex(1.2,-2) complex(1e9,3e19) 1//3 -1//5 -2//-4 1//-0 -0//1] writedlm2("test.csv", a) @test read("test.csv", String) == "-1-2im;1,2-2,0im;1,0e9+3,0e19im;1//3;-1//5;1//2;1//0;0//1\n" b = readdlm2("test.csv", Any) rm("test.csv") @test isequaldlm(a, b, Any) # Complex and Rational - tolerance with blancs, i/j and different signes write("test.csv", " -1-2j; 1,2 - 2,0i ;1.0E9+3.0E19im; -1//-3;1//-5; 1//2 ;1//-0;-0//1 \n") b = readdlm2("test.csv", Any) rm("test.csv") @test b == a # Test Complex and Rational parsing - decimal = '.', delimiter = \t a = Any[complex(-1,-2) complex(1.2,-2) complex(1e9,3e19) 1//3 -1//5 -2//-4 1//-0 -0//1] writedlm2("test.csv", a, '\t', decimal='.') @test read("test.csv", String) == "-1-2im\t1.2-2.0im\t1.0e9+3.0e19im\t1//3\t-1//5\t1//2\t1//0\t0//1\n" b = readdlm2("test.csv",'\t', Any, decimal='.') rm("test.csv") @test isequaldlm(a, b, Any) # Test different types with header and Any Array - decimal comma a = Any["Nr" "Wert";1 Date(2017);2 DateTime(2018);3 Dates.Time(23,54,45,123,456,78);4 1.5e10+5im;5 1500//5;6 1.5e10] writedlm2("test.csv", a) @test read("test.csv", String) == """ Nr;Wert 1;2017-01-01 2;2018-01-01T00:00:00.0 3;23:54:45,123456078 4;1,5e10+5,0im 5;300//1 6;1,5e10 """ b = readdlm2("test.csv", Any, header=true) rm("test.csv") @test a[2:end,:] == b[1] @test a[1:1,:] == b[2] # Test different types with header and Any Array - english decimal a = Any["Nr" "Value";1 Date(2017);2 DateTime(2018);3 Dates.Time(23,54,45,123,456,78);4 1.5e10+5im;5 1500//5;6 1.5e10] writedlm2("test.csv", a, '\t', decimal='.') @test read("test.csv", String) == """ Nr\tValue 1\t2017-01-01 2\t2018-01-01T00:00:00.0 3\t23:54:45.123456078 4\t1.5e10+5.0im 5\t300//1 6\t1.5e10 """ b = readdlm2("test.csv", '\t', Any, decimal='.', header=true) rm("test.csv") @test a[2:end,:] == b[1] @test a[1:1,:] == b[2] # Test Complex Array read and write a = Complex[complex(-1,-2) complex(1.2,-2) complex(-1e9,3e-19)] writedlm2("test.csv", a) @test read("test.csv", String) == "-1-2im;1,2-2,0im;-1,0e9+3,0e-19im\n" b = readdlm2("test.csv", Complex) rm("test.csv") @test a == b @test typeof(b) == Array{Complex,2} a = Complex[complex(-1,-2) complex(1.2,-2) complex(-1e9,3e-19)] writedlm2("test.csv", a, imsuffix="i") @test read("test.csv", String) == "-1-2i;1,2-2,0i;-1,0e9+3,0e-19i\n" b = readdlm2("test.csv", Complex) rm("test.csv") @test a == b @test typeof(b) == Array{Complex,2} a = Any["test" "test2";complex(-1,-2) complex(1.2,-2);complex(-1e9,3e-19) complex(1,115)] writedlm2("test.csv", a) @test read("test.csv", String) == "test;test2\n-1-2im;1,2-2,0im\n-1,0e9+3,0e-19im;1+115im\n" b = readdlm2("test.csv", Any) rm("test.csv") @test a == b @test typeof(b) == Array{Any,2} a = Any["test1" "test2";complex(-1,-2) complex(1.2,-2);complex(-1e9,3e-19) complex(1,115)] writedlm2("test.csv", a) @test read("test.csv", String) == "test1;test2\n-1-2im;1,2-2,0im\n-1,0e9+3,0e-19im;1+115im\n" b, h = readdlm2("test.csv", Complex, header=true) rm("test.csv") @test b == Complex[complex(-1,-2) complex(1.2,-2);complex(-1e9,3e-19) complex(1,115)] @test h == AbstractString["test1" "test2"] a = Complex[complex(-1//3,-7//5) complex(1,-1//3) complex(-1//2,3e-19)] writedlm2("test.csv", a, imsuffix="i") @test read("test.csv", String) == "-1//3-7//5*i;1//1-1//3*i;-0,5+3,0e-19i\n" b = readdlm2("test.csv", Complex) rm("test.csv") @test a == b @test typeof(b) == Array{Complex,2} a = Complex[complex(-1//3,-7//5) complex(1,-1//3) complex(-1//2,3e-19)] writedlm2("test.csv", a) @test read("test.csv", String) == "-1//3-7//5*im;1//1-1//3*im;-0,5+3,0e-19im\n" b = readdlm2("test.csv", Complex) rm("test.csv") @test a == b @test typeof(b) == Array{Complex,2} # Test Time read and write a = Time[Time(12,54,43,123,456,789) Time(13,45);Time(1,45,58,0,0,1) Time(23,59,59)] writedlm2("test.csv", a) @test read("test.csv", String) == "12:54:43,123456789;13:45:00\n01:45:58,000000001;23:59:59\n" b = readdlm2("test.csv", Time) rm("test.csv") @test b == a @test typeof(b) == Array{Time,2} a = Any["test1" "test2";Time(12,54,43,123,456,789) Time(13,45);Time(1,45,58,0,0,1) Time(23,59,59)] writedlm2("test.csv", a) @test read("test.csv", String) == "test1;test2\n12:54:43,123456789;13:45:00\n01:45:58,000000001;23:59:59\n" b, h = readdlm2("test.csv", Time, header=true) rm("test.csv") @test b == Time[Time(12,54,43,123,456,789) Time(13,45);Time(1,45,58,0,0,1) Time(23,59,59)] @test h == AbstractString["test1" "test2"] # Test Rational read and write a = Rational[456//123 123//45;456//23 1203//45] writedlm2("test.csv", a) @test read("test.csv", String) == "152//41;41//15\n456//23;401//15\n" b = readdlm2("test.csv", Rational) rm("test.csv") @test b == a @test typeof(b) == Array{Rational,2} a = Any["test1" "test2";456//123 123//45;456//23 1203//45] writedlm2("test.csv", a) @test read("test.csv", String) == "test1;test2\n152//41;41//15\n456//23;401//15\n" b, h = readdlm2("test.csv", Rational, header=true) rm("test.csv") @test b == Rational[456//123 123//45;456//23 1203//45] @test h == AbstractString["test1" "test2"] # Test DateTime read and write a = DateTime[DateTime(2017) DateTime(2016);DateTime(2015) DateTime(2014)] writedlm2("test.csv", a) @test read("test.csv", String) == "2017-01-01T00:00:00.0;2016-01-01T00:00:00.0\n2015-01-01T00:00:00.0;2014-01-01T00:00:00.0\n" b = readdlm2("test.csv", DateTime) c = readdlm2("test.csv", DateTime, tables=true) # test tables interface @test ReadWriteDlm2.mttoarray(c) == a rm("test.csv") @test b == a @test typeof(b) == Array{DateTime,2} a = Any["test1" "test2";DateTime(2017) DateTime(2016);DateTime(2015) DateTime(2014)] writedlm2("test.csv", a) @test read("test.csv", String) == "test1;test2\n2017-01-01T00:00:00.0;2016-01-01T00:00:00.0\n2015-01-01T00:00:00.0;2014-01-01T00:00:00.0\n" b, h = readdlm2("test.csv", DateTime, header=true) rm("test.csv") @test b == DateTime[DateTime(2017) DateTime(2016);DateTime(2015) DateTime(2014)] @test h == AbstractString["test1" "test2"] # Test Date read and write a = Date[Date(2017) Date(2016);Date(2015) Date(2014)] writedlm2("test.csv", a) @test read("test.csv", String) == "2017-01-01;2016-01-01\n2015-01-01;2014-01-01\n" b = readdlm2("test.csv", Date) rm("test.csv") @test b == a @test typeof(b) == Array{Date,2} a = Any["test1" "test2";Date(2017) Date(2016);Date(2015) Date(2014)] writedlm2("test.csv", a) @test read("test.csv", String) == "test1;test2\n2017-01-01;2016-01-01\n2015-01-01;2014-01-01\n" b, h = readdlm2("test.csv", Date, header=true) rm("test.csv") @test b == Date[Date(2017) Date(2016);Date(2015) Date(2014)] @test h == AbstractString["test1" "test2"] # Test alternative rs Tuple - is decimal ignored? a = Float64[1.1 1.2;2.1 2.2] writedlm2("test.csv", a, decimal='€') @test read("test.csv", String) == "1€1;1€2\n2€1;2€2\n" b = readdlm2("test.csv", Any, rs=(r"(\d)€(\d)", s"\1.\2"), decimal='n') rm("test.csv") @test a == b end
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
8521
#2020 Klaus Stricker - Tests for ReadWriteDlm2 #License is MIT: http://julialang.org/license # rwd2tests_4.jl # Tests for readcsv2 and writecsv2 # ================================ @testset "4_readwritecsv2" begin # test comments with readcsv2 @test isequaldlm(readcsv2(IOBuffer("#this is comment\n1,2,3\n#one more comment\n4,5,6"), comments=true), Any[1 2 3;4 5 6], Any) @test isequaldlm(readcsv2(IOBuffer("#this is \n#comment\n1,2,3\n#one more \n#comment\n4,5,6"), comments=true), Any[1 2 3;4 5 6], Any) # test readcsv2 and writecsv2 with alternative decimal a = Float64[1.1 1.2;2.1 2.2] writecsv2("test.csv", a, decimal='€') @test read("test.csv", String) == "1€1,1€2\n2€1,2€2\n" b = readcsv2("test.csv", Any, rs=(r"(\d)€(\d)", s"\1.\2"), decimal='n') rm("test.csv") @test a == b # Test different types with header for readcsv2 and writecsv2 a = Any["Nr" "Value";1 Date(2017);2 DateTime(2018);3 Dates.Time(23,54,45,123,456,78);4 1.5e10+5im;5 1500//5;6 1.5e10] writecsv2("test.csv", a) @test read("test.csv", String) == """ Nr,Value 1,2017-01-01 2,2018-01-01T00:00:00.0 3,23:54:45.123456078 4,1.5e10+5.0im 5,300//1 6,1.5e10 """ b = readcsv2("test.csv", header=true) rm("test.csv") @test a[2:end,:] == b[1] @test a[1:1,:] == b[2] # Test size for readcsv2 @test size(readcsv2(IOBuffer("1,2,3,4"))) == (1,4) @test size(readcsv2(IOBuffer("1,2,3,"))) == (1,4) @test size(readcsv2(IOBuffer("1,2,3,4\n"))) == (1,4) @test size(readcsv2(IOBuffer("1,2,3,\n"))) == (1,4) @test size(readcsv2(IOBuffer("1,2,3,4\n1,2,3,4"))) == (2,4) @test size(readcsv2(IOBuffer("1,2,3,4\n1,2,3,"))) == (2,4) @test size(readcsv2(IOBuffer("1,2,3,4\n1,2,3"))) == (2,4) @test size(readcsv2(IOBuffer("1,2,3,4\r\n"))) == (1,4) @test size(readcsv2(IOBuffer("1,2,3,4\r\n1,2,3\r\n"))) == (2,4) @test size(readcsv2(IOBuffer("1,2,3,4\r\n1,2,3,4\r\n"))) == (2,4) @test size(readcsv2(IOBuffer("1,2,3,\"4\"\r\n1,2,3,4\r\n"))) == (2,4) #Time types for readcsv2 and writecsv2 a = [Dates.Time(23,55,56,123,456,789) Dates.Time(23,55,56,123,456) Dates.Time(23,55,56,123) Dates.Time(12,45) Dates.Time(11,23,11)] writecsv2("test.csv", a) @test read("test.csv", String) == "23:55:56.123456789,23:55:56.123456,23:55:56.123,12:45:00,11:23:11\n" b = readcsv2("test.csv") rm("test.csv") @test b == a # Test readcsv2/writecsv2 with Complex - Rationals a = Complex[complex(-1//3,-7//5) complex(1,-1//3) complex(-1//2,3e-19)] writecsv2("test.csv", a) @test read("test.csv", String) == "-1//3-7//5*im,1//1-1//3*im,-0.5+3.0e-19im\n" b = readcsv2("test.csv", Complex) rm("test.csv") @test a == b @test typeof(b) == Array{Complex,2} end @testset "4_empty IO-data" begin # Tests for empty IO-Data a = "" writedlm2("test.csv", a) @test read("test.csv", String) == "" b = readdlm2("test.csv") @test typeof(b) == Array{Any,2} @test typeof(readdlm2("test.csv", Any)) == Array{Any,2} rm("test.csv") @test isempty(b) writecsv2("test.csv", a) @test read("test.csv", String) == "" b = readcsv2("test.csv") @test typeof(b) == Array{Any,2} @test typeof(readcsv2("test.csv", Float64)) == Array{Float64,2} rm("test.csv") @test isempty(b) a = [""] writedlm2("test.csv", a) @test read("test.csv", String) == "\n" b = readdlm2("test.csv") @test typeof(b) == Array{Any,2} @test typeof(readdlm2("test.csv", Any)) == Array{Any,2} rm("test.csv") @test isempty(b) writecsv2("test.csv", a) @test read("test.csv", String) == "\n" b = readcsv2("test.csv") @test typeof(b) == Array{Any,2} @test typeof(readcsv2("test.csv", Float64)) == Array{Float64,2} rm("test.csv") @test isempty(b) a = missing writedlm2("test.csv", a) @test read("test.csv", String) == "na\n" b = readcsv2("test.csv") rm("test.csv") @test typeof(b) == Array{Any,2} @test isequal(a, b[1]) writecsv2("test.csv", a) @test read("test.csv", String) == "na\n" b = readcsv2("test.csv") rm("test.csv") @test typeof(b) == Array{Any,2} @test isequal(a, b[1]) a = [nothing] a = reshape(a, 1,1) writedlm2("test.csv", a) @test read("test.csv", String) == "nothing\n" b = readdlm2("test.csv") rm("test.csv") @test typeof(b) == Array{Any,2} @test isequal(a, b) writecsv2("test.csv", a) @test read("test.csv", String) == "nothing\n" b = readdlm2("test.csv") rm("test.csv") @test typeof(b) == Array{Any,2} @test isequal(a, b) a = [1.2 NaN "" nothing missing] writedlm2("test.csv", a) @test read("test.csv", String) == "1,2;NaN;;nothing;na\n" b = readdlm2("test.csv") rm("test.csv") @test isequal(a, b) a = [1.2 NaN "" nothing missing] writecsv2("test.csv", a) @test read("test.csv", String) == "1.2,NaN,,nothing,na\n" b = readcsv2("test.csv") rm("test.csv") @test isequal(a, b) end @testset "4_ random data" begin # Test write and read of random Any array with 10000 rows n = 1000 A = Array{Any}(undef, n, 9) for i = 1:n A[i,:] = Any[randn() rand(Int) rand(Bool) rand(Date(1980,1,1):Day(1):Date(2017,12,31)) rand(Dates.Time(0,0,0,0,0,0):Dates.Nanosecond(1):Dates.Time(23,59,59,999,999,999)) rand(DateTime(1980,1,1,0,0,0,0):Dates.Millisecond(1):DateTime(2017,12,31,23,59,59,999)) randstring(24) complex(randn(), randn()) (rand(Int)//rand(Int))] end writedlm2("test.csv", A) B = readdlm2("test.csv") rm("test.csv") @test isequaldlm(A, B, Any) writecsv2("test.csv", A) B = readcsv2("test.csv") rm("test.csv") @test isequaldlm(A, B, Any) end @testset "4_abstract type" begin #Abstract Time Types a = TimeType[Date(2017, 1, 1) DateTime(2017, 2, 15, 23, 0, 0)] writedlm2("test.csv", a, dfs="mm/yyyy", dtfs="dd.mm.yyyy/HH.h") b = readdlm2("test.csv", TimeType, dfs="mm/yyyy", dtfs="dd.mm.yyyy/HH.h") @test isequaldlm(a, b, TimeType) b = readdlm2("test.csv", TimeType, rs=(), dfs="mm/yyyy", dtfs="dd.mm.yyyy/HH.h") rm("test.csv") @test isequaldlm(a, b, TimeType) # Abstract Number a = Number[1 1.1 1//3 complex(-1,-2) complex(1.2,-2) complex(-1e9,3e-19)] writedlm2("test.csv", a) @test read("test.csv", String) == "1;1,1;1//3;-1-2im;1,2-2,0im;-1,0e9+3,0e-19im\n" b = readdlm2("test.csv", Number) rm("test.csv") @test a == b @test typeof(b) == Array{Number,2} # Abstract real a = readdlm2(IOBuffer("1,1;2\n3;4,5\n5;1//3\n"), Real) b = Real[1.1 2; 3 4.5; 5 1//3] @test a == b @test typeof(a) == typeof(b) end @testset "4_ 1 0 1 0 0" begin # Different Types for "1 0 1 0 0" a = readdlm2(IOBuffer("1;0;1;0;0\n")) b = Any[1 0 1 0 0] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), Float64) b = [1.0 0.0 1.0 0.0 0.0] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), Float16) b = Float16[1.0 0.0 1.0 0.0 0.0] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), Int) b = [1 0 1 0 0] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), Char) b = ['1' '0' '1' '0' '0'] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), AbstractString) b = AbstractString["1" "0" "1" "0" "0"] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), String) b = ["1" "0" "1" "0" "0"] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), Bool) b = [true false true false false] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), Complex{Int}) b = [1+0im 0+0im 1+0im 0+0im 0+0im] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), Complex{Float64}) b = [1.0+0.0im 0.0+0.0im 1.0+0.0im 0.0+0.0im 0.0+0.0im] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), Complex{Rational{Int}}) b = [1//1+0//1*im 0//1+0//1*im 1//1+0//1*im 0//1+0//1*im 0//1+0//1*im] @test a == b @test typeof(a) == typeof(b) a = readdlm2(IOBuffer("1;0;1;0;0\n"), Rational) b = Rational[1//1 0//1 1//1 0//1 0//1] @test a == b @test typeof(a) == typeof(b) end
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
10480
#2020 Klaus Stricker - Tests for ReadWriteDlm2 #License is MIT: http://julialang.org/license # rwd2tests_5.jl # Tests for Tables interface # ========================== @testset "5_Stand1 Tables" begin mat = [1 4.0 "7"; 2 5.0 "8"; 3 6.0 "9"] # first, create a MatrixTable from our matrix input mattbl = Tables.table(mat) # test that the MatrixTable `istable` @test Tables.istable(typeof(mattbl)) # test that it defines row access @test Tables.rowaccess(typeof(mattbl)) # test that it defines column access @test Tables.columnaccess(typeof(mattbl)) @test Tables.columns(mattbl) === mattbl # test that we can access the first "column" of our matrix table by column name @test mattbl.Column1 == [1,2,3] # test our `Tables.AbstractColumns` interface methods @test Tables.getcolumn(mattbl, :Column1) == [1,2,3] @test Tables.getcolumn(mattbl, 1) == [1,2,3] @test Tables.columnnames(mattbl) == [:Column1, :Column2, :Column3] # now let's iterate our MatrixTable to get our first MatrixRow matrowtbl = Tables.rows(mattbl) matrow = first(matrowtbl) @test eltype(matrowtbl) == typeof(matrow) # now we can test our `Tables.AbstractRow` interface methods on our MatrixRow @test matrow.Column1 == 1 @test Tables.getcolumn(matrow, :Column1) == 1 @test Tables.getcolumn(matrow, 1) == 1 @test propertynames(mattbl) == propertynames(matrow) == [:Column1, :Column2, :Column3] end @testset "5_Stand2 Tables" begin rt = [(a=1, b=4.0, c="7"), (a=2, b=5.0, c="8"), (a=3, b=6.0, c="9")] ct = (a=[1,2,3], b=[4.0, 5.0, 6.0]) # let's turn our row table into a plain Julia Matrix object mat = Tables.matrix(rt) # test that our matrix came out like we expected @test mat[:, 1] == [1, 2, 3] @test size(mat) == (3, 3) @test eltype(mat) == Any # so we successfully consumed a row-oriented table, # now let's try with a column-oriented table mat2 = Tables.matrix(ct) @test eltype(mat2) == Float64 @test mat2[:, 1] == ct.a # now let's take our matrix input, and make a column table out of it tbl = Tables.table(mat) |> Tables.columntable @test keys(tbl) == (:Column1, :Column2, :Column3) @test tbl.Column1 == [1, 2, 3] # and same for a row table tbl2 = Tables.table(mat2) |> Tables.rowtable @test length(tbl2) == 3 @test map(x->x.Column1, tbl2) == [1.0, 2.0, 3.0] end @testset "5_matrix2 Tabl" begin mat = Any[1 4.0 true "a"; 2 5.0 false "b"; 3 6.0 true "c"] # first, create a MatrixTable from our matrix input mattbl = Tables.table(mat) # test that the MatrixTable `istable` @test Tables.istable(typeof(mattbl)) # ReadWriteDlm2.matrix2: Matrix{Any}, first row Symbol colnames ma2 = ReadWriteDlm2.matrix2(mattbl) # test that it defines row access @test Tables.rowaccess(typeof(mattbl)) # test that it defines column access @test Tables.columnaccess(typeof(mattbl)) @test Tables.columns(mattbl) === mattbl # test that data fit @test mattbl.Column1 == [1, 2, 3] @test mattbl.Column2 == [4.0, 5.0, 6.0] @test mattbl.Column3 == [true, false, true] @test mattbl.Column4 == ["a", "b", "c"] matrowtbl = Tables.rows(mattbl) @test length(matrowtbl) === 3 @test ma2[2:end, 1] == [1, 2, 3] @test ma2[2:end, 2] == [4.0, 5.0, 6.0] @test ma2[2:end, 3] == [true, false, true] @test ma2[2:end, 4] == ["a", "b", "c"] @test ma2[1, :] == [:Column1, :Column2, :Column3, :Column4] # test our `Tables.AbstractColumns` interface methods @test Tables.getcolumn(mattbl, :Column1) == [1, 2, 3] @test Tables.getcolumn(mattbl, 1) == [1, 2, 3] @test Tables.columnnames(mattbl) == [:Column1, :Column2, :Column3, :Column4] # now let's iterate our MatrixTable to get our first MatrixRow matrow = first(matrowtbl) @test eltype(matrowtbl) == typeof(matrow) # now we can test our `Tables.AbstractRow` interface methods on our MatrixRow @test matrow.Column1 == 1 @test Tables.getcolumn(matrow, :Column1) == 1 @test Tables.getcolumn(matrow, 1) == 1 @test propertynames(mattbl) == propertynames(matrow) == [:Column1, :Column2, :Column3, :Column4] end @testset "5_Speci Tables" begin mat = [1 4.0 "7"; 2 5.0 "8"; 3 6.0 "9"] ct = [Int64, Float64, String] vof = ReadWriteDlm2.vecofvec(mat, ct) # take columns from array -> Vector{Vector{ct}} # first, create a MatrixTable from our Vector{Vector{T}} input mattbl = Tables.table(vof) # test that the MatrixTable `istable` @test Tables.istable(typeof(mattbl)) # test that it defines row access @test Tables.rowaccess(typeof(mattbl)) @test Tables.rows(mattbl) === mattbl # test that it defines column access @test Tables.columnaccess(typeof(mattbl)) @test Tables.columns(mattbl) === mattbl # test that we can access the first "column" of our matrix table by column name @test mattbl.Column1 == [1,2,3] # test our `Tables.AbstractColumns` interface methods @test Tables.getcolumn(mattbl, :Column1) == [1,2,3] @test Tables.getcolumn(mattbl, 1) == [1,2,3] @test Tables.getcolumn(mattbl, ReadWriteDlm2.MatrixTable, 1, :Column1) == [1,2,3] @test Tables.columnnames(mattbl) == [:Column1, :Column2, :Column3] @test length(mattbl) === 3 @test iterate(mattbl)[1] == first(mattbl) @test iterate(mattbl)[2] == 2 @test iterate(mattbl, 4) == nothing @test Tables.schema(mattbl) == Tables.Schema([:Column1, :Column2, :Column3], [Int64, Float64, String]) # now let's iterate our MatrixTable to get our first MatrixRow matrow = first(mattbl) @test eltype(mattbl) == typeof(matrow) # now we can test our `Tables.AbstractRow` interface methods on our MatrixRow @test matrow.Column1 == 1 @test matrow.Column2 == 4.0 @test Tables.getcolumn(matrow, :Column1) == 1 @test Tables.getcolumn(matrow, 1) == 1 @test Tables.getcolumn(matrow, ReadWriteDlm2.MatrixRow, 1, :Column1) == 1 @test propertynames(mattbl) == propertynames(matrow) == [:Column1, :Column2, :Column3] end @testset "5_rwdf Tables" begin ma_in = Any[1 4.0 "7"; 2 5.0 "8"; 3 6.0 "9"] ct = [Int64, Float64, String] # take columns from array -> Vector{Vector{ct}} vof = ReadWriteDlm2.vecofvec(ma_in, ct) # create a MatrixTable from our Vector{Vector{T}} input mattbl = Tables.table(vof) @test Tables.istable(typeof(mattbl)) # take data from Matrixtable mattbl in array ma_out = ReadWriteDlm2.mttoarray(mattbl, elt=Any) # test input array = output array @test ma_out == ma_in ma_in = Any[1 4.0 "7"; 2 5.0 "8"; 3 6.0 "9"] ct = [Float64, Float64, String] # take columns from array -> Vector{Vector{ct}} vof = ReadWriteDlm2.vecofvec(ma_in, ct) # create a MatrixTable from our Vector{Vector{T}} input mattbl = Tables.table(vof) @test Tables.istable(typeof(mattbl)) # take data from Matrixtable mattbl in array ma_out = ReadWriteDlm2.mttoarray(mattbl, elt=Union{String, Float64}) # test input array = output array (different types in column1), but ok @test ma_out == ma_in cn = [:date, :value_1, :value_2] mat = [Date(2017,1,1) 1.4 2; Date(2017,1,2) 1.8 3; nothing missing 4] ct = [Union{Nothing, Date}, Union{Missing, Float64}, Int64] cna = reshape(cn, 1, :) a = vcat(cna, mat) writedlm2("test.csv", a) astr = read("test.csv", String) cstr = "date;value_1;value_2\n2017-01-01;1,4;2\n2017-01-02;1,8;3\nnothing;na;4\n" @test astr == cstr rdlm1 = readdlm2("test.csv", tables=true, header=true) aro1 = ReadWriteDlm2.mttoarray(rdlm1) @test isequal(aro1, mat) rdlm2 = readdlm2("test.csv", Union{Missing, Nothing, Date, Float64}, tables=true, header=true) aro2 = ReadWriteDlm2.mttoarray(rdlm2) @test isequal(aro2, mat) rm("test.csv") end @testset "5_csvdlm Tables" begin cn = [:date, :value_1, :value_2] mat = [Date(2017,1,1) 1.4 2; Date(2017,1,2) 1.8 3] ct = [Union{Nothing, Date}, Union{Missing, Float64}, Int64] vof = ReadWriteDlm2.vecofvec(mat, ct) # take columns from array -> Vector{Vector{ct}} # first, create a MatrixTable from our Vector{Vector{T}} input mattdf = Tables.table(vof, header=cn) # write CSV cna = reshape(Tables.columnnames(mattdf), 1, :) amt = ReadWriteDlm2.mttoarray(mattdf) a = vcat(cna, amt) writedlm2("test1.csv", a) writecsv2("test2.csv", a) # read CSV / Tables Interface @test read("test1.csv", String) == "date;value_1;value_2\n2017-01-01;1,4;2\n2017-01-02;1,8;3\n" @test read("test2.csv", String) == "date,value_1,value_2\n2017-01-01,1.4,2\n2017-01-02,1.8,3\n" df2input1a = readdlm2("test1.csv", dfheader=true) df2input2a = readcsv2("test2.csv", dfheader=true) @test string(df2input1a) == string(df2input2a) df2input1 = readdlm2("test1.csv", tables=true, header=true) df2input2 = readcsv2("test2.csv", tables=true, header=true) @test string(df2input1) == string(df2input2) @test string(df2input1) == string(df2input1a) @test string(df2input2) == string(df2input2a) end @testset "5_MisNtg Tables" begin cn = [:date, :value_1, :value_2] mat = [Date(2017,1,1) 1.4 missing; Date(2017,1,2) 1.8 nothing] ct = [Date, Float64, Union{Missing, Nothing}] vof = ReadWriteDlm2.vecofvec(mat, ct) # take columns from array -> Vector{Vector{ct}} # first, create a MatrixTable from our Vector{Vector{T}} input mattdf = Tables.table(vof, header=cn) # write CSV cna = reshape(Tables.columnnames(mattdf), 1, :) amt = ReadWriteDlm2.mttoarray(mattdf) a = vcat(cna, amt) writedlm2("test1.csv", a) writecsv2("test2.csv", a) # read CSV / Tables Interface @test read("test1.csv", String) == "date;value_1;value_2\n2017-01-01;1,4;na\n2017-01-02;1,8;nothing\n" @test read("test2.csv", String) == "date,value_1,value_2\n2017-01-01,1.4,na\n2017-01-02,1.8,nothing\n" df2input1a = readdlm2("test1.csv", dfheader=true) df2input2a = readcsv2("test2.csv", dfheader=true) @test string(df2input1a) == string(df2input2a) df2input1 = readdlm2("test1.csv", tables=true, header=true) df2input2 = readcsv2("test2.csv", tables=true, header=true) @test string(df2input1) == string(df2input2) @test string(df2input1) == string(df2input1a) @test string(df2input2) == string(df2input2a) end
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
code
7784
#2020 Klaus Stricker - Tests for ReadWriteDlm2 #License is MIT: http://julialang.org/license # rwd2tests_6.jl @testset "6_1 Examples" begin # README.md - Basic Example a = ["text" 1.2; Date(2017,1,1) 1] # create array with eltype: String, Date, Float64 and Int writedlm2("test.csv", a) # test.csv(decimal comma): "text;1,2\n2017-01-01;1\n" @test readdlm2("test.csv") == a # read `CSV` data: All four eltypes are parsed correctly! b = readdlm2("test.csv", tables=true) # test Tables interface # b = ReadWriteDlm2.MatrixTable: (Column1 = Any["text", 2017-01-01], Column2 = Real[1.2, 1]) @test Tables.istable(typeof(b)) @test Tables.rowaccess(typeof(b)) @test Tables.getcolumn(b, :Column1) == Any["text", Date(2017,1,1)] @test Tables.getcolumn(b, :Column2) == Real[1.2, 1] @test Tables.getcolumn(b, 1) == Any["text", Date(2017,1,1)] @test Tables.getcolumn(b, 2) == Real[1.2, 1] @test Tables.columnnames(b) == [:Column1, :Column2] fr = first(b) # first row of 'b' = ReadWriteDlm2.MatrixRow: (Column1 = "text", Column2 = 1.2) @test eltype(b) == typeof(fr) # ReadWriteDlm2.MatrixRow # README.md - More Examples # `writecsv2()` And `readcsv2()` a = Any[1 complex(1.5,2.7);1.0 1//3] # create array with: Int, Complex, Float64 and Rational type writecsv2("test.csv", a) # test.csv(decimal dot): "1,1.5+2.7im\n1.0,1//3\n" @test readcsv2("test.csv") == a # read CSV data: All four types are parsed correctly! rm("test.csv") # `writedlm2()` And `readdlm2()` With Special `decimal=` a = Float64[1.1 1.2;2.1 2.2] writedlm2("test.csv", a; decimal='€') # '€' is decimal Char in 'test.csv' @test readdlm2("test.csv", Float64; decimal='€') == a # standard: use keyword argument @test readdlm2("test.csv", Float64; rs=(r"(\d)€(\d)", s"\1.\2")) == a # alternativ: rs-Regex-Tupel rm("test.csv") # `writedlm2()` And `readdlm2()` With `Union{Missing, Float64}` a = Union{Missing, Float64}[1.1 0/0;missing 2.2;1/0 -1/0] writedlm2("test.csv", a; missingstring="???") # use "???" for missing data @test read("test.csv", String) == "1,1;NaN\n???;2,2\nInf;-Inf\n" b = readdlm2("test.csv", Union{Missing, Float64}; missingstring="???") @test typeof(a) == typeof(b) @test isequal(a, b) rm("test.csv") # `Date` And `DateTime` With `locale="french"` Dates.LOCALES["french"] = Dates.DateLocale( ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], ["janv", "févr", "mars", "avril", "mai", "juin", "juil", "août", "sept", "oct", "nov", "déc"], ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"], ["lu", "ma", "me", "je", "ve", "sa", "di"], ); a = hcat([Date(2017,1,1), DateTime(2017,1,1,5,59,1,898), 1, 1.0, "text"]) writedlm2("test.csv", a; dfs="E, d.U yyyy", dtfs="e, d.u yyyy H:M:S,s", locale="french") @test read("test.csv", String) == "dimanche, 1.janvier 2017\ndi, 1.janv 2017 5:59:1,898\n1\n1,0\ntext\n" @test readdlm2("test.csv"; dfs="E, d.U yyyy", dtfs="e, d.u yyyy H:M:S,s", locale="french") == a rm("test.csv") end @testset "6_2 df-Examples" begin cn = [:date, :value_1, :value_2] mat = [Date(2017,1,1) 1.4 2; Date(2017,1,2) 1.8 3; nothing missing 4] ct = [Union{Nothing, Date}, Union{Missing, Float64}, Int64] vof = ReadWriteDlm2.vecofvec(mat, ct) # take columns from array -> Vector{Vector{ct}} # first, create a MatrixTable from our Vector{Vector{T}} input mattdf = Tables.table(vof, header=cn) # test that the MatrixTable `istable` @test Tables.istable(typeof(mattdf)) # test that it defines row access @test Tables.rowaccess(typeof(mattdf)) @test Tables.rows(mattdf) === mattdf # test that it defines column access @test Tables.columnaccess(typeof(mattdf)) @test Tables.columns(mattdf) === mattdf # test that we can access the first "column" of our matrix table by column name @test mattdf.date == [Date(2017,1,1),Date(2017,1,2),nothing] # test our `Tables.AbstractColumns` interface methods @test Tables.getcolumn(mattdf, :date) == [Date(2017,1,1),Date(2017,1,2),nothing] @test Tables.getcolumn(mattdf, 1) == [Date(2017,1,1),Date(2017,1,2),nothing] @test Tables.columnnames(mattdf) == [:date, :value_1, :value_2] # now let's iterate our MatrixTable to get our first MatrixRow matrow = first(mattdf) @test eltype(mattdf) == typeof(matrow) # now we can test our `Tables.AbstractRow` interface methods on our MatrixRow @test matrow.date == Date(2017,1,1) @test matrow.value_1 == 1.4 @test Tables.getcolumn(matrow, :date) == Date(2017,1,1) @test Tables.getcolumn(matrow, 1) == Date(2017,1,1) @test propertynames(mattdf) == propertynames(matrow) == cn # write CSV cna = reshape(Tables.columnnames(mattdf), 1, :) amt = ReadWriteDlm2.mttoarray(mattdf) a = vcat(cna, amt) writedlm2("test1.csv", a) writecsv2("test2.csv", a) # read CSV / Tables Interface @test read("test1.csv", String) == "date;value_1;value_2\n2017-01-01;1,4;2\n2017-01-02;1,8;3\nnothing;na;4\n" @test read("test2.csv", String) == "date,value_1,value_2\n2017-01-01,1.4,2\n2017-01-02,1.8,3\nnothing,na,4\n" df2input1 = readdlm2("test1.csv", tables=true, header=true) df2input2 = readcsv2("test2.csv", tables=true, header=true) rm("test1.csv") rm("test2.csv") # test result from reading csv @test Tables.istable(typeof(df2input1)) @test Tables.istable(typeof(df2input2)) # test that it defines row access @test Tables.rowaccess(typeof(df2input1)) @test Tables.rowaccess(typeof(df2input2)) @test Tables.rows(df2input1) === df2input1 @test Tables.rows(df2input2) === df2input2 # test that it defines column access @test Tables.columnaccess(typeof(df2input1)) @test Tables.columnaccess(typeof(df2input2)) @test Tables.columns(df2input1) === df2input1 @test Tables.columns(df2input2) === df2input2 # test that we can access the first "column" of our matrix table by column name @test df2input1.date == [Date(2017,1,1),Date(2017,1,2),nothing] @test df2input2.date == [Date(2017,1,1),Date(2017,1,2),nothing] # test our `Tables.AbstractColumns` interface methods @test Tables.getcolumn(df2input1, :date) == [Date(2017,1,1),Date(2017,1,2),nothing] @test Tables.getcolumn(df2input1, 1) == [Date(2017,1,1),Date(2017,1,2),nothing] @test Tables.columnnames(df2input1) == [:date, :value_1, :value_2] @test Tables.getcolumn(df2input2, :date) == [Date(2017,1,1),Date(2017,1,2),nothing] @test Tables.getcolumn(df2input2, 1) == [Date(2017,1,1),Date(2017,1,2),nothing] @test Tables.columnnames(df2input2) == [:date, :value_1, :value_2] # now let's iterate our MatrixTable to get our first MatrixRow matrow = first(df2input1) @test eltype(df2input1) == typeof(matrow) matrow = first(df2input2) @test eltype(df2input2) == typeof(matrow) # now we can test our `Tables.AbstractRow` interface methods on our MatrixRow @test matrow.date == Date(2017,1,1) @test matrow.value_1 == 1.4 @test Tables.getcolumn(matrow, :date) == Date(2017,1,1) @test Tables.getcolumn(matrow, 1) == Date(2017,1,1) @test propertynames(df2input1) == propertynames(matrow) == cn @test matrow.date == Date(2017,1,1) @test matrow.value_1 == 1.4 @test Tables.getcolumn(matrow, :date) == Date(2017,1,1) @test Tables.getcolumn(matrow, 1) == Date(2017,1,1) @test propertynames(df2input2) == propertynames(matrow) == cn end
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.8.2
b89320763efe871aec3d3ae7b4fd24ddb1130dbc
docs
13458
# ReadWriteDlm2 ### CSV IO Supports Decimal Comma, Date, DateTime, Time, Complex, Missing and Rational [![Build status](https://github.com//strickek/ReadWriteDlm2.jl/workflows/CI/badge.svg)](https://github.com//strickek/ReadWriteDlm2.jl/actions) [![Build status](https://ci.appveyor.com/api/projects/status/ojv8nnuw63kh9yba/branch/main?svg=true)](https://ci.appveyor.com/project/strickek/readwritedlm2-jl/branch/main) [![codecov.io](http://codecov.io/github/strickek/ReadWriteDlm2.jl/coverage.svg?branch=main)](http://codecov.io/github/strickek/ReadWriteDlm2.jl?branch=main) `ReadWriteDlm2` functions `readdlm2()`, `writedlm2()`, `readcsv2()` and `writecsv2()` are similar to those of stdlib.DelimitedFiles, but with additional support for `Dates` formats, `Complex`, `Rational`, `Missing` types and special decimal marks. `ReadWriteDlm2` supports the `Tables.jl` interface. * For "decimal dot" users the functions `readcsv2()` and `writecsv2()` have the respective defaults: Delimiter is `','` (fixed) and `decimal='.'`. * The basic idea of `readdlm2()` and `writedlm2()` is to support the [decimal comma countries](https://commons.wikimedia.org/wiki/File:DecimalSeparator.svg?uselang=en#file). These functions use `';'` as default delimiter and `','` as default decimal mark. "Decimal dot" users of these functions need to define `decimal='.'`. * Alternative package: `CSV` (supports also special decimal marks) ### Installation This package is registered and can be installed within the [`Pkg` REPL-mode](https://docs.julialang.org/en/latest/stdlib/Pkg/): Type `]` in the REPL and then: ``` pkg> add ReadWriteDlm2 ``` ### Basic Example([-> more](#more-examples)): How To Use `ReadWriteDlm2` ``` julia> using ReadWriteDlm2, Dates # activate modules ReadWriteDlm2, Dates julia> a = ["text" 1.2; Date(2017,1,1) 1]; # create array with: String, Date, Float64 and Int eltype julia> writedlm2("test.csv", a) # test.csv(decimal comma): "text;1,2\n2017-01-01;1\n" julia> readdlm2("test.csv") # read `CSV` data: All four eltypes are parsed correctly! 2×2 Array{Any,2}: "text" 1.2 2017-01-01 1 julia> using DataFrames # Tables interface: auto Types for DataFrame columns julia> DataFrame(readdlm2("test.csv", tables=true)) 2×2 DataFrame │ Row │ Column1 │ Column2 │ │ │ Any │ Real │ ├─────┼────────────┼─────────┤ │ 1 │ text │ 1.2 │ │ 2 │ 2017-01-01 │ 1 │ ``` ## Function `readdlm2()` Read a matrix from `source`. The `source` can be a text file, stream or byte array. Each line, separated by `eol` (default is `'\n'`), gives one row. The columns are separated by `';'`, another `delim` can be defined. readdlm2(source; options...) readdlm2(source, T::Type; options...) readdlm2(source, delim::Char; options...) readdlm2(source, delim::Char, T::Type; options...) readdlm2(source, delim::Char, eol::Char; options...) readdlm2(source, delim::Char, T::Type, eol::Char; options...) Pre-processing of `source` with regex substitution changes the decimal marks from `d,d` to `d.d`. For default `rs` the keyword argument `decimal=','` sets the decimal Char in the `r`-string of `rs`. When a special regex substitution tuple `rs=(r.., s..)` is defined, the argument `decimal` is not used ( [-> Example](#writedlm2-and-readdlm2-with-special-decimal)). Pre-processing can be switched off with: `rs=()`. In addition to stdlib `readdlm()`, data is also parsed for `Dates` formats (ISO), the`Time` format `HH:MM[:SS[.s{1,9}]]` and for complex and rational numbers. To deactivate parsing dates/time set: `dfs="", dtfs=""`. `locale` defines the language of day (`E`, `e`) and month (`U`, `u`) names. The result will be a (heterogeneous) array of default element type `Any`. If `header=true` it will be a tuple containing the data array and a vector for the columnnames. Other (abstract) types for the data array elements could be defined. If data is empty, a `0×0 Array{T,2}` is returned. With `tables=true`[, `header=true`] option[s] a `Tables` interface compatible `MatrixTable` with individual column types is returned, which for example can be used as argument for `DataFrame()`. ### Additional Keyword Arguments `readdlm2()` * `decimal=','`: Decimal mark Char used by default `rs`, irrelevant if `rs`-tuple is not the default one * `rs=(r"(\d),(\d)", s"\1.\2")`: [Regex](https://docs.julialang.org/en/latest/manual/strings/#Regular-Expressions-1) (r,s)-tuple, the default change d,d to d.d if `decimal=','` * `dtfs="yyyy-mm-ddTHH:MM:SS.s"`: [Format string](https://docs.julialang.org/en/latest/stdlib/Dates/#Dates.DateFormat) for DateTime parsing * `dfs="yyyy-mm-dd"`: [Format string](https://docs.julialang.org/en/latest/stdlib/Dates/#Dates.DateFormat) for Date parsing * `locale="english"`: Language for parsing dates names, default is english * `tables=false`: Return `Tables` interface compatible MatrixTable if `true` * `dfheader=false`: `dfheader=true` is shortform for `tables=true, header=true` * `missingstring="na"`: How missing values are represented, default is `"na"` ### Function `readcsv2()` readcsv2(source, T::Type=Any; opts...) Equivalent to `readdlm2()` with delimiter `','` and `decimal='.'`. ### Documentation For Base `readdlm()` More information about Base functionality and (keyword) arguments - which are also supported by `readdlm2()` and `readcsv2()` - is available in the [documentation for readdlm()](https://docs.julialang.org/en/latest/stdlib/DelimitedFiles/#DelimitedFiles.readdlm-Tuple{Any,AbstractChar,Type,AbstractChar}). ### Compare Default Functionality `readdlm()` - `readdlm2()` - `readcsv2()` | Module | Function | Delimiter | Dec. Mark | Element Type | Ext. Parsing | |:-------------- |:----------------------------|:----------:|:---------:|:-------------|:-------------| | DelimitedFiles | `readdlm()` | `' '` | `'.'` | Float64/Any | No (String) | | ReadWriteDlm2 | `readdlm2()` | `';'` | `','` | Any | Yes | | ReadWriteDlm2 | `readcsv2()` | `','` | `'.'` | Any | Yes | | ReadWriteDlm2 | `readdlm2(opt:tables=true)` | `';'` | `','` | Column spec. | Yes, + col T | | ReadWriteDlm2 | `readcsv2(opt:tables=true)` | `','` | `'.'` | Column spec. | Yes, + col T | ## Function `writedlm2()` Write `A` (a vector, matrix, or an iterable collection of iterable rows, a `Tables` source) as text to `f` (either a filename or an IO stream). The columns are separated by `';'`, another `delim` (Char or String) can be defined. writedlm2(f, A; options...) writedlm2(f, A, delim; options...) By default, a pre-processing of values takes place. Before writing as strings, decimal marks are changed from `'.'` to `','`. With a keyword argument another decimal mark can be defined. To switch off this pre-processing set: `decimal='.'`. In `writedlm2()` the output format for `Date` and `DateTime` data can be defined with format strings. Defaults are the ISO formats. Day (`E`, `e`) and month (`U`, `u`) names are written in the `locale` language. For writing `Complex` numbers the imaginary component suffix can be selected with the `imsuffix=` keyword argument. ### Additional Keyword Arguments `writedlm2()` * `decimal=','`: Character for writing decimal marks, default is a comma * `dtfs="yyyy-mm-ddTHH:MM:SS.s"`: [Format string](https://docs.julialang.org/en/latest/stdlib/Dates/#Dates.DateFormat), DateTime write format * `dfs="yyyy-mm-dd"`: [Format string](https://docs.julialang.org/en/latest/stdlib/Dates/#Dates.DateFormat), Date write format * `locale="english"`: Language for writing date names, default is english * `imsuffix="im"`: Complex - imaginary component suffix `"im"`(=default), `"i"` or `"j"` * `missingstring="na"`: How missing values are written, default is `"na"` ### Function `writecsv2()` writecsv2(f, A; opts...) Equivalent to `writedlm2()` with fixed delimiter `','` and `decimal='.'`. ### Compare Default Functionality `writedlm()` - `writedlm2()` - `writecsv2()` | Module | Function | Delimiter | Decimal Mark | |:--------------- |:------------------ |:---------:|:------------:| | DelimitedFiles | `writedlm()` | `'\t'` | `'.'` | | ReadWriteDlm2 | `writedlm2()` | `';'` | `','` | | ReadWriteDlm2 | `writecsv2()` | `','` | `'.'` | ## More Examples #### `writecsv2()` And `readcsv2()` ``` julia> using ReadWriteDlm2 julia> a = Any[1 complex(1.5,2.7);1.0 1//3]; # create array with: Int, Complex, Float64 and Rational type julia> writecsv2("test.csv", a) # test.csv(decimal dot): "1,1.5+2.7im\n1.0,1//3\n" julia> readcsv2("test.csv") # read CSV data: All four types are parsed correctly! 2×2 Array{Any,2}: 1 1.5+2.7im 1.0 1//3 ``` #### `writedlm2()` And `readdlm2()` With Special `decimal=` ``` julia> using ReadWriteDlm2 julia> a = Float64[1.1 1.2;2.1 2.2] 2×2 Array{Float64,2}: 1.1 1.2 2.1 2.2 julia> writedlm2("test.csv", a; decimal='€') # '€' is decimal Char in 'test.csv' julia> readdlm2("test.csv", Float64; decimal='€') # a) standard: use keyword argument 2×2 Array{Float64,2}: 1.1 1.2 2.1 2.2 julia> readdlm2("test.csv", Float64; rs=(r"(\d)€(\d)", s"\1.\2")) # b) more flexible: rs-Regex-Tupel 2×2 Array{Float64,2}: 1.1 1.2 2.1 2.2 ``` #### `writedlm2()` And `readdlm2()` With `Union{Missing, Float64}` ``` julia> using ReadWriteDlm2 julia> a = Union{Missing, Float64}[1.1 0/0;missing 2.2;1/0 -1/0] 3×2 Array{Union{Missing, Float64},2}: 1.1 NaN missing 2.2 Inf -Inf julia> writedlm2("test.csv", a; missingstring="???") # use "???" for missing data julia> read("test.csv", String) "1,1;NaN\n???;2,2\nInf;-Inf\n" julia> readdlm2("test.csv", Union{Missing, Float64}; missingstring="???") 3×2 Array{Union{Missing, Float64},2}: 1.1 NaN missing 2.2 Inf -Inf ``` #### `Date` And `DateTime` With `locale="french"` ``` julia> using ReadWriteDlm2, Dates julia> Dates.LOCALES["french"] = Dates.DateLocale( ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], ["janv", "févr", "mars", "avril", "mai", "juin", "juil", "août", "sept", "oct", "nov", "déc"], ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"], ["lu", "ma", "me", "je", "ve", "sa", "di"], ); julia> a = hcat([Date(2017,1,1), DateTime(2017,1,1,5,59,1,898), 1, 1.0, "text"]) 5x1 Array{Any,2}: 2017-01-01 2017-01-01T05:59:01.898 1 1.0 "text" julia> writedlm2("test.csv", a; dfs="E, d.U yyyy", dtfs="e, d.u yyyy H:M:S,s", locale="french") julia> read("test.csv", String) # to see what have been written in "test.csv" file "dimanche, 1.janvier 2017\ndi, 1.janv 2017 5:59:1,898\n1\n1,0\ntext\n" julia> readdlm2("test.csv"; dfs="E, d.U yyyy", dtfs="e, d.u yyyy H:M:S,s", locale="french") 5×1 Array{Any,2}: 2017-01-01 2017-01-01T05:59:01.898 1 1.0 "text" ``` #### `Tables`-Interface Example With `DataFrames` See [-> `DataFrames`](https://github.com/JuliaData/DataFrames.jl) for installation and more information. ``` julia> using ReadWriteDlm2, Dates, DataFrames, Statistics ``` ##### Write CSV: `Tables & DataFrames` compared with `Array` ``` julia> a = ["date" "value_1" "value_2"; # Create Array `a` Date(2017,1,1) 1.4 2; Date(2017,1,2) 1.8 3; nothing missing 4] 4×3 Array{Any,2}: "date" "value_1" "value_2" 2017-01-01 1.4 2 2017-01-02 1.8 3 nothing missing 4 julia> df = DataFrame( # Create DataFrame `df` date = [Date(2017,1,1), Date(2017,1,2), nothing], value_1 = [1.4, 1.8, missing], value_2 = [2, 3, 4] ) 3×3 DataFrame │ Row │ date │ value_1 │ value_2 │ │ │ Union… │ Float64⍰ │ Int64 │ ├─────┼────────────┼──────────┼─────────┤ │ 1 │ 2017-01-01 │ 1.4 │ 2 │ │ 2 │ 2017-01-02 │ 1.8 │ 3 │ │ 3 │ │ missing │ 4 │ julia> writedlm2("testa_com.csv", a) # decimal comma: write array a julia> writedlm2("testdf_com.csv", df) # decimal comma: write DataFrame df julia> read("testa_com.csv", String) == # decimal comma: a.csv == df.csv read("testdf_com.csv", String) == "date;value_1;value_2\n2017-01-01;1,4;2\n2017-01-02;1,8;3\nnothing;na;4\n" true julia> writecsv2("testa_dot.csv", a) # decimal dot: write array a julia> writecsv2("testdf_dot.csv", df) # decimal dot: write DataFrame df julia> read("testa_dot.csv", String) == # decimal dot: a.csv == df.csv read("testdf_dot.csv", String) == "date,value_1,value_2\n2017-01-01,1.4,2\n2017-01-02,1.8,3\nnothing,na,4\n" true ``` ##### Read CSV: Using `Tables` interface and create a `DataFrame` ``` julia> df2 = DataFrame(readdlm2("testdf_com.csv", header=true, tables=true)) 3×3 DataFrame │ Row │ date │ value_1 │ value_2 │ │ │ Union… │ Float64⍰ │ Int64 │ ├─────┼────────────┼──────────┼─────────┤ │ 1 │ 2017-01-01 │ 1.4 │ 2 │ │ 2 │ 2017-01-02 │ 1.8 │ 3 │ │ 3 │ │ missing │ 4 │ julia> mean(skipmissing(df2[!, :value_1])) 1.6 julia> mean(df2[!, :value_2]) 3.0 ```
ReadWriteDlm2
https://github.com/strickek/ReadWriteDlm2.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
854
using ClassicalOrthogonalPolynomials, Plots ## # Ideal fluid flow consists of level sets of the imagainary part of a function # that is asymptotic to c*z and whose imaginary part vanishes on Γ # # # On the unit interval, -2*H*u gives the imaginary part of cauchy(u,x) # So if we want to find u defined on Γ so that stieltjes(u,x) = imag(c*x) # then c*z + 2cauchy(u,z) vanishes on Γ ## T = ChebyshevT() U = ChebyshevU() x = axes(U,1) H = inv.(x .- x') c = exp(0.5im) u = Weighted(U) * ((H * Weighted(U)) \ imag(c * x)) ε = eps(); (inv.(0.1+ε*im .- x') * u + inv.(0.1-ε*im .- x') * u)/2 ≈ imag(c*0.1) ε = eps(); real(inv.(0.1+ε*im .- x') * u ) ≈ imag(c*0.1) v = (s,t) -> (z = (s + im*t); imag(c*z) - real(inv.(z .- x') * u)) xx = range(-3,3; length=100) yy = range(-1,1; length=100) plot([-1,1],[0,0]; color=:black) contour!(xx,yy,v.(xx',yy))
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
3137
module SingularIntegrals using ClassicalOrthogonalPolynomials, ContinuumArrays, QuasiArrays, LazyArrays, LazyBandedMatrices, FillArrays, BandedMatrices, LinearAlgebra, SpecialFunctions, HypergeometricFunctions, InfiniteArrays using ContinuumArrays: @simplify, Weight, AbstractAffineQuasiVector, inbounds_getindex, broadcastbasis, MappedBasisLayouts, MemoryLayout, MappedWeightLayout, AbstractWeightLayout, ExpansionLayout, demap, basismap, AbstractBasisLayout, SubBasisLayout using QuasiArrays: AbstractQuasiMatrix, BroadcastQuasiMatrix, LazyQuasiArrayStyle, AbstractQuasiVecOrMat import ClassicalOrthogonalPolynomials: AbstractJacobiWeight, WeightedBasis, jacobimatrix, orthogonalityweight, recurrencecoefficients, _p0, Clenshaw, chop, initiateforwardrecurrence, MappedOPLayouts, unweighted, WeightedOPLayout, MappedOPLayout using LazyBandedMatrices: Tridiagonal, SymTridiagonal, subdiagonaldata, supdiagonaldata, diagonaldata, ApplyLayout import LazyArrays: AbstractCachedMatrix, AbstractCachedArray, paddeddata, arguments, resizedata!, cache_filldata!, zero!, cacheddata, LazyArrayStyle import Base: *, +, -, /, \, Slice, axes, getindex, sum, ==, oneto, size, broadcasted, copy, tail, view import LinearAlgebra: dot using BandedMatrices: _BandedMatrix using FastTransforms: _forwardrecurrence!, _forwardrecurrence_next export associated, stieltjes, logkernel, powerkernel, complexlogkernel include("recurrence.jl") include("stieltjes.jl") include("logkernel.jl") include("power.jl") ### generic fallback for Op in (:Stieltjes, :StieltjesPoint, :LogKernelPoint, :PowerKernelPoint, :LogKernel) @eval begin @simplify function *(H::$Op, wP::WeightedBasis{<:Any,<:Weight,<:Any}) w,P = wP.args Q = OrthogonalPolynomial(w) (H * Weighted(Q)) * (Q \ P) end @simplify *(H::$Op, wP::Weighted{<:Any,<:SubQuasiArray{<:Any,2}}) = H * view(Weighted(parent(wP.P)), parentindices(wP.P)...) end end for lk in (:complexlogkernel, :stieltjes) lk_layout = Symbol(lk, :_layout) @eval $lk_layout(::AbstractBasisLayout, P, z...) = error("not implemented") end # general routines for lk in (:logkernel, :complexlogkernel, :stieltjes) lk_layout = Symbol(lk, :_layout) @eval begin $lk_layout(::AbstractWeightLayout, w, zs::AbstractVector) = [stieltjes(w, z) for z in zs] function $lk_layout(::AbstractWeightLayout, w, z::Inclusion) axes(w,1) == z || error("Not implemented") $lk(w) end function $lk_layout(::AbstractBasisLayout, w, z::Inclusion) axes(w,1) == z || error("Not implemented") $lk(w) end $lk_layout(lay, P, z...) = $lk(expand(P), z...) function $lk_layout(LAY::ApplyLayout{typeof(*)}, V::AbstractQuasiVecOrMat, y...) a = arguments(LAY, V) *($lk(a[1], y...), tail(a)...) end $lk_layout(::ExpansionLayout, A, dims...) = $lk_layout(ApplyLayout{typeof(*)}(), A, dims...) $lk_layout(::SubBasisLayout, A, dims...) = $lk(parent(A), dims...)[:, parentindices(A)[2]] end end end # module SingularIntegrals
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
7629
const ComplexLogKernelPoint{T,C,W<:Number,V,D} = BroadcastQuasiMatrix{T,typeof(log),Tuple{ConvKernel{C,W,V,D}}} const ComplexLogKernelPoints{T,C,W<:AbstractVector{<:Number},V,D} = BroadcastQuasiMatrix{T,typeof(log),Tuple{ConvKernel{C,W,V,D}}} const LogKernelPoint{T<:Real,C,W<:Number,V,D} = BroadcastQuasiMatrix{T,typeof(log),Tuple{BroadcastQuasiMatrix{T,typeof(abs),Tuple{ConvKernel{C,W,V,D}}}}} const LogKernelPoints{T<:Real,C,W<:AbstractVector{<:Number},V,D} = BroadcastQuasiMatrix{T,typeof(log),Tuple{BroadcastQuasiMatrix{T,typeof(abs),Tuple{ConvKernel{C,W,V,D}}}}} const LogKernel{T,D1,D2} = BroadcastQuasiMatrix{T,typeof(log),Tuple{BroadcastQuasiMatrix{T,typeof(abs),Tuple{ConvKernel{T,Inclusion{T,D1},T,D2}}}}} @simplify function *(L::LogKernel, P::AbstractQuasiVecOrMat) T = promote_type(eltype(L), eltype(P)) logkernel(convert(AbstractQuasiArray{T}, P)) end @simplify function *(L::LogKernelPoint, P::AbstractQuasiVecOrMat) T = promote_type(eltype(L), eltype(P)) z, xc = L.args[1].args[1].args logkernel(convert(AbstractQuasiArray{T}, P), z) end @simplify function *(L::LogKernelPoints, P::AbstractQuasiVecOrMat) T = promote_type(eltype(L), eltype(P)) z, xc = L.args[1].args[1].args logkernel(convert(AbstractQuasiArray{T}, P), z) end @simplify function *(L::ComplexLogKernelPoint, P::AbstractQuasiVecOrMat) z, xc = L.args[1].args T = promote_type(eltype(L), eltype(P)) complexlogkernel(convert(AbstractQuasiArray{T}, P), z) end @simplify function *(L::ComplexLogKernelPoints, P::AbstractQuasiVecOrMat) z, xc = L.args[1].args T = promote_type(eltype(L), eltype(P)) complexlogkernel(convert(AbstractQuasiArray{T}, P), z) end ### # LogKernel ### """ logkernel(P) applies the log kernel log(abs(x-t)) to the columns of a quasi matrix, i.e., `(log.(abs.(x - x')) * P)/π` """ logkernel(P, z...) = logkernel_layout(MemoryLayout(P), P, z...) """ complexlogkernel(P) applies the log kernel log(x-t) to the columns of a quasi matrix, i.e., `(log.(x - x') * P)` """ complexlogkernel(P, z...) = complexlogkernel_layout(MemoryLayout(P), P, z...) logkernel(wT::Weighted{T,<:ChebyshevT}) where T = ChebyshevT{T}() * Diagonal(Vcat(-convert(T,π)*log(2*one(T)),-convert(T,π)./(1:∞))) function logkernel_layout(::Union{MappedBasisLayouts, MappedOPLayouts}, wT) V = eltype(wT) kr = basismap(wT) @assert kr isa AbstractAffineQuasiVector W = demap(wT) A = kr.A # L = logkernel(W) # Σ = sum(W; dims=1) # basis(L)[kr,:] * (coefficients(L)/A - OneElement(∞) * Σ*log(abs(A))/A) @assert W isa Weighted{<:Any,<:ChebyshevT} unweighted(wT) * Diagonal(Vcat(-convert(V,π)*(log(2*one(V))+log(abs(A)))/A,-convert(V,π) ./ (A * (1:∞)))) end function logkernel_demap(wT, z) P = demap(wT) kr = basismap(wT) z̃ = inbounds_getindex(kr, z) c = inv(kr.A) LP = logkernel(P, z̃) Σ = sum(P; dims=1) transpose(c*transpose(LP) .+ c*log(c)*vec(Σ)) end logkernel_layout(::Union{MappedBasisLayouts, MappedOPLayouts}, wT, z...) = logkernel_demap(wT, z...) logkernel_layout(::WeightedOPLayout{MappedOPLayout}, wT, z::Real) = logkernel_demap(wT, z) #### # LogKernelPoint #### function complexlogkernel_ics(wP::Weighted{<:Any,<:ChebyshevT}, z::Number) V = promote_type(eltype(wP), typeof(z)) ξ = inv(z + sqrtx2(z)) r0 = convert(V,π)*(-log(ξ)-log(convert(V,2))) r1 = -convert(V,π)*ξ r2 = convert(V,π)/2 + z*r1 r0,r1,r2 end function complexlogkernel_recurrence(wP::Weighted{<:Any,<:ChebyshevT}) # We have for n ≠ 0 L_n(z) = stieltjes(U_n, z) # where U_n(z) = ∫_1^x T_n(x)/sqrt(1-x^2) dx = -(1-x^2)^(-1/2)T_{n-1}(x)/n # We have the 3-term recurrence # T_{n+1}(x) == 2 x T_n(x) - T_{n-1}(x) # Thus # U_{n+1}(x) == -(1-x^2)^(-1/2) T_n(x)/(n+1) # == -(1-x^2)^(-1/2) * ( 2x T_{n-1}(x) - T_{n-2}(x))/(n+1) # == -(1-x^2)^(-1/2) * ( 2n/(n+1) x T_{n-1}(x)/n - (n-1)/(n+1) T_{n-2}(x)/(n-1)) # == (2n/(n+1) * x U_n(x) - (n - 1)/(n+1) * U_{n-1}(x) R = real(eltype(wP)) n = zero(R):∞ (2n) ./ (n .+ 1), Zeros{R}(∞), (n .- 1) ./ (n .+ 1) end function complexlogkernel_ics(wP::Weighted{<:Any,<:ChebyshevU}, z::Number) T = promote_type(eltype(wP), typeof(z)) ξ = inv(z + sqrtx2(z)) r0 = convert(T,π)*(ξ^2/4 - (log.(abs.(ξ)) + log(2*one(T)))/2) r1 = convert(T,π)*(ξ^3/3 - ξ)/2 r2 = convert(T,π)*(ξ^4/4 - ξ^2/2)/2 r0,r1,r2 end function complexlogkernel_recurrence(wP::Weighted{<:Any,<:ChebyshevU}) # We have for n ≠ 0 L_n(z) = stieltjes(U_n, z) # where U_n(z) = ∫_1^x sqrt(1-x^2) U_n(x) dx = -(1-x^2)^(3/2)C_{n-1}(x) * 2/(n * (n + 2)) # where C_n(x) = C_n^{(2)}(x) # We have the 3-term recurrence # C_{n+1}(x) == 2(n + 2) / (n + 1) * x C_n(x) - (n + 3) / (n + 1) C_{n-1}(x) # Thus # U_{n+1}(x) == -(1-x^2)^(3/2) C_n(x) * 2/((n+1) * (n + 3)) # == -(1-x^2)^(3/2) * 2/((n+1) * (n + 3)) ( 2(n + 1) / n * x C_{n-1}(x) - (n + 2) / n C_{n-2}(x)) # == -(1-x^2)^(3/2) * (4 / (n*(n+3)) * x C_{n-1}(x) - 2 (n + 2) /(n*(n+1)*(n+3)) C_{n-2}(x)) # == -(1-x^2)^(3/2) * (2 (n-1)*(n+1) / (n*(n+3)) * x 2/((n-1)*(n+1)) C_{n-1}(x) - (n + 2)*(n-1) /(n*(n+3)) * 2/((n-1)*(n+1)) C_{n-2}(x)) # == (2 (n+2)/(n+3) * x U_n(x) - (n + 2)*(n-1) /(n*(n+3)) * U_{n-1}(x) R = real(eltype(wP)) n = zero(R):∞ (2*(n .+ 2)) ./ (n .+ 3), Zeros{R}(∞), (n .+ 2) .* (n .- 1) ./ (n .* (n .+ 3)) end function complexlogkernel_ics(P::Weighted{<:Any,<:Legendre}, z::Number) T = promote_type(eltype(P), typeof(z)) r0 = (1 + z)log(1 + z) - (z-1)log(z-1) - 2one(T) r1 = (z+1)*r0/2 + 1 - (z+1)log(z+1) r2 = z*r1 + 2*one(T)/3 r0,r1,r2 end function complexlogkernel_recurrence(wP::Weighted{<:Any,<:Legendre}) # We have for n ≠ 0 L_n(z) = stieltjes(U_n, z) # where U_n(z) = ∫_1^x P_n(x) dx = C_{n+1}^{(-1/2)}(x) # Since these are equivalent to weihted OPs (1-x^2)C_{n-1}^(3/2)(x) # we know they satisfy the same recurrence coefficients. # Thus the following could also be written: # A,B,C = recurrencecoefficients(Ultraspherical(-1/2)) # A[2:end],B[2:end],C[2:end] R = real(eltype(wP)) ((one(R):2:∞)./(2:∞), Zeros{R}(∞), (-one(R):∞)./(2:∞)) end complexlogkernel(P::Legendre, z...) = complexlogkernel(Weighted(P), z...) logkernel(P::Legendre, x...) = logkernel(Weighted(P), x...) complexlogkernel_layout(::WeightedOPLayout, wP, z::Number) = transpose(RecurrenceArray(z, complexlogkernel_recurrence(wP), [complexlogkernel_ics(wP,z)...])) function complexlogkernel_layout(::WeightedOPLayout, wP, zs::AbstractVector) T = promote_type(eltype(wP), eltype(zs)) m = length(zs) data = Matrix{T}(undef, 3, m) for j = 1:m z = zs[j] data[1:3,j] .= complexlogkernel_ics(wP, z) end transpose(RecurrenceArray(zs, complexlogkernel_recurrence(wP), data)) end logkernel_layout(::AbstractBasisLayout, P, z...) = real.(complexlogkernel(P, z...)) function logkernel_layout(::WeightedOPLayout, P, x::Real) L = transpose(complexlogkernel(P, complex(x))) transpose(RecurrenceArray(x, (L.A, L.B, L.C), real.(L.data))) end function logkernel_layout(::WeightedOPLayout, P, x::AbstractVector{<:Real}) L = transpose(complexlogkernel(P, complex(x))) transpose(RecurrenceArray(x, (L.A, L.B, L.C), real.(L.data))) end ### # Maps ### function logkernel(S::PiecewiseInterlace, z::Number) @assert length(S.args) == 2 a,b = S.args xa,xb = axes(a,1),axes(b,1) Sa = logkernel(a, z) Sb = logkernel(b, z) transpose(BlockBroadcastArray(vcat, unitblocks(transpose(Sa)), unitblocks(transpose(Sb)))) end
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
2128
const PowerKernel{T,D1,D2,F<:Real} = BroadcastQuasiMatrix{T,typeof(^),Tuple{BroadcastQuasiMatrix{T,typeof(abs),Tuple{ConvKernel{T,Inclusion{T,D1},T,D2}}},F}} # recognize structure of W = abs.(t .- x).^a const PowerKernelPoint{T,W<:Number,V,D,A<:Number} = BroadcastQuasiMatrix{T,typeof(^),Tuple{BroadcastQuasiMatrix{T,typeof(abs),Tuple{ConvKernel{T,W,V,D}}},A}} @simplify function *(K::PowerKernelPoint, wC::AbstractQuasiVecOrMat) T = promote_type(eltype(K), eltype(wC)) cnv,α = K.args z,x = cnv.args[1].args powerkernel(convert(AbstractQuasiArray{T}, wC), α, z) end ### # PowerKernel ### function powerlawmoment(::Val{0}, α, λ, z::Real) T = promote_type(typeof(α), typeof(λ), typeof(z)) if -1 ≤ z ≤ 1 beta((α+one(T))/2, λ+one(T)/2)_₂F₁(-α/2, -λ-α/2, one(T)/2, z^2) else beta(one(T)/2, λ+one(T)/2)abs(z)^α*_₂F₁((1-α)/2, -α/2, 1+λ, 1/z^2) end end function powerlawmoment(::Val{1}, α, λ, z::Real) T = promote_type(typeof(α), typeof(λ), typeof(z)) if -1 ≤ z ≤ 1 -2^(2-α)*λ*sqrt(convert(T,π))*gamma(α+2)*gamma(λ+one(T)/2)/(gamma(α/2)*gamma(α/2+λ+1))*((2*z^2*(α+λ)+1)*_₂F₁(-α/2,-λ-α/2,one(T)/2,z^2)+(z^2-1)*_₂F₁(-α/2,-λ-α/2,-one(T)/2,z^2))/(α*(α+1)*(α+2*λ+1)*z)+2*λ*z*gamma((α+1)/2)*gamma(λ+one(T)/2)/(gamma(λ+α/2+1))*_₂F₁(-α/2,-λ-α/2,one(T)/2,z^2) else -sign(z)α*λ*beta(one(T)/2, λ+one(T)/2)*abs(z)^(α-1)*_₂F₁((1-α)/2, 1-α/2, 2+λ, 1/z^2)/(1+λ) end end powerkernel(wC::UltrasphericalWeight, α, z) = powerlawmoment(Val(0), α, wC.λ, z) powerkernel(wC::LegendreWeight, α, z) = powerkernel(UltrasphericalWeight(wC), α, z) function powerlawrecurrence(α, λ) T = promote_type(typeof(α), typeof(λ)) n = 0:∞ A = @. 2*(λ + n) * (2λ + n) / ((n+1)*(2λ+n+α+1)) B = Zeros{T}(∞) C = @. (n-α-1)*(2λ+n-1)*(2λ+n)/(n*(n+1)*(2λ+n+α+1)) A,B,C end powerkernel(wC::Legendre{T}, α, z) where T = powerkernel(Weighted(Ultraspherical{T}(one(T)/2)), α, z) function powerkernel(wC::Weighted, α, z) λ = wC.P.λ transpose(RecurrenceArray(z, powerlawrecurrence(α, λ), [powerlawmoment(Val(0), α, λ, z), powerlawmoment(Val(1), α, λ, z)])) end
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
7478
""" r = RecurrenceArray(z, (A, B, C), data) is a vector corresponding to the non-domainant solution to the recurrence relationship, for `k = size(data,1)` r[1:k,:] == data r[k+1,j] == (A[k]z[j] + B[k])r[k,j] - C[k]*r[k-1,j] """ mutable struct RecurrenceArray{T, N, ZZ, AA<:AbstractVector, BB<:AbstractVector, CC<:AbstractVector} <: AbstractCachedArray{T,N} z::ZZ A::AA B::BB C::CC data::Array{T,N} datasize::NTuple{N,Int} p0::Vector{T} # stores p_{s-1} to determine when to switch to backward p1::Vector{T} # stores p_{s} to determine when to switch to backward u::Vector{T} # used for backsubstitution to store diagonal of U in LU end const RecurrenceVector{T, A<:AbstractVector, B<:AbstractVector, C<:AbstractVector} = RecurrenceArray{T, 1, T, A, B, C} const RecurrenceMatrix{T, Z<:AbstractVector, A<:AbstractVector, B<:AbstractVector, C<:AbstractVector} = RecurrenceArray{T, 2, Z, A, B, C} RecurrenceArray(z, A, B, C, data::Array{T,N}, datasize, p0, p1) where {T,N} = RecurrenceArray{T,N,typeof(z),typeof(A),typeof(B),typeof(C)}(z, A, B, C, data, datasize, p0, p1, T[]) function RecurrenceArray(z::Number, (A,B,C), data::AbstractVector{T}) where T N = length(data) p0, p1 = initiateforwardrecurrence(N, A, B, C, z, one(z)) if iszero(p1) p1 = one(p1) # avoid degeneracy in recurrence. Probably needs more thought end RecurrenceVector{T,typeof(A),typeof(B),typeof(C)}(z, A, B, C, data, size(data), T[p0], T[p1], T[]) end function RecurrenceArray(z::AbstractVector, (A,B,C), data::AbstractMatrix{T}) where T M,N = size(data) p0 = Vector{T}(undef, N) p1 = Vector{T}(undef, N) for j = axes(z,1) p0[j], p1[j] = initiateforwardrecurrence(M, A, B, C, z[j], one(T)) if iszero(p1[j]) p1[j] = one(p1[j]) # avoid degeneracy in recurrence. Probably needs more thought end end RecurrenceMatrix{T,typeof(z),typeof(A),typeof(B),typeof(C)}(z, A, B, C, data, size(data), p0, p1, T[]) end size(R::RecurrenceVector) = (ℵ₀,) # potential to add maximum size of operator size(R::RecurrenceMatrix) = (ℵ₀, size(R.data,2)) # potential to add maximum size of operator copy(R::RecurrenceArray) = R # immutable entries function _growdata!(B::AbstractArray{<:Any,N}, nm::Vararg{Integer,N}) where N # increase size of array if necessary olddata = B.data νμ = size(olddata) nm = max.(νμ,nm) if νμ ≠ nm B.data = similar(B.data, nm...) B.data[axes(olddata)...] = olddata end end # to estimate error in forward recurrence we compute the dominant solution (the OPs) simeultaneously function resizedata!(K::RecurrenceArray, m, n...) m ≤ 0 && return K # increase size of array if necessary _growdata!(K, m, n...) ν = K.datasize[1] if m > ν A,B,C = K.A,K.B,K.C tol = 100 for j = axes(K.z,1) z = K.z[j] if ν > 2 && iszero(K.data[ν-1,j]) && iszero(K.data[ν,j]) # no data zero!(view(K.data, ν+1:m, j)) else p0, p1 = K.p0[j], K.p1[j] k = ν while abs(p1) < tol*k && k < m p1,p0 = _forwardrecurrence_next(k, A, B, C, z, p0, p1),p1 k += 1 end K.p0[j], K.p1[j] = p0, p1 if k > ν _forwardrecurrence!(view(K.data,:,j), A, B, C, z, ν:k) end if k < m if K isa AbstractVector backwardrecurrence!(K, A, B, C, z, k:m) else backwardrecurrence!(K, A, B, C, z, k:m, j) end end end end K.datasize = (max(K.datasize[1],m), tail(K.datasize)...) end end function backwardrecurrence!(K, A, B, C, z, nN::AbstractUnitRange, j...) n,N = first(nN),last(nN) T = eltype(z) tol = 100eps(real(T)) maxiterations = 100_000_000 data = K.data u = K.u resize!(u, max(length(u), N)) # we use data as a working vector and do an inplace LU # r[n+1] - (A[n]z + B[n])r[n] + C[n] r[n-1] == 0 u[n+1] = -(A[n+1]z + B[n+1]) data[n+1, j...] = -C[n+1]*data[n, j...] # forward elimination k = n+1 while abs(data[k,j...]) > tol k ≥ maxiterations && error("maximum iterations reached") if k == N # need to resize data, lets use rate of decay as estimate μ = min(abs(data[k,j...]/data[k-1,j...]), abs(data[k-1,j...]/data[k-2,j...])) # data[k] * μ^M ≤ ε # M ≥ log(ε/data[k])/log(μ) N = ceil(Int, max(2N, min(maxiterations, log(eps(real(T))/100)/log(μ+eps(real(T)))))) _growdata!(K, N, j...) resize!(u, N) data = K.data end ℓ = -C[k+1]/u[k] u[k+1] = ℓ-(A[k+1]z + B[k+1]) data[k+1,j...] = ℓ*data[k,j...] k += 1 end data[k,j...] /= u[k] # back-sub for κ = k-1:-1:n+1 data[κ,j...] = (data[κ,j...] - data[κ+1,j...])/u[κ] end for κ = k+1:N data[κ,j...] = 0 end K end ### # override indexing to resize first #### function _getindex_resize_iffinite!(A, kr, jr, m::Int) resizedata!(A, m, size(A,2)) A.data[kr,jr] end _getindex_resize_iffinite!(A, kr, jr, _) = layout_getindex(A, kr, jr) @inline getindex(A::RecurrenceMatrix, kr::AbstractUnitRange, jr::AbstractUnitRange) = _getindex_resize_iffinite!(A, kr, jr, maximum(kr)) @inline getindex(A::RecurrenceMatrix, kr::AbstractVector, jr::AbstractVector) = _getindex_resize_iffinite!(A, kr, jr, maximum(kr)) @inline getindex(A::RecurrenceMatrix, k::Integer, jr::AbstractVector) = _getindex_resize_iffinite!(A, k, jr, k) @inline getindex(A::RecurrenceMatrix, k::Integer, jr::AbstractUnitRange) = _getindex_resize_iffinite!(A, k, jr, k) @inline getindex(A::RecurrenceMatrix, k::Integer, ::Colon) = _getindex_resize_iffinite!(A, k, :, k) @inline getindex(A::RecurrenceMatrix, kr::AbstractVector, ::Colon) = _getindex_resize_iffinite!(A, kr, :, maximum(kr)) @inline getindex(A::RecurrenceMatrix, kr::AbstractUnitRange, ::Colon) = _getindex_resize_iffinite!(A, kr, :, maximum(kr)) function view(A::RecurrenceVector, kr::AbstractVector) resizedata!(A, maximum(kr)) view(A.data, kr) end ### # broadcasted ### broadcasted(::LazyArrayStyle, op, A::Transpose{<:Any,<:RecurrenceArray}) = transpose(op.(parent(A))) broadcasted(::LazyArrayStyle, ::typeof(*), c::Number, A::RecurrenceArray) = RecurrenceArray(A.z, A.A, A.B, A.C, c .* A.data, A.datasize, c .* A.p0, c .* A.p1) function recurrence_broadcasted(op, A::RecurrenceMatrix, x::AbstractVector) p = paddeddata(x) n = size(p,1) resizedata!(A, n, size(p,2)) data = copy(A.data) data[1:n,:] .+= p RecurrenceArray(A.z, A.A, A.B, A.C, data, A.datasize, A.p0, A.p1) end function recurrence_broadcasted(op, A::RecurrenceVector, x::AbstractVector) p = paddeddata(x) n = size(p,1) resizedata!(A, n) data = copy(A.data) data[1:n] .+= p RecurrenceArray(A.z, A.A, A.B, A.C, data, A.datasize, A.p0, A.p1) end for op in (:+, :-) @eval begin broadcasted(::LazyArrayStyle, ::typeof($op), A::RecurrenceArray, x::AbstractVector) = recurrence_broadcasted($op, A, x) broadcasted(::LazyArrayStyle, ::typeof($op), A::RecurrenceVector, x::Vcat{<:Any,1}) = recurrence_broadcasted($op, A, x) end end
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
7968
#### # Associated #### """ AssociatedWeighted(P) We normalise so that `orthogonalityweight(::Associated)` is a probability measure. """ struct AssociatedWeight{T,OPs<:AbstractQuasiMatrix{T}} <: Weight{T} P::OPs end axes(w::AssociatedWeight) = (axes(w.P,1),) sum(::AssociatedWeight{T}) where T = one(T) """ Associated(P) constructs the associated orthogonal polynomials for P, which have the Jacobi matrix jacobimatrix(P)[2:end,2:end] and constant first term. Or alternatively w = orthogonalityweight(P) A = recurrencecoefficients(P)[1] Associated(P) == (w/(sum(w)*A[1]))'*((P[:,2:end]' - P[:,2:end]) ./ (x' - x)) where `x = axes(P,1)`. """ struct Associated{T, OPs<:AbstractQuasiMatrix{T}} <: OrthogonalPolynomial{T} P::OPs end associated(P) = Associated(P) axes(Q::Associated) = axes(Q.P) ==(A::Associated, B::Associated) = A.P == B.P orthogonalityweight(Q::Associated) = AssociatedWeight(Q.P) function associated_jacobimatrix(X::Tridiagonal) c,a,b = subdiagonaldata(X),diagonaldata(X),supdiagonaldata(X) Tridiagonal(c[2:end], a[2:end], b[2:end]) end function associated_jacobimatrix(X::SymTridiagonal) a,b = diagonaldata(X),supdiagonaldata(X) SymTridiagonal(a[2:end], b[2:end]) end jacobimatrix(a::Associated) = associated_jacobimatrix(jacobimatrix(a.P)) associated(::ChebyshevT{T}) where T = ChebyshevU{T}() associated(::ChebyshevU{T}) where T = ChebyshevU{T}() const ConvKernel{T,D1,V,D2} = BroadcastQuasiMatrix{T,typeof(-),Tuple{D1,QuasiAdjoint{V,Inclusion{V,D2}}}} const StieltjesPoint{T,W<:Number,V,D} = BroadcastQuasiMatrix{T,typeof(inv),Tuple{ConvKernel{T,W,V,D}}} const StieltjesPoints{T,W<:AbstractVector{<:Number},V,D} = BroadcastQuasiMatrix{T,typeof(inv),Tuple{ConvKernel{T,W,V,D}}} const Stieltjes{T,D1,D2} = BroadcastQuasiMatrix{T,typeof(inv),Tuple{ConvKernel{T,Inclusion{T,D1},T,D2}}} @simplify function *(H::Stieltjes, w::AbstractQuasiVecOrMat) T = promote_type(eltype(H), eltype(w)) stieltjes(convert(AbstractQuasiArray{T}, w), axes(H,1)) end @simplify function *(H::StieltjesPoint, w::AbstractQuasiMatrix) T = promote_type(eltype(H), eltype(w)) z = H.args[1].args[1] convert(AbstractArray{T}, stieltjes(w, z)) end @simplify function *(H::StieltjesPoint, w::AbstractQuasiVector) T = promote_type(eltype(H), eltype(w)) z = H.args[1].args[1] convert(T, stieltjes(w, z)) end """ stieltjes(P, y) computes inv.(y - x') * P understood in a principle value sense. """ stieltjes(P, y...) = stieltjes_layout(MemoryLayout(P), P, y...) """ stieltjes(P) computes inv.(x - x') * P understood in a principle value sense. """ stieltjes(w::ChebyshevTWeight{T}) where T = zeros(T, axes(w,1)) stieltjes(w::ChebyshevUWeight{T}) where T = convert(T,π) * axes(w,1) function stieltjes(w::LegendreWeight{T}) where T x = axes(w,1) log.(x .+ one(T)) .- log.(one(T) .- x) end stieltjes(wT::Weighted{T,<:ChebyshevT}) where T = ChebyshevU{T}() * _BandedMatrix(Fill(-convert(T,π),1,∞), ℵ₀, -1, 1) stieltjes(wU::Weighted{T,<:ChebyshevU}) where T = ChebyshevT{T}() * _BandedMatrix(Fill(convert(T,π),1,∞), ℵ₀, 1, -1) function stieltjes(wP::Weighted{<:Any,<:OrthogonalPolynomial}) P = wP.P w = orthogonalityweight(P) A = recurrencecoefficients(P)[1] Q = associated(P) (-A[1]*sum(w))*[zero(axes(P,1)) Q] + stieltjes(w) .* P end stieltjes(P::Legendre) = stieltjes(Weighted(P)) ## # OffStieltjes ## function stieltjes(W::Weighted{<:Any,<:ChebyshevU}, x::Inclusion) x == axes(W,1) && return stieltjes(W) tol = eps() T̃ = chebyshevt(x) ψ_1 = T̃ \ inv.(x .+ sqrtx2.(x)) # same ψ_1 = x .- sqrt(x^2 - 1) but with relative accuracy as x -> ∞ M = Clenshaw(T̃ * ψ_1, T̃) data = zeros(eltype(ψ_1), ∞, ∞) # Operator has columns π * ψ_1^k copyto!(view(data,:,1), convert(eltype(data),π)*ψ_1) for j = 2:∞ mul!(view(data,:,j),M,view(data,:,j-1)) norm(view(data,:,j)) ≤ tol && break end # we wrap in a Padded to avoid increasing cache size T̃ * PaddedArray(chop(paddeddata(data), tol), size(data)...) end #### # StieltjesPoint #### stieltjesmoment_jacobi_normalization(n::Int,α::Real,β::Real) = 2^(α+β)*gamma(n+α+1)*gamma(n+β+1)/gamma(2n+α+β+2) function stieltjes(w::AbstractJacobiWeight, z::Number) α,β = real(w.a),real(w.b) (x = 2/(1-z);stieltjesmoment_jacobi_normalization(0,α,β)*HypergeometricFunctions.mxa_₂F₁(1,α+1,α+β+2,x)) end function stieltjes(w::ChebyshevTWeight{T}, z::Number) where T α,β = w.a,w.b z in axes(w,1) && return zero(T) convert(T, π)/sqrtx2(z) end function stieltjes(w::ChebyshevUWeight{T}, z::Number) where T α,β = w.a,w.b z in axes(w,1) && return π*z convert(T, π)/(z + sqrtx2(z)) end @simplify function *(S::StieltjesPoints, w::Weight) zs = S.args[1].args[1] # vector of points to eval at stieltjes(w, zs) end function stieltjes(wP::Weighted, z::Number) P = wP.P w = orthogonalityweight(P) A,B,C = recurrencecoefficients(P) r1 = stieltjes(w, z)*_p0(P) # stieltjes of the weight # (a[1]-z)*r[1] + b[1]r[2] == -sum(w)*_p0(P) # (a[1]/b[1]-z/b[1])*r[1] + r[2] == -sum(w)*_p0(P)/b[1] # (A[1]z + B[1])*r[1] - r[2] == A[1]sum(w)*_p0(P) # (A[1]z + B[1])*r[1]-A[1]sum(w)*_p0(P) == r[2] r2 = (A[1]z + B[1])*r1-A[1]sum(w)*_p0(P) transpose(RecurrenceArray(z, (A,B,C), [r1,r2])) end function stieltjes(wP::Weighted, z::AbstractVector) T = promote_type(eltype(z), eltype(wP)) P = wP.P A,B,C = recurrencecoefficients(P) w = orthogonalityweight(P) data = Matrix{T}(undef, 2, length(z)) data[1,:] .= stieltjes(w, z) .* _p0(P) data[2,:] .= (A[1] .* z .+ B[1]) .* data[1,:] .- (A[1]sum(w)*_p0(P)) transpose(RecurrenceArray(z, (A,B,C), data)) end sqrtx2(z::Number) = sqrt(z-1)*sqrt(z+1) sqrtx2(x::Real) = sign(x)*sqrt(x^2-1) stieltjes(P::Legendre, z...) = stieltjes(Weighted(P), z...) @simplify function *(S::StieltjesPoints, wP::Weighted) z = S.args[1].args[1] # vector of points to eval at stieltjes(wP, z) end @simplify function *(S::StieltjesPoints, P::Legendre) S * Weighted(P) end ## # mapped ### function stieltjes_layout(::MappedWeightLayout, w::SubQuasiArray{<:Any,1}) m = parentindices(w)[1] # TODO: mapping other geometries P = parent(w) stieltjes(P)[m] end function stieltjes_layout(::MappedWeightLayout, w::AbstractQuasiVector, z::Number) m = basismap(w) # TODO: mapping other geometries P = demap(w) stieltjes(P, inbounds_getindex(m, z)) end function stieltjes_layout(::Union{MappedBasisLayouts, MappedOPLayouts}, wP::AbstractQuasiMatrix, x::Inclusion) kr = basismap(wP) W = demap(wP) t̃ = axes(W,1) t = axes(wP,1) x == t && return stieltjes(W)[kr,:] M = affine(t,t̃) @assert x isa Inclusion a,b = first(x),last(x) x̃ = Inclusion((M.A * a .+ M.b)..(M.A * b .+ M.b)) # map interval to new interval Q̃,M = arguments(*, stieltjes(W, x̃)) parent(Q̃)[affine(x,axes(parent(Q̃),1)),:] * M end function stieltjes_layout(::Union{MappedBasisLayouts, MappedOPLayouts}, wT::AbstractQuasiMatrix, z::Number) P = demap(wT) z̃ = inbounds_getindex(basismap(wT), z) stieltjes(P, z̃) end ### # Interlace ### function stieltjes(W::PiecewiseInterlace) Hs = broadcast(function(a,b) x,t = axes(a,1),axes(b,1) H = stieltjes(b, x) H end, [W.args...], permutedims([W.args...])) N = length(W.args) Ts = [broadcastbasis(+, broadcast(H -> H.args[1], Hs[k,:])...) for k=1:N] Ms = broadcast((T,H) -> unitblocks(T\H), Ts, Hs) PiecewiseInterlace(Ts...) * BlockBroadcastArray{eltype(W)}(hvcat, N, permutedims(Ms)...) end function stieltjes(S::PiecewiseInterlace, z::Number) @assert length(S.args) == 2 a,b = S.args Sa = stieltjes(a, z) Sb = stieltjes(b, z) transpose(BlockBroadcastArray(vcat, unitblocks(transpose(Sa)), unitblocks(transpose(Sb)))) end
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
1064
using SingularIntegrals, ClassicalOrthogonalPolynomials, ContinuumArrays, QuasiArrays, BandedMatrices, LinearAlgebra, Test using SingularIntegrals: Stieltjes, StieltjesPoint, ChebyshevInterval, associated, Associated, orthogonalityweight, Weighted, *, dot using LazyArrays: MemoryLayout, PaddedLayout, colsupport, rowsupport, paddeddata using LazyBandedMatrices: blockcolsupport, Block, BlockHcat, blockbandwidths include("test_recurrence.jl") @testset "Associated" begin T = ChebyshevT() U = ChebyshevU() @test associated(T) ≡ U @test associated(U) ≡ U @test Associated(T)[0.1,1:10] == Associated(U)[0.1,1:10] == U[0.1,1:10] P = Legendre() Q = Associated(P) x = axes(P,1) u = Q * (Q \ exp.(x)) @test u[0.1] ≈ exp(0.1) @test grid(Q[:,Base.OneTo(5)]) ≈ eigvals(Matrix(jacobimatrix(Normalized(Q))[1:5,1:5])) w = orthogonalityweight(Q) @test axes(w,1) == axes(P,1) @test sum(w) == 1 end include("test_stieltjes.jl") include("test_logkernel.jl") include("test_power.jl") include("test_piecewise.jl")
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
6745
using SingularIntegrals, ClassicalOrthogonalPolynomials, FillArrays, Test using SingularIntegrals: RecurrenceArray, LogKernelPoint using ClassicalOrthogonalPolynomials: affine @testset "ComplexLogKernelPoint" begin P = Legendre() Pc = Legendre{ComplexF64}() x = axes(P,1) L = (z,k) -> sum(Pc / Pc \ (log.(z .- x).*P[:,k+1])) for z in (5, 1+2im, -1+2im, 1-2im, -3+0.0im, -3-0.0im) @test (log.(z .- x') * P)[1:5] ≈ L.(z, 0:4) end for z in ([2.1,3.], [2.1+im,-3-im]) @test (log.(z .- x') * P)[:,1:5] ≈ L.(z, (0:4)') end for z in (-5,-1,0,0.1) @test_throws DomainError log.(z .- x') * P end @testset "expand" begin @test complexlogkernel(exp.(x), 2 + im) ≈ sum(log.((2+im) .- x) .* exp.(x)) @test_throws ErrorException complexlogkernel(Jacobi(0.1,0.2), 2+im) end end @testset "LogKernelPoint" begin @testset "Complex point" begin wU = Weighted(ChebyshevU()) x = axes(wU,1) z = 0.1+0.2im L = log.(abs.(z .- x')) @test L isa LogKernelPoint{Float64,ComplexF64,ComplexF64,Float64,ChebyshevInterval{Float64}} @test (L * wU)[1:5] ≈ [ -1.2919202947616695, -0.20965486677056738, 0.6799687631764493, 0.13811497572177128, -0.2289481463304956] @test L * (wU / wU \ @.(exp(x) * sqrt(1 - x^2))) ≈ -1.4812979070884382 wT = Weighted(ChebyshevT()) @test L * (wT / wT \ @.(exp(x) / sqrt(1 - x^2))) ≈ -1.9619040529776954 #mathematica end @testset "Real point" begin T = ChebyshevT() U = ChebyshevU() x = axes(U,1) t = 2.0 @test (log.(abs.(t .- x') )* Weighted(T))[1,1:3] ≈ [1.9597591637624774, -0.8417872144769223, -0.11277810215896047] #mathematica @test (log.(abs.(t .- x') )* Weighted(U))[1,1:3] ≈ [1.0362686329607178,-0.4108206734393296, -0.054364775221816465] #mathematica t = 0.5 @test (log.(abs.(t .- x') )* Weighted(T))[1,1:3] ≈ [-2.1775860903036017, -1.5707963267948832, 0.7853981633974272] #mathematica @test (log.(abs.(t .- x') )* Weighted(U))[1,1:3] ≈ [-1.4814921268505252, -1.308996938995747, 0.19634954084936207] #mathematica t = 0.5+0im @test (log.(abs.(t .- x') )* Weighted(T))[1,1:3] ≈ [-2.1775860903036017, -1.5707963267948832, 0.7853981633974272] #mathematica @test (log.(abs.(t .- x') )* Weighted(U))[1,1:3] ≈ [-1.4814921268505252, -1.308996938995747, 0.19634954084936207] #mathematica # checks for degeneracy in recurrence initial conditions @test iszero(logkernel(Weighted(T), 10.3)[100]) end @testset "mapped" begin x = Inclusion(1..2) wU = Weighted(ChebyshevU())[affine(x, axes(ChebyshevU(),1)),:] x = axes(wU,1) z = 5 L = log.(abs.(z .- x')) f = wU / wU \ @.(sqrt(2-x)sqrt(x-1)exp(x)) @test L*f ≈ 2.2374312398976586 # MAthematica wU = Weighted(chebyshevu(1..2)) f = wU / wU \ @.(sqrt(2-x)sqrt(x-1)exp(x)) @test L*f ≈ 2.2374312398976586 # MAthematica @testset "vector" begin z = [3.1,4] wU = Weighted(ChebyshevU())[affine(x, axes(ChebyshevU(),1)),:] c = wU \ @.(sqrt(2-x)sqrt(x-1)exp(x)) x = axes(wU,1) @test logkernel(wU, z)[:,1:1000] == (log.(abs.(z .- x')) * wU)[:,1:1000] @test logkernel(wU, z) * c ≈ [logkernel(wU, 3.1)*c, logkernel(wU, 4)*c] end end @testset "Legendre" begin @testset "Float64" begin P = Legendre() x = axes(P,1) L = (z,k) -> sum(P / P \ (log.(abs.(z .- x)).*P[:,k+1])) for z in (5, 1+2im, -1+2im, 1-2im, -3+0.0im, -3-0.0im, -3) @test (log.(abs.(z .- x')) * P)[1:10] ≈ L.(z, 0:9) end end @testset "BigFloat" begin z = big(5.0) P = Legendre{BigFloat}() x = axes(P,1) L = (z,k) -> sum(P / P \ (log.(abs.(z .- x)).*P[:,k+1])) @test (log.(abs.(z .- x')) * P)[1:10] ≈ L.(z, 0:9) end @testset "derivation" begin W = Weighted(Jacobi(1,1)) P = Legendre() x = axes(P,1) L = (z,k) -> sum(P / P \ (log.(abs.(z .- x)).*P[:,k+1])) z = 5 @test L(z,0) ≈ 2log(z+1) + inv.(z .- x') * (P / P \ (x .- 1)) ≈ (1 + z)log(1 + z) - (z-1)log(z-1) - 2 @test L(z,1) ≈ (inv.(z .- x') * W)[1]/(-2) @test z * L(z,0) ≈ 2z*log(z+1) + z*(inv.(z .- x') * (P / P \ (x .- 1))) ≈ 2z*log(z+1) + (inv.(z .- x') * (P / P \ (x.^2 .- 1))) + (inv.(z .- x') * (P / P \ (1 .- x))) - 2 ≈ 2L(z,1) - L(z,0) + 2(z+1)*log(z+1) - 2 @test z * L(z,1) ≈ z * (inv.(z .- x') * W)[1]/(-2) ≈ -2/3 + (inv.(z .- x') * (x .* W))[1]/(-2) ≈ -2/3 + (inv.(z .- x') * W)[2]/(-4) ≈ -2/3 + L(z,2) for k = 2:5 @test z * L(z,k) ≈ (k-1)/(2k+1)*L(z,k-1)+ (k+2)/(2k+1)*L(z,k+1) @test (2k+1)/(k+2)*z * L(z,k) ≈ (k-1)/(k+2)*L(z,k-1)+ L(z,k+1) end r0 = (1 + z)log(1 + z) - (z-1)log(z-1) - 2 r1 = (z+1)*r0/2 + 1 - (z+1)log(z+1) r2 = z*r1 + 2*one(z)/3 r = RecurrenceArray(z, ((1:2:∞)./(2:∞), Zeros(∞), (-1:∞)./(2:∞)), [r0,r1,r2]) @test r[1:10] ≈ L.(z,0:9) end end end @testset "Log kernel" begin T = Chebyshev() wT = Weighted(Chebyshev()) x = axes(wT,1) L = log.(abs.(x .- x')) D = T \ (L * wT) @test ((L * wT) * (T \ exp.(x)))[0.] ≈ -2.3347795490945797 # Mathematica x = Inclusion(-1..1) T = Chebyshev()[1x, :] L = log.(abs.(x .- x')) wT = Weighted(Chebyshev())[1x, :] @test (T \ (L*wT))[1:10,1:10] ≈ D[1:10,1:10] x = Inclusion(0..1) T = Chebyshev()[2x.-1, :] wT = Weighted(Chebyshev())[2x .- 1, :] L = log.(abs.(x .- x')) u = wT * (2 *(T \ exp.(x))) @test u[0.1] ≈ exp(0.1)/sqrt(0.1-0.1^2) @test (L * u)[0.5] ≈ -7.471469928754152 # Mathematica @testset "mapped" begin T = chebyshevt(0..1) x = axes(T,1) L = log.(abs.(x .- x')) @test T[0.2,:]'*((T\L*Weighted(T)) * (T\exp.(x))) ≈ -2.9976362326874373 # Mathematica end @testset "Legendre" begin P = Legendre() f = expand(P, exp) @test logkernel(f, 0.1) ≈ logkernel(f, complex(0.1)) ≈ -2.3204982810441956 @test logkernel(f, [0.1,1.2,-0.5]) ≈ logkernel(f, ComplexF64[0.1,1.2,-0.5]) @test logkernel(f, 0.1 + 0.2im) ≈ -1.6570185704416018 end @testset "sub-Legendre" begin P = Legendre() @test logkernel(P[:,1:10],0.1)' == logkernel(P, 0.1)'[1:10] end end
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
2576
@testset "two-interval" begin T1,T2 = chebyshevt((-2)..(-1)), chebyshevt(0..2) U1,U2 = chebyshevu((-2)..(-1)), chebyshevu(0..2) W = PiecewiseInterlace(Weighted(U1), Weighted(U2)) T = PiecewiseInterlace(T1, T2) U = PiecewiseInterlace(U1, U2) x = axes(W,1) H = T \ inv.(x .- x') * W; @test iszero(H[1,1]) @test H[3,1] ≈ π @test maximum(blockcolsupport(H,Block(5))) ≤ Block(50) @test blockbandwidths(H) == (25,26) c = W \ broadcast(x -> exp(x)* (0 ≤ x ≤ 2 ? sqrt(2-x)*sqrt(x) : sqrt(-1-x)*sqrt(x+2)), x) f = W * c @test T[0.5,1:200]'*(H*c)[1:200] ≈ -6.064426633490422 @testset "inversion" begin H̃ = BlockHcat(Eye((axes(H,1),))[:,Block(1)], H) @test blockcolsupport(H̃,Block(1)) == Block.(1:1) @test last(blockcolsupport(H̃,Block(2))) ≤ Block(30) UT = U \ T D = U \ Derivative(x) * T V = x -> x^4 - 10x^2 Vp = x -> 4x^3 - 20x V_cfs = T \ V.(x) Vp_cfs_U = D * V_cfs Vp_cfs_T = T \ Vp.(x); @test (UT \ Vp_cfs_U)[Block.(1:10)] ≈ Vp_cfs_T[Block.(1:10)] @time c = H̃ \ Vp_cfs_T; @test c[Block.(1:100)] ≈ H̃[Block.(1:100),Block.(1:100)] \ Vp_cfs_T[Block.(1:100)] E1,E2 = c[Block(1)] @test [E1,E2] ≈ [12.939686758642496,-10.360345667126758] c1 = [paddeddata(c)[3:2:end]; Zeros(∞)] c2 = [paddeddata(c)[4:2:end]; Zeros(∞)] u1 = Weighted(U1) * c1 u2 = Weighted(U2) * c2 x1 = axes(u1,1) x2 = axes(u2,1) @test inv.(-1.3 .- x1') * u1 + inv.(-1.3 .- x2') * u2 + E1 ≈ Vp(-1.3) @test inv.(1.3 .- x1') * u1 + inv.(1.3 .- x2') * u2 + E2 ≈ Vp(1.3) end @testset "Stieltjes" begin z = 5.0 @test inv.(z .- x')*f ≈ 1.317290060427562 t = 1.2 @test inv.(t .- x')*f ≈ -2.797995066227555 @test log.(abs.(t .- x'))*f ≈ -5.9907385495482821485 @test log.(abs.(z .- x'))*f ≈ 6.523123127595374 @test log.(abs.((-z) .- x'))*f ≈ 8.93744698863906 end end @testset "three-interval" begin d = (-2..(-1), 0..1, 2..3) T = PiecewiseInterlace(chebyshevt.(d)...) U = PiecewiseInterlace(chebyshevu.(d)...) W = PiecewiseInterlace(Weighted.(U.args)...) x = axes(W,1) H = T \ inv.(x .- x') * W c = W \ broadcast(x -> exp(x) * if -2 ≤ x ≤ -1 sqrt(x+2)sqrt(-1-x) elseif 0 ≤ x ≤ 1 sqrt(1-x)sqrt(x) else sqrt(x-2)sqrt(3-x) end, x) f = W * c @test T[0.5,1:200]'*(H*c)[1:200] ≈ -3.0366466972156143 end
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
3166
using SingularIntegrals, ClassicalOrthogonalPolynomials, Test using SingularIntegrals: PowerKernelPoint, powerlawmoment, powerlawrecurrence, RecurrenceArray @testset "Weights" begin z = 10.0 x = axes(ChebyshevT(),1) α = 0.1 L = abs.(z .- x') .^ α # from Mathmatica λ = 1 L0 = powerlawmoment(Val(0), α, λ, z) L1 = powerlawmoment(Val(1), α, λ, z) @test L* UltrasphericalWeight(λ) ≈ L0 ≈ 1.9772924292721128 @test L1 ≈ -0.009901716900034385 A, B, C = powerlawrecurrence(α, λ) @test (A[2]z + B[2])*L1-C[2]L0 ≈ -0.00022324029766696007 r = RecurrenceArray(z, (A,B,C), [L0,L1]) @test r[5] ≈ -2.5742591209035326E-7 @test r[1:10] ≈ (L * Weighted(Ultraspherical(λ)))[1,1:10] @test L* LegendreWeight() ≈ 2.517472100701719 @test (L * Legendre())[5] ≈ -1.3328397976790363E-7 end @testset "Compare with Mathematica results" begin @testset "z >> 1" begin z = 10.0 x = axes(ChebyshevT(),1) α = 0.1 L = abs.(z .- x') .^ α # from Mathematica λ = 1 L0 = powerlawmoment(Val(0), α, λ, z) L1 = powerlawmoment(Val(1), α, λ, z) @test L* UltrasphericalWeight(λ) ≈ L0 ≈ 1.9772924292721128 @test L1 ≈ -0.009901716900034385 A, B, C = powerlawrecurrence(α, λ) @test (A[2]z + B[2])*L1-C[2]L0 ≈ -0.00022324029766696007 r = RecurrenceArray(z, (A,B,C), [L0,L1]) @test r[5] ≈ -2.5742591209035326E-7 @test r[1:10] ≈ (L * Weighted(Ultraspherical(λ)))[1,1:10] @test L* LegendreWeight() ≈ 2.517472100701719 @test (L * Legendre())[5] ≈ -1.3328397976790363E-7 end @testset "z > 1" begin z = 1.1 x = axes(ChebyshevT(),1) α = 0.1 L = abs.(z .- x') .^ α # from Mathematica λ = 1 L0 = powerlawmoment(Val(0), α, λ, z) L1 = powerlawmoment(Val(1), α, λ, z) @test L* UltrasphericalWeight(λ) ≈ L0 ≈ 1.56655191643602910 @test L1 ≈ -0.0850992609853987 A, B, C = powerlawrecurrence(α, λ) r = RecurrenceArray(z, (A,B,C), [L0,L1]) @test r[5] ≈ -0.00381340800899034 end @testset "z < -1" begin z = -1.43 x = axes(ChebyshevT(),1) α = 0.1 L = abs.(z .- x') .^ α # from Mathematica λ = 1 L0 = powerlawmoment(Val(0), α, λ, z) L1 = powerlawmoment(Val(1), α, λ, z) @test L* UltrasphericalWeight(λ) ≈ L0 ≈ 1.617769472203235 @test L1 ≈ 0.06180254575531147 A, B, C = powerlawrecurrence(α, λ) r = RecurrenceArray(z, (A,B,C), [L0,L1]) @test r[5] ≈ -0.000807806617344142 end @testset "1 < z < 1" begin z = 0.7398 x = axes(ChebyshevT(),1) α = 0.1 L = abs.(z .- x') .^ α # from Mathematica λ = 1 L0 = powerlawmoment(Val(0), α, λ, z) L1 = powerlawmoment(Val(1), α, λ, z) @test L* UltrasphericalWeight(λ) ≈ L0 ≈ 1.480874346601822 @test L1 ≈ -0.1328257513137366 A, B, C = powerlawrecurrence(α, λ) r = RecurrenceArray(z, (A,B,C), [L0,L1]) @test r[5] ≈ 0.02537001925265781 end end
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
1649
using SingularIntegrals, ClassicalOrthogonalPolynomials, Test using SingularIntegrals: RecurrenceArray using ClassicalOrthogonalPolynomials: recurrencecoefficients @testset "RecurrenceArray" begin @testset "RecurrenceVector" begin T,U = ChebyshevT(),ChebyshevU() for z in (0.1, 1.0) r = RecurrenceArray(z, recurrencecoefficients(T), [0.0, 1.0]) @test r[1:1000] ≈ [0; U[z,1:999]] @test r[10_000] ≈ U[z,9_999] r = RecurrenceArray(z, recurrencecoefficients(U), [1.0, z]) @test r[1:1000] ≈ T[z,1:1000] @test r[10_000] ≈ T[z,10_000] end for z in (1.000000001, 1.000001, -1.000001, 10.0, -10.0) ξ = inv(z + sign(z)sqrt(z^2-1)) r = RecurrenceArray(z, recurrencecoefficients(U), [ξ,ξ^2]) @test r[1:1000] ≈ ξ.^(1:1000) @test r[10_000] ≈ ξ.^(10_000) atol=3E-10 end for z in (0.2567881003580743 - 0.33437737333561895im) ξ = π * (z - √(z-1) * √(z+1)) r = RecurrenceArray(z, recurrencecoefficients(U), [ξ,2z*ξ-π]) @test sizeof(r.data) < 1000_000 end end @testset "RecurrenceMatrix" begin U = ChebyshevU() z = [2.,3.,100.] ξ = @. inv(z + sign(z)sqrt(z^2-1)) r = RecurrenceArray(z, recurrencecoefficients(U), [ξ'; ξ'.^2]) @test r[1:100,:] ≈ [RecurrenceArray(z[j], recurrencecoefficients(U), [ξ[j],ξ[j]^2])[k] for k=1:100, j=axes(z,1)] @test r[1:100,:] ≈ r[1:100,1:3] ≈ r[collect(1:100),1:3] ≈ r[1:100,collect(1:3)] ≈ r[collect(1:100),:] @test r[100,:] ≈ r[100,1:3] end end
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
code
7718
using SingularIntegrals, ClassicalOrthogonalPolynomials, QuasiArrays, BandedMatrices, Test using LazyBandedMatrices: blockcolsupport, Block, BlockHcat, blockbandwidths, paddeddata, colsupport, rowsupport using ClassicalOrthogonalPolynomials: orthogonalityweight using SingularIntegrals: Stieltjes, StieltjesPoint @testset "Stieltjes" begin @testset "weights" begin w_T = ChebyshevTWeight() w_U = ChebyshevUWeight() w_P = LegendreWeight() x = axes(w_T,1) H = inv.(x .- x') @test iszero(H*w_T) @test (H*w_U)[0.1] ≈ π/10 @test (H*w_P)[0.1] ≈ log(1.1) - log(1-0.1) @test H * w_T ≡ QuasiZeros{Float64}((x,)) @test H * w_U == π*x @test (H * w_P)[0.1] ≈ log((0.1+1)/(1-0.1)) w_T = orthogonalityweight(chebyshevt(0..1)) w_U = orthogonalityweight(chebyshevu(0..1)) w_P = orthogonalityweight(legendre(0..1)) x = axes(w_T,1) H = inv.(x .- x') @test iszero(H*w_T) @test (H*w_U)[0.1] ≈ (2*0.1-1)*π @test (H*w_P)[0.1] ≈ (log(1+(-0.8)) - log(1-(-0.8))) end @testset "ops" begin wT = Weighted(ChebyshevT()) wU = Weighted(ChebyshevU()) x = axes(wT,1) H = inv.(x .- x') @test H isa Stieltjes{Float64,ChebyshevInterval{Float64}} @test (Ultraspherical(1) \ (H*wT))[1:10,1:10] == diagm(1 => fill(-π,9)) @test (Chebyshev() \ (H*wU))[1:10,1:10] == diagm(-1 => fill(1.0π,9)) # check consistency @test (Ultraspherical(1) \ (H*wT) * (wT \ wU))[1:10,1:10] == ((Ultraspherical(1) \ Chebyshev()) * (Chebyshev() \ (H*wU)))[1:10,1:10] end @testset "Other axes" begin x = Inclusion(0..1) y = 2x .- 1 H = inv.(x .- x') T,U = ChebyshevT(),ChebyshevU() wT = Weighted(T) wU = Weighted(U) wT2 = wT[y,:] wU2 = wU[y,:] @test (Ultraspherical(1)[y,:]\(H*wT2))[1:10,1:10] == diagm(1 => fill(-π,9)) @test (T[y,:]\(H*wU2))[1:10,1:10] == diagm(-1 => fill(1.0π,9)) end @testset "Legendre" begin P = Legendre() x = axes(P,1) H = inv.(x .- x') Q = H*P @test Q[0.1,1:3] ≈ [log(0.1+1)-log(1-0.1), 0.1*(log(0.1+1)-log(1-0.1))-2,-3*0.1 + 1/2*(-1 + 3*0.1^2)*(log(0.1+1)-log(1-0.1))] X = jacobimatrix(P) @test Q[0.1,1:11]'*X[1:11,1:10] ≈ (0.1 * Array(Q[0.1,1:10])' - [2 zeros(1,9)]) end @testset "mapped" begin T = chebyshevt(0..1) U = chebyshevu(0..1) x = axes(T,1) H = inv.(x .- x') @test U\H*Weighted(T) isa BandedMatrix end end @testset "StieltjesPoint" begin T = Chebyshev() wT = Weighted(T) x = axes(wT,1) z = 0.1+0.2im S = inv.(z .- x') @test S isa StieltjesPoint{ComplexF64,ComplexF64,Float64,ChebyshevInterval{Float64}} @test S * ChebyshevWeight() ≈ π/(sqrt(z-1)sqrt(z+1)) @test S * JacobiWeight(0.1,0.2) ≈ 0.051643014475741864 - 2.7066092318596726im f = wT * [[1,2,3]; zeros(∞)]; J = T \ (x .* T) @test π*((z*I-J) \ f.args[2])[1,1] ≈ (S*f)[1] @test π*((z*I-J) \ f.args[2])[1,1] ≈ (S*f.args[1]*f.args[2])[1] x = Inclusion(0..1) y = 2x .- 1 wT2 = wT[y,:] S = inv.(z .- x') f = wT2 * [[1,2,3]; zeros(∞)]; @test (π/2*(((z-1/2)*I - J/2) \ f.args[2]))[1] ≈ (S*f.args[1]*f.args[2])[1] @testset "Real point" begin t = 2.0 T,U,P = ChebyshevT(),ChebyshevU(),Legendre() x = axes(T,1) @test (inv.(t .- x') * Weighted(T))[1:10] ≈ (inv.((t+eps()im) .- x') * Weighted(T))[1:10] @test (inv.(t .- x') * Weighted(U))[1:10] ≈ (inv.((t+eps()im) .- x') * Weighted(U))[1:10] @test (inv.(t .- x') * P)[5] ≈ 0.0023221516632410816 @test (inv.(t .- x') * P)[10] ≈ 2.2435707298304464E-6 t = 2 @test (inv.(t .- x') * Weighted(T))[1:10] ≈ (inv.((t+eps()im) .- x') * Weighted(T))[1:10] @test (inv.(t .- x') * Weighted(U))[1:10] ≈ (inv.((t+eps()im) .- x') * Weighted(U))[1:10] t = 0.5 @test (inv.(t .- x') * Weighted(T))[1,1:3] ≈ [0,-π,-π] @test (inv.(t .- x') * Weighted(U))[1,1:3] ≈ [π/2,-π/2,-π] t = 0.5+0im @test (inv.(t .- x') * Weighted(T))[1,1:3] ≈ [0,-π,-π] @test (inv.(t .- x') * Weighted(U))[1,1:3] ≈ [π/2,-π/2,-π] end @testset "DimensionMismatch" begin x = Inclusion(0..1) z = 2.0 @test_throws DimensionMismatch inv.(z .- x') * Weighted(ChebyshevT()) @test_throws DimensionMismatch inv.(z .- x') * Weighted(ChebyshevU()) @test_throws DimensionMismatch inv.(z .- x') * ChebyshevTWeight() @test_throws DimensionMismatch inv.(z .- x') * ChebyshevUWeight() end @testset "Matrix" begin z = [2.,3.] T = ChebyshevT() wT = Weighted(T) x = axes(wT,1) @test (inv.(z .- x') * wT)[:,1:100] ≈ ([(inv.(z[1] .- x') * wT)[1:100]'; (inv.(z[2] .- x') * wT)[1:100]']) f = wT * (T \ exp.(x)) @test inv.(z .- x') * f ≈ [2.8826861116458593, 1.6307809018753612] end @testset "StieltjesPoints" begin z = [2.,3.] P = Legendre() x = axes(P,1) S = inv.(z .- x') @test (S * P)[:,1:5] ≈ [(inv.(2 .- x')*P)[1:5]'; (inv.(3 .- x')*P)[1:5]'] @test S * JacobiWeight(0.1,0.2) == stieltjes.(Ref(JacobiWeight(0.1,0.2)), z) end end @testset "Ideal Fluid Flow" begin T = ChebyshevT() U = ChebyshevU() x = axes(U,1) H = inv.(x .- x') c = exp(0.5im) u = Weighted(U) * ((H * Weighted(U)) \ imag(c * x)) ε = eps(); @test (inv.(0.1+ε*im .- x') * u + inv.(0.1-ε*im .- x') * u)/2 ≈ imag(c*0.1) @test real(inv.(0.1+ε*im .- x') * u ) ≈ imag(c*0.1) v = (s,t) -> (z = (s + im*t); imag(c*z) - real(inv.(z .- x') * u)) @test v(0.1,0.2) ≈ 0.18496257285081724 # Emperical end @testset "OffStieltjes" begin @testset "ChebyshevU" begin U = ChebyshevU() W = Weighted(U) t = axes(U,1) x = Inclusion(2..3) T = chebyshevt(2..3) H = T \ inv.(x .- t') * W; @test MemoryLayout(H) isa PaddedLayout @test last(colsupport(H,1)) ≤ 20 @test last(colsupport(H,6)) ≤ 40 @test last(rowsupport(H)) ≤ 30 @test T[2.3,1:100]'*(H * (W \ @.(sqrt(1-t^2)exp(t))))[1:100] ≈ 0.9068295340935111 @test T[2.3,1:100]' * H[1:100,1:100] ≈ (inv.(2.3 .- t') * W)[:,1:100] u = (I + H) \ [1; zeros(∞)] @test u[3] ≈ -0.011220808241213699 #Emperical @testset "properties" begin U = chebyshevu(T) X = jacobimatrix(U) Z = jacobimatrix(T) @test Z * H[:,1] - H[:,2]/2 ≈ [sum(W[:,1]); zeros(∞)] @test norm(-H[:,1]/2 + Z * H[:,2] - H[:,3]/2) ≤ 1E-12 L = U \ ((x.^2 .- 1) .* Derivative(x) * T - x .* T) c = T \ sqrt.(x.^2 .- 1) @test [T[begin,:]'; L] \ [sqrt(2^2-1); zeros(∞)] ≈ c end end @testset "mapped" begin U = chebyshevu(-1..0) W = Weighted(U) t = axes(U,1) x = Inclusion(2..3) T = chebyshevt(2..3) H = T \ inv.(x .- t') * W N = 100 @test T[2.3,1:N]' * H[1:N,1:N] ≈ (inv.(2.3 .- t') * W)[:,1:N] U = chebyshevu((-2)..(-1)) W = Weighted(U) T = chebyshevt(0..2) x = axes(T,1) t = axes(W,1) H = T \ inv.(x .- t') * W @test T[0.5,1:N]'*(H * (W \ @.(sqrt(-1-t)*sqrt(t+2)*exp(t))))[1:N] ≈ 0.047390454610749054 end @testset "expand" begin P = Legendre() @test stieltjes(P[:,1], 3) ≈ stieltjes(P,3)[1] @test stieltjes(P[:,1:3], 3) ≈ stieltjes(P,3)[:,1:3] end end
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.3.2
b90124c6b6014e49084c624b0d91f4d000642462
docs
1813
# SingularIntegrals.jl A Julia package for computing singular integrals [![Build Status](https://github.com/JuliaApproximation/SingularIntegrals.jl/workflows/CI/badge.svg)](https://github.com/JuliaApproximation/SingularIntegrals.jl/actions) [![codecov](https://codecov.io/gh/JuliaApproximation/SingularIntegrals.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/JuliaApproximation/SingularIntegrals.jl) [![](https://img.shields.io/badge/docs-latest-blue.svg)](https://JuliaApproximation.github.io/SingularIntegrals.jl) This package supports computing singular integrals involving Hilbert/Stieltjes/Cauchy, log, and power law kernels. Some examples: ```julia julia> using SingularIntegrals, ClassicalOrthogonalPolynomials julia> P = Legendre(); x = axes(P, 1); f = expand(P, exp); # expand exp(x) in Legendre polynomials julia> @time inv.(10 .- x') * f # Stieltjes: ∫₋₁¹ exp(x) / (10-x) dx 0.000034 seconds (22 allocations: 2.266 KiB) 0.24332755428373515 julia> @time inv.(0.1+0im .- x') * f - inv.(0.1-0im .- x') * f ≈ -2π*im*exp(0.1) # example of Plemelj 0.000052 seconds (49 allocations: 6.031 KiB) true julia> @time abs.(10 .- x') .^ 0.2 * f # Power law: ∫₋₁¹ (10-x)^0.2 * exp(x) dx 0.000077 seconds (21 allocations: 1.875 KiB) 3.7006631248289135 julia> @time abs.(0.3 .- x') .^ 0.2 * f # ∫₋₁¹ abs(0.3-x)^0.2 * exp(x) dx 0.000040 seconds (25 allocations: 2.172 KiB) 1.9044201526740234 julia> W = Weighted(ChebyshevU()); f = expand(W, x -> exp(x) * sqrt(1-x^2)); julia> @time log.(abs.(10 .- x')) * f # Log-kernel: ∫₋₁¹ log(10-x) * exp(x) * sqrt(1-x^2) dx 0.000040 seconds (14 allocations: 400 bytes) 4.043032838853287 julia> @time log.(abs.(0.3 .- x')) * f # ∫₋₁¹ log(abs(0.3-x)) * exp(x) * sqrt(1-x^2) dx 0.000035 seconds (116 allocations: 6.250 KiB) -2.320391559008445 ```
SingularIntegrals
https://github.com/JuliaApproximation/SingularIntegrals.jl.git
[ "MIT" ]
0.1.1
19e43171d465f44a9c04309e0088e5b5b66d66e7
code
3288
using BinaryProvider # requires BinaryProvider 0.3.0 or later # Parse some basic command-line arguments const verbose = "--verbose" in ARGS const prefix = Prefix(get([a for a in ARGS if a != "--verbose"], 1, joinpath(@__DIR__, "usr"))) products = [ LibraryProduct(prefix, ["libyaml"], :libyaml), ] # Download binaries from hosted location bin_prefix = "https://github.com/eschnett/libyaml-binaries/releases/download/v1.0.0" # Listing of files generated by BinaryBuilder: download_info = Dict( Linux(:aarch64, libc=:glibc) => ("$bin_prefix/libyaml.v0.2.1.aarch64-linux-gnu.tar.gz", "d2247731b401c96d61995966422d24edf6e3ab06428ddec3f4ed4c12074c4661"), Linux(:aarch64, libc=:musl) => ("$bin_prefix/libyaml.v0.2.1.aarch64-linux-musl.tar.gz", "67a745cbfc238b505fd6a1c677b5fd34177e51472867704a0464e52421454631"), Linux(:armv7l, libc=:glibc, call_abi=:eabihf) => ("$bin_prefix/libyaml.v0.2.1.arm-linux-gnueabihf.tar.gz", "7f43ce82a5c039c7bec13c001631812ca9510131c06b13211dfc6679514559cd"), Linux(:armv7l, libc=:musl, call_abi=:eabihf) => ("$bin_prefix/libyaml.v0.2.1.arm-linux-musleabihf.tar.gz", "ad7dd7464dd1df2b6438484a6dc82e889c222f7ec3688afed54c16875bbcd38a"), Linux(:i686, libc=:glibc) => ("$bin_prefix/libyaml.v0.2.1.i686-linux-gnu.tar.gz", "27448c16b705d58ae903be76e7997045f73a8f28b8dbe52773d3794f73322379"), Linux(:i686, libc=:musl) => ("$bin_prefix/libyaml.v0.2.1.i686-linux-musl.tar.gz", "c448e95e8ce0f2cc3826779c9086addea6fa78ac007bb958d41127ba90818481"), Linux(:powerpc64le, libc=:glibc) => ("$bin_prefix/libyaml.v0.2.1.powerpc64le-linux-gnu.tar.gz", "47d27b1287f93a8aa33ac1570c7660a4ac6529f12006a6cc726f22d2f206428e"), Linux(:x86_64, libc=:glibc) => ("$bin_prefix/libyaml.v0.2.1.x86_64-linux-gnu.tar.gz", "1410f0ffc3206433f30999d051a917fc19301006cadbef5679ef1619c2830002"), Linux(:x86_64, libc=:musl) => ("$bin_prefix/libyaml.v0.2.1.x86_64-linux-musl.tar.gz", "0100c096ab78a7084d21ca84af23d0b2b318d11bef1fdbc31c5df0adb8cb8ca9"), FreeBSD(:x86_64) => ("$bin_prefix/libyaml.v0.2.1.x86_64-unknown-freebsd11.1.tar.gz", "bd8fb84eca65fb20ef5cc493184e5adf17ab89476e9012e7c5ada86b1d8a3b24"), MacOS(:x86_64) => ("$bin_prefix/libyaml.v0.2.1.x86_64-apple-darwin14.tar.gz", "49165350ac38b475fba21a76328bf9725e9de0dca60195249ab3fe73d5e11c4a"), ) # Install unsatisfied or updated dependencies: unsatisfied = any(!satisfied(p; verbose=verbose) for p in products) dl_info = choose_download(download_info, platform_key_abi()) if dl_info === nothing && unsatisfied # If we don't have a compatible .tar.gz to download, complain. # Alternatively, you could attempt to install from a separate provider, # build from source or something even more ambitious here. error("Your platform (\"$(Sys.MACHINE)\", parsed as \"$(triplet(platform_key_abi()))\") is not supported by this package!") end # If we have a download, and we are unsatisfied (or the version we're # trying to install is not itself installed) then load it up! if unsatisfied || !isinstalled(dl_info...; prefix=prefix) # Download and install binaries install(dl_info...; prefix=prefix, force=true, verbose=verbose) end # Write out a deps.jl file that will contain mappings for our products write_deps_file(joinpath(@__DIR__, "deps.jl"), products, verbose=verbose)
LibYAML
https://github.com/eschnett/LibYAML.jl.git
[ "MIT" ]
0.1.1
19e43171d465f44a9c04309e0088e5b5b66d66e7
code
1111
module LibYAML using Libdl # Load `deps.jl`, complaining if it does not exist const depsjl_path = joinpath(@__DIR__, "..", "deps", "deps.jl") if !isfile(depsjl_path) error("LibYAML not installed properly, run Pkg.build(\"LibYAML\"), restart Julia, and try again") end include(depsjl_path) # Module initialization function function __init__() # Always check your dependencies from `deps.jl` check_deps() end """ Get the library version as a string. The function returns the pointer to a static string of the form `X.Y.Z`, where `X` is the major version number, `Y` is a minor version number, and `Z` is the patch version number. """ function get_version_string() unsafe_string(ccall((:yaml_get_version_string, libyaml), Cstring, ())) end """ Get the library version numbers. Returns a tuple `(major, minor, patch)`. """ function get_version() major = Ref{Cint}(0) minor = Ref{Cint}(0) patch = Ref{Cint}(0) ccall((:yaml_get_version, libyaml), Cvoid, (Ref{Cint}, Ref{Cint}, Ref{Cint}), major, minor, patch) (Int(major[]), Int(minor[]), Int(patch[])) end end
LibYAML
https://github.com/eschnett/LibYAML.jl.git
[ "MIT" ]
0.1.1
19e43171d465f44a9c04309e0088e5b5b66d66e7
code
115
using LibYAML using Test @test LibYAML.get_version_string() === "0.2.1" @test LibYAML.get_version() === (0, 2, 1)
LibYAML
https://github.com/eschnett/LibYAML.jl.git
[ "MIT" ]
0.1.1
19e43171d465f44a9c04309e0088e5b5b66d66e7
docs
766
# [LibYAML](https://github.com/eschnett/LibYAML) A Julia library wrapping the (LibYAML)[https://github.com/yaml/libyaml] C library. [![Build Status (Travis)](https://travis-ci.org/eschnett/LibYAML.jl.svg?branch=master)](https://travis-ci.org/eschnett/LibYAML.jl) [![Build status (Appveyor)](https://ci.appveyor.com/api/projects/status/h9h61g8lpoyw20r4/branch/master?svg=true)](https://ci.appveyor.com/project/eschnett/libyaml-jl/branch/master) [unfortunately, Windows is not yet supported] [![Coverage Status (Coveralls)](https://coveralls.io/repos/github/eschnett/LibYAML.jl/badge.svg?branch=master)](https://coveralls.io/github/eschnett/LibYAML.jl?branch=master) XXX [![DOI](https://zenodo.org/badge/144600920.svg)](https://zenodo.org/badge/latestdoi/144600920)
LibYAML
https://github.com/eschnett/LibYAML.jl.git
[ "MIT" ]
0.1.0
fea1a8399e1e9cf0c72fd83a4408be2e6fcabf9e
code
2209
module ProgressView export @monitor, monitor_flush, reset_tasks!, push_task!, pop_task!, maybe_display_tasks, display_tasks const ESC = "\e" # escape const CR = "\r" # carriage return const NL = "\n" # next line const CSI = "$ESC[" # control sequence introducer const CUU = "$(CSI)A" # cursor up const CUD = "$(CSI)B" # cursor down const ED = "$(CSI)J" # erase in display const EL = "$(CSI)K" # erase in line const update_every = 1.0 # update output every that many seconds const stack = Vector{String}() # current task stack const lastoutput = Vector{String}() # currently displayed task stack const lasttime = Ref(0.0) # time at which stack was output macro monitor(taskname::AbstractString, task) quote push_task!($taskname) local result = $(esc(task)) pop_task!() result end end monitor_flush() = display_tasks() function reset_tasks!() empty!(stack) display_tasks() return nothing end function push_task!(task::AbstractString) push!(stack, String(task)) maybe_display_tasks() return nothing end function pop_task!() pop!(stack) maybe_display_tasks() return nothing end function maybe_display_tasks() currenttime = time_ns() / 1.0e+9 if currenttime ≥ lasttime[] + update_every display_tasks() lasttime[] = currenttime end return nothing end function display_tasks() currentoutput = copy(stack) # Find first difference between current and last output tstart = 1 while tstart ≤ length(lastoutput) && tstart ≤ length(currentoutput) && lastoutput[tstart] == currentoutput[tstart] tstart += 1 end # Move cursor up to the first line that needs outputting tmove = length(tstart:length(lastoutput)) print("$CUU"^tmove) # Output new lines for line in tstart:length(currentoutput) print(" "^(line - 1), "$line: ", currentoutput[line], "$EL$NL") end # Clear remaining lines print("$ED") # Save state copy!(lastoutput, currentoutput) return nothing end end
ProgressView
https://github.com/eschnett/ProgressView.jl.git
[ "MIT" ]
0.1.0
fea1a8399e1e9cf0c72fd83a4408be2e6fcabf9e
code
360
using ProgressView using Test function inner() sleep(1.1) return 2 end function fun() sleep(1.1) x = @monitor "inner" inner() @test x == 2 sleep(1.1) return nothing end @testset "ProgressView" begin @monitor "testset" begin @monitor "fun" fun() end sleep(1.1) @monitor "fun" fun() monitor_flush() end
ProgressView
https://github.com/eschnett/ProgressView.jl.git
[ "MIT" ]
0.1.0
fea1a8399e1e9cf0c72fd83a4408be2e6fcabf9e
docs
748
# ProgressView A Julia package for displaying categorical progress information * [GitHub](https://github.com/eschnett/ProgressView.jl): Source code repository * [![GitHub CI](https://github.com/eschnett/ProgressView.jl/workflows/CI/badge.svg)](https://github.com/eschnett/ProgressView.jl/actions) `ProgressView` displays periodically which functions a program is currently executing with a stack-like view. This similar to a hierarchical version of [`ProgressMeter`](https://github.com/timholy/ProgressMeter.jl). ## Example ```Julia function inner() return 2 end function fun() x = @monitor "inner" inner() return nothing end function main() @monitor "fun" fun() end ``` Sample snapshot of output: ``` 1. fun 2. inner ```
ProgressView
https://github.com/eschnett/ProgressView.jl.git
[ "MIT" ]
0.1.7
3a0dab6c751c2cc4642f55ce3922e220a9f811f6
code
1094
# Setup julia dependencies for docs generation if not yet done import Pkg Pkg.activate(@__DIR__) if !isfile(joinpath(@__DIR__, "Manifest.toml")) Pkg.develop(Pkg.PackageSpec(path=joinpath(@__DIR__, ".."))) Pkg.instantiate() end using ASEconvert using Documenter DocMeta.setdocmeta!(ASEconvert, :DocTestSetup, :(using ASEconvert); recursive=true) makedocs(; modules=[ASEconvert], authors="Michael F. Herbst <[email protected]> and contributors", repo="https://github.com/mfherbst/ASEconvert.jl/blob/{commit}{path}#{line}", sitename="ASEconvert.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://mfherbst.github.io/ASEconvert.jl", edit_link="master", assets=String[]), pages=[ "Home" => "index.md", "apireference.md", ]) deploydocs(; repo="github.com/mfherbst/ASEconvert.jl", devbranch="master")
ASEconvert
https://github.com/mfherbst/ASEconvert.jl.git
[ "MIT" ]
0.1.7
3a0dab6c751c2cc4642f55ce3922e220a9f811f6
code
728
module ASEconvert using PythonCall using AtomsBase using Unitful using UnitfulAtomic export ase export pyconvert, pytuple # Reexport from PythonCall export AbstractSystem # Reexport from AtomsBase export ASEcalculator export convert_ase """ Global constant representing the `ase` python module available from Julia. """ const ase = PythonCall.pynew() function __init__() PythonCall.pycopy!(ase, pyimport("ase")) PythonCall.pyconvert_add_rule("ase.atoms:Atoms", AbstractSystem, ase_to_system) # Make a bunch of submodules available for sub in ("ase.io", "ase.build", "ase.lattice", "ase.visualize") pyimport(sub) end end include("ase_conversions.jl") include("atoms_calculators.jl") end
ASEconvert
https://github.com/mfherbst/ASEconvert.jl.git
[ "MIT" ]
0.1.7
3a0dab6c751c2cc4642f55ce3922e220a9f811f6
code
4671
import PeriodicTable # For ASE units, see https://wiki.fysik.dtu.dk/ase/ase/units.html # In particular note that uTime = u"Å" * sqrt(u"u" / u"eV") and thus const uVelocity = sqrt(u"eV" / u"u") function ase_to_system(S::Type{<:AbstractSystem}, ase_atoms::Py) box = [pyconvert(Vector, ase_atoms.cell[i])u"Å" for i = 0:2] atnums = pyconvert(Vector, ase_atoms.get_atomic_numbers()) atsyms = pyconvert(Vector, ase_atoms.symbols) atmasses = pyconvert(Vector, ase_atoms.get_masses()) positions = pyconvert(Matrix, ase_atoms.get_positions()) velocities = pyconvert(Matrix, ase_atoms.get_velocities()) magmoms = pyconvert(Vector, ase_atoms.get_initial_magnetic_moments()) charges = pyconvert(Vector, ase_atoms.get_initial_charges()) ase_info = pyconvert(Dict{String,Any}, ase_atoms.info) atoms = map(1:length(atnums)) do i AtomsBase.Atom(atnums[i], positions[i, :]u"Å", velocities[i, :] * uVelocity; atomic_symbol=Symbol(atsyms[i]), atomic_number=atnums[i], atomic_mass=atmasses[i]u"u", magnetic_moment=magmoms[i], charge=charges[i]u"e_au") end # Parse extra data in info struct info = Dict{Symbol, Any}() for (k, v) in ase_info if k == "charge" info[Symbol(k)] = v * u"e_au" else info[Symbol(k)] = v end end bcs = [p ? Periodic() : DirichletZero() for p in pyconvert(Vector, ase_atoms.pbc)] PythonCall.pyconvert_return(atomic_system(atoms, box, bcs; info...)) end """ convert_ase(system::AbstractSystem) Convert a passed `system` (which satisfies the AtomsBase.AbstractSystem interface) to an `ase.Atoms` datastructure. Conversions to other ASE objects from equivalent Julia objects may be added as additional methods in the future. """ function convert_ase(system::AbstractSystem{D}) where {D} D != 3 && @warn "1D and 2D systems not yet fully supported." n_atoms = length(system) pbc = map(isequal(Periodic()), boundary_conditions(system)) numbers = atomic_number(system) masses = ustrip.(u"u", atomic_mass(system)) symbols_match = [ PeriodicTable.elements[atnum].symbol == string(atomic_symbol(system, i)) for (i, atnum) in enumerate(numbers) ] if !all(symbols_match) @warn("Mismatch between atomic numbers and atomic symbols, which is not " * "supported in ASE. Atomic numbers take preference.") end cell = zeros(3, 3) for (i, v) in enumerate(bounding_box(system)) cell[i, 1:D] = ustrip.(u"Å", v) end positions = zeros(n_atoms, 3) for at = 1:n_atoms positions[at, 1:D] = ustrip.(u"Å", position(system, at)) end velocities = nothing if !ismissing(velocity(system)) velocities = zeros(n_atoms, 3) for at = 1:n_atoms velocities[at, 1:D] = ustrip.(uVelocity, velocity(system, at)) end end # We don't map any extra atom properties, which are not available in ASE as this # only causes a mess: ASE could do something to the atoms, but not taking # care of the extra properties, thus rendering the extra properties invalid # without the user noticing. charges = nothing magmoms = nothing for key in atomkeys(system) if key in (:position, :velocity, :atomic_symbol, :atomic_number, :atomic_mass) continue # Already dealt with elseif key == :charge charges = ustrip.(u"e_au", system[:, :charge]) elseif key == :magnetic_moment magmoms = system[:, :magnetic_moment] else @warn "Skipping atomic property $key, which is not supported in ASE." end end # Map extra system properties info = Dict{String, Any}() for (k, v) in pairs(system) if k in (:bounding_box, :boundary_conditions) continue elseif k in (:charge, ) info[string(k)] = ustrip(u"e_au", v) elseif v isa Quantity || (v isa AbstractArray && eltype(v) <: Quantity) @warn("Unitful quantities are not yet supported in convert_ase. " * "Ignoring key $k") else info[string(k)] = v end end ase.Atoms(; positions, numbers, masses, magmoms, charges, cell, pbc, velocities, info) end # TODO Could have a convert_ase(Vector{AbstractSystem}) to make an ASE trajectory # TODO Could have a convert_ase(Vector{Vector{Unitful}}) to make an ASE cell # TODO Could have a way to make an ASE calculator from an InteratomicPotential object
ASEconvert
https://github.com/mfherbst/ASEconvert.jl.git
[ "MIT" ]
0.1.7
3a0dab6c751c2cc4642f55ce3922e220a9f811f6
code
2261
import AtomsCalculators import AtomsCalculators: @generate_interface, calculate, Energy, Forces, Virial """ ASEcalculator This structure wraps python ASE calculator to AtomsCalculators interface compatible structure. # Example ```julia using ASEconvert using AtomsBuilder using AtomsCalculators using PythonCall ase_emt = pyimport("ase.calculators.emt") calc_emt = ASEcalculator(ase_emt.EMT()) system = bulk(:Cu) * (4, 3, 2) AtomsCalculators.potential_energy(system, calc_emt) AtomsCalculators.forces(system, calc_emt) AtomsCalculators.virial(system, calc_emt) ``` """ mutable struct ASEcalculator calculator::PythonCall.Py end # TODO The ASE calculator could change in-place, so it therefore itself # is basically the state. The state handling should overall therefore # be done more thoroughly here. AtomsCalculators.energy_unit(::ASEcalculator) = u"eV" AtomsCalculators.length_unit(::ASEcalculator) = u"Å" @generate_interface function AtomsCalculators.calculate(::AtomsCalculators.Energy, system, calc::ASEcalculator, parameters=nothing, state=nothing; kwargs...) edata = calc.calculator.get_potential_energy(convert_ase(system)) (; energy=pyconvert(Float64, edata)u"eV", state) end @generate_interface function AtomsCalculators.calculate(::AtomsCalculators.Forces, system, calc::ASEcalculator, parameters=nothing, state=nothing; kwargs...) fdata = calc.calculator.get_forces(convert_ase(system)) # We need to convert from Python row major to Julia column major # and from there to Vector with SVector{3,Float64} element. # We do reallocation in the end to ensure we have the correct memory allignement tmp = pyconvert(Array, fdata) FT = AtomsCalculators.promote_force_type(system, calc) tmp2 = reinterpret(FT, tmp') (; forces=Vector(vec(tmp2)), state) end @generate_interface function AtomsCalculators.calculate(::AtomsCalculators.Virial, system, calc::ASEcalculator, parameters=nothing, state=nothing; kwargs...) ase_system = convert_ase(system) sdata = calc.calculator.get_stress(ase_system) Ω = ase_system.get_volume() stress = -Ω * ase.constraints.voigt_6_to_full_3x3_stress(sdata) (; virial=pyconvert(Array, stress) * u"eV", state) end
ASEconvert
https://github.com/mfherbst/ASEconvert.jl.git
[ "MIT" ]
0.1.7
3a0dab6c751c2cc4642f55ce3922e220a9f811f6
code
5847
using AtomsBase using Test using LinearAlgebra using Unitful using UnitfulAtomic # TODO This file is duplicated across many packages, would be good to make # an AtomsBaseTesting package or something similar. """ Test whether two abstract systems are approximately the same. Certain atomic or system properties can be ignored during the comparison using the respective kwargs. """ function test_approx_eq(s::AbstractSystem, t::AbstractSystem; rtol=1e-14, ignore_atprop=Symbol[], ignore_sysprop=Symbol[], common_only=false) rnorm(a, b) = (ustrip(norm(a)) < rtol ? norm(a - b) / 1unit(norm(a)) : norm(a - b) / norm(a)) for method in (length, size, boundary_conditions) @test method(s) == method(t) end @test maximum(map(rnorm, bounding_box(s), bounding_box(t))) < rtol for method in (position, atomic_mass) @test maximum(map(rnorm, method(s), method(t))) < rtol @test rnorm(method(s, 1), method(t, 1)) < rtol end for method in (atomic_symbol, atomic_number) @test method(s) == method(t) @test method(s, 1) == method(t, 1) end if !(:velocity in ignore_atprop) @test ismissing(velocity(s)) == ismissing(velocity(t)) if !ismissing(velocity(s)) && !ismissing(velocity(t)) @test maximum(map(rnorm, velocity(s), velocity(t))) < rtol @test rnorm(velocity(s, 1), velocity(t, 1)) < rtol end end if common_only test_atprop = [k for k in atomkeys(s) if hasatomkey(t, k)] else extra_atomic_props = (:charge, :covalent_radius, :vdw_radius, :magnetic_moment) test_atprop = Set([atomkeys(s)..., atomkeys(t)..., extra_atomic_props...]) end for prop in test_atprop prop in ignore_atprop && continue prop in (:velocity, :position) && continue if hasatomkey(s, prop) != hasatomkey(t, prop) println("hashatomkey mismatch for $prop") @test hasatomkey(s, prop) == hasatomkey(t, prop) end for (at_s, at_t) in zip(s, t) @test haskey(at_s, prop) == haskey(at_t, prop) if haskey(at_s, prop) && haskey(at_t, prop) if at_s[prop] isa Quantity @test rnorm(at_s[prop], at_t[prop]) < rtol else @test at_s[prop] == at_t[prop] end end end end if common_only test_sysprop = [k for k in keys(s) if haskey(t, k)] else extra_system_props = (:charge, :multiplicity) test_sysprop = Set([keys(s)..., keys(t)..., extra_system_props...]) end for prop in test_sysprop prop in ignore_sysprop && continue if haskey(s, prop) != haskey(t, prop) println("haskey mismatch for $prop") @test haskey(s, prop) == haskey(t, prop) end if s[prop] isa Quantity @test rnorm(s[prop], t[prop]) < rtol elseif prop in (:bounding_box, ) @test maximum(map(rnorm, s[prop], t[prop])) < rtol else @test s[prop] == t[prop] end end end """ Setup a standard test system using some random data and supply the data to the caller. Extra atomic or system properties can be specified using `extra_atprop` and `extra_sysprop` and specific standard keys can be ignored using `drop_atprop` and `drop_sysprop`. """ function make_test_system(D=3; drop_atprop=Symbol[], drop_sysprop=Symbol[], extra_atprop=(; ), extra_sysprop=(; ), cellmatrix=:full) # TODO Should be moved to AtomsBase @assert D == 3 n_atoms = 5 # Generate some random data to store in Atoms atprop = Dict{Symbol,Any}( :position => [randn(3) for _ = 1:n_atoms]u"Å", :velocity => [randn(3) for _ = 1:n_atoms] * 10^6*u"m/s", # Note: reasonable velocity range in au :atomic_symbol => [:H, :H, :C, :N, :He], :atomic_number => [1, 1, 6, 7, 2], :charge => [2, 1, 3.0, -1.0, 0.0]u"e_au", :atomic_mass => 10rand(n_atoms)u"u", :vdw_radius => randn(n_atoms)u"Å", :covalent_radius => randn(n_atoms)u"Å", :magnetic_moment => [0.0, 0.0, 1.0, -1.0, 0.0], ) sysprop = Dict{Symbol,Any}( :extra_data => 42, :charge => -1u"e_au", :multiplicity => 2, ) for prop in drop_atprop pop!(atprop, prop) end for prop in drop_sysprop pop!(sysprop, prop) end sysprop = merge(sysprop, pairs(extra_sysprop)) atprop = merge(atprop, pairs(extra_atprop)) atoms = map(1:n_atoms) do i atargs = Dict(k => v[i] for (k, v) in pairs(atprop) if !(k in (:position, :velocity))) if haskey(atprop, :velocity) Atom(atprop[:atomic_symbol][i], atprop[:position][i], atprop[:velocity][i]; atargs...) else Atom(atprop[:atomic_symbol][i], atprop[:position][i]; atargs...) end end if cellmatrix == :upper_triangular box = [[1.54732, -0.807289, -0.500870], [ 0.0, 0.4654985, 0.5615117], [ 0.0, 0.0, 0.7928950]]u"Å" elseif cellmatrix == :lower_triangular box = [[1.54732, 0.0, 0.0], [-0.807289, 0.4654985, 0.0], [-0.500870, 0.5615117, 0.7928950]]u"Å" else box = [[-1.50304, 0.850344, 0.717239], [ 0.36113, 0.008144, 0.814712], [ 0.06828, 0.381122, 0.129081]]u"Å" end bcs = [Periodic(), Periodic(), DirichletZero()] system = atomic_system(atoms, box, bcs; sysprop...) (; system, atoms, atprop=NamedTuple(atprop), sysprop=NamedTuple(sysprop), box, bcs) end
ASEconvert
https://github.com/mfherbst/ASEconvert.jl.git
[ "MIT" ]
0.1.7
3a0dab6c751c2cc4642f55ce3922e220a9f811f6
code
6558
using ASEconvert using AtomsBase using AtomsBaseTesting using AtomsCalculators using AtomsCalculators.Testing using PythonCall using Test using Unitful using UnitfulAtomic @testset "ASEconvert.jl" begin function make_ase_system(args...; drop_atprop=Symbol[], kwargs...) # ASE does not support vdw_radius and covalent_radius dropkeys = [:covalent_radius, :vdw_radius] make_test_system(args...; drop_atprop=append!(drop_atprop, dropkeys), kwargs...) end # TODO Test reduced dimension @testset "Conversion to ASE (3D, with velocity)" begin system, atoms, atprop, sysprop, box, bcs = make_test_system() ase_atoms = @test_logs((:warn, r"Skipping atomic property vdw_radius"), (:warn, r"Skipping atomic property covalent_radius"), match_mode=:any, convert_ase(system)) D = 3 for i = 1:D @test pyconvert(Vector, ase_atoms.cell[i - 1]) ≈ ustrip.(u"Å", box[i]) atol=1e-14 end @assert bcs == [Periodic(), Periodic(), DirichletZero()] @test pyconvert(Vector, ase_atoms.pbc) == [true, true, false] for (i, atom) in enumerate(ase_atoms) @test(pyconvert(Vector, atom.position) ≈ ustrip.(u"Å", atprop.position[i]), atol=1e-14) @test(pyconvert(Vector, ase_atoms.get_velocities()[i - 1]) ≈ ustrip.(sqrt(u"eV"/u"u"), atprop.velocity[i]), atol=1e-12) @test pyconvert(String, atom.symbol) == string(atprop.atomic_symbol[i]) @test pyconvert(Int, atom.number) == atprop.atomic_number[i] @test pyconvert(Float64, atom.mass) == ustrip(u"u", atprop.atomic_mass[i]) @test pyconvert(Float64, atom.magmom) == atprop.magnetic_moment[i] @test pyconvert(Float64, atom.charge) == ustrip(u"e_au", atprop.charge[i]) end @test pyconvert(Int, ase_atoms.info["extra_data"]) == sysprop.extra_data @test pyconvert(Int, ase_atoms.info["multiplicity"]) == sysprop[:multiplicity] @test pyconvert(Float64, ase_atoms.info["charge"]) == ustrip(u"e_au", sysprop[:charge]) end @testset "Conversion to ASE (without velocities)" begin system = make_ase_system(drop_atprop=[:velocity]).system ase_atoms = convert_ase(system) for (i, atom) in enumerate(ase_atoms) @test iszero(pyconvert(Vector, ase_atoms.get_velocities()[i - 1])) end end @testset "Warning about mismatch between atomic symbols and numbers" begin extra_atprop = (atomic_symbol=[:H, :H, :C, :N, :He], atomic_number=[1, 2, 3, 4, 5]) system = make_ase_system(; extra_atprop).system ase_atoms = @test_logs((:warn, r"Mismatch between atomic numbers"), match_mode=:any, convert_ase(system)) expected_symbols = ["H", "He", "Li", "Be", "B"] for (i, atom) in enumerate(ase_atoms) @test pyconvert(Int, atom.number) == i @test pyconvert(String, atom.symbol) == expected_symbols[i] end end @testset "Ignoring of unitful quantities" begin dropsystem1 = make_ase_system(; extra_sysprop=(; len=12u"m")).system dropsystem2 = make_ase_system(; extra_sysprop=(; mass=[2u"kg", 1u"kg"])).system for sys in (dropsystem1, dropsystem2) ase_atoms = @test_logs((:warn, r"Unitful quantities are not yet supported"), match_mode=:any, convert_ase(sys)) @test pyconvert(Int, ase_atoms.info["extra_data"]) == 42 end end @testset "Conversion AtomsBase -> ASE -> AtomsBase" begin system = make_ase_system().system newsystem = pyconvert(FlexibleSystem, convert_ase(system)) test_approx_eq(system, newsystem) end @testset "Construction of bulk systems in ASE" begin bulk_Fe = pyconvert(AbstractSystem, ase.build.bulk("Fe"; cubic=true)) a = 2.87u"Å" @test bounding_box(bulk_Fe) == a .* [[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]] @test atomic_symbol(bulk_Fe) == [:Fe, :Fe] @test position(bulk_Fe) == [[0.0, 0.0, 0.0], [1.435, 1.435, 1.435]]u"Å" @test velocity(bulk_Fe) == [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]*sqrt(u"eV"/u"u") end @testset "Writing / reading files using ASE" begin system = make_ase_system().system mktempdir() do d file = joinpath(d, "output.xyz") ase.io.write(file, convert_ase(system)) newsystem = pyconvert(FlexibleSystem, ase.io.read(file)) test_approx_eq(system, newsystem; rtol=1e-6) end end @testset "Writing files using ASE, reading using ExtXYZ" begin using PeriodicTable import ExtXYZ # Unfortunately the conventions used in ExtXYZ for storing extra # properties are *not* the same in ASE and ExtXYZ, therefore writing # in one and reading in another is not loss-free. We thus drop some # special things (atomic masses, magmoms, charges) atomic_symbol = [:H, :H, :C, :N, :He] atomic_number = [1, 1, 6, 7, 2] atomic_mass = [elements[at].atomic_mass for at in atomic_number] extra_atprop = (; atomic_symbol, atomic_number, atomic_mass) system = make_ase_system(; extra_atprop, drop_atprop=[:velocity]).system mktempdir() do d file = joinpath(d, "output.xyz") ase.io.write(file, convert_ase(system)) newsystem = ExtXYZ.Atoms(ExtXYZ.read_frame(file)) test_approx_eq(system, newsystem; rtol=1e-6, ignore_atprop=[:initial_charges, :momenta, :masses, :charge, :initial_magmoms, :magnetic_moment]) end end @testset "Test ASEcalculator" begin # Setup LJ calculator in ASE ase_lj = pyimport("ase.calculators.lj") ε = ustrip(u"eV", 125.7u"K" * u"k") σ = ustrip(3.345u"Å") calc_lj = ASEcalculator(ase_lj.LennardJones(; epsilon=ε, sigma=σ)) # Build Argon supercell ase_system = ase.build.bulk("Ar") * pytuple((5, 5, 5)) system = pyconvert(AbstractSystem, ase_system) # Check we have not made a stupid coding mistake @test -0.39120116 ≈ austrip(AtomsCalculators.potential_energy(system, calc_lj)) # Check the full AtomsCalculator test suite passes test_energy_forces_virial(system, calc_lj; rtol=1e-8) end end
ASEconvert
https://github.com/mfherbst/ASEconvert.jl.git
[ "MIT" ]
0.1.7
3a0dab6c751c2cc4642f55ce3922e220a9f811f6
docs
1923
# ASEconvert [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://mfherbst.github.io/ASEconvert.jl/stable/) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://mfherbst.github.io/ASEconvert.jl/dev/) [![Build Status](https://github.com/mfherbst/ASEconvert.jl/actions/workflows/CI.yml/badge.svg?branch=master)](https://github.com/mfherbst/ASEconvert.jl/actions/workflows/CI.yml?query=branch%3Amaster) [![Coverage](https://codecov.io/gh/mfherbst/ASEconvert.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/mfherbst/ASEconvert.jl) Light-weight module to install ASE and provide routines for converting between the Atoms datastructure from [ASE](https://wiki.fysik.dtu.dk/ase/index.html) and atomistic data provided in the [AtomsBase](https://github.com/JuliaMolSim/AtomsBase.jl) ecosystem. For both the package makes use of the [PythonCall](https://github.com/cjdoris/PythonCall.jl/). This can be used for example as follows ```julia using ASEconvert # Make a silicon supercell using ASE atoms_ase = ase.build.bulk("Si") * pytuple((4, 1, 1)) # Convert to an AtomsBase-compatible structure atoms_ab = pyconvert(AbstractSystem, atoms_ase) # Convert back to ASE and create a vacancy newatoms_ase = convert_ase(atoms_ab) newatoms_ase.pop(4) ``` ### AtomsCalculators interface You can use ASE calculators in julia, by wrapping them to a `ASEcalculator` structure. Here is a brief example: ```julia using AtomsCalculators using AtomsBuilder using ASEconvert using PythonCall # Setup calculator in ASE potential = "path to eam potential file" ase_calc = pyimport("ase.calculators.eam").EAM(potential) # Convert into AtomsCalculator-compatible calculator calc = ASEcalculator(ase_calc) # Use it to compute a Nickel supercell system = bulk(:Ni) * (4, 3, 2) AtomsCalculators.potential_energy(system, calc) AtomsCalculators.forces(system, calc) AtomsCalculators.virial(system, calc) ```
ASEconvert
https://github.com/mfherbst/ASEconvert.jl.git
[ "MIT" ]
0.1.7
3a0dab6c751c2cc4642f55ce3922e220a9f811f6
docs
98
```@meta CurrentModule = ASEconvert ``` # API reference ```@autodocs Modules = [ASEconvert] ```
ASEconvert
https://github.com/mfherbst/ASEconvert.jl.git
[ "MIT" ]
0.1.7
3a0dab6c751c2cc4642f55ce3922e220a9f811f6
docs
3254
```@meta CurrentModule = ASEconvert ``` # ASEconvert Light-weight module to install the [atomistic simulation environment (ASE)](https://wiki.fysik.dtu.dk/ase/index.html) and provide routines for cross-converting between ASE datastructures and the respective ones of the [JuliaMolSim](https://juliamolsim.org) ecosystem. E.g. it allows to convert between the ASE Atoms and exposing them using an [AtomsBase](https://github.com/JuliaMolSim/AtomsBase.jl) compatible interface or it allows to employ calculators from ASE as [AtomsCalculators](https://github.com/JuliaMolSim/AtomsCalculators.jl). ## Automatic ASE installation Using the mechanism provided by [PythonCall](https://github.com/cjdoris/PythonCall.jl) and [CondaPkg](https://github.com/cjdoris/CondaPkg.jl) ASEconvert will automatically take care of installing ASE and exporting a useful subset of its modules under the `ase` variable. For example one may easily create bulk systems ```@example using ASEconvert ase.build.bulk("Mg") ``` or surfaces ```@example using ASEconvert ase.build.surface(ase.build.bulk("Mg"), (1, 1, 0), 4, 0, periodic=true) ``` ## Conversion from ASE to AtomsBase ```@example dftk using ASEconvert # Construct bulk magnesium using ASE and convert to atomsbase mg_ase = ase.build.bulk("Mg") mg_atb = pyconvert(AbstractSystem, mg_ase) ``` ```julia using DFTK # Attach pseudopotentials, construct LDA DFT model and solve for DFT ground state system = attach_psp(mg_atb; Mg="hgh/lda/mg-q2") model = model_LDA(system; temperature=1e-3, smearing=Smearing.MarzariVanderbilt()) basis = PlaneWaveBasis(model; Ecut=20, kgrid=(4, 4, 4)) scfres = self_consistent_field(basis) scfres.energies ``` ## Conversion from AtomsBase to ASE ```@example extxyz using ASEconvert using AtomsIO # Read an extxyz file using AtomsIO.jl. system = load_system("Mn3Si.extxyz") ``` This example uses [AtomsIO](https://github.com/mfherbst/AtomsIO.jl) to read the extended XYZ file file `Mn3Si.extxyz`. The data is returned as a subtype of `AtomsBase.AbstractSystem` (in this case an `ExtXYZ.Atoms` from [ExtXYZ](https://github.com/libAtoms/ExtXYZ.jl)). We can thus directly convert this system to an `ase.Atoms` using [`convert_ase`](@ref) and write it again as an ASE json file ```@example extxyz ase.io.write("out.json", convert_ase(system)); ``` ## Employing ASE calculators in Julia ```@example calculators using PythonCall using ASEconvert ase_emt = pyimport("ase.calculators.emt") calculator = ASEcalculator(ase_emt.EMT()) ``` The above codeblock employs [PythonCall](https://github.com/cjdoris/PythonCall.jl) to setup an [EMT calculator](https://wiki.fysik.dtu.dk/ase/ase/calculators/emt.html) in ASE. Using the [`ASEcalculator`](@ref) wrapper this calculator is wrapped and now exposes a standard [AtomsCalculators](https://github.com/JuliaMolSim/AtomsCalculators.jl)-compatible interface. For example one can use it to compute energy and forces of a copper supercell. First we make the supercell: ```@example calculators using AtomsBuilder system = bulk(:Cu) * (4, 3, 2) # Make copper supercell ``` Next we use the `energy_forces` function from `AtomsCalculators`: ```@example calculators using AtomsCalculators AtomsCalculators.energy_forces(system, calculator) ```
ASEconvert
https://github.com/mfherbst/ASEconvert.jl.git
[ "MIT" ]
1.0.1
086c303982f33d174f9979b232bafc3769ebec2c
code
654
using CloudflareR2 using Documenter DocMeta.setdocmeta!(CloudflareR2, :DocTestSetup, :(using CloudflareR2); recursive=true) makedocs(; modules=[CloudflareR2], authors="Agustín Covarrubias", repo="https://github.com/agucova/CloudflareR2.jl/blob/{commit}{path}#{line}", sitename="CloudflareR2.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://agucova.github.io/CloudflareR2.jl", edit_link="main", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/agucova/CloudflareR2.jl", devbranch="main", )
CloudflareR2
https://github.com/agucova/CloudflareR2.jl.git
[ "MIT" ]
1.0.1
086c303982f33d174f9979b232bafc3769ebec2c
code
590
module CloudflareR2 using AWS, AWSS3, URIs include("client.jl") export R2Config export AWSCredentials # exports from AWSS3.jl export S3Path, s3_arn, s3_put, s3_get, s3_get_file, s3_exists, s3_delete, s3_copy, s3_create_bucket, s3_put_cors, s3_enable_versioning, s3_delete_bucket, s3_list_buckets, s3_list_objects, s3_list_keys, s3_list_versions, s3_get_meta, s3_purge_versions, s3_sign_url, s3_begin_multipart_upload, s3_upload_part, s3_complete_multipart_upload, s3_multipart_upload, s3_get_tags, s3_put_tags, s3_delete_tags end
CloudflareR2
https://github.com/agucova/CloudflareR2.jl.git
[ "MIT" ]
1.0.1
086c303982f33d174f9979b232bafc3769ebec2c
code
4209
""" R2Config A configuration object allowing to use the AWS S3 interface from AWS.jl and AWSS3.jl with [Cloudflare R2](https://developers.cloudflare.com/r2/). You can generate your access key ID and secret access key from the [R2 dashboard](https://developers.cloudflare.com/r2/api/s3/tokens/), as well as your account ID from the [Cloudflare dashboard](https://developers.cloudflare.com/fundamentals/get-started/basic-tasks/find-account-and-zone-ids/). ## Constructors ```julia # By passing only your Cloudflare account ID R2Config(account_id; access_key_id, secret_access_key, region) R2Config(account_id, creds; region) # By passing the endpoint directly using URIs R2Config(URI(endpoint); access_key_id, secret_access_key, region) R2Config(URI(endpoint), creds; region) ``` ## Arguments - `account_id`: Your [Cloudflare account ID](https://developers.cloudflare.com/fundamentals/get-started/basic-tasks/find-account-and-zone-ids/). This will be used to construct the endpoint URL. - `endpoint`: Your Cloudflare S3 API endpoint. - `creds`: An `AWSCredentials` object providing the credentials to access R2. - `access_key_id`: An access key ID for Cloudflare R2. This will use `R2_ACCESS_KEY_ID` or `AWS_ACCESS_KEY_ID` if available. - `secret_access_key`: A secret access key for Cloudflare R2. This will use `R2_SECRET_ACCESS_KEY` or `AWS_SECRET_ACCESS_KEY` if available. - `region`: The region to use. Defaults to `"auto"`. Valid values are `"auto"`, `"wnam"`, `"enam"`, `"weur"`, `"eeur"`, and `"apac"`. ## Examples ```julia using R2 # tokens are read from environment # region set to auto config = R2Config("YOUR_ACCOUNT_ID") # using the AWS S3 API s3_list_buckets(config) # using the S3Path interface path = S3Path("s3://bucket-name", config=config) readdir(path) ``` """ struct R2Config <: AbstractAWSConfig endpoint::URI region::String creds::AWSCredentials end CLOUDFLARE_REGIONS = [ "auto", "wnam", "enam", "weur", "eeur", "apac" ] function R2Config(endpoint::URI, creds::AWSCredentials; region::AbstractString="auto") if region ∉ CLOUDFLARE_REGIONS throw(ArgumentError("region must be one of $(CLOUDFLARE_REGIONS).")) end R2Config(endpoint, region, creds) end function isalnum(s::AbstractString)::Bool for c in s isletter(c) || isdigit(c) || return false end return true end function R2Config(account_id::AbstractString, creds::AWSCredentials; region::AbstractString="auto") if !isalnum(account_id) throw(ArgumentError("account_id must be alphanumeric." * "If you want to pass the endpoint directly, pass a URI object instead.")) end endpoint = URI("https://$(account_id).r2.cloudflarestorage.com") R2Config(URI(endpoint), creds; region=region) end function get_access_key_id()::AbstractString access_key = get(ENV, "R2_ACCESS_KEY_ID", nothing) if access_key === nothing access_key = get(ENV, "AWS_ACCESS_KEY_ID", nothing) end if access_key === nothing throw(ArgumentError("No access key ID found.")) end access_key end function get_secret_access_key() secret_access_key = get(ENV, "R2_SECRET_ACCESS_KEY", nothing) if secret_access_key === nothing secret_access_key = get(ENV, "AWS_SECRET_ACCESS_KEY", nothing) end if secret_access_key === nothing throw(ArgumentError("No secret access key found.")) end secret_access_key end function R2Config( id_or_endpoint::Union{AbstractString,URI}; access_key_id::AbstractString=get_access_key_id(), secret_access_key::AbstractString=get_secret_access_key(), region::AbstractString="auto" ) R2Config(id_or_endpoint, AWSCredentials(access_key_id, secret_access_key, "", ""); region=region) end AWS.region(cfg::R2Config) = cfg.region AWS.credentials(cfg::R2Config) = cfg.creds function AWS.generate_service_url(cfg::R2Config, service::String, resource::String) service == "s3" || throw(ArgumentError("An R2 config only supports S3 service requests; got $service")) # NOTE: cannot use joinpath here, as it will silently truncate many resource strings string(cfg.endpoint, resource) end
CloudflareR2
https://github.com/agucova/CloudflareR2.jl.git
[ "MIT" ]
1.0.1
086c303982f33d174f9979b232bafc3769ebec2c
code
988
using CloudflareR2 using Test using URIs # NOTE: the vast majority of min.io functionality is in AWSS3, which is why these tests are so minimal # these should be picked up by R2Config ENV["R2_ACCESS_KEY_ID"] = "testuser" ENV["R2_SECRET_ACCESS_KEY"] = "testpassword" @testset "CloudflareR2.jl" begin cfg = R2Config("ACCOUNTID") @test cfg.region == "auto" @test cfg.endpoint == URI("https://ACCOUNTID.r2.cloudflarestorage.com") # Test invalid account id @test_throws ArgumentError R2Config("non_alpha") # Custom endpoint cfg = R2Config(URI("http://localhost:9000")) @test cfg.region == "auto" # With credentials cfg = R2Config(URI("http://localhost:9000"), access_key_id="test", secret_access_key="test") @test cfg.region == "auto" @test cfg.endpoint == URI("http://localhost:9000") # Test invalid region @test_throws ArgumentError R2Config(URI("http://localhost:9000"), cfg.creds; region="invalid") end
CloudflareR2
https://github.com/agucova/CloudflareR2.jl.git
[ "MIT" ]
1.0.1
086c303982f33d174f9979b232bafc3769ebec2c
docs
821
# CloudflareR2.jl [![CI](https://github.com/agucova/CloudflareR2.jl/actions/workflows/CI.yml/badge.svg)](https://github.com/agucova/CloudflareR2.jl/actions/workflows/CI.yml) [![Documentation](https://img.shields.io/badge/docs-stable-blue.svg)](https://agucova.github.io/CloudflareR2.jl/stable) [![Documentation](https://img.shields.io/badge/docs-dev-blue.svg)](https://agucova.github.io/CloudflareR2.jl/dev) Unofficial Julia tools for interacting with [Cloudflare R2](https://www.cloudflare.com/products/r2/) using the Julia [AWS S3](https://github.com/JuliaCloud/AWSS3.jl) package. > **Note** > This package is a fork from [Minio.jl](https://gitlab.com/ExpandingMan/Minio.jl). > This is also not an official Cloudflare package. You can see the documentation [here](https://agucova.github.io/CloudflareR2.jl/stable).
CloudflareR2
https://github.com/agucova/CloudflareR2.jl.git
[ "MIT" ]
1.0.1
086c303982f33d174f9979b232bafc3769ebec2c
docs
908
```@meta CurrentModule = CloudflareR2 ``` # CloudflareR2 !!! note This package is a fork from [Minio.jl](https://gitlab.com/ExpandingMan/Minio.jl). This is also not an official Cloudflare package. This package provides Julia tools for working with [Cloudflare R2](https://www.cloudflare.com/products/r2/). Cloudflare R2 is fully compatible with the AWS S3 interface, so interaction with R2 is achieved through [AWSS3.jl](https://github.com/JuliaCloud/AWSS3.jl). This package simply contains some convenient constructors to set up the configuration to be used with AWSS3.jl. ## Installation The package itself can be installed with ```julia Pkg.add("CloudflareR2") ``` or `]add CloudflareR2` in the REPL. ## Client This package provides a `AbstractAWSConfig` object to be used with Cloudflare R2. This allows seamless integration with the AWSS3.jl package. ```@docs CloudflareR2.R2Config ```
CloudflareR2
https://github.com/agucova/CloudflareR2.jl.git
[ "MIT" ]
0.3.1
fac1dc69fff3ab196f1d7efcdf01527cfc27e7c3
code
574
using Grader using Documenter DocMeta.setdocmeta!(Grader, :DocTestSetup, :(using Grader); recursive=true) makedocs(; modules=[Grader], authors="Christopher Tessum and contributors", repo="https://github.com/ctessum/Grader.jl/blob/{commit}{path}#{line}", sitename="Grader.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://ctessum.github.io/Grader.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/ctessum/Grader.jl", )
Grader
https://github.com/ctessum/Grader.jl.git
[ "MIT" ]
0.3.1
fac1dc69fff3ab196f1d7efcdf01527cfc27e7c3
code
6041
module Grader export Problem, @rungolden!, @runstudent!, grade!, pl_JSON, fill_answers using Parameters import Random import JSON import Espresso """ Represents an image with a label and url. """ @with_kw mutable struct Image label::String = "" url::String = "" end """ Represents the result of a `grade!` action. """ @with_kw mutable struct TestResult name::String = "" description::String = "" points::Float64 = 0 max_points::Float64 = 0 message::String = "" output::String = "" images::Vector{Image} = [] end """ Represent a problem for grading. Fields: - Gradable: whether the problem is gradable, i.e. whether the all relavent code has executed without any errors - Score: the score of the problem, as a fraction of the maximum possible score - Message: Any message associated with the graded problem - Output: The output of the problem grading - Images: Any images associated with the problem grading - Tests: A list of tests associated with the problem """ @with_kw mutable struct Problem gradable::Bool = true score::Float64 = 0 message::String = "" output::String = "" images::Vector{Image} = [] tests::Vector{TestResult} = [] end """ Return an expression representing the given code inside of a module. """ function asmodexpr(code::AbstractString) mod = "module " * Random.randstring(Random.MersenneTwister(), "abcdefghijklmnopqrstuvwxyz", 20) * "\n" * code * "\nend" Meta.parse(mod) end """ rungolden! p::Problem goldencode::AbstractString Run the provided code string inside a module and return the module. If an error occurs it will be logged in `Problem` `p` as a problem with the "golden" code. """ macro rungolden!(p, goldencode) runcode!(p, goldencode, [], "golden", "Internal grading error, please notify instructor.") end """ @runstudent! p::Problem studentcode::AbstractString Run the provided code string inside a module and return the module. If an error occurs it will be logged in `Problem` `p` as a problem with the "student" code. """ macro runstudent!(p, studentcode, forbidden_symbols=[]) runcode!(p, studentcode, forbidden_symbols, "student", "There was an error running your code, please see information below.") end function runcode!(p, code, forbidden_symbols, codetype, errmessage) return quote local prob = $(esc(p)) local studentresult = Module() try local expr = Grader.asmodexpr($(esc(code))) for symbol ∈ $(esc(forbidden_symbols)) if length(Espresso.findex(symbol, expr)) > 0 error("Using $symbol is not allowed.") end end studentresult = Base.eval(expr) catch err prob.output = prob.output * "error running $($(esc(codetype))) code:\n" * sprint(showerror, err, backtrace()) * "\n" prob.gradable = false prob.message = $(esc(errmessage)) end studentresult end end """ grade!(p::Problem, name::String, description::String, points::Real, expr::Expr, msg_if_incorrect::String) Add a grade for problem `p`. This grade will have the given `name` and `description` in the grader output, and will be associated with the number of `points`. The function will evaluate the given expression `expr`; if it evaluates to true, the given number of `points` will be awarded, otherwise zero points will be awarded and `msg_if_incorrect` will be logged to the problem `p`. """ function grade!(p::Problem, name::String, description::String, points::Real, expr::Expr, msg_if_incorrect::String) if !p.gradable return nothing end t = TestResult(max_points=points, name=name, description=description) correct = false try correct = eval(expr) catch err t.output = t.output * "\n" * sprint(showerror, err) end if correct === missing t.message = "your answer contains a 'missing' value" else try correct ? t.points = points : t.message = msg_if_incorrect catch err t.message = msg_if_incorrect t.output = t.output * "\n" * sprint(showerror, err) end end append!(p.tests, [t]) pts = 0 totalpts = 0 for t in p.tests pts += t.points totalpts += t.max_points end p.score = float(pts) / float(totalpts) return nothing end @doc raw""" fill_answers(code::AbstractString, answerkey::Dict)::String Fill the answer key into a code template and return the resulting code string. For example, consider the code template below, that gives the radius of a circle and asks the student to fill in the area and perimeter. In the template, the area and perimeter are given as variables `a` and `p` with values `missing`, and the student is meant to replace `missing` with the actual answer. ``` jldoctest code = "# Calculate the area and perimeter of a circle with radius 2.\n"* "r = 2\n"* "a = missing # Area\n"* "p = missing # Perimeter\n" answer_code = fill_answers(code, Dict( :(a = missing) => :(a = π * r^2), :(p = missing) => :(p = 2π * r))); p = Problem() answer = @runstudent! p answer_code grade!(p, "area", "calculate area", 1, :($answer.a ≈ 4π), "area is incorrect") grade!(p, "perimeter", "calculate perimeter", 1, :($answer.p ≈ 4π), "perimeter is incorrect") println("Answer key score is $(p.score).") # output Answer key score is 1.0. ``` """ function fill_answers(code::AbstractString, answerkey::Dict)::String expr = Meta.parse("begin\n $code \nend") expr = Espresso.subs(expr, answerkey) io = IOBuffer() print(io, expr) s = String(take!(io)) replace(replace(s, r"end$"=>""), r"^begin"=>"") # remove begin and end added above end """ pl_JSON(io::IO, p::Problem) Write a the contents of the `Problem` `p` to the IO stream `io` as a [PrairieLearn](https://prairielearn.readthedocs.io/en/latest/)-compatible JSON file. """ function pl_JSON(io::IO, p::Problem) JSON.print(io, p) end end
Grader
https://github.com/ctessum/Grader.jl.git
[ "MIT" ]
0.3.1
fac1dc69fff3ab196f1d7efcdf01527cfc27e7c3
code
9124
using Grader using Test @testset "Grader.jl" begin # Test whether evalasmodule is working correctly for a basic problem. @testset "evalasmodule" begin golden_code = """x=2 y = x * 3 """ student_code = """x=2 y = x + x + x z = 4 """ p = Problem() golden_result = @rungolden! p golden_code student_result = @runstudent! p student_code @testset "correct x" begin @test golden_result.x == student_result.x end @testset "correct y" begin @test golden_result.y ≈ student_result.y end @testset "correct z only in student code" begin @test_throws UndefVarError golden_result.z @test student_result.z == 4 end @testset "Throws ParseError for syntax error" begin syntaxerr = "x= @@@" p = Problem() @runstudent! p syntaxerr @test occursin("ParseError", p.output) end end @testset "grade problem" begin @testset "correct answer" begin goldencode = """x=2 y = x * 3 """ studentcode = """x=2 y = x + x + x """ p = Problem() golden = @rungolden! p goldencode student = @runstudent! p studentcode grade!(p, "y", "check y", 2, :($student.y ≈ $golden.y), "y is incorrect") @test length(p.tests) == 1 @test p.tests[1].max_points ≈ 2 @test p.tests[1].points ≈ 2 @test p.score ≈ 1 end @testset "partially correct answer" begin goldencode = """x=2 y = x * 3 z = y + 2 """ studentcode = """x=2 y = x + x + x z = y + 3 """ p = Problem() golden = @rungolden! p goldencode student = @runstudent! p studentcode grade!(p, "y", "check y", 2, :($student.y ≈ $golden.y), "y is incorrect") grade!(p, "z", "check z", 8, :($student.z ≈ $golden.z), "z is incorrect") @test length(p.tests) == 2 @test p.tests[1].max_points ≈ 2 @test p.tests[2].max_points ≈ 8 @test p.tests[1].points ≈ 2 @test p.tests[2].points ≈ 0 @test p.tests[2].message == "z is incorrect" @test p.score ≈ 0.2 end @testset "error in student code" begin goldencode = """x=2 y = x * 3 """ studentcode = """x=2 y = x + x + xx """ p = Problem() golden = @rungolden! p goldencode student = @runstudent! p studentcode grade!(p, "y", "check y", 2, :($student.y ≈ $golden.y), "y is incorrect") @test !p.gradable @test p.message == "There was an error running your code, please see information below." end @testset "missing value in student code" begin goldencode = """x=2 y = x * 3 """ studentcode = """x=2 y = missing """ p = Problem() golden = @rungolden! p goldencode student = @runstudent! p studentcode grade!(p, "y", "check y", 2, :($student.y ≈ $golden.y), "y is incorrect") @test p.gradable @test p.tests[1].message == "your answer contains a 'missing' value" end @testset "error in golden code" begin goldencode = """x=2 y = x * 3y """ studentcode = """x=2 y = x + x + x """ p = Problem() golden = @rungolden! p goldencode student = @runstudent! p studentcode @test !p.gradable @test p.message == "Internal grading error, please notify instructor." end @testset "student missing variable" begin goldencode = """x=2 y = x * 3 """ studentcode = """x=2 """ p = Problem() golden = @rungolden! p goldencode student = @runstudent! p studentcode grade!(p, "y", "check y", 2, :($student.y ≈ $golden.y), "y is incorrect") @test p.tests[1].output == "\nUndefVarError: y not defined" @test p.tests[1].message == "y is incorrect" end @testset "forbidden symbol" begin studentcode = """ using LinearAlgebra x = 2 """ p = Problem() student = @runstudent! p studentcode [:YYY :LinearAlgebra] @test occursin("Using LinearAlgebra is not allowed.", p.output) @test p.message == "There was an error running your code, please see information below." end @testset "type conversion error" begin studentcode = """ function fib(n::Int)::Int nothing end """ goldencode = """ function fib(n::Int)::Int if n <= 1 return n else return fib(n - 1) + fib(n - 2) end end """ p = Problem() golden = @rungolden! p goldencode student = @runstudent! p studentcode Grader.grade!(p, "fib(1)", "Check fib(1)", 1, :($student.fib(1) ≈ $golden.fib(1)), "fib(1) is incorrect") Grader.grade!(p, "fib(7)", "Check fib(7)", 2, :($student.fib(7) ≈ $golden.fib(7)), "fib(7) is incorrect") Grader.grade!(p, "fib(7)", "Check fib(7)", 2, :($golden.fib(7) ≈ $golden.fib(7)), "fib(7) is incorrect") @test p.score ≈ 2.0 / 5.0 @test occursin("Cannot `convert`", p.tests[1].output) @test p.tests[1].message == "fib(1) is incorrect" end end @testset "pl_JSON" begin goldencode = """x=2 y = x * 3 z = y + 2 """ studentcode = """x=2 y = x + x + x z = y + 3 """ p = Problem() golden = @rungolden! p goldencode student = @runstudent! p studentcode grade!(p, "y", "check y", 2, :($student.y ≈ $golden.y), "y is incorrect") grade!(p, "z", "check z", 8, :($student.z ≈ $golden.z), "z is incorrect") s = IOBuffer() pl_JSON(s, p) jsondata = String(take!(s)) @test jsondata == """{"gradable":true,"score":0.2,"message":"","output":"","images":[],"tests":[{"name":"y","description":"check y","points":2.0,"max_points":2.0,"message":"","output":"","images":[]},{"name":"z","description":"check z","points":0.0,"max_points":8.0,"message":"z is incorrect","output":"","images":[]}]}""" @test length(p.tests) == 2 @test p.tests[1].max_points ≈ 2 @test p.tests[2].max_points ≈ 8 @test p.tests[1].points ≈ 2 @test p.tests[2].points ≈ 0 @test p.tests[2].message == "z is incorrect" @test p.score ≈ 0.2 end @testset "fill answers" begin code = """ # Calculate the area and perimeter of a cirle with radius 2. r = 2 a = missing # Area p = missing # Perimeter """ answer_code = fill_answers(code, Dict( :(a = missing) => :(a = π * r^2), :(p = missing) => :(p = 2π * r))) p = Problem() answer = @runstudent! p answer_code grade!(p, "area", "calculate area", 1, :($answer.a ≈ 4π), "area is incorrect") grade!(p, "perimeter", "calculate perimeter", 1, :($answer.p ≈ 4π), "perimeter is incorrect") @test p.score ≈ 1.0 end @testset "fill answers 2" begin code = """ using LinearAlgebra using Markdown n = missing md\"\"\"Testing if markdown strings are okay.\"\"\" """ answer_code = fill_answers(code, Dict( :(n = missing) => :(n = LinearAlgebra.norm([1, 2, 3])) )) p = Problem() answer = @runstudent! p answer_code grade!(p, "norm", "calculate norm", 1, :($answer.n ≈ 3.7416573867739413), "norm is incorrect") @test p.score ≈ 1.0 end @testset "plot" begin using LinearAlgebra studentcode = """ using Plots x=1:10 y = x.^2 xy = plot(x,y) """ p = Problem() student = @runstudent! p studentcode grade!(p, "XY Plot", "Data length", 1, quote xlen = length($student.xy[1][1][:x]) ylen = length($student.xy[1][1][:y]) xlen == ylen == 10 end, "the number of data points in x or y is incorrect") grade!(p, "XY Plot", "Y values", 3, quote ynorm = $norm($student.xy[1][1][:y]) ynorm ≈ 159.16343801262903 end, "The Y values are not correct") @test p.score ≈ 1.0 end end
Grader
https://github.com/ctessum/Grader.jl.git
[ "MIT" ]
0.3.1
fac1dc69fff3ab196f1d7efcdf01527cfc27e7c3
docs
851
# Grader [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://ctessum.github.io/Grader.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://ctessum.github.io/Grader.jl/dev) [![Build Status](https://github.com/ctessum/Grader.jl/workflows/CI/badge.svg)](https://github.com/ctessum/Grader.jl/actions) [![Coverage](https://codecov.io/gh/ctessum/Grader.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/ctessum/Grader.jl) [![Code Style: Blue](https://img.shields.io/badge/code%20style-blue-4495d1.svg)](https://github.com/invenia/BlueStyle) [Grader](https://github.com/ctessum/Grader.jl) is an assignment autograder for Julia. It has been designed to be used with the [PrairieLearn](https://prairielearn.readthedocs.io/en/latest/) learning system, but it could also be used with any other learning system.
Grader
https://github.com/ctessum/Grader.jl.git
[ "MIT" ]
0.3.1
fac1dc69fff3ab196f1d7efcdf01527cfc27e7c3
docs
3436
```@meta CurrentModule = Grader ``` # Grader.jl Documentation [Grader](https://github.com/ctessum/Grader.jl) is an assignment autograder for Julia. It has been designed to be used with the [PrairieLearn](https://prairielearn.readthedocs.io/en/latest/) learning system, but it could also be used with any other learning system. # Examples ## Simple example Here is a simple example of how to use Grader: ```jldoctest using Grader # This is the code with the correct answer: goldencode = """ x=2 y = x * 3 """ # This is the code with the student's answer: studentcode = """ x=2 y = x + x + x """ p = Problem() golden = @rungolden! p goldencode student = @runstudent! p studentcode grade!(p, "y", "check y", 2, :($student.y ≈ $golden.y), "y is incorrect") p # output Problem gradable: Bool true score: Float64 1.0 message: String "" output: String "" images: Array{Grader.Image}((0,)) tests: Array{Grader.TestResult}((1,)) ``` ## Example with incorrect answer Here's an example of what it looks like when the student gets the wrong answer: ```jldoctest using Grader # This is the code with the correct answer: goldencode = """ x=2 y = x * 3 """ # This is the code with the student's answer: studentcode = """ x=2 y = x + x + 2x """ p = Problem() golden = @rungolden! p goldencode student = @runstudent! p studentcode grade!(p, "y", "check y", 2, :($student.y ≈ $golden.y), "y is incorrect") p.tests[1] # output Grader.TestResult name: String "y" description: String "check y" points: Float64 0.0 max_points: Float64 2.0 message: String "y is incorrect" output: String "" images: Array{Grader.Image}((0,)) ``` We can also forbid students from using certain symbols (e.g libraries): ```jldoctest using Grader studentcode = """ using LinearAlgebra x=2 y = x + x + 2x """ p = Problem() @runstudent! p studentcode [:LinearAlgebra] p.output[1:63] # output "error running student code:\nUsing LinearAlgebra is not allowed." ``` ## Example with plot This is a more complex example that grades a plot and writes out the output as JSON. ```jldoctest using Grader using LinearAlgebra, JSON studentcode = """ using Plots x=1:10 y = x.^2 xy = plot(x,y) """ p = Problem() student = @runstudent! p studentcode grade!(p, "XY Plot", "Data length", 1, quote xlen = length($student.xy[1][1][:x]) ylen = length($student.xy[1][1][:y]) xlen == ylen == 10 end, "the number of data points in x or y is incorrect") grade!(p, "XY Plot", "Y values", 3, quote ynorm = $norm($student.xy[1][1][:y]) ynorm ≈ 159.16343801262903 end, "The Y values are not correct") # Output to JSON and print the result b = IOBuffer() pl_JSON(b, p) JSON.print(JSON.parse(String(take!(b))), 4) # output { "images": [], "score": 1.0, "output": "", "message": "", "gradable": true, "tests": [ { "images": [], "name": "XY Plot", "points": 1.0, "output": "", "message": "", "max_points": 1.0, "description": "Data length" }, { "images": [], "name": "XY Plot", "points": 3.0, "output": "", "message": "", "max_points": 3.0, "description": "Y values" } ] } ``` # API Documentation ```@index ``` ```@autodocs Modules = [Grader] ```
Grader
https://github.com/ctessum/Grader.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
604
using Documenter, PhyloDiamond makedocs( sitename="PhyloDiamond.jl", authors="Zhaoxing Wu, Claudia Solís-Lemus, and contributors", modules=[PhyloDiamond], format = Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true"), pages = [ "Home" => "index.md", "Manual" => [ "Installation" => "man/installation.md", "Implementation" => "man/implementation.md", ], "Library" => [ "Public Methods" => "lib/public_methods.md", ] ] ) deploydocs( repo = "github.com/solislemuslab/PhyloDiamond.jl.git", )
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
1111
using PhyloNetworks using PhyloPlots using DataFrames using CSV ## Read network in parenthetical format net = readTopology("((((A,B))#H1:::0.8,((E,F),(#H1:::0.2,(C,D)))),(G,H));") plot(net,:R) ## just to check it matches the ipad notes printEdges(net) ## List of quartets and create dummy CF table with observed cf ## we need this CF table so that readTableCF creates the DataCF object quartets = PhyloNetworks.allQuartets(tipLabels(net), false) tx1 = [] tx2 = [] tx3 = [] tx4 = [] for q in quartets push!(tx1,q.taxon[1]) push!(tx2,q.taxon[2]) push!(tx3,q.taxon[3]) push!(tx4,q.taxon[4]) end df = DataFrame(tx1=tx1, tx2=tx2, tx3=tx3, tx4=tx4, obsCF1=ones(length(tx1)), obsCF2=zeros(length(tx1)), obsCF3=zeros(length(tx1))) cf = readTableCF!(df) ## We need to optimize the pseudolikelihood ## on the network for those dummy observed CF ## in order to compute the expected CFs topologyQPseudolik!(net, cf) df_wide = fittedQuartetCF(cf) ## "true" concordance factors: expcf = df_wide[:,[:tx1, :tx2, :tx3, :tx4, :expCF12, :expCF13, :expCF14]] CSV.write("scripts/julia/N2222_expCF.txt", expcf)
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
1431
## Julia script to map CF table to a values ## Claudia March 2022 ## Note: this is just pseudo code for now ## we also want to put this script into a function with cf,N as input arguments and mean_a as output ## Input: cf = DataFrame(CSV.File("N2222_expCF.txt")) N = [("A","B"),("C","D"),("E","F"),("G","H")] ## create vector a a = zeros(57) ## create vector that counts how many rows are mapped to each a value c = ones(57) ## note: the names of the functions can be changed (I did not have your functions when I wrote this) for row in eachrow(cf) taxa = collect(row[1:4]) ## taxa for that quartet cfs = collect(row[5:7]) ## CFs, not sure if they are in columns 5,6,7 n = get_n_quartet(taxa, N) ## returns the n=(1,2,1,0) quartet vector e.g. ind = which_a(n) ## returns the indices in the a vector for that quartet vector e.g. (34,35,36). The order is major, minor, minor ord_cfs = cfs_in_order(taxa, cfs, N) ## returns the CFs from the table (cfs) in the order major, minor, minor if a[ind] .== 0 ## we have not added these a values before a[ind] = ord_cfs ## we map the CFs values to the a values in the order major, minor, minor else a[ind] += ord_cfs ## we add the CFs values, and we will divide by the c vector at the end (to get the average) c[ind] += 1 ## add one row that is mapped to this a values end end mean_a = a./c ## divide a by c element-wise
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
2315
# Julia script to plot the dog network # Claudia (November 2022) using PhyloNetworks, PhyloPlots # Network by SNaQ and invariants net = readTopology("(((Coyote,((GreyWolf,Dog):0.4736595577884197,#H7:::0.2642622177134866):0.14802726306398745):1.5457473684659713,(GoldenJackal)#H7:::0.7357377822865134):2.4037173930657434,AfricanHuntingDog,Dhole);") rootatnode!(net,"AfricanHuntingDog") plot(net,:R) plot(net,:R, showNodeNumber=true) rotate!(net, -2) rotate!(net, -3) rotate!(net, -4) rotate!(net, -5) using RCall R"par"(mar=[.1,.1,.1,.1]); plot(net, style=:majortree, edgewidth=2.0, arrowlen=0.1, tipoffset = 0.1, majorhybridedgecolor = "forestgreen", minorhybridedgecolor = "forestgreen") # Network by PhyloNet ML net2 = readTopology("(AfricanHuntingDog:1.6101210673311783,(Dhole:3.098659596612107,((GoldenJackal:0.06861236708130897)#H1:0.38708669395167933::0.748622919326696,(Coyote:3.9986647804844644,(#H1:0.8103263495430857::0.25137708067330405,(Dog:2.936141610506084,GreyWolf:0.5582715925453998):0.3935145303756744):0.08298883848855856):2.0660671784296514):2.678281274906509):3.7168919379799035);") rootatnode!(net2,"AfricanHuntingDog") plot(net2,:R, showNodeNumber=true) rotate!(net2, -6) plot(net2, style=:majortree, edgewidth=2.0, arrowlen=0.1, tipoffset = 0.1, majorhybridedgecolor = "blue", minorhybridedgecolor = "blue") ## same as snaq, so not included # Network by PhyloNet MPL net3 = readTopology("(AfricanHuntingDog:1.0,((((Coyote:1.0,(Dog:1.0,GreyWolf:1.0):0.5745418868229112):0.836566984410819,(GoldenJackal:1.0)#H1:1.0::0.940732692938983):2.2916146136988855,#H1:1.0::0.059267307061017016):0.8776623951631757,Dhole:1.0):5.909315396052653);") rootatnode!(net3,"AfricanHuntingDog") plot(net3,:R, showNodeNumber=true) rotate!(net3, -3) rotate!(net3, -4) rotate!(net3, -5) rotate!(net3, -6) plot(net3, edgewidth=2.0, arrowlen=0.1, tipoffset = 0.1, majorhybridedgecolor = "darkmagenta", minorhybridedgecolor = "darkmagenta") # Other networks net = readTopology("((((((1,3),5),(2)#H1),6),#H1),4);") rootatnode!(net,"1") plot(net,:R, showNodeNumber=true) rotate!(net, -4) ## Now with the names: net = readTopology("((((((AfricanHuntDog,Dhole),GoldenJackal),(Coyote)#H1),GreyWolfEUR),#H1),Dog);") rootatnode!(net,"AfricanHuntDog") plot(net,:R, showNodeNumber=true) rotate!(net, -4) plot(net,:R)
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
342
#cd("/Users/zhaoxingwu/Desktop/claudia lab/2022 spring phylogenetic/phylo-invariants") using PhyloNetworks #raxmltrees = joinpath(dirname(pathof(PhyloNetworks)), "..","examples","raxmltrees.tre") #less(raxmltrees) genetrees = readMultiTopology("./simulation/sim_trees_2222_100"); q,t = countquartetsintrees(genetrees); df = writeTableCF(q,t)
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
5282
""" cd("/Users/zhaoxingwu/Desktop/claudia lab/2022 spring phylogenetic/phylo-invariants") include("./scripts/julia/mapping.jl") include("./scripts/julia/invariants.jl") include("./scripts/julia/test_invariants.jl") """ using PhyloNetworks, PhyloPlots, DataFrames, CSV, Statistics, Distributions, Random, DelimitedFiles, Combinatorics using JLD2 #https://github.com/chaoszhang/Weighted-ASTRAL_data #https://www.sciencedirect.com/science/article/pii/S0960982218311254 #choose(13, 4) = 715 #choose(12, 4) function main() end function read_gene_trees() #cf = generate_cf_from_gene_trees("./simulation/dogs_estimated_gene_trees.tree") #genetrees = readMultiTopology("./simulation/sim_trees/dogs_estimated_gene_trees.tree") #save_object("dog_genetrees.jld2", genetrees) #DataFrame(taxon = unique!(vcat(df[:, "t1"], df[:, "t2"], df[:, "t3"], df[:, "t4"]))) """ tm = DataFrame(CSV.File("./simulation/sim_trees/dog/taxonmap.csv")) taxonmap = Dict(row[:individual] => row[:species] for row in eachrow(tm)) genetrees = load_object("dog_genetrees.jld2") q,t = countquartetsintrees(genetrees, taxonmap, showprogressbar=true); save_object("q.jld2", q) save_object("t.jld2", t) df_wide = writeTableCF(q,t) df = df_wide[:,[:t1, :t2, :t3, :t4, :CF12_34, :CF13_24, :CF14_23]] save_object("cf_dog.jld2", df) df = load_object("./simulation/sim_trees/dog/cf_dog_merged.jld2") tm = DataFrame(CSV.File("./simulation/sim_trees/dog/taxonmap.csv")) taxon = unique!(tm[:,"species"]) for temp in ["Grey wolf Asian (Eurasian)", "Grey wolf North American", "Grey wolf Middle Eastern", "African golden wolf hybrid", "African golden wolf Northwestern","African golden wolf Eastern", "AndeanFox"] deleteat!(taxon, findall(x->x==temp,taxon)) df = df[df[:,"t1"].!=temp,:] df = df[df[:,"t2"].!=temp,:] df = df[df[:,"t3"].!=temp,:] df = df[df[:,"t4"].!=temp,:] end value_map = Dict(taxon[i] => i for i in 1:length(taxon)) for col in ["t1", "t2", "t3", "t4"] for i in 1:nrow(df) df[i,col] = string(value_map[df[i,col]]) end end """ end function run_snaq() @time net0 = snaq!(readTopology("./simulation/sim_trees/dog/start.tree"), readTableCF(df), hmax=1, filename="net0_bucky", seed=123, runs=10) end function script_phylonet_dog_unrooted() f = open("./simulation/sim_trees/dog/dogs_estimated_gene_trees.tree", "r") file = open("dog.nex", "a") cnt = 0 write(file, "#NEXUS\nBEGIN Trees;\n") for line in readlines(f) cnt+=1 net = readTopology(line) leaf = [] for i in net.leaf push!(leaf, i.name) end #delete species for i in leaf if i in ind_del deleteleaf!(net, i, keeporiginalroot=true) end end flag = Dict(Pair.(taxon, false)) net_merge = net leaf_del = [] leaf = [] for i in net.leaf push!(leaf, i.name) end for i in 1:length(leaf) if leaf[i] in tm[:,"individual"] if !flag[tm_dict[leaf[i]]] flag[tm_dict[leaf[i]]] = true net_merge.leaf[i].name = string(value_map[tm_dict[leaf[i]]]) else push!(leaf_del, leaf[i]) end end end for i in leaf_del deleteleaf!(net_merge, i, keeporiginalroot=true) end if length(net_merge.leaf) > 3 write(file, "Tree gt"* string(cnt)* "="* writeTopology(net_merge)*"\n") end end write(file, "END;\nBEGIN PHYLONET;\nInferNetwork_MPL (all) 1 -x 10 -pl 10;\nEND;") close(f) close(file) end #creating input file for phylonet function script_phylonet_dog_rooted() f = open("./scripts/julia/dog.nex", "r") file = open("dog_rooted.nex", "a") cnt = 0 write(file, "#NEXUS\nBEGIN Trees;\n") for line in readlines(f) if startswith(line, "Tree") _, net = split(line, "=") net = readTopology(net) if net.numTaxa > 4 cnt+=1 if "1" in tipLabels(net) rootatnode!(net,"1") else rootatnode!(net,"3") end write(file, "Tree gt"* string(cnt)* "="* writeTopology(net)*"\n") end end end write(file, "END;\nBEGIN PHYLONET;\nInferNetwork_MPL (all) 1 -x 10 -pl 10;\nEND;") close(f) close(file) end main() """ tm = DataFrame(CSV.File("./simulation/sim_trees/dog/taxonmap.csv")) #6 species for temp in ["Grey wolf Asian (Eurasian)", "Grey wolf North American", "Grey wolf Middle Eastern", "African golden wolf hybrid", "African golden wolf Northwestern","African golden wolf Eastern", "AndeanFox"] tm = tm[tm[:,"species"].!=temp,:] end tm_dict = Dict(Pair.(tm.individual, tm.species)) taxon = unique!(tm[:,"species"]) value_map = Dict(taxon[i] => i for i in 1:length(taxon)) tm_del = DataFrame(CSV.File("./simulation/sim_trees/dog/taxonmap_del.csv")) #species need to be deleted ind_del = tm_del[:, "individual"] """
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
1794
# Automatic test for the get_a function # Claudia (June 2022) include("../create_cf.jl") # Reading CF table: cf = CSV.read("scripts/julia/N2222_expCF.txt", DataFrame) # Reading network N = [("A", "B"), ("C", "D"), ("E", "F"), ("G", "H")] ## true network i=1 temp = Array(cf[i, :]) q = temp[1:4] cfs = [temp[5], temp[6], temp[7]] n = get_n(N, q) n == [2,0,2,0] || error("wrong n") cfs_ord = cfs_in_order(N, q, cfs) round.(cfs_ord;digits=2) == [0.96,0.02,0.02] || error("wrong cfs_ord") i=69 temp = Array(cf[i, :]) q = temp[1:4] cfs = [temp[5], temp[6], temp[7]] n = get_n(N, q) n == [0,1,1,2] || error("wrong n") cfs_ord = cfs_in_order(N, q, cfs) round.(cfs_ord;digits=2) == [0.91,0.05,0.05] || error("wrong cfs_ord") N = [("A","E"),("C","B"),("D","F"),("G","H")] i=1 temp = Array(cf[i, :]) q = temp[1:4] cfs = [temp[5], temp[6], temp[7]] n = get_n(N, q) n == [2,1,1,0] || error("wrong n") cfs_ord = cfs_in_order(N, q, cfs) round.(cfs_ord;digits=2) == [0.02,0.96,0.02] || error("wrong cfs_ord") i=2 temp = Array(cf[i, :]) q = temp[1:4] cfs = [temp[5], temp[6], temp[7]] n = get_n(N, q) n == [2,2,0,0] || error("wrong n") cfs_ord = cfs_in_order(N, q, cfs) round.(cfs_ord;digits=2) == [0.06,0.87,0.06] || error("wrong cfs_ord") cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", "H")], ["A","H","E","C"], [0.7, 0.2, 0.1]) == [0.1,0.2,0.7] || error("wrong cfs order") cfs_in_order([("E", "F"), ("A", "B"), ("G", "H"), ("C", "D"), ], ["A","H","E","C"], [0.7, 0.2, 0.1]) == [0.2,0.1,0.7] || error("wrong cfs order") cfs_in_order([("A", "B"), ("E", "F"), ("G", "H"), ("C", "D"), ], ["E","C","A","H"], [0.7, 0.2, 0.1]) == [0.2,0.7,0.1] || error("wrong cfs order")
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
6591
#cd("/Users/zhaoxingwu/Desktop/claudia lab/2022 spring phylogenetic/phylo-invariants") include("../scripts/julia/mapping.jl") using DelimitedFiles, DataFrames, CSV # Reading CF table: cf = CSV.read("scripts/julia/N2222_expCF.txt", DataFrame) # We use the following networks to run get_a line by line (see test-get-a.pdf iPad notes) # Reading network #N = [("A", "B"), ("C", "D"), ("E", "F"), ("G", "H")] ## true network #N = [("A", "D"), ("C", "B"), ("E", "F"), ("G", "H")] N = [("A","E"),("C","B"),("D","F"),("G","H")] rst = get_a(cf, N, verbose=false) i=70 temp = Array(cf[i, :]) q = temp[1:4] cfs = [temp[5], temp[6], temp[7]] n = get_n(N, q) cfs_ord = cfs_in_order(N, q, cfs) #reorder cf as major, minor, minor #according to N #for i in 1:Int(length(rst)/3) #println(rst[i*3-2], " ", rst[i*3-1], " ", rst[i*3]) #end #for i in 1:70 # temp = Array(cf[i, :]) # q = temp[1:4] # cfs = temp[5:7] # n = get_n(N, q) #println(n) # if n != [1, 1, 1, 1] #println(cfs_in_order(N, q, cfs)[1], ", ", cfs_in_order(N, q, cfs)[2], ", ", cfs_in_order(N, q, cfs)[3]) # else #println(cfs[1], ", ", cfs[2], ", ", cfs[3]) # end #end #get_a(cf, N) #-------------------------------- # Testing cfs_in_order #-------------------------------- #(1, 1, 1, 1), N2222 println(cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", "H")], ["A","H","E","C"], [0.7, 0.2, 0.1])==[0.1, 0.2, 0.7]) println(cfs_in_order([("E", "F"), ("A", "B"), ("G", "H"), ("C", "D"), ], ["A","H","E","C"], [0.7, 0.2, 0.1])==[0.2, 0.1, 0.7]) println(cfs_in_order([("A", "B"), ("E", "F"), ("G", "H"), ("C", "D"), ], ["E","C","A","H"], [0.7, 0.2, 0.1])==[0.2, 0.7, 0.1]) #N2122 println(cfs_in_order([("A", "B"), ("C", NaN), ("E", "F"), ("G", "H")], ["A","B","E","C"], [0.8, 0.1, 0.1])==[0.8, 0.1, 0.1]) #2110 println(cfs_in_order([("A", "B"), ("C", NaN), ("E", "F"), ("G", "H")], ["A","E","C","B"], [0.1, 0.1, 0.8])==[0.8, 0.1, 0.1]) #2110 println(cfs_in_order([("A", "B"), ("C", NaN), ("E", "F"), ("G", "H")], ["E","G","A","C"], [0.7, 0.2, 0.1])==[0.7, 0.2, 0.1]) #1111 println(cfs_in_order([("A", "B"), ("C", NaN), ("E", "F"), ("G", "H")], ["H","G","A","B"], [0.8, 0.1, 0.1])==[0.8, 0.1, 0.1]) #2002 #N2221 println(cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", NaN)], ["E","B","F","C"], [0.1, 0.8, 0.1])==[0.8, 0.1, 0.1]) #1120 println(cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", NaN)], ["A","B","C","F"], [0.8, 0.1, 0.1])==[0.8, 0.1, 0.1]) #2110 println(cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", NaN)], ["F","G","A","C"], [0.7, 0.2, 0.1])==[0.7, 0.2, 0.1]) #1111 println(cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", NaN)], ["B","F","A","E"], [0.1, 0.8, 0.1])==[0.8, 0.1, 0.1]) #2020 #N2111 println(cfs_in_order([("A", "B"), ("C", NaN), ("E", NaN), ("G", NaN)], ["E","B","G","A"], [0.1, 0.8, 0.1])==[0.8, 0.1, 0.1]) #2011 println(cfs_in_order([("A", "B"), ("C", NaN), ("E", NaN), ("G", NaN)], ["B","E","G","A"], [0.1, 0.1, 0.8])==[0.8, 0.1, 0.1]) #2011 #N2211 println(cfs_in_order([("A", "B"), ("C", "D"), ("E", NaN), ("G", NaN)], ["C","B","D","A"], [0.1, 0.8, 0.1])==[0.8, 0.1, 0.1]) #2200 println(cfs_in_order([("A", "B"), ("C", "D"), ("E", NaN), ("G", NaN)], ["A","B","C","D"], [0.8, 0.1, 0.1])==[0.8, 0.1, 0.1]) #2200 println(cfs_in_order([("A", "B"), ("C", "D"), ("E", NaN), ("G", NaN)], ["C","G","D","A"], [0.1, 0.8, 0.1])==[0.8, 0.1, 0.1]) #1201 println(cfs_in_order([("A", "B"), ("C", "D"), ("E", NaN), ("G", NaN)], ["E","G","C","B"], [0.7, 0.1, 0.2])==[0.7, 0.2, 0.1]) #1111 #-------------------------------- # Testing invariants in true N #-------------------------------- include("../mapping.jl") include("../invariants.jl") # Reading CF table: cf = CSV.read("scripts/julia/N2222_expCF.txt", DataFrame) # Reading network N = [("A", "B"), ("C", "D"), ("E", "F"), ("G", "H")] ## true network a = get_a(cf, N) norm(inv_net1112(a)) norm(inv_net1121(a)) norm(inv_net1211(a)) norm(inv_net2111(a)) norm(inv_net1122(a)) norm(inv_net1212(a)) norm(inv_net2112(a)) norm(inv_net2211(a)) norm(inv_net2121(a)) norm(inv_net1221(a)) norm(inv_net1222(a)) norm(inv_net2212(a)) ## We do not have the true invariants which are 2222, but ## we still expect all invariants to be relative close to 0.0 ## as the order of the taxa matches with the invariants # this is not true for the following network # Reading network N = [("A","E"),("C","B"),("D","F"),("G","H")] a = get_a(cf, N) norm(inv_net1112(a)) norm(inv_net1121(a)) norm(inv_net1211(a)) norm(inv_net2111(a)) norm(inv_net1122(a)) norm(inv_net1212(a)) norm(inv_net2112(a)) norm(inv_net2211(a)) norm(inv_net2121(a)) norm(inv_net1221(a)) norm(inv_net1222(a)) norm(inv_net2212(a)) ## They are much larger than zero, yay! #------------------------------------------------------ # Testing invariants in true N using test_invariants.jl #------------------------------------------------------ include("test_invariants.jl") N = [("A", NaN),("C","D"),("E","F"),("G","H")] network = "(((A)#H1:::0.8, ((#H1:::0.2,(E,F)),(G,H))),(C,D));" #network = "((((C,D),(A)#H1:::0.8),(#H1:::0.2,(E,F))),(G,H));" N_test = [("G", NaN),("E", "A"),("C","H"),("D","F")] println(test_invariants(N_test, generate_cf(N, network))) #writedlm( "temp.csv", test_invariants(N_test, generate_cf(N, network)), ',') t = ["A", "B", "C", "D", "E", "F", "G", "H"] net_all = list_nw(t) N = [("A", "B"),("C","D"),("E","F"),("G","H")] network = "(((A, B)#H1:::0.8, ((#H1:::0.2,(E, F)),(G, H))),(C, D));" cf = generate_cf(N, network) df = DataFrame() for i in 1:length(net_all) colname = "Test$i" df[!,colname] = test_invariants(net_all[i], cf) end #CSV.write( "temp.csv", df) #-------------------------------- # Testing list_nw #-------------------------------- t = ["A", "B", "C", "D", "E"] t = ["A", "B", "C", "D", "E", "F"] t = ["A", "B", "C", "D", "E", "F", "G"] t = ["A", "B", "C", "D", "E", "F", "G", "H"] ret = list_nw(t) for i in 1:length(ret) #println(i, ret[i]) end
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
31598
function main() mac1112 = "a32 - a33, a31 + 2a33 - 1, a28 + a29 + a30 - 1, a23 - a24, a22 + 2a24 - 1, a8 - a9, a7 + 2a9 - 1, 3a9*a30 + a9 - a24 - a33, a24*a29 + 2a24*a30 + a29*a33 - a30*a33 - a33, 3a9*a29 - 2a9 + 2a24 - a33" mac1121 = "a28 + a29 + a30 - 1, a26 - a27, a25 + 2a27 - 1, a20 - a21, a19 + 2a21 - 1, a5 - a6, a4 + 2a6 - 1, a6*a29 + 2a6*a30 - a6 + a21 - a27" mac1122 = "a32 - a33, a31 + 2a33 - 1, a28 + a29 + a30 - 1, a26 - a27, a25 + 2a27 - 1, a23 - a24, a22 + 2a24 - 1, a20 - a21, a19 + 2a21 - 1, a8 - a9, a7 + 2a9 - 1, a5 - a6, a4 + 2a6 - 1, a2 - a3, a1 + 2a3 - 1, 3a9*a30 + a9 - a24 - a33, a24*a29 + 2a24*a30 + a29*a33 - a30*a33 - a33, 3a9*a29 - 2a9 + 2a24 - a33, a6*a29 + 2a6*a30 - a6 + a21 - a27, a3*a29 + 2a3*a30 - 3a6*a33, 3a6*a24 - 3a3*a30 + 3a6*a33 - a3, 3a9*a21 - 3a9*a27 + 3a6*a33 - a3, 3a6*a9 - a3" mac1211 = "a38 - a39, a37 + 2a39 - 1, a35 - a36, a34 + 2a36 - 1, a28 + a29 + a30 - 1, a14 - a15, a13 + 2a15 - 1, a15*a29 - a15*a30 + a36 - a39" mac1212 = "a38 - a39, a37 + 2a39 - 1, a35 - a36, a34 + 2a36 - 1, a32 - a33, a31 + 2a33 - 1, a28 + a29 + a30 - 1, a23 - a24, a22 + 2a24 - 1, a17 - a18, a16 + 2a18 - 1, a14 - a15, a13 + 2a15 - 1, a8 - a9, a7 + 2a9 - 1, a18*a30 - a15*a33 - a9*a36 + a9*a39, 3a9*a30 + a9 - a24 - a33, a24*a29 + 2a24*a30 + a29*a33 - a30*a33 - a33, a18*a29 - a15*a33 + 2a9*a36 - 2a9*a39, a15*a29 - a15*a30 + a36 - a39, 3a9*a29 - 2a9 + 2a24 - a33, 3a15*a24 - 3a9*a36 + 3a9*a39 - a18, 3a9*a15 - a18" mac1221 = "a38 - a39, a37 + 2a39 - 1, a35 - a36, a34 + 2a36 - 1, a28 + a29 + a30 - 1, a26 - a27, a25 + 2a27 - 1, a20 - a21, a19 + 2a21 - 1, a14 - a15, a13 + 2a15 - 1, a11 - a12, a10 + 2a12 - 1, a5 - a6, a4 + 2a6 - 1, a15*a29 - a15*a30 + a36 - a39, a12*a29 - a12*a30 + 3a6*a36 - 3a6*a39, a6*a29 + 2a6*a30 - a6 + a21 - a27, 3a15*a21 - 3a15*a27 + 3a12*a30 - 3a6*a36 + 3a6*a39 - a12, 3a6*a15 - a12, a21*a29*a36 + 2a21*a30*a36 - a27*a29*a39 + a27*a30*a39 - a15*a27 + a12*a30 - a6*a36 - a21*a36 - a27*a36 + 2a21*a39" mac1222 = "a38 - a39, a37 + 2a39 - 1, a35 - a36, a34 + 2a36 - 1, a32 - a33, a31 + 2a33 - 1, a28 + a29 + a30 - 1, a26 - a27, a25 + 2a27 - 1, a23 - a24, a22 + 2a24 - 1, a20 - a21, a19 + 2a21 - 1, a17 - a18, a16 + 2a18 - 1, a14 - a15, a13 + 2a15 - 1, a11 - a12, a10 + 2a12 - 1, a8 - a9, a7 + 2a9 - 1, a5 - a6, a4 + 2a6 - 1, a2 - a3, a1 + 2a3 - 1, a18*a30 - a15*a33 - a9*a36 + a9*a39, 3a9*a30 + a9 - a24 - a33, a24*a29 + 2a24*a30 + a29*a33 - a30*a33 - a33, a18*a29 - a15*a33 + 2a9*a36 - 2a9*a39, a15*a29 - a15*a30 + a36 - a39, a12*a29 - a12*a30 + 3a6*a36 - 3a6*a39, 3a9*a29 - 2a9 + 2a24 - a33, a6*a29 + 2a6*a30 - a6 + a21 - a27, a3*a29 + 2a3*a30 - 3a6*a33, 3a15*a24 - 3a9*a36 + 3a9*a39 - a18, 3a6*a24 - 3a3*a30 + 3a6*a33 - a3, a18*a21 - a12*a24 - a18*a27 + a12*a33 + a3*a36 - a3*a39, 3a15*a21 - 3a15*a27 + 3a12*a30 - 3a6*a36 + 3a6*a39 - a12, 3a9*a21 - 3a9*a27 + 3a6*a33 - a3, a6*a18 - a12*a24 + a3*a36 - a3*a39, 3a9*a15 - a18, 3a6*a15 - a12, a3*a15 - a12*a24 + a3*a36 - a3*a39, a9*a12 - a12*a24 + a3*a36 - a3*a39, 3a6*a9 - a3, a21*a29*a36 + 2a21*a30*a36 - a27*a29*a39 + a27*a30*a39 - a15*a27 + a12*a30 - a6*a36 - a21*a36 - a27*a36 + 2a21*a39, 6a9*a27*a36 - 3a6*a33*a36 - 3a21*a33*a36 - 3a9*a27*a39 - 3a24*a27*a39 + 6a6*a33*a39 + a18*a27 - a12*a33 + a3*a36 - a3*a39" mac2111 = "a53 - a54, a52 + 2a54 - 1, a50 - a51, a49 + 2a51 - 1, a44 - a45, a43 + 2a45 - 1, a28 + a29 + a30 - 1" mac2112 = "a53 - a54, a52 + 2a54 - 1, a50 - a51, a49 + 2a51 - 1, a47 - a48, a46 + 2a48 - 1, a44 - a45, a43 + 2a45 - 1, a32 - a33, a31 + 2a33 - 1, a28 + a29 + a30 - 1, a23 - a24, a22 + 2a24 - 1, a8 - a9, a7 + 2a9 - 1, 3a9*a30 + a9 - a24 - a33, a24*a29 + 2a24*a30 + a29*a33 - a30*a33 - a33, 3a9*a29 - 2a9 + 2a24 - a33" mac2121_sub = "a5*a29 + 2a5*a30 - a5 + a20 - a26, 2a20*a29 a41 + a26*a29 a41 + 3a20*a29 a30*a41 - 3a20*a29*a30 a41 - 3a26*a29*a30 a41 - 2a20*a30 a41 + 2a26*a30 a41 - 3a20*a26*a29 a44 - 3a26 a29 a44 - 3a20*a26*a29*a30*a44 + 6a26 a29*a30*a44 + 6a20*a26*a30 a44 - 3a26 a30 a44 - 6a20 a29 a50 + 3a20*a26*a29 a50 - 15a20 a29*a30*a50 - 6a20*a26*a29*a30*a50 - 6a20 a30 a50 + 3a20*a26*a30 a50 + 3a20*a26*a29 a53 + 3a20*a26*a29*a30*a53 - 6a20*a26*a30 a53 - 4a20*a29 a41 - 2a26*a29 a41 - a20*a29*a30*a41 + a26*a29*a30*a41 + 5a20*a30 a41 + a26*a30 a41 + 3a20 a29*a44 + 6a20*a26*a29*a44 + 3a26 a29*a44 + 6a20 a30*a44 + 18a5*a26*a30*a44 - 6a20*a26*a30*a44 - 3a26 a30*a44 + 6a20*a26*a29*a50 - 9a5*a20*a30*a50 + 9a20 a30*a50 - 9a5*a26*a30*a50 + 12a20*a26*a30*a50 - 3a20 a29*a53 - 3a26 a29*a53 - 6a20 a30*a53 + 3a26 a30*a53 + 3a26*a29*a41 - 3a26*a30*a41 - 3a5 a44 + 3a5*a20*a44 - 3a5*a26*a44 - 6a26 a44 + 3a5 a50 - 6a5*a20*a50 + 3a20 a50 + 6a5*a26*a50 - 6a20*a26*a50 + 3a5*a20*a53 - 3a20 a53 - 3a5*a26*a53 + 6a20*a26*a53\n 3 3 2 2 2 3 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2" mac2211_sub = "a14*a29 - a14*a30 + a35 - a38, 3a29 a35*a38*a44 + 3a29*a30*a35*a38*a44 - 6a30 a35*a38*a44 + 3a29 a35*a38*a50 + 12a29*a30*a35*a38*a50 + 12a30 a35*a38*a50 - 6a29 a38 a50 + 3a29*a30*a38 a50 + 3a30 a38 a50 - 3a29 a35 a53 - 12a29*a30*a35 a53 - 12a30 a35 a53 - 3a29 a35*a38*a53 - 3a29*a30*a35*a38*a53 + 6a30 a35*a38*a53 - a29 a35*a56 - 3a29 a30*a35*a56 + 4a30 a35*a56 - 2a29 a38*a56 - 3a29 a30*a38*a56 + 3a29*a30 a38*a56 + 2a30 a38*a56 + 3a29*a35 a44 + 6a30*a35 a44 - 6a29*a35*a38*a44 - 3a30*a35*a38*a44 + 3a29*a38 a44 - 3a30*a38 a44 - 9a14*a30*a35*a50 - 9a14*a30*a38*a50 - 12a29*a35*a38*a50 - 6a30*a35*a38*a50 + 12a29*a38 a50 + 6a30*a38 a50 + 18a14*a30*a35*a53 + 3a29*a35 a53 + 6a30*a35 a53 - 9a30*a35*a38*a53 - 3a29*a38 a53 + 3a30*a38 a53 + a29 a35*a56 + a29*a30*a35*a56 - 2a30 a35*a56 + 2a29 a38*a56 - a29*a30*a38*a56 - a30 a38*a56 - 3a14*a35*a44 - 3a35 a44 + 3a14*a38*a44 + 9a35*a38*a44 - 6a38 a44 + 3a14 a50 + 6a14*a35*a50 - 6a14*a38*a50 + 3a35*a38*a50 - 3a38 a50 - 3a14 a53 - 3a14*a35*a53 - 6a35 a53 + 3a14*a38*a53 + 3a35*a38*a53 + 3a38 a53 - 2a29*a35*a56 - 4a30*a35*a56 + 2a29*a38*a56 + 4a30*a38*a56 + 2a35*a56 - 2a38*a56\n 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 2 3 3 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2" mac2212_sub = "a17*a30 - a14*a32 - a8*a35 + a8*a38, 3a8*a30 + a8 - a23 - a32, a23*a29 + 2a23*a30 + a29*a32 - a30*a32 - a32, a17*a29 - a14*a32 + 2a8*a35 - 2a8*a38, a14*a29 - a14*a30 + a35 - a38, 3a8*a29 - 2a8 + 2a23 - a32, 3a14*a23 - 3a8*a35 + 3a8*a38 - a17, 3a8*a14 - a17, 3a32*a38*a44 - 2a29*a38*a47 - a30*a38*a47 - 3a32*a38*a50 + 3a32*a35*a53 + 3a8*a38*a53 - 3a23*a38*a53 + a29*a32*a56 - a30*a32*a56 - a17*a44 + a14*a47 - a35*a47 + a38*a47 + a17*a50 - a17*a53 - a8*a56 + a23*a56, 3a8*a35*a44 - 3a32*a35*a44 - 3a8*a38*a44 + a29*a35*a47 + 2a30*a35*a47 + 3a8*a35*a50 - 3a23*a38*a50 + a29*a32*a56 - a30*a32*a56 + a17*a44 - a14*a47 - a35*a47 + a38*a47 - a8*a56 + a23*a56, 3a17*a32*a44 - 6a14*a32*a44*a47 + 3a32*a35*a44*a47 + 3a14*a30*a47 - a29*a35*a47 - 2a30*a35*a47 - 3a8*a17*a44*a50 - 3a17*a32*a44*a50 + 3a14*a32*a47*a50 - 3a8*a35*a47*a50 + 3a23*a38*a47*a50 + 3a8*a17*a50 - 3a17*a23*a44*a53 + 3a8*a35*a47*a53 - 3a8*a38*a47*a53 - 3a17*a23*a50*a53 + 6a8*a32*a44*a56 - a29*a32*a47*a56 + a30*a32*a47*a56 - 3a8 a50*a56 + 3a8*a23*a50*a56 - 3a8*a32*a50*a56 + 3a8 a53*a56 - 3a8*a23*a53*a56 + 3a8*a32*a53*a56 - a35*a47 + a38*a47 + a17*a47*a50 + a17*a47*a53 - 2a32*a47*a56, 9a8*a23*a38*a44*a50 - 9a8*a23*a38*a50 + 9a23*a32*a35*a44*a53 + 9a8*a23*a38*a44*a53 + 3a29*a32*a35*a47*a53 - 3a30*a32*a35*a47*a53 + 9a23 a38*a50*a53 + 9a23*a30*a32*a53*a56 + 3a29*a32 a53*a56 - 3a30*a32 a53*a56 - 3a17*a23*a44 - 3a23*a35*a44*a47 + 6a32*a35*a44*a47 - 3a29*a35*a47 - 3a30*a35*a47 + 3a17*a23*a44*a50 - 9a8*a35*a47*a50 + 3a8*a38*a47*a50 + 3a23*a38*a47*a50 - 3a17*a23*a44*a53 + 3a8*a35*a47*a53 - 3a32*a35*a47*a53 - 3a8*a38*a47*a53 - 3a23*a38*a47*a53 - 6a8*a23*a44*a56 - 3a23*a30*a47*a56 - 3a29*a32*a47*a56 + 3a30*a32*a47*a56 + 6a8*a23*a50*a56 - 3a23 a50*a56 - 3a8*a23*a53*a56 - 3a32 a53*a56 + a14*a47 + 2a35*a47 - a38*a47 - a17*a47*a50 + a17*a47*a53 + 2a8*a47*a56 + a32*a47*a56, 9a23*a32*a35*a44 + 9a23*a30*a35*a44*a47 + a29 a35*a47 + 4a29*a30*a35*a47 - 5a30 a35*a47 - 18a23*a32*a35*a44*a50 - 6a29*a32*a35*a47*a50 + 6a30*a32*a35*a47*a50 + 27a23*a30*a38*a47*a50 + 9a29*a32*a38*a47*a50 - 9a30*a32*a38*a47*a50 + 18a8*a23*a35*a50 - 9a8*a23*a38*a50 - 9a23 a38*a50 - 9a23 a35*a44*a53 + 9a23*a32*a35*a44*a53 + 9a8*a23*a38*a44*a53 + 9a23*a30*a35*a47*a53 + 6a29*a32*a35*a47*a53 - 6a30*a32*a35*a47*a53 - 9a23 a35*a50*a53 + 9a23 a38*a50*a53 + 9a23*a30*a32*a44*a56 + 3a29*a32 a44*a56 - 3a30*a32 a44*a56 + 9a23*a30 a47*a56 + a29 a32*a47*a56 + a29*a30*a32*a47*a56 - 2a30 a32*a47*a56 + 9a23 a30*a50*a56 - 27a23*a30*a32*a50*a56 - 9a29*a32 a50*a56 + 9a30*a32 a50*a56 - 9a23 a30*a53*a56 + 18a23*a30*a32*a53*a56 + 6a29*a32 a53*a56 - 6a30*a32 a53*a56 - 3a17*a23*a44 - 9a23*a35*a44*a47 - 3a32*a35*a44*a47 + 9a23*a38*a44*a47 - 3a29*a35*a47 + 3a29*a38*a47 - 3a30*a38*a47 + 6a17*a23*a44*a50 - 3a8*a35*a47*a50 - 9a23*a35*a47*a50 + 6a32*a35*a47*a50 + 6a8*a38*a47*a50 + 6a23*a38*a47*a50 - 9a32*a38*a47*a50 - 3a17*a23*a44*a53 + 3a8*a35*a47*a53 + 3a23*a35*a47*a53 - 6a32*a35*a47*a53 - 3a8*a38*a47*a53 - 3a23*a38*a47*a53 - 3a8*a23*a44*a56 + 3a23 a44*a56 - 3a32 a44*a56 - 12a23*a30*a47*a56 - 4a29*a32*a47*a56 + a30*a32*a47*a56 - 3a23*a32*a50*a56 + 9a32 a50*a56 - 3a8*a23*a53*a56 + 3a23 a53*a56 + 3a23*a32*a53*a56 - 6a32 a53*a56 + a14*a47 + 4a35*a47 - 4a38*a47 - 2a17*a47*a50 + a17*a47*a53 - a8*a47*a56 + a23*a47*a56 + 4a32*a47*a56, 3a14*a17 a44 - 6a14 a17*a44*a47 + 3a14*a17*a35*a44*a47 + 3a14 a47 - 3a14 a35*a47 - 3a14*a17 a44*a50 - 3a17 a38*a44*a50 + 3a14 a17*a47*a50 + 3a14*a17*a38*a47*a50 + 3a17 a38*a50 - 3a17 a35*a44*a53 + 3a14*a17*a35*a47*a53 - 3a17 a35*a50*a53 + 3a8*a17*a35*a50*a56 - 3a8*a17*a38*a50*a56 - 3a8*a17*a35*a53*a56 + 3a8*a17*a38*a53*a56 + 2a17 a44*a56 - 2a14*a17*a47*a56 + a17*a35*a47*a56 - a17*a38*a47*a56 - a17 a50*a56 + a17 a53*a56, 3a29 a35*a38*a44 + 3a29*a30*a35*a38*a44 - 6a30 a35*a38*a44 + 3a29 a35*a38*a50 + 12a29*a30*a35*a38*a50 + 12a30 a35*a38*a50 - 6a29 a38 a50 + 3a29*a30*a38 a50 + 3a30 a38 a50 - 3a29 a35 a53 - 12a29*a30*a35 a53 - 12a30 a35 a53 - 3a29 a35*a38*a53 - 3a29*a30*a35*a38*a53 + 6a30 a35*a38*a53 - a29 a35*a56 - 3a29 a30*a35*a56 + 4a30 a35*a56 - 2a29 a38*a56 - 3a29 a30*a38*a56 + 3a29*a30 a38*a56 + 2a30 a38*a56 + 3a29*a35 a44 + 6a30*a35 a44 - 6a29*a35*a38*a44 - 3a30*a35*a38*a44 + 3a29*a38 a44 - 3a30*a38 a44 - 9a14*a30*a35*a50 - 9a14*a30*a38*a50 - 12a29*a35*a38*a50 - 6a30*a35*a38*a50 + 12a29*a38 a50 + 6a30*a38 a50 + 18a14*a30*a35*a53 + 3a29*a35 a53 + 6a30*a35 a53 - 9a30*a35*a38*a53 - 3a29*a38 a53 + 3a30*a38 a53 + a29 a35*a56 + a29*a30*a35*a56 - 2a30 a35*a56 + 2a29 a38*a56 - a29*a30*a38*a56 - a30 a38*a56 - 3a14*a35*a44 - 3a35 a44 + 3a14*a38*a44 + 9a35*a38*a44 - 6a38 a44 + 3a14 a50 + 6a14*a35*a50 - 6a14*a38*a50 + 3a35*a38*a50 - 3a38 a50 - 3a14 a53 - 3a14*a35*a53 - 6a35 a53 + 3a14*a38*a53 + 3a35*a38*a53 + 3a38 a53 - 2a29*a35*a56 - 4a30*a35*a56 + 2a29*a38*a56 + 4a30*a38*a56 + 2a35*a56 - 2a38*a56\n 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 2 3 3 2 2 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2" mac2122_inc = "3a8*a30 + a8 - a23 - a32, a23*a29 + 2a23*a30 + a29*a32 - a30*a32 - a32, 3a8*a29 - 2a8 + 2a23 - a32, a5*a29 + 2a5*a30 - a5 + a20 - a26, a2*a29 + 2a2*a30 - 3a5*a32, 3a5*a23 - 3a2*a30 + 3a5*a32 - a2, 3a8*a20 - 3a8*a26 + 3a5*a32 - a2, 3a5*a8 - a2 " mac2221_inc = "a14*a29 - a14*a30 + a35 - a38, a11*a29 - a11*a30 + 3a5*a35 - 3a5*a38, a5*a29 + 2a5*a30 - a5 + a20 - a26, 3a14*a20 - 3a14*a26 + 3a11*a30 - 3a5*a35 + 3a5*a38 - a11, 3a5*a14 - a11, a20*a29*a35 + 2a20*a30*a35 - a26*a29*a38 + a26*a30*a38 - a14*a26 + a11*a30 - a5*a35 - a20*a35 - a26*a35 + 2a20*a38" mac2222_inc = "a17*a30 - a14*a32 - a8*a35 + a8*a38, 3a8*a30 + a8 - a23 - a32, a23*a29 + 2a23*a30 + a29*a32 - a30*a32 - a32, a17*a29 - a14*a32 + 2a8*a35 - 2a8*a38, a14*a29 - a14*a30 + a35 - a38, a11*a29 - a11*a30 + 3a5*a35 - 3a5*a38, 3a8*a29 - 2a8 + 2a23 - a32, a5*a29 + 2a5*a30 - a5 + a20 - a26, a2*a29 + 2a2*a30 - 3a5*a32, 3a14*a23 - 3a8*a35 + 3a8*a38 - a17, 3a5*a23 - 3a2*a30 + 3a5*a32 - a2, a17*a20 - a11*a23 - a17*a26 + a11*a32 + a2*a35 - a2*a38, 3a14*a20 - 3a14*a26 + 3a11*a30 - 3a5*a35 + 3a5*a38 - a11, 3a8*a20 - 3a8*a26 + 3a5*a32 - a2, a5*a17 - a11*a23 + a2*a35 - a2*a38, 3a8*a14 - a17, 3a5*a14 - a11, a2*a14 - a11*a23 + a2*a35 - a2*a38, a8*a11 - a11*a23 + a2*a35 - a2*a38, 3a5*a8 - a2, a20*a29*a35 + 2a20*a30*a35 - a26*a29*a38 + a26*a30*a38 - a14*a26 + a11*a30 - a5*a35 - a20*a35 - a26*a35 + 2a20*a38, 6a8*a26*a35 - 3a5*a32*a35 - 3a20*a32*a35 - 3a8*a26*a38 - 3a23*a26*a38 + 6a5*a32*a38 + a17*a26 - a11*a32 + a2*a35 - a2*a38" latex1112 = macaulay_latex(mac1112, false) latex1121 = macaulay_latex(mac1121, false) latex1122 = macaulay_latex(mac1122, false) latex1211 = macaulay_latex(mac1211, false) latex1212 = macaulay_latex(mac1212, false) latex1221 = macaulay_latex(mac1221, false) latex1222 = macaulay_latex(mac1222, false) latex2111 = macaulay_latex(mac2111, false) latex2112 = macaulay_latex(mac2112, false) latex2121_sub = macaulay_latex(mac2121_sub, true) latex2211_sub = macaulay_latex(mac2211_sub, true) latex2212_sub = macaulay_latex(mac2212_sub, true) latex2122_inc = macaulay_latex(mac2122_inc, false) latex2221_inc = macaulay_latex(mac2221_inc, false) latex2222_inc = macaulay_latex(mac2222_inc, false) println("2122") println(latex_julia(latex2122_inc)) println("2221") println(latex_julia(latex2221_inc)) println("2222") println(latex_julia(latex2222_inc)) """ #a28 + a29 + a30 - 1, a26 - a27, a25 + 2a27 - 1, a20 - a21, a19 + 2a21 - 1, a5 - a6, a4 + 2a6 - 1 a1111 = ["a28", "a29", "a30"] mac1121_sub = "a6*a29 + 2a6*a30 - a6 + a21 - a27" mac1112_sub = "3a9*a30 + a9 - a24 - a33, a24*a29 + 2a24*a30 + a29*a33 - a30*a33 - a33, 3a9*a29 - 2a9 + 2a24 - a33" a2122_inc = unique_cf(mac2122_inc, false, a1111) inv2122_inc = add_missing_inv(a2122_inc, a1111) println("a2122_inc") println(latex_julia(macaulay_latex(arr_sep(inv2122_inc), false))) a2221_inc = unique_cf(mac2221_inc, false, a1111) inv2221_inc = add_missing_inv(a2221_inc, a1111) println("a2221_inc") println(latex_julia(macaulay_latex(arr_sep(inv2221_inc), false))) a2222_inc = unique_cf(mac2222_inc, false, a1111) inv2222_inc = add_missing_inv(a2222_inc, a1111) println("a2222_inc") println(latex_julia(macaulay_latex(arr_sep(inv2222_inc), false))) println("-----------------------") println(latex_julia(macaulay_latex(arr_sep(inv2122_inc), false))) println(latex_julia(macaulay_latex(arr_sep(inv2221_inc), false))) println(latex_julia(macaulay_latex(arr_sep(inv2222_inc), false))) """ end """ add missing invariants of sub networks compared with complete networks input: a: an array of concordance factors (the length should be divisible by 3) there should be no duplicates if split into groups of 3, the first should be the major split, the rest is the minor split eg. ["a37", "a38", "a39"] -> ["a37 + 2a39 - 1", "a38 - a39"] a1111: the triplet of ordered concordance factors derived from n(1, 1, 1, 1) eg. ["a37", "a38", "a39"] -> ["a37 + a38 + a39 - 1"] eg add_missing_inv(["a4", "a5", "a6", "a28", "a29", "a30", "a19", "a20", "a21", "a25", "a26", "a27"], ["a28", "a29", "a30"]) -> ["a28 + a29 + a30 - 1, a26 - a27, a25 + 2a27 - 1, a20 - a21, a19 + 2a21 - 1, a5 - a6, a4 + 2a6 - 1"] output: an array of all missing invariants """ function add_missing_inv(a, a1111) n = length(a) #length of unique concordance factor rst = [] for i in 1:Int(length(a)/3) #iterate every triplet of cf if a[i*3] in a1111 #if the triplet is from n(1111) push!(rst, a[i*3-2]*" + "*a[i*3-1]*" + "*a[i*3]*" - 1") #the sum should be 1 else push!(rst, a[i*3-2]*" + 2"*a[i*3]*" - 1") #the sum should add up to 1 push!(rst, a[i*3-1]*" - "*a[i*3]) #the last two minor splits should be the same end end return rst end """ input: str: strings of the macaulay version invariants before the newline is the invariants without exponent, after the newline is the string of exponent, the position is the same in invariants ASSUME the invariants only contain one element from the triplet exp: true if there is exponent a1111: the triplet of ordered concordance factors derived from n(1, 1, 1, 1) eg unique_cf("a6*a29 + 2a6*a30 - a6 + a21 - a27", false, ["a28", "a29", "a30"]) -> ["a4", "a5", "a6", "a28", "a29", "a30", "a19", "a20", "a21", "a25", "a26", "a27"] BUG: "a23 + a2" will return an error, "a23 + a2 " "a3 + a23" will not return an error output: array of strings, all triplet cf from the string """ function unique_cf(str, exp, a1111) if exp temp = split(str, "\n") str = temp[1] #storing invariants exp = temp[2] #storing exponents end if str[1] != 'a' #if there is a constant before `a` temp = split(str, "a")[2:end] #skip it else temp = split(str, "a") #split the element on "a" end ret = [] #find out all the unique a from the input for i in 1:length(temp) #iterate through every segment of the element after splitting if length(temp[i]) > 0 #skip the empty splitted segment a = "a"*rstrip(temp[i][1:2]) #the first two elements are all numbers, or one number and one non-numerical if temp[i][1:2][2] == '*' || temp[i][1:2][2] == ',' #remove the non-numerical characters a = a[1:2] end ind = findall(x->x==a, ret) #check if a has been added before if size(ind) == (0,) #add the newly found a push!(ret, a) end end end #generate the triplets of cf from the unique cf of the input ret_comp = [] flag = false #record if any cf from n(1111) has been accessed, avoid adding the same triplet multiple times for i in ret int = parse(Int64, i[2:end]) if ("a"*string(int) in a1111) && flag == false #if cf from n(1111) is accessed for the first time push!(ret_comp, a1111[1]) #add the triplet push!(ret_comp, a1111[2]) push!(ret_comp, a1111[3]) flag = true #update the flag elseif !("a"*string(int) in a1111) #if the current cf if not from n(1111) if int % 3 == 0 push!(ret_comp, "a"*string(int - 2)) push!(ret_comp, "a"*string(int - 1)) push!(ret_comp, "a"*string(int)) elseif int % 3 == 1 push!(ret_comp, "a"*string(int)) push!(ret_comp, "a"*string(int + 1)) push!(ret_comp, "a"*string(int + 2)) elseif int % 3 == 2 push!(ret_comp, "a"*string(int - 1)) push!(ret_comp, "a"*string(int)) push!(ret_comp, "a"*string(int + 1)) end end end return ret_comp end """ input: a list of invariants separated by comma (eg. "a22 + 2a24 - 1, a8 - a9, a7 + 2a9 - 1") output: returns arraylist of strings (eg. ["a22 + 2a24 - 1", "a8 - a9", "a7 + 2a9 - 1"]) """ function comma_sep(str) temp = split(str, ",") #split the string on comma ret = [] #storing return value for ele in temp #iterate through each element if length(ele) > 0 #neglect the empty element push!(ret, strip(ele, [' '])) #remove the first tab end end return ret end """ input: returns arraylist of strings (eg. ["a22 + 2a24 - 1", "a8 - a9", "a7 + 2a9 - 1"]) output: a list of invariants separated by comma (eg. "a22 + 2a24 - 1, a8 - a9, a7 + 2a9 - 1") """ function arr_sep(arr) ans = "" for i in 1:(length(arr)-1) ans = ans*arr[i]*", " end return ans*arr[end] end """ input: invariants separated by comma (eg. "a32^2 - a33, a31 + 2a33^2*a45 - 1, a28 + a29 + a30 - 1, a23 - a24, a22 + 2a24 - 1") output: string (eg. "\\item \$ a_{32}^{2} - a_{33}\$ \\item \$ a_{31} + 2a_{33}^{2}*a_{45} - 1\$ \\item \$ a_{28} + a_{29} + a_{30} - 1\$ \\item \$ a_{23} - a_{24}\$ \\item \$ a_{22} + 2a_{24} - 1\$") """ function latex_add_item(str) temp = split(str, ",") #split the string on comma ret = [] #storing return value for ele in temp #iterate through each element if length(ele) > 0 #neglect the empty element push!(ret, "\\item \$\n"*ele*"\$\n") end end return join(ret) end """ input: str: strings of the macaulay version invariants before the newline is the invariants without exponent, after the newline is the string of exponent, the position is the same in invariants eg. macaulay_latex("a5*a29 + 2a5*a30 - a5 + a20 - a26, 2a20*a29 a41\n 3", true) exp: true if there is exponent output: strings of the latex version invariants eg. a_{5}*a_{29} + 2a_{5}*a_{30} - a_{5} + a_{20} - a_{26}, 2a_{20}*a_{29}^{3}*a_{41} """ function macaulay_latex(str, exp) if exp temp = split(str, "\n") str = temp[1] #storing invariants exp = temp[2] #storing exponents j = 0 #store index in str for i in 1:length(exp) j += 1 if exp[i] != ' ' && str[j] == ' ' && str[j+1] != 'a' str=str[1:j-1]*'^'*exp[i]*str[j+1:end] j+=1 elseif exp[i] != ' ' && str[j] == ' ' && str[j+1] == 'a' str=str[1:j-1]*'^'*exp[i]*'*'*str[j+1:end] j+=2 end end end temp = split(str, "a") #split the element on "a" #iterate through every segment of the element after splitting for i in 1:length(temp) #if temp[i] is not empty, #add "a_{}" around the index, add "{}" around the exponent #eg. "a32^2-a33" --> ["", "32^2-", "33"] --> ["", "a_{32}^{2}-", "a_{33}"] if length(temp[i]) > 0 #iterate though every character of the segment (temp[i][j]) for j in 1:length(temp[i]) #if the character is not a number and is the first occurance of non-number if !occursin(r"[0-9]", string(temp[i][j])) #add "}" in between the number and the non-number character temp[i] = temp[i][1:j-1]*"}"*temp[i][j:length(temp[i])] break #if the character is number and is the last character of the segment elseif occursin(r"[0-9]", string(temp[i][j])) && (j == length(temp[i])) temp[i] = temp[i][1:j]*"}" #add "}" to the end end end for j in 1:length(temp[i]) #handle the exponent if occursin(r"[\^]", string(temp[i][j])) if length(temp[i])> j+1 temp[i] = temp[i][1:j]*"{"*temp[i][j+1]*"}"*temp[i][j+2:length(temp[i])] else temp[i] = temp[i][1:j]*"{"*temp[i][j+1]*"}" end end end temp[i] = "a_{"*temp[i] #add "a_{" to the front end end return join(temp) end """ input: strings of the latex version invariants eg. "a_{32}^{2} - a_{33}, a_{31} + 2a_{33}^{2}*a_{45} - 1, a_{28} + a_{29} + a_{30} - 1, a_{23} - a_{24}, a_{22} + 2a_{24} - 1" output: strings of the macaulay version invariants eg. "a32^2 - a33, a31 + 2a33^2*a45 - 1, a28 + a29 + a30 - 1, a23 - a24, a22 + 2a24 - 1" """ function latex_macaulay(str) ret = replace(str, r"[{}_]" => "") return ret end """ input: strings of the latex version invariants eg. "a_{32}^{2} - a_{33}, a_{31} + 2a_{33}^{2}*a_{45} - 1, a_{28} + a_{29} + a_{30} - 1, a_{23} - a_{24}, a_{22} + 2a_{24} - 1" output: strings of the julia version invariants eg. "a[32]^2 - a[33], a[31] + 2a[33]^2*a[45] - 1, a[28] + a[29] + a[30] - 1, a[23] - a[24], a[22] + 2a[24] - 1" BUG: 3a8*a30 + a8 - a23 - a32 wrong output """ function latex_julia(str) ret = [] temp = replace(str, "{" => "[") temp = replace(temp, "}" => "]") temp = replace(temp, "_" => "") temp = split(temp, "^") for i in 1:length(temp) if length(temp[i]) > 0 if length(temp[i]) > 3 if temp[i][1] == '[' && temp[i][3] == ']' && temp[i][4] == 'a' temp[i] = "^"*temp[i][2]*"*"*temp[i][4:length(temp[i])] elseif temp[i][1] == '[' && temp[i][3] == ']' && temp[i][4] != 'a' temp[i] = "^"*temp[i][2]*temp[i][4:length(temp[i])] end else if temp[i][1] == '[' && temp[i][3] == ']' temp[i] = "^"*temp[i][2]*temp[i][4:length(temp[i])] end end end push!(ret, temp[i]) end return join(ret) end main()
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
134
module PhyloDiamond include("invariants.jl") include("mapping.jl") include("ntwk.jl") include("helper.jl") export phylo_diamond end
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
7948
""" input: t: array of taxa length(list_nw(["A", "B", "C", "D", "E", "F", "G", "H"])) ->2520 (N2222) length(list_nw(["A", "B", "C", "D", "E", "F", "G"])) ->2520 (N1222, N2122, N2212, N2221) length(list_nw(["A", "B", "C", "D", "E", "F"])) ->1080 (N1122, N1212, N1221, N2112, N2121, N2211) length(list_nw(["A", "B", "C", "D", "E"])) ->240 (N1112, N1121, N1211, N2111) output: the whole list of potential networks for those taxa """ function list_nw(t) #fill taxa array to length 8 with "na" if length(t) != 8 for i in 1:8-length(t) push!(t, "na") #use string "na" to avoid problems of NaN end end ret = Vector{Any}([]) #n0 for i in 1:7 for j in i+1:8 #if both items are NaN, skip #since n_i should be either 1 or 2 if t[i]=="na" && t[j]=="na" continue end #remove the two selected items: t[i], t[j] temp = deleteat!(deepcopy(t), i) t1 = Vector{Any}(deleteat!(deepcopy(temp), j-1)) #length 6 #n1 for a in 1:5 for b in a+1:6 if t1[a]=="na" && t1[b]=="na" continue end #remove the two selected items: t1[a], t1[b] temp = deleteat!(deepcopy(t1), a) t2 = Vector{Any}(deleteat!(deepcopy(temp), b-1)) #length 4 #n2 for c in 1:3 for d in c+1:4 if t2[c]=="na" && t2[d]=="na" continue end #n3 #remove the two selected items: t2[c], t2[d] temp = deleteat!(deepcopy(t2), c) t3 = Vector{Any}(deleteat!(deepcopy(temp), d-1)) #length 2 if !(t3[1]=="na" && t3[2]=="na") push!(ret, Vector{Any}([ [t[i], t[j]], [t1[a], t1[b]], [t2[c], t2[d]], [t3[1], t3[2]] ])) end end end end end end end ret = Vector{Vector{Vector{Any}}}(unique!(ret)) #remove duplicated items (6 or 5 taxa) return ret end """ input: two N output: true if the two networks are the same; false, otherwise compare_nw([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8")], [("1", "2"), ("3", "4"), ("5", "6"), ("7", "9")]) -> false compare_nw([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8")], [("1", "2"), ("3", "4"), ("5", "6"), ("8", "7")]) -> true """ function compare_nw(N1, N2) for i in 1:4 for j in 1:2 if !(N1[i][j] in N2[i]) return false end end end return true end """ input: array of tuples, individuals from each triangles of the network output: a string of the input, mainly for saving N_to_str([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8", "9")]) -> "[(1,2),(3,4),(5,6),(7,8,9)]" """ function N_to_str(N) ret = "[" for n in N ret=ret*"(" for j in n if j != "na" ret=string(ret, j*",") end end ret=ret[1:end-1]*")," end return ret[1:end-1]*"]" end """ input: array of tuples, individuals from each triangles of the network output: the parenthetical network format based on the wiki rules (default branch length and inheritance probability) N_to_network([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8")]) -> "((7:1,8:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" """ function N_to_network(N) rst = [] for i_taxon in 1:length(N) str = "" for species in N[i_taxon] if species != "na" if N[i_taxon][end] != "na" && N[i_taxon][end] == species str = str*species*":1" elseif N[i_taxon][end] == "na" && N[i_taxon][end-1] == species str = str*species*":1" else str = str*species*":1," end end end push!(rst, str) end return "((" * rst[4] *"):4, (((" * rst[2] * "):2, ((" * rst[1] * "):1)#H1:1::0.7):1, (#H1:1::0.3,(" * rst[3] * "):2):1):1);" end """ input: array of tuples, individuals from each triangles of the network output: an array of each species, ignoring na N_to_t([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8")]) -> [ "1", "2", "3", "4", "5", "6", "7", "8"] """ function N_to_t(N) t = [] for i_taxon in 1:length(N) for species in N[i_taxon] if species != "na" push!(t, species) end end end return t end """ input: array of tuples, individuals from each triangles of the network output: N_num N_to_N_num([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8")]) -> "2222" """ function N_to_N_num(N) rst = "" for i_taxon in 1:length(N) cnt = 0 for species in N[i_taxon] if species != "na" cnt += 1 end end rst = rst*string(cnt) end return rst end """ input: cf table output: an array of distinct taxa names """ function cf_to_t(cf) t = unique!(cf[:,1]) t = vcat(t, unique!(cf[:,2]), unique!(cf[:,3]), unique!(cf[:,4])) return unique!(t) end """ input: the name of the file storing a list of gene trees output: the table of CF values """ function generate_cf_from_gene_trees(filename_genetrees) genetrees = readMultiTopology(filename_genetrees); q,t = countquartetsintrees(genetrees); df_wide = writeTableCF(q,t) df = df_wide[:,[:t1, :t2, :t3, :t4, :CF12_34, :CF13_24, :CF14_23]] return df end """ input: N: array of tuples, individuals from each triangles of the network sd: control the level of noise added to cf table (for simulation use) output: the table of CF values """ function generate_cf(N, sd=0) network = N_to_network(N) net = readTopology(network) #identifiable edges lengths were originally missing, so assigned default value of 1.0 quartets = PhyloNetworks.allQuartets(tipLabels(net), false) tx1 = [] tx2 = [] tx3 = [] tx4 = [] for q in quartets push!(tx1,q.taxon[1]) push!(tx2,q.taxon[2]) push!(tx3,q.taxon[3]) push!(tx4,q.taxon[4]) end df = DataFrame(tx1=tx1, tx2=tx2, tx3=tx3, tx4=tx4, obsCF1=ones(length(tx1)), obsCF2=zeros(length(tx1)), obsCF3=zeros(length(tx1))) cf = readTableCF!(df) ## We need to optimize the pseudolikelihood on the network for those dummy observed CF in order to compute the expected CFs topologyQPseudolik!(net, cf) df_wide = fittedQuartetCF(cf) ## "true" concordance factors: cf = df_wide[:,[:tx1, :tx2, :tx3, :tx4, :expCF12, :expCF13, :expCF14]] ## adding noise to cf table noise = rand(Normal(0, sd), nrow(cf)) for i in 1:nrow(cf) ind = randperm(3) if cf[i, ind[1]+4]+noise[i]<1 && cf[i, ind[1]+4]+noise[i]>0 if cf[i, ind[2]+4]-noise[i]/2<1 && cf[i, ind[2]+4]-noise[i]/2>0 if cf[i, ind[3]+4]-noise[i]/2<1 && cf[i, ind[3]+4]-noise[i]/2>0 cf[i, ind[1]+4] = cf[i, ind[1]+4]+noise[i] cf[i, ind[2]+4] = cf[i, ind[2]+4]-noise[i]/2 cf[i, ind[3]+4] = cf[i, ind[3]+4]-noise[i]/2 end end end end return cf end
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
22375
using LinearAlgebra """ input: a: an array of concordance factors output: an array of invariants """ function inv_net1112(a) length(a) == 57 || error("wrong dimension of a") return [a[32] - a[33], a[31] + 2a[33] - 1, a[28] + a[29] + a[30] - 1, a[23] - a[24], a[22] + 2a[24] - 1, a[8] - a[9], a[7] + 2a[9] - 1, 3a[9]*a[30] + a[9] - a[24] - a[33], a[24]*a[29] + 2a[24]*a[30] + a[29]*a[33] - a[30]*a[33] - a[33], 3a[9]*a[29] - 2a[9] + 2a[24] - a[33]] end function inv_net1121(a) length(a) == 57 || error("wrong dimension of a") return [a[28] + a[29] + a[30] - 1, a[26] - a[27], a[25] + 2a[27] - 1, a[20] - a[21], a[19] + 2a[21] - 1, a[5] - a[6], a[4] + 2a[6] - 1, a[6]*a[29] + 2a[6]*a[30] - a[6] + a[21] - a[27]] end function inv_net1211(a) length(a) == 57 || error("wrong dimension of a") return [a[38] - a[39], a[37] + 2a[39] - 1, a[35] - a[36], a[34] + 2a[36] - 1, a[28] + a[29] + a[30] - 1, a[14] - a[15], a[13] + 2a[15] - 1, a[15]*a[29] - a[15]*a[30] + a[36] - a[39]] end function inv_net2111(a) length(a) == 57 || error("wrong dimension of a") return [a[53] - a[54], a[52] + 2a[54] - 1, a[50] - a[51], a[49] + 2a[51] - 1, a[44] - a[45], a[43] + 2a[45] - 1, a[28] + a[29] + a[30] - 1] end function inv_net1122(a) length(a) == 57 || error("wrong dimension of a") return [a[32] - a[33], a[31] + 2a[33] - 1, a[28] + a[29] + a[30] - 1, a[26] - a[27], a[25] + 2a[27] - 1, a[23] - a[24], a[22] + 2a[24] - 1, a[20] - a[21], a[19] + 2a[21] - 1, a[8] - a[9], a[7] + 2a[9] - 1, a[5] - a[6], a[4] + 2a[6] - 1, a[2] - a[3], a[1] + 2a[3] - 1, 3a[9]*a[30] + a[9] - a[24] - a[33], a[24]*a[29] + 2a[24]*a[30] + a[29]*a[33] - a[30]*a[33] - a[33], 3a[9]*a[29] - 2a[9] + 2a[24] - a[33], a[6]*a[29] + 2a[6]*a[30] - a[6] + a[21] - a[27], a[3]*a[29] + 2a[3]*a[30] - 3a[6]*a[33], 3a[6]*a[24] - 3a[3]*a[30] + 3a[6]*a[33] - a[3], 3a[9]*a[21] - 3a[9]*a[27] + 3a[6]*a[33] - a[3], 3a[6]*a[9] - a[3]] end function inv_net1212(a) length(a) == 57 || error("wrong dimension of a") return [a[38] - a[39], a[37] + 2a[39] - 1, a[35] - a[36], a[34] + 2a[36] - 1, a[32] - a[33], a[31] + 2a[33] - 1, a[28] + a[29] + a[30] - 1, a[23] - a[24], a[22] + 2a[24] - 1, a[17] - a[18], a[16] + 2a[18] - 1, a[14] - a[15], a[13] + 2a[15] - 1, a[8] - a[9], a[7] + 2a[9] - 1, a[18]*a[30] - a[15]*a[33] - a[9]*a[36] + a[9]*a[39], 3a[9]*a[30] + a[9] - a[24] - a[33], a[24]*a[29] + 2a[24]*a[30] + a[29]*a[33] - a[30]*a[33] - a[33], a[18]*a[29] - a[15]*a[33] + 2a[9]*a[36] - 2a[9]*a[39], a[15]*a[29] - a[15]*a[30] + a[36] - a[39], 3a[9]*a[29] - 2a[9] + 2a[24] - a[33], 3a[15]*a[24] - 3a[9]*a[36] + 3a[9]*a[39] - a[18], 3a[9]*a[15] - a[18]] end function inv_net2112(a) length(a) == 57 || error("wrong dimension of a") return [a[53] - a[54], a[52] + 2a[54] - 1, a[50] - a[51], a[49] + 2a[51] - 1, a[47] - a[48], a[46] + 2a[48] - 1, a[44] - a[45], a[43] + 2a[45] - 1, a[32] - a[33], a[31] + 2a[33] - 1, a[28] + a[29] + a[30] - 1, a[23] - a[24], a[22] + 2a[24] - 1, a[8] - a[9], a[7] + 2a[9] - 1, 3a[9]*a[30] + a[9] - a[24] - a[33], a[24]*a[29] + 2a[24]*a[30] + a[29]*a[33] - a[30]*a[33] - a[33], 3a[9]*a[29] - 2a[9] + 2a[24] - a[33]] end function inv_net2211(a) length(a) == 57 || error("wrong dimension of a") return [a[13] + 2a[15] - 1, a[14] - a[15], a[28] + a[29] + a[30] - 1, a[34] + 2a[36] - 1, a[35] - a[36], a[37] + 2a[39] - 1, a[38] - a[39], a[43] + 2a[45] - 1, a[44] - a[45], a[49] + 2a[51] - 1, a[50] - a[51], a[52] + 2a[54] - 1, a[53] - a[54], a[55] + 2a[57] - 1, a[56] - a[57], a[14]*a[29] - a[14]*a[30] + a[35] - a[38], 3a[29]^2*a[35]*a[38]*a[44] + 3a[29]*a[30]*a[35]*a[38]*a[44] - 6a[30]^2*a[35]*a[38]*a[44] + 3a[29]^2*a[35]*a[38]*a[50] + 12a[29]*a[30]*a[35]*a[38]*a[50] + 12a[30]^2*a[35]*a[38]*a[50] - 6a[29]^2*a[38]^2*a[50] + 3a[29]*a[30]*a[38]^2*a[50] + 3a[30]^2*a[38]^2*a[50] - 3a[29]^2*a[35]^2*a[53] - 12a[29]*a[30]*a[35]^2*a[53] - 12a[30]^2*a[35]^2*a[53] - 3a[29]^2*a[35]*a[38]*a[53] - 3a[29]*a[30]*a[35]*a[38]*a[53] + 6a[30]^2*a[35]*a[38]*a[53] - a[29]^3*a[35]*a[56] - 3a[29]^2*a[30]*a[35]*a[56] + 4a[30]^3*a[35]*a[56] - 2a[29]^3*a[38]*a[56] - 3a[29]^2*a[30]*a[38]*a[56] + 3a[29]*a[30]^2*a[38]*a[56] + 2a[30]^3*a[38]*a[56] + 3a[29]*a[35]^2*a[44] + 6a[30]*a[35]^2*a[44] - 6a[29]*a[35]*a[38]*a[44] - 3a[30]*a[35]*a[38]*a[44] + 3a[29]*a[38]^2*a[44] - 3a[30]*a[38]^2*a[44] - 9a[14]*a[30]*a[35]*a[50] - 9a[14]*a[30]*a[38]*a[50] - 12a[29]*a[35]*a[38]*a[50] - 6a[30]*a[35]*a[38]*a[50] + 12a[29]*a[38]^2*a[50] + 6a[30]*a[38]^2*a[50] + 18a[14]*a[30]*a[35]*a[53] + 3a[29]*a[35]^2*a[53] + 6a[30]*a[35]^2*a[53] - 9a[30]*a[35]*a[38]*a[53] - 3a[29]*a[38]^2*a[53] + 3a[30]*a[38]^2*a[53] + a[29]^2*a[35]*a[56] + a[29]*a[30]*a[35]*a[56] - 2a[30]^2*a[35]*a[56] + 2a[29]^2*a[38]*a[56] - a[29]*a[30]*a[38]*a[56] - a[30]^2*a[38]*a[56] - 3a[14]*a[35]*a[44] - 3a[35]^2*a[44] + 3a[14]*a[38]*a[44] + 9a[35]*a[38]*a[44] - 6a[38]^2*a[44] + 3a[14]^2*a[50] + 6a[14]*a[35]*a[50] - 6a[14]*a[38]*a[50] + 3a[35]*a[38]*a[50] - 3a[38]^2*a[50] - 3a[14]^2*a[53] - 3a[14]*a[35]*a[53] - 6a[35]^2*a[53] + 3a[14]*a[38]*a[53] + 3a[35]*a[38]*a[53] + 3a[38]^2*a[53] - 2a[29]*a[35]*a[56] - 4a[30]*a[35]*a[56] + 2a[29]*a[38]*a[56] + 4a[30]*a[38]*a[56] + 2a[35]*a[56] - 2a[38]*a[56]] end function inv_net2121(a) length(a) == 57 || error("wrong dimension of a") return [a[4] + 2a[6] - 1, a[5] - a[6], a[28] + a[29] + a[30] - 1, a[19] + 2a[21] - 1, a[20] - a[21], a[25] + 2a[27] - 1, a[26] - a[27], a[40] + 2a[42] - 1, a[41] - a[42], a[43] + 2a[45] - 1, a[44] - a[45], a[49] + 2a[51] - 1, a[50] - a[51], a[52] + 2a[54] - 1, a[53] - a[54], a[5]*a[29] + 2a[5]*a[30] - a[5] + a[20] - a[26], 2a[20]*a[29]^3*a[41] + a[26]*a[29]^3*a[41] + 3a[20]*a[29]^2*a[30]*a[41] - 3a[20]*a[29]*a[30]^2*a[41] - 3a[26]*a[29]*a[30]^2*a[41] - 2a[20]*a[30]^3*a[41] + 2a[26]*a[30]^3*a[41] - 3a[20]*a[26]*a[29]^2*a[44] - 3a[26]^2*a[29]^2*a[44] - 3a[20]*a[26]*a[29]*a[30]*a[44] + 6a[26]^2*a[29]*a[30]*a[44] + 6a[20]*a[26]*a[30]^2*a[44] - 3a[26]^2*a[30]^2*a[44] - 6a[20]^2*a[29]^2*a[50] + 3a[20]*a[26]*a[29]^2*a[50] - 15a[20]^2*a[29]*a[30]*a[50] - 6a[20]*a[26]*a[29]*a[30]*a[50] - 6a[20]^2*a[30]^2*a[50] + 3a[20]*a[26]*a[30]^2*a[50] + 3a[20]*a[26]*a[29]^2*a[53] + 3a[20]*a[26]*a[29]*a[30]*a[53] - 6a[20]*a[26]*a[30]^2*a[53] - 4a[20]*a[29]^2*a[41] - 2a[26]*a[29]^2*a[41] - a[20]*a[29]*a[30]*a[41] + a[26]*a[29]*a[30]*a[41] + 5a[20]*a[30]^2*a[41] + a[26]*a[30]^2*a[41] + 3a[20]^2*a[29]*a[44] + 6a[20]*a[26]*a[29]*a[44] + 3a[26]^2*a[29]*a[44] + 6a[20]^2*a[30]*a[44] + 18a[5]*a[26]*a[30]*a[44] - 6a[20]*a[26]*a[30]*a[44] - 3a[26]^2*a[30]*a[44] + 6a[20]*a[26]*a[29]*a[50] - 9a[5]*a[20]*a[30]*a[50] + 9a[20]^2*a[30]*a[50] - 9a[5]*a[26]*a[30]*a[50] + 12a[20]*a[26]*a[30]*a[50] - 3a[20]^2*a[29]*a[53] - 3a[26]^2*a[29]*a[53] - 6a[20]^2*a[30]*a[53] + 3a[26]^2*a[30]*a[53] + 3a[26]*a[29]*a[41] - 3a[26]*a[30]*a[41] - 3a[5]^2*a[44] + 3a[5]*a[20]*a[44] - 3a[5]*a[26]*a[44] - 6a[26]^2*a[44] + 3a[5]^2*a[50] - 6a[5]*a[20]*a[50] + 3a[20]^2*a[50] + 6a[5]*a[26]*a[50] - 6a[20]*a[26]*a[50] + 3a[5]*a[20]*a[53] - 3a[20]^2*a[53] - 3a[5]*a[26]*a[53] + 6a[20]*a[26]*a[53]] end function inv_net1221(a) length(a) == 57 || error("wrong dimension of a") return [a[38] - a[39], a[37] + 2a[39] - 1, a[35] - a[36], a[34] + 2a[36] - 1, a[28] + a[29] + a[30] - 1, a[26] - a[27], a[25] + 2a[27] - 1, a[20] - a[21], a[19] + 2a[21] - 1, a[14] - a[15], a[13] + 2a[15] - 1, a[11] - a[12], a[10] + 2a[12] - 1, a[5] - a[6], a[4] + 2a[6] - 1, a[15]*a[29] - a[15]*a[30] + a[36] - a[39], a[12]*a[29] - a[12]*a[30] + 3a[6]*a[36] - 3a[6]*a[39], a[6]*a[29] + 2a[6]*a[30] - a[6] + a[21] - a[27], 3a[15]*a[21] - 3a[15]*a[27] + 3a[12]*a[30] - 3a[6]*a[36] + 3a[6]*a[39] - a[12], 3a[6]*a[15] - a[12], a[21]*a[29]*a[36] + 2a[21]*a[30]*a[36] - a[27]*a[29]*a[39] + a[27]*a[30]*a[39] - a[15]*a[27] + a[12]*a[30] - a[6]*a[36] - a[21]*a[36] - a[27]*a[36] + 2a[21]*a[39]] end function inv_net1222(a) length(a) == 57 || error("wrong dimension of a") return [a[38] - a[39], a[37] + 2a[39] - 1, a[35] - a[36], a[34] + 2a[36] - 1, a[32] - a[33], a[31] + 2a[33] - 1, a[28] + a[29] + a[30] - 1, a[26] - a[27], a[25] + 2a[27] - 1, a[23] - a[24], a[22] + 2a[24] - 1, a[20] - a[21], a[19] + 2a[21] - 1, a[17] - a[18], a[16] + 2a[18] - 1, a[14] - a[15], a[13] + 2a[15] - 1, a[11] - a[12], a[10] + 2a[12] - 1, a[8] - a[9], a[7] + 2a[9] - 1, a[5] - a[6], a[4] + 2a[6] - 1, a[2] - a[3], a[1] + 2a[3] - 1, a[18]*a[30] - a[15]*a[33] - a[9]*a[36] + a[9]*a[39], 3a[9]*a[30] + a[9] - a[24] - a[33], a[24]*a[29] + 2a[24]*a[30] + a[29]*a[33] - a[30]*a[33] - a[33], a[18]*a[29] - a[15]*a[33] + 2a[9]*a[36] - 2a[9]*a[39], a[15]*a[29] - a[15]*a[30] + a[36] - a[39], a[12]*a[29] - a[12]*a[30] + 3a[6]*a[36] - 3a[6]*a[39], 3a[9]*a[29] - 2a[9] + 2a[24] - a[33], a[6]*a[29] + 2a[6]*a[30] - a[6] + a[21] - a[27], a[3]*a[29] + 2a[3]*a[30] - 3a[6]*a[33], 3a[15]*a[24] - 3a[9]*a[36] + 3a[9]*a[39] - a[18], 3a[6]*a[24] - 3a[3]*a[30] + 3a[6]*a[33] - a[3], a[18]*a[21] - a[12]*a[24] - a[18]*a[27] + a[12]*a[33] + a[3]*a[36] - a[3]*a[39], 3a[15]*a[21] - 3a[15]*a[27] + 3a[12]*a[30] - 3a[6]*a[36] + 3a[6]*a[39] - a[12], 3a[9]*a[21] - 3a[9]*a[27] + 3a[6]*a[33] - a[3], a[6]*a[18] - a[12]*a[24] + a[3]*a[36] - a[3]*a[39], 3a[9]*a[15] - a[18], 3a[6]*a[15] - a[12], a[3]*a[15] - a[12]*a[24] + a[3]*a[36] - a[3]*a[39], a[9]*a[12] - a[12]*a[24] + a[3]*a[36] - a[3]*a[39], 3a[6]*a[9] - a[3], a[21]*a[29]*a[36] + 2a[21]*a[30]*a[36] - a[27]*a[29]*a[39] + a[27]*a[30]*a[39] - a[15]*a[27] + a[12]*a[30] - a[6]*a[36] - a[21]*a[36] - a[27]*a[36] + 2a[21]*a[39], 6a[9]*a[27]*a[36] - 3a[6]*a[33]*a[36] - 3a[21]*a[33]*a[36] - 3a[9]*a[27]*a[39] - 3a[24]*a[27]*a[39] + 6a[6]*a[33]*a[39] + a[18]*a[27] - a[12]*a[33] + a[3]*a[36] - a[3]*a[39]] end function inv_net2212(a) length(a) == 57 || error("wrong dimension of a") return [a[16] + 2a[18] - 1, a[17] - a[18], a[28] + a[29] + a[30] - 1, a[13] + 2a[15] - 1, a[14] - a[15], a[31] + 2a[33] - 1, a[32] - a[33], a[7] + 2a[9] - 1, a[8] - a[9], a[34] + 2a[36] - 1, a[35] - a[36], a[37] + 2a[39] - 1, a[38] - a[39], a[22] + 2a[24] - 1, a[23] - a[24], a[43] + 2a[45] - 1, a[44] - a[45], a[46] + 2a[48] - 1, a[47] - a[48], a[49] + 2a[51] - 1, a[50] - a[51], a[52] + 2a[54] - 1, a[53] - a[54], a[55] + 2a[57] - 1, a[56] - a[57], a[17]*a[30] - a[14]*a[32] - a[8]*a[35] + a[8]*a[38], 3a[8]*a[30] + a[8] - a[23] - a[32], a[23]*a[29] + 2a[23]*a[30] + a[29]*a[32] - a[30]*a[32] - a[32], a[17]*a[29] - a[14]*a[32] + 2a[8]*a[35] - 2a[8]*a[38], a[14]*a[29] - a[14]*a[30] + a[35] - a[38], 3a[8]*a[29] - 2a[8] + 2a[23] - a[32], 3a[14]*a[23] - 3a[8]*a[35] + 3a[8]*a[38] - a[17], 3a[8]*a[14] - a[17], 3a[32]*a[38]*a[44] - 2a[29]*a[38]*a[47] - a[30]*a[38]*a[47] - 3a[32]*a[38]*a[50] + 3a[32]*a[35]*a[53] + 3a[8]*a[38]*a[53] - 3a[23]*a[38]*a[53] + a[29]*a[32]*a[56] - a[30]*a[32]*a[56] - a[17]*a[44] + a[14]*a[47] - a[35]*a[47] + a[38]*a[47] + a[17]*a[50] - a[17]*a[53] - a[8]*a[56] + a[23]*a[56], 3a[8]*a[35]*a[44] - 3a[32]*a[35]*a[44] - 3a[8]*a[38]*a[44] + a[29]*a[35]*a[47] + 2a[30]*a[35]*a[47] + 3a[8]*a[35]*a[50] - 3a[23]*a[38]*a[50] + a[29]*a[32]*a[56] - a[30]*a[32]*a[56] + a[17]*a[44] - a[14]*a[47] - a[35]*a[47] + a[38]*a[47] - a[8]*a[56] + a[23]*a[56], 3a[17]*a[32]*a[44]^2 - 6a[14]*a[32]*a[44]*a[47] + 3a[32]*a[35]*a[44]*a[47] + 3a[14]*a[30]*a[47]^2 - a[29]*a[35]*a[47]^2 - 2a[30]*a[35]*a[47]^2 - 3a[8]*a[17]*a[44]*a[50] - 3a[17]*a[32]*a[44]*a[50] + 3a[14]*a[32]*a[47]*a[50] - 3a[8]*a[35]*a[47]*a[50] + 3a[23]*a[38]*a[47]*a[50] + 3a[8]*a[17]*a[50]^2 - 3a[17]*a[23]*a[44]*a[53] + 3a[8]*a[35]*a[47]*a[53] - 3a[8]*a[38]*a[47]*a[53] - 3a[17]*a[23]*a[50]*a[53] + 6a[8]*a[32]*a[44]*a[56] - a[29]*a[32]*a[47]*a[56] + a[30]*a[32]*a[47]*a[56] - 3a[8]^2*a[50]*a[56] + 3a[8]*a[23]*a[50]*a[56] - 3a[8]*a[32]*a[50]*a[56] + 3a[8]^2*a[53]*a[56] - 3a[8]*a[23]*a[53]*a[56] + 3a[8]*a[32]*a[53]*a[56] - a[35]*a[47]^2 + a[38]*a[47]^2 + a[17]*a[47]*a[50] + a[17]*a[47]*a[53] - 2a[32]*a[47]*a[56], 9a[8]*a[23]*a[38]*a[44]*a[50] - 9a[8]*a[23]*a[38]*a[50]^2 + 9a[23]*a[32]*a[35]*a[44]*a[53] + 9a[8]*a[23]*a[38]*a[44]*a[53] + 3a[29]*a[32]*a[35]*a[47]*a[53] - 3a[30]*a[32]*a[35]*a[47]*a[53] + 9a[23]^2*a[38]*a[50]*a[53] + 9a[23]*a[30]*a[32]*a[53]*a[56] + 3a[29]*a[32]^2*a[53]*a[56] - 3a[30]*a[32]^2*a[53]*a[56] - 3a[17]*a[23]*a[44]^2 - 3a[23]*a[35]*a[44]*a[47] + 6a[32]*a[35]*a[44]*a[47] - 3a[29]*a[35]*a[47]^2 - 3a[30]*a[35]*a[47]^2 + 3a[17]*a[23]*a[44]*a[50] - 9a[8]*a[35]*a[47]*a[50] + 3a[8]*a[38]*a[47]*a[50] + 3a[23]*a[38]*a[47]*a[50] - 3a[17]*a[23]*a[44]*a[53] + 3a[8]*a[35]*a[47]*a[53] - 3a[32]*a[35]*a[47]*a[53] - 3a[8]*a[38]*a[47]*a[53] - 3a[23]*a[38]*a[47]*a[53] - 6a[8]*a[23]*a[44]*a[56] - 3a[23]*a[30]*a[47]*a[56] - 3a[29]*a[32]*a[47]*a[56] + 3a[30]*a[32]*a[47]*a[56] + 6a[8]*a[23]*a[50]*a[56] - 3a[23]^2*a[50]*a[56] - 3a[8]*a[23]*a[53]*a[56] - 3a[32]^2*a[53]*a[56] + a[14]*a[47]^2 + 2a[35]*a[47]^2 - a[38]*a[47]^2 - a[17]*a[47]*a[50] + a[17]*a[47]*a[53] + 2a[8]*a[47]*a[56] + a[32]*a[47]*a[56], 9a[23]*a[32]*a[35]*a[44]^2 + 9a[23]*a[30]*a[35]*a[44]*a[47] + a[29]^2*a[35]*a[47]^2 + 4a[29]*a[30]*a[35]*a[47]^2 - 5a[30]^2*a[35]*a[47]^2 - 18a[23]*a[32]*a[35]*a[44]*a[50] - 6a[29]*a[32]*a[35]*a[47]*a[50] + 6a[30]*a[32]*a[35]*a[47]*a[50] + 27a[23]*a[30]*a[38]*a[47]*a[50] + 9a[29]*a[32]*a[38]*a[47]*a[50] - 9a[30]*a[32]*a[38]*a[47]*a[50] + 18a[8]*a[23]*a[35]*a[50]^2 - 9a[8]*a[23]*a[38]*a[50]^2 - 9a[23]^2*a[38]*a[50]^2 - 9a[23]^2*a[35]*a[44]*a[53] + 9a[23]*a[32]*a[35]*a[44]*a[53] + 9a[8]*a[23]*a[38]*a[44]*a[53] + 9a[23]*a[30]*a[35]*a[47]*a[53] + 6a[29]*a[32]*a[35]*a[47]*a[53] - 6a[30]*a[32]*a[35]*a[47]*a[53] - 9a[23]^2*a[35]*a[50]*a[53] + 9a[23]^2*a[38]*a[50]*a[53] + 9a[23]*a[30]*a[32]*a[44]*a[56] + 3a[29]*a[32]^2*a[44]*a[56] - 3a[30]*a[32]^2*a[44]*a[56] + 9a[23]*a[30]^2*a[47]*a[56] + a[29]^2*a[32]*a[47]*a[56] + a[29]*a[30]*a[32]*a[47]*a[56] - 2a[30]^2*a[32]*a[47]*a[56] + 9a[23]^2*a[30]*a[50]*a[56] - 27a[23]*a[30]*a[32]*a[50]*a[56] - 9a[29]*a[32]^2*a[50]*a[56] + 9a[30]*a[32]^2*a[50]*a[56] - 9a[23]^2*a[30]*a[53]*a[56] + 18a[23]*a[30]*a[32]*a[53]*a[56] + 6a[29]*a[32]^2*a[53]*a[56] - 6a[30]*a[32]^2*a[53]*a[56] - 3a[17]*a[23]*a[44]^2 - 9a[23]*a[35]*a[44]*a[47] - 3a[32]*a[35]*a[44]*a[47] + 9a[23]*a[38]*a[44]*a[47] - 3a[29]*a[35]*a[47]^2 + 3a[29]*a[38]*a[47]^2 - 3a[30]*a[38]*a[47]^2 + 6a[17]*a[23]*a[44]*a[50] - 3a[8]*a[35]*a[47]*a[50] - 9a[23]*a[35]*a[47]*a[50] + 6a[32]*a[35]*a[47]*a[50] + 6a[8]*a[38]*a[47]*a[50] + 6a[23]*a[38]*a[47]*a[50] - 9a[32]*a[38]*a[47]*a[50] - 3a[17]*a[23]*a[44]*a[53] + 3a[8]*a[35]*a[47]*a[53] + 3a[23]*a[35]*a[47]*a[53] - 6a[32]*a[35]*a[47]*a[53] - 3a[8]*a[38]*a[47]*a[53] - 3a[23]*a[38]*a[47]*a[53] - 3a[8]*a[23]*a[44]*a[56] + 3a[23]^2*a[44]*a[56] - 3a[32]^2*a[44]*a[56] - 12a[23]*a[30]*a[47]*a[56] - 4a[29]*a[32]*a[47]*a[56] + a[30]*a[32]*a[47]*a[56] - 3a[23]*a[32]*a[50]*a[56] + 9a[32]^2*a[50]*a[56] - 3a[8]*a[23]*a[53]*a[56] + 3a[23]^2*a[53]*a[56] + 3a[23]*a[32]*a[53]*a[56] - 6a[32]^2*a[53]*a[56] + a[14]*a[47]^2 + 4a[35]*a[47]^2 - 4a[38]*a[47]^2 - 2a[17]*a[47]*a[50] + a[17]*a[47]*a[53] - a[8]*a[47]*a[56] + a[23]*a[47]*a[56] + 4a[32]*a[47]*a[56], 3a[14]*a[17]^2*a[44]^2 - 6a[14]^2*a[17]*a[44]*a[47] + 3a[14]*a[17]*a[35]*a[44]*a[47] + 3a[14]^3*a[47]^2 - 3a[14]^2*a[35]*a[47]^2 - 3a[14]*a[17]^2*a[44]*a[50] - 3a[17]^2*a[38]*a[44]*a[50] + 3a[14]^2*a[17]*a[47]*a[50] + 3a[14]*a[17]*a[38]*a[47]*a[50] + 3a[17]^2*a[38]*a[50]^2 - 3a[17]^2*a[35]*a[44]*a[53] + 3a[14]*a[17]*a[35]*a[47]*a[53] - 3a[17]^2*a[35]*a[50]*a[53] + 3a[8]*a[17]*a[35]*a[50]*a[56] - 3a[8]*a[17]*a[38]*a[50]*a[56] - 3a[8]*a[17]*a[35]*a[53]*a[56] + 3a[8]*a[17]*a[38]*a[53]*a[56] + 2a[17]^2*a[44]*a[56] - 2a[14]*a[17]*a[47]*a[56] + a[17]*a[35]*a[47]*a[56] - a[17]*a[38]*a[47]*a[56] - a[17]^2*a[50]*a[56] + a[17]^2*a[53]*a[56], 3a[29]^2*a[35]*a[38]*a[44] + 3a[29]*a[30]*a[35]*a[38]*a[44] - 6a[30]^2*a[35]*a[38]*a[44] + 3a[29]^2*a[35]*a[38]*a[50] + 12a[29]*a[30]*a[35]*a[38]*a[50] + 12a[30]^2*a[35]*a[38]*a[50] - 6a[29]^2*a[38]^2*a[50] + 3a[29]*a[30]*a[38]^2*a[50] + 3a[30]^2*a[38]^2*a[50] - 3a[29]^2*a[35]^2*a[53] - 12a[29]*a[30]*a[35]^2*a[53] - 12a[30]^2*a[35]^2*a[53] - 3a[29]^2*a[35]*a[38]*a[53] - 3a[29]*a[30]*a[35]*a[38]*a[53] + 6a[30]^2*a[35]*a[38]*a[53] - a[29]^3*a[35]*a[56] - 3a[29]^2*a[30]*a[35]*a[56] + 4a[30]^3*a[35]*a[56] - 2a[29]^3*a[38]*a[56] - 3a[29]^2*a[30]*a[38]*a[56] + 3a[29]*a[30]^2*a[38]*a[56] + 2a[30]^3*a[38]*a[56] + 3a[29]*a[35]^2*a[44] + 6a[30]*a[35]^2*a[44] - 6a[29]*a[35]*a[38]*a[44] - 3a[30]*a[35]*a[38]*a[44] + 3a[29]*a[38]^2*a[44] - 3a[30]*a[38]^2*a[44] - 9a[14]*a[30]*a[35]*a[50] - 9a[14]*a[30]*a[38]*a[50] - 12a[29]*a[35]*a[38]*a[50] - 6a[30]*a[35]*a[38]*a[50] + 12a[29]*a[38]^2*a[50] + 6a[30]*a[38]^2*a[50] + 18a[14]*a[30]*a[35]*a[53] + 3a[29]*a[35]^2*a[53] + 6a[30]*a[35]^2*a[53] - 9a[30]*a[35]*a[38]*a[53] - 3a[29]*a[38]^2*a[53] + 3a[30]*a[38]^2*a[53] + a[29]^2*a[35]*a[56] + a[29]*a[30]*a[35]*a[56] - 2a[30]^2*a[35]*a[56] + 2a[29]^2*a[38]*a[56] - a[29]*a[30]*a[38]*a[56] - a[30]^2*a[38]*a[56] - 3a[14]*a[35]*a[44] - 3a[35]^2*a[44] + 3a[14]*a[38]*a[44] + 9a[35]*a[38]*a[44] - 6a[38]^2*a[44] + 3a[14]^2*a[50] + 6a[14]*a[35]*a[50] - 6a[14]*a[38]*a[50] + 3a[35]*a[38]*a[50] - 3a[38]^2*a[50] - 3a[14]^2*a[53] - 3a[14]*a[35]*a[53] - 6a[35]^2*a[53] + 3a[14]*a[38]*a[53] + 3a[35]*a[38]*a[53] + 3a[38]^2*a[53] - 2a[29]*a[35]*a[56] - 4a[30]*a[35]*a[56] + 2a[29]*a[38]*a[56] + 4a[30]*a[38]*a[56] + 2a[35]*a[56] - 2a[38]*a[56]] end function inv_net2122(a) length(a) == 57 || error("wrong dimension of a") return [a[7] + 2a[9] - 1, a[8] - a[9], a[28] + a[29] + a[30] - 1, a[22] + 2a[24] - 1, a[23] - a[24], a[31] + 2a[33] - 1, a[32] - a[33], a[4] + 2a[6] - 1, a[5] - a[6], a[19] + 2a[21] - 1, a[20] - a[21], a[25] + 2a[27] - 1, a[26] - a[27], a[1] + 2a[3] - 1, a[2] - a[3], 3a[8]*a[30] + a[8] - a[23] - a[32], a[23]*a[29] + 2a[23]*a[30] + a[29]*a[32] - a[30]*a[32] - a[32], 3a[8]*a[29] - 2a[8] + 2a[23] - a[32], a[5]*a[29] + 2a[5]*a[30] - a[5] + a[20] - a[26], a[2]*a[29] + 2a[2]*a[30] - 3a[5]*a[32], 3a[5]*a[23] - 3a[2]*a[30] + 3a[5]*a[32] - a[2], 3a[8]*a[20] - 3a[8]*a[26] + 3a[5]*a[32] - a[2], 3a[5]*a[8] - a[2]] end function inv_net2221(a) length(a) == 57 || error("wrong dimension of a") return [a[13] + 2a[15] - 1, a[14] - a[15], a[28] + a[29] + a[30] - 1, a[34] + 2a[36] - 1, a[35] - a[36], a[37] + 2a[39] - 1, a[38] - a[39], a[10] + 2a[12] - 1, a[11] - a[12], a[4] + 2a[6] - 1, a[5] - a[6], a[19] + 2a[21] - 1, a[20] - a[21], a[25] + 2a[27] - 1, a[26] - a[27], a[14]*a[29] - a[14]*a[30] + a[35] - a[38], a[11]*a[29] - a[11]*a[30] + 3a[5]*a[35] - 3a[5]*a[38], a[5]*a[29] + 2a[5]*a[30] - a[5] + a[20] - a[26], 3a[14]*a[20] - 3a[14]*a[26] + 3a[11]*a[30] - 3a[5]*a[35] + 3a[5]*a[38] - a[11], 3a[5]*a[14] - a[11], a[20]*a[29]*a[35] + 2a[20]*a[30]*a[35] - a[26]*a[29]*a[38] + a[26]*a[30]*a[38] - a[14]*a[26] + a[11]*a[30] - a[5]*a[35] - a[20]*a[35] - a[26]*a[35] + 2a[20]*a[38]] end function inv_net2222(a) length(a) == 57 || error("wrong dimension of a") return [a[16] + 2a[18] - 1, a[17] - a[18], a[28] + a[29] + a[30] - 1, a[13] + 2a[15] - 1, a[14] - a[15], a[31] + 2a[33] - 1, a[32] - a[33], a[7] + 2a[9] - 1, a[8] - a[9], a[34] + 2a[36] - 1, a[35] - a[36], a[37] + 2a[39] - 1, a[38] - a[39], a[22] + 2a[24] - 1, a[23] - a[24], a[10] + 2a[12] - 1, a[11] - a[12], a[4] + 2a[6] - 1, a[5] - a[6], a[19] + 2a[21] - 1, a[20] - a[21], a[25] + 2a[27] - 1, a[26] - a[27], a[1] + 2a[3] - 1, a[2] - a[3], a[17]*a[30] - a[14]*a[32] - a[8]*a[35] + a[8]*a[38], 3a[8]*a[30] + a[8] - a[23] - a[32], a[23]*a[29] + 2a[23]*a[30] + a[29]*a[32] - a[30]*a[32] - a[32], a[17]*a[29] - a[14]*a[32] + 2a[8]*a[35] - 2a[8]*a[38], a[14]*a[29] - a[14]*a[30] + a[35] - a[38], a[11]*a[29] - a[11]*a[30] + 3a[5]*a[35] - 3a[5]*a[38], 3a[8]*a[29] - 2a[8] + 2a[23] - a[32], a[5]*a[29] + 2a[5]*a[30] - a[5] + a[20] - a[26], a[2]*a[29] + 2a[2]*a[30] - 3a[5]*a[32], 3a[14]*a[23] - 3a[8]*a[35] + 3a[8]*a[38] - a[17], 3a[5]*a[23] - 3a[2]*a[30] + 3a[5]*a[32] - a[2], a[17]*a[20] - a[11]*a[23] - a[17]*a[26] + a[11]*a[32] + a[2]*a[35] - a[2]*a[38], 3a[14]*a[20] - 3a[14]*a[26] + 3a[11]*a[30] - 3a[5]*a[35] + 3a[5]*a[38] - a[11], 3a[8]*a[20] - 3a[8]*a[26] + 3a[5]*a[32] - a[2], a[5]*a[17] - a[11]*a[23] + a[2]*a[35] - a[2]*a[38], 3a[8]*a[14] - a[17], 3a[5]*a[14] - a[11], a[2]*a[14] - a[11]*a[23] + a[2]*a[35] - a[2]*a[38], a[8]*a[11] - a[11]*a[23] + a[2]*a[35] - a[2]*a[38], 3a[5]*a[8] - a[2], a[20]*a[29]*a[35] + 2a[20]*a[30]*a[35] - a[26]*a[29]*a[38] + a[26]*a[30]*a[38] - a[14]*a[26] + a[11]*a[30] - a[5]*a[35] - a[20]*a[35] - a[26]*a[35] + 2a[20]*a[38], 6a[8]*a[26]*a[35] - 3a[5]*a[32]*a[35] - 3a[20]*a[32]*a[35] - 3a[8]*a[26]*a[38] - 3a[23]*a[26]*a[38] + 6a[5]*a[32]*a[38] + a[17]*a[26] - a[11]*a[32] + a[2]*a[35] - a[2]*a[38]] end
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
6392
using CSV, DataFrames """ input: N: array of tuples, individuals from each triangles of the network q: individuals of the quartet eg. get_n([("A", "B"), ("C", "D"), ("E", "F"), ("G", "H")], ["C", "E", "G", "H"]) [0, 1, 1, 2] get_n([("A", "B"), ("C", "D"), ("E", NaN), ("G", "H")], ["C", "E", "G", "H"]) [0, 1, 1, 2] output: the number of individuals from each of the 4 triangles of the network (the quartet structure) """ function get_n(N, q) rst = [0, 0, 0, 0] for i in 1:4 for j in 1:4 if q[j] in N[i] rst[i] += 1 end end end return rst end """ input: N: array of tuples, individuals from each triangles of the network q: individuals of the quartet cfs: the dataframe storing the cf values eg. cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", "H")], ["A","B","E","C"], [0.8718629189804454,0.06406854050977726,0.06406854050977726]) [0.8718629189804454,0.06406854050977726,0.06406854050977726] output: returns the CFs in the order major, minor, minor """ function cfs_in_order(N, q, cfs) n = get_n(N, q) if n != [1, 1, 1, 1] ind_major = findall(x->x==2, n)[1] # index of n with major split ret = [N[ind_major][1], N[ind_major][2]] # the two taxon in the major split # if q[1] is one of the two taxon in the major split # locate `a` with index of the other taxon in q if q[1] == ret[1] i = findall(x->x==ret[2], q)[1] if i == 2 return [cfs[1], cfs[2], cfs[3]] elseif i == 3 return [cfs[2], cfs[1], cfs[3]] elseif i == 4 return [cfs[3], cfs[1], cfs[2]] end elseif q[1] == ret[2] i = findall(x->x==ret[1], q)[1] if i == 2 return [cfs[1], cfs[2], cfs[3]] elseif i == 3 return [cfs[2], cfs[1], cfs[3]] elseif i == 4 return [cfs[3], cfs[1], cfs[2]] end # if q[1] is not one of the two taxon in the major split elseif (q[2] == ret[1]) & (q[3] == ret[2]) | (q[2] == ret[2]) & (q[3] == ret[1]) return [cfs[3], cfs[1], cfs[2]] elseif (q[2] == ret[1]) & (q[4] == ret[2]) | (q[2] == ret[2]) & (q[4] == ret[1]) return [cfs[2], cfs[1], cfs[3]] elseif (q[3] == ret[1]) & (q[4] == ret[2]) | (q[3] == ret[2]) & (q[4] == ret[1]) return [cfs[1], cfs[2], cfs[3]] end end #handle case1111 #enumerate all possible order of q, and its corresponding cf all_cfs = [] all_q = [] push!(all_cfs, [cfs[1], cfs[2], cfs[3]]) push!(all_q, [q[1], q[2], q[3], q[4]]) push!(all_q, [q[2], q[1], q[4], q[3]]) push!(all_q, [q[3], q[4], q[1], q[2]]) push!(all_q, [q[4], q[3], q[2], q[1]]) push!(all_cfs, [cfs[1], cfs[3], cfs[2]]) push!(all_q, [q[1], q[2], q[4], q[3]]) push!(all_q, [q[2], q[1], q[3], q[4]]) push!(all_q, [q[3], q[4], q[2], q[1]]) push!(all_q, [q[4], q[3], q[1], q[2]]) push!(all_cfs, [cfs[2], cfs[1], cfs[3]]) push!(all_q, [q[1], q[3], q[2], q[4]]) push!(all_q, [q[2], q[4], q[1], q[3]]) push!(all_q, [q[3], q[1], q[4], q[2]]) push!(all_q, [q[4], q[2], q[3], q[1]]) push!(all_cfs, [cfs[2], cfs[3], cfs[1]]) push!(all_q, [q[1], q[3], q[4], q[2]]) push!(all_q, [q[2], q[4], q[3], q[1]]) push!(all_q, [q[3], q[1], q[2], q[4]]) push!(all_q, [q[4], q[2], q[1], q[3]]) push!(all_cfs, [cfs[3], cfs[2], cfs[1]]) push!(all_q, [q[1], q[4], q[3], q[2]]) push!(all_q, [q[2], q[3], q[4], q[1]]) push!(all_q, [q[3], q[2], q[1], q[4]]) push!(all_q, [q[4], q[1], q[2], q[3]]) push!(all_cfs, [cfs[3], cfs[1], cfs[2]]) push!(all_q, [q[1], q[4], q[2], q[3]]) push!(all_q, [q[2], q[3], q[1], q[4]]) push!(all_q, [q[3], q[2], q[4], q[1]]) push!(all_q, [q[4], q[1], q[3], q[2]]) q_order = [] #reorder quartet according to order of N for i in 1:4 for j in 1:4 if q[j] in N[i] push!(q_order, q[j]) end end end if n == [1, 1, 1, 1] ind = findall(x->x==q_order, all_q)[1] return all_cfs[(ind-1)÷4+1] end return false end """ input: cf: dataframe of concordance factors N: array of tuples, individuals from each triangles of the network verbose (default false): print variables to screen output: returns vector a for a's with the same quartet structure `n`, take the mean of a's the order of a is determined by the order of n_order """ function get_a(cf, N; verbose=false::Bool) # 19 different n, 57 different a # this is a vector that we control (as developers), so we can define it internally n_order = [[0, 0, 2, 2], [0, 1, 2, 1], [0, 1, 1, 2], [0, 2, 2, 0], [0, 2, 1, 1], [0, 2, 0, 2], [1, 0, 2, 1], [1, 0, 1, 2], [1, 1, 2, 0], [1, 1, 1, 1], [1, 1, 0, 2], [1, 2, 1, 0], [1, 2, 0, 1], [2, 0, 2, 0], [2, 0, 1, 1], [2, 0, 0, 2], [2, 1, 1, 0], [2, 1, 0, 1], [2, 2, 0, 0]] a = zeros(length(n_order)*3) c = zeros(length(n_order)*3) #create vector that counts how many rows are mapped to each a value #it has the repeated entried to match the dimension of a for i in 1:nrow(cf) verbose && @show i temp = Array(cf[i, :]) q = temp[1:4] verbose && @show q cfs = [temp[5], temp[6], temp[7]] verbose && @show cfs n = get_n(N, q) verbose && @show n if (sum(n) != 4) #if input network does not match with cf table continue end cfs_ord = cfs_in_order(N, q, cfs) #reorder cf as major, minor, minor #according to N verbose && @show cfs_ord ind = findall(x->x==n, n_order)[1] #the correct index of n in vector a verbose && @show ind a[ind*3] += cfs_ord[3] a[ind*3-1] += cfs_ord[2] a[ind*3-2] += cfs_ord[1] c[ind*3] += 1 c[ind*3-1] += 1 c[ind*3-2] += 1 end a = a./c return a end
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
10083
include("mapping.jl") include("invariants.jl") include("helper.jl") using PhyloNetworks, PhyloPlots, DataFrames, CSV, Statistics, Distributions, Random, DelimitedFiles, Combinatorics, StatsBase """ Implement PhyloDiamond algorithm (input cf table) input: cf: concordance factor table (first 4 columns should be taxon names, last 3 columns should be cf values) m: the number of optimal phylogenetic networks returned output_filename: a file name for the output file (or "phylo_diamond.txt" by default) output: top m optimal phylogenetic networks """ function phylo_diamond(cf::DataFrame, m::Int64, output_filename::String="phylo_diamond.txt") cf = rename!(cf,[:tx1,:tx2, :tx3, :tx4, :expCF12,:expCF13,:expCF14]) t = cf_to_t(cf) #get all taxon names if size(cf, 1) != binomial(length(t), 4) || size(cf, 2) != 7 #check the dimension of cf table error("Please provide a complete cf table") end cf, value_map = taxon_dict(cf) #rename taxon to numbers if length(t) <= 5 error("PhyloDiamond only accept more than 5 taxon") elseif length(t) <= 8 phylo_diamond_no_more_than_8_helper(cf, m, output_filename, value_map) else phylo_diamond_more_than_8_helper(cf, m, output_filename, value_map) end end """ Implement PhyloDiamond algorithm (input gene tree file) input: gene_trees_filename m: the number of optimal phylogenetic networks returned output_filename: a file name for the output file (or "phylo_diamond.txt" by default) output: top m optimal phylogenetic networks """ function phylo_diamond(gene_trees_filename::String, m::Int64, output_filename::String="phylo_diamond.txt") cf = generate_cf_from_gene_trees(gene_trees_filename) cf = rename!(cf,[:tx1,:tx2, :tx3, :tx4, :expCF12,:expCF13,:expCF14]) t = cf_to_t(cf) cf, value_map = taxon_dict(cf) if length(t) <= 5 error("PhyloDiamond only accept more than 5 taxon") elseif length(t) <= 8 phylo_diamond_no_more_than_8_helper(cf, m, output_filename, value_map) else phylo_diamond_more_than_8_helper(cf, m, output_filename, value_map) end end """ helper function to handle no more than 8 taxa input: cf: cf table m: the number of optimal phylogenetic networks returned output_filename: input a filename if users need to save output to a file; otherwise leave it blank or "" newick: return networks in newick format if true; otherwise [(1,2),(3,4),(5,6),(7,8,9)] value_map: the dictionary of taxa to numbers output: top m optimal phylogenetic networks """ function phylo_diamond_no_more_than_8_helper(cf, m, output_filename, value_map) t = cf_to_t(cf) net_all = list_nw(t) inv_mean_sorted, net_all_sorted = get_inv_for_nw(net_all, cf) return phylo_diamond_output_helper(inv_mean_sorted[1:m], net_all_sorted[1:m], m, t, value_map, output_filename) end """ helper function to handle more than 8 taxa input: cf: cf table m: the number of optimal phylogenetic networks returned output_filename: input a filename if users need to save output to a file; otherwise leave it blank or "" newick: return networks in newick format if true; otherwise [(1,2),(3,4),(5,6),(7,8,9)] value_map: the dictionary of taxa to numbers output: top m optimal phylogenetic networks """ function phylo_diamond_more_than_8_helper(cf, m, output_filename, value_map) t = cf_to_t(cf) sub_all = subnetwork(t) #all possible subpermutation of the given network inv_mean_sorted, subnet_all_sorted = get_inv_for_nw(sub_all, cf) str = "" rst_net = [] rst_inv = [] for i in 1:length(subnet_all_sorted) #find the all the missing species for the subnetwork with smallest invariants top_t = N_to_t(subnet_all_sorted[i]) mis_species = [] for i in t if !(i in top_t) push!(mis_species, i) end end net = add_mis_species(mis_species, subnet_all_sorted[i:end]) #when selecting other top networks, remove the first few network information if !(net in rst_net) push!(rst_net, net) push!(rst_inv, inv_mean_sorted[i]) end if length(rst_net) == m break end end return phylo_diamond_output_helper(rst_inv, rst_net, m, t, value_map, output_filename) end """ input: mis_species: the taxa missing from the subnetwork net_all_sorted: a list of all possible networks sorted by the invariant values output: add missing species to the subnetwork with smallest invariants """ function add_mis_species(mis_species, net_all_sorted) rst = net_all_sorted[1] n1 = net_all_sorted[1] for mis in mis_species flag = false #whether the missing species is found #find the position of the missing species in the next smallest-inv subnetworks for next_net in 2:length(net_all_sorted) for i in 1:4 if mis in net_all_sorted[next_net][i] n2 = net_all_sorted[next_net] if n1[1][1] in n2[1] && n1[1][2] in n2[1] && n1[4][1] in n2[4] && n1[4][2] in n2[4] if n1[3][1] in n2[2] && n1[3][2] in n2[2] && (n2[3][1] in n1[2] || n2[3][2] in n1[2]) push!(rst[2], mis) flag = true elseif n1[2][1] in n2[3] && n1[2][2] in n2[3] && n2[2][1] in n1[3] || n2[2][2] in n1[3] push!(rst[3], mis) flag = true end else push!(rst[i], mis) flag = true end end end if flag #skip to proceed to the next missing species break end end end for i in 1:4 rst[i] = sort(rst[i]; alg=QuickSort) end return rst end """ (assuming all taxon are denoted by number starting from 1) For the given network N with more than 8 taxon, find a list of taxon in subnetworks with 8 taxon subnetwork([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8", "9")]) -> ["2", "3", "4", "5", "6","7", "8", "9"], ["1", "2", "3", "4", "5", "6", "7", "8"]... """ function subnetwork(t) ind_all = vcat([collect(combinations(1:length(t),i)) for i=8:8]...) #select all combination of 6, 7, 8 indexes for N ret = [] for net_i in ind_all #iterate through all subnetworks ret = vcat(ret, list_nw(string.(net_i))) end return ret end """ input: N: array of tuples, individuals from each triangles of the network cf: the expected CF table output: an array of norm of invariants (we expect the value to be small if it is the correct network) """ function test_invariants(N, cf) a = get_a(cf, N) return [norm(inv_net1112(a)), norm(inv_net1121(a)), norm(inv_net1211(a)), norm(inv_net2111(a)), norm(inv_net1122(a)), norm(inv_net1212(a)), norm(inv_net2112(a)), norm(inv_net2211(a)), norm(inv_net2121(a)), norm(inv_net1221(a)), norm(inv_net1222(a)), norm(inv_net2212(a)), norm(inv_net2122(a)), norm(inv_net2221(a)), norm(inv_net2222(a))] end """ input: inv_mean_sorted: a sorted list of invariant values for each network net_all_sorted: a list of all possible networks sorted by the invariant values newick: return networks in newick format if true; otherwise [(1,2),(3,4),(5,6),(7,8,9)] value_map: the dictionary of taxa to numbers output: a formatted string of optimal networks (net_all_sorted) """ function phylo_diamond_output_helper(inv_mean_sorted, net_all_sorted, m, t, value_map, output_filename) value_map = Dict(value => key for (key, value) in value_map) str = "Inference of top " * string(m) * " " * string(length(t)) * "-taxon phylogenetic networks with phylogenetic invariants\n" rank = tiedrank(inv_mean_sorted) ret = [] for i in 1:length(net_all_sorted) # use the original taxon names according to value_map for a in 1:length(net_all_sorted[i]) for b in 1:length(net_all_sorted[i][a]) if net_all_sorted[i][a][b] != "na" net_all_sorted[i][a][b] = value_map[net_all_sorted[i][a][b]] end end end newick = N_to_network(net_all_sorted[i]) push!(ret, newick) str = str * string(Int(round(rank[i]))) * ". N" * N_to_N_num(net_all_sorted[i]) * " (" * string(inv_mean_sorted[i]) * ")" * "\n" * N_to_str(net_all_sorted[i]) * "\n\"" * newick * "\"\n" end file = open(output_filename, "a") write(file, str) close(file) print(str) return Dict(zip(1:m, ret)) end """ input: net_all: a list of all possible networks cf: cf table output: inv_mean_sorted: a sorted list of invariant values for each network net_all_sorted: a list of all possible networks sorted by the invariant values """ function get_inv_for_nw(net_all, cf) rst_inv = [] for i in 1:length(net_all) val = test_invariants(net_all[i], cf) push!(rst_inv, mean(filter(!isnan, val))) end order = sortperm(rst_inv) inv_mean_sorted = rst_inv[order] net_all_sorted = net_all[order] return inv_mean_sorted, net_all_sorted end """ input: cf table output: replace original taxon names with numbers in the cf table and a mapping from taxon names to numbers """ function taxon_dict(cf) taxon = cf_to_t(cf) value_map = Dict(taxon[i] => string(i) for i in 1:length(taxon)) for col in ["tx1", "tx2", "tx3", "tx4"] for i in 1:nrow(cf) cf[i,col] = string(value_map[cf[i,col]]) end end return cf, value_map end
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
3527
using PhyloDiamond using Test print(pwd()) @testset "PhyloDiamond.jl" begin cf = PhyloDiamond.generate_cf([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8", "9")], 0) dict = PhyloDiamond.phylo_diamond(cf, 5) @test length(dict) == 5 @test dict[5] == "((9:1,5:1,6:1):4, (((7:1,8:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);" @test dict[4] == "((5:1,6:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(7:1,8:1,9:1):2):1):1);" @test dict[2] == "((7:1,8:1,9:1):4, (((5:1,6:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);" @test dict[3] == "((8:1,9:1):4, (((5:1,6:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(7:1,3:1,4:1):2):1):1);" @test dict[1] == "((7:1,8:1,9:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" f = open("phylo_diamond.txt", "r") s = read(f, String) close(f) s_1 = "Inference of top 5 9-taxon phylogenetic networks with phylogenetic invariants\n1. N2223 (2.2216927709301364e-16)\n[(1,2),(3,4),(5,6),(7,8,9)]\n\"((7:1,8:1,9:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);\"\n2. N2223 (2.2230610911746716e-16)\n[(1,2),(5,6),(3,4),(7,8,9)]\n\"((7:1,8:1,9:1):4, (((5:1,6:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);\"\n2. N2232 (2.2230610911746716e-16)\n[(1,2),(5,6),(7,3,4),(8,9)]\n\"((8:1,9:1):4, (((5:1,6:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(7:1,3:1,4:1):2):1):1);\"\n4. N2232 (0.006576057988736475)\n[(1,2),(3,4),(7,8,9),(5,6)]\n\"((5:1,6:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(7:1,8:1,9:1):2):1):1);\"\n5. N2223 (0.00657929000066336)\n[(1,2),(7,8),(3,4),(9,5,6)]\n\"((9:1,5:1,6:1):4, (((7:1,8:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);\"\n" @test s == s_1 rm("phylo_diamond.txt") dict = PhyloDiamond.phylo_diamond("./file/gt.txt", 5) @test length(dict) == 5 @test dict[5] == "((5:1,6:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(7:1,8:1):2):1):1);" @test dict[4] == "((3:1,4:1):4, (((5:1,6:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(7:1,8:1):2):1):1);" @test dict[2] == "((7:1,8:1):4, (((5:1,6:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);" @test dict[3] == "((3:1,4:1):4, (((7:1,8:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" @test dict[1] == "((7:1,8:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" f = open("phylo_diamond.txt", "r") s = read(f, String) close(f) s_1 = "Inference of top 5 8-taxon phylogenetic networks with phylogenetic invariants\n1. N2222 (0.03689157145883046)\n[(1,2),(3,4),(5,6),(7,8)]\n\"((7:1,8:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);\"\n2. N2222 (0.03823994257144703)\n[(1,2),(5,6),(3,4),(7,8)]\n\"((7:1,8:1):4, (((5:1,6:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(3:1,4:1):2):1):1);\"\n3. N2222 (0.04097959230267735)\n[(1,2),(7,8),(5,6),(3,4)]\n\"((3:1,4:1):4, (((7:1,8:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);\"\n4. N2222 (0.04258688497092598)\n[(1,2),(5,6),(7,8),(3,4)]\n\"((3:1,4:1):4, (((5:1,6:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(7:1,8:1):2):1):1);\"\n5. N2222 (0.04789498610785061)\n[(1,2),(3,4),(7,8),(5,6)]\n\"((5:1,6:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(7:1,8:1):2):1):1);\"\n" @test s == s_1 rm("phylo_diamond.txt") end include("test_mapping.jl") include("test_helper.jl")
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
1215
include("../src/helper.jl") @testset "helper.jl" begin @testset "list_nw" begin @test length(list_nw(["A", "B", "C", "D", "E", "F", "G", "H"])) == 2520 #(N2222) @test length(list_nw(["A", "B", "C", "D", "E", "F", "G"])) == 2520 #(N1222, N2122, N2212, N2221) @test length(list_nw(["A", "B", "C", "D", "E", "F"])) == 1080 #(N1122, N1212, N1221, N2112, N2121, N2211) @test length(list_nw(["A", "B", "C", "D", "E"])) == 240 #(N1112, N1121, N1211, N2111) end @test compare_nw([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8")],[("1", "2"), ("3", "4"), ("5", "6"), ("7", "9")]) == false @test compare_nw([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8")],[("1", "2"), ("3", "4"), ("5", "6"), ("8", "7")]) == true @test N_to_str([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8", "9")]) == "[(1,2),(3,4),(5,6),(7,8,9)]" @test N_to_network([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8")]) == "((7:1,8:1):4, (((3:1,4:1):2, ((1:1,2:1):1)#H1:1::0.7):1, (#H1:1::0.3,(5:1,6:1):2):1):1);" @test N_to_t([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8")]) == [ "1", "2", "3", "4", "5", "6", "7", "8"] @test N_to_N_num([("1", "2"), ("3", "4"), ("5", "6"), ("7", "8")]) == "2222" end
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git
[ "MIT" ]
0.1.0
bbf6ce99c629eea8c4ed7ab0e9d660010f2f5de9
code
4043
include("../src/mapping.jl") @testset "mapping.jl" begin @testset "get_a" begin cf=CSV.read("./file/N2222_expCF.txt", DataFrame) # Reading network N = [("A", "B"), ("C", "D"), ("E", "F"), ("G", "H")] ## true network i=1 temp = Array(cf[i, :]) q = temp[1:4] cfs = [temp[5], temp[6], temp[7]] n = get_n(N, q) @test n == [2,0,2,0] cfs_ord = cfs_in_order(N, q, cfs) @test round.(cfs_ord;digits=2) == [0.96,0.02,0.02] i=69 temp = Array(cf[i, :]) q = temp[1:4] cfs = [temp[5], temp[6], temp[7]] n = get_n(N, q) @test n == [0,1,1,2] cfs_ord = cfs_in_order(N, q, cfs) @test round.(cfs_ord;digits=2) == [0.91,0.05,0.05] N = [("A","E"),("C","B"),("D","F"),("G","H")] i=1 temp = Array(cf[i, :]) q = temp[1:4] cfs = [temp[5], temp[6], temp[7]] n = get_n(N, q) @test n == [2,1,1,0] cfs_ord = cfs_in_order(N, q, cfs) @test round.(cfs_ord;digits=2) == [0.02,0.96,0.02] i=2 temp = Array(cf[i, :]) q = temp[1:4] cfs = [temp[5], temp[6], temp[7]] n = get_n(N, q) @test n == [2,2,0,0] cfs_ord = cfs_in_order(N, q, cfs) @test round.(cfs_ord;digits=2) == [0.06,0.87,0.06] end @testset "get_n" begin @test get_n([("A", "B"), ("C", "D"), ("E", "F"), ("G", "H")], ["C", "E", "G", "H"]) == [0, 1, 1, 2] @test get_n([("A", "B"), ("C", "D"), ("E", NaN), ("G", "H")], ["C", "E", "G", "H"]) == [0, 1, 1, 2] end @testset "cfs_in_order" begin #N2222 (1, 1, 1, 1) @test cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", "H")], ["A","H","E","C"], [0.7, 0.2, 0.1])==[0.1, 0.2, 0.7] @test cfs_in_order([("E", "F"), ("A", "B"), ("G", "H"), ("C", "D")], ["A","H","E","C"], [0.7, 0.2, 0.1])==[0.2, 0.1, 0.7] @test cfs_in_order([("A", "B"), ("E", "F"), ("G", "H"), ("C", "D")], ["E","C","A","H"], [0.7, 0.2, 0.1])==[0.2, 0.7, 0.1] #N2122 @test cfs_in_order([("A", "B"), ("C", NaN), ("E", "F"), ("G", "H")], ["A","B","E","C"], [0.8, 0.1, 0.1])==[0.8, 0.1, 0.1] #2110 @test cfs_in_order([("A", "B"), ("C", NaN), ("E", "F"), ("G", "H")], ["A","E","C","B"], [0.1, 0.1, 0.8])==[0.8, 0.1, 0.1] #2110 @test cfs_in_order([("A", "B"), ("C", NaN), ("E", "F"), ("G", "H")], ["E","G","A","C"], [0.7, 0.2, 0.1])==[0.7, 0.2, 0.1] #1111 @test cfs_in_order([("A", "B"), ("C", NaN), ("E", "F"), ("G", "H")], ["H","G","A","B"], [0.8, 0.1, 0.1])==[0.8, 0.1, 0.1] #2002 #N2221 @test cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", NaN)],["E","B","F","C"], [0.1, 0.8, 0.1])==[0.8, 0.1, 0.1] #1120 @test cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", NaN)],["A","B","C","F"], [0.8, 0.1, 0.1])==[0.8, 0.1, 0.1] #2110 @test cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", NaN)],["F","G","A","C"], [0.7, 0.2, 0.1])==[0.7, 0.2, 0.1] #1111 @test cfs_in_order([("A", "B"), ("C", "D"), ("E", "F"), ("G", NaN)],["B","F","A","E"], [0.1, 0.8, 0.1])==[0.8, 0.1, 0.1] #2020 #N2111 @test cfs_in_order([("A", "B"), ("C", NaN), ("E", NaN), ("G", NaN)],["E","B","G","A"], [0.1, 0.8, 0.1])==[0.8, 0.1, 0.1] #2011 @test cfs_in_order([("A", "B"), ("C", NaN), ("E", NaN), ("G", NaN)],["B","E","G","A"], [0.1, 0.1, 0.8])==[0.8, 0.1, 0.1] #2011 #N2211 @test cfs_in_order([("A", "B"), ("C", "D"), ("E", NaN), ("G", NaN)],["C","B","D","A"], [0.1, 0.8, 0.1])==[0.8, 0.1, 0.1] #2200 @test cfs_in_order([("A", "B"), ("C", "D"), ("E", NaN), ("G", NaN)],["A","B","C","D"], [0.8, 0.1, 0.1])==[0.8, 0.1, 0.1] #2200 @test cfs_in_order([("A", "B"), ("C", "D"), ("E", NaN), ("G", NaN)],["C","G","D","A"], [0.1, 0.8, 0.1])==[0.8, 0.1, 0.1] #1201 @test cfs_in_order([("A", "B"), ("C", "D"), ("E", NaN), ("G", NaN)],["E","G","C","B"], [0.7, 0.1, 0.2])==[0.7, 0.2, 0.1] #1111 end end
PhyloDiamond
https://github.com/solislemuslab/PhyloDiamond.jl.git