Beispiel #1
0
    def spectrumAllData(self, data_file_path):
        '''
        Parameters
        ----------
        data_file_path: string
                measurement data folder

        Returns
        -------
        spe_tip: numpy array
            spectrum obtained by fft of tip data
        freq_tip: numpy array
            frequency obtained by fft of tip data
        spe_tilt: numpy array
            spectrum obtained by fft of tilt data
        freq_tilt: numpy array
            frequency obtained by fft of tilt data
        '''
        list = glob.glob(os.path.join(data_file_path, '*.h5'))
        coef_tilt_list = []
        coef_tip_list = []
        for i in range(len(list)):
            name = 'img_%04d.h5' % i
            print(name)
            file_name = os.path.join(data_file_path, name)
            start_image = self._ic.from4D(file_name)
            coef, mat = zernike.zernikeFit(start_image, np.array([2, 3]))
            coef_tip_list.append(coef[0])
            coef_tilt_list.append(coef[1])
        tip = np.array(coef_tip_list)
        tilt = np.array(coef_tilt_list)

        spe_tip, freq_tip = self._fft(tip)
        spe_tilt, freq_tilt = self._fft(tilt)
        return spe_tip, freq_tip, spe_tilt, freq_tilt
Beispiel #2
0
def zernikeTipTiltCoefOnSingleImage(interf, masked_ima=None):
    """
    On single image returns the coefficients of tip and tilt both in Zernike of Noll
    and in units of the interferometer

    Parameters
    ----------
    interf: object
        interferometer object

    Other Parameters
    ---------------
    masked_ima: numpy masked array
        if it is not passed acquires the interferometer

    Returns
    -------
        tip_tilt: numpy array
                Zernike Noll coefficients
        i4d_coef: numpy array
                Interferometers values
    """
    if masked_ima is None:
        masked_ima = interf.acquire_phasemap(1)
    else:
        masked_ima = masked_ima
    coef, mat = zernike.zernikeFit(masked_ima, np.array([2, 3]))
    tip = -coef[0] / (633e-9) * np.sqrt(2)
    tilt = coef[1] / (633e-9) * np.sqrt(2)

    i4d_coef = fit(masked_ima)
    return np.array([tip, tilt]), i4d_coef
Beispiel #3
0
    def piston_noise(self, data_file_path):
        ''' Remove tip and tilt from image and average the results
        .. dovrei vedere una variazione nel tempo

        Parameters
        ----------
            data_file_path: string
                            measurement data folder

        Returns
        -------
            mean: numpy array
                vector containing images's mean
            time: numpy array
                vector of the time at which the image were taken
        '''
        list = glob.glob(os.path.join(data_file_path, '*.h5'))
        image_number = len(list)
        time = np.arange(image_number) * (1 / 27.58)

        mean_list = []
        for j in range(image_number):
            name = 'img_%04d.h5' % j
            file_name = os.path.join(data_file_path, name)
            image = self._ic.from4D(file_name)
            zernike_coeff_array, mat = zernike.zernikeFit(
                image, np.array([2, 3]))
            sur = zernike.zernikeSurface(image, zernike_coeff_array, mat)
            image_ttr = image - sur
            mean = image_ttr.mean()
            mean_list.append(mean)

        spe, freq = self._fft(mean)
        return np.array(mean_list), time, spe, freq
Beispiel #4
0
    def _createCubeTTrFromCube(self, fitEx=None):
        # ci mette un eternit a fare l estenzione dell immagine
        #cube = self._readCube()
        cube_ttr = None
        if fitEx is None:
            for i in range(self._cube.shape[2]):
                image = self._cube[:, :, i]
                coef, mat = zernike.zernikeFit(image, np.array([2, 3]))
                surf = zernike.zernikeSurface(image, coef, mat)
                image_ttr = image - surf
                if cube_ttr is None:
                    cube_ttr = image_ttr
                else:
                    cube_ttr = np.ma.dstack((cube_ttr, image_ttr))
        else:
            for i in range(self._cube.shape[2]):
                coef, interf_coef = tip_tilt_interf_fit.fit(self._cube[:, :, i])
                image_ttr = self._ttd.ttRemoverFromCoeff(coef, self._cube[:, :, i])
                if cube_ttr is None:
                    cube_ttr = image_ttr
                else:
                    cube_ttr = np.ma.dstack((cube_ttr, image_ttr))

        self._saveCube(cube_ttr, 'Total_Cube_ttr.fits')
        return cube_ttr
Beispiel #5
0
    def tiptilt_series(self, data_file_path):
        ''' Remove tip and tilt from image and average the results
        .. dovrei vedere una variazione nel tempo

        Parameters
        ----------
            data_file_path: string
                            measurement data folder

        Returns
        -------
            mean: numpy array
                vector containing images's mean
            time: numpy array
                vector of the time at which the image were taken
        '''
        list = glob.glob(os.path.join(data_file_path, '*.h5'))
        image_number = len(list)
        time = np.arange(image_number) * (1 / 27.58)

        tt_list = []
        for j in range(image_number):
            name = 'img_%04d.h5' % j
            file_name = os.path.join(data_file_path, name)
            image = self._ic.from4D(file_name)
            coeff, mat = zernike.zernikeFit(image, np.array([1, 2, 3]))

            tt_list.append(coeff)

        tt = np.array(tt_list)

        return tt
Beispiel #6
0
    def testZernikeOnPar(self, image):
        '''
        Parameters
        ----------
        image: numpy masked array
            image to test

        Returns
        -------
        coef1:
        coef2:
        '''
        from m4.ground import zernike
        x, y = self.fiduciali(image)
        centro, axs, raggio = self._fitEllipse(x, y)
        pxs = raggio / OttParameters.RADIUS_FIDUCIAL_POINT
        par_radius = pxs * OttParameters.parab_radius
        #         import pdb
        #         pdb.set_trace()
        circle = self._drawCircle(centro, par_radius, image)
        ima = np.ma.masked_array(image, mask=np.invert(circle.astype(bool)))
        coef1, mat = zernike.zernikeFit(ima, np.arange(10) + 1)

        xx, yy = self.coord(image, centro, raggio)
        mm = (circle == 1)
        coef2 = zernike._surf_fit(xx[mm], yy[mm], image.data[mm],
                                  np.arange(10) + 1)
        return coef1, coef2
Beispiel #7
0
    def _zernikeCoeffCalculator(self, img):
        """
        Returns:
                final_coef = zernike coeff on the image
                            (zernike modes 2,3,4,7,8)
                final_coef_selected = zernike selected using intMatModesVector (zernike2control)
        """
        if fold_name.simulated == 1:
            mask_index = OtherParameters.MASK_INDEX_SIMULATORE
        else:
            mask_index = OtherParameters.MASK_INDEX_TOWER
        r = ROI()
        roi = r.roiGenerator(img)
        mask = roi[mask_index]
        mm = np.ma.mask_or(img.mask, mask)

        new_image = np.ma.masked_array(img, mask=mm)
        coef, mat = zernike.zernikeFit(new_image, np.arange(10) + 1)
        z = np.array([1, 2, 3, 6, 7])
        all_final_coef = coef[z]

        if self._intMatModesVector is None:
            final_coef_selected = all_final_coef
        else:
            final_coef_selected = np.zeros(self._intMatModesVector.size)
            for i in range(self._intMatModesVector.size):
                final_coef_selected[i] = all_final_coef[
                    self._intMatModesVector[i]]
        return all_final_coef, final_coef_selected
Beispiel #8
0
    def longTerm_rmsConvection(self):
        where = fold_name.OPD_SERIES_ROOT_FOLDER
        #where = '/mnt/m4storage/Data/M4Data/OPTData/OPD_series/'
        #where = '/home/labot/data/M4/Data/M4Data/OPTData/OPD_series'
        path = os.path.join(where, self.tt)
        D1 = sorted(glob.glob(os.path.join(path, '*.fits')))
        #D = D1[0:-np.int(len(D1)/8)]
        D = D1[0:-2]

        cube = None
        for name in D:
            print(name)
            image = read_data.readFits_maskedImage(name)
            if cube is None:
                cube = image
            else:
                cube = np.ma.dstack((cube, image))
        mean = np.ma.mean(cube, axis=2)

        rms_list = []
        for i in range(cube.shape[2]):
            #print(i)
            ima = cube[:, :, i] - mean
            coef, mat = zernike.zernikeFit(ima, np.arange(8) + 1)
            surf = zernike.zernikeSurface(ima, coef, mat)
            new_ima = ima - surf
            rms = new_ima.std()
            rms_list.append(rms)

        rms = np.array(rms_list)
        x = np.arange(rms.size)
        x_list = []
        for i in range(rms.size):
            aa = D[i].split('_')[-1]
            tt = aa.split('.')[0]
            x_list.append(tt)
        x_time = np.array(x_list)
        ntick = 11
        plt.figure(figsize=(10, 6))
        plt.plot(x, rms, '-')
        plt.xticks(x, x_time[::len(x_time) / ntick], rotation=45)
        plt.locator_params(nbins=ntick, axis='x', tight=True)
        plt.ylabel('rms[m]')
        plt.title('%s' % self.tt)

        results_path = os.path.join(fold_name.OUT_FOLDER, 'LongTermStability')
        dove = os.path.join(results_path, self.tt)
        if os.path.exists(dove):
            dove = dove
        else:
            os.makedirs(dove)
        name = os.path.join(dove, 'rmsMeanDiff.fits')
        pyfits.writeto(name, rms, overwrite=True)

        name = os.path.join(dove, '%s-rms.png' % self.tt)
        if os.path.isfile(name):
            os.remove(name)
        plt.savefig(name)
        return rms
Beispiel #9
0
    def testZernike(self):
        img = np.random.rand(500, 500)
        mask = np.ones((500, 500), dtype=bool)
        rr, cc = circle(250, 250, 100)
        mask[rr, cc] = 0
        masked_ima = np.ma.masked_array(img, mask=mask)

        coef, mat = zernike.zernikeFit(masked_ima, np.arange(10) + 1)
        zernike.zernikeSurface(masked_ima, coef, mat)
Beispiel #10
0
    def tipTiltVSTime(self, data_file_path, start, stop):
        '''
        Attenzione: questa funzione vuole il file path 
        '''
        last_name = data_file_path.split('/')[-1]
        if last_name == 'hdf5':
            list_tot = glob.glob(os.path.join(data_file_path, '*.h5'))
            tt = data_file_path.split('/')[-2]
            ext = 1
        else:
            list_tot = glob.glob(os.path.join(data_file_path, '*.fits'))
            tt = data_file_path.split('/')[-1]
            ext = 0

        list_tot.sort()
        list = list_tot[start:stop]

        if last_name == 'hdf5':
            time = np.arange(0, len(list)) * 1 / 27.58
        else:
            time = 'calcolare dal tt'

        tip_tilt = []
        for name in list:
            image = read_data.read_phasemap(name, ext)
            coef, mat = zernike.zernikeFit(image, np.array([1, 2, 3]))
            tip_tilt.append(coef)

        tip = np.array(tip_tilt)[:, 1]
        tilt = np.array(tip_tilt)[:, 2]
        #PLOT
        plt.figure(figsize=(10, 6))
        plt.plot(time, tip * 1e9, label='TIP')
        plt.plot(time, tilt * 1e9, label='TILT')
        plt.legend()
        plt.title(tt)
        plt.ylabel('zernike coef [nm]')
        plt.xlabel('time [s]')

        #SAVE
        results_path = os.path.join(fold_name.OUT_FOLDER, 'Noise')
        x = data_file_path.split("/")
        if last_name == 'hdf5':
            dove = os.path.join(results_path, x[len(x) - 2])
        else:
            dove = os.path.join(results_path, x[len(x) - 1])
        if os.path.exists(dove):
            dove = dove
        else:
            os.makedirs(dove)
        name = os.path.join(dove, 'tipTilt_time.png')
        if os.path.isfile(name):
            os.remove(name)
        plt.savefig(name)

        return np.array(tip_tilt), time
Beispiel #11
0
    def diffOpticalMonitoring(self, n_images, delayshort, delaylong):
        '''
        # Fa due misure poco distanti tra loro e poi aspetta tanto
        Parameters
        ----------
        n_images: int
            number of images to acquire
        delayshort: float
            time gap between images couple
        delaylong: float
            time gap between images couple
        Returns
        ------
        tt: string
            tracking number of measurements
        '''
        store_in_folder = fold_name.OPD_SERIES_ROOT_FOLDER
        dove, tt = tracking_number_folder.createFolderToStoreMeasurements(
            store_in_folder)

        zer_list = []
        temp_list = []
        t0 = time.time()
        for i in range(n_images):
            for i in range(2):
                ti = time.time()
                dt = ti - t0
                masked_ima = self._interf.acquire_phasemap(1)
                temp_vect = self._ott.temperature.getTemperature()
                name = Timestamp.now() + '.fits'
                fits_file_name = os.path.join(dove, name)
                pyfits.writeto(fits_file_name, masked_ima.data)
                pyfits.append(fits_file_name, masked_ima.mask.astype(int))

                coef, mat = zernike.zernikeFit(masked_ima, np.arange(10) + 1)
                vect = np.append(dt, coef)
                zer_list.append(vect)
                temp_list.append(temp_vect)

                fits_file_name = os.path.join(dove, 'zernike.fits')
                pyfits.writeto(fits_file_name,
                               np.array(zer_list),
                               overwrite=True)
                fits_file_name = os.path.join(dove, 'temperature.fits')
                pyfits.writeto(fits_file_name,
                               np.array(temp_list),
                               overwrite=True)
                print('Waiting for next frame in pair')
                time.sleep(delayshort)

            print('Waiting for next iterations')
            time.sleep(delaylong)

        return tt
Beispiel #12
0
def diffPiston(image):
    '''
    Parameters
    ----------
        image: masked array
            image for the analysis

    Returns
    -------
        diff_piston: numpy masked array
    '''
    dimx = image.shape[0]
    dimy = image.shape[1]
    imas = image[:, 0:np.int(dimy / 2)]
    imad = image[np.int(dimx / 2):, :]

    coefs, mat = zernike.zernikeFit(imas, np.arange(3) + 1)
    coefd, mat = zernike.zernikeFit(imad, np.arange(3) + 1)
    diff_piston = coefs[0] - coefd[1]
    return diff_piston
Beispiel #13
0
    def tipTiltDetrend(self, image, roi, final_index, analysis_ind=None):
        """
        Parameters
        ----------
            image: numpy masked array
                    image to be analyzed
            roi: list
                roi of the image
            final_index: int
                    index of final roi
            analysis_index: nunpy array
                            index of roi to be used for
                            the analysis

        Returns
        -------
                image_ttr: numpy array
                         image without tip and tilt
        """
        roi_copy = np.copy(roi)
        self._logger.debug('Removal of tip-tilt from roi[%d]', final_index)
        self._totalMatList = []
        coefList = []
        for r in roi:
            if np.any(r == 0):
                imag = np.ma.masked_array(image.data, mask=r)
                ima = np.ma.MaskedArray.copy(imag)
                coef, mat = zernike.zernikeFit(ima, np.array([1, 2, 3]))
                self._totalMatList.append(mat[:, 1:])
                coefList.append(coef)

        if analysis_ind is None:
            analysis_ind = np.array([1, 2])  #from roi
            #coef_list = coefList
            #del coef_list[final_index]
        else:
            analysis_ind = analysis_ind
        coef_list = []
        for i in range(len(analysis_ind)):
            coef_list.append(coefList[analysis_ind[i]])

        piston, tip, tilt = np.average(coef_list, axis=0)

        surfcoef = np.array([tip, tilt])

        image_whit_tt = np.ma.masked_array(image.data, mask=roi[final_index])
        zernike_surface_to_subtract = zernike.zernikeSurface(
            image_whit_tt, surfcoef, self._totalMatList[final_index])
        image_ttr = image_whit_tt - zernike_surface_to_subtract
        return image_ttr
Beispiel #14
0
 def _tipTiltCalculator(self, cube):
     coef_tilt_list = []
     coef_tip_list = []
     for i in range(cube.shape[2]):
         image = cube[:, :, i]
         coef, mat = zernike.zernikeFit(image, np.array([2, 3]))
         coef_tip_list.append(-coef[0] / (633e-9) * np.sqrt(2))
         coef_tilt_list.append(coef[1] / (633e-9) * np.sqrt(2))
     tip = np.array(coef_tip_list)
     tilt = np.array(coef_tilt_list)
     #devo diventare angoli
     #mettendo la maschera
     #fare il plot di tip, tilt (plot isometrico:stesse dimensioni x y)
     return tip, tilt
Beispiel #15
0
    def _createInteractionMatrix(self, mask):
        coefList = []
        self._cube = self.getCube()
        for i in range(self._cube.shape[2]):
            ima = np.ma.masked_array(self._cube[:, :, i], mask=mask)
            coef, mat = zernike.zernikeFit(ima, np.arange(10) + 1)
            # z= np.array([2,3,4,7,8])
            z = np.array([1, 2, 3, 6, 7])
            final_coef = np.zeros(z.shape[0])
            final_coef = coef[z]
            self._mat = mat
            coefList.append(final_coef)

        self._intMat = np.zeros((coefList[0].shape[0], self._cube.shape[2]))
        for j in range(self._cube.shape[2]):
            self._intMat.T[j] = coefList[j]
Beispiel #16
0
def tiptilt_fit(ima):
    '''
    Parameters
    ----------
        image: masked array

    Returns
    -------
        ima_ttr: numpy masked array
            image without tip and tilt
    '''
    if ima is not None:
        coef, mat = zernike.zernikeFit(ima, np.array([2, 3]))
        surf = zernike.zernikeSurface(ima, coef, mat)
        new_image = ima - surf
        ima_ttr = np.ma.masked_array(new_image, mask=ima.mask)
        return ima_ttr
Beispiel #17
0
    def opticalMonitoring(self, n_images, delay):
        '''
        #monitora

        Parameters
        ----------
        n_images: int
            number of images to acquire
        delay: int [s]
            waiting time (in seconds) between two image acquisitions

        Returns
        ------
        tt: string
            tracking number of measurements
        '''
        store_in_folder = fold_name.OPD_SERIES_ROOT_FOLDER
        dove, tt = tracking_number_folder.createFolderToStoreMeasurements(
            store_in_folder)

        zer_list = []
        temp_list = []
        t0 = time.time()
        for i in range(n_images):
            ti = time.time()
            dt = ti - t0
            masked_ima = self._interf.acquire_phasemap(1)
            temp_vect = self._ott.temperature.getTemperature()
            name = Timestamp.now() + '.fits'
            fits_file_name = os.path.join(dove, name)
            pyfits.writeto(fits_file_name, masked_ima.data)
            pyfits.append(fits_file_name, masked_ima.mask.astype(int))

            coef, mat = zernike.zernikeFit(masked_ima, np.arange(10) + 1)
            vect = np.append(dt, coef)
            zer_list.append(vect)
            temp_list.append(temp_vect)

            fits_file_name = os.path.join(dove, 'zernike.fits')
            pyfits.writeto(fits_file_name, np.array(zer_list), overwrite=True)
            fits_file_name = os.path.join(dove, 'temperature.fits')
            pyfits.writeto(fits_file_name, np.array(temp_list), overwrite=True)

            time.sleep(delay)
        return tt
Beispiel #18
0
    def _rmsFromCube(self, cube_to_process):
        '''
        Parameters
        ----------
            cube_to_process: [pixel, pixel, number of imagescube]
                            cube generated by the analyzer_iffunctions

        Returns
        -------
            rms_mean: numpy array
                    rms averaged on the number of modes used in the iff's acquisition
            tip: numpy array
                tip averaged on the number of modes used in the iff's acquisition
            tilt: numpy array
                tilt averaged on the number of modes used in the iff's acquisition
        '''
        self._logger.debug('Calculation of rms, tip and tilt')
        rms_list = []
        coef_tilt_list = []
        coef_tip_list = []
        quad_list = []
        ptv_list = []
        for i in range(cube_to_process.shape[2]):
            image = cube_to_process[:, :, i]
            coef, mat = zernike.zernikeFit(image, np.array([1, 2, 3]))
            sur = zernike.zernikeSurface(image, coef, mat)
            image_ttr = image - sur
            ptv = np.max(image_ttr) - np.min(image_ttr)
            ptv_list.append(ptv)
            rms = image_ttr.std()
            rms_list.append(rms)
            coef_tip_list.append(coef[1])
            coef_tilt_list.append(coef[2])
            quad = np.sqrt(coef[1]**2 + coef[2]**2)
            quad_list.append(quad)
        ptv_vector = np.array(ptv_list)
        rms_vector = np.array(rms_list)
        tip = np.array(coef_tip_list).mean()
        tilt = np.array(coef_tilt_list).mean()
        quad_tt = np.array(quad_list).mean()
        rms_mean = np.mean(rms_vector)
        ptv_mean = np.mean(ptv_vector)
        return rms_mean, quad_tt, tilt, ptv_mean
Beispiel #19
0
    def validFrames(self):
        '''Create the plot of individual RMS of each frames
        (without tip/tilt) together with RMS of the average frame
        '''
        rs_img = self._readRsImg()
        coef, mat = zernike.zernikeFit(rs_img, np.array([2, 3]))
        surf = zernike.zernikeSurface(rs_img, coef, mat)
        rs_ttr = rs_img - surf
        r0 = rs_ttr.std()

        cube_ttr = self._readCube(1)
        rs_vect = np.zeros(cube_ttr.shape[2])
        for j in range(cube_ttr.shape[2]):
            rs_vect[j] = cube_ttr[:, :, j].std()

        plt.figure()
        plt.plot(np.arange(cube_ttr.shape[2]), rs_vect, label='Data'); plt.yscale('log')
        plt.plot(np.zeros(cube_ttr.shape[2]) + r0, label='Average')
        plt.ylabel('m RMS'); plt.xlabel('# frames')
        plt.title('Images WFE'); plt.legend()
Beispiel #20
0
    def parTiltTest(self, act, val_vec):
        '''
        Parameters
        ----------
        act: int
            number of the actuator to move
        val_vec: int
            value to assignee to actuator

        Returns
        -------
        quad: numpy array
            vector of rss
        coef: numpy array
            vector of zernike coefficients of image-difference
        image0: numpy masked array
            start image
        delta_list: list
            different from start image
        '''
        image0 = self._interf.acquire_phasemap(10)
        delta_list = []
        sum_list = []
        coef_list = []
        for i in range(val_vec.size):
            self._opc._setAct(act, val_vec[i])
            image = self._interf.acquire_phasemap(10)
            delta = image - image0
            delta_list.append(delta)
            coef, mat = zernike.zernikeFit(delta, np.arange(10) + 1)
            coef_list.append(coef)
            sum = np.sqrt(coef[1]**2 + coef[2]**2)
            sum_list.append(sum)
        quad = np.array(sum_list)
        plt.plot(val_vec, quad, '-o')
        return quad, np.array(coef_list), image0, delta_list
Beispiel #21
0
    def alignTest(self, tt, n_images, perturbation_vec, pre=False):
        '''
        Parameters
        ---------
        tt: string
            tracking number for the alignment
        n_images: int
            number of frames for the interferometer
        perturbation_vec: numpy array
            np.array([par_focus, par_tilt, par_tip])

        Other Parameters
        ----------------
        pre: boolean
            if True a pre-tiptilt alignment before the 5 dof one

        Returns
        -------
        coeff_matrix: numpy array
            zernike coefficients matrix for all the images
        tt: string
            tracking number of measurements
        '''
        # Homing the system
        self._ottca.par_and_rm_aligner(True, tt, n_images, np.array([0, 1]),
                                       np.array([3, 4]))
        #a.ott_alignment(n_images, 1, np.array([0,1]), np.array([3,4]), tt)
        par0 = self._ott.parabola.getPosition()
        rm0 = self._ott.referenceMirror.getPosition()
        # Set perturbation from perturbation_vec
        focus = perturbation_vec[0]
        tip = perturbation_vec[1]
        tilt = perturbation_vec[2]
        par1 = np.copy(par0)
        par1[2] += focus
        par1[3] += tip
        par1[4] += tilt
        rm1 = np.copy(rm0)
        rm1[3] += -tip * 2.05
        rm1[4] += -tilt * 2.05
        # Initialization
        zern_vec = np.arange(1, 12, 1)
        coeff = []
        # Start image, perturbation and perturbed image
        image = self._interf.acquire_phasemap(n_images)
        pippo = zernike.zernikeFit(image, zern_vec)
        coeff.append(pippo[0])
        self._ott.parabola.setPosition(par1)
        self._ott.referenceMirror.setPosition(rm1)
        image = self._interf.acquire_phasemap(n_images)
        pippo = zernike.zernikeFit(image, zern_vec)
        coeff.append(pippo[0])
        # TipTilt pre-alignment
        if pre is True:
            self._ottca.par_and_rm_aligner(True, tt, n_images, np.array([0,
                                                                         1]),
                                           np.array([3, 4]))
            #a.ott_alignment(n_images, 1, np.array([0,1]), np.array([3,4]), tt)
            image = self._interf.acquire_phasemap(2)
            pippo = zernike.zernikeFit(image, zern_vec)
            coeff.append(pippo[0])
        # First alignment
        self._ottca.par_and_rm_aligner(True, tt, n_images, np.array([0, 1]),
                                       np.array([3, 4]))
        #a.ott_alignment(n_images, 1, np.array([0,1,2,3,4]), np.array([0,1,2,3,4]), tt)
        image = self._interf.acquire_phasemap(2)
        pippo = zernike.zernikeFit(image, zern_vec)
        coeff.append(pippo[0])
        # Second alignment
        self._ottca.par_and_rm_aligner(True, tt, n_images, np.array([0, 1]),
                                       np.array([3, 4]))
        #a.ott_alignment(n_images, 1, np.array([0,1]), np.array([3,4]), tt)
        image = self._interf.acquire_phasemap(n_images)
        pippo = zernike.zernikeFit(image, zern_vec)
        coeff.append(pippo[0])
        # Check image
        image = self._interf.acquire_phasemap(n_images)
        pippo = zernike.zernikeFit(image, zern_vec)
        coeff.append(pippo[0])

        coeff_matrix = np.array(coeff) * 1e9
        parend = self._ott.parabola.getPosition()

        store_in_folder = os.path.join(fold_name.REPEATABILITY_ROOT_FOLDER,
                                       'Alignment')
        dove, tt = tracking_number_folder.createFolderToStoreMeasurements(
            store_in_folder)
        fits_file_name = os.path.join(dove, 'zernike.fits')
        pyfits.writeto(fits_file_name, coeff_matrix, overwrite=True)

        print(parend - par0)
        return coeff_matrix, tt
Beispiel #22
0
    def analysis_whit_structure_function(self,
                                         data_file_path,
                                         tau_vector,
                                         h5_or_fits=None):
        '''
        .. 4000 = total number of image in hdf5

        Parameters
        ----------
            data_file_path: string
                            measurement data folder
            tau_vector: numpy array
                        vector of tau to use

        Other Parameters
        ----------------
        h5_or_fits: if it is none the h5 data analysis is performed

        Returns
        -------
            rms_medio: numpy array
                    calculated on the difference of the images (distant tau)
            quad_med: numpy array
                     squaring sum of tip and tilt calculated on the difference
                    of the images
        '''
        if h5_or_fits is None:
            list = glob.glob(os.path.join(data_file_path, '*.h5'))
        else:
            listtot = glob.glob(os.path.join(data_file_path, '*.fits'))
            listtot.sort()
            list = listtot[0:-2]
        image_number = len(list)
        i_max = np.int((image_number - tau_vector[tau_vector.shape[0] - 1]) /
                       (tau_vector[tau_vector.shape[0] - 1] * 2))
        if i_max <= 10:
            raise OSError('tau = %s too large. i_max = %d' %
                          (tau_vector[tau_vector.shape[0] - 1], i_max))
        rms_medio_list = []
        quad_med_list = []
        for j in range(tau_vector.shape[0]):
            dist = tau_vector[j]
            print(dist)
            rms_list = []
            quad_list = []
            for i in range(i_max):
                k = i * dist * 2
                if h5_or_fits is None:
                    #k = i * dist * 2
                    name = 'img_%04d.h5' % k
                    file_name = os.path.join(data_file_path, name)
                    image_k = self._ic.from4D(file_name)
                    name = 'img_%04d.h5' % (k + dist)
                    file_name = os.path.join(data_file_path, name)
                    image_dist = self._ic.from4D(file_name)
                else:
                    image_k = read_data.readFits_maskedImage(list[k])
                    image_dist = read_data.readFits_maskedImage(list[k + dist])

                image_diff = image_k - image_dist
                zernike_coeff_array, mat = zernike.zernikeFit(
                    image_diff, np.array([2, 3]))
                sur = zernike.zernikeSurface(image_diff, zernike_coeff_array,
                                             mat)
                image_ttr = image_diff - sur
                quad = np.sqrt(zernike_coeff_array[0]**2 +
                               zernike_coeff_array[1]**2)

                rms = image_ttr.std()
                rms_list.append(rms)
                quad_list.append(quad)
            rms_vector = np.array(rms_list)
            aa = rms_vector.mean()
            rms_medio_list.append(aa)
            quad_med_list.append(np.array(quad_list).mean())
        rms_medio = np.array(rms_medio_list)
        quad_med = np.array(quad_med_list)

        # per calcolo statistical amplitude of convention
        n_meas = rms_vector.shape[0] * 2 * tau_vector.shape[0]

        return rms_medio, quad_med, n_meas
Beispiel #23
0
    def parPistonTest(self, piston_value, deltapos_filepath, amp,
                      tt_for_align):
        '''
        Parameters
        ----------
        piston_value: int
            relative value for the parab piston
        deltapos_filepath: string
            file path for par and rm delta positions
        amp: float
            tip tilt amplitude for par and rm
        tt_for_align: string
            tracking number for alignment

        Returns
        -------
        tt: string
            tracking number of measurements
        '''
        # '/home/m4/pardeltapos.fits'
        hduList = pyfits.open(deltapos_filepath)
        deltapos = hduList[0].data
        dx = deltapos[:, 0] * amp
        dy = deltapos[:, 1] * amp
        dove, tt = tracking_number_folder.createFolderToStoreMeasurements(
            fold_name.PISTON_TEST_ROOT_FOLDER)
        par0 = self._ott.parabola.getPosition()
        rm0 = self._ott.referenceMirror.getPosition()
        n_frames_meas = 10
        n_frames_alignment = 3
        rmcoeff = -2.04

        coef_list = []
        par_list = []
        rm_list = []
        for i in range(dx.size):
            if i == 0:
                print('Iteration 0')
            else:
                print('Iteration %d' % i)
                par_new = par0.copy()
                rm_new = rm0.copy()
                par_new[3] += dx[i]
                rm_new[3] += rmcoeff * dx[i]
                par_new[4] += dy[i]
                rm_new[4] += rmcoeff * dy[i]
                self._ott.parabola.setPosition(par_new)
                self._ott.referenceMirror.setPosition(rm_new)
                par_cmd, rm_cmd = self._ottca.par_and_rm_aligner(
                    True, tt_for_align, n_frames_alignment, np.array([0, 1]),
                    np.array([3, 4]))
#                 a.ott_alignment(n_frames_alignment, 1,
#                                                   np.array([0, 1]),
#                                                   np.array([3, 4]),
#                                                   tt_for_align)

            par = self._ott.parabola.getPosition()
            rm = self._ott.referenceMirror.getPosition()
            par_list.append(par)
            rm_list.append(rm)
            masked_ima0 = self._interf.acquire_phasemap(n_frames_meas)
            par[2] += piston_value
            self._ott.parabola.setPosition(par)
            masked_ima1 = self._interf.acquire_phasemap(n_frames_meas)
            par[2] -= piston_value
            self._ott.parabola.setPosition(par)
            diff = masked_ima1 - masked_ima0
            name = 'diff_%04d.fits' % i
            self._interf.save_phasemap(dove, name, diff)
            coef, mat = zernike.zernikeFit(diff, np.arange(10) + 1)
            coef_list.append(coef)

            fits_file_name = os.path.join(dove, 'Zernike.fits')
            pyfits.writeto(fits_file_name, np.array(coef_list), overwrite=True)
            fits_file_name = os.path.join(dove, 'PAR_Positions.fits')
            pyfits.writeto(fits_file_name, np.array(par_list), overwrite=True)
            fits_file_name = os.path.join(dove, 'RM_Positions.fits')
            pyfits.writeto(fits_file_name, np.array(rm_list), overwrite=True)
        return tt
Beispiel #24
0
def robustImageFromDataSet(n_images,
                           data_file_path,
                           zernike_vector_to_subtract,
                           offset=None):
    ''' From fits files and whit offset subtraction

    Parameters
    ----------
    n_images: int
        number of images to analyze
    path: string
        total path for data analysis

    Other Parameters
    ----------------
    offset: if it is None data analysis is made by split n_images in two
            else re-reads the offset image saved in the tt folder and subtracts it
            to each image during cube creation

    Returns
    -------
    robust_image: numpy masked array
        robust image from data set
    '''
    last_name = data_file_path.split('/')[-1]
    if last_name == 'hdf5':
        list_tot = glob.glob(os.path.join(data_file_path, '*.h5'))
        tt = data_file_path.split('/')[-2]
        ext = 1
    else:
        list_tot = glob.glob(os.path.join(data_file_path, '*.fits'))
        tt = data_file_path.split('/')[-1]
        ext = 0

    list_tot.sort()
    list = list_tot[0:n_images]
    if offset is None:
        half = np.int(len(list) / 2)
        list1 = list[0:half]
        list2 = list[half:]

        cube1 = None
        print('Creating cube 1')
        for name in list1:
            #print(name)
            image = read_data.read_phasemap(name, ext)
            if cube1 is None:
                cube1 = image
            else:
                cube1 = np.ma.dstack((cube1, image))

        cube2 = None
        print('Creating cube 2')
        for name in list2:
            #print(name)
            image = read_data.read_phasemap(name, ext)
            if cube2 is None:
                cube2 = image
            else:
                cube2 = np.ma.dstack((cube1, image))

        mean1 = np.ma.mean(cube1, axis=2)
        mean2 = np.ma.mean(cube2, axis=2)

        final_image = mean2 - mean1

    else:
        fits_file_name = os.path.join(config.OUT_FOLDER, 'Req', tt,
                                      'OptOffset.fits')
        image_optOffset = read_data.readFits_maskedImage(fits_file_name)

        cube = None
        print('Creating cube')
        for name in list:
            #print(name)
            ima = read_data.read_phasemap(name, ext)
            image = ima - image_optOffset
            if cube is None:
                cube = image
            else:
                cube = np.ma.dstack((cube, image))
        final_image = np.ma.mean(cube, axis=2)

    coef, mat = zernike.zernikeFit(final_image, zernike_vector_to_subtract)
    surf = zernike.zernikeSurface(final_image, coef, mat)
    image_ttr = final_image - surf
    return image_ttr
Beispiel #25
0
    def scanAstigmComa(self, stepamp, nstep, nframes=10):  # by RB 20210117.
        '''
        Parameters
        ----------
        stepamp: int
            amplitude for tip and tilt
        nstep: int
            number of step measurements
        nframes: int
            number of interferometr's frames

        Returns
        ------
        tt: string
            tracking number of measurements
        '''
        # goal: to measure coma and astigmatism at different PAR position, spanning 500 arcsec
        store_in_folder = fold_name.CALIBRATION_ROOT_FOLDER
        dove, tt = tracking_number_folder.createFolderToStoreMeasurements(
            store_in_folder)
        par2rm = -2.05
        zern_vect = []
        parpos = []
        rmpos = []
        par0 = self._ott.parabola.getPosition()
        rm0 = self._ott.referenceMirror.getPosition()
        n2move = np.array([3, 4])
        thedirection = np.array([-1, 1])
        n_frames_alignment = 3
        tt_for_align = '20210111_152430'

        for k in n2move:
            for v in thedirection:

                for i in range(nstep):
                    par1 = par0.copy()
                    parmove = stepamp * i * v
                    par1[k] += parmove
                    print('Moving PAR[%d] by %d' % (k, parmove))
                    self._ott.parabola.setPosition(par1)
                    rm1 = rm0.copy()
                    rmmove = stepamp * i * v * par2rm
                    rm1[k] += rmmove
                    self._ott.referenceMirror.setPosition(rm1)
                    print('Moving RM[%d] by %d' % (k, rmmove))
                    par_cmd, rm_cmd = self._ottca.par_and_rm_aligner(
                        True, tt_for_align, n_frames_alignment,
                        np.array([0, 1]), np.array([3, 4]))
                    #                     a.ott_alignment(n_frames_alignment, 1,
                    #                                                       np.array([0, 1]),
                    #                                                       np.array([3, 4]),
                    #                                                       tt_for_align)
                    par2 = self._ott.parabola.getPosition()
                    rm2 = self._ott.referenceMirror.getPosition()
                    masked_ima = self._interf.acquire_phasemap(nframes)
                    name = Timestamp.now() + '.fits'
                    fits_file_name = os.path.join(dove, name)
                    pyfits.writeto(fits_file_name, masked_ima.data)
                    pyfits.append(fits_file_name, masked_ima.mask.astype(int))

                    coef, mat = zernike.zernikeFit(masked_ima,
                                                   np.arange(10) + 1)
                    zern_vect.append(coef)
                    parpos.append(par2)
                    rmpos.append(rm2)

                    fits_file_name = os.path.join(dove, 'zernike.fits')
                    pyfits.writeto(fits_file_name,
                                   np.array(zern_vect),
                                   overwrite=True)
                    fits_file_name = os.path.join(dove, 'PAR_positions.fits')
                    pyfits.writeto(fits_file_name,
                                   np.array(parpos),
                                   overwrite=True)
                    fits_file_name = os.path.join(dove, 'RM_positions.fits')
                    pyfits.writeto(fits_file_name,
                                   np.array(rmpos),
                                   overwrite=True)

        self._ott.parabola.setPosition(par0)
        self._ott.referenceMirror.setPosition(rm0)
        return tt