Exemplo n.º 1
0
def solveBVP2(f, N):
    # calc step size 
    h = 1/N
    # set boundary conditions
    y0 = 0
    yN = 0
    # define nodes
    x = np.linspace(0, 1, N)
    # define internal nodes
    x_int = x[1:N-1]
    
    # create LHS (banded) matrix 
    n_mat = N - 2
    Ah = np.zeros((2, n_mat))
    # Fill banded matrix Ab 
    Ah[0][:] = -1 
    Ah[1][:] = 2 - (h**2) 
    
    # create RHS matrix 
    b = np.zeros((N-2,1))
    # fill RHS with f(x_int)
    for i in range(n_mat):
        b[i] = f(x_int[i]) * h**2
        
    # solve system 
    y_int = solveh_banded(Ah,b)
    output = np.append(y0, y_int)
    output = np.append(output, yN)
    
    # plot solns 
    plt.plot(x,output)
    plt.title("Fin Diff Approximation for " + f.__name__)
    plt.title("N =" + str(N), loc = 'left')

    return output 
Exemplo n.º 2
0
 def smooth(self, w):
     foo = self.upper_bands.copy()
     foo[-1] += w  # last row is the diagonal
     return solveh_banded(foo,
                          w * self.y,
                          overwrite_ab=True,
                          overwrite_b=True)
Exemplo n.º 3
0
def minimize_Z_EL_cython(A, l1, l2, rho):
    """"""
    
    # build banded matrix:
    n = len(A)
    Bmat = numpy.zeros((2,n))
    Bmat[0,:] = -2*l2/rho
    Bmat[1,1:n-1] = 1 +4*l2/rho
    Bmat[1,0] = Bmat[1,n-1] = 1 + 2*l2/rho
    
    # convert A into an array:
    A_ = numpy.zeros((len(A), A[0].shape[0], A[0].shape[0]))
    for i in range(len(A)):
	A_[i,:,:] = A[i]
    
    sudoZ = A_[:]
    for i in range(A[0].shape[0]):
	for j in range(i, A[0].shape[0]):
	    resp = A_[:,i,j]
	    # get LS solution:
	    beta_hat = solveh_banded(Bmat, resp, overwrite_ab=True, overwrite_b=True)
	    
	    # shooting algorithm:
	    beta_hat = Z_shooting.Z_shooting(B=beta_hat, y=resp, l1=l1, l2=l2, tol=0.1, max_iter=100)
	    
	    sudoZ[:,i,j] = beta_hat
	    sudoZ[:,j,i] = beta_hat

    # return to a list (terribly inefficient! I have to change this!)
    Z_ = [None] * len(A)
    for i in range(len(A)):
	Z_[i] = sudoZ[i,:,:]
	
    return Z_
Exemplo n.º 4
0
    def fit(self, y, x=None, weights=None, pen=0.):
        banded = True

        if x is None:
            x = self.tau[(self.M-1):-(self.M-1)] # internal knots

        if pen == 0.: # can't use cholesky for singular matrices
            banded = False
            
        if x.shape != y.shape:
            raise ValueError, 'x and y shape do not agree, by default x are the Bspline\'s internal knots'
        
        bt = self.basis(x)
        if pen >= self.penmax:
            pen = self.penmax

        if weights is None:
            weights = N.array(1.)

        wmean = weights.mean()
        _w = N.sqrt(weights / wmean)
        bt *= _w

        # throw out rows with zeros (this happens at boundary points!)

        mask = N.flatnonzero(1 - N.alltrue(N.equal(bt, 0), axis=0))

        bt = bt[:, mask]
        y = y[mask]

        self.df_total = y.shape[0]

        if bt.shape[1] != y.shape[0]:
            raise ValueError, "some x values are outside range of B-spline knots"
        bty = N.dot(bt, _w * y)
        self.N = y.shape[0]
        if not banded:
            self.btb = N.dot(bt, bt.T)
            _g = _band2array(self.g, lower=1, symmetric=True)
            self.coef, _, self.rank = L.lstsq(self.btb + pen*_g, bty)[0:3]
            self.rank = min(self.rank, self.btb.shape[0])
        else:
            self.btb = N.zeros(self.g.shape, N.float64)
            nband, nbasis = self.g.shape
            for i in range(nbasis):
                for k in range(min(nband, nbasis-i)):
                    self.btb[k, i] = (bt[i] * bt[i+k]).sum()

            bty.shape = (1, bty.shape[0])
            self.chol, self.coef = solveh_banded(self.btb + 
                                                 pen*self.g,
                                                 bty, lower=1)

        self.coef = N.squeeze(self.coef)
        self.resid = N.sqrt(wmean) * (y * _w - N.dot(self.coef, bt))
        self.pen = pen
Exemplo n.º 5
0
 def test_03_upper(self):
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     # with the RHS as a 2D array with shape (3,1).
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([1.0, 4.0, 1.0]).reshape(-1,1)
     x = solveh_banded(ab, b)
     assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1,1))
Exemplo n.º 6
0
 def test_01_float32(self):
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     #
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
     b = array([1.0, 4.0, 1.0], dtype=float32)
     x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 7
0
 def test_01_complex(self):
     # Solve
     # [ 4 -j 0]     [ -j]
     # [ j 4 -j] X = [4-j]
     # [ 0 j  4]     [4+j]
     #
     ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
     b = array([-1.0j, 4.0-1j, 4+1j])
     x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 1.0])
Exemplo n.º 8
0
 def test_03_upper(self):
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     # with the RHS as a 2D array with shape (3,1).
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([1.0, 4.0, 1.0]).reshape(-1, 1)
     x = solveh_banded(ab, b)
     assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1, 1))
Exemplo n.º 9
0
 def test_01_upper(self):
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     # with the RHS as a 1D array.
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([1.0, 4.0, 1.0])
     x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 10
0
 def test_tridiag_01_lower(self):
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     #
     ab = array([[4.0, 4.0, 4.0], [1.0, 1.0, -99]])
     b = array([1.0, 4.0, 1.0])
     x = solveh_banded(ab, b, lower=True)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 11
0
 def test_01_upper(self):
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     # with the RHS as a 1D array.
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([1.0, 4.0, 1.0])
     x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 12
0
 def test_01_float32(self):
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     #
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
     b = array([1.0, 4.0, 1.0], dtype=float32)
     x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 13
0
 def test_01_lower(self):
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     #
     ab = array([[4.0, 4.0, 4.0], [1.0, 1.0, -99]])
     b = array([1.0, 4.0, 1.0])
     x = solveh_banded(ab, b, lower=True)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 14
0
 def test_check_finite(self):
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     # with the RHS as a 1D array.
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([1.0, 4.0, 1.0])
     x = solveh_banded(ab, b, check_finite=False)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 15
0
 def test_01_complex(self):
     # Solve
     # [ 4 -j 0]     [ -j]
     # [ j 4 -j] X = [4-j]
     # [ 0 j  4]     [4+j]
     #
     ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
     b = array([-1.0j, 4.0 - 1j, 4 + 1j])
     x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 1.0])
Exemplo n.º 16
0
 def test_check_finite(self):
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     # with the RHS as a 1D array.
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([1.0, 4.0, 1.0])
     x = solveh_banded(ab, b, check_finite=False)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
 def timestep(self, input_signal, output_condition=0,
              curr_noise=0, sub_noise=0, cond_noise=0):
     """
     Compute the time evolution for one timestep using increments of
     the driving noise (current, subunit or conductance or a mixture)
     and the corresponding input signal at the soma. The output as an
     outflux current can also be specified.
     
     Note that the noise has to be initialized outside the class in
     order to be able to compare models for given trajectories of the
     noise. Shape of the noise has to be
     curr_noise.shape = (N_axon+1, M)
     sub_noise.shape = (3, N_axon+1, M)
     cond_noise.shape = (11, N_axon+1, M)
     """
     [v, m, h, n] = self.state.copy()
     # Explicit Euler(-Maruyama) step for gating variables
     self.state[1] += self.dt * self.t_m(v) * (self.m_inf(v)-m)
     self.state[2] += self.dt * self.t_h(v) * (self.h_inf(v)-h)
     self.state[3] += self.dt * self.t_n(v) * (self.n_inf(v)-n)
     # If subunit noise is switched on
     if np.max(self.sigma_sub):
         N = self.N_axon + 1
         self.state[1][:N, :] += (np.sqrt(self.alpha_m(v[:N, :]) *
                 (1-m[:N, :]) + self.beta_m(v[:N, :]) * m[:N, :]) *
                 self.sigma_sub[0] * sub_noise[0])
         self.state[2][:N, :] += (np.sqrt(self.alpha_h(v[:N, :]) *
                 (1-h[:N, :]) + self.beta_h(v[:N, :]) * h[:N, :]) *
                 self.sigma_sub[1] * sub_noise[1])
         self.state[3][:N, :] += (np.sqrt(self.alpha_n(v[:N, :]) *
                 (1-n[:N, :]) + self.beta_n(v[:N, :]) * n[:N, :]) *
                 self.sigma_sub[2] * sub_noise[2])
     # Respect boundaries!
     for i in xrange(3):
         self.state[i][self.state[i]>1] = 1
         self.state[i][self.state[i]<0] = 0
     # Semi-implicit Euler step for voltage variable
     rhs = v - self.dt*self.fv(v, m, h, n)
     rhs[:self.N_axon+1, :] += self.sigma_curr*curr_noise
     # If conductance noise is switched on
     if self.sigma_cond:
         rhs[:self.N_axon+1,:] -= self.compute_cond_noise(cond_noise)
     # Input signal as Neumann boundary condition for left axon endpoint
     rhs[0] += self.boundary * input_signal
     # Output condition as Neumann boundary condition for right axon endpoint
     rhs[-1] += self.boundary * output_condition
     # Modification of RHS to make discrete Neumann Laplacian symmetric
     rhs[0] *= 0.5
     rhs[-1] *= 0.5
     # Solve the linear problem
     self.state[0] = lng.solveh_banded(self.bandedmatrix, rhs,
                                       check_finite=False)
     # Update state
     #self.state = [v_neu, m_neu, h_neu, n_neu]
     self.time_elapsed += self.dt
Exemplo n.º 18
0
 def test_01_lower(self):
     # Solve
     # [ 4 1 2 0]     [1]
     # [ 1 4 1 2] X = [4]
     # [ 2 1 4 1]     [1]
     # [ 0 2 1 4]     [2]
     #
     ab = array([[4.0, 4.0, 4.0, 4.0], [1.0, 1.0, 1.0, -99], [2.0, 2.0, 0.0, 0.0]])
     b = array([1.0, 4.0, 1.0, 2.0])
     x = solveh_banded(ab, b, lower=True)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0, 0.0])
Exemplo n.º 19
0
 def test_01_complex(self):
     # Solve
     # [ 4 -j  2  0]     [2-j]
     # [ j  4 -j  2] X = [4-j]
     # [ 2  j  4 -j]     [4+j]
     # [ 0  2  j  4]     [2+j]
     #
     ab = array([[0.0, 0.0, 2.0, 2.0], [-99, -1.0j, -1.0j, -1.0j], [4.0, 4.0, 4.0, 4.0]])
     b = array([2 - 1.0j, 4.0 - 1j, 4 + 1j, 2 + 1j])
     x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 1.0, 0.0])
Exemplo n.º 20
0
 def test_tridiag_02_complex(self):
     # Solve
     # [ 4 -j 0]     [ -j    4j]
     # [ j 4 -j] X = [4-j  -1-j]
     # [ 0 j  4]     [4+j   4  ]
     #
     ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
     b = array([[-1j, 4.0j], [4.0 - 1j, -1.0 - 1j], [4.0 + 1j, 4.0]])
     x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0j], [1.0, 0.0], [1.0, 1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 21
0
 def test_tridiag_02_float32(self):
     # Solve
     # [ 4 1 0]     [1 4]
     # [ 1 4 1] X = [4 2]
     # [ 0 1 4]     [1 4]
     #
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
     b = array([[1.0, 4.0], [4.0, 2.0], [1.0, 4.0]], dtype=float32)
     x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 22
0
 def test_tridiag_02_lower(self):
     # Solve
     # [ 4 1 0]     [1 4]
     # [ 1 4 1] X = [4 2]
     # [ 0 1 4]     [1 4]
     #
     ab = array([[4.0, 4.0, 4.0], [1.0, 1.0, -99]])
     b = array([[1.0, 4.0], [4.0, 2.0], [1.0, 4.0]])
     x = solveh_banded(ab, b, lower=True)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 23
0
 def test_tridiag_02_float32(self):
     # Solve
     # [ 4 1 0]     [1 4]
     # [ 1 4 1] X = [4 2]
     # [ 0 1 4]     [1 4]
     #
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
     b = array([[1.0, 4.0], [4.0, 2.0], [1.0, 4.0]], dtype=float32)
     x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 24
0
 def test_tridiag_02_lower(self):
     # Solve
     # [ 4 1 0]     [1 4]
     # [ 1 4 1] X = [4 2]
     # [ 0 1 4]     [1 4]
     #
     ab = array([[4.0, 4.0, 4.0], [1.0, 1.0, -99]])
     b = array([[1.0, 4.0], [4.0, 2.0], [1.0, 4.0]])
     x = solveh_banded(ab, b, lower=True)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 25
0
 def test_02_complex(self):
     # Solve
     # [ 4 -j 0]     [ -j    4j]
     # [ j 4 -j] X = [4-j  -1-j]
     # [ 0 j  4]     [4+j   4  ]
     #
     ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
     b = array([[-1j, 4.0j], [4.0 - 1j, -1.0 - 1j], [4.0 + 1j, 4.0]])
     x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0j], [1.0, 0.0], [1.0, 1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 26
0
 def test_01_float32(self):
     warnings.simplefilter("ignore", category=DeprecationWarning)
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     #
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
     b = array([1.0, 4.0, 1.0], dtype=float32)
     c, x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 27
0
 def test_03_upper(self):
     warnings.simplefilter("ignore", category=DeprecationWarning)
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     # with the RHS as a 2D array with shape (3,1).
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([1.0, 4.0, 1.0]).reshape(-1, 1)
     c, x = solveh_banded(ab, b)
     assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1, 1))
Exemplo n.º 28
0
 def test_01_lower(self):
     warnings.simplefilter("ignore", category=DeprecationWarning)
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     #
     ab = array([[4.0, 4.0, 4.0], [1.0, 1.0, -99]])
     b = array([1.0, 4.0, 1.0])
     c, x = solveh_banded(ab, b, lower=True)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 29
0
def scipy_solve_symm_block_tridiag(H_diag, H_upper_diag, v, ab=None):
    """
    use scipy.linalg.solve_banded to solve a symmetric block tridiagonal system

    see https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.solveh_banded.html
    """
    from scipy.linalg import solveh_banded
    ab = convert_block_tridiag_to_banded(H_diag, H_upper_diag) \
        if ab is None else ab
    x = solveh_banded(ab, v.ravel(), lower=True)
    return x.reshape(v.shape)
Exemplo n.º 30
0
 def test_01_lower(self):
     warnings.simplefilter('ignore', category=DeprecationWarning)
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     #
     ab = array([[4.0, 4.0, 4.0], [1.0, 1.0, -99]])
     b = array([1.0, 4.0, 1.0])
     c, x = solveh_banded(ab, b, lower=True)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 31
0
 def test_03_upper(self):
     warnings.simplefilter('ignore', category=DeprecationWarning)
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     # with the RHS as a 2D array with shape (3,1).
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([1.0, 4.0, 1.0]).reshape(-1, 1)
     c, x = solveh_banded(ab, b)
     assert_array_almost_equal(x, array([0.0, 1.0, 0.0]).reshape(-1, 1))
Exemplo n.º 32
0
 def test_01_float32(self):
     warnings.simplefilter('ignore', category=DeprecationWarning)
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     #
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]], dtype=float32)
     b = array([1.0, 4.0, 1.0], dtype=float32)
     c, x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
Exemplo n.º 33
0
 def test_01_complex(self):
     warnings.simplefilter('ignore', category=DeprecationWarning)
     # Solve
     # [ 4 -j 0]     [ -j]
     # [ j 4 -j] X = [4-j]
     # [ 0 j  4]     [4+j]
     #
     ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
     b = array([-1.0j, 4.0 - 1j, 4 + 1j])
     c, x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 1.0])
Exemplo n.º 34
0
 def test_01_complex(self):
     warnings.simplefilter("ignore", category=DeprecationWarning)
     # Solve
     # [ 4 -j 0]     [ -j]
     # [ j 4 -j] X = [4-j]
     # [ 0 j  4]     [4+j]
     #
     ab = array([[-99, -1.0j, -1.0j], [4.0, 4.0, 4.0]])
     b = array([-1.0j, 4.0 - 1j, 4 + 1j])
     c, x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 1.0])
Exemplo n.º 35
0
 def test_02_upper(self):
     # Solve
     # [ 4 1 0]     [1 4]
     # [ 1 4 1] X = [4 2]
     # [ 0 1 4]     [1 4]
     #
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([[1.0, 4.0], [4.0, 2.0], [1.0, 4.0]])
     x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 36
0
 def test_02_upper(self):
     warnings.simplefilter("ignore", category=DeprecationWarning)
     # Solve
     # [ 4 1 0]     [1 4]
     # [ 1 4 1] X = [4 2]
     # [ 0 1 4]     [1 4]
     #
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([[1.0, 4.0], [4.0, 2.0], [1.0, 4.0]])
     c, x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 37
0
 def test_01_complex(self):
     # Solve
     # [ 4 -j  2  0]     [2-j]
     # [ j  4 -j  2] X = [4-j]
     # [ 2  j  4 -j]     [4+j]
     # [ 0  2  j  4]     [2+j]
     #
     ab = array([[0.0, 0.0, 2.0, 2.0], [-99, -1.0j, -1.0j, -1.0j],
                 [4.0, 4.0, 4.0, 4.0]])
     b = array([2 - 1.0j, 4.0 - 1j, 4 + 1j, 2 + 1j])
     x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 1.0, 0.0])
Exemplo n.º 38
0
 def test_02_upper(self):
     warnings.simplefilter('ignore', category=DeprecationWarning)
     # Solve
     # [ 4 1 0]     [1 4]
     # [ 1 4 1] X = [4 2]
     # [ 0 1 4]     [1 4]
     #
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([[1.0, 4.0], [4.0, 2.0], [1.0, 4.0]])
     c, x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 39
0
 def test_02_lower(self):
     # Solve
     # [ 4 1 2 0]     [1 6]
     # [ 1 4 1 2] X = [4 2]
     # [ 2 1 4 1]     [1 6]
     # [ 0 2 1 4]     [2 1]
     #
     ab = array([[4.0, 4.0, 4.0, 4.0], [1.0, 1.0, 1.0, -99], [2.0, 2.0, 0.0, 0.0]])
     b = array([[1.0, 6.0], [4.0, 2.0], [1.0, 6.0], [2.0, 1.0]])
     x = solveh_banded(ab, b, lower=True)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 40
0
 def test_02_float32(self):
     # Solve
     # [ 4 1 2 0]     [1 6]
     # [ 1 4 1 2] X = [4 2]
     # [ 2 1 4 1]     [1 6]
     # [ 0 2 1 4]     [2 1]
     #
     ab = array([[0.0, 0.0, 2.0, 2.0], [-99, 1.0, 1.0, 1.0], [4.0, 4.0, 4.0, 4.0]], dtype=float32)
     b = array([[1.0, 6.0], [4.0, 2.0], [1.0, 6.0], [2.0, 1.0]], dtype=float32)
     x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 41
0
 def test_02_complex(self):
     # Solve
     # [ 4 -j  2  0]     [2-j 2+4j]
     # [ j  4 -j  2] X = [4-j -1-j]
     # [ 2  j  4 -j]     [4+j 4+2j]
     # [ 0  2  j  4]     [2+j j]
     #
     ab = array([[0.0, 0.0, 2.0, 2.0], [-99, -1.0j, -1.0j, -1.0j], [4.0, 4.0, 4.0, 4.0]])
     b = array([[2 - 1j, 2 + 4j], [4.0 - 1j, -1 - 1j], [4.0 + 1j, 4 + 2j], [2 + 1j, 1j]])
     x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0j], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 42
0
def inverse_pfb(ts_pfb, ntap, window=hamming):
    """Invert the SWARM PFB timestream.
    
    Parameters
    ----------
    ts_pfb : np.ndarray[nsamp, nfreq]
        The PFB timestream.
    ntap : integer
        The number of number of blocks combined into the final timestream.
    window : function (ntap, lblock) -> np.ndarray[lblock * ntap]
        The window function to apply to each block.
    """
    
    # Inverse fourier transform to get the pseudo-timestream
    pseudo_ts = np.fft.irfft(ts_pfb, axis=-1)
    
    # Transpose timestream
    pseudo_ts = pseudo_ts.T.copy()
    
    # Pull out the number of blocks and their length
    lblock, nblock = pseudo_ts.shape
    ntsblock = nblock + ntap - 1
    
    # Coefficients for the P matrix
    coeff_P = window(ntap, lblock).reshape(ntap, lblock)  # Create the window array

    # Coefficients for the PP^T matrix
    coeff_PPT = np.array([ (  coeff_P[:, np.newaxis, :]
                            * coeff_P[np.newaxis, :, :] ).diagonal(offset=k).sum(axis=-1)
                           for k in range(ntap) ])
    
    rec_ts = np.zeros((lblock, ntsblock), dtype=np.float64)
    
    for i_off in range(lblock):

        # Create band matrix representation of P
        band_P = np.zeros((ntap, ntsblock), dtype=np.float64)
        band_P[:] = coeff_P[::-1, i_off, np.newaxis]

        # Create band matrix representation of PP^T (symmetric)
        band_PPT = np.zeros((ntap, nblock), dtype=np.float64)
        band_PPT[:] = coeff_PPT[::-1, i_off, np.newaxis]

        # Solve for intermediate vector
        yh = la.solveh_banded(band_PPT, pseudo_ts[i_off])

        # Project into timestream estimate
        rec_ts[i_off] = band_mv(band_P, 0, ntap-1, ntsblock, nblock, yh, trans=True)

    # Transpose timestream back
    rec_ts = rec_ts.T.copy()
    
    return rec_ts
Exemplo n.º 43
0
 def test_02_lower(self):
     # Solve
     # [ 4 1 2 0]     [1 6]
     # [ 1 4 1 2] X = [4 2]
     # [ 2 1 4 1]     [1 6]
     # [ 0 2 1 4]     [2 1]
     #
     ab = array([[4.0, 4.0, 4.0, 4.0], [1.0, 1.0, 1.0, -99],
                 [2.0, 2.0, 0.0, 0.0]])
     b = array([[1.0, 6.0], [4.0, 2.0], [1.0, 6.0], [2.0, 1.0]])
     x = solveh_banded(ab, b, lower=True)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 44
0
def minimize_Z_EL_parallel_Approx(resp, Bmat, l1):
    """Parallel implementation of Z_EL step
    
    INPUT:
	  - resp: vector for (i,j) partial correlation estimates 
	  - Bmat: tridiagonal matrix used to solve L2 problem
	  - l1, l2, rho: penalty parameters
    
    """
    
    beta_hat = stVec(solveh_banded(Bmat, resp, overwrite_ab=True, overwrite_b=True), l1)
    
    return beta_hat    
Exemplo n.º 45
0
def minimize_Z_EL_parallel_cython(resp, Bmat, l1, l2):
    """Parallel implementation of Z_EL step
    
    INPUT:
	  - resp: vector for (i,j) partial correlation estimates 
	  - Bmat: tridiagonal matrix used to solve L2 problem
	  - l1, l2, rho: penalty parameters
    
    """
    
    beta_hat = solveh_banded(Bmat, resp, overwrite_ab=True, overwrite_b=True)
    beta_hat = Z_shooting.Z_shooting(B=beta_hat, y=resp, l1=l1, l2=l2, tol=.1, max_iter=100)
    
    return beta_hat
Exemplo n.º 46
0
    def solve(self, n=20, kappa=1e6):
        t0 = timer()
        #n support points including boundary points
        X = sp.linspace(self.dmleft, self.dmright, n).reshape([1, n])
        self.xi_x = X
        #stiffness at mid of points
        #print a
        #interval size
        h = (self.dmright - self.dmleft) / (n - 1)

        A = sp.zeros([2, n])
        for i in xrange(n - 1):
            a = self.problem.lhs(0.5 * (X[:, i] + X[:, i + 1]))[0]
            A[1, i] += -a / h
            A[1, i + 1] += -a / h
            A[0, i + 1] -= -a / h
        A[1, 0] += kappa
        A[1, n - 1] += kappa

        b = sp.zeros([n, 1])
        b[0, 0] = self.problem.rhs(
            X[:, 0]) * h * 0.5 + kappa * self.problem.bcleft
        b[n - 1, 0] = self.problem.rhs(
            X[:, n - 1]) * h * 0.5 + kappa * self.problem.bcright
        for i in xrange(1, n - 1):
            b[i, 0] = self.problem.rhs(X[:, i]) * h
        self.xi = spl.solveh_banded(A, b, lower=False)

        self.solvetime = timer() - t0
        logger.info('solvetime = {}'.format(self.solvetime))

        def xtoif(x):
            i, r = divmod(min(x, self.dmright - 1e-9) - self.dmleft, h)
            return int(i), r / h

        def u(x):
            i, f = xtoif(x[0])
            u = (1. - f) * self.xi[i, 0] + f * self.xi[i + 1, 0]
            return sp.array([[u]])

        def du(x):
            i, f = xtoif(x[0])
            du = (self.xi[i + 1, 0] - self.xi[i, 0]) / h
            return sp.array([[du]])

        def d2u(x):
            return sp.array([[0.]])

        self.soln = solution(self.D, u, du, d2u)
        return
Exemplo n.º 47
0
def minimize_Z_EL_parallel_Approx(resp, Bmat, l1):
    """Parallel implementation of Z_EL step
    
    INPUT:
	  - resp: vector for (i,j) partial correlation estimates 
	  - Bmat: tridiagonal matrix used to solve L2 problem
	  - l1, l2, rho: penalty parameters
    
    """

    beta_hat = stVec(
        solveh_banded(Bmat, resp, overwrite_ab=True, overwrite_b=True), l1)

    return beta_hat
Exemplo n.º 48
0
 def test_02_complex(self):
     # Solve
     # [ 4 -j  2  0]     [2-j 2+4j]
     # [ j  4 -j  2] X = [4-j -1-j]
     # [ 2  j  4 -j]     [4+j 4+2j]
     # [ 0  2  j  4]     [2+j j]
     #
     ab = array([[0.0, 0.0, 2.0, 2.0], [-99, -1.0j, -1.0j, -1.0j],
                 [4.0, 4.0, 4.0, 4.0]])
     b = array([[2 - 1j, 2 + 4j], [4.0 - 1j, -1 - 1j], [4.0 + 1j, 4 + 2j],
                [2 + 1j, 1j]])
     x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0j], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 49
0
 def test_02_float32(self):
     # Solve
     # [ 4 1 2 0]     [1 6]
     # [ 1 4 1 2] X = [4 2]
     # [ 2 1 4 1]     [1 6]
     # [ 0 2 1 4]     [2 1]
     #
     ab = array(
         [[0.0, 0.0, 2.0, 2.0], [-99, 1.0, 1.0, 1.0], [4.0, 4.0, 4.0, 4.0]],
         dtype=float32)
     b = array([[1.0, 6.0], [4.0, 2.0], [1.0, 6.0], [2.0, 1.0]],
               dtype=float32)
     x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0], [1.0, 0.0], [0.0, 1.0], [0.0, 0.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 50
0
 def test_02_upper(self):
     # Solve
     # [ 4 1 0]     [1 4]
     # [ 1 4 1] X = [4 2]
     # [ 0 1 4]     [1 4]
     #
     ab = array([[-99, 1.0, 1.0],
                 [4.0, 4.0, 4.0]])
     b = array([[1.0, 4.0],
                [4.0, 2.0],
                [1.0, 4.0]])
     x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0],
                       [1.0, 0.0],
                       [0.0, 1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 51
0
def hpfilter02(x, penalty=1600):
	"""Return: (cycle, trend), based on Heer and Maussner.
	Requires ``scipy`` (for sparse matrices).

	Parameters
	----------
	x : array-like
		The 1d timeseries to filter.
	penalty : float
		The Hodrick-Prescott smoothing parameter. A value of 1600 is
		suggested for quarterly data. Ravn and Uhlig suggest using a value
		of 6.25 (1600/4**4) for annual data and 129600 (1600*3**4) for monthly
		data.

	Assumes x is 1d; penalty is often called 'lambda'.

	Conceptualize the calculation as follows:
	eye <- diag( length(y) )
	d2 <- diff( eye, d=2 )
	z <- solve( eye + penalty * crossprod(d2),  y )
	"""
	#local m, i, nobs;
	import numpy as np
	from scipy.linalg import solveh_banded

	nobs = len(x)
	m = np.zeros((3, nobs))
	#construct the banded matrix
	for i in range(nobs):
		m[0,i] = penalty;
		m[1,i] = -4*penalty;
		m[2,i] = 1 + 6*penalty;
	m[0,0] = 0
	m[1,0] = 0
	m[2,0] = 1+penalty

	m[0,1] = 0
	m[1,1] = -2*penalty
	m[2,1] = 1+5*penalty

	m[1,nobs-1] = m[1,1]
	m[2,nobs-1] = m[2,0]
	m[2,nobs-2] = m[2,1]

	trend = solveh_banded(m, x)
	cycle = x - trend
	return cycle, trend
Exemplo n.º 52
0
def hpfilter02(x, penalty=1600):
    """Return: (cycle, trend), based on Heer and Maussner.
	Requires ``scipy`` (for sparse matrices).

	Parameters
	----------
	x : array-like
		The 1d timeseries to filter.
	penalty : float
		The Hodrick-Prescott smoothing parameter. A value of 1600 is
		suggested for quarterly data. Ravn and Uhlig suggest using a value
		of 6.25 (1600/4**4) for annual data and 129600 (1600*3**4) for monthly
		data.

	Assumes x is 1d; penalty is often called 'lambda'.

	Conceptualize the calculation as follows:
	eye <- diag( length(y) )
	d2 <- diff( eye, d=2 )
	z <- solve( eye + penalty * crossprod(d2),  y )
	"""
    #local m, i, nobs;
    import numpy as np
    from scipy.linalg import solveh_banded

    nobs = len(x)
    m = np.zeros((3, nobs))
    #construct the banded matrix
    for i in range(nobs):
        m[0, i] = penalty
        m[1, i] = -4 * penalty
        m[2, i] = 1 + 6 * penalty
    m[0, 0] = 0
    m[1, 0] = 0
    m[2, 0] = 1 + penalty

    m[0, 1] = 0
    m[1, 1] = -2 * penalty
    m[2, 1] = 1 + 5 * penalty

    m[1, nobs - 1] = m[1, 1]
    m[2, nobs - 1] = m[2, 0]
    m[2, nobs - 2] = m[2, 1]

    trend = solveh_banded(m, x)
    cycle = x - trend
    return cycle, trend
Exemplo n.º 53
0
 def test_01_upper(self):
     warnings.simplefilter('ignore', category=DeprecationWarning)
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     # with the RHS as a 1D array.
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([1.0, 4.0, 1.0])
     c, x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
     # Remove the following part of this test in scipy 0.9.
     a = array([[4.0, 1.0, 0.0], [1.0, 4.0, 1.0], [0.0, 1.0, 4.0]])
     fac = zeros_like(a)
     fac[range(3), range(3)] = c[-1]
     fac[(0, 1), (1, 2)] = c[0, 1:]
     assert_array_almost_equal(a, dot(fac.T, fac))
Exemplo n.º 54
0
 def test_01_upper(self):
     warnings.simplefilter("ignore", category=DeprecationWarning)
     # Solve
     # [ 4 1 0]     [1]
     # [ 1 4 1] X = [4]
     # [ 0 1 4]     [1]
     # with the RHS as a 1D array.
     ab = array([[-99, 1.0, 1.0], [4.0, 4.0, 4.0]])
     b = array([1.0, 4.0, 1.0])
     c, x = solveh_banded(ab, b)
     assert_array_almost_equal(x, [0.0, 1.0, 0.0])
     # Remove the following part of this test in scipy 0.9.
     a = array([[4.0, 1.0, 0.0], [1.0, 4.0, 1.0], [0.0, 1.0, 4.0]])
     fac = zeros_like(a)
     fac[range(3), range(3)] = c[-1]
     fac[(0, 1), (1, 2)] = c[0, 1:]
     assert_array_almost_equal(a, dot(fac.T, fac))
Exemplo n.º 55
0
 def test_02_complex(self):
     warnings.simplefilter('ignore', category=DeprecationWarning)
     # Solve
     # [ 4 -j 0]     [ -j    4j]
     # [ j 4 -j] X = [4-j  -1-j]
     # [ 0 j  4]     [4+j   4  ]
     #
     ab = array([[-99, -1.0j, -1.0j],
                 [4.0, 4.0, 4.0]])
     b = array([[   -1j,    4.0j],
                [4.0-1j, -1.0-1j],
                [4.0+1j,     4.0]])
     c, x = solveh_banded(ab, b)
     expected = array([[0.0, 1.0j],
                       [1.0,  0.0],
                       [1.0,  1.0]])
     assert_array_almost_equal(x, expected)
Exemplo n.º 56
0
def solveBVP2(f,N):
    h = 1.0/N
    x = zeros(N-1)
    for i in range(N-1):
        x[i] = (i+1)*h
    f_h = [f(num) for num in x]
    
    diag_h = [2+h**2]*(N-1)
    sub_diag_h = [-1]*(N-2)
    a_h = array([[0]+sub_diag_h, diag_h])
    
    u_h = solveh_banded(a_h,f_h)
    figure()
    plot(x,u_h)
    xlabel('x')
    ylabel('u')
    title('n='+ str(N))
    show()
Exemplo n.º 57
0
def minimize_Z_EL(A, l1, l2, rho):
    """2nd step: Minimize Z step of the ADMM algorithm for solving SIGL
    input:
	- A is a list such that A[i] = thetaZ_parallel_helper_Approx[i] + U[i]
    outout:
	- new update of Z (ie a list)"""

    # build banded matrix:
    n = len(A)
    Bmat = numpy.zeros((2, n))
    Bmat[0, :] = -2 * l2 / rho
    Bmat[1, 1:n - 1] = 1 + 4 * l2 / rho
    Bmat[1, 0] = Bmat[1, n - 1] = 1 + 2 * l2 / rho

    # convert A into an array:
    A_ = numpy.zeros((len(A), A[0].shape[0], A[0].shape[0]))
    for i in range(len(A)):
        A_[i, :, :] = A[i]

    sudoZ = A_[:]
    for i in range(A[0].shape[0]):
        for j in range(i, A[0].shape[0]):
            resp = A_[:, i, j]
            beta_hat = solveh_banded(Bmat,
                                     resp,
                                     overwrite_ab=True,
                                     overwrite_b=True)

            # apply soft thresholding:
            beta_hat = [
                math.copysign(1, x) * max(0,
                                          abs(x) - l1) for x in beta_hat
            ]

            sudoZ[:, i, j] = beta_hat
            sudoZ[:, j, i] = beta_hat

    # return to a list (terribly inefficient! I have to change this!)
    Z_ = [None] * len(A)
    for i in range(len(A)):
        Z_[i] = sudoZ[i, :, :]

    return Z_
Exemplo n.º 58
0
def minimize_Z_EL_parallel_cython(resp, Bmat, l1, l2):
    """Parallel implementation of Z_EL step
    
    INPUT:
	  - resp: vector for (i,j) partial correlation estimates 
	  - Bmat: tridiagonal matrix used to solve L2 problem
	  - l1, l2, rho: penalty parameters
    
    """

    beta_hat = solveh_banded(Bmat, resp, overwrite_ab=True, overwrite_b=True)
    beta_hat = Z_shooting.Z_shooting(B=beta_hat,
                                     y=resp,
                                     l1=l1,
                                     l2=l2,
                                     tol=.1,
                                     max_iter=100)

    return beta_hat
Exemplo n.º 59
0
def minimize_Z_EL_cython(A, l1, l2, rho):
    """"""

    # build banded matrix:
    n = len(A)
    Bmat = numpy.zeros((2, n))
    Bmat[0, :] = -2 * l2 / rho
    Bmat[1, 1:n - 1] = 1 + 4 * l2 / rho
    Bmat[1, 0] = Bmat[1, n - 1] = 1 + 2 * l2 / rho

    # convert A into an array:
    A_ = numpy.zeros((len(A), A[0].shape[0], A[0].shape[0]))
    for i in range(len(A)):
        A_[i, :, :] = A[i]

    sudoZ = A_[:]
    for i in range(A[0].shape[0]):
        for j in range(i, A[0].shape[0]):
            resp = A_[:, i, j]
            # get LS solution:
            beta_hat = solveh_banded(Bmat,
                                     resp,
                                     overwrite_ab=True,
                                     overwrite_b=True)

            # shooting algorithm:
            beta_hat = Z_shooting.Z_shooting(B=beta_hat,
                                             y=resp,
                                             l1=l1,
                                             l2=l2,
                                             tol=0.1,
                                             max_iter=100)

            sudoZ[:, i, j] = beta_hat
            sudoZ[:, j, i] = beta_hat

    # return to a list (terribly inefficient! I have to change this!)
    Z_ = [None] * len(A)
    for i in range(len(A)):
        Z_[i] = sudoZ[i, :, :]

    return Z_
Exemplo n.º 60
0
	def solve(self):
		if(self.theSOE==None):
			print('WARNING BandSPDLinLapackSolver::solve() - No LinearSOE object has been set. \n')
			return -1

		A = self.theSOE.A
		B = self.theSOE.B

		# first copy B into X ???
		# for i in range(0, n):
		# 	X[i] = B[i]

		# now solve AX = B
		if self.theSOE.factored == False: 
			# factored == cholesky decomposition
			# factored and solve
			self.theSOE.X = solveh_banded(A, B)
		
		self.theSOE.factored = True
		return 0