<commit_before># -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License

from __future__ import absolute_import, division, print_function

import numpy as np
import warnings
from astropy.io import fits

from . import UVCal
from . import utils as uvutils


def _warn_oldcalfits(filename):
    warnings.warn('{file} appears to be an old calfits format '
                  'which does not fully conform to the FITS standard. '
                  'Setting default values now, set strict_fits=True '
                  'to error rather than warn on this problem, '
                  'rewrite this file with write_calfits to ensure '
                  'FITS compliance. Support for this file will '
                  'go away in version 1.5'.format(file=filename),
                  DeprecationWarning)


def _warn_olddelay(filename):
    warnings.warn('{file} appears to be an old calfits format '
                  'for delay files which has been deprecated. '
                  'Rewrite this file with write_calfits to ensure '
                  'future compatibility. Support for this file will '
                  'go away in version 1.5'.format(file=filename),
                  DeprecationWarning)


def _warn_oldstyle(filename):
    warnings.warn('{file} appears to be an old calfits format '
                  'which has been deprecated. '
                  'Rewrite this file with write_calfits to ensure '
                  'future compatibility. Support for this file will '
                  'go away in version 1.5'.format(file=filename),
                  DeprecationWarning)


class CALFITS(UVCal):
    """
    Defines a calfits-specific class for reading and writing calfits files.
    """

    def write_calfits(self, filename, run_check=True, check_extra=True,
                      run_check_acceptability=True, clobber=False):
        """
        Write the data to a calfits file.

        Args:
            filename: The calfits file to write to.
            run_check: Option to check for the existence and proper shapes of
                parameters before writing the file. Default is True.
            check_extra: Option to check optional parameters as well as required
                ones. Default is True.
            run_check_acceptability: Option to check acceptable range of the values of
                parameters before writing the file. Default is True.
            clobber: Option to overwrite the filename if the file already exists.
                Default is False.
        """
        if run_check:
            self.check(check_extra=check_extra,
                       run_check_acceptability=run_check_acceptability)

        if self.Nfreqs > 1:
            freq_spacing = self.freq_array[0, 1:] - self.freq_array[0, :-1]
            if not np.isclose(np.min(freq_spacing), np.max(freq_spacing),
                              rtol=self._freq_array.tols[0], atol=self._freq_array.tols[1]):
                raise ValueError('The frequencies are not evenly spaced (probably '
                                 'because of a select operation). The calfits format '
                                 'does not support unevenly spaced frequencies.')
            if np.isclose(freq_spacing[0], self.channel_width):
                freq_spacing = self.channel_width
            else:
                rounded_spacing = np.around(freq_spacing, int(np.ceil(np.log10(self._freq_array.tols[1]) * -1)))
                freq_spacing = rounded_spacing[0]
        else:
            freq_spacing = self.channel_width

        if self.Ntimes > 1:
            time_spacing = np.diff(self.time_array)
            if not np.isclose(np.min(time_spacing), np.max(time_spacing),
                              rtol=self._time_array.tols[0], atol=self._time_array.tols[1]):
                raise ValueError('The times are not evenly spaced (probably '
                                 'because of a select operation). The calfits format '
                                 'does not support unevenly spaced times.')
            if np.isclose(time_spacing[0], self.integration_time / (24. * 60.**2)):
                time_spacing = self.integration_time / (24. * 60.**2)
            else:
                rounded_spacing = np.around(time_spacing,
                                            int(np.ceil(np.log10(self._time_array.tols[1]
                                                                 / self.Ntimes) * -1) + 1))
                time_spacing = rounded_spacing[0]
        else:
            time_spacing = self.integration_time / (24. * 60.**2)

        if self.Njones > 1:
            jones_spacing = np.diff(self.jones_array)
            if np.min(jones_spacing) < np.max(jones_spacing):
                raise ValueError('The jones values are not evenly spaced.'
                                 'The calibration fits file format does not'
                                 ' support unevenly spaced polarizations.')
            jones_spacing = jones_spacing[0]
        else:
            jones_spacing = -1

        prihdr = fits.Header()
        if self.total_quality_array is not None:
            totqualhdr = fits.Header()
            totqualhdr['EXTNAME'] = 'TOTQLTY'
        if self.cal_type != 'gain':
            sechdr = fits.Header()
            sechdr['EXTNAME'] = 'FLAGS'
        # Conforming to fits format
        prihdr['SIMPLE'] = True
        prihdr['BITPIX'] = 32
        prihdr['TELESCOP'] = self.telescope_name
        prihdr['GNCONVEN'] = self.gain_convention
        prihdr['GNSCALE'] = self.gain_scale
        prihdr['CALTYPE'] = self.cal_type
        prihdr['CALSTYLE'] = self.cal_style
        if self.sky_field is not None:
            prihdr['FIELD'] = self.sky_field
        if self.sky_catalog is not None:
            prihdr['CATALOG'] = self.sky_catalog
        if self.ref_antenna_name is not None:
            prihdr['REFANT'] = self.ref_antenna_name
        if self.Nsources is not None:
            prihdr['NSOURCES'] = self.Nsources
        if self.baseline_range is not None:
            prihdr['BL_RANGE'] = '[' + ', '.join([str(b) for b in self.baseline_range]) + ']'
        if self.diffuse_model is not None:
            prihdr['DIFFUSE'] = self.diffuse_model
        prihdr['INTTIME'] = self.integration_time
        prihdr['CHWIDTH'] = self.channel_width
        prihdr['XORIENT'] = self.x_orientation
        if self.cal_type == 'delay':
            prihdr['FRQRANGE'] = ','.join(map(str, self.freq_range))
        elif self.freq_range is not None:
            prihdr['FRQRANGE'] = ','.join(map(str, self.freq_range))
        prihdr['TMERANGE'] = ','.join(map(str, self.time_range))

        if self.observer:
            prihdr['OBSERVER'] = self.observer
        if self.git_origin_cal:
            prihdr['ORIGCAL'] = self.git_origin_cal
        if self.git_hash_cal:
            prihdr['HASHCAL'] = self.git_hash_cal

        if self.cal_type == 'unknown':
            raise ValueError("unknown calibration type. Do not know how to "
                             "store parameters")

        # Define primary header values
        # Arrays have (column-major) dimensions of [Nimages, Njones, Ntimes, Nfreqs, Nspw, Nantennas]
        # For a "delay"-type calibration, Nfreqs is a shallow axis

        # set the axis for number of arrays
        prihdr['CTYPE1'] = ('Narrays', 'Number of image arrays.')
        prihdr['CUNIT1'] = 'Integer'
        prihdr['CDELT1'] = 1
        prihdr['CRPIX1'] = 1
        prihdr['CRVAL1'] = 1<commit_msg>calfits gain_scale write update<commit_after># -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License

from __future__ import absolute_import, division, print_function

import numpy as np
import warnings
from astropy.io import fits

from . import UVCal
from . import utils as uvutils


def _warn_oldcalfits(filename):
    warnings.warn('{file} appears to be an old calfits format '
                  'which does not fully conform to the FITS standard. '
                  'Setting default values now, set strict_fits=True '
                  'to error rather than warn on this problem, '
                  'rewrite this file with write_calfits to ensure '
                  'FITS compliance. Support for this file will '
                  'go away in version 1.5'.format(file=filename),
                  DeprecationWarning)


def _warn_olddelay(filename):
    warnings.warn('{file} appears to be an old calfits format '
                  'for delay files which has been deprecated. '
                  'Rewrite this file with write_calfits to ensure '
                  'future compatibility. Support for this file will '
                  'go away in version 1.5'.format(file=filename),
                  DeprecationWarning)


def _warn_oldstyle(filename):
    warnings.warn('{file} appears to be an old calfits format '
                  'which has been deprecated. '
                  'Rewrite this file with write_calfits to ensure '
                  'future compatibility. Support for this file will '
                  'go away in version 1.5'.format(file=filename),
                  DeprecationWarning)


class CALFITS(UVCal):
    """
    Defines a calfits-specific class for reading and writing calfits files.
    """

    def write_calfits(self, filename, run_check=True, check_extra=True,
                      run_check_acceptability=True, clobber=False):
        """
        Write the data to a calfits file.

        Args:
            filename: The calfits file to write to.
            run_check: Option to check for the existence and proper shapes of
                parameters before writing the file. Default is True.
            check_extra: Option to check optional parameters as well as required
                ones. Default is True.
            run_check_acceptability: Option to check acceptable range of the values of
                parameters before writing the file. Default is True.
            clobber: Option to overwrite the filename if the file already exists.
                Default is False.
        """
        if run_check:
            self.check(check_extra=check_extra,
                       run_check_acceptability=run_check_acceptability)

        if self.Nfreqs > 1:
            freq_spacing = self.freq_array[0, 1:] - self.freq_array[0, :-1]
            if not np.isclose(np.min(freq_spacing), np.max(freq_spacing),
                              rtol=self._freq_array.tols[0], atol=self._freq_array.tols[1]):
                raise ValueError('The frequencies are not evenly spaced (probably '
                                 'because of a select operation). The calfits format '
                                 'does not support unevenly spaced frequencies.')
            if np.isclose(freq_spacing[0], self.channel_width):
                freq_spacing = self.channel_width
            else:
                rounded_spacing = np.around(freq_spacing, int(np.ceil(np.log10(self._freq_array.tols[1]) * -1)))
                freq_spacing = rounded_spacing[0]
        else:
            freq_spacing = self.channel_width

        if self.Ntimes > 1:
            time_spacing = np.diff(self.time_array)
            if not np.isclose(np.min(time_spacing), np.max(time_spacing),
                              rtol=self._time_array.tols[0], atol=self._time_array.tols[1]):
                raise ValueError('The times are not evenly spaced (probably '
                                 'because of a select operation). The calfits format '
                                 'does not support unevenly spaced times.')
            if np.isclose(time_spacing[0], self.integration_time / (24. * 60.**2)):
                time_spacing = self.integration_time / (24. * 60.**2)
            else:
                rounded_spacing = np.around(time_spacing,
                                            int(np.ceil(np.log10(self._time_array.tols[1]
                                                                 / self.Ntimes) * -1) + 1))
                time_spacing = rounded_spacing[0]
        else:
            time_spacing = self.integration_time / (24. * 60.**2)

        if self.Njones > 1:
            jones_spacing = np.diff(self.jones_array)
            if np.min(jones_spacing) < np.max(jones_spacing):
                raise ValueError('The jones values are not evenly spaced.'
                                 'The calibration fits file format does not'
                                 ' support unevenly spaced polarizations.')
            jones_spacing = jones_spacing[0]
        else:
            jones_spacing = -1

        prihdr = fits.Header()
        if self.total_quality_array is not None:
            totqualhdr = fits.Header()
            totqualhdr['EXTNAME'] = 'TOTQLTY'
        if self.cal_type != 'gain':
            sechdr = fits.Header()
            sechdr['EXTNAME'] = 'FLAGS'
        # Conforming to fits format
        prihdr['SIMPLE'] = True
        prihdr['BITPIX'] = 32
        prihdr['TELESCOP'] = self.telescope_name
        prihdr['GNCONVEN'] = self.gain_convention
        prihdr['CALTYPE'] = self.cal_type
        prihdr['CALSTYLE'] = self.cal_style
        if self.sky_field is not None:
            prihdr['FIELD'] = self.sky_field
        if self.sky_catalog is not None:
            prihdr['CATALOG'] = self.sky_catalog
        if self.ref_antenna_name is not None:
            prihdr['REFANT'] = self.ref_antenna_name
        if self.Nsources is not None:
            prihdr['NSOURCES'] = self.Nsources
        if self.baseline_range is not None:
            prihdr['BL_RANGE'] = '[' + ', '.join([str(b) for b in self.baseline_range]) + ']'
        if self.diffuse_model is not None:
            prihdr['DIFFUSE'] = self.diffuse_model
        if self.gain_scale is not None:
            prihdr['GNSCALE'] = self.gain_scale
        prihdr['INTTIME'] = self.integration_time
        prihdr['CHWIDTH'] = self.channel_width
        prihdr['XORIENT'] = self.x_orientation
        if self.cal_type == 'delay':
            prihdr['FRQRANGE'] = ','.join(map(str, self.freq_range))
        elif self.freq_range is not None:
            prihdr['FRQRANGE'] = ','.join(map(str, self.freq_range))
        prihdr['TMERANGE'] = ','.join(map(str, self.time_range))

        if self.observer:
            prihdr['OBSERVER'] = self.observer
        if self.git_origin_cal:
            prihdr['ORIGCAL'] = self.git_origin_cal
        if self.git_hash_cal:
            prihdr['HASHCAL'] = self.git_hash_cal

        if self.cal_type == 'unknown':
            raise ValueError("unknown calibration type. Do not know how to "
                             "store parameters")

        # Define primary header values
        # Arrays have (column-major) dimensions of [Nimages, Njones, Ntimes, Nfreqs, Nspw, Nantennas]
        # For a "delay"-type calibration, Nfreqs is a shallow axis

        # set the axis for number of arrays
        prihdr['CTYPE1'] = ('Narrays', 'Number of image arrays.')
        prihdr['CUNIT1'] = 'Integer'
        prihdr['CDELT1'] = 1
        prihdr['CRPIX1'] = 1
        prihdr['CRVAL1'] = 1
{'fraction_non_alphanumeric': 0.09050308682516747, 'fraction_numerical': 0.008275318534086432, 'mean_word_length': 1.8665286144578312, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '875933', 'n_tokens_mistral': 4414, 'n_tokens_neox': 4088, 'n_words': 1175}