Пример #1
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
Пример #2
0
    def createCube_forTestDataInOpdImages(self):
        tt = '20191210_143625'
        fold = os.path.join(Configuration.OPD_DATA_FOLDER,
                            'OPDImages', tt, 'hdf5')

        hduList = pyfits.open(os.path.join(fold, 'ampVect.fits'))
        self._cmdAmplitude = hduList[0].data
        hduList = pyfits.open(os.path.join(fold, 'modeRange.fits'))
        self._actsVector = hduList[0].data
        hduList = pyfits.open(os.path.join(fold, 'template.fits'))
        vector_of_push_pull = hduList[0].data

        cube = None
        tip_til_det = TipTiltDetrend()
        r = ROI()
#         for i in range(self._actsVector.shape[0]):
        for i in range(7):
            k = i * vector_of_push_pull.shape[0]
            imaList = []
            for j in range(vector_of_push_pull.shape[0]):
                l = k + j
                file_name = os.path.join(fold, 'img_%04d.h5') %l
                img = self._ic.from4D(file_name)
                roi = r.roiGenerator(img)
                ima_tt = tip_til_det.tipTiltRemover(img, roi, 3)
                imaList.append(ima_tt)

            image = imaList[0] + imaList[1] - imaList[2]

            if cube is None:
                cube = image
            else:
                cube = np.ma.dstack((cube, image))

        return cube
Пример #3
0
    def createCubeFromImageFolder(self, data_file_path, tiptilt_detrend=None, phase_ambiguity=None):
        cube_all_act = None
        where = self._indexReorganization()
        ampl_reorg = self._amplitudeReorganization(self._actsVector,
                                                   self._indexingList,
                                                   self._cmdAmplitude,
                                                   self._nPushPull)
        for i in range(self._actsVector.shape[0]):
            for k in range(self._nPushPull):
                p = self._nPushPull * i + k
                n = where[p][0][0]
                mis_amp = k* self._indexingList.shape[1] + n
                mis = k * self._indexingList.shape[1] * self._template.shape[0] \
                        + n * self._template.shape[0]

                name = 'img_%04d.h5' %mis
                file_name = os.path.join(data_file_path, name)
                image_for_dim = self._ic.from4D(file_name)

                image_sum = np.zeros((image_for_dim.shape[0],
                                     image_for_dim.shape[1]))
                for l in range(1, self._template.shape[0]):
                    name = 'img_%04d.h5' %(mis+l)
                    file_name = os.path.join(data_file_path, name)
                    ima = self._ic.from4D(file_name)
                    image = image_sum + ima * self._template[l]
                img_if = image / (2 * ampl_reorg[mis_amp] * (self._template.shape[0] - 1))
                if tiptilt_detrend is None:
                    img_if = img_if
                else:
                    r = ROI()
                    roi = r.roiGenerator(img_if)
                    tt = TipTiltDetrend()
                    img_if = tt.tipTiltRemover(img_if, roi, 3)

                if_push_pull_kth = img_if-np.ma.median(img_if)

                if k == 0:
                    all_push_pull_act_jth = if_push_pull_kth
                else:
                    all_push_pull_act_jth = np.ma.dstack((all_push_pull_act_jth,
                                                          if_push_pull_kth))

            if self._nPushPull == 1:
                if_act_jth = all_push_pull_act_jth
            else:
                if_act_jth = np.ma.mean(all_push_pull_act_jth, axis=2)

            if cube_all_act is None:
                cube_all_act = if_act_jth
            else:
                cube_all_act = np.ma.dstack((cube_all_act, if_act_jth))
        self._cube = cube_all_act

        return self._cube
Пример #4
0
 def __init__(self, analyzerIFFunctions):
     """The constructor:
         analyzerIFFunctions = analyzer object to use
     """
     self._logger = logging.getLogger('FLATTENING:')
     self._an = analyzerIFFunctions
     self._who = self._an._who
     self._roi = ROI()
     self._mirror = DMirror()
     self._command = None
     self._flatteningWf = None
Пример #5
0
 def _findMask(self, cube):
     ima = cube[:, :, 0]
     from m4.utils.roi import ROI
     r = ROI()
     roi = r.roiGenerator(ima)
     if fold_name.simulated == 1:
         mask_index = OtherParameters.MASK_INDEX_SIMULATORE
     else:
         mask_index = OtherParameters.MASK_INDEX_TOWER
     mask = roi[mask_index]
     return mask
Пример #6
0
 def __init__(self, ott, interf):
     """The constructor """
     self._logger = logging.getLogger('ALIG_ZER:')
     self._ott = ott
     self._interf = interf
     self._cal = OpticalCalibration(ott, interf)
     self._tt = None
     self._roi = ROI()
Пример #7
0
    def analyzerCalibrationMeasurement(self, tt, mask_index):
        '''
        args:
            tt = tracking number of the measures to be analysed
            mask_index = int the reference mirror mask index

        returns:
                self_intMat = interation matrix
                self._rec = reconstructor
        '''
        a = opt_calibration.loadCommandMatrixFromFits(tt)
        a.createCube(tt)
        cube = a.getCube()
        ima = cube[:, :, 0]
        from m4.utils.roi import ROI
        r = ROI()
        roi = r.roiGenerator(ima)
        mask = roi[mask_index]
        dove = os.path.join(self._storageFolder(), tt)
        self._saveMask(dove, mask)
        self._intMat = a.getInteractionMatrix(mask)
        self._rec = a.getReconstructor(mask)
        self._saveIntMatAndRec(dove)
        return self._intMat, self._rec
Пример #8
0
 def __init__(self):
     """The constructor """
     self._roi = ROI()
     self._lambda = Interferometer.WAVEL
     self._n = None
Пример #9
0
class PhaseSolve():
    """
    Class...
    una immagine dell'interferemotro che mette un lamba mezzi tra due superfici se non ho pistone
    se ho il pistone seguo la variazione di pistone (tipo 2 nanometri, pi+ piccolo di lamba mezzi)
    quindi le due immagini possono essere rimesse insieme usando questa condizione. 
    Devo riportare a fare differenziale zero le due immagini
    deve lavorare su una coppia di immagini e confrontarle con una soglia

    terzo caso: ho una misura e nessuna condizione, cioè la misura delle spl. 
    Vince la misura di interferometro se sono vicini, se sono lontani.
    """
    def __init__(self):
        """The constructor """
        self._roi = ROI()
        self._lambda = Configuration.LAMBDA
        self._n = None

    def n_calculator(self, spl_values):
        n = np.zeros(spl_values.shape[0])
        for i in range(spl_values.shape[0]):
            n[i] = (2. * spl_values[i]) / self._lambda
        self._n = n
        return self._n

    def m4PhaseSolver(self, m4_ima, spl_values):
        self.n_calculator(spl_values)
        roiList = self._roi.roiGenerator(m4_ima)
        m4_new_image = None

        media = []
        imgList = []
        for roi in roiList:
            imgg = np.ma.masked_array(m4_ima.data, mask=roi)
            m = imgg.mean()
            media.append(m)
            imgList.append(imgg)

        aa = np.arange(self._n.shape[0])
        zipped = zip(aa, imgList)
        img_phase_solve_list = []
        for i, imgg in zipped:
            img_phase_solve = np.ma.masked_array(imgg.data - self._n[i],
                                                 mask=imgg.mask)
            img_phase_solve_list.append(img_phase_solve)

        img_phase_solve_list[len(img_phase_solve_list)-1] = \
                       np.ma.masked_array(imgList[len(imgList)-2].data,
                                          mask= imgList[len(imgList)-2].mask)

        for j in range(1, len(img_phase_solve_list)):
            if m4_new_image is None:
                m4_new_image = np.ma.array(img_phase_solve_list[0].filled(1) * \
                                           img_phase_solve_list[j].filled(1),
                                           mask=(img_phase_solve_list[0].mask * \
                                                 img_phase_solve_list[j].mask))
            else:
                m4_new_image = np.ma.array(m4_new_image.filled(1) * \
                                           img_phase_solve_list[j].filled(1),
                                           mask=(m4_new_image.mask * \
                                                 img_phase_solve_list[j].mask))

        return m4_new_image, img_phase_solve_list, imgList

    def masterRoiPhaseSolver(self, seg_ima, spl_value):
        self.n_calculator(spl_value)
        roiList = self._roi.roiGenerator(seg_ima)

        imgg = np.ma.masked_array(seg_ima.data, mask=roiList[3])

        img_phase_solve = np.ma.masked_array(imgg.data - self._n,
                                             mask=imgg.mask)

        return img_phase_solve
Пример #10
0
    def createCube(self, tiptilt_detrend=None, phase_ambiguity=None):
        '''
            Args:
                ttDetrend = in the creation of the cube the images are reduced
                            removing tip tilt on the central segment

                phaseSolve=

            Returns:
                self._cube = cube
        '''
        cube_all_act = None
        self._ttData()
        self._logCubeCreation(tiptilt_detrend, phase_ambiguity)   #modRB here add the Zernike removal or best decide how to manage the Zernike shapes, if to remove them in flattening only
        where = self._indexReorganization()                       #modRB here add the image immersion in the full frame
        #misure_pos, misure_neg = self._splitMeasureFromFits(self._cubeMeasure)
        ampl_reorg = self._amplitudeReorganization(self._actsVector,
                                                   self._indexingList,
                                                   self._cmdAmplitude,
                                                   self._nPushPull)


        for i in range(self._actsVector.shape[0]):
            for k in range(self._nPushPull):
                p = self._nPushPull * i + k
                n = where[p][0][0]
                mis_amp = k* self._indexingList.shape[1] + n
                mis = k * self._indexingList.shape[1] * self._template.shape[0] \
                        + n * self._template.shape[0]

                #img_pos = misure_pos[:,:,mis]
                #img_neg = misure_neg[:,:,mis]
                image_sum = np.zeros((self._cubeMeasure.shape[0],
                                     self._cubeMeasure.shape[1]))
                for l in range(1, self._template.shape[0]):
                    image = image_sum + self._cubeMeasure[:,:, mis+l] * self._template[l]
                img_if = image / (2 * ampl_reorg[mis_amp] * (self._template.shape[0] - 1))
                if tiptilt_detrend is None:
                    img_if = img_if
                else:
                    r = ROI()
                    roi = r.roiGenerator(img_if)
                    tt = TipTiltDetrend()
                    img_if = tt.tipTiltRemover(img_if, roi, 3)

                if_push_pull_kth = img_if-np.ma.median(img_if)

                if k == 0:
                    all_push_pull_act_jth = if_push_pull_kth
                else:
                    all_push_pull_act_jth = np.ma.dstack((all_push_pull_act_jth,
                                                          if_push_pull_kth))

            if self._nPushPull == 1:
                if_act_jth = all_push_pull_act_jth
            else:
                if_act_jth = np.ma.mean(all_push_pull_act_jth, axis=2)

            if cube_all_act is None:
                cube_all_act = if_act_jth
            else:
                cube_all_act = np.ma.dstack((cube_all_act, if_act_jth))
        self._cube = cube_all_act

        return self._cube
Пример #11
0
    def createCubeFromImageFolder(self, data_file_path=None, tiptilt_detrend=None,
                                  phase_ambiguity=None):
        '''
        Parameters
        ----------
                data_file_path: string
                                measurement data file path

        Other Parameters
        ----------
                ttDetrend: optional
                            in the creation of the cube the images are reduced
                            removing tip tilt on the central segment

                phaseSolve: optional

        Returns
        -------
                cube = masked array [pixels, pixels, number of images]
                        cube from analysis
        '''
        if data_file_path is None:
            data_file_path = self._h5Folder #viene da loadInfoFromIFFsTtFolder
        else:
            data_file_path = data_file_path
        
        where = self._indexReorganization()
        ampl_reorg = self._amplitudeReorganization(self._actsVector,
                                                   self._indexingList,
                                                   self._cmdAmplitude,
                                                   self._nPushPull)
        cube_all_act = []
        for i in range(self._actsVector.shape[0]):
            print(i)
            for k in range(self._nPushPull):
                p = self._nPushPull * i + k
                n = where[p]
                mis_amp = k* self._indexingList.shape[1] + n
                mis_push = (k * self._indexingList.shape[1]+ n) * 2*self._template.shape[0]
                mis_pull = self._template.shape[0] + mis_push
                mis_list = [mis_push, mis_pull]

                pp_images = []
                for mis in mis_list:
                    name = 'img_%04d.h5' %mis
                    file_name = os.path.join(data_file_path, name)
                    image0 = self._ic.from4D(file_name)

#                 image_sum = np.zeros((image_for_dim.shape[0],
#                                       image_for_dim.shape[1]))
                    image_list = [image0]
                    for l in range(1, self._template.shape[0]):
                        name = 'img_%04d.h5' %(mis+l)
                        file_name = os.path.join(data_file_path, name)
                        ima = self._ic.from4D(file_name)
                        image_list.append(ima)

                    image = np.zeros((image0.shape[0], image0.shape[1]))
                    for p in range(1, len(image_list)):
                        #opd2add   = opdtemp[*,*,p]*form[p]+opdtemp[*,*,p-1]*form[p-1]
                        #opd      += opd2add
                        opd2add = image_list[p] * self._template[p] + image_list[p-1] * self._template[p-1]
                        master_mask2add = np.ma.mask_or(image_list[p].mask, image_list[p-1].mask)
                        if p==1:
                            master_mask = master_mask2add
                        else:
                            master_mask = np.ma.mask_or(master_mask, master_mask2add)
                        image += opd2add
                    image = np.ma.masked_array(image, mask=master_mask)
                    #image = image + ima * self._template[l] #sbagliato
                    pp_images.append(image)
                image = pp_images[0] + pp_images[1] #da rivedere molto
                img_if = image / (2 * ampl_reorg[mis_amp] * (self._template.shape[0] - 1))
                if tiptilt_detrend is None:
                    img_if = img_if
                else:
                    r = ROI()
                    roi = r.roiGenerator(img_if)
                    tt = TipTiltDetrend()
                    img_if = tt.tipTiltDetrend(img_if, roi, 3)

                if_push_pull_kth = img_if

                if k == 0:
                    all_push_pull_act_jth = if_push_pull_kth
                else:
                    all_push_pull_act_jth = np.ma.dstack((all_push_pull_act_jth,
                                                          if_push_pull_kth))

            if self._nPushPull == 1:
                if_act_jth = all_push_pull_act_jth
            else:
                if_act_jth = np.ma.mean(all_push_pull_act_jth, axis=2)

            cube_all_act.append(if_act_jth)
        self._cube = np.ma.dstack(cube_all_act)
        return self._cube
Пример #12
0
 def __init__(self):
     """The constructor """
     self._cal = opt_calibration()
     self._roi = ROI()
     self._zOnM4 = ZernikeOnM4()
Пример #13
0
class Alignment():
    """
    Class to be used for alignment of the optical tower
    and the deformable mirror

    HOW TO USE IT:
    from m4.alignment import Alignment
    a = Alignment()
    #for the optical tower
    tt = a.ott_calibration(commandAmpVector, nPushPull, maskIndex)
    cmd = a.ott_alignment(tt)
    #for deformable mirror
    tt, zCoefComa, comaSurface = a.m4_calibration(...)
    cmd = a.m4_alignement(zCoefComa)
    """
    def __init__(self):
        """The constructor """
        self._cal = opt_calibration()
        self._roi = ROI()
        self._zOnM4 = ZernikeOnM4()

    def ott_calibration(
            self, command_amp_vector, n_push_pull,
            mask_index):  #modRB calibration forse non è il nome migliore??
        '''
            Calibration of the optical tower                                 #modRB trovare un modo per identificare in maniera automatica la maschera del componente voluto. es.: prodotto con maschere note
            args:
                command_amp_vector = vector containing the movement values
                                    of the 5 degrees of freedom
                n_push_pull = number of push pull for each degree of freedom
                mask_index = int (3 for the RM mask)

            returns:
                    tt = tracking number of measurement
        '''
        self._moveRM()
        self._tt = self._cal.measureCalibrationMatrix(0, command_amp_vector,
                                                      n_push_pull)
        int_mat, rec = self._cal.analyzerCalibrationMeasurement(
            self._tt, mask_index)
        return self._tt

    def ott_alignement(self, tt=None):
        """
        Args:
            tt = tracking number of measurement of which you want to use the
                interaction matrix and reconstructor
                None for the last measurement made
        Returns:
                cmd = vector of command to apply to PAR+RM dof
        """
        if tt is None:
            al = opt_alignment(self._tt)
        else:
            al = opt_alignment(tt)
        cmd = al.opt_align()
        self._applyCmd()
        return cmd

    def m4_calibration(self, commandAmpVector_ForParRmAlignement,
                       nPushPull_ForParRmAlignement,
                       maskIndex_ForParRmAlignement,
                       commandAmpVector_ForM4Calibration,
                       nPushPull_ForM4Calibration, maskIndex_ForM4Alignement):
        """
        Calibration of the deformable mirror

        Args:
            commandAmpVector_ForParRmAlignement = amplitude to be applied to par+rm
            nPushPull_ForParRmAlignemen = number of push pull for par+rm dof
            maskIndex_ForParRmAlignement = number of mask index to use
            commandAmpVector_ForM4Calibration = amplitude to be applied to m4
            nPushPull_ForM4Calibration = number of push pull for m4 dof
            maskIndex_ForM4Alignement = number of mask index to use

        Returns:
            zernike_coef_coma = zernike coefficient value for coma calculated
                                by the function _measureComaOnSegmentMask
            coma_surface = reconstructed surface
        """
        self._moveSegmentView()
        tt = self.ott_calibration(commandAmpVector_ForParRmAlignement,
                                  nPushPull_ForParRmAlignement,
                                  maskIndex_ForParRmAlignement)
        cmd = self.ott_alignement(tt)
        self._moveRM()
        zernike_coef_coma, coma_surface = self._measureComaOnSegmentMask()
        self._tt = self._cal.measureCalibrationMatrix(
            3, commandAmpVector_ForM4Calibration, nPushPull_ForM4Calibration)
        intMat, rec = self._cal.analyzerCalibrationMeasurement(
            self._tt, maskIndex_ForM4Alignement)
        return self._tt, zernike_coef_coma, coma_surface

    def m4_alignement(self, zernike_coef_coma, tt=None):
        """
        Args:
            zernike_coef_coma = zernike coefficient value for coma
            tt = tracking number of measurement of which you want to use the
                interaction matrix and reconstructor
                None for the last measurement made
        Returns:
                cmd = vector of command to apply to M4 dof
        """
        if tt is None:
            al = opt_alignment(self._tt)
        else:
            al = opt_alignment(tt)
        cmd = al.opt_align(zernike_coef_coma)
        return cmd

    def _moveRM(self):
        pass

    def _moveSegmentView(self):
        pass

    def _applyCmd(self):
        pass

    def _measureComaOnSegmentMask(self):
        ima = obj.readImageFromFitsFileName(
            'Allineamento/20191001_081344/img.fits')
        roi = self._roi.roiGenerator(ima)
        segment_ima = np.ma.masked_array(ima.data, mask=roi[11])

        coef, mat = self._zOnM4.zernikeFit(segment_ima, np.arange(2, 11))
        coma = coef[5]
        coma_surface = self._zOnM4.zernikeSurface(np.array([coma]),
                                                  segment_ima.mask, mat,
                                                  np.array([5]))
        return coma, coma_surface
Пример #14
0
    def createCubeFromImageFolder(self,
                                  data_file_path,
                                  tiptilt_detrend=None,
                                  phase_ambiguity=None):
        '''
        Parameters
        ----------
                data_file_path: string
                                measurement data file path

        Other Parameters
        ----------
                ttDetrend: optional
                            in the creation of the cube the images are reduced
                            removing tip tilt on the central segment

                phaseSolve: optional

        Returns
        -------
                cube = masked array [pixels, pixels, number of images]
                        cube from analysis
        '''
        cube_all_act = None
        where = self._indexReorganization()
        ampl_reorg = self._amplitudeReorganization(self._actsVector,
                                                   self._indexingList,
                                                   self._cmdAmplitude,
                                                   self._nPushPull)
        for i in range(self._actsVector.shape[0]):
            for k in range(self._nPushPull):
                p = self._nPushPull * i + k
                n = where[p][0][0]
                mis_amp = k * self._indexingList.shape[1] + n
                mis = k * self._indexingList.shape[1] * self._template.shape[0] \
                        + n * self._template.shape[0]

                name = 'img_%04d.h5' % mis
                file_name = os.path.join(data_file_path, name)
                image_for_dim = self._ic.from4D(file_name)

                image_sum = np.zeros(
                    (image_for_dim.shape[0], image_for_dim.shape[1]))
                for l in range(1, self._template.shape[0]):
                    name = 'img_%04d.h5' % (mis + l)
                    file_name = os.path.join(data_file_path, name)
                    ima = self._ic.from4D(file_name)
                    image = image_sum + ima * self._template[l]
                img_if = image / (2 * ampl_reorg[mis_amp] *
                                  (self._template.shape[0] - 1))
                if tiptilt_detrend is None:
                    img_if = img_if
                else:
                    r = ROI()
                    roi = r.roiGenerator(img_if)
                    tt = TipTiltDetrend()
                    img_if = tt.tipTiltDetrend(img_if, roi, 3)

                if_push_pull_kth = img_if - np.ma.median(img_if)

                if k == 0:
                    all_push_pull_act_jth = if_push_pull_kth
                else:
                    all_push_pull_act_jth = np.ma.dstack(
                        (all_push_pull_act_jth, if_push_pull_kth))

            if self._nPushPull == 1:
                if_act_jth = all_push_pull_act_jth
            else:
                if_act_jth = np.ma.mean(all_push_pull_act_jth, axis=2)

            if cube_all_act is None:
                cube_all_act = if_act_jth
            else:
                cube_all_act = np.ma.dstack((cube_all_act, if_act_jth))
        self._cube = cube_all_act

        return self._cube
Пример #15
0
    def createCube(self, tiptilt_detrend=None, phase_ambiguity=None):
        '''
        Other Parameters
        ----------
                ttDetrend: optional
                            in the creation of the cube the images are reduced
                            removing tip tilt on the central segment

                phaseSolve: optional

        Returns
        -------
                cube = masked array [pixels, pixels, number of images]
                        cube from analysis
        '''
        cube_all_act = None
        self._ttData()
        self._logCubeCreation(tiptilt_detrend, phase_ambiguity)
        where = self._indexReorganization()
        #misure_pos, misure_neg = self._splitMeasureFromFits(self._cubeMeasure)
        ampl_reorg = self._amplitudeReorganization(self._actsVector,
                                                   self._indexingList,
                                                   self._cmdAmplitude,
                                                   self._nPushPull)

        for i in range(self._actsVector.shape[0]):
            for k in range(self._nPushPull):
                p = self._nPushPull * i + k
                n = where[p][0][0]
                mis_amp = k * self._indexingList.shape[1] + n
                mis = k * self._indexingList.shape[1] * self._template.shape[0] \
                        + n * self._template.shape[0]

                #img_pos = misure_pos[:,:,mis]
                #img_neg = misure_neg[:,:,mis]
                image_sum = np.zeros(
                    (self._cubeMeasure.shape[0], self._cubeMeasure.shape[1]))
                for l in range(1, self._template.shape[0]):
                    image = image_sum + self._cubeMeasure[:, :, mis +
                                                          l] * self._template[l]
                img_if = image / (2 * ampl_reorg[mis_amp] *
                                  (self._template.shape[0] - 1))
                if tiptilt_detrend is None:
                    img_if = img_if
                else:
                    r = ROI()
                    roi = r.roiGenerator(img_if)
                    tt = TipTiltDetrend()
                    img_if = tt.tipTiltDetrend(img_if, roi, 3)

                if_push_pull_kth = img_if - np.ma.median(img_if)

                if k == 0:
                    all_push_pull_act_jth = if_push_pull_kth
                else:
                    all_push_pull_act_jth = np.ma.dstack(
                        (all_push_pull_act_jth, if_push_pull_kth))

            if self._nPushPull == 1:
                if_act_jth = all_push_pull_act_jth
            else:
                if_act_jth = np.ma.mean(all_push_pull_act_jth, axis=2)

            if cube_all_act is None:
                cube_all_act = if_act_jth
            else:
                cube_all_act = np.ma.dstack((cube_all_act, if_act_jth))
        self._cube = cube_all_act

        return self._cube
Пример #16
0
class Flattenig():
    """ Class dealing with the determination and application of the wave front
    flattening command.
    """
    def __init__(self, analyzerIFFunctions):
        """The constructor:
            analyzerIFFunctions = analyzer object to use
        """
        self._logger = logging.getLogger('FLATTENING:')
        self._an = analyzerIFFunctions
        self._who = self._an._who
        self._roi = ROI()
        self._mirror = DMirror()
        self._command = None
        self._flatteningWf = None

    @staticmethod
    def _storageFolder():
        """ Creates the path where to save measurement data"""
        return fold_name.FLAT_ROOT_FOLD

    def readVMatrix(self):
        """ Function that returns V matrix (892, 811) for the segment
        """
        root = OttParameters.V_MATRIX_FOR_SEGMENT_ROOT_811
        #root = Configuration.V_MATRIX_FOR_SEGMENT_ROOT_892
        hduList = pyfits.open(root)
        v_matrix = hduList[0].data
        v_matrix_cut = v_matrix[:, 0:811]
        return v_matrix_cut

#comando che permette di ottenere la misura del wf dall'interferometro (wf)
#ampr = np.random.randn(25)
#wf = np.dot(self._an._cube, ampr)

    def flatCommand(self, wf):
        """ Returns the command to give to the actuators to level
        the wf considered
        """
        tt = Timestamp.now()
        fitsFileName = os.path.join(Flattenig._storageFolder(), tt)

        self._logger.info('Calculation of the flat command')
        circular_mask = self._roi._circularMaskForSegmentCreator()
        mask_no_edge_actuators = np.ma.mask_or(wf.mask, circular_mask)

        normal_mask = np.ma.mask_or(wf.mask, self._an.getMasterMask())
        super_mask = np.ma.mask_or(mask_no_edge_actuators,
                                   self._an.getMasterMask())
        wf_masked = np.ma.masked_array(wf.data, mask=super_mask)
        pyfits.writeto(os.path.join(fitsFileName, 'imgstart.fits'),
                       wf_masked.data)
        pyfits.append(os.path.join(fitsFileName, 'imgstart.fits'),
                      wf_masked.mask.astype(int))

        self._an.setDetectorMask(wf_masked.mask | self._an.getMasterMask())
        rec = self._an.getReconstructor()

        amp = -np.dot(rec, wf_masked.compressed())
        v_matrix_cut = self.readVMatrix()
        self._command = np.dot(v_matrix_cut, amp)
        pyfits.writeto(os.path.join(fitsFileName, 'flatDeltaCommand.fits'),
                       self._command)
        return self._command

    def syntheticWfCreator(self, wf_mask, command):
        """ Returns the synthetic wavefront using the input command
        and the same masked wavefront used to determine the command itself.
        """
        v_matrix_cut = self.readVMatrix()
        v_pinv = np.linalg.pinv(v_matrix_cut)
        amp = np.dot(v_pinv, command)
        sintetic_wf = np.dot(self._an.getInteractionMatrix(), amp)

        circular_mask = self._roi._circularMaskForSegmentCreator()
        mask_no_edge_actuators = np.ma.mask_or(wf_mask, circular_mask)
        normal_mm = np.ma.mask_or(wf_mask, self._an.getMasterMask())
        super_mm = np.ma.mask_or(mask_no_edge_actuators,
                                 self._an.getMasterMask())
        final_wf_data = np.zeros(
            (OttParameters.DIAMETER_IN_PIXEL_FOR_SEGMENT_IMAGES,
             OttParameters.DIAMETER_IN_PIXEL_FOR_SEGMENT_IMAGES))
        final_wf_data[np.where(super_mm == False)] = sintetic_wf
        final_wf = np.ma.masked_array(final_wf_data, mask=super_mm)
        return final_wf

    def flattening(self, command, seg):
        """ Function for flat command application
        """
        self._logger.info('Application of the flat command')
        #dentro delta command misura già la posizione dello specchio (pos)
        delta_command = self._mirror.mirror_command(command, seg)
        #la applico e misuro il nuovo wf
        return delta_command

    def save(self):
        """ Function to save the info file
        """
        store_in_folder = Flattenig._storageFolder()
        dove, tt = tracking_number_folder.createFolderToStoreMeasurements(
            store_in_folder)
        fits_file_name = os.path.join(dove, 'info.fits')
        header = pyfits.Header()
        header['WHO'] = self._who
        pyfits.writeto(fits_file_name, self._command, header)
        pyfits.append(fits_file_name, self._flatteningWf.data, header)
        pyfits.append(fits_file_name, self._flatteningWf.mask.astype(int),
                      header)
        return tt

    @staticmethod
    def load(tracking_number):
        """ Function for reload
        """
        theObject = Flattenig(tracking_number)
        store_in_folder = Flattenig._storageFolder()
        folder = os.path.join(store_in_folder, tracking_number)
        info_fits_file_name = os.path.join(folder, 'info.fits')
        header = pyfits.getheader(info_fits_file_name)
        hduList = pyfits.open(info_fits_file_name)
        theObject._who = header['WHO']
        theObject._command = hduList[0].data
        theObject._flattening = np.ma.masked_array(
            hduList[1].data, hduList[2].data.astype(bool))
        return theObject
Пример #17
0
class PhaseSolve():
    """
    Class for ...

    HOW TO USE IT::

        from m4.utils.img_redux import PhaseSolve
        PS = PhaseSolve()
    """
    def __init__(self):
        """The constructor """
        self._roi = ROI()
        self._lambda = Interferometer.WAVEL
        self._n = None

    def n_calculator(self, spl_values):
        n = np.zeros(spl_values.shape[0])
        for i in range(spl_values.shape[0]):
            n[i] = (2. * spl_values[i]) / self._lambda
        self._n = n
        return self._n

    def m4PhaseSolver(self, m4_ima, spl_values):
        self.n_calculator(spl_values)
        roiList = self._roi.roiGenerator(m4_ima)
        m4_new_image = None

        media = []
        imgList = []
        for roi in roiList:
            imgg = np.ma.masked_array(m4_ima.data, mask=roi)
            m = imgg.mean()
            media.append(m)
            imgList.append(imgg)

        aa = np.arange(self._n.shape[0])
        zipped = zip(aa, imgList)
        img_phase_solve_list = []
        for i, imgg in zipped:
            img_phase_solve = np.ma.masked_array(imgg.data - self._n[i],
                                                 mask=imgg.mask)
            img_phase_solve_list.append(img_phase_solve)

        img_phase_solve_list[len(img_phase_solve_list)-1] = \
                       np.ma.masked_array(imgList[len(imgList)-2].data,
                                          mask= imgList[len(imgList)-2].mask)

        for j in range(1, len(img_phase_solve_list)):
            if m4_new_image is None:
                m4_new_image = np.ma.array(img_phase_solve_list[0].filled(1) * \
                                           img_phase_solve_list[j].filled(1),
                                           mask=(img_phase_solve_list[0].mask * \
                                                 img_phase_solve_list[j].mask))
            else:
                m4_new_image = np.ma.array(m4_new_image.filled(1) * \
                                           img_phase_solve_list[j].filled(1),
                                           mask=(m4_new_image.mask * \
                                                 img_phase_solve_list[j].mask))

        return m4_new_image, img_phase_solve_list, imgList

    def masterRoiPhaseSolver(self, seg_ima, spl_value):
        self.n_calculator(spl_value)
        roiList = self._roi.roiGenerator(seg_ima)

        imgg = np.ma.masked_array(seg_ima.data, mask=roiList[3])

        img_phase_solve = np.ma.masked_array(imgg.data - self._n,
                                             mask=imgg.mask)

        return img_phase_solve
Пример #18
0
 def __init__(self):
     """The constructor """
     self._roi = ROI()
     self._lambda = Configuration.LAMBDA
     self._n = None