def dz(self, value):
        self._dz = float(value)
        self.log.info("Using binning factor of {}".format(self.binning))

        # Create configuration file with the proper parameters
        cwfs_config_template = """#Auxiliary Telescope parameters:
Obscuration 				0.423
Focal_length (m)			21.6
Aperture_diameter (m)   		1.2
Offset (m)				{}
Pixel_size (m)			{}
"""
        config_index = "auxtel_latiss"
        path = Path(cwfs.__file__).resolve().parents[3].joinpath(
            "data", config_index)
        if not path.exists():
            os.makedirs(path)
        dest = path.joinpath(f"{config_index}.param")
        with open(dest, "w") as fp:
            # Write the file and set the offset and pixel size parameters
            fp.write(
                cwfs_config_template.format(self._dz * 0.041,
                                            10e-6 * self.binning))

        self.inst = Instrument(config_index, int(self.side * 2 / self.binning))
        self.algo = Algorithm("exp", self.inst, 1)
Пример #2
0
    def testMatlab(self):
        global doPlot
        if doPlot:
            fig = plt.figure(figsize=(10, 10))

        j = 0                           # counter for matlab outputs, self.matlabZFile_Tol
        for imgDir, filenameFmt, fldxy, algorithms, model in self.tests:
            imgDir = os.path.join(str(self.rootdir), imgDir)
            intraFile = os.path.join(imgDir, filenameFmt % "intra")
            I1 = Image(readFile(intraFile), fldxy, Image.INTRA)

            extraFile = os.path.join(imgDir, filenameFmt % "extra")
            I2 = Image(readFile(extraFile), fldxy, Image.EXTRA)

            inst = Instrument(self.myinst, I1.sizeinPix)

            for algorithm in algorithms:
                matlabZFile, tol = self.matlabZFile_Tol[j]; j += 1

                algo = Algorithm(algorithm, inst, 1)
                algo.runIt(inst, I1, I2, model)

                zer = algo.zer4UpNm
                matZ = np.loadtxt(os.path.join(self.validationDir, matlabZFile))

                aerr = np.abs(matZ - zer)
                print("%-31s max(abs(err)) = %8.3g median(abs(err)) = %8.3g [Z_%d], tol=%.0f nm" %
                      (matlabZFile, np.max(aerr), np.median(aerr), self.Zernike0 + np.argmax(aerr), tol))

                if doPlot:
                    ax = plt.subplot(self.nTest, 1, j)
                    plt.plot(self.x, matZ, label='Matlab', marker='o', color='r', markersize=10)
                    plt.plot(self.x, zer, label='Python',  marker='.', color='b', markersize=10)
                    plt.axvline(self.Zernike0 + np.argmax(aerr), ls=':', color='black')
                    plt.legend(loc="best", shadow=True, title=matlabZFile, fancybox=True)
                    ax.get_legend().get_title().set_color("red")
                    plt.xlim(self.x[0] - 0.5, self.x[-1] + 0.5)

                assert np.max(aerr) < tol

        if doPlot:
            plt.show()
Пример #3
0
    def __init__(self, cwfsDir, imageDir, instruFile, algoFile, iSim,
                 imgSizeinPix, band, wavelength, debugLevel):
        self.imageDir = imageDir
        self.obsId = None
        self.iSim = iSim
        self.band = band
        self.iIter = 0
        self.nWFS = 4
        self.nRun = 1
        self.nExp = 1
        self.wfsName = ['intra', 'extra']
        self.halfChip = ['C0', 'C1']  # C0 is always intra, C1 is extra

        self.cwfsDir = cwfsDir
        self.imgSizeinPix = imgSizeinPix
        self.inst = Instrument(instruFile, imgSizeinPix)
        self.algo = Algorithm(algoFile, self.inst, debugLevel)
        self.znwcs = self.algo.numTerms
        self.znwcs3 = self.znwcs - 3
        self.myZn = np.zeros((self.znwcs3 * self.nWFS, 2))
        self.trueZn = np.zeros((self.znwcs3 * self.nWFS, 2))
        aa = instruFile
        if aa[-2:].isdigit():
            aa = aa[:-2]
        aosSrcDir = os.path.split(os.path.abspath(__file__))[0]
        intrinsicFile = '%s/../data/%s/intrinsic_zn.txt' % (aosSrcDir, aa)
        if np.abs(wavelength - 0.5) > 1e-3:
            intrinsicFile = intrinsicFile.replace('zn.txt',
                                                  'zn_%s.txt' % band.upper())
        intrinsicAll = np.loadtxt(intrinsicFile)
        intrinsicAll = intrinsicAll * wavelength
        self.intrinsicWFS = intrinsicAll[-self.nWFS:,
                                         3:self.algo.numTerms].reshape((-1, 1))
        self.covM = np.loadtxt('%s/../data/covM86.txt' %
                               aosSrcDir)  # in unit of nm^2
        self.covM = self.covM * 1e-6  # in unit of um^2

        if debugLevel >= 3:
            print('znwcs3=%d' % self.znwcs3)
            print(self.intrinsicWFS.shape)
            print(self.intrinsicWFS[:5])
Пример #4
0
    def __init__(self, cwfsDir, instruFile, algoFile, imgSizeinPix, band, wavelength, aosDataDir, debugLevel=0):
        """

        Initiate the aosWFS class.

        Arguments:
            cwfsDir {[str]} -- cwfs directory.
            instruFile {[str]} -- Instrument folder name.
            algoFile {[str]} -- Algorithm to solve the TIE.
            imgSizeinPix {[int]} -- Pix size in one dimension.
            band {[str]} -- Active filter ("u", "g", "r", "i", "z", "y").
            wavelength {[float]} -- Wavelength in um.
            aosDataDir {[str]} -- AOS data directory.

        Keyword Arguments:
            debugLevel {[int]} -- Debug level. The higher value gives more information.
                                (default: {0})
        """

        # Get the instrument name
        instName, defocalOffset = getInstName(instruFile)

        # Declare the Zk, catalog donut, and calculated z files
        self.zFile = None
        self.catFile = None
        self.zCompFile = None

        # Previous zFile (Zk), which means the z4-zn in the previous iteration
        self.zFile_m1 = None

        # Number of wavefront sensor
        self.nWFS = {self.LSST: 4, self.COMCAM: 9}[instName]

        # Number of run in each iteration of phosim
        self.nRun = {self.LSST: 1, self.COMCAM: 2}[instName]

        # Number of exposure in each run
        # For ComCam, only 1 set of intra and 1 set of extra for each iter
        self.nExp = {self.LSST: 2, self.COMCAM: 1}[instName]

        # Decide the defocal distance offset in mm
        self.offset = [-defocalOffset, defocalOffset]

        # Will refactorize the directory root problem.

        # Record the directory now
        aosDir = os.getcwd()

        # Assign the cwfs directory
        self.cwfsDir = cwfsDir

        # Change the directory now to the cwfs directory
        os.chdir(cwfsDir)

        # Read the instrument and algorithm data
        self.inst = Instrument(instruFile, int(imgSizeinPix))
        self.algo = Algorithm(algoFile, self.inst, debugLevel)

        # Change back the directory
        os.chdir(aosDir)

        # Terms of annular Zernike polynomials
        self.znwcs = self.algo.numTerms

        # Only consider the terms z4-zn. The first three terms are piston, x-tilt, and y-tilt
        self.znwcs3 = self.znwcs - 3

        # Construct the matrix of annular Zernike polynomials for all WFSs.
        self.myZn = np.zeros((self.znwcs3 * self.nWFS, 2))
        self.trueZn = self.myZn.copy()

        # Directory of intrinsic Zn file belong to the specific instrument
        intrinsicZnFileName = "intrinsic_zn_%s.txt" % band.upper()

        # Monochromatic condition in referenced wavelength
        if (wavelength == 0.5):
            intrinsicZnFileName = "intrinsic_zn.txt"

        intrinsicFile = os.path.join(aosDataDir, instName, intrinsicZnFileName)

        # Read the intrinsic Zn data and times the wavelength
        intrinsicAll = np.loadtxt(intrinsicFile)*wavelength

        # Read the intrinsic Zk
        self.intrinsicWFS = intrinsicAll[-self.nWFS:, 3:self.znwcs].reshape((-1, 1))

        # Read the covariance matrix in unit of nm^2
        # Covariance matrix with 86 runs.
        covMFilePath = os.path.join(aosDataDir, "covM86.txt")
        self.covM = np.loadtxt(covMFilePath)

        # Reconstruct the covariance matrix if necessary (not baseline condition)
        # The way to construct the covariance matrix here is weird. Actually, there
        # is no 4x4 repeation in original "covM86.txt". Need to check with Bo for this.

        # Expand the covariance matrix by repeating the matrix
        if (self.nWFS > 4):
            nrepeat = int(np.ceil(self.nWFS/4))
            self.covM = np.tile(self.covM, (nrepeat, nrepeat))

        # Take the needed part
        if (self.nWFS != 4):
            self.covM = self.covM[:(self.znwcs3 * self.nWFS), :(self.znwcs3 * self.nWFS)]

        # Change the unit to um^2
        self.covM *= 1e-6

        # Show the debug information
        if (debugLevel >= 3):
            print("znwcs3=%d" % self.znwcs3)
            print(self.intrinsicWFS.shape)
            print(self.intrinsicWFS[:5])