Commit 80e3c620 authored by vertighel's avatar vertighel
Browse files

Modified ini files, tried to generate some new header

parent 85f8cbc6
Loading
Loading
Loading
Loading
Loading
+5 −5
Original line number Diff line number Diff line
@@ -33,12 +33,12 @@ MJD-OBS = | [d] Modified Julian Date of observation
TELESCOP =            | Telescope name
FOCALLEN =            | [mm] Telescope focal length
APTDIA =              | [mm] Telescope aperture diameter
OBS-LONG =            | [deg] Observatory longitude (East < 0)
OBS-LONG =            | [deg] Observatory longitude (East > 0)
OBS-LAT =             | [deg] Observatory latitude (North > 0)
OBS-ELEV =            | [m] Observatory altitude above sea level
FOCUSPOS =            | [um] Focuser position
FOCUSTEM =            | [C] Focuser temperature
DEROTANG = 0          | [deg] Rotator angle
DEROTANG = 0          | [deg] Rotator angle, if any
                      
[Imaging]          
INSTRUME =            | Instrument name
@@ -55,7 +55,7 @@ CCD-TEMP = | [C] CCD temperature
GAIN =                | [e-/ADU] Gain
RDNOISE =             | [e- RMS] Readout noise

IMAGETYP =            | Frame type (LIGHT, DARK, BIAS, FLAT)
IMAGETYP =            | Frame type
FILTER =              | Photometric filter used
EXPTIME =             | [s] Exposure time
XBINNING =            | Binning factor in X
@@ -88,7 +88,7 @@ EQUINOX = 2000.0 | [yr] Equinox of coordinates

[Final]
FILEORIG =            | Original file name
SWCREATE =            | Software that created this file
SWCREATE =            | Software that created FILEORIG
CHECKSUM =            | Checksum of header
DATASUM =             | Data sum of FITS file
ORIGIN = NOCHE v0.1   | Origin of FITS file
+190 −102
Original line number Diff line number Diff line
import configparser
from pathlib import Path
from configparser import DuplicateOptionError
from ast import literal_eval

import numpy as np
from astropy.coordinates import SkyCoord, EarthLocation
@@ -54,9 +56,9 @@ class Noche:
        self._obs_dir = "observatories"

        self.header = fits.Header()
        self.hdu = None
        
        self.load_default_header(header_template_path)
        # self.load_noctis_observatory("oarpaf")
        # self.set_coordinates(05.3, 70.0, Time.now().isot)


    @property
@@ -87,15 +89,10 @@ class Noche:
            path = Path(__file__).parent / self._head_dir / "header_base_v1.ini"
            log.info(path)

        config = configparser.ConfigParser(inline_comment_prefixes=('#',))
        try:
            config.read(path)
        except IndexError as e:
            log.error("File not found")
        config = self._load_config(path)        
        
        for section in config.sections():
            for key, value in config.items(section):
                
                try:
                    val, comment = value.split("|")
                    comment = comment.strip()
@@ -109,7 +106,7 @@ class Noche:
        self._update()


    def load_noctis_observatory(self, name='oarpaf', flavor=None):
    def load_noctis_observatory(self, name='oarpaf', fits_file=None):
        """
        Load one of the NOCTIS observatory parameters such as
        location and detector specifics,
@@ -119,8 +116,6 @@ class Noche:
        ----------
        name : str
            One of the supported observatories.
        flavor : str, optional
            Section name of the configuration file. If not specified, takes the first one.
        """

        data_dir = Path(__file__).parent / self._obs_dir
@@ -128,12 +123,15 @@ class Noche:

        log.debug(ini_path)
        if not ini_path.exists():
            raise FileNotFoundError(f"Observatory config '{ini_path}' not found.")
            msg = f"Observatory config '{ini_path}' not found."
            # raise FileNotFoundError(msg)
            log.error(msg)
            return

        self.load_observatory(str(ini_path), flavor=flavor)
        self.load_observatory(path=str(ini_path), fits_file=fits_file)


    def load_observatory(self, path=None, flavor=None):
    def load_observatory(self, path=None, fits_file=None):
        """
        Load observatory parameters such as location and detector specifics,
        and update relevant FITS keywords.
@@ -142,31 +140,83 @@ class Noche:
        ----------
        path : str
            Configuration file in .ini format.
        flavor : str, optional
            Section name of the configuration file. If not specified, takes the first one.
        """

        config = configparser.ConfigParser(inline_comment_prefixes=('#',))
        config.read(path)
        config = self._load_config(path)        

        sections = config.sections()

        if not flavor:
            loc = config[sections[0]]
        else:
            loc = config[flavor]
        loc = config["Fixed"]

        self.set_location(loc["OBS-LONG"], loc["OBS-LAT"], loc["OBS-ELEV"])

        for k in loc.keys():
            log.info(k)
            val = self._parse(loc[k])
            if k in self.header:
                self.header[k] = val

        self.header["DETSIZE"] = f'[1:{self.header["NAXIS1"]},1:{self.header["NAXIS2"]}]'
        #self.header["DETSIZE"] = f'[1:{self.header["NAXIS1"]},1:{self.header["NAXIS2"]}]'

        if fits_file:
            self.fill_from_fits_file(path, fits_file)

        self._update()


    def fill_from_fits_file(self, path=None, fits_file=None):
        """
        Load relevant header info from a fits file of the specific observatory.

         - [Mapping] section defines how the new keywords are related
           to the old ones.
           For example: FOCUSPOS = TELFOCUS

         - [Formula] section defines the formula to apply to a header
           value to match the specifics of the new one.
           For example: FOCUSPOS = (x)/1000 # Transforming mm in um.

        Parameters
        ----------
        path : str
            Configuration file in .ini format.
        fits_file : str
            FITS file position.

        """

        config = self._load_config(path)        

        filename = Path(fits_file)
        self.load_fits(filename)
        fits_file_header = self.hdu.header

        sections = config.sections()

        loc = config["Mapping"]
        for k in loc.keys():
            fits_keyword = loc[k]
            fits_value = fits_file_header[fits_keyword]
            val = self._parse(fits_value)
            self.header[k] = val
            log.info(f"{k:<8} : {val}")

        loc = config["Formula"]
        for k in loc.keys():
            fits_formula = loc[k]
            x = self.header[k]
            self.header[k] = eval(fits_formula)
            log.info(f"{k:<8} : from {x} to {self.header[k]}")
            del x

        self.set_coordinates(self.header["RA"],
                             self.header["DEC"],
                             obstime=self.header["DATE-OBS"])
            
        self._update()

        self.header["FILEORIG"] = filename.name


    def set_location(self, lon, lat, alt):
        """
@@ -212,7 +262,7 @@ class Noche:
        self._update()


    def set_object(self, objname, update_coord=True, obstime=None):
    def set_object(self, objname, update_coord=False, obstime=None):
        """
        Resolve object coordinates and set OBJECT keyword.

@@ -273,8 +323,10 @@ class Noche:
            time = Time(obstime)
            self.set_obstime(time)

        self.header['RA'] = coord.ra.to_string(unit=u.hourangle, sep=':')
        self.header['DEC'] = coord.dec.to_string(unit=u.deg, sep=':')
        self.header['RA'] = coord.ra.to_string(unit=u.hourangle, sep=':',
                                               pad=True, precision=1)
        self.header['DEC'] = coord.dec.to_string(unit=u.deg, sep=':', pad=True,
                                                 precision=1)
        self.header['RA_DEG'] = coord.ra.deg
        self.header['DEC_DEG'] = coord.dec.deg

@@ -342,9 +394,17 @@ class Noche:
        if self._coord == None or self._location == None:
            raise ValueError("Observation Coordinates, Instrument parameters must be set.")

        crpix = [self.header['NAXIS1']/2, self.header['NAXIS2']/2]
        cdelt = [round(self.header["PIXSCALE"]*u.arcsec.to(u.deg), 7),
                 round(self.header["PIXSCALE"]*u.arcsec.to(u.deg), 7)]

        detsize = self.header['DETSIZE'].strip('[]')
        x_str, y_str = detsize.split(',')

        # Ottieni i limiti numerici
        _, xsize = map(int, x_str.split(':'))
        _, ysize = map(int, y_str.split(':'))

        crpix = [xsize/self.header["XBINNING"]/2, ysize/self.header["YBINNING"]/2]
        cdelt1 = round(self.header["PIXSCALE"]*self.header["XBINNING"]*u.arcsec.to(u.deg), 7)
        cdelt2 = round(self.header["PIXSCALE"]*self.header["YBINNING"]*u.arcsec.to(u.deg), 7)

        if not angle:
            angle = self.header["DEROTANG"]
@@ -358,11 +418,11 @@ class Noche:
        self.header['CRPIX2'] = crpix[1]
        self.header['CRVAL1'] = crval_ra
        self.header['CRVAL2'] = crval_dec
        self.header['CDELT1'] = cdelt[0]
        self.header['CDELT2'] = cdelt[1]
        self.header["PC1_1"] = -np.cos(angle)
        self.header['CDELT1'] = cdelt1
        self.header['CDELT2'] = cdelt2
        self.header["PC1_1"] = +np.cos(angle) *-1 # E to left
        self.header["PC1_2"] = -np.sin(angle)
        self.header["PC2_1"] = +np.sin(angle)
        self.header["PC1_2"] = +np.sin(angle)
        self.header["PC2_2"] = +np.cos(angle)


@@ -412,6 +472,32 @@ class Noche:
            if self.header[k] == None:
                print(k, self.header[k])

    def load_fits(self, fits_file):

        filename = fits_file
        hdul = fits.open(filename)
        self.hdu = hdul[0]

            
    def write_noctis_fits(self, filename=None, overwrite=True):
        noche_hdu = self.hdu.copy()
        noche_hdu.header = self.header
        noche_hdu.writeto(filename,
                          overwrite=overwrite, checksum=True)

    @staticmethod
    def _load_config(path):
                
        config = configparser.ConfigParser(inline_comment_prefixes=('#',))

        try:
            config.read(path)
            return config
        except IndexError as e:
            log.error("File not found: {e}")
        except DuplicateOptionError as e:
            log.error(e)
                

    def _update(self):
        """
@@ -440,7 +526,10 @@ class Noche:
            Parsed value.
        """

        try:
            val = val.strip()
        except AttributeError as e:
            pass

        if not val:
            val = None
@@ -462,4 +551,3 @@ class Noche:
                    pass

        return val
+27 −22
Original line number Diff line number Diff line
[ABObservatory]
[Fixed]
TELESCOP = ABObservatory          # Telescope name
APTDIA = 300                      # [mm] Telescope aperture diameter
FOCALLEN = 1170                   # [mm] Telescope focal length
OBS-LONG = -11.2430135            # [deg] Observatory longitude (East < 0)  
OBS-LONG = -11.2430135            # [deg] Observatory longitude (East > 0)  
OBS-LAT = 43.5235203              # [deg] Observatory latitude (North > 0)  
OBS-ELEV = 1025                   # [m] Observatory altitude above sea level
DEROTANG = 0                      # [deg] Rotator angle, if any
INSTRUME = ABOb instrument        # Instrument name
OBSTYPE = Imaging                 # Observation type
DETECTOR = Atik 383 L             # Detector identifier
NAXIS1 = 3354                     # [px] X Dimensions of detector in binning 1
NAXIS2 = 2529                     # [px] Y dimension of detector in binning 1
DETSIZE = [1:3354,1:2529]         # [px] [1:x,1:y] Physical CCD dimensions
XPIXSZ = 5.4                      # [um] Pixel X axis size
YPIXSZ = 5.4                      # [um] Pixel Y axis size
PIXSCALE = 3600                   # [arcsec/px] Plate scale in binning 1
PIXSCALE = 36                     # [arcsec/px] Plate scale in binning 1
GAIN =                            # [e-/ADU] Gain
RDNOISE =                         # [e- RMS] Readout noise

[ABObservatory-bis]
TELESCOP = ABObservatory          # Telescope name
APTDIA = 300                      # [mm] Telescope aperture diameter
FOCALLEN = 1170                   # [mm] Telescope focal length
OBS-LONG = -11.2430135            # [deg] Observatory longitude (East < 0)  
OBS-LAT = 43.5235203              # [deg] Observatory latitude (North > 0)  
OBS-ELEV = 1025                   # [m] Observatory altitude above sea level
INSTRUME = ABOb instrument        # Instrument name
OBSTYPE = Imaging                 # Observation type
DETECTOR = Atik 383 L             # Detector identifier
NAXIS1 = 3354                     # [px] X Dimensions of detector in binning 1
NAXIS2 = 2529                     # [px] Y dimension of detector in binning 1
XPIXSZ = 5.4                      # [um] Pixel X axis size
YPIXSZ = 5.4                      # [um] Pixel Y axis size
PIXSCALE = 3600                   # [arcsec/px] Plate scale in binning 1
GAIN =                            # [e-/ADU] Gain
RDNOISE =                         # [e- RMS] Readout noise
[Mapping]
NAXIS1 = NAXIS1                   # [px] X Dimensions of detector
NAXIS2 = NAXIS2                   # [px] Y dimension of detector
OBSERVER = OBSERVER               # Observer name
OBJECT   = OBJECT                 # Name of observed object
RA = OBJCTRA                      # In sexagesimal or decimal format
DEC = OBJCTDEC                    # In sexagesimal or decimal format
DATE-OBS = DATE-OBS               # [YYYY-MM-DDTHH:MM:SS] UTC observation date
FOCUSTEM = FOCUSTEM               # [C] Focuser temperature
FOCUSPOS = FOCUSPOS               # [um] Focuser position
SET-TEMP = SET-TEMP               # [C] CCD temperature set point
CCD-TEMP = CCD-TEMP               # [C] CCD temperature
IMAGETYP = IMAGETYP               # Frame type
FILTER = FILTER                   # Photometric filter used
EXPTIME = EXPTIME                 # [s] Exposure time
XBINNING = XBINNING               # Binning factor in X
YBINNING = YBINNING               # Binning factor in Y
TEMPERAT = AOCAMBT                # [C] Ambient temperature
SWCREATE = SWCREATE               # Software that created FILEORIG

[Formula]
+28 −24
Original line number Diff line number Diff line
[GRT]
[Fixed]
TELESCOP = GRT                    # Telescope name
APTDIA = 400                      # [mm] Telescope aperture diameter
FOCALLEN = 1520                   # [mm] Telescope focal length
OBS-LONG = -11.2430135            # [deg] Observatory longitude (East < 0)  
OBS-LAT = 43.5235203              # [deg] Observatory latitude (North > 0)  
OBS-ELEV = 1025                   # [m] Observatory altitude above sea level
OBS-LONG = 14.020563              # [deg] Observatory longitude (East > 0)  
OBS-LAT =  37.9391183             # [deg] Observatory latitude (North > 0)  
OBS-ELEV = 606                    # [m] Observatory altitude above sea level
DEROTANG = 0                      # [deg] Rotator angle, if any
INSTRUME = GRT instrument         # Instrument name
OBSTYPE = Imaging                 # Observation type
DETECTOR = Moravian CMOS C4-16000 # Detector identifier
NAXIS1 = 4096                     # [px] X Dimensions of detector in binning 1
NAXIS2 = 4096                     # [px] Y dimension of detector in binning 1
DETSIZE = [1:4096,1:4096]         # [px] [1:x,1:y] Physical CCD dimensions
XPIXSZ = 9                        # [um] Pixel X axis size
YPIXSZ = 9                        # [um] Pixel Y axis size
PIXSCALE = 1.22                   # [arcsec/px] Plate scale in binning 1
GAIN =                            # [e-/ADU] Gain
GAIN = 0.850                      # [e-/ADU] Gain
RDNOISE =                         # [e- RMS] Readout noise

[GRT-bis]
TELESCOP = GRT                    # Telescope name
APTDIA = 400                      # [mm] Telescope aperture diameter
FOCALLEN = 1520                   # [mm] Telescope focal length
OBS-LONG = -11.2430135            # [deg] Observatory longitude (East < 0)  
OBS-LAT = 43.5235203              # [deg] Observatory latitude (North > 0)  
OBS-ELEV = 1025                   # [m] Observatory altitude above sea level
INSTRUME = GRT instrument         # Instrument name
OBSTYPE = Imaging                 # Observation type
DETECTOR = Moravian CMOS C4-16000 # Detector identifier
NAXIS1 = 4096                     # [px] X Dimensions of detector in binning 1
NAXIS2 = 4096                     # [px] Y dimension of detector in binning 1
XPIXSZ = 9                        # [um] Pixel X axis size
YPIXSZ = 9                        # [um] Pixel Y axis size
PIXSCALE = 1.22                   # [arcsec/px] Plate scale in binning 1
GAIN =                            # [e-/ADU] Gain
RDNOISE =                         # [e- RMS] Readout noise
[Mapping]
NAXIS1 = NAXIS1                   # [px] X Dimensions of detector
NAXIS2 = NAXIS2                   # [px] Y dimension of detector
OBSERVER = OBSERVER               # Observer name
OBJECT   = OBJECT                 # Name of observed object
RA = OBJCTRA                      # In sexagesimal or decimal format
DEC = OBJCTDEC                    # In sexagesimal or decimal format
DATE-OBS = DATE-OBS               # [YYYY-MM-DDTHH:MM:SS] UTC observation date
FOCUSTEM = FOCTEMP                # [C] Focuser temperature
FOCUSPOS = FOCPOS                 # [um] Focuser position
SET-TEMP = SET-TEMP               # [C] CCD temperature set point
CCD-TEMP = CCD-TEMP               # [C] CCD temperature
IMAGETYP = IMAGETYP               # Frame type
FILTER = FILTER                   # Photometric filter used
EXPTIME = EXPTIME                 # [s] Exposure time
XBINNING = XBINNING               # Binning factor in X
YBINNING = YBINNING               # Binning factor in Y
# TEMPERAT = AOCAMBT                # [C] Ambient temperature
SWCREATE = SWCREATE               # Software that created FILEORIG

[Formula]
+27 −22
Original line number Diff line number Diff line
[OARPAF]
[Fixed]
TELESCOP = OARPAF                 # Telescope name
APTDIA = 800                      # [mm] Telescope aperture diameter
FOCALLEN = 6400                   # [mm] Telescope focal length
OBS-LONG = -9.2034                # [deg] Observatory longitude (East < 0)  
OBS-LONG = 9.2034                 # [deg] Observatory longitude (East > 0)  
OBS-LAT = 44.5912                 # [deg] Observatory latitude (North > 0)  
OBS-ELEV = 1469                   # [m] Observatory altitude above sea level
DEROTANG = -89.67                 # [deg] Rotator angle, if any
INSTRUME = Cerbero                # Instrument name
OBSTYPE = Imaging                 # Observation type
DETECTOR = SBIG STX-16081         # Detector identifier
NAXIS1 = 4144                     # [px] X Dimensions of detector in binning 1
NAXIS2 = 4126                     # [px] Y dimension of detector in binning 1
DETSIZE = [1:4144,1:4126]         # [px] [1:x,1:y] Physical CCD dimensions
XPIXSZ = 9                        # [um] Pixel X axis size
YPIXSZ = 9                        # [um] Pixel Y axis size
PIXSCALE = 0.29                   # [arcsec/px] Plate scale in binning 1
PIXSCALE = 0.283                  # [arcsec/px] Plate scale in binning 1
GAIN = 1.5                        # [e-/ADU] Gain
RDNOISE = 8.0                     # [e- RMS] Readout noise

[OARPAF-bis]
TELESCOP = OARPAF                 # Telescope name
APTDIA = 800                      # [mm] Telescope aperture diameter
FOCALLEN = 6400                   # [mm] Telescope focal length
OBS-LONG = -9.2034                # [deg] Observatory longitude (East < 0)  
OBS-LAT = 44.5912                 # [deg] Observatory latitude (North > 0)  
OBS-ELEV = 1469                   # [m] Observatory altitude above sea level
INSTRUME = Cerbero                # Instrument name
OBSTYPE = Spectroscopy            # Observation type
DETECTOR = SBIG STL-11000M        # Detector identifier
NAXIS1 = 2048                     # [px] X Dimensions of detector in binning 1
NAXIS2 = 4096                     # [px] Y dimension of detector in binning 1
XPIXSZ = 9                        # [um] Pixel X axis size
YPIXSZ = 9                        # [um] Pixel Y axis size
PIXSCALE = 0.29                   # [arcsec/px] Plate scale in binning 1
GAIN =                            # [e-/ADU] Gain
RDNOISE =                         # [e- RMS] Readout noise
[Mapping]
NAXIS1 = NAXIS1                   # [px] X Dimensions of detector
NAXIS2 = NAXIS2                   # [px] Y dimension of detector
OBSERVER = OBSERVER               # Observer name
OBJECT   = OBJECT                 # Name of observed object
RA = RA                           # In sexagesimal or decimal format
DEC = DEC                         # In sexagesimal or decimal format
DATE-OBS = DATE-OBS               # [YYYY-MM-DDTHH:MM:SS] UTC observation date
FOCUSTEM = HIERARCH TEL M2 TEMP   # [C] Focuser temperature
FOCUSPOS = TELFOCUS               # [um] Focuser position
SET-TEMP = SET-TEMP               # [C] CCD temperature set point
CCD-TEMP = CCD-TEMP               # [C] CCD temperature
IMAGETYP = IMAGETYP               # Frame type
FILTER = FILTER                   # Photometric filter used
EXPTIME = EXPTIME                 # [s] Exposure time
XBINNING = XBINNING               # Binning factor in X
YBINNING = YBINNING               # Binning factor in Y
TEMPERAT = HIERARCH CAM AMBIENT   # [C] Ambient temperature
SWCREATE = SWCREATE               # Software that created FILEORIG

[Formula]
RA = (x)/15
Loading