Example #1
0
    def check_20Feb04_bug(self):
        a = [[1, 1], [1.0, 0]]  # ok
        x0 = solve(a, [1, 0j])
        assert_array_almost_equal(numpy.dot(a, x0), [1, 0])

        a = [[1, 1], [1.2, 0]]  # gives failure with clapack.zgesv(..,rowmajor=0)
        b = [1, 0j]
        x0 = solve(a, b)
        assert_array_almost_equal(numpy.dot(a, x0), [1, 0])
Example #2
0
def test_floating1():
    '''testcase floating1'''
    mat = numpy.array([[3., 3., 3., 6.], [3., 4., 5., 6.], [1., 5., 6., 2.]])
    vec = numpy.array([42., 50., 37.])

    sol = [-1, 2, 3, -1]
    sol2, rank = solve(mat, vec, field=RealField)
    mat = mat.round(decimals=14)
    sol2, rank = solve(mat, vec, field=RealField)
    #sol2 = numpy.array(simplify_full_rank(sol2), dtype=float)
    for i, val in enumerate(sol2):
        assert sol[i] - val < 1e-14
    assert rank == 3
Example #3
0
def direct_lstsq(a, b, cmplx=0):
    at = transpose(a)
    if cmplx:
        at = conjugate(at)
    a1 = dot(at, a)
    b1 = dot(at, b)
    return solve(a1, b1)
    def __call__(self, x):
        if not(min(self.x)<=x<=max(self.x)):
	    return float('nan')
	
	distance = [((self.x[i]-x)**2, i) for i in xrange(len(self.x))]
	distance.sort()
        
        dist, indx = distance[0]
        if dist==0.0:
	    return self.y[indx]
	
        A = []
        B = []
	
        # 1st point
        dist, indx = distance[0]
        A.append( [self.x[indx]**i for i in xrange(2, -1, -1)] )
        B.append( [self.y[indx]] )
	
        # 2st point
        dist, indx = distance[1]
        A.append( [self.x[indx]**i for i in xrange(2, -1, -1)] )
        B.append( [self.y[indx]] )
	
        # 3st point
        dist, indx = distance[2]
        A.append( [self.x[indx]**i for i in xrange(2, -1, -1)] )
        B.append( [self.y[indx]] )
	
        X = solve(A, B)
	
	return sum(X[i][0]*x**(2-i) for i in xrange(3))
Example #5
0
 def check_random_complex(self):
     n = 20
     a = random([n, n]) + 1j * random([n, n])
     for i in range(n):
         a[i, i] = 20 * (0.1 + a[i, i])
     for i in range(2):
         b = random([n, 3])
         x = solve(a, b)
         assert_array_almost_equal(numpy.dot(a, x), b)
Example #6
0
def test_rank_2():
    '''testcase rank_2'''

    vec = numpy.array([14., 14., 20.])
    mat = numpy.array([[1., 2., 3.], [1., 2., 3.], [2., 3., 4.]])
    _ = numpy.array((1., 2., 3.))
    _, rank = solve(mat, vec, RealField)
#    assert all(sol == sol2)
    assert rank == 2
Example #7
0
    def check_lu(self):
        a = random((10,10))
        b = random((10,))

        x1 = solve(a,b)

        lu_a = lu_factor(a)
        x2 = lu_solve(lu_a,b)

        assert_array_equal(x1,x2)
Example #8
0
def test_floating2():
    '''testcase 2'''
    mat = numpy.array([[3., 0., 0.], [0., 6., 0.], [0., 8., 0]])
    vec = numpy.array([3., 6., 8])

    sol = numpy.array([1., 1., 0.])
    _, rank = solve(mat, vec, RealField)

    assert all(sol == [1., 1., 0.])
    assert rank == 2
Example #9
0
 def check_nils_20Feb04(self):
     n = 2
     A = random([n, n]) + random([n, n]) * 1j
     X = zeros((n, n), "D")
     Ainv = inv(A)
     R = identity(n) + identity(n) * 0j
     for i in arange(0, n):
         r = R[:, i]
         X[:, i] = solve(A, r)
     assert_array_almost_equal(X, Ainv)
Example #10
0
def interp2d(x, y, data):

    class point(list):
        def __init__(self, *args):
	    list.__init__(self, args)
    pt0 = point(x, y)

    # check that the ref point is inside the data points
    xs, ys, fs = data.T
    if not(min(xs)<=x<=max(xs)) or not(min(ys)<=y<=max(ys)):
        raise Exception('Extrapolation is not allowed.')
    
    def dist(pt0, pt1):
        # compute the absolute distance
        return sqrt(sum([ (a-b)**2 for a, b in zip(pt0, pt1) ]))
    # generate a list of distance between the ref point and each data points
    dist0 = [ dist(point(x, y), pt0) for x, y, f in data ]
    
    if min(dist0)==0.0:
        indx = dist0.index(0.0)
	return data[indx][-1]

    A = array([])
    B = array([])
    for i in xrange(len(dist0)):
        # find the index of the nearest point
        indx = dist0.index(min(dist0))
	# replace the nearest point by infinite
        dist0[indx] = float('inf')
        x, y, f = data[indx]
	# build the system a*x+b*x+c = f -> linear interpolation
        A.append([x, y, 1.])
        B.append([f])
	# when the determinant is not null, the system can be solved
	det_A = det(A.T.dot(A))
	if det_A<>0:
	    break
    if det_A==0:
	raise Exception('The linear interpolation cannot be done.')

    # A.T.dot(A) gives a square matrix, independantly of the number of selected points 
    X = solve(A.T.dot(A), A.T.dot(B))
    a, b, c, = X.T[0]
    
    # check that the system give accurate result
    err = 0.0; ref = 0.0
    for [x, y, dummy], f in zip(A, B.T[0]):
        err += (a*x+b*y+c - f)**2
	ref += f*f
    err = sqrt(err/ref)
    if err>1e-6:
        Exception('The linear interpolation is not accurate.')
	return None
    
    return a*pt0[0]+b*pt0[1]+c
Example #11
0
 def check_random_sym(self):
     n = 20
     a = random([n, n])
     for i in range(n):
         a[i, i] = abs(20 * (0.1 + a[i, i]))
         for j in range(i):
             a[i, j] = a[j, i]
     for i in range(4):
         b = random([n])
         x = solve(a, b, sym_pos=1)
         assert_array_almost_equal(numpy.dot(a, x), b)
Example #12
0
def system_solve(fs,fc_list,bw_list,gdb_list,max_gdb=6):
    # return the gain coefficients that will better represent the
    # system that the user input
    # build a row matrix with coeffcients for a representative
    F = [ system_coeff(fs,f,bw,fc_list) for f,bw in zip(fc_list,bw_list) ]
    
    G0 = linalg.solve(F,gdb_list)

    G0 = [ min(max_gdb,max(-max_gdb,g)) for g in G0 ]
    
    return G0
Example #13
0
def system_solve(fs, fc_list, bw_list, gdb_list, max_gdb=6):
    # return the gain coefficients that will better represent the
    # system that the user input
    # build a row matrix with coeffcients for a representative
    F = [system_coeff(fs, f, bw, fc_list) for f, bw in zip(fc_list, bw_list)]

    G0 = linalg.solve(F, gdb_list)

    G0 = [min(max_gdb, max(-max_gdb, g)) for g in G0]

    return G0
Example #14
0
 def check_random_sym_complex(self):
     n = 20
     a = random([n, n])
     # a  = a + 1j*random([n,n]) # XXX: with this the accuracy will be very low
     for i in range(n):
         a[i, i] = abs(20 * (0.1 + a[i, i]))
         for j in range(i):
             a[i, j] = numpy.conjugate(a[j, i])
     b = random([n]) + 2j * random([n])
     for i in range(2):
         x = solve(a, b, sym_pos=1)
         assert_array_almost_equal(numpy.dot(a, x), b)
Example #15
0
def test_gf8_matrix():
    '''testcase GF8'''
    import algebra
    field = algebra.get_field_two(3)

    mat = numpy.array([[3, 2], [1, 2]])
    vec = numpy.array([3, 2])
    sol = numpy.array([5, 6])

    sol2, rank = solve(mat, vec, field=field)
    for i, val in enumerate(sol2):
        assert sol[i] == val
    assert rank == 2
Example #16
0
def test_floating0():
    '''testcase floating 0'''
    mat = numpy.array([[3., 3., 3.], [3., 4., 5.], [1., 5., 6.]])
    # X = numpy.array([1, 2, 3])
    vec = numpy.array([18., 26., 29.])

    sol = numpy.array([1., 2., 3.])
    sol2, rank = solve(mat, vec, field=RealField)
    #sol2, rank = solve(mat, vec, field=RealField)
    
    for i, val in enumerate(sol2):
        assert sol[i] - val < 1e-14
    assert rank == 3
Example #17
0
def Spline(curve1, curve2, n=100):
    n = int(n)
    if isinstance(curve1, Segment) and isinstance(curve2, Segment): 
        x0, y0 = curve1[1].x, curve1[1].y
        x1, y1 = curve2[0].x, curve2[0].y
        slope0 = (curve1[1].y-curve1[0].y)/(curve1[1].x-curve1[0].x)
        slope1 = (curve2[1].y-curve2[0].y)/(curve2[1].x-curve2[0].x)
        A = array([[x0**3, x0**2, x0, 1.0],
                   [x1**3, x1**2, x1, 1.0],
                   [3.0*x0**2, 2.0*x0, 1.0, 0.0],
                   [3.0*x1**2, 2.0*x1, 1.0, 0.0]])
        B = array([y0, y1, slope0, slope1])
        X = solve(A, B)
        curve3 = []
        for x in linspace(x0, x1, n):
            curve3.append( Point(x, polyval(X, x)) )
        return Path(*curve3)
  def __init__(self, x, y):
      self.x = x
      self.y = y
 
      self.xscale = 1.0/(x[-1]-x[0]), -1.0/(x[-1]-x[0])*x[0]
      self.yscale = 1.0/(y[-1]-y[0]), -1.0/(y[-1]-y[0])*y[0]
  
      x = [xi*self.xscale[0] + self.xscale[1] for xi in x]
      y = [yi*self.yscale[0] + self.yscale[1] for yi in y]
      dim = (len(self.x)-1)*3
      a = zeros((dim,dim))
      b = zeros((dim,1))
      
      j = 0
      for i in xrange(len(x)-1):
          x0, y0 = x[i], y[i]
          a[j][i*3] = x0**2
          a[j][i*3+1] = x0
          a[j][i*3+2] = 1.0
          j = j+1
          
          x1, y1 = x[i+1], y[i+1]
          a[j][i*3] = x1**2
          a[j][i*3+1] = x1
          a[j][i*3+2] = 1.0
          j = j+1
          
      for i in xrange(1, len(x)-1, 1):
          x1, y1 = x[i], y[i]
          a[j][(i-1)*3] = 2.0*x1
          a[j][(i-1)*3+1] = 1.0
          a[j][i*3] = -2.0*x1
          a[j][i*3+1] = -1.0
          j = j+1
          
      a[j][0] = 1.0
      a[j][3] = -1.0
      
      j=0
      for i in xrange(len(x)-1):
          b[j][0] = y[i]
          j = j+1
          b[j][0] = y[i+1]
          j = j+1
      
      self.p = [x[0] for x in solve(a, b)]
    def __call__(self, point):
        for c, (min_r, max_r) in zip(point, self.ranges):
	    if not(min_r<=c<=max_r):
	        return float('nan')
	
        # generate a list of normalized distance between the ref point and each data points
        distance = [ (sum((a-b)**2/(a*a+b*b) for a, b in zip(pt, point) if a<>b), indx) for indx, pt in enumerate(self.points) ]
	# sort  the distance
	distance.sort()
        
        dist, indx = distance[0]
        if dist==0.0:
	    return self.values[indx]
	
        # initialise
        # build the system a*x+b*y+c*z...+k = f -> linear interpolation
        A = array([])
        B = array([])

        # 1st point
        dist, indx = distance[0]
        A.append( list(self.points[indx]) + [1.0] )
        B.append([self.values[indx]])

        for i in xrange(self.m):
	    # ith point
            for dist, indx in distance[1:]:
	        if not(self.points[indx][i] in A.T[i]):
                    A.append( list(self.points[indx]) + [1.0] )
                    B.append([self.values[indx]])
	            break

        X = solve(A, B)
        r = 0.0
        for i in xrange(self.m):
            r += X[i][0]*point[i]
	r += X[-1][0]
	return r
Example #20
0
 def check_simple_complex(self):
     a = array([[5, 2], [2j, 4]], "D")
     for b in [[1j, 0], [[1j, 1j], [0, 2]], [1, 0j], array([1, 0], "D")]:
         x = solve(a, b)
         assert_array_almost_equal(numpy.dot(a, x), b)
Example #21
0
def interp3d(x, y, z, data):

    class point(list):
        def __init__(self, *args):
	    list.__init__(self, args)
    pt0 = point(x, y, z)

    # check that the ref point is inside the data points
    xs, ys, zs, fs = data.T
    if not(min(xs)<=x<=max(xs)) or not(min(ys)<=y<=max(ys)) or not(min(zs)<=z<=max(zs)):
        raise Exception('Extrapolation is not allowed.')
    
    def dist(pt0, pt1):
        # compute the absolute distance
	try:
            return sqrt(sum([ (2*(a-b)/(a+b))**2 for a, b in zip(pt0, pt1)]))
	except:
            return sqrt(sum([ (a-b)**2 for a, b in zip(pt0, pt1) ]))
    # generate a list of distance between the ref point and each data points
    dist0 = [ (i, dist(point(x, y, z), pt0)) for i, (x, y, z, f) in enumerate(data) ]
    # sort
    dist0 = sorted(dist0, key=lambda x : x[1])
    
    if dist0[1]==0.0:
	return data[dist0[0]][-1]
	
    # initialise
    A = array([])
    B = array([])

    # first point
    x, y, z, f = data[dist0[0][0]]
    # build the system a*x+b*y+c*z+d = f -> linear interpolation
    A.append([x, y, z, 1.])
    B.append([f])
    
    # second point
    for k, v in dist0:
        x, y, z, f = data[k]
	if not(x in A.T[0]):
            A.append([x, y, z, 1.])
            B.append([f])
	    break
	    
    # third point
    for k, v in dist0:
        x, y, z, f = data[k]
	if not(y in A.T[1]):
            A.append([x, y, z, 1.])
            B.append([f])
	    break
	    
    # fourth point
    for k, v in dist0:
        x, y, z, f = data[k]
	if not(z in A.T[2]):
            A.append([x, y, z, 1.])
            B.append([f])
	    break
	    
    X = solve(A, B)
    a, b, c, d, = X.T[0]
    
    # check that the system give accurate result
    err = 0.0; ref = 0.0
    for [x, y, z, dummy], f in zip(A, B.T[0]):
        err += (a*x+b*y+c*z+d - f)**2
	ref += f*f
    if ref<>0:
        err = sqrt(err/ref)
    else:
        err = sqrt(err)
    if err>1e-6:
        Exception('The linear interpolation is not accurate.')
    
    return a*pt0[0]+b*pt0[1]+c*pt0[2]+d
Example #22
0
 def check_simple(self):
     a = [[1, 20], [-30, 4]]
     for b in ([[1, 0], [0, 1]], [1, 0], [[2, 1], [-30, 4]]):
         x = solve(a, b)
         assert_array_almost_equal(numpy.dot(a, x), b)
Example #23
0
 def check_simple_sym(self):
     a = [[2, 3], [3, 5]]
     for lower in [0, 1]:
         for b in ([[1, 0], [0, 1]], [1, 0]):
             x = solve(a, b, sym_pos=1, lower=lower)
             assert_array_almost_equal(numpy.dot(a, x), b)
Example #24
0
    def next(self):

	isJnull = self.checkJacobian()
	for i, f in enumerate(self.f):
	    if f == float('nan'):
	        raise LevMarError('The point %d is a Nan. The optimizer has been stopped.'%i)
	    
    
        # stopping criteria
        if norm(self.g.T[0])<self.gtol:
            raise StopIteration('Magnitude of gradient smaller than the \'gtol\' tolerance.')
        # increment iter
        self.iter += 1
        if self.iter>self.maxiter:
            raise StopIteration('Number of iterations exceeded \'maxiter\' or number of function evaluations exceeded \'maxfev\'.')
     
        
        # save previous state
        self.X0, self.A0, self.g0, self.f0 = self.X.copy(), self.A.copy(), self.g.copy(), self.f.copy(), 
	
        # compute dX
        I = identity(len(self.A))
        self.dX = array(solve(self.A + self.mu, self.g.T[0], verbose=False))
	
        # stopping criteria
        #if norm(self.dX)<self.xtol*(norm(self.X)+self.xtol):
        #    raise StopIteration()
	if not(False in [a<b for a, b in zip(abs(self.dX), self.xtol*(abs(self.X)+self.xtol))]):
            raise StopIteration('Change in x smaller than the \'xtol\' tolerance.')

        self.X = self.X + self.dX
        
        # compute f using the new X
        self.f = self.func(self.X)
        f = array([self.f]).T
        
        self.Fn = 0.5*f.T.dot(f)[0][0]
        
        dX = array([self.dX]).T
        self.dL = (0.5*(dX.T.dot(self.mu.dot(dX) + self.g)))[0][0]
	self.dF = self.F0-self.Fn
	
	if len(self.bounds):
	    isStepAcceptable = not(False in [min(bound)<=x<=max(bound) for x, bound in zip(self.X, self.bounds)])
	else:
	    isStepAcceptable = True
        
        # if step acceptable
        if ((self.dF>0 and self.dL>0) or (self.dF<0 and self.dL<0)) and isStepAcceptable:
            # compute jacobian, A and g
            self.J = self.Dfun(self.X)
            self.A = self.J.T.dot(self.J)
            self.g = -self.J.T.dot(f)

            # damp mu and update F0 parameter
            self.mu = self.mu*max(0.333333333, (1.0-(2.0*(self.dF/self.dL)-1.0)**3)/2.0)
            self.nu = self.damping[1]
            self.F0 = self.Fn
         
        else:
            # restore
            self.X, self.A, self.g, self.f = self.X0.copy(), self.A0.copy(), self.g0.copy(), self.f0.copy(), 
            # damp mu
            self.mu = self.mu*self.nu
            self.nu = 2.0*self.nu
                
        # save and return X and residual
        residual = norm(self.f)
        self.append((self.iter, self.X, residual))
        return self.iter, self.X, residual
Example #25
0
 def check_simple_sym_complex(self):
     a = [[5, 2], [2, 4]]
     for b in [[1j, 0], [[1j, 1j], [0, 2]]]:
         x = solve(a, b, sym_pos=1)
         assert_array_almost_equal(numpy.dot(a, x), b)
Example #26
0
import numpy
import math
import linalg
x = numpy.random.randint(0, 100, 10)
sum = 0
for i in x:
    sum += i
x_sr = sum / len(x)
sig = math.sqrt((sum * (x - x_sr)**2) / len(x))
print('sum = ', sum)
print('x_sr = ', x_sr)
print('sig = ', sig)
#сигма = корень((сумма (x - x_среднее)^2) / длина_массива)

a = '3 * x0 + x1 = 9'
b = 'x0 + 2 * x1 = 8'
print(linalg.solve(a, b))