Esempio n. 1
0
def cigalerun(config, noise='none', overwrite='True'):
    ''' run CIGALE'''

    os.chdir(cigale_dir())
    configuration = config.configuration
    if os.path.isfile(os.path.join(cigale_dir(), 'pcigale.ini')):
        if configuration:
            analysis_module = get_module(configuration['analysis_method'])
            analysis_module.process(configuration)
            if os.path.exists('noise_%s' % noise):
                if overwrite != 'True':
                    print('*** CAUTION: Result folder already exists ***')
                    shutil.rmtree('out')
                else:
                    shutil.rmtree('noise_%s' % noise)
                    os.rename('out', 'noise_%s' % noise)
            else:
                os.rename('out', 'noise_%s' % noise)
    else:
        print('*** You need to generate CIGALE ini file! ***')
Esempio n. 2
0
File: cigale.py Progetto: FRBs/FRB
def run(photometry_table,
        zcol,
        data_file="cigale_in.fits",
        config_file="pcigale.ini",
        wait_for_input=False,
        plot=True,
        outdir='out',
        compare_obs_model=False,
        **kwargs):
    """
    Input parameters and then run CIGALE.

    Args:
        photometry_table (astropy Table):
            A table from some photometric catalog with magnitudes and
            error measurements. Currently supports
            DES, DECaLS, SDSS, Pan-STARRS and WISE
        zcol (str):
            Name of the column with redshift estimates.
        data_file (str, optional):
            Root name for the photometry data file generated used as input to CIGALE
        config_file (str, optional):
            Root name for the file where CIGALE's configuration is generated
        wait_for_input (bool, optional):
            If true, waits for the user to finish editing the auto-generated config file
            before running.
        plot (bool, optional):
            Plots the best fit SED if true
        cores (int, optional):
            Number of CPU cores to be used. Defaults
            to all cores on the system.
        outdir (str, optional):
            Path to the many outputs of CIGALE
            If not supplied, the outputs will appear in a folder named out/
        compare_obs_model (bool, optional):
            If True compare the input observed fluxes with the model fluxes
            This writes a Table to outdir named 'photo_observed_model.dat'

    kwargs:  These are passed into gen_cigale_in() and _initialise()
        save_sed (bool, optional):
            Save the best fit SEDs to disk for each galaxy.
        variables (str or list, optional):
            A single galaxy property name to save to results
            or a list of variable names. Names must belong
            to the list defined in the CIGALE documentation.
        sed_modules (list of 'str', optional):
            A list of SED modules to be used in the 
            PDF analysis. If this is being input, there
            should be a corresponding correct dict
            for sed_modules_params.
        sed_module_params (dict, optional):
            A dict containing parameter values for
            the input SED modules. Better not use this
            unless you know exactly what you're doing.

    """
    gen_cigale_in(photometry_table,
                  zcol,
                  infile=data_file,
                  overwrite=True,
                  **kwargs)
    _initialise(data_file, config_file=config_file, **kwargs)
    if wait_for_input:
        input("Edit the generated config file {:s} and press any key to run.".
              format(config_file))
    cigconf = Configuration(config_file)
    analysis_module = get_module(cigconf.configuration['analysis_method'])
    analysis_module.process(cigconf.configuration)
    if plot:
        try:
            from pcigale_plots import sed  # This modifies the backend to Agg so I hide it here
            old_version = True
        except ImportError:
            from pcigale_plots.plot_types.sed import sed
            old_version = False

        if old_version:
            import pcigale
            #warnings.warn("You are using CIGALE version {:s}, for which support is deprecated. Please update to 2020.0 or higher.".format(pcigale.__version__))
            sed(cigconf, "mJy", True)
        else:
            # TODO: Let the user customize the plot.
            series = [
                'stellar_attenuated', 'stellar_unattenuated', 'dust', 'agn',
                'model'
            ]
            sed(cigconf, "mJy", True, (False, False), (False, False), series,
                "pdf", "out")
        # Set back to a GUI
        import matplotlib
        matplotlib.use('TkAgg')

    # Rename the default output directory?
    if outdir != 'out':
        try:
            os.system("rm -rf {}".format(outdir))
            os.system("mv out {:s}".format(outdir))
        except:
            print("Invalid output directory path. Output stored in out/")

    # Move input files into outdir too
    os.system("mv {:s} {:s}".format(data_file, outdir))
    os.system("mv {:s} {:s}".format(config_file, outdir))
    os.system("mv {:s}.spec {:s}".format(config_file, outdir))

    # Compare?
    if compare_obs_model:
        #Generate an observation/model flux comparison table.
        with Database() as base:
            filters = OrderedDict([
                (name, base.get_filter(name))
                for name in cigconf.configuration['bands']
                if not (name.endswith('_err') or name.startswith('line'))
            ])
            filters_wl = np.array(
                [filt.pivot_wavelength for filt in filters.values()])
            mods = Table.read(outdir + '/results.fits')

            try:
                obs = Table.read(
                    os.path.join(outdir, cigconf.configuration['data_file']))
            except:
                print(
                    "Something went wrong here. Astropy was unable to read the observations table. Please ensure it is in the fits format."
                )
                return
            for model, obj in zip(mods, obs):
                photo_obs_model = Table()
                photo_obs_model['lambda_filter'] = [
                    wl / 1000 for wl in filters_wl
                ]
                photo_obs_model['model_flux'] = np.array(
                    [model["best." + filt] for filt in filters.keys()])
                photo_obs_model['observed_flux'] = np.array(
                    [obj[filt] for filt in filters.keys()])
                photo_obs_model['observed_flux_err'] = np.array(
                    [obj[filt + '_err'] for filt in filters.keys()])
                photo_obs_model.write(outdir + "/photo_observed_model_" +
                                      str(model['id']) + ".dat",
                                      format="ascii",
                                      overwrite=True)
            #import pdb; pdb.set_trace()

    return