Exemplo n.º 1
0
 def get_position():  # type: () -> PositionType
     T = h5_dict['State Vectors Times']  # in seconds relative to ref time
     T += ref_time_offset
     Pos = h5_dict['ECEF Satellite Position']
     Vel = h5_dict['ECEF Satellite Velocity']  # for cross validation
     # Let's perform polynomial fitting for the position with cross validation for overfitting checks
     deg = 1
     prev_vel_error = numpy.inf
     P_x, P_y, P_z = None, None, None
     while deg < min(6, Pos.shape[0]):
         # fit position
         P_x = polynomial.polyfit(T, Pos[:, 0], deg=deg)
         P_y = polynomial.polyfit(T, Pos[:, 1], deg=deg)
         P_z = polynomial.polyfit(T, Pos[:, 2], deg=deg)
         # extract estimated velocities
         Vel_est = numpy.stack(
             (polynomial.polyval(T, polynomial.polyder(P_x)),
              polynomial.polyval(T, polynomial.polyder(P_y)),
              polynomial.polyval(T, polynomial.polyder(P_z))), axis=-1)
         # check our velocity error
         vel_err = Vel_est - Vel
         cur_vel_error = numpy.sum((vel_err*vel_err))
         deg += 1
         # stop if the error is not smaller than at the previous step
         if cur_vel_error >= prev_vel_error:
             break
     return PositionType(ARPPoly=XYZPolyType(X=P_x, Y=P_y, Z=P_z))
Exemplo n.º 2
0
def make_Zernike_grads(mask, roi = None, max_order = 100, return_grids = False, return_basis = False, yx_bounds = None, test = False):
    if return_grids :
        basis, basis_grid, y, x = make_Zernike_basis(mask, roi, max_order, return_grids, yx_bounds, test)
    else :
        basis = make_Zernike_basis(mask, roi, max_order, return_grids, yx_bounds, test)

    # calculate the x and y gradients
    from numpy.polynomial import polynomial as P
    
    # just a list of [(grad_ss, grad_fs), ...] where the grads are in a polynomial basis
    grads = [ (P.polyder(b, axis=0), P.polyder(b, axis=1)) for b in basis ]

    if return_grids :
        # just a list of [(grad_ss, grad_fs), ...] where the grads are evaluated on a y, x grid
        grad_grids = [(P.polygrid2d(y, x, g[0]), P.polygrid2d(y, x, g[1])) for g in grads]

        if return_basis :
            return grads, grad_grids, basis, basis_grid
        else :
            return grads, grad_grids
    else :
        if return_basis :
            return grads, basis
        else :
            return grads
Exemplo n.º 3
0
 def acceleration_at(self, t):
     vel_coef_x = poly.polyder(self.coef_x)
     vel_coef_y = poly.polyder(self.coef_y)
     acc_coef_x = poly.polyder(vel_coef_x)
     acc_coef_y = poly.polyder(vel_coef_y)
     acc_x = poly.polyval(t, acc_coef_x)
     acc_y = poly.polyval(t, acc_coef_y)
     return (acc_x, acc_y)
 def constrnp(pars):
     if orderp > 0:
         return (-1) * Arange**(-ordern - 1) * polyval(
             Arange, polyder(pars[1:ordern + 1], m=1)) + polyval(
                 Arange, polyder(pars[ordern + 1:], m=1))
     else:
         return (-1) * Arange**(-ordern - 1) * polyval(
             Arange, polyder(pars[1:ordern + 1], m=1))
Exemplo n.º 5
0
def get_der_rational(num, den):
    dnum = poly.polyder(num)
    dden = poly.polyder(den)
    dnum_den = poly.polymul(dnum, den)
    dden_num = poly.polymul(num, dden)
    num_new = poly.polysub(dnum_den, dden_num)
    den_new = poly.polymul(den, den)
    return (num_new, den_new)
Exemplo n.º 6
0
    def test_polyder_axis(self):
        # check that axis keyword works
        c2d = np.random.random((3, 4))

        tgt = np.vstack([poly.polyder(c) for c in c2d.T]).T
        res = poly.polyder(c2d, axis=0)
        assert_almost_equal(res, tgt)

        tgt = np.vstack([poly.polyder(c) for c in c2d])
        res = poly.polyder(c2d, axis=1)
        assert_almost_equal(res, tgt)
Exemplo n.º 7
0
    def test_polyder_axis(self):
        # check that axis keyword works
        c2d = np.random.random((3, 4))

        tgt = np.vstack([poly.polyder(c) for c in c2d.T]).T
        res = poly.polyder(c2d, axis=0)
        assert_almost_equal(res, tgt)

        tgt = np.vstack([poly.polyder(c) for c in c2d])
        res = poly.polyder(c2d, axis=1)
        assert_almost_equal(res, tgt)
Exemplo n.º 8
0
def getXs(cxy, x, y):
    f = polyval2d(x, y, cxy)
    fx = polyval2d(x, y, polyder(cxy, axis=0))
    fy = polyval2d(x, y, polyder(cxy, axis=1))
    fxx = polyval2d(x, y, polyder(polyder(cxy, axis=0), axis=0))
    fxy = polyval2d(x, y, polyder(polyder(cxy, axis=0), axis=1))
    fyy = polyval2d(x, y, polyder(polyder(cxy, axis=1), axis=1))
    return f, fx, fy, fxx, fxy, fyy
Exemplo n.º 9
0
    def _set_sicd(self, the_sicd):
        # type : (SICDType) -> None
        if the_sicd is None:
            self._sicd = None
            return

        if not isinstance(the_sicd, SICDType):
            raise TypeError(
                'the_sicd must be an insatnce of SICDType, got type {}'.format(
                    type(the_sicd)))

        self._sicd = the_sicd
        row_delta_kcoa_poly, self._row_fft_sgn = _get_deskew_params(
            the_sicd, 0)
        col_delta_kcoa_poly, self._col_fft_sgn = _get_deskew_params(
            the_sicd, 1)
        if self.dimension == 0:
            self._delta_kcoa_poly_axis = row_delta_kcoa_poly
            delta_kcoa_poly_int = polynomial.polyint(row_delta_kcoa_poly,
                                                     axis=0)
            self._delta_kcoa_poly_off_axis = _add_poly(
                -polynomial.polyder(delta_kcoa_poly_int, axis=1),
                col_delta_kcoa_poly)
        else:
            self._delta_kcoa_poly_axis = col_delta_kcoa_poly
            delta_kcoa_poly_int = polynomial.polyint(col_delta_kcoa_poly,
                                                     axis=1)
            self._delta_kcoa_poly_off_axis = _add_poly(
                -polynomial.polyder(delta_kcoa_poly_int, axis=0),
                row_delta_kcoa_poly)

        self._row_shift = the_sicd.ImageData.SCPPixel.Row - the_sicd.ImageData.FirstRow
        self._row_mult = the_sicd.Grid.Row.SS
        self._col_shift = the_sicd.ImageData.SCPPixel.Col - the_sicd.ImageData.FirstCol
        self._col_mult = the_sicd.Grid.Col.SS
        self._row_pad = max(
            1., 1. / (the_sicd.Grid.Row.SS * the_sicd.Grid.Row.ImpRespBW))
        self._row_weight = the_sicd.Grid.Row.WgtFunct.copy(
        ) if the_sicd.Grid.Row.WgtFunct is not None else None
        self._col_pad = max(
            1., 1. / (the_sicd.Grid.Col.SS * the_sicd.Grid.Col.ImpRespBW))
        self._col_weight = the_sicd.Grid.Col.WgtFunct.copy(
        ) if the_sicd.Grid.Col.WgtFunct is not None else None
        self._is_normalized = is_normalized(the_sicd, self.dimension)
        self._is_not_skewed_row = is_not_skewed(the_sicd, 0)
        self._is_not_skewed_col = is_not_skewed(the_sicd, 1)
        self._is_uniform_weight_row = is_uniform_weight(the_sicd, 0)
        self._is_uniform_weight_col = is_uniform_weight(the_sicd, 1)
Exemplo n.º 10
0
    def grad(self, point):
        '''
        Evaluates the gradient of the polynomial at the given point.

        Parameters
        ----------
        point : array-like
            the point at which to evaluate the polynomial

        Returns
        -------
        out : ndarray
            Gradient of the polynomial at the given point.
        '''
        super(MultiPower, self).__call__(point)

        out = np.empty(self.dim, dtype="complex_")
        if self.jac is None:
            jac = list()
            for i in range(self.dim):
                jac.append(poly.polyder(self.coeff, axis=i))
            self.jac = jac
        spot = 0
        for i in self.jac:
            out[spot] = polyvalnd(point, i)
            spot += 1

        return out
Exemplo n.º 11
0
def deskewmem(input_data,
              DeltaKCOAPoly,
              dim0_coords_m,
              dim1_coords_m,
              dim,
              fft_sgn=-1):
    """Performs deskew (centering of the spectrum on zero frequency) on a complex dataset.

    INPUTS:
       input_data:  Complex FFT Data
       DeltaKCOAPoly:  Polynomial that describes center of frequency support of data.
       dim0_coords_m:  Coordinate of each "row" in dimension 0
       dim1_coords_m:  Coordinate of each "column" in dimension 1
       dim:  Dimension over which to perform deskew
       fft_sgn:  FFT sign required to transform data to spatial frequency domain
    OUTPUTS:
       output_data:  Deskewed data
       new_DeltaKCOAPoly:  Frequency support shift in the non-deskew dimension
          caused by the deskew.
    """

    # Integrate DeltaKCOA polynomial (in meters) to form new polynomial DeltaKCOAPoly_int
    DeltaKCOAPoly_int = polynomial.polyint(DeltaKCOAPoly, axis=dim)
    # New DeltaKCOAPoly in other dimension will be negative of the derivative of
    # DeltaKCOAPoly_int in other dimension (assuming it was zero before).
    new_DeltaKCOAPoly = -polynomial.polyder(DeltaKCOAPoly_int, axis=dim - 1)
    # Apply phase adjustment from polynomial
    [dim1_coords_m_2d, dim0_coords_m_2d] = np.meshgrid(dim1_coords_m,
                                                       dim0_coords_m)
    output_data = np.multiply(
        input_data,
        np.exp(1j * fft_sgn * 2 * np.pi * polynomial.polyval2d(
            dim0_coords_m_2d, dim1_coords_m_2d, DeltaKCOAPoly_int)))
    return output_data, new_DeltaKCOAPoly
Exemplo n.º 12
0
    def __call__(self, i, x, p = 0):
        """
        k is degree is 0+
        0 <= i < len(t)
        t[0] <= x <= t[-1]
        p < k
        """
        t = self._t
        jj = np.where(np.logical_and(x >= t[:-1], x < t[1:]))[0]
        if len(jj) == 0:
            if x == t[-1]:
                j = self._n + self._k - 2
            else:
                return 0
        else:
            j = jj[0]

        if self._derivatives:
            k = self._k - p
            a = self._a[i, j, k, :k+1]
        else:
            a = self._a[i, j, -1]
            if p > 0:
                a = polyder(a, p)

        return polyval(x, a)
Exemplo n.º 13
0
def drawCriticalLines2():

    eps3 = 1e-1

    derivative = npp.polyder(f_as_poly)
    criticalPoints = npp.polyroots(derivative)

    #phase = (lambda v: np.angle(npp.polyval(v[0]+1j*v[1],f_as_poly)))
    phase = np.angle(values)
    #hessian = nd.Hessian(phase)

    for z0 in criticalPoints:

        z1 = z0 + eps3
        z2 = z0 + eps3
        z3 = z0 - eps3
        z4 = z0 - eps3

        draw_contour_from(z1, eps3)
        draw_contour_from(z2, -eps3)
        draw_contour_from(z3, eps3)
        draw_contour_from(z4, -eps3)

        (x0, y0) = complex_to_pixel(z0)
        pg.draw.circle(window, (255, 0, 0), (x0, y0), circle_size, 0)
        pg.draw.circle(window, (0, 0, 0), (x0, y0), circle_size, 3)
Exemplo n.º 14
0
    def poly_lagrange(i, alldata: pd.DataFrame):
        if i < 3 or i > len(alldata):
            logging.warning('"outside fit interval"')
        data = alldata.iloc[i - 3:i + 5, :]
        mid = data.iloc[3, :]
        scale = data.iloc[7, :] - data.iloc[0, :]
        scaled_data = (data - mid) / scale

        polys_svid = {}
        vel_svid = {}
        time_col = scaled_data.iloc[:, 0]
        for dfcol in scaled_data.columns:
            if dfcol != 'UTC Time':
                coefs = (P.Polynomial(
                    lagrange(np.array(time_col),
                             np.array(scaled_data[dfcol]))).coef)[::-1]
                polys_svid[dfcol] = coefs
                vel_svid[dfcol] = P.polyder(coefs)

        return {
            i: {
                'mid': mid,
                'scale': scale,
                'polys_svid': polys_svid,
                'vel_svid': vel_svid
            }
        }
Exemplo n.º 15
0
    def generate(self):
        self.compute_polynomials(self.tridiag_matrices[0])
        self.frozen_spectral_w = [self.spectral_weight(self.eigen_values[0][i]) for i in range(self.n_traj)]

        for sample in range(1, self.n_samples+1):
            self.compute_polynomials(self.tridiag_matrices[sample-1])
            self.compute_brownians()

            d_A = 0
            for i in range(self.n_traj):
                lbda_i = self.eigen_values[sample-1][i]
                G_i = self.compute_G(lbda_i, self.tridiag_matrices[sample-1])

                eigen_values_list = [lbda for lbda in list(self.eigen_values[sample - 1]) if lbda != lbda_i]
                sum_term = sum([(1 / (lbda_i - lbda_k)) for lbda_k in eigen_values_list])

                d_A -= (self.brownians[sample][i] + self.dt*(-lbda_i/2 + sum_term))*(self.frozen_spectral_w[i]**2)*G_i
            #print(d_A)

            d_P = 0
            for i in range(0, self.dim):
                lbda_i = self.eigen_values[sample-1][i]
                for k in range(0, self.dim):
                    for l in range(0, self.dim):
                        add = P.polyval(lbda_i, self.p[k]) * P.polyval(lbda_i, P.polyder(self.p[l])) + P.polyval(lbda_i, P.polyder(self.p[k])) * P.polyval(lbda_i, self.p[l])
                        d_P -= 0.5 * self.frozen_spectral_w[i]**2 * add * self.compute_G_kl(k, l, self.tridiag_matrices[sample-1], self.eigen_values[sample-1]) * self.dt

            draw_A = self.tridiag_matrices[sample-1] + d_A + d_P
            #print(d_P)
            #print(draw_A)
            self.tridiag_matrices.append(draw_A)
            self.eigen_values.append(sorted(np.linalg.eigvalsh(self.tridiag_matrices[sample]), reverse=True))
            print(eigen_values_list)
Exemplo n.º 16
0
def jointPieces(Dt, Nsamples, polys, der_list):
    # Number of derivates to evaluate
    numDer = len(der_list)

    # Number of pieces to join
    numPieces = len(Dt)

    # Time offsets
    toff = np.zeros(numPieces + 1)
    toff[1: numPieces + 1] = \
            np.matmul(np.tril(np.ones((numPieces, numPieces)), 0), np.array(Dt))

    # Matrix of time and output vector to represent the pieces
    t = np.zeros((numPieces, Nsamples))
    y = np.zeros((numPieces, Nsamples))

    # The overall time vector to include all the pieces
    T = np.zeros((numPieces * Nsamples))
    Y = np.zeros((numDer, numPieces * Nsamples))

    # Evaluation
    for i in range(len(Dt)):
        dt = Dt[i] / Nsamples
        t[i, :] = np.arange(0, Nsamples) * dt
        for j in range(numDer):
            # Evaluate the polynomial
            pder = pl.polyder(polys[i, :], der_list[j])
            y[i, :] = pl.polyval(t[i, :], pder)
            # Compose the single vectors
            Y[j, i * Nsamples:(i + 1) * Nsamples] = y[i, :]
            T[i * Nsamples:(i + 1) * Nsamples] = t[i, :] + toff[i]

    return (T, Y)
Exemplo n.º 17
0
def solve_polyfit(xarr, yarr, degree, weight, deriv=None):
    # Obtain solution using polyfit
    z = P.polyfit(xarr, yarr, deg=degree, w=weight)

    if deriv is not None:
        z = P.polyder(z, m=deriv)
    return z
    def _get_sensitivity_mean_coefficients(self, header_specifier: str, all_temperatures: List[List[float]],
                                           coefficients_list: Tuple[List[List[float]], List[List[float]]],
                                           indexes: List[int], headers: List[str], type_specifier: str, units: str):
        if len(all_temperatures[0]) < 3:
            return
        for header in headers:
            fbg_name = fbg_name_from_header(header)
            master_temperatures = _get_master_temperatures(all_temperatures)
            mean_column_name = "{} Mean {}".format(fbg_name, header_specifier)
            y_values = self.calibration_data_frame[mean_column_name][1:]
            mean_temperature_column_name = "Mean Temperature (K)"
            x_values = self.calibration_data_frame[mean_temperature_column_name][1:]

            coefficients = []
            for order in range(1, 4):
                coefficients = poly.polyfit(x_values, y_values, order)
                error = np.sum((poly.polyval(x_values, coefficients) - y_values)**2)
                if error <= 10**-6:
                    break
            derivative_coefficients = poly.polyder(coefficients)

            sensitivity_column_name = "{} {} Sensitivity {}".format(fbg_name, type_specifier, units)
            scalar = 1000 if type_specifier == "Wavelength" else 1
            results = poly.polyval(master_temperatures, derivative_coefficients)
            self.calibration_data_frame[sensitivity_column_name] = results
            self.calibration_data_frame[sensitivity_column_name] *= scalar
            coefficients_list[0].append(list(reversed(coefficients)))
            coefficients_list[1].append(list(reversed(derivative_coefficients)))
            self._add_deviation_index(sensitivity_column_name, indexes)
Exemplo n.º 19
0
def smoothing_poly_lnprior(poly, degree, xmin, xmax, gamma=1):
    """
    A smoothing prior that suppresses higher order derivatives of a polynomial,
    poly = a + b x + c x*x + ..., described by a vector of its coefficients,
    [a, b, c, ...].

    Functional form is:

    ln p(poly coeffs) =
      -gamma * integrate( (diff(poly(x), x, degree))^2, x, xmin, xmax)

    So it takes the `degree`th derivative of the polynomial, squares it,
    integrates that from xmin to xmax, and scales by -gamma.
    """
    # Take the `degree`th derivative of the polynomial.
    poly_diff = P.polyder(poly, m=degree)
    # Square the polynomial.
    poly_diff_sq = P.polypow(poly_diff, 2)
    # Take the indefinite integral of the polynomial.
    poly_int_indef = P.polyint(poly_diff_sq)
    # Evaluate the integral at xmin and xmax to get the definite integral.
    poly_int_def = (
        P.polyval(xmax, poly_int_indef) - P.polyval(xmin, poly_int_indef)
    )
    # Scale by -gamma to get the log prior
    lnp = -gamma * poly_int_def

    return lnp
Exemplo n.º 20
0
    def NewtonRaphson(self, L, initial_guess, max_iterations,
                      accuracy):  # NewtonRaphson function takes 5 arguments

        # L is the co-efficient list, e.g.,-
        # If the polynomial is x^2-9x+14, then-
        # L=[14,-9,1]
        # initial_guess is the starting value, e.g.-
        # initial_guess=8
        # max_iterations is the maximum allowed number of iterations
        # accuracy is the desired Accuracy

        self.co_eff = L
        self.initial_guess = initial_guess
        self.max_iterations = max_iterations
        self.accuracy = accuracy
        derivative = P.polyder(
            self.co_eff)  # calculating derivative of polynomial
        x = self.initial_guess  # variable to store initial guess
        count = 0  # variable to count iterations
        while (count < self.max_iterations):
            y = x - (P.polyval(x, self.co_eff) / P.polyval(x, derivative)
                     )  # calculating next value
            if (abs(P.polyval(y, self.co_eff)) <=
                    self.accuracy):  # terminal condition
                return (y)  # return value
            x = y  # preparing for next iteration
            count += 1
        return ("Iterations exceed limit")
Exemplo n.º 21
0
    def Lagrange(L,M):                                                               
        polylist=[]
        n=len(L)                                                           
        w=(-1*L[0],1)                                                      
        for i in range(1,n):
            w=P.polymul(w,(-1*L[i],1))                                    
        result=array([0.0 for i in range(len(w)-1)])                    
        derivative=P.polyder(w)                                             
        for i in range(n):
            polylist.append((P.polydiv(w,(-1*L[i],1))[0]*M[i])/P.polyval(L[i],derivative))
            result+=polylist[-1]   

        polynomial=""                                                  
        for i in range(len(result)-1,0,-1):                                 
            if(result[i]!=0):
                if(result[i]>0 and i!=(len(result)-1)):
                    polynomial+=" + "+str(result[i])+"x^"+str(i)+" "
                elif(result[i]>0 and i==(len(result)-1)):
                    polynomial+=str(result[i])+"x^"+str(i)+" "
                else:
                    polynomial+=" - "+str(-1*result[i])+"x^"+str(i)+" "
        if(result[0]!=0):
            polynomial+=" + "+str(result[0]) if result[0]>0 else " - "+str(-1*result[0])
        plot(L,M,polylist,result)
        return (polynomial)
Exemplo n.º 22
0
def poly_solve(poly, tau, line, terminate):
    # Derivative
    if poly.size > 3 and np.abs(poly[-1]) < np.finfo(float).eps:
        poly[-1] = 0.0
    der = p.polyder(poly)
    # Stationary Points
    stat_x = p.polyroots(der)
    stat_f = p.polyval(stat_x, poly)
    stat_x_feasible = stat_x[terminate.feasible(line, stat_x, stat_f)]
    stat_f_feasible = stat_f[terminate.feasible(line, stat_x, stat_f)]
    # Bounds Extrema
    bound_x = tau
    bound_f = p.polyval(bound_x, poly)
    bound_x_feasible = bound_x[terminate.feasible(line, bound_x, bound_f)]
    bound_f_feasible = bound_f[terminate.feasible(line, bound_x, bound_f)]
    # Termination Extrema
    term_x = terminate.extrema(line, poly)
    if term_x.size > 0:
        term_f = p.polyval(term_x, poly)
    else:
        term_f = np.array([])
    # Combine
    comb_x = np.concatenate((stat_x_feasible, bound_x_feasible, term_x))
    comb_f = np.concatenate((stat_f_feasible, bound_f_feasible, term_f))
    # Bounds Filter
    comb_final_x = comb_x[np.logical_and(bound_x[0] <= comb_x, comb_x <= bound_x[1])]
    comb_final_f = comb_f[np.logical_and(bound_x[0] <= comb_x, comb_x <= bound_x[1])]
    # Return Result
    if comb_final_x.size == 0:
        return None
    else:
        return comb_final_x[np.argmin(comb_final_f)]
Exemplo n.º 23
0
def smoothing_poly_lnprior(poly, degree, xmin, xmax, gamma=1):
    """
    A smoothing prior that suppresses higher order derivatives of a polynomial,
    poly = a + b x + c x*x + ..., described by a vector of its coefficients,
    [a, b, c, ...].

    Functional form is:

    ln p(poly coeffs) =
      -gamma * integrate( (diff(poly(x), x, degree))^2, x, xmin, xmax)

    So it takes the `degree`th derivative of the polynomial, squares it,
    integrates that from xmin to xmax, and scales by -gamma.
    """
    # Take the `degree`th derivative of the polynomial.
    poly_diff = P.polyder(poly, m=degree)
    # Square the polynomial.
    poly_diff_sq = P.polypow(poly_diff, 2)
    # Take the indefinite integral of the polynomial.
    poly_int_indef = P.polyint(poly_diff_sq)
    # Evaluate the integral at xmin and xmax to get the definite integral.
    poly_int_def = (P.polyval(xmax, poly_int_indef) -
                    P.polyval(xmin, poly_int_indef))
    # Scale by -gamma to get the log prior
    lnp = -gamma * poly_int_def

    return lnp
Exemplo n.º 24
0
def combine_quadrupole_plate(c, intfun, cP, intfunP):
    x_cder = polynomial.polyder(c, axis=0)
    x_cPder = polynomial.polyder(cP, axis=0)
    y_cder = polynomial.polyder(c, axis=1)
    y_cPder = polynomial.polyder(cP, axis=1)

    Ex = lambda x, y, z: (intfunP(z) * polynomial.polyval2d(x, y, x_cPder) +
                          intfun(z) * polynomial.polyval2d(x, y, x_cder)) / 100
    Ey = lambda x, y, z: (intfunP(z) * polynomial.polyval2d(x, y, y_cPder) +
                          intfun(z) * polynomial.polyval2d(x, y, y_cder)) / 100
    Ez = lambda x, y, z: (intfunP.derivative()(z) * polynomial.polyval2d(
        x, y, cP) + intfun.derivative()
                          (z) * polynomial.polyval2d(x, y, c)) / 100
    Emag = lambda x, y, z: np.sqrt(
        Ex(x, y, z)**2 + Ey(x, y, z)**2 + Ez(x, y, z)**2)
    return Ex, Ey, Ez, Emag
Exemplo n.º 25
0
def deskewmem(input_data, DeltaKCOAPoly, dim0_coords_m, dim1_coords_m, dim, fft_sgn=-1):
    """
    Performs deskew (centering of the spectrum on zero frequency) on a complex dataset.

    Parameters
    ----------
    input_data : numpy.ndarray
        Complex FFT Data
    DeltaKCOAPoly : numpy.ndarray
        Polynomial that describes center of frequency support of data.
    dim0_coords_m : numpy.ndarray
    dim1_coords_m : numpy.ndarray
    dim : int
    fft_sgn : int|float

    Returns
    -------
    Tuple[numpy.ndarray, numpy.ndarray]
        * `output_data` - Deskewed data
        * `new_DeltaKCOAPoly` - Frequency support shift in the non-deskew dimension caused by the deskew.
    """

    # Integrate DeltaKCOA polynomial (in meters) to form new polynomial DeltaKCOAPoly_int
    DeltaKCOAPoly_int = polynomial.polyint(DeltaKCOAPoly, axis=dim)
    # New DeltaKCOAPoly in other dimension will be negative of the derivative of
    # DeltaKCOAPoly_int in other dimension (assuming it was zero before).
    new_DeltaKCOAPoly = - polynomial.polyder(DeltaKCOAPoly_int, axis=dim-1)
    # Apply phase adjustment from polynomial
    dim1_coords_m_2d, dim0_coords_m_2d = np.meshgrid(dim1_coords_m, dim0_coords_m)
    output_data = np.multiply(input_data, np.exp(1j * fft_sgn * 2 * np.pi *
                                                 polynomial.polyval2d(
                                                     dim0_coords_m_2d,
                                                     dim1_coords_m_2d,
                                                     DeltaKCOAPoly_int)))
    return output_data, new_DeltaKCOAPoly
Exemplo n.º 26
0
def solve_leastsq(yarr, ycov, vander, vanderT, deriv=None):
    ycovinv = inv(ycov)
    prefactor = inv(np.dot(np.dot(vanderT, ycovinv), vander))
    postfactor = np.dot(np.dot(vanderT, ycovinv), yarr)
    z = np.dot(prefactor, postfactor)

    if deriv is not None:
        z = P.polyder(z, m=deriv)

    return z
    def deriv(self):
        """ compute first derivative

        Returns
        -------
        dPP : PseudoPolynomial
            d(PP)/dx represented as a PseudoPolynomial
        """
        dp = pol.polyder(self.p)
        dq = pol.polyder(self.q)


        p = pol.polysub(pol.polymul((1, 0, -1), dp),
                        pol.polymul((0, 2 * self.r), self.p))
        q = pol.polysub(pol.polymul((1, 0, -1), dq),
                        pol.polymul((0, 2 * self.r + 1), self.q))
        r = self.r - 1

        return PseudoPolynomial(p=remove_zeros(p), q=remove_zeros(q), r=r)
Exemplo n.º 28
0
def combine_quadrupole_plate_factor(c, intfun, cP, intfunP, factor):
    """
    Change the homogeneous field strenght by a factor
    """
    x_cder = polynomial.polyder(c, axis=0)
    x_cPder = polynomial.polyder(cP, axis=0)
    y_cder = polynomial.polyder(c, axis=1)
    y_cPder = polynomial.polyder(cP, axis=1)

    Ex = lambda x, y, z: (factor * (intfunP(z) * polynomial.polyval2d(
        x, y, x_cPder)) + intfun(z) * polynomial.polyval2d(x, y, x_cder)) / 100
    Ey = lambda x, y, z: (factor * (intfunP(z) * polynomial.polyval2d(
        x, y, y_cPder)) + intfun(z) * polynomial.polyval2d(x, y, y_cder)) / 100
    Ez = lambda x, y, z: (factor * (intfunP.derivative()(z) * polynomial.
                                    polyval2d(x, y, cP)) + intfun.derivative()
                          (z) * polynomial.polyval2d(x, y, c)) / 100
    Emag = lambda x, y, z: np.sqrt(
        Ex(x, y, z)**2 + Ey(x, y, z)**2 + Ez(x, y, z)**2)
    return Ex, Ey, Ez, Emag
Exemplo n.º 29
0
    def __init__(self,
                 z_values_range_params,
                 c_values_range_params,
                 dimension_params,
                 formula_params,
                 max_iterations=None):
        super().__init__(z_values_range_params, c_values_range_params,
                         dimension_params, formula_params, max_iterations)

        self._coefficient_array_deriv = polyder(
            self._formula_params.coefficient_array)
Exemplo n.º 30
0
def calculate_t5(x, wf):
    sample_i = np.indices(wf.shape)[-1]
    peakpos = np.argmax(wf, axis=1).astype(np.intp)
    t = np.zeros(wf.shape[0])
    for i, w in enumerate(wf):
        start = peakpos[i] - 3
        end = peakpos[i] + 3
        c = npp.polyfit(x[start:end], w[start:end], 2)
        dc = npp.polyder(c)
        t[i] = -dc[0] / dc[1]
    return t
Exemplo n.º 31
0
def newtReconstructHessian(freqs,locations, spectrum, numPts):
    """

    :param freqs:
    :param locations:
    :param spectrum:
    :param numPts:
    :return:
    """
    deriv=poly.polyder(spectrum,m=2,axis=0)
    return genericNewtVal(locations,deriv)
Exemplo n.º 32
0
def newtReconstructDerivative(freqs, locations, spectrum, numPts):
    """

    :param freqs:
    :param locations:
    :param spectrum:
    :param numPts:
    :return: derivative of iFFT of the spectrum as an array with shape (Npts, Ncomponent) or (Ncomponent,) if 1-d
    """
    deriv=poly.polyder(spectrum, axis=0)
    return genericNewtVal(locations, deriv)
Exemplo n.º 33
0
    def eval(self, t, der=np.array([0])):
        """
        Evaluate the piecewise polynomial

        Args:
            t vector of time instants
            der derivative to evaluate
        """

        # Check whether the evaluation is requested on a scalar or on an
        # iterable
        try:
            # Iterable: t is a vector
            t = np.array(t)
            _ = iter(t)
            nsamples = t.size
            if (t[0] < 0.0) or (t[nsamples - 1] > self.knots[-1]):
                print("PwPoly.eval(): Trying to evaluate outside " +
                      "the time support of the piecewise polynomial\n" +
                      "t_max = {}, t = {}".format(self.knots[-1], t[nsamples -
                                                                    1]))

            # Allocate the variable
            yout = np.zeros((nsamples), dtype=float)
            for (k, t_) in enumerate(t):
                i = self.find_piece(t_)
                # Evaluate the required polynomial derivative
                pder = pl.polyder(self.coeff_m[i, :], der)
                yout[k] = pl.polyval(t_ - self.knots[i], pder)
        except TypeError:
            # Non iterable: t is a single value
            if (t < 0.0) or (t > self.knots[-1]):
                print("PwPoly.eval(): Trying to evaluate outside " +
                      "the time support of the piecewise polynomial\n" +
                      "t_max = {}, t = {}".format(self.knots[-1], t))

            i = self.find_piece(t)
            pder = pl.polyder(self.coeff_m[i, :], der)
            yout = pl.polyval(t - self.knots[i], pder)

        return yout
def newton_zero(p, lo, hi, acc=1E-5):

    ylo = pol.polyval(lo, p)
    yhi = pol.polyval(hi, p)

    x0 = linzero(lo, hi, ylo, yhi)

    dp = pol.polyder(p)
    f = lambda x, p=p: pol.polyval(x, p)
    df = lambda x, dp=dp: pol.polyval(x, dp)

    return newton(f, x0, fprime=df)
Exemplo n.º 35
0
    def test_polyder(self) :
        # check exceptions
        assert_raises(ValueError, poly.polyder, [0], -1)

        # check that zeroth deriviative does nothing
        for i in range(5) :
            tgt = [1] + [0]*i
            res = poly.polyder(tgt, m=0)
            assert_equal(trim(res), trim(tgt))

        # check that derivation is the inverse of integration
        for i in range(5) :
            for j in range(2,5) :
                tgt = [1] + [0]*i
                res = poly.polyder(poly.polyint(tgt, m=j), m=j)
                assert_almost_equal(trim(res), trim(tgt))

        # check derivation with scaling
        for i in range(5) :
            for j in range(2,5) :
                tgt = [1] + [0]*i
                res = poly.polyder(poly.polyint(tgt, m=j, scl=2), m=j, scl=.5)
                assert_almost_equal(trim(res), trim(tgt))
        def Lagrange(self,A,B):

            from numpy import array
            from numpy.polynomial import polynomial as P
            n=len(A)
            w=(-1*A[0],1)
            for i in range(1,n):
                w=P.polymul(w,(-1*A[i],1))
            result=array([0.0 for i in range(len(w)-1)])
            derivative=P.polyder(w)
            for i in range(n):
                result+=(P.polydiv(w,(-1*A[i],1))[0]*B[i])/P.polyval(A[i],derivative)
            s=self.plot(list(result),A,B)
            return s
Exemplo n.º 37
0
def findderivative(x,y,derivorder=1):

    window_len=25
#    if spectrum.ndim != 1:
#        raise ValueError, "smooth only accepts 1 dimension arrays."
#
#    if spectrum.size < window_len:
#        raise ValueError, "Input vector needs to be bigger than window size."

        
    

    retval = numpy.ndarray(y.shape)
    for i in range(y.size):
        
        i_min = max(0,i-window_len/2)
        i_max = min( i+window_len/2-1, y.size)
        fit = pf(x[i_min:i_max+1],y[i_min:i_max+1],min(5,window_len))
        retval[i] = polyval(x[i],polyder(fit,derivorder),tensor=False) 
        
    return retval
    def Lagrange(self,U,V):                                                
       
        
       
        n=len(U)                                                           
        w=(-1*U[0],1)                                                      
        for i in range(1,n):
            w=P.polymul(w,(-1*U[i],1))                                    
        result=array([0.0 for i in range(len(w)-1)])                    
        derivative=P.polyder(w)                                             
        for i in range(n):
            result+=(P.polydiv(w,(-1*U[i],1))[0]*V[i])/P.polyval(U[i],derivative)


        temp=list(result);
        cofficient=temp
        l=len(cofficient);
        temp=[];
        for i in range(l-1):
            temp.append(str(cofficient[l-(i+1)])+'x^'+str(l-(i+1))+str('+'))
        temp.append(str(cofficient[0])+'x^'+str(0));
        str1=''.join(temp)
        return(str1)   
Exemplo n.º 39
0
    def __call__(self, i, x, p = 0):
        """
        k is degree is 0+
        0 <= i < len(t)
        t[0] <= x <= t[-1]
        p < k

        NumPy vectorized version.
        """
        _x = x
        if np.isscalar(x):
            x = (x,)
        if not isinstance(x, np.ndarray):
            x = np.array(x)

        w = np.zeros_like(x)
        t = self._t
        for j in range(self._k, self._n + self._k - 1):
            if j == self._n + self._k - 2:
                jj = np.where(np.logical_and(x >= t[j], x <= t[j + 1]))[0]
            else:
                jj = np.where(np.logical_and(x >= t[j], x < t[j + 1]))[0]

            if self._derivatives:
                k = self._k - p
                a = self._a[i, j, k]
            else:
                a = self._a[i, j, -1]
                if p > 0:
                    a = polyder(a, p)

            w[jj] = polyval(x[jj], a)

        if np.isscalar(_x):
            w = w[0]
        return w
import numpy as np
from numpy.polynomial import polynomial as P
import matplotlib.pyplot as plt

x = np.linspace(0, 8 * np.pi, 50)
y1 = np.cos(x)
y2 = np.sin(x - np.pi)

# Fitting data
coeff, stats = P.polyfit(x, y1, 20, full=True)
roots = np.real(P.polyroots(coeff))
fit = P.Polynomial(coeff)
yf1 = fit(x)

# Differentiating fitted polynomial
new_coeff = P.polyder(coeff)
dfit = P.Polynomial(new_coeff)
yf2 = dfit(x)

# Plotting results for illustration
fig = plt.figure(figsize=(8,6))
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax1.set_title('Data and fitting')
ax2.set_title('Differentiation')

ax1.set_xlim(0, x.max())
ax2.set_xlim(0, x.max())
ax1.set_ylim(-1.25, 1.25)
ax2.set_ylim(-1.25, 1.25)
Exemplo n.º 41
0
def polyder(cs, m=1, scl=1):
    from numpy.polynomial.polynomial import polyder
    return polyder(cs, m, scl)
Exemplo n.º 42
0
 def _derivative(c, m):
     return polynomial.polyder(c, m)
# -*- coding: utf-8 -*-
#Na ravnoj podlozi projekti je ispaljen pod kutem od 45 stupnjeva i pao 
#je 580 m dalje. Procijenite maksimalnu visinu koju je projektil postigao.

from numpy import *
from numpy.polynomial import polynomial as p
import pylab

M1=array([[1,0,0],[0,1,0],[1,580,580**2]])  
M2=array([0,1,0])

a=linalg.solve(M1,M2) #Funkcija koja daje interpolacijski polinom

# U slucaju da moramo provjeriti rezultate:
print p.polyval(0.,a)          #provjera p(0)=0
print p.polyval(0.,p.polyder(a))    #provjera p'(0)=1 :Za deriviranu vrijednost 
print p.polyval(580.,a)               #provjera p(580)=0

print 'Maksimalna visina je', p.polyval(580./2,a),'metara.'

#Crtanje funkcije:
x=linspace(0-0.5,580+0.5,100)
y=p.polyval(x,a)

pylab.plot(x,y)
pylab.show()
Exemplo n.º 44
0
def get_generalized_curvature(signal_in, total_points, deg):
  """
    Calculate curvature of n-dimensional trajectory, signal_in of shape (t, n)
    Use total_points adjacent points to fit a polynomial of degree deg
    Then calculate generalized curvature explicitly from the polynomial
    total_points: ~11
    deg: ~5
    Args:
      signal_in: (T, n)
      total_points: number of points to use, ~11
      deg: degree of polynomial, ~5
    Returns:
      k_t: curvatures
      e_t: frenet frames
  """

  def dt_id1(a, ap):
    """ 
      derivative of a/norm(a)
      input: a and da/dt, a and da/dt are n-dim vectors
      output: d/dt ( a/norm(a) )
    """
    return ap/np.linalg.norm(a) - np.dot(ap, a)*a/(np.dot(a, a)**(1.5))

  def dt_id2(a, b, ap, bp):
    """ 
      derivative of inner(a, b)*b
      input: a, b, da/dt, db/dt, each an n-dim vector
      output: d/dt ( inner(a, b)*b )
    """
    return (np.dot(ap, b) + np.dot(a, bp))*b + np.dot(a, b)*bp

  total_curvatures = np.min((signal_in.shape[1]-1, deg-1)) # have many curvatures to calculate
  k_t = np.zeros((signal_in.shape[0], total_curvatures)) # initialize curvatures, k
  e_t = np.zeros(signal_in.shape+(total_curvatures+1,)) # frenet frames, (t, n, curvatures+1)

  half = np.floor(total_points/2).astype(int)

  for t in range(half, signal_in.shape[0] - half): # end point correct?
    times = np.arange(t-half, t+half+1)
    times_local = times - t # will always be -half:half
    tmid = times_local[half] # tmid = 0
    p = P.polyfit(times_local, signal_in[times], deg)
    pp = [] # coefficients of polynomial (and its derivatives)
    pt = [] # polynomial (and its derivs) evaluated at time t
    for deriv in range(deg+2): # +2 because there are deg+1 nonzero derivatives of the polynomial, and +1 because of range()
      pp.append(P.polyder(p, deriv))
      pt.append(P.polyval(tmid, pp[-1]).T) # evaluate at 0

    e = [] # frenet basis, e1, e2, ... at time t
    ep = [] # derivatives, e1', e2', ...
    e_ = [] # unnormalized es
    e_p = [] # unnormalized (e')s

    k = [] # generalized curvature at time t

    # first axis of frenet frame
    e.append(pt[1]/np.linalg.norm(pt[1]))
    ep.append(dt_id1(pt[1], pt[2]))

    for dim in range(2, total_curvatures+2):
      # Start gram-schmidt orthogonalization on e:
      e_.append(pt[dim])
      e_p.append(pt[dim+1])
      for j in range(dim-1):
        e_[-1] = e_[-1] - np.dot(pt[dim], e[j])*e[j] # orthogonalize relative to every other e
        e_p[-1] = e_p[-1] - dt_id2(pt[dim], e[j], pt[dim+1], ep[j]) # derivative of e_
      e.append(e_[-1]/np.linalg.norm(e_[-1])) # normalize e_ to get e
      ep.append(dt_id1(e_[-1], e_p[-1])) # derivative of e

      k.append(np.dot(ep[-2], e[-1])/np.linalg.norm(pt[1]))
    k_t[t, :] = np.array(k)
    e_t[t, :, :] = np.array(e).T

  return k_t, e_t