Exemplo n.º 1
0
def _testme():
    from scipy.sparse import csc_matrix
    from numpy import array
    from scipy.linsolve import spdiags, spsolve, use_solver

    print "Inverting a sparse linear system:"
    print "The sparse matrix (constructed from diagonals):"
    a = spdiags([[1, 2, 3, 4, 5], [6, 5, 8, 9, 10]], [0, 1], 5, 5)
    b = array([1, 2, 3, 4, 5])
    print "Solve: single precision complex:"
    use_solver( useUmfpack = False )
    a = a.astype('F')
    x = spsolve(a, b)
    print x
    print "Error: ", a*x-b

    print "Solve: double precision complex:"
    use_solver( useUmfpack = True )
    a = a.astype('D')
    x = spsolve(a, b)
    print x
    print "Error: ", a*x-b

    print "Solve: double precision:"
    a = a.astype('d')
    x = spsolve(a, b)
    print x
    print "Error: ", a*x-b

    print "Solve: single precision:"
    use_solver( useUmfpack = False )
    a = a.astype('f')
    x = spsolve(a, b.astype('f'))
    print x
    print "Error: ", a*x-b
Exemplo n.º 2
0
def levenberg_iteration(z, z_p, z_l, x_p, x_l, f_p, f_l, C, lamb):
    """
    """
    x = build_zx(x_p, x_l)
    J = build_jacobian(z, x_p, x_l, f_p, f_l)
    #J = build_jacobian_numeric(z, x_p,x_l,f_p,f_l)

    Jsp = J.tocsr()
    Csp = C.tocsr()
    alpha = Jsp.T.dot(Csp.dot(Jsp))

    fy_i = []
    for i, f in zip(z_p, f_p):
        l1 = matrix([i[0], i[1], i[2]]).T
        l2 = f[0](x_p[f[1]], x_p[f[2]])
        result = l1 - l2
        fy_i += result.T.tolist()[0]
    for i, f in zip(z_l, f_l):
        l1 = matrix([[i[0]], [i[1]]])
        l2 = f[0](x_p[f[1]], x_l[f[2]])
        result = l1 - l2
        fy_i += result.T.tolist()[0]
    fy_i = array(fy_i, dtype=float64).T
    beta = Jsp.T.dot(Csp.dot(fy_i))

    # Augmented alpha
    alpha.setdiag(sparse.extract_diagonal(alpha) * (1 + lamb))

    #### sparse solver
    return linsolve.spsolve(alpha, beta)
Exemplo n.º 3
0
 def check_solve_sparse_rhs(self):
     """Solve with UMFPACK: double precision, sparse rhs"""
     linsolve.use_solver( useUmfpack = True )
     a = self.a.astype('d')
     b = csc_matrix( self.b )
     x = linsolve.spsolve(a, b)
     #print x
     #print "Error: ", a*x-b
     assert_array_almost_equal(a*x, self.b)
Exemplo n.º 4
0
 def check_solve_umfpack(self):
     """Solve with UMFPACK: double precision"""
     linsolve.use_solver( useUmfpack = True )
     a = self.a.astype('d')
     b = self.b
     x = linsolve.spsolve(a, b)
     #print x
     #print "Error: ", a*x-b
     assert_array_almost_equal(a*x, b)
Exemplo n.º 5
0
 def check_solve_without_umfpack(self): 
     """Solve: single precision"""
     linsolve.use_solver( useUmfpack = False )
     a = self.a.astype('f')
     b = self.b
     x = linsolve.spsolve(a, b.astype('f'))
     #print x
     #print "Error: ", a*x-b
     assert_array_almost_equal(a*x, b)
Exemplo n.º 6
0
def GetEigSparse(D, e1, e2, w):
    w -= dot(w, e1) * e1 / dot(e1, e1)
    w -= dot(w, e2) * e2 / dot(e2, e2)

    for i in range(3):
        w = linsolve.spsolve(D, w)

        w -= dot(w, e1) * e1 / dot(e1, e1)
        w -= dot(w, e2) * e2 / dot(e2, e2)
        w /= dot(w, w)**.5

    return w
def GetEigSparse(D, e1, e2, w):
    w -= dot(w,e1) * e1 / dot(e1,e1)
    w -= dot(w,e2) * e2 / dot(e2,e2)

    for i in range(3):
        w = linsolve.spsolve(D,w)
        
        w -= dot(w,e1) * e1 / dot(e1,e1)
        w -= dot(w,e2) * e2 / dot(e2,e2)
        w /= dot(w,w)**.5        

    return w
Exemplo n.º 8
0
 def solve(self, rhs):
     ij = vstack((self.x_l,self.y_l))
     #print "ij", ij
     #print "data ", self.data_l
     mtx = sparse.coo_matrix((self.data_l,ij))
     mtx.tocsr()
     ts_solve_s = time()
     u_vct = linsolve.spsolve( mtx, rhs )
     ts_solve_e = time()
     dif_solve = ts_solve_e - ts_solve_s
     print "Sparse Solve: %8.2f sec" %dif_solve
     return u_vct  
Exemplo n.º 9
0
    def eval( self, e = None ):

        if not self.sync_resp_tracing:
            self.rtrace_mngr.start_timer()

        adap = self.adap
        tstepper = self.ts
        self.setup()

        self.ls_counter = 0
        
        # Measure computation time
        
        self.eval_timer.reset()

        # Register the list of variables requrired by the adaptive
        # strategy in the time stepper to include their evaluation in
        # the corrector-predictor evaluation ts.extend_output_list(
        # adap.get_indicator_list() )
        #
        while self.t_n1 <= self.T.max and not self.user_wants_abort:

            self.iter_timer.reset()

            if LOGGING_ON:
                log.info( '===================================')
                log.info('time t_n1 = %f',self.t_n1)

            self.ls_counter += 1
            self.report_load_step()
            self.k = 0
            step_flag = 'predictor'
            while self.k < self.KMAX:
                
                self.report_iteration()

                # Extract the matrix representation of the time t_n1
                # stepper for the given time and control variable u
                #
                self.crpr_timer.reset()
                self.K, self.F_int, self.F_ext = tstepper.eval( step_flag,
                                                                    self.U_k,
                                                                    self.t_n,
                                                                    self.t_n1 )
                
                #self.K = sparse.csr_matrix(K_full)
                self.crpr_timer.record()

                self.rtrace_mngr_timer.reset()
                self.rtrace_mngr.record_iter( self.U_k )
                self.rtrace_mngr_timer.record()

                if adap.ihandler_needed():
                    adap.ihandler_invoke()
                    self.d_t *= adap.ihandler_get_scale()
                    self.t_n1 = self.t_n + self.d_t
                    step_flag = 'predictor'
                    self.k = 0

                    if LOGGING_ON:
                        log.info( "redo time step" )
                    continue

                self.R_k = self.F_ext - self.F_int

                if norm(self.R_k) < self.tolerance:  # convergence satisfied
                    self.n_reset = 0
                    if LOGGING_ON:
                        log.info( "time step equilibrated in %d step(s)", self.k )
                    break                        # update_switch -> on

                self.solv_timer.reset()
                #self.d_U = solve(self.K,self.R_k)
                #s_solve = linsolve.factorized(self.K)
                #self.d_U = s_solve(self.R_k)
                self.d_U = linsolve.spsolve(self.K,self.R_k) # DG_k * d_U = r
                self.solv_timer.record()

                self.U_k += self.d_U  

                self.k      += 1
                self.tot_k  += 1
                self.ttot_k += 1
                step_flag = 'corrector'

            else:                                # handling nonconverged step

                if LOGGING_ON:
                    log.info("no convergence reached - refinement in time")
                self.n_reset = self.n_reset + 1  # adaptive strategy halving d_t
                if self.n_reset > self.RESETMAX: # max number of resets achieved

                    # Handle this situation with an exception with an
                    # associated dialog box and concise report of the
                    # iteration process
                    #
                    # @TODO raise the NoConvergence exception
                    if not self.sync_resp_tracing:
                        self.rtrace_mngr.stop_timer()
                        self.rtrace_mngr.timer_tick()
                    return
                
                self.d_t *= adap.fhandler_get_scale()
                self.t_n1 = self.t_n + self.d_t

                if LOGGING_ON:
                    log.info("redo time step with dt = %s", )
                continue

            self.iter_timer.record()
            #self.mem_counter.record()

            if self.sync_resp_tracing:
                self.rtrace_mngr.timer_tick()

            if adap.ehandler_needed(): # explicit adaptations 
                if adap.ehandler_accept():  # accept equilibrium?
                    self.accept_time_step() # register the state and response
                adap.ehandler_invoke()
            else:
                self.accept_time_step()
                self.d_t *= adap.ehandler_get_scale()
                self.t_n  = self.t_n1
                self.t_n1 = self.t_n + self.d_t
                self.T.val = self.t_n1
                
        # Report computation time
        #
        self.eval_timer.record()
        self.eval_timer.report()

        if not self.sync_resp_tracing:
            self.rtrace_mngr.stop_timer()
            self.rtrace_mngr.timer_tick()

        return
Exemplo n.º 10
0
b = array([12,15,20])

Afull[ix_(a),ix_(a)]=1.
Asp[a,b] = 1.

Bsp = Asp + Asp

#print Asp[ix_(a),ix_(b)]
Asp[2,:] = 3

Bsp = Asp + Asp
#Asp[ix_(a),5]=1.
print "after"
b = arange(1,1001)
Asp = Asp.astype('d')
xsp = linsolve.spsolve(Asp,b)
print xsp
print "finished"

Asp = sparse.dok_matrix((4,4))
Asp[2,:] = 5
Bsp = Asp + Asp

Asp[3,2] = 8

print 'col 2', Asp.getcol(2)
Bsp = Bsp + Asp

print 'Asp'
print Bsp[3,1]
Exemplo n.º 11
0
    def pde_interval(self, start, end):
        """ compute the density evolution for the given interval """
        # length of the time interval
        U = end - start
        # final density matrix for this interval
        P_vt = zeros((self.W + 1, U))
        # set initial value
        if self.debug:
            print "W", self.W
            print "U", U
            print P_vt
        P_vt[self.V_reset_index, 0] = 1

        for t in xrange(U - 1):
            # V_rest as defined by lif
            V_rest = self.lif.V_rest(start + t)
            # A B and C diagonals of Lambda
            A = zeros(self.W - 2)
            B = zeros(self.W - 1)
            C = zeros(self.W - 2)

            # now we go and fill the matrix in
            a, b, c, u, w = self.a, self.b, self.c, self.u, self.w

            b_array = self.lif.g * (self.V_values[1:-1] / 2 - V_rest)

            #here we scrapped the for loop, yes!
            #but scrapped readability, no!
            A[:] = -(2 * a * u + b_array[:] * w * u)

            B[:] = ((4 * a * u) - (2 * c * w**2 * u) + (4 * w**2))

            C[:] = -(2 * a * u - b_array[:] * w * u)

            self.beta[1:-1] = (2*a*u + b_array[1:]*w*u) * P_vt[3:-1,t] + \
                (-4*a*u + 2*c*w**2*u + 4*w**2) * P_vt[2:-2,t] +   \
                (2*a*u - b_array[:-1]*w*u) * P_vt[1:-3,t]

            # now we set the diagonals of the tridiagonal matrix
            self.Lambda.setdiag(A, 1)
            self.Lambda.setdiag(B)
            self.Lambda.setdiag(C, -1)

            if self.debug:
                print "A :", A
                print "B :", B
                print "C :", C
                print "Lambda: ", self.Lambda.todense()
                print "Lambda22: ", Lambda2.todense()
                print "beta: ", self.beta

            chi = linsolve.spsolve(self.Lambda, self.beta)

            if self.debug:
                print "chi:", chi
                print "sumchi", chi.sum()

            P_vt[1:-1, t + 1] = chi[:]

            if self.debug: print "P_vt: ", P_vt

        return P_vt
Exemplo n.º 12
0
 def solve(self, rhs):
     return linsolve.spsolve( self.mtx, rhs )   
Exemplo n.º 13
0
            QuickJacobian(x, Nb, Links, Tethers, D)
            Dsp = sparse.csc_matrix(array(D))

            _f = _FiberForce (Nb, x, Xss, Yss, Links, Tethers)
            f = F - _f

            e3 = 0. * x            
            z = x - e1 * x[Parts[7][0]] - e2 * x[Parts[7][0]+Nb]
            for p in range(2,7):
                for i in Parts[p]:
                    e3[i] = z[i+Nb]
                    e3[i+Nb] = -z[i]


            f -= e3 * dot(f,e3) / dot(e3,e3)
            y = linsolve.spsolve(Dsp,f)
            y -= e3 * dot(y,e3) / dot(e3,e3)

            damp = 1
            x += damp * y
            subMax = max(list(abs(f)))
            print "       submax:",subMax, "  damp:",damp

        


        f = _FiberForce (Nb, x, Xss, Yss, Links, Tethers)
        r = b + dot(dt*A,f) - x

#        clf(); plot(r); #&&raw_input("")
        MaxRes = max(list(abs(r)))