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.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 13575 |
function mLiQSS_integrate(Al::QSSAlgorithm{:nmliqss,O},CommonqssData::CommonQSS_data{0},liqssdata::LiQSS_data{O,false},specialLiqssData::SpecialLiqssQSS_data, odep::NLODEProblem{PRTYPE,T,0,0,CS},f::Function,jac::Function,SD::Function,exacteA::Function) where {PRTYPE,CS,O,T}
cacheA=specialLiqssData.cacheA
direction=specialLiqssData.direction
#qminus= specialLiqssData.qminus
buddySimul=specialLiqssData.buddySimul
ft = CommonqssData.finalTime;initTime = CommonqssData.initialTime;relQ = CommonqssData.dQrel;absQ = CommonqssData.dQmin;maxErr=CommonqssData.maxErr;
#setprecision(BigFloat,64)
#savetimeincrement=CommonqssData.savetimeincrement;savetime = savetimeincrement
quantum = CommonqssData.quantum;nextStateTime = CommonqssData.nextStateTime;nextEventTime = CommonqssData.nextEventTime;
nextInputTime = CommonqssData.nextInputTime
tx = CommonqssData.tx;tq = CommonqssData.tq;x = CommonqssData.x;q = CommonqssData.q;t=CommonqssData.t
savedVars=CommonqssData.savedVars;
savedTimes=CommonqssData.savedTimes;integratorCache=CommonqssData.integratorCache;taylorOpsCache=CommonqssData.taylorOpsCache;#cacheSize=odep.cacheSize
#prevStepVal = specialLiqssData.prevStepVal
#a=deepcopy(odep.initJac);
#a=liqssdata.a
#u=liqssdata.u;#tu=liqssdata.tu
#***************************************************************
qaux=liqssdata.qaux;dxaux=liqssdata.dxaux#= olddx=liqssdata.olddx; ; olddxSpec=liqssdata.olddxSpec =#
d=[0.0]
numSteps = Vector{Int}(undef, T)
pp=pointer(Vector{NTuple{2,Float64}}(undef, 7))
respp = pointer(Vector{Float64}(undef, 2))
temporaryhelper = Vector{Int}(undef, 1)
temporaryhelper[1]=0
savedVarsQ = Vector{Vector{Float64}}(undef, T)
savedVarsQ[1]=Vector{Float64}() ;savedVarsQ[2]=Vector{Float64}()
cacherealPosi=Vector{Vector{Float64}}(undef,3);cacherealPosj=Vector{Vector{Float64}}(undef,3);
for i =1:3
cacherealPosi[i]=zeros(2)
cacherealPosj[i]=zeros(2)
end
exacteA(q,cacheA,1,1) # this 'unnecessary call' 'compiles' the function and it helps remove allocations when used after !!!
#@show exacteA
#######################################compute initial values##################################################
n=1
for k = 1:O # compute initial derivatives for x and q (similar to a recursive way )
n=n*k
for i = 1:T
q[i].coeffs[k] = x[i].coeffs[k] # q computed from x and it is going to be used in the next x
end
for i = 1:T
clearCache(taylorOpsCache,Val(CS),Val(O));f(i,q,t ,taylorOpsCache)
ndifferentiate!(integratorCache,taylorOpsCache[1] , k - 1)
x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2)
end
end
for i = 1:T
numSteps[i]=0
#= @timeit "savevars" =# push!(savedVars[i],x[i][0])
#push!(savedVarsQ[i],q[i][0])
push!(savedTimes[i],0.0)
quantum[i] = relQ * abs(x[i].coeffs[1]) ;quantum[i]=quantum[i] < absQ ? absQ : quantum[i];quantum[i]=quantum[i] > maxErr ? maxErr : quantum[i]
updateQ(Val(O),i,x,q,quantum,exacteA,d,cacheA,dxaux,qaux,tx,tq,initTime,ft,nextStateTime)
end
for i = 1:T
clearCache(taylorOpsCache,Val(CS),Val(O));f(i,q,t,taylorOpsCache);
computeDerivative(Val(O), x[i], taylorOpsCache[1])#0.0 used to be elapsed...even down below not neeeded anymore
Liqss_reComputeNextTime(Val(O), i, initTime, nextStateTime, x, q, quantum)
computeNextInputTime(Val(O), i, initTime, 0.1,taylorOpsCache[1] , nextInputTime, x, quantum)#not complete, currently elapsed=0.1 is temp until fixed
#prevStepVal[i]=x[i][0]#assignXPrevStepVals(Val(O),prevStepVal,x,i)
end
###################################################################################################################################################################
####################################################################################################################################################################
#---------------------------------------------------------------------------------while loop-------------------------------------------------------------------------
###################################################################################################################################################################
####################################################################################################################################################################
simt = initTime ;simulStepCount=0;totalSteps=0;
totalStepswhenCycles=0
#simul=false
while simt < ft && totalSteps < 300000000
sch = updateScheduler(Val(T),nextStateTime,nextEventTime, nextInputTime)
simt = sch[2];index = sch[1]
if simt>ft
#simt=ft
push!(savedVars[1],x[1][0])# this is not needed as later user can get any value through interpolation
push!(savedTimes[1],ft)
push!(savedVars[2],x[2][0])# this is not needed as later user can get any value through interpolation
push!(savedTimes[2],ft)
break
end
numSteps[index]+=1;totalSteps+=1
if simulStepCount>0
totalStepswhenCycles+=1
end
t[0]=simt
##########################################state########################################
if sch[3] == :ST_STATE
xitemp=x[index][0]
elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index]
#dirI=x[index][0]-savedVars[index][end]
dirI=x[index][0]-xitemp
for b in (jac(index) ) # update Qb : to be used to calculate exacte Aindexb
elapsedq = simt - tq[b] ;
if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
firstguess=updateQ(Val(O),index,x,q,quantum,exacteA,d,cacheA,dxaux,qaux,tx,tq,simt,ft,nextStateTime) ;tq[index] = simt
#----------------------------------------------------check dependecy cycles---------------------------------------------
for j in SD(index)
for b in (jac(j) ) # update Qb: to be used to calculate exacte Ajb
elapsedq = simt - tq[b] ;
if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq); tq[b]=simt end
end
exacteA(q,cacheA,index,j);aij=cacheA[1]
exacteA(q,cacheA,j,index);aji=cacheA[1]
#= exacteA(x,cacheA,index,j);aij=cacheA[1]
exacteA(x,cacheA,j,index);aji=cacheA[1] =#
if j!=index && aij*aji!=0.0
#prvStepValj= savedVars[j][end]#getPrevStepVal(prevStepVal,j)
for i =1:3
cacherealPosi[i][1]=0.0; cacherealPosi[i][2]=0.0
cacherealPosj[i][1]=0.0; cacherealPosj[i][2]=0.0
end
if misCycle_and_simulUpdate(cacherealPosi,cacherealPosj,respp,pp,temporaryhelper,Val(O),index,j,dirI,firstguess,x,q,quantum,exacteA,cacheA,dxaux,qaux,tx,tq,simt,ft)
simulStepCount+=1
#= clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,t,taylorOpsCache);computeDerivative(Val(O), x[index], taylorOpsCache[1])
# clearCache(taylorOpsCache,Val(CS),Val(O));f(j,q,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), index, simt, nextStateTime, x, q, quantum)
# Liqss_reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
for k in SD(j) #j influences k
if k!=index && k!=j
elapsedx = simt - tx[k]; x[k].coeffs[1] = x[k](elapsedx);tx[k] = simt
elapsedq = simt - tq[k]; if elapsedq > 0 ;integrateState(Val(O-1),q[k],elapsedq); tq[k] = simt end
for b in (jac(k) )
elapsedq = simt - tq[b]
if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(k,q,t,taylorOpsCache);computeDerivative(Val(O), x[k], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), k, simt, nextStateTime, x, q, quantum)
end#end if k!=0
end#end for k depend on j =#
end#end ifcycle check
# end #end if allow one simulupdate
end#end if j!=0
end#end FOR_cycle check
#-------------------------------------------------------------------------------------
#---------------------------------normal liqss: proceed--------------------------------
#-------------------------------------------------------------------------------------
for c in SD(index) #index influences c
elapsedx = simt - tx[c] ;if elapsedx>0 x[c].coeffs[1] = x[c](elapsedx);tx[c] = simt end #
elapsedq = simt - tq[c];if elapsedq > 0 ;integrateState(Val(O-1),q[c],elapsedq);tq[c] = simt end # c never been visited
#= for b in (jac(c) ) # update other influences
elapsedq = simt - tq[b] ;if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end =#
clearCache(taylorOpsCache,Val(CS),Val(O)); f(c,q,t,taylorOpsCache);computeDerivative(Val(O), x[c], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), c, simt, nextStateTime, x, q, quantum)
end#end for SD
#= if simt==0.9341868806288225
@show simt,index,totalSteps,totalStepswhenCycles,simulStepCount
@show x,q
@show nextStateTime
end =#
##################################input########################################
elseif sch[3] == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself
@show index
elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index]
for k = 1:O q[index].coeffs[k] = x[index].coeffs[k] end; tq[index] = simt
for b in jac(index)
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,t,taylorOpsCache)
computeNextInputTime(Val(O), index, simt, elapsed,taylorOpsCache[1] , nextInputTime, x, quantum)
computeDerivative(Val(O), x[index], taylorOpsCache[1]#= ,integratorCache,elapsed =#)
for j in (SD(index))
elapsedx = simt - tx[j];
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt
quantum[j] = relQ * abs(x[j].coeffs[1]) ;quantum[j]=quantum[j] < absQ ? absQ : quantum[j];quantum[j]=quantum[j] > maxErr ? maxErr : quantum[j]
end
elapsedq = simt - tq[j];if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt end#q needs to be updated here for recomputeNext
for b in jac(j)
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(j,q,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1]#= ,integratorCache,elapsed =#)
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for
#= for i = 1:length(SZ[index])
j = SZ[index][i]
if j != 0
for b = 1:T # elapsed update all other vars that this derj depends upon.
if zc_SimpleJac[j][b] != 0
elapsedx = simt - tx[b];if elapsedx>0 integrateState(Val(O),x[b],integratorCache,elapsedx);tx[b]=simt end
# elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
end
#= clearCache(taylorOpsCache,Val(CS),Val(O))#normally and later i should update x,q (integrate q=q+e derQ for higher orders)
computeNextEventTime(j,zcf[j](x,d,t,taylorOpsCache),oldsignValue,simt, nextEventTime, quantum)#,maxIterer) =#
clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,j,-1,x,d,t,taylorOpsCache)
computeNextEventTime(j,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum)
end
end =#
#################################################################event########################################
end#end state/input/event
push!(savedVars[index],(x[index][0]+q[index][0])/2)
push!(savedTimes[index],simt)
# push!(savedVarsQ[index],q[index][0])
end#end while
#@show temporaryhelper
#= @timeit "createSol" =#
createSol(Val(T),Val(O),savedTimes,savedVars, "mLiqss$O",string(odep.prname),absQ,totalSteps,simulStepCount,0,numSteps,ft)
#createSol(Val(T),Val(O),savedTimes,savedVars,savedVarsQ, "mliqss$O",string(odep.prname),absQ,totalSteps#= ,totalStepswhenCycles =#,simulStepCount,numSteps,ft)
# change this to function /constrcutor...remember it is bad to access structs (objects) directly
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 22594 | function nLiQSS_integrate(CommonqssData::CommonQSS_data{O,0},liqssdata::LiQSS_data{O,false},specialLiqssData::SpecialLiqssQSS_data, odep::NLODEProblem{PRTYPE,T,0,0,CS},f::Function,jac::Function,SD::Function,map::Function) where {PRTYPE,O,CS,T}
cacheA=specialLiqssData.cacheA
direction=specialLiqssData.direction
qminus= specialLiqssData.qminus
buddySimul=specialLiqssData.buddySimul
ft = CommonqssData.finalTime;initTime = CommonqssData.initialTime;relQ = CommonqssData.dQrel;absQ = CommonqssData.dQmin;maxErr=CommonqssData.maxErr;
savetimeincrement=CommonqssData.savetimeincrement;savetime = savetimeincrement
quantum = CommonqssData.quantum;nextStateTime = CommonqssData.nextStateTime;nextEventTime = CommonqssData.nextEventTime;nextInputTime = CommonqssData.nextInputTime
tx = CommonqssData.tx;tq = CommonqssData.tq;x = CommonqssData.x;q = CommonqssData.q;t=CommonqssData.t
savedVars=CommonqssData.savedVars;
savedTimes=CommonqssData.savedTimes;integratorCache=CommonqssData.integratorCache;taylorOpsCache=CommonqssData.taylorOpsCache;cacheSize=odep.cacheSize
# prevStepVal = specialQSSdata.prevStepVal
#a=deepcopy(odep.initJac);
#a=liqssdata.a
#u=liqssdata.u;#tu=liqssdata.tu
#***************************************************************
qaux=liqssdata.qaux;olddx=liqssdata.olddx;dxaux=liqssdata.dxaux;olddxSpec=liqssdata.olddxSpec
#numSteps = zeros(MVector{T,Int})
numSteps = Vector{Int}(undef, T)
#######################################compute initial values##################################################
n=1
for k = 1:O # compute initial derivatives for x and q (similar to a recursive way )
n=n*k
for i = 1:T
q[i].coeffs[k] = x[i].coeffs[k] # q computed from x and it is going to be used in the next x
end
for i = 1:T
clearCache(taylorOpsCache,Val(CS),Val(O));f(i,q,t ,taylorOpsCache)
ndifferentiate!(integratorCache,taylorOpsCache[1] , k - 1)
x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2)
end
end
for i = 1:T
end
for i = 1:T
#= p=1
for k=1:O
p=p*k
m=p/k
for j=1:T
if j!=i
u[i][j][k]=p*x[i][k]-a[i][i]*m*q[i][k-1]-a[i][j]*m*q[j][k-1]
else
u[i][j][k]=p*x[i][k]-a[i][i]*m*q[i][k-1]
end
end
end =#
numSteps[i]=0
push!(savedVars[i],x[i][0])
push!(savedTimes[i],0.0)
quantum[i] = relQ * abs(x[i].coeffs[1]) ;quantum[i]=quantum[i] < absQ ? absQ : quantum[i];quantum[i]=quantum[i] > maxErr ? maxErr : quantum[i]
updateQ(Val(O),i,x,q,quantum,map,cacheA,dxaux,qaux,olddx,tx,tq,initTime,ft,nextStateTime)
end
for i = 1:T
clearCache(taylorOpsCache,Val(CS),Val(O));f(i,q,t,taylorOpsCache);computeDerivative(Val(O), x[i], taylorOpsCache[1])#0.0 used to be elapsed...even down below not neeeded anymore
Liqss_reComputeNextTime(Val(O), i, initTime, nextStateTime, x, q, quantum)
computeNextInputTime(Val(O), i, initTime, 0.1,taylorOpsCache[1] , nextInputTime, x, quantum)#not complete, currently elapsed=0.1 is temp until fixed
end
###################################################################################################################################################################
####################################################################################################################################################################
#---------------------------------------------------------------------------------while loop-------------------------------------------------------------------------
###################################################################################################################################################################
####################################################################################################################################################################
simt = initTime ;simulStepCount=0;totalSteps=0;prevStepTime=initTime
simul=false
@show map
while simt < ft && totalSteps < 20
#= if breakloop[1]>5.0
break
end =#
sch = updateScheduler(Val(T),nextStateTime,nextEventTime, nextInputTime)
simt = sch[2]
#= if simt>ft
saveLast!(Val(T),Val(O),savedVars, savedTimes,saveVarsHelper,ft,prevStepTime, x)
break ###################################################break##########################################
end =#
index = sch[1]
totalSteps+=1
t[0]=simt
##########################################state########################################
if sch[3] == :ST_STATE
elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index]
#= @timeit "newDiff" =# #= newDiff=x[index][0]-getPrevStepVal(prevStepVal,index)
dir=direction[index]
if newDiff*dir <0.0
direction[index]=-dir
elseif newDiff==0 && dir!=0.0
direction[index]=0.0
elseif newDiff!=0 && dir==0.0
direction[index]=newDiff
else
end =#
#nupdate different from update: it has the modification u=x-aq instead of u1=u1+e*u2
#= @timeit "nupdateQ" =# updateQ(Val(O),index,x,q,quantum,map,cacheA,dxaux,qaux,olddx,tx,tq,simt,ft,nextStateTime) ;tq[index] = simt
# Liqss_ComputeNextTime(Val(O), index, simt, nextStateTime, x, q, quantum)
olddxSpec[index][1]=x[index][1]
#----------------------------------------------------check dependecy cycles---------------------------------------------
#qminus[index]=
simul=false
buddySimul[1]=0;buddySimul[2]=0;
for j in SD(index)
map(q,cacheA,index,j)
aij=cacheA[1]
map(q,cacheA,j,index)
aji=cacheA[1]
if j!=index && aij*aji!=0.0
#if buddySimul[1]==0 # allow single simul...later remove and allow multiple simul
# prvStepVal= getPrevStepVal(prevStepVal,j)
#= @timeit "if cycle" =# if nisCycle_and_simulUpdate(Val(O),index,j#= ,prvStepVal =#,direction,x,q,quantum,map,cacheA,dxaux,qaux,olddx,olddxSpec,tx,tq,simt,ft,qminus#= ,nextStateTime =#)
simulStepCount+=1
simul=true
#qminus[index]=1.0
if buddySimul[1]==0 # this is for testing: coded towars advection (2 vars at most)
buddySimul[1]=j
else
buddySimul[2]=j
end
for b in (jac(j) )
elapsedq = simt - tq[b] ;if elapsedq>0 qminus[b]=q[b][0];integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
# elapsedx = simt - tx[b];if elapsedx > 0 integrateState(Val(O),x[b],elapsedx);tx[b] = simt end
end
for b in ( jac(index) )
elapsedq = simt - tq[b] ;if elapsedq>0 qminus[b]=q[b][0];integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
# elapsedx = simt - tx[b];if elapsedx > 0 integrateState(Val(O),x[b],elapsedx);tx[b] = simt end
end
#compute olddxSpec_i using new qi and qjaux to annihilate the influence of qi (keep j influence only) when finding aij=(dxi-dxi)/(qj-qjaux)
# end#end??????????????????????????????
# @timeit "block2 after simul" begin
qjtemp=q[j][0];q[j][0]=qaux[j][1]
clearCache(taylorOpsCache,Val(CS),Val(O));
#= @timeit "f" =# f(index,q,t,taylorOpsCache);#computeDerivative(Val(O), x[index], taylorOpsCache[1])
olddxSpec[index][1]=taylorOpsCache[1][0]
clearCache(taylorOpsCache,Val(CS),Val(O));
#= @timeit "f" =# f(j,q,t,taylorOpsCache);#computeDerivative(Val(O), x[j], taylorOpsCache[1])
olddx[j][1]=taylorOpsCache[1][0] # needed to find a_jj (qi annihilated, qj kept)
# olddxSpec[index][1]= x[index][1] # new qi used now so it does not have an effect later on aij
q[j][0]=qjtemp # get back qj
qitemp=q[index][0];q[index][0]=qaux[index][1]#
clearCache(taylorOpsCache,Val(CS),Val(O));
#= @timeit "f" =# f(index,q,t,taylorOpsCache);#computeDerivative(Val(O), x[index], taylorOpsCache[1])
olddx[index][1]=taylorOpsCache[1][0]
clearCache(taylorOpsCache,Val(CS),Val(O));
#= @timeit "f" =# f(j,q,t,taylorOpsCache);#computeDerivative(Val(O), x[j], taylorOpsCache[1])
olddxSpec[j][1]=taylorOpsCache[1][0] # new qj used now so it does not have an effect later on aji
q[index][0]=qitemp
clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,t,taylorOpsCache);computeDerivative(Val(O), x[index], taylorOpsCache[1])
clearCache(taylorOpsCache,Val(CS),Val(O));f(j,q,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1])
# updateOtherApprox(index,j,x,q,map,cacheA,qaux,olddxSpec)
# updateOtherApprox(j,index,x,q,map,cacheA,qaux,olddxSpec)
Liqss_reComputeNextTime(Val(O), index, simt, nextStateTime, x, q, quantum)
Liqss_reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
for k in SD(j) #j influences k
if k!=index && k!=j
elapsedx = simt - tx[k]; x[k].coeffs[1] = x[k](elapsedx);tx[k] = simt
elapsedq = simt - tq[k]; if elapsedq > 0 qminus[k]=q[k][0];integrateState(Val(O-1),q[k],elapsedq); tq[k] = simt end
indexInJacK=false;kInjacK=false
for b in (jac(k) )
elapsedq = simt - tq[b]
if elapsedq>0
qminus[b]=q[b][0];
integrateState(Val(O-1),q[b],elapsedq);
tq[b]=simt
end
if b==index
indexInJacK=true
elseif b==k
kInjacK=true
end
end
# update akj #i want influence of j on dxk
if indexInJacK # index also will influence xk
qjtemp=q[j][0];q[j][0]=qaux[j][1]
clearCache(taylorOpsCache,Val(CS),Val(O));
f(k,q,t,taylorOpsCache); #to get rid off index influence for akj
olddxSpec[k][1]=taylorOpsCache[1][0]
q[j][0]=qjtemp
else
#= differentiate!(integratorCache,x[k])
olddxSpec[k][1] = integratorCache(elapsedx) =#
integrateOldx(Val(O),x[k],olddxSpec[k],elapsedx)
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(k,q,t,taylorOpsCache);computeDerivative(Val(O), x[k], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), k, simt, nextStateTime, x, q, quantum)
# updateOtherApprox(k,j,x,q,map,cacheA,qaux,olddxSpec)#
##########i want influence of k on k
if kInjacK
qctemp=q[k][0];
# @timeit "qminus"
q[k][0]=qminus[k]# i want only the effect of qc on acc: remove influence of index and j
clearCache(taylorOpsCache,Val(CS),Val(O));
#= @timeit "f" =# f(k,q,t,taylorOpsCache);
olddx[k][1]=taylorOpsCache[1][0]# acc =(dxc-oldxc)/(qc-qcminus)
q[k][0]=qctemp
# nupdateLinearApprox(k,x,q,map,cacheA,qminus,olddx)# acc =(dxc-oldxc)/(qc-qcminus)
#= else
nupdateU_aNull(Val(O),k,x,u,simt)# acc==0 =#
end
end#end if k!=0
end#end for k depend on j
# updateLinearApprox(j,x,q,map,cacheA,qaux,olddx)
end#end ifcycle check
# end #end if allow one simulupdate
end#end if j!=0
end#end FOR_cycle check
#-------------------------------------------------------------------------------------
#---------------------------------normal liqss: proceed--------------------------------
#-------------------------------------------------------------------------------------
for c in SD(index) #index influences c
if c==buddySimul[1] || c==buddySimul[2] || (c==index && buddySimul[1]!=0) # buddysimul!=0 means simulstep happened c==j already been taken care off under simul aci=aji already updated after simul and acc=ajj also updated at end of simul
#and if c==index acc && aci=aii to be updated below at end;
elseif c==index && buddySimul[1]==0 # simulstep did not happen; still no need to update acc & aci =aii (to be updated at end); only recomputeNext needed
for b in (jac(c) ) # update other influences
elapsedq = simt - tq[b] ;if elapsedq>0 qminus[b]=q[b][0];integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));
#= @timeit "f" =# f(c,q,t,taylorOpsCache)
computeDerivative(Val(O), x[c], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), c, simt, nextStateTime, x, q, quantum)
else# c is another var (not index); it needs aci & acc to be updated
elapsedx = simt - tx[c]
if elapsedx>0
x[c].coeffs[1] = x[c](elapsedx);tx[c] = simt
#= differentiate!(integratorCache,x[c])
olddxSpec[c][1] = integratorCache(elapsedx) =#
integrateOldx(Val(O),x[c],olddxSpec[c],elapsedx)
end # case simul happened c=k
elapsedq = simt - tq[c]
if elapsedq > 0 qminus[c]=q[c][0];integrateState(Val(O-1),q[c],elapsedq);tq[c] = simt end # c never been visited
buddySimulInJacC=false;cInjacC=false
for b in (jac(c) ) # update other influences
elapsedq = simt - tq[b] ;if elapsedq>0 qminus[b]=q[b][0];integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
if (b==buddySimul[1])||(b==buddySimul[2])
buddySimulInJacC=true
elseif b==c
cInjacC=true
end
end
# update aci #i want influence of index on dxc
if buddySimulInJacC # simulupdate happened and qjthrown also will influence dxc
#@show 55
qitemp=q[index][0];q[index][0]=qaux[index][1] #to get rid off buddySimul influence;we want only infleuce of index to find aci
clearCache(taylorOpsCache,Val(CS),Val(O));
#= @timeit "f" =# f(c,q,t,taylorOpsCache);
olddxSpec[c][1]=taylorOpsCache[1][0]
q[index][0]=qitemp
#= else#buddysimul ie j does not influence c (ie only index influences c) code for c as if no simulstep even if there was a simulupdate (c does not care)
differentiate!(integratorCache,x[c])
olddxSpec[c][1] = integratorCache(elapsedx) =## this (as if) updates all Qs involved in dxc (including index)
# aci=(dxc-oldspec)/(qithrow-qielaps)
end
clearCache(taylorOpsCache,Val(CS),Val(O));
#= @timeit "f" =# f(c,q,t,taylorOpsCache)
computeDerivative(Val(O), x[c], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), c, simt, nextStateTime, x, q, quantum)
# updateOtherApprox(c,index,x,q,map,cacheA,qaux,olddxSpec)# error in map
if cInjacC
qctemp=q[c][0];q[c][0]=qminus[c]# i want only the effect of qc on acc: remove influence of index and j
clearCache(taylorOpsCache,Val(CS),Val(O));f(c,q,t,taylorOpsCache);
olddx[c][1]=taylorOpsCache[1][0]# acc =(dxc-oldxc)/(qc-qcminus)
q[c][0]=qctemp
# nupdateLinearApprox(c,x,q,map,cacheA,qminus,olddx)# acc =(dxc-oldxc)/(qc-qcminus)
#= else
nupdateUaNull(Val(O),c,x,u,simt)# acc==0 =#
end
end#end if c==index or else
end#end for SD
# updateLinearApprox(index,x,q,map,cacheA,qaux,olddx)#error in map#######||||||||||||||||||||||||||||||||||||liqss|||||||||||||||||||||||||||||||||||||||||
##################################input########################################
elseif sch[3] == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself
@show index
elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index]
for k = 1:O q[index].coeffs[k] = x[index].coeffs[k] end; tq[index] = simt
for b in jac(index)
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,t,taylorOpsCache)
computeNextInputTime(Val(O), index, simt, elapsed,taylorOpsCache[1] , nextInputTime, x, quantum)
computeDerivative(Val(O), x[index], taylorOpsCache[1])
for j in (SD(index))
elapsedx = simt - tx[j];
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt
quantum[j] = relQ * abs(x[j].coeffs[1]) ;quantum[j]=quantum[j] < absQ ? absQ : quantum[j];quantum[j]=quantum[j] > maxErr ? maxErr : quantum[j]
end
elapsedq = simt - tq[j];if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt end#q needs to be updated here for recomputeNext
for b in jac(j)
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(j,q,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for
#= for i = 1:length(SZ[index])
j = SZ[index][i]
if j != 0
for b = 1:T # elapsed update all other vars that this derj depends upon.
if zc_SimpleJac[j][b] != 0
elapsedx = simt - tx[b];if elapsedx>0 integrateState(Val(O),x[b],elapsedx);tx[b]=simt end
# elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
end
#= clearCache(taylorOpsCache,Val(CS),Val(O))#normally and later i should update x,q (integrate q=q+e derQ for higher orders)
computeNextEventTime(j,zcf[j](x,d,t,taylorOpsCache),oldsignValue,simt, nextEventTime, quantum)#,maxIterer) =#
clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,j,-1,x,d,t,taylorOpsCache)
computeNextEventTime(j,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum)
end
end =#
#################################################################event########################################
end#end state/input/event
push!(savedVars[index],x[index][0])
push!(savedTimes[index],simt)
end#end while
#=
for i=1:T# throw away empty points
resize!(savedVars[i],saveVarsHelper[1])
end
resize!(savedTimes,saveVarsHelper[1]) =#
# print_timer()
#@timeit "createSol"
createSol(Val(T),Val(O),savedTimes,savedVars, "nLiqss$O",string(odep.prname),absQ,totalSteps,simulStepCount,0,numSteps,ft)
# change this to function /constrcutor...remember it is bad to access structs (objects) directly
end#end integrate
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 14541 |
function integrate(Al::QSSAlgorithm{:nmliqss,O},CommonqssData::CommonQSS_data{0},liqssdata::LiQSS_data{O,false},specialLiqssData::SpecialLiqssQSS_data, odep::NLODEProblem{PRTYPE,T,0,0,CS},f::Function,jac::Function,SD::Function,exactA::Function) where {PRTYPE,CS,O,T}
cacheA=specialLiqssData.cacheA
#direction=specialLiqssData.direction
#qminus= specialLiqssData.qminus
#buddySimul=specialLiqssData.buddySimul
ft = CommonqssData.finalTime;initTime = CommonqssData.initialTime;relQ = CommonqssData.dQrel;absQ = CommonqssData.dQmin;maxErr=CommonqssData.maxErr;
#savetimeincrement=CommonqssData.savetimeincrement;savetime = savetimeincrement
quantum = CommonqssData.quantum;nextStateTime = CommonqssData.nextStateTime;nextEventTime = CommonqssData.nextEventTime; nextInputTime = CommonqssData.nextInputTime
tx = CommonqssData.tx;tq = CommonqssData.tq;x = CommonqssData.x;q = CommonqssData.q;t=CommonqssData.t
savedVars=CommonqssData.savedVars;
savedTimes=CommonqssData.savedTimes;integratorCache=CommonqssData.integratorCache;taylorOpsCache=CommonqssData.taylorOpsCache;#cacheSize=odep.cacheSize
#prevStepVal = specialLiqssData.prevStepVal
#a=deepcopy(odep.initJac);
#a=liqssdata.a
#u=liqssdata.u;#tu=liqssdata.tu
#***************************************************************
qaux=liqssdata.qaux;dxaux=liqssdata.dxaux#= olddx=liqssdata.olddx; ; olddxSpec=liqssdata.olddxSpec =#
d=[0.0]# this is a dummy var used in updateQ and simulUpdate because in the discrete world exactA needs d, this is better than creating new updateQ and simulUpdate functions
savedDers = Vector{Vector{Float64}}(undef, T)
# savedVarsQ = Vector{Vector{Float64}}(undef, T)
#= setprecision(BigFloat,80)
pp=pointer(Vector{NTuple{2,BigFloat}}(undef, 7))
respp = pointer(Vector{BigFloat}(undef, 6))
acceptedi=Vector{Vector{BigFloat}}(undef,4*O-1);acceptedj=Vector{Vector{BigFloat}}(undef,4*O-1); #inner vector always of size 2....interval...low and high...later optimize maybe
cacheRootsi=Vector{BigFloat}(undef,8*O-4);
cacheRootsj=Vector{BigFloat}(undef,8*O-4);
=#
pp=pointer(Vector{NTuple{2,Float64}}(undef, 7))
respp = pointer(Vector{Float64}(undef, 6))
acceptedi=Vector{Vector{Float64}}(undef,4*O-1);acceptedj=Vector{Vector{Float64}}(undef,4*O-1);
cacheRootsi=zeros(8*O-4) #vect of floats to hold roots for simul_analytic
cacheRootsj=zeros(8*O-4)
for i =1:4*O-1 #3
acceptedi[i]=[0.0,0.0]#zeros(2)
acceptedj[i]=[0.0,0.0]#zeros(2)
end
exactA(q,d,cacheA,1,1,initTime+1e-9)
trackSimul = Vector{Int}(undef, 1)
numSteps = Vector{Int}(undef, T)
#@show f
#######################################compute initial values##################################################
n=1
for k = 1:O # compute initial derivatives for x and q (similar to a recursive way )
n=n*k
for i = 1:T
q[i].coeffs[k] = x[i].coeffs[k] # q computed from x and it is going to be used in the next x
end
for i = 1:T
clearCache(taylorOpsCache,Val(CS),Val(O));f(i,q,t ,taylorOpsCache)
ndifferentiate!(integratorCache,taylorOpsCache[1] , k - 1)
x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2)
end
end
for i = 1:T
numSteps[i]=0
#= @timeit "savevars" =# push!(savedVars[i],x[i][0])
#push!(savedVarsQ[i],q[i][0])
push!(savedTimes[i],0.0)
quantum[i] = relQ * abs(x[i].coeffs[1]) ;quantum[i]=quantum[i] < absQ ? absQ : quantum[i];quantum[i]=quantum[i] > maxErr ? maxErr : quantum[i]
updateQ(Val(O),i,x,q,quantum,exactA,d,cacheA,dxaux,qaux,tx,tq,initTime,ft,nextStateTime)
end
# for i = 1:T
# clearCache(taylorOpsCache,Val(CS),Val(O));f(i,q,t,taylorOpsCache);
# computeDerivative(Val(O), x[i], taylorOpsCache[1])#0.0 used to be elapsed...even down below not neeeded anymore
#Liqss_reComputeNextTime(Val(O), i, initTime, nextStateTime, x, q, quantum)
# t[0]=0.1;clearCache(taylorOpsCache,Val(CS),Val(O));f(i,q,t,taylorOpsCache);# to detect if rhs contains time components
#@show taylorOpsCache
#computeNextInputTime(Val(O), i, initTime, 0.1,taylorOpsCache[1] , nextInputTime, x, quantum)#not complete, currently elapsed=0.1 is temp until fixed
#prevStepVal[i]=x[i][0]#assignXPrevStepVals(Val(O),prevStepVal,x,i)
# end
#@show x
###################################################################################################################################################################
####################################################################################################################################################################
#---------------------------------------------------------------------------------while loop-------------------------------------------------------------------------
###################################################################################################################################################################
####################################################################################################################################################################
simt = initTime ;simulStepCount=0;totalSteps=0;inputSteps=0
#simul=false
printonce=0
while simt < ft && totalSteps < 30000000
sch = updateScheduler(Val(T),nextStateTime,nextEventTime, nextInputTime)
simt = sch[2];index = sch[1]
if simt>ft
break #
end
numSteps[index]+=1;totalSteps+=1
#= if (simt>ft/2 || totalSteps==40000) && printonce==0
printonce=1
end
if printonce==1
@show "half",simt
printonce=2
end =#
t[0]=simt
##########################################state########################################
if sch[3] == :ST_STATE
xitemp=x[index][0]
elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index]
if abs(x[index].coeffs[2])>1e6 quantum[index]=10*quantum[index] end # i added this for the case a function is climbing (up/down) fast
#dirI=x[index][0]-savedVars[index][end]
dirI=x[index][0]-xitemp
for b in (jac(index) ) # update Qb : to be used to calculate exacte Aindexb...move below updateQ
elapsedq = simt - tq[b] ;
if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
firstguess=updateQ(Val(O),index,x,q,quantum,exactA,d,cacheA,dxaux,qaux,tx,tq,simt,ft,nextStateTime) ;tq[index] = simt
#----------------------------------------------------check dependecy cycles---------------------------------------------
trackSimul[1]=0
#= for i =1:5
cacheRatio[i]=0.0; cacheQ[i]=0.0;
end =#
for j in SD(index)
for b in (jac(j) ) # update Qb: to be used to calculate exacte Ajb
elapsedq = simt - tq[b] ;
if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq); tq[b]=simt end
end
cacheA[1]=0.0;exactA(q,d,cacheA,index,j,simt);aij=cacheA[1]#
cacheA[1]=0.0;exactA(q,d,cacheA,j,index,simt);aji=cacheA[1]
if j!=index && aij*aji!=0.0
if nmisCycle_and_simulUpdate(cacheRootsi,cacheRootsj,acceptedi,acceptedj,aij,aji,respp,pp,trackSimul,Val(O),index,j,dirI,firstguess,x,q,quantum,exactA,d,cacheA,dxaux,qaux,tx,tq,simt,ft)
simulStepCount+=1
clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,t,taylorOpsCache);computeDerivative(Val(O), x[index], taylorOpsCache[1])
for k in SD(j) #j influences k
if k!=index && k!=j
elapsedx = simt - tx[k]; x[k].coeffs[1] = x[k](elapsedx);tx[k] = simt
elapsedq = simt - tq[k]; if elapsedq > 0 ;integrateState(Val(O-1),q[k],elapsedq); tq[k] = simt end
for b in (jac(k) )
elapsedq = simt - tq[b]
if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(k,q,t,taylorOpsCache);computeDerivative(Val(O), x[k], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), k, simt, nextStateTime, x, q, quantum)
end#end if k!=0
end#end for k depend on j
end#end ifcycle check
# end #end if allow one simulupdate
end#end if j!=0
end#end FOR_cycle check
if trackSimul[1]!=0 #qi changed after throw
# clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,t,taylorOpsCache);computeDerivative(Val(O), x[index], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), index, simt, nextStateTime, x, q, quantum)
end
#-------------------------------------------------------------------------------------
#---------------------------------normal liqss: proceed--------------------------------
#-------------------------------------------------------------------------------------
for c in SD(index) #index influences c
elapsedx = simt - tx[c] ;
if elapsedx>0
x[c].coeffs[1] = x[c](elapsedx);
tx[c] = simt
end #
elapsedq = simt - tq[c];if elapsedq > 0 ;integrateState(Val(O-1),q[c],elapsedq);tq[c] = simt end # c never been visited
#= for b in (jac(c) ) # update other influences
elapsedq = simt - tq[b] ;if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end =#
clearCache(taylorOpsCache,Val(CS),Val(O)); f(c,q,t,taylorOpsCache);computeDerivative(Val(O), x[c], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), c, simt, nextStateTime, x, q, quantum)
end#end for SD
#= if 11.163688670259043<simt<12.165
@show simt,index,x[index],q[index],nextStateTime
end =#
##################################input########################################
elseif sch[3] == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself
#= println("nmliqss intgrator under input, index= $index, totalsteps= $totalSteps")
inputSteps+=1
elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index]
#for k = 1:O q[index].coeffs[k] = x[index].coeffs[k] end; tq[index] = simt
notneeded=updateQ(Val(O),index,x,q,quantum,exactA,cacheA,dxaux,qaux,tx,tq,simt,ft,nextStateTime) ;tq[index] = simt
for b in jac(index)
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,t,taylorOpsCache)
computeDerivative(Val(O), x[index], taylorOpsCache[1]#= ,integratorCache,elapsed =#)
reComputeNextTime(Val(O), index, simt, nextStateTime, x, q, quantum)
t[0]=simt+0.1; clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,t,taylorOpsCache);# to detect if rhs contains time components
computeNextInputTime(Val(O), index, simt, 0.1,taylorOpsCache[1] , nextInputTime, x, quantum)
for j in (SD(index))
elapsedx = simt - tx[j];
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt
quantum[j] = relQ * abs(x[j].coeffs[1]) ;quantum[j]=quantum[j] < absQ ? absQ : quantum[j];quantum[j]=quantum[j] > maxErr ? maxErr : quantum[j]
end
elapsedq = simt - tq[j];if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt end#q needs to be updated here for recomputeNext
for b in jac(j)
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(j,q,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1]#= ,integratorCache,elapsed =#)
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for =#
#= for i = 1:length(SZ[index])
j = SZ[index][i]
if j != 0
for b = 1:T # elapsed update all other vars that this derj depends upon.
if zc_SimpleJac[j][b] != 0
elapsedx = simt - tx[b];if elapsedx>0 integrateState(Val(O),x[b],integratorCache,elapsedx);tx[b]=simt end
# elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
end
#= clearCache(taylorOpsCache,Val(CS),Val(O))#normally and later i should update x,q (integrate q=q+e derQ for higher orders)
computeNextEventTime(j,zcf[j](x,d,t,taylorOpsCache),oldsignValue,simt, nextEventTime, quantum)#,maxIterer) =#
clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,j,-1,x,d,t,taylorOpsCache)
computeNextEventTime(j,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum)
end
end =#
#################################################################event########################################
end#end state/input/event
# push!(savedVars[index],x[index][0])
push!(savedVars[index],(x[index][0]+q[index][0])/2)
push!(savedTimes[index],simt)
# push!(savedVarsQ[index],q[index][0])
#= for i=1:T
push!(savedVars[i],x[i][0])
push!(savedTimes[i],simt)
# push!(savedVarsQ[i],q[i][0])
end =#
#= if index==1 && 0.042<simt<0.043
@show x
@show q
end =#
end#end while
createSol(Val(T),Val(O),savedTimes,savedVars, "nmliqss$O",string(odep.prname),absQ,totalSteps,simulStepCount,0,numSteps,ft)
# change this to function /constrcutor...remember it is bad to access structs (objects) directly
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 25822 | #using TimerOutputs
function integrate(Al::QSSAlgorithm{:nmliqss,O},CommonqssData::CommonQSS_data{Z},liqssdata::LiQSS_data{O,false},specialLiqssData::SpecialLiqssQSS_data, odep::NLODEProblem{PRTYPE,T,Z,D,CS}) where {PRTYPE,O,T,Z,D,CS}
if VERBOSE println("begining of intgrate dummy function") end
end
function integrate(Al::QSSAlgorithm{:nmliqss,O},CommonqssData::CommonQSS_data{Z},liqssdata::LiQSS_data{O,false},specialLiqssData::SpecialLiqssQSS_data, odep::NLODEProblem{PRTYPE,T,Z,D,CS},f::Function,jac::Function,SD::Function,exactA::Function) where {PRTYPE,O,T,Z,D,CS}
if VERBOSE println("begining of intgrate function") end
cacheA=specialLiqssData.cacheA
ft = CommonqssData.finalTime;initTime = CommonqssData.initialTime;relQ = CommonqssData.dQrel;absQ = CommonqssData.dQmin;maxErr=CommonqssData.maxErr;
savetimeincrement=CommonqssData.savetimeincrement;savetime = savetimeincrement
quantum = CommonqssData.quantum;nextStateTime = CommonqssData.nextStateTime;nextEventTime = CommonqssData.nextEventTime;nextInputTime = CommonqssData.nextInputTime
tx = CommonqssData.tx;tq = CommonqssData.tq;x = CommonqssData.x;q = CommonqssData.q;t=CommonqssData.t
savedVars=CommonqssData.savedVars;
savedTimes=CommonqssData.savedTimes;integratorCache=CommonqssData.integratorCache;taylorOpsCache=CommonqssData.taylorOpsCache;#cacheSize=odep.cacheSize
#prevStepVal = specialLiqssData.prevStepVal
#*********************************problem info*****************************************
d = CommonqssData.d
#= exactA=odep.exactJac
f=odep.eqs
if VERBOSE println("after function declare") end =#
zc_SimpleJac=odep.ZCjac
HZ=odep.HZ
HD=odep.HD
SZ=odep.SZ
evDep = odep.eventDependencies
if DEBUG2 @show HD,HZ end
qaux=liqssdata.qaux;dxaux=liqssdata.dxaux#= olddx=liqssdata.olddx; ; olddxSpec=liqssdata.olddxSpec =#
#savedDers = Vector{Vector{Float64}}(undef, T)
# savedVarsQ = Vector{Vector{Float64}}(undef, T)
#= setprecision(BigFloat,80)
pp=pointer(Vector{NTuple{2,BigFloat}}(undef, 7))
respp = pointer(Vector{BigFloat}(undef, 6))
acceptedi=Vector{Vector{BigFloat}}(undef,4*O-1);acceptedj=Vector{Vector{BigFloat}}(undef,4*O-1); #inner vector always of size 2....interval...low and high...later optimize maybe
cacheRootsi=Vector{BigFloat}(undef,8*O-4);
cacheRootsj=Vector{BigFloat}(undef,8*O-4); =#
pp=pointer(Vector{NTuple{2,Float64}}(undef, 7))
respp = pointer(Vector{Float64}(undef, 6))
acceptedi=Vector{Vector{Float64}}(undef,4*O-1);acceptedj=Vector{Vector{Float64}}(undef,4*O-1);
cacheRootsi=zeros(8*O-4) #vect of floats to hold roots for simul_analytic
cacheRootsj=zeros(8*O-4)
for i =1:4*O-1 #3
acceptedi[i]=[0.0,0.0]#zeros(2)
acceptedj[i]=[0.0,0.0]#zeros(2)
end
#@show exactA
exactA(q,d,cacheA,1,1,initTime+1e-9)
#@show f
f(1,-1,-1,q,d, t ,taylorOpsCache)
trackSimul = Vector{Int}(undef, 1)
# cacheRatio=zeros(5);cacheQ=zeros(5)
#********************************helper values*******************************
oldsignValue = MMatrix{Z,2}(zeros(Z*2)) #usedto track if zc changed sign; each zc has a value and a sign
numSteps = Vector{Int}(undef, T)
#######################################compute initial values##################################################
if VERBOSE println("before x init") end
n=1
for k = 1:O # compute initial derivatives for x and q (similar to a recursive way )
n=n*k
for i = 1:T q[i].coeffs[k] = x[i].coeffs[k] end # q computed from x and it is going to be used in the next x
for i = 1:T
clearCache(taylorOpsCache,Val(CS),Val(O));f(i,-1,-1,q,d, t ,taylorOpsCache)
ndifferentiate!(integratorCache,taylorOpsCache[1] , k - 1)
x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2)
end
end
if VERBOSE println("after init") end
for i = 1:T
numSteps[i]=0
#savedDers[i]=Vector{Float64}()
push!(savedVars[i],x[i][0])
# push!(savedDers[i],x[i][1])
push!(savedTimes[i],0.0)
quantum[i] = relQ * abs(x[i].coeffs[1]) ;quantum[i]=quantum[i] < absQ ? absQ : quantum[i];quantum[i]=quantum[i] > maxErr ? maxErr : quantum[i]
updateQ(Val(O),i,x,q,quantum,exactA,d,cacheA,dxaux,qaux,tx,tq,initTime+1e-12,ft,nextStateTime) #1e-9 exactAfunc contains 1/t
end
if VERBOSE println("after initial updateQ") end
for i=1:Z
clearCache(taylorOpsCache,Val(CS),Val(O)); f(-1,i,-1,x,d,t,taylorOpsCache)
oldsignValue[i,2]=taylorOpsCache[1][0] #value
oldsignValue[i,1]=sign(taylorOpsCache[1][0]) #sign modify
computeNextEventTime(Val(O),i,taylorOpsCache[1],oldsignValue,initTime, nextEventTime, quantum,absQ)
end
###################################################################################################################################################################
####################################################################################################################################################################
#---------------------------------------------------------------------------------while loop-------------------------------------------------------------------------
###################################################################################################################################################################
####################################################################################################################################################################
simt = initTime ;totalSteps=0;prevStepTime=initTime;modifiedIndex=0; countEvents=0;inputstep=0;statestep=0;simulStepCount=0
ft<savetime && error("ft<savetime")
if VERBOSE println("start integration") end
while simt< ft && totalSteps < 50000000
sch = updateScheduler(Val(T),nextStateTime,nextEventTime, nextInputTime)
simt = sch[2];index = sch[1];stepType=sch[3]
# @timeit "saveLast"
if simt>ft
#saveLast!(Val(T),Val(O),savedVars, savedTimes,saveVarsHelper,ft,prevStepTime, x)
break ###################################################break##########################################
end
totalSteps+=1
t[0]=simt
DEBUG_time=DEBUG && #= (29750 <=totalSteps<=29750) =# #= (0.0003557 <=simt<=0.0003559 ) =# simt==1.0323797751288692e-9
##########################################state########################################
if stepType == :ST_STATE
statestep+=1
if DEBUG_time #&& (index!=13 && index!=15)
println("at simt=$simt x $index at begining of state step = $(x)")
println("-------------q begining of state step = $q")
@show totalSteps
end
xitemp=x[index][0]
numSteps[index]+=1;
elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt ;
dirI=x[index][0]-xitemp
#= if abs(dirI)>3*quantum[index]
x[index][0]=xitemp+ 3*quantum[index] *sign(dirI)
println("at start of state step, x moved more than 2 deltas")
end # this is a rare case where dxi gets changed a lot by an event =#
quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index]
#= if abs(x[index].coeffs[2])>1e9
quantum[index]=10*quantum[index]
@show simt, index,x[index]
end =# # i added this for the case a function is climbing (up/down) fast
for b in (jac(index) ) # update Qb : to be used to calculate exacte Aindexb
elapsedq = simt - tq[b] ;
if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
firstguess=updateQ(Val(O),index,x,q,quantum,exactA,d,cacheA,dxaux,qaux,tx,tq,simt,ft,nextStateTime) ;tq[index] = simt
#----------------------------------------------------check dependecy cycles---------------------------------------------
trackSimul[1]=0
#= for i =1:5
cacheRatio[i]=0.0; cacheQ[i]=0.0;
end =#
for j in SD(index)
for b in (jac(j) ) # update Qb: to be used to calculate exacte Ajb
elapsedq = simt - tq[b] ;
if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq); tq[b]=simt end
end
cacheA[1]=0.0; exactA(q,d,cacheA,index,j,simt);aij=cacheA[1]# can be passed to simul so that i dont call exactfunc again
cacheA[1]=0.0;exactA(q,d,cacheA,j,index,simt);aji=cacheA[1]
if j!=index && aij*aji!=0.0
#prvStepValj= savedVars[j][end]#getPrevStepVal(prevStepVal,j)
#= if simt==0.0005977635736228422
@show j,aij,aji
end =#
#= for i =1:3
cacherealPosi[i][1]=0.0; cacherealPosi[i][2]=0.0
cacherealPosj[i][1]=0.0; cacherealPosj[i][2]=0.0
end =#
# @show aij,aji
#= test=false
if test =#
if nmisCycle_and_simulUpdate(cacheRootsi,cacheRootsj,acceptedi,acceptedj,aij,aji,respp,pp,trackSimul,Val(O),index,j,dirI,firstguess,x,q,quantum,exactA,d,cacheA,dxaux,qaux,tx,tq,simt,ft)
simulStepCount+=1
clearCache(taylorOpsCache,Val(CS),Val(O));f(index,-1,-1,q,d,t,taylorOpsCache);computeDerivative(Val(O), x[index], taylorOpsCache[1])
# clearCache(taylorOpsCache,Val(CS),Val(O));f(j,q,d,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1])
# Liqss_reComputeNextTime(Val(O), index, simt, nextStateTime, x, q, quantum)
# Liqss_reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
for k in SD(j) #j influences k
if k!=index && k!=j
elapsedx = simt - tx[k]; x[k].coeffs[1] = x[k](elapsedx);tx[k] = simt
elapsedq = simt - tq[k]; if elapsedq > 0 ;integrateState(Val(O-1),q[k],elapsedq); tq[k] = simt end
for b in (jac(k) )
elapsedq = simt - tq[b]
if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(k,-1,-1,q,d,t,taylorOpsCache);computeDerivative(Val(O), x[k], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), k, simt, nextStateTime, x, q, quantum)
end#end if k!=0
end#end for k depend on j
for k in (SZ[j]) # qj changed, so zcf should be checked
for b in zc_SimpleJac[k] # elapsed update all other vars that this derj depends upon.
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
#elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,k,-1,q,d,t,taylorOpsCache) # run ZCF--------
computeNextEventTime(Val(O),k,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ)
end#end for SZ
end#end ifcycle check
# end #end if allow one simulupdate
end#end if j!=0
end#end FOR_cycle check
if trackSimul[1]!=0 #qi changed after throw
# clearCache(taylorOpsCache,Val(CS),Val(O));f(index,q,d,t,taylorOpsCache);computeDerivative(Val(O), x[index], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), index, simt, nextStateTime, x, q, quantum)
end
#-------------------------------------------------------------------------------------
#---------------------------------normal liqss: proceed--------------------------------
#-------------------------------------------------------------------------------------
#= if simt==0.0007352244633292483
println("before normal dependency")
@show x,q
@show tx,tq
end =#
for c in SD(index) #index influences c
elapsedx = simt - tx[c] ;
if elapsedx>0
x[c].coeffs[1] = x[c](elapsedx);
# if 0.0003>simt>0.00029 @show index, c,simt, tx[c], x[c].coeffs[1] end
tx[c] = simt
end #
elapsedq = simt - tq[c];if elapsedq > 0 ;integrateState(Val(O-1),q[c],elapsedq);tq[c] = simt end # c never been visited
#= for b in (jac(c) ) # update other influences
elapsedq = simt - tq[b] ;if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end =#
clearCache(taylorOpsCache,Val(CS),Val(O)); f(c,-1,-1,q,d,t,taylorOpsCache);computeDerivative(Val(O), x[c], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), c, simt, nextStateTime, x, q, quantum)
end#end for SD
#= if 0.0003>simt>0.00029
println("---after normal SD---------------", q,x,totalSteps)
end =#
for j in (SZ[index])
for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon.
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
#elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,j,-1,q,d,t,taylorOpsCache) # run ZCF--------
computeNextEventTime(Val(O),j,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ)
end#end for SZ
if DEBUG_time #&& (index!=13 && index!=15)
println("at simt=$simt x $index at end of state step = $(x)")
println("-------------q end of state step = $q")
@show totalSteps
end
#= if DEBUG_time #&& (index==3 || index==6)
println("========end state=======")
@show index,simt
@show x[]
# @show nextStateTime,quantum
end =#
##################################input########################################
elseif stepType == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself
inputstep+=1
#= if VERBOSE println("nmliqss discreteintgrator under input, index= $index, totalsteps= $totalSteps") end
elapsed = simt - tx[index];integrateState(Val(O),x[index],elapsed);tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1]) ;quantum[index]=quantum[index] < absQ ? absQ : quantum[index];quantum[index]=quantum[index] > maxErr ? maxErr : quantum[index]
for k = 1:O q[index].coeffs[k] = x[index].coeffs[k] end; tq[index] = simt
for b in jac(index)
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(index,-1,-1,q,d,t,taylorOpsCache)
computeNextInputTime(Val(O), index, simt, elapsed,taylorOpsCache[1] , nextInputTime, x, quantum)
computeDerivative(Val(O), x[index], taylorOpsCache[1])
for j in(SD(index))
elapsedx = simt - tx[j];
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt
# quantum[j] = relQ * abs(x[j].coeffs[1]) ;quantum[j]=quantum[j] < absQ ? absQ : quantum[j];quantum[j]=quantum[j] > maxErr ? maxErr : quantum[j]
end
elapsedq = simt - tq[j];if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt end#q needs to be updated here for recomputeNext
# elapsed update all other vars that this derj depends upon.
for b in jac(j)
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(j,-1,-1,q,d,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for
for j in (SZ[index])
for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon.
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
# elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
#= clearCache(taylorOpsCache,Val(CS),Val(O))#normally and later i should update x,q (integrate q=q+e derQ for higher orders)
computeNextEventTime(Val(O),j,zcf[j](x,d,t,taylorOpsCache),oldsignValue,simt, nextEventTime, quantum)#,maxIterer) =#
clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,j,-1,x,d,t,taylorOpsCache)
computeNextEventTime(Val(O),j,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum)
end =#
#################################################################event########################################
else
if DEBUG_time
println("x at start of event simt=$simt index=$index")
println("-------------x start of event = $x")
println("-------------q start of event = $q")
#@show index,d
end
for b in zc_SimpleJac[index] # elapsed update all other vars that this zc depends upon.
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
# modifiedIndex=0#first we have a zc happened which corresponds to nexteventtime and index (one of zc) but we want also the sign in O to know ev+ or ev-
clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,index,-1,q,d,t,taylorOpsCache) # run ZCF--------
if DEBUG_time
@show index,oldsignValue[index,2],taylorOpsCache[1][0]
end
if oldsignValue[index,2]*taylorOpsCache[1][0]>=0
if abs(taylorOpsCache[1][0])>1e-9*absQ # if both have same sign and zcf is not very small: zc=1e-9*absQ is allowed as an event
computeNextEventTime(Val(O),index,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ)
# @show index,countEvents
# @show oldsignValue[index,2],taylorOpsCache[1][0]
if DEBUG_time println("wrong estimation of event at $simt") end
continue
end
end
if abs(oldsignValue[index,2]) <=1e-9*absQ #earlier zc=1e-9*absQ was considered event , so now it should be prevented from passing
nextEventTime[index]=Inf # at this instant next zc will be triggered now, and this will lead to infinite events, so cannot computenextevent here
continue
end
# needSaveEvent=true
if taylorOpsCache[1][0]>oldsignValue[index,2] #scheduled rise
modifiedIndex=2*index-1
elseif taylorOpsCache[1][0]<oldsignValue[index,2] #scheduled drop
modifiedIndex=2*index
else # == ( zcf==oldZCF)
if DEBUG_time println("this should never be reached ZCF==oldZCF at $simt cuz small old not allowed and large zc not allowed!!") end
computeNextEventTime(Val(O),index,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ)
continue
end
countEvents+=1
oldsignValue[index,2]=taylorOpsCache[1][0]
oldsignValue[index,1]=sign(taylorOpsCache[1][0])
#= if DEBUG_time
@show modifiedIndex,x
@show q
end =#
for b in evDep[modifiedIndex].evContRHS
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
f(-1,-1,modifiedIndex,x,d,t,taylorOpsCache)# execute event----------------no need to clear cache; events touch vectors directly
if VERBOSE
@show d
end
for i in evDep[modifiedIndex].evCont
#------------event influences a Continete var: ...here update quantum and q and computenext
#= if DEBUG_time
println("q begin evcont simt=$simt q2=$(q[2])")
@show nextStateTime[2],quantum[2]
end =#
quantum[i] = relQ * abs(x[i].coeffs[1]) ;quantum[i]=quantum[i] < absQ ? absQ : quantum[i];quantum[i]=quantum[i] > maxErr ? maxErr : quantum[i]
# q[i][0]=x[i][0]; # for liqss updateQ?
#= if abs(x[i].coeffs[2])>1e9
# @show quantum[i]
quantum[i]=10*quantum[i]
end =#
firstguess=updateQ(Val(O),i,x,q,quantum,exactA,d,cacheA,dxaux,qaux,tx,tq,simt,ft,nextStateTime)
# computeNextTime(Val(O), i, simt, nextStateTime, x, quantum)
tx[i] = simt;tq[i] = simt
Liqss_reComputeNextTime(Val(O), i, simt, nextStateTime, x, q, quantum)
#= if DEBUG_time
println("x end evcont simt=$simt x2=$(x[2])")
println("q end evcont simt=$simt q2=$(q[2])")
@show countEvents,totalSteps,statestep
@show nextStateTime[2],quantum[2]
end =#
end
#= if VERBOSE
@show x,q,nextStateTime
end =#
# nextEventTime[index]=Inf #investigate more
computeNextEventTime(Val(O),index,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ) #update zcf before thiscatch in qss quantizer to avoid infinite events
for j in (HD[modifiedIndex]) # care about dependency to this event only
elapsedx = simt - tx[j];if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx);tx[j] = simt;#= @show j,x[j] =# end
elapsedq = simt - tq[j];if elapsedq > 0 integrateState(Val(O-1),q[j],elapsedq);tq[j] = simt;#= @show q[j] =# end#q needs to be updated here for recomputeNext
for b = 1:T # elapsed update all other vars that this derj depends upon.
if b in jac(j)
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt;#= @show q[b] =# end
end
end
if DEBUG_time
println("q $j after intgratestate")
@show x[j],q[j]
end
clearCache(taylorOpsCache,Val(CS),Val(O));f(j,-1,-1,q,d,t,taylorOpsCache);computeDerivative(Val(O), x[j], taylorOpsCache[1])
#firstguess=updateQ(Val(O),j,x,q,quantum,exactA,d,cacheA,dxaux,qaux,tx,tq,simt,ft,nextStateTime)
Liqss_reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end
for j in (HZ[modifiedIndex])
for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon.
#elapsedx = simt - tx[b];if elapsedx>0 integrateState(Val(O),x[b],elapsedx);tx[b]=simt end
elapsedq = simt - tq[b];if elapsedq>0 integrateState(Val(O-1),q[b],elapsedq);tq[b]=simt end
end
#= clearCache(taylorOpsCache,Val(CS),Val(O)) #normally and later i should update q (integrate q=q+e derQ for higher orders)
computeNextEventTime(Val(O),j,zcf[j](x,d,t,taylorOpsCache),oldsignValue,simt, nextEventTime, quantum)#,maxIterer) =#
clearCache(taylorOpsCache,Val(CS),Val(O));f(-1,j,-1,q,d,t,taylorOpsCache) # run ZCF--------
if VERBOSE @show j,oldsignValue[j,2],taylorOpsCache[1][0] end
computeNextEventTime(Val(O),j,taylorOpsCache[1],oldsignValue,simt, nextEventTime, quantum,absQ)
# if 0.022>simt > 0.018 println("$index $j at simt=$simt nexteventtime from HZ= ",nextEventTime) end
end
if DEBUG_time
# println("x at end of event simt=$simt x=$(x)")
println("q at end of event simt=$simt q2=$(q)")
@show countEvents,totalSteps,statestep
# @show nextStateTime,quantum
end
#= if 9.236846540089048e-5<=simt<9.237519926276279e-5
println("-------------end of event------------")
@show simt,nextStateTime[5]
@show x[5],q[5],quantum[5]
end =#
end#end state/input/event
#for i=1:T
# if simt > savetime #limit saveat
savetime = simt+savetimeincrement
if stepType != :ST_EVENT
push!(savedVars[index],x[index][0])
#push!(savedDers[index],x[index][0])
push!(savedTimes[index],simt)
#= for i =1:T
push!(savedVars[i],x[i][0])
# push!(savedDers[i],x[i][1])
push!(savedTimes[i],simt)
end =#
else
#countEvents+=1
# if 1e-3<simt<1e-2 || 1e-5<simt<1e-4
for j in (HD[modifiedIndex])
push!(savedVars[j],x[j][0])
#push!(savedDers[j],x[j][1])
push!(savedTimes[j],simt)
#= if simt==0.00035
@show j,x[j][0]
end =#
end
# end
end
# end
#push!(savedVarsQ[i],q[i][0])
prevStepTime=simt
# end
end#end while
#@show countEvents,inputstep,statestep,simulStepCount
#@show savedVars
#createSol(Val(T),Val(O),savedTimes,savedVars, "qss$O",string(nameof(f)),absQ,totalSteps,0)#0 I track simulSteps
#createSol(Val(T),Val(O),savedTimes,savedVars, "nmLiqss$O",string(odep.prname),absQ,totalSteps,simulStepCount,countEvents,numSteps,ft)
createSol(Val(T),Val(O),savedTimes,savedVars#= ,savedDers =#, "nmLiqss$O",string(odep.prname),absQ,totalSteps,simulStepCount,countEvents,numSteps,ft)
end#end integrate | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 16568 | #iters
#= function updateQ(::Val{1},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64}#= ,av::Vector{Vector{Float64}} =#,exactA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})
# a=av[i][i]
cacheA[1]=0.0;exactA(qv,d,cacheA,i,i,simt)
a=cacheA[1]
#= if i==1
if abs(a+1.1)>1e-3
@show i,a
end
else
if abs(a+20.0)>1e-3
@show i,a
end
end =#
q=qv[i][0];x=xv[i][0];x1=xv[i][1];
qaux[i][1]=q
#= olddx[i][1]=x1 =#
u=x1-a*q
#uv[i][i][1]=u
dx=x1
dxaux[i][1]=x1
h=0.0
Δ=quantum[i]
debugH=4.3;debugL=14.1
if a !=0.0
if dx==0.0
dx=u+(q)*a
if dx==0.0
dx=1e-26
end
end
#for order1 finding h is easy but for higher orders iterations are cheaper than finding exact h using a quadratic,cubic...
#exacte for order1: h=-2Δ/(u+xa-2aΔ) or h=2Δ/(u+xa+2aΔ)
h = ft-simt
q = (x + h * u) /(1 - h * a)
if (abs(q - x) > 1*quantum[i]) # removing this did nothing...check @btime later
h = (abs( quantum[i] / dx));
q= (x + h * u) /(1 - h * a)
end
while (abs(q - x) > 1*quantum[i])
h = h * 0.99*(quantum[i] / abs(q - x));
q= (x + h * u) /(1 - h * a)
end
#= α=-(a*x+u)/a
h1denom=a*(x+Δ)+u;h2denom=a*(x-Δ)+u
if h1denom==0.0 h1denom=1e-26 end
if h2denom==0.0 h2denom=1e-26 end
h1=Δ/h1denom
h2=-Δ/h2denom
if a<0
if α>Δ
h=h1;q=x+Δ
elseif α<-Δ
h=h2;q=x-Δ
else
h=max(ft-simt,-1/a)
q=(x+h*u)/(1-h*a)#1-h*a non neg because h > -1/a > 1/a
end
else #a>0
if α>Δ
h=h2;q=x-Δ
elseif α<-Δ
h=h1;q=x+Δ
else
if a*x+u>0
h=max(ft-simt,-(a*x+u+a*Δ)/(a*(a*x+u-a*Δ)))# midpoint between asymptote and delta
else
h=max(ft-simt,-(a*x+u-a*Δ)/(a*(a*x+u+a*Δ)))
end
q=(x+h*u)/(1-h*a)#1-h*a non neg because values of h from graph show that h >1/a
end
end =#
else
dx=u
if dx>0.0
q=x+quantum[i]#
else
q=x-quantum[i]
end
if dx!=0
h=(abs(quantum[i]/dx))
else
h=Inf
end
end
qv[i][0]=q
# println("inside single updateQ: q & qaux[$i][1]= ",q," ; ",qaux[i][1])
nextStateTime[i]=simt+h
return h
end =#
#iters from 0
#= function updateQ(::Val{1},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64}#= ,av::Vector{Vector{Float64}} =#,exactA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})
# a=av[i][i]
cacheA[1]=0.0;exactA(qv,d,cacheA,i,i,simt)
a=cacheA[1]
#= if i==1
if abs(a+1.1)>1e-3
@show i,a
end
else
if abs(a+20.0)>1e-3
@show i,a
end
end =#
q=qv[i][0];x=xv[i][0];x1=xv[i][1];
qaux[i][1]=q
#= olddx[i][1]=x1 =#
u=x1-a*q
#uv[i][i][1]=u
dx=x1
dxaux[i][1]=x1
h=0.0
Δ=quantum[i]
debugH=4.3;debugL=14.1
if a !=0.0
if dx==0.0
dx=u+(q)*a
if dx==0.0
dx=1e-26
end
end
#for order1 finding h is easy but for higher orders iterations are cheaper than finding exact h using a quadratic,cubic...
#exacte for order1: h=-2Δ/(u+xa-2aΔ) or h=2Δ/(u+xa+2aΔ)
h = 1e-8
h_=h
# lastH=h
q = (x + h * u) /(1 - h * a)
#= if (abs(q - x) > 1*quantum[i]) # removing this did nothing...check @btime later
h = (abs( quantum[i] / dx));
q= (x + h * u) /(1 - h * a)
end =#
maxIter=1000
while (abs(q - x) < 1*quantum[i]) && (maxIter>0)
maxIter-=1
h_=h
h = h * 1.001*(quantum[i] / abs(q - x));
q= (x + h * u) /(1 - h * a)
if maxIter < 1 println("maxiter of updateQ = ",maxIter) end
# lastH=h
end
if (abs(q - x) > 2*quantum[i]) # if h takes too much outside, go back to prevoius h
h=h_
q= (x + h * u) /(1 - h * a)
end
# Qlast=(x + lastH * u) /(1 - lastH * a)
#= k = ft-simt
qq = (x + k * u) /(1 - k * a)
if (abs(qq - x) > 1*quantum[i]) # removing this did nothing...check @btime later
k = (abs( quantum[i] / dx));
qq= (x + k * u) /(1 - k * a)
end
while (abs(qq - x) > 1*quantum[i])
k = k * 0.99*(quantum[i] / abs(qq - x));
qq= (x + k * u) /(1 - k * a)
end
if abs(h-k)>1e-8
@show h,k,q-x,qq-x,quantum[i]
end =#
else
dx=u
if dx>0.0
q=x+quantum[i]#
else
q=x-quantum[i]
end
if dx!=0
h=(abs(quantum[i]/dx))
else
h=Inf
end
end
qv[i][0]=q
# println("inside single updateQ: q & qaux[$i][1]= ",q," ; ",qaux[i][1])
nextStateTime[i]=simt+h
return h
end =#
#analytic favor q-x
function updateQ(::Val{1},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64}#= ,av::Vector{Vector{Float64}} =#,exactA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})
cacheA[1]=0.0;exactA(qv,d,cacheA,i,i,simt);a=cacheA[1]
q=qv[i][0];x=xv[i][0];x1=xv[i][1];
qaux[i][1]=q
u=x1-a*q
dxaux[i][1]=x1
h=0.0
Δ=quantum[i]
if a !=0.0
α=-(a*x+u)/a
#= h1denom=a*(x+Δ)+u;h2denom=a*(x-Δ)+u
if h1denom==0.0 h1denom=1e-26 end
if h2denom==0.0 h2denom=1e-26 end
h1=Δ/h1denom
h2=-Δ/h2denom =#
h1denom=a*(x+Δ)+u;h2denom=a*(x-Δ)+u
#= if h1denom==0.0 h1denom=1e-26 end
if h2denom==0.0 h2denom=1e-26 end =#
h1=Δ/h1denom # h1denom ==0 only when case α==Δ h1 and h2 not used h=Inf. ..
h2=-Δ/h2denom #idem
if a<0
if α>Δ
h=h1;q=x+Δ
elseif α<-Δ
h=h2;q=x-Δ
else
h=Inf
q=-u/a
end
else #a>0
if α>Δ
h=h2;q=x-Δ
elseif α<-Δ
h=h1;q=x+Δ
else
if a*x+u>0
q=x-Δ #
h=h2
else
q=x+Δ
h=h1
end
end
end
else #a=0
if x1>0.0
q=x+Δ #
else
q=x-Δ
end
if x1!=0
h=(abs(Δ /x1))
else
h=Inf
end
end
qv[i][0]=q
nextStateTime[i]=simt+h
return h
end
#analytic favor q-x but care about h large
#= function updateQ(::Val{1},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64}#= ,av::Vector{Vector{Float64}} =#,exactA::Function,cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})
# a=av[i][i]
cacheA[1]=0.0;exactA(qv,cacheA,i,i)
a=cacheA[1]
#= if i==1
if abs(a+1.1)>1e-3
@show i,a
end
else
if abs(a+20.0)>1e-3
@show i,a
end
end =#
q=qv[i][0];x=xv[i][0];x1=xv[i][1];
qaux[i][1]=q
#= olddx[i][1]=x1 =#
u=x1-a*q
#uv[i][i][1]=u
dx=x1
dxaux[i][1]=x1
h=0.0
Δ=quantum[i]
if a !=0.0
if dx==0.0
dx=u+(q)*a
if dx==0.0
dx=1e-26
end
end
α=-(a*x+u)/a
h1denom=a*(x+Δ)+u;h2denom=a*(x-Δ)+u
if h1denom==0.0 h1denom=1e-26 end
if h2denom==0.0 h2denom=1e-26 end
h1=Δ/h1denom
h2=-Δ/h2denom
if a<0
if α>Δ
h=h1;q=x+Δ
elseif α<-Δ
h=h2;q=x-Δ
else
#= h=Inf
if a*x+u>0
q=x+α
else
q=x+α
end =#
#= h=-1/a
q=(x+h*u)/(1-h*a) =#
h=max(ft-simt,-1/a)
q=(x+h*u)/(1-h*a)#1-h*a non neg because a<0
end
else #a>0
if α>Δ
h=h2;q=x-Δ
elseif α<-Δ
h=h1;q=x+Δ
else
#= h=Inf
if a*x+u>0
q=x+α
else
q=x+α
end =#
#= if a*x+u>0
h=h2;q=x-Δ
else
h=h1;q=x+Δ
end =#
#= h=1/a+ft-simt # i have if simt>=ft break in intgrator
q=(x+h*u)/(1-h*a) =#
#= if abs(α)<Δ/2
h=2/a
q=x+2α
else
h=3/a
q=(x+h*u)/(1-h*a)
end =#
if a*x+u>0
h=max(ft-simt,-(a*x+u+a*Δ)/(a*(a*x+u-a*Δ)))# midpoint between asymptote and delta
#= q=x-Δ #
h=h2 =#
else
h=max(ft-simt,-(a*x+u-a*Δ)/(a*(a*x+u+a*Δ)))
#= q=x+Δ
h=h1 =#
end
q=(x+h*u)/(1-h*a)#1-h*a non neg because values of h from graph show that h >1/a
end
end
else
dx=u
if dx>0.0
q=x+quantum[i]#
else
q=x-quantum[i]
end
if dx!=0
h=(abs(quantum[i]/dx))
else
h=Inf
end
end
qv[i][0]=q
#= if simt>=0.22816661756287676
dxithr=a*q+u
@show dxithr
end =#
# println("inside single updateQ: q & qaux[$i][1]= ",q," ; ",qaux[i][1])
nextStateTime[i]=simt+h
return h
end =#
#=
function updateQ(::Val{1},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64}#= ,av::Vector{Vector{Float64}} =#,exactA::Function,cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})
# a=av[i][i]
cacheA[1]=0.0;exactA(qv,cacheA,i,i)
a=cacheA[1]
quan=quantum[i]
q=qv[i][0];x=xv[i][0];x1=xv[i][1];
qaux[i][1]=q
# olddx[i][1]=x1
u=x1-a*q
#uv[i][i][1]=u
dx=x1
dxaux[i][1]=x1
h=0.0
if a !=0.0
if dx==0.0
dx=u+(q)*a
if dx==0.0
dx=1e-26
end
end
#for order1 finding h is easy but for higher orders iterations are cheaper than finding exact h using a quadratic,cubic...
#exacte for order1: h=-2Δ/(u+xa-2aΔ) or h=2Δ/(u+xa+2aΔ)
h = ft-simt
q = (x + h * u) /(1 - h * a)
if (abs(q - x) > 1*quan) # removing this did nothing...check @btime later
h = (abs( quan / dx));
q= (x + h * u) /(1 - h * a)
end
while (abs(q - x) > 1*quan)
h = h * 0.99*(quan / abs(q - x));
q= (x + h * u) /(1 - h * a)
end
else
dx=u
if dx>0.0
q=x+quan#
else
q=x-quan
end
if dx!=0
h=(abs(quan/dx))
else
h=Inf
end
end
qv[i][0]=q
# println("inside single updateQ: q & qaux[$i][1]= ",q," ; ",qaux[i][1])
nextStateTime[i]=simt+h
return h
end =#
function Liqss_reComputeNextTime(::Val{1}, i::Int, simt::Float64, nextStateTime::Vector{Float64}, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64}#= ,a::Vector{Vector{Float64}} =#)
dt=0.0; q=qv[i][0];x=xv[i][0];x1=xv[i][1]
if abs(q-x) >= 2*quantum[i] # this happened when var i and j s turns are now...var i depends on j, j is asked here for next time...or if you want to increase quant*10 later it can be put back to normal and q & x are spread out by 10quan
nextStateTime[i] = simt+1e-12
@show simt,i
else
if x1 !=0.0 #&& abs(q-x)>quantum[i]/10
dt=(q-x)/x1
if dt>0.0
nextStateTime[i]=simt+dt# later guard against very small dt
elseif dt<0.0
if x1>0.0
nextStateTime[i]=simt+(q-x+2*quantum[i])/x1
else
nextStateTime[i]=simt+(q-x-2*quantum[i])/x1
end
end
else
nextStateTime[i]=Inf
end
end
if nextStateTime[i]<=simt
nextStateTime[i]=simt+Inf#1e-12
end
# this is coming from the fact that a variable can reach 2quan distance when it is not its turn, then computation above gives next=simt+(p-p)/dx...p-p should be zero but it can be very small negative
end
#= function updateQ(::Val{1},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64}#= ,av::Vector{Vector{Float64}} =#,exactA::Function,cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})
# a=av[i][i]
cacheA[1]=0.0;exactA(qv,cacheA,i,i)
a=cacheA[1]
#= if i==1
if abs(a+1.1)>1e-3
@show i,a
end
else
if abs(a+20.0)>1e-3
@show i,a
end
end =#
q=qv[i][0];x=xv[i][0];x1=xv[i][1];
qaux[i][1]=q
#= olddx[i][1]=x1 =#
u=x1-a*q
#uv[i][i][1]=u
dx=x1
dxaux[i][1]=x1
h=0.0
if a !=0.0
if dx==0.0
dx=u+(q)*a
if dx==0.0
dx=1e-26
end
end
#for order1 finding h is easy but for higher orders iterations are cheaper than finding exact h using a quadratic,cubic...
#exacte for order1: h=-2Δ/(u+xa-2aΔ) or h=2Δ/(u+xa+2aΔ)
#= h = (ft+100.0-simt)
q = (x + h * u) /(1 - h * a)
if (abs(q - x) > quantum[i]) =#
h1=-1.0
h0 = (ft-simt)
q0 = (x + h0 * u) /(1 - h0 * a)
if (abs(q - x) < quantum[i])
h1=h0
end
# end
#= if (abs(q - x) > 2*quantum[i]) # removing this did nothing...check @btime later
h = (abs( quantum[i] / dx));
q= (x + h * u) /(1 - h * a)
end =#
#= while (abs(q - x) > 2*quantum[i])
h = h * 1.98*(quantum[i] / abs(q - x));
q= (x + h * u) /(1 - h * a)
end =#
coefQ=1
#if (abs(q - x) > coefQ*quantum[i])
h2=coefQ*quantum[i]/(a*(x+coefQ*quantum[i])+u)
if h2<0
h2=-coefQ*quantum[i]/(a*(x-coefQ*quantum[i])+u)
q=x-coefQ*quantum[i]
else
q=x+coefQ*quantum[i]
end
#end
if h2<0
h=Inf
end
h=max(h1,h2)
#= if h==ft+100.0-simt
@show i,simt,x,x1,q,a*q+u
end =#
else
dx=u
if dx>0.0
q=x+quantum[i]#
else
q=x-quantum[i]
end
if dx!=0
h=(abs(quantum[i]/dx))
else
h=Inf
end
end
qv[i][0]=q
# println("inside single updateQ: q & qaux[$i][1]= ",q," ; ",qaux[i][1])
nextStateTime[i]=simt+h
return nothing
end
=#
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 18940 |
#iterations
#= function updateQ(::Val{2},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64},exactA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{2,Float64}},qaux::Vector{MVector{2,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})
cacheA[1]=0.0;exactA(qv,d,cacheA,i,i);a=cacheA[1]
# exactA(xv,cacheA,i,i);a=cacheA[1]
q=qv[i][0] ;q1=qv[i][1]; x=xv[i][0]; x1=xv[i][1]; x2=xv[i][2]*2; #u1=uv[i][i][1]; u2=uv[i][i][2]
qaux[i][1]=q+(simt-tq[i])*q1#appears only here...updated here and used in updateApprox and in updateQevent later
qaux[i][2]=q1 #appears only here...updated here and used in updateQevent
u1=x1-a*qaux[i][1]
u2=x2-a*q1
dxaux[i][1]=x1
dxaux[i][2]=x2
ddx=x2
quan=quantum[i]
h=0.0
if a!=0.0
if ddx ==0.0
ddx=a*a*q+a*u1 +u2
if ddx==0.0
ddx=1e-40# changing -40 to -6 nothing changed
# println("ddx=0")
end
end
h = ft-simt; q=(x-h*a*x-h*h*(a*u1+u2)/2)/(1 - h * a + h * h * a * a / 2)
if (abs(q - x) > 2.0* quan) # removing this did nothing...check @btime later
h = sqrt(abs(2*quan / ddx)) # sqrt highly recommended...removing it leads to many sim steps..//2* is necessary in 2*quan when using ddx
#= q = ((x + h * u1 + h * h / 2 * u2) * (1 - h * a) + (h * h / 2 * a - h) * (u1 + h * u2)) /
(1 - h * a + h * h * a * a / 2) =#
# qtemp=(x-h*a*x-h*h*(a*u1+u2)/2)/(1 - h * a + h * h * a * a / 2)
q=x+(-h*h*(a*a*x+a*u1+u2)/2)/((1 - h * a + h * h * a * a / 2))
#= if abs(q-qtemp)>1e-16
@show qtemp,q
end =#
end
maxIter=10000
# tempH=h
while (abs(q - x) >2.0* quan) && (maxIter>0) && (h>0)
h = h *sqrt(quan / abs(q - x))
# h = h *0.99*(1.8*quan / abs(q - x))
#= q = ((x + h * u1 + h * h / 2 * u2) * (1 - h * a) + (h * h / 2 * a - h) * (u1 + h * u2)) /
(1 - h * a + h * h * a * a / 2) =#
# qtemp=(x-h*a*x-h*h*(a*u1+u2)/2)/(1 - h * a + h * h * a * a / 2)
q=x+(-h*h*(a*a*x+a*u1+u2)/2)/((1 - h * a + h * h * a * a / 2))
#= if abs(q-qtemp)>1e-16
@show q,qtemp
end =#
maxIter-=1
end
if maxIter==0
println("updateQ maxIterReached")
end
#= if (abs(q - x) > 2* quan)
coef=@SVector [quan, -a*quan,(a*a*(x+quan)+a*u1+u2)/2]#
h1= minPosRoot(coef, Val(2))
coef=@SVector [-quan, a*quan,(a*a*(x-quan)+a*u1+u2)/2]#
h2= minPosRoot(coef, Val(2))
if h1<h2
h=h1;q=x+quan
else
h=h2;q=x-quan
end
qtemp=(x-h*a*x-h*h*(a*u1+u2)/2)/(1 - h * a + h * h * a * a / 2)
if abs(qtemp-q)>1e-12
println("error quad vs qexpression")
end
if h1!=Inf && h2!=Inf
println("quadratic eq double mpr")
end
if h1==Inf && h2==Inf
println("quadratic eq NO mpr")
end
end =#
#=
if (abs(q - x) > 2* quan)
# if x2<0.0 #x2 might changed direction...I should use ddx but again ddx=aq+u and q in unknown the sign is unknown
#= pertQuan=quan-1e-13 #
q=x+pertQuan # guess q to be thrown up
coef=@SVector [pertQuan, -a*pertQuan,(a*a*(x+pertQuan)+a*u1+u2)/2]#
h= minPosRoot(coef, Val(2))
pertQuan=quan+1e-13
coef=@SVector [pertQuan, -a*pertQuan,(a*a*(x+pertQuan)+a*u1+u2)/2]#
h2= minPosRoot(coef, Val(2))
if h2<h
q=x+pertQuan
h=h2
end
########### q to be thrown down
pertQuan=quan-1e-13
coef=@SVector [-pertQuan, a*pertQuan,(a*a*(x-pertQuan)+a*u1+u2)/2]#
h2= minPosRoot(coef, Val(2))
if h2<h
q=x-pertQuan
h=h2
end
pertQuan=quan+1e-13
coef=@SVector [-pertQuan, a*pertQuan,(a*a*(x-pertQuan)+a*u1+u2)/2]#
h2= minPosRoot(coef, Val(2))
if h2<h
q=x-pertQuan
h=h2
end =#
pertQuan=quan
coef=@SVector [-pertQuan, a*pertQuan,(a*a*(x-pertQuan)+a*u1+u2)/2]#
h= minPosRoot(coef, Val(2))
q=x-pertQuan
#= if h2<h
q=x-pertQuan
h=h2
end =#
coef=@SVector [pertQuan, -a*pertQuan,(a*a*(x+pertQuan)+a*u1+u2)/2]#
h2= minPosRoot(coef, Val(2))
if h2<h
q=x+pertQuan
h=h2
end
# end
end =#
α1=1-h*a
if abs(α1)==0.0
α1=1e-30*sign(α1)
end
q1=(a*q+u1+h*u2)/α1 #later investigate 1=h*a
else
#println("a==0")
if x2!=0.0
h=sqrt(abs(2*quan/x2)) #sqrt necessary with u2
q=x-h*h*x2/2
q1=x1+h*x2
else
# println("x2==0")
if x1!=0.0
h=abs(quan/x1)
q=x+h*x1
q1=0#x#/2
else
h=Inf
q=x
q1=x1
end
end
end
qv[i][0]=q
qv[i][1]=q1
nextStateTime[i]=simt+h
return h
end =#
#analytic
function updateQ(::Val{2},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64},exactA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{2,Float64}},qaux::Vector{MVector{2,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})
cacheA[1]=0.0;exactA(qv,d,cacheA,i,i,simt);a=cacheA[1]
# exactA(xv,cacheA,i,i);a=cacheA[1]
q=qv[i][0] ;q1=qv[i][1]; x=xv[i][0]; x1=xv[i][1]; x2=xv[i][2]*2; #u1=uv[i][i][1]; u2=uv[i][i][2]
qaux[i][1]=q+(simt-tq[i])*q1#appears only here...updated here and used in updateApprox and in updateQevent later
qaux[i][2]=q1 #appears only here...updated here and used in updateQevent
u1=x1-a*qaux[i][1]
u2=x2-a*q1
dxaux[i][1]=x1
dxaux[i][2]=x2
ddx=x2
quan=quantum[i]
h=0.0
if a!=0.0
# quan=quan*1.5
if a*a*x+a*u1+u2<=0.0
if -(a*a*x+a*u1+u2)/(a*a)<quan # asymptote<delta...no sol ...no need to check
h=Inf
q=-(a*u1+u2)/(a*a)#q=x+asymp
else
q=x+quan
coefi=NTuple{3,Float64}(((a*a*(x+quan)+a*u1+u2)/2,-a*quan,quan))
h=minPosRootv1(coefi) #needed for dq
#math was used to show h cannot be 1/a
end
elseif a*a*x+a*u1+u2>=0.0
if -(a*a*x+a*u1+u2)/(a*a)>-quan # asymptote>-delta...no sol ...no need to check
h=Inf
q=-(a*u1+u2)/(a*a)
else
coefi=NTuple{3,Float64}(((a*a*(x-quan)+a*u1+u2)/2,a*quan,-quan))
h=minPosRootv1(coefi)
# h=mprv2(coefi)
q=x-quan
end
else#a*a*x+a*u1+u2==0 -->f=0....q=x+f(h)=x+h*g(h) -->g(h)==0...dx==0 -->aq+u==0
q=-u1/a
h=Inf
end
if h!=Inf
if h!=1/a
q1=(a*q+u1+h*u2)/(1-h*a)
else#h=1/a
error("report bug: updateQ: h cannot=1/a; h=$h , 1/a=$(1/h)")
end
else #h==inf make ddx==0 dq=-u2/a
q1=-u2/a
end
#= if h!=Inf
α1=1-h*a
if abs(α1)==0.0
α1=1e-30*sign(α1)
end
q1=(a*q+u1+h*u2)/α1
else #h==inf make ddx==0 dq=-u2/a
q1=-u2/a
end =#
else
#println("a==0")
if x2!=0.0
h=sqrt(abs(2*quan/x2)) #sqrt necessary with u2
q=x-h*h*x2/2
q1=x1+h*x2
else
# println("x2==0")
if x1!=0.0
#quantum[i]=1quan
h=abs(1*quan/x1) # *10 just to widen the step otherwise it would behave like 1st order
q=x+h*x1
q1=0.0
else
h=Inf
q=x
q1=0.0
end
end
end
#= if 2.500745083181994e-5<=simt<3.00745083181994e-5
@show simt,i,q,x,h,a
@show a*a*x+a*u1+u2
end =#
qv[i][0]=q
qv[i][1]=q1
nextStateTime[i]=simt+h
return h
end
#=
function nupdateQ(::Val{2}#= ,cacheA::MVector{1,Float64},map::Function =#,i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64},av::Vector{Vector{Float64}},uv::Vector{Vector{MVector{O,Float64}}},qaux::Vector{MVector{O,Float64}},olddx::Vector{MVector{O,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})where{O}
#a=getA(Val(Sparsity),cacheA,av,i,i,map)
a=av[i][i]
q=qv[i][0] ;q1=qv[i][1]; x=xv[i][0]; x1=xv[i][1]; x2=xv[i][2]*2; u1=uv[i][i][1]; u2=uv[i][i][2]
qaux[i][1]=q+(simt-tq[i])*q1#appears only here...updated here and used in updateApprox and in updateQevent later
qaux[i][2]=q1 #appears only here...updated here and used in updateQevent
olddx[i][1]=x1#appears only here...updated here and used in updateApprox
#u1=u1+(simt-tu[i])*u2 # for order 2: u=u+tu*deru this is necessary deleting causes scheduler error
u1=x1-a*qaux[i][1]
uv[i][i][1]=u1
uv[i][i][2]=x2-a*q1
u2=uv[i][i][2]
#tu[i]=simt
# olddx[i][2]=2*x2#
ddx=x2
quan=quantum[i]
h=0.0
#= if simt == 0.004395600232045285
@show a
@show x1
@show u1
@show u2
end =#
if a!=0.0
if ddx ==0.0
ddx=a*a*q+a*u1 +u2
if ddx==0.0
ddx=1e-40# changing -40 to -6 nothing changed
#println("ddx=0")
end
end
h = ft-simt
#tempH1=h
#q = ((x + h * u1 + h * h / 2 * u2) * (1 - h * a) + (h * h / 2 * a - h) * (u1 + h * u2)) /(1 - h * a + h * h * a * a / 2)
q=(x-h*a*x-h*h*(a*u1+u2)/2)/(1 - h * a + h * h * a * a / 2)
if (abs(q - x) > 2* quan) # removing this did nothing...check @btime later
h = sqrt(abs(2*quan / ddx)) # sqrt highly recommended...removing it leads to many sim steps..//2* is necessary in 2*quan when using ddx
q = ((x + h * u1 + h * h / 2 * u2) * (1 - h * a) + (h * h / 2 * a - h) * (u1 + h * u2)) /
(1 - h * a + h * h * a * a / 2)
end
maxIter=1000
tempH=h
while (abs(q - x) > 2* quan) && (maxIter>0) && (h>0)
h = h *sqrt(quan / abs(q - x))
q = ((x + h * u1 + h * h / 2 * u2) * (1 - h * a) + (h * h / 2 * a - h) * (u1 + h * u2)) /
(1 - h * a + h * h * a * a / 2)
maxIter-=1
end
q1=(a*q+u1+h*u2)/(1-h*a) #later investigate 1=h*a
else
if x2!=0.0
h=sqrt(abs(2*quan/x2)) #sqrt necessary with u2
q=x-h*h*x2/2
q1=x1+h*x2
else
# println("x2==0")
if x1!=0.0
h=abs(quan/x1)
q=x+h*x1
q1=x1
else
h=Inf
q=x
q1=x1
end
end
end
qv[i][0]=q
qv[i][1]=q1
nextStateTime[i]=simt+h
return h
end =#
function Liqss_reComputeNextTime(::Val{2}, i::Int, simt::Float64, nextStateTime::Vector{Float64}, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64}#= ,a::Vector{Vector{Float64}} =#)
q=qv[i][0];x=xv[i][0];q1=qv[i][1];x1=xv[i][1];x2=xv[i][2];quani=quantum[i]
β=0
if abs(q-x) >= 2*quani # this happened when var i and j s turns are now...var i depends on j, j is asked here for next time...or if you want to increase quant*10 later it can be put back to normal and q & x are spread out by 10quan
nextStateTime[i] = simt+1e-12
# @show simt,i,q-x,quani,q,x
#= if simt==2.500745083181994e-5
println("quantizer-recomputeNext: abs(q-x) >= 2*quani")
@show simt,i,x,q,abs(q-x),quani
end =#
#= if simt>3.486047550372409
@show djsksfs
end =#
#elseif q!=x#abs(q-x)>quani/10000.0# #q=x ..let it be caught later by 2*Quantum
else
coef=@SVector [q-x#= -1e-13 =#, q1-x1,-x2]#
nextStateTime[i] = simt + minPosRoot(coef, Val(2))
if q-x >0.0#1e-9
coef=setindex(coef, q-x-2*quantum[i],1)
timetemp = simt + minPosRoot(coef, Val(2))
if timetemp < nextStateTime[i]
nextStateTime[i]=timetemp
end
#= if 0.000691<simt<0.00071
@show qv,xv,nextStateTime
end =#
elseif q-x <0.0#-1e-9
coef=setindex(coef, q-x+2*quantum[i],1)
timetemp = simt + minPosRoot(coef, Val(2))
if timetemp < nextStateTime[i]
nextStateTime[i]=timetemp
end
#= if 0.000691<simt<0.00071
@show coef
@show nextStateTime
@show simt,i,quantum[i]
end =#
#else# q=x ..let it be caught later by 2*Quantum
# nextStateTime[i]=simt+Inf#1e-19
#nextStateTime[i]=simt+1e-19
#= if q-x==0.0
nextStateTime[i]=simt+Inf#1e-19 #
else
nextStateTime[i]=simt+1e-12#Inf#1e-19 #
end =#
end
if nextStateTime[i]<=simt # this is coming from the fact that a variable can reach 2quan distance when it is not its turn, then computation above gives next=simt+(p-p)/dx...p-p should be zero but it can be very small negative
nextStateTime[i]=simt+Inf#1e-14
# @show simt,nextStateTime[i],i,x,q,quantum[i],xv[i][1]
end
#= if 2.500745083181994e-5<=simt<3.00745083181994e-5
@show simt,i,nextStateTime,x,q
end =#
#else
#= adavnce=nextStateTime[i]-simt
@show i,abs(q-x),quani/100.0,nextStateTime[i],simt,adavnce =#
end
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 8634 |
function updateQ(::Val{3},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64},exacteA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{3,Float64}},qaux::Vector{MVector{3,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})
#a=av[i][i]
cacheA[1]=0.0;exacteA(qv,d,cacheA,i,i);a=cacheA[1]
q=qv[i][0];q1=qv[i][1];q2=2*qv[i][2];x=xv[i][0];x1=xv[i][1];x2=2*xv[i][2];x3=6*xv[i][3];u1=uv[i][i][1];u2=uv[i][i][2];u3=uv[i][i][3]
elapsed=simt-tq[i]
qaux[i][1]=q+elapsed*q1+elapsed*elapsed*q2/2#appears only here...updated here and used in updateApprox and in updateQevent later
qaux[i][2]=q1+elapsed*q2 ;qaux[i][3]=q2 #never used
olddx[i][1]=x1
# tq[i]=simt
# elapsed=simt-tu[i]
# u1=u1+elapsed*u2+elapsed*elapsed*u3/2
u1=x1-a*qaux[i][1]
uv[i][i][1]=u1
#= u2=u2+elapsed*u3
uv[i][i][2]=u2 =#
uv[i][i][2]=x2-a*qaux[i][2] #---------------------------------------------------------------
u2=uv[i][i][2]
uv[i][i][3]=x3-a*q2
u3=uv[i][i][3]
# tu[i]=simt
dddx=x3
dxaux[i][1]=x1
dxaux[i][2]=x2
dxaux[i][3]=x3
quan=quantum[i]
h=0.0
# println("before q update",abs(q - x) > 2 * quan)
if a!=0.0
if dddx ==0.0
dddx=a*a*a*(q)+a*a*u1+a*u2+u3 #*2
if dddx==0.0
dddx=1e-40# changing -40 to -6 nothing changed
println("dddx=0") #this appeared once with sys1 liqss3
end
end
h = ft-simt
α=h*(1-a*h+h*h*a*a/3)/(1-h*a)
λ=x+h*u1+h*h*u2/2+h*h*h*u3/6
β=-α*(u1-u1*h*a-h*h*(a*u2+u3)/2)/(1-a*h+h*h*a*a/2)-h*h*(0.5-h*a/6)*(u2+h*u3)/(1-a*h)+λ
γ=1-a*h+α*a*(1-a*h)/(1-a*h+h*h*a*a/2)
q = β/γ
if (abs(q - x) > 2*quan) # removing this did nothing...check @btime later
h = cbrt(abs((6*quan) / dddx));
#h= cbrt(abs((q-x) / x3));#h=cbrt(abs(6*(q-x) / x3))# shifts up a little
α=h*(1-a*h+h*h*a*a/3)/(1-h*a)
β=-α*(u1-u1*h*a-h*h*(a*u2+u3)/2)/(1-a*h+h*h*a*a/2)-h*h*(0.5-h*a/6)*(u2+h*u3)/(1-a*h)+x+h*u1+h*h*u2/2+h*h*h*u3/6
γ=1-a*h+α*a*(1-a*h)/(1-a*h+h*h*a*a/2)
q = β/γ
end
maxIter=515
while (abs(q - x) > 2*quan) && (maxIter>0)
maxIter-=1
# h = h *(0.98*quan / abs(q - x));
h = h *cbrt(quan / abs(q - x));
α=h*(1-a*h+h*h*a*a/3)/(1-h*a)
β=-α*(u1-u1*h*a-h*h*(a*u2+u3)/2)/(1-a*h+h*h*a*a/2)-h*h*(0.5-h*a/6)*(u2+h*u3)/(1-a*h)+x+h*u1+h*h*u2/2+h*h*h*u3/6
γ=1-a*h+α*a*(1-a*h)/(1-a*h+h*h*a*a/2)
q = β/γ
end
q1=(a*(1-h*a)*q+u1*(1-h*a)-h*h*(a*u2+u3)/2)/(1-h*a+h*h*a*a/2)
q2=(a*q1+u2+h*u3)/(1-h*a)
if maxIter <200
@show maxIter
end
if h==0.0
@show h
end
else
if x3!=0.0
h=cbrt(abs(6*quan/x3))
q=x+h*h*h*x3/6
q1=x1-x3*h*h/2 #*2
q2=x2+h*x3
else
if x2!=0
h=sqrt(abs(2*quan/x2))
q=x-h*h*x2/2
q1=x1+h*x2
else
if x1!=0
h=abs(quan/x1)
q=x+h*x1
else
q=x
h=Inf
end
q1=x1
end
q2=x2
end
end
qv[i][0]=q
qv[i][1]=q1
qv[i][2]=q2/2
nextStateTime[i]=simt+h
return nothing
end
function nupdateQ(::Val{3},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64},av::Vector{Vector{Float64}},uv::Vector{Vector{MVector{O,Float64}}},qaux::Vector{MVector{O,Float64}},olddx::Vector{MVector{O,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextStateTime::Vector{Float64})where{O}
a=av[i][i]
q=qv[i][0];q1=qv[i][1];q2=2*qv[i][2];x=xv[i][0];x1=xv[i][1];x2=2*xv[i][2];x3=6*xv[i][3];u1=uv[i][i][1];u2=uv[i][i][2];u3=uv[i][i][3]
elapsed=simt-tq[i]
qaux[i][1]=q+elapsed*q1+elapsed*elapsed*q2/2#appears only here...updated here and used in updateApprox and in updateQevent later
qaux[i][2]=q1+elapsed*q2 ;qaux[i][3]=q2 #never used
olddx[i][1]=x1
# tq[i]=simt
#elapsed=simt-tu[i]
#u1=u1+elapsed*u2+elapsed*elapsed*u3/2
u1=x1-a*qaux[i][1]
uv[i][i][1]=u1
# u2=u2+elapsed*u3
# uv[i][i][2]=u2
uv[i][i][2]=x2-a*qaux[i][2]
u2=uv[i][i][2]
uv[i][i][3]=x3-a*q2
u3=uv[i][i][3]
#tu[i]=simt
dddx=x3
quan=quantum[i]
h=0.0
if a!=0.0
if dddx ==0.0
dddx=a*a*a*(q)+a*a*u1+a*u2+u3 #*2
if dddx==0.0
dddx=1e-40# changing -40 to -6 nothing changed
println("nupdate dddx=0") #this appeared once with sys1 liqss3
end
end
h = ft-simt
α=h*(1-a*h+h*h*a*a/3)/(1-h*a)
λ=x+h*u1+h*h*u2/2+h*h*h*u3/6
β=-α*(u1-u1*h*a-h*h*(a*u2+u3)/2)/(1-a*h+h*h*a*a/2)-h*h*(0.5-h*a/6)*(u2+h*u3)/(1-a*h)+λ
γ=1-a*h+α*a*(1-a*h)/(1-a*h+h*h*a*a/2)
q = β/γ
if (abs(q - x) > 2* quan) # removing this did nothing...check @btime later
h = cbrt(abs((6*quan) / dddx));
#h= cbrt(abs((q-x) / x3));#h=cbrt(abs(6*(q-x) / x3))# shifts up a little
α=h*(1-a*h+h*h*a*a/3)/(1-h*a)
β=-α*(u1-u1*h*a-h*h*(a*u2+u3)/2)/(1-a*h+h*h*a*a/2)-h*h*(0.5-h*a/6)*(u2+h*u3)/(1-a*h)+x+h*u1+h*h*u2/2+h*h*h*u3/6
γ=1-a*h+α*a*(1-a*h)/(1-a*h+h*h*a*a/2)
q = β/γ
end
maxIter=515
while (abs(q - x) > 2* quan) && (maxIter>0)
maxIter-=1
# h = h *(0.98*quan / abs(q - x));
h = h *cbrt(quan / abs(q - x))
α=h*(1-a*h+h*h*a*a/3)/(1-h*a)
β=-α*(u1-u1*h*a-h*h*(a*u2+u3)/2)/(1-a*h+h*h*a*a/2)-h*h*(0.5-h*a/6)*(u2+h*u3)/(1-a*h)+x+h*u1+h*h*u2/2+h*h*h*u3/6
γ=1-a*h+α*a*(1-a*h)/(1-a*h+h*h*a*a/2)
q = β/γ
end
q1=(a*(1-h*a)*q+u1*(1-h*a)-h*h*(a*u2+u3)/2)/(1-h*a+h*h*a*a/2)
q2=(a*q1+u2+h*u3)/(1-h*a)
if maxIter <200
@show maxIter
end
if h==0.0
@show h
end
else
if x3!=0.0
h=cbrt(abs(6*quan/x3))
q=x+h*h*h*x3/6
q1=x1-x3*h*h/2 #*2
q2=x2+h*x3
else
if x2!=0
h=sqrt(abs(2*quan/x2))
q=x-h*h*x2/2
q1=x1+h*x2
else
if x1!=0
h=abs(quan/x1)
q=x+h*x1
else
q=x
end
q1=x1
end
q2=x2
end
end
qv[i][0]=q
qv[i][1]=q1
qv[i][2]=q2/2
nextStateTime[i]=simt+h
return nothing
end
function Liqss_reComputeNextTime(::Val{3}, i::Int, simt::Float64, nextStateTime::Vector{Float64}, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64}#= ,a::Vector{Vector{Float64}} =#)
q=qv[i][0];x=xv[i][0];q1=qv[i][1];x1=xv[i][1];x2=xv[i][2];q2=qv[i][2];x3=xv[i][3]
coef=@SVector [q - x , q1-x1,q2-x2,-x3]# x and q might get away even further(change of sign) and we want that to be no more than another quan
nextStateTime[i] = simt + minPosRoot(coef, Val(3))
if abs(q-x) >= 2*quani # this happened when var i and j s turns are now...var i depends on j, j is asked here for next time...or if you want to increase quant*10 later it can be put back to normal and q & x are spread out by 10quan
nextStateTime[i] = simt+1e-15
else
if q-x >0
coef=setindex(coef, q-x-2*quantum[i],1)
timetemp = simt + minPosRoot(coef, Val(3))
if timetemp < nextStateTime[i]
nextStateTime[i]=timetemp
end
elseif q-x <0
coef=setindex(coef, q-x+2*quantum[i],1)
timetemp = simt + minPosRoot(coef, Val(3))
if timetemp < nextStateTime[i]
nextStateTime[i]=timetemp
end
else
#nextStateTime[i]=simt+Inf#1e-19
end
if nextStateTime[i]<simt # this is coming from the fact that a variable can reach 2quan distance when it is not its turn, then computation above gives next=simt+(p-p)/dx...p-p should be zero but it can be very small negative
nextStateTime[i]=simt+1e-15
# @show simt,nextStateTime[i],i,x,q,quantum[i],xv[i][1]
end
end
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 11436 |
######################################################################################################################################"
function computeNextTime(::Val{1}, i::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})#i can be absorbed
absDeltaT=1e-12 # minimum deltaT to protect against der=Inf coming from sqrt(0) for example...similar to min ΔQ
if (x[i].coeffs[2]) != 0
tempTime=max(abs(quantum[i] /(x[i].coeffs[2])),absDeltaT)# i can avoid the use of max
if tempTime!=absDeltaT #normal
nextTime[i] = simt + tempTime#sqrt(abs(quantum[i] / ((x[i].coeffs[3])*2))) #*2 cuz coeff contains fact()
else#usual (quant/der) is very small
x[i].coeffs[2]=sign(x[i].coeffs[2])*(abs(quantum[i])/absDeltaT)# adjust derivative if it is too high
nextTime[i] = simt + tempTime
if DEBUG println("qssQuantizer: smalldelta in compute next") end
end
else
nextTime[i] = Inf
end
return nothing
end
function computeNextTime(::Val{2}, i::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})
absDeltaT=1e-12 # minimum deltaT to protect against der=Inf coming from sqrt(0) for example...similar to min ΔQ
if (x[i].coeffs[3]) != 0
tempTime=max(sqrt(abs(quantum[i] / ((x[i].coeffs[3])))),absDeltaT)
if tempTime!=absDeltaT #normal
nextTime[i] = simt + tempTime#sqrt(abs(quantum[i] / ((x[i].coeffs[3])*2))) #*2 cuz coeff contains fact()
else#usual sqrt(quant/der) is very small
x[i].coeffs[3]=sign(x[i].coeffs[3])*(abs(quantum[i])/(absDeltaT*absDeltaT))/2# adjust second derivative if it is too high
nextTime[i] = simt + tempTime
if DEBUG println("qssQuantizer: smalldelta in compute next") end
end
else
if (x[i].coeffs[2]) != 0
#quantum[i]=2*quantum[i]
tempTime=max(abs(quantum[i] /(x[i].coeffs[2])),absDeltaT)# i can avoid the use of max
if tempTime!=absDeltaT #normal
nextTime[i] = simt + tempTime#sqrt(abs(quantum[i] / ((x[i].coeffs[3])*2))) #*2 cuz coeff contains fact()
else#usual (quant/der) is very small
x[i].coeffs[2]=sign(x[i].coeffs[2])*(abs(quantum[i])/absDeltaT)# adjust derivative if it is too high
nextTime[i] = simt + tempTime
if DEBUG println("qssQuantizer: smalldelta in compute next") end
end
else
nextTime[i] = Inf
end
end
return nothing
end
function computeNextTime(::Val{3}, i::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})
absDeltaT=1e-12 # minimum deltaT to protect against der=Inf coming from sqrt(0) for example...similar to min ΔQ
if (x[i].coeffs[4]) != 0
tempTime=max(cbrt(abs(quantum[i] / ((x[i].coeffs[4])))),absDeltaT) #6/6
if tempTime!=absDeltaT #normal
nextTime[i] = simt + tempTime#sqrt(abs(quantum[i] / ((x[i].coeffs[3])*2))) #*2 cuz coeff contains fact()
else#usual sqrt(quant/der) is very small
x[i].coeffs[4]=sign(x[i].coeffs[4])*(abs(quantum[i])/(absDeltaT*absDeltaT*absDeltaT))/6# adjust third derivative if it is too high
nextTime[i] = simt + tempTime
if DEBUG println("qssQuantizer: smalldelta in compute next") end
end
else
nextTime[i] = Inf
end
return nothing
end
######################################################################################################################################"
function reComputeNextTime(::Val{1}, index::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64})
absDeltaT=1e-12
coef=@SVector [q[index].coeffs[1] - (x[index].coeffs[1]) - quantum[index], -x[index].coeffs[2]]
time1 = simt + minPosRoot(coef, Val(1))
coef=setindex(coef,q[index].coeffs[1] - (x[index].coeffs[1]) + quantum[index],1)
time2 = simt + minPosRoot(coef, Val(1))
timeTemp = time1 < time2 ? time1 : time2
tempTime=max(timeTemp,absDeltaT) #guard against very small Δt
#if tempTime==absDeltaT #normal
# if DEBUG println("smalldelta in recompute next, simt= ",simt) end
# end
nextTime[index] = simt +tempTime
end
function reComputeNextTime(::Val{2}, index::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64})
absDeltaT=1e-15
if abs(q[index].coeffs[1] - (x[index].coeffs[1])) >= quantum[index] # this happened when var i and j s turns are now...var i depends on j, j is asked here for next time
nextTime[index] = simt+1e-15
else
coef=@SVector [q[index].coeffs[1] - (x[index].coeffs[1]) - quantum[index], q[index].coeffs[2]-x[index].coeffs[2],-(x[index].coeffs[3])]#not *2 because i am solving c+bt+a/2*t^2
time1 = minPosRoot(coef, Val(2))
coef=setindex(coef,q[index].coeffs[1] - (x[index].coeffs[1]) + quantum[index],1)
time2 = minPosRoot(coef, Val(2))
timeTemp = time1 < time2 ? time1 : time2
tempTime=max(timeTemp,absDeltaT)#guard against very small Δt
# if tempTime==absDeltaT #normal
# x[index].coeffs[3]=sign(x[index].coeffs[3])*(abs(quantum[index])/(absDeltaT*absDeltaT))/2
# if DEBUG println("smalldelta in recompute next, simt= ",simt) end
# end
nextTime[index] = simt +tempTime
end
return nothing
end
function reComputeNextTime(::Val{3}, index::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64})
#coef=@SVector [q[index].coeffs[1] - (x[index].coeffs[1]) - quantum[index], q[index].coeffs[2]-x[index].coeffs[2],(q[index].coeffs[3])-(x[index].coeffs[3]),-(x[index].coeffs[4])]
#time1 = simt + minPosRoot(coef, Val(3))
#pp=pointer(Vector{NTuple{2,Float64}}(undef, 5))
a=-x[index][3];b=q[index][2]-x[index][2];c=q[index][1]-x[index][1];d=q[index][0]-x[index][0]-quantum[index]
#GC.enable(false)
#time1 = simt+smallestpositiverootintervalnewtonregulafalsi((a, b, c, d))
time1 = simt+cubic5(a, b, c, d)
# GC.enable(true)
#coef=setindex(coef,q[index].coeffs[1] - (x[index].coeffs[1]) + quantum[index],1)
d=q[index][0]-x[index][0]+quantum[index]
# GC.enable(false)
#time2 = simt+smallestpositiverootintervalnewtonregulafalsi((a, b, c, d))
time2 = simt+cubic5(a, b, c, d)
# GC.enable(true)
#time2 = simt + minPosRoot(coef, Val(3))
timeTemp = time1 < time2 ? time1 : time2
absDeltaT=1e-12
tempTime=max(timeTemp,absDeltaT)#guard against very small Δt
nextTime[index] = simt +tempTime
return nothing
end
######################################################################################################################################"
function computeNextInputTime(::Val{1}, i::Int, simt::Float64,elapsed::Float64, tt::Taylor0 ,nextInputTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})
df=0.0
oldDerX=x[i].coeffs[2]
newDerX=tt.coeffs[1]
if elapsed > 0
df=(newDerX-oldDerX)/elapsed #df mimics second der
else
df= quantum[i]*1e6
end
if df!=0.0
nextInputTime[i]=simt+sqrt(abs(2*quantum[i] / df))
else
nextInputTime[i] = Inf
end
return nothing
end
function computeNextInputTime(::Val{2}, i::Int, simt::Float64,elapsed::Float64, tt::Taylor0 ,nextInputTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})
ddf=0.0;df=0.0
oldDerDerX=((x[i].coeffs[3])*2.0)
# @show x
newDerDerX=(tt.coeffs[2])# 1st der of tt cuz tt itself is derx=f
#@show tt
if elapsed > 0.0
ddf=(newDerDerX-oldDerDerX)/(elapsed)
# println("df=new-old= ",df)
else
ddf= quantum[i]*1e6#*1e12
if DEBUG println("QSS quantizer elapsed=0!") end
end
if ddf!=0.0
nextInputTime[i]=simt+cbrt((abs(quantum[i]/df))) #ddf mimics 3rd der
# println("usedcbrt")
else #df=0->newddx=oldddx ->
if DEBUG println("QSS quantizer ddf=0 ") end
oldDerX=((x[i].coeffs[2]))
# @show x
newDerX=(tt.coeffs[1])# 1st der of tt cuz tt itself is derx=f
# @show tt
if elapsed > 0.0
df=(newDerX-oldDerX)/(elapsed) #df mimic second derivative
# println("df=new-old= ",df)
else
df= quantum[i]*1e6#*1e12
if DEBUG println("QSS quantizer elapsed=0!") end
end
if df!=0.0
nextInputTime[i]=simt+sqrt((abs(quantum[i]/df)))
else
if x[i][1]!=0 #predicted second derivative is 0 & should not be used to determine nexttime. use 1st der
#nextInputTime[i]=simt+(abs(2*quantum[i] / x[i][1])) #*2 is not analytic: is just there to increase stepsize
nextInputTime[i]=simt+sqrt(abs(1*quantum[i] / x[i][1])) #I used the same formulae even with 1st der so that it is fair to other vars
else
nextInputTime[i] = Inf
end
end
end
# @show nextInputTime
return nothing
end
function computeNextInputTime(::Val{3}, i::Int, simt::Float64,elapsed::Float64, tt::Taylor0 ,nextInputTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})
df=0.0
oldDerDerX=((x[i].coeffs[3])*2.0)
#@show x
newDerDerX=(tt.coeffs[2])# 1st der of tt cuz tt itself is derx=f
#@show newDerDerX
if elapsed > 0.0
df=(newDerDerX-oldDerDerX)/(elapsed)
# println("df=new-old= ",df)
else
df= quantum[i]*1e6#*1e12
end
if df!=0.0
nextInputTime[i]=simt+cbrt((abs(quantum[i]/df))) #df mimics 3rd der
# println("usedcbrt")
else
if newDerDerX==0 && x[i][1]!=0 #predicted second derivative is 0 & should be not be used to determine nexttime. use 1st der
#nextInputTime[i]=simt+(abs(2*quantum[i] / x[i][1])) #*2 is not analytic: is just there to increase stepsize
nextInputTime[i]=simt+sqrt(abs(1*quantum[i] / x[i][1])) #I used the same formulae even with 1st der so that it is fair to other vars
else
nextInputTime[i] = Inf
end
end
return nothing
end
function computeNextEventTime(::Val{O},j::Int,ZCFun::Taylor0,oldsignValue,simt, nextEventTime, quantum::Vector{Float64},absQ::Float64) where {O}
#= if ZCFun[0]==0.0 && oldsignValue[j,1] !=0.0#abs(oldsignValue[j,1])>1e-15
if DEBUG2 println("qss quantizer:zcf$j ZCF=0.0 (rare) immediate event at simt= $simt oldzcf value= $(oldsignValue[j,2]) ") end
nextEventTime[j]=simt
else =#
if (oldsignValue[j,1] != sign(ZCFun[0])) && abs(oldsignValue[j,2]) >1e-9*absQ #prevent double tapping: when zcf is leaving zero it should be considered an event
if DEBUG println("qss quantizer:zcf$j immediate event at simt= $simt oldzcf value= $(oldsignValue[j,2]) newZCF value= $(ZCFun[0])"); end
nextEventTime[j]=simt
elseif oldsignValue[j,2] ==0.0 && ZCFun[0] ==0.0 # initial value 0 --> do not do anything
nextEventTime[j]=Inf
else # old and new ZCF both pos or both neg
# coef=@SVector [ZCFun[0],ZCFun[1],ZCFun[2]]
mpr=minPosRoot(ZCFun, Val(O))
if mpr<1e-14 # prevent very close events
mpr=1e-12
#sl=ZCFun[0]+mpr*ZCFun[1]+mpr*mpr*ZCFun[2]/2
end
nextEventTime[j] =simt + mpr
if DEBUG2
println("qss quantizer:zcf$j at simt= $simt ****scheduled**** event at $(simt + mpr) oldzcf value= $(oldsignValue[j,2]) newZCF value= $(ZCFun[0])")
end
oldsignValue[j,1]=sign(ZCFun[0])#update the values
oldsignValue[j,2]=ZCFun[0]
end
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1252 | @inline function integrateState(::Val{0}, x::Taylor0,elapsed::Float64)
#nothing: created for elapse-updating q in order1 which does not happen
end
@inline function integrateState(::Val{1}, x::Taylor0,elapsed::Float64)
x.coeffs[1] = x(elapsed)
end
@inline function integrateState(::Val{2}, x::Taylor0,elapsed::Float64)
x.coeffs[1] = x(elapsed)
x.coeffs[2] = x.coeffs[2]+elapsed*x.coeffs[3]*2
end
@inline function integrateState(::Val{3}, x::Taylor0,elapsed::Float64)
x.coeffs[1] = x(elapsed)
x.coeffs[2] = x.coeffs[2]+elapsed*x.coeffs[3]*2+elapsed*elapsed*x.coeffs[4]*3
x.coeffs[3] = x.coeffs[3]+elapsed*x.coeffs[4]*3#(x.coeffs[3]*2+elapsed*x.coeffs[4]*6)/2
end
######################################################################################################################################"
function computeDerivative( ::Val{1} ,x::Taylor0,f::Taylor0 )
x.coeffs[2] =f.coeffs[1]
return nothing
end
function computeDerivative( ::Val{2} ,x::Taylor0,f::Taylor0)
x.coeffs[2] =f.coeffs[1]
x.coeffs[3] =f.coeffs[2]/2
return nothing
end
function computeDerivative( ::Val{3} ,x::Taylor0,f::Taylor0)
x.coeffs[2] =f[0]
x.coeffs[3]=f.coeffs[2]/2
x.coeffs[4]=f.coeffs[3]/3 # coeff3*2/6
return nothing
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 19126 | #analy
function nmisCycle_and_simulUpdate(cacheRootsi::Vector{Float64},cacheRootsj::Vector{Float64},acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{1},index::Int,j::Int,dirI::Float64,dti::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exacteA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exacteA(q,d,cacheA,index,index,simt)
aii=cacheA[1]
cacheA[1]=0.0;exacteA(q,d,cacheA,j,j,simt)
ajj=cacheA[1]
#= exacteA(q,cacheA,index,j)
aij=cacheA[1]
exacteA(q,cacheA,j,index)
aji=cacheA[1] =#
xi=x[index][0];xj=x[j][0];ẋi=x[index][1];ẋj=x[j][1]
qi=q[index][0];qj=q[j][0]
quanj=quantum[j];quani=quantum[index]
#qaux[j][1]=qj;
elapsed = simt - tx[j];x[j][0]= xj+elapsed*ẋj;
xj=x[j][0]
tx[j]=simt
qiminus=qaux[index][1]
#ujj=ẋj-ajj*qj
uji=ẋj-ajj*qj-aji*qiminus
#uii=dxaux[index][1]-aii*qaux[index][1]
uij=dxaux[index][1]-aii*qiminus-aij*qj
iscycle=false
dxj=aji*qi+ajj*qj+uji #only future qi #emulate fj
dxithrow=aii*qi+aij*qj+uij #only future qi
qjplus=xj+sign(dxj)*quanj #emulate updateQ(j)...
dxi=aii*qi+aij*qjplus+uij #both future qi & qj #emulate fi
#dxj2=ajj*qjplus+aji*qi+uji
#= if abs(dxithrow)<1e-15 && dxithrow!=0.0
dxithrow=0.0
end =#
########condition:Union
#= if abs(dxj)*3<abs(ẋj) || abs(dxj)>3*abs(ẋj) || (dxj*ẋj)<0.0
if abs(dxi)>3*abs(ẋi) || abs(dxi)*3<abs(ẋi) || (dxi*ẋi)<0.0
iscycle=true
end
end =#
########condition:Union i
#= if abs(dxj-ẋj)>(abs(dxj+ẋj)/2)
if abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2)
iscycle=true
end
end =#
########condition:Union i union
if (abs(dxj)*3<abs(ẋj) || abs(dxj)>3*abs(ẋj) || (dxj*ẋj)<0.0)
cancelCriteria=1e-6*quani
if abs(dxi)>3*abs(dxithrow) || abs(dxi)*3<abs(dxithrow) || (dxi*dxithrow)<0.0
iscycle=true
if abs(dxi)<cancelCriteria && abs(dxithrow)<cancelCriteria #significant change is relative to der values. cancel if all values are small
iscycle=false
# println("cancel dxi & dxthr small")
end
end
if abs(dxi)>10*abs(ẋi) || abs(dxi)*10<abs(ẋi) #|| (dxi*ẋi)<0.0
iscycle=true
if abs(dxi)<cancelCriteria && abs(ẋi)<cancelCriteria #significant change is relative to der values. cancel if all values are small
iscycle=false
# println("cancel dxi & ẋi small")
end
end
if abs(dxj)<1e-6*quanj && abs(ẋj)<1e-6*quanj #significant change is relative to der values. cancel if all values are small
iscycle=false
#println("cancel dxj & ẋj small")
end
end
#= if 9.087757893221387e-5<=simt<=9.23684654009e-5
println("simulUpdate $iscycle at simt=$simt index=$index, j=$j")
@show ẋi,dxi,dxithrow,ẋj,dxj
@show qj,xj
end =#
if iscycle
#clear accIntrvals and cache of roots
for i =1:3# 3 ord1 ,7 ord2
acceptedi[i][1]=0.0; acceptedi[i][2]=0.0
acceptedj[i][1]=0.0; acceptedj[i][2]=0.0
end
for i=1:4
cacheRootsi[i]=0.0
cacheRootsj[i]=0.0
end
#find positive zeros f=+-Δ
bi=aii*xi+aij*xj+uij;ci=aij*(aji*xi+uji)-ajj*(aii*xi+uij);αi=-ajj-aii;βi=aii*ajj-aij*aji
bj=ajj*xj+aji*xi+uji;cj=aji*(aij*xj+uij)-aii*(ajj*xj+uji);αj=-aii-ajj;βj=ajj*aii-aji*aij
coefi=NTuple{3,Float64}((βi*quani-ci,αi*quani-bi,quani))
coefi2=NTuple{3,Float64}((-βi*quani-ci,-αi*quani-bi,-quani))
coefj=NTuple{3,Float64}((βj*quanj-cj,αj*quanj-bj,quanj))
coefj2=NTuple{3,Float64}((-βj*quanj-cj,-αj*quanj-bj,-quanj))
resi1,resi2=quadRootv2(coefi)
resi3,resi4=quadRootv2(coefi2)
resj1,resj2=quadRootv2(coefj)
resj3,resj4=quadRootv2(coefj2)
#= unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2)
allrealrootintervalnewtonregulafalsi(coefi,respp,pp)
resi1,resi2=unsafe_load(respp,1),unsafe_load(respp,2)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2)
allrealrootintervalnewtonregulafalsi(coefi2,respp,pp)
resi3,resi4=unsafe_load(respp,1),unsafe_load(respp,2)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2)
allrealrootintervalnewtonregulafalsi(coefj,respp,pp)
resj1,resj2=unsafe_load(respp,1),unsafe_load(respp,2)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2)
allrealrootintervalnewtonregulafalsi(coefj2,respp,pp)
resj3,resj4=unsafe_load(respp,1),unsafe_load(respp,2) =#
#construct intervals
constructIntrval(acceptedi,resi1,resi2,resi3,resi4)
constructIntrval(acceptedj,resj1,resj2,resj3,resj4)
#find best H (largest overlap)
ki=3;kj=3
while true
currentLi=acceptedi[ki][1];currentHi=acceptedi[ki][2]
currentLj=acceptedj[kj][1];currentHj=acceptedj[kj][2]
if currentLj<=currentLi<currentHj || currentLi<=currentLj<currentHi#resj[end][1]<=resi[end][1]<=resj[end][2] || resi[end][1]<=resj[end][1]<=resi[end][2] #overlap
h=min(currentHi,currentHj )
#= if simt==6.167911302732222e-9
@show h
end =#
if h==Inf && (currentLj!=0.0 || currentLi!=0.0) # except case both 0 sols h1=(0,Inf)
h=max(currentLj,currentLi#= ,ft-simt,dti =#) #ft-simt in case they are both ver small...elaborate on his later
end
if h==Inf # both lower bounds ==0 --> zero sols for both
qi=getQfromAsymptote(simt,xi,βi,ci,αi,bi)
qj=getQfromAsymptote(simt,xj,βj,cj,αj,bj)
else
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
if Δ!=0.0
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
else
qi,qj,h,maxIter=IterationH(h,xi,quani, xj,quanj,aii,ajj,aij,aji,uij,uji)
if maxIter==0
return false
end
end
end
break
else
if currentHj==0.0 && currentHi==0.0#empty
ki-=1;kj-=1
elseif currentHj==0.0 && currentHi!=0.0
kj-=1
elseif currentHi==0.0 && currentHj!=0.0
ki-=1
else #both non zero
if currentLj<currentLi#remove last seg of resi
ki-=1
else #remove last seg of resj
kj-=1
end
end
end
end # end while
q[j][0]=qj
tq[j]=simt
q[index][0]=qi# store back helper vars
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
end
return iscycle
end
#iters
# function nmisCycle_and_simulUpdate(acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{1},index::Int,j::Int,dirI::Float64,dti::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exacteA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
#= function nmisCycle_and_simulUpdate(cacheRootsi::Vector{Float64},cacheRootsj::Vector{Float64},acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{1},index::Int,j::Int,dirI::Float64,dti::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exacteA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exacteA(q,d,cacheA,index,index)
aii=cacheA[1]
cacheA[1]=0.0;exacteA(q,d,cacheA,j,j)
ajj=cacheA[1]
#= exacteA(q,cacheA,index,j)
aij=cacheA[1]
exacteA(q,cacheA,j,index)
aji=cacheA[1] =#
xi=x[index][0];xj=x[j][0];ẋi=x[index][1];ẋj=x[j][1]
qi=q[index][0];qj=q[j][0]
quanj=quantum[j];quani=quantum[index]
#qaux[j][1]=qj;
elapsed = simt - tx[j];x[j][0]= xj+elapsed*ẋj;
xj=x[j][0]
tx[j]=simt
qiminus=qaux[index][1]
#ujj=ẋj-ajj*qj
uji=ẋj-ajj*qj-aji*qiminus
#uii=dxaux[index][1]-aii*qaux[index][1]
uij=dxaux[index][1]-aii*qiminus-aij*qj
iscycle=false
dxj=aji*qi+ajj*qj+uji #only future qi #emulate fj
dxithrow=aii*qi+aij*qj+uij #only future qi
qjplus=xj+sign(dxj)*quanj #emulate updateQ(j)...
dxi=aii*qi+aij*qjplus+uij #both future qi & qj #emulate fi
#dxj2=ajj*qjplus+aji*qi+uji
#= if abs(dxithrow)<1e-15 && dxithrow!=0.0
dxithrow=0.0
end =#
########condition:Union
#= if abs(dxj)*3<abs(ẋj) || abs(dxj)>3*abs(ẋj) || (dxj*ẋj)<0.0
if abs(dxi)>3*abs(ẋi) || abs(dxi)*3<abs(ẋi) || (dxi*ẋi)<0.0
iscycle=true
end
end =#
########condition:Union i
#= if abs(dxj-ẋj)>(abs(dxj+ẋj)/2)
if abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2)
iscycle=true
end
end =#
########condition:Union i union
if (abs(dxj)*3<abs(ẋj) || abs(dxj)>3*abs(ẋj) || (dxj*ẋj)<0.0)
cancelCriteria=1e-3*quani
if abs(dxi)>3*abs(dxithrow) || abs(dxi)*3<abs(dxithrow) || (dxi*dxithrow)<0.0
iscycle=true
if abs(dxi)<cancelCriteria && abs(dxithrow)<cancelCriteria #significant change is relative to der values. cancel if all values are small
iscycle=false
# println("cancel dxi & dxthr small")
end
end
if abs(dxi)>10*abs(ẋi) || abs(dxi)*10<abs(ẋi) #|| (dxi*ẋi)<0.0
iscycle=true
if abs(dxi)<cancelCriteria && abs(ẋi)<cancelCriteria #significant change is relative to der values. cancel if all values are small
iscycle=false
# println("cancel dxi & ẋi small")
end
end
if abs(dxj)<1e-6*quanj && abs(ẋj)<1e-6*quanj #significant change is relative to der values. cancel if all values are small
iscycle=false
#println("cancel dxj & ẋj small")
end
end
#= if 9.087757893221387e-5<=simt<=9.23684654009e-5
println("simulUpdate $iscycle at simt=$simt index=$index, j=$j")
@show ẋi,dxi,dxithrow,ẋj,dxj
@show qj,xj
end =#
if iscycle
h=ft-simt
# h=firstguessH
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
if (abs(qi - xi) > 1*quani || abs(qj - xj) > 1*quanj) #checking qi-xi is not needed since firstguess just made it less than delta
h1 = (abs(quani / ẋi));h2 = (abs(quanj / ẋj));
h=min(h1,h2)
h_two=h
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
#= if Δ==0
Δ=1e-12
end =#
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
end
maxIter=1000
while (abs(qi - xi) > 1*quani || abs(qj - xj) > 1*quanj) && (maxIter>0)
maxIter-=1
h1 = h * (0.99*quani / abs(qi - xi));
#= Δtemp=(1-h1*aii)*(1-h1*ajj)-h1*h1*aij*aji
qitemp = ((1-h1*ajj)*(xi+h1*uij)+h1*aij*(xj+h1*uji))/Δtemp =#
h2 = h * (0.99*quanj / abs(qj - xj));
#= Δtemp=(1-h2*aii)*(1-h2*ajj)-h2*h2*aij*aji
qjtemp = ((1-h2*ajj)*(xi+h2*uij)+h2*aij*(xj+h2*uji))/Δtemp
if abs(qitemp - xi) > 1*quani || abs(qjtemp - xj) > 1*quanj
println("regle de croix did not work")
end =#
h=min(h1,h2)
h_three=h
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
#= if Δ==0
Δ=1e-12
println("delta liqss1 simulupdate==0")
end =#
if Δ!=0
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
end
if maxIter < 1 println("maxiter of updateQ = ",maxIter) end
end
if maxIter < 1
return false
end
q[index][0]=qi# store back helper vars
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
q[j][0]=qj
#= push!(simulqxiVals,abs(qi-xi))
push!(simulqxjVals,abs(qj-xj))
push!(simuldeltaiVals,quani)
push!(simuldeltajVals,quanj) =#
tq[j]=simt
end #end second dependecy check
return iscycle
end =#
#= function nmisCycle_and_simulUpdate(acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{1},index::Int,j::Int,dirI::Float64,dti::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exacteA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
exacteA(q,d,cacheA,index,index)
aii=cacheA[1]
exacteA(q,d,cacheA,j,j)
ajj=cacheA[1]
exacteA(q,d,cacheA,index,j)
aij=cacheA[1]
exacteA(q,d,cacheA,j,index)
aji=cacheA[1]
xi=x[index][0];xj=x[j][0];ẋi=x[index][1];ẋj=x[j][1]
qi=q[index][0];qj=q[j][0]
quanj=quantum[j];quani=quantum[index]
qaux[j][1]=qj;#olddx[j][1]=ẋj
elapsed = simt - tx[j];x[j][0]= xj+elapsed*ẋj;
xj=x[j][0]
tx[j]=simt
#ujj=ẋj-ajj*qj
uji=ẋj-ajj*qj-aji*qaux[index][1]
#uii=dxaux[index][1]-aii*qaux[index][1]
uij=dxaux[index][1]-aii*qaux[index][1]-aij*qj#qaux[j][1]
iscycle=false
dxj=aji*qi+ajj*qaux[j][1]+uji #only future qi
qjplus=xj+sign(dxj)*quanj
dxi=aii*qi+aij*qjplus+uij #both future qi & qj
dxi2=aii*qi+aij*qj+uij #only future qi
dxj2=aji*qi+ajj*qjplus+uji#both future qi & qj
#= if simt>=0.22816661756287676
@show simt,index
@show ẋi,dxi
@show ẋj,dxj
@show xj,qj,qjplus,quanj
@show xi,qaux[index][1],qi,quani
@show firstguessH
end =#
if #= abs(dxj-ẋj)>abs(dxj+ẋj)/1.8 =#((abs(dxj)*3<abs(ẋj) || abs(dxj)>3*abs(ẋj))#= && abs(ẋj * dxj) > 1e-3 =# )|| (dxj*ẋj)<=0.0#= && abs(dxj-ẋj)>abs(dxj+ẋj)/20 =#
# if (dxj*ẋj)<=0.0
# if abs(a[j][index]*2*quantum[index])>abs(x[j][1])
############################################################################
if #= abs(dxi-ẋi)>abs(dxi+ẋi)/1.8 =#((abs(dxi)*3<abs(ẋi) || abs(dxi)>3*abs(ẋi))#= && abs(ẋi * dxi)> 1e-3 =# )|| (dxi*ẋi)<=0.0 #= && abs(dxi-ẋi)>abs(dxi+ẋi)/20 =#
#if (dxi*ẋi)<=0.0
iscycle=true
h_two=-1.0;h_three=-1.0
h=ft-simt
# h=firstguessH
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
if (abs(qi - xi) > 1*quani || abs(qj - xj) > 1*quanj) #checking qi-xi is not needed since firstguess just made it less than delta
h1 = (abs(quani / ẋi));h2 = (abs(quanj / ẋj));
h=min(h1,h2)
h_two=h
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
if Δ==0
Δ=1e-12
end
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
end
maxIter=1000
while (abs(qi - xi) > 1*quani || abs(qj - xj) > 1*quanj) && (maxIter>0)
maxIter-=1
h1 = h * (0.99*quani / abs(qi - xi));
#= Δtemp=(1-h1*aii)*(1-h1*ajj)-h1*h1*aij*aji
qitemp = ((1-h1*ajj)*(xi+h1*uij)+h1*aij*(xj+h1*uji))/Δtemp =#
h2 = h * (0.99*quanj / abs(qj - xj));
#= Δtemp=(1-h2*aii)*(1-h2*ajj)-h2*h2*aij*aji
qjtemp = ((1-h2*ajj)*(xi+h2*uij)+h2*aij*(xj+h2*uji))/Δtemp
if abs(qitemp - xi) > 1*quani || abs(qjtemp - xj) > 1*quanj
println("regle de croix did not work")
end =#
h=min(h1,h2)
h_three=h
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
if Δ==0
Δ=1e-12
println("delta liqss1 simulupdate==0")
end
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
if maxIter < 1 println("maxiter of updateQ = ",maxIter) end
end
# if maxIter < 950 println("maxiter = ",maxIter) end
# @show simt,index,h
#= push!(simulHTimes,simt)
push!(simulHVals,h) =#
# @show h,qi,qj
q[index][0]=qi# store back helper vars
q[j][0]=qj
#= push!(simulqxiVals,abs(qi-xi))
push!(simulqxjVals,abs(qj-xj))
push!(simuldeltaiVals,quani)
push!(simuldeltajVals,quanj) =#
tq[j]=simt
end #end second dependecy check
end # end outer dependency check
return iscycle
end =#
function getQfromAsymptote(simt,x::Float64,β::P,c::P,α::P,b::P) where {P<:Union{BigFloat,Float64}}
q=0.0
if β==0.0 && c!=0.0
println("report bug: β==0 && c!=0.0: this leads to asym=Inf while this code came from asym<Delta at $simt")
elseif β==0.0 && c==0.0
if α==0.0 && b!=0.0
println("report bug: α==0 && b!=0.0 this leads to asym=Inf while this code came from asym<Delta at $simt")
elseif α==0.0 && b==0.0
q=x
else
q=x+b/α
end
else
q=x+c/β #asymptote...even though not guaranteed to be best
end
q
end
function iterationH(h::Float64,xi::Float64,quani::Float64, xj::Float64,quanj::Float64,aii::Float64,ajj::Float64,aij::Float64,aji::Float64,uij::Float64,uji::Float64)
qi,qj=0.0,0.0
maxIter=1000
while (abs(qi - xi) > 1*quani || abs(qj - xj) > 1*quanj) && (maxIter>0)
maxIter-=1
h1 = h * (0.99*quani / abs(qi - xi));
h2 = h * (0.99*quanj / abs(qj - xj));
h=min(h1,h2)
h_three=h
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
if Δ!=0
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
end
# if maxIter < 1 println("maxiter of updateQ = ",maxIter) end
end
qi,qj,h,maxIter
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 10830 |
#iters
function nmisCycle_and_simulUpdate(cacheRootsi::Vector{Float64},cacheRootsj::Vector{Float64},acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{1},index::Int,j::Int,dirI::Float64,dti::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exactA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exactA(q,d,cacheA,index,index,simt)
aii=cacheA[1]
cacheA[1]=0.0;exactA(q,d,cacheA,j,j,simt)
ajj=cacheA[1]
#= exactA(q,cacheA,index,j)
aij=cacheA[1]
exactA(q,cacheA,j,index)
aji=cacheA[1] =#
xi=x[index][0];xj=x[j][0];ẋi=x[index][1];ẋj=x[j][1]
qi=q[index][0];qj=q[j][0]
quanj=quantum[j];quani=quantum[index]
#qaux[j][1]=qj;
elapsed = simt - tx[j];x[j][0]= xj+elapsed*ẋj;
xj=x[j][0]
tx[j]=simt
qiminus=qaux[index][1]
#ujj=ẋj-ajj*qj
uji=ẋj-ajj*qj-aji*qiminus
#uii=dxaux[index][1]-aii*qaux[index][1]
uij=dxaux[index][1]-aii*qiminus-aij*qj
iscycle=false
dxj=aji*qi+ajj*qj+uji #only future qi #emulate fj
dxithrow=aii*qi+aij*qj+uij #only future qi
qjplus=xj+sign(dxj)*quanj #emulate updateQ(j)...
dxi=aii*qi+aij*qjplus+uij #both future qi & qj #emulate fi
#dxj2=ajj*qjplus+aji*qi+uji
#= if abs(dxithrow)<1e-15 && dxithrow!=0.0
dxithrow=0.0
end =#
########condition:Union
#= if abs(dxj)*3<abs(ẋj) || abs(dxj)>3*abs(ẋj) || (dxj*ẋj)<0.0
if abs(dxi)>3*abs(ẋi) || abs(dxi)*3<abs(ẋi) || (dxi*ẋi)<0.0
iscycle=true
end
end =#
########condition:Union i
#= if abs(dxj-ẋj)>(abs(dxj+ẋj)/2)
if abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2)
iscycle=true
end
end =#
########condition:Union i union
if (abs(dxj)*3<abs(ẋj) || abs(dxj)>3*abs(ẋj) || (dxj*ẋj)<0.0)
cancelCriteria=1e-6*quani
if abs(dxi)>3*abs(dxithrow) || abs(dxi)*3<abs(dxithrow) || (dxi*dxithrow)<0.0
iscycle=true
if abs(dxi)<cancelCriteria && abs(dxithrow)<cancelCriteria #significant change is relative to der values. cancel if all values are small
iscycle=false
# println("cancel dxi & dxthr small")
end
end
if abs(dxi)>10*abs(ẋi) || abs(dxi)*10<abs(ẋi) #|| (dxi*ẋi)<0.0
iscycle=true
if abs(dxi)<cancelCriteria && abs(ẋi)<cancelCriteria #significant change is relative to der values. cancel if all values are small
iscycle=false
# println("cancel dxi & ẋi small")
end
end
if abs(dxj)<1e-6*quanj && abs(ẋj)<1e-6*quanj #significant change is relative to der values. cancel if all values are small
iscycle=false
#println("cancel dxj & ẋj small")
end
end
#= if 9.087757893221387e-5<=simt<=9.23684654009e-5
println("simulUpdate $iscycle at simt=$simt index=$index, j=$j")
@show ẋi,dxi,dxithrow,ẋj,dxj
@show qj,xj
end =#
if iscycle
h=ft-simt
# h=firstguessH
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
if (abs(qi - xi) > 2*quani || abs(qj - xj) > 2*quanj) #checking qi-xi is not needed since firstguess just made it less than delta
h1 = (abs(quani / ẋi));h2 = (abs(quanj / ẋj));
h=min(h1,h2)
h_two=h
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
#= if Δ==0
Δ=1e-12
end =#
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
end
maxIter=1000
while (abs(qi - xi) > 2*quani || abs(qj - xj) > 2*quanj) && (maxIter>0)
maxIter-=1
h1 = h * (0.99*quani / abs(qi - xi));
#= Δtemp=(1-h1*aii)*(1-h1*ajj)-h1*h1*aij*aji
qitemp = ((1-h1*ajj)*(xi+h1*uij)+h1*aij*(xj+h1*uji))/Δtemp =#
h2 = h * (0.99*quanj / abs(qj - xj));
#= Δtemp=(1-h2*aii)*(1-h2*ajj)-h2*h2*aij*aji
qjtemp = ((1-h2*ajj)*(xi+h2*uij)+h2*aij*(xj+h2*uji))/Δtemp
if abs(qitemp - xi) > 1*quani || abs(qjtemp - xj) > 1*quanj
println("regle de croix did not work")
end =#
h=min(h1,h2)
h_three=h
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
#= if Δ==0
Δ=1e-12
println("delta liqss1 simulupdate==0")
end =#
if Δ!=0
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
end
if maxIter < 1 println("maxiter of updateQ = ",maxIter) end
end
if maxIter < 1
return false
end
q[index][0]=qi# store back helper vars
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
q[j][0]=qj
#= push!(simulqxiVals,abs(qi-xi))
push!(simulqxjVals,abs(qj-xj))
push!(simuldeltaiVals,quani)
push!(simuldeltajVals,quanj) =#
tq[j]=simt
end #end second dependecy check
return iscycle
end
#iters from 0===>1e-9
#= function nmisCycle_and_simulUpdate(cacheRootsi::Vector{Float64},cacheRootsj::Vector{Float64},acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{1},index::Int,j::Int,dirI::Float64,dti::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exactA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{1,Float64}},qaux::Vector{MVector{1,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exactA(q,d,cacheA,index,index,simt)
aii=cacheA[1]
cacheA[1]=0.0;exactA(q,d,cacheA,j,j,simt)
ajj=cacheA[1]
#= exactA(q,cacheA,index,j)
aij=cacheA[1]
exactA(q,cacheA,j,index)
aji=cacheA[1] =#
xi=x[index][0];xj=x[j][0];ẋi=x[index][1];ẋj=x[j][1]
qi=q[index][0];qj=q[j][0]
quanj=quantum[j];quani=quantum[index]
#qaux[j][1]=qj;
elapsed = simt - tx[j];x[j][0]= xj+elapsed*ẋj;
xj=x[j][0]
tx[j]=simt
qiminus=qaux[index][1]
#ujj=ẋj-ajj*qj
uji=ẋj-ajj*qj-aji*qiminus
#uii=dxaux[index][1]-aii*qaux[index][1]
uij=dxaux[index][1]-aii*qiminus-aij*qj
iscycle=false
dxj=aji*qi+ajj*qj+uji #only future qi #emulate fj
dxithrow=aii*qi+aij*qj+uij #only future qi
qjplus=xj+sign(dxj)*quanj #emulate updateQ(j)...
dxi=aii*qi+aij*qjplus+uij #both future qi & qj #emulate fi
#dxj2=ajj*qjplus+aji*qi+uji
#= if abs(dxithrow)<1e-15 && dxithrow!=0.0
dxithrow=0.0
end =#
########condition:Union
#= if abs(dxj)*3<abs(ẋj) || abs(dxj)>3*abs(ẋj) || (dxj*ẋj)<0.0
if abs(dxi)>3*abs(ẋi) || abs(dxi)*3<abs(ẋi) || (dxi*ẋi)<0.0
iscycle=true
end
end =#
########condition:Union i
#= if abs(dxj-ẋj)>(abs(dxj+ẋj)/2)
if abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2)
iscycle=true
end
end =#
########condition:Union i union
if (abs(dxj)*3<abs(ẋj) || abs(dxj)>3*abs(ẋj) || (dxj*ẋj)<0.0)
cancelCriteria=1e-6*quani
if abs(dxi)>3*abs(dxithrow) || abs(dxi)*3<abs(dxithrow) || (dxi*dxithrow)<0.0
iscycle=true
if abs(dxi)<cancelCriteria && abs(dxithrow)<cancelCriteria #significant change is relative to der values. cancel if all values are small
iscycle=false
# println("cancel dxi & dxthr small")
end
end
if abs(dxi)>10*abs(ẋi) || abs(dxi)*10<abs(ẋi) #|| (dxi*ẋi)<0.0
iscycle=true
if abs(dxi)<cancelCriteria && abs(ẋi)<cancelCriteria #significant change is relative to der values. cancel if all values are small
iscycle=false
# println("cancel dxi & ẋi small")
end
end
if abs(dxj)<1e-6*quanj && abs(ẋj)<1e-6*quanj #significant change is relative to der values. cancel if all values are small
iscycle=false
#println("cancel dxj & ẋj small")
end
end
#= if 9.087757893221387e-5<=simt<=9.23684654009e-5
println("simulUpdate $iscycle at simt=$simt index=$index, j=$j")
@show ẋi,dxi,dxithrow,ẋj,dxj
@show qj,xj
end =#
if iscycle
h=1e-9
h_=h
# h=firstguessH
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
#= if (abs(qi - xi) > 2*quani || abs(qj - xj) > 2*quanj) #checking qi-xi is not needed since firstguess just made it less than delta
h1 = (abs(quani / ẋi));h2 = (abs(quanj / ẋj));
h=min(h1,h2)
h_two=h
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
#= if Δ==0
Δ=1e-12
end =#
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
end =#
maxIter=1000
while (abs(qi - xi) < 2*quani || abs(qj - xj) < 2*quanj) && (maxIter>0) # maxiters here is better than maxiter in normal iters because here h is acceptable when we reach maxiter
maxIter-=1
h_=h
h1 = h * (1.001*quani / abs(qi - xi));
#= Δtemp=(1-h1*aii)*(1-h1*ajj)-h1*h1*aij*aji
qitemp = ((1-h1*ajj)*(xi+h1*uij)+h1*aij*(xj+h1*uji))/Δtemp =#
h2 = h * (1.001*quanj / abs(qj - xj));
#= Δtemp=(1-h2*aii)*(1-h2*ajj)-h2*h2*aij*aji
qjtemp = ((1-h2*ajj)*(xi+h2*uij)+h2*aij*(xj+h2*uji))/Δtemp
if abs(qitemp - xi) > 1*quani || abs(qjtemp - xj) > 1*quanj
println("regle de croix did not work")
end =#
h=max(h1,h2)
# h_three=h
Δ=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
#= if Δ==0
Δ=1e-12
println("delta liqss1 simulupdate==0")
end =#
if Δ!=0
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
end
if maxIter < 1 println("maxiter of updateQ = ",maxIter) end
end
h=h_ # go back to last h if exit the loop
qi = ((1-h*ajj)*(xi+h*uij)+h*aij*(xj+h*uji))/Δ
qj = ((1-h*aii)*(xj+h*uji)+h*aji*(xi+h*uij))/Δ
if maxIter < 1 # this is not needed in iters from 0
return false
end
q[index][0]=qi# store back helper vars
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
q[j][0]=qj
#= push!(simulqxiVals,abs(qi-xi))
push!(simulqxjVals,abs(qj-xj))
push!(simuldeltaiVals,quani)
push!(simuldeltajVals,quanj) =#
tq[j]=simt
end #end second dependecy check
return iscycle
end =#
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 29001 |
function nmisCycle_and_simulUpdate(cacheRootsi::Vector{Float64},cacheRootsj::Vector{Float64},acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{2},index::Int,j::Int,dirI::Float64,firstguessH::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exacteA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{2,Float64}},qaux::Vector{MVector{2,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exacteA(q,d,cacheA,index,index)
aii=cacheA[1]
cacheA[1]=0.0; exacteA(q,d,cacheA,j,j)
ajj=cacheA[1]
uii=dxaux[index][1]-aii*qaux[index][1]
ui2=dxaux[index][2]-aii*qaux[index][2]
#= uii=x[index][1]-aii*q[index][0]
ui2=x[index][2]-aii*q[index][1] =#
xi=x[index][0];xj=x[j][0];qi=q[index][0];qj=q[j][0];qi1=q[index][1];qj1=q[j][1];xi1=x[index][1];xi2=2*x[index][2];xj1=x[j][1];xj2=2*x[j][2]
#uii=u[index][index][1];ujj=u[j][j][1]#;uij=u[index][j][1];uji=u[j][index][1]#;uji2=u[j][index][2]
quanj=quantum[j];quani=quantum[index];
e1 = simt - tx[j];e2 = simt - tq[j];#= e3=simt - tu[j];tu[j]=simt; =#
prevXj=x[j][0]
x[j][0]= x[j](e1);xj=x[j][0];tx[j]=simt
qj=qj+e2*qj1 ;qaux[j][1]=qj;tq[j] = simt ;q[j][0]=qj
xj1=x[j][1]+e1*xj2;
newDiff=(xj-prevXj)
ujj=xj1-ajj*qj
#u[j][j][1]=ujj
uji=ujj-aji*qaux[index][1]#
#uji=u[j][index][1]
uj2=xj2-ajj*qj1###################################################-----------------------
uji2=uj2-aji*qaux[index][2]#
#u[j][index][2]=u[j][j][2]-ajj*qaux[index][1] # from article p20 line25 more cycles ...shaky with no bumps
# uji2=u[j][index][2]
dxj=aji*qi+ajj*qaux[j][1]+uji
ddxj=aji*qi1+ajj*qj1+uji2
if abs(ddxj)==0.0
ddxj=1e-30
if DEBUG2 @show ddxj end
end
iscycle=false
qjplus=xj-sign(ddxj)*quanj
hj=sqrt(2*quanj/abs(ddxj))#
α1=1-hj*ajj
if abs(α1)==0.0
α1=1e-30
@show α1
end
dqjplus=(aji*(qi+hj*qi1)+ajj*qjplus+uji+hj*uji2)/α1
uij=uii-aij*qaux[j][1]
# uij=u[index][j][1]
uij2=ui2-aij*qj1#########qaux[j][2] updated in normal Qupdate..ft=20 slightly shifts up
#β=dxi+sqrt(abs(ddxi)*quani/2)
#h2=sqrt(2*quani/abs(ddxi))
#uij2=u[index][j][2]
dxithrow=aii*qi+aij*qj+uij
ddxithrow=aii*qi1+aij*qj1+uij2
dxi=aii*qi+aij*qjplus+uij
ddxi=aii*qi1+aij*dqjplus+uij2
if abs(ddxi)==0.0
ddxi=1e-30
if DEBUG2 @show ddxi end
end
hi=sqrt(2*quani/abs(ddxi))
βidir=dxi+hi*ddxi/2
βjdir=dxj+hj*ddxj/2
βidth=dxithrow+hi*ddxithrow/2
αidir=xi1+hi*xi2/2
βj=xj1+hj*xj2/2
########condition:Union
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:Union i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:combineDer Union i
if abs(βjdir-βj)>(abs(βjdir+βj)/2) || dqjplus*newDiff<0.0
if abs(βidir-βidth)>(abs(βidir+βidth)/2) || βidir*dirI<0.0
iscycle=true
end
coef_signig=100
if (abs(dxi)>(abs(xi1)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#) || (abs(xi1)>(abs(dxi)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#)
iscycle=true
end
#= if abs(βidir-αidir)>(abs(βidir+αidir)/2)
iscycle=true
end =#
end
if (ddxithrow>0 && dxithrow<0 && qi1>0) || (ddxithrow<0 && dxithrow>0 && qi1<0)
xmin=xi-dxithrow*dxithrow/ddxithrow
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end
#= if (ddxi>0 && dxi<0 && qi1>0) || (ddxi<0 && dxi>0 && qi1<0)
xmin=xi-dxi*dxi/ddxi
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end =#
########condition:kinda signif alone i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) # || dqjplus*newDiff<0.0
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) #|| βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1 i
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
#= if index==1 && j==4 && 0.1<simt<1.1
iscycle=true
end =#
if iscycle
#= quani=1.7*quani
quanj=1.7*quanj =#
for i =1:7# 3 ord1 ,7 ord2
acceptedi[i][1]=0.0; acceptedi[i][2]=0.0
acceptedj[i][1]=0.0; acceptedj[i][2]=0.0
end
for i=1:12
cacheRootsi[i]=0.0
cacheRootsj[i]=0.0
end
trackSimul[1]+=1
aiijj=BigFloat(aii+ajj)
aiijj_=BigFloat(aij*aji-aii*ajj)
coefΔh0=4.0
coefΔh1=-8.0*aiijj
coefΔh2=6.0*aiijj*aiijj-4.0*aiijj_
coefΔh3=6.0*aiijj*aiijj_-2.0*aiijj*aiijj*aiijj
coefΔh4=aiijj_*aiijj_-4.0*aiijj_*aiijj*aiijj
coefΔh5=-3.0*aiijj*aiijj_*aiijj_
coefΔh6=-aiijj_*aiijj_*aiijj_
coefH0=4.0*xi
coefH1=-8.0*xi*aiijj
#coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*aii*ajj-aji*aij+ajj*ajj)-aij*aiijj*xj)
coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-3.0*aiijj_+2.0*aiijj*aiijj+aiijj*ajj)-aij*aiijj*xj)
#coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(2.0*aii*ajj-aji*aij+ajj*ajj)+ajj*aiijj_*xi+aij*aiijj*aiijj*xj-aij*aiijj_*xj)
coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(ajj*aiijj-aiijj_)+ajj*aiijj_*xi+aij*aiijj*aiijj*xj-aij*aiijj_*xj)
coefH4=2.0*(aiijj*(uij*aiijj_-ajj*uij2+aij*uji2)-0.5*(2.0*aii*ajj-aji*aij+ajj*ajj)*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-ajj*aiijj_*aiijj*xi+0.5*aij*aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)+aij*aiijj_*aiijj*xj)
coefH5=(2.0*aii*ajj-aji*aij+ajj*ajj)*(ajj*uij2-uij*aiijj_-aij*uji2)-ajj*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-aij*aiijj*(aii*uji2-uji*aiijj_-aji*uij2)+aij*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)
coefH6=ajj*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)-aij*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)
coefH0j=4.0*xj
coefH1j=-8.0*xj*aiijj
coefH2j=2.0*(-ajj*uji-aji*uij-uji2+xj*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*ajj*aii-aij*aji+aii*aii)-aji*aiijj*xi)
coefH3j=2.0*((-uji*aiijj_+aii*uji2-aji*uij2)+aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-xj*aiijj*(2.0*ajj*aii-aij*aji+aii*aii)+aii*aiijj_*xj+aji*aiijj*aiijj*xi-aji*aiijj_*xi)
coefH4j=2.0*(aiijj*(uji*aiijj_-aii*uji2+aji*uij2)-0.5*(aii*aiijj-aiijj_)*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aii*aiijj_*aiijj*xj+0.5*aji*aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)+aji*aiijj_*aiijj*xi)
coefH5j=(aii*aiijj-aiijj_)*(aii*uji2-uji*aiijj_-aji*uij2)-aii*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aji*aiijj*(ajj*uij2-uij*aiijj_-aij*uji2)+aji*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)
coefH6j=aii*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)-aji*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)
#= coefi=NTuple{7,Float64}((coefH6-coefΔh6*(xi+quani),coefH5-coefΔh5*(xi+quani),coefH4-coefΔh4*(xi+quani),coefH3-coefΔh3*(xi+quani),coefH2-coefΔh2*(xi+quani),coefH1-coefΔh1*(xi+quani),coefH0-coefΔh0*(xi+quani)))
coefi2=NTuple{7,Float64}((coefH6-coefΔh6*(xi-quani),coefH5-coefΔh5*(xi-quani),coefH4-coefΔh4*(xi-quani),coefH3-coefΔh3*(xi-quani),coefH2-coefΔh2*(xi-quani),coefH1-coefΔh1*(xi-quani),coefH0-coefΔh0*(xi-quani)))
coefj=NTuple{7,Float64}((coefH6j-coefΔh6*(xj+quanj),coefH5j-coefΔh5*(xj+quanj),coefH4j-coefΔh4*(xj+quanj),coefH3j-coefΔh3*(xj+quanj),coefH2j-coefΔh2*(xj+quanj),coefH1j-coefΔh1*(xj+quanj),coefH0j-coefΔh0*(xj+quanj)))
coefj2=NTuple{7,Float64}((coefH6j-coefΔh6*(xj-quanj),coefH5j-coefΔh5*(xj-quanj),coefH4j-coefΔh4*(xj-quanj),coefH3j-coefΔh3*(xj-quanj),coefH2j-coefΔh2*(xj-quanj),coefH1j-coefΔh1*(xj-quanj),coefH0j-coefΔh0*(xj-quanj)))
resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12=0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12=0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
Base.GC.enable(false)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefi,respp,pp)
resi1,resi2,resi3,resi4,resi5,resi6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefi2,respp,pp)
resi7,resi8,resi9,resi10,resi11,resi12=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefj,respp,pp)
resj1,resj2,resj3,resj4,resj5,resj6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefj2,respp,pp)
resj7,resj8,resj9,resj10,resj11,resj12=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
Base.GC.enable(true) =#
#to be deleted: test
#= for h in (resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
if h>0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
if abs(qi-xi)>2quani
error("your own h not working for you, i")
end
end
end
end
for h in (resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12)
if h>0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
if abs(qj-xj)>2quanj
error("your own h not working for you, j")
end
end
end
end
#filter roots
counterRooti=1
for h in (resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
if h>0 && h!=Inf
cacheRootsi[counterRooti]=h
counterRooti+=1
end
end
sort!(cacheRootsi);
counterRootj=1
for h in (resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12)
if h>0 && h!=Inf
cacheRootsj[counterRootj]=h
counterRootj+=1
end
end =#
#= coefi=[coefH0-coefΔh0*(xi+quani),coefH1-coefΔh1*(xi+quani),coefH2-coefΔh2*(xi+quani),coefH3-coefΔh3*(xi+quani),coefH4-coefΔh4*(xi+quani),coefH5-coefΔh5*(xi+quani),coefH6-coefΔh6*(xi+quani)]
coefj=[coefH0j-coefΔh0*(xj+quanj),coefH1j-coefΔh1*(xj+quanj),coefH2j-coefΔh2*(xj+quanj),coefH3j-coefΔh3*(xj+quanj),coefH4j-coefΔh4*(xj+quanj),coefH5j-coefΔh5*(xj+quanj),coefH6j-coefΔh6*(xj+quanj)]
coefi2=[coefH0-coefΔh0*(xi-quani),coefH1-coefΔh1*(xi-quani),coefH2-coefΔh2*(xi-quani),coefH3-coefΔh3*(xi-quani),coefH4-coefΔh4*(xi-quani),coefH5-coefΔh5*(xi-quani),coefH6-coefΔh6*(xi-quani)]
coefj2=[coefH0j-coefΔh0*(xj-quanj),coefH1j-coefΔh1*(xj-quanj),coefH2j-coefΔh2*(xj-quanj),coefH3j-coefΔh3*(xj-quanj),coefH4j-coefΔh4*(xj-quanj),coefH5j-coefΔh5*(xj-quanj),coefH6j-coefΔh6*(xj-quanj)]
=#
coefi=[BigFloat(coefH0-coefΔh0*(xi+quani)),BigFloat(coefH1-coefΔh1*(xi+quani)),BigFloat(coefH2-coefΔh2*(xi+quani)),BigFloat(coefH3-coefΔh3*(xi+quani)),BigFloat(coefH4-coefΔh4*(xi+quani)),BigFloat(coefH5-coefΔh5*(xi+quani)),BigFloat(coefH6-coefΔh6*(xi+quani))]
coefj=[BigFloat(coefH0j-coefΔh0*(xj+quanj)),BigFloat(coefH1j-coefΔh1*(xj+quanj)),BigFloat(coefH2j-coefΔh2*(xj+quanj)),BigFloat(coefH3j-coefΔh3*(xj+quanj)),BigFloat(coefH4j-coefΔh4*(xj+quanj)),BigFloat(coefH5j-coefΔh5*(xj+quanj)),BigFloat(coefH6j-coefΔh6*(xj+quanj))]
coefi2=[BigFloat(coefH0-coefΔh0*(xi-quani)),BigFloat(coefH1-coefΔh1*(xi-quani)),BigFloat(coefH2-coefΔh2*(xi-quani)),BigFloat(coefH3-coefΔh3*(xi-quani)),BigFloat(coefH4-coefΔh4*(xi-quani)),BigFloat(coefH5-coefΔh5*(xi-quani)),BigFloat(coefH6-coefΔh6*(xi-quani))]
coefj2=[BigFloat(coefH0j-coefΔh0*(xj-quanj)),BigFloat(coefH1j-coefΔh1*(xj-quanj)),BigFloat(coefH2j-coefΔh2*(xj-quanj)),BigFloat(coefH3j-coefΔh3*(xj-quanj)),BigFloat(coefH4j-coefΔh4*(xj-quanj)),BigFloat(coefH5j-coefΔh5*(xj-quanj)),BigFloat(coefH6j-coefΔh6*(xj-quanj))]
ri=roots(coefi)
rj=roots(coefj)
ri2=roots(coefi2)
rj2=roots(coefj2)
#filter roots
counterRooti=1
for h in ri
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsi[counterRooti]=(real(h))
counterRooti+=1
end
end
checkRoots(cacheRootsi,coefi,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quani)
for h in ri2
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsi[counterRooti]=(real(h))
counterRooti+=1
end
end
sort!(cacheRootsi);
counterRootj=1
for h in rj
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsj[counterRootj]=(real(h))
counterRootj+=1
end
end
checkRoots(cacheRootsj,coefj,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quanj)
for h in rj2
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsj[counterRootj]=(real(h))
counterRootj+=1
end
end
sort!(cacheRootsj);
#= for h in cacheRootsi
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
if abs(qi-xi)>2quani
error("your own h not working for you, i")
end
end
end
for h in cacheRootsj
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
if abs(qj-xj)>2quanj
error("your own h not working for you, j")
end
end
end =#
#construct intervals
constructIntrval(acceptedi,cacheRootsi)
constructIntrval(acceptedj,cacheRootsj)
ki=7;kj=7
h=-1.0
while true
if ki==0 || kj==0
error("bug in finding the overlap")
end
currentLi=acceptedi[ki][1];currentHi=acceptedi[ki][2]
currentLj=acceptedj[kj][1];currentHj=acceptedj[kj][2]
if currentLj<=currentLi<currentHj || currentLi<=currentLj<currentHi#resj[end][1]<=resi[end][1]<=resj[end][2] || resi[end][1]<=resj[end][1]<=resi[end][2] #overlap
h=min(currentHi,currentHj )
if h==Inf && (currentLj!=0.0 || currentLi!=0.0) # except case both 0 sols h1=(0,Inf)
h=max(currentLj,currentLi#= ,ft-simt,dti =#) #ft-simt in case they are both ver small...elaborate on his later
#= if simt==2.500745083181994e-5
@show currentLj,currentLi
end =#
end
if h==Inf # both lower bounds ==0 --> zero sols for both
if aiijj_!=0.0
qi=coefH6/coefΔh6
qj=coefH6j/coefΔh6
#qi=getQfromAsymptote(xi,coefH0,coefH1,coefH2,coefH3,coefH4,coefH5,coefH6,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6)
#qj=getQfromAsymptote(xj,coefH0j,coefH1j,coefH2j,coefH3j,coefH4j,coefH5j,coefH6j,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6)
qi1=(aji*uij2-uji2*aij)/aiijj_ #resul of ddx=aq+aq+u=0 ...2eqs 2 unknowns
qj1=(-uij2-aii*qi1)/aij
else
return false
end
else #h!=Inf
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ22)!=0.0 && Δ1!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
#= if 2.500745083181994e-5<=simt<3.00745083181994e-5
@show "simul: ",index,qi,xi,quani,h,simt,j,qj,xj,quanj
end =#
else
println("singularities Δ22=0")#do iterations
maxIter=10000
while (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj) && (maxIter>0)
maxIter-=1
h1 = h * sqrt(quani / abs(qi - xi));
h2 = h * sqrt(quanj / abs(qj - xj));
#= h1 = h * (0.99*1.8*quani / abs(qi - xi));
h2 = h * (0.99*1.8*quanj / abs(qj - xj)); =#
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
if maxIter==0 || Δ1==0.0 # maxIter=0 :failed to bring q down within a reasonable time. Δ1==0.0 should never happen when maxIter>0...but keep it there for now
return false
end
end
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
end
break
else
if currentHj==0.0 && currentHi==0.0#empty
ki-=1;kj-=1
elseif currentHj==0.0 && currentHi!=0.0
kj-=1
elseif currentHi==0.0 && currentHj!=0.0
ki-=1
else #both non zero
if currentLj<currentLi#remove last seg of resi
ki-=1
else #remove last seg of resj
kj-=1
end
end
end
end # end while
#checkRoots(cacheRootsi,coefi,coefi2) # for free stress-testing allrealrootintervalnewtonregulafalsi
# checkRoots(cacheRootsj,coefj,coefj2) #later check if error in roots makes q-x >2quan...use commented code below
q[index][0]=Float64(qi)# store back helper vars
q[j][0]=Float64(qj)
q[index][1]=Float64(qi1)
q[j][1]=Float64(qj1)
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
end #end if iscycle
return iscycle
end
#= function checkRootsIntNew(cacheRootsi,coefi,coefi2)
for h in cacheRootsi
zci=abs(coefi[1]*h^6+coefi[2]*h^5+coefi[3]*h^4+coefi[4]*h^3+coefi[5]*h^2+coefi[6]*h+coefi[7])
zci2=abs(coefi2[1]*h^6+coefi2[2]*h^5+coefi2[3]*h^4+coefi2[4]*h^3+coefi2[5]*h^2+coefi2[6]*h+coefi2[7])
if zci>1e-6 && zci2>1e-6
println("error in mliqss_quantizer2: coming from root solver ")
@show h,coefi,zci
@show coefi2,zci2
end
end
end =#
#= function checkRoots(cacheRootsi,coefi,coefi2)
for h in cacheRootsi
if h>0 # cache is large and contains 0 0 0 0 0 0
zci=abs(coefi[7]*h^6+coefi[6]*h^5+coefi[5]*h^4+coefi[4]*h^3+coefi[3]*h^2+coefi[2]*h+coefi[1])
zci2=abs(coefi2[7]*h^6+coefi2[6]*h^5+coefi2[5]*h^4+coefi2[4]*h^3+coefi2[3]*h^2+coefi2[2]*h+coefi2[1])
if zci>1e-5 && zci2>1e-5
println("error in mliqss_quantizer2: coming from root solver ")
if zci>1e-5 @show h,coefi,zci end
if zci2>1e-5 @show h,coefi2,zci2 end
end
end
end
end =#
function checkRoots(cacheRootsi,coefi,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quani)
for h in cacheRootsi
if h>0 # cache is large and contains 0 0 0 0 0 0
zci=abs(coefi[7]*h^6+coefi[6]*h^5+coefi[5]*h^4+coefi[4]*h^3+coefi[3]*h^2+coefi[2]*h+coefi[1])
Δ=coefΔh0+h*coefΔh1+coefΔh2*h*h+coefΔh3*h^3+coefΔh4*h^4+coefΔh5*h^5+coefΔh6*h^6
if (zci/(Δ*Δ))>(quani/10)
println("zci not zero makes q changes by more than a quan...root finding not good...Δ=$Δ")
@show h,zci,quani,coefi
end
#= if zci>1e-5
println("error in mliqss_quantizer2: coming from root solver ")
@show h,coefi,zci
end =#
end
end
end
#= function getQfromAsymptote(x::Float64,coefH0::Float64,coefH1::P,coefH2::P,coefH3::P,coefH4::P,coefH5::P,coefH6::P,coefΔh0::Float64,coefΔh1::P,coefΔh2::P,coefΔh3::P,coefΔh4::P,coefΔh5::P,coefΔh6::P) where {P<:Union{BigFloat,Float64}}
q=0.0
if coefΔh6==0.0 && coefH6!=0.0
@show coefΔh6,coefH6
error("report bug in simul2: could appear when a var becomes a NaN")
elseif coefΔh6==0.0 && coefH6==0.0
if coefΔh5==0.0 && coefH5!=0.0
println("simul2: coef5 asymptote should not be outside of +-delta !!!")
elseif coefΔh5==0.0 && coefH5==0.0
if coefΔh4==0.0 && coefH4!=0.0
println("simul2: coef4 asymptote should not be outside of +-delta !!!")
elseif coefΔh4==0.0 && coefH4==0.0
if coefΔh3==0.0 && coefH3!=0.0
println("simul2: coef3 asymptote should not be outside of +-delta !!!")
elseif coefΔh3==0.0 && coefH3==0.0
if coefΔh2==0.0 && coefH2!=0.0
println("simul2: coef2 asymptote should not be outside of +-delta !!!")
elseif coefΔh2==0.0 && coefH2==0.0
if coefΔh1==0.0 && coefH1!=0.0
println("simul2: coef1 asymptote should not be outside of +-delta !!!")
elseif coefΔh1==0.0 && coefH1==0.0
if coefΔh0!=0.0
q=coefH0/coefΔh0
else
q=x
end
else#coefΔh1!=0.0
q=coefH1/coefΔh1
end
else#coefΔh2!=0.0
q=coefH2/coefΔh2
end
else#coefΔh3!=0.0
q=coefH3/coefΔh3
end
else#coefΔh4!=0.0
q=coefH4/coefΔh4
end
else#coefΔh5!=0.0
q=coefH5/coefΔh5
end
else#coefΔh6!=0.0
q=coefH6/coefΔh6
end
q
end =# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 28942 |
function nmisCycle_and_simulUpdate(cacheRootsi::Vector{Float64},cacheRootsj::Vector{Float64},acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{2},index::Int,j::Int,dirI::Float64,firstguessH::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exacteA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{2,Float64}},qaux::Vector{MVector{2,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exacteA(q,d,cacheA,index,index)
aii=cacheA[1]
cacheA[1]=0.0; exacteA(q,d,cacheA,j,j)
ajj=cacheA[1]
uii=dxaux[index][1]-aii*qaux[index][1]
ui2=dxaux[index][2]-aii*qaux[index][2]
#= uii=x[index][1]-aii*q[index][0]
ui2=x[index][2]-aii*q[index][1] =#
xi=x[index][0];xj=x[j][0];qi=q[index][0];qj=q[j][0];qi1=q[index][1];qj1=q[j][1];xi1=x[index][1];xi2=2*x[index][2];xj1=x[j][1];xj2=2*x[j][2]
#uii=u[index][index][1];ujj=u[j][j][1]#;uij=u[index][j][1];uji=u[j][index][1]#;uji2=u[j][index][2]
quanj=quantum[j];quani=quantum[index];
e1 = simt - tx[j];e2 = simt - tq[j];#= e3=simt - tu[j];tu[j]=simt; =#
prevXj=x[j][0]
x[j][0]= x[j](e1);xj=x[j][0];tx[j]=simt
qj=qj+e2*qj1 ;qaux[j][1]=qj;tq[j] = simt ;q[j][0]=qj
xj1=x[j][1]+e1*xj2;
newDiff=(xj-prevXj)
ujj=xj1-ajj*qj
#u[j][j][1]=ujj
uji=ujj-aji*qaux[index][1]#
#uji=u[j][index][1]
uj2=xj2-ajj*qj1###################################################-----------------------
uji2=uj2-aji*qaux[index][2]#
#u[j][index][2]=u[j][j][2]-ajj*qaux[index][1] # from article p20 line25 more cycles ...shaky with no bumps
# uji2=u[j][index][2]
dxj=aji*qi+ajj*qaux[j][1]+uji
ddxj=aji*qi1+ajj*qj1+uji2
if abs(ddxj)==0.0
ddxj=1e-30
if DEBUG2 @show ddxj end
end
iscycle=false
qjplus=xj-sign(ddxj)*quanj
hj=sqrt(2*quanj/abs(ddxj))#
α1=1-hj*ajj
if abs(α1)==0.0
α1=1e-30
@show α1
end
dqjplus=(aji*(qi+hj*qi1)+ajj*qjplus+uji+hj*uji2)/α1
uij=uii-aij*qaux[j][1]
# uij=u[index][j][1]
uij2=ui2-aij*qj1#########qaux[j][2] updated in normal Qupdate..ft=20 slightly shifts up
#β=dxi+sqrt(abs(ddxi)*quani/2)
#h2=sqrt(2*quani/abs(ddxi))
#uij2=u[index][j][2]
dxithrow=aii*qi+aij*qj+uij
ddxithrow=aii*qi1+aij*qj1+uij2
dxi=aii*qi+aij*qjplus+uij
ddxi=aii*qi1+aij*dqjplus+uij2
if abs(ddxi)==0.0
ddxi=1e-30
if DEBUG2 @show ddxi end
end
hi=sqrt(2*quani/abs(ddxi))
βidir=dxi+hi*ddxi/2
βjdir=dxj+hj*ddxj/2
βidth=dxithrow+hi*ddxithrow/2
αidir=xi1+hi*xi2/2
βj=xj1+hj*xj2/2
########condition:Union
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:Union i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:combineDer Union i
if abs(βjdir-βj)>(abs(βjdir+βj)/2) || dqjplus*newDiff<0.0
if abs(βidir-βidth)>(abs(βidir+βidth)/2) || βidir*dirI<0.0
iscycle=true
end
coef_signig=100
if (abs(dxi)>(abs(xi1)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#) || (abs(xi1)>(abs(dxi)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#)
iscycle=true
end
#= if abs(βidir-αidir)>(abs(βidir+αidir)/2)
iscycle=true
end =#
end
if (ddxithrow>0 && dxithrow<0 && qi1>0) || (ddxithrow<0 && dxithrow>0 && qi1<0)
xmin=xi-dxithrow*dxithrow/ddxithrow
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end
#= if (ddxi>0 && dxi<0 && qi1>0) || (ddxi<0 && dxi>0 && qi1<0)
xmin=xi-dxi*dxi/ddxi
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end =#
########condition:kinda signif alone i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) # || dqjplus*newDiff<0.0
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) #|| βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1 i
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
#= if index==1 && j==4 && 0.1<simt<1.1
iscycle=true
end =#
if iscycle
#= quani=1.7*quani
quanj=1.7*quanj =#
for i =1:7# 3 ord1 ,7 ord2
acceptedi[i][1]=0.0; acceptedi[i][2]=0.0
acceptedj[i][1]=0.0; acceptedj[i][2]=0.0
end
for i=1:12
cacheRootsi[i]=0.0
cacheRootsj[i]=0.0
end
trackSimul[1]+=1
aiijj=(aii+ajj)
aiijj_=(aij*aji-aii*ajj)
coefΔh0=4.0
coefΔh1=-8.0*aiijj
coefΔh2=6.0*aiijj*aiijj-4.0*aiijj_
coefΔh3=6.0*aiijj*aiijj_-2.0*aiijj*aiijj*aiijj
coefΔh4=aiijj_*aiijj_-4.0*aiijj_*aiijj*aiijj
coefΔh5=-3.0*aiijj*aiijj_*aiijj_
coefΔh6=-aiijj_*aiijj_*aiijj_
coefH0=4.0*xi
coefH1=-8.0*xi*aiijj
#coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*aii*ajj-aji*aij+ajj*ajj)-aij*aiijj*xj)
coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-3.0*aiijj_+2.0*aiijj*aiijj+aiijj*ajj)-aij*aiijj*xj)
#coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(2.0*aii*ajj-aji*aij+ajj*ajj)+ajj*aiijj_*xi+aij*aiijj*aiijj*xj-aij*aiijj_*xj)
coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(ajj*aiijj-aiijj_)+ajj*aiijj_*xi+aij*aiijj*aiijj*xj-aij*aiijj_*xj)
coefH4=2.0*(aiijj*(uij*aiijj_-ajj*uij2+aij*uji2)-0.5*(2.0*aii*ajj-aji*aij+ajj*ajj)*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-ajj*aiijj_*aiijj*xi+0.5*aij*aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)+aij*aiijj_*aiijj*xj)
coefH5=(2.0*aii*ajj-aji*aij+ajj*ajj)*(ajj*uij2-uij*aiijj_-aij*uji2)-ajj*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-aij*aiijj*(aii*uji2-uji*aiijj_-aji*uij2)+aij*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)
coefH6=ajj*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)-aij*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)
coefH0j=4.0*xj
coefH1j=-8.0*xj*aiijj
coefH2j=2.0*(-ajj*uji-aji*uij-uji2+xj*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*ajj*aii-aij*aji+aii*aii)-aji*aiijj*xi)
coefH3j=2.0*((-uji*aiijj_+aii*uji2-aji*uij2)+aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-xj*aiijj*(2.0*ajj*aii-aij*aji+aii*aii)+aii*aiijj_*xj+aji*aiijj*aiijj*xi-aji*aiijj_*xi)
coefH4j=2.0*(aiijj*(uji*aiijj_-aii*uji2+aji*uij2)-0.5*(aii*aiijj-aiijj_)*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aii*aiijj_*aiijj*xj+0.5*aji*aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)+aji*aiijj_*aiijj*xi)
coefH5j=(aii*aiijj-aiijj_)*(aii*uji2-uji*aiijj_-aji*uij2)-aii*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aji*aiijj*(ajj*uij2-uij*aiijj_-aij*uji2)+aji*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)
coefH6j=aii*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)-aji*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)
#= coefi=NTuple{7,Float64}((coefH6-coefΔh6*(xi+quani),coefH5-coefΔh5*(xi+quani),coefH4-coefΔh4*(xi+quani),coefH3-coefΔh3*(xi+quani),coefH2-coefΔh2*(xi+quani),coefH1-coefΔh1*(xi+quani),coefH0-coefΔh0*(xi+quani)))
coefi2=NTuple{7,Float64}((coefH6-coefΔh6*(xi-quani),coefH5-coefΔh5*(xi-quani),coefH4-coefΔh4*(xi-quani),coefH3-coefΔh3*(xi-quani),coefH2-coefΔh2*(xi-quani),coefH1-coefΔh1*(xi-quani),coefH0-coefΔh0*(xi-quani)))
coefj=NTuple{7,Float64}((coefH6j-coefΔh6*(xj+quanj),coefH5j-coefΔh5*(xj+quanj),coefH4j-coefΔh4*(xj+quanj),coefH3j-coefΔh3*(xj+quanj),coefH2j-coefΔh2*(xj+quanj),coefH1j-coefΔh1*(xj+quanj),coefH0j-coefΔh0*(xj+quanj)))
coefj2=NTuple{7,Float64}((coefH6j-coefΔh6*(xj-quanj),coefH5j-coefΔh5*(xj-quanj),coefH4j-coefΔh4*(xj-quanj),coefH3j-coefΔh3*(xj-quanj),coefH2j-coefΔh2*(xj-quanj),coefH1j-coefΔh1*(xj-quanj),coefH0j-coefΔh0*(xj-quanj)))
resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12=0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12=0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
Base.GC.enable(false)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefi,respp,pp)
resi1,resi2,resi3,resi4,resi5,resi6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefi2,respp,pp)
resi7,resi8,resi9,resi10,resi11,resi12=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefj,respp,pp)
resj1,resj2,resj3,resj4,resj5,resj6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefj2,respp,pp)
resj7,resj8,resj9,resj10,resj11,resj12=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
Base.GC.enable(true) =#
#to be deleted: test
#= for h in (resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
if h>0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
if abs(qi-xi)>2quani
error("your own h not working for you, i")
end
end
end
end
for h in (resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12)
if h>0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
if abs(qj-xj)>2quanj
error("your own h not working for you, j")
end
end
end
end
#filter roots
counterRooti=1
for h in (resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
if h>0 && h!=Inf
cacheRootsi[counterRooti]=h
counterRooti+=1
end
end
sort!(cacheRootsi);
counterRootj=1
for h in (resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12)
if h>0 && h!=Inf
cacheRootsj[counterRootj]=h
counterRootj+=1
end
end =#
coefi=[coefH0-coefΔh0*(xi+quani),coefH1-coefΔh1*(xi+quani),coefH2-coefΔh2*(xi+quani),coefH3-coefΔh3*(xi+quani),coefH4-coefΔh4*(xi+quani),coefH5-coefΔh5*(xi+quani),coefH6-coefΔh6*(xi+quani)]
coefj=[coefH0j-coefΔh0*(xj+quanj),coefH1j-coefΔh1*(xj+quanj),coefH2j-coefΔh2*(xj+quanj),coefH3j-coefΔh3*(xj+quanj),coefH4j-coefΔh4*(xj+quanj),coefH5j-coefΔh5*(xj+quanj),coefH6j-coefΔh6*(xj+quanj)]
coefi2=[coefH0-coefΔh0*(xi-quani),coefH1-coefΔh1*(xi-quani),coefH2-coefΔh2*(xi-quani),coefH3-coefΔh3*(xi-quani),coefH4-coefΔh4*(xi-quani),coefH5-coefΔh5*(xi-quani),coefH6-coefΔh6*(xi-quani)]
coefj2=[coefH0j-coefΔh0*(xj-quanj),coefH1j-coefΔh1*(xj-quanj),coefH2j-coefΔh2*(xj-quanj),coefH3j-coefΔh3*(xj-quanj),coefH4j-coefΔh4*(xj-quanj),coefH5j-coefΔh5*(xj-quanj),coefH6j-coefΔh6*(xj-quanj)]
#= coefi=[BigFloat(coefH0-coefΔh0*(xi+quani)),BigFloat(coefH1-coefΔh1*(xi+quani)),BigFloat(coefH2-coefΔh2*(xi+quani)),BigFloat(coefH3-coefΔh3*(xi+quani)),BigFloat(coefH4-coefΔh4*(xi+quani)),BigFloat(coefH5-coefΔh5*(xi+quani)),BigFloat(coefH6-coefΔh6*(xi+quani))]
coefj=[BigFloat(coefH0j-coefΔh0*(xj+quanj)),BigFloat(coefH1j-coefΔh1*(xj+quanj)),BigFloat(coefH2j-coefΔh2*(xj+quanj)),BigFloat(coefH3j-coefΔh3*(xj+quanj)),BigFloat(coefH4j-coefΔh4*(xj+quanj)),BigFloat(coefH5j-coefΔh5*(xj+quanj)),BigFloat(coefH6j-coefΔh6*(xj+quanj))]
coefi2=[BigFloat(coefH0-coefΔh0*(xi-quani)),BigFloat(coefH1-coefΔh1*(xi-quani)),BigFloat(coefH2-coefΔh2*(xi-quani)),BigFloat(coefH3-coefΔh3*(xi-quani)),BigFloat(coefH4-coefΔh4*(xi-quani)),BigFloat(coefH5-coefΔh5*(xi-quani)),BigFloat(coefH6-coefΔh6*(xi-quani))]
coefj2=[BigFloat(coefH0j-coefΔh0*(xj-quanj)),BigFloat(coefH1j-coefΔh1*(xj-quanj)),BigFloat(coefH2j-coefΔh2*(xj-quanj)),BigFloat(coefH3j-coefΔh3*(xj-quanj)),BigFloat(coefH4j-coefΔh4*(xj-quanj)),BigFloat(coefH5j-coefΔh5*(xj-quanj)),BigFloat(coefH6j-coefΔh6*(xj-quanj))]
=#
ri=roots(coefi)
rj=roots(coefj)
ri2=roots(coefi2)
rj2=roots(coefj2)
#filter roots
counterRooti=1
for h in ri
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsi[counterRooti]=Float64(real(h))
counterRooti+=1
end
end
checkRoots(cacheRootsi,coefi,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quani)
for h in ri2
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsi[counterRooti]=Float64(real(h))
counterRooti+=1
end
end
sort!(cacheRootsi);
counterRootj=1
for h in rj
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsj[counterRootj]=Float64(real(h))
counterRootj+=1
end
end
checkRoots(cacheRootsj,coefj,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quanj)
for h in rj2
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsj[counterRootj]=Float64(real(h))
counterRootj+=1
end
end
sort!(cacheRootsj);
#= for h in cacheRootsi
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
if abs(qi-xi)>2quani
error("your own h not working for you, i")
end
end
end
for h in cacheRootsj
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
if abs(qj-xj)>2quanj
error("your own h not working for you, j")
end
end
end =#
#construct intervals
constructIntrval(acceptedi,cacheRootsi)
constructIntrval(acceptedj,cacheRootsj)
ki=7;kj=7
h=-1.0
while true
if ki==0 || kj==0
error("bug in finding the overlap")
end
currentLi=acceptedi[ki][1];currentHi=acceptedi[ki][2]
currentLj=acceptedj[kj][1];currentHj=acceptedj[kj][2]
if currentLj<=currentLi<currentHj || currentLi<=currentLj<currentHi#resj[end][1]<=resi[end][1]<=resj[end][2] || resi[end][1]<=resj[end][1]<=resi[end][2] #overlap
h=min(currentHi,currentHj )
if h==Inf && (currentLj!=0.0 || currentLi!=0.0) # except case both 0 sols h1=(0,Inf)
h=max(currentLj,currentLi#= ,ft-simt,dti =#) #ft-simt in case they are both ver small...elaborate on his later
#= if simt==2.500745083181994e-5
@show currentLj,currentLi
end =#
end
if h==Inf # both lower bounds ==0 --> zero sols for both
if aiijj_!=0.0
qi=coefH6/coefΔh6
qj=coefH6j/coefΔh6
#qi=getQfromAsymptote(xi,coefH0,coefH1,coefH2,coefH3,coefH4,coefH5,coefH6,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6)
#qj=getQfromAsymptote(xj,coefH0j,coefH1j,coefH2j,coefH3j,coefH4j,coefH5j,coefH6j,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6)
qi1=(aji*uij2-uji2*aij)/aiijj_ #resul of ddx=aq+aq+u=0 ...2eqs 2 unknowns
qj1=(-uij2-aii*qi1)/aij
else
return false
end
else #h!=Inf
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ22)!=0.0 && Δ1!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
#= if 2.500745083181994e-5<=simt<3.00745083181994e-5
@show "simul: ",index,qi,xi,quani,h,simt,j,qj,xj,quanj
end =#
else
println("singularities Δ22=0")#do iterations
maxIter=10000
while (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj) && (maxIter>0)
maxIter-=1
h1 = h * sqrt(quani / abs(qi - xi));
h2 = h * sqrt(quanj / abs(qj - xj));
#= h1 = h * (0.99*1.8*quani / abs(qi - xi));
h2 = h * (0.99*1.8*quanj / abs(qj - xj)); =#
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
if maxIter==0 || Δ1==0.0 # maxIter=0 :failed to bring q down within a reasonable time. Δ1==0.0 should never happen when maxIter>0...but keep it there for now
return false
end
end
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
end
break
else
if currentHj==0.0 && currentHi==0.0#empty
ki-=1;kj-=1
elseif currentHj==0.0 && currentHi!=0.0
kj-=1
elseif currentHi==0.0 && currentHj!=0.0
ki-=1
else #both non zero
if currentLj<currentLi#remove last seg of resi
ki-=1
else #remove last seg of resj
kj-=1
end
end
end
end # end while
#checkRoots(cacheRootsi,coefi,coefi2) # for free stress-testing allrealrootintervalnewtonregulafalsi
# checkRoots(cacheRootsj,coefj,coefj2) #later check if error in roots makes q-x >2quan...use commented code below
q[index][0]=(qi)# store back helper vars
q[j][0]=(qj)
q[index][1]=(qi1)
q[j][1]=(qj1)
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
end #end if iscycle
return iscycle
end
#= function checkRootsIntNew(cacheRootsi,coefi,coefi2)
for h in cacheRootsi
zci=abs(coefi[1]*h^6+coefi[2]*h^5+coefi[3]*h^4+coefi[4]*h^3+coefi[5]*h^2+coefi[6]*h+coefi[7])
zci2=abs(coefi2[1]*h^6+coefi2[2]*h^5+coefi2[3]*h^4+coefi2[4]*h^3+coefi2[5]*h^2+coefi2[6]*h+coefi2[7])
if zci>1e-6 && zci2>1e-6
println("error in mliqss_quantizer2: coming from root solver ")
@show h,coefi,zci
@show coefi2,zci2
end
end
end =#
#= function checkRoots(cacheRootsi,coefi,coefi2)
for h in cacheRootsi
if h>0 # cache is large and contains 0 0 0 0 0 0
zci=abs(coefi[7]*h^6+coefi[6]*h^5+coefi[5]*h^4+coefi[4]*h^3+coefi[3]*h^2+coefi[2]*h+coefi[1])
zci2=abs(coefi2[7]*h^6+coefi2[6]*h^5+coefi2[5]*h^4+coefi2[4]*h^3+coefi2[3]*h^2+coefi2[2]*h+coefi2[1])
if zci>1e-5 && zci2>1e-5
println("error in mliqss_quantizer2: coming from root solver ")
if zci>1e-5 @show h,coefi,zci end
if zci2>1e-5 @show h,coefi2,zci2 end
end
end
end
end =#
function checkRoots(cacheRootsi,coefi,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quani)
for h in cacheRootsi
if h>0 # cache is large and contains 0 0 0 0 0 0
zci=abs(coefi[7]*h^6+coefi[6]*h^5+coefi[5]*h^4+coefi[4]*h^3+coefi[3]*h^2+coefi[2]*h+coefi[1])
Δ=coefΔh0+h*coefΔh1+coefΔh2*h*h+coefΔh3*h^3+coefΔh4*h^4+coefΔh5*h^5+coefΔh6*h^6
if (zci/Δ*Δ)>quani
error("zci not zero makes q changes by more than a quan...root finding not good...Δ=$Δ")
end
#= if zci>1e-5
println("error in mliqss_quantizer2: coming from root solver ")
@show h,coefi,zci
end =#
end
end
end
#= function getQfromAsymptote(x::Float64,coefH0::Float64,coefH1::P,coefH2::P,coefH3::P,coefH4::P,coefH5::P,coefH6::P,coefΔh0::Float64,coefΔh1::P,coefΔh2::P,coefΔh3::P,coefΔh4::P,coefΔh5::P,coefΔh6::P) where {P<:Union{BigFloat,Float64}}
q=0.0
if coefΔh6==0.0 && coefH6!=0.0
@show coefΔh6,coefH6
error("report bug in simul2: could appear when a var becomes a NaN")
elseif coefΔh6==0.0 && coefH6==0.0
if coefΔh5==0.0 && coefH5!=0.0
println("simul2: coef5 asymptote should not be outside of +-delta !!!")
elseif coefΔh5==0.0 && coefH5==0.0
if coefΔh4==0.0 && coefH4!=0.0
println("simul2: coef4 asymptote should not be outside of +-delta !!!")
elseif coefΔh4==0.0 && coefH4==0.0
if coefΔh3==0.0 && coefH3!=0.0
println("simul2: coef3 asymptote should not be outside of +-delta !!!")
elseif coefΔh3==0.0 && coefH3==0.0
if coefΔh2==0.0 && coefH2!=0.0
println("simul2: coef2 asymptote should not be outside of +-delta !!!")
elseif coefΔh2==0.0 && coefH2==0.0
if coefΔh1==0.0 && coefH1!=0.0
println("simul2: coef1 asymptote should not be outside of +-delta !!!")
elseif coefΔh1==0.0 && coefH1==0.0
if coefΔh0!=0.0
q=coefH0/coefΔh0
else
q=x
end
else#coefΔh1!=0.0
q=coefH1/coefΔh1
end
else#coefΔh2!=0.0
q=coefH2/coefΔh2
end
else#coefΔh3!=0.0
q=coefH3/coefΔh3
end
else#coefΔh4!=0.0
q=coefH4/coefΔh4
end
else#coefΔh5!=0.0
q=coefH5/coefΔh5
end
else#coefΔh6!=0.0
q=coefH6/coefΔh6
end
q
end =# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 30522 |
function nmisCycle_and_simulUpdate(cacheRootsi::Vector{Float64},cacheRootsj::Vector{Float64},acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{2},index::Int,j::Int,dirI::Float64,firstguessH::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exactA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{2,Float64}},qaux::Vector{MVector{2,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exactA(q,d,cacheA,index,index,simt)
aii=cacheA[1]
cacheA[1]=0.0; exactA(q,d,cacheA,j,j,simt)
ajj=cacheA[1]
uii=dxaux[index][1]-aii*qaux[index][1]
ui2=dxaux[index][2]-aii*qaux[index][2]
#= uii=x[index][1]-aii*q[index][0]
ui2=x[index][2]-aii*q[index][1] =#
xi=x[index][0];xj=x[j][0];qi=q[index][0];qj=q[j][0];qi1=q[index][1];qj1=q[j][1];xi1=x[index][1];xi2=2*x[index][2];xj1=x[j][1];xj2=2*x[j][2]
#uii=u[index][index][1];ujj=u[j][j][1]#;uij=u[index][j][1];uji=u[j][index][1]#;uji2=u[j][index][2]
quanj=quantum[j];quani=quantum[index];
e1 = simt - tx[j];e2 = simt - tq[j];#= e3=simt - tu[j];tu[j]=simt; =#
prevXj=x[j][0]
x[j][0]= x[j](e1);xj=x[j][0];tx[j]=simt
qj=qj+e2*qj1 ;qaux[j][1]=qj;tq[j] = simt ;q[j][0]=qj
xj1=x[j][1]+e1*xj2;
newDiff=(xj-prevXj)
#= dirj=direction[j]
if newDiff*dirj <0.0
dirj=-dirj
elseif newDiff==0 && dirj!=0.0
dirj=0.0
elseif newDiff!=0 && dirj==0.0
dirj=newDiff
else
end
direction[j]=dirj =#
#ujj=ujj+e1*u[j][j][2]
ujj=xj1-ajj*qj
#u[j][j][1]=ujj
uji=ujj-aji*qaux[index][1]#
#uji=u[j][index][1]
uj2=xj2-ajj*qj1###################################################-----------------------
uji2=uj2-aji*qaux[index][2]#
#u[j][index][2]=u[j][j][2]-ajj*qaux[index][1] # from article p20 line25 more cycles ...shaky with no bumps
# uji2=u[j][index][2]
dxj=aji*qi+ajj*qaux[j][1]+uji
ddxj=aji*qi1+ajj*qj1+uji2
if abs(ddxj)==0.0
ddxj=1e-30
if DEBUG2 @show ddxj end
end
iscycle=false
qjplus=xj-sign(ddxj)*quanj
hj=sqrt(2*quanj/abs(ddxj))#
α1=1-hj*ajj
if abs(α1)==0.0
α1=1e-30
@show α1
end
dqjplus=(aji*(qi+hj*qi1)+ajj*qjplus+uji+hj*uji2)/α1
uij=uii-aij*qaux[j][1]
# uij=u[index][j][1]
uij2=ui2-aij*qj1#########qaux[j][2] updated in normal Qupdate..ft=20 slightly shifts up
#β=dxi+sqrt(abs(ddxi)*quani/2)
#h2=sqrt(2*quani/abs(ddxi))
#uij2=u[index][j][2]
dxithrow=aii*qi+aij*qj+uij
ddxithrow=aii*qi1+aij*qj1+uij2
dxi=aii*qi+aij*qjplus+uij
ddxi=aii*qi1+aij*dqjplus+uij2
if abs(ddxi)==0.0
ddxi=1e-30
if DEBUG2 @show ddxi end
end
hi=sqrt(2*quani/abs(ddxi))
βidir=dxi+hi*ddxi/2
βjdir=dxj+hj*ddxj/2
βidth=dxithrow+hi*ddxithrow/2
αidir=xi1+hi*xi2/2
βj=xj1+hj*xj2/2
########condition:Union
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2)) || βidir*dirI<0.0
iscycle=true
end
end
########condition:Union i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:combineDer Union i
#= if abs(βjdir-βj)>(abs(βjdir+βj)/2) || dqjplus*newDiff<0.0
if abs(βidir-βidth)>(abs(βidir+βidth)/2) || βidir*dirI<0.0
iscycle=true
end
coef_signig=100
if (abs(dxi)>(abs(xi1)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#) || (abs(xi1)>(abs(dxi)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#)
iscycle=true
end
#= if abs(βidir-αidir)>(abs(βidir+αidir)/2)
iscycle=true
end =#
end =#
if (ddxithrow>0 && dxithrow<0 && qi1>0) || (ddxithrow<0 && dxithrow>0 && qi1<0)
xmin=xi-dxithrow*dxithrow/ddxithrow
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end
#= if (ddxi>0 && dxi<0 && qi1>0) || (ddxi<0 && dxi>0 && qi1<0)
xmin=xi-dxi*dxi/ddxi
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end =#
########condition:kinda signif alone i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) # || dqjplus*newDiff<0.0
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) #|| βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1 i
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
#= if index==1 && j==4 && 0.1<simt<1.1
iscycle=true
end =#
if iscycle
aiijj=aii+ajj
aiijj_=aij*aji-aii*ajj
coefΔh1=-8.0*aiijj
coefΔh2=6.0*aiijj*aiijj-4.0*aiijj_
coefΔh3=6.0*aiijj*aiijj_-2.0*aiijj*aiijj*aiijj
coefΔh4=aiijj_*aiijj_-4.0*aiijj_*aiijj*aiijj
coefΔh5=-3.0*aiijj*aiijj_*aiijj_
coefΔh6=-aiijj_*aiijj_*aiijj_
coefH1=-8.0*xi*aiijj
coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*aii*ajj-aji*aij+ajj*ajj)-aij*aiijj*xj)
coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(2.0*aii*ajj-aji*aij+ajj*ajj)+ajj*aiijj_*xi+aij*aiijj*aiijj*xj-aij*aiijj_*xj)
coefH4=2.0*(aiijj*(uij*aiijj_-ajj*uij2+aij*uji2)-0.5*(2.0*aii*ajj-aji*aij+ajj*ajj)*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-ajj*aiijj_*aiijj*xi+0.5*aij*aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)+aij*aiijj_*aiijj*xj)
coefH5=(2.0*aii*ajj-aji*aij+ajj*ajj)*(ajj*uij2-uij*aiijj_-aij*uji2)-ajj*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-aij*aiijj*(aii*uji2-uji*aiijj_-aji*uij2)+aij*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)
coefH6=ajj*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)-aij*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)
coefH1j=-8.0*xj*aiijj
coefH2j=2.0*(-ajj*uji-aji*uij-uji2+xj*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*ajj*aii-aij*aji+aii*aii)-aji*aiijj*xi)
coefH3j=2.0*((-uji*aiijj_+aii*uji2-aji*uij2)+aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-xj*aiijj*(2.0*ajj*aii-aij*aji+aii*aii)+aii*aiijj_*xj+aji*aiijj*aiijj*xi-aji*aiijj_*xi)
coefH4j=2.0*(aiijj*(uji*aiijj_-aii*uji2+aji*uij2)-0.5*(2.0*ajj*aii-aij*aji+aii*aii)*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aii*aiijj_*aiijj*xj+0.5*aji*aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)+aji*aiijj_*aiijj*xi)
coefH5j=(2.0*ajj*aii-aij*aji+aii*aii)*(aii*uji2-uji*aiijj_-aji*uij2)-aii*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aji*aiijj*(ajj*uij2-uij*aiijj_-aij*uji2)+aji*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)
coefH6j=aii*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)-aji*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)
h = ft-simt
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
if (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj)
h1 = sqrt(abs(2*quani/xi2));h2 = sqrt(abs(2*quanj/xj2)); #later add derderX =1e-12 when x2==0?
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
maxIter=10000
while (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj) && (maxIter>0)
maxIter-=1
h1 = h * sqrt(quani / abs(qi - xi));
h2 = h * sqrt(quanj / abs(qj - xj));
#= h1 = h * (0.99*1.8*quani / abs(qi - xi));
h2 = h * (0.99*1.8*quanj / abs(qj - xj)); =#
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
#qi,qj,Δ1=Float64(qi),Float64(qj),Float64(Δ1)
if maxIter<900 #ie simul step failed
println("simulstep $maxIter")
end
if maxIter==0 #ie simul step failed
println("simulstep failed maxiter")
return false
end
if 0<h<1e-20 #ie simul step failed # h==0 is allowed because is like an equilibrium
println("simulstep failed small h=",h)
@show simt,maxIter
return false
end
if Δ1==0.0 # should never happen when maxIter>0...before deployement, group the 2 prev if statments
println("iter simul Δ1 ==0")
return false
end
q[index][0]=qi# store back helper vars
q[j][0]=qj
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
q[index][1]=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# store back helper vars
q[j][1]=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
#= if abs(qi-xi)<quani/1000 && abs(qj-xj)<quanj/1000 && simt<5.0
#if quani/1000<abs(qi-xi)<quani/10 && quanj/1000<abs(qj-xj)<quanj/10
println("end of simul: qi & qj thrown both very close")
@show abs(qi-xi),quani , abs(qj-xj),quanj
@show simt
end =#
end #end if iscycle
return iscycle
end
####################################nliqss################################################################
#=
function nisCycle_and_simulUpdate(::Val{2},index::Int,j::Int#= ,prevStepVal::Float64 =#,direction::Vector{Float64}, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},map::Function,cacheA::MVector{1,Float64},dxaux::Vector{MVector{O,Float64}},qaux::Vector{MVector{O,Float64}},olddx::Vector{MVector{O,Float64}},olddxSpec::Vector{MVector{O,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64,qminus::Vector{Float64})where{O}
# @timeit "inside nmisCycle block1" begin
#aii=getA(Val(Sparsity),cacheA,a,index,index,map);ajj=getA(Val(Sparsity),cacheA,a,j,j,map);aij=getA(Val(Sparsity),cacheA,a,index,j,map);aji=getA(Val(Sparsity),cacheA,a,j,index,map)
#aii=a[index][index];ajj=a[j][j];aij=a[index][j];aji=a[j][index]
map(q,cacheA,index,index)
aii=cacheA[1]
map(q,cacheA,j,j)
ajj=cacheA[1]
map(q,cacheA,index,j)
aij=cacheA[1]
map(q,cacheA,j,index)
aji=cacheA[1]
xi=x[index][0];xj=x[j][0];qi=q[index][0];qj=q[j][0];qi1=q[index][1];qj1=q[j][1];xi1=x[index][1];xi2=2*x[index][2];xj1=x[j][1];xj2=2*x[j][2]
# uii=u[index][index][1];#ujj=u[j][j][1]#;uij=u[index][j][1];uji=u[j][index][1]#;uji2=u[j][index][2]
uii=dxaux[index][1]-aii*qaux[index][1]
# u[index][index][1]=uii
ui2=dxaux[index][2]-aii*qaux[index][2]
# u[index][index][2]=ui2
# ui2=u[index][index][2]
quanj=quantum[j];quani=quantum[index];
e1 = simt - tx[j];e2 = simt - tq[j];#= e3=simt - tu[j];tu[j]=simt; =#
x[j][0]= x[j](e1);xj=x[j][0];tx[j]=simt
qminus[j]=qj
qj=qj+e2*qj1 ;qaux[j][1]=qj;tq[j] = simt ;q[j][0]=qj
xj1=x[j][1]+e1*xj2;olddxSpec[j][1]=xj1;olddx[j][1]=xj1
#= newDiff=(xj-prevStepVal)
dirj=direction[j]
if newDiff*dirj <0.0
dirj=-dirj
elseif newDiff==0 && dirj!=0.0
dirj=0.0
elseif newDiff!=0 && dirj==0.0
dirj=newDiff
else
end
direction[j]=dirj =#
#ujj=ujj+e1*u[j][j][2]
ujj=xj1-ajj*qj
#u[j][j][1]=ujj
uji=ujj-aji*qaux[index][1]#
# u[j][index][1]=uji
#u[j][j][2]=xj2-ajj*qj1###################################################-----------------------
uj2=xj2-ajj*qj1
# u[j][j][2]=uj2
uji2=uj2-aji*qaux[index][2]#
#u[j][index][2]=u[j][j][2]-ajj*qaux[index][1] # from article p20 line25 more cycles ...shaky with no bumps
# u[j][index][2]=uji2
#@show uji2
dxj=aji*qi+ajj*qaux[j][1]+uji
ddxj=aji*qi1+ajj*qj1+uji2
#@show aji,ajj,uji2
iscycle=false
qjplus=xj-sign(ddxj)*quanj
h=sqrt(2*quanj/abs(ddxj))#2*quantum funny oscillating graph; xj2 vibrating
dqjplus=(aji*(qi+h*qi1)+ajj*qjplus+uji+h*uji2)/(1-h*ajj)
#end#end init iscycle
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #|| (dqjplus)*dirj<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
#β=dxi+sqrt(abs(ddxi)*quani/2)
#h2=sqrt(2*quani/abs(ddxi))
uij=uii-aij*qaux[j][1]
# u[index][j][1]=uij
uij2=ui2-aij*qj1#########qaux[j][2] updated in normal Qupdate..ft=20 slightly shifts up
# u[index][j][2]=uij2
dxi=aii*qi+aij*qjplus+uij
ddxi=aii*qi1+aij*dqjplus+uij2
βidir=dxi+sqrt(2*quani/abs(ddxi))*ddxi/2
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2)) #|| βidir*direction[index]<0.0
# @timeit "inside nmisCycle block2" begin
iscycle=true
h = ft-simt
Δ1=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
αii=(aii*(1-h*ajj)+h*aij*aji)/Δ1
αij=((1-h*ajj)*aij+h*aij*ajj)/Δ1
αji=(aji*aii*h+(1-h*aii)*aji)/Δ1
αjj=(h*aji*aij+(1-h*aii)*ajj)/Δ1
βii=1+h*(αii-aii)-h*h*(aii*αii+aij*αji)/2
βij=h*(αij-aij)-h*h*(aii*αij+aij*αjj)/2
βji=h*(αji-aji)-h*h*(aji*αii+ajj*αji)/2
βjj=1+h*(αjj-ajj)-h*h*(aji*αij+ajj*αjj)/2
Δ2=βii*βjj-βij*βji
λii=(h*h*aii/2-h)*(1-h*ajj)+h*h*h*aji*aij/2
λij=(h*h*aii/2-h)*h*aij+h*h*aij*(1-h*aii)/2
λji=h*h*aji/2*(1-h*ajj)+(h*h*ajj/2-h)*h*aji
λjj=h*h*h*aij*aji/2+(h*h*ajj/2-h)*(1-h*aii)
parti=((λii*(uij+h*uij2)+λij*(uji+h*uji2))/Δ1)+(xi+h*uij+h*h*uij2/2)#part1[1]+xpart2[1]#
partj=((λji*(uij+h*uij2)+λjj*(uji+h*uji2))/Δ1)+(xj+h*uji+h*h*uji2/2)#part1[2]+xpart2[2]#
qi=((βjj/Δ2)*parti-(βij/Δ2)*partj)
qj=((βii/Δ2)*partj-(βji/Δ2)*parti)
if (abs(qi - xi) > 2*quani || abs(qj - xj) > 2*quanj)
h1 = sqrt(abs(2*quani/xi2));h2 = sqrt(abs(2*quanj/xj2)); #later add derderX =1e-12 when x2==0
h=min(h1,h2)
Δ1=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
αii=(aii*(1-h*ajj)+h*aij*aji)/Δ1
αij=((1-h*ajj)*aij+h*aij*ajj)/Δ1
αji=(aji*aii*h+(1-h*aii)*aji)/Δ1
αjj=(h*aji*aij+(1-h*aii)*ajj)/Δ1
βii=1+h*(αii-aii)-h*h*(aii*αii+aij*αji)/2
βij=h*(αij-aij)-h*h*(aii*αij+aij*αjj)/2
βji=h*(αji-aji)-h*h*(aji*αii+ajj*αji)/2
βjj=1+h*(αjj-ajj)-h*h*(aji*αij+ajj*αjj)/2
Δ2=βii*βjj-βij*βji
λii=(h*h*aii/2-h)*(1-h*ajj)+h*h*h*aji*aij/2
λij=(h*h*aii/2-h)*h*aij+h*h*aij*(1-h*aii)/2
λji=h*h*aji/2*(1-h*ajj)+(h*h*ajj/2-h)*h*aji
λjj=h*h*h*aij*aji/2+(h*h*ajj/2-h)*(1-h*aii)
parti=((λii*(uij+h*uij2)+λij*(uji+h*uji2))/Δ1)+(xi+h*uij+h*h*uij2/2)#part1[1]+xpart2[1]#
partj=((λji*(uij+h*uij2)+λjj*(uji+h*uji2))/Δ1)+(xj+h*uji+h*h*uji2/2)#part1[2]+xpart2[2]#
qi=((βjj/Δ2)*parti-(βij/Δ2)*partj)
qj=((βii/Δ2)*partj-(βji/Δ2)*parti)
end
maxIter=600
while (abs(qi - xi) > 2*quani || abs(qj - xj) > 2*quanj) && (maxIter>0)
maxIter-=1
#= h1 = h * (0.98*quani / abs(qi - xi));
h2 = h * (0.98*quanj / abs(qj - xj)); =#
h1 = h * sqrt(quani / abs(qi - xi));
h2 = h * sqrt(quanj / abs(qj - xj));
h=min(h1,h2)
Δ1=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
αii=(aii*(1-h*ajj)+h*aij*aji)/Δ1
αij=((1-h*ajj)*aij+h*aij*ajj)/Δ1
αji=(aji*aii*h+(1-h*aii)*aji)/Δ1
αjj=(h*aji*aij+(1-h*aii)*ajj)/Δ1
βii=1+h*(αii-aii)-h*h*(aii*αii+aij*αji)/2
βij=h*(αij-aij)-h*h*(aii*αij+aij*αjj)/2
βji=h*(αji-aji)-h*h*(aji*αii+ajj*αji)/2
βjj=1+h*(αjj-ajj)-h*h*(aji*αij+ajj*αjj)/2
Δ2=βii*βjj-βij*βji
λii=(h*h*aii/2-h)*(1-h*ajj)+h*h*h*aji*aij/2
λij=(h*h*aii/2-h)*h*aij+h*h*aij*(1-h*aii)/2
λji=h*h*aji/2*(1-h*ajj)+(h*h*ajj/2-h)*h*aji
λjj=h*h*h*aij*aji/2+(h*h*ajj/2-h)*(1-h*aii)
parti=((λii*(uij+h*uij2)+λij*(uji+h*uji2))/Δ1)+(xi+h*uij+h*h*uij2/2)#part1[1]+xpart2[1]#
partj=((λji*(uij+h*uij2)+λjj*(uji+h*uji2))/Δ1)+(xj+h*uji+h*h*uji2/2)#part1[2]+xpart2[2]#
qi=((βjj/Δ2)*parti-(βij/Δ2)*partj)
qj=((βii/Δ2)*partj-(βji/Δ2)*parti)
end
if maxIter < 1
@show maxIter
@show simt
@show a
end
q[index][0]=qi# store back helper vars
q[j][0]=qj
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
q[index][1]=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# store back helper vars
q[j][1]=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
# end#end block2?????????????????????????????????????????????????????????????????
end #end second dependecy check
end # end outer dependency check
return iscycle
end
=#
#####################################old mliqss
function isCycle_and_simulUpdate(::Val{2},index::Int,j::Int,#= direction::Vector{Float64}, =# x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},a::Vector{Vector{Float64}},u::Vector{Vector{MVector{O,Float64}}},qaux::Vector{MVector{O,Float64}},olddx::Vector{MVector{O,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)where{O}
aii=a[index][index];ajj=a[j][j];aij=a[index][j];aji=a[j][index];
# aii=getA(Val(Sparsity),cacheA,a,index,index,map);ajj=getA(Val(Sparsity),cacheA,a,j,j,map);aij=getA(Val(Sparsity),cacheA,a,index,j,map);aji=getA(Val(Sparsity),cacheA,a,j,index,map)
xi=x[index][0];xj=x[j][0];qi=q[index][0];qj=q[j][0];qi1=q[index][1];qj1=q[j][1];xi1=x[index][1];xi2=2*x[index][2];xj1=x[j][1];xj2=2*x[j][2]
uii=u[index][index][1];ujj=u[j][j][1]#;uij=u[index][j][1];uji=u[j][index][1]#;uji2=u[j][index][2]
quanj=quantum[j];quani=quantum[index];
e1 = simt - tx[j];e2 = simt - tq[j];#= e3=simt - tu[j];tu[j]=simt; =#
x[j][0]= x[j](e1);xj=x[j][0];tx[j]=simt
qj=qj+e2*qj1 ;qaux[j][1]=qj;tq[j] = simt ;q[j][0]=qj
xj1=x[j][1]+e1*xj2#= ;olddxSpec[j][1]=xj1 =#;olddx[j][1]=xj1
# ujj=ujj+e1*u[j][j][2]
ujj=xj1-ajj*qj
u[j][j][1]=ujj
u[j][index][1]=ujj-aji*qaux[index][1]# using q[i][0] creates a really huge bump at 18 (no go) because we want to elaps-update uji
uji=u[j][index][1]
u[j][j][2]=xj2-ajj*qj1###################################################-----------------------
u[j][index][2]=u[j][j][2]-aji*qaux[index][2]#less cycles but with a bump at 1.5...ft20: smooth with some bumps
#u[j][index][2]=u[j][j][2]-ajj*qaux[index][1] # from article p20 line25 more cycles ...shaky with no bumps
uji2=u[j][index][2]
dxj=aji*qi+ajj*qaux[j][1]+uji
ddxj=aji*qi1+ajj*qj1+uji2
iscycle=false
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2))
qjplus=xj-sign(ddxj)*quanj
h=sqrt(2*quanj/abs(ddxj))#2*quantum funny oscillating graph; xj2 vibrating
dqjplus=(aji*(qi+h*qi1)+ajj*qjplus+uji+h*uji2)/(1-h*ajj)
u[index][j][1]=uii-aij*qaux[j][1]
uij=u[index][j][1]
u[index][j][2]=u[index][index][2]-aij*qj1#########qaux[j][2] updated in normal Qupdate..ft=20 slightly shifts up
uij2=u[index][j][2]
dxi=aii*qi+aij*qjplus+uij
ddxi=aii*qi1+aij*dqjplus+uij2
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2))
iscycle=true
h = ft-simt
Δ1=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
αii=(aii*(1-h*ajj)+h*aij*aji)/Δ1
αij=((1-h*ajj)*aij+h*aij*ajj)/Δ1
αji=(aji*aii*h+(1-h*aii)*aji)/Δ1
αjj=(h*aji*aij+(1-h*aii)*ajj)/Δ1
βii=1+h*(αii-aii)-h*h*(aii*αii+aij*αji)/2
βij=h*(αij-aij)-h*h*(aii*αij+aij*αjj)/2
βji=h*(αji-aji)-h*h*(aji*αii+ajj*αji)/2
βjj=1+h*(αjj-ajj)-h*h*(aji*αij+ajj*αjj)/2
Δ2=βii*βjj-βij*βji
λii=(h*h*aii/2-h)*(1-h*ajj)+h*h*h*aji*aij/2
λij=(h*h*aii/2-h)*h*aij+h*h*aij*(1-h*aii)/2
λji=h*h*aji/2*(1-h*ajj)+(h*h*ajj/2-h)*h*aji
λjj=h*h*h*aij*aji/2+(h*h*ajj/2-h)*(1-h*aii)
parti=((λii*(uij+h*uij2)+λij*(uji+h*uji2))/Δ1)+(xi+h*uij+h*h*uij2/2)#part1[1]+xpart2[1]#
partj=((λji*(uij+h*uij2)+λjj*(uji+h*uji2))/Δ1)+(xj+h*uji+h*h*uji2/2)#part1[2]+xpart2[2]#
qi=((βjj/Δ2)*parti-(βij/Δ2)*partj)
qj=((βii/Δ2)*partj-(βji/Δ2)*parti)
if (abs(qi - xi) > 2*quani || abs(qj - xj) > 2*quanj)
h1 = sqrt(abs(2*quani/xi2));h2 = sqrt(abs(2*quanj/xj2)); #later add derderX =1e-12 when x2==0
h=min(h1,h2)
Δ1=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
αii=(aii*(1-h*ajj)+h*aij*aji)/Δ1
αij=((1-h*ajj)*aij+h*aij*ajj)/Δ1
αji=(aji*aii*h+(1-h*aii)*aji)/Δ1
αjj=(h*aji*aij+(1-h*aii)*ajj)/Δ1
βii=1+h*(αii-aii)-h*h*(aii*αii+aij*αji)/2
βij=h*(αij-aij)-h*h*(aii*αij+aij*αjj)/2
βji=h*(αji-aji)-h*h*(aji*αii+ajj*αji)/2
βjj=1+h*(αjj-ajj)-h*h*(aji*αij+ajj*αjj)/2
Δ2=βii*βjj-βij*βji
λii=(h*h*aii/2-h)*(1-h*ajj)+h*h*h*aji*aij/2
λij=(h*h*aii/2-h)*h*aij+h*h*aij*(1-h*aii)/2
λji=h*h*aji/2*(1-h*ajj)+(h*h*ajj/2-h)*h*aji
λjj=h*h*h*aij*aji/2+(h*h*ajj/2-h)*(1-h*aii)
parti=((λii*(uij+h*uij2)+λij*(uji+h*uji2))/Δ1)+(xi+h*uij+h*h*uij2/2)#part1[1]+xpart2[1]#
partj=((λji*(uij+h*uij2)+λjj*(uji+h*uji2))/Δ1)+(xj+h*uji+h*h*uji2/2)#part1[2]+xpart2[2]#
qi=((βjj/Δ2)*parti-(βij/Δ2)*partj)
qj=((βii/Δ2)*partj-(βji/Δ2)*parti)
end
maxIter=600
while (abs(qi - xi) > 2*quani || abs(qj - xj) > 2*quanj) && (maxIter>0)
maxIter-=1
#= h1 = h * (0.98*quani / abs(qi - xi));
h2 = h * (0.98*quanj / abs(qj - xj)); =#
h1 = h * sqrt(quani / abs(qi - xi));
h2 = h * sqrt(quanj / abs(qj - xj));
h=min(h1,h2)
Δ1=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
αii=(aii*(1-h*ajj)+h*aij*aji)/Δ1
αij=((1-h*ajj)*aij+h*aij*ajj)/Δ1
αji=(aji*aii*h+(1-h*aii)*aji)/Δ1
αjj=(h*aji*aij+(1-h*aii)*ajj)/Δ1
βii=1+h*(αii-aii)-h*h*(aii*αii+aij*αji)/2
βij=h*(αij-aij)-h*h*(aii*αij+aij*αjj)/2
βji=h*(αji-aji)-h*h*(aji*αii+ajj*αji)/2
βjj=1+h*(αjj-ajj)-h*h*(aji*αij+ajj*αjj)/2
Δ2=βii*βjj-βij*βji
λii=(h*h*aii/2-h)*(1-h*ajj)+h*h*h*aji*aij/2
λij=(h*h*aii/2-h)*h*aij+h*h*aij*(1-h*aii)/2
λji=h*h*aji/2*(1-h*ajj)+(h*h*ajj/2-h)*h*aji
λjj=h*h*h*aij*aji/2+(h*h*ajj/2-h)*(1-h*aii)
parti=((λii*(uij+h*uij2)+λij*(uji+h*uji2))/Δ1)+(xi+h*uij+h*h*uij2/2)#part1[1]+xpart2[1]#
partj=((λji*(uij+h*uij2)+λjj*(uji+h*uji2))/Δ1)+(xj+h*uji+h*h*uji2/2)#part1[2]+xpart2[2]#
qi=((βjj/Δ2)*parti-(βij/Δ2)*partj)
qj=((βii/Δ2)*partj-(βji/Δ2)*parti)
end
if maxIter < 1
@show maxIter
@show simt
@show a
end
q[index][0]=qi# store back helper vars
q[j][0]=qj
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
q[index][1]=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# store back helper vars
q[j][1]=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
end #end second dependecy check
end # end outer dependency check
return iscycle
end
#=
function updateQ(::Val{2},i::Int, xv::Vector{Taylor0},qv::Vector{Taylor0}, quantum::Vector{Float64}#= ,av::Vector{Vector{Float64}} =#,exactA::Function,cacheA::MVector{1,Float64},dxaux::Vector{MVector{O,Float64}},qaux::Vector{MVector{O,Float64}},olddx::Vector{MVector{O,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64, nextTime::Vector{Float64})where{O}
#a=getA(Val(Sparsity),cacheA,av,i,i,map)
#a=av[i][i]
cacheA[1]=0.0; exactA(qv,cacheA,i,i)
a=cacheA[1]
# @show a,i
q=qv[i][0] ;q1=qv[i][1]; x=xv[i][0]; x1=xv[i][1]; x2=xv[i][2]*2; #u1=uv[i][i][1]; u2=uv[i][i][2]
qaux[i][1]=q#+(simt-tq[i])*q1#appears only here...updated here and used in updateApprox and in updateQevent later
qaux[i][2]=q1 #appears only here...updated here and used in updateQevent
olddx[i][1]=x1#appears only here...updated here and used in updateApprox
olddx[i][2]=x2
#u1=u1+(simt-tu[i])*u2 # for order 2: u=u+tu*deru this is necessary deleting causes scheduler error
u1=x1-a*qaux[i][1]
# uv[i][i][1]=u1
dxaux[i][1]=x1
dxaux[i][2]=x2
u2=x2-a*q1
# uv[i][i][2]= u2
# tu[i]=simt
# olddx[i][2]=2*x2#
ddx=x2
quan=quantum[i]
h=0.0
if a!=0.0
if ddx ==0.0
ddx=a*a*q+a*u1 +u2
if ddx==0.0
ddx=1e-40# changing -40 to -6 nothing changed
# println("ddx=0")
end
end
h = ft-simt
#tempH1=h
#q = ((x + h * u1 + h * h / 2 * u2) * (1 - h * a) + (h * h / 2 * a - h) * (u1 + h * u2)) /(1 - h * a + h * h * a * a / 2)
q=(x-h*a*x-h*h*(a*u1+u2)/2)/(1 - h * a + h * h * a * a / 2)
if (abs(q - x) > 2* quan) # removing this did nothing...check @btime later
h = sqrt(abs(2*quan / ddx)) # sqrt highly recommended...removing it leads to many sim steps..//2* is necessary in 2*quan when using ddx
q = ((x + h * u1 + h * h / 2 * u2) * (1 - h * a) + (h * h / 2 * a - h) * (u1 + h * u2)) /
(1 - h * a + h * h * a * a / 2)
# q = (x-h*a*x-h*h*(a*u1+u2)/2)/(1 - h * a + h * h * a * a / 2)
end
maxIter=1000
# tempH=h
#= if (abs(q - x) >2* quan)
coef=@SVector [quan, a*quan,-(a*a*(x-quan)+a*u1+u2)/2]#
h1= minPosRoot(coef, Val(2))
coef=@SVector [-quan, -a*quan,-(a*a*(x+quan)+a*u1+u2)/2]#
h2= minPosRoot(coef, Val(2))
if h1<h2
h=h1;q=x-quan
else
h=h2;q=x+quan
end
end =#
while (abs(q - x) >2* quan) && (maxIter>0) && (h>0)
h = h *sqrt(quan / abs(q - x))
q = ((x + h * u1 + h * h / 2 * u2) * (1 - h * a) + (h * h / 2 * a - h) * (u1 + h * u2)) /
(1 - h * a + h * h * a * a / 2)
# q = (x-h*a*x-h*h*(a*u1+u2)/2)/(1 - h * a + h * h * a * a / 2)
maxIter-=1
end
q1=(a*q+u1+h*u2)/(1-h*a) #later investigate 1=h*a
else
if x2!=0.0
h=sqrt(abs(2*quan/x2)) #sqrt necessary with u2
q=x-h*h*x2/2
q1=x1+h*x2
else
# println("x2==0")
if x1!=0.0
h=abs(quan/x1)
q=x+h*x1
q1=x1
else
h=Inf
q=x
q1=x1
end
end
end
qv[i][0]=q
qv[i][1]=q1
nextTime[i]=simt+h
return nothing
end =# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 21966 |
function nmisCycle_and_simulUpdate(cacheRootsi::Vector{BigFloat},cacheRootsj::Vector{BigFloat},acceptedi::Vector{Vector{BigFloat}},acceptedj::Vector{Vector{BigFloat}},aij::Float64,aji::Float64,respp::Ptr{BigFloat}, pp::Ptr{NTuple{2,BigFloat}},trackSimul,::Val{2},index::Int,j::Int,dirI::Float64,firstguessH::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exacteA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{2,Float64}},qaux::Vector{MVector{2,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exacteA(q,d,cacheA,index,index)
aii=cacheA[1]
cacheA[1]=0.0; exacteA(q,d,cacheA,j,j)
ajj=cacheA[1]
uii=dxaux[index][1]-aii*qaux[index][1]
ui2=dxaux[index][2]-aii*qaux[index][2]
#= uii=x[index][1]-aii*q[index][0]
ui2=x[index][2]-aii*q[index][1] =#
xi=x[index][0];xj=x[j][0];qi=q[index][0];qj=q[j][0];qi1=q[index][1];qj1=q[j][1];xi1=x[index][1];xi2=2*x[index][2];xj1=x[j][1];xj2=2*x[j][2]
#uii=u[index][index][1];ujj=u[j][j][1]#;uij=u[index][j][1];uji=u[j][index][1]#;uji2=u[j][index][2]
quanj=quantum[j];quani=quantum[index];
e1 = simt - tx[j];e2 = simt - tq[j];#= e3=simt - tu[j];tu[j]=simt; =#
prevXj=x[j][0]
x[j][0]= x[j](e1);xjaux=x[j][0];tx[j]=simt
qj=qj+e2*qj1 ;qaux[j][1]=qj;tq[j] = simt ;q[j][0]=qj
xj1=x[j][1]+e1*xj2;
newDiff=(xjaux-prevXj)
#= dirj=direction[j]
if newDiff*dirj <0.0
dirj=-dirj
elseif newDiff==0 && dirj!=0.0
dirj=0.0
elseif newDiff!=0 && dirj==0.0
dirj=newDiff
else
end
direction[j]=dirj =#
#ujj=ujj+e1*u[j][j][2]
ujj=xj1-ajj*qj
#u[j][j][1]=ujj
uji=ujj-aji*qaux[index][1]#
#uji=u[j][index][1]
uj2=xj2-ajj*qj1###################################################-----------------------
uji2=uj2-aji*qaux[index][2]#
#u[j][index][2]=u[j][j][2]-ajj*qaux[index][1] # from article p20 line25 more cycles ...shaky with no bumps
# uji2=u[j][index][2]
dxj=aji*qi+ajj*qaux[j][1]+uji
ddxj=aji*qi1+ajj*qj1+uji2
if abs(ddxj)==0.0
ddxj=1e-30
if DEBUG2 @show ddxj end
end
iscycle=false
qjplus=xjaux-sign(ddxj)*quanj
hj=sqrt(2*quanj/abs(ddxj))#
α1=1-hj*ajj
if abs(α1)==0.0
α1=1e-30
@show α1
end
dqjplus=(aji*(qi+hj*qi1)+ajj*qjplus+uji+hj*uji2)/α1
uij=uii-aij*qaux[j][1]
# uij=u[index][j][1]
uij2=ui2-aij*qj1#########qaux[j][2] updated in normal Qupdate..ft=20 slightly shifts up
#β=dxi+sqrt(abs(ddxi)*quani/2)
#h2=sqrt(2*quani/abs(ddxi))
#uij2=u[index][j][2]
dxithrow=aii*qi+aij*qj+uij
ddxithrow=aii*qi1+aij*qj1+uij2
dxi=aii*qi+aij*qjplus+uij
ddxi=aii*qi1+aij*dqjplus+uij2
if abs(ddxi)==0.0
ddxi=1e-30
if DEBUG2 @show ddxi end
end
hi=sqrt(2*quani/abs(ddxi))
βidir=dxi+hi*ddxi/2
βjdir=dxj+hj*ddxj/2
βidth=dxithrow+hi*ddxithrow/2
αidir=xi1+hi*xi2/2
βj=xj1+hj*xj2/2
########condition:Union
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:Union i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:combineDer Union i
if abs(βjdir-βj)>(abs(βjdir+βj)/2) || dqjplus*newDiff<0.0
if abs(βidir-βidth)>(abs(βidir+βidth)/2) || βidir*dirI<0.0
iscycle=true
end
coef_signig=100
if (abs(dxi)>(abs(xi1)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#) || (abs(xi1)>(abs(dxi)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#)
iscycle=true
end
#= if abs(βidir-αidir)>(abs(βidir+αidir)/2)
iscycle=true
end =#
end
if (ddxithrow>0 && dxithrow<0 && qi1>0) || (ddxithrow<0 && dxithrow>0 && qi1<0)
xmin=xi-dxithrow*dxithrow/ddxithrow
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end
#= if (ddxi>0 && dxi<0 && qi1>0) || (ddxi<0 && dxi>0 && qi1<0)
xmin=xi-dxi*dxi/ddxi
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end =#
########condition:kinda signif alone i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) # || dqjplus*newDiff<0.0
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) #|| βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1 i
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
#= if index==1 && j==4 && 0.1<simt<1.1
iscycle=true
end =#
if iscycle
quani=1.2*quani
quanj=1.2*quanj
for i =1:7# 3 ord1 ,7 ord2
acceptedi[i][1]=0.0; acceptedi[i][2]=0.0
acceptedj[i][1]=0.0; acceptedj[i][2]=0.0
end
for i=1:12
cacheRootsi[i]=0.0
cacheRootsj[i]=0.0
end
trackSimul[1]+=1
aiijj=BigFloat(aii+ajj)
aiijj_=BigFloat(aij*aji-aii*ajj)
coefΔh0=4.0
coefΔh1=-8.0*aiijj
coefΔh2=6.0*aiijj*aiijj-4.0*aiijj_
coefΔh3=6.0*aiijj*aiijj_-2.0*aiijj*aiijj*aiijj
coefΔh4=aiijj_*aiijj_-4.0*aiijj_*aiijj*aiijj
coefΔh5=-3.0*aiijj*aiijj_*aiijj_
coefΔh6=-aiijj_*aiijj_*aiijj_
coefH0=4.0*xi
coefH1=-8.0*xi*aiijj
coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*aii*ajj-aji*aij+ajj*ajj)-aij*aiijj*xjaux)
coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(2.0*aii*ajj-aji*aij+ajj*ajj)+ajj*aiijj_*xi+aij*aiijj*aiijj*xjaux-aij*aiijj_*xjaux)
coefH4=2.0*(aiijj*(uij*aiijj_-ajj*uij2+aij*uji2)-0.5*(2.0*aii*ajj-aji*aij+ajj*ajj)*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-ajj*aiijj_*aiijj*xi+0.5*aij*aiijj*(ajj*uji+aji*uij+uji2+2.0*xjaux*aiijj_)+aij*aiijj_*aiijj*xjaux)
coefH5=(2.0*aii*ajj-aji*aij+ajj*ajj)*(ajj*uij2-uij*aiijj_-aij*uji2)-ajj*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-aij*aiijj*(aii*uji2-uji*aiijj_-aji*uij2)+aij*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xjaux*aiijj_)
coefH6=ajj*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)-aij*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)
coefH0j=4.0*xjaux
coefH1j=-8.0*xjaux*aiijj
coefH2j=2.0*(-ajj*uji-aji*uij-uji2+xjaux*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*ajj*aii-aij*aji+aii*aii)-aji*aiijj*xi)
coefH3j=2.0*((-uji*aiijj_+aii*uji2-aji*uij2)+aiijj*(ajj*uji+aji*uij+uji2+2.0*xjaux*aiijj_)-xjaux*aiijj*(2.0*ajj*aii-aij*aji+aii*aii)+aii*aiijj_*xjaux+aji*aiijj*aiijj*xi-aji*aiijj_*xi)
coefH4j=2.0*(aiijj*(uji*aiijj_-aii*uji2+aji*uij2)-0.5*(2.0*ajj*aii-aij*aji+aii*aii)*(ajj*uji+aji*uij+uji2+2.0*xjaux*aiijj_)-aii*aiijj_*aiijj*xjaux+0.5*aji*aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)+aji*aiijj_*aiijj*xi)
coefH5j=(2.0*ajj*aii-aij*aji+aii*aii)*(aii*uji2-uji*aiijj_-aji*uij2)-aii*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xjaux*aiijj_)-aji*aiijj*(ajj*uij2-uij*aiijj_-aij*uji2)+aji*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)
coefH6j=aii*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)-aji*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)
if coefΔh6==0.0 && coefH6j!=0.0
println("math check")
@show aiijj_
@show aii*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)-aji*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)
@show -aiijj_*aiijj_*aiijj_#coefΔh6
end
#= if coefH6>1e6 || coefH5>1e6 || coefH4>1e6 || coefH3>1e6 || coefH2>1e6
@show coefH6,coefH5,coefH3,coefH2,coefH4
end
if coefH6j>1e6 || coefH5j>1e6 || coefH4j>1e6 || coefH3j>1e6 || coefH2j>1e6
@show coefH6j,coefH5j,coefH3j,coefH2j,coefH4j
end
if coefΔh6>1e6 || coefΔh5>1e6 || coefΔh4>1e6 || coefΔh3>1e6 || coefΔh2>1e6
@show coefΔh6,coefΔh5,coefΔh4,coefΔh3,coefΔh2
end =#
#= coefi=NTuple{7,Float64}((coefH6-coefΔh6*(xi+quani),coefH5-coefΔh5*(xi+quani),coefH4-coefΔh4*(xi+quani),coefH3-coefΔh3*(xi+quani),coefH2-coefΔh2*(xi+quani),coefH1-coefΔh1*(xi+quani),coefH0-coefΔh0*(xi+quani)))
coefi2=NTuple{7,Float64}((coefH6-coefΔh6*(xi-quani),coefH5-coefΔh5*(xi-quani),coefH4-coefΔh4*(xi-quani),coefH3-coefΔh3*(xi-quani),coefH2-coefΔh2*(xi-quani),coefH1-coefΔh1*(xi-quani),coefH0-coefΔh0*(xi-quani)))
coefj=NTuple{7,Float64}((coefH6-coefΔh6*(xjaux+quanj),coefH5-coefΔh5*(xjaux+quanj),coefH4-coefΔh4*(xjaux+quanj),coefH3-coefΔh3*(xjaux+quanj),coefH2-coefΔh2*(xjaux+quanj),coefH1-coefΔh1*(xjaux+quanj),coefH0-coefΔh0*(xjaux+quanj)))
coefj2=NTuple{7,Float64}((coefH6-coefΔh6*(xjaux-quanj),coefH5-coefΔh5*(xjaux-quanj),coefH4-coefΔh4*(xjaux-quanj),coefH3-coefΔh3*(xjaux-quanj),coefH2-coefΔh2*(xjaux-quanj),coefH1-coefΔh1*(xjaux-quanj),coefH0-coefΔh0*(xjaux-quanj)))
=#
coefi=NTuple{7,BigFloat}((coefH6-coefΔh6*(xi+quani),coefH5-coefΔh5*(xi+quani),coefH4-coefΔh4*(xi+quani),coefH3-coefΔh3*(xi+quani),coefH2-coefΔh2*(xi+quani),coefH1-coefΔh1*(xi+quani),coefH0-coefΔh0*(xi+quani)))
coefi2=NTuple{7,BigFloat}((coefH6-coefΔh6*(xi-quani),coefH5-coefΔh5*(xi-quani),coefH4-coefΔh4*(xi-quani),coefH3-coefΔh3*(xi-quani),coefH2-coefΔh2*(xi-quani),coefH1-coefΔh1*(xi-quani),coefH0-coefΔh0*(xi-quani)))
coefj=NTuple{7,BigFloat}((coefH6j-coefΔh6*(xjaux+quanj),coefH5j-coefΔh5*(xjaux+quanj),coefH4j-coefΔh4*(xjaux+quanj),coefH3j-coefΔh3*(xjaux+quanj),coefH2j-coefΔh2*(xjaux+quanj),coefH1j-coefΔh1*(xjaux+quanj),coefH0j-coefΔh0*(xjaux+quanj)))
coefj2=NTuple{7,BigFloat}((coefH6j-coefΔh6*(xjaux-quanj),coefH5j-coefΔh5*(xjaux-quanj),coefH4j-coefΔh4*(xjaux-quanj),coefH3j-coefΔh3*(xjaux-quanj),coefH2j-coefΔh2*(xjaux-quanj),coefH1j-coefΔh1*(xjaux-quanj),coefH0j-coefΔh0*(xjaux-quanj)))
Base.GC.enable(false)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefi,respp,pp)
resi1,resi2,resi3,resi4,resi5,resi6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefi2,respp,pp)
resi7,resi8,resi9,resi10,resi11,resi12=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefj,respp,pp)
resj1,resj2,resj3,resj4,resj5,resj6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefj2,respp,pp)
resj7,resj8,resj9,resj10,resj11,resj12=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
Base.GC.enable(true)
#filter roots
#filterRoots(cacheRootsi,resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
for h in (resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
if h>0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
end
#if abs(qi-xi)>1.2*quani
# end
end
end
for h in (resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12)
if h>0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qj=(4.0*xjaux+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
# qii,qj,Δ1=simulQ(quani,quanj,simt,aii,aij,aji,ajj,h,xi,xjaux,uij,uij2,uji,uji2)
#if abs(qj-xjaux)>1.2*quanj
#= if simt==3.486047550372409
@show "simulCheck first good hi: ",simt,h,qj,xjaux,quanj
@show resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12
@show coefj,coefj2
zf=coefj[1]*h^6+coefj[2]*h^5+coefj[3]*h^4+coefj[4]*h^3+coefj[5]*h^2+coefj[6]*h+coefj[7]
@show zf
end =#
#return false
#end
end
end
counterRooti=1
for h in (resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
if h>0
cacheRootsi[counterRooti]=h
counterRooti+=1
end
end
sort!(cacheRootsi);
counterRootj=1
for h in (resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12)
if h>0 && h!=Inf
cacheRootsj[counterRootj]=h
counterRootj+=1
end
end
sort!(cacheRootsj);
#construct intervals
constructIntrval(acceptedi,cacheRootsi)
constructIntrval(acceptedj,cacheRootsj)
ki=7;kj=7
h=-1.0
#= @show cacheRootsi
@show acceptedi
@show cacheRootsj
@show acceptedj
@show simt,j =#
while true
#if ki==0 || kj==0
#end
currentLi=acceptedi[ki][1];currentHi=acceptedi[ki][2]
currentLj=acceptedj[kj][1];currentHj=acceptedj[kj][2]
if currentLj<=currentLi<currentHj || currentLi<=currentLj<currentHi#resj[end][1]<=resi[end][1]<=resj[end][2] || resi[end][1]<=resj[end][1]<=resi[end][2] #overlap
h=min(currentHi,currentHj )
if h==Inf && (currentLj!=0.0 || currentLi!=0.0) # except case both 0 sols h1=(0,Inf)
h=max(currentLj,currentLi#= ,ft-simt,dti =#) #ft-simt in case they are both ver small...elaborate on his later
if simt==2.500745083181994e-5
@show currentLj,currentLi
end
end
if h==Inf # both lower bounds ==0 --> zero sols for both
# qi=xi+ci/βi #asymptote...even though not guaranteed to be best
#qj=xj+cj/βj
qi=getQfromAsymptote(xi,coefH0,coefH1,coefH2,coefH3,coefH4,coefH5,coefH6,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6)
qj=getQfromAsymptote(xjaux,coefH0j,coefH1j,coefH2j,coefH3j,coefH4j,coefH5j,coefH6j,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6)
#@show "asymptote:",simt,qi,xi,quani,coefH6,coefΔh6
else
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xjaux+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
#= if 2.500745083181994e-5<=simt<3.00745083181994e-5
@show "simul: ",index,qi,xi,quani,h,simt,j,qj,xjaux,quanj
end =#
else
println("singularities Δ22=0")
#do iterations
end
end
break
else
if currentHj==0.0 && currentHi==0.0#empty
ki-=1;kj-=1
elseif currentHj==0.0 && currentHi!=0.0
kj-=1
elseif currentHi==0.0 && currentHj!=0.0
ki-=1
else #both non zero
if currentLj<currentLi#remove last seg of resi
ki-=1
else #remove last seg of resj
kj-=1
end
end
end
end # end while
#checkRoots(cacheRootsi,coefi,coefi2) # for free stress-testing allrealrootintervalnewtonregulafalsi
# checkRoots(cacheRootsj,coefj,coefj2) #later check if error in roots makes q-x >2quan...use commented code below
if h==-1.0
println("h not being updated in while loop")
end
if h!=Inf
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)==0.0
Δ1=1e-30
@show Δ1
end
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
if abs(q1parti)==0.0
q1parti=1e-30*sign(q1parti)
@show q1parti,simt
end
if abs(q1partj)==0.0
q1partj=1e-30
@show q1partj,simt
end
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# store back helper vars
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
else
qi1=(aji*uij2-uji2*aij)/aiijj_ #resul of ddx=aq+aq+u=0 ...2eqs 2 unknowns
qj1=(-uij2-aii*qi1)/aij
end
q[index][0]=Float64(qi)# store back helper vars
q[j][0]=Float64(qj)
q[index][1]=Float64(qi1)
q[j][1]=Float64(qj1)
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
end #end if iscycle
return iscycle
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 74094 |
function nmisCycle_and_simulUpdate(cacheRootsi::Vector{BigFloat},cacheRootsj::Vector{BigFloat},acceptedi::Vector{Vector{BigFloat}},acceptedj::Vector{Vector{BigFloat}},aij::Float64,aji::Float64,respp::Ptr{BigFloat}, pp::Ptr{NTuple{2,BigFloat}},trackSimul,::Val{2},index::Int,j::Int,dirI::Float64,firstguessH::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exacteA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{2,Float64}},qaux::Vector{MVector{2,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exacteA(q,d,cacheA,index,index)
aii=cacheA[1]
cacheA[1]=0.0; exacteA(q,d,cacheA,j,j)
ajj=cacheA[1]
uii=dxaux[index][1]-aii*qaux[index][1]
ui2=dxaux[index][2]-aii*qaux[index][2]
#= uii=x[index][1]-aii*q[index][0]
ui2=x[index][2]-aii*q[index][1] =#
xi=x[index][0];xj=x[j][0];qi=q[index][0];qj=q[j][0];qi1=q[index][1];qj1=q[j][1];xi1=x[index][1];xi2=2*x[index][2];xj1=x[j][1];xj2=2*x[j][2]
#uii=u[index][index][1];ujj=u[j][j][1]#;uij=u[index][j][1];uji=u[j][index][1]#;uji2=u[j][index][2]
quanj=quantum[j];quani=quantum[index];
e1 = simt - tx[j];e2 = simt - tq[j];#= e3=simt - tu[j];tu[j]=simt; =#
prevXj=x[j][0]
x[j][0]= x[j](e1);xj=x[j][0];tx[j]=simt
qj=qj+e2*qj1 ;qaux[j][1]=qj;tq[j] = simt ;q[j][0]=qj
xj1=x[j][1]+e1*xj2;
newDiff=(xj-prevXj)
ujj=xj1-ajj*qj
#u[j][j][1]=ujj
uji=ujj-aji*qaux[index][1]#
#uji=u[j][index][1]
uj2=xj2-ajj*qj1###################################################-----------------------
uji2=uj2-aji*qaux[index][2]#
#u[j][index][2]=u[j][j][2]-ajj*qaux[index][1] # from article p20 line25 more cycles ...shaky with no bumps
# uji2=u[j][index][2]
dxj=aji*qi+ajj*qaux[j][1]+uji
ddxj=aji*qi1+ajj*qj1+uji2
if abs(ddxj)==0.0
ddxj=1e-30
if DEBUG2 @show ddxj end
end
iscycle=false
qjplus=xj-sign(ddxj)*quanj
hj=sqrt(2*quanj/abs(ddxj))#
α1=1-hj*ajj
if abs(α1)==0.0
α1=1e-30
@show α1
end
dqjplus=(aji*(qi+hj*qi1)+ajj*qjplus+uji+hj*uji2)/α1
uij=uii-aij*qaux[j][1]
# uij=u[index][j][1]
uij2=ui2-aij*qj1#########qaux[j][2] updated in normal Qupdate..ft=20 slightly shifts up
#β=dxi+sqrt(abs(ddxi)*quani/2)
#h2=sqrt(2*quani/abs(ddxi))
#uij2=u[index][j][2]
dxithrow=aii*qi+aij*qj+uij
ddxithrow=aii*qi1+aij*qj1+uij2
dxi=aii*qi+aij*qjplus+uij
ddxi=aii*qi1+aij*dqjplus+uij2
if abs(ddxi)==0.0
ddxi=1e-30
if DEBUG2 @show ddxi end
end
hi=sqrt(2*quani/abs(ddxi))
βidir=dxi+hi*ddxi/2
βjdir=dxj+hj*ddxj/2
βidth=dxithrow+hi*ddxithrow/2
αidir=xi1+hi*xi2/2
βj=xj1+hj*xj2/2
########condition:Union
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:Union i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:combineDer Union i
if abs(βjdir-βj)>(abs(βjdir+βj)/2) || dqjplus*newDiff<0.0
if abs(βidir-βidth)>(abs(βidir+βidth)/2) || βidir*dirI<0.0
iscycle=true
end
coef_signig=100
if (abs(dxi)>(abs(xi1)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#) || (abs(xi1)>(abs(dxi)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#)
iscycle=true
end
#= if abs(βidir-αidir)>(abs(βidir+αidir)/2)
iscycle=true
end =#
end
if (ddxithrow>0 && dxithrow<0 && qi1>0) || (ddxithrow<0 && dxithrow>0 && qi1<0)
xmin=xi-dxithrow*dxithrow/ddxithrow
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end
#= if (ddxi>0 && dxi<0 && qi1>0) || (ddxi<0 && dxi>0 && qi1<0)
xmin=xi-dxi*dxi/ddxi
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end =#
########condition:kinda signif alone i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) # || dqjplus*newDiff<0.0
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) #|| βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1 i
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
#= if index==1 && j==4 && 0.1<simt<1.1
iscycle=true
end =#
if iscycle
#= quani=1.7*quani
quanj=1.7*quanj =#
for i =1:7# 3 ord1 ,7 ord2
acceptedi[i][1]=0.0; acceptedi[i][2]=0.0
acceptedj[i][1]=0.0; acceptedj[i][2]=0.0
end
for i=1:12
cacheRootsi[i]=0.0
cacheRootsj[i]=0.0
end
trackSimul[1]+=1
aiijj=BigFloat(aii+ajj)
aiijj_=BigFloat(aij*aji-aii*ajj)
coefΔh0=4.0
coefΔh1=-8.0*aiijj
coefΔh2=6.0*aiijj*aiijj-4.0*aiijj_
coefΔh3=6.0*aiijj*aiijj_-2.0*aiijj*aiijj*aiijj
coefΔh4=aiijj_*aiijj_-4.0*aiijj_*aiijj*aiijj
coefΔh5=-3.0*aiijj*aiijj_*aiijj_
coefΔh6=-aiijj_*aiijj_*aiijj_
coefH0=4.0*xi
coefH1=-8.0*xi*aiijj
#coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*aii*ajj-aji*aij+ajj*ajj)-aij*aiijj*xj)
coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-3.0*aiijj_+2.0*aiijj*aiijj+aiijj*ajj)-aij*aiijj*xj)
#coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(2.0*aii*ajj-aji*aij+ajj*ajj)+ajj*aiijj_*xi+aij*aiijj*aiijj*xj-aij*aiijj_*xj)
coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(ajj*aiijj-aiijj_)+ajj*aiijj_*xi+aij*aiijj*aiijj*xj-aij*aiijj_*xj)
coefH4=2.0*(aiijj*(uij*aiijj_-ajj*uij2+aij*uji2)-0.5*(2.0*aii*ajj-aji*aij+ajj*ajj)*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-ajj*aiijj_*aiijj*xi+0.5*aij*aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)+aij*aiijj_*aiijj*xj)
coefH5=(2.0*aii*ajj-aji*aij+ajj*ajj)*(ajj*uij2-uij*aiijj_-aij*uji2)-ajj*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-aij*aiijj*(aii*uji2-uji*aiijj_-aji*uij2)+aij*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)
coefH6=ajj*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)-aij*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)
coefH0j=4.0*xj
coefH1j=-8.0*xj*aiijj
coefH2j=2.0*(-ajj*uji-aji*uij-uji2+xj*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*ajj*aii-aij*aji+aii*aii)-aji*aiijj*xi)
coefH3j=2.0*((-uji*aiijj_+aii*uji2-aji*uij2)+aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-xj*aiijj*(2.0*ajj*aii-aij*aji+aii*aii)+aii*aiijj_*xj+aji*aiijj*aiijj*xi-aji*aiijj_*xi)
coefH4j=2.0*(aiijj*(uji*aiijj_-aii*uji2+aji*uij2)-0.5*(aii*aiijj-aiijj_)*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aii*aiijj_*aiijj*xj+0.5*aji*aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)+aji*aiijj_*aiijj*xi)
coefH5j=(aii*aiijj-aiijj_)*(aii*uji2-uji*aiijj_-aji*uij2)-aii*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aji*aiijj*(ajj*uij2-uij*aiijj_-aij*uji2)+aji*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)
coefH6j=aii*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)-aji*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)
#= coefi=NTuple{7,Float64}((coefH6-coefΔh6*(xi+quani),coefH5-coefΔh5*(xi+quani),coefH4-coefΔh4*(xi+quani),coefH3-coefΔh3*(xi+quani),coefH2-coefΔh2*(xi+quani),coefH1-coefΔh1*(xi+quani),coefH0-coefΔh0*(xi+quani)))
coefi2=NTuple{7,Float64}((coefH6-coefΔh6*(xi-quani),coefH5-coefΔh5*(xi-quani),coefH4-coefΔh4*(xi-quani),coefH3-coefΔh3*(xi-quani),coefH2-coefΔh2*(xi-quani),coefH1-coefΔh1*(xi-quani),coefH0-coefΔh0*(xi-quani)))
coefj=NTuple{7,Float64}((coefH6j-coefΔh6*(xj+quanj),coefH5j-coefΔh5*(xj+quanj),coefH4j-coefΔh4*(xj+quanj),coefH3j-coefΔh3*(xj+quanj),coefH2j-coefΔh2*(xj+quanj),coefH1j-coefΔh1*(xj+quanj),coefH0j-coefΔh0*(xj+quanj)))
coefj2=NTuple{7,Float64}((coefH6j-coefΔh6*(xj-quanj),coefH5j-coefΔh5*(xj-quanj),coefH4j-coefΔh4*(xj-quanj),coefH3j-coefΔh3*(xj-quanj),coefH2j-coefΔh2*(xj-quanj),coefH1j-coefΔh1*(xj-quanj),coefH0j-coefΔh0*(xj-quanj)))
resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12=0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12=0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
Base.GC.enable(false)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefi,respp,pp)
resi1,resi2,resi3,resi4,resi5,resi6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefi2,respp,pp)
resi7,resi8,resi9,resi10,resi11,resi12=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefj,respp,pp)
resj1,resj2,resj3,resj4,resj5,resj6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefj2,respp,pp)
resj7,resj8,resj9,resj10,resj11,resj12=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
Base.GC.enable(true) =#
#to be deleted: test
#= for h in (resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
if h>0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
if abs(qi-xi)>2quani
error("your own h not working for you, i")
end
end
end
end
for h in (resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12)
if h>0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
if abs(qj-xj)>2quanj
error("your own h not working for you, j")
end
end
end
end
#filter roots
counterRooti=1
for h in (resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
if h>0 && h!=Inf
cacheRootsi[counterRooti]=h
counterRooti+=1
end
end
sort!(cacheRootsi);
counterRootj=1
for h in (resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12)
if h>0 && h!=Inf
cacheRootsj[counterRootj]=h
counterRootj+=1
end
end =#
#= coefi=[coefH0-coefΔh0*(xi+quani),coefH1-coefΔh1*(xi+quani),coefH2-coefΔh2*(xi+quani),coefH3-coefΔh3*(xi+quani),coefH4-coefΔh4*(xi+quani),coefH5-coefΔh5*(xi+quani),coefH6-coefΔh6*(xi+quani)]
coefj=[coefH0j-coefΔh0*(xj+quanj),coefH1j-coefΔh1*(xj+quanj),coefH2j-coefΔh2*(xj+quanj),coefH3j-coefΔh3*(xj+quanj),coefH4j-coefΔh4*(xj+quanj),coefH5j-coefΔh5*(xj+quanj),coefH6j-coefΔh6*(xj+quanj)]
coefi2=[coefH0-coefΔh0*(xi-quani),coefH1-coefΔh1*(xi-quani),coefH2-coefΔh2*(xi-quani),coefH3-coefΔh3*(xi-quani),coefH4-coefΔh4*(xi-quani),coefH5-coefΔh5*(xi-quani),coefH6-coefΔh6*(xi-quani)]
coefj2=[coefH0j-coefΔh0*(xj-quanj),coefH1j-coefΔh1*(xj-quanj),coefH2j-coefΔh2*(xj-quanj),coefH3j-coefΔh3*(xj-quanj),coefH4j-coefΔh4*(xj-quanj),coefH5j-coefΔh5*(xj-quanj),coefH6j-coefΔh6*(xj-quanj)]
=#
coefi=[BigFloat(coefH0-coefΔh0*(xi+quani)),BigFloat(coefH1-coefΔh1*(xi+quani)),BigFloat(coefH2-coefΔh2*(xi+quani)),BigFloat(coefH3-coefΔh3*(xi+quani)),BigFloat(coefH4-coefΔh4*(xi+quani)),BigFloat(coefH5-coefΔh5*(xi+quani)),BigFloat(coefH6-coefΔh6*(xi+quani))]
coefj=[BigFloat(coefH0j-coefΔh0*(xj+quanj)),BigFloat(coefH1j-coefΔh1*(xj+quanj)),BigFloat(coefH2j-coefΔh2*(xj+quanj)),BigFloat(coefH3j-coefΔh3*(xj+quanj)),BigFloat(coefH4j-coefΔh4*(xj+quanj)),BigFloat(coefH5j-coefΔh5*(xj+quanj)),BigFloat(coefH6j-coefΔh6*(xj+quanj))]
coefi2=[BigFloat(coefH0-coefΔh0*(xi-quani)),BigFloat(coefH1-coefΔh1*(xi-quani)),BigFloat(coefH2-coefΔh2*(xi-quani)),BigFloat(coefH3-coefΔh3*(xi-quani)),BigFloat(coefH4-coefΔh4*(xi-quani)),BigFloat(coefH5-coefΔh5*(xi-quani)),BigFloat(coefH6-coefΔh6*(xi-quani))]
coefj2=[BigFloat(coefH0j-coefΔh0*(xj-quanj)),BigFloat(coefH1j-coefΔh1*(xj-quanj)),BigFloat(coefH2j-coefΔh2*(xj-quanj)),BigFloat(coefH3j-coefΔh3*(xj-quanj)),BigFloat(coefH4j-coefΔh4*(xj-quanj)),BigFloat(coefH5j-coefΔh5*(xj-quanj)),BigFloat(coefH6j-coefΔh6*(xj-quanj))]
ri=roots(coefi)
rj=roots(coefj)
ri2=roots(coefi2)
rj2=roots(coefj2)
#filter roots
counterRooti=1
for h in ri
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsi[counterRooti]=(real(h))
counterRooti+=1
end
end
checkRoots(cacheRootsi,coefi,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quani)
for h in ri2
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsi[counterRooti]=(real(h))
counterRooti+=1
end
end
sort!(cacheRootsi);
counterRootj=1
for h in rj
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsj[counterRootj]=(real(h))
counterRootj+=1
end
end
checkRoots(cacheRootsj,coefj,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quanj)
for h in rj2
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsj[counterRootj]=(real(h))
counterRootj+=1
end
end
sort!(cacheRootsj);
#= for h in cacheRootsi
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
if abs(qi-xi)>2quani
error("your own h not working for you, i")
end
end
end
for h in cacheRootsj
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
if abs(qj-xj)>2quanj
error("your own h not working for you, j")
end
end
end =#
#construct intervals
constructIntrval(acceptedi,cacheRootsi)
constructIntrval(acceptedj,cacheRootsj)
ki=7;kj=7
h=-1.0
debugTracker=0
tryIteration=false
Δ1=0.0
while true
if ki==0 || kj==0
error("bug in finding the overlap")
end
currentLi=acceptedi[ki][1];currentHi=acceptedi[ki][2]
currentLj=acceptedj[kj][1];currentHj=acceptedj[kj][2]
if currentLj<=currentLi<currentHj || currentLi<=currentLj<currentHi#resj[end][1]<=resi[end][1]<=resj[end][2] || resi[end][1]<=resj[end][1]<=resi[end][2] #overlap
h=min(currentHi,currentHj )
if h==Inf && (currentLj!=0.0 || currentLi!=0.0) # except case both 0 sols h1=(0,Inf)
h=max(currentLj,currentLi#= ,ft-simt,dti =#) #ft-simt in case they are both ver small...elaborate on his later
#= if simt==2.500745083181994e-5
@show currentLj,currentLi
end =#
end
if h==Inf # both lower bounds ==0 --> zero sols for both
if aiijj_!=0.0
qi=coefH6/coefΔh6;qj=coefH6j/coefΔh6
cac=checkAcceptanceCriteria(qi,xi,quani,qj,xj,quanj)
if cac
#= qi1=(aji*uij2-uji2*aij)/aiijj_ #resul of ddx=aq+aq+u=0 ...2eqs 2 unknowns
qj1=(-uij2-aii*qi1)/aij =#
h=ft
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
while Δ1==0.0
h=h*0.98
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
end
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
debugTracker=1
else
tryIteration=true
end
else
tryIteration=true
end
if tryIteration
#return false
#later try to study critical points(maxima) to find best
h = ft-simt
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
if (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj)
h1 = sqrt(abs(2*quani/xi2));h2 = sqrt(abs(2*quanj/xj2)); #later add derderX =1e-12 when x2==0?
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
maxIter=10000
while (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj) && (maxIter>0)
maxIter-=1
h1 = h * sqrt(quani / abs(qi - xi));
h2 = h * sqrt(quanj / abs(qj - xj));
#= h1 = h * (0.99*1.8*quani / abs(qi - xi));
h2 = h * (0.99*1.8*quanj / abs(qj - xj)); =#
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
if maxIter==0 || Δ1==0.0 # maxIter=0 :failed to bring q down within a reasonable time. Δ1==0.0 should never happen when maxIter>0...but keep it there for now
return false
end
debugTracker=2
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
end#end if iteration
else #h!=Inf
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ22)!=0.0 && Δ1!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
#= if 2.500745083181994e-5<=simt<3.00745083181994e-5
@show "simul: ",index,qi,xi,quani,h,simt,j,qj,xj,quanj
end =#
cac=checkAcceptanceCriteria(qi,xi,quani,qj,xj,quanj)
if !cac
tryIteration=true
else
debugTracker=3
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
end
else
tryIteration=true
end
if tryIteration
#println("singularities Δ22=0")#do iterations
h = ft-simt
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
if (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj)
h1 = sqrt(abs(2*quani/xi2));h2 = sqrt(abs(2*quanj/xj2)); #later add derderX =1e-12 when x2==0?
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
maxIter=10000
while (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj) && (maxIter>0)
maxIter-=1
h1 = h * sqrt(quani / abs(qi - xi));
h2 = h * sqrt(quanj / abs(qj - xj));
#= h1 = h * (0.99*1.8*quani / abs(qi - xi));
h2 = h * (0.99*1.8*quanj / abs(qj - xj)); =#
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end # end while iteration
if maxIter==0 || Δ1==0.0 # maxIter=0 :failed to bring q down within a reasonable time. Δ1==0.0 should never happen when maxIter>0...but keep it there for now
return false
end
debugTracker=4
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
end# end if tryiteration
#= q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj =#
end# end h inf or else
break
else
if currentHj==0.0 && currentHi==0.0#empty
ki-=1;kj-=1
elseif currentHj==0.0 && currentHi!=0.0
kj-=1
elseif currentHi==0.0 && currentHj!=0.0
ki-=1
else #both non zero
if currentLj<currentLi#remove last seg of resi
ki-=1
else #remove last seg of resj
kj-=1
end
end
end
end # end while
#checkRoots(cacheRootsi,coefi,coefi2) # for free stress-testing allrealrootintervalnewtonregulafalsi
# checkRoots(cacheRootsj,coefj,coefj2) #later check if error in roots makes q-x >2quan...use commented code below
q[index][0]=Float64(qi)# store back helper vars
q[j][0]=Float64(qj)
q[index][1]=Float64(qi1)
q[j][1]=Float64(qj1)
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
#= if abs(qi-xi)<quani/1000 && abs(qj-xj)<quanj/1000
#if quani/1000<abs(qi-xi)<quani/10 && quanj/1000<abs(qj-xj)<quanj/10
println("end of simul: qi & qj thrown both very close")
@show abs(qi-xi),quani , abs(qj-xj),quanj
@show simt,debugTracker
end =#
#= if isnan(qi)
@show simt,"qi",debugTracker
end
if isnan(qi1)
@show simt,"qi1",debugTracker
end
if isnan(qj)
@show simt,"qj",debugTracker
end
if isnan(qj1)
@show simt,"qj1",debugTracker
end =#
end #end if iscycle
return iscycle
end
function nmisCycle_and_simulUpdate(cacheRootsi::Vector{Float64},cacheRootsj::Vector{Float64},acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{2},index::Int,j::Int,dirI::Float64,firstguessH::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exacteA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{2,Float64}},qaux::Vector{MVector{2,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exacteA(q,d,cacheA,index,index)
aii=cacheA[1]
cacheA[1]=0.0; exacteA(q,d,cacheA,j,j)
ajj=cacheA[1]
uii=dxaux[index][1]-aii*qaux[index][1]
ui2=dxaux[index][2]-aii*qaux[index][2]
#= uii=x[index][1]-aii*q[index][0]
ui2=x[index][2]-aii*q[index][1] =#
xi=x[index][0];xj=x[j][0];qi=q[index][0];qj=q[j][0];qi1=q[index][1];qj1=q[j][1];xi1=x[index][1];xi2=2*x[index][2];xj1=x[j][1];xj2=2*x[j][2]
#uii=u[index][index][1];ujj=u[j][j][1]#;uij=u[index][j][1];uji=u[j][index][1]#;uji2=u[j][index][2]
quanj=quantum[j];quani=quantum[index];
e1 = simt - tx[j];e2 = simt - tq[j];#= e3=simt - tu[j];tu[j]=simt; =#
prevXj=x[j][0]
x[j][0]= x[j](e1);xj=x[j][0];tx[j]=simt
qj=qj+e2*qj1 ;qaux[j][1]=qj;tq[j] = simt ;q[j][0]=qj
xj1=x[j][1]+e1*xj2;
newDiff=(xj-prevXj)
ujj=xj1-ajj*qj
#u[j][j][1]=ujj
uji=ujj-aji*qaux[index][1]#
#uji=u[j][index][1]
uj2=xj2-ajj*qj1###################################################-----------------------
uji2=uj2-aji*qaux[index][2]#
#u[j][index][2]=u[j][j][2]-ajj*qaux[index][1] # from article p20 line25 more cycles ...shaky with no bumps
# uji2=u[j][index][2]
dxj=aji*qi+ajj*qaux[j][1]+uji
ddxj=aji*qi1+ajj*qj1+uji2
if abs(ddxj)==0.0
ddxj=1e-30
if DEBUG2 @show ddxj end
end
iscycle=false
qjplus=xj-sign(ddxj)*quanj
hj=sqrt(2*quanj/abs(ddxj))#
α1=1-hj*ajj
if abs(α1)==0.0
α1=1e-30
@show α1
end
dqjplus=(aji*(qi+hj*qi1)+ajj*qjplus+uji+hj*uji2)/α1
uij=uii-aij*qaux[j][1]
# uij=u[index][j][1]
uij2=ui2-aij*qj1#########qaux[j][2] updated in normal Qupdate..ft=20 slightly shifts up
#β=dxi+sqrt(abs(ddxi)*quani/2)
#h2=sqrt(2*quani/abs(ddxi))
#uij2=u[index][j][2]
dxithrow=aii*qi+aij*qj+uij
ddxithrow=aii*qi1+aij*qj1+uij2
dxi=aii*qi+aij*qjplus+uij
ddxi=aii*qi1+aij*dqjplus+uij2
if abs(ddxi)==0.0
ddxi=1e-30
if DEBUG2 @show ddxi end
end
hi=sqrt(2*quani/abs(ddxi))
βidir=dxi+hi*ddxi/2
βjdir=dxj+hj*ddxj/2
βidth=dxithrow+hi*ddxithrow/2
αidir=xi1+hi*xi2/2
βj=xj1+hj*xj2/2
########condition:Union
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:Union i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:combineDer Union i
if abs(βjdir-βj)>(abs(βjdir+βj)/2) || dqjplus*newDiff<0.0
if abs(βidir-βidth)>(abs(βidir+βidth)/2) || βidir*dirI<0.0
iscycle=true
end
coef_signig=100
if (abs(dxi)>(abs(xi1)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#) || (abs(xi1)>(abs(dxi)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#)
iscycle=true
end
#= if abs(βidir-αidir)>(abs(βidir+αidir)/2)
iscycle=true
end =#
end
if (ddxithrow>0 && dxithrow<0 && qi1>0) || (ddxithrow<0 && dxithrow>0 && qi1<0)
xmin=xi-dxithrow*dxithrow/ddxithrow
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end
#= if (ddxi>0 && dxi<0 && qi1>0) || (ddxi<0 && dxi>0 && qi1<0)
xmin=xi-dxi*dxi/ddxi
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end =#
########condition:kinda signif alone i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) # || dqjplus*newDiff<0.0
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) #|| βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1 i
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
#= if index==1 && j==4 && 0.1<simt<1.1
iscycle=true
end =#
if iscycle
#= quani=1.7*quani
quanj=1.7*quanj =#
for i =1:7# 3 ord1 ,7 ord2
acceptedi[i][1]=0.0; acceptedi[i][2]=0.0
acceptedj[i][1]=0.0; acceptedj[i][2]=0.0
end
for i=1:12
cacheRootsi[i]=0.0
cacheRootsj[i]=0.0
end
trackSimul[1]+=1
aiijj=Float64(aii+ajj)
aiijj_=Float64(aij*aji-aii*ajj)
coefΔh0=4.0
coefΔh1=-8.0*aiijj
coefΔh2=6.0*aiijj*aiijj-4.0*aiijj_
coefΔh3=6.0*aiijj*aiijj_-2.0*aiijj*aiijj*aiijj
coefΔh4=aiijj_*aiijj_-4.0*aiijj_*aiijj*aiijj
coefΔh5=-3.0*aiijj*aiijj_*aiijj_
coefΔh6=-aiijj_*aiijj_*aiijj_
coefH0=4.0*xi
coefH1=-8.0*xi*aiijj
#coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*aii*ajj-aji*aij+ajj*ajj)-aij*aiijj*xj)
coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-3.0*aiijj_+2.0*aiijj*aiijj+aiijj*ajj)-aij*aiijj*xj)
#coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(2.0*aii*ajj-aji*aij+ajj*ajj)+ajj*aiijj_*xi+aij*aiijj*aiijj*xj-aij*aiijj_*xj)
coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(ajj*aiijj-aiijj_)+ajj*aiijj_*xi+aij*aiijj*aiijj*xj-aij*aiijj_*xj)
coefH4=2.0*(aiijj*(uij*aiijj_-ajj*uij2+aij*uji2)-0.5*(2.0*aii*ajj-aji*aij+ajj*ajj)*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-ajj*aiijj_*aiijj*xi+0.5*aij*aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)+aij*aiijj_*aiijj*xj)
coefH5=(2.0*aii*ajj-aji*aij+ajj*ajj)*(ajj*uij2-uij*aiijj_-aij*uji2)-ajj*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-aij*aiijj*(aii*uji2-uji*aiijj_-aji*uij2)+aij*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)
coefH6=ajj*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)-aij*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)
coefH0j=4.0*xj
coefH1j=-8.0*xj*aiijj
coefH2j=2.0*(-ajj*uji-aji*uij-uji2+xj*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*ajj*aii-aij*aji+aii*aii)-aji*aiijj*xi)
coefH3j=2.0*((-uji*aiijj_+aii*uji2-aji*uij2)+aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-xj*aiijj*(2.0*ajj*aii-aij*aji+aii*aii)+aii*aiijj_*xj+aji*aiijj*aiijj*xi-aji*aiijj_*xi)
coefH4j=2.0*(aiijj*(uji*aiijj_-aii*uji2+aji*uij2)-0.5*(aii*aiijj-aiijj_)*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aii*aiijj_*aiijj*xj+0.5*aji*aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)+aji*aiijj_*aiijj*xi)
coefH5j=(aii*aiijj-aiijj_)*(aii*uji2-uji*aiijj_-aji*uij2)-aii*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aji*aiijj*(ajj*uij2-uij*aiijj_-aij*uji2)+aji*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)
coefH6j=aii*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)-aji*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)
#= coefi=NTuple{7,Float64}((coefH6-coefΔh6*(xi+quani),coefH5-coefΔh5*(xi+quani),coefH4-coefΔh4*(xi+quani),coefH3-coefΔh3*(xi+quani),coefH2-coefΔh2*(xi+quani),coefH1-coefΔh1*(xi+quani),coefH0-coefΔh0*(xi+quani)))
coefi2=NTuple{7,Float64}((coefH6-coefΔh6*(xi-quani),coefH5-coefΔh5*(xi-quani),coefH4-coefΔh4*(xi-quani),coefH3-coefΔh3*(xi-quani),coefH2-coefΔh2*(xi-quani),coefH1-coefΔh1*(xi-quani),coefH0-coefΔh0*(xi-quani)))
coefj=NTuple{7,Float64}((coefH6j-coefΔh6*(xj+quanj),coefH5j-coefΔh5*(xj+quanj),coefH4j-coefΔh4*(xj+quanj),coefH3j-coefΔh3*(xj+quanj),coefH2j-coefΔh2*(xj+quanj),coefH1j-coefΔh1*(xj+quanj),coefH0j-coefΔh0*(xj+quanj)))
coefj2=NTuple{7,Float64}((coefH6j-coefΔh6*(xj-quanj),coefH5j-coefΔh5*(xj-quanj),coefH4j-coefΔh4*(xj-quanj),coefH3j-coefΔh3*(xj-quanj),coefH2j-coefΔh2*(xj-quanj),coefH1j-coefΔh1*(xj-quanj),coefH0j-coefΔh0*(xj-quanj)))
resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12=0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12=0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0
Base.GC.enable(false)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefi,respp,pp)
resi1,resi2,resi3,resi4,resi5,resi6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefi2,respp,pp)
resi7,resi8,resi9,resi10,resi11,resi12=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefj,respp,pp)
resj1,resj2,resj3,resj4,resj5,resj6=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
unsafe_store!(respp, -1.0, 1);unsafe_store!(respp, -1.0, 2);unsafe_store!(respp, -1.0, 3);unsafe_store!(respp, -1.0, 4);unsafe_store!(respp, -1.0, 5);unsafe_store!(respp, -1.0, 6)
allrealrootintervalnewtonregulafalsi(coefj2,respp,pp)
resj7,resj8,resj9,resj10,resj11,resj12=unsafe_load(respp,1),unsafe_load(respp,2),unsafe_load(respp,3),unsafe_load(respp,4),unsafe_load(respp,5),unsafe_load(respp,6)
Base.GC.enable(true) =#
#to be deleted: test
#= for h in (resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
if h>0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
if abs(qi-xi)>2quani
error("your own h not working for you, i")
end
end
end
end
for h in (resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12)
if h>0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
if abs(qj-xj)>2quanj
error("your own h not working for you, j")
end
end
end
end
#filter roots
counterRooti=1
for h in (resi1,resi2,resi3,resi4,resi5,resi6,resi7,resi8,resi9,resi10,resi11,resi12)
if h>0 && h!=Inf
cacheRootsi[counterRooti]=h
counterRooti+=1
end
end
sort!(cacheRootsi);
counterRootj=1
for h in (resj1,resj2,resj3,resj4,resj5,resj6,resj7,resj8,resj9,resj10,resj11,resj12)
if h>0 && h!=Inf
cacheRootsj[counterRootj]=h
counterRootj+=1
end
end =#
#= coefi=[coefH0-coefΔh0*(xi+quani),coefH1-coefΔh1*(xi+quani),coefH2-coefΔh2*(xi+quani),coefH3-coefΔh3*(xi+quani),coefH4-coefΔh4*(xi+quani),coefH5-coefΔh5*(xi+quani),coefH6-coefΔh6*(xi+quani)]
coefj=[coefH0j-coefΔh0*(xj+quanj),coefH1j-coefΔh1*(xj+quanj),coefH2j-coefΔh2*(xj+quanj),coefH3j-coefΔh3*(xj+quanj),coefH4j-coefΔh4*(xj+quanj),coefH5j-coefΔh5*(xj+quanj),coefH6j-coefΔh6*(xj+quanj)]
coefi2=[coefH0-coefΔh0*(xi-quani),coefH1-coefΔh1*(xi-quani),coefH2-coefΔh2*(xi-quani),coefH3-coefΔh3*(xi-quani),coefH4-coefΔh4*(xi-quani),coefH5-coefΔh5*(xi-quani),coefH6-coefΔh6*(xi-quani)]
coefj2=[coefH0j-coefΔh0*(xj-quanj),coefH1j-coefΔh1*(xj-quanj),coefH2j-coefΔh2*(xj-quanj),coefH3j-coefΔh3*(xj-quanj),coefH4j-coefΔh4*(xj-quanj),coefH5j-coefΔh5*(xj-quanj),coefH6j-coefΔh6*(xj-quanj)]
=#
coefi=[Float64(coefH0-coefΔh0*(xi+quani)),Float64(coefH1-coefΔh1*(xi+quani)),Float64(coefH2-coefΔh2*(xi+quani)),Float64(coefH3-coefΔh3*(xi+quani)),Float64(coefH4-coefΔh4*(xi+quani)),Float64(coefH5-coefΔh5*(xi+quani)),Float64(coefH6-coefΔh6*(xi+quani))]
coefj=[Float64(coefH0j-coefΔh0*(xj+quanj)),Float64(coefH1j-coefΔh1*(xj+quanj)),Float64(coefH2j-coefΔh2*(xj+quanj)),Float64(coefH3j-coefΔh3*(xj+quanj)),Float64(coefH4j-coefΔh4*(xj+quanj)),Float64(coefH5j-coefΔh5*(xj+quanj)),Float64(coefH6j-coefΔh6*(xj+quanj))]
coefi2=[Float64(coefH0-coefΔh0*(xi-quani)),Float64(coefH1-coefΔh1*(xi-quani)),Float64(coefH2-coefΔh2*(xi-quani)),Float64(coefH3-coefΔh3*(xi-quani)),Float64(coefH4-coefΔh4*(xi-quani)),Float64(coefH5-coefΔh5*(xi-quani)),Float64(coefH6-coefΔh6*(xi-quani))]
coefj2=[Float64(coefH0j-coefΔh0*(xj-quanj)),Float64(coefH1j-coefΔh1*(xj-quanj)),Float64(coefH2j-coefΔh2*(xj-quanj)),Float64(coefH3j-coefΔh3*(xj-quanj)),Float64(coefH4j-coefΔh4*(xj-quanj)),Float64(coefH5j-coefΔh5*(xj-quanj)),Float64(coefH6j-coefΔh6*(xj-quanj))]
ri=roots(coefi)
rj=roots(coefj)
ri2=roots(coefi2)
rj2=roots(coefj2)
#filter roots
counterRooti=1
for h in ri
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsi[counterRooti]=(real(h))
counterRooti+=1
end
end
checkRoots(cacheRootsi,coefi,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quani)
for h in ri2
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsi[counterRooti]=(real(h))
counterRooti+=1
end
end
sort!(cacheRootsi);
counterRootj=1
for h in rj
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsj[counterRootj]=(real(h))
counterRootj+=1
end
end
checkRoots(cacheRootsj,coefj,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quanj)
for h in rj2
if abs(imag(h)) < 1.0e-15 && real(h)>0.0
cacheRootsj[counterRootj]=(real(h))
counterRootj+=1
end
end
sort!(cacheRootsj);
#= for h in cacheRootsi
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
if abs(qi-xi)>2quani
error("your own h not working for you, i")
end
end
end
for h in cacheRootsj
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
if abs(qj-xj)>2quanj
error("your own h not working for you, j")
end
end
end =#
#construct intervals
constructIntrval(acceptedi,cacheRootsi)
constructIntrval(acceptedj,cacheRootsj)
ki=7;kj=7
h=-1.0
debugTracker=0
tryIteration=false
Δ1=0.0
while true
if ki==0 || kj==0
error("bug in finding the overlap")
end
currentLi=acceptedi[ki][1];currentHi=acceptedi[ki][2]
currentLj=acceptedj[kj][1];currentHj=acceptedj[kj][2]
if currentLj<=currentLi<currentHj || currentLi<=currentLj<currentHi#resj[end][1]<=resi[end][1]<=resj[end][2] || resi[end][1]<=resj[end][1]<=resi[end][2] #overlap
h=min(currentHi,currentHj )
if h==Inf && (currentLj!=0.0 || currentLi!=0.0) # except case both 0 sols h1=(0,Inf)
h=max(currentLj,currentLi#= ,ft-simt,dti =#) #ft-simt in case they are both ver small...elaborate on his later
#= if simt==2.500745083181994e-5
@show currentLj,currentLi
end =#
end
if h==Inf # both lower bounds ==0 --> zero sols for both
if aiijj_!=0.0
qi=coefH6/coefΔh6;qj=coefH6j/coefΔh6
cac=checkAcceptanceCriteria(qi,xi,quani,qj,xj,quanj)
if cac
#= qi1=(aji*uij2-uji2*aij)/aiijj_ #resul of ddx=aq+aq+u=0 ...2eqs 2 unknowns
qj1=(-uij2-aii*qi1)/aij =#
h=ft
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
while Δ1==0.0
h=h*0.98
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
end
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
debugTracker=1
else
tryIteration=true
end
else
tryIteration=true
end
if tryIteration
#return false
#later try to study critical points(maxima) to find best
h = ft-simt
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
if (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj)
h1 = sqrt(abs(2*quani/xi2));h2 = sqrt(abs(2*quanj/xj2)); #later add derderX =1e-12 when x2==0?
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
maxIter=10000
while (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj) && (maxIter>0)
maxIter-=1
h1 = h * sqrt(quani / abs(qi - xi));
h2 = h * sqrt(quanj / abs(qj - xj));
#= h1 = h * (0.99*1.8*quani / abs(qi - xi));
h2 = h * (0.99*1.8*quanj / abs(qj - xj)); =#
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
if maxIter==0 || Δ1==0.0 # maxIter=0 :failed to bring q down within a reasonable time. Δ1==0.0 should never happen when maxIter>0...but keep it there for now
return false
end
debugTracker=2
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
end#end if iteration
else #h!=Inf
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ22)!=0.0 && Δ1!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
#= if 2.500745083181994e-5<=simt<3.00745083181994e-5
@show "simul: ",index,qi,xi,quani,h,simt,j,qj,xj,quanj
end =#
cac=checkAcceptanceCriteria(qi,xi,quani,qj,xj,quanj)
if !cac
tryIteration=true
else
debugTracker=3
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
end
else
tryIteration=true
end
if tryIteration
#println("singularities Δ22=0")#do iterations
h = ft-simt
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
if (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj)
h1 = sqrt(abs(2*quani/xi2));h2 = sqrt(abs(2*quanj/xj2)); #later add derderX =1e-12 when x2==0?
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
maxIter=10000
while (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj) && (maxIter>0)
maxIter-=1
h1 = h * sqrt(quani / abs(qi - xi));
h2 = h * sqrt(quanj / abs(qj - xj));
#= h1 = h * (0.99*1.8*quani / abs(qi - xi));
h2 = h * (0.99*1.8*quanj / abs(qj - xj)); =#
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end # end while iteration
if maxIter==0 || Δ1==0.0 # maxIter=0 :failed to bring q down within a reasonable time. Δ1==0.0 should never happen when maxIter>0...but keep it there for now
return false
end
debugTracker=4
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
end# end if tryiteration
#= q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
qi1=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# Δ1!=0 from iterations
qj1=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj =#
end# end h inf or else
break
else
if currentHj==0.0 && currentHi==0.0#empty
ki-=1;kj-=1
elseif currentHj==0.0 && currentHi!=0.0
kj-=1
elseif currentHi==0.0 && currentHj!=0.0
ki-=1
else #both non zero
if currentLj<currentLi#remove last seg of resi
ki-=1
else #remove last seg of resj
kj-=1
end
end
end
end # end while
#checkRoots(cacheRootsi,coefi,coefi2) # for free stress-testing allrealrootintervalnewtonregulafalsi
# checkRoots(cacheRootsj,coefj,coefj2) #later check if error in roots makes q-x >2quan...use commented code below
q[index][0]=Float64(qi)# store back helper vars
q[j][0]=Float64(qj)
q[index][1]=Float64(qi1)
q[j][1]=Float64(qj1)
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
#= if abs(qi-xi)<quani/1000 && abs(qj-xj)<quanj/1000
#if quani/1000<abs(qi-xi)<quani/10 && quanj/1000<abs(qj-xj)<quanj/10
println("end of simul: qi & qj thrown both very close")
@show abs(qi-xi),quani , abs(qj-xj),quanj
@show simt,debugTracker
end =#
#= if isnan(qi)
@show simt,"qi",debugTracker
end
if isnan(qi1)
@show simt,"qi1",debugTracker
end
if isnan(qj)
@show simt,"qj",debugTracker
end
if isnan(qj1)
@show simt,"qj1",debugTracker
end =#
end #end if iscycle
return iscycle
end
#= function checkRootsIntNew(cacheRootsi,coefi,coefi2)
for h in cacheRootsi
zci=abs(coefi[1]*h^6+coefi[2]*h^5+coefi[3]*h^4+coefi[4]*h^3+coefi[5]*h^2+coefi[6]*h+coefi[7])
zci2=abs(coefi2[1]*h^6+coefi2[2]*h^5+coefi2[3]*h^4+coefi2[4]*h^3+coefi2[5]*h^2+coefi2[6]*h+coefi2[7])
if zci>1e-6 && zci2>1e-6
println("error in mliqss_quantizer2: coming from root solver ")
@show h,coefi,zci
@show coefi2,zci2
end
end
end =#
#= function checkRoots(cacheRootsi,coefi,coefi2)
for h in cacheRootsi
if h>0 # cache is large and contains 0 0 0 0 0 0
zci=abs(coefi[7]*h^6+coefi[6]*h^5+coefi[5]*h^4+coefi[4]*h^3+coefi[3]*h^2+coefi[2]*h+coefi[1])
zci2=abs(coefi2[7]*h^6+coefi2[6]*h^5+coefi2[5]*h^4+coefi2[4]*h^3+coefi2[3]*h^2+coefi2[2]*h+coefi2[1])
if zci>1e-5 && zci2>1e-5
println("error in mliqss_quantizer2: coming from root solver ")
if zci>1e-5 @show h,coefi,zci end
if zci2>1e-5 @show h,coefi2,zci2 end
end
end
end
end =#
function checkRoots(cacheRootsi,coefi,coefΔh0,coefΔh1,coefΔh2,coefΔh3,coefΔh4,coefΔh5,coefΔh6,quani)
for h in cacheRootsi
if h>0 # cache is large and contains 0 0 0 0 0 0
zci=coefi[7]*h^6+coefi[6]*h^5+coefi[5]*h^4+coefi[4]*h^3+coefi[3]*h^2+coefi[2]*h+coefi[1]
Δ=coefΔh0+h*coefΔh1+coefΔh2*h*h+coefΔh3*h^3+coefΔh4*h^4+coefΔh5*h^5+coefΔh6*h^6
if (zci/(Δ*Δ))>(quani/100)
println("zci not zero makes q changes by more than a quan...root finding not good...Δ=$Δ")
@show h,zci,quani,coefi
@show typeof(h),typeof(zci),typeof(quani),typeof(coefi)
end
#= if zci>1e-5
println("error in mliqss_quantizer2: coming from root solver ")
@show h,coefi,zci
end =#
end
end
end
#= function getQfromAsymptote(x::Float64,coefH0::Float64,coefH1::P,coefH2::P,coefH3::P,coefH4::P,coefH5::P,coefH6::P,coefΔh0::Float64,coefΔh1::P,coefΔh2::P,coefΔh3::P,coefΔh4::P,coefΔh5::P,coefΔh6::P) where {P<:Union{BigFloat,Float64}}
q=0.0
if coefΔh6==0.0 && coefH6!=0.0
@show coefΔh6,coefH6
error("report bug in simul2: could appear when a var becomes a NaN")
elseif coefΔh6==0.0 && coefH6==0.0
if coefΔh5==0.0 && coefH5!=0.0
println("simul2: coef5 asymptote should not be outside of +-delta !!!")
elseif coefΔh5==0.0 && coefH5==0.0
if coefΔh4==0.0 && coefH4!=0.0
println("simul2: coef4 asymptote should not be outside of +-delta !!!")
elseif coefΔh4==0.0 && coefH4==0.0
if coefΔh3==0.0 && coefH3!=0.0
println("simul2: coef3 asymptote should not be outside of +-delta !!!")
elseif coefΔh3==0.0 && coefH3==0.0
if coefΔh2==0.0 && coefH2!=0.0
println("simul2: coef2 asymptote should not be outside of +-delta !!!")
elseif coefΔh2==0.0 && coefH2==0.0
if coefΔh1==0.0 && coefH1!=0.0
println("simul2: coef1 asymptote should not be outside of +-delta !!!")
elseif coefΔh1==0.0 && coefH1==0.0
if coefΔh0!=0.0
q=coefH0/coefΔh0
else
q=x
end
else#coefΔh1!=0.0
q=coefH1/coefΔh1
end
else#coefΔh2!=0.0
q=coefH2/coefΔh2
end
else#coefΔh3!=0.0
q=coefH3/coefΔh3
end
else#coefΔh4!=0.0
q=coefH4/coefΔh4
end
else#coefΔh5!=0.0
q=coefH5/coefΔh5
end
else#coefΔh6!=0.0
q=coefH6/coefΔh6
end
q
end =#
function checkAcceptanceCriteria(qi,xi,quani,qj,xj,quanj)
testVari=100;testVarj=100
if abs(qi-xi)==0.0
testVari=1
elseif quani/100000.0<abs(qi-xi)<=quani/1000.0
testVari=2
elseif quani/1000.0<abs(qi-xi)<=quani/100.0
testVari=3
elseif quani/100.0<abs(qi-xi)<=quani/2.0
testVari=4
elseif quani/2.0<abs(qi-xi)<=quani/1.0
testVari=5
elseif abs(qi-xi)<2quani
testVari=6
else
#testVari=6
end
if abs(qj-xj)==0.0
testVarj=1
elseif quanj/100000.0<abs(qj-xj)<=quanj/1000.0
testVarj=2
elseif quanj/1000.0<abs(qj-xj)<=quanj/100.0
testVarj=3
elseif quanj/100.0<abs(qj-xj)<=quanj/2.0
testVarj=4
elseif quanj/2.0<abs(qj-xj)<=quanj/1.0
testVarj=5
elseif abs(qj-xj)<2quanj
testVarj=6
else
#testVarj=6
end
#if testVari*testVarj==9 || testVari*testVarj==1#either both normal throws or special case equilibrium
if testVari*testVarj==25 #|| testVari*testVarj==20 #|| testVari*testVarj==15 #|| testVari*testVarj==10 #|| testVari*testVarj==5
return true
else
return true#false
end
end
function checkAcceptanceCriteria2(qi,xi,quani,qj,xj,quanj)
return false
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 9226 |
function nmisCycle_and_simulUpdate(::Val{3},index::Int,j::Int,prevStepVal::Float64,direction::Vector{Float64}, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},a::Vector{Vector{Float64}},u::Vector{Vector{MVector{O,Float64}}},qaux::Vector{MVector{O,Float64}},olddx::Vector{MVector{O,Float64}},olddxSpec::Vector{MVector{O,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64,qminus::Vector{Float64})where{O}
aii=a[index][index];ajj=a[j][j];aij=a[index][j];aji=a[j][index]
xi=x[index][0];xj=x[j][0];qi=q[index][0];qj=q[j][0];qi1=q[index][1];qi2=2*q[index][2];qj1=q[j][1];qj2=2*q[j][2]
uii=u[index][index][1];uij=u[index][j][1];ujj=u[j][j][1]#;uji=u[j][index][1]#;uji2=u[j][index][2]
quanj=quantum[j];quani=quantum[index];xi1=x[index][1];xi2=2*x[index][2];xi3=6*x[index][3];xj1=x[j][1];xj2=2*x[j][2];xj3=6*x[j][3]
e1 = simt - tx[j];e2 = simt - tq[j]; tx[j]=simt;
x[j][0]= x[j](e1);xjaux=x[j][0]
xj1=xj1+e1*xj2+e1*e1*xj3/2;olddxSpec[j][1]=xj1;olddx[j][1]=xj1; xj2=xj2+e1*xj3
qj=qj+e2*qj1+e2*e2*qj2/2 ;qj1=qj1+e2*qj2; qaux[j][1]=qj ;qaux[j][2]=qj1
newDiff=(x[j][0]-prevStepVal)
dir=direction[j]
if newDiff*dir <0.0
direction[j]=-dir
elseif newDiff==0 && dir!=0.0
direction[j]=0.0
elseif newDiff!=0 && dir==0.0
direction[j]=newDiff
else
#do not update direction
end
ujj=ujj+e1*u[j][j][2]+e1*e1*u[j][j][3]/2
#ujj=xj1-ajj*qj
u[j][j][1]=ujj
#u[j][j][2]=u[j][j][2]+e1*u[j][j][3]
u[j][j][2]=xj2-ajj*qj1
u[j][j][3]=xj3-ajj*qj2###################################
u[j][index][1]=ujj-aji*qaux[index][1]#
uji=u[j][index][1]
u[j][index][2]=u[j][j][2]-aji*qaux[index][2]#less cycles but with a bump at 1.5...ft20: smooth with some bumps
uji2=u[j][index][2]
u[j][index][3]=u[j][j][3]-aji*qaux[index][3]#
uji3=u[j][index][3]
dxj=aji*qi+ajj*qaux[j][1]+uji
ddxj=aji*qi1+ajj*qj1+uji2
dddxj=aji*qi2+ajj*qj2+uji3
iscycle=false
u[index][j][1]=u[index][index][1]-aij*qaux[j][1]
uij=u[index][j][1]
u[index][j][2]=u[index][index][2]-aij*qj1
uij2=u[index][j][2]
u[index][j][3]=u[index][index][3]-aij*qj2
uij3=u[index][j][3]
# if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2) || abs(dddxj-xj3)>(abs(dddxj+xj3)/2))
h1=cbrt(abs(6*quanj/dddxj))
qjplus=xjaux+h1*h1*h1*dddxj/6
#@show h,qjplus,xjaux
λ=ajj*qjplus+aji*qi+uji+h1*(aji*qi1+uji2)+h1*h1*(aji*qi2+uji3)/2
α=(h1-h1*h1/2)*(aji*(qi1+h1*qi2)+uji2+h1*uji3)/(1-h1*ajj)
β=1-h1*ajj+(h1-h1*h1/2)*ajj/(1-h1*ajj)
dqjplus=(λ-α)/β
ddqjplus=(aji*(qi1+h1*qi2)+ajj*dqjplus+uji2+h1*uji3)/(1-h1*ajj)
###
#u[index][j][1]=u[index][index][1]-a[index][j]*q[j][0] # shifts down at 18
#= u[index][j][1]=u[index][index][1]-aij*qaux[j][1]
uij=u[index][j][1]
u[index][j][2]=u[index][index][2]-aij*qj1#########qaux[j][2] updated in normal Qupdate..ft=20 slightly shifts up
uij2=u[index][j][2] =#
dxi=aii*qi+aij*qjplus+uij
ddxi=aii*qi1+aij*dqjplus+uij2
dddxi=aii*qi2+aij*ddqjplus+uij3
#= #dqjplus-qj1 is enough: normally (qjplus+h*dqjlpus-qj+h*qj1) . dqjplus-qj1 is better than dqjplus alone cuz the case dqjplus=0
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || (dqjplus+h1*ddqjplus)*direction[j]<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
h2=cbrt(abs(6*quani/dddxi))
β=dxi+ddxi*h2/2+dddxi*h2*h2/6
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2)) || β*direction[index]<0.0 =#
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2) || abs(dddxj-xj3)>(abs(dddxj+xj3)/2)) || (dqjplus+h1*ddqjplus)*direction[j]<0.0#(dqjplus+h1*ddqjplus-qj1-e1*qj2)*direction[j]<0.0
h2=cbrt(abs(6*quani/dddxi))
h2=cbrt(abs(6*quani/dddxi))
β=dxi+ddxi*h2/2+dddxi*h2*h2/6
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2) || abs(dddxi-xi3)>(abs(dddxi+xi3)/2))|| β*direction[index]<0.0
# if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2) || abs(dddxi-xi3)>(abs(dddxi+xi3)/2))
iscycle=true
h = ft-simt;
qi,qj,Mi,Mj,Linvii,Linvij,Linvji,Linvjj,Nii,Nij,Nji,Njj=simulQ3(aii,aij,aji,ajj,h,xi,xjaux,uij,uij2,uij3,uji,uji2,uji3)
if (abs(qi - xi) > 2*quani || abs(qj - xjaux) > 2*quanj) # removing this did nothing...check @btime later
h1 = cbrt(abs(6*quani/dddxi));h2 = cbrt(abs(6*quanj/dddxj)); #later add derderX =1e-12 when x2==0
h=min(h1,h2)
qi,qj,Mi,Mj,Linvii,Linvij,Linvji,Linvjj,Nii,Nij,Nji,Njj=simulQ3(aii,aij,aji,ajj,h,xi,xjaux,uij,uij2,uij3,uji,uji2,uji3)
end
maxIter=600000
while (abs(qi - xi) > 2*quani || abs(qj - xjaux) > 2*quanj) && (maxIter>0) && (h!=0.0)
maxIter-=1
# h1 = h * (0.98*quani / abs(qi - xi));
h1 = h *cbrt(quani / abs(qi - xi))
# h2 = h * (0.98*quanj / abs(qj - xjaux));
h2 = h *cbrt(quanj / abs(qj - xjaux))
h=min(h1,h2)
qi,qj,Mi,Mj,Linvii,Linvij,Linvji,Linvjj,Nii,Nij,Nji,Njj=simulQ3(aii,aij,aji,ajj,h,xi,xjaux,uij,uij2,uij3,uji,uji2,uji3)
end
if maxIter < 1
println("maxtiter simult_val{3}")
@show maxIter
end
q[index][0]=qi# store back helper vars
q[j][0]=qj
MAQi=Mi+aii*qi+aij*qj+uij+h*uij2+h*h*uij3/2;MAQj=Mj+ajj*qj+aji*qi+uji+h*uji2+h*h*uji3/2
# MAQ=(M+A*Q+U+h*U2+(h*h/2)*U3)# Q1=Linv*MAQ
q1i=Linvii*MAQi+Linvij*MAQj;q1j=Linvji*MAQi+Linvjj*MAQj
q[index][1]=q1i#Q1[1]# store back helper vars
q[j][1]=q1j#Q1[2]
AQUi=aii*q1i+aij*q1j+uij2+h*uij3;AQUj=ajj*q1j+aji*q1i+uji2+h*uji3
q2i=Nii*AQUi+Nij*AQUj;q2j=Nji*AQUi+Njj*AQUj
q[index][2]=q2i/2#Q2[1]/2# store back helper vars: /2 for taylor standard storage
q[j][2]=q2j/2#Q2[2]/2
tq[j]=simt
end #end second dependecy check
end # end outer dependency check
#= if debug
println("end of iscycle function")
end =#
return iscycle
end
#######################################################################################################################################################
@inline function simulQ3(#= simul3Helper::MVector{10,Float64}, =#aii::Float64,aij::Float64,aji::Float64,ajj::Float64,h::Float64,xi::Float64,xjaux::Float64,uij::Float64,uij2::Float64,uij3::Float64,uji::Float64,uji2::Float64,uji3::Float64)
#=
the following matrix-based code is changed below (no matrices)
N=inv(I-h*A)
R=h*I-(h*h/2)*A+((h*h/2)*N*A-(h*h*h/6)*A*N*A)
Linv=inv(I-h*A+h*N*A-(h*h/2)*A*N*A)
M=((h*h/2)*A-h*I)*N*(U2+h*U3)
P=X+(h*U+(h*h/2)*U2+(h*h*h/6)*U3)
S=-R*Linv*(M+U+h*U2+(h*h/2)*U3)-(((h*h/2)*I-(h*h*h/6)*A)*N*(U2+h*U3))+P
Q=inv(I-h*A+R*Linv*A)*S =#
h_2=h*h/2;h_6=h*h*h/6
# N=inv(I-h*A)
Δ1=(1-h*aii)*(1-h*ajj)-h*h*aij*aji
Nii=(1-h*ajj)/Δ1;Nij=(h*aij)/Δ1;Nji=(aji*h)/Δ1;Njj=(1-h*aii)/Δ1#N=inv(I-h*A)
NAii=Nii*aii+Nij*aji;NAij=Nii*aij+Nij*ajj;NAji=Nji*aii+Njj*aji;NAjj=Nji*aij+Njj*ajj
ANAii=aii*NAii+aij*NAji;ANAij=aii*NAij+aij*NAjj;ANAji=aji*NAii+ajj*NAji;ANAjj=aji*NAij+ajj*NAjj
Rii=h-(h_2)*aii+(h_2)*NAii-(h_6)*ANAii;Rij=-(h_2)*aij+(h_2)*NAij-(h_6)*ANAij;Rji=-(h_2)*aji+(h_2)*NAji-(h_6)*ANAji;Rjj=h-(h_2)*ajj+(h_2)*NAjj-(h_6)*ANAjj#R=h*I-(h*h/2)*A+((h*h/2)*N*A-(h*h*h/6)*A*N*A)
# R=[Rii Rij;Rji Rjj]
Lii=1-h*aii+h*NAii-(h_2)*ANAii;Lij=-h*aij+h*NAij-(h_2)*ANAij;Lji=-h*aji+h*NAji-(h_2)*ANAji;Ljj=1-h*ajj+h*NAjj-(h_2)*ANAjj
ΔL=Lii*Ljj-Lij*Lji
Linvii=Ljj/ΔL;Linvij=-Lij/ΔL;Linvji=-Lji/ΔL;Linvjj=Lii/ΔL## Linv=inv(I-h*A+h*N*A-(h*h/2)*A*N*A)
# Linv=[Linvii Linvij;Linvji Linvjj]
# M=((h*h/2)*A-h*I)*N*(U2+h*U3)
U23i=uij2+h*uij3
U23j=uji2+h*uji3
NU23i=Nii*U23i+Nij*U23j
NU23j=Nji*U23i+Njj*U23j
Mi=(h_2*aii-h)*NU23i+h_2*aij*NU23j
Mj=h_2*aji*NU23i+(h_2*ajj-h)*NU23j
# M=[Mi;Mj]#M=((h*h/2)*A-h*I)*N*(U2+h*U3)
Pi=xi+(h*uij+(h_2)*uij2+(h_6)*uij3);Pj=xjaux+(h*uji+(h_2)*uji2+(h_6)*uji3)# P=X+(h*U+(h*h/2)*U2+(h*h*h/6)*U3)
# P=[Pi;Pj]
S2i=(h_2-h_6*aii)*NU23i-h_6*aij*NU23j;S2j=(h_2-h_6*ajj)*NU23j-h_6*aji*NU23i# S2=(((h_2)*I-(h_6)*A)*N*(U2+h*U3))
# S2=[S2i;S2j]
S1i=(Mi+uij+h*uij2+(h_2)*uij3);S1j=(Mj+uji+h*uji2+(h_2)*uji3)# S1=(M+U+h*U2+(h_2)*U3)
LinvS1i=Linvii*S1i+Linvij*S1j;LinvS1j=Linvji*S1i+Linvjj*S1j
# LinvS1=[LinvS1i;LinvS1j]
RLinvS1i=Rii*LinvS1i+Rij*LinvS1j;RLinvS1j=Rji*LinvS1i+Rjj*LinvS1j
# RLinvS1=[RLinvS1i;RLinvS1j]
# S=P-RLinvS1-S2
Si=Pi-RLinvS1i-S2i
Sj=Pj-RLinvS1j-S2j
#S=[Si;Sj]
LinvAii=Linvii*aii+Linvij*aji;LinvAij=Linvii*aij+Linvij*ajj;LinvAji=Linvji*aii+Linvjj*aji;LinvAjj=Linvji*aij+Linvjj*ajj
RLinvAii=Rii*LinvAii+Rij*LinvAji;RLinvAij=Rii*LinvAij+Rij*LinvAjj;RLinvAji=Rji*LinvAii+Rjj*LinvAji;RLinvAjj=Rji*LinvAij+Rjj*LinvAjj
#α=I_hARLinvA#
αii=1-h*aii+RLinvAii; αij=-h*aij+RLinvAij;αji=-h*aji+RLinvAji; αjj=1-h*ajj+RLinvAjj
Δα=αii*αjj-αij*αji
InvAlphaii=αjj/Δα;InvAlphaij=-αij/Δα;InvAlphaji=-αji/Δα;InvAlphajj=αii/Δα;
# InvAlpha=[InvAlphaii InvAlphaij;InvAlphaji InvAlphajj]
qi=InvAlphaii*Si+InvAlphaij*Sj
qj=InvAlphaji*Si+InvAlphajj*Sj
return (qi,qj,Mi,Mj,Linvii,Linvij,Linvji,Linvjj,Nii,Nij,Nji,Njj)
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 10206 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
# Arithmetic operations: +, -, *, /
## Equality ##
#= ==(a::Taylor0, b::Taylor0{S}) where {T<:Number,S<:Number} = ==(promote(a,b)...) =#
function ==(a::Taylor0, b::Taylor0)
#= if a.order != b.order
a, b = fixorder(a, b)
end =#
return a.coeffs == b.coeffs
end
iszero(a::Taylor0) = iszero(a.coeffs)
## zero and one ##
zero(a::Taylor0) = Taylor0(zero.(a.coeffs))
function zero(a::Taylor0,cache::Taylor0)
cache.coeffs .= 0.0
return cache
end
function one(a::Taylor0,cache::Taylor0)
cache.coeffs .= 0.0
cache[0]=1.0
return cache
end
function one(a::Taylor0)
b = zero(a)
b[0] = one(b[0])
return b
end
## Addition fallback for case a+a+a+a+a+a+a+a+a+a+a+a+a+a##
#= (+)(a::Taylor0, b::Taylor0{S}) where {T<:Number,S<:Number} =
(+)(promote(a,b)...) =#
function (+)(a::Taylor0, b::Taylor0)
#= if a.order != b.order
a, b = fixorder(a, b)
end =#
v = similar(a.coeffs)
@__dot__ v = (+)(a.coeffs, b.coeffs)
return Taylor0(v, a.order)
end
function (+)(a::Taylor0)
v = similar(a.coeffs)
@__dot__ v = (+)(a.coeffs)
return Taylor0(v, a.order)
end
#= (+)(a::Taylor0, b::S) where {T<:Number,S<:Number} =
(+)(promote(a,b)...) =#
function (+)(a::Taylor0, b::T) where {T<:Number}
coeffs = copy(a.coeffs)
@inbounds coeffs[1] = (+)(a[0], b)
return Taylor0(coeffs, a.order)
end
#= (+)(b::S, a::Taylor0) where {T<:Number,S<:Number} =
(+)(promote(b,a)...) =#
function (+)(b::T, a::Taylor0) where {T<:Number}
coeffs = similar(a.coeffs)
@__dot__ coeffs = (+)(a.coeffs)
@inbounds coeffs[1] = (+)(b, a[0])
return Taylor0(coeffs, a.order)
end
## substraction ##
#= (-)(a::Taylor0, b::Taylor0{S}) where {T<:Number,S<:Number} =
(-)(promote(a,b)...) =#
function (-)(a::Taylor0, b::Taylor0)
if a.order != b.order
a, b = fixorder(a, b)
end
v = similar(a.coeffs)
@__dot__ v = (-)(a.coeffs, b.coeffs)
return Taylor0(v, a.order)
end
function (-)(a::Taylor0)
v = similar(a.coeffs)
@__dot__ v = (-)(a.coeffs)
return Taylor0(v, a.order)
end
#= (-)(a::Taylor0, b::S) where {T<:Number,S<:Number} =
(-)(promote(a,b)...) =#
function (-)(a::Taylor0, b::T) where {T<:Number}
coeffs = copy(a.coeffs)
@inbounds coeffs[1] = (-)(a[0], b)
return Taylor0(coeffs, a.order)
end
#= (-)(b::S, a::Taylor0) where {T<:Number,S<:Number} =
(-)(promote(b,a)...) =#
function (-)(b::T, a::Taylor0) where {T<:Number}
coeffs = similar(a.coeffs)
@__dot__ coeffs = (-)(a.coeffs)
@inbounds coeffs[1] = (-)(b, a[0])
return Taylor0(coeffs, a.order)
end
## Multiplication fallback for case a*a*a*a*a*a*a*a*a*a*a*a*a##
function *(a::Taylor0, b::Taylor0)
#= if a.order != b.order
a, b = fixorder(a, b)
end =#
c = Taylor0(zero(a[0]), a.order)
for ord in eachindex(c)
mul!(c, a, b, ord) # updates c[ord]
end
return c
end
#= function *(a::T, b::Taylor0{S}) where {T<:NumberNotSeries,S<:NumberNotSeries}
@inbounds aux = a * b.coeffs[1]
v = Array{typeof(aux)}(undef, length(b.coeffs))
@__dot__ v = a * b.coeffs
return Taylor0(v, b.order)
end
*(b::Taylor0{S}, a::T) where {T<:NumberNotSeries,S<:NumberNotSeries} = a * b =#
function (*)(a::T, b::Taylor0) where {T<:Number}
v = Array{T}(undef, length(b.coeffs))
@__dot__ v = a * b.coeffs
return Taylor0(v, b.order)
end
*(b::Taylor0, a::T) where {T<:Number} = a * b
# Internal multiplication functions
@inline function mul!(c::Taylor0, a::Taylor0, b::Taylor0, k::Int)
@inbounds c[k] = a[0] * b[k]
@inbounds for i = 1:k
c[k] += a[i] * b[k-i]
end
return nothing
end
#= @inline function mul!(v::Taylor0, a::Taylor0, b::NumberNotSeries, k::Int)
@inbounds v[k] = a[k] * b
return nothing
end
@inline function mul!(v::Taylor0, a::NumberNotSeries, b::Taylor0, k::Int)
@inbounds v[k] = a * b[k]
return nothing
end =#
#=
@doc doc"""
mul!(c, a, b, k::Int) --> nothing
Update the `k`-th expansion coefficient `c[k]` of `c = a * b`,
where all `c`, `a`, and `b` are either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
c_k = \sum_{j=0}^k a_j b_{k-j}.
```
""" mul!
"""
mul!(c, a, b) --> nothing
Return `c = a*b` with no allocation; all arguments are `HomogeneousPolynomial`.
"""
=#
## Division ##
#= function /(a::Taylor0{Rational{T}}, b::S) where {T<:Integer,S<:NumberNotSeries}
R = typeof( a[0] // b)
v = Array{R}(undef, a.order+1)
@__dot__ v = a.coeffs // b
return Taylor0(v, a.order)
end =#
#= function /(a::Taylor0, b::S) where {T<:NumberNotSeries,S<:NumberNotSeries}
@inbounds aux = a.coeffs[1] / b
v = Array{typeof(aux)}(undef, length(a.coeffs))
@__dot__ v = a.coeffs / b
return Taylor0(v, a.order)
end =#
function /(a::Taylor0, b::T) where {T<:Number}
@inbounds aux = a.coeffs[1] / b
v = Array{typeof(aux)}(undef, length(a.coeffs))
@__dot__ v = a.coeffs / b
return Taylor0(v, a.order)
end
#= /(a::Taylor0, b::Taylor0{S}) where {T<:Number,S<:Number} = /(promote(a,b)...) =#
function /(a::Taylor0, b::Taylor0)
iszero(a) && !iszero(b) && return zero(a)
if a.order != b.order
a, b = fixorder(a, b)
end
# order and coefficient of first factorized term
ordfact, cdivfact = divfactorization(a, b)
c = Taylor0(cdivfact, a.order-ordfact)
for ord in eachindex(c)
div!(c, a, b, ord) # updates c[ord]
end
return c
end
@inline function divfactorization(a1::Taylor0, b1::Taylor0)
# order of first factorized term; a1 and b1 assumed to be of the same order
a1nz = findfirst(a1)
b1nz = findfirst(b1)
a1nz = a1nz ≥ 0 ? a1nz : a1.order
b1nz = b1nz ≥ 0 ? b1nz : a1.order
ordfact = min(a1nz, b1nz)
cdivfact = a1[ordfact] / b1[ordfact]
# Is the polynomial factorizable?
iszero(b1[ordfact]) && throw( ArgumentError(
"""Division does not define a Taylor0 polynomial;
order k=$(ordfact) => coeff[$(ordfact)]=$(cdivfact).""") )
return ordfact, cdivfact
end
## TODO: Implement factorization (divfactorization) for TaylorN polynomials
#=
# Homogeneous coefficient for the division
@doc doc"""
div!(c, a, b, k::Int)
Compute the `k-th` expansion coefficient `c[k]` of `c = a / b`,
where all `c`, `a` and `b` are either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
c_k = \frac{1}{b_0} \big(a_k - \sum_{j=0}^{k-1} c_j b_{k-j}\big).
```
For `Taylor0` polynomials, a similar formula is implemented which
exploits `k_0`, the order of the first non-zero coefficient of `a`.
""" div! =#
@inline function div!(c::Taylor0, a::Taylor0, b::Taylor0, k::Int)
# order and coefficient of first factorized term
ordfact, cdivfact = divfactorization(a, b)
if k == 0
@inbounds c[0] = cdivfact
return nothing
end
imin = max(0, k+ordfact-b.order)
@inbounds c[k] = c[imin] * b[k+ordfact-imin]
@inbounds for i = imin+1:k-1
c[k] += c[i] * b[k+ordfact-i]
end
if k+ordfact ≤ b.order
@inbounds c[k] = (a[k+ordfact]-c[k]) / b[ordfact]
else
@inbounds c[k] = - c[k] / b[ordfact]
end
return nothing
end
#= @inline function div!(v::Taylor0, a::Taylor0, b::NumberNotSeries, k::Int)
@inbounds v[k] = a[k] / b
return nothing
end
div!(v::Taylor0, b::NumberNotSeries, a::Taylor0, k::Int) =
div!(v::Taylor0, Taylor0(b, a.order), a, k) =#
#= """
mul!(Y, A, B)
Multiply A*B and save the result in Y.
""" =#
#= function mul!(y::Vector{Taylor0},
a::Union{Matrix{T},SparseMatrixCSC{T}},
b::Vector{Taylor0}) where {T<:Number}
n, k = size(a)
@assert (length(y)== n && length(b)== k)
# determine the maximal order of b
# order = maximum([b1.order for b1 in b])
order = maximum(get_order.(b))
# Use matrices of coefficients (of proper size) and mul!
# B = zeros(T, k, order+1)
B = Array{T}(undef, k, order+1)
B = zero.(B)
for i = 1:k
@inbounds ord = b[i].order
@inbounds for j = 1:ord+1
B[i,j] = b[i][j-1]
end
end
Y = Array{T}(undef, n, order+1)
mul!(Y, a, B)
@inbounds for i = 1:n
# y[i] = Taylor0( collect(Y[i,:]), order)
y[i] = Taylor0( Y[i,:], order)
end
return y
end =#
# Adapted from (Julia v1.2) stdlib/v1.2/LinearAlgebra/src/dense.jl#721-734,
# licensed under MIT "Expat".
# Specialize a method of `inv` for Matrix{Taylor0}. Simply, avoid pivoting,
# since the polynomial field is not an ordered one.
# function Base.inv(A::StridedMatrix{Taylor0}) where T
# checksquare(A)
# S = Taylor0{typeof((one(T)*zero(T) + one(T)*zero(T))/one(T))}
# AA = convert(AbstractArray{S}, A)
# if istriu(AA)
# Ai = triu!(parent(inv(UpperTriangular(AA))))
# elseif istril(AA)
# Ai = tril!(parent(inv(LowerTriangular(AA))))
# else
# # Do not use pivoting !!
# Ai = inv!(lu(AA, Val(false)))
# Ai = convert(typeof(parent(Ai)), Ai)
# end
# return Ai
# end
#= # see https://github.com/JuliaLang/julia/pull/40623
const LU_RowMaximum = VERSION >= v"1.7.0-DEV.1188" ? RowMaximum() : Val(true)
const LU_NoPivot = VERSION >= v"1.7.0-DEV.1188" ? NoPivot() : Val(false)
# Adapted from (Julia v1.2) stdlib/v1.2/LinearAlgebra/src/lu.jl#240-253
# and (Julia v1.4.0-dev) stdlib/LinearAlgebra/v1.4/src/lu.jl#270-274,
# licensed under MIT "Expat".
# Specialize a method of `lu` for Matrix{Taylor0}, which avoids pivoting,
# since the polynomial field is not an ordered one.
# We can't assume an ordered field so we first try without pivoting
function lu(A::AbstractMatrix{Taylor0}; check::Bool = true) where {T<:Number}
S = Taylor0{lutype(T)}
F = lu!(copy_oftype(A, S), LU_NoPivot; check = false)
if issuccess(F)
return F
else
return lu!(copy_oftype(A, S), LU_RowMaximum; check = check)
end
end =#
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 13868 |
(addsub)(a, b, c)=(-)((+)(a,b),c)
(subsub)(a, b, c)=(-)((-)(a,b),c)
(subadd)(a, b, c)=(+)((-)(a,b),c)# this should not exist cuz addsub has 3 args + cache
function addTfoldl(op, res, bs...)# op is only addt so remove later
l = length(bs)
#i = 0; l == i && return a # already checked
l == 1 && return res
i = 2; l == i && return op(res, bs[1],bs[end])
i = 3; l == i && return op(res, bs[1], bs[2],bs[end])
i = 4; l == i && return op(op(res, bs[1], bs[2],bs[end]), bs[3],bs[end])
i = 5; l == i && return op(op(res, bs[1], bs[2],bs[end]), bs[3],bs[4],bs[end])
i = 6; l == i && return op(op(op(res, bs[1], bs[2],bs[end]), bs[3],bs[4],bs[end]),bs[5],bs[end])
i = 7; l == i && return op(op(op(res, bs[1], bs[2],bs[end]), bs[3],bs[4],bs[end]),bs[5],bs[6],bs[end])
i = 8; l == i && return op(op(op(op(res, bs[1], bs[2],bs[end]), bs[3],bs[4],bs[end]),bs[5],bs[6],bs[end]),bs[7],bs[end])
i = 9;y=op(op(op(op(res, bs[1], bs[2],bs[end]), bs[3],bs[4],bs[end]),bs[5],bs[6],bs[end]),bs[7],bs[8],bs[end]); l == i && return y
#last i creates y and passes it to the next loop: note that from this point, op will allocate
# warn the users . (inserting -0 will avoid allocation lol!)
for i in i:l-1 # -1 cuz last one is cache...but these lines are never reached cuz macro does not create mulT for args >7 in the first place
y = op(y, bs[i],bs[end])
end
return y
end
function addT(a, b, c,d, xs...)
if length(xs)!=0# if ==0 case below where d==cache
addTfoldl(addT, addT( addT(a,b,c,xs[end]) , d ,xs[end] ), xs...)
end
end
function mulTfoldl(res::P, bs...) where {P<:Taylor0}
l = length(bs)
i = 2; l == i && return res
i = 3; l == i && return mulTT(res, bs[1],bs[end-1],bs[end])
i = 4; l == i && return mulTT(mulTT(res, bs[1],bs[end-1],bs[end]),bs[2],bs[end-1],bs[end])
i = 5; l == i && return mulTT(mulTT(mulTT(res, bs[1],bs[end-1],bs[end]),bs[2],bs[end-1],bs[end]),bs[3],bs[end-1],bs[end])
i = 6; l == i && return mulTT(mulTT(mulTT(mulTT(res, bs[1],bs[end-1],bs[end]),bs[2],bs[end-1],bs[end]),bs[3],bs[end-1],bs[end]),bs[4],bs[end-1],bs[end])
#= if l == 6
println("alloc!!!")
return mulTT(mulTT(mulTT(mulTT(res, bs[1],bs[end-1],bs[end]),bs[2],bs[end-1],bs[end]),bs[3],bs[end-1],bs[end]),bs[4],bs[end-1],bs[end])
end =#
end
function mulTT(a::P, b::R, c::Q, xs...)where {P,Q,R <:Union{Taylor0,Number}}
if length(xs)>1
mulTfoldl( mulTT( mulTT(a,b,xs[end-1],xs[end]) , c,xs[end-1] ,xs[end] ), xs...)
end
end
# all methods should have new names . no type piracy!!! if Taylor1 to be used
function createT(a::Taylor0,cache::Taylor0)
@__dot__ cache.coeffs=a.coeffs
return cache
end
function createT(a::T,cache::Taylor0) where {T<:Number} # requires cache1 clean
cache[0]=a
return cache
end
function addsub(a::Taylor0, b::Taylor0,c::Taylor0,cache::Taylor0)
@__dot__ cache.coeffs=(-)((+)(a.coeffs,b.coeffs),c.coeffs)
return cache
end
function addsub(a::Taylor0, b::Taylor0,c::T,cache::Taylor0) where {T<:Number}
cache.coeffs.=b.coeffs
cache[0]=cache[0]-c
@__dot__ cache.coeffs = (+)(cache.coeffs, a.coeffs)
return cache
end
function addsub(a::T, b::Taylor0,c::Taylor0,cache::Taylor0) where {T<:Number}
cache.coeffs.=b.coeffs
cache[0]=a+ cache[0]
@__dot__ cache.coeffs = (-)(cache.coeffs, c.coeffs)
return cache
end
addsub(a::Taylor0, b::T,c::Taylor0,cache::Taylor0) where {T<:Number}=addsub(b, a ,c,cache)#addsub(b::T, a::Taylor0 ,c::Taylor0,cache::Taylor0) where {T<:Number}
function addsub(a::T, b::T,c::Taylor0,cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = (-)(c.coeffs)
cache[0]=a+b+ cache[0]
return cache
end
function addsub(c::Taylor0,a::T, b::T,cache::Taylor0) where {T<:Number}
cache.coeffs.=c.coeffs
cache[0]=a+ cache[0]-b
return cache
end
addsub(a::T, c::Taylor0,b::T,cache::Taylor0) where {T<:Number}= addsub(c,a, b,cache)
function addsub(c::T,a::T, b::T,cache::Taylor0) where {T<:Number}#requires cache clean
cache[0]=a+c-b
return cache
end
###########"negate###########
function negateT(a::Taylor0,cache::Taylor0) #where {T<:Number}
@__dot__ cache.coeffs = (-)(a.coeffs)
return cache
end
function negateT(a::T,cache::Taylor0) where {T<:Number} # requires cache1 clean
cache[0]=-a
return cache
end
#################################################subsub########################################################"
function subsub(a::Taylor0, b::Taylor0,c::Taylor0,cache::Taylor0)
@__dot__ cache.coeffs = subsub(a.coeffs, b.coeffs,c.coeffs)
return cache
end
function subsub(a::Taylor0, b::Taylor0,c::T,cache::Taylor0) where {T<:Number}
cache.coeffs.=b.coeffs
cache[0]=cache[0]+c #(a-b-c=a-(b+c))
@__dot__ cache.coeffs = (-)(a.coeffs, cache.coeffs)
return cache
end
subsub(a::Taylor0, b::T,c::Taylor0,cache::Taylor0) where {T<:Number}=subsub(a, c,b,cache)
function subsub(a::T,b::Taylor0, c::Taylor0,cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = (-)(b.coeffs)
cache[0]=a+ cache[0]
@__dot__ cache.coeffs = (-)(cache.coeffs, c.coeffs)
return cache
end
function subsub(a::Taylor0, b::T,c::T,cache::Taylor0) where {T<:Number}
cache.coeffs.=a.coeffs
cache[0]=cache[0]-b-c
return cache
end
function subsub( a::T,b::Taylor0,c::T,cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = (-)(b.coeffs)
cache[0]=cache[0]+a-c
return cache
end
subsub( b::T,c::T,a::Taylor0,cache::Taylor0) where {T<:Number}=subsub( b,a,c,cache)
function subsub( a::T,b::T,c::T,cache::Taylor0) where {T<:Number}#require emptying the cache
cache[0]=a-b-c
return cache
end
#################################subadd####################################""
function subadd(a::P,b::Q,c::R,cache::Taylor0) where {P,Q,R <:Union{Taylor0,Number}}
addsub(a,c,b,cache)
end
##################################""subT################################
function subT(a::Taylor0, b::Taylor0,cache::Taylor0)# where {T<:Number}
@__dot__ cache.coeffs = (-)(a.coeffs, b.coeffs)
return cache
end
function subT(a::Taylor0, b::T,cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = a.coeffs
cache[0]=cache[0]-b
return cache
end
function subT(a::T, b::Taylor0,cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = (-)(b.coeffs)
cache[0]=cache[0]+a
return cache
end
function subT( a::T,b::T,cache::Taylor0) where {T<:Number} ##require emptying the cache
#cache.coeffs.=0.0 # ok to empty...allocates !!!
cache[0]=a-b
return cache
end
#= function addT(a::Taylor0, b::T) where {T<:Number} #case where no cache is given, a is not a var and it is ok to modify it (its the result of previous inter-ops)
a[0]=a[0]+b
return a
end =#
#= function addT(a::Taylor0, b::Taylor0) where {T<:Number} #case where no cache is given, ok to squash a
@__dot__ a.coeffs = (+)(a.coeffs, b.coeffs)
return a
end =#
function addT(a::Taylor0, b::Taylor0,cache::Taylor0)
@__dot__ cache.coeffs = (+)(a.coeffs, b.coeffs)
return cache
end
function addT(a::Taylor0, b::T,cache::Taylor0) where {T<:Number}
cache.coeffs.=a.coeffs
cache[0]=cache[0]+b
return cache
end
addT(b::T,a::Taylor0,cache::Taylor0) where {T<:Number}=addT(a, b,cache)
function addT( a::T,b::T,cache::Taylor0) where {T<:Number}#require emptying the cache
#cache.coeffs.=0.0 #
cache[0]=a+b
return cache
end
#add Three vars a b c
function addT(a::Taylor0, b::Taylor0,c::Taylor0,cache::Taylor0)
@__dot__ cache.coeffs = (+)(a.coeffs, b.coeffs,c.coeffs)
return cache
end
function addT(a::Taylor0, b::Taylor0,c::T,cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = (+)(a.coeffs, b.coeffs)
cache[0]=cache[0]+c
return cache
end
addT(a::Taylor0,c::T, b::Taylor0,cache::Taylor0) where {T<:Number}=addT(a, b,c,cache)
addT(c::T, a::Taylor0, b::Taylor0,cache::Taylor0) where {T<:Number}=addT(a, b,c,cache)
function addT(a::Taylor0, b::T,c::T,cache::Taylor0) where {T<:Number}
cache.coeffs.=a.coeffs
cache[0]=cache[0]+c+b
return cache
end
addT( b::T,a::Taylor0,c::T,cache::Taylor0) where {T<:Number}=addT(a, b,c,cache)
addT( b::T,c::T,a::Taylor0,cache::Taylor0) where {T<:Number}=addT(a, b,c,cache)
function addT( a::T,b::T,c::T,cache::Taylor0) where {T<:Number}#require clean cache
cache[0]=a+b+c
return cache
end
####################mul uses one cache when the original mul has only two elemnts a * b
function mulT(a::Taylor0, b::T,cache1::Taylor0) where {T<:Number}
fill!(cache1.coeffs, b)##I fixed broadcast dimension mismatch
@__dot__ cache1.coeffs = a.coeffs * cache1.coeffs ##I fixed broadcast dimension mismatch
return cache1
end
mulT(a::T,b::Taylor0, cache1::Taylor0) where {T<:Number} = mulT(b , a,cache1)
function mulT(a::Taylor0, b::Taylor0,cache1::Taylor0)
for k in eachindex(a)
@inbounds cache1[k] = a[0] * b[k]
@inbounds for i = 1:k
cache1[k] += a[i] * b[k-i]
end
end
return cache1
end
function mulT(a::T, b::T,cache1::Taylor0) where {T<:Number}
#cache1 needs to be clean: a clear here will alloc...this is the only "mul" that wants a clean cache
#sometimes the cache can be dirty at only first position: it will not throw an assert error!!!
# cache[1].coeffs.=0.0 #it causes two allocs for mul(cst,cst,a,b)
cache1[0]=a*b
return cache1
end
#########################mul uses two caches when the op has many terms###########################
function mulTT(a::Taylor0, b::T,cache1::Taylor0,cache2::Taylor0) where {T<:Number}#in middle ops: a is the returned cache1 so do not fudge a or cache1 before the end
fill!(cache2.coeffs, b)
@__dot__ cache1.coeffs = a.coeffs * cache2.coeffs ##fixed broadcast dimension mismatch
return cache1
end
mulTT(a::T,b::Taylor0, cache1::Taylor0,cache2::Taylor0) where {T<:Number} = mulTT(b , a,cache1,cache2)
function mulTT(a::Taylor0, b::Taylor0,cache1::Taylor0,cache2::Taylor0) #in middle ops: a is the returned cache1 so do not fudge a or cache1 before the end
for k in eachindex(a)
@inbounds cache2[k] = a[0] * b[k]
@inbounds for i = 1:k
cache2[k] += a[i] * b[k-i]
end
end
@__dot__ cache1.coeffs = cache2.coeffs
return cache1
end
function mulTT(a::T, b::T,cache1::Taylor0,cache2::Taylor0) where {T<:Number}
#cache1 needs to be clean: a clear here will alloc...this is the only "mul" that wants a clean cache
#sometimes the cache can be dirty at only first position: it will not throw an assert error!!!
# cache[1].coeffs.=0.0 #it causes two allocs for mul(cst,cst,a,b)
cache1[0]=a*b
return cache1
end
#########################################muladdT and subadd not test : added T to muladd cuz there did not want to import muladd to extend...maybe later
#= function muladdT(a::Taylor0, b::Taylor0, c::Taylor0,cache1::Taylor0) where {T<:Number}
for k in eachindex(a)
cache1[k] = a[0] * b[k] + c[k]
@inbounds for i = 1:k
cache1[k] += a[i] * b[k-i]
end
end
@__dot__ cache1.coeffs = cache2.coeffs
return cache1
end =#
function muladdT(a::P,b::Q,c::R,cache1::Taylor0) where {P,Q,R <:Union{Taylor0,Number}}
addT(mulT(a, b,cache1),c,cache1) # improvement of added performance not tested: there is one extra step of
#puting cache in itself
end
function mulsub(a::P,b::Q,c::R,cache1::Taylor0) where {P,Q,R <:Union{Taylor0,Number}}
subT(mulT(a, b,cache1),c,cache1)
end
function divT(a::T, b::T,cache1::Taylor0) where {T<:Number}
cache1[0]=a/b
return cache1
end
function divT(a::Taylor0, b::T,cache1::Taylor0) where {T<:Number}
fill!(cache1.coeffs, b)
#println("division")
#= @inbounds aux = a.coeffs[1] / b
v = Array{typeof(aux)}(undef, length(a.coeffs)) =#
@__dot__ cache1.coeffs = a.coeffs / cache1.coeffs
return cache1
end
function divT(a::T, b::Taylor0,cache1::Taylor0) where {T<:Number}
powerT(b, -1.0,cache1)
@__dot__ cache1.coeffs=cache1.coeffs*a ### broadcast dimension mismatch------------------div can have 2 caches then...:(
return cache1
end
#divT(a::Taylor0, b::Taylor0{S}) where {T<:Number,S<:Number} = divT(promote(a,b)...)
function divT(a::Taylor0, b::Taylor0,cache1::Taylor0)
iszero(a) && !iszero(b) && return cache1 # this op has its own clean cache2
ordfact, cdivfact = divfactorization(a, b)
cache1[0] = cdivfact
for k=1:a.order-ordfact
imin = max(0, k+ordfact-b.order)
@inbounds cache1[k] = cache1[imin] * b[k+ordfact-imin]
@inbounds for i = imin+1:k-1
cache1[k] += cache1[i] * b[k+ordfact-i]
end
if k+ordfact ≤ b.order
@inbounds cache1[k] = (a[k+ordfact]-cache1[k]) / b[ordfact]
else
@inbounds cache1[k] = - cache1[k] / b[ordfact]
end
end
return cache1
end
function clearCache(cache::Vector{Taylor0},::Val{CS},::Val{3}) where {CS}
for i=1:CS
cache[i][0]=0.0
cache[i][1]=0.0
cache[i][2]=0.0
cache[i][3]=0.0 # no need to clean? higher value is empty
end
end
#= function clearCache(cache::Vector{Taylor0},::Val{2}) #where {CS}
#for i=1:CS
cache[1].coeffs.=0.0
cache[2].coeffs.=0.0
# end
end =#
function clearCache(cache::Vector{Taylor0},::Val{CS},::Val{2}) where {CS}
for i=1:CS
cache[i][0]=0.0
cache[i][1]=0.0
cache[i][2]=0.0
end
end
function clearCache(cache::Vector{Taylor0},::Val{CS},::Val{1}) where {CS}
for i=1:CS
cache[i][0]=0.0
cache[i][1]=0.0
end
end
#= function clearCache(cache::Vector{Taylor0}) #where {T<:Number}
for i=1:length(cache)
cache[i].coeffs.=0.0
end
end =# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 6548 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
## Auxiliary function ##
#= """
resize_coeffs1!{T<Number}(coeffs::Array{T,1}, order::Int)
If the length of `coeffs` is smaller than `order+1`, it resizes
`coeffs` appropriately filling it with zeros.
""" =#
#= function resize_coeffs1!(coeffs::Array{T,1}, order::Int) where {T<:Number}
lencoef = length(coeffs)
resize!(coeffs, order+1)
#println("resize-coeffs")
if order > lencoef-1
z = zero(coeffs[1])
@simd for ord in lencoef+1:order+1
@inbounds coeffs[ord] = z
end
end
return nothing
end =#
#= """
resize_coeffsHP!{T<Number}(coeffs::Array{T,1}, order::Int)
If the length of `coeffs` is smaller than the number of coefficients
correspondinf to `order` (given by `size_table[order+1]`), it resizes
`coeffs` appropriately filling it with zeros.
""" =#
#= function resize_coeffsHP!(coeffs::Array{T,1}, order::Int) where {T<:Number}
lencoef = length( coeffs )
@inbounds num_coeffs = size_table[order+1]
@assert order ≤ get_order() && lencoef ≤ num_coeffs
num_coeffs == lencoef && return nothing
resize!(coeffs, num_coeffs)
z = zero(coeffs[1])
@simd for ord in lencoef+1:num_coeffs
@inbounds coeffs[ord] = z
end
return nothing
end =#
## Minimum order of an HomogeneousPolynomial compatible with the vector's length
#= function orderH(coeffs::Array{T,1}) where {T<:Number}
ord = 0
ll = length(coeffs)
for i = 1:get_order()+1
@inbounds num_coeffs = size_table[i]
ll ≤ num_coeffs && break
ord += 1
end
return ord
end =#
## getcoeff ##
#= """
getcoeff(a, n)
Return the coefficient of order `n::Int` of a `a::Taylor0` polynomial.
""" =#
getcoeff(a::Taylor0, n::Int) = (@assert 0 ≤ n ≤ a.order; return a[n])
getindex(a::Taylor0, n::Int) = a.coeffs[n+1]
getindex(a::Taylor0, u::UnitRange{Int}) = view(a.coeffs, u .+ 1 )
getindex(a::Taylor0, c::Colon) = view(a.coeffs, c)
getindex(a::Taylor0, u::StepRange{Int,Int}) =
view(a.coeffs, u[:] .+ 1)
setindex!(a::Taylor0, x::T, n::Int) where {T<:Number} = a.coeffs[n+1] = x
setindex!(a::Taylor0, x::T, u::UnitRange{Int}) where {T<:Number} =
a.coeffs[u .+ 1] .= x
function setindex!(a::Taylor0, x::Array{T,1}, u::UnitRange{Int}) where {T<:Number}
@assert length(u) == length(x)
for ind in eachindex(x)
a.coeffs[u[ind]+1] = x[ind]
end
end
setindex!(a::Taylor0, x::T, c::Colon) where {T<:Number} = a.coeffs[c] .= x
setindex!(a::Taylor0, x::Array{T,1}, c::Colon) where {T<:Number} = a.coeffs[c] .= x
setindex!(a::Taylor0, x::T, u::StepRange{Int,Int}) where {T<:Number} =
a.coeffs[u[:] .+ 1] .= x
function setindex!(a::Taylor0, x::Array{T,1}, u::StepRange{Int,Int}) where {T<:Number}
@assert length(u) == length(x)
for ind in eachindex(x)
a.coeffs[u[ind]+1] = x[ind]
end
end
#= function setorder(a::Taylor0, n::Int) #setfield!: immutable struct of type Taylor0 cannot be changed
a.order=n
end =#
## eltype, length, get_order, etc ##
@inline iterate(a::Taylor0, state=0) = state > a.order ? nothing : (a.coeffs[state+1], state+1)
# Base.iterate(rS::Iterators.Reverse{Taylor0}, state=rS.itr.order) = state < 0 ? nothing : (a.coeffs[state], state-1)
@inline length(a::Taylor0) = length(a.coeffs)
@inline firstindex(a::Taylor0) = 0
@inline lastindex(a::Taylor0) = a.order
@inline eachindex(a::Taylor0) = firstindex(a):lastindex(a)
#@inline numtype(::Taylor0{S}) where {S<:Number} = S
@inline size(a::Taylor0) = size(a.coeffs)
@inline get_order(a::Taylor0) = a.order
@inline axes(a::Taylor0) = ()
numtype(a) = eltype(a)
#= @doc doc"""
numtype(a::AbstractSeries)
Returns the type of the elements of the coefficients of `a`.
""" numtype =#
# Dumb methods included to properly export normalize_taylor (if IntervalArithmetic is loaded)
#@inline normalize_taylor(a::AbstractSeries) = a
## fixorder ##
#= @inline function fixorder(a::Taylor0, b::Taylor0)
a.order == b.order && return a, b
minorder, maxorder = minmax(a.order, b.order)
if minorder ≤ 0
minorder = maxorder
end
return Taylor0(copy(a.coeffs), minorder), Taylor0(copy(b.coeffs), minorder)
end =#
# can i go to the higher order when fixing orders??
@inline function fixorder(a::Taylor0, b::Taylor0)
# a.order == b.order && return a, b
if a.order < b.order
resize_coeffs1!(a.coeffs,b.order)
return Taylor0(a.coeffs, b.order),b
elseif a.order > b.order
resize_coeffs1!(b.coeffs,a.order)
return a, Taylor0(b.coeffs, a.order)
end
end
# Finds the first non zero entry; extended to Taylor0
function Base.findfirst(a::Taylor0)
first = findfirst(x->!iszero(x), a.coeffs)
isa(first, Nothing) && return -1
return first-1
end
# Finds the last non-zero entry; extended to Taylor0
function Base.findlast(a::Taylor0)
last = findlast(x->!iszero(x), a.coeffs)
isa(last, Nothing) && return -1
return last-1
end
## copyto! ##
# Inspired from base/abstractarray.jl, line 665
function copyto!(dst::Taylor0, src::Taylor0)
length(dst) < length(src) && throw(ArgumentError(string("Destination has fewer elements than required; no copy performed")))
destiter = eachindex(dst)
y = iterate(destiter)
for x in src
dst[y[1]] = x
y = iterate(destiter, y[2])
end
return dst
end
#=
"""
constant_term(a)
Return the constant value (zero order coefficient) for `Taylor0`
and `TaylorN`. The fallback behavior is to return `a` itself if
`a::Number`, or `a[1]` when `a::Vector`.
""" =#
constant_term(a::Taylor0) = a[0]
constant_term(a::Vector{T}) where {T<:Number} = constant_term.(a)
constant_term(a::Number) = a
#= """
linear_polynomial(a)
Returns the linear part of `a` as a polynomial (`Taylor0` or `TaylorN`),
*without* the constant term. The fallback behavior is to return `a` itself.
""" =#
#= linear_polynomial(a::Taylor0) = Taylor0([zero(a[1]), a[1]], a.order)
linear_polynomial(a::Vector{T}) where {T<:Number} = linear_polynomial.(a)
linear_polynomial(a::Number) = a
#= """
nonlinear_polynomial(a)
Returns the nonlinear part of `a`. The fallback behavior is to return `zero(a)`.
""" =#
nonlinear_polynomial(a::AbstractSeries) = a - constant_term(a) - linear_polynomial(a)
nonlinear_polynomial(a::Vector{T}) where {T<:Number} = nonlinear_polynomial.(a)
nonlinear_polynomial(a::Number) = zero(a) =#
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 3307 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
#= ## Differentiating ##
"""
differentiate(a)
Return the `Taylor0` polynomial of the differential of `a::Taylor0`.
The order of the result is `a.order-1`.
The function `derivative` is an exact synonym of `differentiate`.
""" =#
function differentiate(a::Taylor0)
res = Taylor0(zero(a[0]), a.order(a)-1)
for ord in eachindex(res)
differentiate!(res, a, ord)
end
return res
end
#= """
derivative
An exact synonym of [`differentiate`](@ref).
""" =#
const derivative = differentiate
#= """
differentiate!(res, a) --> nothing
In-place version of `differentiate`. Compute the `Taylor0` polynomial of the
differential of `a::Taylor0` and return it as `res` (order of `res` remains
unchanged).
""" =#
#= function differentiate!(p::Taylor0, a::Taylor0)
for k in eachindex(a)
#differentiate!(res, a, ord)
@inbounds p[k] = (k+1)*a[k+1]
end
nothing
end =#
function differentiate!(p::Taylor0, a::Taylor0, k::Int)
if k < a.order
@inbounds p[k] = (k+1)*a[k+1]
end
return nothing
end
function differentiate!(::Val{O},cache::Taylor0, a::Taylor0)where {O}
for k=0:O-1
# differentiate!(res, a, ord)
# if k < a.order
@inbounds cache[k] = (k+1)*a[k+1]
#end
end
cache[O]=0.0 #cache Letter O not zero
nothing
end
function differentiate(a::Taylor0, n::Int)
if n > a.order
return Taylor0(T, 0)
elseif n==0
return a
else
res = differentiate(a)
for i = 2:n
differentiate!(Val(a.order),res, res)
end
return Taylor0(view(res.coeffs, 1:a.order-n+1))
end
end
function ndifferentiate!(cache::Taylor0,a::Taylor0, n::Int)
if n > a.order
cache.coeffs.=0.0
elseif n==0
cache.coeffs.=a.coeffs
else
differentiate!(Val(a.order),cache,a)
for i = 2:n
differentiate!(Val(a.order),cache, cache)
end
#return Taylor0(view(res.coeffs, 1:a.order-n+1))
end
end
#= """
differentiate(n, a)
Return the value of the `n`-th differentiate of the polynomial `a`.
""" =#
function differentiate(n::Int, a::Taylor0)
@assert a.order ≥ n ≥ 0
factorial( widen(n) ) * a[n]
end
## Integrating ##
#= """
integrate(a, [x])
Return the integral of `a::Taylor0`. The constant of integration
(0-th order coefficient) is set to `x`, which is zero if ommitted.
""" =#
function integrate(a::Taylor0, x::S) where {S<:Number}
order = get_order(a)
aa = a[0]/1 + zero(x)
R = typeof(aa)
coeffs = Array{typeof(aa)}(undef, order+1)
fill!(coeffs, zero(aa))
@inbounds for i = 1:order
coeffs[i+1] = a[i-1] / i
end
@inbounds coeffs[1] = convert(R, x)
return Taylor0(coeffs, a.order)
end
integrate(a::Taylor0) = integrate(a, zero(a[0]))
function integrate!(p::Taylor0, a::Taylor0, x::S) where {S<:Number}
p.coeffs[1]=x
@inbounds for i = 1:a.order
p[i] = a[i-1] / i
end
return nothing
end
function integrate!( a::Taylor0, x::S) where {S<:Number}
@inbounds for i in a.order-1:-1:0
a[i+1] = a[i] / (i+1)
end
a.coeffs[1]=x
return nothing
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 2533 | # Float64his file is part of the Taylor0Series.jl Julia package, MIFloat64 license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIFloat64 Expat license
#
#=
"""
AbstractSeries{Float64<:Number} <: Number
Parameterized abstract type for [`Taylor0`](@ref),
[`HomogeneousPolynomial`](@ref) and [`Float64aylorN`](@ref).
""" =#
###################abstract type AbstractSeries{Float64<:Number} <: Number end
## Constructors ##
######################### Taylor0
#= """
Taylor0{Float64<:Number} <: AbstractSeries{Float64}
DataFloat64ype for polynomial expansions in one independent variable.
**Fields:**
- `coeffs :: Array{Float64,1}` Expansion coefficients; the ``i``-th
component is the coefficient of degree ``i-1`` of the expansion.
- `order :: Int` Maximum order (degree) of the polynomial.
Note that `Taylor0` variables are callable. For more information, see
[`evaluate`](@ref).
""" =#
struct Taylor0 #<: AbstractSeries{Float64}
coeffs :: Array{Float64,1}
order :: Int
## Inner constructor ##
#= function Taylor0(coeffs::Array{Float64,1}, order::Int)
#resize_coeffs1!(coeffs, order)
return new(coeffs, order)
end =#
end
## Outer constructors ##
Taylor0(x::Taylor0) = x
#Taylor0(coeffs::Array{Float64,1}, order::Int) = Taylor0(coeffs, order)
Taylor0(coeffs::Array{Float64,1}) = Taylor0(coeffs, length(coeffs)-1)
function Taylor0(x::Float64, order::Int)
v = fill(0.0, order+1)
v[1] = x
return Taylor0(v, order)
end
# Methods using 1-d views to create Taylor0's
#= Taylor0(a::SubArray{Float64,1}, order::Int) = Taylor0(a.parent[a.indices...], order)
Taylor0(a::SubArray{Float64,1}) = Taylor0(a.parent[a.indices...]) =#
# Shortcut to define Taylor0 independent variables
#= """
Taylor0([Float64::Float64ype=Float64], order::Int)
Shortcut to define the independent variable of a `Taylor0` polynomial of
given `order`. Float64he default type for `Float64` is `Float64`.
```julia
julia> Taylor0(16)
1.0 t + 𝒪(t¹⁷)
julia> Taylor0(Rational{Int}, 4)
1//1 t + 𝒪(t⁵)
```
""" =#
#= Taylor0(::Type{Float64}, order::Int) = Taylor0( [0.0, 1.0], order)
Taylor0(order::Int) = Taylor0(Float64, order) =#
# A `Number` which is not an `AbstractSeries`
#const NumberNotSeries = Union{Real,Complex}
# A `Number` which is not `Float64aylorN` nor a `HomogeneousPolynomial`
#const NumberNotSeriesN = Union{Real,Complex,Taylor0}
## Additional Taylor0 outer constructor ##
#Taylor0(x::S) where {Float64<:Number,S<:NumberNotSeries} = Taylor0([convert(Float64,x)], 0)
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 2276 | # This file is part of the Taylor0Series.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
## Conversion
convert(::Type{Taylor0}, a::Taylor0) = Taylor0(convert(Array{Float64,1}, a.coeffs), a.order)
convert(::Type{Taylor0}, a::Taylor0) = a
#convert(::Type{Taylor0{Rational{T}}}, a::Taylor0{S}) where {T<:Integer,S<:AbstractFloat} = Taylor0(rationalize.(a[:]), a.order)
convert(::Type{Taylor0}, b::Array{Float64,1}) =
Taylor0(b, length(b)-1)
convert(::Type{Taylor0}, b::Array{S,1}) where {S<:Number} =
Taylor0(convert(Array{Float64,1},b), length(b)-1)
convert(::Type{Taylor0}, b::S) where {T<:Number,S<:Number} =
Taylor0([convert(T,b)], 0)
convert(::Type{Taylor0}, b::T) = Taylor0([b], 0)
convert(::Type{Taylor0}, a::T) = Taylor0(a, 0)
# Promotion
#= promote_rule(::Type{Taylor0}, ::Type{Taylor0}) = Taylor0
promote_rule(::Type{Taylor0}, ::Type{Taylor0{S}}) where {T<:Number,S<:Number} =
Taylor0{promote_type(T,S)} =#
promote_rule(::Type{Taylor0}, ::Type{Array{Float64,1}}) = Taylor0
#= promote_rule(::Type{Taylor0}, ::Type{Array{S,1}}) where {T<:Number,S<:Number} =
Taylor0{promote_type(T,S)} =#
#promote_rule(::Type{Taylor0}, ::Type{T}) where {T<:Number} = Taylor0
#= promote_rule(::Type{Taylor0}, ::Type{S}) where {T<:Number,S<:Number} =
Taylor0{promote_type(T,S)} =#
#= promote_rule(::Type{Taylor0{Taylor0}}, ::Type{Taylor0}) where {T<:Number} =
Taylor0{Taylor0} =#
# Order may matter
#= promote_rule(::Type{S}, ::Type{T}) where {S<:NumberNotSeries,T<:AbstractSeries} =
promote_rule(T,S)
# disambiguation with Base
promote_rule(::Type{Bool}, ::Type{T}) where {T<:AbstractSeries} = promote_rule(T, Bool)
promote_rule(::Type{S}, ::Type{T}) where
{S<:AbstractIrrational,T<:AbstractSeries} = promote_rule(T,S)
=#
# Nested Taylor0's
#= function promote(a::Taylor0{Taylor0}, b::Taylor0) where {T<:NumberNotSeriesN}
order_a = get_order(a)
order_b = get_order(b)
zb = zero(b)
new_bcoeffs = similar(a.coeffs)
new_bcoeffs[1] = b
@inbounds for ind in 2:order_a+1
new_bcoeffs[ind] = zb
end
return a, Taylor0(b, order_a)
end
promote(b::Taylor0, a::Taylor0{Taylor0}) where {T<:NumberNotSeriesN} =
reverse(promote(a, b))
=# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 3595 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
## Evaluating ##
#= """
evaluate(a, [dx])
Evaluate a `Taylor0` polynomial using Horner's rule (hand coded). If `dx` is
ommitted, its value is considered as zero. Note that the syntax `a(dx)` is
equivalent to `evaluate(a,dx)`, and `a()` is equivalent to `evaluate(a)`.
""" =#
function evaluate(a::Taylor0, dx::T) where {T<:Number}
@inbounds suma = a[end]
@inbounds for k in a.order-1:-1:0
suma = suma*dx + a[k]
end
suma
end
#= function evaluate(a::Taylor0, dx::S) where {S<:Number}
suma = a[end]*one(dx)
@inbounds for k in a.order-1:-1:0
suma = suma*dx + a[k]
end
suma
end =#
evaluate(a::Taylor0) = a[0]
#= """
evaluate(x, δt)
Evaluates each element of `x::AbstractArray{Taylor0}`,
representing the dependent variables of an ODE, at *time* δt. Note that the
syntax `x(δt)` is equivalent to `evaluate(x, δt)`, and `x()`
is equivalent to `evaluate(x)`.
""" =#
#= evaluate(x::AbstractArray{Taylor0}, δt::S) where
{T<:Number,S<:Number} = evaluate.(x, δt)
evaluate(a::AbstractArray{Taylor0}) where {T<:Number} = evaluate.(a, zero(T)) =#
#= """
evaluate!(x, δt, x0)
Evaluates each element of `x::AbstractArray{Taylor0}`,
representing the Taylor expansion for the dependent variables
of an ODE at *time* `δt`. It updates the vector `x0` with the
computed values.
""" =#
#= function evaluate!(x::AbstractArray{Taylor0}, δt::S,
x0::AbstractArray{T}) where {T<:Number,S<:Number}
@inbounds for i in eachindex(x, x0)
x0[i] = evaluate( x[i], δt )
end
nothing
end =#
#= """
evaluate(a, x)
Substitute `x::Taylor0` as independent variable in a `a::Taylor0` polynomial.
Note that the syntax `a(x)` is equivalent to `evaluate(a, x)`.
""" =#
#= evaluate(a::Taylor0, x::Taylor0{S}) where {T<:Number,S<:Number} =
evaluate(promote(a,x)...) =#
function evaluate(a::Taylor0, x::Taylor0)
if a.order != x.order
a, x = fixorder(a, x)#allocates...delete later
end
@inbounds suma = a[end]*one(x)
@inbounds for k = a.order-1:-1:0
suma = suma*x + a[k]
end
suma
end
function evaluateX(a::Taylor0, x::Taylor0) #not tested
if a.order != x.order
a, x = fixorder(a, x)
end
@inbounds suma = a[end]*one(x)
@inbounds for k = a.order-1:-1:0
suma = suma*x + a[k]
end
#println("suma",suma)
@inbounds for k = 0:a.order-1
a[k]=suma[k]
end
return nothing
end
#= function evaluate(a::Taylor0{Taylor0}, x::Taylor0) where {T<:Number}
@inbounds suma = a[end]*one(x)
@inbounds for k = a.order-1:-1:0
suma = suma*x + a[k]
end
suma
end
function evaluate(a::Taylor0, x::Taylor0{Taylor0}) where {T<:Number}
@inbounds suma = a[end]*one(x)
@inbounds for k = a.order-1:-1:0
suma = suma*x + a[k]
end
suma
end =#
evaluate(p::Taylor0, x::Array{S}) where {S<:Number} =
evaluate.([p], x)
#function-like behavior for Taylor0
(p::Taylor0)(x) = evaluate(p, x)
(p::Taylor0)() = evaluate(p)
#function-like behavior for Vector{Taylor0}
#= if VERSION >= v"1.3"
(p::AbstractArray{Taylor0})(x) where {T<:Number} = evaluate.(p, x)
(p::AbstractArray{Taylor0})() where {T<:Number} = evaluate.(p)
else
(p::Array{Taylor0})(x) where {T<:Number} = evaluate.(p, x)
(p::SubArray{Taylor0})(x) where {T<:Number} = evaluate.(p, x)
(p::Array{Taylor0})() where {T<:Number} = evaluate.(p)
(p::SubArray{Taylor0})() where {T<:Number} = evaluate.(p)
end =#
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 19784 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
# Functions
function exp(a::Taylor0)
order = a.order
aux = exp(constant_term(a))
# @show aux
aa = one(aux) * a
# @show aa
# @show aa===a
# @show one(aux)
c = Taylor0( aux, order )
# @show c
for k in eachindex(a)
exp!(c, aa, k)
end
return c
end
function log(a::Taylor0)
iszero(constant_term(a)) && throw(DomainError(a,
"""The 0-th order coefficient must be non-zero in order to expand `log` around 0."""))
order = a.order
aux = log(constant_term(a))
aa = one(aux) * a
c = Taylor0( aux, order )
for k in eachindex(a)
log!(c, aa, k)
end
return c
end
sin(a::Taylor0) = sincos(a)[1]
cos(a::Taylor0) = sincos(a)[2]
function sincos(a::Taylor0)
order = a.order
aux = sin(constant_term(a))
aa = one(aux) * a
s = Taylor0( aux, order )
c = Taylor0( cos(constant_term(a)), order )
for k in eachindex(a)
sincos!(s, c, aa, k)
end
return s, c
end
function tan(a::Taylor0)
order = a.order
aux = tan(constant_term(a))
aa = one(aux) * a
c = Taylor0(aux, order)
c2 = Taylor0(aux^2, order)
for k in eachindex(a)
tan!(c, aa, c2, k)
end
return c
end
function asin(a::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of asin(x) diverges at x = ±1."""))
order = a.order
aux = asin(a0)
aa = one(aux) * a
c = Taylor0( aux, order )
r = Taylor0( sqrt(1 - a0^2), order )
for k in eachindex(a)
asin!(c, aa, r, k)
end
return c
end
function acos(a::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of asin(x) diverges at x = ±1."""))
order = a.order
aux = acos(a0)
aa = one(aux) * a
c = Taylor0( aux, order )
r = Taylor0( sqrt(1 - a0^2), order )
for k in eachindex(a)
acos!(c, aa, r, k)
end
return c
end
function atan(a::Taylor0)
order = a.order
a0 = constant_term(a)
aux = atan(a0)
aa = one(aux) * a
c = Taylor0( aux, order)
r = Taylor0(one(aux) + a0^2, order)
iszero(constant_term(r)) && throw(DomainError(a,
"""Series expansion of atan(x) diverges at x = ±im."""))
for k in eachindex(a)
atan!(c, aa, r, k)
end
return c
end
function atan(a::Taylor0, b::Taylor0)
c = atan(a/b)
c[0] = atan(constant_term(a), constant_term(b))
return c
end
sinh(a::Taylor0) = sinhcosh(a)[1]
cosh(a::Taylor0) = sinhcosh(a)[2]
function sinhcosh(a::Taylor0)
order = a.order
aux = sinh(constant_term(a))
aa = one(aux) * a
s = Taylor0( aux, order)
c = Taylor0( cosh(constant_term(a)), order)
for k in eachindex(a)
sinhcosh!(s, c, aa, k)
end
return s, c
end
function tanh(a::Taylor0)
order = a.order
aux = tanh( constant_term(a) )
aa = one(aux) * a
c = Taylor0( aux, order)
c2 = Taylor0( aux^2, order)
for k in eachindex(a)
tanh!(c, aa, c2, k)
end
return c
end
function asinh(a::Taylor0)
order = a.order
a0 = constant_term(a)
aux = asinh(a0)
aa = one(aux) * a
c = Taylor0( aux, order )
r = Taylor0( sqrt(a0^2 + 1), order )
iszero(constant_term(r)) && throw(DomainError(a,
"""Series expansion of asinh(x) diverges at x = ±im."""))
for k in eachindex(a)
asinh!(c, aa, r, k)
end
return c
end
function acosh(a::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of acosh(x) diverges at x = ±1."""))
order = a.order
aux = acosh(a0)
aa = one(aux) * a
c = Taylor0( aux, order )
r = Taylor0( sqrt(a0^2 - 1), order )
for k in eachindex(a)
acosh!(c, aa, r, k)
end
return c
end
function atanh(a::Taylor0)
order = a.order
a0 = constant_term(a)
aux = atanh(a0)
aa = one(aux) * a
c = Taylor0( aux, order)
r = Taylor0(one(aux) - a0^2, order)
iszero(constant_term(r)) && throw(DomainError(a,
"""Series expansion of atanh(x) diverges at x = ±1."""))
for k in eachindex(a)
atanh!(c, aa, r, k)
end
return c
end
# Recursive functions (homogeneous coefficients)
@inline function identity!(c::Taylor0, a::Taylor0, k::Int)
@inbounds c[k] = identity(a[k])
return nothing
end
@inline function zero!(c::Taylor0, a::Taylor0, k::Int)
@inbounds c[k] = zero(a[k])
return nothing
end
@inline function one!(c::Taylor0, a::Taylor0, k::Int)
if k == 0
@inbounds c[0] = one(a[0])
else
@inbounds c[k] = zero(a[k])
end
return nothing
end
@inline function abs!(c::Taylor0, a::Taylor0, k::Int)
z = zero(constant_term(a))
if constant_term(constant_term(a)) > constant_term(z)
return add!(c, a, k)
elseif constant_term(constant_term(a)) < constant_term(z)
return subst!(c, a, k)
else
throw(DomainError(a,
"""The 0th order coefficient must be non-zero
(abs(x) is not differentiable at x=0)."""))
end
return nothing
end
@inline abs2!(c::Taylor0, a::Taylor0, k::Int) = sqr!(c, a, k)
@inline function exp!(c::Taylor0, a::Taylor0, k::Int)
if k == 0
@inbounds c[0] = exp(constant_term(a)) #this was already computed before!!no need to do anything if k==0
return nothing
end
@inbounds c[k] = k * a[k] * c[0]
@inbounds for i = 1:k-1
c[k] += (k-i) * a[k-i] * c[i]
end
@inbounds c[k] = c[k] / k
return nothing
end
@inline function log!(c::Taylor0, a::Taylor0, k::Int)
if k == 0
@inbounds c[0] = log(constant_term(a))
return nothing
elseif k == 1
@inbounds c[1] = a[1] / constant_term(a)
return nothing
end
@inbounds c[k] = (k-1) * a[1] * c[k-1]
@inbounds for i = 2:k-1
c[k] += (k-i) * a[i] * c[k-i]
end
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(a)
return nothing
end
@inline function sincos!(s::Taylor0, c::Taylor0, a::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds s[0], c[0] = sincos( a0 )
return nothing
end
x = a[1]
@inbounds s[k] = x * c[k-1]
@inbounds c[k] = -x * s[k-1]
@inbounds for i = 2:k
x = i * a[i]
s[k] += x * c[k-i]
c[k] -= x * s[k-i]
end
@inbounds s[k] = s[k] / k
@inbounds c[k] = c[k] / k
return nothing
end
@inline function tan!(c::Taylor0, a::Taylor0, c2::Taylor0, k::Int)
if k == 0
@inbounds aux = tan( constant_term(a) )
@inbounds c[0] = aux
@inbounds c2[0] = aux^2
return nothing
end
@inbounds c[k] = k * a[k] * c2[0]
@inbounds for i = 1:k-1
c[k] += (k-i) * a[k-i] * c2[i]
end
@inbounds c[k] = a[k] + c[k]/k
sqr!(c2, c, k)
return nothing
end
@inline function asin!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = asin( a0 )
@inbounds r[0] = sqrt( 1 - a0^2 )
return nothing
end
@inbounds c[k] = (k-1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k-i) * r[i] * c[k-i]
end
sqrt!(r, 1-a^2, k)
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(r)
return nothing
end
@inline function acos!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = acos( a0 )
@inbounds r[0] = sqrt( 1 - a0^2 )
return nothing
end
@inbounds c[k] = (k-1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k-i) * r[i] * c[k-i]
end
sqrt!(r, 1-a^2, k)
@inbounds c[k] = -(a[k] + c[k]/k) / constant_term(r)
return nothing
end
@inline function atan!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = atan( a0 )
@inbounds r[0] = 1 + a0^2
return nothing
end
@inbounds c[k] = (k-1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k-i) * r[i] * c[k-i]
end
@inbounds sqr!(r, a, k)
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(r)
return nothing
end
@inline function sinhcosh!(s::Taylor0, c::Taylor0, a::Taylor0, k::Int)
if k == 0
@inbounds s[0] = sinh( constant_term(a) )
@inbounds c[0] = cosh( constant_term(a) )
return nothing
end
x = a[1]
@inbounds s[k] = x * c[k-1]
@inbounds c[k] = x * s[k-1]
@inbounds for i = 2:k
x = i * a[i]
s[k] += x * c[k-i]
c[k] += x * s[k-i]
end
s[k] = s[k] / k
c[k] = c[k] / k
return nothing
end
@inline function tanh!(c::Taylor0, a::Taylor0, c2::Taylor0, k::Int)
if k == 0
@inbounds aux = tanh( constant_term(a) )
@inbounds c[0] = aux
@inbounds c2[0] = aux^2
return nothing
end
@inbounds c[k] = k * a[k] * c2[0]
@inbounds for i = 1:k-1
c[k] += (k-i) * a[k-i] * c2[i]
end
@inbounds c[k] = a[k] - c[k]/k
sqr!(c2, c, k)
return nothing
end
@inline function asinh!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = asinh( a0 )
@inbounds r[0] = sqrt( a0^2 + 1 )
return nothing
end
@inbounds c[k] = (k-1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k-i) * r[i] * c[k-i]
end
sqrt!(r, a^2+1, k) # a^...allocates will need a third cache
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(r)
return nothing
end
@inline function acosh!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = acosh( a0 )
@inbounds r[0] = sqrt( a0^2 - 1 )
return nothing
end
@inbounds c[k] = (k-1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k-i) * r[i] * c[k-i]
end
sqrt!(r, a^2-1, k)
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(r)
return nothing
end
@inline function atanh!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = atanh( a0 )
@inbounds r[0] = 1 - a0^2
return nothing
end
@inbounds c[k] = (k-1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k-i) * r[i] * c[k-i]
end
@inbounds sqr!(r, a, k)
@inbounds c[k] = (a[k] + c[k]/k) / constant_term(r)
return nothing
end
#= @doc doc"""
inverse(f)
Return the Taylor expansion of ``f^{-1}(t)``, of order `N = f.order`,
for `f::Taylor0` polynomial if the first coefficient of `f` is zero.
Otherwise, a `DomainError` is thrown.
The algorithm implements Lagrange inversion at ``t=0`` if ``f(0)=0``:
```math
\begin{equation*}
f^{-1}(t) = \sum_{n=1}^{N} \frac{t^n}{n!} \left.
\frac{{\rm d}^{n-1}}{{\rm d} z^{n-1}}\left(\frac{z}{f(z)}\right)^n
\right\vert_{z=0}.
\end{equation*}
```
""" inverse =#
function inverse(f::Taylor0)
if f[0] != 0.0
throw(DomainError(f,
"""
Evaluation of Taylor0 series at 0 is non-zero. For high accuracy, revert
a Taylor0 series with first coefficient 0 and re-expand about f(0).
"""))
end
z = Taylor0(0.0,f.order)
zdivf = z/f
zdivfpown = zdivf
S = TS.numtype(zdivf)
coeffs = zeros(S,f.order+1)
@inbounds for n in 1:f.order
coeffs[n+1] = zdivfpown[n-1]/n
zdivfpown *= zdivf
end
Taylor0(coeffs, f.order)
end
#=
# Documentation for the recursion relations
@doc doc"""
exp!(c, a, k) --> nothing
Update the `k-th` expansion coefficient `c[k+1]` of `c = exp(a)`
for both `c` and `a` either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
\begin{equation*}
c_k = \frac{1}{k} \sum_{j=0}^{k-1} (k-j) a_{k-j} c_j.
\end{equation*}
```
""" exp!
@doc doc"""
log!(c, a, k) --> nothing
Update the `k-th` expansion coefficient `c[k+1]` of `c = log(a)`
for both `c` and `a` either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
\begin{equation*}
c_k = \frac{1}{a_0} \big(a_k - \frac{1}{k} \sum_{j=0}^{k-1} j a_{k-j} c_j \big).
\end{equation*}
```
""" log!
@doc doc"""
sincos!(s, c, a, k) --> nothing
Update the `k-th` expansion coefficients `s[k+1]` and `c[k+1]`
of `s = sin(a)` and `c = cos(a)` simultaneously, for `s`, `c` and `a`
either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
\begin{eqnarray*}
s_k &=& \frac{1}{k}\sum_{j=0}^{k-1} (k-j) a_{k-j} c_j ,\\
c_k &=& -\frac{1}{k}\sum_{j=0}^{k-1} (k-j) a_{k-j} s_j.
\end{eqnarray*}
```
""" sincos!
@doc doc"""
tan!(c, a, p, k::Int) --> nothing
Update the `k-th` expansion coefficients `c[k+1]` of `c = tan(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `p = c^2` and
is passed as an argument for efficiency.
The coefficients are given by
```math
\begin{equation*}
c_k = a_k + \frac{1}{k} \sum_{j=0}^{k-1} (k-j) a_{k-j} p_j.
\end{equation*}
```
""" tan!
@doc doc"""
asin!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = asin(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = sqrt(1-c^2)` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = \frac{1}{ \sqrt{r_0} }
\big( a_k - \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j \big).
\end{equation*}
```
""" asin!
@doc doc"""
acos!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = acos(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = sqrt(1-c^2)` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = - \frac{1}{ r_0 }
\big( a_k - \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j \big).
\end{equation*}
```
""" acos!
@doc doc"""
atan!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = atan(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = 1+a^2` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = \frac{1}{r_0}\big(a_k - \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j\big).
\end{equation*}
```
""" atan!
@doc doc"""
sinhcosh!(s, c, a, k)
Update the `k-th` expansion coefficients `s[k+1]` and `c[k+1]`
of `s = sinh(a)` and `c = cosh(a)` simultaneously, for `s`, `c` and `a`
either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
\begin{eqnarray*}
s_k &=& \frac{1}{k} \sum_{j=0}^{k-1} (k-j) a_{k-j} c_j, \\
c_k &=& \frac{1}{k} \sum_{j=0}^{k-1} (k-j) a_{k-j} s_j.
\end{eqnarray*}
```
""" sinhcosh!
@doc doc"""
tanh!(c, a, p, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = tanh(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `p = a^2` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = a_k - \frac{1}{k} \sum_{j=0}^{k-1} (k-j) a_{k-j} p_j.
\end{equation*}
```
""" tanh!
@doc doc"""
asinh!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = asinh(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = sqrt(1-c^2)` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = \frac{1}{ \sqrt{r_0} }
\big( a_k - \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j \big).
\end{equation*}
```
""" asinh!
@doc doc"""
acosh!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = acosh(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = sqrt(c^2-1)` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = \frac{1}{ r_0 }
\big( a_k - \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j \big).
\end{equation*}
```
""" acosh!
@doc doc"""
atanh!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = atanh(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = 1-a^2` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = \frac{1}{r_0}\big(a_k + \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j\big).
\end{equation*}
```
""" atanh!
=# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 22951 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
# Functions
function exp(a::Taylor0,c::Taylor0)
order = a.order
#aux = exp(constant_term(a))
for k in eachindex(a)
exp!(c, a, k)
end
return c
end
function exp(a::T,c::Taylor0)where {T<:Number}
c[0]=exp(a)
return c
end
function log(a::Taylor0,c::Taylor0)
iszero(constant_term(a)) && throw(DomainError(a,
"""The 0-th order coefficient must be non-zero in order to expand `log` around 0."""))
for k in eachindex(a)
log!(c, a, k)
end
return c
end
function log(a::T,c::Taylor0)where {T<:Number}
iszero(a) && throw(DomainError(a,
""" log(0) undefined."""))
c[0]=log(a)
return c
end
function sincos(a::Taylor0,s::Taylor0,c::Taylor0)
for k in eachindex(a)
sincos!(s, c, a, k)
end
return s, c
end
sin(a::Taylor0,s::Taylor0,c::Taylor0) = sincos(a,s,c)[1]
cos(a::Taylor0,c::Taylor0,s::Taylor0) = sincos(a,s,c)[2]
function sin(a::T,s::Taylor0,c::Taylor0)where {T<:Number}
s[0]=sin(a)
return s
end
function cos(a::T,s::Taylor0,c::Taylor0)where {T<:Number}
s[0]=cos(a)
return s
end
function tan(a::Taylor0,c::Taylor0,c2::Taylor0)
for k in eachindex(a)
tan!(c, a, c2, k)
end
return c
end
function tan(a::T,c::Taylor0,c2::Taylor0)where {T<:Number}
c[0]=tan(a)
return c
end
#####################################constant case not implemented yet
function asin(a::Taylor0,c::Taylor0,r::Taylor0,cache3::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of asin(x) diverges at x = ±1."""))
for k in eachindex(a)
asin!(c, a, r,cache3, k)
end
return c
end
function acos(a::Taylor0,c::Taylor0,r::Taylor0,cache3::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of asin(x) diverges at x = ±1."""))
for k in eachindex(a)
acos!(c, a, r,cache3, k)
end
return c
end
function atan(a::Taylor0,c::Taylor0,r::Taylor0)
#= a0 = constant_term(a)
rc = 1 + a0^2
iszero(rc) && throw(DomainError(a,
"""Series expansion of atan(x) diverges at x = ±im.""")) =#
for k in eachindex(a)
atan!(c, a, r, k)
end
return c
end
@inline function asin!(c::Taylor0, a::Taylor0, r::Taylor0,cache3::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = asin( a0 )
@inbounds r[0] = sqrt( 1 - a0^2 )
return nothing
end
@inbounds c[k] = (k-1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k-i) * r[i] * c[k-i]
end
cache3=square(a,cache3)
@__dot__ cache3.coeffs = (-)(cache3.coeffs)
cache3[0]=1+cache3[0] #1-square(a,cache3)=1-a^2
sqrt!(r,cache3 , k)
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(r)
return nothing
end
@inline function acos!(c::Taylor0, a::Taylor0, r::Taylor0,cache3::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = acos( a0 )
@inbounds r[0] = sqrt( 1 - a0^2 )
return nothing
end
@inbounds c[k] = (k-1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k-i) * r[i] * c[k-i]
end
#sqrt!(r, 1-a^2, k)
cache3=square(a,cache3)
@__dot__ cache3.coeffs = (-)(cache3.coeffs)
cache3[0]=1+cache3[0] #1-square(a,cache3)=1-a^2
sqrt!(r,cache3 , k)
@inbounds c[k] = -(a[k] + c[k]/k) / constant_term(r)
return nothing
end
#=
function atan(a::Taylor0, b::Taylor0)
c = atan(a/b)
c[0] = atan(constant_term(a), constant_term(b))
return c
end
sinh(a::Taylor0) = sinhcosh(a)[1]
cosh(a::Taylor0) = sinhcosh(a)[2]
function sinhcosh(a::Taylor0)
order = a.order
aux = sinh(constant_term(a))
aa = one(aux) * a
s = Taylor0( aux, order)
c = Taylor0( cosh(constant_term(a)), order)
for k in eachindex(a)
sinhcosh!(s, c, aa, k)
end
return s, c
end
function tanh(a::Taylor0)
order = a.order
aux = tanh( constant_term(a) )
aa = one(aux) * a
c = Taylor0( aux, order)
c2 = Taylor0( aux^2, order)
for k in eachindex(a)
tanh!(c, aa, c2, k)
end
return c
end
function asinh(a::Taylor0)
order = a.order
a0 = constant_term(a)
aux = asinh(a0)
aa = one(aux) * a
c = Taylor0( aux, order )
r = Taylor0( sqrt(a0^2 + 1), order )
iszero(constant_term(r)) && throw(DomainError(a,
"""Series expansion of asinh(x) diverges at x = ±im."""))
for k in eachindex(a)
asinh!(c, aa, r, k)
end
return c
end
function acosh(a::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of acosh(x) diverges at x = ±1."""))
order = a.order
aux = acosh(a0)
aa = one(aux) * a
c = Taylor0( aux, order )
r = Taylor0( sqrt(a0^2 - 1), order )
for k in eachindex(a)
acosh!(c, aa, r, k)
end
return c
end
function atanh(a::Taylor0)
order = a.order
a0 = constant_term(a)
aux = atanh(a0)
aa = one(aux) * a
c = Taylor0( aux, order)
r = Taylor0(one(aux) - a0^2, order)
iszero(constant_term(r)) && throw(DomainError(a,
"""Series expansion of atanh(x) diverges at x = ±1."""))
for k in eachindex(a)
atanh!(c, aa, r, k)
end
return c
end
# Recursive functions (homogeneous coefficients)
@inline function identity!(c::Taylor0, a::Taylor0, k::Int) where {T<:Number}
@inbounds c[k] = identity(a[k])
return nothing
end
@inline function zero!(c::Taylor0, a::Taylor0, k::Int) where {T<:Number}
@inbounds c[k] = zero(a[k])
return nothing
end
@inline function one!(c::Taylor0, a::Taylor0, k::Int) where {T<:Number}
if k == 0
@inbounds c[0] = one(a[0])
else
@inbounds c[k] = zero(a[k])
end
return nothing
end
@inline function abs!(c::Taylor0, a::Taylor0, k::Int) where {T<:Number}
z = zero(constant_term(a))
if constant_term(constant_term(a)) > constant_term(z)
return add!(c, a, k)
elseif constant_term(constant_term(a)) < constant_term(z)
return subst!(c, a, k)
else
throw(DomainError(a,
"""The 0th order coefficient must be non-zero
(abs(x) is not differentiable at x=0)."""))
end
return nothing
end
@inline abs2!(c::Taylor0, a::Taylor0, k::Int) where {T<:Number} = sqr!(c, a, k)
@inline function exp!(c::Taylor0, a::Taylor0, k::Int) where {T<:Number}
if k == 0
@inbounds c[0] = exp(constant_term(a)) #this was already computed before!!no need to do anything if k==0
return nothing
end
if Taylor0 == Taylor0
@inbounds c[k] = k * a[k] * c[0]
else
@inbounds mul!(c[k], k * a[k], c[0])
end
@inbounds for i = 1:k-1
if Taylor0 == Taylor0
c[k] += (k-i) * a[k-i] * c[i]
else
mul!(c[k], (k-i) * a[k-i], c[i])
end
end
@inbounds c[k] = c[k] / k
return nothing
end
@inline function log!(c::Taylor0, a::Taylor0, k::Int) where {T<:Number}
if k == 0
@inbounds c[0] = log(constant_term(a))
return nothing
elseif k == 1
@inbounds c[1] = a[1] / constant_term(a)
return nothing
end
if Taylor0 == Taylor0
@inbounds c[k] = (k-1) * a[1] * c[k-1]
else
@inbounds mul!(c[k], (k-1)*a[1], c[k-1])
end
@inbounds for i = 2:k-1
if Taylor0 == Taylor0
c[k] += (k-i) * a[i] * c[k-i]
else
mul!(c[k], (k-i)*a[i], c[k-i])
end
end
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(a)
return nothing
end
@inline function sincos!(s::Taylor0, c::Taylor0, a::Taylor0, k::Int) where {T<:Number}
if k == 0
a0 = constant_term(a)
@inbounds s[0], c[0] = sincos( a0 )
return nothing
end
x = a[1]
if Taylor0 == Taylor0
@inbounds s[k] = x * c[k-1]
@inbounds c[k] = -x * s[k-1]
else
mul!(s[k], x, c[k-1])
mul!(c[k], -x, s[k-1])
end
@inbounds for i = 2:k
x = i * a[i]
if Taylor0 == Taylor0
s[k] += x * c[k-i]
c[k] -= x * s[k-i]
else
mul!(s[k], x, c[k-i])
mul!(c[k], -x, s[k-i])
end
end
@inbounds s[k] = s[k] / k
@inbounds c[k] = c[k] / k
return nothing
end
@inline function tan!(c::Taylor0, a::Taylor0, c2::Taylor0, k::Int) where {T<:Number}
if k == 0
@inbounds aux = tan( constant_term(a) )
@inbounds c[0] = aux
@inbounds c2[0] = aux^2
return nothing
end
if Taylor0 == Taylor0
@inbounds c[k] = k * a[k] * c2[0]
else
@inbounds mul!(c[k], k * a[k], c2[0])
end
@inbounds for i = 1:k-1
if Taylor0 == Taylor0
c[k] += (k-i) * a[k-i] * c2[i]
else
mul!(c[k], (k-i) * a[k-i], c2[i])
end
end
@inbounds c[k] = a[k] + c[k]/k
sqr!(c2, c, k)
return nothing
end
@inline function asin!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int) where {T<:Number}
if k == 0
a0 = constant_term(a)
@inbounds c[0] = asin( a0 )
@inbounds r[0] = sqrt( 1 - a0^2 )
return nothing
end
if Taylor0 == Taylor0
@inbounds c[k] = (k-1) * r[1] * c[k-1]
else
@inbounds mul!(c[k], (k-1) * r[1], c[k-1])
end
@inbounds for i in 2:k-1
if Taylor0 == Taylor0
c[k] += (k-i) * r[i] * c[k-i]
else
mul!(c[k], (k-i) * r[i], c[k-i])
end
end
sqrt!(r, 1-a^2, k)
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(r)
return nothing
end
@inline function acos!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int) where {T<:Number}
if k == 0
a0 = constant_term(a)
@inbounds c[0] = acos( a0 )
@inbounds r[0] = sqrt( 1 - a0^2 )
return nothing
end
if Taylor0 == Taylor0
@inbounds c[k] = (k-1) * r[1] * c[k-1]
else
@inbounds mul!(c[k], (k-1) * r[1], c[k-1])
end
@inbounds for i in 2:k-1
if Taylor0 == Taylor0
c[k] += (k-i) * r[i] * c[k-i]
else
mul!(c[k], (k-i) * r[i], c[k-i])
end
end
sqrt!(r, 1-a^2, k)
@inbounds c[k] = -(a[k] + c[k]/k) / constant_term(r)
return nothing
end
@inline function atan!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int) where {T<:Number}
if k == 0
a0 = constant_term(a)
@inbounds c[0] = atan( a0 )
@inbounds r[0] = 1 + a0^2
return nothing
end
if Taylor0 == Taylor0
@inbounds c[k] = (k-1) * r[1] * c[k-1]
else
@inbounds mul!(c[k], (k-1) * r[1], c[k-1])
end
@inbounds for i in 2:k-1
if Taylor0 == Taylor0
c[k] += (k-i) * r[i] * c[k-i]
else
mul!(c[k], (k-i) * r[i], c[k-i])
end
end
@inbounds sqr!(r, a, k)
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(r)
return nothing
end
@inline function sinhcosh!(s::Taylor0, c::Taylor0, a::Taylor0, k::Int) where {T<:Number}
if k == 0
@inbounds s[0] = sinh( constant_term(a) )
@inbounds c[0] = cosh( constant_term(a) )
return nothing
end
x = a[1]
if Taylor0 == Taylor0
@inbounds s[k] = x * c[k-1]
@inbounds c[k] = x * s[k-1]
else
@inbounds mul!(s[k], x, c[k-1])
@inbounds mul!(c[k], x, s[k-1])
end
@inbounds for i = 2:k
x = i * a[i]
if Taylor0 == Taylor0
s[k] += x * c[k-i]
c[k] += x * s[k-i]
else
mul!(s[k], x, c[k-i])
mul!(c[k], x, s[k-i])
end
end
s[k] = s[k] / k
c[k] = c[k] / k
return nothing
end
@inline function tanh!(c::Taylor0, a::Taylor0, c2::Taylor0, k::Int) where {T<:Number}
if k == 0
@inbounds aux = tanh( constant_term(a) )
@inbounds c[0] = aux
@inbounds c2[0] = aux^2
return nothing
end
if Taylor0 == Taylor0
@inbounds c[k] = k * a[k] * c2[0]
else
@inbounds mul!(c[k], k * a[k], c2[0])
end
@inbounds for i = 1:k-1
if Taylor0 == Taylor0
c[k] += (k-i) * a[k-i] * c2[i]
else
mul!(c[k], (k-i) * a[k-i], c2[i])
end
end
@inbounds c[k] = a[k] - c[k]/k
sqr!(c2, c, k)
return nothing
end
@inline function asinh!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int) where {T<:Number}
if k == 0
a0 = constant_term(a)
@inbounds c[0] = asinh( a0 )
@inbounds r[0] = sqrt( a0^2 + 1 )
return nothing
end
if Taylor0 == Taylor0
@inbounds c[k] = (k-1) * r[1] * c[k-1]
else
@inbounds mul!(c[k], (k-1) * r[1], c[k-1])
end
@inbounds for i in 2:k-1
if Taylor0 == Taylor0
c[k] += (k-i) * r[i] * c[k-i]
else
mul!(c[k], (k-i) * r[i], c[k-i])
end
end
sqrt!(r, a^2+1, k)
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(r)
return nothing
end
@inline function acosh!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int) where {T<:Number}
if k == 0
a0 = constant_term(a)
@inbounds c[0] = acosh( a0 )
@inbounds r[0] = sqrt( a0^2 - 1 )
return nothing
end
if Taylor0 == Taylor0
@inbounds c[k] = (k-1) * r[1] * c[k-1]
else
@inbounds mul!(c[k], (k-1) * r[1], c[k-1])
end
@inbounds for i in 2:k-1
if Taylor0 == Taylor0
c[k] += (k-i) * r[i] * c[k-i]
else
mul!(c[k], (k-i) * r[i], c[k-i])
end
end
sqrt!(r, a^2-1, k)
@inbounds c[k] = (a[k] - c[k]/k) / constant_term(r)
return nothing
end
@inline function atanh!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int) where {T<:Number}
if k == 0
a0 = constant_term(a)
@inbounds c[0] = atanh( a0 )
@inbounds r[0] = 1 - a0^2
return nothing
end
if Taylor0 == Taylor0
@inbounds c[k] = (k-1) * r[1] * c[k-1]
else
@inbounds mul!(c[k], (k-1) * r[1], c[k-1])
end
@inbounds for i in 2:k-1
if Taylor0 == Taylor0
c[k] += (k-i) * r[i] * c[k-i]
else
mul!(c[k], (k-i) * r[i], c[k-i])
end
end
@inbounds sqr!(r, a, k)
@inbounds c[k] = (a[k] + c[k]/k) / constant_term(r)
return nothing
end
#= @doc doc"""
inverse(f)
Return the Taylor expansion of ``f^{-1}(t)``, of order `N = f.order`,
for `f::Taylor0` polynomial if the first coefficient of `f` is zero.
Otherwise, a `DomainError` is thrown.
The algorithm implements Lagrange inversion at ``t=0`` if ``f(0)=0``:
```math
\begin{equation*}
f^{-1}(t) = \sum_{n=1}^{N} \frac{t^n}{n!} \left.
\frac{{\rm d}^{n-1}}{{\rm d} z^{n-1}}\left(\frac{z}{f(z)}\right)^n
\right\vert_{z=0}.
\end{equation*}
```
""" inverse =#
function inverse(f::Taylor0) where {T<:Number}
if f[0] != zero(T)
throw(DomainError(f,
"""
Evaluation of Taylor0 series at 0 is non-zero. For high accuracy, revert
a Taylor0 series with first coefficient 0 and re-expand about f(0).
"""))
end
z = Taylor0(T,f.order)
zdivf = z/f
zdivfpown = zdivf
S = TS.numtype(zdivf)
coeffs = zeros(S,f.order+1)
@inbounds for n in 1:f.order
coeffs[n+1] = zdivfpown[n-1]/n
zdivfpown *= zdivf
end
Taylor0(coeffs, f.order)
end
#=
# Documentation for the recursion relations
@doc doc"""
exp!(c, a, k) --> nothing
Update the `k-th` expansion coefficient `c[k+1]` of `c = exp(a)`
for both `c` and `a` either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
\begin{equation*}
c_k = \frac{1}{k} \sum_{j=0}^{k-1} (k-j) a_{k-j} c_j.
\end{equation*}
```
""" exp!
@doc doc"""
log!(c, a, k) --> nothing
Update the `k-th` expansion coefficient `c[k+1]` of `c = log(a)`
for both `c` and `a` either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
\begin{equation*}
c_k = \frac{1}{a_0} \big(a_k - \frac{1}{k} \sum_{j=0}^{k-1} j a_{k-j} c_j \big).
\end{equation*}
```
""" log!
@doc doc"""
sincos!(s, c, a, k) --> nothing
Update the `k-th` expansion coefficients `s[k+1]` and `c[k+1]`
of `s = sin(a)` and `c = cos(a)` simultaneously, for `s`, `c` and `a`
either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
\begin{eqnarray*}
s_k &=& \frac{1}{k}\sum_{j=0}^{k-1} (k-j) a_{k-j} c_j ,\\
c_k &=& -\frac{1}{k}\sum_{j=0}^{k-1} (k-j) a_{k-j} s_j.
\end{eqnarray*}
```
""" sincos!
@doc doc"""
tan!(c, a, p, k::Int) --> nothing
Update the `k-th` expansion coefficients `c[k+1]` of `c = tan(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `p = c^2` and
is passed as an argument for efficiency.
The coefficients are given by
```math
\begin{equation*}
c_k = a_k + \frac{1}{k} \sum_{j=0}^{k-1} (k-j) a_{k-j} p_j.
\end{equation*}
```
""" tan!
@doc doc"""
asin!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = asin(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = sqrt(1-c^2)` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = \frac{1}{ \sqrt{r_0} }
\big( a_k - \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j \big).
\end{equation*}
```
""" asin!
@doc doc"""
acos!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = acos(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = sqrt(1-c^2)` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = - \frac{1}{ r_0 }
\big( a_k - \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j \big).
\end{equation*}
```
""" acos!
@doc doc"""
atan!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = atan(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = 1+a^2` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = \frac{1}{r_0}\big(a_k - \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j\big).
\end{equation*}
```
""" atan!
@doc doc"""
sinhcosh!(s, c, a, k)
Update the `k-th` expansion coefficients `s[k+1]` and `c[k+1]`
of `s = sinh(a)` and `c = cosh(a)` simultaneously, for `s`, `c` and `a`
either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
\begin{eqnarray*}
s_k &=& \frac{1}{k} \sum_{j=0}^{k-1} (k-j) a_{k-j} c_j, \\
c_k &=& \frac{1}{k} \sum_{j=0}^{k-1} (k-j) a_{k-j} s_j.
\end{eqnarray*}
```
""" sinhcosh!
@doc doc"""
tanh!(c, a, p, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = tanh(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `p = a^2` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = a_k - \frac{1}{k} \sum_{j=0}^{k-1} (k-j) a_{k-j} p_j.
\end{equation*}
```
""" tanh!
@doc doc"""
asinh!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = asinh(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = sqrt(1-c^2)` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = \frac{1}{ \sqrt{r_0} }
\big( a_k - \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j \big).
\end{equation*}
```
""" asinh!
@doc doc"""
acosh!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = acosh(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = sqrt(c^2-1)` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = \frac{1}{ r_0 }
\big( a_k - \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j \big).
\end{equation*}
```
""" acosh!
@doc doc"""
atanh!(c, a, r, k)
Update the `k-th` expansion coefficients `c[k+1]` of `c = atanh(a)`,
for `c` and `a` either `Taylor0` or `TaylorN`; `r = 1-a^2` and
is passed as an argument for efficiency.
```math
\begin{equation*}
c_k = \frac{1}{r_0}\big(a_k + \frac{1}{k} \sum_{j=1}^{k-1} j r_{k-j} c_j\big).
\end{equation*}
```
""" atanh!
=# =# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 6752 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
## real, imag, conj and ctranspose ##
#= real(a::Taylor0) = Taylor0(real.(a.coeffs), a.order)
imag(a::Taylor0) = Taylor0(imag.(a.coeffs), a.order)
conj(a::Taylor0) = Taylor0(conj.(a.coeffs), a.order)
adjoint(a::Taylor0) = conj(a)
## isinf and isnan ##
isinf(a::Taylor0) = any( isinf.(a.coeffs) )
isnan(a::Taylor0) = any( isnan.(a.coeffs) ) =#
## Division functions: rem and mod ##
#= for op in (:mod, :rem)
@eval begin
function ($op)(a::Taylor0, x::T) where {T<:Real}
coeffs = copy(a.coeffs)
@inbounds coeffs[1] = ($op)(constant_term(a), x)
return Taylor0(coeffs, a.order)
end
function ($op)(a::Taylor0, x::S) where {T<:Real,S<:Real}
R = promote_type(T, S)
a = convert(Taylor0{R}, a)
return ($op)(a, convert(R,x))
end
end
end =#
## mod2pi and abs ##
#= function mod2pi(a::Taylor0) where {T<:Real}
coeffs = copy(a.coeffs)
@inbounds coeffs[1] = mod2pi( constant_term(a) )
return Taylor0( coeffs, a.order)
end =#
function abs(a::Taylor0)
if constant_term(a) > 0
return a
elseif constant_term(a) < 0
return -a
else
throw(DomainError(a,
"""The 0th order Taylor0 coefficient must be non-zero
(abs(x) is not differentiable at x=0)."""))
end
end
function abs(a::Taylor0,cache1::Taylor0)
if constant_term(a) > 0
return a
elseif constant_term(a) < 0
@__dot__ cache1.coeffs = (-)(a.coeffs)
return cache1
else
cache1.coeffs .=Inf # no need to throw error, Inf is fine...for my solver i deal with it by guarding against small steps
cache1[0]=0.0
return cache1
#= throw(DomainError(a,
"""The 0th order Taylor0 coefficient must be non-zero
(abs(x) is not differentiable at x=0).""")) =#
end
end
function abs(a::T,cache1::Taylor0) where {T<:Number}
cache1[0]=abs(a)
return cache1
#= throw(DomainError(a,
"""The 0th order Taylor0 coefficient must be non-zero
(abs(x) is not differentiable at x=0).""")) =#
end
#abs2(a::Taylor0) = real(a)^2 + imag(a)^2
#abs(x::Taylor0) where {T<:Complex} = sqrt(abs2(x))
#abs(x::Taylor0{Taylor0}) where {T<:Complex} = sqrt(abs2(x))
#= @doc doc"""
abs(a)
For a `Real` type returns `a` if `constant_term(a) > 0` and `-a` if `constant_term(a) < 0` for
`a <:Union{Taylor0,TaylorN}`.
For a `Complex` type, such as `Taylor0{ComplexF64}`, returns `sqrt(real(a)^2 + imag(a)^2)`.
Notice that `typeof(abs(a)) <: AbstractSeries` and
that for a `Complex` argument a `Real` type is returned (e.g. `typeof(abs(a::Taylor0{ComplexF64})) == Taylor0{Float64}`).
""" abs
#norm
@doc doc"""
norm(x::AbstractSeries, p::Real)
Returns the p-norm of an `x::AbstractSeries`, defined by
```math
\begin{equation*}
\left\Vert x \right\Vert_p = \left( \sum_k | x_k |^p \right)^{\frac{1}{p}},
\end{equation*}
```
which returns a non-negative number.
""" norm =#
#= norm(x::AbstractSeries, p::Real=2) = norm( norm.(x.coeffs, p), p)
#norm for Taylor vectors
norm(v::Vector{T}, p::Real=2) where {T<:AbstractSeries} = norm( norm.(v, p), p)
# rtoldefault
rtoldefault(::Type{Taylor0}) where {T<:Number} = rtoldefault(T)
rtoldefault(::Taylor0) where {T<:Number} = rtoldefault(T) =#
#= # isfinite
"""
isfinite(x::AbstractSeries) -> Bool
Test whether the coefficients of the polynomial `x` are finite.
"""
isfinite(x::AbstractSeries) = !isnan(x) && !isinf(x)
# isapprox; modified from Julia's Base.isapprox
"""
isapprox(x::AbstractSeries, y::AbstractSeries; rtol::Real=sqrt(eps), atol::Real=0, nans::Bool=false)
Inexact equality comparison between polynomials: returns `true` if
`norm(x-y,1) <= atol + rtol*max(norm(x,1), norm(y,1))`, where `x` and `y` are
polynomials. For more details, see [`Base.isapprox`](@ref).
""" =#
#= function isapprox(x::T, y::S; rtol::Real=rtoldefault(x,y,0), atol::Real=0.0,
nans::Bool=false) where {T<:AbstractSeries,S<:AbstractSeries}
x == y || (isfinite(x) && isfinite(y) &&
norm(x-y,1) <= atol + rtol*max(norm(x,1), norm(y,1))) ||
(nans && isnan(x) && isnan(y))
end
#isapprox for vectors of Taylors
function isapprox(x::Vector{T}, y::Vector{S}; rtol::Real=rtoldefault(T,S,0), atol::Real=0.0,
nans::Bool=false) where {T<:AbstractSeries,S<:AbstractSeries}
x == y || norm(x-y,1) <= atol + rtol*max(norm(x,1), norm(y,1)) ||
(nans && isnan(x) && isnan(y))
end
#taylor_expand function for Taylor0
#= """
taylor_expand(f, x0; order)
Computes the Taylor expansion of the function `f` around the point `x0`.
If `x0` is a scalar, a `Taylor0` expansion will be returned. If `x0` is a vector,
a `TaylorN` expansion will be computed. If the dimension of x0 (`length(x0)`)
is different from the variables set for `TaylorN` (`get_numvars()`), an
`AssertionError` will be thrown.
""" =#
function taylor_expand(f::F; order::Int=15) where {F}
a = Taylor0(order)
return f(a)
end
function taylor_expand(f::F, x0::T; order::Int=15) where {F,T<:Number}
a = Taylor0([x0, one(T)], order)
return f(a)
end
#update! function for Taylor0
#= """
update!(a, x0)
Takes `a <: Union{Taylo1,TaylorN}` and expands it around the coordinate `x0`.
""" =#
function update!(a::Taylor0, x0::T) where {T<:Number}
a.coeffs .= evaluate(a, Taylor0([x0, one(x0)], a.order) ).coeffs
nothing
end
deg2rad(z::Taylor0) where {T<:AbstractFloat} = z * (convert(T, pi) / 180)
deg2rad(z::Taylor0) where {T<:Real} = z * (convert(float(T), pi) / 180)
rad2deg(z::Taylor0) where {T<:AbstractFloat} = z * (180 / convert(T, pi))
rad2deg(z::Taylor0) where {T<:Real} = z * (180 / convert(float(T), pi))
# Internal mutating deg2rad!, rad2deg! functions
@inline function deg2rad!(v::Taylor0, a::Taylor0, k::Int) where {T<:AbstractFloat}
@inbounds v[k] = a[k] * (convert(T, pi) / 180)
return nothing
end
@inline function deg2rad!(v::Taylor0{S}, a::Taylor0, k::Int) where {S<:AbstractFloat,T<:Real}
@inbounds v[k] = a[k] * (convert(float(T), pi) / 180)
return nothing
end
@inline function rad2deg!(v::Taylor0, a::Taylor0, k::Int) where {T<:AbstractFloat}
@inbounds v[k] = a[k] * (180 / convert(T, pi))
return nothing
end
@inline function rad2deg!(v::Taylor0{S}, a::Taylor0, k::Int) where {S<:AbstractFloat,T<:Real}
@inbounds v[k] = a[k] * (180 / convert(float(T), pi))
return nothing
end
=# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1227 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Parameters for HomogeneousPolynomial and TaylorN
#=
"""
ParamsTaylor0
DataType holding the current variable name for `Taylor0`.
**Field:**
- `var_name :: String` Names of the variables
These parameters can be changed using [`set_Taylor0_varname`](@ref)
""" =#
mutable struct ParamsTaylor0
var_name :: String
end
const _params_Taylor0_ = ParamsTaylor0("t")
#= """
set_Taylor0_varname(var::String)
Change the displayed variable for `Taylor0` objects.
""" =#
set_Taylor0_varname(var::String) = _params_Taylor0_.var_name = strip(var)
# Control the display of the big 𝒪 notation
const bigOnotation = Bool[true]
const _show_default = [false]
#= """
displayBigO(d::Bool) --> nothing
Set/unset displaying of the big 𝒪 notation in the output
of `Taylor0` and `TaylorN` polynomials. The initial value is
`true`.
""" =#
displayBigO(d::Bool) = (bigOnotation[end] = d; d)
#=
"""
use_Base_show(d::Bool) --> nothing
Use `Base.show_default` method (default `show` method
in Base), or a custom display. The initial value is
`false`, so customized display is used.
""" =#
use_show_default(d::Bool) = (_show_default[end] = d; d)
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 8933 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
#= The following method computes `a^float(n)` (except for cases like
Taylor0{Interval{T}}^n, where `power_by_squaring` is used), to
use internally `pow!`.
=#
#^(a::Taylor0, n::Integer) = a^float(n)
function ^(a::Taylor0, n::Integer)
n == 0 && return one(a)
n == 1 && return copy(a)
n == 2 && return square(a)
n < 0 && throw(DomainError("taylor^n & n<0 !!"))
return power_by_squaring(a, n)
end
#= function ^(a::Taylor0{Rational{T}}, n::Integer) where {T<:Integer}
n == 0 && return one(a)
n == 1 && return copy(a)
n == 2 && return square(a)
n < 0 && return inv( a^(-n) )
return power_by_squaring(a, n)
end =#
^(a::Taylor0, x::Rational) = a^(x.num/x.den)
^(a::Taylor0, b::Taylor0) = exp( b*log(a) )
^(a::Taylor0, x::T) where {T<:Complex} = exp( x*log(a) )
# power_by_squaring; slightly modified from base/intfuncs.jl
# Licensed under MIT "Expat"
function power_by_squaring(x::Taylor0, p::Integer)
p == 1 && return copy(x)
p == 0 && return one(x)
p == 2 && return square(x)
t = trailing_zeros(p) + 1
p >>= t
while (t -= 1) > 0
x = square(x)
end
y = x
while p > 0
t = trailing_zeros(p) + 1
p >>= t
while (t -= 1) ≥ 0
x = square(x)
end
y *= x
end
return y
end
## Real power ##
function ^(a::Taylor0, r::S) where {S<:Real}
# println()
#a0 = constant_term(a)
# @show(a, a0)
#aux = one(a0)^r
# @show(aux)
iszero(r) && return Taylor0(1.0, a.order)
# aa = aux*a
# @show(aa)
r == 1 && return a
r == 2 && return square(a)
r == 1/2 && return sqrt(a)
l0 = findfirst(a)
# @show l0
lnull = trunc(Int, r*l0 )
# @show lnull
if (a.order-lnull < 0) || (lnull > a.order)
# @show a.order
return Taylor0( 0.0, a.order)
end
c_order = l0 == 0 ? a.order : min(a.order, trunc(Int,r*a.order))
# @show(c_order)
c = Taylor0(0.0, c_order)
for k = 0:c_order
pow!(c, aa, r, k)
end
# println()
return c
end
# Homogeneous coefficients for real power
#= @doc doc"""
pow!(c, a, r::Real, k::Int)
Update the `k`-th expansion coefficient `c[k]` of `c = a^r`, for
both `c` and `a` either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
c_k = \frac{1}{k a_0} \sum_{j=0}^{k-1} \big(r(k-j) -j\big)a_{k-j} c_j.
```
For `Taylor0` polynomials, a similar formula is implemented which
exploits `k_0`, the order of the first non-zero coefficient of `a`.
""" =#
@inline function pow!(c::Taylor0, a::Taylor0, r::S, k::Int) where {S<:Real}
if r == 0
return one!(c, a, k)
elseif r == 1
return identity!(c, a, k)
elseif r == 2
return sqr!(c, a, k)
elseif r == 0.5
return sqrt!(c, a, k)
end
# First non-zero coefficient
l0 = findfirst(a)
if l0 < 0
c[k] = zero(a[0])
return nothing
end
# The first non-zero coefficient of the result; must be integer
#= !isinteger(r*l0) && throw(DomainError(a,
"""The 0th order Taylor0 coefficient must be non-zero
to raise the Taylor0 polynomial to a non-integer exponent.""")) =#
lnull = trunc(Int, r*l0 )
kprime = k-lnull
if (kprime < 0) || (lnull > a.order)
@inbounds c[k] = zero(a[0])
return nothing
end
# Relevant for positive integer r, to avoid round-off errors
if isinteger(r) && r > 0 && (k > r*findlast(a))
@inbounds c[k] = zero(a[0])
return nothing
end
if k == lnull
@inbounds c[k] = (a[l0])^r
return nothing
end
# The recursion formula
if l0+kprime ≤ a.order
@inbounds c[k] = r * kprime * c[lnull] * a[l0+kprime]
else
@inbounds c[k] = zero(a[0])
end
for i = 1:k-lnull-1
((i+lnull) > a.order || (l0+kprime-i > a.order)) && continue
aux = r*(kprime-i) - i
@inbounds c[k] += aux * c[i+lnull] * a[l0+kprime-i]
end
@inbounds c[k] = c[k] / (kprime * a[l0])
return nothing
end
#=
## Square ##
"""
square(a::AbstractSeries) --> typeof(a)
Return `a^2`; see [`TaylorSeries.sqr!`](@ref).
"""
=#
function square(a::Taylor0)
c = Taylor0( constant_term(a)^2, a.order)
for k in 1:a.order
sqr!(c, a, k)
end
return c
end
#= # Homogeneous coefficients for square
@doc doc"""
sqr!(c, a, k::Int) --> nothing
Update the `k-th` expansion coefficient `c[k]` of `c = a^2`, for
both `c` and `a` either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
\begin{eqnarray*}
c_k & = & 2 \sum_{j=0}^{(k-1)/2} a_{k-j} a_j,
\text{ if k is odd,} \\
c_k & = & 2 \sum_{j=0}^{(k-2)/2} a_{k-j} a_j + (a_{k/2})^2,
\text{ if k is even. }
\end{eqnarray*}
```
""" sqr! =#
@inline function sqr!(c::Taylor0, a::Taylor0, k::Int)
if k == 0
@inbounds c[0] = constant_term(a)^2
return nothing
end
kodd = k%2
kend = div(k - 2 + kodd, 2)
@inbounds for i = 0:kend
# if Taylor0 == Taylor0
c[k] += a[i] * a[k-i]
#= else
mul!(c[k], a[i], a[k-i])
end =#
end
@inbounds c[k] = 2 * c[k]
kodd == 1 && return nothing
#if Taylor0 == Taylor0
@inbounds c[k] += a[div(k,2)]^2
#= else
sqr!(c[k], a[div(k,2)])
end =#
return nothing
end
## Square root ##
function sqrt(a::Taylor0)
# First non-zero coefficient
l0nz = findfirst(a)
# println("l0nz= ",l0nz )
#aux = zero(sqrt( constant_term(a) ))
aux=zero(a[0])
# @show aux
#= println(" constant_term(a)= ",constant_term(a))
println("sqrt( constant_term(a)= ",sqrt(constant_term(a)))
println("aux= ",aux) =#
if l0nz < 0
# println("l0nz < 0 ",Taylor0(aux, a.order))
return Taylor0(aux, a.order)
#elseif l0nz%2 == 1 # l0nz must be pair
#= throw(DomainError(a,
"""First non-vanishing Taylor0 coefficient must correspond
to an **even power** in order to expand `sqrt` around 0.""")) =#
end
# The last l0nz coefficients are set to zero.
# lnull = l0nz >> 1 # integer division by 2
#println("lnull= ",lnull)
# c_order = l0nz == 0 ? a.order : a.order >> 1
# println("a_order= ",a.order)
# println("c_order= ",c_order)
c = Taylor0( sqrt( a[0] ), a.order )
# println("c= ",c)
# println("c= ",c)
aa = one(aux) * a
#println("aa= ",aa) #a int aa
#println("aa=a ",aa===a)
for k = 1:a.order
sqrt!(c, aa, k, 0)
# println("after sqrt!c= ",c)
end
return c
end
# Homogeneous coefficients for the square-root
#= @doc doc"""
sqrt!(c, a, k::Int, k0::Int=0)
Compute the `k-th` expansion coefficient `c[k]` of `c = sqrt(a)`
for both`c` and `a` either `Taylor0` or `TaylorN`.
The coefficients are given by
```math
\begin{eqnarray*}
c_k &=& \frac{1}{2 c_0} \big( a_k - 2 \sum_{j=1}^{(k-1)/2} c_{k-j}c_j\big),
\text{ if k is odd,} \\
c_k &=& \frac{1}{2 c_0} \big( a_k - 2 \sum_{j=1}^{(k-2)/2} c_{k-j}c_j
- (c_{k/2})^2\big), \text{ if k is even.}
\end{eqnarray*}
```
For `Taylor0` polynomials, `k0` is the order of the first non-zero
coefficient, which must be even.
""" sqrt! =#
@inline function sqrt!(c::Taylor0, a::Taylor0, k::Int, k0::Int=0)
#println("k= ",k)
# println("k0= ",k0)
if k == k0
@inbounds c[k] = sqrt(a[2*k0])
println("i think this is a dead branch")
return nothing
end
kodd = (k - k0)%2
# println("kodd= ",kodd)
kend = div(k - k0 - 2 + kodd, 2)
# println("kend= ",kend)
imax = min(k0+kend, a.order)
# println("imax= ",imax)
imin = max(k0+1, k+k0-a.order)
# println("imin= ",imin)
#imin ≤ imax && ( @inbounds println("c in loop= ",c) c[k] = c[imin] * c[k+k0-imin] )
if imin ≤ imax
# println("c in imin imax= ",c)
c[k] = c[imin] * c[k+k0-imin]
end
# println("c= ",c)
@inbounds for i = imin+1:imax
c[k] += c[i] * c[k+k0-i]
# println("c in loop= ",c)
end
if k+k0 ≤ a.order
@inbounds aux = a[k+k0] - 2*c[k]
# println("aux if <order= ",aux)
else
@inbounds aux = - 2*c[k]
# println("aux else= ",aux)
end
if kodd == 0
@inbounds aux = aux - (c[kend+k0+1])^2
# println("aux if kodd==0 = ",aux)
end
@inbounds c[k] = aux / (2*c[k0])
#println("final c inside sqrt!= ",c)
return nothing
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1661 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
powerT(a::Taylor0, n::Integer,cache1::Taylor0) = powerT(a, float(n),cache1)
## Real power ##
function powerT(a::Taylor0, r::S,cache1::Taylor0) where {S<:Real}
if iszero(r) #later test r=0.0
cache1[0]=1.0
return cache1
end
# @show(aa)
r == 1 && return a
r == 2 && return square(a,cache1)
r == 1/2 && return sqrt(a,cache1)
l0 = findfirst(a)
# @show l0
lnull = trunc(Int, r*l0 )
# @show lnull
if (a.order-lnull < 0) || (lnull > a.order)
# @show a.order
return cache1 #empty
end
c_order = l0 == 0 ? a.order : min(a.order, trunc(Int,r*a.order))
# @show(c_order)
#c = Taylor0(zero(aux), c_order)
for k = 0:c_order
pow!(cache1, a, r, k)
end
# println()
return cache1
end
function powerT(a::T, r::S,cache1::Taylor0) where {S<:Real,T<:Number}
cache1[0]=a^r
return cache1
end
function square(a::Taylor0,cache1::Taylor0) #internal helper function ...no need to take care of a==number
#c = Taylor0( constant_term(a)^2, a.order)
cache1[0]=constant_term(a)^2
for k in 1:a.order
sqr!(cache1, a, k)
end
return cache1
end
## Square root ##
function sqrt(a::Taylor0,cache1::Taylor0)
l0nz = findfirst(a)
if l0nz < 0
cache1
end
cache1[0]=sqrt(a[0])
for k = 1:a.order
sqrt!(cache1, a, k, 0)
end
return cache1
end
function sqrt(a::T,cache1::Taylor0)where {T<:Number}
cache1[0]=sqrt(a)
return cache1
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 180 | using qss
using StaticArrays
using BenchmarkTools
t2=Taylor0([2.0,2.0,3.0],2)
t1=Taylor0([1.0,1.1],1)
#= cache1=Taylor0([0.0,0.0,0.0],2)
cache2=Taylor0([0.0,0.0,0.0],2) =#
@show t1 | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 767 | using qssgenerated
using BenchmarkTools
t2=Taylor0([2.0,2.0,3.0],2)
t1=Taylor0([1.0,1.0,0.0],2)
cache1=Taylor0([0.0,0.0,0.0],2)
cache2=Taylor0([0.0,0.0,0.0],2)
function test0(t2::Taylor0{Float64})
one(t2)
end
function test0(t2::Taylor0{Float64},cache::Taylor0{Float64})
qssgenerated.one(t2,cache)
end
function test1(t2::Taylor0{Float64},t1::Taylor0{Float64})
res=t2/t1/t1
end
function test2(t2::Taylor0{Float64},t1::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
res2=qssgenerated.divT(qss.divT(t2,t1,cache1),t1,cache2)
end
#= @show test0(t2)
@show test0(t2,cache1) =#
#@btime test0(t2)
#@btime test0(t2,cache1)
#= @show test1(t2,t1)
@show test2(t2,t1,cache1,cache2) =#
#@btime test1(t2,t1)
#@btime test2(t2,t1,cache1,cache2)
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1067 | using qss
using BenchmarkTools
t2=Taylor0([2.0,2.0,3.0],2)
t1=Taylor0([1.0,1.1],1)
cache1=Taylor0([0.0,0.0,0.0],2)
cache2=Taylor0([0.0,0.0,0.0],2)
function test0(t2::Taylor0{Float64},t1::Taylor0{Float64})
qss.resize_coeffs1!(t2.coeffs,1)
#@show
t2.coeffs[1]
# @show
qss.getcoeff(t2,1)
# @show
qss.getindex(t2,1)
# @show
qss.setindex!(t2,2.22,1)
return nothing
end
function test1(t2::Taylor0{Float64},t1::Taylor0{Float64})
qss.iterate(t1,0)
qss.iterate(t1,1)
end
function test2(t2::Taylor0{Float64},t1::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
qss.fixorder(t2,t1)
end
#= @show test0(t2,t1)
@show t2
@btime test0(t2,t1)=#
#@btime test1(t2,t1)
#test1(t2,t1)
#=
t1,t2=test2(t1,t2,cache1,cache2)
@show t1
@show t2 =#
#@btime test2(t2,t1,cache1,cache2)
function test4(t2::Taylor0{Float64},t1::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
qss.copyto!(cache1,t2)
end
#= @show test4(t2,t1,cache1,cache2)
@show cache1 =#
@btime test4(t2,t1,cache1,cache2) | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 2631 | using qss
using BenchmarkTools
t2=Taylor0([0.5,2.0,3.0],2)
t1=Taylor0([1.0,1.1],1)
x=Taylor0([0.0,0.0,0.0],2)
cache1=Taylor0([0.0,0.0,0.0],2)
cache2=Taylor0([0.0,0.0,0.0],2)
cache3=Taylor0([0.0,0.0,0.0],2)
function testexp0(t2::Taylor0{Float64},cache1::Taylor0{Float64})
qss.exp(t2,cache1)
end
function testexp1(t2::Taylor0{Float64},t1::Taylor0{Float64})
exp(t2)
end
function testlog0(t2::Taylor0{Float64},cache1::Taylor0{Float64})
qss.log(t2,cache1)
end
function testlog1(t2::Taylor0{Float64},t1::Taylor0{Float64})
log(t2)
end
function testsincos0(t2::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
qss.sincos(t2,cache1,cache2)
end
function testsincos1(t2::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
sincos(t2)
end
function testtan0(t2::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
qss.tan(t2,cache1,cache2)
end
function testtan1(t2::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
tan(t2)
end
function testasin0(t2::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64},cache3::Taylor0{Float64})
qss.asin(t2,cache1,cache2,cache3)
end
function testasin1(t2::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
asin(t2)
end
function testacos0(t2::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64},cache3::Taylor0{Float64})
qss.acos(t2,cache1,cache2,cache3)
end
function testacos1(t2::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
acos(t2)
end
function testabs0(t2::Taylor0{Float64},cache1::Taylor0{Float64})
qss.abs(t2,cache1)
end
function testabs1(t2::Taylor0{Float64},cache1::Taylor0{Float64})
abs(t2)
end
#= @show testlog0(t2,cache1)
@show testlog1(t2,cache1) =#
#@btime testlog0(t2,cache1)
#@btime testlog1(t2,cache1)
#= @show testsincos0(t2,cache1,cache2)
@show testsincos1(t2,cache1,cache2) =#
#@btime testsincos0(t2,cache1,cache2)
#@btime testsincos1(t2,cache1,cache2)
#= @show testtan0(t2,cache1,cache2)
@show testtan1(t2,cache1,cache2) =#
#@btime testtan0(t2,cache1,cache2)
#@btime testtan1(t2,cache1,cache2)
#= @show testasin0(t2,cache1,cache2,cache3)
@show testasin1(t2,cache1,cache2) =#
#@btime testasin0(t2,cache1,cache2,cache3)
#@btime testasin1(t2,cache1,cache2)
#=
@show testacos0(t2,cache1,cache2,cache3)
@show testacos1(t2,cache1,cache2) =#
#@btime testasin0(t2,cache1,cache2,cache3) #(0 allocations: 0 bytes)
#@btime testasin1(t2,cache1,cache2) #(15 allocations: 1.08 KiB)
#= @show testabs0(t2,cache1)
@show testabs1(t2,cache1) =#
@btime testabs0(t2,cache1)
#@btime testabs1(t2,cache1)
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1865 | using qss
using BenchmarkTools
t2=Taylor0([0.5,2.0,3.0],2)
t1=Taylor0([1.0,1.1],1)
x=Taylor0([0.0,0.0,0.0],2)
cache1=Taylor0([0.0,0.0,0.0],2)
cache2=Taylor0([0.0,0.0,0.0],2)
cache3=Taylor0([0.0,0.0,0.0],2)
function testsquare0(t2::Taylor0{Float64},cache1::Taylor0{Float64})
qss.square(t2,cache1)
end
function testsquare1(t2::Taylor0{Float64},t1::Taylor0{Float64})
t2^2
end
function testsqrt0(t2::Taylor0{Float64},cache1::Taylor0{Float64})
qss.sqrt(t2,cache1)
end
function testsqrt1(t2::Taylor0{Float64},t1::Taylor0{Float64})
sqrt(t2)
end
function testpower0(t2::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
qss.powerT(t2,3,cache1)
end
function testpower1(t2::Taylor0{Float64},cache1::Taylor0{Float64},cache2::Taylor0{Float64})
^(t2,3)
end
#################real power###############
function testrealpower0(t2::Taylor0{Float64},cache1::Taylor0{Float64})
qss.powerT(t2,3.22,cache1)
end
function testrealpower1(t2::Taylor0{Float64},cache1::Taylor0{Float64})
^(t2,3.22)
end
#=
@show testsquare0(t2,cache1)
@show testsquare1(t2,cache1) =#
#@btime testsquare0(t2,cache1)#21.193 ns (0 allocations: 0 bytes)
#@btime testsquare1(t2,cache1)# 102.524 ns (2 allocations: 160 bytes)
#= @show testsqrt0(t2,cache1)
@show testsqrt1(t2,cache1) =#
#@btime testsqrt0(t2,cache1)#20.749 ns (0 allocations: 0 bytes)
#@btime testsqrt1(t2,cache1)#99.014 ns (2 allocations: 160 bytes)
#= @show testpower0(t2,cache1,cache2)
@show testpower1(t2,cache1,cache2) =#
#@btime testpower0(t2,cache1,cache2)#60.724 ns (0 allocations: 0 bytes)
#@btime testpower1(t2,cache1,cache2)#132.472 ns (2 allocations: 160 bytes)
#= @show testrealpower0(t2,cache1)
@show testrealpower1(t2,cache1) =#
#@btime testrealpower0(t2,cache1)#142.59 ns (0 allocations: 0 bytes)
#@btime testrealpower1(t2,cache1)#216.271 ns (2 allocations: 160 bytes)
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 3064 | using TaylorSeries
using BenchmarkTools
using qssgenerated
import Base.:/
av = vec(3(rand(1,3) .- 1.5))
bv = vec(3(rand(1,3) .- 1.5))
cv = vec(3(rand(1,3) .- 1.5))
dv = vec(3(rand(1,3) .- 1.5))
ev = vec(3(rand(1,3) .- 1.5))
fv = vec(3(rand(1,3) .- 1.5))
gv = vec(3(rand(1,3) .- 1.5))
hv = vec(3(rand(1,3) .- 1.5))
a1 = Taylor1(av,2)
b1 = Taylor1(bv,2)
c1 = Taylor1(cv,2)
d1 = Taylor1(dv,2)
e1 = Taylor1(ev,2)
f1 = Taylor1(fv,2)
g1 = Taylor1(gv,2)
h1 = Taylor1(hv,2)
a0 = Taylor0(av,2)
b0 = Taylor0(bv,2)
c0 = Taylor0(cv,2)
d0 = Taylor0(dv,2)
e0 = Taylor0(ev,2)
f0 = Taylor0(fv,2)
g0 = Taylor0(gv,2)
h0 = Taylor0(hv,2)
i=3rand() - 1.5
j=3rand() - 1.5
k=3rand() - 1.5
cache=[Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2)]
function clearCache(cache::Vector{Taylor0{Float64}}) #where {T<:Number}
for i=1:12
cache[i].coeffs.=0.0
end
end
function same(sum1::Taylor1{Float64},sum2::Taylor0{Float64})
isclose=true
for i=0:length(sum1.coeffs)-1
if abs(sum1[i]-sum2[i])>1e-9
#if (sum1[i]!=sum2[i])
isclose=false
break
end
end
return isclose
end
function same(sum1::Float64,sum2::Taylor0{Float64})
return abs(sum1-sum2[0])<1e-9
#return (sum1==sum2[0])
end
macro changeAST(ex)
Base.remove_linenums!(ex)
# dump(ex; maxdepth=18)
qssgenerated.twoInOne(ex)
# dump( ex.args[1])
#@show ex.args[1]
#= # return
return nothing =#
esc(ex.args[1])# return
end
function /(a::T, b::Taylor1{T}) where {T<:Number}
c=^(b, -1.0)
c2 = Taylor1( b.order )
@__dot__ c2.coeffs=c.coeffs*a ### broadcast dimension mismatch------------------div can have 2 caches then...:(
return c2
end
function normalTest(a1::Taylor1{Float64},b1::Taylor1{Float64},c1::Taylor1{Float64},d1::Taylor1{Float64},e1::Taylor1{Float64},f1::Taylor1{Float64},g1::Taylor1{Float64},h1::Taylor1{Float64},a0::Taylor0{Float64},b0::Taylor0{Float64},c0::Taylor0{Float64},d0::Taylor0{Float64},e0::Taylor0{Float64},f0::Taylor0{Float64},g0::Taylor0{Float64},h0::Taylor0{Float64},cache::Vector{Taylor0{Float64}},i::Float64,j::Float64,k::Float64)
+(-(+(+(*(*(-(a1,b1),j),c1),d1),i),e1),f1)
end
function freeTest(a1::Taylor1{Float64},b1::Taylor1{Float64},c1::Taylor1{Float64},d1::Taylor1{Float64},e1::Taylor1{Float64},f1::Taylor1{Float64},g1::Taylor1{Float64},h1::Taylor1{Float64},a0::Taylor0{Float64},b0::Taylor0{Float64},c0::Taylor0{Float64},d0::Taylor0{Float64},e0::Taylor0{Float64},f0::Taylor0{Float64},g0::Taylor0{Float64},h0::Taylor0{Float64},cache::Vector{Taylor0{Float64}},i::Float64,j::Float64,k::Float64)
clearCache(cache)
@changeAST (+(-(+(+(*(*(-(a0,b0),j),c0),d0),i),e0),f0),1)
end
@btime normalTest(a1,b1,c1,d1,e1,f1,g1,h1,a0,b0,c0,d0,e0,f0,g0,h0,cache,i,j,k)
@btime freeTest(a1,b1,c1,d1,e1,f1,g1,h1,a0,b0,c0,d0,e0,f0,g0,h0,cache,i,j,k)
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 6073 | using TaylorSeries
using BenchmarkTools
using qssgenerated
av = vec(3(rand(1,3) .+ 1.5)) #changed + for log and sqrt only
bv = vec(3(rand(1,3) .+ 1.5))
cv = vec(3(rand(1,3) .+ 1.5))
dv = vec(3(rand(1,3) .+ 1.5))
a1 = Taylor1(av,2)
b1 = Taylor1(bv,2)
c1 = Taylor1(cv,2)
d1 = Taylor1(dv,2)
a0 = Taylor0(av,2)
b0 = Taylor0(bv,2)
c0 = Taylor0(cv,2)
d0 = Taylor0(dv,2)
e=3rand() + 1.5
f=3rand() + 1.5
cache=[Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2)]
function clearCache(cache::Vector{Taylor0{Float64}}) #where {T<:Number}
for i=1:10
cache[i].coeffs.=0.0
end
end
function same(sum1::Taylor1{Float64},sum2::Taylor0{Float64})
if sum1[0]==Inf && sum2[0]==Inf
return true
end
for i=0:length(sum1.coeffs)-1
if abs(sum1[i]-sum2[i])>1e-9
#if (sum1[i]!=sum2[i])
return false
end
end
return true
end
function same(sum1::Float64,sum2::Taylor0{Float64})
if sum1==Inf && sum2[0]==Inf
return true
end
return abs(sum1-sum2[0])<1e-9
#return (sum1==sum2[0])
end
macro changeAST(ex)
Base.remove_linenums!(ex)
# dump(ex; maxdepth=18)
qssgenerated.twoInOne(ex)
# dump( ex.args[1])
#@show ex.args[1]
#= # return
return nothing =#
esc(ex.args[1])# return
end
function investigationTest(a1::Taylor1{Float64},b1::Taylor1{Float64},c1::Taylor1{Float64},d1::Taylor1{Float64},a0::Taylor0{Float64},b0::Taylor0{Float64},c0::Taylor0{Float64},d0::Taylor0{Float64},cache::Vector{Taylor0{Float64}},e::Float64,f::Float64)
clearCache(cache)
@show @changeAST((((b0 - f) - a0) * d0, 1))
@show ((b1 - f) + a1) * d1
end
function outerInvestigation()
for _=1:20
av = vec(3(rand(1,3) .- 1.5))
bv = vec(3(rand(1,3) .- 1.5))
cv = vec(3(rand(1,3) .- 1.5))
dv = vec(3(rand(1,3) .- 1.5))
a1 = Taylor1(av,2)
b1 = Taylor1(bv,2)
c1 = Taylor1(cv,2)
d1 = Taylor1(dv,2)
a0 = Taylor0(av,2)
b0 = Taylor0(bv,2)
c0 = Taylor0(cv,2)
d0 = Taylor0(dv,2)
e=3rand() - 1.5
f=3rand() - 1.5
investigationTest(a1,b1,c1,d1,a0,b0,c0,d0,cache,e,f)
end
end
#outerInvestigation()
function boundaryTest(a1::Taylor1{Float64},b1::Taylor1{Float64},c1::Taylor1{Float64},d1::Taylor1{Float64},a0::Taylor0{Float64},b0::Taylor0{Float64},c0::Taylor0{Float64},d0::Taylor0{Float64},cache::Vector{Taylor0{Float64}},e::Float64,f::Float64)
mulTT(1.2, 2.1, a0, b0, 3.2, c0,d0, cache[1], cache[2])
#@show 1.2*2.1*a1*b1*3.2*c1*d1
return nothing
end
@btime boundaryTest(a1,b1,c1,d1,a0,b0,c0,d0,cache,e,f)
#= function stressTest(a1::Taylor1{Float64},b1::Taylor1{Float64},c1::Taylor1{Float64},d1::Taylor1{Float64},a0::Taylor0{Float64},b0::Taylor0{Float64},c0::Taylor0{Float64},d0::Taylor0{Float64},cache::Vector{Taylor0{Float64}},e::Float64,f::Float64)
for op1 in (:+,:-,:*,:/)
for op2 in (:+,:-,:*,:/)
for op3 in (:+,:-,:*,:/)
for (term11,term01) in((:a1,:a0),(:e,:e))
for (term12,term02) in((:a1,:a0),(:b1,:b0))
for (term13,term03) in((:c1,:c0),(:f,:f))
for (term14,term04) in((:d1,:d0),(:a1,:a0))
@eval begin
clearCache(cache)
@assert same($op3($op1($op2($term12,$term13),$term11),$term14), @changeAST ($op3($op1($op2($term02,$term03),$term01),$term04),1))
#= if !same($op3($op1($op2($term12,$term13),$term11),$term14), @changeAST ($op3($op1($op2($term02,$term03),$term01),$term04),1))
@show cache
@show $op3($op1($op2($term12,$term13),$term11),$term14)
@show @changeAST ($op3($op1($op2($term02,$term03),$term01),$term04),1)
end =#
end
end
end
end
end
end
end
end
end
=#
#stressTest(a1,b1,c1,d1,a0,b0,c0,d0,cache,e,f) #successful
function stressTest2(a1::Taylor1{Float64},b1::Taylor1{Float64},c1::Taylor1{Float64},d1::Taylor1{Float64},a0::Taylor0{Float64},b0::Taylor0{Float64},c0::Taylor0{Float64},d0::Taylor0{Float64},cache::Vector{Taylor0{Float64}},e::Float64,f::Float64)
for op1 in (:abs,:exp,:cos,:sin)
for op2 in (:abs,:exp,:cos,:sin)
for op3 in (:abs,:exp,:cos,:sin)
for (term11,term01) in((:a1,:a0),(:e,:e))
for (term12,term02) in((:a1,:a0),(:b1,:b0))
@eval begin
clearCache(cache)
@assert same($op3($op1($op2($term12))), @changeAST ($op3($op1($op2($term02))),1))
clearCache(cache)
@assert same($op3($op1($op2($term11))), @changeAST ($op3($op1($op2($term01))),1))
end
end
end
end
end
end
end
#stressTest2(a1,b1,c1,d1,a0,b0,c0,d0,cache,e,f)#successful
#= function stressTest3(a1::Taylor1{Float64},b1::Taylor1{Float64},c1::Taylor1{Float64},d1::Taylor1{Float64},a0::Taylor0{Float64},b0::Taylor0{Float64},c0::Taylor0{Float64},d0::Taylor0{Float64},cache::Vector{Taylor0{Float64}},e::Float64,f::Float64)
for op1 in (:sqrt,:log)
for op2 in (:sqrt,:log)
for (term11,term01) in((:a1,:a0),(:e,:e))
for (term12,term02) in((:a1,:a0),(:b1,:b0))
@eval begin
clearCache(cache)
@assert same($op1($op2($term12)), @changeAST ($op1($op2($term02)),1))
clearCache(cache)
@assert same($op1($op2($term11)), @changeAST ($op1($op2($term01)),1))
end
end
end
end
end
end =#
#stressTest3(a1,b1,c1,d1,a0,b0,c0,d0,cache,e,f)#successful | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 6053 | using TaylorSeries
using qssgenerated
import Base.:/
av = vec(3(rand(1,3) .- 1.5))
bv = vec(3(rand(1,3) .- 1.5))
cv = vec(3(rand(1,3) .- 1.5))
dv = vec(3(rand(1,3) .- 1.5))
ev = vec(3(rand(1,3) .- 1.5))
fv = vec(3(rand(1,3) .- 1.5))
gv = vec(3(rand(1,3) .- 1.5))
hv = vec(3(rand(1,3) .- 1.5))
a1 = Taylor1(av,2)
b1 = Taylor1(bv,2)
c1 = Taylor1(cv,2)
d1 = Taylor1(dv,2)
e1 = Taylor1(ev,2)
f1 = Taylor1(fv,2)
g1 = Taylor1(gv,2)
h1 = Taylor1(hv,2)
a0 = Taylor0(av,2)
b0 = Taylor0(bv,2)
c0 = Taylor0(cv,2)
d0 = Taylor0(dv,2)
e0 = Taylor0(ev,2)
f0 = Taylor0(fv,2)
g0 = Taylor0(gv,2)
h0 = Taylor0(hv,2)
i=3rand() - 1.5
j=3rand() - 1.5
k=3rand() - 1.5
cache=[Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2),Taylor0([0.0,0.0,0.0],2)]
function clearCache(cache::Vector{Taylor0{Float64}}) #where {T<:Number}
for i=1:12
cache[i].coeffs.=0.0
end
end
function same(sum1::Taylor1{Float64},sum2::Taylor0{Float64})
isclose=true
for i=0:length(sum1.coeffs)-1
if abs(sum1[i]-sum2[i])>1e-9
#if (sum1[i]!=sum2[i])
isclose=false
break
end
end
return isclose
end
function same(sum1::Float64,sum2::Taylor0{Float64})
return abs(sum1-sum2[0])<1e-9
#return (sum1==sum2[0])
end
macro changeAST(ex)
Base.remove_linenums!(ex)
# dump(ex; maxdepth=18)
qssgenerated.twoInOne(ex)
# dump( ex.args[1])
#@show ex.args[1]
#= # return
return nothing =#
esc(ex.args[1])# return
end
function /(a::T, b::Taylor1{T}) where {T<:Number}
c=^(b, -1.0)
c2 = Taylor1( b.order )
@__dot__ c2.coeffs=c.coeffs*a ### broadcast dimension mismatch------------------div can have 2 caches then...:(
return c2
end
function stressTest(a1::Taylor1{Float64},b1::Taylor1{Float64},c1::Taylor1{Float64},d1::Taylor1{Float64},e1::Taylor1{Float64},f1::Taylor1{Float64},g1::Taylor1{Float64},h1::Taylor1{Float64},a0::Taylor0{Float64},b0::Taylor0{Float64},c0::Taylor0{Float64},d0::Taylor0{Float64},e0::Taylor0{Float64},f0::Taylor0{Float64},g0::Taylor0{Float64},h0::Taylor0{Float64},cache::Vector{Taylor0{Float64}},i::Float64,j::Float64,k::Float64)
for op1 in (:+,:-,:*,:/)
for op2 in (:+,:-,:*,:/)
for op3 in (:+,:-,:*,:/)
for (term11,term01) in((:a1,:a0),(:j,:j))
for (term12,term02) in((:a1,:a0),(:b1,:b0))
for (term13,term03) in((:c1,:c0),(:i,:i))
for (term14,term04) in((:d1,:d0),(:a1,:a0))
for (term15,term05) in((:a1,:a0),(:j,:j))
for (term16,term06) in((:a1,:a0),(:b1,:b0))
for (term17,term07) in((:c1,:c0),(:i,:i))
for (term18,term08) in((:d1,:d0),(:a1,:a0))
@eval begin
clearCache(cache)
@assert same($op1($op3($op2($op1($op3($op2($op1($term11,$term12),$term13),$term14),$term15),$term16),$term17),$term18),@changeAST ($op1($op3($op2($op1($op3($op2($op1($term01,$term02),$term03),$term04),$term05),$term06),$term07),$term08),1))
#= if !same($op3($op1($op2($term12,$term13),$term11),$term14), @changeAST ($op3($op1($op2($term02,$term03),$term01),$term04),1))
@show cache
@show $op3($op1($op2($term12,$term13),$term11),$term14)
@show @changeAST ($op3($op1($op2($term02,$term03),$term01),$term04),1)
end =#
end
end
end
end
end
end
end
end
end
end
end
end
end
stressTest(a1,b1,c1,d1,e1,f1,g1,h1,a0,b0,c0,d0,e0,f0,g0,h0,cache,i,j,k)#successful
#= function stressTest2(a1::Taylor1{Float64},b1::Taylor1{Float64},c1::Taylor1{Float64},d1::Taylor1{Float64},a0::Taylor0{Float64},b0::Taylor0{Float64},c0::Taylor0{Float64},d0::Taylor0{Float64},cache::Vector{Taylor0{Float64}},e::Float64,f::Float64)
for op1 in (:abs,:exp,:cos,:sin)
for op2 in (:abs,:exp,:cos,:sin)
for op3 in (:abs,:exp,:cos,:sin)
for (term11,term01) in((:a1,:a0),(:e,:e))
for (term12,term02) in((:a1,:a0),(:b1,:b0))
@eval begin
clearCache(cache)
@assert same($op3($op1($op2($term12))), @changeAST ($op3($op1($op2($term02))),1))
@assert same($op3($op1($op2($term11))), @changeAST ($op3($op1($op2($term01))),1))
end
end
end
end
end
end
end
#stressTest2(a1,b1,c1,d1,a0,b0,c0,d0,cache,e,f)
function stressTest3(a1::Taylor1{Float64},b1::Taylor1{Float64},c1::Taylor1{Float64},d1::Taylor1{Float64},a0::Taylor0{Float64},b0::Taylor0{Float64},c0::Taylor0{Float64},d0::Taylor0{Float64},cache::Vector{Taylor0{Float64}},e::Float64,f::Float64)
for op1 in (:abs,:exp,:cos,:sin)
for op2 in (:abs,:exp,:cos,:sin)
for op3 in (:abs,:exp,:cos,:sin)
for (term11,term01) in((:a1,:a0),(:e,:e))
for (term12,term02) in((:a1,:a0),(:b1,:b0))
@eval begin
clearCache(cache)
@assert same($op3($op1($op2($term12))), @changeAST ($op3($op1($op2($term02))),1))
@assert same($op3($op1($op2($term11))), @changeAST ($op3($op1($op2($term01))),1))
end
end
end
end
end
end
end
#stressTest3(a1,b1,c1,d1,a0,b0,c0,d0,cache,e,f) =# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 25211 | # This file is part of TS.jl, MIT licensed
#
#using TS
using qss
using Test
#using LinearAlgebra, SparseArrays
# This is used to check the fallack of pretty_print
struct SymbNumber <: Number
s :: Symbol
end
Base.iszero(::SymbNumber) = false
const TS = qss
@testset "Tests for Taylor0 expansions" begin
eeuler = Base.MathConstants.e
ta(a) = Taylor0([a,one(a)],15)
t = Taylor0(Int,15)
tim = im*t
zt = zero(t)
ot = 1.0*one(t)
tol1 = eps(1.0)
#= @test TS === qss
@test Taylor0 <: AbstractSeries
@test Taylor0{Float64} <: AbstractSeries{Float64}
@test TS.numtype(1.0) == eltype(1.0)
@test TS.numtype([1.0]) == eltype([1.0])
@test TS.normalize_taylor(t) == t
@test TS.normalize_taylor(tim) == tim
@test Taylor0([1,2,3,4,5], 2) == Taylor0([1,2,3])
@test Taylor0(t[0:3]) == Taylor0(t[0:get_order(t)], 4)
@test get_order(t) == 15
@test get_order(Taylor0([1,2,3,4,5], 2)) == 2
@test size(t) == (16,)
@test firstindex(t) == 0
@test lastindex(t) == 15
@test eachindex(t) == 0:15
@test iterate(t) == (0.0, 1)
@test iterate(t, 1) == (1.0, 2)
@test iterate(t, 16) == nothing
@test axes(t) == ()
@test axes([t]) == (Base.OneTo(1),)
v = [1,2]
@test typeof(resize_coeffs1!(v,3)) == Nothing
@test v == [1,2,0,0]
resize_coeffs1!(v,0)
@test v == [1]
resize_coeffs1!(v,3)
setindex!(Taylor0(v),3,2)
@test v == [1,0,3,0]
pol_int = Taylor0(v)
@test pol_int[:] == [1,0,3,0]
@test pol_int[:] == pol_int.coeffs[:]
@test pol_int[1:2:3] == pol_int.coeffs[2:2:4]
setindex!(pol_int,0,0:2)
@test v == zero(v)
setindex!(pol_int,1,:)
@test v == ones(Int, 4)
setindex!(pol_int, v, :)
@test v == ones(Int, 4)
setindex!(pol_int, zeros(Int, 4), 0:3)
@test v == zeros(Int, 4)
pol_int[:] .= 0
@test v == zero(v)
pol_int[0:2:end] = 2
@test all(v[1:2:end] .== 2)
pol_int[0:2:3] = [0, 1]
@test all(v[1:2:3] .== [0, 1])
rv = [rand(0:3) for i in 1:4]
@test Taylor0(rv)[:] == rv
y = sin(Taylor0(16))
@test y[:] == y.coeffs
y[:] .= cos(Taylor0(16))[:]
@test y == cos(Taylor0(16))
@test y[:] == cos(Taylor0(16))[:]
y = sin(Taylor0(16))
rv = rand(5)
y[0:4] .= rv
@test y[0:4] == rv
@test y[5:end] == y.coeffs[6:end]
rv = rand( length(y.coeffs) )
y[:] .= rv
@test y[:] == rv
y[:] .= cos(Taylor0(16)).coeffs
@test y == cos(Taylor0(16))
@test y[:] == cos(Taylor0(16))[:]
y[:] .= 0.0
@test y[:] == zero(y[:])
y = sin(Taylor0(16))
rv = rand.(length(0:4))
y[0:4] .= rv
@test y[0:4] == rv
@test y[6:end] == sin(Taylor0(16))[6:end]
rv = rand.(length(y))
y[:] .= rv
@test y[:] == rv
y[0:4:end] .= 1.0
@test all(y.coeffs[1:4:end] .== 1.0)
y[0:2:8] .= rv[1:5]
@test y.coeffs[1:2:9] == rv[1:5]
@test_throws AssertionError y[0:2:3] = rv
@test Taylor0([0,1,0,0]) == Taylor0(3)
@test getcoeff(Taylor0(Complex{Float64},3),1) == complex(1.0,0.0)
@test Taylor0(Complex{Float64},3)[1] == complex(1.0,0.0)
@test getindex(Taylor0(3),1) == 1.0
@inferred convert(Taylor0{Complex{Float64}},ot) == Taylor0{Complex{Float64}}
@test eltype(convert(Taylor0{Complex{Float64}},ot)) == Taylor0{Complex{Float64}}
@test eltype(convert(Taylor0{Complex{Float64}},1)) == Taylor0{Complex{Float64}}
@test eltype(convert(Taylor0, 1im)) == Taylor0{Complex{Int}}
@test TS.numtype(convert(Taylor0{Complex{Float64}},ot)) == Complex{Float64}
@test TS.numtype(convert(Taylor0{Complex{Float64}},1)) == Complex{Float64}
@test TS.numtype(convert(Taylor0, 1im)) == Complex{Int}
@test convert(Taylor0, 1im) == Taylor0(1im, 0)
@test convert(eltype(t), t) === t
@test convert(eltype(ot), ot) === ot
@test convert(Taylor0{Int},[0,2]) == 2*t
@test convert(Taylor0{Complex{Int}},[0,2]) == (2+0im)*t
@test convert(Taylor0{BigFloat},[0.0, 1.0]) == ta(big(0.0))
@test promote(t,Taylor0(1.0,0)) == (ta(0.0),ot)
@test promote(0,Taylor0(1.0,0)) == (zt,ot)
@test eltype(promote(ta(0),zeros(Int,2))[2]) == Taylor0{Int}
@test eltype(promote(ta(0.0),zeros(Int,2))[2]) == Taylor0{Float64}
@test eltype(promote(0,Taylor0(ot))[1]) == Taylor0{Float64}
@test eltype(promote(1.0+im, zt)[1]) == Taylor0{Complex{Float64}}
@test TS.numtype(promote(ta(0),zeros(Int,2))[2]) == Int
@test TS.numtype(promote(ta(0.0),zeros(Int,2))[2]) == Float64
@test TS.numtype(promote(0,Taylor0(ot))[1]) == Float64
@test TS.numtype(promote(1.0+im, zt)[1]) == Complex{Float64}
@test length(Taylor0(10)) == 11
@test length.( TS.fixorder(zt, Taylor0([1])) ) == (16, 16)
@test length.( TS.fixorder(zt, Taylor0([1], 1)) ) == (2, 2)
@test eltype(TS.fixorder(zt,Taylor0([1]))[1]) == Taylor0{Int}
@test TS.numtype(TS.fixorder(zt,Taylor0([1]))[1]) == Int
@test TS.findfirst(t) == 1
@test TS.findfirst(t^2) == 2
@test TS.findfirst(ot) == 0
@test TS.findfirst(zt) == -1
@test TS.findlast(t) == 1
@test TS.findlast(t^2) == 2
@test TS.findlast(ot) == 0
@test TS.findlast(zt) == -1
@test iszero(zero(t))
@test !iszero(one(t))
@test isinf(Taylor0([typemax(1.0)]))
@test isnan(Taylor0([typemax(1.0), NaN]))
@test constant_term(2.0) == 2.0
@test constant_term(t) == 0
@test constant_term(tim) == complex(0, 0)
@test constant_term([zt, t]) == [0, 0]
@test linear_polynomial(2) == 2
@test linear_polynomial(t) == t
@test linear_polynomial(1+tim^2) == zero(tim)
@test get_order(linear_polynomial(1+tim^2)) == get_order(tim)
@test linear_polynomial([zero(tim), tim, tim^2]) == [zero(tim), tim, zero(tim)]
@test nonlinear_polynomial(2im) == 0im
@test nonlinear_polynomial(1+t) == zero(t)
@test nonlinear_polynomial(1+tim^2) == tim^2
@test nonlinear_polynomial([zero(tim), tim, 1+tim^2]) == [zero(tim), zero(tim), tim^2]
@test ot == 1
@test 0.0 == zt
@test getcoeff(tim,1) == complex(0,1)
@test zt+1.0 == ot
@test 1.0-ot == zt
@test t+t == 2t
@test t-t == zt
@test +t == -(-t)
=#
tsquare = Taylor0([0,0,1],15)
@test t * true == t
@test false * t == zero(t)
@test t^0 == t^0.0 == one(t)
#= @test t*t == tsquare
@test t*1 == t
@test 0*t == zt =#
@test (-t)^2 == tsquare
@test t^3 == tsquare*t
@test zero(t)/t == zero(t)
@test get_order(zero(t)/t) == get_order(t)
@test one(t)/one(t) == 1.0
#= @test tsquare/t == t
@test get_order(tsquare/t) == get_order(tsquare)-1
@test t/(t*3) == (1/3)*ot
@test get_order(t/(t*3)) == get_order(t)-1
@test t/3im == -tim/3
@test 1/(1-t) == Taylor0(ones(t.order+1))
@test Taylor0([0,1,1])/t == t+1
@test get_order(Taylor0([0,1,1])/t) == 1
@test (t+im)^2 == tsquare+2im*t-1
@test (t+im)^3 == Taylor0([-1im,-3,3im,1],15)
@test (t+im)^4 == Taylor0([1,-4im,-6,4im,1],15) =#
@test imag(tsquare+2im*t-1) == 2t
@test (Rational(1,2)*tsquare)[2] == 1//2
@test t^2/tsquare == ot
@test get_order(t^2/tsquare) == get_order(t)-2
@test ((1+t)^(1/3))[2]+1/9 ≤ tol1
@test (1.0-tsquare)^3 == (1.0-t)^3*(1.0+t)^3
@test (1-tsquare)^2 == (1+t)^2.0 * (1-t)^2.0
#@test (sqrt(1+t))[2] == -1/8
@test ((1-tsquare)^(1//2))^2 == 1-tsquare
@test ((1-t)^(1//4))[14] == -4188908511//549755813888
#= @test abs(((1+t)^3.2)[13] + 5.4021062656e-5) < tol1
@test Taylor0(BigFloat,5)/6 == 1im*Taylor0(5)/complex(0,BigInt(6))
@test Taylor0(BigFloat,5)/(6*Taylor0(3)) == 1/BigInt(6)
@test Taylor0(BigFloat,5)/(6im*Taylor0(3)) == -1im/BigInt(6)
@test isapprox((1+(1.5+t)/4)^(-2), inv(1+(1.5+t)/4)^2, rtol=eps(Float64))
@test isapprox((1+(big(1.5)+t)/4)^(-2), inv(1+(big(1.5)+t)/4)^2, rtol=eps(BigFloat))
@test isapprox((1+(1.5+t)/4)^(-2), inv(1+(1.5+t)/4)^2, rtol=eps(Float64))
@test isapprox((1+(big(1.5)+t)/4)^(-2), inv(1+(big(1.5)+t)/4)^2, rtol=eps(BigFloat))
@test isapprox((1+(1.5+t)/5)^(-2.5), inv(1+(1.5+t)/5)^2.5, rtol=eps(Float64))
@test isapprox((1+(big(1.5)+t)/5)^(-2.5), inv(1+(big(1.5)+t)/5)^2.5, rtol=2eps(BigFloat)) =#
# These tests involve some sort of factorization
@test t/(t+t^2) == 1/(1+t)
@test get_order(t/(t+t^2)) == get_order(1/(1+t))-1
#@test sqrt(t^2+t^3) == t*sqrt(1+t)
#@test get_order(sqrt(t^2+t^3)) == get_order(t) >> 1
#@test get_order(t*sqrt(1+t)) == get_order(t)
# @test (t^3+t^4)^(1/3) ≈ t*(1+t)^(1/3)
@test norm((t^3+t^4)^(1/3) - t*(1+t)^(1/3), Inf) < eps()
@test get_order((t^3+t^4)^(1/3)) == 5
@test ((t^3+t^4)^(1/3))[5] == -10/243
trational = ta(0//1)
@inferred ta(0//1) == Taylor0{Rational{Int}}
@test eltype(trational) == Taylor0{Rational{Int}}
@test TS.numtype(trational) == Rational{Int}
@test trational + 1//3 == Taylor0([1//3,1],15)
@test complex(3,1)*trational^2 == Taylor0([0//1,0//1,complex(3,1)//1],15)
@test trational^2/3 == Taylor0([0//1,0//1,1//3],15)
@test trational^3/complex(7,1) == Taylor0([0,0,0,complex(7//50,-1//50)],15)
@test sqrt(zero(t)) == zero(t)
@test isapprox( rem(4.1 + t,4)[0], 0.1 )
@test isapprox( mod(4.1 + t,4)[0], 0.1 )
@test isapprox( rem(1+Taylor0(Int,4),4.0)[0], 1.0 )
@test isapprox( mod(1+Taylor0(Int,4),4.0)[0], 1.0 )
@test isapprox( mod2pi(2pi+0.1+t)[0], 0.1 )
@test abs(ta(1)) == ta(1)
@test abs(ta(-1.0)) == -ta(-1.0)
@test taylor_expand(x->2x,order=10) == 2*Taylor0(10)
@test taylor_expand(x->x^2+1) == Taylor0(15)*Taylor0(15) + 1
@test evaluate(taylor_expand(cos,0.)) == cos(0.)
@test evaluate(taylor_expand(tan,pi/4)) == tan(pi/4)
@test eltype(taylor_expand(x->x^2+1,1)) == Taylor0{Int}
@test TS.numtype(taylor_expand(x->x^2+1,1)) == Int
tsq = t^2
update!(tsq,2.0)
@test tsq == (t+2.0)^2
update!(tsq,-2.0)
@test tsq == t^2
@test log(exp(tsquare)) == tsquare
@test exp(log(1-tsquare)) == 1-tsquare
@test log((1-t)^2) == 2*log(1-t)
@test real(exp(tim)) == cos(t)
@test imag(exp(tim)) == sin(t)
@test exp(conj(tim)) == cos(t)-im*sin(t) == exp(tim')
@test abs2(tim) == tsquare
# @test abs(tim) == t #sqrt int
@test isapprox(abs2(exp(tim)), ot)
@test isapprox(abs(exp(tim)), ot)
@test (exp(t))^(2im) == cos(2t)+im*sin(2t)
@test (exp(t))^Taylor0([-5.2im]) == cos(5.2t)-im*sin(5.2t)
@test getcoeff(convert(Taylor0{Rational{Int}},cos(t)),8) == 1//factorial(8)
@test abs((tan(t))[7]- 17/315) < tol1
@test abs((tan(t))[13]- 21844/6081075) < tol1
@test tan(1.3+t) ≈ sin(1.3+t)/cos(1.3+t)
@test cot(1.3+t) ≈ 1/tan(1.3+t)
@test evaluate(exp(Taylor0([0,1],17)),1.0) == 1.0*eeuler
@test evaluate(exp(Taylor0([0,1],1))) == 1.0
@test evaluate(exp(t),t^2) == exp(t^2)
@test evaluate(exp(Taylor0(BigFloat, 15)), t^2) == exp(Taylor0(BigFloat, 15)^2)
@test evaluate(exp(Taylor0(BigFloat, 15)), t^2) isa Taylor0{BigFloat}
#Test function-like behavior for Taylor0s
t17 = Taylor0([0,1],17)
myexpfun = exp(t17)
@test myexpfun(1.0) == 1.0*eeuler
@test myexpfun() == 1.0
@test myexpfun(t17^2) == exp(t17^2)
@test exp(t17^2)(t17) == exp(t17^2)
p = cos(t17)
q = sin(t17)
@test cos(-im*t)(1)+im*sin(-im*t)(1) == exp(-im*t)(im)
@test p(-im*t17)(1)+im*q(-im*t17)(1) == exp(-im*t17)(im)
cossin1 = x->p(q(x))
@test evaluate(p, evaluate(q, pi/4)) == cossin1(pi/4)
cossin2 = p(q)
@test evaluate(evaluate(p,q), pi/4) == cossin2(pi/4)
@test evaluate(p, q) == cossin2
@test p(q)() == evaluate(evaluate(p, q))
@test evaluate(p, q) == p(q)
@test evaluate(q, p) == q(p)
cs = x->cos(sin(x))
csdiff = (cs(t17)-cossin2(t17)).(-2:0.1:2)
@test norm(csdiff, 1) < 5e-15
a = [p,q]
@test a(0.1) == evaluate.([p,q],0.1)
@test a.(0.1) == a(0.1)
@test a.() == evaluate.([p, q])
@test a.() == [p(), q()]
@test a.() == a()
@test view(a, 1:1)() == [a[1]()]
vr = rand(2)
@test p.(vr) == evaluate.([p], vr)
Mr = rand(3,3,3)
@test p.(Mr) == evaluate.([p], Mr)
vr = rand(5)
@test p(vr) == p.(vr)
@test view(a, 1:1)(vr) == evaluate.([p],vr)
@test p(Mr) == p.(Mr)
@test p(Mr) == evaluate.([p], Mr)
taylor_a = Taylor0(Int,10)
taylor_x = exp(Taylor0(Float64,13))
@test taylor_x(taylor_a) == evaluate(taylor_x, taylor_a)
A_T1 = [t 2t 3t; 4t 5t 6t ]
@test evaluate(A_T1,1.0) == [1.0 2.0 3.0; 4.0 5.0 6.0]
@test evaluate(A_T1,1.0) == A_T1(1.0)
@test evaluate(A_T1) == A_T1()
@test A_T1(tsquare) == [tsquare 2tsquare 3tsquare; 4tsquare 5tsquare 6tsquare]
@test view(A_T1, :, :)(1.0) == A_T1(1.0)
@test view(A_T1, :, 1)(1.0) == A_T1[:,1](1.0)
@test sin(asin(tsquare)) == tsquare
@test tan(atan(tsquare)) == tsquare
@test atan(tan(tsquare)) == tsquare
@test atan(sin(tsquare)/cos(tsquare)) == atan(sin(tsquare), cos(tsquare))
@test constant_term(atan(sin(3pi/4+tsquare), cos(3pi/4+tsquare))) == 3pi/4
@test atan(sin(3pi/4+tsquare)/cos(3pi/4+tsquare)) - atan(sin(3pi/4+tsquare), cos(3pi/4+tsquare)) == -pi
@test sinh(asinh(tsquare)) ≈ tsquare
@test tanh(atanh(tsquare)) ≈ tsquare
@test atanh(tanh(tsquare)) ≈ tsquare
# @test asinh(t) ≈ log(t + sqrt(t^2 + 1)) #sqrt int
# @test cosh(asinh(t)) ≈ sqrt(t^2 + 1) #sqrt int
t_complex = Taylor0(Complex{Int}, 15) # for use with acosh, which in the Reals is only defined for x ≥ 1
@test cosh(acosh(t_complex)) ≈ t_complex
@test differentiate(acosh(t_complex)) ≈ 1/sqrt(t_complex^2 - 1)
@test acosh(t_complex) ≈ log(t_complex + sqrt(t_complex^2 - 1))
@test sinh(acosh(t_complex)) ≈ sqrt(t_complex^2 - 1)
@test asin(t) + acos(t) == pi/2
@test differentiate(acos(t)) == - 1/sqrt(1-Taylor0(t.order-1)^2)
@test get_order(differentiate(acos(t))) == t.order-1
@test - sinh(t) + cosh(t) == exp(-t)
@test sinh(t) + cosh(t) == exp(t)
@test evaluate(- sinh(t)^2 + cosh(t)^2 , rand()) == 1
@test evaluate(- sinh(t)^2 + cosh(t)^2 , 0) == 1
@test tanh(t + 0im) == -1im * tan(t*1im)
@test evaluate(tanh(t/2),1.5) == evaluate(sinh(t) / (cosh(t) + 1),1.5)
@test cosh(t) == real(cos(im*t))
@test sinh(t) == imag(sin(im*t))
ut = 1.0*t
tt = zero(ut)
TS.one!(tt, ut, 0)
@test tt[0] == 1.0
TS.one!(tt, ut, 1)
@test tt[1] == 0.0
#= # TS.abs!(tt, 1.0+ut, 0) # add! not defined
@test tt[0] == 1.0
#TS.add!(tt, ut, ut, 1) # add! not defined
@test tt[1] == 2.0
TS.add!(tt, -3.0, 0) # add! not defined
@test tt[0] == -3.0
TS.add!(tt, -3.0, 1) # add! not defined
@test tt[1] == 0.0
TS.subst!(tt, ut, ut, 1)
@test tt[1] == 0.0
TS.subst!(tt, -3.0, 0)
@test tt[0] == 3.0
TS.subst!(tt, -2.5, 1) =#
@test tt[1] == 0.0
iind, cind = TS.divfactorization(ut, ut)
@test iind == 1
@test cind == 1.0
TS.div!(tt, ut, ut, 0)
@test tt[0] == cind
TS.div!(tt, 1+ut, 1+ut, 0)
@test tt[0] == 1.0
TS.div!(tt, 1, 1+ut, 0)
@test tt[0] == 1.0
TS.pow!(tt, 1.0+t, 1.5, 0)
@test tt[0] == 1.0
TS.pow!(tt, 0.0*t, 1.5, 0)
@test tt[0] == 0.0
TS.pow!(tt, 0.0+t, 18, 0)
@test tt[0] == 0.0
TS.pow!(tt, 1.0+t, 1.5, 0)
@test tt[0] == 1.0
TS.pow!(tt, 1.0+t, 0.5, 1)
@test tt[1] == 0.5
TS.pow!(tt, 1.0+t, 0, 0)
@test tt[0] == 1.0
TS.pow!(tt, 1.0+t, 1, 1)
@test tt[1] == 1.0
tt = zero(ut)
TS.pow!(tt, 1.0+t, 2, 0)
@test tt[0] == 1.0
TS.pow!(tt, 1.0+t, 2, 1)
@test tt[1] == 2.0
TS.pow!(tt, 1.0+t, 2, 2)
@test tt[2] == 1.0
TS.sqrt!(tt, 1.0+t, 0, 0)
@test tt[0] == 1.0
TS.sqrt!(tt, 1.0+t, 0)
@test tt[0] == 1.0
TS.exp!(tt, 1.0*t, 0)
@test tt[0] == exp(t[0])
TS.log!(tt, 1.0+t, 0)
@test tt[0] == 0.0
ct = zero(ut)
TS.sincos!(tt, ct, 1.0*t, 0)
@test tt[0] == sin(t[0])
@test ct[0] == cos(t[0])
TS.tan!(tt, 1.0*t, ct, 0)
@test tt[0] == tan(t[0])
@test ct[0] == tan(t[0])^2
TS.asin!(tt, 1.0*t, ct, 0)
@test tt[0] == asin(t[0])
@test ct[0] == sqrt(1.0-t[0]^2)
TS.acos!(tt, 1.0*t, ct, 0)
@test tt[0] == acos(t[0])
@test ct[0] == sqrt(1.0-t[0]^2)
TS.atan!(tt, ut, ct, 0)
@test tt[0] == atan(t[0])
@test ct[0] == 1.0+t[0]^2
TS.sinhcosh!(tt, ct, ut, 0)
@test tt[0] == sinh(t[0])
@test ct[0] == cosh(t[0])
TS.tanh!(tt, ut, ct, 0)
@test tt[0] == tanh(t[0])
@test ct[0] == tanh(t[0])^2
v = [sin(t), exp(-t)]
vv = Vector{Float64}(undef, 2)
@test evaluate!(v, zero(Int), vv) == nothing
@test vv == [0.0,1.0]
@test evaluate!(v, 0.0, vv) == nothing
@test vv == [0.0,1.0]
@test evaluate!(v, 0.0, view(vv, 1:2)) == nothing
@test vv == [0.0,1.0]
@test evaluate(v) == vv
@test isapprox(evaluate(v, complex(0.0,0.2)),
[complex(0.0,sinh(0.2)),complex(cos(0.2),sin(-0.2))], atol=eps(), rtol=0.0)
m = [sin(t) exp(-t); cos(t) exp(t)]
m0 = 0.5
#= mres = Matrix{Float64}(undef, 2, 2)
mres_expected = [sin(m0) exp(-m0); cos(m0) exp(m0)]
@test evaluate!(m, m0, mres) == nothing
@test mres == mres_expected =#
ee_ta = exp(ta(1.0))
@test get_order(differentiate(ee_ta, 0)) == 15
@test get_order(differentiate(ee_ta, 1)) == 14
@test get_order(differentiate(ee_ta, 16)) == 0
@test differentiate(ee_ta, 0) == ee_ta
expected_result_approx = Taylor0(ee_ta[0:10])
@test differentiate(exp(ta(1.0)), 5) ≈ expected_result_approx atol=eps() rtol=0.0
expected_result_approx = Taylor0(zero(ee_ta),0)
@test differentiate(ee_ta, 16) == Taylor0(zero(ee_ta),0)
@test eltype(differentiate(ee_ta, 16)) == eltype(ee_ta)
ee_ta = exp(ta(1.0pi))
expected_result_approx = Taylor0(ee_ta[0:12])
@test differentiate(ee_ta, 3) ≈ expected_result_approx atol=eps(16.0) rtol=0.0
expected_result_approx = Taylor0(ee_ta[0:5])
@test differentiate(exp(ta(1.0pi)), 10) ≈ expected_result_approx atol=eps(64.0) rtol=0.0
@test differentiate(exp(ta(1.0)), 5)() == exp(1.0)
@test differentiate(exp(ta(1.0pi)), 3)() == exp(1.0pi)
@test isapprox(derivative(exp(ta(1.0pi)), 10)() , exp(1.0pi) )
@test differentiate(5, exp(ta(1.0))) == exp(1.0)
@test differentiate(3, exp(ta(1.0pi))) == exp(1.0pi)
@test isapprox(differentiate(10, exp(ta(1.0pi))) , exp(1.0pi) )
@test integrate(differentiate(exp(t)),1) == exp(t)
@test integrate(cos(t)) == sin(t)
@test promote(ta(0.0), t) == (ta(0.0),ta(0.0))
@test norm((inverse(exp(t)-1) - log(1+t)).coeffs) < 2tol1
cfs = [(-n)^(n-1)/factorial(n) for n = 1:15]
@test norm(inverse(t*exp(t))[1:end]./cfs .- 1) < 4tol1
@test_throws ArgumentError Taylor0([1,2,3], -2)
@test_throws DomainError abs(ta(big(0)))
@test_throws ArgumentError 1/t
@test_throws ArgumentError zt/zt
@test_throws DomainError t^1.5
@test_throws ArgumentError t^(-2)
@test_throws DomainError sqrt(t)
@test_throws DomainError log(t)
@test_throws ArgumentError cos(t)/sin(t)
@test_throws AssertionError differentiate(30, exp(ta(1.0pi)))
@test_throws DomainError inverse(exp(t))
@test_throws DomainError abs(t)
use_show_default(true)
aa = sqrt(2)+Taylor0(2)
@test string(aa) == "Taylor0{Float64}([1.4142135623730951, 1.0, 0.0], 2)"
@test string([aa, aa]) ==
"Taylor0{Float64}[Taylor0{Float64}([1.4142135623730951, 1.0, 0.0], 2), " *
"Taylor0{Float64}([1.4142135623730951, 1.0, 0.0], 2)]"
use_show_default(false)
@test string(aa) == " 1.4142135623730951 + 1.0 t + 𝒪(t³)"
set_Taylor0_varname(" x ")
@test string(aa) == " 1.4142135623730951 + 1.0 x + 𝒪(x³)"
set_Taylor0_varname("t")
displayBigO(false)
@test string(ta(-3)) == " - 3 + 1 t "
@test string(ta(0)^3-3) == " - 3 + 1 t³ "
#@test TS.pretty_print(ta(3im)) == " ( 0 + 3im ) + ( 1 + 0im ) t "
@test string(Taylor0([1,2,3,4,5], 2)) == string(Taylor0([1,2,3]))
displayBigO(true)
@test string(ta(-3)) == " - 3 + 1 t + 𝒪(t¹⁶)"
@test string(ta(0)^3-3) == " - 3 + 1 t³ + 𝒪(t¹⁶)"
#@test TS.pretty_print(ta(3im)) == " ( 0 + 3im ) + ( 1 + 0im ) t + 𝒪(t¹⁶)"
@test string(Taylor0([1,2,3,4,5], 2)) == string(Taylor0([1,2,3]))
a = collect(1:12)
t_a = Taylor0(a,15)
t_C = complex(3.0,4.0) * t_a
rnd = rand(10)
@test typeof( norm(Taylor0(rnd)) ) == Float64
@test norm(Taylor0(rnd)) > 0
@test norm(t_a) == norm(a)
@test norm(Taylor0(a,15),3) == sum((a.^3))^(1/3)
@test norm(t_a,Inf) == 12
@test norm(t_C) == norm(complex(3.0,4.0)*a)
# @test TS.rtoldefault(Taylor0{Int}) == 0
# @test TS.rtoldefault(Taylor0{Float64}) == sqrt(eps(Float64))
#@test TS.rtoldefault(Taylor0{BigFloat}) == sqrt(eps(BigFloat))
# @test TS.real(Taylor0{Float64}) == Taylor0{Float64}
# @test TS.real(Taylor0{Complex{Float64}}) == Taylor0{Float64}
@test isfinite(t_C)
@test isfinite(t_a)
@test !isfinite( Taylor0([0, Inf]) )
@test !isfinite( Taylor0([NaN, 0]) )
b = convert(Vector{Float64}, a)
b[3] += eps(10.0)
b[5] -= eps(10.0)
t_b = Taylor0(b,15)
t_C2 = t_C+eps(100.0)
t_C3 = t_C+eps(100.0)*im
@test isapprox(t_C, t_C)
@test t_a ≈ t_a
@test t_a ≈ t_b
@test t_C ≈ t_C2
@test t_C ≈ t_C3
@test t_C3 ≈ t_C2
t = Taylor0(25)
p = sin(t)
q = sin(t+eps())
@test t ≈ t
@test t ≈ t+sqrt(eps())
@test isapprox(p, q, atol=eps())
tf = Taylor0(35)
@test Taylor0([180.0, rad2deg(1.0)], 35) == rad2deg(pi+tf)
@test sin(pi/2+deg2rad(1.0)tf) == sin(deg2rad(90+tf))
a = Taylor0(rand(10))
b = Taylor0(rand(10))
c = deepcopy(a)
TS.deg2rad!(b, a, 0)
@test a == c
@test a[0]*(pi/180) == b[0]
TS.deg2rad!.(b, a, [0,1,2])
# @test a == c
# for i in 0:2
# @test a[i]*(pi/180) == b[i]
# end
a = Taylor0(rand(10))
b = Taylor0(rand(10))
c = deepcopy(a)
# TS.rad2deg!(b, a, 0)
@test a == c
@test a[0]*(180/pi) == b[0]
# TS.rad2deg!.(b, a, [0,1,2])
# @test a == c
# for i in 0:2
# @test a[i]*(180/pi) == b[i]
# end
# Test additional Taylor0 constructors
@test Taylor0{Float64}(true) == Taylor0([1.0])
@test Taylor0{Float64}(false) == Taylor0([0.0])
@test Taylor0{Int}(true) == Taylor0([1])
@test Taylor0{Int}(false) == Taylor0([0])
# Test fallback pretty_print
st = Taylor0([SymbNumber(:x₀), SymbNumber(:x₁)])
@test string(st) == " SymbNumber(:x₀) + SymbNumber(:x₁) t + 𝒪(t²)"
end
@testset "Test inv for Matrix{Taylor0{Float64}}" begin
t = Taylor0(5)
a = Diagonal(rand(0:10,3)) + rand(3, 3)
ainv = inv(a)
b = Taylor0.(a, 5)
binv = inv(b)
c = Symmetric(b)
cinv = inv(c)
tol = 1.0e-11
for its = 1:10
a .= Diagonal(rand(2:12,3)) + rand(3, 3)
ainv .= inv(a)
b .= Taylor0.(a, 5)
binv .= inv(b)
c .= Symmetric(Taylor0.(a, 5))
cinv .= inv(c)
@test norm(binv - ainv, Inf) ≤ tol
@test norm(b*binv - I, Inf) ≤ tol
@test norm(binv*b - I, Inf) ≤ tol
@test norm(triu(b)*inv(UpperTriangular(b)) - I, Inf) ≤ tol
@test norm(inv(LowerTriangular(b))*tril(b) - I, Inf) ≤ tol
ainv .= inv(Symmetric(a))
@test norm(cinv - ainv, Inf) ≤ tol
@test norm(c*cinv - I, Inf) ≤ tol
@test norm(cinv*c - I, Inf) ≤ tol
@test norm(triu(c)*inv(UpperTriangular(c)) - I, Inf) ≤ tol
@test norm(inv(LowerTriangular(c))*tril(c) - I, Inf) ≤ tol
b .= b .+ t
binv .= inv(b)
@test norm(b*binv - I, Inf) ≤ tol
@test norm(binv*b - I, Inf) ≤ tol
@test norm(triu(b)*inv(triu(b)) - I, Inf) ≤ tol
@test norm(inv(tril(b))*tril(b) - I, Inf) ≤ tol
c .= Symmetric(b)
cinv .= inv(c)
@test norm(c*cinv - I, Inf) ≤ tol
@test norm(cinv*c - I, Inf) ≤ tol
end
end
#= @testset "Matrix multiplication for Taylor0" begin
order = 30
n1 = 100
k1 = 90
order = max(n1,k1)
B1 = randn(n1,order)
Y1 = randn(k1,order)
A1 = randn(k1,n1)
for A in (A1,sparse(A1))
# B and Y contain elements of different orders
B = Taylor0{Float64}[Taylor0(collect(B1[i,1:i]),i) for i=1:n1]
Y = Taylor0{Float64}[Taylor0(collect(Y1[k,1:k]),k) for k=1:k1]
Bcopy = deepcopy(B)
mul!(Y,A,B)
# do we get the same result when using the `A*B` form?
@test A*B≈Y
# Y should be extended after the multilpication
@test reduce(&, [y1.order for y1 in Y] .== Y[1].order)
# B should be unchanged
@test B==Bcopy
# is the result compatible with the matrix multiplication? We
# only check the zeroth order of the Taylor series.
y1=sum(Y)[0]
Y=A*B1[:,1]
y2=sum(Y)
# There is a small numerical error when comparing the generic
# multiplication and the specialized version
@test abs(y1-y2) < n1*(eps(y1)+eps(y2))
@test_throws DimensionMismatch mul!(Y,A[:,1:end-1],B)
@test_throws DimensionMismatch mul!(Y,A[1:end-1,:],B)
@test_throws DimensionMismatch mul!(Y,A,B[1:end-1])
@test_throws DimensionMismatch mul!(Y[1:end-1],A,B)
end
end =#
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 2472 |
using BenchmarkTools
import Base: eachindex, getindex, setindex!
struct MyType{T<:Number}
coeffs :: Array{T,1}
size :: Int
end
getindex(a::MyType, n::Int) = a.coeffs[n+1]
setindex!(a::MyType{T}, x::T, n::Int) where {T<:Number} = a.coeffs[n+1] = x
@inline firstindex(a::MyType) = 0
@inline lastindex(a::MyType) = a.size
@inline eachindex(a::MyType) = firstindex(a):lastindex(a)
function mulTfoldl(res::P, bs...) where {P<:MyType}
l = length(bs)
i = 2; l == i && return res
i = 3; l == i && return mulTT(res, bs[1],bs[end-1],bs[end])
i = 4; l == i && return mulTT(mulTT(res, bs[1],bs[end-1],bs[end]),bs[2],bs[end-1],bs[end])
i = 5; l == i && return mulTT(mulTT(mulTT(res, bs[1],bs[end-1],bs[end]),bs[2],bs[end-1],bs[end]),bs[3],bs[end-1],bs[end])
i = 6; l == i && return mulTT(mulTT(mulTT(mulTT(res, bs[1],bs[end-1],bs[end]),bs[2],bs[end-1],bs[end]),bs[3],bs[end-1],bs[end]),bs[4],bs[end-1],bs[end])
end
function mulTT(a::P, b::R, c::Q, xs...)where {P,Q,R <:Union{MyType,Number}}
if length(xs)>1
mulTfoldl( mulTT( mulTT(a,b,xs[end-1],xs[end]) , c,xs[end-1] ,xs[end] ), xs...)
end
end
function mulTT(a::MyType{T}, b::T,cache1::MyType{T},cache2::MyType{T}) where {T<:Number}
fill!(cache2.coeffs, b)
@__dot__ cache1.coeffs = a.coeffs * cache2.coeffs ##fixed broadcast dimension mismatch
return cache1
end
mulTT(a::T,b::MyType{T}, cache1::MyType{T},cache2::MyType{T}) where {T<:Number} = mulTT(b , a,cache1,cache2)
function mulTT(a::MyType{T}, b::MyType{T},cache1::MyType{T},cache2::MyType{T}) where {T<:Number}
for k in eachindex(a)
@inbounds cache2[k] = a[0] * b[k]
@inbounds for i = 1:k
cache2[k] += a[i] * b[k-i]
end
end
@__dot__ cache1.coeffs = cache2.coeffs
return cache1
end
function mulTT(a::T, b::T,cache1::MyType{T},cache2::MyType{T}) where {T<:Number}
cache1[0]=a*b
return cache1
end
av = vec(3(rand(1,3) .- 1.5))
bv = vec(3(rand(1,3) .- 1.5))
cv = vec(3(rand(1,3) .- 1.5))
dv = vec(3(rand(1,3) .- 1.5))
a0 = MyType(av,2)
b0 = MyType(bv,2)
c0 = MyType(cv,2)
d0 = MyType(dv,2)
e=3rand() - 1.5
f=3rand() - 1.5
cache=[MyType([0.0,0.0,0.0],2),MyType([0.0,0.0,0.0],2)]
function boundaryTest(a0::MyType{Float64},b0::MyType{Float64},c0::MyType{Float64},d0::MyType{Float64},cache::Vector{MyType{Float64}},e::Float64,f::Float64)
@show mulTT(e, f, a0, b0, e, c0,d0, cache[1], cache[2])
end
boundaryTest(a0,b0,c0,d0,cache,e,f) | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 180 | using qss
using StaticArrays
using BenchmarkTools
t2=Taylor0([2.0,2.0,3.0],2)
t1=Taylor0([1.0,1.1],1)
#= cache1=Taylor0([0.0,0.0,0.0],2)
cache2=Taylor0([0.0,0.0,0.0],2) =#
@show t1 | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 169 |
#using qss
function testmul(t::Taylor0{Float64})
t1=Taylor0([1.0,2.0,0.0],2)
res=t*t1
end
function testmul()
t1=Taylor0([1.0,2.0,0.0],2)
res=t1*t1
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1628 | #import Pkg; Pkg.add("Documenter");Pkg.develop(url="https://github.com/mongibellili/QuantizedSystemSolver.git")
using Documenter
using QuantizedSystemSolver
# Set up deployment environment variables
#const DOCUMENTER_KEY = ENV["DOCUMENTER_KEY"] # Load the private key from environment variables
# Function to deploy documentation
makedocs(
sitename = "Quantized System Solver",
modules = [QuantizedSystemSolver],
pages = [
"Home" => "index.md",
"Tutorial" => "userGuide.md",
"Developer Guide" => "developerGuide.md",
"Examples" => "examples.md",
]
)
deploydocs(
repo = "github.com/mongibellili/QuantizedSystemSolver.git",
branch = "gh-pages",
# deploy_key = ENV["DOCUMENTER_KEY"] # Provide the deployment key explicitly
)
# Perform deployment using SSH key authentication
# run(`git config --global user.email "[email protected]"`)
# run(`git config --global user.name "mongibellili"`)
# cd("C:/Users/belli/Documents/mongibellili.github.io")
# run(`pwd`)
# cd("C:/Users/belli/.julia/dev/QuantizedSystemSolver/docs/build/")
# run(`pwd`)
# Copy the generated documentation files to the repository
# run(`cp -r "C:/Users/belli/.julia/dev/QuantizedSystemSolver/docs/build/*"`) # Adjust the path based on your actual build directory
# Add, commit, and push the changes
# run(`git add .`)
# run(`git commit -m "Deploy documentation"`)
# run(`git push origin gh-pages`) # Push to the gh-pages branch (or your designated branch)
# Main execution block
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 3426 | module QuantizedSystemSolver
const global VERBOSE=false # later move to solve to allow user to use it.
const global DEBUG=false
using RuntimeGeneratedFunctions
using StaticArrays
using SymEngine
using PolynomialRoots
using ExprTools #combineddef
using MacroTools: postwalk,prewalk, @capture#, isexpr,
using Plots: plot!,plot,savefig
using Dates: now,year,month,day,hour,minute,second #fortimestamp
RuntimeGeneratedFunctions.init(@__MODULE__)
##### this section belongs to taylorseries subcomponent
import Base: ==, +, -, *, /, ^
#import Base: Base.gc_enable
import Base: iterate, size, eachindex, firstindex, lastindex,
length, getindex, setindex!
import Base: sqrt, exp, log, sin, cos, sincos, tan,
asin, acos, atan, sinh, cosh, tanh, atanh, asinh, acosh,
zero, one, zeros, ones, isinf, isnan, iszero,
convert, promote_rule, promote, show,abs
##### list of public (API)
export NLodeProblem,solve ,NLODEProblem,QSSAlgorithm,Sol# docs used NLODEProblem, QSSAlgorithm
export qss1,qss2,qss3,liqss1,liqss2,liqss3,saveat,nmliqss1,nmliqss2,nmliqss3
export save_Sol,plot_Sol,getPlot,getPlot!,save_SolSum,solInterpolated,plot_SolSum
export getError,getErrorByRodas,getAllErrorsByRefs,getAverageErrorByRefs,getErrorByRefs
export Taylor0,mulT,mulTT,createT,addsub,negateT,subsub,subadd,subT,addT,muladdT,mulsub,divT,powerT,constructIntrval,getQfromAsymptote,iterationH,testTaylor # for testing
##### include section of Taylor series subcomponent
include("ownTaylor/constructors.jl")
include("ownTaylor/arithmetic.jl")
include("ownTaylor/arithmeticT.jl")
include("ownTaylor/functions.jl")
include("ownTaylor/functionsT.jl")
include("ownTaylor/power.jl")
include("ownTaylor/powerT.jl")
##### Utils
include("Utils/rootfinders/SimUtils.jl")
##### Common
include("Common/TaylorEquationConstruction.jl")
include("Common/QSSNL_AbstractTypes.jl")
include("Common/Solution.jl")
include("Common/SolutionPlot.jl")
include("Common/SolutionError.jl")
include("Common/Helper_QSSNLProblem.jl")
include("Common/Helper_QSSNLDiscreteProblem.jl")
include("Common/QSSNLContinousProblem.jl")
include("Common/QSSNLdiscrProblem.jl")
include("Common/QSS_Algorithm.jl")
include("Common/QSS_data.jl")
include("Common/Scheduler.jl")
##### integrators
include("dense/NL_integrators/NL_QSS_Integrator.jl")
include("dense/NL_integrators/NL_QSS_discreteIntegrator.jl")
# implicit integrator when large entries on the main diagonal of the jacobian
include("dense/NL_integrators/NL_LiQSS_Integrator.jl")
include("dense/NL_integrators/NL_LiQSS_discreteIntegrator.jl")
# implicit integrator when large entries NOT on the main diagonal of the jacobian
include("dense/NL_integrators/NL_nmLiQSS_Integrator.jl")
include("dense/NL_integrators/NL_nmLiQSS_discreteIntegrator.jl")
##### Quantizers
include("dense/Quantizers/Quantizer_Common.jl")
include("dense/Quantizers/QSS_quantizer.jl")
include("dense/Quantizers/LiQSS_quantizer1.jl")
include("dense/Quantizers/LiQSS_quantizer2.jl")
#include("dense/Quantizers/LiQSS_quantizer3.jl")
include("dense/Quantizers/mLiQSS_quantizer1.jl")
include("dense/Quantizers/mLiQSS_quantizer2.jl")
#include("dense/Quantizers/mLiQSS_quantizer3.jl")
##### main entrance/ Interface
include("Interface/indexMacro.jl")
include("Interface/QSS_Solve.jl")
end # module
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 7095 | struct EventDependencyStruct
id::Int
evCont::Vector{Int} #index tracking used for HD & HZ. Also it is used to update q,quantum,recomputeNext when x is modified in an event
evDisc::Vector{Int} #index tracking used for HD & HZ.
evContRHS::Vector{Int} #index tracking used to update other Qs before executing the event
end
# the following functions handle discrete problems
# to extract jac & dD....SD can be extracted from jac later
function extractJacDepNormal(varNum::Int,rhs::Union{Symbol,Int,Expr},jac :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},exacteJacExpr :: Dict{Expr,Union{Float64,Int,Symbol,Expr}},symDict::Dict{Symbol,Expr},dD :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}})
jacSet=Set{Union{Int,Symbol,Expr}}()
#jacDiscrSet=Set{Union{Int,Symbol,Expr}}()
m=postwalk(rhs) do a #
if a isa Expr && a.head == :ref && a.args[1]==:q# q[2]
push!(jacSet, (a.args[2])) # du[varNum=1]=rhs=u[5]+u[2] : 2 and 5 are stored in jacset one at a time
a=eliminateRef(a)#q[i] -> qi
elseif a isa Expr && a.head == :ref && a.args[1]==:d# d[3]
# push!(jacDiscrSet, (a.args[2])) #
dDset=Set{Union{Int,Symbol,Expr}}()
if haskey(dD, (a.args[2])) # dict dD already contains key a.args[2] (in this case var 3)
dDset=get(dD,(a.args[2]),dDset) # if var d3 first time to influence some var, dDset is empty, otherwise get its set of influences
end
push!(dDset, varNum) # d3 also influences varNum
dD[(a.args[2])]=dDset #update the dict
a=eliminateRef(a)#d[i] -> di
end
return a
end
# extract the jac
basi = convert(Basic, m) # m ready: all refs are symbols
for i in jacSet # jacset contains vars in RHS
symarg=symbolFromRef(i) # specific to elements in jacSet: get q1 from 1 for exple
coef = diff(basi, symarg) # symbolic differentiation: returns type Basic
coefstr=string(coef);coefExpr=Meta.parse(coefstr)#convert from basic to expression
jacEntry=restoreRef(coefExpr,symDict)# get back ref: qi->q[i][0] ...0 because later in exactJac fun cache[1]::Float64=jacEntry
exacteJacExpr[:(($varNum,$i))]=jacEntry # entry (varNum,i) is jacEntry
end
if length(jacSet)>0 jac[varNum]=jacSet end
#if length(jacDiscrSet)>0 jacDiscr[varNum]=jacDiscrSet end
end
# like above except (b,niter) instead of varNum
function extractJacDepLoop(b::Int,niter::Int,rhs::Union{Symbol,Int,Expr},jac :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},exacteJacExpr :: Dict{Expr,Union{Float64,Int,Symbol,Expr}},symDict::Dict{Symbol,Expr},dD :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}})
jacSet=Set{Union{Int,Symbol,Expr}}()
m=postwalk(rhs) do a
if a isa Expr && a.head == :ref && a.args[1]==:q#
push!(jacSet, (a.args[2])) #
a=eliminateRef(a)#q[i] -> qi
elseif a isa Expr && a.head == :ref && a.args[1]==:d
if a.args[2] isa Int #for now allow only d[integer]
dDset=Set{Union{Int,Symbol,Expr}}()
if haskey(dD, (a.args[2]))
dDset=get(dD,(a.args[2]),dDset)
end
push!(dDset, :(($b,$niter)))
dD[(a.args[2])]=dDset
end
a=eliminateRef(a)#q[i] -> qi
end
return a
end
basi = convert(Basic, m)
for i in jacSet
symarg=symbolFromRef(i);
coef = diff(basi, symarg)
coefstr=string(coef);
coefExpr=Meta.parse(coefstr)
jacEntry=restoreRef(coefExpr,symDict)
exacteJacExpr[:((($b,$niter),$i))]=jacEntry
end
jac[:(($b,$niter))]=jacSet
end
function extractZCJacDepNormal(counter::Int,zcf::Expr,zcjac :: Vector{Vector{Int}},SZ ::Dict{Int,Set{Int}},dZ :: Dict{Int,Set{Int}})
zcjacSet=Set{Int}()
#zcjacDiscrSet=Set{Int}()
postwalk(zcf) do a #
if a isa Expr && a.head == :ref && a.args[1]==:q#
push!(zcjacSet, (a.args[2])) #
SZset=Set{Int}()
if haskey(SZ, (a.args[2]))
SZset=get(SZ,(a.args[2]),SZset)
end
push!(SZset, counter)
SZ[(a.args[2])]=SZset
elseif a isa Expr && a.head == :ref && a.args[1]==:d#
# push!(zcjacDiscrSet, (a.args[2])) #
dZset=Set{Int}()
if haskey(dZ, (a.args[2]))
dZset=get(dZ,(a.args[2]),dZset)
end
push!(dZset, counter)
dZ[(a.args[2])]=dZset
end
return a
end
push!(zcjac,collect(zcjacSet))#convert set to vector
#push!(zcjacDiscr,collect(zcjacDiscrSet))
end
function createDependencyToEventsDiscr(dD::Vector{Vector{Int}},dZ::Dict{Int64, Set{Int64}},eventDep::Vector{EventDependencyStruct})
Y=length(eventDep)
lendD=length(dD)
HD2 = Vector{Vector{Int}}(undef, Y)
HZ2 = Vector{Vector{Int}}(undef, Y)
for ii=1:Y
HD2[ii] =Vector{Int}()# define it so i can push elements as i find them below
HZ2[ii] =Vector{Int}()# define it so i can push elements as i find them below
end
for j=1:Y
hdSet=Set{Int}()
hzSet=Set{Int}()
evdiscrete=eventDep[j].evDisc
for i in evdiscrete
if i<=lendD
for k in dD[i]
push!(hdSet,k)
end
end
tempSet=Set{Int}()
if haskey(dZ, i)
tempSet=get(dZ,i,tempSet)
end
for kk in tempSet
push!(hzSet,kk)
end
end
HD2[j] =collect(hdSet)# define it so i can push elements as i find them below
HZ2[j] =collect(hzSet)
end #end for j (events)
return (HZ2,HD2)
end
function createDependencyToEventsCont(SD::Vector{Vector{Int}},sZ::Dict{Int64, Set{Int64}},eventDep::Vector{EventDependencyStruct})
Y=length(eventDep)
HD2 = Vector{Vector{Int}}(undef, Y)
HZ2 = Vector{Vector{Int}}(undef, Y)
for ii=1:Y
HD2[ii] =Vector{Int}()# define it so i can push elements as i find them below
HZ2[ii] =Vector{Int}()# define it so i can push elements as i find them below
end
for j=1:Y
hdSet=Set{Int}()
hzSet=Set{Int}()
evContin=eventDep[j].evCont
for i in evContin
for k in SD[i]
push!(hdSet,k)
end
tempSet=Set{Int}()
if haskey(sZ, i)
tempSet=get(sZ,i,tempSet)
end
for kk in tempSet
push!(hzSet,kk)
end
end
HD2[j] =collect(hdSet)# define it so i can push elements as i find them below
HZ2[j] =collect(hzSet)
end #end for j (events)
return (HZ2,HD2)
end
#function unionDependency(HZ1::SVector{Y,SVector{Z,Int}},HZ2::SVector{Y,SVector{Z,Int}})where{Z,Y}
function unionDependency(HZ1::Vector{Vector{Int}},HZ2::Vector{Vector{Int}})
Y=length(HZ1)
HZ = Vector{Vector{Int}}(undef, Y)
for ii=1:Y
HZ[ii] =Vector{Int}()# define it so i can push elements as i find them below
end
for j=1:Y
hzSet=Set{Int}()
for kk in HZ1[j]
push!(hzSet,kk)
end
for kk in HZ2[j]
push!(hzSet,kk)
end
HZ[j]=collect(hzSet)
end
HZ
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 6457 | function changeExprToFirstValue(ex::Expr)##
newEx=postwalk(ex) do a # change u[1] to u[1][0]
if a isa Expr && a.head == :ref && a.args[1]==:q # change q[1] to q[1][0]
outerRef=Expr(:ref)
push!(outerRef.args,a)
push!(outerRef.args,:(0))
a=outerRef
end
return a
end
newEx
end
function eliminateRef(a)#q[i] -> qi
if a.args[2] isa Expr
if a.args[2].args[1]==:+
a=Symbol((a.args[1]),(a.args[2].args[2]), "plus",(a.args[2].args[3]))
elseif a.args[2].args[1]==:-
a=Symbol((a.args[1]),(a.args[2].args[2]), "minus",(a.args[2].args[3]))
elseif a.args[2].args[1]==:*
a=Symbol((a.args[1]),(a.args[2].args[2]), "times",(a.args[2].args[3]))
elseif a.args[2].args[1]==:/
#a=Symbol((a.args[1]),(a.args[2].args[2]), "over",(a.args[2].args[3]))
Error("parameter_index division is not implemented Yet")
end
else
a=Symbol((a.args[1]),(a.args[2]))
end
return a
end
function symbolFromRef(refEx)#refEx is i+1 in q[i+1] for example
if refEx isa Expr #
if refEx.args[1]==:+
refEx=Symbol("q",(refEx.args[2]), "plus",(refEx.args[3]))
elseif refEx.args[1]==:-
refEx=Symbol("q",(refEx.args[2]), "minus",(refEx.args[3]))
elseif refEx.args[1]==:*
refEx=Symbol("q",(refEx.args[2]), "times",(refEx.args[3]))
#= elseif refEx.args[1]==:/
#refEx=Symbol("q",(refEx.args[2]), "over",(refEx.args[3]))
Error("parameter_index division is not implemented Yet") =#
end
else
refEx=Symbol("q",(refEx))
end
return refEx
end
function symbolFromRefd(refEx)#refEx is i+1 in q[i+1] for example
if refEx isa Expr #
if refEx.args[1]==:+
refEx=Symbol("d",(refEx.args[2]), "plus",(refEx.args[3]))
elseif refEx.args[1]==:-
refEx=Symbol("d",(refEx.args[2]), "minus",(refEx.args[3]))
elseif refEx.args[1]==:*
refEx=Symbol("d",(refEx.args[2]), "times",(refEx.args[3]))
#= elseif refEx.args[1]==:/
#refEx=Symbol("d",(refEx.args[2]), "over",(refEx.args[3]))
Error("parameter_index division is not implemented Yet") =#
end
else
refEx=Symbol("d",(refEx))
end
return refEx
end
function restoreRef(coefExpr,symDict)
newEx=postwalk(coefExpr) do element#
if element isa Symbol && !(element in (:+,:-,:*,:/)) && haskey(symDict, element) && element != :d
element=symDict[element]
element=changeExprToFirstValue(element)# change u[1] to u[1][0]
elseif element== :d
element=symDict[element]
end
return element
end#end postwalk
newEx
end
function changeVarNames_params(ex::Expr,stateVarName::Symbol,muteVar::Symbol,param::Dict{Symbol,Union{Float64,Expr}},symDict::Dict{Symbol,Expr})#
newEx=postwalk(ex) do element#postwalk to change var names and parameters
if element isa Symbol
if haskey(param, element)#symbol is a parameter
element=copy(param[element]) # copy needed in the case symbol id=expression substitued in equations...do not want all eqs reference same expression...ie if 1 eq changes, other eqs change
elseif element==stateVarName #symbol is a var
element=:q
elseif element==:discrete #symbol is a discr var
element=:d
elseif element==muteVar #symbol is a mute var
element=:i
#= else # + - * /
=#
end
elseif element isa Expr && element.head == :ref && element.args[1]==:q#
symarg=symbolFromRef(element.args[2]) #q[i] -> qi
symDict[symarg]=element #store this translation q[i] <-> qi for later use
elseif element isa Expr && element.head == :ref && element.args[1]==:d#
symarg=symbolFromRefd(element.args[2]) #d[i] -> di
symDict[symarg]=element #store this translation d[i] <-> di
end
return element
end#end postwalk
newEx
end
function changeVarNames_params(ex::Expr,stateVarName::Symbol,muteVar::Symbol,param::Dict{Symbol,Union{Float64,Expr}})######special for if statements and events
newEx=postwalk(ex) do element#postwalk to change var names and parameters
if element isa Symbol
if haskey(param, element)#symbol is a parameter
element=copy(param[element])
elseif element==stateVarName #symbol is a var
element=:q
elseif element==:discrete #symbol is a discr var
element=:d
elseif element==muteVar #symbol is a mute var
element=:i
end
end
return element
end#end postwalk
newEx
end
# these 2 function handle continuous problems only
function extractJacDepNormal(varNum::Int,rhs::Union{Int,Expr},jac :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}, exacteJacExpr :: Dict{Expr,Union{Float64,Int,Symbol,Expr}},symDict::Dict{Symbol,Expr})
jacSet=Set{Union{Int,Symbol,Expr}}()
m=postwalk(rhs) do a #
if a isa Expr && a.head == :ref #
push!(jacSet, (a.args[2])) # du[varNum=1]=rhs=u[5]+u[2] : 2 and 5 are stored in jacset
a=eliminateRef(a)#q[i] -> qi
end
return a
end
basi = convert(Basic, m)
for i in jacSet
symarg=symbolFromRef(i) # specific to elements in jacSet: get q1 from 1 for exple
coef = diff(basi, symarg) # symbolic differentiation: returns type Basic
coefstr=string(coef);coefExpr=Meta.parse(coefstr)#convert from basic to expression
jacEntry=restoreRef(coefExpr,symDict)# get back ref: qi->q[i][0] ...0 because later in exactJac fun cache[1]::Float64=jacEntry
exacteJacExpr[:(($varNum,$i))]=jacEntry # entry (varNum,i) is jacEntry
end
if length(jacSet)>0 jac[varNum]=jacSet end # jac={1->(2,5)}
#@show jac
end
function extractJacDepLoop(b::Int,niter::Int,rhs::Union{Int,Expr},jac :: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}} ,exacteJacExpr :: Dict{Expr,Union{Float64,Int,Symbol,Expr}},symDict::Dict{Symbol,Expr})
jacSet=Set{Union{Int,Symbol,Expr}}()
m=postwalk(rhs) do a
if a isa Expr && a.head == :ref #
push!(jacSet, (a.args[2])) #
a=eliminateRef(a)
end
return a
end
basi = convert(Basic, m)
for i in jacSet
symarg=symbolFromRef(i);
coef = diff(basi, symarg)
coefstr=string(coef);
coefExpr=Meta.parse(coefstr)
jacEntry=restoreRef(coefExpr,symDict)
exacteJacExpr[:((($b,$niter),$i))]=jacEntry
end
if length(jacSet)>0 jac[:(($b,$niter))]=jacSet end
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 14780 | """NLODEContProblem{PRTYPE,T,Z,Y,CS}
A struct that holds the Problem of a system of ODEs. It has the following fields:\n
- prname: The name of the problem\n
- prtype: The type of the problem\n
- a: The size of the problem\n
- b: The number of zero crossing functions\n
- c: The number of discrete events\n
- cacheSize: The size of the cache\n
- initConditions: The initial conditions of the problem\n
- eqs: The function that holds all the ODEs\n
- jac: The Jacobian dependency\n
- SD: The state derivative dependency\n
- exactJac: The exact Jacobian function\n
- jacDim: The Jacobian dimension (if sparsity to be exploited)
"""
struct NLODEContProblem{PRTYPE,T,Z,Y,CS}<: NLODEProblem{PRTYPE,T,Z,Y,CS}
prname::Symbol # problem name used to distinguish printed results
prtype::Val{PRTYPE} # problem type: not used but created in case in the future we want to handle problems differently
a::Val{T} #problem size based on number of vars: T is used not a: 'a' is a mute var
b::Val{Z} #number of Zero crossing functions (ZCF) based on number of 'if statements': Z is used not b: 'b' is a mute var
c::Val{Y} #number of discrete events=2*ZCF: Z is used not c: 'c' is a mute var
cacheSize::Val{CS}# CS= cache size is used : 'cacheSize' is a mute var
initConditions::Vector{Float64} #
eqs::Function#function that holds all ODEs
jac::Vector{Vector{Int}}#Jacobian dependency..I have a der and I want to know which vars affect it...opposite of SD...is a vect for direct method (later @resumable..closure..for saved method)
SD::Vector{Vector{Int}}# I have a var and I want the der that are affected by it
exactJac::Function # used only in the implicit intgration
#map::Function # if sparsity to be exploited: it maps a[i][j] to a[i][γ] where γ usually=1,2,3...(a small int)
jacDim::Function # if sparsity to be exploited: gives length of each row
end
# to create NLODEContProblem above
function NLodeProblemFunc(odeExprs::Expr,::Val{T},::Val{0},::Val{0}, initConditions::Vector{Float64} ,du::Symbol,symDict::Dict{Symbol,Expr})where {T}
if VERBOSE println("nlodeprobfun T= $T") end
equs=Dict{Union{Int,Expr},Expr}() #du[int] or du[i]==du[a<i<b]==du[(a:b)]
jac = Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}()# datastrucutre 'Set' used because we do not want to insert an existing varNum
exacteJacExpr = Dict{Expr,Union{Float64,Int,Symbol,Expr}}()
# NO need to constrcut SD...SDVect will be extracted from Jac
num_cache_equs=1#initial cachesize::will hold the number of caches (vectors) of the longest equation
for argI in odeExprs.args
#only diff eqs: du[]= number || ref || call
if argI isa Expr && argI.head == :(=) && argI.args[1] isa Expr && argI.args[1].head == :ref && argI.args[1].args[1]==du#expr LHS=RHS and LHS is du
y=argI.args[1];rhs=argI.args[2]
varNum=y.args[2] # order/index of variable
if rhs isa Number # rhs of equ =number
equs[varNum]=:($((transformFSimplecase(:($(rhs)))))) #change rhs from N to cache=taylor0=[[N,0,0],2] for order 2 for exple
elseif rhs isa Symbol # case du=t
#equs[varNum ]=quote $rhs end
equs[varNum ]=:($((transformFSimplecase(:($(rhs))))))#
elseif rhs.head==:ref #rhs is only one var
extractJacDepNormal(varNum,rhs,jac,exacteJacExpr ,symDict ) #extract jacobian and exactJac approx form from normal equation
equs[varNum ]=:($((transformFSimplecase(:($(rhs))))))#change rhs from q[i] to cache=q[i] ...just put taylor var in cache
else #rhs head==call...to be tested later for math functions and other possible scenarios or user erros
extractJacDepNormal(varNum,rhs,jac,exacteJacExpr,symDict )
temp=(transformF(:($(rhs),1))).args[2] #temp=number of caches distibuted...rhs already changed inside
if num_cache_equs<temp
num_cache_equs=temp
end
equs[varNum]=rhs
end
elseif @capture(argI, for counter_ in b_:niter_ loopbody__ end) #case where diff equation is an expr in for loop
specRHS=loopbody[1].args[2]
extractJacDepLoop(b,niter,specRHS,jac,exacteJacExpr,symDict ) #extract jacobian and SD dependencies from loop
temp=(transformF(:($(specRHS),1))).args[2]
if num_cache_equs<temp
num_cache_equs=temp
end
equs[:(($b,$niter))]=specRHS
else#end of equations and user enter something weird...handle later
# error("expression $x: top level contains only expressions 'A=B' or 'if a b' or for loop... ")#
end #end for x in
end #end for args #########################################################################################################
fname= :f #default problem name
#path="./temp.jl" #default path
if odeExprs.args[1] isa Expr && odeExprs.args[1].args[2] isa Expr && odeExprs.args[1].args[2].head == :tuple#user has to enter problem info in a tuple
fname= odeExprs.args[1].args[2].args[1]
#path=odeExprs.args[1].args[2].args[2]
end
exacteJacfunction=createExactJacFun(exacteJacExpr,fname)
exactJacfunctionF=@RuntimeGeneratedFunction(exacteJacfunction)
diffEqfunction=createContEqFun(equs,fname)# diff equations before this are stored in a dict:: now we have a giant function that holds all diff equations
jacVect=createJacVect(jac,Val(T)) #jacobian dependency
SDVect=createSDVect(jac,Val(T)) # state derivative dependency
# mapFun=createMapFun(jac,fname) # for sparsity
jacDimFunction=createJacDimensionFun(jac,fname) #for sparsity
diffEqfunctionF=@RuntimeGeneratedFunction(diffEqfunction) # @RuntimeGeneratedFunction changes a fun expression to actual fun without running into world age problems
# mapFunF=@RuntimeGeneratedFunction(mapFun)
jacDimFunctionF=@RuntimeGeneratedFunction(jacDimFunction)
prob=NLODEContProblem(fname,Val(1),Val(T),Val(0),Val(0),Val(num_cache_equs),initConditions,diffEqfunctionF,jacVect,SDVect,exactJacfunctionF,jacDimFunctionF)# prtype type 1...prob not saved and struct contains vects
end
function createContEqFun(equs::Dict{Union{Int,Expr},Expr},funName::Symbol)
s="if i==0 return nothing\n" # :i is the mute var
for elmt in equs
Base.remove_linenums!(elmt[1])
Base.remove_linenums!(elmt[2])
if elmt[1] isa Int
s*="elseif i==$(elmt[1]) $(elmt[2]) ;return nothing\n"
end
if elmt[1] isa Expr
s*="elseif $(elmt[1].args[1])<=i<=$(elmt[1].args[2]) $(elmt[2]) ;return nothing\n"
end
end
s*=" end "
myex1=Meta.parse(s)
Base.remove_linenums!(myex1)
def=Dict{Symbol,Any}()
def[:head] = :function
def[:name] = funName
def[:args] = [:(i::Int),:(q::Vector{Taylor0}),:(t::Taylor0),:(cache::Vector{Taylor0})]
def[:body] = myex1
functioncode=combinedef(def)
end
function createJacDimensionFun(jac:: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},funName::Symbol)
ss="if i==0 return 0\n"
for dictElement in jac
if dictElement[1] isa Int
ss*="elseif i==$(dictElement[1]) \n"
ss*="return $(length(dictElement[2])) \n"
# ss*=" return nothing \n"
elseif dictElement[1] isa Expr
ss*="elseif $(dictElement[1].args[1])<=i<=$(dictElement[1].args[2]) \n"
ss*="return $(length(dictElement[2])) \n"
end
end
ss*=" end \n"
myex1=Meta.parse(ss)
Base.remove_linenums!(myex1)
def1=Dict{Symbol,Any}() #any changeto Union{expr,Symbol} ????
def1[:head] = :function
def1[:name] = Symbol(:jacDimension,funName)
def1[:args] = [:(i::Int)]
def1[:body] = myex1
functioncode1=combinedef(def1)
end
#do not delete next commented function...needed for future code extension
#= function createMapFun(jac:: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},funName::Symbol)
ss="if i==0 return nothing\n"
for dictElement in jac
#= Base.remove_linenums!(dictElement[1])
Base.remove_linenums!(dictElement[2]) =#
# counterJac=1
if dictElement[1] isa Int
ss*="elseif i==$(dictElement[1]) \n"
ns=sort!(collect(dictElement[2]))
ss*="if j==0 return nothing\n"
iter=1
for k in ns
ss*="elseif j==$k \n"
ss*="cache[1]=$iter \n"
ss*=" return nothing \n"
iter+=1
end
ss*=" end \n"
elseif dictElement[1] isa Expr
ss*="elseif $(dictElement[1].args[1])<=i<=$(dictElement[1].args[2]) \n"
@show dictElement[2]
ns=sort!(collect(dictElement[2]))
ss*="if j==0 return nothing\n"
iter=1
for k in ns
ss*="elseif j==$k \n"
ss*="cache[1]=$iter \n"
ss*=" return nothing \n"
iter+=1
end
ss*=" end \n"
end
end
ss*=" end \n"
myex1=Meta.parse(ss)
Base.remove_linenums!(myex1)
def1=Dict{Symbol,Any}() #any changeto Union{expr,Symbol} ????
def1[:head] = :function
def1[:name] = Symbol(:map,funName)
def1[:args] = [:(cache::MVector{1,Int}),:(i::Int),:(j::Int)]
def1[:body] = myex1
functioncode1=combinedef(def1)
end =#
function createExactJacFun(jac:: Dict{Expr,Union{Float64,Int,Symbol,Expr}},funName::Symbol)
ss="if i==0 return nothing\n"
for dictElement in jac
if dictElement[1].args[1] isa Int
ss*="elseif i==$(dictElement[1].args[1]) && j==$(dictElement[1].args[2]) \n"
ss*="cache[1]=$(dictElement[2]) \n"
ss*=" return nothing \n"
elseif dictElement[1].args[1] isa Expr
ss*="elseif $(dictElement[1].args[1].args[1])<=i<=$(dictElement[1].args[1].args[2]) && j==$(dictElement[1].args[2]) \n"
ss*="cache[1]=$(dictElement[2]) \n"
ss*=" return nothing \n"
end
end
ss*=" end \n"
myex1=Meta.parse(ss)
Base.remove_linenums!(myex1)
def1=Dict{Symbol,Any}() #any changeto Union{expr,Symbol} ????
def1[:head] = :function
def1[:name] = Symbol(:exactJac,funName)
def1[:args] = [:(q::Vector{Taylor0}),:(d::Vector{Float64}),:(cache::MVector{1,Float64}),:(i::Int),:(j::Int),:(t::Float64)]
def1[:body] = myex1
functioncode1=combinedef(def1)
end
function createExactJacDiscreteFun(jac:: Dict{Expr,Union{Float64,Int,Symbol,Expr}},funName::Symbol)
ss="if i==0 return nothing\n"
for dictElement in jac
if dictElement[1].args[1] isa Int
ss*="elseif i==$(dictElement[1].args[1]) && j==$(dictElement[1].args[2]) \n"
ss*="cache[1]=$(dictElement[2]) \n"
ss*=" return nothing \n"
elseif dictElement[1].args[1] isa Expr
ss*="elseif $(dictElement[1].args[1].args[1])<=i<=$(dictElement[1].args[1].args[2]) && j==$(dictElement[1].args[2]) \n"
ss*="cache[1]=$(dictElement[2]) \n"
ss*=" return nothing \n"
end
end
ss*=" end \n"
myex1=Meta.parse(ss)
Base.remove_linenums!(myex1)
def1=Dict{Symbol,Any}() #any changeto Union{expr,Symbol} ????
def1[:head] = :function
def1[:name] = Symbol(:exactJac,funName)
def1[:args] = [:(q::Vector{Taylor0}),:(d::Vector{Float64}),:(cache::MVector{1,Float64}),:(i::Int),:(j::Int),:(t::Float64)] # in jac t does not need to be a taylor
def1[:body] = myex1
functioncode1=combinedef(def1)
end
function createJacVect(jac:: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},::Val{T}) where{T}#
jacVect = Vector{Vector{Int}}(undef, T)
for i=1:T
jacVect[i]=Vector{Int}()# define it so i can push elements as i find them below
end
for dictElement in jac
if dictElement[1] isa Int #jac[varNum]=jacSet
jacVect[dictElement[1]]=collect(dictElement[2])
elseif dictElement[1] isa Expr #jac[:(($b,$niter))]=jacSet
for j_=(dictElement[1].args[1]):(dictElement[1].args[2])
temp=Vector{Int}()
for element in dictElement[2]
if element isa Expr || element isa Symbol#can split symbol alone since no need to postwalk
fa= postwalk(a -> a isa Symbol && a==:i ? j_ : a, element) # change each symbol i to exact number
push!(temp,Int(eval(fa)))
else #element is int
push!(temp,element)
end
end
jacVect[j_]=temp
end
end
end
jacVect
end
function createSDVect(jac:: Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}},::Val{T}) where{T}
sdVect = Vector{Vector{Int}}(undef, T)
for ii=1:T
sdVect[ii]=Vector{Int}()# define it so i can push elements as i find them below
end
#SD = Dict{Union{Int64, Expr}, Set{Union{Int64, Expr, Symbol}}}(2 => Set([1]), 10 => Set([10]), :((2, 9)) => Set([:k, :(k - 1), :(k + 1)]), 9 => Set([10]), 1 => Set([1]))
for dictElement in jac
if dictElement[1] isa Int # key is an int
for k in dictElement[2] #elments values
push!(sdVect[k],dictElement[1])
end
elseif dictElement[1] isa Expr # key is an expression
for j_=(dictElement[1].args[1]):(dictElement[1].args[2]) # j_=b:N this can be expensive when N is large::this is why it is recommended to use a function createsd (save) for large prob
for element in dictElement[2]
if element isa Expr || element isa Symbol#element=
fa= postwalk(a -> a isa Symbol && a==:i ? j_ : a, element)
push!(sdVect[Int(eval(fa))],j_)
else#element is int
push!(sdVect[element],j_)
end
end
end
end
end
sdVect
end
#= function Base.isless(ex1::Expr, ex2::Expr)#:i is the mute var that prob is now using
fa= postwalk(a -> a isa Symbol && a==:i ? 1 : a, ex1)# check isa symbol not needed
fb=postwalk(a -> a isa Symbol && a==:i ? 1 : a, ex2)
eval(fa)<eval(fb)
end
function Base.isless(ex1::Expr, ex2::Symbol)
fa= postwalk(a -> a isa Symbol && a==:i ? 1 : a, ex1)
eval(fa)<1
end
function Base.isless(ex1::Symbol, ex2::Expr)
fa= postwalk(a -> a isa Symbol && a==:i ? 1 : a, ex2)
1<eval(fa)
end =# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 826 |
"""NLODEProblem{PRTYPE,T,Z,Y,CS}
This is superclass for all NLODE problems. It is parametric on these:\n
- The problem type PRTYPE.\n
- The number of continuous variables T\n
- The number of events (zero crossing functions) Z\n
- The actual number of events (an if-else statment has one zero crossing functions and two events) Y\n
- The cache size CS.
"""
abstract type NLODEProblem{PRTYPE,T,Z,Y,CS} end
"""ALGORITHM{N,O}
This is superclass for all QSS algorithms. It is parametric on these:\n
- The name of the algorithm N\n
- The order of the algorithm O
"""
abstract type ALGORITHM{N,O} end
"""Sol{T,O}
This is superclass for all QSS solutions. It is parametric on these:\n
- The number of continuous variables T\n
- The order of the algorithm O
"""
abstract type Sol{T,O} end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 16490 |
#struct that holds prob data
struct NLODEDiscProblem{PRTYPE,T,Z,D,CS}<: NLODEProblem{PRTYPE,T,Z,D,CS}
prname::Symbol
prtype::Val{PRTYPE}
a::Val{T}
b::Val{Z}
c::Val{D}
cacheSize::Val{CS}
initConditions::Vector{Float64}
discreteVars::Vector{Float64}
jac::Vector{Vector{Int}}#Jacobian dependency..I have a der and I want to know which vars affect it...opposite of SD
ZCjac::Vector{Vector{Int}} # to update other Qs before checking ZCfunction
eqs::Function#function that holds all ODEs
eventDependencies::Vector{EventDependencyStruct}#
SD::Vector{Vector{Int}}# I have a var and I want the der that are affected by it
HZ::Vector{Vector{Int}}# an ev occured and I want the ZC that are affected by it
HD::Vector{Vector{Int}}# an ev occured and I want the der that are affected by it
SZ::Vector{Vector{Int}}# I have a var and I want the ZC that are affected by it
exactJac::Function #used only in the implicit integration: linear approximation
end
function getInitCond(prob::NLODEDiscProblem,i::Int)
return prob.initConditions[i]
end
#= function getInitCond(prob::savedNLODEDiscProblem,i::Int)
return prob.initConditions(i)
end =#
# receives user code and creates the problem struct
function NLodeProblemFunc(odeExprs::Expr,::Val{T},::Val{D},::Val{Z},initCond::Vector{Float64},du::Symbol,symDict::Dict{Symbol,Expr})where {T,D,Z}
if VERBOSE println("discrete nlodeprobfun T D Z= $T $D $Z") end
# @show odeExprs
discrVars=Vector{Float64}()
equs=Dict{Union{Int,Expr},Union{Int,Symbol,Expr}}()
jac = Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}()# set used because do not want to insert an existing varNum
#SD = Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}() # NO need to constrcut SD...SDVect will be extracted from Jac (needed for func-save case)
#jacDiscrete = Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}()# for now is similar to continous jac...if feature of d[i] not to be added then jacDiscr=Dict{Union{Int,Expr},Set{Int}}()...later
dD = Dict{Union{Int,Expr},Set{Union{Int,Symbol,Expr}}}() # similarly if feature not given then dD=Dict{Int,Set{Union{Int,Symbol,Expr}}}()
exacteJacExpr = Dict{Expr,Union{Float64,Int,Symbol,Expr}}()
zcequs=Vector{Expr}()#vect to collect if-statements
eventequs=Vector{Expr}()#vect to collect events
ZCjac=Vector{Vector{Int}}()#zeros(SVector{Z,SVector{T,Int}}) # bad when T is large...it is a good idea to use Vector{Vector{Int}}(undef, Z)
ZCFCounter=0
#SZ=Vector{Vector{Int}}()#zeros(SVector{T,SVector{Z,Int}}) # bad when T is large...(opposite of ZCjac)...many vars dont influence zcf so it is better to use dict
# dZ=Vector{Vector{Int}}()#zeros(SVector{D,SVector{Z,Int}})# usually D (num of disc vars) and Z (num of zcfunctions) are small even for real problems
SZ= Dict{Int,Set{Int}}()
dZ= Dict{Int,Set{Int}}() #since D is not large ...i can use zeros(SVector{D,SVector{Z,Int}})
evsArr = EventDependencyStruct[]
num_cache_equs=1#cachesize
for argI in odeExprs.args
if argI isa Expr && argI.head == :(=) && argI.args[1]== :discrete
discrVars = Vector{Float64}(argI.args[2].args)
#only diff eqs: du[]= number/one ref/call
elseif argI isa Expr && argI.head == :(=) && argI.args[1] isa Expr && argI.args[1].head == :ref && argI.args[1].args[1]==du#&& ((argI.args[2] isa Expr && (argI.args[2].head ==:ref || argI.args[2].head ==:call ))||argI.args[2] isa Number)
y=argI.args[1];rhs=argI.args[2]
varNum=y.args[2] # order of variable
if rhs isa Number || rhs isa Symbol # rhs of equ =number or symbol
equs[varNum]=:($((transformFSimplecase(:($(rhs))))))
elseif rhs isa Expr && rhs.head==:ref && rhs.args[1]==:q #rhs is only one var...# rhs.args[1]==:q # check not needed?
extractJacDepNormal(varNum,rhs,jac,exacteJacExpr ,symDict,dD )
# end
equs[varNum ]=:($((transformFSimplecase(:($(rhs))))))
else #rhs head==call...to be tested later for math functions and other possible scenarios or user erros
extractJacDepNormal(varNum,rhs,jac,exacteJacExpr ,symDict,dD )
temp=(transformF(:($(rhs),1))).args[2] #number of caches distibuted ...no need interpolation and wrap in expr?....before was cuz quote....
if num_cache_equs<temp
num_cache_equs=temp
end
equs[varNum]=rhs
end
elseif @capture(argI, for counter_ in b_:niter_ loopbody__ end)
specRHS=loopbody[1].args[2]
# extractJacDepLoop(b,niter,specRHS,jac ,jacDiscrete ,SD,dD )
extractJacDepLoop(b,niter,specRHS,jac,exacteJacExpr,symDict ,dD )
temp=(transformF(:($(specRHS),1))).args[2]
if num_cache_equs<temp
num_cache_equs=temp
end
equs[:(($b,$niter))]=specRHS
elseif argI isa Expr && argI.head==:if #@capture if did not work
zcf=argI.args[1].args[2]
ZCFCounter+=1
extractZCJacDepNormal(ZCFCounter,zcf,ZCjac ,SZ ,dZ )
if zcf.head==:ref #if one_Var
push!(zcequs,(transformFSimplecase(:($(zcf)))))
########################push!(zcequs,:($((transformFSimplecase(:($(zcf)))))))
else # if whole expre ops with many vars
temp=:($((transformF(:($(zcf),1))).args[2])) #number of caches distibuted, given 1 place holder for ex.args[2] to be filled inside and returned
if num_cache_equs<temp
num_cache_equs=temp
end
push!(zcequs,(zcf))
end
##################################################################################################################
# events
##################################################################################################################
# each 'if-statmets' has 2 events (arg[2]=posEv and arg[3]=NegEv) each pos or neg event has a function...later i can try one event for zc
if length(argI.args)==2 #if user only wrote the positive evnt, here I added the negative event wich does nothing
nothingexpr = quote nothing end # neg dummy event
push!(argI.args, nothingexpr)
Base.remove_linenums!(argI.args[3])
end
#pos event
newPosEventExprToFunc=changeExprToFirstValue(argI.args[2]) #change u[1] to u[1][0] # pos ev can't be a symbol ...later maybe add check anyway
push!(eventequs,newPosEventExprToFunc)
#neg eve
if argI.args[3].args[1] isa Expr # argI.args[3] isa expr and is either an equation or :block symbol end ...so lets check .args[1]
newNegEventExprToFunc=changeExprToFirstValue(argI.args[3])
push!(eventequs,newNegEventExprToFunc)
else
push!(eventequs,argI.args[3]) #symbol nothing
end
#after constructing the equations we move to dependencies: we need to change A[n] to An so that they become symbols
posEvExp = argI.args[2]
negEvExp = argI.args[3]
#dump(negEvExp)
indexPosEv = 2 * length(zcequs) - 1 # store events in order
indexNegEv = 2 * length(zcequs)
#------------------pos Event--------------------#
posEv_disArrLHS= Vector{Int}()#@SVector fill(NaN, D) #...better than @SVector zeros(D), I can use NaN
posEv_conArrLHS= Vector{Int}()#@SVector fill(NaN, T)
posEv_conArrRHS=Vector{Int}()#@SVector zeros(T) #to be used inside intgrator to updateOtherQs (intgrateState) before executing the event there is no discArrRHS because d is not changing overtime to be updated
for j = 1:length(posEvExp.args) # j coressponds the number of statements under one posEvent
# !(posEvExp.args[j] isa Expr && posEvExp.args[j].head == :(=)) && error("event should be A=B")
if (posEvExp.args[j] isa Expr && posEvExp.args[j].head == :(=))
poslhs=posEvExp.args[j].args[1];posrhs=posEvExp.args[j].args[2]
# !(poslhs isa Expr && poslhs.head == :ref && (poslhs.args[1]==:q || poslhs.args[1]==:d)) && error("lhs of events must be a continuous or a discrete variable")
if (poslhs isa Expr && poslhs.head == :ref && (poslhs.args[1]==:q || poslhs.args[1]==:d))
if poslhs.args[1]==:q
push!(posEv_conArrLHS,poslhs.args[2])
else # lhs is a disc var
push!(posEv_disArrLHS,poslhs.args[2])
end
#@show poslhs,posrhs
postwalk(posrhs) do a #
if a isa Expr && a.head == :ref && a.args[1]==:q#
push!(posEv_conArrRHS, (a.args[2])) #
end
return a
end
end
end
end
#------------------neg Event--------------------#
negEv_disArrLHS= Vector{Int}()#@SVector fill(NaN, D) #...better than @SVector zeros(D), I can use NaN
negEv_conArrLHS= Vector{Int}()#@SVector fill(NaN, T)
negEv_conArrRHS=Vector{Int}()#@SVector zeros(T) #to be used inside intgrator to updateOtherQs (intgrateState) before executing the event there is no discArrRHS because d is not changing overtime to be updated
if negEvExp.args[1] != :nothing
for j = 1:length(negEvExp.args) # j coressponds the number of statements under one negEvent
# !(negEvExp.args[j] isa Expr && negEvExp.args[j].head == :(=)) && error("event should be A=B")
neglhs=negEvExp.args[j].args[1];negrhs=negEvExp.args[j].args[1]
# !(neglhs isa Expr && neglhs.head == :ref && (neglhs.args[1]==:q || neglhs.args[1]==:d)) && error("lhs of events must be a continuous or a discrete variable")
if (neglhs isa Expr && neglhs.head == :ref && (neglhs.args[1]==:q || neglhs.args[1]==:d))
if neglhs.args[1]==:q
push!(negEv_conArrLHS,neglhs.args[2])
else # lhs is a disc var
push!(negEv_disArrLHS,neglhs.args[2])
end
postwalk(negrhs) do a #
if a isa Expr && a.head == :ref && a.args[1]==:q#
push!(negEv_conArrRHS, (a.args[2])) #
end
return a
end
end
end
end
structposEvent = EventDependencyStruct(indexPosEv, posEv_conArrLHS, posEv_disArrLHS,posEv_conArrRHS) # right now posEv_conArr is vect of ...
push!(evsArr, structposEvent)
structnegEvent = EventDependencyStruct(indexNegEv, negEv_conArrLHS, negEv_disArrLHS,negEv_conArrRHS)
push!(evsArr, structnegEvent)
end #end cases
end #end for #########################################################################################################
allEpxpr=Expr(:block)
##############diffEqua######################
s="if i==0 return nothing\n" # :i is the mute var
for elmt in equs
Base.remove_linenums!(elmt[1])
Base.remove_linenums!(elmt[2])
if elmt[1] isa Int
s*="elseif i==$(elmt[1]) $(elmt[2]) ;return nothing\n"
end
if elmt[1] isa Expr
s*="elseif $(elmt[1].args[1])<=i<=$(elmt[1].args[2]) $(elmt[2]) ;return nothing\n"
end
end
s*=" end "
myex1=Meta.parse(s)
push!(allEpxpr.args,myex1)
##############ZCF######################
if length(zcequs)>0
#= io = IOBuffer()
write(io, "if zc==1 $(zcequs[1]) ;return nothing") =#
s="if zc==1 $(zcequs[1]) ;return nothing"
for i=2:length(zcequs)
s*= " elseif zc==$i $(zcequs[i]) ;return nothing"
end
# write(io, " else $(zcequs[length(zcequs)]) ;return nothing end ")
s*= " end "
myex2=Meta.parse(s)
push!(allEpxpr.args,myex2)
end
##############events######################
if length(eventequs)>0
s= "if ev==1 $(eventequs[1]) ;return nothing"
for i=2:length(eventequs)
s*= " elseif ev==$i $(eventequs[i]) ;return nothing"
end
# write(io, " else $(zcequs[length(zcequs)]) ;return nothing end ")
s*= " end "
myex3=Meta.parse(s)
push!(allEpxpr.args,myex3)
end
fname= :f #default problem name
#path="./temp.jl" #default path
if odeExprs.args[1] isa Expr && odeExprs.args[1].args[2] isa Expr && odeExprs.args[1].args[2].head == :tuple#user has to enter problem info in a tuple
fname= odeExprs.args[1].args[2].args[1]
#path=odeExprs.args[1].args[2].args[2]
end
Base.remove_linenums!(allEpxpr)
def=Dict{Symbol,Any}()
def[:head] = :function
def[:name] = fname
def[:args] = [:(i::Int),:(zc::Int),:(ev::Int),:(q::Vector{Taylor0}),:(d::Vector{Float64}), :(t::Taylor0),:(cache::Vector{Taylor0})]
def[:body] = allEpxpr
#def[:rtype]=:nothing# test if cache1 always holds sol
functioncode=combinedef(def)
functioncodeF=@RuntimeGeneratedFunction(functioncode)
jacVect=createJacVect(jac,Val(T))
SDVect=createSDVect(jac,Val(T))
dDVect =createdDvect(dD,Val(D))
SZvect=createSZvect(SZ,Val(T))
# temporary dependencies to be used to determine HD and HZ...determine HD: event-->Derivative && determine HZ:Event-->ZCfunction....influence of events on derivatives and zcfunctions:
#an event is a discrteVar change or a cont Var change. So HD=HD1 UNION HD2 (same for HZ=HZ1 UNION HZ2)
# (1) through a discrete Var:
# ============================
# HD1=Hd-->dD where Hd comes from the eventDependecies Struct.
# HZ1=Hd-->dZ where Hd comes from the eventDependecies Struct.
HZ1HD1=createDependencyToEventsDiscr(dDVect,dZ,evsArr)
# (2) through a continous Var:
# ==============================
# HD2=Hs-->sD where Hs comes from the eventDependecies Struct.(sd already created)
# HZ2=Hs-->sZ where Hs comes from the eventDependecies Struct.(sZ already created)
HZ2HD2=createDependencyToEventsCont(SDVect,SZ,evsArr)
##########UNION##############
HZ=unionDependency(HZ1HD1[1],HZ2HD2[1])
HD=unionDependency(HZ1HD1[2],HZ2HD2[2])
# mapFun=createMapFun(jac,fname)
# mapFunF=@RuntimeGeneratedFunction(mapFun)
exacteJacfunction=createExactJacDiscreteFun(exacteJacExpr,fname)
exacteJacfunctionF=@RuntimeGeneratedFunction(exacteJacfunction)
if VERBOSE println("discrete problem created") end
myodeProblem = NLODEDiscProblem(fname,Val(1),Val(T),Val(Z),Val(D),Val(num_cache_equs),initCond, discrVars, jacVect ,ZCjac ,functioncodeF, evsArr,SDVect,HZ,HD,SZvect,exacteJacfunctionF)
end
function createdDvect(dD::Dict{Union{Int64, Expr}, Set{Union{Int64, Expr, Symbol}}},::Val{D})where{D}
dDVect = Vector{Vector{Int}}(undef, D)
for ii=1:D
dDVect[ii]=Vector{Int}()# define it so i can push elements as i find them below
end
for dictElement in dD
temp=Vector{Int}()
for k in dictElement[2]
if k isa Int
push!(temp,k)
elseif k isa Expr #tuple
for j_=(k.args[1]):(k.args[2])
push!(temp,j_)
end
end
end
dDVect[dictElement[1]]=temp
end
dDVect
end
function createSZvect(SZ :: Dict{Int64, Set{Int64}},::Val{T})where{T}
szVect = Vector{Vector{Int}}(undef, T)
for ii=1:T
szVect[ii]=Vector{Int}()# define it so i can push elements as i find them below
end
for ele in SZ
szVect[ele[1]]=collect(ele[2])
end
szVect
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1838 | #
struct QSSAlgorithm{N,O}#<:QSSAlgorithm{N,O}
name::Val{N}
order::Val{O}
end
"""qss1()
calls the explicit quantized state system solver with order 1
"""
qss1()=QSSAlgorithm(Val(:qss),Val(1))
"""qss2()
calls the explicit quantized state system solver with order 2
"""
qss2()=QSSAlgorithm(Val(:qss),Val(2))
#= """qss3()
calls the explicit quantized state system solver with order 3
""" =#
#qss3()=QSSAlgorithm(Val(:qss),Val(3))
"""nmliqss1()
calls the modified imlicit quantized state system solver with order 1.
It is efficient when the system contains large entries outside the main diagonal of the Jacobian .
"""
nmliqss1()=QSSAlgorithm(Val(:nmliqss),Val(1))
"""nmliqss2()
calls the modified imlicit quantized state system solver with order 2.
It is efficient when the system contains large entries outside the main diagonal of the Jacobian .
"""
nmliqss2()=QSSAlgorithm(Val(:nmliqss),Val(2))
#= """nmliqss3()
calls the modified imlicit quantized state system solver with order 3.
It is efficient when the system contains large entries outside the main diagonal of the Jacobian .
""" =#
#nmliqss3()=QSSAlgorithm(Val(:nmliqss),Val(3))
#= nliqss1()=QSSAlgorithm(Val(:nliqss),Val(1))
nliqss2()=QSSAlgorithm(Val(:nliqss),Val(2))
nliqss3()=QSSAlgorithm(Val(:nliqss),Val(3))
mliqss1()=QSSAlgorithm(Val(:mliqss),Val(1))
mliqss2()=QSSAlgorithm(Val(:mliqss),Val(2))
mliqss3()=QSSAlgorithm(Val(:mliqss),Val(3)) =#
"""liqss1()
calls the imlicit quantized state system solver with order 1.
"""
liqss1()=QSSAlgorithm(Val(:liqss),Val(1))
"""liqss2()
calls the imlicit quantized state system solver with order 2.
"""
liqss2()=QSSAlgorithm(Val(:liqss),Val(2))
#= """liqss3()
calls the imlicit quantized state system solver with order 3.
""" =#
#liqss3()=QSSAlgorithm(Val(:liqss),Val(3))
#= sparse()=Val(true)
dense()=Val(false) =#
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1120 |
#= """ hold helper datastructures needed for simulation, can be seen as the model in the qss architecture (model-integrator-quantizer)""" =#
struct CommonQSS_data{Z}
quantum :: Vector{Float64}
x :: Vector{Taylor0} #MVector cannot hold non-isbits
q :: Vector{Taylor0}
tx :: Vector{Float64}
tq :: Vector{Float64}
d::Vector{Float64}
nextStateTime :: Vector{Float64}
nextInputTime :: Vector{Float64} #
nextEventTime :: MVector{Z,Float64}
t::Taylor0# mute taylor var to be used with math functions to represent time
integratorCache::Taylor0
taylorOpsCache::Vector{Taylor0}
finalTime:: Float64
savetimeincrement::Float64
initialTime :: Float64
dQmin ::Float64
dQrel ::Float64
maxErr ::Float64
maxStepsAllowed ::Int
savedTimes :: Vector{Vector{Float64}}
savedVars:: Vector{Vector{Float64}}
end
#= ```
data needed only for implicit case
``` =#
struct LiQSS_data{O,Sparsity}
vs::Val{Sparsity}
cacheA::MVector{1,Float64}
qaux::Vector{MVector{O,Float64}}
dxaux::Vector{MVector{O,Float64}}
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1457 |
function updateScheduler(::Val{T},nextStateTime::Vector{Float64},nextEventTime :: MVector{Z,Float64},nextInputTime :: Vector{Float64})where{T,Z} #later MVect for nextInput
minStateTime=Inf
minState_index=0 # what if all nextstateTime= Inf ...especially at begining????? min_index stays 0!!!
minEventTime=Inf
minEvent_index=0
minInputTime=Inf
minInput_index=0
returnedVar=() # used to print something if something is bad
for i=1:T
if nextStateTime[i]<minStateTime
minStateTime=nextStateTime[i]
minState_index=i
end
if nextInputTime[i] < minInputTime
minInputTime=nextInputTime[i]
minInput_index=i
end
end
for i=1:Z
if nextEventTime[i] < minEventTime
minEventTime=nextEventTime[i]
minEvent_index=i
end
end
if minEventTime<minStateTime
if minInputTime<minEventTime
returnedVar=(minInput_index,minInputTime,:ST_INPUT)
else
returnedVar=(minEvent_index,minEventTime,:ST_EVENT)
end
else
if minInputTime<minStateTime
returnedVar=(minInput_index,minInputTime,:ST_INPUT)
else
returnedVar=(minState_index,minStateTime,:ST_STATE)
end
end
if returnedVar[1]==0
returnedVar=(1,Inf,:ST_STATE)
# println("null step made state step")
end
return returnedVar
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 4326 | """LightSol{T,O}
A struct that holds the solution of a system of ODEs. It has the following fields:\n
- size: The number of continuous variables T\n
- order: The order of the algorithm O\n
- savedTimes: A vector of vectors of Float64 that holds the times at which the continuous variables were saved\n
- savedVars: A vector of vectors of Float64 that holds the values of the continuous variables at the times they were saved\n
- algName: The name of the algorithm used to solve the system\n
- sysName: The name of the system\n
- absQ: The absolute tolerance used in the simulation\n
- totalSteps: The total number of steps taken by the algorithm\n
- simulStepCount: The number of simultaneous updates during the simulation\n
- evCount: The number of events that occurred during the simulation\n
- numSteps: A vector of Int that holds the number of steps taken by the algorithm for each continuous variable\n
- ft: The final time of the simulation
"""
struct LightSol{T,O}<:Sol{T,O}
size::Val{T}
order::Val{O}
savedTimes::Vector{Vector{Float64}}
savedVars::Vector{Vector{Float64}}
#savedVarsQ::Vector{Vector{Float64}}
algName::String
sysName::String
absQ::Float64
totalSteps::Int
simulStepCount::Int
evCount::Int
numSteps ::Vector{Int}
ft::Float64
end
@inline function createSol(::Val{T},::Val{O}, savedTimes:: Vector{Vector{Float64}},savedVars :: Vector{Vector{Float64}},solver::String,nameof_F::String,absQ::Float64,totalSteps::Int#= ,stepsaftersimul::Int =#,simulStepCount::Int,evCount::Int,numSteps ::Vector{Int},ft::Float64#= ,simulStepsVals :: Vector{Vector{Float64}}, simulStepsDers :: Vector{Vector{Float64}} ,simulStepsTimes :: Vector{Vector{Float64}} =#)where {T,O}
# println("light")
sol=LightSol(Val(T),Val(O),savedTimes, savedVars,solver,nameof_F,absQ,totalSteps#= ,stepsaftersimul =#,simulStepCount,evCount,numSteps,ft#= ,simulStepsVals,simulStepsDers,simulStepsTimes =#)
end
function getindex(s::Sol, i::Int64)
if i==1
return s.savedTimes
elseif i==2
return s.savedVars
else
error("sol has 2 attributes: time and states")
end
end
@inline function evaluateSol(sol::Sol{T,O},index::Int,t::Float64)where {T,O}
(t>sol.ft) && error("given point is outside the solution range! Verify where you want to evaluate the solution")
x=sol[2][index][end]
#integratorCache=Taylor0(zeros(O+1),O)
for i=2:length(sol[1][index])#savedTimes after the init time...init time is at index i=1
if sol[1][index][i]>t # i-1 is closest lower point
f1=sol[2][index][i-1];f2=sol[2][index][i];t1=sol[1][index][i-1] ;t2=sol[1][index][i]# find x=f(t)=at+b...linear interpolation
a=(f2-f1)/(t2-t1)
b=(f1*t2-f2*t1)/(t2-t1)
x=a*t+b
# println("1st case")
return x#taylor evaluation after small elapsed with the point before (i-1)
elseif sol[1][index][i]==t # i-1 is closest lower point
x=sol[2][index][i]
# println("2nd case")
return x
end
end
# println("3rd case")
return x #if var never changed then return init cond or if t>lastSavedTime for this var then return last value
end
function solInterpolated(sol::Sol{T,O},step::Float64)where {T,O}
interpTimes=Float64[]
allInterpTimes=Vector{Vector{Float64}}(undef, T)
t=0.0 #later can change to init_time which could be diff than zero
push!(interpTimes,t)
while t+step<sol.ft
t=t+step
push!(interpTimes,t)
end
push!(interpTimes,sol.ft)
numInterpPoints=length(interpTimes)
interpValues=nothing
if sol isa LightSol
interpValues=Vector{Vector{Float64}}(undef, T)
end
for index=1:T
interpValues[index]=[]
push!(interpValues[index],sol[2][index][1]) #1st element is the init cond (true value)
for i=2:numInterpPoints-1
push!(interpValues[index],evaluateSol(sol,index,interpTimes[i]))
end
push!(interpValues[index],sol[2][index][end]) #last pt @ft
allInterpTimes[index]=interpTimes
end
createSol(Val(T),Val(O),allInterpTimes,interpValues,sol.algName,sol.sysName,sol.absQ,sol.totalSteps#= ,sol.stepsaftersimul =#,sol.simulStepCount,sol.evCount,sol.numSteps,sol.ft#= ,sol.simulStepsVals,sol.simulStepsDers,sol.simulStepsVals =#)
end
(sol::Sol)(index::Int,t::Float64) = evaluateSol(sol,index,t)
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 2386 |
"""getError(sol::Sol{T,O},index::Int,f::Function) where{T,O}
This function calculates the relative error of the solution with respect to a reference function.
"""
function getError(sol::Sol{T,O},index::Int,f::Function) where{T,O}
index>T && error("the system contains only $T variables!")
numPoints=length(sol.savedTimes[index])
sumTrueSqr=0.0
sumDiffSqr=0.0
relerror=0.0
for i = 1:numPoints-1 #each point is a taylor
ts=f(sol.savedTimes[index][i])
sumDiffSqr+=(sol.savedVars[index][i]-ts)*(sol.savedVars[index][i]-ts)
sumTrueSqr+=ts*ts
end
relerror=sqrt(sumDiffSqr/sumTrueSqr)
return relerror
end
function getErrorByRefs(sol::Sol{T,O},index::Int,solRef::Vector{Any})where{T,O}
#numVars=length(sol.savedVars)
index>T && error("the system contains only $T variables!")
numPoints=length(sol.savedTimes[index])
sumTrueSqr=0.0
sumDiffSqr=0.0
relerror=0.0
for i = 1:numPoints-1 #-1 because savedtimes holds init cond at begining
ts=solRef[i][index]
sumDiffSqr+=(sol.savedVars[index][i]-ts)*(sol.savedVars[index][i]-ts)
sumTrueSqr+=ts*ts
end
if abs(sumTrueSqr)>1e-12
relerror=sqrt(sumDiffSqr/sumTrueSqr)
else
relerror=0.0
end
return relerror
end
#= @inline function getX_fromSavedVars(savedVars :: Vector{Array{Taylor0}},index::Int,i::Int)
return savedVars[index][i].coeffs[1]
end =#
@inline function getX_fromSavedVars(savedVars :: Vector{Vector{Float64}},index::Int,i::Int)
return savedVars[index][i]
end
"""getAverageErrorByRefs(sol::Sol{T,O},solRef::Vector{Any}) where{T,O}
This function calculates the average relative error of the solution with respect to a reference solution.
The relative error is calculated for each variable, and then it is averaged over all variables.
"""
function getAverageErrorByRefs(sol::Sol{T,O},solRef::Vector{Any}) where{T,O}
numPoints=length(sol.savedTimes[1])
allErrors=0.0
for index=1:T
sumTrueSqr=0.0
sumDiffSqr=0.0
relerror=0.0
for i = 1:numPoints-1 #each point is a taylor
ts=solRef[i][index]
Ns=getX_fromSavedVars(sol.savedVars,index,i)
sumDiffSqr+=(Ns-ts)*(Ns-ts)
sumTrueSqr+=ts*ts
end
if abs(sumTrueSqr)>1e-12
relerror=sqrt(sumDiffSqr/sumTrueSqr)
else
relerror=0.0
end
allErrors+= relerror
end
return allErrors/T
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 5119 | """plot_Sol(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool,marker=:circle::Symbol) where{T,O}
This function generates a plot of the solution of the system (returned as a plot object).
With the exception of the solution object, all arguments are optional.
The default values are:\n
- note = " "\n
- xlims = (0.0,0.0)\n
- ylims = (0.0,0.0)\n
- legend = true\n
- marker=:circle
"""
function plot_Sol(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool,marker=:circle::Symbol) where{T,O}
p1=plot()
if xvars!=()
for k in xvars
if k==1
stle=:dash
sze=2
elseif k==2
stle=:solid
sze=4
elseif k==3
stle=:dot
sze=3
elseif k==4
stle=:dashdot
sze=2
else
sze=1
stle=:solid
end
p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k],line=(sze,stle),marker=(marker),label="x$k $(sol.numSteps[k])"#= ,legend=:right =#)
end
else
for k=1:T
if k==1
mycolor=:red
else
mycolor=:purple
end
p1=plot!(p1,sol.savedTimes[k], sol.savedVars[k],marker=(marker),markersize=2,label="x$k $(sol.numSteps[k])"#= ,legend=:false =#)
end
end
if xlims!=(0.0,0.0) && ylims!=(0.0,0.0)
p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note", xlims=xlims ,ylims=ylims)
elseif xlims!=(0.0,0.0) && ylims==(0.0,0.0)
p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note", xlims=xlims #= ,ylims=ylims =#)
elseif xlims==(0.0,0.0) && ylims!=(0.0,0.0)
p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note"#= , xlims=xlims =#,ylims=ylims)
else
p1=plot!(p1, title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note",legend=legend)
end
p1
end
"""save_Sol(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O}
Save the plot of the system solution for the variables xvars.
With the exception of the solution object, all arguments are optional.
The default values are:\n
- note = " "\n
- xlims = (0.0,0.0)\n
- ylims = (0.0,0.0)\n
- legend = true
"""
function save_Sol(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O}
p1= plot_Sol(sol,xvars...;note=note,xlims=xlims,ylims=ylims,legend=legend)
mydate=now()
timestamp=(string(year(mydate),"_",month(mydate),"_",day(mydate),"_",hour(mydate),"_",minute(mydate),"_",second(mydate)))
savefig(p1, "plot_$(sol.sysName)_$(sol.algName)_$(xvars)_$(sol.absQ)_$(note)_ft_$(sol.ft)_$(timestamp).png")
end
function save_SolSum(sol::Sol{T,O},xvars::Int...;interp=0.0001,note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O}
p1= plot_SolSum(sol,xvars...;interp=interp,note=note,xlims=xlims,ylims=ylims,legend=legend)
mydate=now()
timestamp=(string(year(mydate),"_",month(mydate),"_",day(mydate),"_",hour(mydate),"_",minute(mydate),"_",second(mydate)))
savefig(p1, "plot_$(sol.sysName)_$(sol.algName)_$(xvars)_$(sol.absQ)_$(note)_ft_$(sol.ft)_$(timestamp).png")
end
#plot the sum of variables
function plot_SolSum(sol::Sol{T,O},xvars::Int...;interp=0.0001,note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O}
p1=plot()
if xvars!=()
solInterp=solInterpolated(sol,interp) # for now interpl all
sumV=solInterp.savedVars[xvars[1]]
sumT=solInterp.savedTimes[xvars[1]]#
numPoints=length(sumT)
for i=1:numPoints
for k=2: length(xvars)
sumV[i]+=solInterp.savedVars[xvars[k]][i]
end
end
p1=plot!(p1,sumT, sumV,marker=(:circle),#= ,legend=:right =#)
else
println("pick vars to plot their sum")
end
if xlims!=(0.0,0.0) && ylims!=(0.0,0.0)
p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note", xlims=xlims ,ylims=ylims)
elseif xlims!=(0.0,0.0) && ylims==(0.0,0.0)
p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note", xlims=xlims #= ,ylims=ylims =#)
elseif xlims==(0.0,0.0) && ylims!=(0.0,0.0)
p1=plot!(p1,title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note"#= , xlims=xlims =#,ylims=ylims)
else
p1=plot!(p1, title="$(sol.sysName)_$(sol.algName)_$(sol.absQ)_$(sol.totalSteps)_$(sol.simulStepCount)_$(sol.evCount) \n $note",legend=legend)
end
p1
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 10309 |
function transformFSimplecase(ex)# it s easier and healthier to leave the big case alone in one prewalk (below) when returning the size of the distributed cahce
ex=Expr(:call, :createT,ex)# case where rhs of eq is a number needed to change to taylor (in cache) to be used for qss || #case where rhs is q[i]...reutrn cache that contains it
cachexpr = Expr(:ref, :cache) # add cache[1] to createT(ex,....)
push!(cachexpr.args,1)
push!( ex.args, cachexpr)
return ex
end
function transformF(ex)# name to be changed later....i call this funciton in the docs the function that does the transformation
cachexpr_lengthtracker = Expr(:mongi)# an expr to track the number of distributed caches
prewalk(ex) do x
#############################minus sign#############################################
if x isa Expr && x.head == :call && x.args[1] == :- && length(x.args) == 3 && !(x.args[2] isa Int) && !(x.args[3] isa Int) #last 2 to avoid changing u[i-1] #MacroTools.isexpr(x, :call) replaces the begining
if x.args[2] isa Expr && x.args[2].head == :call && x.args[2].args[1] == :- && length(x.args[2].args) == 3
push!(x.args, x.args[3])# args[4]=c
x.args[3] = x.args[2].args[3]# args[3]=b
x.args[2] = x.args[2].args[2]# args[2]=a
x.args[1] = :subsub
push!(cachexpr_lengthtracker.args,:b) #b is anything ...not needed, just to fill vector tracker
cachexpr = Expr(:ref, :cache) #prepare cache
push!(cachexpr.args,length(cachexpr_lengthtracker.args))#constrcut cache with index cache[1]
push!(x.args, cachexpr)
elseif x.args[2] isa Expr && x.args[2].head == :call && x.args[2].args[1] == :+ && length(x.args[2].args) == 3
push!(x.args, x.args[3])# args[4]=c
x.args[3] = x.args[2].args[3]# args[3]=b
x.args[2] = x.args[2].args[2]# args[2]=a
x.args[1] = :addsub # £ µ § ~....
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
#cachexpr.args[2] = index[i]
push!(x.args, cachexpr)
elseif x.args[2] isa Expr && x.args[2].head == :call && x.args[2].args[1] == :* && length(x.args[2].args) == 3
push!(x.args, x.args[3])# args[4]=c
x.args[3] = x.args[2].args[3]# args[3]=b
x.args[2] = x.args[2].args[2]# args[2]=a
x.args[1] = :mulsub # £ µ § ~....
push!(cachexpr_lengthtracker.args,:b)
cachexpr1 = Expr(:ref, :cache)
push!(cachexpr1.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr1)
else
x.args[1] = :subT # symbol changed cuz avoid type taylor piracy
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr)
end
elseif x isa Expr && x.head == :call && x.args[1] == :- && length(x.args) == 2 && !(x.args[2] isa Number)#negate
x.args[1] = :negateT # symbol changed cuz avoid type taylor piracy
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr)
############################### plus sign#######################################
elseif x isa Expr && x.head == :call && x.args[1] == :+ && length(x.args) == 3 && typeof(x.args[2])!=Int && typeof(x.args[3])!=Int #last 2 to avoid changing u[i+1]
if x.args[2] isa Expr && x.args[2].head == :call && x.args[2].args[1] == :- && length(x.args[2].args) == 3
push!(x.args, x.args[3])# args[4]=c
x.args[3] = x.args[2].args[3]# args[3]=b
x.args[2] = x.args[2].args[2]# args[2]=a
x.args[1] = :subadd#:µ # £ § ....
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
#cachexpr.args[2] = index[i]
push!(x.args, cachexpr)
elseif x.args[2] isa Expr && x.args[2].head == :call && x.args[2].args[1] == :* && length(x.args[2].args) == 3
push!(x.args, x.args[3])# args[4]=c
x.args[3] = x.args[2].args[3]# args[3]=b
x.args[2] = x.args[2].args[2]# args[2]=a
x.args[1] = :muladdT#:µ # £ § ....
push!(cachexpr_lengthtracker.args,:b)
cachexpr1 = Expr(:ref, :cache)
push!(cachexpr1.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr1)
else
x.args[1] = :addT
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr)
end
elseif x isa Expr && x.head == :call && x.args[1] == :+ && (4 <= length(x.args) <= 9) # special add :i stopped at 9 cuz by testing it was allocating anyway after 9
x.args[1] = :addT
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr)
############################### multiply sign#######################################
#never happens :# elseif x isa Expr && x.head == :call && x.args[1]==:* && length(x.args)==3 to get addmul or submul
elseif x isa Expr && x.head == :call && (x.args[1] == :*) && (3 == length(x.args)) && typeof(x.args[2])!=Int && typeof(x.args[3])!=Int #last 2 to avoid changing u[i*1]
x.args[1] = :mulT
push!(cachexpr_lengthtracker.args,:b)
cachexpr1 = Expr(:ref, :cache)
push!(cachexpr1.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr1)
elseif x isa Expr && x.head == :call && (x.args[1] == :*) && (4 <= length(x.args) <= 7)# i stopped at 7 cuz by testing it was allocating anyway after 7
x.args[1] = :mulTT
push!(cachexpr_lengthtracker.args,:b)
cachexpr1 = Expr(:ref, :cache)
push!(cachexpr1.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr1)
push!(cachexpr_lengthtracker.args,:b)
cachexpr2 = Expr(:ref, :cache) #multiply needs two caches
push!(cachexpr2.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr2)
elseif x isa Expr && x.head == :call && (x.args[1] == :/) && typeof(x.args[2])!=Int && typeof(x.args[3])!=Int #last 2 to avoid changing u[i/1]
x.args[1] = :divT
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr)
elseif x isa Expr && x.head == :call && (x.args[1] == :exp ||x.args[1] == :log ||x.args[1] == :sqrt ||x.args[1] == :abs )
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr)
elseif x isa Expr && x.head == :call && (x.args[1] == :^ )
x.args[1] = :powerT # should be like above but for lets keep it now...in test qss.^ caused a problem...fix later
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr)
elseif x isa Expr && x.head == :call && (x.args[1] == :cos ||x.args[1] == :sin ||x.args[1] == :tan||x.args[1] == :atan )
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr)
#second cache
push!(cachexpr_lengthtracker.args,:b)#index2
cachexpr2 = Expr(:ref, :cache)
push!(cachexpr2.args,length(cachexpr_lengthtracker.args))#construct cache[2]
push!(x.args, cachexpr2)
elseif x isa Expr && x.head == :call && (x.args[1] == :acos ||x.args[1] == :asin)
#did not change symbol here
push!(cachexpr_lengthtracker.args,:b)
cachexpr = Expr(:ref, :cache)
push!(cachexpr.args,length(cachexpr_lengthtracker.args))
push!(x.args, cachexpr)
#second cache
push!(cachexpr_lengthtracker.args,:b)#index2
cachexpr2 = Expr(:ref, :cache)
push!(cachexpr2.args,length(cachexpr_lengthtracker.args))#construct cache[2]
push!(x.args, cachexpr2)
#third cache
push!(cachexpr_lengthtracker.args,:b)#index3
cachexpr2 = Expr(:ref, :cache)
push!(cachexpr2.args,length(cachexpr_lengthtracker.args))#construct cache[2]
push!(x.args, cachexpr2)
elseif false #holder for "myviewing" for next symbol for other functions..
end
return x # this is the line that actually enables modification of the original expression (prewalk only)
end#end prewalk
#return ex ########################################************************
ex.args[2]=length(cachexpr_lengthtracker.args)# return the number of caches distributed...later clean the max of all these
return ex
# end #end if number else prewalk
end#end function
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 6666 | # user does not provide solver. default mliqss2 is used
function solve(prob::NLODEProblem{PRTYPE,T,Z,D,CS},tspan::Tuple{Float64, Float64};sparsity::Val{Sparsity}=Val(false),saveat=1e-9::Float64,abstol=1e-4::Float64,reltol=1e-3::Float64,maxErr=Inf::Float64,maxStepsAllowed=10000000) where {PRTYPE,T,Z,D,CS,Sparsity}
solve(prob,QSSAlgorithm(Val(:nmliqss),Val(2)),tspan;sparsity=sparsity,saveat=saveat,abstol=abstol,reltol=reltol,maxErr=maxErr,maxStepsAllowed=maxStepsAllowed)
end
"""solve(prob::NLODEProblem{PRTYPE,T,Z,D,CS},al::QSSAlgorithm{SolverType, OrderType},tspan::Tuple{Float64, Float64};sparsity::Val{Sparsity}=Val(false),saveat=1e-9::Float64,abstol=1e-4::Float64,reltol=1e-3::Float64,maxErr=Inf::Float64,maxStepsAllowed=10000000) where{PRTYPE,T,Z,D,CS,SolverType,OrderType,Sparsity}
This function dispatches on a specific integrator based on the algorithm provided.
With the exception of the argument prob and tspan, all other arguments are optional and have default values:\n
-The algorithm defaults to nmliqss2, and it is specified by the QSSAlgorithm type, which is a composite type that has a name and an order. It can be extended independently of the solver.\n
-The sparsity argument defaults to false. If true, the integrator will use a sparse representation of the Jacobian matrix (not implemented).\n
-The saveat argument defaults to 1e-9. It specifies the time step at which the integrator will save the solution (not implemented).\n
-The abstol argument defaults to 1e-4. It specifies the absolute tolerance of the integrator.\n
-The reltol argument defaults to 1e-3. It specifies the relative tolerance of the integrator.\n
-The maxErr argument defaults to Inf. It specifies the maximum error allowed by the integrator. This is used as an upper bound for the quantum when a variable goes large.\n
-The maxStepsAllowed argument defaults to 10000000. It specifies the maximum number of steps allowed by the integrator. If the user wants to extend the limit on the maximum number of steps, this argument can be used.\n
After the simulation, the solution is returned as a Solution object.
"""
function solve(prob::NLODEProblem{PRTYPE,T,Z,D,CS},al::QSSAlgorithm{SolverType, OrderType},tspan::Tuple{Float64, Float64};sparsity::Val{Sparsity}=Val(false),saveat=1e-9::Float64,abstol=1e-4::Float64,reltol=1e-3::Float64,maxErr=Inf::Float64,maxStepsAllowed=10000000) where{PRTYPE,T,Z,D,CS,SolverType,OrderType,Sparsity}
custom_Solve(prob,al,Val(Sparsity),tspan[2],saveat,tspan[1],abstol,reltol,maxErr,maxStepsAllowed)
end
#default solve method: this is not to be touched...extension or modification is done through creating another custom_solve with different PRTYPE
function custom_Solve(prob::NLODEProblem{PRTYPE,T,Z,D,CS},al::QSSAlgorithm{Solver, Order},::Val{Sparsity},finalTime::Float64,saveat::Float64,initialTime::Float64,abstol::Float64,reltol::Float64,maxErr::Float64,maxStepsAllowed::Int) where{PRTYPE,T,Z,D,CS,Solver,Order,Sparsity}
# sizehint=floor(Int64, 1.0+(finalTime/saveat)*0.6)
commonQSSdata=createCommonData(prob,Val(Order),finalTime,saveat, initialTime,abstol,reltol,maxErr,maxStepsAllowed)
jac=getClosure(prob.jac)::Function #if in future jac and SD are different datastructures
SD=getClosure(prob.SD)::Function
if Solver==:qss
integrate(al,commonQSSdata,prob,prob.eqs,jac,SD)
else
liqssdata=createLiqssData(prob,Val(Sparsity),Val(T),Val(Order))
integrate(al,commonQSSdata,liqssdata,prob,prob.eqs,jac,SD,prob.exactJac)
end
end
#= function getClosure(jacSD::Function)::Function #
function closureJacSD(i::Int)
jacSD(i)
end
return closureJacSD
end =#
function getClosure(jacSD::Vector{Vector{Int}})::Function
function closureJacSD(i::Int)
jacSD[i]
end
return closureJacSD
end
#helper methods...not to be touched...extension can be done through creating others via specializing on one PRTYPE or more of the symbols (PRTYPE,T,Z,D,Order) if in the future...
#################################################################################################################################################################################
function createCommonData(prob::NLODEProblem{PRTYPE,T,Z,D,CS},::Val{Order},finalTime::Float64,saveat::Float64,initialTime::Float64,abstol::Float64,reltol::Float64,maxErr::Float64,maxStepsAllowed::Int)where{PRTYPE,T,Z,D,CS,Order}
quantum = zeros(T)
x = Vector{Taylor0}(undef, T)
q = Vector{Taylor0}(undef, T)
savedTimes=Vector{Vector{Float64}}(undef, T)
savedVars = Vector{Vector{Float64}}(undef, T)
nextStateTime = zeros(T)
nextInputTime = zeros(T)
tx = zeros(T)
tq = zeros(T)
nextEventTime=@MVector zeros(Z)# only Z number of zcf is usually under 100...so use of SA is ok
t = Taylor0(zeros(Order + 1), Order)
t[1]=1.0
t[0]=initialTime
integratorCache=Taylor0(zeros(Order+1),Order) #for integratestate only
d=zeros(D)
for i=1:D
d[i]=prob.discreteVars[i]
end
#= @show d
@show prob.discreteVars =#
for i = 1:T
nextInputTime[i]=Inf
nextStateTime[i]=Inf
x[i]=Taylor0(zeros(Order + 1), Order)
x[i][0]= getInitCond(prob,i) # x[i][0]= prob.initConditions[i] if to remove saving as func
q[i]=Taylor0(zeros(Order+1), Order)#q normally 1order lower than x but since we want f(q) to be a taylor that holds all info (1,2,3), lets have q of same Order and not update last coeff
tx[i] = initialTime
tq[i] = initialTime
savedTimes[i]=Vector{Float64}()
savedVars[i]=Vector{Float64}()
end
taylorOpsCache=Array{Taylor0,1}()# cache= vector of taylor0s of size CS
for i=1:CS
push!(taylorOpsCache,Taylor0(zeros(Order+1),Order))
end
commonQSSdata= CommonQSS_data(quantum,x,q,tx,tq,d,nextStateTime,nextInputTime ,nextEventTime , t, integratorCache,taylorOpsCache,finalTime,saveat, initialTime,abstol,reltol,maxErr,maxStepsAllowed,savedTimes,savedVars)
end
#no sparsity
function createLiqssData(prob::NLODEProblem{PRTYPE,T,Z,D,CS},::Val{false},::Val{T},::Val{Order})where{PRTYPE,T,Z,D,CS,Order}
qaux = Vector{MVector{Order,Float64}}(undef, T)
dxaux=Vector{MVector{Order,Float64}}(undef, T)
for i=1:T
qaux[i]=zeros(MVector{Order,Float64})
dxaux[i]=zeros(MVector{Order,Float64})
end
cacheA=zeros(MVector{1,Float64})
liqssdata= LiQSS_data(Val(false),cacheA,qaux,dxaux)
end
# get init conds for normal vect...getinitcond for fun can be found with qssnlsavedprob file
function getInitCond(prob::NLODEContProblem,i::Int)
return prob.initConditions[i]
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 5807 | #macro NLodeProblem(odeExprs)
"""NLodeProblem(odeExprs)
This function parses the user code to dispatches on a specific problem construction.
It returns a Problem object to be passed to the solve function.
"""
function NLodeProblem(odeExprs)
Base.remove_linenums!(odeExprs)
if VERBOSE println("starting prob parsing...") end
probHelper=arrangeProb(odeExprs)# replace symbols and params , extract info about size,symbols,initconds
probSize=probHelper.problemSize
discSize=probHelper.discreteSize
zcSize=probHelper.numZC
initConds=probHelper.initConditions # vector
symDict=probHelper.symDict
du=probHelper.du
if length(initConds)==0 #user chose shortcuts...initcond saved in a dict
initConds=zeros(probSize)# vector of init conds to be created
savedinitConds=probHelper.savedInitCond #init conds already created in a dict
for i in savedinitConds
if i[1] isa Int #if key (i[1]) is an integer
initConds[i[1]]=i[2]
else # key is an expression
for j=(i[1].args[1]):(i[1].args[2])
initConds[j]=i[2]
end
end
end
end
# @show odeExprs
NLodeProblemFunc(odeExprs,Val(probSize),Val(discSize),Val(zcSize),initConds,du,symDict) #returns prob
end
struct probHelper #helper struct to return stuff from arrangeProb
problemSize::Int
discreteSize::Int
numZC::Int
savedInitCond::Dict{Union{Int,Expr},Float64}
initConditions::Vector{Float64}
du::Symbol
symDict::Dict{Symbol,Expr}
end
function arrangeProb(x::Expr) # replace symbols and params , extract info about sizes,symbols,initconds
param=Dict{Symbol,Union{Float64,Expr}}()
symDict=Dict{Symbol,Expr}()
stateVarName=:q
du=:nothing #default anything
problemSize=0
discreteSize=0
numZC=0
savedInitCond=Dict{Union{Int,Expr},Float64}()
initConditions=Vector{Float64}()
for argI in x.args
if argI isa Expr && argI.head == :(=) #&& @capture(argI, y_ = rhs_)
y=argI.args[1];rhs=argI.args[2]
if y isa Symbol && rhs isa Number #params: fill dict of param
param[y]=rhs
elseif y isa Symbol && rhs isa Expr && (rhs.head==:call || rhs.head==:ref) #params=epression fill dict of param
argI.args[2]=changeVarNames_params(rhs,stateVarName,:nothing,param,symDict)
param[y]=argI.args[2]
elseif y isa Expr && y.head == :ref && rhs isa Number #initial conds "1st way" u[a]=N or u[a:b]=N...
if string(y.args[1])[1] !='d' #prevent the case diffEq du[]=Number
stateVarName=y.args[1] #extract var name
if du==:nothing du=Symbol(:d,stateVarName) end # construct symbol du
if y.args[2] isa Expr && y.args[2].args[1]== :(:) #u[a:b]=N
# length(y.args[2].args)==3 || error(" use syntax u[a:b]") # not needed
savedInitCond[:(($(y.args[2].args[2]),$(y.args[2].args[3])))]=rhs# dict {expr->float}
if problemSize < y.args[2].args[3]
problemSize=y.args[2].args[3] #largest b determines probSize
end
elseif y.args[2] isa Int #u[a]=N
problemSize+=1
savedInitCond[y.args[2]]=rhs#.args[1]
end
end
elseif y isa Symbol && rhs isa Expr && rhs.head==:vect # cont vars u=[] "2nd way" or discrete vars d=[]
if y!=:discrete
stateVarName=y
du=Symbol(:d,stateVarName)
initConditions= convert(Array{Float64,1}, rhs.args)
problemSize=length(rhs.args)
else
discreteSize = length(rhs.args)
end
elseif y isa Expr && y.head == :ref && (rhs isa Expr && rhs.head !=:vect)#&& rhs.head==:call or ref # a diff equa not in a loop
argI.args[2]=changeVarNames_params(rhs,stateVarName,:nothing,param,symDict)
elseif y isa Expr && y.head == :ref && rhs isa Symbol
if haskey(param, rhs)#symbol is a parameter
argI.args[2]=copy(param[rhs])
end
end
elseif @capture(argI, for var_ in b_:niter_ loopbody__ end)
argI.args[2]=changeVarNames_params(loopbody[1],stateVarName,var,param,symDict)
elseif argI isa Expr && argI.head==:if
numZC+=1
(length(argI.args)!=3 && length(argI.args)!=2) && error("use format if A>0 B else C or if A>0 B")
!(argI.args[1] isa Expr && argI.args[1].head==:call && argI.args[1].args[1]==:> && (argI.args[1].args[3]==0||argI.args[1].args[3]==0.0)) && error("use the format 'if a>0: change if a>b to if a-b>0")
# !(argI.args[1].args[2] isa Expr) && error("LHS of > must be be an expression!")
argI.args[1].args[2]=changeVarNames_params(argI.args[1].args[2],stateVarName,:nothing,param)#zcf
# name changes have to be per block
if length(argI.args)==2 #user used if a b
argI.args[2]=changeVarNames_params(argI.args[2],stateVarName,:nothing,param) #posEv
elseif length(argI.args)==3 #user used if a b else c
argI.args[2]=changeVarNames_params(argI.args[2],stateVarName,:nothing,param)#posEv
argI.args[3]=changeVarNames_params(argI.args[3],stateVarName,:nothing,param)#negEv
end
end#end cases of argI
end#end for argI in args
p=probHelper(problemSize,discreteSize,numZC,savedInitCond,initConditions,du,symDict)
end#end function
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 9648 | #using StaticArrays
function minPosRoot(coeff::SVector{2,Float64}, ::Val{1}) # coming from val(1) means coef has x and derx only...size 2 #call from reComputeNextTime
mpr = -1
if coeff[2] == 0
mpr = Inf
else
mpr = -coeff[1] / coeff[2]
end
if mpr < 0
mpr = Inf
end
# println("mpr inside minPosRoot in utils= ",mpr)
return mpr
end
function minPosRoot(coeff::Taylor0, ::Val{1}) # coming from val(1) means coef has x and derx only...size 2 call from compute event order1
mpr = -1
if coeff[1] == 0
mpr = Inf
else
mpr = -coeff[0] / coeff[1]
end
if mpr < 0
mpr = Inf
end
return mpr
end
function minPosRootv1(coeff::NTuple{3,Float64}) #called from updateQ order2
a = coeff[1]
b = coeff[2]
c = coeff[3]
mpr = -1 #coef1=c, coef2=b, coef3=a
if a == 0 || 10000 * abs(a) < abs(b)# coef3 is the coef of t^2
if b == 0 # julia allows to divide by zero and result is Inf ...so no need to check
mpr = Inf
else
mpr = -c / b
end
if mpr < 0
mpr = Inf
end
else
#double disc;
disc = b * b - 4 * a * c#b^2-4ac
if disc < 0 # no real roots
mpr = Inf
else
#double sd, r1;
sd = sqrt(disc)
r1 = (-b + sd) / (2 * a)
if r1 > 0
mpr = r1
else
mpr = Inf
end
r1 = (-b - sd) / (2 * a)
if ((r1 > 0) && (r1 < mpr))
mpr = r1
end
end
end
return mpr
end
function minPosRoot(coeff::SVector{3,Float64}, ::Val{2}) # credit goes to github.com/CIFASIS/qss-solver # call from reComputeNextTime order2
mpr = -1
a = coeff[3]
b = coeff[2]
c = coeff[1] # a is coeff 3 because in taylor representation 1 is var 2 is der 3 is derder
if a == 0 || (10000 * abs(a)) < abs(b)# coef3 is the coef of t^2
if b == 0
mpr = Inf
else
mpr = -c / b
end
if mpr < 0
mpr = Inf
end
else
#double disc;
disc = b * b - 4 * a * c#b^2-4ac
if disc < 0 # no real roots
mpr = Inf
else
#double sd, r1;
sd = sqrt(disc)
r1 = (-b + sd) / (2 * a)
if r1 > 0
mpr = r1
else
mpr = Inf
end
r1 = (-b - sd) / (2 * a)
if ((r1 > 0) && (r1 < mpr))
mpr = r1
end
end
end
return mpr
end
function minPosRoot(coeff::Taylor0, ::Val{2}) # credit goes to github.com/CIFASIS/qss-solver # call from compute event(::Val{2})
mpr = -1
a = coeff[2]
b = coeff[1]
c = coeff[0] # a is coeff 3 because in taylor representation 1 is var 2 is der 3 is derder
if a == 0 || (100000 * abs(a)) < abs(b)# coef3 is the coef of t^2
if b == 0
mpr = Inf
else
mpr = -c / b
end
if mpr < 0
mpr = Inf
end
else
#double disc;
disc = b * b - 4 * a * c#b^2-4ac
if disc < 0 # no real roots
mpr = Inf
else
#double sd, r1;
sd = sqrt(disc)
r1 = (-b + sd) / (2 * a)
if r1 > 0
mpr = r1
else
mpr = Inf
end
r1 = (-b - sd) / (2 * a)
if ((r1 > 0) && (r1 < mpr))
mpr = r1
end
end
end
return mpr
end
function quadRootv2(coeff::NTuple{3,Float64}) # call from mliqss1/simultupdate1
mpr = (-1.0, -1.0) #size 2 to use mpr[2] in quantizer
a = coeff[1]
b = coeff[2]
c = coeff[3]
if a == 0.0 || (1e7 * abs(a)) < abs(b)# coef3 is the coef of t^2
if b != 0.0
if 0 < -c / b < 1e7 # neglecting a small 'a' then having a large h would cause an error 'a*h*h' because large
mpr = (-c / b, -1.0)
end
end
elseif b == 0.0
if -c / a > 0
mpr = (sqrt(-c / a), -1.0)
end
elseif c == 0.0
mpr = (-1.0, -b / a)
else
#double disc;
Δ = 1.0 - 4.0 * c * a / (b * b)
if Δ > 0.0
sq = sqrt(Δ)
r1 = -0.5 * (1.0 + sq) * b / a
r2 = -0.5 * (1.0 - sq) * b / a
mpr = (r1, r2)
elseif Δ == 0.0
r1 = -0.5 * b / a
mpr = (r1, r1 - 1e-12)
end
end
return mpr
end
function constructIntrval2(cache::Vector{Vector{Float64}}, t1::Float64, t2::Float64)
h1 = min(t1, t2)
h4 = max(t1, t2)
# res=((0.0,h1),(h4,Inf))
cache[1][1] = 0.0
cache[1][2] = h1
cache[2][1] = h4
cache[2][2] = Inf
return nothing
end
#constructIntrval(tup2::Tuple{},tup::NTuple{2, Float64})=constructIntrval(tup,tup2)
#merge has 3 elements
function constructIntrval3(cache::Vector{Vector{Float64}}, t1::Float64, t2::Float64, t3::Float64)
#t1=tup[1];t2=tup[2];t3=tup2[1]
t12 = min(t1, t2)
t21 = max(t1, t2)
if t3 < t12
# res=((0.0,t3),(t12,t21))
cache[1][1] = 0.0
cache[1][2] = t3
cache[2][1] = t12
cache[2][2] = t21
else
if t3 < t21
# res=((0.0,t12),(t3,t21))
cache[1][1] = 0.0
cache[1][2] = t12
cache[2][1] = t3
cache[2][2] = t21
else
#res=((0.0,t12),(t21,t3))
cache[1][1] = 0.0
cache[1][2] = t12
cache[2][1] = t21
cache[2][2] = t3
end
end
return nothing
end
#merge has 4 elements
function constructIntrval4(cache::Vector{Vector{Float64}}, t1::Float64, t2::Float64, t3::Float64, t4::Float64,)
# t1=tup[1];t2=tup[2];t3=tup2[1];t4=tup2[2]
h1 = min(t1, t2, t3, t4)
h4 = max(t1, t2, t3, t4)
if t1 == h1
if t2 == h4
# res=((0,t1),(min(t3,t4),max(t3,t4)),(t2,Inf))
cache[1][1] = 0.0
cache[1][2] = t1
cache[2][1] = min(t3, t4)
cache[2][2] = max(t3, t4)
cache[3][1] = t2
cache[3][2] = Inf
elseif t3 == h4
#res=((0,t1),(min(t2,t4),max(t2,t4)),(t3,Inf))
cache[1][1] = 0.0
cache[1][2] = t1
cache[2][1] = min(t2, t4)
cache[2][2] = max(t2, t4)
cache[3][1] = t3
cache[3][2] = Inf
else
# res=((0,t1),(min(t2,t3),max(t2,t3)),(t4,Inf))
cache[1][1] = 0.0
cache[1][2] = t1
cache[2][1] = min(t3, t2)
cache[2][2] = max(t3, t2)
cache[3][1] = t4
cache[3][2] = Inf
end
elseif t2 == h1
if t1 == h4
#res=((0,t2),(min(t3,t4),max(t3,t4)),(t1,Inf))
cache[1][1] = 0.0
cache[1][2] = t2
cache[2][1] = min(t3, t4)
cache[2][2] = max(t3, t4)
cache[3][1] = t1
cache[3][2] = Inf
elseif t3 == h4
#res=((0,t2),(min(t1,t4),max(t1,t4)),(t3,Inf))
cache[1][1] = 0.0
cache[1][2] = t2
cache[2][1] = min(t1, t4)
cache[2][2] = max(t1, t4)
cache[3][1] = t3
cache[3][2] = Inf
else
# res=((0,t2),(min(t1,t3),max(t1,t3)),(t4,Inf))
cache[1][1] = 0.0
cache[1][2] = t2
cache[2][1] = min(t3, t1)
cache[2][2] = max(t3, t1)
cache[3][1] = t4
cache[3][2] = Inf
end
elseif t3 == h1
if t1 == h4
#res=((0,t3),(min(t2,t4),max(t2,t4)),(t1,Inf))
cache[1][1] = 0.0
cache[1][2] = t3
cache[2][1] = min(t2, t4)
cache[2][2] = max(t2, t4)
cache[3][1] = t1
cache[3][2] = Inf
elseif t2 == h4
#res=((0,t3),(min(t1,t4),max(t1,t4)),(t2,Inf))
cache[1][1] = 0.0
cache[1][2] = t3
cache[2][1] = min(t1, t4)
cache[2][2] = max(t1, t4)
cache[3][1] = t2
cache[3][2] = Inf
else
#res=((0,t3),(min(t1,t2),max(t1,t2)),(t4,Inf))
cache[1][1] = 0.0
cache[1][2] = t3
cache[2][1] = min(t1, t2)
cache[2][2] = max(t1, t2)
cache[3][1] = t4
cache[3][2] = Inf
end
else
if t1 == h4
cache[1][1] = 0.0
cache[1][2] = t4
cache[2][1] = min(t3, t2)
cache[2][2] = max(t3, t2)
cache[3][1] = t1
cache[3][2] = Inf
elseif t2 == h4
cache[1][1] = 0.0
cache[1][2] = t4
cache[2][1] = min(t3, t1)
cache[2][2] = max(t3, t1)
cache[3][1] = t2
cache[3][2] = Inf
else
cache[1][1] = 0.0
cache[1][2] = t4
cache[2][1] = min(t1, t2)
cache[2][2] = max(t1, t2)
cache[3][1] = t3
cache[3][2] = Inf
end
end
return nothing
end
@inline function constructIntrval(cache::Vector{Vector{Float64}}, res1::Float64, res2::Float64, res3::Float64, res4::Float64)
if res1 <= 0.0 && res2 <= 0.0 && res3 <= 0.0 && res4 <= 0.0
cache[1][1] = 0.0
cache[1][2] = Inf
elseif res1 > 0.0 && res2 <= 0.0 && res3 <= 0.0 && res4 <= 0.0
cache[1][1] = 0.0
cache[1][2] = res1
elseif res2 > 0.0 && res1 <= 0.0 && res3 <= 0.0 && res4 <= 0.0
cache[1][1] = 0.0
cache[1][2] = res2
elseif res3 > 0.0 && res2 <= 0.0 && res1 <= 0.0 && res4 <= 0.0
cache[1][1] = 0.0
cache[1][2] = res3
elseif res4 > 0.0 && res2 <= 0.0 && res3 <= 0.0 && res1 <= 0.0
cache[1][1] = 0.0
cache[1][2] = res4
elseif res1 > 0.0 && res2 > 0.0 && res3 <= 0.0 && res4 <= 0.0
constructIntrval2(cache, res1, res2)
elseif res1 > 0.0 && res3 > 0.0 && res2 <= 0.0 && res4 <= 0.0
constructIntrval2(cache, res1, res3)
elseif res1 > 0.0 && res4 > 0.0 && res2 <= 0.0 && res3 <= 0.0
constructIntrval2(cache, res1, res4)
elseif res2 > 0.0 && res3 > 0.0 && res1 <= 0.0 && res4 <= 0.0
constructIntrval2(cache, res2, res3)
elseif res2 > 0.0 && res4 > 0.0 && res1 <= 0.0 && res3 <= 0.0
constructIntrval2(cache, res2, res4)
elseif res3 > 0.0 && res4 > 0.0 && res1 <= 0.0 && res2 <= 0.0
constructIntrval2(cache, res3, res4)
elseif res1 > 0.0 && res2 > 0.0 && res3 > 0.0 && res4 <= 0.0
constructIntrval3(cache, res1, res2, res3)
elseif res1 > 0.0 && res2 > 0.0 && res4 > 0.0 && res3 <= 0.0
constructIntrval3(cache, res1, res2, res4)
elseif res1 > 0.0 && res3 > 0.0 && res4 > 0.0 && res2 <= 0.0
constructIntrval3(cache, res1, res3, res4)
elseif res1 <= 0.0 && res3 > 0.0 && res4 > 0.0 && res2 > 0.0
constructIntrval3(cache, res2, res3, res4)
else
constructIntrval4(cache, res1, res2, res3, res4)
end
return nothing
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 8260 | #using TimerOutputs
#using InteractiveUtils
function integrate(Al::QSSAlgorithm{:liqss,O}, CommonqssData::CommonQSS_data{0}, liqssdata::LiQSS_data{O,false}, odep::NLODEProblem{PRTYPE,T,0,0,CS}, f::Function, jac::Function, SD::Function, exactA::Function) where {PRTYPE,CS,O,T}
cacheA = liqssdata.cacheA
ft = CommonqssData.finalTime
initTime = CommonqssData.initialTime
relQ = CommonqssData.dQrel
absQ = CommonqssData.dQmin
maxErr = CommonqssData.maxErr
maxStepsAllowed = CommonqssData.maxStepsAllowed
savetimeincrement = CommonqssData.savetimeincrement
savetime = savetimeincrement # not implemented yet
quantum = CommonqssData.quantum
nextStateTime = CommonqssData.nextStateTime
nextEventTime = CommonqssData.nextEventTime
nextInputTime = CommonqssData.nextInputTime
tx = CommonqssData.tx
tq = CommonqssData.tq
x = CommonqssData.x
q = CommonqssData.q
t = CommonqssData.t
savedVars = CommonqssData.savedVars
savedTimes = CommonqssData.savedTimes
integratorCache = CommonqssData.integratorCache
taylorOpsCache = CommonqssData.taylorOpsCache#Val(CS)=odep.Val(CS)
#***************************************************************
qaux = liqssdata.qaux
dxaux = liqssdata.dxaux#olddxSpec=liqssdata.olddxSpec;olddx=liqssdata.olddx
numSteps = Vector{Int}(undef, T)
d = [0.0]# this is a dummy var used in updateQ and simulUpdate because in the discrete world exactA needs d
exactA(q, d, cacheA, 1, 1, initTime + 1e-9)
#######################################compute initial values##################################################
n = 1
for k = 1:O # compute initial derivatives for x and q (similar to a recursive way )
n = n * k
for i = 1:T
q[i].coeffs[k] = x[i].coeffs[k] # q computed from x and it is going to be used in the next x
end
for i = 1:T
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, q, t, taylorOpsCache)
ndifferentiate!(integratorCache, taylorOpsCache[1], k - 1)
x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2)
end
end
smallAdvance = ft / 100
t[0] = initTime
for i = 1:T
numSteps[i] = 0
push!(savedVars[i], x[i][0])
push!(savedTimes[i], 0.0)
quantum[i] = relQ * abs(x[i].coeffs[1])
quantum[i] = quantum[i] < absQ ? absQ : quantum[i]
quantum[i] = quantum[i] > maxErr ? maxErr : quantum[i]
if isempty(jac(i))
computeNextTime(Val(O), i, initTime, nextInputTime, x, quantum)
if nextInputTime[i] == Inf
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, q, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), i, initTime, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[i] == Inf
nextInputTime[i] = initTime + 10 * smallAdvance
end
end
else
updateQ(Val(O), i, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, initTime + 1e-12, ft, nextStateTime) #1e-9 exactAfunc contains 1/t???
end
end
###################################################################################################################################################################
####################################################################################################################################################################
#---------------------------------------------------------------------------------while loop-------------------------------------------------------------------------
###################################################################################################################################################################
####################################################################################################################################################################
simt = initTime
simulStepCount = 0
totalSteps = 0
simul = false
while simt < ft && totalSteps < maxStepsAllowed
if totalSteps == maxStepsAllowed - 1
@warn("The algorithm liqss$O is taking too long to converge. The simulation will be stopped. Consider using a different algorithm!")
end
sch = updateScheduler(Val(T), nextStateTime, nextEventTime, nextInputTime)
simt = sch[2]
index = sch[1]
if simt > ft
break
end
numSteps[index] += 1
totalSteps += 1
t[0] = simt
##########################################state########################################
if sch[3] == :ST_STATE
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
updateQ(Val(O), index, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, simt, ft, nextStateTime)
tq[index] = simt
for j in SD(index)
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end
end
for b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, q, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for SD
##################################input########################################
elseif sch[3] == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
for k = 1:O
q[index].coeffs[k] = x[index].coeffs[k]
end
tq[index] = simt
#= for b in jac(index)
elapsedq = simt - tq[b]
if elapsedq > 0 ;integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end =#
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, q, t, taylorOpsCache)
computeDerivative(Val(O), x[index], taylorOpsCache[1])
computeNextTime(Val(O), index, simt, nextInputTime, x, quantum) #
if nextInputTime[index] > simt + 2 * elapsed
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, q, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), index, simt, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[index] > simt + 2 * elapsed
nextInputTime[index] = simt + 2 * elapsed
end
end
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
end
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end#q needs to be updated here for recomputeNext
for b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, q, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for
end#end state/input/event
push!(savedVars[index], x[index][0])
push!(savedTimes[index], simt)
end#end while
createSol(Val(T), Val(O), savedTimes, savedVars, "liqss$O", string(odep.prname), absQ, totalSteps, simulStepCount, 0, numSteps, ft)
end#end integrate
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 16308 | function integrate(Al::QSSAlgorithm{:liqss,O}, CommonqssData::CommonQSS_data{Z}, liqssdata::LiQSS_data{O,false}, odep::NLODEProblem{PRTYPE,T,Z,D,CS}, f::Function, jac::Function, SD::Function, exactA::Function) where {PRTYPE,O,T,Z,D,CS}
if VERBOSE println("begining of intgrate function") end
cacheA = liqssdata.cacheA
ft = CommonqssData.finalTime
initTime = CommonqssData.initialTime
relQ = CommonqssData.dQrel
absQ = CommonqssData.dQmin
maxErr = CommonqssData.maxErr
maxStepsAllowed = CommonqssData.maxStepsAllowed
savetimeincrement = CommonqssData.savetimeincrement
savetime = savetimeincrement
quantum = CommonqssData.quantum
nextStateTime = CommonqssData.nextStateTime
nextEventTime = CommonqssData.nextEventTime
nextInputTime = CommonqssData.nextInputTime
tx = CommonqssData.tx
tq = CommonqssData.tq
x = CommonqssData.x
q = CommonqssData.q
t = CommonqssData.t
qaux = liqssdata.qaux
dxaux = liqssdata.dxaux
savedVars = CommonqssData.savedVars
savedTimes = CommonqssData.savedTimes
integratorCache = CommonqssData.integratorCache
taylorOpsCache = CommonqssData.taylorOpsCache#cacheSize=odep.cacheSize
#*********************************problem info*****************************************
d = CommonqssData.d
zc_SimpleJac = odep.ZCjac
HZ = odep.HZ
HD = odep.HD
SZ = odep.SZ
evDep = odep.eventDependencies
# to be removed later: used for root finding using Newton_Intrvals
pp = pointer(Vector{NTuple{2,Float64}}(undef, 7))
respp = pointer(Vector{Float64}(undef, 6))
acceptedi = Vector{Vector{Float64}}(undef, 4 * O - 1)
acceptedj = Vector{Vector{Float64}}(undef, 4 * O - 1)
cacheRootsi = zeros(8 * O - 4) #vect of floats to hold roots for simul_analytic
cacheRootsj = zeros(8 * O - 4)
for i = 1:4*O-1
acceptedi[i] = [0.0, 0.0]#zeros(2)
acceptedj[i] = [0.0, 0.0]#zeros(2)
end
exactA(q, d, cacheA, 1, 1, initTime + 1e-9)
f(1, -1, -1, q, d, t, taylorOpsCache)
trackSimul = Vector{Int}(undef, 1)
#********************************helper values*******************************
oldsignValue = MMatrix{Z,2}(zeros(Z * 2)) #usedto track if zc changed sign; each zc has a value and a sign
numSteps = Vector{Int}(undef, T)
#######################################compute initial values##################################################
n = 1
for k = 1:O # compute initial derivatives for x and q (similar to a recursive way )
n = n * k
for i = 1:T
q[i].coeffs[k] = x[i].coeffs[k]
end # q computed from x and it is going to be used in the next x
for i = 1:T
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, -1, -1, q, d, t, taylorOpsCache)
ndifferentiate!(integratorCache, taylorOpsCache[1], k - 1)
x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2)
end
end
smallAdvance = ft / 1000
t[0] = initTime
for i = 1:T
numSteps[i] = 0
push!(savedVars[i], x[i][0])
push!(savedTimes[i], 0.0)
quantum[i] = relQ * abs(x[i].coeffs[1])
quantum[i] = quantum[i] < absQ ? absQ : quantum[i]
quantum[i] = quantum[i] > maxErr ? maxErr : quantum[i]
if isempty(jac(i))
computeNextTime(Val(O), i, initTime, nextInputTime, x, quantum)
if nextInputTime[i] == Inf
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, -1, -1, q, d, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), i, initTime, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[i] > initTime + 2 * smallAdvance
nextInputTime[i] = initTime + 2 * smallAdvance
end
end
else
updateQ(Val(O), i, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, initTime + 1e-12, ft, nextStateTime) #1e-9 exactAfunc contains 1/t???
end
end
for i = 1:Z
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, i, -1, x, d, t, taylorOpsCache)
oldsignValue[i, 2] = taylorOpsCache[1][0] #value
oldsignValue[i, 1] = sign(taylorOpsCache[1][0]) #sign modify
computeNextEventTime(Val(O), i, taylorOpsCache[1], oldsignValue, initTime, nextEventTime, quantum, absQ)
end
###################################################################################################################################################################
####################################################################################################################################################################
#---------------------------------------------------------------------------------while loop-------------------------------------------------------------------------
###################################################################################################################################################################
####################################################################################################################################################################
simt = initTime
totalSteps = 0
modifiedIndex = 0
countEvents = 0
inputstep = 0
statestep = 0
simulStepCount = 0
ft < savetime && error("ft<savetime")
if VERBOSE println("start integration") end
while simt < ft && totalSteps < maxStepsAllowed
if totalSteps == maxStepsAllowed - 1 @warn("The algorithm liqss$O is taking too long to converge. The simulation will be stopped. Consider using a different algorithm!") end
sch = updateScheduler(Val(T), nextStateTime, nextEventTime, nextInputTime)
simt = sch[2]
index = sch[1]
stepType = sch[3]
if simt > ft
#saveLast!(Val(T),Val(O),savedVars, savedTimes,saveVarsHelper,ft,prevStepTime, x)
break ###################################################break##########################################
end
totalSteps += 1
t[0] = simt
##########################################state########################################
if stepType == :ST_STATE
statestep += 1
xitemp = x[index][0]
numSteps[index] += 1
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
dirI = x[index][0] - xitemp
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
firstguess = updateQ(Val(O), index, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, simt, ft, nextStateTime)
tq[index] = simt
for c in SD(index) #index influences c
elapsedx = simt - tx[c]
if elapsedx > 0
x[c].coeffs[1] = x[c](elapsedx)
tx[c] = simt
end #
elapsedq = simt - tq[c]
if elapsedq > 0
integrateState(Val(O - 1), q[c], elapsedq)
tq[c] = simt
end # c never been visited
clearCache(taylorOpsCache, Val(CS), Val(O))
f(c, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[c], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), c, simt, nextStateTime, x, q, quantum)
end#end for SD
for j in (SZ[index])
for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon.
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, j, -1, q, d, t, taylorOpsCache) # run ZCF--------
computeNextEventTime(Val(O), j, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
end#end for SZ
##################################input########################################
elseif stepType == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself
inputstep += 1
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
for k = 1:O
q[index].coeffs[k] = x[index].coeffs[k]
end
tq[index] = simt
#= for b in jac(index)
elapsedq = simt - tq[b]
if elapsedq > 0 ;integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end =#
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[index], taylorOpsCache[1])
computeNextTime(Val(O), index, simt, nextInputTime, x, quantum) #
if nextInputTime[index] > simt + 2 * elapsed
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, -1, -1, q, d, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), index, simt, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[index] > simt + 2 * elapsed
nextInputTime[index] = simt + 2 * elapsed
end
end
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
end
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end#q needs to be updated here for recomputeNext
# elapsed update all other vars that this derj depends upon.
for b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0 integrateState(Val(O - 1), q[b], elapsedq); tq[b] = simt end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx) ;tx[j] = simt end
elapsedq = simt - tq[j]
if elapsedq > 0 integrateState(Val(O - 1), q[j], elapsedq) ;tq[j] = simt end#q needs to be updated here for recomputeNext
# elapsed update all other vars that this derj depends upon.
for b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for
for j in (SZ[index])
for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon.
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, j, -1, q, d, t, taylorOpsCache) # run ZCF--------
computeNextEventTime(Val(O), j, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
end#end for SZ
#################################################################event########################################
else
for b in zc_SimpleJac[index] # elapsed update all other vars that this zc depends upon.
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
# modifiedIndex=0#first we have a zc happened which corresponds to nexteventtime and index (one of zc) but we want also the sign in O to know ev+ or ev-
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, index, -1, q, d, t, taylorOpsCache) # run ZCF--------
if oldsignValue[index, 2] * taylorOpsCache[1][0] >= 0
if abs(taylorOpsCache[1][0]) > 1e-9 * absQ # if both have same sign and zcf is not very small: zc=1e-9*absQ is allowed as an event
computeNextEventTime(Val(O), index, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
continue
end
end
if abs(oldsignValue[index, 2]) <= 1e-9 * absQ #earlier zc=1e-9*absQ was considered event , so now it should be prevented from passing
nextEventTime[index] = Inf # at this instant next zc will be triggered now, and this will lead to infinite events, so cannot computenextevent here
continue
end
if taylorOpsCache[1][0] > oldsignValue[index, 2] #scheduled rise
modifiedIndex = 2 * index - 1
elseif taylorOpsCache[1][0] < oldsignValue[index, 2] #scheduled drop
modifiedIndex = 2 * index
else # == ( zcf==oldZCF)
computeNextEventTime(Val(O), index, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
continue
end
countEvents += 1
oldsignValue[index, 2] = taylorOpsCache[1][0]
oldsignValue[index, 1] = sign(taylorOpsCache[1][0])
for b in evDep[modifiedIndex].evContRHS
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
f(-1, -1, modifiedIndex, x, d, t, taylorOpsCache)# execute event----------------no need to clear cache; events touch vectors directly
for i in evDep[modifiedIndex].evCont
quantum[i] = relQ * abs(x[i].coeffs[1])
quantum[i] = quantum[i] < absQ ? absQ : quantum[i]
quantum[i] = quantum[i] > maxErr ? maxErr : quantum[i]
firstguess = updateQ(Val(O), i, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, simt, ft, nextStateTime)
tx[i] = simt;tq[i] = simt
Liqss_reComputeNextTime(Val(O), i, simt, nextStateTime, x, q, quantum)
end
computeNextEventTime(Val(O), index, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ) #update zcf before thiscatch in qss quantizer to avoid infinite events
for j in (HD[modifiedIndex]) # care about dependency to this event only
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
end #= @show j,x[j] =#
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end#q needs to be updated here for recomputeNext
for b = 1:T # elapsed update all other vars that this derj depends upon.
if b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end #= @show q[b] =#
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end
for j in (HZ[modifiedIndex])
for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon.
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, j, -1, q, d, t, taylorOpsCache) # run ZCF--------
computeNextEventTime(Val(O), j, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
end
end#end state/input/event
savetime = simt + savetimeincrement # not implemented yet
if stepType != :ST_EVENT
push!(savedVars[index], x[index][0])
push!(savedTimes[index], simt)
else
for j in (HD[modifiedIndex])
push!(savedVars[j], x[j][0])
push!(savedTimes[j], simt)
end
end
end#end while
createSol(Val(T), Val(O), savedTimes, savedVars, "liqss$O", string(odep.prname), absQ, totalSteps, simulStepCount, countEvents, numSteps, ft) #= ,savedDers =#
end#end integrate | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 5879 | function integrate(Al::QSSAlgorithm{:qss,O}, CommonqssData::CommonQSS_data{0}, odep::NLODEProblem{PRTYPE,T,0,0,CS}, f::Function, jac::Function, SD::Function) where {PRTYPE,O,T,CS}
ft = CommonqssData.finalTime
initTime = CommonqssData.initialTime
relQ = CommonqssData.dQrel
absQ = CommonqssData.dQmin
maxErr = CommonqssData.maxErr
maxStepsAllowed = CommonqssData.maxStepsAllowed
quantum = CommonqssData.quantum
nextStateTime = CommonqssData.nextStateTime
nextEventTime = CommonqssData.nextEventTime
nextInputTime = CommonqssData.nextInputTime
tx = CommonqssData.tx
tq = CommonqssData.tq
x = CommonqssData.x
q = CommonqssData.q
t = CommonqssData.t
savedVars = CommonqssData.savedVars
savedTimes = CommonqssData.savedTimes
integratorCache = CommonqssData.integratorCache
taylorOpsCache = CommonqssData.taylorOpsCache
numSteps = Vector{Int}(undef, T)
n = 1
for k = 1:O
n = n * k
for i = 1:T
q[i].coeffs[k] = x[i].coeffs[k]
end
for i = 1:T
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, q, t, taylorOpsCache)
ndifferentiate!(integratorCache, taylorOpsCache[1], k - 1)
x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n
end
end
smallAdvance = ft / 100
t[0] = initTime
for i = 1:T
numSteps[i] = 0
push!(savedVars[i], x[i][0])
push!(savedTimes[i], 0.0)
quantum[i] = relQ * abs(x[i].coeffs[1])
quantum[i] = quantum[i] < absQ ? absQ : quantum[i]
quantum[i] = quantum[i] > maxErr ? maxErr : quantum[i]
if isempty(jac(i))
computeNextTime(Val(O), i, initTime, nextInputTime, x, quantum)
if nextInputTime[i] == Inf
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, q, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), i, initTime, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[i] > initTime + 2 * smallAdvance
nextInputTime[i] = initTime + 2 * smallAdvance
end
end
else
computeNextTime(Val(O), i, initTime, nextStateTime, x, quantum)
end
end
simt = initTime
totalSteps = 0
prevStepTime = initTime
while simt < ft && totalSteps < maxStepsAllowed
if totalSteps == maxStepsAllowed - 1 @warn("The algorithm qss$O is taking too long to converge. The simulation will be stopped. Consider using a different algorithm!") end
sch = updateScheduler(Val(T), nextStateTime, nextEventTime, nextInputTime)
simt = sch[2]
index = sch[1]
totalSteps += 1
t[0] = simt
if sch[3] == :ST_STATE
numSteps[index] += 1
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
for k = 1:O
q[index].coeffs[k] = x[index].coeffs[k]
end
tq[index] = simt
computeNextTime(Val(O), index, simt, nextStateTime, x, quantum)
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
end
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end
for b in (jac(j))
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, q, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end
elseif sch[3] == :ST_INPUT
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
for k = 1:O
q[index].coeffs[k] = x[index].coeffs[k]
end
tq[index] = simt
#= for b in jac(index)
elapsedq = simt - tq[b]
if elapsedq > 0 ;integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end =#
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, q, t, taylorOpsCache)
computeDerivative(Val(O), x[index], taylorOpsCache[1])
computeNextTime(Val(O), index, simt, nextInputTime, x, quantum)
if nextInputTime[index] > simt + 2 * elapsed
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, q, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), index, simt, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[index] > simt + 2 * elapsed
nextInputTime[index] = simt + 2 * elapsed
end
end
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
end
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end
for b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0 integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, q, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end
end
push!(savedVars[index], x[index][0])
push!(savedTimes[index], simt)
end
createSol(Val(T), Val(O), savedTimes, savedVars, "qss$O", string(odep.prname), absQ, totalSteps, 0, 0, numSteps, ft)
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 11484 | function integrate(Al::QSSAlgorithm{:qss,O}, CommonqssData::CommonQSS_data{Z}, odep::NLODEProblem{PRTYPE,T,Z,Y,CS}, f::Function, jac::Function, SD::Function) where {PRTYPE,O,T,Z,Y,CS}
ft = CommonqssData.finalTime
initTime = CommonqssData.initialTime
relQ = CommonqssData.dQrel
absQ = CommonqssData.dQmin
maxErr = CommonqssData.maxErr
maxStepsAllowed = CommonqssData.maxStepsAllowed
quantum = CommonqssData.quantum
nextStateTime = CommonqssData.nextStateTime
nextEventTime = CommonqssData.nextEventTime
nextInputTime = CommonqssData.nextInputTime
tx = CommonqssData.tx
tq = CommonqssData.tq
x = CommonqssData.x
q = CommonqssData.q
t = CommonqssData.t
savedVars = CommonqssData.savedVars
savedTimes = CommonqssData.savedTimes
integratorCache = CommonqssData.integratorCache
taylorOpsCache = CommonqssData.taylorOpsCache
d = CommonqssData.d
zc_SimpleJac = odep.ZCjac
HZ = odep.HZ
HD = odep.HD
SZ = odep.SZ
evDep = odep.eventDependencies
oldsignValue = MMatrix{Z,2}(zeros(Z * 2))
numSteps = Vector{Int}(undef, T)
n = 1
for k = 1:O
n = n * k
for i = 1:T
q[i].coeffs[k] = x[i].coeffs[k]
end
for i = 1:T
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, -1, -1, q, d, t, taylorOpsCache)
ndifferentiate!(integratorCache, taylorOpsCache[1], k - 1)
x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n
end
end
smallAdvance = ft / 100
t[0] = initTime
for i = 1:T
numSteps[i] = 0
push!(savedVars[i], x[i][0])
push!(savedTimes[i], 0.0)
quantum[i] = relQ * abs(x[i].coeffs[1])
quantum[i] = quantum[i] < absQ ? absQ : quantum[i]
quantum[i] = quantum[i] > maxErr ? maxErr : quantum[i]
if isempty(jac(i))
computeNextTime(Val(O), i, initTime, nextInputTime, x, quantum)
if nextInputTime[i] == Inf
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, -1, -1, q, d, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), i, initTime, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[i] > initTime + 2 * smallAdvance
nextInputTime[i] = initTime + 2 * smallAdvance
end
end
else
computeNextTime(Val(O), i, initTime, nextStateTime, x, quantum)
end
end
for i = 1:Z
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, i, -1, x, d, t, taylorOpsCache)
oldsignValue[i, 2] = taylorOpsCache[1][0]
oldsignValue[i, 1] = sign(taylorOpsCache[1][0])
computeNextEventTime(Val(O), i, taylorOpsCache[1], oldsignValue, initTime, nextEventTime, quantum, absQ)
end
simt = initTime
totalSteps = 0
prevStepTime = initTime
modifiedIndex = 0
statestep = 0
countEvents = 0
while simt < ft && totalSteps < maxStepsAllowed
if totalSteps == maxStepsAllowed - 1 @warn("The algorithm qss$O is taking too long to converge. The simulation will be stopped. Consider using a different algorithm!") end
sch = updateScheduler(Val(T), nextStateTime, nextEventTime, nextInputTime)
simt = sch[2]
index = sch[1]
stepType = sch[3]
if simt > ft
break
end
totalSteps += 1
t[0] = simt
if stepType == :ST_STATE
statestep += 1
numSteps[index] += 1
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
#= if abs(x[index].coeffs[2]) > 1e7
quantum[index] = 10 * quantum[index]
end =#
for k = 1:O
q[index].coeffs[k] = x[index].coeffs[k]
end
tq[index] = simt
computeNextTime(Val(O), index, simt, nextStateTime, x, quantum)
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
end
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end
for b in (jac(j))
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end
for j in (SZ[index])
for b in zc_SimpleJac[j]
elapsedq = simt - tq[b]
if elapsedq > 0 integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, j, -1, q, d, t, taylorOpsCache)
computeNextEventTime(Val(O), j, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
end
elseif stepType == :ST_INPUT
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
for k = 1:O
q[index].coeffs[k] = x[index].coeffs[k]
end
tq[index] = simt
#= for b in jac(index)
elapsedq = simt - tq[b]
if elapsedq > 0 ;integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end =#
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[index], taylorOpsCache[1])
computeNextTime(Val(O), index, simt, nextInputTime, x, quantum)
if nextInputTime[index] > simt + 2 * elapsed
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, -1, -1, q, d, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), index, simt, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[index] > simt + 2 * elapsed
nextInputTime[index] = simt + 2 * elapsed
end
end
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
end
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end
for b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0 integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx) ;tx[j] = simt end
elapsedq = simt - tq[j]
if elapsedq > 0 integrateState(Val(O - 1), q[j], elapsedq) ;tq[j] = simt end
for b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0 integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end
for j in (SZ[index])
for b in zc_SimpleJac[j]
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, j, -1, q, d, t, taylorOpsCache)
computeNextEventTime(Val(O), j, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
end
else
for b in zc_SimpleJac[index]
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, index, -1, q, d, t, taylorOpsCache)
if oldsignValue[index, 2] * taylorOpsCache[1][0] >= 0
if abs(taylorOpsCache[1][0]) > 1e-9 * absQ
computeNextEventTime(Val(O), index, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
continue
end
end
if abs(oldsignValue[index, 2]) <= 1e-9 * absQ
nextEventTime[index] = Inf
continue
end
if taylorOpsCache[1][0] > oldsignValue[index, 2]
modifiedIndex = 2 * index - 1
elseif taylorOpsCache[1][0] < oldsignValue[index, 2]
modifiedIndex = 2 * index
else
computeNextEventTime(Val(O), index, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
continue
end
countEvents += 1
oldsignValue[index, 2] = taylorOpsCache[1][0]
oldsignValue[index, 1] = sign(taylorOpsCache[1][0])
for b in evDep[modifiedIndex].evContRHS
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
f(-1, -1, modifiedIndex, x, d, t, taylorOpsCache)
for i in evDep[modifiedIndex].evCont
quantum[i] = relQ * abs(x[i].coeffs[1])
quantum[i] = quantum[i] < absQ ? absQ : quantum[i]
quantum[i] = quantum[i] > maxErr ? maxErr : quantum[i]
for k = 0:O-1 q[i][k] = x[i][k] end
tx[i] = simt
tq[i] = simt
computeNextTime(Val(O), i, simt, nextStateTime, x, quantum)
end
computeNextEventTime(Val(O), index, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
for j in (HD[modifiedIndex])
elapsedx = simt - tx[j]
if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx) ;tx[j] = simt end
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end
for b = 1:T
if b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end
for j in (HZ[modifiedIndex])
for b in zc_SimpleJac[j]
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, j, -1, q, d, t, taylorOpsCache)
computeNextEventTime(Val(O), j, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
end
end
if stepType != :ST_EVENT
push!(savedVars[index], x[index][0])
push!(savedTimes[index], simt)
else
for j in (HD[modifiedIndex])
push!(savedVars[j], x[j][0])
push!(savedTimes[j], simt)
end
end
#prevStepTime = simt
end
createSol(Val(T), Val(O), savedTimes, savedVars, "qss$O", string(odep.prname), absQ, totalSteps, 0, countEvents, numSteps, ft)
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 11416 | function integrate(Al::QSSAlgorithm{:nmliqss,O}, CommonqssData::CommonQSS_data{0}, liqssdata::LiQSS_data{O,false}, odep::NLODEProblem{PRTYPE,T,0,0,CS}, f::Function, jac::Function, SD::Function, exactA::Function) where {PRTYPE,CS,O,T}
cacheA = liqssdata.cacheA
ft = CommonqssData.finalTime
initTime = CommonqssData.initialTime
relQ = CommonqssData.dQrel
absQ = CommonqssData.dQmin
maxErr = CommonqssData.maxErr
maxStepsAllowed = CommonqssData.maxStepsAllowed
quantum = CommonqssData.quantum
nextStateTime = CommonqssData.nextStateTime
nextEventTime = CommonqssData.nextEventTime
nextInputTime = CommonqssData.nextInputTime
tx = CommonqssData.tx
tq = CommonqssData.tq
x = CommonqssData.x
q = CommonqssData.q
t = CommonqssData.t
savedVars = CommonqssData.savedVars
savedTimes = CommonqssData.savedTimes
integratorCache = CommonqssData.integratorCache
taylorOpsCache = CommonqssData.taylorOpsCache#cacheSize=odep.cacheSize
qaux = liqssdata.qaux
dxaux = liqssdata.dxaux #= olddx=liqssdata.olddx; ; olddxSpec=liqssdata.olddxSpec =#
d = [0.0]# this is a dummy var used in updateQ and simulUpdate because in the discrete world exactA needs d, this is better than creating new updateQ and simulUpdate functions
pp = pointer(Vector{NTuple{2,Float64}}(undef, 7))
respp = pointer(Vector{Float64}(undef, 6))
acceptedi = Vector{Vector{Float64}}(undef, 4 * O - 1)
acceptedj = Vector{Vector{Float64}}(undef, 4 * O - 1)
cacheRootsi = zeros(8 * O - 4) #vect of floats to hold roots for simul_analytic
cacheRootsj = zeros(8 * O - 4)
for i = 1:4*O-1 #3
acceptedi[i] = [0.0, 0.0]#zeros(2)
acceptedj[i] = [0.0, 0.0]#zeros(2)
end
exactA(q, d, cacheA, 1, 1, initTime + 1e-9)
trackSimul = Vector{Int}(undef, 1)
numSteps = Vector{Int}(undef, T)
#######################################compute initial values##################################################
n = 1
for k = 1:O # compute initial derivatives for x and q (similar to a recursive way )
n = n * k
for i = 1:T
q[i].coeffs[k] = x[i].coeffs[k] # q computed from x and it is going to be used in the next x
end
for i = 1:T
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, q, t, taylorOpsCache)
ndifferentiate!(integratorCache, taylorOpsCache[1], k - 1)
x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2)
end
end
smallAdvance = ft / 1000
t[0] = initTime
for i = 1:T
numSteps[i] = 0
push!(savedVars[i], x[i][0])
push!(savedTimes[i], 0.0)
quantum[i] = relQ * abs(x[i].coeffs[1])
quantum[i] = quantum[i] < absQ ? absQ : quantum[i]
quantum[i] = quantum[i] > maxErr ? maxErr : quantum[i]
if isempty(jac(i))
# #@show i
computeNextTime(Val(O), i, initTime, nextInputTime, x, quantum)
if nextInputTime[i] == Inf
# #@show nextInputTime
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, q, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), i, initTime, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[i] > initTime + 2 * smallAdvance
nextInputTime[i] = initTime + 2 * smallAdvance
end
end
else
updateQ(Val(O), i, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, initTime + 1e-12, ft, nextStateTime) #1e-9 exactAfunc contains 1/t???
end
end
###################################################################################################################################################################
####################################################################################################################################################################
#---------------------------------------------------------------------------------while loop-------------------------------------------------------------------------
###################################################################################################################################################################
####################################################################################################################################################################
simt = initTime
simulStepCount = 0
totalSteps = 0
inputSteps = 0
printonce = 0
while simt < ft && totalSteps < maxStepsAllowed
if totalSteps == maxStepsAllowed - 1
@warn("The algorithm nmliqss$O is taking too long to converge. The simulation will be stopped. Consider using a different algorithm!")
end
sch = updateScheduler(Val(T), nextStateTime, nextEventTime, nextInputTime)
simt = sch[2]
index = sch[1]
if simt > ft
break #
end
numSteps[index] += 1
totalSteps += 1
t[0] = simt
##########################################state########################################
if sch[3] == :ST_STATE
xitemp = x[index][0]
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
dirI = x[index][0] - xitemp
for b in (jac(index)) # update Qb : to be used to calculate exacte Aindexb...move below updateQ
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
firstguess = updateQ(Val(O), index, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, simt, ft, nextStateTime)
tq[index] = simt
#----------------------------------------------------check dependecy cycles---------------------------------------------
trackSimul[1] = 0
for j in SD(index)
for b in (jac(j)) # update Qb: to be used to calculate exacte Ajb
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
cacheA[1] = 0.0
exactA(q, d, cacheA, index, j, simt)
aij = cacheA[1]#
cacheA[1] = 0.0
exactA(q, d, cacheA, j, index, simt)
aji = cacheA[1]
if j != index && aij * aji != 0.0
if nmisCycle_and_simulUpdate(cacheRootsi, cacheRootsj, acceptedi, acceptedj, aij, aji, respp, pp, trackSimul, Val(O), index, j, dirI, firstguess, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, simt, ft)
simulStepCount += 1
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, q, t, taylorOpsCache)
computeDerivative(Val(O), x[index], taylorOpsCache[1])
for k in SD(j) #j influences k
if k != index && k != j
elapsedx = simt - tx[k]
x[k].coeffs[1] = x[k](elapsedx)
tx[k] = simt
elapsedq = simt - tq[k]
if elapsedq > 0 integrateState(Val(O - 1), q[k], elapsedq) ;tq[k] = simt end
for b in (jac(k))
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(k, q, t, taylorOpsCache)
computeDerivative(Val(O), x[k], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), k, simt, nextStateTime, x, q, quantum)
end#end if k!=0
end#end for k depend on j
end#end ifcycle check
end#end if j!=0
end#end FOR_cycle check
if trackSimul[1] != 0 #qi changed after throw
Liqss_reComputeNextTime(Val(O), index, simt, nextStateTime, x, q, quantum)
end
#-------------------------------------------------------------------------------------
#---------------------------------normal liqss: proceed--------------------------------
#-------------------------------------------------------------------------------------
for c in SD(index) #index influences c
elapsedx = simt - tx[c]
if elapsedx > 0 x[c].coeffs[1] = x[c](elapsedx) ;tx[c] = simt end #
elapsedq = simt - tq[c]
if elapsedq > 0 integrateState(Val(O - 1), q[c], elapsedq) ;tq[c] = simt end # c never been visited
clearCache(taylorOpsCache, Val(CS), Val(O))
f(c, q, t, taylorOpsCache)
computeDerivative(Val(O), x[c], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), c, simt, nextStateTime, x, q, quantum)
end#end for SD
##################################input########################################
elseif sch[3] == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
for k = 1:O
q[index].coeffs[k] = x[index].coeffs[k]
end
tq[index] = simt
#= for b in jac(index)
elapsedq = simt - tq[b]
if elapsedq > 0 ;integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end =#
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, q, t, taylorOpsCache)
computeDerivative(Val(O), x[index], taylorOpsCache[1])
computeNextTime(Val(O), index, simt, nextInputTime, x, quantum) #
if nextInputTime[index] > simt + 2 * elapsed
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, q, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), index, simt, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[index] > simt + 2 * elapsed
nextInputTime[index] = simt + 2 * elapsed
end
end
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
end
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end#q needs to be updated here for recomputeNext
for b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0 integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, q, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for
#################################################################event########################################
end#end state/input/event
push!(savedVars[index], (x[index][0] + q[index][0]) / 2)
push!(savedTimes[index], simt)
end#end while
createSol(Val(T), Val(O), savedTimes, savedVars, "nmliqss$O", string(odep.prname), absQ, totalSteps, simulStepCount, 0, numSteps, ft)
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 19543 | function integrate(Al::QSSAlgorithm{:nmliqss,O}, CommonqssData::CommonQSS_data{Z}, liqssdata::LiQSS_data{O,false}, odep::NLODEProblem{PRTYPE,T,Z,D,CS}, f::Function, jac::Function, SD::Function, exactA::Function) where {PRTYPE,O,T,Z,D,CS}
if VERBOSE println("begining of intgrate function") end
cacheA = liqssdata.cacheA
ft = CommonqssData.finalTime
initTime = CommonqssData.initialTime
relQ = CommonqssData.dQrel
absQ = CommonqssData.dQmin
maxErr = CommonqssData.maxErr
maxStepsAllowed = CommonqssData.maxStepsAllowed
savetimeincrement = CommonqssData.savetimeincrement
savetime = savetimeincrement
quantum = CommonqssData.quantum
nextStateTime = CommonqssData.nextStateTime
nextEventTime = CommonqssData.nextEventTime
nextInputTime = CommonqssData.nextInputTime
tx = CommonqssData.tx
tq = CommonqssData.tq
x = CommonqssData.x
q = CommonqssData.q
t = CommonqssData.t
savedVars = CommonqssData.savedVars
savedTimes = CommonqssData.savedTimes
integratorCache = CommonqssData.integratorCache
taylorOpsCache = CommonqssData.taylorOpsCache#cacheSize=odep.cacheSize
#*********************************problem info*****************************************
d = CommonqssData.d
zc_SimpleJac = odep.ZCjac
HZ = odep.HZ
HD = odep.HD
SZ = odep.SZ
evDep = odep.eventDependencies
qaux = liqssdata.qaux
dxaux = liqssdata.dxaux
# to be deleted: used for root finding using Newton_Intrvals
pp = pointer(Vector{NTuple{2,Float64}}(undef, 7))
respp = pointer(Vector{Float64}(undef, 6))
acceptedi = Vector{Vector{Float64}}(undef, 4 * O - 1)
acceptedj = Vector{Vector{Float64}}(undef, 4 * O - 1)
cacheRootsi = zeros(8 * O - 4) #vect of floats to hold roots for simul_analytic
cacheRootsj = zeros(8 * O - 4)
for i = 1:4*O-1
acceptedi[i] = [0.0, 0.0]#zeros(2)
acceptedj[i] = [0.0, 0.0]#zeros(2)
end
exactA(q, d, cacheA, 1, 1, initTime + 1e-9)
f(1, -1, -1, q, d, t, taylorOpsCache)
trackSimul = Vector{Int}(undef, 1)
#********************************helper values*******************************
oldsignValue = MMatrix{Z,2}(zeros(Z * 2)) #usedto track if zc changed sign; each zc has a value and a sign
numSteps = Vector{Int}(undef, T)
#######################################compute initial values##################################################
n = 1
for k = 1:O # compute initial derivatives for x and q (similar to a recursive way )
n = n * k
for i = 1:T
q[i].coeffs[k] = x[i].coeffs[k]
end # q computed from x and it is going to be used in the next x
for i = 1:T
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, -1, -1, q, d, t, taylorOpsCache)
ndifferentiate!(integratorCache, taylorOpsCache[1], k - 1)
x[i].coeffs[k+1] = (integratorCache.coeffs[1]) / n # /fact cuz i will store der/fac like the convention...to extract the derivatives (at endof sim) multiply by fac derderx=coef[3]*fac(2)
end
end
smallAdvance = ft / 1000
t[0] = initTime
for i = 1:T
numSteps[i] = 0
push!(savedVars[i], x[i][0])
push!(savedTimes[i], 0.0)
quantum[i] = relQ * abs(x[i].coeffs[1])
quantum[i] = quantum[i] < absQ ? absQ : quantum[i]
quantum[i] = quantum[i] > maxErr ? maxErr : quantum[i]
if isempty(jac(i))
computeNextTime(Val(O), i, initTime, nextInputTime, x, quantum)
if nextInputTime[i] == Inf
clearCache(taylorOpsCache, Val(CS), Val(O))
f(i, -1, -1, q, d, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), i, initTime, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[i] > initTime + 2 * smallAdvance
nextInputTime[i] = initTime + 2 * smallAdvance
end
end
else
updateQ(Val(O), i, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, initTime + 1e-12, ft, nextStateTime) #1e-9 exactAfunc contains 1/t???
end
end
for i = 1:Z
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, i, -1, x, d, t, taylorOpsCache)
oldsignValue[i, 2] = taylorOpsCache[1][0] #value
oldsignValue[i, 1] = sign(taylorOpsCache[1][0]) #sign modify
computeNextEventTime(Val(O), i, taylorOpsCache[1], oldsignValue, initTime, nextEventTime, quantum, absQ)
end
###################################################################################################################################################################
####################################################################################################################################################################
#---------------------------------------------------------------------------------while loop-------------------------------------------------------------------------
###################################################################################################################################################################
####################################################################################################################################################################
simt = initTime
totalSteps = 0
prevStepTime = initTime
modifiedIndex = 0
countEvents = 0
inputstep = 0
statestep = 0
simulStepCount = 0
ft < savetime && error("ft<savetime")
if VERBOSE println("start integration") end
while simt < ft && totalSteps < maxStepsAllowed
if totalSteps == maxStepsAllowed - 1 @warn("The algorithm nmliqss$O is taking too long to converge. The simulation will be stopped. Consider using a different algorithm!") end
sch = updateScheduler(Val(T), nextStateTime, nextEventTime, nextInputTime)
simt = sch[2]
index = sch[1]
stepType = sch[3]
if simt > ft
break ###################################################break##########################################
end
totalSteps += 1
t[0] = simt
##########################################state########################################
if stepType == :ST_STATE
statestep += 1
xitemp = x[index][0]
numSteps[index] += 1
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
dirI = x[index][0] - xitemp
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
for b in (jac(index)) # update Qb : to be used to calculate exacte Aindexb
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
firstguess = updateQ(Val(O), index, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, simt, ft, nextStateTime)
tq[index] = simt
#----------------------------------------------------check dependecy cycles---------------------------------------------
trackSimul[1] = 0
for j in SD(index)
for b in (jac(j)) # update Qb: to be used to calculate exacte Ajb
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
cacheA[1] = 0.0
exactA(q, d, cacheA, index, j, simt)
aij = cacheA[1]# can be passed to simul so that i dont call exactfunc again
cacheA[1] = 0.0
exactA(q, d, cacheA, j, index, simt)
aji = cacheA[1]
if j != index && aij * aji != 0.0
if nmisCycle_and_simulUpdate(cacheRootsi, cacheRootsj, acceptedi, acceptedj, aij, aji, respp, pp, trackSimul, Val(O), index, j, dirI, firstguess, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, simt, ft)
simulStepCount += 1
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[index], taylorOpsCache[1])
for k in SD(j) #j influences k
if k != index && k != j
elapsedx = simt - tx[k]
x[k].coeffs[1] = x[k](elapsedx)
tx[k] = simt
elapsedq = simt - tq[k]
if elapsedq > 0
integrateState(Val(O - 1), q[k], elapsedq)
tq[k] = simt
end
for b in (jac(k))
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(k, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[k], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), k, simt, nextStateTime, x, q, quantum)
end#end if k!=0
end#end for k depend on j
for k in (SZ[j]) # qj changed, so zcf should be checked
for b in zc_SimpleJac[k] # elapsed update all other vars that this derj depends upon.
elapsedq = simt - tq[b]
if elapsedq > 0 integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, k, -1, q, d, t, taylorOpsCache) # run ZCF--------
computeNextEventTime(Val(O), k, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
end#end for SZ
end#end ifcycle check
end#end if j!=0
end#end FOR_cycle check
if trackSimul[1] != 0 #qi changed after throw
Liqss_reComputeNextTime(Val(O), index, simt, nextStateTime, x, q, quantum)
end
#-------------------------------------------------------------------------------------
#---------------------------------normal liqss: proceed--------------------------------
#-------------------------------------------------------------------------------------
for c in SD(index) #index influences c
elapsedx = simt - tx[c]
if elapsedx > 0
x[c].coeffs[1] = x[c](elapsedx)
tx[c] = simt
end #
elapsedq = simt - tq[c]
if elapsedq > 0 integrateState(Val(O - 1), q[c], elapsedq) ;tq[c] = simt end # c never been visited
clearCache(taylorOpsCache, Val(CS), Val(O))
f(c, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[c], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), c, simt, nextStateTime, x, q, quantum)
end#end for SD
for j in (SZ[index])
for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon.
elapsedq = simt - tq[b]
if elapsedq > 0 integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, j, -1, q, d, t, taylorOpsCache) # run ZCF--------
computeNextEventTime(Val(O), j, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
end#end for SZ
##################################input########################################
elseif stepType == :ST_INPUT # time of change has come to a state var that does not depend on anything...no one will give you a chance to change but yourself
elapsed = simt - tx[index]
integrateState(Val(O), x[index], elapsed)
tx[index] = simt
quantum[index] = relQ * abs(x[index].coeffs[1])
quantum[index] = quantum[index] < absQ ? absQ : quantum[index]
quantum[index] = quantum[index] > maxErr ? maxErr : quantum[index]
for k = 1:O
q[index].coeffs[k] = x[index].coeffs[k]
end
tq[index] = simt
#= for b in jac(index)
elapsedq = simt - tq[b]
if elapsedq > 0 ;integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end =#
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[index], taylorOpsCache[1])
computeNextTime(Val(O), index, simt, nextInputTime, x, quantum) #
if nextInputTime[index] > simt + 2 * elapsed
clearCache(taylorOpsCache, Val(CS), Val(O))
f(index, -1, -1, q, d, t + smallAdvance, taylorOpsCache)
computeNextInputTime(Val(O), index, simt, smallAdvance, taylorOpsCache[1], nextInputTime, x, quantum)
if nextInputTime[index] > simt + 2 * elapsed
nextInputTime[index] = simt + 2 * elapsed
end
end
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
end
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end#q needs to be updated here for recomputeNext
# elapsed update all other vars that this derj depends upon.
for b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for
for j in (SD(index))
elapsedx = simt - tx[j]
if elapsedx > 0 x[j].coeffs[1] = x[j](elapsedx) ;tx[j] = simt end
elapsedq = simt - tq[j]
if elapsedq > 0 integrateState(Val(O - 1), q[j], elapsedq) ;tq[j] = simt end#q needs to be updated here for recomputeNext
# elapsed update all other vars that this derj depends upon.
for b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0 integrateState(Val(O - 1), q[b], elapsedq) ;tq[b] = simt end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end#end for
for j in (SZ[index])
for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon.
elapsedq = simt - tq[b]
if elapsedq > 0 integrateState(Val(O - 1), q[b], elapsedq); tq[b] = simt end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, j, -1, q, d, t, taylorOpsCache) # run ZCF--------
computeNextEventTime(Val(O), j, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
end#end for SZ
#################################################################event########################################
else
for b in zc_SimpleJac[index] # elapsed update all other vars that this zc depends upon.
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, index, -1, q, d, t, taylorOpsCache) # run ZCF again to verify--------
if oldsignValue[index, 2] * taylorOpsCache[1][0] >= 0 # if computeNextEvent errored
if abs(taylorOpsCache[1][0]) > 1e-9 * absQ # if error is negligeable then ok consider as event, else reject....if both have same sign and zcf is not very small: zc==1e-9*absQ is allowed as an event
computeNextEventTime(Val(O), index, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
continue #event rejected
end
end
if abs(oldsignValue[index, 2]) <= 1e-9 * absQ #earlier zc==1e-9*absQ was considered event , so now it should be prevented from passing
nextEventTime[index] = Inf # at this instant next zc will be triggered now, and this will lead to infinite events, so cannot computenextevent here
continue
end
if taylorOpsCache[1][0] > oldsignValue[index, 2] #scheduled rise
modifiedIndex = 2 * index - 1
elseif taylorOpsCache[1][0] < oldsignValue[index, 2] #scheduled drop
modifiedIndex = 2 * index
else # == ( zcf==oldZCF)
computeNextEventTime(Val(O), index, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
continue
end
countEvents += 1
oldsignValue[index, 2] = taylorOpsCache[1][0]
oldsignValue[index, 1] = sign(taylorOpsCache[1][0])
for b in evDep[modifiedIndex].evContRHS
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
f(-1, -1, modifiedIndex, x, d, t, taylorOpsCache)# execute event----------------no need to clear cache; events touch vectors directly
for i in evDep[modifiedIndex].evCont
quantum[i] = relQ * abs(x[i].coeffs[1])
quantum[i] = quantum[i] < absQ ? absQ : quantum[i]
quantum[i] = quantum[i] > maxErr ? maxErr : quantum[i]
firstguess = updateQ(Val(O), i, x, q, quantum, exactA, d, cacheA, dxaux, qaux, tx, tq, simt, ft, nextStateTime)
tx[i] = simt
tq[i] = simt
Liqss_reComputeNextTime(Val(O), i, simt, nextStateTime, x, q, quantum)
end
computeNextEventTime(Val(O), index, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ) #update zcf before thiscatch in qss quantizer to avoid infinite events
for j in (HD[modifiedIndex]) # care about dependency to this event only
elapsedx = simt - tx[j]
if elapsedx > 0
x[j].coeffs[1] = x[j](elapsedx)
tx[j] = simt
end #= @show j,x[j] =#
elapsedq = simt - tq[j]
if elapsedq > 0
integrateState(Val(O - 1), q[j], elapsedq)
tq[j] = simt
end#q needs to be updated here for recomputeNext
for b = 1:T # elapsed update all other vars that this derj depends upon.
if b in jac(j)
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end #= @show q[b] =#
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(j, -1, -1, q, d, t, taylorOpsCache)
computeDerivative(Val(O), x[j], taylorOpsCache[1])
Liqss_reComputeNextTime(Val(O), j, simt, nextStateTime, x, q, quantum)
end
for j in (HZ[modifiedIndex])
for b in zc_SimpleJac[j] # elapsed update all other vars that this derj depends upon.
elapsedq = simt - tq[b]
if elapsedq > 0
integrateState(Val(O - 1), q[b], elapsedq)
tq[b] = simt
end
end
clearCache(taylorOpsCache, Val(CS), Val(O))
f(-1, j, -1, q, d, t, taylorOpsCache) # run ZCF--------
computeNextEventTime(Val(O), j, taylorOpsCache[1], oldsignValue, simt, nextEventTime, quantum, absQ)
end
end#end state/input/event
savetime = simt + savetimeincrement
if stepType != :ST_EVENT
push!(savedVars[index], x[index][0])
push!(savedTimes[index], simt)
else
for j in (HD[modifiedIndex])
push!(savedVars[j], x[j][0])
push!(savedTimes[j], simt)
end
end
end#end while
createSol(Val(T), Val(O), savedTimes, savedVars, "nmLiqss$O", string(odep.prname), absQ, totalSteps, simulStepCount, countEvents, numSteps, ft) #= ,savedDers =#
end#end integrate | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 2476 | function updateQ(::Val{1}, i::Int, xv::Vector{Taylor0}, qv::Vector{Taylor0}, quantum::Vector{Float64}, exactA::Function, d::Vector{Float64}, cacheA::MVector{1,Float64}, dxaux::Vector{MVector{1,Float64}}, qaux::Vector{MVector{1,Float64}}, tx::Vector{Float64}, tq::Vector{Float64}, simt::Float64, ft::Float64, nextStateTime::Vector{Float64})
cacheA[1] = 0.0
exactA(qv, d, cacheA, i, i, simt)
a = cacheA[1]
q = qv[i][0]
x = xv[i][0]
x1 = xv[i][1]
qaux[i][1] = q
u = x1 - a * q
dxaux[i][1] = x1
h = 0.0
Δ = quantum[i]
if a != 0.0
α = -(a * x + u) / a
h1denom = a * (x + Δ) + u
h2denom = a * (x - Δ) + u
h1 = Δ / h1denom
h2 = -Δ / h2denom
if a < 0
if α > Δ
h = h1
q = x + Δ
elseif α < -Δ
h = h2
q = x - Δ
else
h = Inf
q = -u / a
end
else
if α > Δ
h = h2
q = x - Δ
elseif α < -Δ
h = h1
q = x + Δ
else
if a * x + u > 0
q = x - Δ
h = h2
else
q = x + Δ
h = h1
end
end
end
else
if x1 > 0.0
q = x + Δ
else
q = x - Δ
end
if x1 != 0
h = (abs(Δ / x1))
else
h = Inf
end
end
qv[i][0] = q
nextStateTime[i] = simt + h
return h
end
function Liqss_reComputeNextTime(::Val{1}, i::Int, simt::Float64, nextStateTime::Vector{Float64}, xv::Vector{Taylor0}, qv::Vector{Taylor0}, quantum::Vector{Float64})
dt = 0.0
q = qv[i][0]
x = xv[i][0]
x1 = xv[i][1]
if abs(q - x) >= 2 * quantum[i]
nextStateTime[i] = simt + 1e-12
else
if x1 != 0.0
dt = (q - x) / x1
if dt > 0.0
nextStateTime[i] = simt + dt
elseif dt < 0.0
if x1 > 0.0
nextStateTime[i] = simt + (q - x + 2 * quantum[i]) / x1
else
nextStateTime[i] = simt + (q - x - 2 * quantum[i]) / x1
end
end
else
nextStateTime[i] = Inf
end
end
if nextStateTime[i] <= simt
nextStateTime[i] = simt + Inf
end
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 4605 | #analytic
function updateQ(::Val{2}, i::Int, xv::Vector{Taylor0}, qv::Vector{Taylor0}, quantum::Vector{Float64}, exactA::Function, d::Vector{Float64}, cacheA::MVector{1,Float64}, dxaux::Vector{MVector{2,Float64}}, qaux::Vector{MVector{2,Float64}}, tx::Vector{Float64}, tq::Vector{Float64}, simt::Float64, ft::Float64, nextStateTime::Vector{Float64})
cacheA[1] = 0.0
exactA(qv, d, cacheA, i, i, simt)
a = cacheA[1]
# exactA(xv,cacheA,i,i);a=cacheA[1]
q = qv[i][0]
q1 = qv[i][1]
x = xv[i][0]
x1 = xv[i][1]
x2 = xv[i][2] * 2 #u1=uv[i][i][1]; u2=uv[i][i][2]
qaux[i][1] = q + (simt - tq[i]) * q1#appears only here...updated here and used in updateApprox and in updateQevent later
qaux[i][2] = q1 #appears only here...updated here and used in updateQevent
u1 = x1 - a * qaux[i][1]
u2 = x2 - a * q1
dxaux[i][1] = x1
dxaux[i][2] = x2
ddx = x2
quan = quantum[i]
h = 0.0
if a != 0.0
if a * a * x + a * u1 + u2 <= 0.0
if -(a * a * x + a * u1 + u2) / (a * a) < quan # asymptote<delta...no sol ...no need to check
h = Inf
q = -(a * u1 + u2) / (a * a)#q=x+asymp
else
q = x + quan
coefi = NTuple{3,Float64}(((a * a * (x + quan) + a * u1 + u2) / 2, -a * quan, quan))
h = minPosRootv1(coefi) #needed for dq
#math was used to show h cannot be 1/a
end
elseif a * a * x + a * u1 + u2 >= 0.0
if -(a * a * x + a * u1 + u2) / (a * a) > -quan # asymptote>-delta...no sol ...no need to check
h = Inf
q = -(a * u1 + u2) / (a * a)
else
coefi = NTuple{3,Float64}(((a * a * (x - quan) + a * u1 + u2) / 2, a * quan, -quan))
h = minPosRootv1(coefi)
q = x - quan
end
else#a*a*x+a*u1+u2==0 -->f=0....q=x+f(h)=x+h*g(h) -->g(h)==0...dx==0 -->aq+u==0
q = -u1 / a
h = Inf
end
if h != Inf
if h != 1 / a
q1 = (a * q + u1 + h * u2) / (1 - h * a)
else#h=1/a
error("report bug: updateQ: h cannot=1/a; h=$h , 1/a=$(1/h)")
end
else #h==inf make ddx==0 dq=-u2/a
q1 = -u2 / a
end
else
#println("a==0")
if x2 != 0.0
h = sqrt(abs(2 * quan / x2)) #sqrt necessary with u2
q = x - h * h * x2 / 2
q1 = x1 + h * x2
else
# println("x2==0")
if x1 != 0.0
#quantum[i]=1quan
h = abs(1 * quan / x1) # *10 just to widen the step otherwise it would behave like 1st order
q = x + h * x1
q1 = 0.0
else
h = Inf
q = x
q1 = 0.0
end
end
end
qv[i][0] = q
qv[i][1] = q1
nextStateTime[i] = simt + h
return h
end
function Liqss_reComputeNextTime(::Val{2}, i::Int, simt::Float64, nextStateTime::Vector{Float64}, xv::Vector{Taylor0}, qv::Vector{Taylor0}, quantum::Vector{Float64}) #= ,a::Vector{Vector{Float64}} =#
q = qv[i][0]
x = xv[i][0]
q1 = qv[i][1]
x1 = xv[i][1]
x2 = xv[i][2]
quani = quantum[i]
β = 0
if abs(q - x) >= 2 * quani # this happened when var i and j s turns are now...var i depends on j, j is asked here for next time...or if you want to increase quant*10 later it can be put back to normal and q & x are spread out by 10quan
nextStateTime[i] = simt + 1e-12
else
coef = @SVector [q - x, q1 - x1, -x2]#
nextStateTime[i] = simt + minPosRoot(coef, Val(2))
if q - x > 0.0#1e-9
coef = setindex(coef, q - x - 2 * quantum[i], 1)
timetemp = simt + minPosRoot(coef, Val(2))
if timetemp < nextStateTime[i]
nextStateTime[i] = timetemp
end
elseif q - x < 0.0#-1e-9
coef = setindex(coef, q - x + 2 * quantum[i], 1)
timetemp = simt + minPosRoot(coef, Val(2))
if timetemp < nextStateTime[i]
nextStateTime[i] = timetemp
end
end
if nextStateTime[i] <= simt # this is coming from the fact that a variable can reach 2quan distance when it is not its turn, then computation above gives next=simt+(p-p)/dx...p-p should be zero but it can be very small negative
nextStateTime[i] = simt + Inf#1e-14
# @show simt,nextStateTime[i],i,x,q,quantum[i],xv[i][1]
end
end
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 9387 | ######################################################################################################################################"
function computeNextTime(::Val{1}, i::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})#i can be absorbed
absDeltaT=1e-12 # minimum deltaT to protect against der=Inf coming from sqrt(0) for example...similar to min ΔQ
if (x[i].coeffs[2]) != 0
tempTime=max(abs(quantum[i] /(x[i].coeffs[2])),absDeltaT)# i can avoid the use of max
if tempTime!=absDeltaT #normal
nextTime[i] = simt + tempTime#sqrt(abs(quantum[i] / ((x[i].coeffs[3])*2))) #*2 cuz coeff contains fact()
else#usual (quant/der) is very small
x[i].coeffs[2]=sign(x[i].coeffs[2])*(abs(quantum[i])/absDeltaT)# adjust derivative if it is too high
nextTime[i] = simt + tempTime
#if DEBUG println("*************qssQuantizer: smalldelta in compute next") end
end
else
nextTime[i] = Inf
end
return nothing
end
function computeNextTime(::Val{2}, i::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})
absDeltaT=1e-12 # minimum deltaT to protect against der=Inf coming from sqrt(0) for example...similar to min ΔQ
if (x[i].coeffs[3]) != 0
tempTime=max(sqrt(abs(quantum[i] / ((x[i].coeffs[3])))),absDeltaT)
if tempTime!=absDeltaT #normal
nextTime[i] = simt + tempTime#sqrt(abs(quantum[i] / ((x[i].coeffs[3])*2))) #*2 cuz coeff contains fact()
else#usual sqrt(quant/der) is very small
x[i].coeffs[3]=sign(x[i].coeffs[3])*(abs(quantum[i])/(absDeltaT*absDeltaT))/2# adjust second derivative if it is too high
nextTime[i] = simt + tempTime
#if DEBUG println("qssQuantizer: smalldelta in compute next") end
end
else
if (x[i].coeffs[2]) != 0
tempTime=max(abs(quantum[i] /(x[i].coeffs[2])),absDeltaT)# i can avoid the use of max
if tempTime!=absDeltaT #normal
nextTime[i] = simt + tempTime#sqrt(abs(quantum[i] / ((x[i].coeffs[3])*2))) #*2 cuz coeff contains fact()
else#usual (quant/der) is very small
x[i].coeffs[2]=sign(x[i].coeffs[2])*(abs(quantum[i])/absDeltaT)# adjust derivative if it is too high
nextTime[i] = simt + tempTime
#if DEBUG println("qssQuantizer: smalldelta in compute next") end
end
else
nextTime[i] = Inf
end
end
return nothing
end
#= function computeNextTime(::Val{3}, i::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})
absDeltaT=1e-12 # minimum deltaT to protect against der=Inf coming from sqrt(0) for example...similar to min ΔQ
if (x[i].coeffs[4]) != 0
tempTime=max(cbrt(abs(quantum[i] / ((x[i].coeffs[4])))),absDeltaT) #6/6
if tempTime!=absDeltaT #normal
nextTime[i] = simt + tempTime#sqrt(abs(quantum[i] / ((x[i].coeffs[3])*2))) #*2 cuz coeff contains fact()
else#usual sqrt(quant/der) is very small
x[i].coeffs[4]=sign(x[i].coeffs[4])*(abs(quantum[i])/(absDeltaT*absDeltaT*absDeltaT))/6# adjust third derivative if it is too high
nextTime[i] = simt + tempTime
if DEBUG println("qssQuantizer: smalldelta in compute next") end
end
else
nextTime[i] = Inf
end
return nothing
end =#
######################################################################################################################################"
function reComputeNextTime(::Val{1}, index::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64})
absDeltaT=1e-12
if abs(q[index].coeffs[1] - (x[index].coeffs[1])) >= quantum[index] # this happened when var i and j s turns are now...var i depends on j, j is asked here for next time
nextTime[index] = simt+1e-16
else
coef=@SVector [q[index].coeffs[1] - (x[index].coeffs[1]) - quantum[index], -x[index].coeffs[2]]
time1 = minPosRoot(coef, Val(1))
coef=setindex(coef,q[index].coeffs[1] - (x[index].coeffs[1]) + quantum[index],1)
time2 = minPosRoot(coef, Val(1))
timeTemp = time1 < time2 ? time1 : time2
tempTime=max(timeTemp,absDeltaT) #guard against very small Δt
nextTime[index] = simt +tempTime
end
end
function reComputeNextTime(::Val{2}, index::Int, simt::Float64, nextTime::Vector{Float64}, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64})
absDeltaT=1e-15
if abs(q[index].coeffs[1] - (x[index].coeffs[1])) >= quantum[index] # this happened when var i and j s turns are now...var i depends on j, j is asked here for next time
nextTime[index] = simt+1e-12
else
coef=@SVector [q[index].coeffs[1] - (x[index].coeffs[1]) - quantum[index], q[index].coeffs[2]-x[index].coeffs[2],-(x[index].coeffs[3])]#not *2 because i am solving c+bt+a/2*t^2
time1 = minPosRoot(coef, Val(2))
coef=setindex(coef,q[index].coeffs[1] - (x[index].coeffs[1]) + quantum[index],1)
time2 = minPosRoot(coef, Val(2))
timeTemp = time1 < time2 ? time1 : time2
tempTime=max(timeTemp,absDeltaT)#guard against very small Δt
nextTime[index] = simt +tempTime
end
return nothing
end
######################################################################################################################################"
function computeNextInputTime(::Val{1}, i::Int, simt::Float64,elapsed::Float64, tt::Taylor0 ,nextInputTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})
df=0.0
oldDerX=x[i].coeffs[2]
newDerX=tt.coeffs[1]
if elapsed > 0
df=(newDerX-oldDerX)/elapsed #df mimics second der
else
df= quantum[i]*1e6
end
if df!=0.0
nextInputTime[i]=simt+sqrt(abs(2*quantum[i] / df))
else
nextInputTime[i] = Inf
end
return nothing
end
function computeNextInputTime(::Val{2}, i::Int, simt::Float64,elapsed::Float64, tt::Taylor0 ,nextInputTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})
ddf=0.0;df=0.0
oldDerDerX=((x[i].coeffs[3])*2.0)
newDerDerX=(tt.coeffs[2])# 1st der of tt cuz tt itself is derx=f
if elapsed > 0.0
ddf=(newDerDerX-oldDerDerX)/(elapsed)
else
ddf= quantum[i]*1e6#*1e12
#if DEBUG println("QSS quantizer elapsed=0!") end
end
if ddf!=0.0
nextInputTime[i]=simt+cbrt((abs(quantum[i]/df))) #ddf mimics 3rd der
else #df=0->newddx=oldddx ->
#if DEBUG println("QSS quantizer ddf=0 ") end
oldDerX=((x[i].coeffs[2]))
newDerX=(tt.coeffs[1])# 1st der of tt cuz tt itself is derx=f
if elapsed > 0.0
df=(newDerX-oldDerX)/(elapsed) #df mimic second derivative
else
df= quantum[i]*1e6#*1e12
end
if df!=0.0
nextInputTime[i]=simt+sqrt((abs(quantum[i]/df)))
else
if x[i][1]!=0 #predicted second derivative is 0 & should not be used to determine nexttime. use 1st der
nextInputTime[i]=simt+sqrt(abs(1*quantum[i] / x[i][1])) #I used the same formulae even with 1st der so that it is fair to other vars
else
nextInputTime[i] = Inf
end
end
end
return nothing
end
#= function computeNextInputTime(::Val{3}, i::Int, simt::Float64,elapsed::Float64, tt::Taylor0 ,nextInputTime::Vector{Float64}, x::Vector{Taylor0}, quantum::Vector{Float64})
df=0.0
oldDerDerX=((x[i].coeffs[3])*2.0)
#@show x
newDerDerX=(tt.coeffs[2])# 1st der of tt cuz tt itself is derx=f
#@show newDerDerX
if elapsed > 0.0
df=(newDerDerX-oldDerDerX)/(elapsed)
# println("df=new-old= ",df)
else
df= quantum[i]*1e6#*1e12
end
if df!=0.0
nextInputTime[i]=simt+cbrt((abs(quantum[i]/df))) #df mimics 3rd der
# println("usedcbrt")
else
if newDerDerX==0 && x[i][1]!=0 #predicted second derivative is 0 & should be not be used to determine nexttime. use 1st der
#nextInputTime[i]=simt+(abs(2*quantum[i] / x[i][1])) #*2 is not analytic: is just there to increase stepsize
nextInputTime[i]=simt+sqrt(abs(1*quantum[i] / x[i][1])) #I used the same formulae even with 1st der so that it is fair to other vars
else
nextInputTime[i] = Inf
end
end
return nothing
end =#
function computeNextEventTime(::Val{O},j::Int,ZCFun::Taylor0,oldsignValue,simt, nextEventTime, quantum::Vector{Float64},absQ::Float64) where {O}
if (oldsignValue[j,1] != sign(ZCFun[0])) && abs(oldsignValue[j,2]) >1e-9*absQ #prevent double tapping: when zcf is leaving zero it should be considered an event
if DEBUG println("qss quantizer:zcf$j immediate event at simt= $simt oldzcf value= $(oldsignValue[j,2]) newZCF value= $(ZCFun[0])"); end
nextEventTime[j]=simt
elseif oldsignValue[j,2] ==0.0 && ZCFun[0] ==0.0 # initial value 0 --> do not do anything
nextEventTime[j]=Inf
else # old and new ZCF both pos or both neg
mpr=minPosRoot(ZCFun, Val(O))
if mpr<1e-14 # prevent very close events
mpr=1e-12
end
nextEventTime[j] =simt + mpr
if DEBUG
println("qss quantizer:zcf$j at simt= $simt ****scheduled**** event at $(simt + mpr) oldzcf value= $(oldsignValue[j,2]) newZCF value= $(ZCFun[0])")
end
oldsignValue[j,1]=sign(ZCFun[0])#update the values
oldsignValue[j,2]=ZCFun[0]
end
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1264 | @inline function integrateState(::Val{0}, x::Taylor0,elapsed::Float64)
#nothing: created for elapse-updating q in order1 which does not happen
end
@inline function integrateState(::Val{1}, x::Taylor0,elapsed::Float64)
x.coeffs[1] = x(elapsed)
end
@inline function integrateState(::Val{2}, x::Taylor0,elapsed::Float64)
x.coeffs[1] = x(elapsed)
x.coeffs[2] = x.coeffs[2]+elapsed*x.coeffs[3]*2
end
#= @inline function integrateState(::Val{3}, x::Taylor0,elapsed::Float64)
x.coeffs[1] = x(elapsed)
x.coeffs[2] = x.coeffs[2]+elapsed*x.coeffs[3]*2+elapsed*elapsed*x.coeffs[4]*3
x.coeffs[3] = x.coeffs[3]+elapsed*x.coeffs[4]*3#(x.coeffs[3]*2+elapsed*x.coeffs[4]*6)/2
end =#
######################################################################################################################################"
function computeDerivative( ::Val{1} ,x::Taylor0,f::Taylor0 )
x.coeffs[2] =f.coeffs[1]
return nothing
end
function computeDerivative( ::Val{2} ,x::Taylor0,f::Taylor0)
x.coeffs[2] =f.coeffs[1]
x.coeffs[3] =f.coeffs[2]/2
return nothing
end
#= function computeDerivative( ::Val{3} ,x::Taylor0,f::Taylor0)
x.coeffs[2] =f[0]
x.coeffs[3]=f.coeffs[2]/2
x.coeffs[4]=f.coeffs[3]/3 # coeff3*2/6
return nothing
end =# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 7047 | #analy
function nmisCycle_and_simulUpdate(cacheRootsi::Vector{Float64}, cacheRootsj::Vector{Float64}, acceptedi::Vector{Vector{Float64}}, acceptedj::Vector{Vector{Float64}}, aij::Float64, aji::Float64, respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}}, trackSimul, ::Val{1}, index::Int, j::Int, dirI::Float64, dti::Float64, x::Vector{Taylor0}, q::Vector{Taylor0}, quantum::Vector{Float64}, exacteA::Function, d::Vector{Float64}, cacheA::MVector{1,Float64}, dxaux::Vector{MVector{1,Float64}}, qaux::Vector{MVector{1,Float64}}, tx::Vector{Float64}, tq::Vector{Float64}, simt::Float64, ft::Float64)
cacheA[1] = 0.0
exacteA(q, d, cacheA, index, index, simt)
aii = cacheA[1]
cacheA[1] = 0.0
exacteA(q, d, cacheA, j, j, simt)
ajj = cacheA[1]
xi = x[index][0]
xj = x[j][0]
ẋi = x[index][1]
ẋj = x[j][1]
qi = q[index][0]
qj = q[j][0]
quanj = quantum[j]
quani = quantum[index]
elapsed = simt - tx[j]
x[j][0] = xj + elapsed * ẋj
xj = x[j][0]
tx[j] = simt
qiminus = qaux[index][1]
uji = ẋj - ajj * qj - aji * qiminus
uij = dxaux[index][1] - aii * qiminus - aij * qj
iscycle = false
dxj = aji * qi + ajj * qj + uji #only future qi #emulate fj
dxithrow = aii * qi + aij * qj + uij #only future qi
qjplus = xj + sign(dxj) * quanj #emulate updateQ(j)...
dxi = aii * qi + aij * qjplus + uij #both future qi & qj #emulate fi
########condition:Union
#= if abs(dxj)*3<abs(ẋj) || abs(dxj)>3*abs(ẋj) || (dxj*ẋj)<0.0
if abs(dxi)>3*abs(ẋi) || abs(dxi)*3<abs(ẋi) || (dxi*ẋi)<0.0
iscycle=true
end
end =#
########condition:Union i union
if (abs(dxj) * 3 < abs(ẋj) || abs(dxj) > 3 * abs(ẋj) || (dxj * ẋj) < 0.0)
cancelCriteria = 1e-6 * quani
if abs(dxi) > 3 * abs(dxithrow) || abs(dxi) * 3 < abs(dxithrow) || (dxi * dxithrow) < 0.0
iscycle = true
if abs(dxi) < cancelCriteria && abs(dxithrow) < cancelCriteria #significant change is relative to der values. cancel if all values are small
iscycle = false
end
end
if abs(dxi) > 10 * abs(ẋi) || abs(dxi) * 10 < abs(ẋi) #|| (dxi*ẋi)<0.0
iscycle = true
if abs(dxi) < cancelCriteria && abs(ẋi) < cancelCriteria #significant change is relative to der values. cancel if all values are small
iscycle = false
end
end
if abs(dxj) < 1e-6 * quanj && abs(ẋj) < 1e-6 * quanj #significant change is relative to der values. cancel if all values are small
iscycle = false
end
end
if iscycle
#clear accIntrvals and cache of roots
for i = 1:3# 3 ord1 ,7 ord2
acceptedi[i][1] = 0.0
acceptedi[i][2] = 0.0
acceptedj[i][1] = 0.0
acceptedj[i][2] = 0.0
end
for i = 1:4
cacheRootsi[i] = 0.0
cacheRootsj[i] = 0.0
end
#find positive zeros f=+-Δ
bi = aii * xi + aij * xj + uij
ci = aij * (aji * xi + uji) - ajj * (aii * xi + uij)
αi = -ajj - aii
βi = aii * ajj - aij * aji
bj = ajj * xj + aji * xi + uji
cj = aji * (aij * xj + uij) - aii * (ajj * xj + uji)
αj = -aii - ajj
βj = ajj * aii - aji * aij
coefi = NTuple{3,Float64}((βi * quani - ci, αi * quani - bi, quani))
coefi2 = NTuple{3,Float64}((-βi * quani - ci, -αi * quani - bi, -quani))
coefj = NTuple{3,Float64}((βj * quanj - cj, αj * quanj - bj, quanj))
coefj2 = NTuple{3,Float64}((-βj * quanj - cj, -αj * quanj - bj, -quanj))
resi1, resi2 = quadRootv2(coefi)
resi3, resi4 = quadRootv2(coefi2)
resj1, resj2 = quadRootv2(coefj)
resj3, resj4 = quadRootv2(coefj2)
#construct intervals
constructIntrval(acceptedi, resi1, resi2, resi3, resi4)
constructIntrval(acceptedj, resj1, resj2, resj3, resj4)
#find best H (largest overlap)
ki = 3
kj = 3
while true
currentLi = acceptedi[ki][1]
currentHi = acceptedi[ki][2]
currentLj = acceptedj[kj][1]
currentHj = acceptedj[kj][2]
if currentLj <= currentLi < currentHj || currentLi <= currentLj < currentHi#resj[end][1]<=resi[end][1]<=resj[end][2] || resi[end][1]<=resj[end][1]<=resi[end][2] #overlap
h = min(currentHi, currentHj)
if h == Inf && (currentLj != 0.0 || currentLi != 0.0) # except case both 0 sols h1=(0,Inf)
h = max(currentLj, currentLi) #ft-simt in case they are both ver small...elaborate on his later
end
if h == Inf # both lower bounds ==0 --> zero sols for both
qi = getQfromAsymptote(simt, xi, βi, ci, αi, bi)
qj = getQfromAsymptote(simt, xj, βj, cj, αj, bj)
else
Δ = (1 - h * aii) * (1 - h * ajj) - h * h * aij * aji
if Δ != 0.0
qi = ((1 - h * ajj) * (xi + h * uij) + h * aij * (xj + h * uji)) / Δ
qj = ((1 - h * aii) * (xj + h * uji) + h * aji * (xi + h * uij)) / Δ
else
qi, qj, h, maxIter = IterationH(h, xi, quani, xj, quanj, aii, ajj, aij, aji, uij, uji)
if maxIter == 0
return false
end
end
end
break
else
if currentHj == 0.0 && currentHi == 0.0#empty
ki -= 1
kj -= 1
elseif currentHj == 0.0 && currentHi != 0.0
kj -= 1
elseif currentHi == 0.0 && currentHj != 0.0
ki -= 1
else #both non zero
if currentLj < currentLi#remove last seg of resi
ki -= 1
else #remove last seg of resj
kj -= 1
end
end
end
end # end while
q[j][0] = qj
tq[j] = simt
q[index][0] = qi# store back helper vars
trackSimul[1] += 1 # do not have to recomputeNext if qi never changed
end
return iscycle
end
function getQfromAsymptote(simt, x::Float64, β::P, c::P, α::P, b::P) where {P<:Union{BigFloat,Float64}}
q = 0.0
if β == 0.0 && c != 0.0
println("report bug: β==0 && c!=0.0: this leads to asym=Inf while this code came from asym<Delta at $simt")
elseif β == 0.0 && c == 0.0
if α == 0.0 && b != 0.0
println("report bug: α==0 && b!=0.0 this leads to asym=Inf while this code came from asym<Delta at $simt")
elseif α == 0.0 && b == 0.0
q = x
else
q = x + b / α
end
else
q = x + c / β #asymptote...even though not guaranteed to be best
end
q
end
function iterationH(h::Float64, xi::Float64, quani::Float64, xj::Float64, quanj::Float64, aii::Float64, ajj::Float64, aij::Float64, aji::Float64, uij::Float64, uji::Float64)
qi, qj = 0.0, 0.0
maxIter = 1000
while (abs(qi - xi) > 1 * quani || abs(qj - xj) > 1 * quanj) && (maxIter > 0)
maxIter -= 1
h1 = h * (0.99 * quani / abs(qi - xi))
h2 = h * (0.99 * quanj / abs(qj - xj))
h = min(h1, h2)
h_three = h
Δ = (1 - h * aii) * (1 - h * ajj) - h * h * aij * aji
if Δ != 0
qi = ((1 - h * ajj) * (xi + h * uij) + h * aij * (xj + h * uji)) / Δ
qj = ((1 - h * aii) * (xj + h * uji) + h * aji * (xi + h * uij)) / Δ
end
# if maxIter < 1 println("maxiter of updateQ = ",maxIter) end
end
qi, qj, h, maxIter
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 11165 | function nmisCycle_and_simulUpdate(cacheRootsi::Vector{Float64},cacheRootsj::Vector{Float64},acceptedi::Vector{Vector{Float64}},acceptedj::Vector{Vector{Float64}},aij::Float64,aji::Float64,respp::Ptr{Float64}, pp::Ptr{NTuple{2,Float64}},trackSimul,::Val{2},index::Int,j::Int,dirI::Float64,firstguessH::Float64, x::Vector{Taylor0},q::Vector{Taylor0}, quantum::Vector{Float64},exactA::Function,d::Vector{Float64},cacheA::MVector{1,Float64},dxaux::Vector{MVector{2,Float64}},qaux::Vector{MVector{2,Float64}},tx::Vector{Float64},tq::Vector{Float64},simt::Float64,ft::Float64)
cacheA[1]=0.0;exactA(q,d,cacheA,index,index,simt)
aii=cacheA[1]
cacheA[1]=0.0; exactA(q,d,cacheA,j,j,simt)
ajj=cacheA[1]
uii=dxaux[index][1]-aii*qaux[index][1]
ui2=dxaux[index][2]-aii*qaux[index][2]
xi=x[index][0];xj=x[j][0];qi=q[index][0];qj=q[j][0];qi1=q[index][1];qj1=q[j][1];xi1=x[index][1];xi2=2*x[index][2];xj1=x[j][1];xj2=2*x[j][2]
quanj=quantum[j];quani=quantum[index];
e1 = simt - tx[j];e2 = simt - tq[j];#= e3=simt - tu[j];tu[j]=simt; =#
prevXj=x[j][0]
x[j][0]= x[j](e1);xj=x[j][0];tx[j]=simt
qj=qj+e2*qj1 ;qaux[j][1]=qj;tq[j] = simt ;q[j][0]=qj
xj1=x[j][1]+e1*xj2;
newDiff=(xj-prevXj)
ujj=xj1-ajj*qj
uji=ujj-aji*qaux[index][1]#
uj2=xj2-ajj*qj1###################################################-----------------------
uji2=uj2-aji*qaux[index][2]#
dxj=aji*qi+ajj*qaux[j][1]+uji
ddxj=aji*qi1+ajj*qj1+uji2
if abs(ddxj)==0.0 ddxj=1e-30 end
iscycle=false
qjplus=xj-sign(ddxj)*quanj
hj=sqrt(2*quanj/abs(ddxj))#
α1=1-hj*ajj
if abs(α1)==0.0 α1=1e-30 end
dqjplus=(aji*(qi+hj*qi1)+ajj*qjplus+uji+hj*uji2)/α1
uij=uii-aij*qaux[j][1]
uij2=ui2-aij*qj1#########qaux[j][2] updated in normal Qupdate..ft=20 slightly shifts up
dxithrow=aii*qi+aij*qj+uij
ddxithrow=aii*qi1+aij*qj1+uij2
dxi=aii*qi+aij*qjplus+uij
ddxi=aii*qi1+aij*dqjplus+uij2
if abs(ddxi)==0.0 ddxi=1e-30 end
hi=sqrt(2*quani/abs(ddxi))
βidir=dxi+hi*ddxi/2
βjdir=dxj+hj*ddxj/2
βidth=dxithrow+hi*ddxithrow/2
αidir=xi1+hi*xi2/2
βj=xj1+hj*xj2/2
########condition:Union
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2)) || βidir*dirI<0.0
iscycle=true
end
end
########condition:Union i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) || dqjplus*newDiff<0.0 #(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) || βidir*dirI<0.0
iscycle=true
end
end =#
########condition:combineDer Union i
#= if abs(βjdir-βj)>(abs(βjdir+βj)/2) || dqjplus*newDiff<0.0
if abs(βidir-βidth)>(abs(βidir+βidth)/2) || βidir*dirI<0.0
iscycle=true
end
coef_signig=100
if (abs(dxi)>(abs(xi1)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#) || (abs(xi1)>(abs(dxi)*coef_signig) #= && (abs(ddxi)>(abs(xi2)*coef_signig)||abs(xi2)>(abs(ddxi)*coef_signig)) =#)
iscycle=true
end
#= if abs(βidir-αidir)>(abs(βidir+αidir)/2)
iscycle=true
end =#
end =#
if (ddxithrow>0 && dxithrow<0 && qi1>0) || (ddxithrow<0 && dxithrow>0 && qi1<0)
xmin=xi-dxithrow*dxithrow/ddxithrow
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end
#= if (ddxi>0 && dxi<0 && qi1>0) || (ddxi<0 && dxi>0 && qi1<0)
xmin=xi-dxi*dxi/ddxi
if abs(xmin-xi)/abs(qi-xi)>0.8 # xmin is close to q and a change in q might flip its sign of dq
iscycle=false #
end
end =#
########condition:kinda signif alone i
#= if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) # || dqjplus*newDiff<0.0
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2)) #|| βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-xi1)>(abs(dxi+xi1)/2) || abs(ddxi-xi2)>(abs(ddxi+xi2)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
########condition:cond1 i
#= if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end
if dqjplus*newDiff<0.0 #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if (abs(dxi-dxithrow)>(abs(dxi+dxithrow)/2) || abs(ddxi-ddxithrow)>(abs(ddxi+ddxithrow)/2))
iscycle=true
end
end
if (abs(dxj-xj1)>(abs(dxj+xj1)/2) || abs(ddxj-xj2)>(abs(ddxj+xj2)/2)) #= || (dqjplus==0.0 && newDiff!=0.0) =##(dqjplus*qj1)<=0.0 with dir is better since when dir =0 we do not enter
if βidir*dirI<0.0
iscycle=true
end
end =#
#= if index==1 && j==4 && 0.1<simt<1.1
iscycle=true
end =#
if iscycle
aiijj=aii+ajj
aiijj_=aij*aji-aii*ajj
coefΔh1=-8.0*aiijj
coefΔh2=6.0*aiijj*aiijj-4.0*aiijj_
coefΔh3=6.0*aiijj*aiijj_-2.0*aiijj*aiijj*aiijj
coefΔh4=aiijj_*aiijj_-4.0*aiijj_*aiijj*aiijj
coefΔh5=-3.0*aiijj*aiijj_*aiijj_
coefΔh6=-aiijj_*aiijj_*aiijj_
coefH1=-8.0*xi*aiijj
coefH2=2.0*(-aii*uij-aij*uji-uij2+xi*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*aii*ajj-aji*aij+ajj*ajj)-aij*aiijj*xj)
coefH3=2.0*((-uij*aiijj_+ajj*uij2-aij*uji2)+aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-xi*aiijj*(2.0*aii*ajj-aji*aij+ajj*ajj)+ajj*aiijj_*xi+aij*aiijj*aiijj*xj-aij*aiijj_*xj)
coefH4=2.0*(aiijj*(uij*aiijj_-ajj*uij2+aij*uji2)-0.5*(2.0*aii*ajj-aji*aij+ajj*ajj)*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-ajj*aiijj_*aiijj*xi+0.5*aij*aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)+aij*aiijj_*aiijj*xj)
coefH5=(2.0*aii*ajj-aji*aij+ajj*ajj)*(ajj*uij2-uij*aiijj_-aij*uji2)-ajj*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)-aij*aiijj*(aii*uji2-uji*aiijj_-aji*uij2)+aij*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)
coefH6=ajj*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)-aij*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)
coefH1j=-8.0*xj*aiijj
coefH2j=2.0*(-ajj*uji-aji*uij-uji2+xj*(-2.0*aiijj_+2.0*aiijj*aiijj+2.0*ajj*aii-aij*aji+aii*aii)-aji*aiijj*xi)
coefH3j=2.0*((-uji*aiijj_+aii*uji2-aji*uij2)+aiijj*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-xj*aiijj*(2.0*ajj*aii-aij*aji+aii*aii)+aii*aiijj_*xj+aji*aiijj*aiijj*xi-aji*aiijj_*xi)
coefH4j=2.0*(aiijj*(uji*aiijj_-aii*uji2+aji*uij2)-0.5*(2.0*ajj*aii-aij*aji+aii*aii)*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aii*aiijj_*aiijj*xj+0.5*aji*aiijj*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)+aji*aiijj_*aiijj*xi)
coefH5j=(2.0*ajj*aii-aij*aji+aii*aii)*(aii*uji2-uji*aiijj_-aji*uij2)-aii*aiijj_*(ajj*uji+aji*uij+uji2+2.0*xj*aiijj_)-aji*aiijj*(ajj*uij2-uij*aiijj_-aij*uji2)+aji*aiijj_*(aii*uij+aij*uji+uij2+2.0*xi*aiijj_)
coefH6j=aii*aiijj_*(aii*uji2-uji*aiijj_-aji*uij2)-aji*aiijj_*(ajj*uij2-uij*aiijj_-aij*uji2)
h = ft-simt
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
if (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj)
h1 = sqrt(abs(2*quani/ddxi));h2 = sqrt(abs(2*quanj/ddxj)); #later add derderX =1e-12 when x2==0?
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
maxIter=10000
while (abs(qi - xi) > 2.0*quani || abs(qj - xj) > 2.0*quanj) && (maxIter>0)
maxIter-=1
h1 = h * sqrt(quani / abs(qi - xi));
h2 = h * sqrt(quanj / abs(qj - xj));
h=min(h1,h2)
Δ1=1.0-h*(aiijj)-h*h*(aiijj_)
if abs(Δ1)!=0.0
h_2=h*h;h_3=h_2*h;h_4=h_3*h;h_5=h_4*h;h_6=h_5*h
Δ22=4.0+h*coefΔh1+h_2*(coefΔh2)+h_3*(coefΔh3)+h_4*(coefΔh4)+h_5*coefΔh5+h_6*coefΔh6
if abs(Δ22)!=0.0
qi=(4.0*xi+h*coefH1+h_2*coefH2+h_3*coefH3+h_4*coefH4+h_5*coefH5+h_6*coefH6)/Δ22
qj=(4.0*xj+h*coefH1j+h_2*coefH2j+h_3*coefH3j+h_4*coefH4j+h_5*coefH5j+h_6*coefH6j)/Δ22
end
end
end
if maxIter<900 #ie simul step failed
println("simulstep $maxIter")
end
if maxIter==0 #ie simul step failed
println("simulstep failed maxiter")
return false
end
if 0<h<1e-20 #ie simul step failed # h==0 is allowed because is like an equilibrium
println("simulstep failed small h=",h)
return false
end
if Δ1==0.0 # should never happen when maxIter>0...before deployement, group the 2 prev if statments
println("iter simul Δ1 ==0")
return false
end
q[index][0]=qi# store back helper vars
q[j][0]=qj
q1parti=aii*qi+aij*qj+uij+h*uij2
q1partj=aji*qi+ajj*qj+uji+h*uji2
q[index][1]=((1-h*ajj)/Δ1)*q1parti+(h*aij/Δ1)*q1partj# store back helper vars
q[j][1]=(h*aji/Δ1)*q1parti+((1-h*aii)/Δ1)*q1partj
trackSimul[1]+=1 # do not have to recomputeNext if qi never changed
end #end if iscycle
return iscycle
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 3723 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
function ==(a::Taylor0, b::Taylor0)
return a.coeffs == b.coeffs
end
zero(a::Taylor0) = Taylor0(zero.(a.coeffs))
function zero(a::Taylor0, cache::Taylor0)
cache.coeffs .= 0.0
return cache
end
function one(a::Taylor0, cache::Taylor0)
cache.coeffs .= 0.0
cache[0] = 1.0
return cache
end
function one(a::Taylor0)
b = zero(a)
b[0] = one(b[0])
return b
end
function (+)(a::Taylor0, b::Taylor0)
v = similar(a.coeffs)
@__dot__ v = (+)(a.coeffs, b.coeffs)
return Taylor0(v, a.order)
end
function (+)(a::Taylor0)
v = similar(a.coeffs)
@__dot__ v = (+)(a.coeffs)
return Taylor0(v, a.order)
end
function (+)(a::Taylor0, b::T) where {T<:Number}
coeffs = copy(a.coeffs)
@inbounds coeffs[1] = (+)(a[0], b)
return Taylor0(coeffs, a.order)
end
(+)(b::T, a::Taylor0) where {T<:Number} = (+)(a, b)
function (-)(a::Taylor0, b::Taylor0)
#if a.order != b.order a, b = fixorder(a, b) end
v = similar(a.coeffs)
@__dot__ v = (-)(a.coeffs, b.coeffs)
return Taylor0(v, a.order)
end
function (-)(a::Taylor0)
v = similar(a.coeffs)
@__dot__ v = (-)(a.coeffs)
return Taylor0(v, a.order)
end
function (-)(a::Taylor0, b::T) where {T<:Number}
coeffs = copy(a.coeffs)
@inbounds coeffs[1] = (-)(a[0], b)
return Taylor0(coeffs, a.order)
end
function (-)(b::T, a::Taylor0) where {T<:Number}
coeffs = similar(a.coeffs)
@__dot__ coeffs = (-)(a.coeffs)
@inbounds coeffs[1] = (-)(b, a[0])
return Taylor0(coeffs, a.order)
end
function *(a::Taylor0, b::Taylor0)
c = Taylor0(zero(a[0]), a.order)
for ord in eachindex(c)
mul!(c, a, b, ord)
end
return c
end
function (*)(a::T, b::Taylor0) where {T<:Number}
v = Array{T}(undef, length(b.coeffs))
@__dot__ v = a * b.coeffs
return Taylor0(v, b.order)
end
*(b::Taylor0, a::T) where {T<:Number} = a * b
@inline function mul!(c::Taylor0, a::Taylor0, b::Taylor0, k::Int)
@inbounds c[k] = a[0] * b[k]
@inbounds for i = 1:k
c[k] += a[i] * b[k-i]
end
return nothing
end
function /(a::Taylor0, b::T) where {T<:Number}
@inbounds aux = a.coeffs[1] / b
v = Array{typeof(aux)}(undef, length(a.coeffs))
@__dot__ v = a.coeffs / b
return Taylor0(v, a.order)
end
function /(a::Taylor0, b::Taylor0)
iszero(a) && !iszero(b) && return zero(a)
#if a.order != b.order a, b = fixorder(a, b) end
ordfact, cdivfact = divfactorization(a, b)
c = Taylor0(cdivfact, a.order - ordfact)
for ord in eachindex(c)
div!(c, a, b, ord)
end
return c
end
@inline function divfactorization(a1::Taylor0, b1::Taylor0)
a1nz = findfirst(a1)
b1nz = findfirst(b1)
a1nz = a1nz ≥ 0 ? a1nz : a1.order
b1nz = b1nz ≥ 0 ? b1nz : a1.order
ordfact = min(a1nz, b1nz)
cdivfact = a1[ordfact] / b1[ordfact]
iszero(b1[ordfact]) && throw(ArgumentError(
"""Division does not define a Taylor0 polynomial;
order k=$(ordfact) => coeff[$(ordfact)]=$(cdivfact)."""))
return ordfact, cdivfact
end
@inline function div!(c::Taylor0, a::Taylor0, b::Taylor0, k::Int)
ordfact, cdivfact = divfactorization(a, b)
if k == 0
@inbounds c[0] = cdivfact
return nothing
end
imin = max(0, k + ordfact - b.order)
@inbounds c[k] = c[imin] * b[k+ordfact-imin]
@inbounds for i = imin+1:k-1
c[k] += c[i] * b[k+ordfact-i]
end
if k + ordfact ≤ b.order
@inbounds c[k] = (a[k+ordfact] - c[k]) / b[ordfact]
else
@inbounds c[k] = -c[k] / b[ordfact]
end
return nothing
end
#/(a::Int,b::Int)=Int(Float64(a)/b) | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 14565 | (addsub)(a, b, c) = (-)((+)(a, b), c)
(subsub)(a, b, c) = (-)((-)(a, b), c)
(subadd)(a, b, c) = (+)((-)(a, b), c)# this should not exist cuz addsub has 3 args + cache
function addTfoldl(op, res, bs...)# op is only addt so remove later
l = length(bs)
#i = 0; l == i && return a # already checked
l == 1 && return res
i = 2
l == i && return op(res, bs[1], bs[end])
i = 3
l == i && return op(res, bs[1], bs[2], bs[end])
i = 4
l == i && return op(op(res, bs[1], bs[2], bs[end]), bs[3], bs[end])
i = 5
l == i && return op(op(res, bs[1], bs[2], bs[end]), bs[3], bs[4], bs[end])
i = 6
l == i && return op(op(op(res, bs[1], bs[2], bs[end]), bs[3], bs[4], bs[end]), bs[5], bs[end])
i = 7
l == i && return op(op(op(res, bs[1], bs[2], bs[end]), bs[3], bs[4], bs[end]), bs[5], bs[6], bs[end])
i = 8
l == i && return op(op(op(op(res, bs[1], bs[2], bs[end]), bs[3], bs[4], bs[end]), bs[5], bs[6], bs[end]), bs[7], bs[end])
i = 9
y = op(op(op(op(res, bs[1], bs[2], bs[end]), bs[3], bs[4], bs[end]), bs[5], bs[6], bs[end]), bs[7], bs[8], bs[end])
l == i && return y
#last i creates y and passes it to the next loop: note that from this point, op will allocate
# warn the users . (inserting -0 will avoid allocation lol!)
for i in i:l-1 # -1 cuz last one is cache...but these lines are never reached cuz macro does not create mulT for args >7 in the first place
y = op(y, bs[i], bs[end])
end
return y
end
function addT(a, b, c, d, xs...)
if length(xs) != 0# if ==0 case below where d==cache
addTfoldl(addT, addT(addT(a, b, c, xs[end]), d, xs[end]), xs...)
end
end
function mulTfoldl(res::P, bs...) where {P<:Taylor0}
l = length(bs)
i = 2
l == i && return res
i = 3
l == i && return mulTT(res, bs[1], bs[end-1], bs[end])
i = 4
l == i && return mulTT(mulTT(res, bs[1], bs[end-1], bs[end]), bs[2], bs[end-1], bs[end])
i = 5
l == i && return mulTT(mulTT(mulTT(res, bs[1], bs[end-1], bs[end]), bs[2], bs[end-1], bs[end]), bs[3], bs[end-1], bs[end])
i = 6
l == i && return mulTT(mulTT(mulTT(mulTT(res, bs[1], bs[end-1], bs[end]), bs[2], bs[end-1], bs[end]), bs[3], bs[end-1], bs[end]), bs[4], bs[end-1], bs[end])
#= if l == 6
println("alloc!!!")
return mulTT(mulTT(mulTT(mulTT(res, bs[1],bs[end-1],bs[end]),bs[2],bs[end-1],bs[end]),bs[3],bs[end-1],bs[end]),bs[4],bs[end-1],bs[end])
end =#
end
function mulTT(a::P, b::R, c::Q, xs...) where {P,Q,R<:Union{Taylor0,Number}}
if length(xs) > 1
mulTfoldl(mulTT(mulTT(a, b, xs[end-1], xs[end]), c, xs[end-1], xs[end]), xs...)
end
end
# all methods should have new names . no type piracy!!! if Taylor1 to be used
function createT(a::Taylor0, cache::Taylor0)
@__dot__ cache.coeffs = a.coeffs
return cache
end
"""createT(a::T,cache::Taylor0) where {T<:Number}
creates a Taylor0 from a constant. In case of order 2, cache=[a,0,0]
"""
function createT(a::T, cache::Taylor0) where {T<:Number} # requires cache1 clean
cache[0] = a
return cache
end
"""addsub(a::Taylor0, b::Taylor0,c::Taylor0,cache::Taylor0)
cache=a+b-c
"""
function addsub(a::Taylor0, b::Taylor0, c::Taylor0, cache::Taylor0)
@__dot__ cache.coeffs = (-)((+)(a.coeffs, b.coeffs), c.coeffs)
return cache
end
function addsub(a::Taylor0, b::Taylor0, c::T, cache::Taylor0) where {T<:Number}
cache.coeffs .= b.coeffs
cache[0] = cache[0] - c
@__dot__ cache.coeffs = (+)(cache.coeffs, a.coeffs)
return cache
end
"""addsub(a::T, b::Taylor0,c::Taylor0,cache::Taylor0) where {T<:Number}
Order2 case: cache=[a+b[0]-c[0],b[1]-c[1],b[2]-c[2]]
"""
function addsub(a::T, b::Taylor0, c::Taylor0, cache::Taylor0) where {T<:Number}
cache.coeffs .= b.coeffs
cache[0] = a + cache[0]
@__dot__ cache.coeffs = (-)(cache.coeffs, c.coeffs)
return cache
end
addsub(a::Taylor0, b::T, c::Taylor0, cache::Taylor0) where {T<:Number} = addsub(b, a, c, cache)#addsub(b::T, a::Taylor0 ,c::Taylor0,cache::Taylor0) where {T<:Number}
function addsub(a::T, b::T, c::Taylor0, cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = (-)(c.coeffs)
cache[0] = a + b + cache[0]
return cache
end
function addsub(c::Taylor0, a::T, b::T, cache::Taylor0) where {T<:Number}
cache.coeffs .= c.coeffs
cache[0] = a + cache[0] - b
return cache
end
addsub(a::T, c::Taylor0, b::T, cache::Taylor0) where {T<:Number} = addsub(c, a, b, cache)
function addsub(c::T, a::T, b::T, cache::Taylor0) where {T<:Number}#requires cache clean
cache[0] = a + c - b
return cache
end
###########"negate###########
"""negateT(a::Taylor0,cache::Taylor0)
cache=-a
"""
function negateT(a::Taylor0, cache::Taylor0) #where {T<:Number}
@__dot__ cache.coeffs = (-)(a.coeffs)
return cache
end
function negateT(a::T, cache::Taylor0) where {T<:Number} # requires cache1 clean
cache[0] = -a
return cache
end
#################################################subsub########################################################"
"""subsub(a::Taylor0, b::Taylor0,c::Taylor0,cache::Taylor0)
cache=a-b-c
"""
function subsub(a::Taylor0, b::Taylor0, c::Taylor0, cache::Taylor0)
@__dot__ cache.coeffs = subsub(a.coeffs, b.coeffs, c.coeffs)
return cache
end
function subsub(a::Taylor0, b::Taylor0, c::T, cache::Taylor0) where {T<:Number}
cache.coeffs .= b.coeffs
cache[0] = cache[0] + c #(a-b-c=a-(b+c))
@__dot__ cache.coeffs = (-)(a.coeffs, cache.coeffs)
return cache
end
subsub(a::Taylor0, b::T, c::Taylor0, cache::Taylor0) where {T<:Number} = subsub(a, c, b, cache)
function subsub(a::T, b::Taylor0, c::Taylor0, cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = (-)(b.coeffs)
cache[0] = a + cache[0]
@__dot__ cache.coeffs = (-)(cache.coeffs, c.coeffs)
return cache
end
function subsub(a::Taylor0, b::T, c::T, cache::Taylor0) where {T<:Number}
cache.coeffs .= a.coeffs
cache[0] = cache[0] - b - c
return cache
end
function subsub(a::T, b::Taylor0, c::T, cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = (-)(b.coeffs)
cache[0] = cache[0] + a - c
return cache
end
subsub(b::T, c::T, a::Taylor0, cache::Taylor0) where {T<:Number} = subsub(b, a, c, cache)
function subsub(a::T, b::T, c::T, cache::Taylor0) where {T<:Number}#require emptying the cache
cache[0] = a - b - c
return cache
end
#################################subadd####################################""
function subadd(a::P, b::Q, c::R, cache::Taylor0) where {P,Q,R<:Union{Taylor0,Number}}
addsub(a, c, b, cache)
end
##################################""subT################################
"""subT(a::Taylor0, b::Taylor0,cache::Taylor0)
cache=a-b
"""
function subT(a::Taylor0, b::Taylor0, cache::Taylor0)# where {T<:Number}
@__dot__ cache.coeffs = (-)(a.coeffs, b.coeffs)
return cache
end
function subT(a::Taylor0, b::T, cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = a.coeffs
cache[0] = cache[0] - b
return cache
end
function subT(a::T, b::Taylor0, cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = (-)(b.coeffs)
cache[0] = cache[0] + a
return cache
end
function subT(a::T, b::T, cache::Taylor0) where {T<:Number} ##require emptying the cache
#cache.coeffs.=0.0 # ok to empty...allocates !!!
cache[0] = a - b
return cache
end
#= function addT(a::Taylor0, b::T) where {T<:Number} #case where no cache is given, a is not a var and it is ok to modify it (its the result of previous inter-ops)
a[0]=a[0]+b
return a
end =#
#= function addT(a::Taylor0, b::Taylor0) where {T<:Number} #case where no cache is given, ok to squash a
@__dot__ a.coeffs = (+)(a.coeffs, b.coeffs)
return a
end =#
"""addT(a::Taylor0, b::Taylor0,cache::Taylor0)
cache=a+b
"""
function addT(a::Taylor0, b::Taylor0, cache::Taylor0)
@__dot__ cache.coeffs = (+)(a.coeffs, b.coeffs)
return cache
end
function addT(a::Taylor0, b::T, cache::Taylor0) where {T<:Number}
cache.coeffs .= a.coeffs
cache[0] = cache[0] + b
return cache
end
addT(b::T, a::Taylor0, cache::Taylor0) where {T<:Number} = addT(a, b, cache)
function addT(a::T, b::T, cache::Taylor0) where {T<:Number}#require emptying the cache
#cache.coeffs.=0.0 #
cache[0] = a + b
return cache
end
#add Three vars a b c
function addT(a::Taylor0, b::Taylor0, c::Taylor0, cache::Taylor0)
@__dot__ cache.coeffs = (+)(a.coeffs, b.coeffs, c.coeffs)
return cache
end
function addT(a::Taylor0, b::Taylor0, c::T, cache::Taylor0) where {T<:Number}
@__dot__ cache.coeffs = (+)(a.coeffs, b.coeffs)
cache[0] = cache[0] + c
return cache
end
addT(a::Taylor0, c::T, b::Taylor0, cache::Taylor0) where {T<:Number} = addT(a, b, c, cache)
addT(c::T, a::Taylor0, b::Taylor0, cache::Taylor0) where {T<:Number} = addT(a, b, c, cache)
function addT(a::Taylor0, b::T, c::T, cache::Taylor0) where {T<:Number}
cache.coeffs .= a.coeffs
cache[0] = cache[0] + c + b
return cache
end
addT(b::T, a::Taylor0, c::T, cache::Taylor0) where {T<:Number} = addT(a, b, c, cache)
addT(b::T, c::T, a::Taylor0, cache::Taylor0) where {T<:Number} = addT(a, b, c, cache)
function addT(a::T, b::T, c::T, cache::Taylor0) where {T<:Number}#require clean cache
cache[0] = a + b + c
return cache
end
####################mul uses one cache when the original mul has only two elemnts a * b
function mulT(a::Taylor0, b::T, cache1::Taylor0) where {T<:Number}
fill!(cache1.coeffs, b)##I fixed broadcast dimension mismatch
@__dot__ cache1.coeffs = a.coeffs * cache1.coeffs ##I fixed broadcast dimension mismatch
return cache1
end
mulT(a::T, b::Taylor0, cache1::Taylor0) where {T<:Number} = mulT(b, a, cache1)
"""mulT(a::Taylor0, b::Taylor0,cache1::Taylor0)
cache1=a*b
"""
function mulT(a::Taylor0, b::Taylor0, cache1::Taylor0)
for k in eachindex(a)
@inbounds cache1[k] = a[0] * b[k]
@inbounds for i = 1:k
cache1[k] += a[i] * b[k-i]
end
end
return cache1
end
function mulT(a::T, b::T, cache1::Taylor0) where {T<:Number}
#cache1 needs to be clean: a clear here will alloc...this is the only "mul" that wants a clean cache
#sometimes the cache can be dirty at only first position: it will not throw an assert error!!!
# cache[1].coeffs.=0.0 #it causes two allocs for mul(cst,cst,a,b)
cache1[0] = a * b
return cache1
end
#########################mul uses two caches when the op has many terms###########################
function mulTT(a::Taylor0, b::T, cache1::Taylor0, cache2::Taylor0) where {T<:Number}#in middle ops: a is the returned cache1 so do not fudge a or cache1 before the end
fill!(cache2.coeffs, b)
@__dot__ cache1.coeffs = a.coeffs * cache2.coeffs ##fixed broadcast dimension mismatch
return cache1
end
mulTT(a::T, b::Taylor0, cache1::Taylor0, cache2::Taylor0) where {T<:Number} = mulTT(b, a, cache1, cache2)
function mulTT(a::Taylor0, b::Taylor0, cache1::Taylor0, cache2::Taylor0) #in middle ops: a is the returned cache1 so do not fudge a or cache1 before the end
for k in eachindex(a)
@inbounds cache2[k] = a[0] * b[k]
@inbounds for i = 1:k
cache2[k] += a[i] * b[k-i]
end
end
@__dot__ cache1.coeffs = cache2.coeffs
return cache1
end
function mulTT(a::T, b::T, cache1::Taylor0, cache2::Taylor0) where {T<:Number}
#cache1 needs to be clean: a clear here will alloc...this is the only "mul" that wants a clean cache
#sometimes the cache can be dirty at only first position: it will not throw an assert error!!!
# cache[1].coeffs.=0.0 #it causes two allocs for mul(cst,cst,a,b)
cache1[0] = a * b
return cache1
end
#########################################muladdT and subadd not test : added T to muladd cuz there did not want to import muladd to extend...maybe later
#= function muladdT(a::Taylor0, b::Taylor0, c::Taylor0,cache1::Taylor0) where {T<:Number}
for k in eachindex(a)
cache1[k] = a[0] * b[k] + c[k]
@inbounds for i = 1:k
cache1[k] += a[i] * b[k-i]
end
end
@__dot__ cache1.coeffs = cache2.coeffs
return cache1
end =#
"""muladdT(a::P,b::Q,c::R,cache1::Taylor0) where {P,Q,R <:Union{Taylor0,Number}}
cache1=a*b+c
"""
function muladdT(a::P, b::Q, c::R, cache1::Taylor0) where {P,Q,R<:Union{Taylor0,Number}}
addT(mulT(a, b, cache1), c, cache1) # improvement of added performance not tested: there is one extra step of
#puting cache in itself
end
"""mulsub(a::P,b::Q,c::R,cache1::Taylor0) where {P,Q,R <:Union{Taylor0,Number}}
cache1=a*b-c
"""
function mulsub(a::P, b::Q, c::R, cache1::Taylor0) where {P,Q,R<:Union{Taylor0,Number}}
subT(mulT(a, b, cache1), c, cache1)
end
function divT(a::T, b::T, cache1::Taylor0) where {T<:Number}
cache1[0] = a / b
return cache1
end
function divT(a::Taylor0, b::T, cache1::Taylor0) where {T<:Number}
fill!(cache1.coeffs, b)
#println("division")
#= @inbounds aux = a.coeffs[1] / b
v = Array{typeof(aux)}(undef, length(a.coeffs)) =#
@__dot__ cache1.coeffs = a.coeffs / cache1.coeffs
return cache1
end
function divT(a::T, b::Taylor0, cache1::Taylor0) where {T<:Number}
powerT(b, -1.0, cache1)
@__dot__ cache1.coeffs = cache1.coeffs * a ### broadcast dimension mismatch------------------div can have 2 caches then...:(
return cache1
end
#divT(a::Taylor0, b::Taylor0{S}) where {T<:Number,S<:Number} = divT(promote(a,b)...)
"""divT(a::Taylor0, b::Taylor0,cache1::Taylor0)
cache1=a/b
"""
function divT(a::Taylor0, b::Taylor0, cache1::Taylor0)
iszero(a) && !iszero(b) && return cache1 # this op has its own clean cache2
ordfact, cdivfact = divfactorization(a, b)
cache1[0] = cdivfact
for k = 1:a.order-ordfact
imin = max(0, k + ordfact - b.order)
@inbounds cache1[k] = cache1[imin] * b[k+ordfact-imin]
@inbounds for i = imin+1:k-1
cache1[k] += cache1[i] * b[k+ordfact-i]
end
if k + ordfact ≤ b.order
@inbounds cache1[k] = (a[k+ordfact] - cache1[k]) / b[ordfact]
else
@inbounds cache1[k] = -cache1[k] / b[ordfact]
end
end
return cache1
end
#= function clearCache(cache::Vector{Taylor0},::Val{CS},::Val{3}) where {CS}
for i=1:CS
cache[i][0]=0.0
cache[i][1]=0.0
cache[i][2]=0.0
cache[i][3]=0.0 # no need to clean? higher value is empty
end
end =#
#= function clearCache(cache::Vector{Taylor0},::Val{2}) #where {CS}
#for i=1:CS
cache[1].coeffs.=0.0
cache[2].coeffs.=0.0
# end
end =#
function clearCache(cache::Vector{Taylor0}, ::Val{CS}, ::Val{2}) where {CS}
for i = 1:CS
cache[i][0] = 0.0
cache[i][1] = 0.0
cache[i][2] = 0.0
end
end
function clearCache(cache::Vector{Taylor0}, ::Val{CS}, ::Val{1}) where {CS}
for i = 1:CS
cache[i][0] = 0.0
cache[i][1] = 0.0
end
end
#= function clearCache(cache::Vector{Taylor0}) #where {T<:Number}
for i=1:length(cache)
cache[i].coeffs.=0.0
end
end =# | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 2745 | # Float64his file is part of the Taylor0Series.jl Julia package, MIFloat64 license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIFloat64 Expat license
#
## Constructors ##
"""Taylor0
A struct that defines a Taylor Variable. It has the following fields:\n
- coeffs: An array of Float64 that holds the coefficients of the Taylor series\n
- order: The order of the Taylor series
"""
struct Taylor0 #<: AbstractSeries{Float64}
coeffs::Array{Float64,1}
order::Int
end
Taylor0(x::Taylor0) = x
Taylor0(coeffs::Array{Float64,1}) = Taylor0(coeffs, length(coeffs) - 1)
function Taylor0(x::Float64, order::Int)
v = fill(0.0, order + 1)
v[1] = x
return Taylor0(v, order)
end
getcoeff(a::Taylor0, n::Int) = (@assert 0 ≤ n ≤ a.order;return a[n])
getindex(a::Taylor0, n::Int) = a.coeffs[n+1]
setindex!(a::Taylor0, x::T, n::Int) where {T<:Number} = a.coeffs[n+1] = x
#@inline iterate(a::Taylor0, state=0) = state > a.order ? nothing : (a.coeffs[state+1], state + 1)
@inline length(a::Taylor0) = length(a.coeffs)
@inline firstindex(a::Taylor0) = 0
@inline lastindex(a::Taylor0) = a.order
@inline eachindex(a::Taylor0) = firstindex(a):lastindex(a)
@inline size(a::Taylor0) = size(a.coeffs)
@inline get_order(a::Taylor0) = a.order
#numtype(a) = eltype(a)
# Finds the first non zero entry; extended to Taylor0
function Base.findfirst(a::Taylor0)
first = findfirst(x -> !iszero(x), a.coeffs)
isa(first, Nothing) && return -1
return first - 1
end
# Finds the last non-zero entry; extended to Taylor0
function Base.findlast(a::Taylor0)
last = findlast(x -> !iszero(x), a.coeffs)
isa(last, Nothing) && return -1
return last - 1
end
constant_term(a::Taylor0) = a[0]
function evaluate(a::Taylor0, dx::T) where {T<:Number}
@inbounds suma = a[end]
@inbounds for k in a.order-1:-1:0
suma = suma * dx + a[k]
end
suma
end
(p::Taylor0)(x) = evaluate(p, x)
#= function differentiate!(p::Taylor0, a::Taylor0, k::Int)
if k < a.order
@inbounds p[k] = (k + 1) * a[k+1]
end
return nothing
end =#
function differentiate!(::Val{O}, cache::Taylor0, a::Taylor0) where {O}
for k = 0:O-1
@inbounds cache[k] = (k + 1) * a[k+1]
end
cache[O] = 0.0 #cache Letter O not zero
nothing
end
function ndifferentiate!(cache::Taylor0, a::Taylor0, n::Int)
if n > a.order
cache.coeffs .= 0.0
elseif n == 0
cache.coeffs .= a.coeffs
else
differentiate!(Val(a.order), cache, a)
for i = 2:n
differentiate!(Val(a.order), cache, cache)
end
#return Taylor0(view(res.coeffs, 1:a.order-n+1))
end
end
function testTaylor(a::Taylor0)
Taylor0(a)
getcoeff(a,1)
length(a)
size(a)
get_order(a)
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 9863 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
# Functions
function exp(a::Taylor0)
order = a.order
aux = exp(constant_term(a))
aa = one(aux) * a
c = Taylor0(aux, order)
for k in eachindex(a)
exp!(c, aa, k)
end
return c
end
function log(a::Taylor0)
iszero(constant_term(a)) && throw(DomainError(a,
"""The 0-th order coefficient must be non-zero in order to expand `log` around 0."""))
order = a.order
aux = log(constant_term(a))
aa = one(aux) * a
c = Taylor0(aux, order)
for k in eachindex(a)
log!(c, aa, k)
end
return c
end
sin(a::Taylor0) = sincos(a)[1]
cos(a::Taylor0) = sincos(a)[2]
function sincos(a::Taylor0)
order = a.order
aux = sin(constant_term(a))
aa = one(aux) * a
s = Taylor0(aux, order)
c = Taylor0(cos(constant_term(a)), order)
for k in eachindex(a)
sincos!(s, c, aa, k)
end
return s, c
end
function tan(a::Taylor0)
order = a.order
aux = tan(constant_term(a))
aa = one(aux) * a
c = Taylor0(aux, order)
c2 = Taylor0(aux^2, order)
for k in eachindex(a)
tan!(c, aa, c2, k)
end
return c
end
function asin(a::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of asin(x) diverges at x = ±1."""))
order = a.order
aux = asin(a0)
aa = one(aux) * a
c = Taylor0(aux, order)
r = Taylor0(sqrt(1 - a0^2), order)
for k in eachindex(a)
asin!(c, aa, r, k)
end
return c
end
function acos(a::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of asin(x) diverges at x = ±1."""))
order = a.order
aux = acos(a0)
aa = one(aux) * a
c = Taylor0(aux, order)
r = Taylor0(sqrt(1 - a0^2), order)
for k in eachindex(a)
acos!(c, aa, r, k)
end
return c
end
function atan(a::Taylor0)
order = a.order
a0 = constant_term(a)
aux = atan(a0)
aa = one(aux) * a
c = Taylor0(aux, order)
r = Taylor0(one(aux) + a0^2, order)
iszero(constant_term(r)) && throw(DomainError(a,
"""Series expansion of atan(x) diverges at x = ±im."""))
for k in eachindex(a)
atan!(c, aa, r, k)
end
return c
end
sinh(a::Taylor0) = sinhcosh(a)[1]
cosh(a::Taylor0) = sinhcosh(a)[2]
function sinhcosh(a::Taylor0)
order = a.order
aux = sinh(constant_term(a))
aa = one(aux) * a
s = Taylor0(aux, order)
c = Taylor0(cosh(constant_term(a)), order)
for k in eachindex(a)
sinhcosh!(s, c, aa, k)
end
return s, c
end
function tanh(a::Taylor0)
order = a.order
aux = tanh(constant_term(a))
aa = one(aux) * a
c = Taylor0(aux, order)
c2 = Taylor0(aux^2, order)
for k in eachindex(a)
tanh!(c, aa, c2, k)
end
return c
end
function asinh(a::Taylor0)
order = a.order
a0 = constant_term(a)
aux = asinh(a0)
aa = one(aux) * a
c = Taylor0(aux, order)
r = Taylor0(sqrt(a0^2 + 1), order)
iszero(constant_term(r)) && throw(DomainError(a,
"""Series expansion of asinh(x) diverges at x = ±im."""))
for k in eachindex(a)
asinh!(c, aa, r, k)
end
return c
end
function acosh(a::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of acosh(x) diverges at x = ±1."""))
order = a.order
aux = acosh(a0)
aa = one(aux) * a
c = Taylor0(aux, order)
r = Taylor0(sqrt(a0^2 - 1), order)
for k in eachindex(a)
acosh!(c, aa, r, k)
end
return c
end
function atanh(a::Taylor0)
order = a.order
a0 = constant_term(a)
aux = atanh(a0)
aa = one(aux) * a
c = Taylor0(aux, order)
r = Taylor0(one(aux) - a0^2, order)
iszero(constant_term(r)) && throw(DomainError(a,
"""Series expansion of atanh(x) diverges at x = ±1."""))
for k in eachindex(a)
atanh!(c, aa, r, k)
end
return c
end
@inline function exp!(c::Taylor0, a::Taylor0, k::Int)
if k == 0
@inbounds c[0] = exp(constant_term(a)) #this was already computed before!!no need to do anything if k==0
return nothing
end
@inbounds c[k] = k * a[k] * c[0]
@inbounds for i = 1:k-1
c[k] += (k - i) * a[k-i] * c[i]
end
@inbounds c[k] = c[k] / k
return nothing
end
@inline function log!(c::Taylor0, a::Taylor0, k::Int)
if k == 0
@inbounds c[0] = log(constant_term(a))
return nothing
elseif k == 1
@inbounds c[1] = a[1] / constant_term(a)
return nothing
end
@inbounds c[k] = (k - 1) * a[1] * c[k-1]
@inbounds for i = 2:k-1
c[k] += (k - i) * a[i] * c[k-i]
end
@inbounds c[k] = (a[k] - c[k] / k) / constant_term(a)
return nothing
end
@inline function sincos!(s::Taylor0, c::Taylor0, a::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds s[0], c[0] = sincos(a0)
return nothing
end
x = a[1]
@inbounds s[k] = x * c[k-1]
@inbounds c[k] = -x * s[k-1]
@inbounds for i = 2:k
x = i * a[i]
s[k] += x * c[k-i]
c[k] -= x * s[k-i]
end
@inbounds s[k] = s[k] / k
@inbounds c[k] = c[k] / k
return nothing
end
@inline function tan!(c::Taylor0, a::Taylor0, c2::Taylor0, k::Int)
if k == 0
@inbounds aux = tan(constant_term(a))
@inbounds c[0] = aux
@inbounds c2[0] = aux^2
return nothing
end
@inbounds c[k] = k * a[k] * c2[0]
@inbounds for i = 1:k-1
c[k] += (k - i) * a[k-i] * c2[i]
end
@inbounds c[k] = a[k] + c[k] / k
sqr!(c2, c, k)
return nothing
end
@inline function asin!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = asin(a0)
@inbounds r[0] = sqrt(1 - a0^2)
return nothing
end
@inbounds c[k] = (k - 1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k - i) * r[i] * c[k-i]
end
sqrt!(r, 1 - a^2, k)
@inbounds c[k] = (a[k] - c[k] / k) / constant_term(r)
return nothing
end
@inline function acos!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = acos(a0)
@inbounds r[0] = sqrt(1 - a0^2)
return nothing
end
@inbounds c[k] = (k - 1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k - i) * r[i] * c[k-i]
end
sqrt!(r, 1 - a^2, k)
@inbounds c[k] = -(a[k] + c[k] / k) / constant_term(r)
return nothing
end
@inline function atan!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = atan(a0)
@inbounds r[0] = 1 + a0^2
return nothing
end
@inbounds c[k] = (k - 1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k - i) * r[i] * c[k-i]
end
@inbounds sqr!(r, a, k)
@inbounds c[k] = (a[k] - c[k] / k) / constant_term(r)
return nothing
end
@inline function sinhcosh!(s::Taylor0, c::Taylor0, a::Taylor0, k::Int)
if k == 0
@inbounds s[0] = sinh(constant_term(a))
@inbounds c[0] = cosh(constant_term(a))
return nothing
end
x = a[1]
@inbounds s[k] = x * c[k-1]
@inbounds c[k] = x * s[k-1]
@inbounds for i = 2:k
x = i * a[i]
s[k] += x * c[k-i]
c[k] += x * s[k-i]
end
s[k] = s[k] / k
c[k] = c[k] / k
return nothing
end
@inline function tanh!(c::Taylor0, a::Taylor0, c2::Taylor0, k::Int)
if k == 0
@inbounds aux = tanh(constant_term(a))
@inbounds c[0] = aux
@inbounds c2[0] = aux^2
return nothing
end
@inbounds c[k] = k * a[k] * c2[0]
@inbounds for i = 1:k-1
c[k] += (k - i) * a[k-i] * c2[i]
end
@inbounds c[k] = a[k] - c[k] / k
sqr!(c2, c, k)
return nothing
end
@inline function asinh!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = asinh(a0)
@inbounds r[0] = sqrt(a0^2 + 1)
return nothing
end
@inbounds c[k] = (k - 1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k - i) * r[i] * c[k-i]
end
sqrt!(r, a^2 + 1, k) # a^...allocates will need a third cache
@inbounds c[k] = (a[k] - c[k] / k) / constant_term(r)
return nothing
end
@inline function acosh!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = acosh(a0)
@inbounds r[0] = sqrt(a0^2 - 1)
return nothing
end
@inbounds c[k] = (k - 1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k - i) * r[i] * c[k-i]
end
sqrt!(r, a^2 - 1, k)
@inbounds c[k] = (a[k] - c[k] / k) / constant_term(r)
return nothing
end
@inline function atanh!(c::Taylor0, a::Taylor0, r::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = atanh(a0)
@inbounds r[0] = 1 - a0^2
return nothing
end
@inbounds c[k] = (k - 1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k - i) * r[i] * c[k-i]
end
@inbounds sqr!(r, a, k)
@inbounds c[k] = (a[k] + c[k] / k) / constant_term(r)
return nothing
end
function abs(a::Taylor0)
if constant_term(a) > 0
return a
elseif constant_term(a) < 0
return -a
else
throw(DomainError(a,
"""The 0th order Taylor0 coefficient must be non-zero
(abs(x) is not differentiable at x=0)."""))
end
end
function Derivative(y, x)
#error("abs is not defined yet. please report this issue if ABS was not used in the original code")
if x > 0
return 1
elseif x < 0
return -1
else
return 0
end
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 3977 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
# Functions
function exp(a::Taylor0, c::Taylor0)
order = a.order
#aux = exp(constant_term(a))
for k in eachindex(a)
exp!(c, a, k)
end
return c
end
function exp(a::T, c::Taylor0) where {T<:Number}
c[0] = exp(a)
return c
end
function log(a::Taylor0, c::Taylor0)
iszero(constant_term(a)) && throw(DomainError(a,
"""The 0-th order coefficient must be non-zero in order to expand `log` around 0."""))
for k in eachindex(a)
log!(c, a, k)
end
return c
end
function log(a::T, c::Taylor0) where {T<:Number}
iszero(a) && throw(DomainError(a,
""" log(0) undefined."""))
c[0] = log(a)
return c
end
function sincos(a::Taylor0, s::Taylor0, c::Taylor0)
for k in eachindex(a)
sincos!(s, c, a, k)
end
return s, c
end
sin(a::Taylor0, s::Taylor0, c::Taylor0) = sincos(a, s, c)[1]
cos(a::Taylor0, c::Taylor0, s::Taylor0) = sincos(a, s, c)[2]
function sin(a::T, s::Taylor0, c::Taylor0) where {T<:Number}
s[0] = sin(a)
return s
end
function cos(a::T, s::Taylor0, c::Taylor0) where {T<:Number}
s[0] = cos(a)
return s
end
function tan(a::Taylor0, c::Taylor0, c2::Taylor0)
for k in eachindex(a)
tan!(c, a, c2, k)
end
return c
end
function tan(a::T, c::Taylor0, c2::Taylor0) where {T<:Number}
c[0] = tan(a)
return c
end
#####################################constant case not implemented yet
function asin(a::Taylor0, c::Taylor0, r::Taylor0, cache3::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of asin(x) diverges at x = ±1."""))
for k in eachindex(a)
asin!(c, a, r, cache3, k)
end
return c
end
function acos(a::Taylor0, c::Taylor0, r::Taylor0, cache3::Taylor0)
a0 = constant_term(a)
a0^2 == one(a0) && throw(DomainError(a,
"""Series expansion of asin(x) diverges at x = ±1."""))
for k in eachindex(a)
acos!(c, a, r, cache3, k)
end
return c
end
function atan(a::Taylor0, c::Taylor0, r::Taylor0)
for k in eachindex(a)
atan!(c, a, r, k)
end
return c
end
@inline function asin!(c::Taylor0, a::Taylor0, r::Taylor0, cache3::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = asin(a0)
@inbounds r[0] = sqrt(1 - a0^2)
return nothing
end
@inbounds c[k] = (k - 1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k - i) * r[i] * c[k-i]
end
cache3 = square(a, cache3)
@__dot__ cache3.coeffs = (-)(cache3.coeffs)
cache3[0] = 1 + cache3[0] #1-square(a,cache3)=1-a^2
sqrt!(r, cache3, k)
@inbounds c[k] = (a[k] - c[k] / k) / constant_term(r)
return nothing
end
@inline function acos!(c::Taylor0, a::Taylor0, r::Taylor0, cache3::Taylor0, k::Int)
if k == 0
a0 = constant_term(a)
@inbounds c[0] = acos(a0)
@inbounds r[0] = sqrt(1 - a0^2)
return nothing
end
@inbounds c[k] = (k - 1) * r[1] * c[k-1]
@inbounds for i in 2:k-1
c[k] += (k - i) * r[i] * c[k-i]
end
cache3 = square(a, cache3)
@__dot__ cache3.coeffs = (-)(cache3.coeffs)
cache3[0] = 1 + cache3[0] #1-square(a,cache3)=1-a^2
sqrt!(r, cache3, k)
@inbounds c[k] = -(a[k] + c[k] / k) / constant_term(r)
return nothing
end
function abs(a::Taylor0, cache1::Taylor0)
if constant_term(a) > 0
@__dot__ cache1.coeffs = (a.coeffs)
return cache1
elseif constant_term(a) < 0
@__dot__ cache1.coeffs = (-)(a.coeffs)
return cache1
else
cache1.coeffs .= Inf # no need to throw error, Inf is fine...for my solver i deal with it by guarding against small steps
cache1[0] = 0.0
return cache1
end
end
function abs(a::T, cache1::Taylor0) where {T<:Number}
cache1[0] = abs(a)
return cache1
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 3868 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
function ^(a::Taylor0, n::Integer)
n == 0 && return one(a)
n == 1 && return (a)
n == 2 && return square(a)
n < 0 && throw(DomainError("taylor^n & n<0 !!"))
return power_by_squaring(a, n)
end
#^(a::Taylor0, x::Rational) = a^(x.num / x.den)
^(a::Taylor0, b::Taylor0) = exp(b * log(a))
#^(a::Taylor0, x::T) where {T<:Complex} = exp(x * log(a))
function power_by_squaring(x::Taylor0, p::Integer)
p == 1 && return (x)
p == 0 && return one(x)
p == 2 && return square(x)
t = trailing_zeros(p) + 1
p >>= t
while (t -= 1) > 0
x = square(x)
end
y = x
while p > 0
t = trailing_zeros(p) + 1
p >>= t
while (t -= 1) ≥ 0
x = square(x)
end
y *= x
end
return y
end
## Real power ##
function ^(a::Taylor0, r::S) where {S<:Real}
a0 = constant_term(a)
aux = one(a0)^r
iszero(r) && return Taylor0(1.0, a.order)
aa = aux * a
r == 1 && return a
r == 2 && return square(a)
r == 1 / 2 && return sqrt(a)
l0 = findfirst(a)
lnull = trunc(Int, r * l0)
if (a.order - lnull < 0) || (lnull > a.order)
return Taylor0(0.0, a.order)
end
c_order = l0 == 0 ? a.order : min(a.order, trunc(Int, r * a.order))
c = Taylor0(0.0, c_order)
for k = 0:c_order
pow!(c, aa, r, k)
end
return c
end
@inline function pow!(c::Taylor0, a::Taylor0, r::S, k::Int) where {S<:Real}
l0 = findfirst(a)
if l0 < 0
c[k] = zero(a[0])
return nothing
end
lnull = trunc(Int, r * l0)
kprime = k - lnull
if (kprime < 0) || (lnull > a.order)
@inbounds c[k] = zero(a[0])
return nothing
end
if isinteger(r) && r > 0 && (k > r * findlast(a))
@inbounds c[k] = zero(a[0])
return nothing
end
if k == lnull
@inbounds c[k] = (a[l0])^r
return nothing
end
# The recursion formula
if l0 + kprime ≤ a.order
@inbounds c[k] = r * kprime * c[lnull] * a[l0+kprime]
else
@inbounds c[k] = zero(a[0])
end
for i = 1:k-lnull-1
((i + lnull) > a.order || (l0 + kprime - i > a.order)) && continue
aux = r * (kprime - i) - i
@inbounds c[k] += aux * c[i+lnull] * a[l0+kprime-i]
end
@inbounds c[k] = c[k] / (kprime * a[l0])
return nothing
end
function square(a::Taylor0)
c = Taylor0(constant_term(a)^2, a.order)
for k in 1:a.order
sqr!(c, a, k)
end
return c
end
@inline function sqr!(c::Taylor0, a::Taylor0, k::Int)
if k == 0
@inbounds c[0] = constant_term(a)^2
return nothing
end
kodd = k % 2
kend = div(k - 2 + kodd, 2)
@inbounds for i = 0:kend
c[k] += a[i] * a[k-i]
end
@inbounds c[k] = 2 * c[k]
kodd == 1 && return nothing
@inbounds c[k] += a[div(k, 2)]^2
return nothing
end
## Square root ##
function sqrt(a::Taylor0)
l0nz = findfirst(a)
aux = zero(a[0])
if l0nz < 0
return Taylor0(aux, a.order)
end
c = Taylor0(sqrt(a[0]), a.order)
aa = one(aux) * a
for k = 1:a.order
sqrt!(c, aa, k, 0)
end
return c
end
@inline function sqrt!(c::Taylor0, a::Taylor0, k::Int, k0::Int=0)
kodd = (k - k0) % 2
kend = div(k - k0 - 2 + kodd, 2)
imax = min(k0 + kend, a.order)
imin = max(k0 + 1, k + k0 - a.order)
if imin ≤ imax
c[k] = c[imin] * c[k+k0-imin]
end
@inbounds for i = imin+1:imax
c[k] += c[i] * c[k+k0-i]
end
if k + k0 ≤ a.order
@inbounds aux = a[k+k0] - 2 * c[k]
else
@inbounds aux = -2 * c[k]
end
if kodd == 0
@inbounds aux = aux - (c[kend+k0+1])^2
end
@inbounds c[k] = aux / (2 * c[k0])
return nothing
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1505 | # This file is part of the TaylorSeries.jl Julia package, MIT license
#
# Luis Benet & David P. Sanders
# UNAM
#
# MIT Expat license
#
powerT(a::Taylor0, n::Integer, cache1::Taylor0) = powerT(a, float(n), cache1)
## Real power ##
function powerT(a::Taylor0, r::S, cache1::Taylor0) where {S<:Real}
if iszero(r) #later test r=0.0
cache1[0] = 1.0
return cache1
end
r == 1.0 && return a
r == 2.0 && return square(a, cache1)
r == 1 / 2 && return sqrt(a, cache1)
l0 = findfirst(a)
lnull = trunc(Int, r * l0)
if (a.order - lnull < 0) || (lnull > a.order)
return cache1 #empty
end
c_order = l0 == 0 ? a.order : min(a.order, trunc(Int, r * a.order))
for k = 0:c_order
pow!(cache1, a, r, k)
end
return cache1
end
function powerT(a::T, r::S, cache1::Taylor0) where {S<:Real,T<:Number}
cache1[0] = a^r
return cache1
end
function square(a::Taylor0, cache1::Taylor0) #internal helper function ...no need to take care of a==number
#c = Taylor0( constant_term(a)^2, a.order)
cache1[0] = constant_term(a)^2
for k in 1:a.order
sqr!(cache1, a, k)
end
return cache1
end
## Square root ##
function sqrt(a::Taylor0, cache1::Taylor0)
l0nz = findfirst(a)
if l0nz < 0
cache1
end
cache1[0] = sqrt(a[0])
for k = 1:a.order
sqrt!(cache1, a, k, 0)
end
return cache1
end
function sqrt(a::T, cache1::Taylor0) where {T<:Number}
cache1[0] = sqrt(a)
return cache1
end | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 362 | #get .cov files
#= using Pkg
Pkg.test("QuantizedSystemSolver"; coverage=true) # run this then comment and run next code
=#
# get lcov from .cov files (summary)
using Coverage
coverage = process_folder()
open("lcov.info", "w") do io
LCOV.write(io, coverage)
end;
#clean up the folder when not needed
#= using Coverage
Coverage.clean_folder(".") =#
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 4017 | using QuantizedSystemSolver
t1=Taylor0([1.0,1.0,0.0],2)
t2=Taylor0([2.0,2.0,3.0],2)
t3=Taylor0([1.0,1.0,0.0],2)
cache1=Taylor0([1.0,1.0,1.0],2)
cache2=Taylor0([1.0,1.0,1.0],2)
@test zero(t2)==Taylor0([0.0,0.0,0.0],2)
@test one(t2)==Taylor0([1.0,0.0,0.0],2)
@test t1==t3
zero(t1,cache1)
@test cache1[0]==0.0
one(t1,cache1)
@test cache1[0]==1.0
t4=t1+t3
@test +t1==Taylor0([1.0,1.0,0.0],2)
@test t4==Taylor0([2.0,2.0,0.0],2)
@test 5.0+t4==Taylor0([7.0,2.0,0.0],2)
@test t4+5.0==Taylor0([7.0,2.0,0.0],2)
@test t4-t3==t1
@test -t4==Taylor0([-2.0,-2.0,0.0],2)
@test t4-5.0==Taylor0([-3.0,2.0,0.0],2)
@test 5.0-t4==Taylor0([3.0,-2.0,-0.0],2)
@test 5.0*t4==Taylor0([10.0,10.0,0.0],2)
@test t4*5.0==Taylor0([10.0,10.0,0.0],2)
@test t4/2.0==Taylor0([1.0,1.0,0.0],2)
@test t1*t2 == Taylor0([2.0, 4.0, 5.0], 2)
@test t4/t1 ==Taylor0([2.0, 0.0, 0.0], 2)
createT(3.6,cache1)
@test cache1[0]==3.6
createT(t2,cache1)
@test cache1[0]==2.0
addT(4.3,5.2,cache1)
@test cache1[0]==9.5
addT(t1,5.6,cache1)
@test cache1[0]==6.6
addT(5.6,t1,cache1)
@test cache1[0]==6.6
addT(t1,t2,cache1)
@test cache1[0]==3.0
addT(t1,t2,4.8,cache1)
@test cache1[0]==7.8
addT(1.0,1.0,4.8,cache1)
@test cache1[0]==6.8
addT(t1,4.8,t2,cache1)
@test cache1[0]==7.8
addT(4.8,t2,t1,cache1)
@test cache1[0]==7.8
addT(4.8,t2,1.0,cache1)
@test cache1[0]==7.8
addT(4.8,1.0,t2,cache1)
@test cache1[0]==7.8
addT(t1,t2,t3,cache1)
@test cache1[0]==4.0
addT(t1,t2,t3,1.2,cache1)
@test cache1[0]==5.2
addT(t1,t2,t3,1.2,1.0,cache1)
@test cache1[0]==6.2
addT(t1,t2,t3,1.2,1.0,1.0,cache1)
@test cache1[0]==7.2
addT(t1,t2,t3,1.2,1.0,1.0,t1,cache1)
@test cache1[0]==8.2
addT(t1,t2,t3,1.2,1.0,1.0,t1,1.0,cache1)
@test cache1[0]==9.2
addT(t1,t2,t3,1.2,1.0,1.0,t1,1.0,0.3,cache1)
@test cache1[0]==9.5
addT(t1,0.5,t2,t3,1.2,1.0,1.0,t1,1.0,0.3,cache1)
@test cache1[0]==10.0
subT(4.3,5.3,cache1)
@test cache1[0]==-1.0
subT(t2,t1,cache1)
@test cache1==Taylor0([1.0, 1.0, 3.0], 2)
cache1=Taylor0([0.0,0.0,0.0],2)
subT(2.0,t1,cache1)
@test cache1==Taylor0([1.0, -1.0, 0.0], 2)
subT(t1,2.0,cache1)
@test cache1==Taylor0([-1.0, 1.0, 0.0], 2)
negateT(t1,cache1)
@test cache1==Taylor0([-1.0, -1.0, 0.0], 2)
cache1=Taylor0([0.0,0.0,0.0],2)
negateT(2.0,cache1)
@test cache1==Taylor0([-2.0, 0.0, 0.0], 2)
addsub(5.0,1.5,2.0,cache1)
@test cache1[0]==4.5
addsub(t1,t2,t3,cache1)
@test cache1[0]==2.0
addsub(t1,5.0,t2,cache1)
@test cache1[0]==4.0
addsub(0.5,5.0,t2,cache1)
@test cache1[0]==3.5
addsub(t2,1.0,0.5,cache1)
@test cache1[0]==2.5
addsub(1.0,t2,0.5,cache1)
@test cache1[0]==2.5
subadd(5.0,1.5,2.0,cache1)
@test cache1[0]==5.5
subsub(5.0,1.5,2.0,cache1)
@test cache1[0]==1.5
subsub(t1,t2,t3,cache1)
@test cache1[0]==-2.0
subsub(t1,5.0,t2,cache1)
@test cache1[0]==-6.0
subsub(5.0,t1,t2,cache1)
@test cache1[0]==2.0
subsub(0.5,5.0,t2,cache1)
@test cache1[0]==-6.5
subsub(t1,1.0,1.0,cache1)
@test cache1[0]==-1.0
#mulT
mulT(4.3,5.2,cache1)
@test cache1[0]==22.36
mulT(t1,5.6,cache1)
@test cache1[0]==5.6
mulT(t1,t2,cache1)
@test cache1[0]==2.0
#mulTT
mulTT(5.0,1.5,2.0,cache1,cache2)
@test cache1[0]==15.0
mulTT(t1,t2,t3,cache1,cache2)
@test cache1[0]==2.0
mulTT(t1,5.0,t2,cache1,cache2)
@test cache1[0]==10.0
mulTT(0.5,5.0,t2,cache1,cache2)
@test cache1[0]==5.0
mulTT(0.5,5.0,t2,1.0,cache1,cache2)
@test cache1[0]==5.0
mulTT(0.5,5.0,t2,1.0,t1,cache1,cache2)
@test cache1[0]==5.0
mulTT(0.5,5.0,t2,1.0,t1,0.5,cache1,cache2)
@test cache1[0]==2.5
mulTT(0.5,5.0,t2,1.0,t1,0.5,1.0,cache1,cache2)
@test cache1[0]==2.5
#muladdT
muladdT(5.0,1.5,2.0,cache1)
@test cache1[0]==9.5
muladdT(t1,t2,t3,cache1)
@test cache1[0]==3.0
muladdT(t1,5.0,t2,cache1)
@test cache1[0]==7.0
muladdT(0.5,5.0,t2,cache1)
@test cache1[0]==4.5
#mulsub
mulsub(5.0,1.5,2.0,cache1)
@test cache1[0]==5.5
mulsub(t1,t2,t3,cache1)
@test cache1[0]==1.0
mulsub(t1,5.0,t2,cache1)
@test cache1[0]==3.0
mulsub(0.5,5.0,t2,cache1)
@test cache1[0]==0.5
#divT
divT(4.3,2.0,cache1)
@test cache1[0]==2.15
divT(t1,2.0,cache1)
@test cache1[0]==0.5
divT(5.6,t1,cache1)
@test cache1[0]==5.6
divT(t1,t2,cache1)
@test cache1[0]==0.5 | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 2228 | using QuantizedSystemSolver
using Test
t1=Taylor0([1.0,1.0,0.0],2)
t2=Taylor0([0.5,2.0,3.0],2)
t3=Taylor0([2.0,1.0,0.0],2)
cache1=Taylor0([1.0,1.0,1.0],2)
cache2=Taylor0([1.0,1.0,1.0],2)
testTaylor(t1)
@test exp(t2)[0]≈1.6487212707001282
@test log(t2)[0]≈-0.6931471805599453
@test sin(t2)[0]≈0.479425538604203
@test cos(t2)[0]≈0.8775825618903728
@test tan(t2)[0]≈0.5463024898437905
@test asin(t2)[0]≈0.5235987755982989
@test acos(t2)[0]≈1.0471975511965979
@test atan(t2)[0]≈0.4636476090008061
@test sinh(t2)[0]≈0.5210953054937474
@test cosh(t2)[0]≈1.1276259652063807
@test tanh(t2)[0]≈0.46211715726000974
@test asinh(t2)[0]≈0.48121182505960347
@test acosh(t3)[0]≈1.3169578969248166
@test atanh(t2)[0]≈0.5493061443340549
@test abs(t2)[0]≈0.5
@test abs(-t2)[0]≈0.5
cache3=Taylor0([0.0,0.0,0.0],2)
@test exp(t2,cache1)[0]≈1.6487212707001282
@test log(t2,cache1)[0]≈-0.6931471805599453
@test sin(t2,cache1,cache2)[0]≈0.479425538604203
@test cos(t2,cache1,cache2)[0]≈0.8775825618903728
@test tan(t2,cache1,cache2)[0]≈0.5463024898437905
@test asin(t2,cache1,cache2,cache3)[0]≈0.5235987755982989
@test acos(t2,cache1,cache2,cache3)[0]≈1.0471975511965979
@test atan(t2,cache1,cache2)[0]≈0.4636476090008061
@test abs(t2,cache1)[0]≈0.5
@test (t2^0)[0]≈1.0
@test (t2^1)[0]≈0.5
@test (t2^2)[0]≈0.25
@test (t2^3)[0]≈0.125
@test (t2^0.0)[0]≈1.0
@test (t2^1.0)[0]≈0.5
@test (t2^2.0)[0]≈0.25
@test (t2^3.0)[0]≈0.125
@test (t2^0.5)[0]≈0.7071067811865476
@test sqrt(t2)[0]≈0.7071067811865476
@test powerT(t2,0,cache1)[0]≈1.0
@test powerT(t2,1,cache1)[0]≈0.5
@test powerT(t2,2,cache1)[0]≈0.25
@test powerT(t2,3.0,cache1)[0]≈0.125
@test sqrt(t2,cache1)[0]≈0.7071067811865476
t2=1.0
@test exp(t2,cache1)[0]≈2.718281828459045
@test log(t2,cache1)[0]≈0.0
@test sin(t2,cache1,cache2)[0]≈0.8414709848078965
@test cos(t2,cache1,cache2)[0]≈0.5403023058681398
@test tan(t2,cache1,cache2)[0]≈1.5574077246549023
@test abs(t2,cache1)[0]≈1.0
t4=Taylor0([-2.0,1.0,0.0],2)
@test abs(t4,cache1)[0]≈2.0
@test (t2^2)≈1.0
@test (t2^3.0)≈1.0
@test sqrt(t2)≈1.0
@test powerT(t2,2,cache1)[0]≈1.0
@test powerT(t2,3.0,cache1)[0]≈1.0
@test sqrt(t2,cache1)[0]≈1.0 | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 2427 |
using QuantizedSystemSolver
#using XLSX
#using BenchmarkTools
using BSON
#using TimerOutputs
#using Plots
function test(case,solvr)
absTol=1e-5
relTol=1e-2
BSON.@load "./solVectAdvection_N1000d01_Feagin14e-12.bson" solFeagin14VectorN1000d01
prob=NLodeProblem(quote
name=(adrN1000d01,)
u[1:333]=1.0
u[334:1000]=0.0
_dx=100.0#1/dx=N/10=1000/10
a=1.0;d=0.1;r=1000.0
#discrete=[0.0]
du[1] = -a*_dx*(u[1]-0.0)+d*_dx*_dx*(u[2]-2.0*u[1]+0.0)+r*u[1]*u[1]*(1.0-u[1])
for k in 2:999
du[k]=-a*_dx*(u[k]-u[k-1])+d*_dx*_dx*(u[k+1]-2.0*u[k]+u[k-1])+r*u[k]*u[k]*(1.0-u[k]) ;
end
du[1000]=-a*_dx*(u[1000]-u[999])+d*_dx*_dx*(2.0*u[999]-2.0*u[1000])+r*u[1000]*u[1000]*(1.0-u[1000])
#= if u[1]-10.0>0.0 #fake to test discreteintgrator & loop
discrete[1]=1.0
end =#
end)
println("start adr solving")
ttnmliqss=0.0
tspan=(0.0,5.0)
solnmliqss=solve(prob,abstol=absTol,reltol=relTol,tspan)#
# @show solnmliqss.totalSteps,solnmliqss.simulStepCount
#save_Sol(solnmliqss,1,2,600,1000,note="analy1")
#@show solnmliqss.savedVars
#save_Sol(solnmliqss)
solnmliqssInterp=solInterpolated(solnmliqss,0.01)
#@show solnmliqssInterp.savedVars
err4=getAverageErrorByRefs(solFeagin14VectorN1000d01,solnmliqssInterp)
# @show err4,solnmliqss.totalSteps
#ttnmliqss=@belapsed solve($prob,$solvr,abstol=$absTol,saveat=0.01,reltol=$relTol,$tspan)
resnmliqss12E_2= ("$(solnmliqss.algName)",relTol,err4,solnmliqss.totalSteps,solnmliqss.simulStepCount,ttnmliqss)
@show resnmliqss12E_2
#= XLSX.openxlsx("3sys $(solvr)_$(case)_$(relTol).xlsx", mode="w") do xf
sheet = xf[1]
sheet["A1"] = "3sys __$case)"
sheet["A4"] = collect(("solver","Tolerance","error","totalSteps","simul_steps","time"))
sheet["A5"] = collect(resnmliqss1E_2)
sheet["A6"] = collect(resnmliqss11E_2)
sheet["A7"] = collect(resnmliqss12E_2)
#= sheet["A8"] = collect(resnmliqss2E_2)
sheet["A9"] = collect(resnmliqss2E_3)
sheet["A10"] = collect(resnmliqss2E_4) =#
end =#
end
case="order1_"
println("golden search")
#test(case,mliqss1()) #goldenSearch
println("compareBounds")
test(case,nmliqss2()) #compareBounds
#test(case,mliqssBounds1())
println("iterations")
#test(case,nliqss1()) #iterations | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1073 | using QuantizedSystemSolver
function test()
odeprob = NLodeProblem(quote #NLodeProblem(quote ... end);
name=(buck,)
C = 1e-4; L = 1e-4; R = 10.0;U = 24.0; T = 1e-4; DC = 0.5; ROn = 1e-5;ROff = 1e5;
discrete = [1e5,1e-5,1e-4,0.0,0.0];u = [0.0,0.0]
rd=discrete[1];rs=discrete[2];nextT=discrete[3];lastT=discrete[4];diodeon=discrete[5]
il=u[1] ;uc=u[2]
id=(il*rs-U)/(rd+rs) # diode's current
du[1] =(-id*rd-uc)/L
du[2]=(il-uc/R)/C
if t-nextT>0.0
lastT=nextT;nextT=nextT+T;rs=ROn
end
if t-lastT-DC*T>0.0
rs=ROff
end
if diodeon*(id)+(1.0-diodeon)*(id*rd-0.6)>0
rd=ROn;diodeon=1.0
else
rd=ROff;diodeon=0.0
end
end)
tspan = (0.0, 0.001)
sol= solve(odeprob,qss2(),tspan,abstol=1e-4,reltol=1e-3)
save_Sol(sol)
xp=sol(2,0.0005)
@show xp
#getAverageErrorByRefs(solRef::Vector{Any},solmliqss::Sol{T,O})
end
test()
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1932 | acceptedi=Vector{Vector{Float64}}(undef,3)
for i =1:3
acceptedi[i]=[0.0,0.0]#zeros(2)
end
constructIntrval(acceptedi,1.0,2.0,3.0,4.0)
@test acceptedi[1] ==[0.0, 1.0]
@test acceptedi[2]==[2.0, 3.0]
@test acceptedi[3] ==[4.0, Inf]
constructIntrval(acceptedi,1.0,2.0,4.0,3.0)
constructIntrval(acceptedi,1.0,4.0,3.0,2.0)
constructIntrval(acceptedi,2.0,1.0,3.0,4.0)
constructIntrval(acceptedi,2.0,1.0,4.0,3.0)
constructIntrval(acceptedi,4.0,1.0,3.0,2.0)
constructIntrval(acceptedi,4.0,3.0,1.0,2.0)
constructIntrval(acceptedi,3.0,4.0,1.0,2.0)
constructIntrval(acceptedi,4.0,3.0,2.0,1.0)
constructIntrval(acceptedi,3.0,4.0,2.0,1.0)
constructIntrval(acceptedi,2.0,3.0,4.0,1.0)
constructIntrval(acceptedi,-1.0,2.0,3.0,4.0)
constructIntrval(acceptedi,-1.0,4.0,3.0,2.0)
constructIntrval(acceptedi,-1.0,2.0,4.0,3.0)
constructIntrval(acceptedi,1.0,-2.0,3.0,4.0)
constructIntrval(acceptedi,1.0,2.0,-3.0,4.0)
constructIntrval(acceptedi,1.0,2.0,3.0,-4.0)
constructIntrval(acceptedi,-1.0,-2.0,3.0,4.0)
constructIntrval(acceptedi,-1.0,2.0,-3.0,4.0)
constructIntrval(acceptedi,-1.0,2.0,3.0,-4.0)
constructIntrval(acceptedi,1.0,-2.0,-3.0,4.0)
constructIntrval(acceptedi,1.0,-2.0,3.0,-4.0)
constructIntrval(acceptedi,1.0,2.0,-3.0,-4.0)
constructIntrval(acceptedi,-1.0,-2.0,-3.0,4.0)
constructIntrval(acceptedi,-1.0,-2.0,3.0,-4.0)
constructIntrval(acceptedi,-1.0,2.0,-3.0,-4.0)
constructIntrval(acceptedi,1.0,-2.0,-3.0,-4.0)
simt, x, β, c, α, b=0.05,1.0,3.5,-0.5,1.0,-6.0
getQfromAsymptote(simt, x, β, c, α, b)
simt, x, β, c, α, b=0.05,1.0,0.0,-0.5,1.0,-6.0
getQfromAsymptote(simt, x, β, c, α, b)
simt, x, β, c, α, b=0.05,1.0,0.0,0.0,1.0,-6.0
getQfromAsymptote(simt, x, β, c, α, b)
simt, x, β, c, α, b=0.05,1.0,0.0,0.0,0.0,-6.0
getQfromAsymptote(simt, x, β, c, α, b)
h, xi, quani, xj, quanj, aii, ajj, aij, aji, uij, uji=1.0,0.1,0.0001,-3.0,0.003,2.0,0.5,10.0,1.5,1.0,1.0
iterationH(h, xi, quani, xj, quanj, aii, ajj, aij, aji, uij, uji) | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 990 | using QuantizedSystemSolver
function test()
odeprob = NLodeProblem(quote
name=(cuk,)
C = 1e-4; L = 1e-4; R = 10.0;U = 24.0; T = 1e-4; DC = 0.25; ROn = 1e-5;ROff = 1e5;L1=1e-4;C1=1e-4
discrete = [1e5,1e-5,1e-4,0.0,0.0]
u = [0.0,0.0,0.0,0.0]
rd=discrete[1];rs=discrete[2];nextT=discrete[3];lastT=discrete[4];diodeon=discrete[5]
il=u[1] ;uc=u[3];il1=u[2] ;uc1=u[4]
id=((il+il1)*rs-uc1)/(rd+rs) # diode's current
du[1] =(-id*rd-uc)/L #il
du[2]=(U-uc1-id*rd)/L1 #il1
du[3]=(il-uc/R)/C #uc
du[4]=(id-il)/C1 #uc1
if t-nextT>0.0
lastT=nextT
nextT=nextT+T
rs=ROn
end
if t-lastT-DC*T>0.0
rs=ROff
end
if diodeon*(id)+(1.0-diodeon)*(id*rd)>0
rd=ROn
diodeon=1.0
else
rd=ROff
diodeon=0.0
end
end)
tspan=(0.0,0.001)
sol= solve(odeprob,nmliqss2(),abstol=1e-4,reltol=1e-3,tspan)
save_Sol(sol,note="QuantizedSystemSolver")
end
test()
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 2345 | using QuantizedSystemSolver
#using BenchmarkTools
using Test
function test()
odeprob = NLodeProblem(quote
name=(cuk4sym,)
C = 1e-4; L = 1e-4; R = 10.0;U = 24.0; T = 1e-4; DC = 0.25; ROn = 1e-5;ROff = 1e5;L1=1e-4;C1=1e-4;C2 = 1e-4;L2 = 1e-4;
#discrete Rd(start=1e5), Rs(start=1e-5), nextT(start=T),lastT,diodeon;
discrete = [1e5,1e-5,1e-4,0.0,0.0]
Rd=discrete[1];Rs=discrete[2];nextT=discrete[3];lastT=discrete[4];diodeon=discrete[5]
u[1:13]=0.0
uc2=u[13]
il2_1=u[i] ;il2_2=u[i-4] ;il2_3=u[i-8] ;il1_1=u[i+4] ;il1_2=u[i] ;il1_3=u[i-4] ;uc1_1=u[i+8];uc1_2=u[i+4] ;uc1_3=u[i] ;
id1=(((il2_1+il1_1)*Rs-uc1_1)/(Rd+Rs))
id2=(((il2_2+il1_2)*Rs-uc1_2)/(Rd+Rs))
id3=(((il2_3+il1_3)*Rs-uc1_3)/(Rd+Rs))
for i=1:4 #il2
du[i] =(-uc2-Rs*id1)/L2
end
for i=5:8 #il1
du[i]=(U-uc1_2-id2*Rs)/L1
end
for i=9:12 #uc1
du[i]=(id3-il2_3)/C1
end
du[13]=(u[1]+u[2]+u[3]+u[4]-uc2/R)/C2
if t-nextT>0.0
lastT=nextT
nextT=nextT+T
Rs=ROn
end
if t-lastT-DC*T>0.0
Rs=ROff
end
if diodeon*(((u[1]+u[5])*Rs-u[9])/(Rd+Rs))+(1.0-diodeon)*(((u[1]+u[5])*Rs-u[9])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
if diodeon*(((u[2]+u[6])*Rs-u[10])/(Rd+Rs))+(1.0-diodeon)*(((u[2]+u[6])*Rs-u[10])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
if diodeon*(((u[3]+u[7])*Rs-u[11])/(Rd+Rs))+(1.0-diodeon)*(((u[3]+u[7])*Rs-u[11])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
if diodeon*(((u[4]+u[8])*Rs-u[12])/(Rd+Rs))+(1.0-diodeon)*(((u[4]+u[8])*Rs-u[12])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
end)
tspan=(0.0,0.0005)
println("start solving")
sol= solve(odeprob,nmliqss2(),abstol=1e-4,reltol=1e-3,tspan)
@test -0.46<sol(1,0.0004)<-0.4
@test 0.4<sol(5,0.0004)<0.45
@test 2.55<sol(9,0.0004)<2.57
@test -2.98<sol(13,0.0004)<-2.9
end
#@btime
test() | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 791 | using OrdinaryDiffEq
#= using BenchmarkTools
using XLSX =#
using Plots
function odeDiffEquPackage()
function funcName(du,u,p,t)# api requires four args
#= du[1] = acos(sin(u[2]))
du[2] = (u[1]) =#
#= du[1] = t
du[2] =1.24*u[1]-0.01*u[2]+0.2 =#
du[1] = t
for k in 2:5
du[k]=(u[k]-u[k-1]) ;
end
end
tspan = (0.0,5.0)
u0= [1.0, 0.0,1.0, 0.0,1.0]
prob = ODEProblem(funcName,u0,tspan)
absTol=1e-5
relTol=1e-2
solRosenbrock23 = solve(prob,Rosenbrock23(),saveat=0.01,abstol = absTol, reltol = relTol) #1.235 ms (1598 allocations: 235.42 KiB)
p1=plot!(solRosenbrock23,marker=(:circle),markersize=2)
savefig(p1, "plot_solRosenbrock23_N8.png")
end
odeDiffEquPackage()
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 10353 | odeprob = NLodeProblem(quote
name=(sysb1,)
u = [-1.0, -2.0]
du[1] = -2.0
du[2] =1.24*u[1]-0.01*u[2]+0.2
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@show -2.6<sol(1,0.7)<-2.2
@show -3.517<sol(2,0.7)<-3.117
odeprob = NLodeProblem(quote
name=(sysb2,)
u = [-1.0, -2.0]
du[1] = -u[2]
du[2] =1.24*u[1]+0.01*u[2]-0.2
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@show 0.5<sol(1,0.7)<0.7
@show -2.4<sol(2,0.7)<-2.2
odeprob = NLodeProblem(quote
name=(sysb53,)
u = [-1.0, -2.0]
du[1] = -20.0*u[1]-80.0*u[2]+1600.0
du[2] =1.24*u[1]-0.01*u[2]+0.2
end)
tspan=(0.0,10.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
plot_Sol(sol)
plot_Sol(sol,1)
u1, u2 = -8.73522174738572, -7.385745994549763
λ1, λ2 = -10.841674966758294, -9.168325033241706
c1, c2 = 121.14809142478035, -143.14809142478035
xp1, xp2 = 0.0, 20.0
x1(t)=c1*u1*exp(λ1*t)+c2*u2*exp(λ2*t)+xp1
x2(t)=c1*exp(λ1*t)+c2*exp(λ2*t)+xp2
solnmliqssInterp=solInterpolated(sol,0.01)
er1=getError(solnmliqssInterp,1,x1)
er2=getError(solnmliqssInterp,2,x2)
@test 0.0<er1<0.00099
@test 0.0<er2<7.4e-5
odeprob = NLodeProblem(quote #NLodeProblem(quote ... end);
name=(buck,)
C = 1e-4; L = 1e-4; R = 10.0;U = 24.0; T = 1e-4; DC = 0.5; ROn = 1e-5;ROff = 1e5;
discrete = [1e5,1e-5,1e-4,0.0,0.0];u = [0.0,0.0]
rd=discrete[1];rs=discrete[2];nextT=discrete[3];lastT=discrete[4];diodeon=discrete[5]
il=u[1] ;uc=u[2]
id=(il*rs-U)/(rd+rs) # diode's current
du[1] =(-id*rd-uc)/L
du[2]=(il-uc/R)/C
if t-nextT>0.0
lastT=nextT;nextT=nextT+T;rs=ROn
end
if t-lastT-DC*T>0.0
rs=ROff
end
if diodeon*(id)+(1.0-diodeon)*(id*rd-0.6)>0
rd=ROn;diodeon=1.0
else
rd=ROff;diodeon=0.0
end
end)
tspan = (0.0, 0.001)
sol= solve(odeprob,nmliqss2(),tspan,abstol=1e-4,reltol=1e-3)
@test 19.0<sol(2,0.0005)<19.4
sol= solve(odeprob,nmliqss1(),tspan,abstol=1e-4,reltol=1e-3)
@test 19.0<sol(2,0.0005)<19.4
sol= solve(odeprob,qss2(),tspan,abstol=1e-4,reltol=1e-3)
BSON.@load "./solVectAdvection_N1000d01_Feagin14e-12.bson" solFeagin14VectorN1000d01
prob=NLodeProblem(quote
name=(adrN1000d01,)
u[1:333]=1.0
u[334:1000]=0.0
_dx=100.0#1/dx=N/10=1000/10
a=1.0;d=0.1;r=1000.0
#discrete=[0.0]
du[1] = -a*_dx*(u[1]-0.0)+d*_dx*_dx*(u[2]-2.0*u[1]+0.0)+r*u[1]*u[1]*(1.0-u[1])
for k in 2:999
du[k]=-a*_dx*(u[k]-u[k-1])+d*_dx*_dx*(u[k+1]-2.0*u[k]+u[k-1])+r*u[k]*u[k]*(1.0-u[k]) ;
end
du[1000]=-a*_dx*(u[1000]-u[999])+d*_dx*_dx*(2.0*u[999]-2.0*u[1000])+r*u[1000]*u[1000]*(1.0-u[1000])
#= if u[1]-10.0>0.0 #fake to test discreteintgrator & loop
discrete[1]=1.0
end =#
end)
tspan=(0.0,5.0)
sol=solve(prob,nmliqss1(),abstol=1e-5,reltol=1e-2,tspan)#
sol=solve(prob,abstol=1e-5,reltol=1e-2,tspan)#
solnmliqssInterp=solInterpolated(sol,0.01)
getErrorByRefs(solnmliqssInterp,1,solFeagin14VectorN1000d01)
err4=getAverageErrorByRefs(solnmliqssInterp,solFeagin14VectorN1000d01)
@test err4<0.05
@show 0.35<sol(1,1.5)<0.39
@show 0.63<sol(2,1.5)<0.67
@show 0.97<sol(400,1.5)<1.0
@show 0.97<sol(600,1.5)<1.0
@show 0.97<sol(1000,1.5)<1.0
odeprob = NLodeProblem(quote
name=(tyson,)
u = [0.0,0.75,0.25,0.0,0.0,0.0]
du[1] = u[4]-1e6*u[1]+1e3*u[2]
du[2] =-200.0*u[2]*u[5]+1e6*u[1]-1e3*u[2]
du[3] = 200.0*u[2]*u[5]-u[3]*(0.018+180.0*(u[4]/(u[1]+u[2]+u[3]+u[4]))^2)
du[4] =u[3]*(0.018+180.0*(u[4]/(u[1]+u[2]+u[3]+u[4]))^2)-u[4]
du[5] = 0.015-200.0*u[2]*u[5]
du[6] =u[4]-0.6*u[6]
end )
tspan=(0.0,25.0)
sol=solve(odeprob,nmliqss2(),tspan)
@show 0.00001<sol(1,20.0)<0.01
@show 0.8<sol(2,20.0)<0.99
@show 0.05<sol(3,20.0)<0.09
@show 0.00001<sol(4,20.0)<0.01
@show 0.0<sol(5,20.0)<8.0e-4
@show 0.01<sol(6,20.0)<0.02
odeprob = NLodeProblem(quote
name=(sysbN5,)
#u = [1.0, 0.0]
u[1]=1.0
u[2] = 0.0
du[1] = -sin(t)
du[2] = (u[1])
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss2(),tspan)
@show 0.5<sol(1,0.7)<0.9
@show 0.4<sol(2,0.7)<0.8
odeprob = NLodeProblem(quote
name=(sysbN6,)
u = [1.0, 0.0]
du[1] = -exp(u[2])
du[2] = (u[1])
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss2(),tspan)
@show 0.07<sol(1,0.7)<0.1
@show 0.2<sol(2,0.7)<0.6
odeprob = NLodeProblem(quote
name=(sysbN66,)
u = [1.0, 0.0]
du[1] = -abs(u[2])
du[2] = (u[1])
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,liqss1(),tspan)
@show 0.6<sol(1,0.7)<0.8
@show 0.5<sol(2,0.7)<0.7
odeprob = NLodeProblem(quote
name=(sysbN8,)
u = [1.0, 0.0]
du[1] = acos(sin(u[2]))
du[2] = (u[1])
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss2(),tspan)
@test 1.3<sol(1,0.5)<1.8
@test 0.4<sol(2,0.5)<0.8
odeprob = NLodeProblem(quote
name=(sysbN7,)
u = [1.0, 0.0]
du[1] = -(u[2]+t^2)
du[2] = u[1]
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss2(),tspan)
@test 0.7<sol(1,0.5)<0.9
odeprob = NLodeProblem(quote
name=(sysN10,)
u = [1.0, 0.0]
du[1] = t
du[2] =1.24*u[1]-0.01*u[2]+0.2
end)
tspan=(0.0,5.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test 0.6<sol(2,0.5)<0.8
odeprob = NLodeProblem(quote
name=(sysN11,)
u = [1.0, 0.0]
du[1] = t
du[2] =1.24*u[1]-0.01*u[2]+0.2
if t-2.0>0.0
u[1] = 0.0
else
u[2] = 0.0
end
end)
tspan=(0.0,5.0)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test 0.6<sol(2,0.5)<0.8
odeprob = NLodeProblem(quote
name=(sysN12,)
u = [1.0, 0.0,1.0, 0.0,1.0]
du[1] = t
for k in 2:5
du[k]=(u[k]-u[k-1]) ;
end
if t-3.0>0.0
u[1] = 1.0
u[2] = 0.0
u[3] = 1.0
u[4] = 0.0
u[5] = 1.0
end
end)
tspan=(0.0,6.0)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test -0.75<sol(2,0.5)<-0.6
plot_SolSum(sol,1,2,xlims=(0.0,1.0),ylims=(0.0,2.0))
plot_SolSum(sol,1,2,xlims=(0.0,1.0),ylims=(0.0,0.0))
plot_SolSum(sol,1,2,xlims=(0.0,0.0),ylims=(0.0,1.0))
plot_SolSum(sol,1,2)
save_Sol(sol,1,2,3,4,5)
save_SolSum(sol,1,2)
plot_Sol(sol,1,2,)
plot_Sol(sol,1,2,xlims=(0.0,1.0),ylims=(0.0,2.0))
plot_Sol(sol,1,2,xlims=(0.0,1.0),ylims=(0.0,0.0))
plot_Sol(sol,1,2,xlims=(0.0,0.0),ylims=(0.0,1.0))
odeprob = NLodeProblem(quote
name=(sysN13,)
u = [1.0, 0.0,1.0, 0.0,1.0]
discrete = [0.5]
du[1] = t
for k in 2:5
du[k]=discrete[1]*(u[k]-u[k-1]) ;
end
if t-5.0>0.0
discrete[1]=0.0
end
if t-3.0>0.0
u[1] = 1.0
u[2] = 0.0
u[3] = 1.0
u[4] = 0.0
u[5] = 1.0
discrete[1]=1.0
end
end)
tspan=(0.0,6.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test 1.1<sol(1,0.5)<1.3
@test -0.35<sol(2,0.5)<-0.2
odeprob = NLodeProblem(quote
name=(sysN14,)
u = [1.0, 0.0,1.0, 0.0,1.0]
discrete = [0.5]
du[1] = t
for k in 2:5
du[k]=discrete[1]*(u[k]-u[k-1]) ;
end
if t-5.0>0.0
discrete[1]=0.0
end
if u[1]-2.0>0.0
u[1] = 1.0
u[2] = 0.0
u[3] = 1.0
u[4] = 0.0
u[5] = 1.0
discrete[1]=1.0
end
end)
tspan=(0.0,6.0)
sol=solve(odeprob,nmliqss2(),tspan)
@test -0.35<sol(2,0.5)<-0.2
sol=solve(odeprob,liqss2(),tspan)
odeprob = NLodeProblem(quote
name=(sysN15,)
u = [1.0, 1.0,1.0, 0.0,1.0,1.0]
discrete = [0.5,1.0,1.0,1.0,1.0,1.0]
du[1] = t+u[2]
for k in 2:5
du[k]=discrete[k]*(u[k*1]-u[k-1]-u[k+1])+(discrete[k+1]+discrete[k-1])*discrete[k*1] ;
end
if t-5.0>0.0
discrete[2]=0.0
end
if u[1]+u[2]-3.0>0.0
u[1] = 1.0
u[3] = 1.0
u[4] = 0.0
discrete[1]=1.0
end
if discrete[1]-u[4]+u[5]>0.0
u[2]=0.0
end
end)
tspan=(0.0,6.0)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@show 1.7<sol(1,0.7)<1.95
@show 0.2<sol(2,0.7)<0.35
odeprob = NLodeProblem(quote
name=(cuk4sym,)
C = 1e-4; L = 1e-4; R = 10.0;U = 24.0; T = 1e-4; DC = 0.25; ROn = 1e-5;ROff = 1e5;L1=1e-4;C1=1e-4;C2 = 1e-4;L2 = 1e-4;
#discrete Rd(start=1e5), Rs(start=1e-5), nextT(start=T),lastT,diodeon;
discrete = [1e5,1e-5,1e-4,0.0,0.0]
Rd=discrete[1];Rs=discrete[2];nextT=discrete[3];lastT=discrete[4];diodeon=discrete[5]
u[1:13]=0.0
uc2=u[13]
il2_1=u[i] ;il2_2=u[i-4] ;il2_3=u[i-8] ;il1_1=u[i+4] ;il1_2=u[i] ;il1_3=u[i-4] ;uc1_1=u[i+8];uc1_2=u[i+4] ;uc1_3=u[i] ;
id1=(((il2_1+il1_1)*Rs-uc1_1)/(Rd+Rs))
id2=(((il2_2+il1_2)*Rs-uc1_2)/(Rd+Rs))
id3=(((il2_3+il1_3)*Rs-uc1_3)/(Rd+Rs))
for i=1:4 #il2
du[i] =(-uc2-Rs*id1)/L2
end
for i=5:8 #il1
du[i]=(U-uc1_2-id2*Rs)/L1
end
for i=9:12 #uc1
du[i]=(id3-il2_3)/C1
end
du[13]=(u[1]+u[2]+u[3]+u[4]-uc2/R)/C2
if t-nextT>0.0
lastT=nextT
nextT=nextT+T
Rs=ROn
end
if t-lastT-DC*T>0.0
Rs=ROff
end
if diodeon*(((u[1]+u[5])*Rs-u[9])/(Rd+Rs))+(1.0-diodeon)*(((u[1]+u[5])*Rs-u[9])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
if diodeon*(((u[2]+u[6])*Rs-u[10])/(Rd+Rs))+(1.0-diodeon)*(((u[2]+u[6])*Rs-u[10])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
if diodeon*(((u[3]+u[7])*Rs-u[11])/(Rd+Rs))+(1.0-diodeon)*(((u[3]+u[7])*Rs-u[11])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
if diodeon*(((u[4]+u[8])*Rs-u[12])/(Rd+Rs))+(1.0-diodeon)*(((u[4]+u[8])*Rs-u[12])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
end)
tspan=(0.0,0.0005)
sol= solve(odeprob,nmliqss2(),abstol=1e-4,reltol=1e-3,tspan)
@test -0.46<sol(1,0.0004)<-0.4
@test 0.4<sol(5,0.0004)<0.45
@test 2.55<sol(9,0.0004)<2.57
@test -2.98<sol(13,0.0004)<-2.9 | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 8358 |
using QuantizedSystemSolver
using Test
#=
odeprob = NLodeProblem(quote
name=(sysb1,)
u = [-1.0, -2.0]
du[1] = -2.0
du[2] =1.24*u[1]-0.01*u[2]+0.2
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test -2.6<sol(1,0.7)<-2.2
@test -3.517<sol(2,0.7)<-3.117
odeprob = NLodeProblem(quote
name=(sysb2,)
u = [-1.0, -2.0]
du[1] = -u[2]
du[2] =1.24*u[1]+0.01*u[2]-0.2
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test 0.5<sol(1,0.7)<0.7
@test -2.4<sol(2,0.7)<-2.2
odeprob = NLodeProblem(quote
name=(sysb53,)
u = [-1.0, -2.0]
du[1] = -20.0*u[1]-80.0*u[2]+1600.0
du[2] =1.24*u[1]-0.01*u[2]+0.2
end)
tspan=(0.0,10.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
plot_Sol(sol)
plot_Sol(sol,1)
u1, u2 = -8.73522174738572, -7.385745994549763
λ1, λ2 = -10.841674966758294, -9.168325033241706
c1, c2 = 121.14809142478035, -143.14809142478035
xp1, xp2 = 0.0, 20.0
x1(t)=c1*u1*exp(λ1*t)+c2*u2*exp(λ2*t)+xp1
x2(t)=c1*exp(λ1*t)+c2*exp(λ2*t)+xp2
solnmliqssInterp=solInterpolated(sol,0.01)
er1=getError(solnmliqssInterp,1,x1)
er2=getError(solnmliqssInterp,2,x2)
@test 0.0<er1<0.00099
@test 0.0<er2<7.4e-5
odeprob = NLodeProblem(quote #NLodeProblem(quote ... end);
name=(buck,)
C = 1e-4; L = 1e-4; R = 10.0;U = 24.0; T = 1e-4; DC = 0.5; ROn = 1e-5;ROff = 1e5;
discrete = [1e5,1e-5,1e-4,0.0,0.0];u = [0.0,0.0]
rd=discrete[1];rs=discrete[2];nextT=discrete[3];lastT=discrete[4];diodeon=discrete[5]
il=u[1] ;uc=u[2]
id=(il*rs-U)/(rd+rs) # diode's current
du[1] =(-id*rd-uc)/L
du[2]=(il-uc/R)/C
if t-nextT>0.0
lastT=nextT;nextT=nextT+T;rs=ROn
end
if t-lastT-DC*T>0.0
rs=ROff
end
if diodeon*(id)+(1.0-diodeon)*(id*rd-0.6)>0
rd=ROn;diodeon=1.0
else
rd=ROff;diodeon=0.0
end
end)
tspan = (0.0, 0.001)
sol= solve(odeprob,nmliqss2(),tspan,abstol=1e-4,reltol=1e-3)
@test 19.0<sol(2,0.0005)<19.4
sol= solve(odeprob,nmliqss1(),tspan,abstol=1e-4,reltol=1e-3)
@test 19.0<sol(2,0.0005)<19.4
sol= solve(odeprob,qss2(),tspan,abstol=1e-4,reltol=1e-3)
prob=NLodeProblem(quote
name=(adrN1000d01,)
u[1:333]=1.0
u[334:1000]=0.0
_dx=100.0#1/dx=N/10=1000/10
a=1.0;d=0.1;r=1000.0
#discrete=[0.0]
du[1] = -a*_dx*(u[1]-0.0)+d*_dx*_dx*(u[2]-2.0*u[1]+0.0)+r*u[1]*u[1]*(1.0-u[1])
for k in 2:999
du[k]=-a*_dx*(u[k]-u[k-1])+d*_dx*_dx*(u[k+1]-2.0*u[k]+u[k-1])+r*u[k]*u[k]*(1.0-u[k]) ;
end
du[1000]=-a*_dx*(u[1000]-u[999])+d*_dx*_dx*(2.0*u[999]-2.0*u[1000])+r*u[1000]*u[1000]*(1.0-u[1000])
#= if u[1]-10.0>0.0 #fake to test discreteintgrator & loop
discrete[1]=1.0
end =#
end)
tspan=(0.0,5.0)
sol=solve(prob,nmliqss1(),abstol=1e-5,reltol=1e-2,tspan)#
sol=solve(prob,abstol=1e-5,reltol=1e-2,tspan)#
@test 0.35<sol(1,1.5)<0.39
@test 0.63<sol(2,1.5)<0.67
@test 0.97<sol(400,1.5)<1.0
@test 0.97<sol(600,1.5)<1.0
@test 0.97<sol(1000,1.5)<1.0
odeprob = NLodeProblem(quote
name=(tyson,)
u = [0.0,0.75,0.25,0.0,0.0,0.0]
du[1] = u[4]-1e6*u[1]+1e3*u[2]
du[2] =-200.0*u[2]*u[5]+1e6*u[1]-1e3*u[2]
du[3] = 200.0*u[2]*u[5]-u[3]*(0.018+180.0*(u[4]/(u[1]+u[2]+u[3]+u[4]))^2)
du[4] =u[3]*(0.018+180.0*(u[4]/(u[1]+u[2]+u[3]+u[4]))^2)-u[4]
du[5] = 0.015-200.0*u[2]*u[5]
du[6] =u[4]-0.6*u[6]
end )
tspan=(0.0,25.0)
sol=solve(odeprob,nmliqss2(),tspan)
@test 0.00001<sol(1,20.0)<0.01
@test 0.8<sol(2,20.0)<0.99
@test 0.05<sol(3,20.0)<0.09
@test 0.00001<sol(4,20.0)<0.01
@test 0.0<sol(5,20.0)<8.0e-4
@test 0.01<sol(6,20.0)<0.02
odeprob = NLodeProblem(quote
name=(sysbN5,)
#u = [1.0, 0.0]
u[1]=1.0
u[2] = 0.0
du[1] = -sin(t)
du[2] = (u[1])
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss2(),tspan)
@test 0.5<sol(1,0.7)<0.9
@test 0.4<sol(2,0.7)<0.8
odeprob = NLodeProblem(quote
name=(sysbN6,)
u = [1.0, 0.0]
du[1] = -exp(u[2])
du[2] = (u[1])
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss2(),tspan)
@test 0.07<sol(1,0.7)<0.1
@test 0.2<sol(2,0.7)<0.6
odeprob = NLodeProblem(quote
name=(sysbN66,)
u = [1.0, 0.0]
du[1] = -abs(u[2])
du[2] = (u[1])
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,liqss1(),tspan)
@test 0.6<sol(1,0.7)<0.8
@test 0.5<sol(2,0.7)<0.7
odeprob = NLodeProblem(quote
name=(sysbN8,)
u = [1.0, 0.0]
du[1] = acos(sin(u[2]))
du[2] = (u[1])
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss2(),tspan)
@test 1.3<sol(1,0.5)<1.8
@test 0.4<sol(2,0.5)<0.8
odeprob = NLodeProblem(quote
name=(sysbN7,)
u = [1.0, 0.0]
du[1] = -(u[2]+t^2)
du[2] = u[1]
end)
tspan=(0.0,1.0)
sol=solve(odeprob,qss2(),tspan)
@test 0.7<sol(1,0.5)<0.9
odeprob = NLodeProblem(quote
name=(sysN10,)
u = [1.0, 0.0]
du[1] = t
du[2] =1.24*u[1]-0.01*u[2]+0.2
end)
tspan=(0.0,5.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test 0.6<sol(2,0.5)<0.8
odeprob = NLodeProblem(quote
name=(sysN11,)
u = [1.0, 0.0]
du[1] = t
du[2] =1.24*u[1]-0.01*u[2]+0.2
if t-2.0>0.0
u[1] = 0.0
else
u[2] = 0.0
end
end)
tspan=(0.0,5.0)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test 0.6<sol(2,0.5)<0.8
odeprob = NLodeProblem(quote
name=(sysN12,)
u = [1.0, 0.0,1.0, 0.0,1.0]
du[1] = t
for k in 2:5
du[k]=(u[k]-u[k-1]) ;
end
if t-3.0>0.0
u[1] = 1.0
u[2] = 0.0
u[3] = 1.0
u[4] = 0.0
u[5] = 1.0
end
end)
tspan=(0.0,6.0)
sol=solve(odeprob,qss2(),tspan)
sol=solve(odeprob,liqss2(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test -0.75<sol(2,0.5)<-0.6
plot_SolSum(sol,1,2,xlims=(0.0,1.0),ylims=(0.0,2.0))
plot_SolSum(sol,1,2,xlims=(0.0,1.0),ylims=(0.0,0.0))
plot_SolSum(sol,1,2,xlims=(0.0,0.0),ylims=(0.0,1.0))
plot_SolSum(sol,1,2)
save_Sol(sol,1,2,3,4,5)
save_SolSum(sol,1,2)
plot_Sol(sol,1,2,)
plot_Sol(sol,1,2,xlims=(0.0,1.0),ylims=(0.0,2.0))
plot_Sol(sol,1,2,xlims=(0.0,1.0),ylims=(0.0,0.0))
plot_Sol(sol,1,2,xlims=(0.0,0.0),ylims=(0.0,1.0))
=#
#= odeprob = NLodeProblem(quote
name=(sysN13,)
u = [1.0, 0.0,1.0, 0.0,1.0]
discrete = [0.5]
du[1] = t
for k in 2:5
du[k]=discrete[1]*(u[k]-u[k-1]) ;
end
if t-5.0>0.0
discrete[1]=0.0
end
if t-3.0>0.0
u[1] = 1.0
u[2] = 0.0
u[3] = 1.0
u[4] = 0.0
u[5] = 1.0
discrete[1]=1.0
end
end)
tspan=(0.0,6.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test 1.1<sol(1,0.5)<1.3
@test -0.2<sol(2,0.5)<0.2
=#
#= odeprob = NLodeProblem(quote
name=(sysN14,)
u = [1.0, 0.0,1.0, 0.0,1.0]
discrete = [0.5]
du[1] = t
for k in 2:5
du[k]=discrete[1]*(u[k]-u[k-1]) ;
end
if t-5.0>0.0
discrete[1]=0.0
end
if u[1]-2.0>0.0
u[1] = 1.0
u[2] = 0.0
u[3] = 1.0
u[4] = 0.0
u[5] = 1.0
discrete[1]=1.0
end
end)
tspan=(0.0,6.0)
sol=solve(odeprob,nmliqss2(),tspan)
@test -0.35<sol(2,0.5)<-0.2
sol=solve(odeprob,liqss2(),tspan) =#
odeprob = NLodeProblem(quote
name=(sysN15,)
u = [1.0, 1.0,1.0, 0.0,1.0,1.0]
discrete = [0.5,1.0,1.0,1.0,1.0,1.0]
du[1] = t+u[2]
for k in 2:5
du[k]=discrete[k]*(u[k*1]-u[k-1]-u[k+1])+(discrete[k+1]+discrete[k-1])*discrete[k*1] ;
end
if t-5.0>0.0
discrete[2]=0.0
end
if u[1]+u[2]-3.0>0.0
u[1] = 1.0
u[3] = 1.0
u[4] = 0.0
discrete[1]=1.0
end
if discrete[1]-u[4]+u[5]>0.0
u[2]=0.0
end
end)
tspan=(0.0,6.0)
#sol=solve(odeprob,nmliqss2(),tspan)
sol=solve(odeprob,qss2(),tspan)
@show odeprob.discreteVars
sol=solve(odeprob,liqss2(),tspan)
save_Sol(sol,ylims=(-5.0,5.0))
@show sol(2,0.7)
@show sol(1,0.7)
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1542 | using QuantizedSystemSolver
using Test
using BSON
@testset "QuantizedSystemSolver.jl" begin
# Write your tests here.
include("./Taylor0testFunctions.jl")
include("./Taylor0testArithmetic.jl")
include("./exampleTest.jl")
include("./constructIntervalTest.jl")
odeprob = NLodeProblem(quote
#sys b53
name=(sysb53,)
u = [-1.0, -2.0]
du[1] = -20.0*u[1]-80.0*u[2]+1600.0
du[2] =1.24*u[1]-0.01*u[2]+0.2
end)
@test typeof(odeprob) <: QuantizedSystemSolver.NLODEProblem{1,2,0,0,3}
@test odeprob.prname == :sysb53
@test odeprob.initConditions == [-1.0, -2.0]
@test odeprob.jac == [[1,2], [1,2]] || odeprob.jac == [[2,1], [2,1]]
@test odeprob.SD == [[1,2], [1,2]] || odeprob.SD == [[2,1], [2,1]]
@test typeof(odeprob.eqs) <: Function
@test typeof(odeprob.exactJac) <: Function
@test typeof(odeprob.jacDim) <: Function
@test odeprob.a == Val(2)
@test odeprob.b == Val(0)
@test odeprob.c == Val(0)
@test odeprob.prtype == Val(1)
Order=1
cache=Array{Taylor0,1}()# cache= vector of taylor0s of size CS
for i=1:3
push!(cache,Taylor0(zeros(Order+1),Order))
end
q1=Taylor0([1.0,0.0], Order)
q2=Taylor0([2.0,0.0], Order)
q=[q1,q2];
t=Taylor0(zeros(Order + 1), Order)
odeprob.eqs(1, q, t, cache)
@test cache[1][0]==-20.0*1.0-80.0*2.0+1600.0
tspan=(0.0,1.0)
sol=solve(odeprob,nmliqss1(),tspan)
@test sol.algName == "nmliqss1"
@test 18.8<sol(2,0.5)<19.2
end
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | code | 1382 |
using QuantizedSystemSolver
#= odeprob = NLodeProblem(quote
name=(lorenz,)
u = [1.0,0.0,0.0]
du[1] = 10.0(u[2]-u[1])
du[2] = u[1]*(28.0-u[3]) - u[2]
du[3] = u[1]*u[2] - (8/3)*u[3]
end)
tspan=(0.0,10.0)
sol=solve(odeprob,qss2(),tspan)
save_Sol(sol) =#
#= odeprob = NLodeProblem(quote
name=(vanderpol,)
u = [0.0,1.7]
du[1] = u[2]
du[2] = (1.0-u[1]*u[1])*u[2]-u[1]
end)
tspan=(0.0,10.0)
sol=solve(odeprob,nmliqss2(),tspan)
save_Sol(sol)
=#
#= odeprob = NLodeProblem(quote
name=(oregonator,)
u = [1.0,1.0,0.0]
du[1] = 100.8*(9.523809523809524e-5*u[2]-u[1]*u[2]+u[1]*(1.0-u[1]))
du[2] =40320.0*(-9.523809523809524e-5*u[2]-u[1]*u[2]+u[3])
du[3] = u[1] -u[3]
end)
tspan=(0.0,10.0)
sol=solve(odeprob,nmliqss2(),tspan)
save_Sol(sol) =#
using Test
odeprob = NLodeProblem(quote
name=(sysN13,)
u = [1.0, 0.0,1.0, 0.0,1.0]
discrete = [0.5]
du[1] = t
for k in 2:5
du[k]=discrete[1]*(u[k]-u[k-1]) ;
end
if t-5.0>0.0
discrete[1]=0.0
end
if t-3.0>0.0
u[1] = 1.0
u[2] = 0.0
u[3] = 1.0
u[4] = 0.0
u[5] = 1.0
discrete[1]=1.0
end
end)
tspan=(0.0,6.0)
sol=solve(odeprob,qss1(),tspan)
sol=solve(odeprob,liqss1(),tspan)
sol=solve(odeprob,nmliqss2(),tspan)
@test 1.1<sol(1,0.5)<1.3
@test -0.35<sol(2,0.5)<-0.2 | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | docs | 3992 | # QuantizedSystemSolver
[](https://mongibellili.github.io/QuantizedSystemSolver/dev/)
[](https://github.com/mongibellili/QuantizedSystemSolver/actions/workflows/CI.yml)
[](https://codecov.io/gh/mongibellili/QuantizedSystemSolver)
The growing intricacy of contemporary engineering systems, typically reduced to differential equations with events, poses a difficulty in digitally simulating them using traditional numerical integration techniques. The Quantized State System (QSS) and the Linearly Implicit Quantized State System (LIQSS) are different methods for tackling such problems.
The QuantizedSystemSolver aims to solve a set of Ordinary differential equations with a set of events. It implements the quantized state system methods: An approach that builds the solution by updating the system variables independently as opposed to classic integration methods that update all the system variables every step.
# Example: Buck circuit
[The Buck](https://en.wikipedia.org/wiki/Buck_converter) is a converter that decreases voltage and increases current with a greater power efficiency than linear regulators. After a mesh analysis we get the problem discribed below.
<img width="220" alt="buckcircuit" src="https://github.com/mongibellili/QuantizedSystemSolver/assets/59377156/c0bcfdbe-ed12-4bb0-8ad1-649ae72dfdd2">
## Problem
The NLodeProblem function takes the following user code:
```julia
odeprob = NLodeProblem(quote
name=(buck,)
#parameters
C = 1e-4; L = 1e-4; R = 10.0;U = 24.0; T = 1e-4; DC = 0.5; ROn = 1e-5;ROff = 1e5;
#discrete and continous variables
discrete = [1e5,1e-5,1e-4,0.0,0.0];u = [0.0,0.0]
#rename for convenience
rd=discrete[1];rs=discrete[2];nextT=discrete[3];lastT=discrete[4];diodeon=discrete[5]
il=u[1] ;uc=u[2]
#helper equations
id=(il*rs-U)/(rd+rs) # diode's current
#differential equations
du[1] =(-id*rd-uc)/L
du[2]=(il-uc/R)/C
#events
if t-nextT>0.0
lastT=nextT;nextT=nextT+T;rs=ROn
end
if t-lastT-DC*T>0.0
rs=ROff
end
if diodeon*(id)+(1.0-diodeon)*(id*rd-0.6)>0
rd=ROn;diodeon=1.0
else
rd=ROff;diodeon=0.0
end
end)
```
The output is an object that subtypes the
```julia
abstract type NLODEProblem{PRTYPE,T,Z,Y,CS} end
```
## Solve
The solve function takes the previous problem (NLODEProblem{PRTYPE,T,Z,Y,CS}) with a chosen algorithm (ALGORITHM{N,O}) and some simulation settings:
```julia
tspan = (0.0, 0.001)
sol= solve(odeprob,nmliqss2(),tspan,abstol=1e-4,reltol=1e-3)
```
It outputs a solution of type Sol{T,O}.
## Query the solution
```julia
# The value of variable 2 at time 0.0005
sol(2,0.0005)
19.209921627620943
# The total number of steps to end the simulation
sol.totalSteps
498
# The number of simultaneous steps during the simulation
sol.simulStepCount
132
# The total number of events during the simulation
sol.evCount
53
# The actual data is stored in two vectors:
sol.savedTimes
sol.savedVars
```
## Plot the solution
```julia
# If the user wants to perform other tasks with the plot:
plot_Sol(sol)
```
```julia
# If the user wants to save the plot to a file:
save_Sol(sol)
```

## Error Analysis
```julia
#Compute the error against an analytic solution
error=getError(sol::Sol{T,O},index::Int,f::Function)
#Compute the error against a reference solution
error=getAverageErrorByRefs(sol,solRef::Vector{Any})
```
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | docs | 176 | # Available Algorithms
```@docs
qss1()
```
```@docs
qss2()
```
```@docs
liqss1()
```
```@docs
liqss2()
```
```@docs
nmliqss1()
```
```@docs
nmliqss2()
```
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | docs | 284 | # Problem Extension
Problem extension can be achieved easily via PRTYPE which is of type Val, or another subtype of the superclass can be created.
```@docs
QuantizedSystemSolver.NLODEProblem{PRTYPE,T,Z,Y,CS}
```
```@docs
QuantizedSystemSolver.NLODEContProblem{PRTYPE,T,Z,Y,CS}
``` | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | docs | 899 | # Taylor0
These are just some examples. Taylor0 is defined for many other functions. However, other functions can also be added.
```@docs
Taylor0
```
```@docs
createT(a::T,cache::Taylor0) where {T<:Number}
```
```@docs
addT(a::Taylor0, b::Taylor0,cache::Taylor0)
```
```@docs
subT(a::Taylor0, b::Taylor0,cache::Taylor0)
```
```@docs
mulT(a::Taylor0, b::Taylor0,cache1::Taylor0)
```
```@docs
divT(a::Taylor0, b::Taylor0,cache1::Taylor0)
```
```@docs
addsub(a::Taylor0, b::Taylor0,c::Taylor0,cache::Taylor0)
```
```@docs
addsub(a::T, b::Taylor0,c::Taylor0,cache::Taylor0) where {T<:Number}
```
```@docs
negateT(a::Taylor0,cache::Taylor0)
```
```@docs
subsub(a::Taylor0, b::Taylor0,c::Taylor0,cache::Taylor0)
```
```@docs
muladdT(a::P,b::Q,c::R,cache1::Taylor0) where {P,Q,R <:Union{Taylor0,Number}}
```
```@docs
mulsub(a::P,b::Q,c::R,cache1::Taylor0) where {P,Q,R <:Union{Taylor0,Number}}
```
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | docs | 332 | # Algorithm Extension
Currently only QSS1,2,3 ; LiQSS1,2,3 ; and mLiQSS1,2,3 exist. Any new algorithm can be added via the name N which is of type Val, with O is the order which also of type Val. For example qss1 is created by:
```julia
qss1()=QSSAlgorithm(Val(:qss),Val(1))
```
```@docs
QuantizedSystemSolver.ALGORITHM{N,O}
``` | QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | docs | 641 | # Developer Guide
While the package is optimized to be fast, extensibility is not compromised. It is divided into 3 entities that can be extended separately: Problem, Algorithm, and Solution. The package uses other packages such as MacroTools.jl for user-code parsing, SymEngine.jl for Jacobian computation, and a modified TaylorSeries.jl that uses caching to obtain free Taylor variables. The approximation through Taylor variables transforms any complicated equations to polynomials, which makes root finding cheaper.
### [Algorithm Extension ](@ref)
### [Problem Extension](@ref)
### [Solution Extension](@ref)
### [Taylor0 ](@ref)
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | docs | 6252 | # Examples
### Systems of 2 Linear Time Invariant Differential equations
```julia
odeprob = NLodeProblem(quote
name=(sysb53,)
u = [-1.0, -2.0]
du[1] = -20.0*u[1]-80.0*u[2]+1600.0
du[2] =1.24*u[1]-0.01*u[2]+0.2
end)
tspan=(0.0,1.0)
```
This is a great example that shows when we need to use the explicit qss, the implicit liqss, or the modified implicit nmliqss. This is a stiff problem so we need to use the implicit methods, but it also contains larger entries outside the main diagonal of the Jacobian. Therefore, nmliqss should the most appropriate algorithm to use.
```julia
sol=solve(odeprob,qss1(),tspan)
save_Sol(sol)
```

```julia
sol=solve(odeprob,qss2(),tspan)
save_Sol(sol)
```

```julia
sol=solve(odeprob,liqss1(),tspan)
save_Sol(sol)
```

```julia
sol=solve(odeprob,liqss2(),tspan)
save_Sol(sol)
```

```julia
sol=solve(odeprob,nmliqss1(),tspan)
save_Sol(sol)
```

```julia
sol=solve(odeprob,nmliqss2(),tspan)
save_Sol(sol)
```

The nmliqss plot does not finish at the final time because it terminated when it reached the equilibrium in which the values are the same as the values at the final time.
### The Tyson Model
```julia
function test(solvr,absTol,relTol)
odeprob = NLodeProblem(quote
name=(tyson,)
u = [0.0,0.75,0.25,0.0,0.0,0.0]
du[1] = u[4]-1e6*u[1]+1e3*u[2]
du[2] =-200.0*u[2]*u[5]+1e6*u[1]-1e3*u[2]
du[3] = 200.0*u[2]*u[5]-u[3]*(0.018+180.0*(u[4]/(u[1]+u[2]+u[3]+u[4]))^2)
du[4] =u[3]*(0.018+180.0*(u[4]/(u[1]+u[2]+u[3]+u[4]))^2)-u[4]
du[5] = 0.015-200.0*u[2]*u[5]
du[6] =u[4]-0.6*u[6]
end )
println("start tyson solving")
tspan=(0.0,25.0)
sol=solve(odeprob,solvr,abstol=absTol,reltol=relTol,tspan)
println("start saving plot")
save_Sol(sol)
end
absTol=1e-5
relTol=1e-2
solvrs=[qss1(),liqss1(),nmliqss1(),nmliqss2()]
for solvr in solvrs
test(solvr,absTol,relTol)
end
```
This model also is stiff and it needs a stiff method, but also the normal liqss will produce unnecessary cycles. Hence, the nmliqss is again the most appropriate.




### Oregonator; Vanderpl
```julia
odeprob = NLodeProblem(quote
name=(vanderpol,)
u = [0.0,1.7]
du[1] = u[2]
du[2] = (1.0-u[1]*u[1])*u[2]-u[1]
end)
tspan=(0.0,10.0)
sol=solve(odeprob,nmliqss2(),tspan)
save_Sol(sol)
```

```julia
odeprob = NLodeProblem(quote
name=(oregonator,)
u = [1.0,1.0,0.0]
du[1] = 100.8*(9.523809523809524e-5*u[2]-u[1]*u[2]+u[1]*(1.0-u[1]))
du[2] =40320.0*(-9.523809523809524e-5*u[2]-u[1]*u[2]+u[3])
du[3] = u[1] -u[3]
end)
tspan=(0.0,10.0)
sol=solve(odeprob,nmliqss2(),tspan)
save_Sol(sol)
```

### Bouncing Ball
```julia
odeprob = NLodeProblem(quote
name=(sysd0,)
u = [50.0,0.0]
discrete=[0.0]
du[1] = u[2]
du[2] = -9.8#+discrete[1]*u[1]
if -u[1]>0.0
u[2]=-u[2]
end
end)
tspan=(0.0,15.0)
sol=solve(odeprob,qss2(),tspan)
```

### Conditional Dosing in Pharmacometrics
This section shows [the Conditional Dosing in Pharmacometrics](https://docs.sciml.ai/DiffEqDocs/stable/examples/conditional_dosing/) example tested using the Tsit5() of the DifferentialEquations.jl
```julia
odeprob = NLodeProblem(quote
name=(sysd0,)
u = [10.0]
discrete=[-1e5]
du[1] =-u[1]
if t-4.0>0.0
discrete[1]=0.0
end
if t-4.00000001>0.0
discrete[1]=-1e5
end
if discrete[1]+(4.0-u[1])>0.0
u[1]=u[1]+10.0
end
end)
tspan=(0.0,10.0)
sol=solve(odeprob,nmliqss2(),tspan)
save_Sol(sol)
```
The condition t == 4 && u[1] < 4 can be replaced by using another discrete variable (flag) that is triggered when t==4 , and it triggers the check of u[1] < 4.

### Four stage Cuk Converter :

```julia
odeprob = NLodeProblem(quote
name=(cuk4sym,)
C = 1e-4; L = 1e-4; R = 10.0;U = 24.0; T = 1e-4; DC = 0.25; ROn = 1e-5;ROff = 1e5;L1=1e-4;C1=1e-4;C2 = 1e-4;L2 = 1e-4;
#discrete Rd(start=1e5), Rs(start=1e-5), nextT(start=T),lastT,diodeon;
discrete = [1e5,1e-5,1e-4,0.0,0.0]
Rd=discrete[1];Rs=discrete[2];nextT=discrete[3];lastT=discrete[4];diodeon=discrete[5]
u[1:13]=0.0
uc2=u[13]
il2_1=u[i] ;il2_2=u[i-4] ;il2_3=u[i-8] ;il1_1=u[i+4] ;il1_2=u[i] ;il1_3=u[i-4] ;uc1_1=u[i+8];uc1_2=u[i+4] ;uc1_3=u[i] ;
id1=(((il2_1+il1_1)*Rs-uc1_1)/(Rd+Rs))
id2=(((il2_2+il1_2)*Rs-uc1_2)/(Rd+Rs))
id3=(((il2_3+il1_3)*Rs-uc1_3)/(Rd+Rs))
for i=1:4 #il2
du[i] =(-uc2-Rs*id1)/L2
end
for i=5:8 #il1
du[i]=(U-uc1_2-id2*Rs)/L1
end
for i=9:12 #uc1
du[i]=(id3-il2_3)/C1
end
du[13]=(u[1]+u[2]+u[3]+u[4]-uc2/R)/C2
if t-nextT>0.0
lastT=nextT
nextT=nextT+T
Rs=ROn
end
if t-lastT-DC*T>0.0
Rs=ROff
end
if diodeon*(((u[1]+u[5])*Rs-u[9])/(Rd+Rs))+(1.0-diodeon)*(((u[1]+u[5])*Rs-u[9])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
if diodeon*(((u[2]+u[6])*Rs-u[10])/(Rd+Rs))+(1.0-diodeon)*(((u[2]+u[6])*Rs-u[10])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
if diodeon*(((u[3]+u[7])*Rs-u[11])/(Rd+Rs))+(1.0-diodeon)*(((u[3]+u[7])*Rs-u[11])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
if diodeon*(((u[4]+u[8])*Rs-u[12])/(Rd+Rs))+(1.0-diodeon)*(((u[4]+u[8])*Rs-u[12])*Rd/(Rd+Rs))>0
Rd=ROn
diodeon=1.0
else
Rd=ROff
diodeon=0.0
end
end)
tspan=(0.0,0.0005)
sol= solve(odeprob,nmliqss2(),abstol=1e-4,reltol=1e-3,tspan)
```

| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | docs | 121 | # Quantized System Solver
```@contents
Pages = ["userGuide.md", "developerGuide.md","examples.md"]
Depth = 1
```
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
|
[
"MIT"
] | 1.0.1 | b4bf1003586f2ee6cb98d8df29e88cbbfacd2ea1 | docs | 939 |
# Application Programming Interface
```@docs
NLodeProblem(odeExprs)
```
```@docs
solve(prob::NLODEProblem{PRTYPE,T,Z,D,CS},al::QSSAlgorithm{SolverType, OrderType},tspan::Tuple{Float64, Float64};sparsity::Val{Sparsity}=Val(false),saveat=1e-9::Float64,abstol=1e-4::Float64,reltol=1e-3::Float64,maxErr=Inf::Float64,maxStepsAllowed=10000000) where{PRTYPE,T,Z,D,CS,SolverType,OrderType,Sparsity}
```
```@docs
plot_Sol(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool,marker=:circle::Symbol) where{T,O}
```
```@docs
save_Sol(sol::Sol{T,O},xvars::Int...;note=" "::String,xlims=(0.0,0.0)::Tuple{Float64, Float64},ylims=(0.0,0.0)::Tuple{Float64, Float64},legend=:true::Bool) where{T,O}
```
```@docs
getError(sol::Sol{T,O},index::Int,f::Function) where{T,O}
```
```@docs
getAverageErrorByRefs(sol::Sol{T,O},solRef::Vector{Any}) where{T,O}
```
| QuantizedSystemSolver | https://github.com/mongibellili/QuantizedSystemSolver.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.