        Checks if the triggering antennas lie in a straight vertical line
        Throws error if not.

        Parameters
        ----------
        station: Station object
            Description of the current station
        det: Detector object
            Description of the current detector
        triggered_channels: array of ints
            channels ids of the channels that form the primary phasing array
            if None, all channels are taken


        Calculate power summed over a length defined by 'window', overlapping at intervals defined by 'step'

        Parameters
        ----------
        coh_sum: array of floats
            Phased signal to be integrated over
        window: int
            Power integral window
            Units of ADC time ticks
        step: int
            Time step in power integral. If equal to window, there is no time overlap
            in between neighboring integration windows
            Units of ADC time ticks.
        adc_output: string
            - 'voltage' to store the ADC output as discretised voltage trace
            - 'counts' to store the ADC output in ADC counts

        Returns
        -------
        power:
            Integrated power in each integration window
        num_frames
            Number of integration windows calculated


        Phase signals together given the rolls

        Parameters
        ----------
        traces: 2D array of floats
            Signals from the antennas to be phased together.
        beam_rolls: 2D array of floats
            The amount to shift each signal before phasing the
            traces together

        Returns
        -------
        phased_traces: array of arrays


        simulates phased array trigger for each event

        Several channels are phased by delaying their signals by an amount given
        by a pointing angle. Several pointing angles are possible in order to cover
        the sky. The array triggered_channels controls the channels that are phased,
        according to the angles phasing_angles.

        Parameters
        ----------
        station: Station object
            Description of the current station
        det: Detector object
            Description of the current detector
        Vrms: float
            RMS of the noise on a channel, used to automatically create the digitizer
            reference voltage. If set to None, tries to use reference voltage as defined
            int the detector description file.
        threshold: float
            threshold above (or below) a trigger is issued, absolute amplitude
        triggered_channels: array of ints
            channels ids of the channels that form the primary phasing array
            if None, all channels are taken
        phasing_angles: array of float
            pointing angles for the primary beam
        ref_index: float
            refractive index for beam forming
        trigger_adc: bool, default True
            If True, analog to digital conversion is performed. It must be specified in the
            detector file. See analogToDigitalConverter module for information
        clock_offset: float
            Overall clock offset, for adc clock jitter reasons
        trigger_filter: array floats
            Freq. domain of the response to be applied to post-ADC traces
            Must be length for "MC freq"
        upsampling_factor: integer
            Upsampling factor. The trace will be a upsampled to a
            sampling frequency int_factor times higher than the original one
            after conversion to digital
        window: int
            Power integral window
            Units of ADC time ticks
        step: int
            Time step in power integral. If equal to window, there is no time overlap
            in between neighboring integration windows.
            Units of ADC time ticks
        Returns
        -------
        is_triggered: bool
            True if the triggering condition is met
        trigger_delays: dictionary
            the delays for the primary channels that have caused a trigger.
            If there is no trigger, it's an empty dictionary


        simulates phased array trigger for each event

        Several channels are phased by delaying their signals by an amount given
        by a pointing angle. Several pointing angles are possible in order to cover
        the sky. The array triggered_channels controls the channels that are phased,
        according to the angles phasing_angles.

        Parameters
        ----------
        evt: Event object
            Description of the current event
        station: Station object
            Description of the current station
        det: Detector object
            Description of the current detector
        Vrms: float
            RMS of the noise on a channel, used to automatically create the digitizer
            reference voltage. If set to None, tries to use reference voltage as defined
            int the detector description file.
        threshold: float
            threshold above (or below) a trigger is issued, absolute amplitude
        triggered_channels: array of ints
            channels ids of the channels that form the primary phasing array
            if None, all channels are taken
        trigger_name: string
            name for the trigger
        phasing_angles: array of float
            pointing angles for the primary beam
        set_not_triggered: bool (default: False)
            if True not trigger simulation will be performed and this trigger will be set to not_triggered
        ref_index: float
            refractive index for beam forming
        trigger_adc: bool, default True
            If True, analog to digital conversion is performed. It must be specified in the
            detector file. See analogToDigitalConverter module for information
        clock_offset: float
            Overall clock offset, for adc clock jitter reasons
        adc_output: string
            - 'voltage' to store the ADC output as discretised voltage trace
            - 'counts' to store the ADC output in ADC counts
        trigger_filter: array floats
            Freq. domain of the response to be applied to post-ADC traces
            Must be length for "MC freq"
        upsampling_factor: integer
            Upsampling factor. The trace will be a upsampled to a
            sampling frequency int_factor times higher than the original one
            after conversion to digital
        window: int
            Power integral window
            Units of ADC time ticks
        step: int
            Time step in power integral. If equal to window, there is no time overlap
            in between neighboring integration windows.
            Units of ADC time ticks
        Returns
        -------
        is_triggered: bool
            True if the triggering condition is met


        Setup function for the eventReader module

        Parameters
        -----------
        filename: array if strings
            names of the input files
        read_detector: boolean
            If True, the eventReader will parse the detector description and event event headers
             in the event files. This is necessary to use the get_detector functions
        log_level: logging enum


    Returns the function to scan a file with the given file version
    Convention for function names is scan_files_MAJORVERSION_MINORVERSION,
    specifying the first version that function is for


        begin method

        Parameters
        ----------
        filename: string
            Name of the file into which events shall be written
        max_file_size: maximum file size in Mbytes
                    (if the file exceeds the maximum file the output will be split into another file)
        check_for_duplicates: bool (default False)
            if True, the event writer raises an exception when an event with a (run,eventid) pair is written that is already
            present in the data file
        events_per_file: int
            Maximum number of events to be written into the same file. After more than events_per_file have been written
            into the same file, the output will be split into another file. If max_file_size and events_per_file are
            both set, the file will be split whenever any of the two conditions is fullfilled.


        writes NuRadioReco event into a file

        Parameters
        ----------
        evt: NuRadioReco event object
        det: detector object
            If a detector object is passed, the detector description for the
            events is written in the file as well
        mode: dictionary (default: {'Channels': True, 'ElectricFields': True, 'SimChannels': True, 'SimElectricFields': True})
            specifies what will saved into the *.nur output file
            can contain the strings
            * 'Channels': if True channel traces of Stations will be saved
            * 'ElectricFields': if True (reconstructed) electric field traces of Stations will be saved
            * 'SimChannels': if True SimChannels of SimStations will be saved
            * 'SimElectricFields': if True electric field traces of SimStations will be saved


        Checks if an event with the same ID and run number has already been written to the file
        and throws an error if that is the case.


        Begin function of the ARA reader

        Parameters
        ----------
        input_file: string
            path to file to read


        Run function of the ARA reader

        Parameters
        ----------
        n_channels: int
            number of ARA channels to loop over, default 16

        sampling: float (units time)
            default sampling of ARA detector


        Parameters
        ----------
        noise_folder: string
            the folder containing the noise files
        station_id: int
            the station id, specifies from which station the forced triggers are used
            as a noise sample. The data must have the naming convention 'forced_station_??.nur'
            where ?? is replaced with the station id. If station_id is None, the noiseImporter
            will try to find the station with the same iD as the one passed to the run
            function in the noise file
        noise_files: list of strings (default: None)
            List of noisefiles. If None is passed, all files in the noise_folder are used
        channel_mapping: dict or None
            option relevant for MC studies of new station designs where we do not
            have forced triggers for. The channel_mapping dictionary maps the channel
            ids of the MC station to the channel ids of the noise data
            Default is None which is 1-to-1 mapping
        log_level: loggging log level
            the log level, default logging.WARNING
        mean_opt: boolean
            option to subtract mean from trace. Set mean_opt=False to remove mean subtraction from trace.


Calculate weights according to the area that one simulated position represents.
    Weights are therefore given in units of area.
    Note: The volume of a 2d convex hull is the area.


    creates an NuRadioReco sim station from the observer object of the coreas hdf5 file

    Parameters
    ----------
    station_id : station id
        the id of the station to create
    corsika : hdf5 file object
        the open hdf5 file object of the corsika hdf5 file
    observer : hdf5 observer object
    channel_ids :
    weight : weight of individual station
        weight corresponds to area covered by station

    Returns
    -------
    sim_station: sim station
        ARIANNA simulated station object


        begin method

        initialize readCoREAS module

        Parameters
        ----------
        input_files: input files
            list of coreas hdf5 files
        xmin: float
            minimum x coordinate of the area in which core positions are distributed
        xmax: float
            maximum x coordinate of the area in which core positions are distributed
        ymin: float
            minimum y coordinate of the area in which core positions are distributed
        ynax: float
            maximum y coordinate of the area in which core positions are distributed
        n_cores: number of cores (integer)
            the number of random core positions to generate for each input file
        seed: int (default: None)
            Seed for the random number generation. If None is passed, no seed is set


        Read in a random sample of stations from a CoREAS file.
        For each position the closest observer is selected and a simulated
        event is created for that observer.

        Parameters
        ----------
        detector: Detector object
            Detector description of the detector that shall be simulated
        output_mode: integer (default 0)
            0: only the event object is returned
            1: the function reuturns the event object, the current inputfilename, the distance between the choosen station and the requested core position,
               and the area in which the core positions are randomly distributed


        begin method

        initialize readCoREAS module

        Parameters
        ----------
        input_files: input files
            list of coreas hdf5 files
        station_id: station id
            id number of the station
        n_cores: number of cores (integer)
            the number of random core positions to generate for each input file
        max_distance: radius of random cores (double or None)
            if None: max distance is set to the maximum ground distance of the
            star pattern simulation
        seed: int (default: None)
            Seed for the random number generation. If None is passed, no seed is set


        Read in a random sample of stations from a CoREAS file.
        A number of random positions is selected within a certain radius.
        For each position the closest observer is selected and a simulated
        event is created for that observer.

        Parameters
        ----------
        detector: Detector object
            Detector description of the detector that shall be simulated
        output_mode: integer (default 0)
            0: only the event object is returned
            1: the function reuturns the event object, the current inputfilename, the distance between the choosen station and the requested core position,
               and the area in which the core positions are randomly distributed


        begin method

        initialize readCoREAS module

        Parameters
        ----------
        input_files: input files
            list of coreas hdf5 files
        station_id: station id
            id number of the radio station as defined in detector


        Reads in all observers in the CoREAS files and returns a new simulated
        event for each.

        Parameters
        ----------
        detector: Detector object
            Detector description of the detector that shall be simulated


        run method, selects CoREAS simulations that have any signal in
        desired frequency_window.
        Crude approximation with n_std sigma * noise

        Parameters
        ------------
        evt: Event
        sim_station: sim_station
            CoREAS simulated efields
        det: Detector
        frequency_window: list
            [lower, upper] frequencies that will be used for analysis
        n_std: int
            number of std deviations needed, can make cut stricter, if needed

        Returns
        ------------
        selected_sim: bool
            if True then simulation has signal in desired range


        begin method

        initialize readCoREASShower module

        Parameters
        ----------
        input_files: input files
            list of coreas hdf5 files
        det: genericDetector object
            If a genericDetector is passed, the stations from the CoREAS file
            will be added to it and the run method returns both the event and
            the detector
        logger_level: string or logging variable
            Set verbosity level for logger (default: logging.NOTSET)
        set_ascending_run_and_event_number: bool
            If set to True the run number and event id is set to
            self.__ascending_run_and_event_number instead of beeing taken
            from the simulation file. The value is increases monoton.
            This can be used to avoid ambiguities values (default: False)


Reads in a CoREAS file and returns an event containing all simulated stations


    This function parses the antenna names given in a CoREAS simulation and tries to find an ID
    It can be extended to other name patterns


        read FPN and gain calibrated ARIANNA data (snowshovel data format)

        Parameters
        ----------
        input_files: array of strings
            a list of input files
        trigger_types: list of strings or None
            only events that have the specified trigger types are read.
            The trigger types can ['thermal', 'forced']. Default is None which
            means that all events are read regardless of their trigger type
        time_interval: [datetime, datetime] or None
            all events outside of the specified time interval are skipped
            Default is None, i.e., all events are read
        tree: string
            low level reconstruction stage. Available options are
             * RawData: the raw ADC counts
             * FPNSubData: FPN subtracted data (still ADC counts but with mean zero)
             * AmpOutData: FPN and gain calibrated data (default)
        run_number: int or None
            run number, all events with a different run number will be skipped.
            Default is None which means that all events are read in
        event_ids: dictionary or None
            specify any combination of run and event ids, all other events will be skipped.
            key is the run id, values are the event ids
            Default is None which means that all events are read in
        random_iterator: bool (default False)
            if True walk through event in a random order


adds a NuRadioReco.framework.sim_channel to the SimStation object


returns true if station has trigger, false otherwise


        registers modules applied to this event

        Parameters
        -----------
        instance: module instance
            the instance of the module that should be registered
        name: module name
            the name of the module
        kwargs:
            the key word arguments of the run method


        registers modules applied to this event

        Parameters
        -----------
        station_id: int
            the station id
        instance: module instance
            the instance of the module that should be registered
        name: module name
            the name of the module
        kwargs:
            the key word arguments of the run method


        returns an interator that loops over all modules. If a station id is provided it loops
        over all modules that are applied on event or station level (on this particular station). If no
        station_id is provided, the loop is only over the event modules.
        The order follows the sequence these modules were applied


        Adds a radio shower to the event

        Parameters
        ------------------------
        shower: RadioShower object
            The shower to be added to the event


        Returns true if at least one shower is stored in the event

        If shower_id is given, it checks if this particular shower exists


        Add a simulated shower to the event

        Parameters
        ------------------------
        sim_shower: RadioShower object
            The shower to be added to the event


        Returns true if at least one simulated shower is stored in the event

        If shower_id is given, it checks if this particular shower exists


        checks if station has a trigger with a certain name

        Paramters
        ---------
        trigger_name: string
            the name of the trigger

        Returns bool


        convenience function.

        Parameters
        ----------
        trigger_name: string or None (default None)
            * if None: The function returns False if not trigger was set. If one or multiple triggers were set,
                       it returns True if any of those triggers triggered
            * if trigger name is set: return if the trigger with name 'trigger_name' has a trigger


        Uses the fourier shift theorem to apply a time shift to the trace
        Note that this is a cyclic shift, which means the trace will wrap
        around, which might lead to problems, especially for large time shifts.

        Parameters:
        --------------------
        delta_t: float
            Time by which the trace should be shifted
        silent: boolean (default:False)
            Turn off warnings if time shift is larger than 10% of trace length
            Only use this option if you are sure that your trace is long enough
            to acommodate the time shift


        Add a generic station to the detector. The station is treated like a
        generic station in the original detector description file, i.e. all missing
        properties and all channels will be taken from the default station.
        If a station with the same ID already exists, this function does nothing.

        Parameters
        --------------
        station_dict: dictionary
            dictionary containing the station properties. Needs to at least include
            a station_id, any other missing parameters will be taken from the
            default station


        Adds an entry to the list of event-specific changes to the detector
        description.

        Parameters
        ------------------
        properties: dictionary
            Dictionary of the properties that should be changed, with keys being
            any of the property names in the detector description and values the
            values that these properties should be changed to
        station_id: integer
            ID of the station whose properties should be changed
        run_number: integer
            Run number of the event for which the changes are valid
        event_id: integer
            Event ID of the event for which the changes are valid


resets all previously set antenna orientation offsets


resets all previously set antenna position offsets


    helper function to linearly interpolate between two complex numbers

    Parameters:
    ------
    x: float
        the requested position
    x0, y0: float, complex float
        the first data point
    x1, y1: float, complex float
        the second data point
    interpolation_method: string
        specifies if interpolation is in
        * complex (default) i.e. real and imaginary part
        * magnitude and phase

    Returns: compex float
        the interpolated value


Same as `interpolate_linear` but all parameters can be vectors


    Preprocess an antenna pattern in XFDTD file format. The vector effective length is calculated and the output is saved to the NuRadioReco pickle format.

    This conversion function ASSUMES THAT THE XFDTD SIMULATION IS DONE IN AIR! HERE WE DO A FIRST ORDER RESCALING
    TO A DIFFERENT INDEX OF REFRACTION by just rescaling the frequencies by f -> f/n.

    Parameters:
    ----------
    path_gain: string
        path to gain file
    path_phases: string
        path to phases file
    outputfilename: string
        path to outputfilename
    n_index: float
        refractive index for requested antenna file. The method assumes that simulations are done in air (n = 1)


    reads in WIPLD data

    Parameters
    ----------
    ad1: string
        path to ad1 file
    ra1: string
        path to radiation pattern file
    orientation: string
        path to orientation file
    gen_num: int
        which antenna (one or two) to pull from
    s_parameters: list of 2 ints
        determines which s-parametr to extract (ex: [1,2] extracts S_12 parameter).

    Returns
    -----------------
    all parameters of the files


    preprocesses WIPLD file

    this function implements the older insufficient calculation of the vector effective length. This VEL only
    relates the incident electric field to the open circuit voltage and not the voltage in a 50 Ohm system.

    Parameters
    ----------
    path: string
        path to folder containing ad1, ra1, and orientation files.
    gen_num: int
        which antenna (one or two) to pull from
    s_parameters: list of 2 ints
        determines which s-parametr to extract (ex: [1,2] extracts S_12 parameter).

    Returns
    ---------------
        * orientation theta: orientation of the antenna, as a zenith angle (0deg is the zenith, 180deg is straight down); for LPDA: outward along boresight; for dipoles: upward along axis of azimuthal symmetry
        * orientation phi: orientation of the antenna, as an azimuth angle (counting from East counterclockwise); for LPDA: outward along boresight; for dipoles: upward along axis of azimuthal symmetry
        * rotation theta: rotation of the antenna, is perpendicular to 'orientation', for LPDAs: vector perpendicular to the plane containing the the tines
        * rotation phi: rotation of the antenna, is perpendicular to 'orientation', for LPDAs: vector perpendicular to the plane containing the the tines
        * ff2: array of frequencies
        * theta: zenith angle of inicdent electric field
        * phi: azimuth angle of incident electric field
        * H_phi: the complex vector effective length of the ePhi polarization component
        * H_theta: the complex vector effective length of the eTheta polarization component


    saves preprocessed WIPLD files to a pickle file

    Parameters
    ----------
    path: string
        path to folder containing ad1, ra1, and orientation files.


    preprocesses WIPLD file

    this function implements the older insufficient calculation of the vector effective length. This VEL only
    relates the incident electric field to the open circuit voltage and not the voltage in a 50 Ohm system.

    Parameters
    ----------
    path: string
        path to folder containing ad1, ra1, and orientation files.
    gen_num: int
        which antenna (one or two) to pull from
    s_parameters: list of 2 ints
        determines which s-parametr to extract (ex: [1,2] extracts S_12 parameter).

    Returns
    ------------
        * orientation theta: orientation of the antenna, as a zenith angle (0deg is the zenith, 180deg is straight down); for LPDA: outward along boresight; for dipoles: upward along axis of azimuthal symmetry
        * orientation phi: orientation of the antenna, as an azimuth angle (counting from East counterclockwise); for LPDA: outward along boresight; for dipoles: upward along axis of azimuthal symmetry
        * rotation theta: rotation of the antenna, is perpendicular to 'orientation', for LPDAs: vector perpendicular to the plane containing the the tines
        * rotation phi: rotation of the antenna, is perpendicular to 'orientation', for LPDAs: vector perpendicular to the plane containing the the tines
        * ff2: array of frequencies
        * theta: zenith angle of inicdent electric field
        * phi: azimuth angle of incident electric field
        * H_phi: the complex vector effective length of the ePhi polarization component
        * H_theta: the complex vector effective length of the eTheta polarization component


    this function saves the realized gain in an ARASim readable format

    Parameters
    ----------
    path: string
        path to folder containing ad1, ra1, and orientation files.


    Helper function that parses the ARAsim ASCII files containig antenna responses

    Parameters:
    ----------
    ara: string
        path to the file

    Returns:
        * ff: array of floats
            frequencies
        * thetas: array of floats
            zenith angle of inicdent electric field
        * phis: array of floats
            azimuth angle of inicdent electric field
        * gains: array of floats
            corresponding linear gain values
        * phases: array of floats
            corresponding phases


    preprocess an antenna pattern in the ARASim ASCII file format. The vector effective length is calculated and
    the output is saved to the NuRadioReco pickle format.

    Parameters:
    ----------
    path: string
        the path to the file


    Helper function that parses the HFSS files containig antenna responses

    Parameters:
    ----------
    hfss: string
        path to the file

    Returns:
        * ff: array of floats
            frequencies
        * thetas: array of floats
            zenith angle of inicdent electric field
        * phis: array of floats
            azimuth angle of inicdent electric field
        * magnitudes_theta: array of floats
            corresponding logarithmic magnitude values theta component
        * magnitudes_phi: array of floats
            corresponding logarithmic magnitude values phi component
        * phases_phi: array of floats
            corresponding phases phi component
        * phases_theta: array of floats
            corresponding phases theta component


    preprocess an antenna pattern in the HFSS file format. The vector effective length is calculated and the output is saved in the NuRadioReco pickle format.

    The vector effective length calculation still needs to be verified.

    The frequencies, theta, phi, magnitude theta, magnitude phi, phase theta and phase phi are read from the csv file and than ordered according to the NuRadioReco format.

    Parameters:
    ----------
    path: string
        the path to the file


    preprocess an antenna pattern in the XFDTD file format. The vector effective length is calculated and
    the output is saved to the NuRadioReco pickle format.

    Parameters:
    ----------
    path: string
        the path to the file


        transform zenith and azimuth angle in ARIANNA coordinate system to the WIPLD coordinate system.
        In addition the orientation of the antenna as deployed in the field is taken into account.

        Parameters:
        ----------


get vector effective length in WIPLD coordinate system


        loads an antenna pattern and returns the antenna pattern class

        Paramters
        ----------
        name: string
            the name of the antenna pattern
        **kwargs: dict
            key word arguments that are passed to the init function of the `AntennaPattern` class (see
            documentation of this class for further information)


    buffers the complete SQL database into a TinyDB object (either in memory or into a local JSON file)

    Parameters
    ----------
    in_memory: bool
        if True: the mysql database will be buffered as a tiny tb object that only exists in memory
        if False: the mysql database will be buffered as a tiny tb object and saved in a local json file
    filename: string
        only relevant if `in_memory = True`: the filename of the json file of the tiny db object


        checks if a station is present in the database

        Parameters
        ----------
        station_id: int
            the station id

        Returns bool


        updates the detector description to a new time

        Parameters
        ----------
        time: astropy.time.Time
            the time to update the detector description to
            for backward compatibility datetime is also accepted, but astropy.time is prefered


        returns true if the detector description has the field `noiseless` and if this field is True.

        Allows to run a noiseless simulation on specific channels (for example to simulate a single-antenna proxy
        along with the phased array)

        Parameters
        ----------
        station_id: int
            station id
        channel_id: int
            the channel id


    Default file was imported from:
    https://github.com/bhokansonfasig/pyrex/tree/master/pyrex/custom/ara/data

    Parameters
    --------
    path: string
        Path to the file containing the system response


    Read out amplifier gain and phase. Currently only examples have been implemented.
    Needs a better structure in the future, possibly with database.


load individual amp measurement from file and buffer interpolation function


    preprocess individual 300 series measurements

    Parameters
    ----------
    amp: string
        amp series - box number - and channel. Ex: 300-01
    channel: int
        channel id
    path: string
        directory where amp responses are located. Default is "HardwareResponses/"


    Read out amplifier gain and phase. Currently only examples have been implemented.
    Needs a better structure in the future, possibly with database.
    The hardware response incorporator currently reads in the load amp response.
    If you want to read in the RI function fur your reconstruction it needs to be changed
    in modules/RNO_G/hardweareResponseIncorporator.py l. 52, amp response.


    Controls the map with station positions

    Parameters:
    ---------------
    dummy: any
        Is only used to trigger a redrawing of the map. Any action that
        requires the map to be redrawn changes the content of the dummy
        element to trigger a redraw, but the dummy does not actually
        contain any relevant information.


    Receives the information which station in the station position
    plot was clicked and passes it to the element containing the
    selected station

    Parameters:
    -------------
    click: dict
        Dictionary containing information on the click event


    Draws the 3D view of the selected station

    Parameters:
    -----------------------
    station_id: int
        ID of the selected station
    checklist: array
        Array containing state of the station view
        options checkboxes


    Receives the information which channel in the station layout
    plot was clicked and passes it to the element containing the
    selected channel

    Parameters:
    -------------
    click: dict
        Dictionary containing information on the click event


    Draws plot for antenna and amplifier response

    Parameters:
    -----------------------
    response_type: array of strings
        Contains state of the radio buttons that allow to select if response of
        only amps, only antennas or amps + antennas should be drawn
    zenith: number
        Value of the slider to select the zenith angle of the incoming signal
        (relevant for antenna response)
    azimuth: number
        Value of the slider to select the azimuth angle of the incoming signal
        (relevant for antenna response)
    station_id: int
        ID of the selected station
    channel_id: int
        ID of the selected channel
    log_checklist: array of strings
        Contains state of the checklist to select logarithmic plotting
        of amplitude and detrending of phase


    Updates the table showing the station properties

    Parameters:
    -----------------
    station_id: int
        The ID of the station whose properties are shown


    Updates the options in the dropdown menu to select the file from which the
    detector should be read.

    Parameters:
    -----------------------
    folder_dummy: string
        Path to the folder from which files can be selected
    refresh_button: int
        Technically gives the number of times the refresh button was clicked, but in
        practice this parameter is ony used to trigger an update after a click on the
        button
    file_type: string
        The type of file from which the detector should be read. Options are 'event_file',
        'detector' and 'generic_detector'
    folder_input: string
        Path to the folder from which files can be selected.


    Opens the detector. After the detector has been opened, it returns an output
    for a dummy object to trigger a redraw of all plots

    Parameters:
    -----------------
    n_clicks: int
        Technically, the number of times the reload button was clicked, practically
        only used to trigger this function
    time_n_clicks: int
        Similar use as n_clicks, but for the


    Controls if the inputs to set default station and default channel
    are shown

    Parameters:
    --------------------------
    detector_type: string
        Value of the detector type selection dropdown


    Controls if the button to open the selected detector file is active

    Parameters:
    -----------------------
    filename: string
        Name of the selected detector file
    detector_type: string
        Value of the detector type selection dropdown
    default_station: int
        Value of the default station input


    Controls if the event selection menu is visible

    Parameters:
    ---------------------
    file_type: str
        Value of the detector type selection dropdown


    Controls the content of the channel properties table

    Parameters:
    ---------------------
    station_id: int
        ID of the station whose properties are displayed

    channel_id: int
        ID of the channel whose properties are displayed


    if 'recefield' in dropdown_traces or 'simefield' in dropdown_traces:
        det.update(station.get_station_time())
    if 'recefield' in dropdown_traces:
        channel_ids = []
        for channel in station.iter_channels():
            channel_ids.append(channel.get_id())
        for electric_field in station.get_electric_fields():
            for i_trace, trace in enumerate(
                    trace_utilities.get_channel_voltage_from_efield(station, electric_field, channel_ids, det,
                                                                    station.get_parameter(stnp.zenith),
                                                                    station.get_parameter(stnp.azimuth),
                                                                    antenna_pattern_provider)):
                direction_time_delay = geometryUtilities.get_time_delay_from_direction(
                    station.get_parameter(stnp.zenith), station.get_parameter(stnp.azimuth),
                    det.get_relative_position(station.get_id(), channel_ids[i_trace]) - electric_field.get_position())
                time_shift = direction_time_delay - trace_start_time_offset
                plotly.graph_objs.append_trace(plotly.graph_objs.Scatter(
                    x=(electric_field.get_times() + time_shift) / units.ns,
                    y=fft.freq2time(trace, electric_field.get_sampling_rate()) / units.mV,
                    line=dict(
                        dash='solid',
                        color=colors[i_trace % len(colors)]
                    ),
                    opacity=.5
                ), i_trace + 1, 1)
                plotly.graph_objs.append_trace(plotly.graph_objs.Scatter(
                    x=electric_field.get_frequencies() / units.MHz,
                    y=np.abs(trace) / units.mV,
                    line=dict(
                        dash='solid',
                        color=colors[i_trace % len(colors)]
                    ),
                    opacity=.5
                ), i_trace + 1, 2)
    if 'simefield' in dropdown_traces:
        sim_station = station.get_sim_station()
        for i_channel, channel in enumerate(station.iter_channels()):
            for electric_field in sim_station.get_electric_fields_for_channels([channel.get_id()]):
                trace = \
                    trace_utilities.get_channel_voltage_from_efield(sim_station, electric_field, [channel.get_id()],
                                                                    det,
                                                                    electric_field.get_parameter(efp.zenith),
                                                                    electric_field.get_parameter(efp.azimuth),
                                                                    antenna_pattern_provider)[0]
                channel = station.get_channel(channel.get_id())
                if station.is_cosmic_ray():
                    direction_time_delay = geometryUtilities.get_time_delay_from_direction(
                        sim_station.get_parameter(stnp.zenith), sim_station.get_parameter(stnp.azimuth),
                        det.get_relative_position(sim_station.get_id(),
                                                  channel.get_id()) - electric_field.get_position())
                    time_shift = direction_time_delay - trace_start_time_offset
                else:
                    time_shift = - trace_start_time_offset
                fig.append_trace(plotly.graph_objs.Scatter(
                    x=(electric_field.get_times() + time_shift) / units.ns,
                    y=fft.freq2time(trace, electric_field.get_sampling_rate()) / units.mV,
                    line=dict(
                        dash='solid',
                        color=colors[i_channel % len(colors)]
                    ),
                    opacity=.5
                ), i_channel + 1, 1)
                fig.append_trace(plotly.graph_objs.Scatter(
                    x=electric_field.get_frequencies() / units.MHz,
                    y=np.abs(trace) / units.mV,
                    line=dict(
                        dash='solid',
                        color=colors[i_channel % len(colors)]
                    ),
                    opacity=.5
                ), i_channel + 1, 2)


    Read in a pickle file and return the result
    This utility is supposed to provide compatibility for pickles created with
    different python versions. If a simple pickle.load fails, it will try to
    load the file with a specific encoding.

    Parameters
    ---------
    filename: string
        Name of the pickle file to be opened
    encoding: string
        Encoding to be used if the first attempt to open the pickle fails


    energy is defined as the integral of squared voltage normalized to a time window of 128 ns

    Parameters
    ----------
    energy:


        generates noise traces for all channels that will cause a high/low majority logic trigger

        Returns np.array of shape (n_channels, n_samples)


    This function performs an upsampling by inserting a number of zeroes
    between samples and then applying a finite impulse response (FIR) filter.

    Parameters
    ----------
    trace: array of floats
        Trace to be upsampled
    original_sampling_frequency: float
        Sampling frequency of the input trace
    int_factor: integer
        Upsampling factor. The resulting trace will have a sampling frequency
        int_factor times higher than the original one
    ntaps: integer
        Number of taps (order) of the FIR filter

    Returns
    -------
    upsampled_trace: array of floats
        The upsampled trace


    Filters a trace using a Butterworth filter.

    Parameters
    ----------
    trace: array of floats
        Trace to be filtered
    sampling_frequency: float
        Sampling frequency
    passband: (float, float) tuple
        Tuple indicating the cutoff frequencies
    order: integer
        Filter order

    Returns
    ------
    filtered_trace: array of floats
        The filtered trace


    Calculates the response from a Butterworth filter and applies it to the
    input spectrum

    Parameters
    ----------
    spectrum: array of complex
        Fourier spectrum to be filtere
    frequencies: array of floats
        Frequencies of the input spectrum
    passband: (float, float) tuple
        Tuple indicating the cutoff frequencies
    order: integer
        Filter order

    Returns
    -------
    filtered_spectrum: array of complex
        The filtered spectrum


    Delays a trace by transforming it to frequency and multiplying by phases.
    Since this method is cyclic, the trace has to be cropped. It only accepts
    positive delays, so some samples from the beginning are thrown away and then
    some samples from the end so that the total number of samples is equal to
    the argument delayed samples.

    Parameters
    ----------
    trace: array of floats
        Array containing the trace
    sampling_frequency: float
        Sampling rate for the trace
    time_delay: float
        Time delay used for transforming the trace. Must be positive or 0
    delayed_samples: integer
        Number of samples that the delayed trace must contain

    Returns
    -------
    delayed_trace: array of floats
        The delayed, cropped trace


    performs forward FFT with correct normalization that conserves the power

    Parameters
    ----------
    trace: np.array
        time trace to be transformed into frequency space
    sampling_rate: float
        sampling rate of the trace


    performs backward FFT with correct normalization that conserves the power

    Parameters
    ----------
    spectrum: complex np array
        the frequency spectrum
    sampling_rate: float
        sampling rate of the spectrum
    n: int
        the number of sample in the time domain (relevant if time trace has an odd number of samples)


        Calculate a signal as processed by the tunnel diode.
        The given signal is convolved with the tunnel diode response as in
        AraSim.

        The diode model used in this module returns a dimensionless power trace,
        where the antenna resistance is only a normalisation for the final
        voltage. That's why the antenna resistance has been fixed to a value
        of 8.5 ohms.

        Parameters
        ----------
        channel: Channel
            Signal to be processed by the tunnel diode.

        Returns
        -------
        trace_after_tunnel_diode: array
            Signal output of the tunnel diode for the input `channel`.
            Careful! This trace is dimensionless and comes from a convolution
            of the power with the diode response.


        Calculates the mean and the standard deviation for the diode-filtered noise.

        Parameters
        ----------
        sampling_rate: float
            Sampling rate
        min_freq: float
            Minimum frequency of the bandwidth
        max_freq: float
            Maximum frequency of the bandwidth
        amplitude: float
            Voltage amplitude (RMS) for the noise
        type: string
            Noise type
        n_tries: int
            Number of times the calculation is carried out, to get proper
            averages for the mean and the standard deviation.
        n_samples: int
            Number of samples for each individual noise trace

        Returns
        -------
        power_mean: float
            Mean of the diode-filtered noise
        power_std: float
            Standard deviation of the diode-filtered noise


Angle helper function


    Assert that two complex structures have almost equal contents.

    Compares lists, dicts and tuples recursively. Checks numeric values
    using test_case's :py:meth:`unittest.TestCase.assertAlmostEqual` and
    checks all other values with :py:meth:`unittest.TestCase.assertEqual`.
    Accepts additional positional and keyword arguments and pass those
    intact to assertAlmostEqual() (that's how you specify comparison
    precision).

    :param test_case: TestCase object on which we can call all of the basic
    'assert' methods.
    :type test_case: :py:class:`unittest.TestCase` object


useful function if AIDA is used from PyShell


    this is the *real* main function that starts AIDA decon
    - exclusing commandline handling
    if `settings_filename` is given here, it will get `execfile`d in `Set`
       (note that `ParseCommandLine()` it doing this by itself)


    Use this function as input to the CCG code of D.M. Goodman @ LLNL

    Original void function needed by the CCG code:
        "funct(nc, xo, fn, gn, iqflag)"

    Original Input:
    'nc' = Nd = number of variables (unchanged), this is used in
        Calculate_h_J_and_gradJ
    'xo' = 1D vector of variables = "object" OR "PSF" (input values)

    Rewrite below...
    Additional Set parameter inputs:
    'shape' = shape of data - to convert from 1D xo to nD data
    'costfunction_type' = specification of the costfunction to use for
            different deconvolution types (classical, myopic, nobjects,
            npsfs)
    'OTF' = Fourier Transform of PSF estimate
    'grad' = gradient array (= gn; see below)
    'OBJECT' = Fourier Transform of object estimate
    'IMAGE' = Fourier Transform of image
    'axesFT' = axes in which to perform FFTs

    (Original) Returns:
    'fn' = function value at xo = "J"
    'gn' = 'grad' = 1D vector of the gradient at xn
    'iqflag' = inquiry flag


    Returns the cost function, J and modifies its derivative with respect to
    the PSF, h, in the case where the _PSF_ is to be minimized

    Note that not all cost_function terms are calculated; only those that
    vary with respect to what is being differentiated/minimized are computed


    Returns the cost function of J and modified its derivative with respect
    to the object, o

    Note that not all cost_function terms are calculated; only those that
    vary with respect to what is being differentiated/minimized are computed


    Prints 'timeinseconds' in secs, mins, or hrs, whichever is the most
    appropriate denomination

    if denominator != 1: divide timeinseconds by it
    check first if denominator is zero


    Returns 'background' subtracted 'image' along with 'inv_w'
    (inverse of weights), 'sigma_det' (Gaussian std of detector noise),
    and an estimate for the 'wiener' coefficient if requested (returns 'None')
    for this variable otherwise. 'dtype' sets the return dtype for 'inv_w'.

    Returns:
    (image, inv_w, sigma_det, wiener)


    Computes the weights, w(r), for use in calculating the data fidelity
    term, Jn.  Note that w(r) should be squared for the Jn calculation

    'baseline' = 0. is the default, which assumes there are intensity values
    less than this from which to calculate the detection noise statistics

    Returns a tuple of (1/weights, noise, and sigma_det)
    where 'noise' is to be used in calculating the Weiner parameter and
    'sigma_det' is the standard deviation for the Gaussian readout noise

    Returns:
    ((1./w).astype(dtype), np.sqrt(sigma_det2))


    Updates weights, w(r), for use in calculating the data fidelity
    term, Jn.

    Returns: (1./w)


    Returns the Wiener filter weight parameter (as np.float64) for use
    in the function 'WienerFilter':

    weight = <||NOISE||^2> / <||OBJECT||^2>, which is
        ~the inverse of the signal-to-noise ratio

    'dark_image' is the detection noise
    'OBJECT' is the realFT of the object (~image)

     If 'dark_image' is a number, this function will assume this is the
        standard deviation of the detector noise

    Returns:
    (absNOISE*absNOISE).mean()/(absOBJECT*absOBJECT).mean()


Returns a cleaned, centered, resized PSF for use in AIDA given a raw PSF


    Locates the true center and approximate pixel center of a PSF using
    centroid fitting

    return (center, pixel_center)


    Returns the center coordinates of a 2D _or_ 3D 'PSF' array, assuming a
    somewhat Gaussian PSF whose center can be determined by centroid fitting.
    Assumes that there are no bad pixels - so it is recommendend that the PSF
    supplied be cleaned or median-filtered first.

    'xyCentroidSize' is the side-length of the square area around the xy-peak
    'xyCentroidSize' should be an odd number
    'xyCentroidSize' should be (at least) 7 times the sigma of a "gaussian
                     shaped" peak

    Returns: (zc, yc, xc)


    Returns a tuple of coordinates for the centroid of an 'array'

    Returns:
    tuple(center + relative_center - (size - 1)/2)


    Returns tuple of resized PSF along with 'center' and 'pixel_center'
    depending on 'cropshape' and whether 'condition' case is satisfied
    by the input variables:

    'condition' = 1:        PSF has larger shape than cropshape
    'condition' = 2:        PSF has smaller shape than cropshape

    Returns:
    (PSF, center, pixel_center)


    Takes PSF data in an array and resizes it to 'new_shape'.  Then:

    (1) PSF is centered about the maximum value (we assume all cosmic ray pixels
        have been removed!)
    (2) PSF image/array is truncated if it is larger than 'new_shape'
    (3) Values beyond the PSF array for PSFs with a shape smaller than
        'new_shape' are filled in (so that PSF.shape = 'new_shape') using a
        mean value calculated from edge values of the PSF image
    (4) A new PSF array is returned that matches 'new_shape'


    Returns a cleaned-up version of a normalized PSF image for use in AIDA.
    Note that this function assumes that these images have been pre-processed
    already by dark current subtraction and flat-fielding.

    'clean' =   (1,0,0,0)       - remove bad pixels
                (0,1,0,0)       - subtract background
                                    ('clean_threshold_percent'/'clean_sigma')
                (0,0,1,0)       - threshold to zero
                (0,0,0,1)       - normalize by sum

    Returns: PSFout.astype(dtype)


    Removes bad pixels (cosmic rays, dead/hot pixels) from a 2D _or_ 3D 'PSF'
    by comparison with a median filtered version.  Intensity values that are
    'delta' percent higher than the median filtered PSF will be replaced with
    a median filtered value.  However, points within 'exclude_radius' from the
    'center' of the PSF will not be touched.  If 'center' is 'none', 'center'
    will be determined using the 'FindPSFcentroid' function.

    Returns: PSFout


    Returns a background subtracted PSF.  Level subtracted is either
    'background_percent' of the PSF maximum _or_ 'nsigmas' of Gaussian
    background noise (calculated from negative pixels) subtracted.
    'nsigmas' subtraction takes precedence over 'background_percent'

    Returns:
    (PSF - background)


    Returns a PSF that is thresholded with 'threshold_percent'*PSF.max() _or_
    with 'threshold_value'.  Values below this threshold are replaced with
    'fillvalue'

    now changes PSF in-place
    old version:   Returns:
    old version:   np.where(PSF < threshold_value, fill, PSF)


    Normalizes 'PSF' by the sum

    return (PSF / normalization)


    Given a 'realOTF', this sets values below 'OTF_threshold_percent' and
    pixels outside 'cutoff_radius' from the origin to 'fill' values

    Returns: cOTF


Returns a polynomial fit value for the zero-value of 'OTF'


    Computes 2D radial average of an array up to radius 'array.shape[-2]/2+1'
    Beyond that, values are set to 'fill'.  'subtract_background' will subtract
    an average 'array-background' value computed from regions beyond this
    radius from the entire radial average, before filling with value 'fill'

    Returns:
    (radial_mD[...,:array.shape[-2]/2+1], radial_nD, array_background)


    Returns 2D and 3D radial average arrays along with estimate of array
    background calculated from entries outside of 1/2 length of array in the y
    dimension.  First calculates radial average about xy, then averages across
    z dimension separately.

    If 'FT' is set true, average across z dimension is computed with appropriate
    index matching for a Fourier Transform array

    Returns:
    (radial_2D, radial_3D, array_background)


    Returns a n-1 D radial average of array

    Returns:
    (histogram / frequency)


    Generates and returns a radially symmetric function sampled in
    volume(image) of shape
    if 'origin' is 'None' the origin defaults to the center
    func is a 1D function with 2 paramaters: r0,r
    dtype is Float32


    Used for lambda type functions to wrap array, 'q', of size 'nq'.  If
    'wrap' = 1, then wrap, otherwise, don't wrap.  Works on a per axis basis


    Writes out 'data_array' as a '.fits' or '.mrc' file or '.tif'files

    For format='m', writes out 'data_array' in .mrc format, including a header
        containing array 'shape' information
    For format='f', writes out 'data_array' in .fits format, with shape
        information stored in the [1].data  slot (default)
    For format='t', writes out 'data_array' in .tif format

	Also outputs PNG versions of the results, for easy viewing.


    Changed by Clement 2016-08-16 : handling of TIFF files added
    Returns the file format of a file(s) within 'directory' identified by
    'filenamebase'.

    Assumes the file(s) is either in .fits ('f') or .mrc ('m') or >tif ('t') format and will
    select the format that characterizes the majority of files that are located;
    if the same number of .fits and .mrc files are identified, the format will
    default to 'f'


Returns list of files in directory with specified 'prefix' and 'suffix'


    Resizes (crops or pads) images so that dimensions are set to the closest
    length of 2^n

    Returns: new_image


    Returns the appropriate 'kernel' for use in calculating the gradient
    of an object image via convolution (see CalcGradient function).

    Kernels available here correspond to: (1) a simple directed finite-
    difference approach advocated by Mugnier et al. (2001) "Myopic
    deconvolution from wavefront sensing" JOSA A 18:862-872; (2) a symmetric
    finite-difference approach as described by Press et al. (1992) Numerical
    Recipes (2nd Ed) pp.186-188; or (3) an isotropic differencing scheme
    suggested by Frei and Chen (1977) "Fast boundary detection: a generalization
    and a new algorithm" IEEE Trans. Computers C-26:988

    'dimension' specifies the dimension of the data for which a kernel should be
            returned (currently '2' or '3')
    'operator' specifies the type of gradient kernel to select.  Options are:
            'pixel' (directed finite difference)
            'symmetric' (symmetric finite difference)
            'FC' (Frei-Chen isotropic finite difference scheme)
    'shift' is the finite-difference orientation.
            Default is '-1' meaning: object(x) - object(x-1)  ("backwards")
            Alternatively for '1':   object(x) - object(x+1)  ("forwards")


    Returns a Wiener filtered image according to:

    object = invFT(conjugate(OTF)*IMAGE / (||OTF||^2 + weight))

    'weight' is the scalar Wiener Filter parameter quantity
        Note that this represents a "squared" quantity:
            weight = (sigma_noise/sigma_image)**2


    Returns 'data' with edges along dimensions up to 'ndim' set to 'value'

    'ndim' is assumed to be <= data.ndim (no safeguard in place)


Converts a real Fourier Transform array to a full Fourier Transform


    workaround for broken Priithon's U.topPercentile():
    always scale a to max 65535 - ignore values < 0


    Used in 'AIDA.py' to process, set-up, and check input variables supplied
    by the user

    Loads user specified variables from 'AIDA_Settings.py' and/or the command
    line and  checks their validity.  Also processes specified image and PSF
    files in preparation for deconvolution, writing out mPSF and v files


    Returns (mPSF, inv_u, mOTF, inv_v)
    Based on ComputeMeanVariance single pass function


Writes mPSF, u, and v to file


Calculates inv_v for the spring damping term in the decon equation


    Creates arrays for IMAGE and associated image weights for memory
    usage levels greater than zero.  The data stored in these arrays are
    called by GetImageData()


    Returns 'theta' given data fidelity weights 'w' and 'sigma_det'

    Uses:
        'Set.theta_input'
        'Set.theta_definition'
        'Set.dimension'


    Prints user supplied info specified in AIDA.py, consistent with
    the specified 'infolevel' flag

    Used in 'AIDArun.py'


    Runs AIDA in 'classical' or 'myopic' mode

    'decon_type' specifies 'classical' or 'myopic' decon
    'infolevel' controls the amount of information printed
    'memusagelevel' controls the number of variables stored in memory

    DeconSingleFrame works on image files sequentially.
    Procedure is as follows:
    (1) Load image and prepare Image data/stats
    (2) Prepare arrays for results storage
    (3) Run PCGSingleframe and generate
        deconvolved object and PSF
    (4) Output object and PSf result to disk.


    Prepares storage arrays for object and PSF results that are later Set.
    for file output.

    Variables in the 'Set' module modified by this function:

    'Set' module variables used as input:


    This function provides Image data necessary to calculate the Cost
    Function

    'IMAGE' is the Fourier Transform of the image
    'inv_theta' is a regularization factor used in the object prior term
    'sigma_det' is a measure of Gaussian noise present in the image
    'inv_w' is a regularization factor used in the data fidelity term
    'wiener' (optional) can be used to generate a wiener-filtered initial
            guess for the object

    ProcessImageData either calculates these variables or alternatively
    references existing arrays containing these variables for higher
    memory usage levels.


    The core routine of AIDA in 'myopic' mode

    [ORDER OF AIDA Minimization]

        INITIAL PASS:
            (1) Fix PSF = invFT(mOTF) ==>> PSF(i=0)
            (2) Set object(j=0) = 0 (option: Weiner filtered image)

        SUBSEQUENT PASSES:
            (3) Using PSF(i), solve for object(j+1) using CCG
            (4) If |object(j+1) - object(j)| <= object_tolerance,
                    check_object=1
            (5) Using object(j+1), solve for PSF(i+1) using CCG
            (6) If |PSF(i+1) - PSF(i)| <= PSF_tolerance, check_PSF=1
            (7) If (check_object == 'stop' && check_PSF == 'stop'), STOP
            (8) Else, go to (1) with i==>>i+1 and j==>>j+1

    For Set.terms[0] == 0 a PSF is fit to a sampled PSF distribution
    Currently used for testing purposes

    'decon_type' specifes 'nobjects' or 'npsfs' decon
    'infolevel' controls the level of information printed
    'memusagelevel' specifies the number of variables
        stored to memory
    'object_results' and 'PSF_results' stores the deconvolved
        object and PSF for output
    'results_index' indexes the results files based on the
        iteration in the hyperparameter search


    Prints partial conjugate gradient results consistent with user-specified
    'infolevel' flag

    Used in 'AIDA_Functions.doPCG_Classical' and 'AIDA_Functions.doPCG_Npairs'


    Computes lambda_object using formula derived by E. Hom:

        lambda_object = 1./ < (sqrt(2*pi*w)/theta) - 1 >

    Works on a single image:PSF pair


    Prepares variables and setings for input into CCG code for minimization
    Checks returned CCG data for convergence.
    Used in PCGSingleFrame and PCGMultiFrame

    'check_PSF' flags when PSF difference is beneath tolerance
    'PSF_stops' is the number of consecutive PSF differences
            beneath tolerance


    Prints results about the object minimization step in AIDA

    Used in 'AIDA_Functions.???', 'AIDA_Functions.???d',...


Prints convergence status of AIDA consistent with 'infolevel' flag


    Prepares variables and setings for input into CCG code for
    minimization.  Checks returned CCG data for convergence
    Used in PCGSingleFrame and PCGMultiFrame

    'check_PSF' flags when PSF difference is beneath tolerance
    'PSF_stops' is the number of consecutive PSF differences
            beneath tolerance


    Prints details about the AIDA deconvolution for a given dataset image

    Used in 'AIDA_Functions.???', 'AIDA_Functions.???', etc.


    Takes AIDA decon object and PSF result arrays and prepares for output to
    file.

    'object_results' = deconvolved object, can be a single object or an
            array of objects)
    'PSF_results' = deconvolved PSF, can be a single PSF or an array of PSFs)
    'file' = indexing reference Set. to indicate the corresponding image file
            for which object and PSF results are being outputted.
            If '', multiple results are outputted into a single file

    N.B. 'decon_type'=classical and 'file'=None outputs the mean PSF to file,
    the only PSF Set. in the classical decon scheme.  This is done only once
    per decon.

    [Variables in the 'Set' module modified by this function:
        Set.output_results_shape
        Set.images_in_file
        Set.output_array_shape
        Set.object_results_array
        Set.PSF_results_array

    'Set' module variables used as input:
        Set.decon_type
        Set.terms
        Set.images_in_file
        Set.output_results_shape
        Set.output_format
        Set.results_directory
        Set.image_list
        Set.output_array_shape
    ]


Generates output filename for the function '_ProcessOutput'


    Prints details about the AIDA deconvolution for a given dataset

    Used in 'AIDA_Functions.DeconClassical', 'AIDA_Functions.DeconNpairs',
    'AIDA_Functions.DeconNobjects', and 'AIDA_Functions.DeconNpsfs'


    Runs AIDA in 'nobjects' or 'npsfs' mode.

    'decon_type' specifies nobjects or npsfs decon
    'infolevel' controls the amount of information printed
    'memusagelevel' controls the number of variables stored to memory

    This function prepares arrays for results storage, receives decon results
    from PCGMultiframe and outputs those results to file

    If specified by the user, a hyperparameter search over lambda_object and
    and theta is executed here.  Theta search is centered around an analytical
    expresion for theta (using the Hom formula) and expanded using
    inv_theta_multiplier


    The core routine of AIDA in 'nobjects' or 'npsfs' mode

        [ORDER OF AIDA Minimization]

            INITIAL PASS:
                (1) Fix PSF = invFT(mOTF) ==>> PSF(i=0)
                (2) Set object(j=0) = 0 (option: Weiner filtered image)

            SUBSEQUENT PASSES:
                (3) Using PSF(i), solve for object(j+1) using CCG
                (4) If |object(j+1) - object(j)| <= object_tolerance,
                        check_object=1
                (5) Using object(j+1), solve for PSF(i+1) using CCG
                (6) If |PSF(i+1) - PSF(i)| <= PSF_tolerance, check_PSF=1
                (7) If (check_object == 'stop' && check_PSF == 'stop'), STOP
                (8) Else, go to (1) with i==>>i+1 and j==>>j+1

        'decon_type' specifes 'nobjects' or 'npsfs' decon
        'infolevel' controls the level of information printed
        'memusagelevel' specifies the number of variables
            stored to memory
        'object_results' and 'PSF_results' stores the deconvolved
            object and PSF for output
        'results_index' indexes the results files based on the
            iteration in the hyperparameter search


    Prints the list of images to be used in the deconvolution, along with
    associated AIDA parameters determined from the properties of each image
    Used ONLY in PCG_Multiframe


    Prints summary AIDA deconvolution statistics

    Used in 'AIDA.py'


Enable the cache.


Disable the cache.


Return whether the cache is currently enabled.


Refresh the object referenced by key to stop it being culled
        on the next round.


Insert the passed object into the cache, referenced by key,
        a hashable.


Lookup the object referenced by key and return it, refreshing
        the cache at the same time.


Perform a 1D FFT.

    The first three arguments are as per :func:`scipy.fftpack.fft`;
    the rest of the arguments are documented
    in the :ref:`additional argument docs<interfaces_additional_args>`.


Perform a 1D inverse FFT.

    The first three arguments are as per :func:`scipy.fftpack.ifft`;
    the rest of the arguments are documented
    in the :ref:`additional argument docs<interfaces_additional_args>`.


Perform a 2D FFT.

    The first three arguments are as per :func:`scipy.fftpack.fft2`;
    the rest of the arguments are documented
    in the :ref:`additional argument docs<interfaces_additional_args>`.


Perform a 2D inverse FFT.

    The first three arguments are as per :func:`scipy.fftpack.ifft2`;
    the rest of the arguments are documented in the
    :ref:`additional argument docs <interfaces_additional_args>`.


Perform an n-D FFT.

    The first three arguments are as per :func:`scipy.fftpack.fftn`;
    the rest of the arguments are documented
    in the :ref:`additional argument docs<interfaces_additional_args>`.


Perform an n-D inverse FFT.

    The first three arguments are as per :func:`scipy.fftpack.ifftn`;
    the rest of the arguments are documented
    in the :ref:`additional argument docs<interfaces_additional_args>`.


Convert the complex output from pyfftw to the real output expected
    from :func:`scipy.fftpack.rfft`.


Convert the expected real input to :func:`scipy.fftpack.irfft` to
    the complex input needed by pyfftw.


Perform a 1D real FFT.

    The first three arguments are as per :func:`scipy.fftpack.rfft`;
    the rest of the arguments are documented
    in the :ref:`additional argument docs<interfaces_additional_args>`.


Perform a 1D real inverse FFT.

    The first three arguments are as per :func:`scipy.fftpack.irfft`;
    the rest of the arguments are documented
    in the :ref:`additional argument docs<interfaces_additional_args>`.


_unitary() utility copied from numpy


Perform a 1D FFT.

    The first four arguments are as per :func:`numpy.fft.fft`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform a 1D inverse FFT.

    The first four arguments are as per :func:`numpy.fft.ifft`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform a 2D FFT.

    The first four arguments are as per :func:`numpy.fft.fft2`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform a 2D inverse FFT.

    The first four arguments are as per :func:`numpy.fft.ifft2`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform an n-D FFT.

    The first four arguments are as per :func:`numpy.fft.fftn`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform an n-D inverse FFT.

    The first four arguments are as per :func:`numpy.fft.ifftn`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform a 1D real FFT.

    The three four arguments are as per :func:`numpy.fft.rfft`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform a 1D real inverse FFT.

    The first three arguments are as per :func:`numpy.fft.irfft`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform a 2D real FFT.

    The first three arguments are as per :func:`numpy.fft.rfft2`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform a 2D real inverse FFT.

    The first three arguments are as per :func:`numpy.fft.irfft2`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform an n-D real FFT.

    The first three arguments are as per :func:`numpy.fft.rfftn`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform an n-D real inverse FFT.

    The first three arguments are as per :func:`numpy.fft.rfftn`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform a 1D FFT of a signal with hermitian symmetry.
    This yields a real output spectrum. See :func:`numpy.fft.hfft`
    for more information.

    The first three arguments are as per :func:`numpy.fft.hfft`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Perform a 1D inverse FFT of a real-spectrum, yielding
    a signal with hermitian symmetry. See :func:`numpy.fft.ihfft`
    for more information.

    The first three arguments are as per :func:`numpy.fft.ihfft`;
    the rest of the arguments are documented
    in the :ref:`additional arguments docs<interfaces_additional_args>`.


Generic transform interface for all the transforms. No
    defaults exist. The transform must be specified exactly.


 This function returns two slicers that are to be used to
    copy the data from the input array to the FFTW object internal
    array, which can then be passed to _FFTWWrapper:

    ``(update_input_array_slicer, FFTW_array_slicer)``

    On calls to :class:`~pyfftw.builders._utils._FFTWWrapper` objects,
    the input array is copied in as:

    ``FFTW_array[FFTW_array_slicer] = input_array[update_input_array_slicer]``


Given a passed in array ``a``, and the rest of the arguments
    (that have been fleshed out with
    :func:`~pyfftw.builders._utils._cook_nd_args`), compute
    the shape the input and output arrays need to be in order
    to satisfy all the requirements for the transform. The input
    shape *may* be different to the shape of a.

    returns:
    ``(input_shape, output_shape)``


Similar to :func:`numpy.fft.fftpack._cook_nd_args`.


Return a :class:`pyfftw.FFTW` object representing a 1D FFT.

    The first three arguments are as per :func:`numpy.fft.fft`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing a 1D
    inverse FFT.

    The first three arguments are as per :func:`numpy.fft.ifft`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing a 2D FFT.

    The first three arguments are as per :func:`numpy.fft.fft2`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing a
    2D inverse FFT.

    The first three arguments are as per :func:`numpy.fft.ifft2`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing a n-D FFT.

    The first three arguments are as per :func:`numpy.fft.fftn`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing an n-D
    inverse FFT.

    The first three arguments are as per :func:`numpy.fft.ifftn`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing a 1D
    real FFT.

    The first three arguments are as per :func:`numpy.fft.rfft`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing a 1D
    real inverse FFT.

    The first three arguments are as per :func:`numpy.fft.irfft`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing a 2D
    real FFT.

    The first three arguments are as per :func:`numpy.fft.rfft2`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing a 2D
    real inverse FFT.

    The first three arguments are as per :func:`numpy.fft.irfft2`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing an n-D
    real FFT.

    The first three arguments are as per :func:`numpy.fft.rfftn`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


Return a :class:`pyfftw.FFTW` object representing an n-D
    real inverse FFT.

    The first three arguments are as per :func:`numpy.fft.rfftn`;
    the rest of the arguments are documented
    :ref:`in the module docs <builders_args>`.


A : array to be shifted


    return "well behaved" version of a numpy array
    1) convert lists or tuple to numpy-array
    2) make copy of numpy arrays if non-contigous or non-native

    (used in conjunction with SWIGed functions)


returns min,max of arr


returns min,max,mean of arr


returns an array of shape arr.shape[:-2] and dtype outtype
    if outtype=None it uses arr.dtype


    data should be list of (x,y)  tuples
    TODO: or (x,y,deltaY)
    (instead of 'list' you can of course have an array w/
    shape=(n,2) or shape=(n,3), n beeing the number of data points

    if data.ndim == 1 or data.shape = (n,1) it fits assuming x=0,1,2,3,...n-1

    f is your 'model' function that takes two arguments:
    a tuple of parameters and x

    The function returns a list containing the optimal parameter values
    and the chi-squared value describing the quality of the fit.


    t can be a scalar or a vector
    returns y value(s) of a 1D-gaussian model

    parms can be tuple of ltength 2,3 or 4, with
    2: tuple is [sigma, peakVal]
    3: tuple is [x0, sigma, peakVal]
    4: tuple is [y0, x0, sigma, peakVal]

    x0 is center of gaussian (default 0)
    y0 is baseline offset gaussian (default 0)
    sigma is sigma (stddev) of gaussian
    peakval is  "center height" above baseline


    see yGaussian.
    p: initial guess
    data: vector of data points to be fit


    t can be a scalar or a vector
    returns y value(s) of a polygon model
    parms:
      baseline, first-order coeff, 2nd, ...


    see yPoly

    data should be list of y or (x,y)- or (x,y,deltaY)-tuples
    (instead of 'list' you can of course have an array w/
    shape=(n,2) or shape=(n,3), n beeing the number of data points

    uses polynomial 'model' ( U.yPoly )

    The function returns a list containing the optimal parameter values
    and the chi-squared value describing the quality of the fit.


    creates/returns  array with nBins int32 entries
       fills it with histogram of 'a'
    if amin and/or amax is None it calculates the min/max of a and uses that
    if nBins is None:
        nBins = int(amax-amin+1)
        if narr is of float dtype  Bins < 100:
            nBins = 100
    if histArr is given it is used to fill in the histogram values
        then nBins must be None and histArr of dtype N.int32

    if norm:
       divide bins (=histArr) by sum of bins and convert to float64
    if returnTuple:
        return (histArr, nBins, amin, amax)


Convert numpy array to image
       a must be of ndim 2 and dtype UInt8,Float32 or UInt16
       if a.ndim ==3:
          a.dtype must be uint8
          the first axis is interpreted as RGB color axis -- for fewer "sections" in a, remaining are assumed to be zero
          rgbOrder: order in which axes are mapped to RGB(A) channels


    extension to PIL save TIFF
    **params is directly forwarded to PIL save function


    Saves data array as image file (format from    extension !! .tif,.jpg,...)
    tries to use number format of 'arr'
    also supports multipage TIFF:
        3D arrays: grey (if more than 4 z-secs or forceMultipage==True)
        4D arrays: color (second dim must be of len 2..4 (RG[B[A]])"

    for multi-color images:
         rgbOrder: order in which axes are mapped to RGB(A) channels

    !!be careful about up-down orientation !!


    check that fn contains a '%02d'-like part'
    autofix if necessary (add enough digits to fit n filenames)


    Saves 3D data array as 8-bit gray image file sequence (format from  extension !! .tif,.jpg,...)
    filename should contain a "template" like %02d - use '%%' otherwise inplace of single '%'
    template gets replaced with 00,01,02,03,...

    for multi-color images:
         rgbOrder: order in which axes are mapped to RGB(A) channels

    !!be careful about up-down orientation !!


allocates and returns array of given dtype and shape


    calculate nd fourier transform
    performs real- fft, i.e. the return array has shape with last dim halfed+1

    `a` should be a real array,
      otherwise it gets converted to
      minFdtype


returns n-dim Gaussian centered at 0
    if integralScale is not None
         result.sum() == integralScale
    if peakVal       is not None
         result max is peakVal
    if both are None
         results defaults to integralScale==1


if copy==1 (and inplace==0 !!) fftw uses a copy of af to prevent overwriting the original
       (fftw always messes up the input array when inv-fft complex_to_real)


open existing Mrc file

    returns memmaped array
    array has special 'Mrc' attribute


20051201 - test failed - data did NOT get shifted my next bytes !!!


maps the extended header space to a recarray
        if nz==0: then it maps 'NumSecs' tuples
        if nz==-1 then it maps the _maximal_ available space
             then self.extHdrArray will likely have more entries then the 'NumSecs'


return string indicating meaning of shape dimensions
        ##
        ## ZTW   <- non-interleaved
        ## WZT   <- OM1 ( easy on stage)
        ## ZWT   <- added by API (used at all ??)
        ## ^
        ## |
        ## +--- first letter 'fastest'

        fixme: possibly wrong when doDataMap found bad file-size


do some basic checks like filesize, ...


use this to get 'spiffed up' array


return 3D array filled with the data
    (non memmap)


    ifExists shoud be one of
       ask
       raise
       overwrite
       skip

    (only first letter is checked)

     use zAxisOrder if arr.ndim > 3:
       zAxisOrder is given in order conform to python(last is fastest)
          (spaces,commas,dots,minuses  are ignored)
       examples:
          4D: time,z,y,x          -->  zAxisOrder= 't z'
          5D: time, wave, z,y,x   -->  zAxisOrder= 't,z,w'
       refer to Mrc spec 'ImgSequence' (interleaved or not)
       zAxisOrder None means:
          3D: 'z'
          4D: 'tz'
          5D: 'tzw'

    if hdr is not None:  copy all fields(except 'Num',...)
    if calcMMM:  calculate min,max,mean of data set and set hdr field
    if hdrEval:  exec this string ("hdr" refers to the 'new' header)

    TODO: not implemented yet, extInts=None, extFloats=None


        use zAxisOrder if arr.ndim > 3:
          zAxisOrder is given in order conform to python(last is fastest)
             (spaces,commas,dots,minuses  are ignored)
          examples:
             4D: time,z,y,x          -->  zAxisOrder= 't z'
             5D: time, wave, z,y,x   -->  zAxisOrder= 't,z,w'
          refer to Mrc spec 'ImgSequence' (interleaved or not)
          zAxisOrder None means:
             3D: 'z'
             4D: 'tz'
             5D: 'tzw'


if i is None read "next" section at current position


if i is None write "next" section at current position


return smallest multiple of 1024 to fit extHdr data


    return "smart" shape
    considering numTimes, numWavelenth and hdr.ImgSequence

    if verbose:
        print somthing like: w,t,z,y,x  ot z,y,x


return string indicating meaning of shape dimensions
    ##
    ## wtz   <- non-interleaved
    ## tzw   <- OM1 ( easy on stage)
    ## twz   <- added by API (used at all ??)
    ## ^
    ## |
    ## +--- first letter 'fastest'

    fixme: possibly wrong when doDataMap found bad file-size


note: if  nxOrShape is tuple it is nz,ny,nx (note the order!!)


copy all field of the header
       EXCEPT  shape AND PixelType AND all fields related to extended hdr


    use this if your costGradFunction wants
    additional arguments and/or keyword-arguments
    (constant thought optimization)

    example:
    def myCGF(x, gg, zzz=0, set=1):
        ...
        gg[:] = ... zzz...
        return set*x, 0

    ccg.getsol( ... costGradFunc=ccg.makeCostGradFunction(myCGF, set=4) ...)


    use this if your have separate functions for
    cost and gradient calculation
    also
    additional arguments and/or keyword-arguments
    (constant thought optimization)
    can be specified.

    example:
    def myCost(x, zzz=0, set=1):
        ...
        return set*x, 0

    def myGrad(x, gg, zzz=0, set=1):
        ...
        gg[:] = ... zzz...

    ccg.getsol( ... costGradFunc=ccg.makeCostGradFunction2(myCost, myGrad, set=4) ...)


Returns the preamble for the header file.

  Args:
    n:  the maximum arity of the predicate macros to be generated.


Returns the implementation of n-ary predicate assertions.


Returns the preamble for the unit test file.


Returns the tests for n-ary predicate assertions.


    Normalizes Google Test's XML output to eliminate references to transient
    information that may change from run to run.

    *  The "time" attribute of <testsuites>, <testsuite> and <testcase>
       elements is replaced with a single asterisk, if it contains
       only digit characters.
    *  The "timestamp" attribute of <testsuites> elements is replaced with a
       single asterisk, if it contains a valid ISO8601 datetime value.
    *  The "type_param" attribute of <testcase> elements is replaced with a
       single asterisk (if it sn non-empty) as it is the type name returned
       by the compiler and is platform dependent.
    *  The line info reported in the first line of the "message"
       attribute and CDATA section of <failure> elements is replaced with the
       file's basename and a single asterisk for the line number.
    *  The directory names in file paths are removed.
    *  The stack traces are removed.


Tests that environment variable should affect the corresponding flag.


Lint the codebase (except for clang-format/tidy).


Run the tests (requires a compiler).


Run the packaging tests.


Build the docs. Pass "serve" to serve.


Inspect the closed issues and make entries for a changelog.


Build SDists and wheels.


        The CXX standard level. If set, will add the required flags. If left at
        0, it will trigger an automatic search when pybind11's build_ext is
        used. If None, will have no effect.  Besides just the flags, this may
        add a macos-min 10.9 or 10.14 flag if MACOSX_DEPLOYMENT_TARGET is
        unset.


Prepare and enter a temporary directory, cleanup when done


    Return the flag if a flag name is supported on the
    specified compiler, otherwise None (can be used as a boolean).
    If multiple flags are passed, return the first that matches.


Return the max supported C++ std level (17, 14, or 11). Returns latest on Windows.


Build extensions, injecting C++ std for Pybind11Extension if needed.


    Generate Pybind11Extensions from source files directly located in a Python
    source tree.

    ``package_dir`` behaves as in ``setuptools.setup``.  If unset, the Python
    package root parent is determined as the first parent directory that does
    not contain an ``__init__.py`` file.


    This will recompile only if the source file changes. It does not check
    header files, so a more advanced function or Ccache is better if you have
    editable header files in your package.


    This is the safest but slowest choice (and is the default) - will always
    recompile sources.


Builds a function object usable as distutils.ccompiler.CCompiler.compile.


Installs the compile function into distutils.ccompiler.CCompiler.compile.


    Check the version of swig, >= 3.0 is required

    Notes
    -----
    *   swig is only needed for developers installing from the source directory,
        with ``python setup.py install``
    *   the swig-generated files are included by default in the pypi distribution,
        so the swig dependency is not needed


Function to download CLASS from github and and build the library


Copy the Cosmology object, optionally changing the Transfer Function


Internal function to return the nonlinear biasing function


Interpolator from simulation data for nonlinear biases


A dict storing the types of nonlinear biasing to use


        Whether to use the nonlinear biasing scheme from Vlah et al. 2013,
        which amounts to a single `b2_00` and `b2_01` functional form
        as a function of linear bias


Update the dict stored in :attr:`nonlinear_bias_type`


The nonlinear bias term that enters into Phm


The nonlinear bias term that enters into (P11+P02)[mu2]


The nonlinear bias term that enters into P02[mu4]


The nonlinear bias term that enters into (P13+P22+P04)[mu4]


The nonlinear bias term that enters into P01[mu2]


The nonlinear bias term that enters into (P12+P03)[mu4]


    Power law extrapolation function, with a slope that can
    optionally vary with independent variable

    :math: f(x, alpha, beta) = x^{alpha + beta*log10(x)}

    Parameters
    ----------
    x : float, array_like
        the (normalized) array of independent variables
    alpha : float
        the constant power-law slope
    beta : float, optional (`0`)
        the variable power-law slope, default is `0`


        The name of the function, which is a class method of ``model``
        and takes (k, mu) as its arguments


        The wavenumber value, above which we will extrapolate the power
        spectrum with a power law of varying slope


        Only include wavenumbers above this value when fitting the high-k
        extrapolation parameters


        Only include wavenumbers below this value when fitting the low-k
        extrapolation parameters


The minumum wavenumber that the model can compute


The maximum wavenumber that the model can compute


Internal variable that defines wavenumbers on a grid for interpolating


Internal variable that defines mus on a grid for interpolating


        The (k,mu) grid for interpolating -- stacked such that
        the output shape is (Nk, Nmu, 2)


The interpolating for ``model.Pgal``, interpolated using the (k,mu) grid


The splines for ``(alpha, beta)`` vs `_mus` for the high-k extrapolation


        Return a tuple (`alpha`, `beta`) for this `mu` value for use in the
        high-k extrapolation


        Return `alpha` for this `mu` value for use in the low-k extrapolation
        (`beta` = 0 by assumption)


        Compute the multipoles by integrating over the extrapolated
        power spectrum


Decorator to properly normalize Jmn integrals


Decorator to properly normalize Imn integrals


Decorator to properly normalize one loop Imn integrals


The 1-loop density auto spectrum


The 1-loop density-velocity cross spectrum


The 1-loop velocity auto spectrum


The 1-loop P22 power spectrum


The internal driver class to compute the I(m, n) integrals


The internal driver class to compute the J(m, n) integrals


        The internal driver class to compute the 1-loop I(m, n) integrals,
        which integrate over `P_dv(q) P_dv(|k-q|)`


        The internal driver class to compute the 1-loop I(m, n) integrals,
        which integrate over `P_vv(q) P_dd(|k-q|)`


        The internal driver class to compute the 1-loop I(m, n) integrals,
        which integrate over `P_vv(q) P_vv(|k-q|)`


The unnormalized velocity kurtosis


        The velocity kurtosis <v_parallel^4>, computed using the 1-loop divergence
        auto spectra Pvv, aka P22bar


        The dark matter velocity dispersion at z, as a function of k,
        ``\sigma^2_v(k)`` [units: `(Mpc/h)^2`]


    Return the function G(p), as defined in Wilson et al 2015.

    See also: WA Al-Salam 1953

    Returns
    -------
    numer, denom: int
        the numerator and denominator


        Initialize the splines used to compute the convolution
        kernels for each ell from the discretely-measued
        window multipoles


Return the appropriate kernel


    Convolve the input ell = 0, 2, 4 power multipoles, specified by `Pell`,
    with the specified window function.

    Parameters
    ----------
    k : array_like, (Nk,)
        the array of wavenumbers where `Pell` is defined -- to avoid convolution
        errors, `k` should probably extend to higher values than the desired `k_out`
    ells : array_like, (Nell,)
        the ell values
    Pell : array_like, (Nk, Nell)
        the ell = 0, 2, 4 power multipoles, defined at `k`


The kernel to use in the Gaussian process


The solver to use in the Gaussian process


The Gaussian process hyperparameters


The `pandas.DataFrame` holding the data to interpolate


Interpolate using the associated errors on the simulation values


The names of the independent variables to interpolate


The name of the dependent variable to interpolate


The shape of the second axis of `x`


The number of independent variables, also the size of `theta`


The unscaled independent variables


The unscaled dependent variable


The unscaled error on the dependent variable


The class to scale the `x` attribute


The class to scale the `y` attribute


The scaled independent variables


The scaled dependent variable


The scaled error on the dependent variable


The Gaussian process needed to do the interpolation


The growth rate, defined as the `dlnD/dlna`.


The `pygcl.LinearPS` object defining the linear power spectrum at `z=0`


Desired redshift for the output power spectrum


        Sigma_8 at `z=0` to compute the spectrum at, which gives the
        normalization of the linear power spectrum


Load the P11 simulation data


        Return an interpolation table for P11, normalized by the no-wiggle
        power spectrum


        Extrapolate out of the range of (f*sigma8)^2 by assuming the shape of
        the normalized power spectrum is the same, i.e., just rescaling
        by the low-k amplitude


Load the simulation data


        Return an interpolation table for Pdv, normalized by the no-wiggle
        power spectrum


        Extrapolate out of the range of f*sigma8^2 by assuming the shape of
        the normalized power spectrum is the same, i.e., just rescaling
        by the low-k amplitude


    A decorator decorator, allowing the decorator to be used as:
    @decorator(with, arguments, and=kwargs)
    or
    @decorator


            Recursively find all cached properties
            that depend on a given parameter


Test the equality of an old and new value


    Decorator to represent a model parameter that must
    be set by the user


    Decorator to represent a model parameter will be cached
    and automatically updated if any of its dependencies change


    A decorator that represents a cached property that
    is a function of `k`. The cached property that is stored
    is a spline that predicts the function as a function of `k`


            If `ignore_cache` is True, force an evaluation
            of the decorated function


    Compute the smoothed correlation function multipoles, by extrapolating
    a power spectrum in `k` and Fourier transforming the power
    spectrum multipoles, with a Gaussian smoothing kernel

    :math: \Xi_\ell(s) = i^\ell \int (dq/2\pi^2) q^2 W(q*R) P_\ell(q) j_\ell(q*s)

    Parameters
    ----------
    model : rsd.DarkMatterSpectrum or its derived classes
        the power spectrum model instance which will be extrapolated and integrated
        over to compute the power spectrum multipoles specified by `ells`
    r : array_like
        the separations to compute the correlation function multipoles at [units: `Mpc/h`]
    power : pyRSD.rsd.power_biased
        The power spectrum class specifying the redshift-space power spectrum
        to integrate over
    ells : int or array_like
        the desired multipole numbers to compute
    R : float, optional
        the radius of the Gaussian smoothig kernel to use; default is `0`
    kwargs: passed to `ExtrapolatedPowerSpectrum` constructor
            model_func : str, optional (`Pgal`)
                the name of the function, which is a class method of ``model``
                and takes (k, mu) as its arguments
            k_lo : float
                wavenumber to extrapolate below; default is ``model.kmin``
            k_hi : float
                wavenumber to extrapolate above; default is ``model.kmax``
            kcut_lo : float
                only include wavenumbers below this value when fitting
                the extrapolation parameters; default is `5*k_lo`
            kcut_hi : float
                only include wavenumbers above this value when fitting
                the extrapolation parameters; default is `0.5*k_hi`


Align the input domain values


Convert a tuple of coordinate arrays to a (..., ndim)-shaped array.


    Return the `true` k values, given an observed (k, mu).

    This corresponds to the `k` to evaluate P(k,mu) at when including
    the AP effect


    Return the `true` mu values, given an observed mu

    This corresponds to the `mu` to evaluate P(k,mu) at when including
    the AP effect


Decorator to avoid return lists/tuples of length 1


Decorator to align input by repeating any scalar entries


    Decorator to optionally cache the function return value

    If the class has a :attr:`_scratch` that is a dictionary,
    this decorator will cache the function return value,
    using the input arguments and function name as the hash key


    Decorator to introduce the AP effect by rescaling input
    `k` and `mu`

    The first three arguments to `f` should be `self`, `k`, `mu`


    Decorator to properly handle broadcasting of k, mu.

    This will call the decorator function with the fully
    broadcasted values, such that the input arguments
    have shape (Nk, Nmu)

    Notes
    -----
    This assumes the first two arguments of ``f()``
    are `k` and `mu`


Decorator to compute the monopole from a `self.power` function


Decorator to compute the quadrupole from a `self.power` function


Decorator to compute the hexadecapole from a `self.power` function


Decorator to compute the tetrahexadecapole from a `self.power` function


        Check the inputs for being in the bounds of the interpolated data.

        Parameters
        ----------
        x_new : array

        Returns
        -------
        out_of_bounds : bool array
            The mask on x_new of values that are out of the bounds.


Evaluate the spline


If `True`, return the Zel'dovich power term from an interpolation table


The cosmology of the input linear power spectrum


Evaluate the bias to mass relation at the interpolation grid points


The velocity normalization of the sigma to mass relation


The mass normalization of the sigma to mass relation


The Hubble parameter at `z`


The normalized Hubble parameter at `z`


        Return the line-of-sight velocity dispersion for dark matter using
        the relationship found between velocity dispersion and halo mass found
        by Evrard et al. 2008:

        \sigma_DM(M, z) = (1082.9 km/s) * (E(z) * M / 1e15 M_sun/h)**0.33

        Parameters
        ----------
        mass : float
            The halo mass in units of `M_sun/h`


Return the mass at this bias and sigma8 value


    Given an input bias, return the corresponding mass, using Tinker et al.
    bias fits

    Notes
    -----
    This returns the halo mass in units of M_sun / h