Skip to content

Commit

Permalink
Unifying scipy imports
Browse files Browse the repository at this point in the history
  • Loading branch information
PeterMeisrimelModelon committed Jan 24, 2024
1 parent 3f8e9ea commit f748446
Show file tree
Hide file tree
Showing 15 changed files with 85 additions and 91 deletions.
4 changes: 2 additions & 2 deletions examples/cvode_with_jac_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import numpy as np
import scipy.sparse as SP
import scipy.sparse as sps
import nose
from assimulo.solvers import CVode
from assimulo.problem import Explicit_Problem
Expand Down Expand Up @@ -59,7 +59,7 @@ def jac(t,y):
rowvals = [0, 1, 0, 1, 2, 0, 1]
data = [-0.04, 0.04, 1e4*y[2], -1e4*y[2]-6e7*y[1], 6e7*y[1], 1e4*y[1], -1e4*y[1]]

J = SP.csc_matrix((data, rowvals, colptrs))
J = sps.csc_matrix((data, rowvals, colptrs))
return J

#Defines an Assimulo explicit problem
Expand Down
33 changes: 15 additions & 18 deletions examples/kinsol_ors.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,16 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import numpy as np
import scipy.linalg as LIN
import scipy.io as IO
import scipy.sparse as SPARSE
import scipy.sparse.linalg as LINSP
import nose
import os
import nose
import numpy as np
import scipy as sp
import scipy.sparse as sps
from assimulo.solvers import KINSOL
from assimulo.problem import Algebraic_Problem
import warnings
import scipy.sparse

warnings.simplefilter("ignore", scipy.sparse.SparseEfficiencyWarning)
warnings.simplefilter("ignore", sps.SparseEfficiencyWarning)

file_path = os.path.dirname(os.path.realpath(__file__))

Expand All @@ -39,22 +36,22 @@ def run_example(with_plots=True):
Iterative Methods for Sparse Linear Systems.
"""
#Read the original matrix
A_original = IO.mmread(os.path.join(file_path,"kinsol_ors_matrix.mtx"))
A_original = sp.io.mmread(os.path.join(file_path,"kinsol_ors_matrix.mtx"))

#Scale the original matrix
A = SPARSE.spdiags(1.0/A_original.diagonal(), 0, len(A_original.diagonal()), len(A_original.diagonal())) * A_original
A = sps.spdiags(1.0/A_original.diagonal(), 0, len(A_original.diagonal()), len(A_original.diagonal())) * A_original

#Preconditioning by Symmetric Gauss Seidel
if True:
D = SPARSE.spdiags(A.diagonal(), 0, len(A_original.diagonal()), len(A_original.diagonal()))
Dinv = SPARSE.spdiags(1.0/A.diagonal(), 0, len(A_original.diagonal()), len(A_original.diagonal()))
E = -SPARSE.tril(A,k=-1)
F = -SPARSE.triu(A,k=1)
D = sps.spdiags(A.diagonal(), 0, len(A_original.diagonal()), len(A_original.diagonal()))
Dinv = sps.spdiags(1.0/A.diagonal(), 0, len(A_original.diagonal()), len(A_original.diagonal()))
E = -sps.tril(A,k=-1)
F = -sps.triu(A,k=1)
L = (D-E).dot(Dinv)
U = D-F
Prec = L.dot(U)

solvePrec = LINSP.factorized(Prec)
solvePrec = sps.linalg.factorized(Prec)

#Create the RHS
b = A.dot(np.ones(A.shape[0]))
Expand Down Expand Up @@ -91,7 +88,7 @@ def prec_solve(r):
def setup_param(solver):
solver.linear_solver = "spgmr"
solver.max_dim_krylov_subspace = 10
solver.ftol = LIN.norm(res(solver.y0))*1e-9
solver.ftol = np.linalg.norm(res(solver.y0))*1e-9
solver.max_iter = 300
solver.verbosity = 10
solver.globalization_strategy = "none"
Expand All @@ -105,8 +102,8 @@ def setup_param(solver):
#Solve Preconditioned system
y_prec = alg_solver_prec.solve()

print("Error , in y: ", LIN.norm(y-np.ones(len(y))))
print("Error (preconditioned), in y: ", LIN.norm(y_prec-np.ones(len(y_prec))))
print("Error , in y: ", np.linalg.norm(y-np.ones(len(y))))
print("Error (preconditioned), in y: ", np.linalg.norm(y_prec-np.ones(len(y_prec))))

if with_plots:
import pylab as P
Expand Down
7 changes: 3 additions & 4 deletions examples/mech_system_pendulum.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import numpy as np
import nose
import scipy.linalg as sl
import numpy as np
from assimulo.special_systems import Mechanical_System
from assimulo.solvers import IDA, ODASSL

Expand Down Expand Up @@ -58,10 +57,10 @@ def run_example(index="ind1", with_plots=True, with_test=False):
final_residual=my_pend.res(0.,dae_pend.y,dae_pend.yd)

print(my_pend.name+" Residuals after the integration run\n")
print(final_residual, 'Norm: ', sl.norm(final_residual))
print(final_residual, 'Norm: ', np.linalg.norm(final_residual))

if with_test:
nose.tools.assert_less(sl.norm(final_residual), 1.5e-1)
nose.tools.assert_less(np.linalg.norm(final_residual), 1.5e-1)
if with_plots:
dae_pend.plot(mask=[1,1]+(len(my_pend.y0)-2)*[0])
return my_pend, dae_pend
Expand Down
4 changes: 2 additions & 2 deletions examples/radau5ode_with_disc_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import numpy as np
import scipy.sparse as sp
import scipy.sparse as sps
import nose
from assimulo.solvers import Radau5ODE
from assimulo.problem import Explicit_Problem
Expand Down Expand Up @@ -54,7 +54,7 @@ def rhs(self,t,y,sw):
return np.array([yd_0,yd_1,yd_2])

def jac(self, t, y):
return sp.csc_matrix((len(y), len(y)), dtype = 'float')
return sps.csc_matrix((len(y), len(y)), dtype = 'float')

jac_nnz = 0

Expand Down
6 changes: 3 additions & 3 deletions examples/radau5ode_with_jac_sparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import numpy as np
import scipy.sparse as SP
import nose
import numpy as np
import scipy.sparse as sps
from assimulo.solvers import Radau5ODE
from assimulo.problem import Explicit_Problem

Expand Down Expand Up @@ -57,7 +57,7 @@ def jac(t,y):
rowvals = [0, 1, 0, 1, 2, 0, 1]
data = [-0.04, 0.04, 1e4*y[2], -1e4*y[2]-6e7*y[1], 6e7*y[1], 1e4*y[1], -1e4*y[1]]

J = SP.csc_matrix((data, rowvals, colptrs))
J = sps.csc_matrix((data, rowvals, colptrs))
return J

#Defines an Assimulo explicit problem
Expand Down
13 changes: 7 additions & 6 deletions src/lib/sundials_callbacks_ida_cvode.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import cython
import traceback
import scipy.sparse as sps
from assimulo.exception import AssimuloRecoverableError

cdef int cv_rhs(realtype t, N_Vector yv, N_Vector yvdot, void* problem_data) noexcept:
Expand Down Expand Up @@ -123,8 +124,8 @@ IF SUNDIALS_VERSION >= (3,0,0):
else:
jac=(<object>pData.JAC)(t,y)

if not isinstance(jac, sparse.csc_matrix):
jac = sparse.csc_matrix(jac)
if not isinstance(jac, sps.csc_matrix):
jac = sps.csc_matrix(jac)
raise AssimuloException("The Jacobian must be stored on Scipy's CSC format.")
ret_nnz = jac.nnz
if ret_nnz > nnz:
Expand Down Expand Up @@ -188,8 +189,8 @@ ELSE:
else:
jac=(<object>pData.JAC)(t,y)

if not isinstance(jac, sparse.csc_matrix):
jac = sparse.csc_matrix(jac)
if not isinstance(jac, sps.csc_matrix):
jac = sps.csc_matrix(jac)
raise AssimuloException("The Jacobian must be stored on Scipy's CSC format.")
ret_nnz = jac.nnz
if ret_nnz > nnz:
Expand Down Expand Up @@ -250,7 +251,7 @@ IF SUNDIALS_VERSION >= (3,0,0):
traceback.print_exc()
return CVDLS_JACFUNC_UNRECVR

if isinstance(jac, sparse.csc_matrix):
if isinstance(jac, sps.csc_matrix):
for j in range(Neq):
col_i = Jacobian.cols[j]
for i in range(jac.indptr[j], jac.indptr[j+1]):
Expand Down Expand Up @@ -300,7 +301,7 @@ ELSE:
traceback.print_exc()
return CVDLS_JACFUNC_UNRECVR

if isinstance(jac, sparse.csc_matrix):
if isinstance(jac, sps.csc_matrix):
for j in range(Neq):
col_i = DENSE_COL(Jacobian, j)
for i in range(jac.indptr[j], jac.indptr[j+1]):
Expand Down
4 changes: 2 additions & 2 deletions src/solvers/euler.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

cimport numpy as np
import numpy as np
import scipy.sparse as sp
import scipy.sparse as sps

from assimulo.explicit_ode cimport Explicit_ODE
from assimulo.exception import AssimuloException
Expand Down Expand Up @@ -331,7 +331,7 @@ cdef class ImplicitEuler(Explicit_ODE):
if self.usejac: #Retrieve the user-defined jacobian
jac = self.problem.jac(t,y)

if isinstance(jac, sp.csc_matrix):
if isinstance(jac, sps.csc_matrix):
jac = jac.toarray()
else: #Calculate a numeric jacobian
delt = np.array([(self._eps*max(abs(yi),1.e-5))**0.5 for yi in y])*np.identity(self._leny) #Calculate a disturbance
Expand Down
27 changes: 13 additions & 14 deletions src/solvers/odepack.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@
import sys
import logging
import numpy as np
import scipy.linalg as Sc
import scipy.sparse as sp
import scipy.sparse as sps

from assimulo.exception import ODEPACK_Exception, RKStarter_Exception
from assimulo.ode import ID_PY_COMPLETE, ID_PY_EVENT, NORMAL
Expand Down Expand Up @@ -154,11 +153,11 @@ def autostart(self,t,y,sw0=[]):
direction=np.sign(tf-t0)

#Perturb initial condition and compute rough Lipschitz constant
cent=Sc.norm(y)/normscale/100.
cent=np.linalg.norm(y)/normscale/100.
v0=y+cent*np.random.rand(len(y),1)
u0prime=f(t,y,sw0)
v0prime=f(t,v0,sw0)
Lip=Sc.norm(u0prime-v0prime)/Sc.norm(y-v0)
Lip=np.linalg.norm(u0prime-v0prime)/np.linalg.norm(y-v0)
h=direction*min(1e-3*T,max(1e-8*T,0.05/Lip))
#step 1: fwd Euler step
u1=y+h*u0prime
Expand All @@ -168,11 +167,11 @@ def autostart(self,t,y,sw0=[]):
u0comp=u1-h*u1prime
#step 3: estimate of local error
du=u0comp-y
dunorm=Sc.norm(du)
dunorm=np.linalg.norm(du)
errnorm=dunorm/normscale
#step 4: new estimate of Lipschitz constant
u0comprime=f(t0,u0comp,sw0)
L=Sc.norm(u0comprime-u0prime)/dunorm
L=np.linalg.norm(u0comprime-u0prime)/dunorm
M=np.dot(du,u0comprime-u0prime)/dunorm**2
#step 5: construct a refined starting stepsize
theta1=tolscale/np.sqrt(errnorm)
Expand Down Expand Up @@ -203,7 +202,7 @@ def integrate_start(self, t, y):
# a) get previous stepsize if any
hu, nqu ,nq ,nyh, nqnyh = get_lsod_common()
#H = hu if hu != 0. else 1.e-4 # this needs some reflections
#H =(abs(RWORK[0]-t)*((self.options["rtol"])**(1/(self.rkstarter+1))))/(100*Sc.norm(self.problem.rhs(t,y,self.sw))+10)#if hu != 0. else 1.e-4
#H =(abs(RWORK[0]-t)*((self.options["rtol"])**(1/(self.rkstarter+1))))/(100*np.linalg.norm(self.problem.rhs(t,y,self.sw))+10)#if hu != 0. else 1.e-4
H=1e-2
#H=self.autostart(t,y)
#H=3*H
Expand Down Expand Up @@ -271,7 +270,7 @@ def _jacobian(self, t, y):
"""
jac = self.problem.jac(t,y)

if isinstance(jac, sp.csc_matrix):
if isinstance(jac, sps.csc_matrix):
jac = jac.toarray()

return jac
Expand Down Expand Up @@ -908,7 +907,7 @@ def rk_like13(self, t0, y0, sw0):
c+=1
nord[0,:] = y0
nord[1,:] = h*K[0,:]
nord[2:,:] = Sc.solve(self.A[self.number_of_steps],b)
nord[2:,:] = np.linalg.solve(self.A[self.number_of_steps],b)
return nord
def rk_like14(self, t0, y0, sw0):
"""
Expand All @@ -931,7 +930,7 @@ def rk_like14(self, t0, y0, sw0):
c+=1
nord[0,:] = y0
nord[1,:] = h*K[0,:]
nord[2:,:] = Sc.solve(self.A[self.number_of_steps],b)
nord[2:,:] = np.linalg.solve(self.A[self.number_of_steps],b)
return nord
def rk_like15(self, t0, y0, sw0):
"""
Expand All @@ -954,7 +953,7 @@ def rk_like15(self, t0, y0, sw0):
c+=1
nord[0,:] = y0
nord[1,:] = h*K[0,:]
nord[2:,:] = Sc.solve(self.A[self.number_of_steps],b)
nord[2:,:] = np.linalg.solve(self.A[self.number_of_steps],b)
return nord
def nordsieck(self,k):
"""
Expand All @@ -975,12 +974,12 @@ def Nordsieck_RKn(self,t0,y,sw0):
co=np.array([co_nord[0]])
nord_n=np.vander(co_nord[0],self.number_of_steps+1)
b=y[1:]-y0-co.T*yf
nord=Sc.solve(nord_n[0:2,0:2],b)
nord=np.linalg.solve(nord_n[0:2,0:2],b)
elif l==4:
co=np.array([co_nord[1]])
nord_n=np.vander(co_nord[1],self.number_of_steps+1)
b=y[1:]-y0-H*co.T*yf
nord=Sc.solve(nord_n[0:3,0:3],b)
nord=np.linalg.solve(nord_n[0:3,0:3],b)
nord=np.vstack((y0,H*yf,nord[::-1]))
return nord
def Nordsieck_RKs(self,t0,y,sw0):
Expand All @@ -994,7 +993,7 @@ def Nordsieck_RKs(self,t0,y,sw0):
co=co_nord[s-2]
co=np.array([co])
b=y[1:]-y0-H*co.T*yf
nord=Sc.solve(A[s],b)
nord=np.linalg.solve(A[s],b)
nord=np.vstack((y0,H*yf,nord))
return nord

Expand Down
26 changes: 13 additions & 13 deletions src/solvers/radau5.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import numpy as np
import scipy as S
import scipy.sparse as sp
import scipy as sp
import scipy.sparse as sps

from assimulo.exception import (
AssimuloException,
Expand Down Expand Up @@ -339,7 +339,7 @@ def _jacobian(self, t, y):
ret = 0
try:
jac = self.problem.jac(t,y)
if isinstance(jac, sp.csc_matrix) and (self.options["linear_solver"] == "DENSE"):
if isinstance(jac, sps.csc_matrix) and (self.options["linear_solver"] == "DENSE"):
jac = jac.toarray()
except BaseException as E:
jac = np.eye(len(y))
Expand Down Expand Up @@ -694,8 +694,8 @@ def newton(self,t,y):
for k in range(20):

self._curiter = 0 #Reset the iteration
self._fac_con = max(self._fac_con, self._eps)**0.8;
self._theta = abs(self.thet);
self._fac_con = max(self._fac_con, self._eps)**0.8
self._theta = abs(self.thet)

if self._needjac:
self._jac = self.jacobian(t,y)
Expand All @@ -707,9 +707,9 @@ def newton(self,t,y):
self._g = self._gamma/self.h
self._B = self._g*self.I - self._jac

self._P1,self._L1,self._U1 = S.linalg.lu(self._B) #LU decomposition
self._P2,self._L2,self._U2 = S.linalg.lu(self._a*self.I-self._jac)
self._P3,self._L3,self._U3 = S.linalg.lu(self._b*self.I-self._jac)
self._P1,self._L1,self._U1 = sp.linalg.lu(self._B) #LU decomposition
self._P2,self._L2,self._U2 = sp.linalg.lu(self._a*self.I-self._jac)
self._P3,self._L3,self._U3 = sp.linalg.lu(self._b*self.I-self._jac)

self._needLU = False

Expand Down Expand Up @@ -1513,8 +1513,8 @@ def newton(self,t,y,yd):
for k in range(20):

self._curiter = 0 #Reset the iteration
self._fac_con = max(self._fac_con, self._eps)**0.8;
self._theta = abs(self.thet);
self._fac_con = max(self._fac_con, self._eps)**0.8
self._theta = abs(self.thet)

if self._needjac:
self._jac = self.jacobian(t,y,yd)
Expand All @@ -1526,9 +1526,9 @@ def newton(self,t,y,yd):
self._g = self._gamma/self.h
self._B = self._g*self.M - self._jac

self._P1,self._L1,self._U1 = S.linalg.lu(self._B) #LU decomposition
self._P2,self._L2,self._U2 = S.linalg.lu(self._a*self.M-self._jac)
self._P3,self._L3,self._U3 = S.linalg.lu(self._b*self.M-self._jac)
self._P1,self._L1,self._U1 = sp.linalg.lu(self._B) #LU decomposition
self._P2,self._L2,self._U2 = sp.linalg.lu(self._a*self.M-self._jac)
self._P3,self._L3,self._U3 = sp.linalg.lu(self._b*self.M-self._jac)

self._needLU = False

Expand Down
Loading

0 comments on commit f748446

Please sign in to comment.