Пример #1
0
def test_with_bounding_box():
    """
    Test the option to evaluate a model respecting
    its bunding_box.
    """
    p = models.Polynomial2D(2) & models.Polynomial2D(2)
    m = models.Mapping((0, 1, 0, 1)) | p
    with NumpyRNGContext(1234567):
        m.parameters = np.random.rand(12)

    m.bounding_box = ((3, 9), (1, 8))
    x, y = np.mgrid[:10, :10]
    a, b = m(x, y)
    aw, bw = m(x, y, with_bounding_box=True)
    ind = (~np.isnan(aw)).nonzero()
    assert_allclose(a[ind], aw[ind])
    assert_allclose(b[ind], bw[ind])

    aw, bw = m(x, y, with_bounding_box=True, fill_value=1000)
    ind = (aw != 1000).nonzero()
    assert_allclose(a[ind], aw[ind])
    assert_allclose(b[ind], bw[ind])

    # test the order of bbox is not reversed for 1D models
    p = models.Polynomial1D(1, c0=12, c1=2.3)
    p.bounding_box = (0, 5)
    assert (p(1) == p(1, with_bounding_box=True))
Пример #2
0
def test_fitters_with_weights(fitter):
    """Issue #5737 """
    fitter = fitter()

    if isinstance(fitter, _NLLSQFitter):
        pytest.xfail("This test is poorly designed and causes issues for "
                     "scipy.optimize.least_squares based fitters")

    Xin, Yin = np.mgrid[0:21, 0:21]

    with NumpyRNGContext(_RANDOM_SEED):
        zsig = np.random.normal(0, 0.01, size=Xin.shape)

    # Non-linear model
    g2 = models.Gaussian2D(10, 10, 9, 2, 3)
    z = g2(Xin, Yin)
    gmod = fitter(models.Gaussian2D(15, 7, 8, 1.3, 1.2), Xin, Yin, z + zsig)
    assert_allclose(gmod.parameters, g2.parameters, atol=10 ** (-2))

    # Linear model
    p2 = models.Polynomial2D(3)
    p2.parameters = np.arange(10)/1.2
    z = p2(Xin, Yin)
    with pytest.warns(AstropyUserWarning,
                      match=r'Model is linear in parameters'):
        pmod = fitter(models.Polynomial2D(3), Xin, Yin, z + zsig)
    assert_allclose(pmod.parameters, p2.parameters, atol=10 ** (-2))
Пример #3
0
def pcf_forward(pcffile, outname):
    """
    Create the **IDT** forward transform from collimator to gwa.
    """
    with open(pcffile) as f:
        lines = [l.strip() for l in f.readlines()]

    factors = lines[lines.index('*Factor 2') + 1].split()
    # factor==1/factor in backward msa2ote direction and factor==factor in sky2detector direction
    scale = models.Scale(float(factors[0]), name="x_scale") & \
          models.Scale(float(factors[1]), name="y_scale")

    rotation_angle = lines[lines.index('*Rotation') + 1]
    # The minius sign here is because astropy.modeling has the opposite direction of rotation than the idl implementation
    rotation = models.Rotation2D(-float(rotation_angle), name='rotation')


    # Here the model is called "output_shift" but in the team version it is the "input_shift".
    input_rot_center = lines[lines.index('*InputRotationCentre 2') + 1].split()
    input_rot_shift = models.Shift(-float(input_rot_center[0]), name='input_x_shift') & \
                 models.Shift(-float(input_rot_center[1]), name='input_y_shift')


    # Here the model is called "input_shift" but in the team version it is the "output_shift".
    output_rot_center = lines[lines.index('*OutputRotationCentre 2') + 1].split()
    output_rot_shift = models.Shift(float(output_rot_center[0]), name='output_x_shift') & \
                  models.Shift(float(output_rot_center[1]), name='output_y_shift')

    degree = int(lines[lines.index('*FitOrder') + 1])
    xcoeff_index = lines.index('*xForwardCoefficients 21 2')
    xlines = lines[xcoeff_index + 1: xcoeff_index + 22]
    xcoeff_forward = coeffs_from_pcf(degree, xlines)
    x_poly_forward = models.Polynomial2D(degree, name='x_poly_forward', **xcoeff_forward)

    ycoeff_index = lines.index('*yForwardCoefficients 21 2')
    ycoeff_forward = coeffs_from_pcf(degree, lines[ycoeff_index + 1: ycoeff_index + 22])
    y_poly_forward = models.Polynomial2D(degree, name='y_poly_forward', **ycoeff_forward)

    xcoeff_index = lines.index('*xBackwardCoefficients 21 2')
    xcoeff_backward = coeffs_from_pcf(degree, lines[xcoeff_index + 1: xcoeff_index + 22])
    x_poly_backward = models.Polynomial2D(degree, name='x_poly_backward', **xcoeff_backward)

    ycoeff_index = lines.index('*yBackwardCoefficients 21 2')
    ycoeff_backward = coeffs_from_pcf(degree, lines[ycoeff_index + 1: ycoeff_index + 22])
    y_poly_backward = models.Polynomial2D(degree, name='y_poly_backward', **ycoeff_backward)

    x_poly_forward.inverse = x_poly_backward
    y_poly_forward.inverse = y_poly_backward

    poly_mapping1  = Mapping((0, 1, 0, 1))
    poly_mapping1.inverse = Identity(2)
    poly_mapping2 = Identity(2)
    poly_mapping2.inverse = Mapping((0, 1, 0, 1))

    model = input_rot_shift | rotation | scale | output_rot_shift | \
          poly_mapping1 | x_poly_forward & y_poly_forward | poly_mapping2
    f = AsdfFile()
    f.tree = {'model': model}
    f.write_to(outname)
Пример #4
0
def test_bounding_box_pass_with_ignored():
    """Test the possiblity of setting ignored variables in bounding box"""

    model = models.Polynomial2D(2)
    bbox = ModelBoundingBox.validate(model, (-1, 1), ignored=['y'])
    model.bounding_box = bbox
    assert model.bounding_box.bounding_box() == (-1, 1)
    assert model.bounding_box == bbox

    model = models.Polynomial2D(2)
    bind_bounding_box(model, (-1, 1), ignored=['y'])
    assert model.bounding_box.bounding_box() == (-1, 1)
    assert model.bounding_box == bbox
Пример #5
0
def test_linear_fitter_with_weights():
    """Regression test for #7035"""
    Xin, Yin = np.mgrid[0:21, 0:21]
    fitter = LinearLSQFitter()

    with NumpyRNGContext(_RANDOM_SEED):
        zsig = np.random.normal(0, 0.01, size=Xin.shape)

    p2 = models.Polynomial2D(3)
    p2.parameters = np.arange(10)/1.2
    z = p2(Xin, Yin)
    pmod = fitter(models.Polynomial2D(3), Xin, Yin, z + zsig, weights=zsig**(-2))
    assert_allclose(pmod.parameters, p2.parameters, atol=10 ** (-2))
Пример #6
0
def test_linear_fitter_with_weights_flat():
    """Same as the above #7035 test but with flattened inputs"""
    Xin, Yin = np.mgrid[0:21, 0:21]
    Xin, Yin = Xin.flatten(), Yin.flatten()
    fitter = LinearLSQFitter()

    with NumpyRNGContext(_RANDOM_SEED):
        zsig = np.random.normal(0, 0.01, size=Xin.shape)

    p2 = models.Polynomial2D(3)
    p2.parameters = np.arange(10)/1.2
    z = p2(Xin, Yin)
    pmod = fitter(models.Polynomial2D(3), Xin, Yin, z + zsig, weights=zsig**(-2))
    assert_allclose(pmod.parameters, p2.parameters, atol=10 ** (-2))
Пример #7
0
def create_channel_selector(alpha, lam, channel, beta, ch_v2, ch_v3):
    if channel == 1:
        nslice = range(101, 122)  #21
    elif channel == 2:
        nslice = range(201, 218)  #17
    elif channel == 3:
        nslice = 16
    elif channel == 4:
        nslice = 12
    else:
        raise ValueError("Incorrect channel #")

    # transformation from local system (alpha, beta) to V2/V3
    p_v2 = models.Polynomial2D(2)
    p_v3 = models.Polynomial2D(2)
    p_v2.c0_0, p_v2.c0_1, p_v2.c1_0, p_v2.c1_1 = ch_v2[1:]
    p_v3.c0_0, p_v3.c0_1, p_v3.c1_0, p_v3.c1_1 = ch_v3[1:]
    ab_v2v3 = p_v2 & p_v3

    ind = []
    for i in range(5):
        for j in range(5):
            ind.append((i, j))

    selector = {}
    # In the paper the formula is (x-xs)^j*y^i, so the 'x' corresponds
    # to y in modeling. - swapped in Mapping
    axs = alpha.field('x_s')
    lxs = lam.field('x_s')
    #for i in range(nslice):
    for i, sl in enumerate(nslice):
        ashift = models.Shift(axs[i])
        lshift = models.Shift(lxs[i])
        palpha = models.Polynomial2D(8)
        plam = models.Polynomial2D(8)
        for index, coeff in zip(ind, alpha[i][1:]):
            setattr(palpha, 'c{0}_{1}'.format(index[0], index[1]), coeff)
        for index, coeff in zip(ind, lam[i][1:]):
            setattr(plam, 'c{0}_{1}'.format(index[0], index[1]), coeff)
        alpha_model = ashift & models.Identity(1) | palpha
        lam_model = lshift & models.Identity(1) | plam
        beta_model = models.Const1D(beta[0] + (i - 1) * beta[1])
        # Note swapping of axes
        a_b_l = models.Mapping(
            (1, 0, 0, 1, 0)) | alpha_model & beta_model & lam_model
        v2_v3_l = a_b_l | models.Mapping(
            (0, 1, 0, 1, 2)) | ab_v2v3 & models.Identity(1)
        selector[sl] = v2_v3_l
    # return alpha, beta, lambda
    return selector
Пример #8
0
def fit_polynomial(data, degree, mask=None, sigma_clip_background=False):

    """
    This function ...
    :param data:
    :param degree:
    :param mask:
    :param sigma_clip_background:
    :return:
    """

    if sigma_clip_background: mask = statistics.sigma_clip_mask(data, sigma_level=3.0, mask=mask)

    # Fit the data using astropy.modeling
    poly_init = models.Polynomial2D(degree=degree)
    fit_model = fitting.LevMarLSQFitter()

    # Split x, y and z values that are not masked
    x_values, y_values, z_values = general.split_xyz(data, mask=mask, arrays=True)

    # Ignore model linearity warning from the fitter
    with warnings.catch_warnings():

        warnings.simplefilter('ignore')
        poly = fit_model(poly_init, x_values, y_values, z_values)  # What comes out is the model with the parameters set

    # Return the polynomial model and the new mask
    if sigma_clip_background: return poly, mask

    # Return the polynomial model
    else: return poly
Пример #9
0
    def _calculate_dvel_2D(self):
        """
        Fit a 2D surface to dvel vs. pixel vs. order
        """
        # threshold (units of MAD) to throw out shifts
        sigclip = 5
        vshift = self.vshift.copy()
        med = np.median(vshift)
        mad = np.median(np.abs(vshift - med))
        bout = np.abs(vshift - med) > sigclip * mad
        vshift = ma.masked_array(vshift, bout)

        if np.std(vshift) > 25:
            print("WARNING: velocity shifts not well determined")
            vshift *= 0

        pix = np.arange(self.npix)
        ord = np.arange(self.nord)
        x, y = np.meshgrid(self.pixmid-np.mean(pix), ord)

        p_init = models.Polynomial2D(degree=3)
        fit_p = fitting.LevMarLSQFitter()

        p = fit_p(p_init, x, y, vshift)

        dvel = np.zeros((self.nord, self.npix))
        XX, YY = np.meshgrid(pix-np.mean(pix), ord)
        fit = p(XX, YY)
        dvel = dvel + fit

        return dvel
Пример #10
0
def image_poly_filter(image, mask=None, degree=2, return_bg=False):
    '''
    polynominal filter the image
    '''
    if degree is None:
        return image

    import warnings
    from astropy.modeling import models, fitting

    if mask is None:
        mask = np.ones(image.shape)
        mask[image == 0] = 0
    sp = np.where(mask != 0)

    Nx, Ny = image.shape
    x, y = np.meshgrid(np.arange(Nx), np.arange(Ny))

    p_init = models.Polynomial2D(degree=degree)
    fit_p = fitting.LevMarLSQFitter()

    with warnings.catch_warnings():
        # Ignore model linearity warning from the fitter
        warnings.simplefilter('ignore')
        p = fit_p(p_init, x[sp], y[sp], image[sp])

    bgmap = p(x, y)
    image_filt = image - bgmap

    if return_bg:
        return image_filt, bgmap

    return image_filt
Пример #11
0
def test_model_copy_with_bounding_box():
    model = models.Polynomial2D(2)
    bbox = ModelBoundingBox.validate(model, ((-0.5, 1047.5), (-0.5, 2047.5)),
                                     order='F')

    # No bbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert model_copy.get_bounding_box() == model.get_bounding_box() == None

    # with bbox
    model.bounding_box = bbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert id(model_copy.bounding_box) != id(model.bounding_box)
    for index, interval in model.bounding_box.intervals.items():
        interval_copy = model_copy.bounding_box.intervals[index]
        assert interval == interval_copy
        assert id(interval) != interval_copy

    # add model to compound model
    model1 = model | models.Identity(1)
    model_copy = model1.copy()
    assert id(model_copy) != id(model1)
    assert model_copy.get_bounding_box() == model1.get_bounding_box() == None
Пример #12
0
def create_xy_models(data, channel, coeff_names, name):
    """
    Create a 2D polynomial model for the transformation
    local_MIRI --> detector frame.
    """
    nslices = len(data)
    sl = channel * 100 + np.arange(1, nslices + 1)
    shname = "shift_{0}".format(name)
    pname = "polynomial_{0}".format(name)
    transforms = {}
    for i in range(nslices):
        sl = channel * 100 + i + 1
        al = data[i]
        xs = al[0]
        coeffs = {}
        for c, val in zip(coeff_names, al[1:]):
            coeffs[c] = val

        # First we do Adrian's transforms
        thisxform = models.Shift(
            -xs, name=shname) & models.Identity(1) | models.Polynomial2D(
                8, name=pname, **coeffs)
        # Then we need to shift from the 1-indexed pixels used by transforms to the
        # 0-indexed pixels used by the pipeline
        # (both Adrian and the pipeline include reference pixels)
        # Only a single output so only a single shift
        thisshift = models.Shift(-1)
        # Put the models together
        transforms[sl] = thisxform | thisshift

    return transforms
Пример #13
0
def create_poly_models(data, channel, coeff_names, name):
    """
    Create a 2D polynomial model for the transformation
    detector --> local MIRI frame
    Works for alpha and lambda coordinates.
    """
    nslices = len(data)
    sl = channel * 100 + np.arange(1, nslices + 1)

    transforms = {}
    for i in range(nslices):
        sl = channel * 100 + i + 1
        al = data[i]
        xs = al[0]
        coeffs = {}
        for c, val in zip(coeff_names, al[1:]):
            coeffs[c] = val

        # First we need to shift from the 0-indexed pixels input by the pipeline to the
        # 1-indexed pixels used by Adrians transforms
        # (both Adrian and the pipeline include reference pixels)
        # Remember that the coordinates here are in order y,x
        thisshift = models.Shift(1) & models.Shift(1)
        # Now do Adrians transforms
        thisxform = models.Identity(1) & models.Shift(
            -xs) | models.Polynomial2D(8, name=name, **coeffs)
        # Put the models together
        transforms[sl] = thisshift | thisxform

    return transforms
Пример #14
0
def quadratic_peakfinder(x, y, z):
    """
    Fit for the peak ``(x, y)`` position by fitting the data with a
    2nd-degree 2D polynomial.

    Parameters
    ----------
    x : array-like
        Input coordinates.

    y : array-like
        Input coordinates.

    z : array-like
        Input values.

    Returns
    -------
    x, y : float
        The ``x`` and ``y`` position of the fitted peak value.
    """

    p_init = models.Polynomial2D(degree=2)  # default coefficients are zero
    fitter = fitting.LinearLSQFitter()
    p_fit = fitter(p_init, x, y, z)

    y_peak = ((2 * p_fit.c2_0 * p_fit.c0_1 - p_fit.c1_0 * p_fit.c1_1) /
              (p_fit.c1_1**2 - 4 * p_fit.c0_2 * p_fit.c2_0))
    x_peak = -(p_fit.c0_1 + 2 * p_fit.c0_2 * y_peak) / p_fit.c1_1

    return x_peak, y_peak
Пример #15
0
def to_model(coeffs, degree=5):
    """
    Creates an astropy.modeling.Model object

    Parameters
    ----------
    coeffs : array like
        Coefficients in the same order as in the ISIM transformations file.
    degree : int
        Degree of polynomial.
        Default is 5 as in the ISIM file but many of the polynomials are of
        a smaller degree.

    Returns
    -------
    poly : astropy.modeling.Polynomial2D
        Polynomial model transforming one coordinate (x or y) between two systems.
    """
    c = {}
    names = []
    for i in range(5):
        for j in range(5):
            if i+j < degree+1:
                names.append('c{0}_{1}'.format(i, j))

    for name, coe in zip(names, coeffs):
        c[name] = coe
    return models.Polynomial2D(degree, **c)
Пример #16
0
def gauss_center(data, sigma=3., theta=0.):
    """center the data  by fitting a 2d gaussian to the region.

    Parameters
    ----------

    data: float
        should be a 2d array, the initial center is used to estimate
        the fit center
    """
    # use a smaller bounding box so that we are only fitting the local data
    delta = int(len(data) / 2)  # guess the center
    amp = data.max() - data.min()  # guess the amplitude
    ldata = len(data)
    yy, xx = np.mgrid[:ldata, :ldata]

    # Fit model to data
    fit = fitting.LevMarLSQFitter()

    # Gaussian2D(amp,xmean,ymean,xstd,ystd,theta) + a constant
    model = (models.Gaussian2D(amp, delta, delta, sigma, sigma, theta) +
             models.Polynomial2D(c0_0=data.min(), degree=0))
    with warnings.catch_warnings():
        # Ignore model linearity warning from the fitter
        warnings.simplefilter('ignore')
        results = fit(model, xx, yy, data)

    # previous yield amp, ycenter, xcenter, sigma, offset
    return results
Пример #17
0
def test_model_copy_with_compound_bounding_box():
    model = models.Polynomial2D(2)
    bbox = {(0,): (-0.5, 1047.5),
            (1,): (-0.5, 3047.5)}
    cbbox = CompoundBoundingBox.validate(model, bbox, selector_args=[('x', True)], order='F')

    # No cbbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert model_copy.get_bounding_box() == model.get_bounding_box() == None

    # with cbbox
    model.bounding_box = cbbox
    model_copy = model.copy()
    assert id(model_copy) != id(model)
    assert id(model_copy.bounding_box) != id(model.bounding_box)
    assert model_copy.bounding_box.selector_args == model.bounding_box.selector_args
    assert id(model_copy.bounding_box.selector_args) != id(model.bounding_box.selector_args)
    for selector, bbox in model.bounding_box.bounding_boxes.items():
        for index, interval in bbox.intervals.items():
            interval_copy = model_copy.bounding_box.bounding_boxes[selector].intervals[index]
            assert interval == interval_copy
            assert id(interval) != interval_copy

    # add model to compound model
    model1 = model | models.Identity(1)
    model_copy = model1.copy()
    assert id(model_copy) != id(model1)
    assert model_copy.get_bounding_box() == model1.get_bounding_box() == None
Пример #18
0
 def test_2d_with_weights_without_sigma_clip(self):
     model = models.Polynomial2D(0)
     fitter = LevMarLSQFitter()  # LinearLSQFitter doesn't handle weights properly in 2D
     with pytest.warns(AstropyUserWarning,
                       match=r'Model is linear in parameters'):
         fit = fitter(model, self.x, self.y, self.z, weights=self.weights)
     assert(fit.parameters[0] > 1.0)     # outliers pulled it high
Пример #19
0
    def setup_class(self):
        self.model = models.Polynomial2D(2)
        self.y, self.x = np.mgrid[:5, :5]

        def poly2(x, y):
            return 1 + 2 * x + 3 * x ** 2 + 4 * y + 5 * y ** 2 + 6 * x * y
        self.z = poly2(self.x, self.y)
Пример #20
0
def fit_airy_2d(data, x=None, y=None):
    """Fit an AiryDisk2D model to the data."""
    delta = int(len(data) / 2)  # guess the center
    ldata = len(data)

    if not x:
        x = delta
    if not y:
        y = delta
    fixed_pars = {"x_0": True, "y_0": True}  # hold these constant
    yy, xx = np.mgrid[:ldata, :ldata]

    # fit model to the data
    fit = fitting.LevMarLSQFitter()

    # AiryDisk2D(amplitude, x_0, y_0, radius) + constant
    model = (models.AiryDisk2D(
        np.max(data), x_0=x, y_0=y, radius=delta, fixed=fixed_pars) +
             models.Polynomial2D(c0_0=data.min(), degree=0))
    with warnings.catch_warnings():
        # Ignore model warnings for new_plot_window
        warnings.simplefilter('ignore')
        results = fit(model, xx, yy, data)

    return results
def fit_poly_surface_2D(x_norm,
                        y_norm,
                        z,
                        weights=None,
                        polytype='chebyshev',
                        poly_deg=5,
                        timit=False,
                        debug_level=0):
    """
    Calculate 2D polynomial fit to normalized x and y values.
    Wrapper function for using the astropy fitting library.
    
    INPUT:
    'x_norm'      : x-values (pixels) of all the lines, re-normalized to [-1,+1]
    'm_norm'      : order numbers of all the lines, re-normalized to [-1,+1]
    'z'           : the 2-dim array of 'observed' values
    'weights'     : weights to use in the fitting
    'polytype'    : types of polynomials to use (either '(p)olynomial' (default), '(l)egendre', or '(c)hebyshev' are accepted)
    'poly_deg'    : degree of the polynomials
    'timit'       : boolean - do you want to measure execution run time?
    'debug_level' : for debugging... 
        
    OUTPUT:
    'p'  : coefficients of the best-fit polynomials
    """

    if timit:
        start_time = time.time()

    if polytype.lower() in ['p', 'polynomial']:
        p_init = models.Polynomial2D(poly_deg)
        if debug_level > 0:
            print('OK, using standard polynomials...')
    elif polytype.lower() in ['c', 'chebyshev']:
        p_init = models.Chebyshev2D(poly_deg, poly_deg)
        if debug_level > 0:
            print('OK, using Chebyshev polynomials...')
    elif polytype.lower() in ['l', 'legendre']:
        p_init = models.Legendre2D(poly_deg, poly_deg)
        if debug_level > 0:
            print('OK, using Legendre polynomials...')
    else:
        print(
            "ERROR: polytype not recognised ['(P)olynomial' / '(C)hebyshev' / '(L)egendre']"
        )
        return

    fit_p = fitting.LevMarLSQFitter()

    with warnings.catch_warnings():
        # Ignore model linearity warning from the fitter
        warnings.simplefilter('ignore')
        p = fit_p(p_init, x_norm, y_norm, z, weights=weights)

    if timit:
        print('Time elapsed: ' +
              np.round(time.time() - start_time, 2).astype(str) +
              ' seconds...')

    return p
Пример #22
0
def fit_gaussian_to_cutout(cutout, seeing_pix):
    """Fit a 2D gaussian to the cutout to determine the location of the maximum
    Inputs: 
        cutout: a small array representing a cutout from the direct image.
        seeing_pix: a guess of the seeing size in pixel for gaussian fit
    Output:
        res: result of the 2D polynomial (res[0]) and gaussian fit (res[1]). 
                The location of the source is determined by the gaussian part, of course.
                (MMB: Are these backwards? e.g. gaussian is res[0]?)
                """

    g_init = models.Gaussian2D(amplitude = np.max(cutout), \
                                x_mean = np.shape(cutout)[1]/2,y_mean = np.shape(cutout)[0]/2,\
                                x_stddev = seeing_pix, y_stddev = seeing_pix)
    #allow for some DC offset
    const_init = models.Polynomial2D(2)
    #Use LevMar LSQ fitter
    fitter = fitting.LevMarLSQFitter()
    #Just get x,y grid for the cutout
    y, x = np.mgrid[:np.shape(cutout)[0], :np.shape(cutout)[1]]
    #fit
    res = fitter(g_init + const_init, x, y, cutout)
    #We want x,y location from the Gaussian part
    #print(res[0].amplitude.value, res[0].x_stddev.value)
    return res
Пример #23
0
def to_model(coeffs, degree=5):
    """
    Creates an astropy.modeling.Model object

    Parameters
    ----------
    coeffs : array like
        Coefficients from the ISIM transformations file.
    degree : int
        Degree of polynomial.
        Default is 5 as in the ISIM file but many of the polynomials are of
        a smaller degree.

    Returns
    -------
    poly : astropy.modeling.Polynomial2D
        Polynomial model transforming one coordinate (x or y) between two systems.
    """

    #map Colin's coefficients into the order expected by Polynomial2D
    c = {}
    for cname in coeffs.colnames:
        siaf_i = int(cname[-2])
        siaf_j = int(cname[-1])
        name = 'c{0}_{1}'.format(siaf_i - siaf_j, siaf_j)
        c[name] = coeffs[cname].data[0]

    #0,0 coefficient should not be used, according to Colin's TR
    #JWST-STScI-001550
    c['c0_0'] = 0

    return models.Polynomial2D(degree, **c)
Пример #24
0
def create_xy_models(data, channel, coeff_names, name):
    """
    Create a 2D polynomial model for the transformation
    local_MIRI --> detector frame.
    """
    nslices = len(data)
    sl = channel * 100 + np.arange(1, nslices + 1)
    shname = "shift_{0}".format(name)
    pname = "polynomial_{0}".format(name)
    transforms = {}
    for i in range(nslices):
        sl = channel * 100 + i + 1
        al = data[i]
        xs = al[0]
        coeffs = {}
        for c, val in zip(coeff_names, al[1:]):
            coeffs[c] = val

        # As of CDP-8b both the IDT transform as the pipeline use 0-indexed pixels, and
        # include the 4 reference pixels in their counting.  Therefore we do not need to
        # apply any index shift, just the transform.
        thisxform = models.Shift(
            -xs, name=shname) & models.Identity(1) | models.Polynomial2D(
                8, name=pname, **coeffs)
        transforms[sl] = thisxform

    return transforms
Пример #25
0
def create_poly_models(data, channel, coeff_names, name):
    """
    Create a 2D polynomial model for the transformation
    detector --> local MIRI frame
    Works for alpha and lambda coordinates.
    """
    nslices = len(data)
    sl = channel * 100 + np.arange(1, nslices + 1)

    transforms = {}
    for i in range(nslices):
        sl = channel * 100 + i + 1
        al = data[i]
        xs = al[0]
        coeffs = {}
        for c, val in zip(coeff_names, al[1:]):
            coeffs[c] = val

        # As of CDP-8b both the IDT transform as the pipeline use 0-indexed pixels, and
        # include the 4 reference pixels in their counting.  Therefore we do not need to
        # apply any index shift, just the transform.
        thisxform = models.Identity(1) & models.Shift(
            -xs) | models.Polynomial2D(8, name=name, **coeffs)
        # Put the models together
        transforms[sl] = thisxform

    return transforms
Пример #26
0
 def test_2d_without_weights_with_sigma_clip(self):
     model = models.Polynomial2D(0)
     fitter = FittingWithOutlierRemoval(LinearLSQFitter(), sigma_clip,
                                        niter=3, sigma=3.)
     fit, mask = fitter(model, self.x, self.y, self.z)
     assert((~mask).sum() == self.z.size - 2)
     assert(mask[0, 0] and mask[0, 1])
     assert_allclose(fit.parameters[0], 0.0, atol=10**(-2))
Пример #27
0
    def test_p2_nset_npset(self):
        """N param_sets, N 2D data sets, Poly2d"""

        p2 = models.Polynomial2D(5, n_models=2)
        xx = np.array([self.x, self.x])
        yy = np.array([self.y, self.y])
        z = p2(xx, yy)
        assert z.shape == (2, 10, 10)
Пример #28
0
 def test_2d_with_weights_with_sigma_clip(self):
     """smoke test for #7020 - fails without fitting.py patch because weights does not propagate"""
     model = models.Polynomial2D(0)
     fitter = FittingWithOutlierRemoval(LevMarLSQFitter(), sigma_clip,
                                        niter=3, sigma=3.)
     fit, filtered = fitter(model, self.x, self.y, self.z, weights=self.weights)
     assert(fit.parameters[0] > 10**(-2))  # weights pulled it > 0
     assert(fit.parameters[0] < 1.0)       # outliers didn't pull it out of [-1:1] because they had been removed
Пример #29
0
    def test_2d_with_weights_without_sigma_clip(self, fitter):
        fitter = fitter()

        model = models.Polynomial2D(0)
        with pytest.warns(AstropyUserWarning,
                          match=r'Model is linear in parameters'):
            fit = fitter(model, self.x, self.y, self.z, weights=self.weights)
        assert(fit.parameters[0] > 1.0)     # outliers pulled it high
Пример #30
0
    def posTrans(self, posMchs, stars):
        
        #print(posMchs)
        for i, tm in enumerate(posMchs):
            if i==0:
                dataOi = posMchs[i][0]
                dataTi = posMchs[i][1]
            else:
                dataOi = np.concatenate([dataOi,posMchs[i][0]])
                dataTi = np.concatenate([dataTi,posMchs[i][1]])
        
        xshift,yshift, xrms, yrms = self.evaluatePos(dataOi, dataTi)
        print("xshift=%.2f, yshift=%.2f, xrms=%.5f, yrms=%.5f"%(xshift,yshift, xrms, yrms))
        '''
        minLen = dataTi.shape[0]
        if minLen>dataOi.shape[0]:
            minLen=dataOi.shape[0]
        
        dataTi2 = dataTi[:minLen]
        dataOi2 = dataOi[:minLen]
        '''
        dataTi2 = dataTi
        dataOi2 = dataOi
        
        oix = dataOi2[:,0]
        oiy = dataOi2[:,1]
        tix = dataTi2[:,0]
        tiy = dataTi2[:,1]
        
        p_init = models.Polynomial2D(degree=1)
        fit_p = fitting.LevMarLSQFitter()
        
        with warnings.catch_warnings():
            # Ignore model linearity warning from the fitter
            warnings.simplefilter('ignore')
            tixp = fit_p(p_init, oix, oiy, tix)
            tiyp = fit_p(p_init, oix, oiy, tiy)
            
            tix2 = tixp(oix, oiy)
            tiy2 = tiyp(oix, oiy)
        
        dataTi2 = np.concatenate([tix2.reshape((tix2.shape[0],1)),tiy2.reshape((tix2.shape[0],1))],axis=1)
        xshift,yshift, xrms, yrms = self.evaluatePos(dataTi, dataTi2)
        print("xshift=%.2f, yshift=%.2f, xrms=%.5f, yrms=%.5f"%(xshift,yshift, xrms, yrms))
    
        starPoss = stars[:,3:5]
        oix = starPoss[:,0]
        oiy = starPoss[:,1]
        tix2 = tixp(oix, oiy)
        tiy2 = tiyp(oix, oiy)
        starPossTi = np.concatenate([tix2.reshape((tix2.shape[0],1)),tiy2.reshape((tix2.shape[0],1))],axis=1)

        xshift,yshift, xrms, yrms = self.evaluatePos(starPoss, starPossTi)
        stars[:,3:5] = starPossTi
        print("xshift=%.2f, yshift=%.2f, xrms=%.5f, yrms=%.5f"%(xshift,yshift, xrms, yrms))
        
        
        return stars