예제 #1
0
    def test_legvander2d(self) :
        # also tests polyval2d for non-square coefficient array
        x1, x2, x3 = self.x
        c = np.random.random((2, 3))
        van = leg.legvander2d(x1, x2, [1, 2])
        tgt = leg.legval2d(x1, x2, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # check shape
        van = leg.legvander2d([x1], [x2], [1, 2])
        assert_(van.shape == (1, 5, 6))
예제 #2
0
    def test_legvander2d(self) :
        # also tests polyval2d for non-square coefficient array
        x1, x2, x3 = self.x
        c = np.random.random((2, 3))
        van = leg.legvander2d(x1, x2, [1, 2])
        tgt = leg.legval2d(x1, x2, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # check shape
        van = leg.legvander2d([x1], [x2], [1, 2])
        assert_(van.shape == (1, 5, 6))
예제 #3
0
파일: serial.py 프로젝트: yedivanseven/LPDE
 def __move(self, event: Event) -> bool:
     if event.id in self.__phi_ijn.columns:
         location = self.__map.in_from(event.location)
         phi_ijn = legvander2d(*location, self.__degree)[0]/self.__scale.vec
         self.__phi_ijn.loc[:, event.id] = phi_ijn
         return True
     return False
예제 #4
0
def leg2dfit(array, deg, rcond=None, full=False, w=None):
    '''

  2D Legendre Fitting.
  This routine has an issue with mapping back off of the [-1,1] interval. The issue lies in the normalization.

  '''

    order = int(deg) + 1
    flat_array = array.ravel()

    # find positions of nans
    goodpts = np.where(np.isnan(flat_array))

    if w is not None:
        if w.ndim != 2:
            raise TypeError("expected 2D array for w")
        if array.shape != w.shape:
            raise TypeError("expected array and w to have same shape")
        goodpts = np.where(~np.isnan(flat_array + w.ravel()))
        w = w.ravel()[goodpts]

    x, y = np.meshgrid(np.linspace(-1, 1, array.shape[0]),
                       np.linspace(-1, 1, array.shape[1]))
    x, y = x.ravel()[goodpts], y.ravel()[goodpts]

    # check arguments.
    if deg < 0:
        raise ValueError("expected deg >= 0")

    # set up the least squares matrices in transposed form
    lhs = legvander2d(x, y, [deg, deg]).T
    rhs = flat_array[goodpts].T

    if w is not None:
        lhs = lhs * w
        rhs = rhs * w

    # set rcond
    if rcond is None:
        rcond = len(x) * np.finfo(x.dtype).eps

    # scale the design matrix and solve the least squares equation
    if issubclass(lhs.dtype.type, np.complexfloating):
        scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))
    else:
        scl = np.sqrt(np.square(lhs).sum(1))
        print scl

    c, resids, rank, s = lstsq(lhs.T / scl, rhs.T, rcond)
    c = (c.T / scl).T

    # warn on rank reduction
    if rank != order**2. and not full:
        msg = "The fit may be poorly conditioned"
        warnings.warn(msg)
    if full:
        return c, [resids, rank, s, rcond]
    else:
        return c
예제 #5
0
def leg2dfit(array, deg, rcond=None, full=False, w=None):
  '''

  2D Legendre Fitting.
  This routine has an issue with mapping back off of the [-1,1] interval. The issue lies in the normalization.

  '''

  order = int(deg) + 1
  flat_array = array.ravel()

  # find positions of nans
  goodpts = np.where(np.isnan(flat_array))

  if w is not None:
    if w.ndim != 2:
        raise TypeError("expected 2D array for w")
    if array.shape != w.shape:
        raise TypeError("expected array and w to have same shape")
    goodpts = np.where(~np.isnan(flat_array+w.ravel()))
    w = w.ravel()[goodpts]

  x, y = np.meshgrid(np.linspace(-1,1,array.shape[0]), np.linspace(-1,1,array.shape[1]))
  x, y = x.ravel()[goodpts], y.ravel()[goodpts]

  # check arguments.
  if deg < 0 :
      raise ValueError("expected deg >= 0")

  # set up the least squares matrices in transposed form
  lhs = legvander2d(x, y, [deg,deg]).T
  rhs = flat_array[goodpts].T

  if w is not None:
    lhs = lhs * w
    rhs = rhs * w

  # set rcond
  if rcond is None :
    rcond = len(x)*np.finfo(x.dtype).eps

  # scale the design matrix and solve the least squares equation
  if issubclass(lhs.dtype.type, np.complexfloating):
      scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))
  else:
      scl = np.sqrt(np.square(lhs).sum(1))
      print scl

  c, resids, rank, s = lstsq(lhs.T/scl, rhs.T, rcond)
  c = (c.T/scl).T

  # warn on rank reduction
  if rank != order**2. and not full:
      msg = "The fit may be poorly conditioned"
      warnings.warn(msg)
  if full :
    return c, [resids, rank, s, rcond]
  else :
    return c
예제 #6
0
파일: FF.py 프로젝트: dianadianadiana/STScI
def norder2dlegendre(nx, ny):
    ''' 
        Purpose
        -------
        Create the 2D nx th and ny th order Legendre polynomial using
        numpy.polynomial.legendre.legvander2d(x, y, [nx, ny])
    '''
    x = Symbol('x')
    y = Symbol('y')
    funcarr = leg.legvander2d(x,y,[nx,ny])
    funcarr = funcarr[0]            # Because chebvander2d returns a 2d matrix
    funclist = funcarr.tolist()     # lambdify only takes in lists and not arrays
    f = lambdify((x, y), funclist)  # Note: lambdify looks at 1 as 1 and makes f[0] = 1 and not an array
    return funclist, f
예제 #7
0
def legForwardTransform(orders, locations, functionVals):
    if len(locations.shape)==1:
        return np.array(leg.legfit(locations, functionVals, orders[0]))
    else:
        if locations.shape[1]==2:
            V=leg.legvander2d(locations[:,0], locations[:,1], orders)
        elif locations.shape[1]==3:
            V=leg.legvander3d(locations[:,0],locations[:,1],locations[:,2], orders)
        elif locations.shape[1]==4:
            V=legvander4d(locations,orders)
        elif locations.shape[1]==5:
            V=legvander5d(locations,orders)
        else:
            raise NotImplementedError # there's a bad startup joke about this being good enough for the paper.
        ret, _, _, _=npl.lstsq(V, functionVals, rcond=None)
        return np.reshape(ret, (np.array(orders)+1).flatten())
예제 #8
0
 def run(self) -> None:
     while True:
         try:
             queue_item = self.__params.point_queue.get(timeout=TIMEOUT)
             points = self.__type_and_shape_checked(queue_item)
         except OSError:
             raise OSError('Point queue is already closed. Instantiate a'
                           ' new <Parallel> object to get going again!')
         except Empty:
             if self.__flag.stop.is_set():
                 break
         else:
             self.__phi_ijn = legvander2d(*points, self.__params.degree).T/\
                              self.__scale.vecT
             self.__minimize()
     self.__flag.done.set()
예제 #9
0
def culledLegForwardTransform(orders, locations, functionVals, threshold=None):
    # inspired by : A Simple Regularization of the Polynomial Interpolation For the Runge Phenomemenon
    if len(locations.shape)==1:
        vandermonde=leg.legvander(locations, orders[0])
    elif locations.shape[1]==2:
        vandermonde=leg.legvander2d(locations[:,0], locations[:,1], orders)
    elif locations.shape[1]==3:
        vandermonde=leg.legvander3d(locations[:,0],locations[:,1],locations[:,2], orders)
    elif locations.shape[1]==4:
        vandermonde=legvander4d(locations,orders)
    elif locations.shape[1]==5:
        vandermonde=legvander5d(locations,orders)
    else:
        raise NotImplementedError # there's a bad startup joke about this being good enough for the paper.

    # preconditioner = np.diag((0.94) ** (2* (np.arange(vandermonde.shape[0]))))
    # vandermonde=np.dot(preconditioner, vandermonde)

    U,S,Vh=np.linalg.svd(vandermonde)
    numTake=0
    filtS=S
    if threshold is None:
        Eps= np.finfo(functionVals.dtype).eps
        Neps = np.prod(cmn.numpyze(orders)) * Eps * S[0] #truncation due to ill-conditioning
        Nt = max(np.argmax(Vh, axis=0)) #"Automatic" determination of threshold due to Runge's phenomenon
        threshold=min(Neps, Nt)
    while numTake<=0:
        filter=S>threshold
        numTake=filter.sum()
        if numTake>0:
            filtU=U[:,:numTake]; filtS=S[:numTake]; filtVh=Vh[:numTake, :]
        else:
            if threshold>1e-13:
                threshold=threshold/2
                warnings.warn('cutting threshold for eigenvalues to '+str(threshold))
            else:
                warnings('seems all eigenvalues are zero (<1e-13), setting to zero and breaking')
                filtS=np.zeros_like(S)
    truncVander=np.dot(filtU,np.dot(np.diag(filtS),filtVh))

    ret, _, _, _=npl.lstsq(truncVander, functionVals, rcond=None)
    return np.reshape(ret, np.array(orders).flatten()+1)
예제 #10
0
def A(n):
    return legvander2d(x,th,[n,n])/(0.0573/164.102)
예제 #11
0
 def vandermonde(self, points):
     """"""
     vander = legvander2d(points[:, 0], points[:, 1],
                          [self.degree, self.degree])
     ulmask = CoeffPolynomial.upper_left_triangular_mask(self.degree)
     return vander[:, ulmask.ravel()]