def setUp(self):

        self.holeshape = "hex"

        # directory containing the test data
        data_dir = os.path.join(os.path.dirname(__file__),
                                'test_data/find_affine2d_parameters')
        self.data_dir = data_dir
        print(data_dir)
        if not os.path.exists(data_dir):
            os.makedirs(data_dir)

        pixel = 0.0656 * u.arcsec.to(u.rad)
        npix = 87
        wave = np.array([
            (1.0, 4.3e-6),
        ])  # m
        over = 3
        holeshape = 'hex'

        rotd_true = 9.25
        rotdegs = (8.0, 9.0, 10.0, 11.0, 12.0
                   )  # search in this range of rotation (degrees)

        # store the real affine to be uased to create test data
        self.affine = utils.Affine2d(
            rotradccw=np.pi * utils.avoidhexsingularity(rotd_true) / 180.0,
            name="{0:.4}".format(float(rotd_true)))
        self.affine.show(label="Creating affine2d for PSF data")

        # create image data to find its rotation, as a sample test...
        imagefn = data_dir + "/imagedata.fits"
        jw = NRM_Model(mask='jwst', holeshape="hex", affine2d=self.affine)
        jw.set_pixelscale(pixel)
        jw.simulate(fov=npix, bandpass=wave, over=over)
        fits.writeto(imagefn, jw.psf, overwrite=True)
        imagedata = jw.psf.copy()
        del jw
        fits.getdata(imagefn)
        psf_offset = (0.0, 0.0)
        print("driver:", rotdegs)
        mx, my, sx, sy, xo, yo, = (1.0, 1.0, 0.0, 0.0, 0.0, 0.0)
        aff_best_rot = FAP.find_rotation(imagedata,
                                         psf_offset,
                                         rotdegs,
                                         mx,
                                         my,
                                         sx,
                                         sy,
                                         xo,
                                         yo,
                                         pixel,
                                         npix,
                                         wave,
                                         over,
                                         holeshape,
                                         outdir=data_dir)

        print(aff_best_rot)
        self.aff_best_rot = aff_best_rot
示例#2
0
def analyze_data(fitsfn,
                 observables_dir="",
                 affine2d=None,
                 psf_offset_find_rotation=(0.0, 0.0),
                 psf_offset_ff=None,
                 rotsearch_d=None,
                 set_pistons=None):
    """ 
        returns: affine2d (measured or input), 
        psf_offset_find_rotation (input),
        psf_offset_ff (input or found),
        fringe pistons/r (found)
    """

    print("analyze_data: input file", fitsfn)

    data = fits.getdata(fitsfn)
    dim = data.shape[1]

    mx, my, sx, sy, xo, yo, = (1.0, 1.0, 0.0, 0.0, 0.0, 0.0)

    if affine2d is None:
        print(" analyze_data: Finding affine2d...")
        affine2d = FAP.find_rotation(data[0, :, :],
                                     psf_offset_find_rotation,
                                     rotsearch_d,
                                     mx,
                                     my,
                                     sx,
                                     sy,
                                     xo,
                                     yo,
                                     PIXELSCALE_r,
                                     dim,
                                     bandpass,
                                     oversample,
                                     holeshape,
                                     outdir=fitsimdir)
        print("analyze_data:  Using measured affine2d...", affine2d.name)
    else:
        print("analyze_data:  Using incoming affine2d ", affine2d.name)

    niriss = InstrumentData.NIRISS(filt, bandpass=bandpass, affine2d=affine2d)
    ff_t = nrm_core.FringeFitter(niriss,
                                 psf_offset_ff=psf_offset_ff,
                                 datadir=fitsimdir,
                                 savedir=fitsimdir + observables_dir,
                                 oversample=oversample,
                                 interactive=False)
    ff_t.fit_fringes(fitsfn)
    examine_residuals(ff_t)

    np.set_printoptions(formatter={'float': lambda x: '{:+.2e}'.format(x)},
                        linewidth=80)
    print("analyze_data: fringepistons/rad", ff_t.nrm.fringepistons)
    default_printoptions()
    return affine2d, psf_offset_find_rotation, ff_t.nrm.psf_offset, ff_t.nrm.fringepistons
示例#3
0
def rotsim_mir(rotdegs=0.0, ov=1):
    """ This function sets up directory and file names, writes a 2D file,
        and then mirage-izes it to disk.
        Data is written to a hardcoded ddata directory at the momet:
            ~/data/niriss_verification/*"
        A subdirectory labelled with oversampling is created for implaneia analysis output.
        rotdegs: pupil rotation in degrees
    """

    # Set up directories for :
    #    input fits miragelike files
    #    output optical Interferometry directory for implaneia text files & fits files
    #    where to find the mirage example to borrow its header
    home = os.path.expanduser('~')
    import getpass
    username = getpass.getuser()

    # Mirage header needed from:
    mirext = "_mir"
    if (username=="anand"):
        mirexample = home + \
                "/gitsrc/ImPlaneIA/example_data/example_niriss/"+\
                "jw00793001001_01101_00001_nis_cal.fits" 
    else:
        mirexample = home + \
             "/ImplaneIA/notebooks/simulatedpsfs/" + \
             "jw00793001001_01101_00001_nis_cal.fits" 


    # create simdata and output observables directories data
    #
    ov = 1 # oversampling for simulation of psf
    fitsimdir = home+"/data/implaneia/niriss_verification/"
    if not os.path.exists(fitsimdir):  
        os.makedirs(fitsimdir) 
        print("Created image simulation data directory:\n\t", fitsimdir)

    oidir = fitsimdir + "ov{:d}".format(ov)
    if not os.path.exists(oidir):
        os.mkdir(oidir)
        print("Created oi text output file directory:\n\t", oidir)
    else:
        print("Using existing oi text output file directory:\n\t", oidir)

    if not os.path.exists(fitsimdir+'/rotdir/'):  
        os.mkdir(fitsimdir+'/rotdir/') 

    # Create psf with implaneia
    #
    simfn = create_data(fitsimdir, rotdegs, ov) 
    # get back miragefile.fits string (not full path)
    mirfn = utils.amisim2mirage(fitsimdir, simfn.replace(".fits",""), mirexample, FILT)
    if mirfn[0] == '/': mirfn=mirfn[1:]
    print("mirage-like file", mirfn, 'written in', fitsimdir)
    
    simdata = fits.getdata(fitsimdir+mirfn, 1)[0,:,:]
    print("simdata.shape", simdata.shape)
    # in real data:
    # psfoffset =  locatecenter(simdata, filt)
    psf_offset = (0.5,0.5)

    # Extract observables with implaneia
    #
    from nrm_analysis import find_affine2d_parameters as FAP
    mx, my, sx,sy, xo,yo, = (1.0,1.0, 0.0,0.0, 0.0,0.0)
    rotsearch_d = (8.0, 9.0, 10.0, 11.0, 12.0)
    wave = np.array([(1.0, 4.3e-6),])  # SI  - we won't know from the data what lam_c -  comes from outside?
                   # real-life - use apprpriate bandpass array
    aff_rot_measured = FAP.find_rotation(simdata, psf_offset,
                      rotsearch_d, mx, my, sx,sy, xo,yo,
                      PIXELSCALE_r, 80, wave, ov, 'hex', outdir=fitsimdir+"/rotdir/")

    image2oi(fitsimdir+mirfn, oidir, oversample=ov, filt=FILT, bp=MONOF430M, prec=4, affine2d=aff_rot_measured)

    # Helpful printout after implaneia bulk output
    #
    print(InstrumentData.__file__)
    aff_rot_measured.show()
    def test_find_pass_affine_rot(self):

        header = fits.getheader(self.imagefn)
        filename = os.path.basename(self.imagefn)
        datadir = os.path.dirname(self.imagefn)
        print('\n')
        print('  >> >> >> >> testing self.imagefn %s' % self.imagefn)
        print('  >> >> >> >> testing self.datadir %s' % self.datadir)
        print('  >> >> >> >> testing self.savedir %s' % self.savedir)

        fn = filename.replace('.fits', '')
        print('  >> >> >> >> fn %s' % fn)

        print("driver rotd_search:", rotd_search)
        print("driver rotd_true:", rotd_true)
        mx, my, sx, sy, xo, yo, = (1.0, 1.0, 0.0, 0.0, 0.0, 0.0)
        psf_offset = (0.0, 0.0)

        # FIND ROTATION FROM IMAGE DATA CREATED USING KNOWN ROTATION AND SCALE
        aff_best_rot = FAP.find_rotation(self.simulated_image,
                                         psf_offset,
                                         rotd_search,
                                         mx,
                                         my,
                                         sx,
                                         sy,
                                         xo,
                                         yo,
                                         header['PIXELSCL'] * arcsec2rad,
                                         n_image,
                                         self.monochromatic_wavelength_m,
                                         oversample,
                                         holeshape,
                                         outdir=None)
        print("rotd_measured:", aff_best_rot)
        aff_best_rot.show(label="Measured ")
        # you have to re-initialize an InstrumentData.NIRISS object with the
        # best rotation affine parameter now in order to use it in further data reduction

        if 'Monochromatic' in self.filter_name:
            nirissdata = InstrumentData.NIRISS(filt=self.filter,
                                               affine2d=aff_best_rot)
            nirissdata.wls = [self.monochromatic_wavelength_m]
            print((nirissdata.wls))

        ff = nrm_core.FringeFitter(nirissdata,
                                   oversample=oversample,
                                   savedir=self.savedir,
                                   datadir=datadir,
                                   npix=n_image,
                                   interactive=False,
                                   hold_centering=True)
        print(('FringeFitter oversampling: %d' % ff.oversample))

        threads = 1
        ff.fit_fringes([filename])

        CP_file = sorted(
            glob.glob(
                os.path.join(datadir,
                             '%s/%s*.txt' % (filename.split('.')[0], 'CPs_'))))
        print("CP_file: ", type(CP_file), len(CP_file))
        CP = Table.read(CP_file[0],
                        format='ascii.no_header',
                        names=({'closure_phase'}))

        #         perform the actual test
        self.assertTrue(
            np.mean(np.array(CP['closure_phase'])) < 1e-7,
            'Simulated closure phases of point source are non-zero'
        )  # Avoiding hex singularity in hextransformEE.py causes this sort of noise in exactly-XYaligned PSF 2018 AS