Build a filter matrix with each row being an index of wave and
    each column being a unique filter.  This makes computation from spectra
    to magnitudes quick and easy.

    Parameters
    ----------
    args : class
        The args class is carried from function to function with information
        from command line input and config.py
    wave : numpy array
        The wave array corresponds to the wavelengths of the SSP models being
        used.

    Returns
    -------
    Fil_matrix : numpy array (2 dim)
        As mentioned above, the Fil_matrix has rows of wavelength and
        columns for each filter in args.filt_dict/config.filt_dict


This function reads a very specific input file and joins it with
    archived 3dhst catalogs.  The input file should have the following columns:
    Field, ID, z

    Parameters
    ----------
    args : class
        The args class is carried from function to function with information
        from command line input and config.py

    Returns
    -------
    y : numpy array (2 dim)
        Photometric flux densities (in units of micro-Janskies)
    yerr : numpy array (2 dim)
        Photometric errors
    z : numpy array (1 dim)
        Redshift from the file returned as a numpy array
    flag : numpy array (2 dim)
        Flag set to True for filters in the catalog_filter_dict in config.py
    em : Astropy Table (2 dim)
        Emission line fluxes in ergs / cm2 / s
        Desired lines are read from dictionary in config.py
    emerr : Astropy Table (2 dim)
        Emission line errors in ergs / cm2 / s
    absindx : Astropy Table (2 dim)
        Absorption line indices read from the input file
    absindx_e : Astropy Table (2 dim)
        Errors on the absorption line indices


 Draw random samples from a uniform distribution

    Parameters
    ----------
    nsamples : int
        Number of draws
    start : float
        lower bound
    end : float
        higher bound

    Returns
    -------
    uniform_sample : numpy array (1 dim)
        randomly drawn variables from a uniform distribution


 Draw random samples from a normal distribution

    Parameters
    ----------
    nsamples : int
        Number of draws
    means : numpy array or list
        Average values to draw from
    sigmas : numpy array or list
        Standard deviation of the return distributions

    Returns
    -------
    normal_sample : numpy array (1 dim)
        randomly drawn variables from a normal distribution


 Create mock data to test quality of MCSED fits

    Parameters
    ----------
    args : class
        The args class is carried from function to function with information
        from command line input and config.py
    mcsed_model : class
        Mcsed class for building fake galaxies given input thetas

    Returns
    -------
    y : numpy array (2 dim)
        Photometric magnitudes for mock galaxies
    yerr : numpy array (2 dim)
        Photometric errors in magnitudes
    z : numpy array (1 dim)
        Redshift for mock galaxies
    truth : numpy array (2 dim)
        Mock input parameters for each fake galaxy, e.g. dust, sfh, mass


    Execute the main functionality of MCSED

    Test mode: "python run_mcsed_fit.py -t"

    Live mode: "python run_mcsed_fit.py -f test_data.dat"

    For a "live" run, the key input ("-f") is a file with three columns:
    Field ID z

    If using the Skelton catalog:
        The field options are: cosmos, goodsn, goodss, aegis, uds
        The ID is the skelton photometric id for the given field
        The redshift, z, is fixed in the fitting


Plot SFH for given set of parameters


 Evaluate double power law SFH

        Parameters
        ----------
        t : numpy array (1 dim)
            lookback time in Gyr (time = 0 is observation of galaxy)
        force_params : bool or list
            if list, use these values to compute SFR
            same length and order as in get_params() method

        Returns
        -------
        msfr : numpy array (1 dim)
            Star formation rate at given time in time array


 Evaluate burst SFH

        Parameters
        ----------
        t : numpy array (1 dim)
            lookback time in Gyr (time = 0 is observation of galaxy)
        force_params : bool or list
            if list, use these values to compute SFR
            same length and order as in get_params() method

        Returns
        -------
        msfr : numpy array (1 dim)
            Star formation rate at given time in time array


 Evaluate polynomial SFH

        Parameters
        ----------
        t : numpy array (1 dim)
            lookback time in Gyr (time = 0 is observation of galaxy)
        force_params : bool or list
            if list, use these values to compute SFR
            same length and order as in get_params() method

        Returns
        -------
        msfr : numpy array (1 dim)
            Star formation rate at given time in time array


 Evaluate exponential SFH

        Parameters
        ----------
        t : numpy array (1 dim)
            lookback time in Gyr (time = 0 is observation of galaxy)
        force_params : bool or list
            if list, use these values to compute SFR
            same length and order as in get_params() method

        Returns
        -------
        msfr : numpy array (1 dim)
            Star formation rate at given time in time array


 Evaluate binned_lsfr SFH

        Parameters
        ----------
        t : numpy array (1 dim)
            lookback time in Gyr (time = 0 is observation of galaxy)
        force_params : bool or list
            if list, use these values to compute SFR
            same length and order as in get_params() method

        Returns
        -------
        msfr : numpy array (1 dim)
            Star formation rate at given time in time array


Remove filters in a given wavelength range

        Parameters
        ----------
        wave1 : float
            start wavelength of masked range (in Angstroms)
        wave2 : float
            end wavelength of masked range (in Angstroms)
        restframe : bool
            if True, wave1 and wave2 correspond to rest-frame wavelengths


        measure absorption indices using current spectrum

        Parameters
        ----------
        spectrum : None or 1d array
            if not None, measure the absorption indices using the input spectrum
            (must have same shape as self.wave)

        Returns
        -------
        update self.absindxCSPdict, the dictionary of absorption line indices


Build a composite stellar population model for a given star
        formation history, dust attenuation law, and dust emission law.

        In addition to the returns it also modifies a lineflux dictionary

        Returns
        -------
        csp : numpy array (1 dim)
            Composite stellar population model (micro-Jy) at self.redshift
            (both stellar and nebular components)
        starcsp : numpy array (1 dim)
            Composite stellar population model (micro-Jy) at self.redshift
            (stellar component)
        nebcsp : numpy array (1 dim)
            Composite stellar population model (micro-Jy) at self.redshift
            (nebular component)
        mass : float
            Mass for csp given the SFH input
        mdust_eb : float
            Dust mass if dust emission is being fit AND assume energy balance


        Measure chi2 from the input spectrum. Used in measuring chi2 from
        the median spectrum, emline fluxes, and absorption line indices

        Parameters
        ----------
        spectrum : 1d array
            same shape as self.wave

        Returns
        -------
        update the chi2 dictionary


 Simple, uniform prior for input variables

        Returns
        -------
        0.0 if all parameters are in bounds, -np.inf if any are out of bounds


 Calculate the log likelihood and return the value and stellar mass
        of the model as well as other derived parameters

        Returns
        -------
        log likelihood, mass, sfr10, sfr100, fpdr, mdust_eb : (all float)
            The log likelihood includes a chi2_term and a parameters term.
            The mass comes from building of the composite stellar population
            The parameters sfr10, sfr100, fpdr, mdust_eb are derived in get_derived_params(self)


 Calculate the log probabilty and return the value and stellar mass
        (as well as derived parameters) of the model

        Returns
        -------
        log prior + log likelihood, [mass,sfr10,sfr100,fpdr,mdust_eb]: (all floats)
            The log probability is just the sum of the logs of the prior and
            likelihood.  The mass comes from the building of the composite
            stellar population. The other derived parameters are calculated in get_derived_params()


 Using emcee to find parameter estimations for given set of
        data measurements and errors


Make spectum plot for current model


Add Subplots to Triangle plot below


 Make a triangle corner plot for samples from fit

        Input
        -----
        outname : string
            The triangle plot will be saved as "triangle_{outname}.png"
        lnprobcut : float
            Some of the emcee chains include outliers.  This value serves as
            a cut in log probability space with respect to the maximum
            probability.  For reference, a Gaussian 1-sigma is 2.5 in log prob
            space.
        imgtype : string
            The file extension of the output plot


 Make a sample plot

        Input
        -----
        outname : string
            The sample plot will be saved as "sample_{outname}.png"
        imgtype : string
            The file extension of the output plot


Assumes that "Ln Prob" is the last column in self.samples


		print bcolors.OKGREEN+ '\n************ OBJECT %i ************' % (k) + bcolors.ENDC
		# STEP 1: Copying the image to the current directory
		print bcolors.OKBLUE+ '1. Copying the input image ...' + bcolors.ENDC
		print >> ff, '**** The object number: %i ****' % (number)
		print >> ff, '1. Copying the input image %s to the current directory.' % (file_image)

		if file_image.find('.fits.gz')>=1 or file_field.find('.fit.gz')>=1:
			shutil.copy(file_image,file_field+'.gz')
			subprocess.call("gzip -d %s" % (file_field+'.gz'), shell=True)
		elif file_image.find('.fits.bz2')>=1 or file_field.find('.fit.bz2')>=1:
			shutil.copy(file_image,file_field+'.bz2')
			subprocess.call("bzip2 -d %s" % (file_field+'.bz2'), shell=True)
		else:
			shutil.copy(file_image,file_field)


The function to update the fits header adding some keywords to it. Theses are required for Galfitif you do not have a weight image!


 The function which will bring position angle
         measured by sextrator in the range -90 and 90


		for i in range(dimy):
			for k in range(dimx):
				repeat = 0
				for m in range(len(cl_star)):
					if img[i,k]>0 and cl_star[m]>0.9 and img[int(yc[m]),int(xc[m])]==img[i,k] and repeat==0:
						print "%i %i" % (k,i)
						repeat = repeat + 1


	for k in range(6,N):
		teta=radians(90.-theta[k])
		III = []

		for i in range(int(xc-(a[k]+gap/2.)*cos(teta)),int(xc+(a[k]+gap/2.)*cos(teta)),1):
			for l in range(int(yc-(b[k]+gap/2.)*sin(teta)),int(yc+(b[k]+gap/2.)*sin(teta)),1):
				if ceil( ((i-xc)*cos(teta) - (l-yc)*sin(teta))**2/((a[k]-gap/2.)**2) + ((i-xc)*sin(teta)+(l-yc)*cos(teta))**2/((b[k]-gap/2.)**2))>=1. and floor( ((i-xc)*cos(teta) - (l-yc)*sin(teta))**2/((a[k]+gap/2.)**2) + ((i-xc)*sin(teta)+(l-yc)*cos(teta))**2/((b[k]+gap/2.)**2))<=1.:
					III.append(I[l,i])
					#print I[l,i]


	from pyraf import iraf
	file_in = file_in + '['+str(xmin)+':'+str(xmax)+','+str(ymin)+':'+str(ymax)+']'
	print file_in
	iraf.imcopy(file_in,file_out)


	for k in range(0, ny):
		if fabs(k- yc+0.5)<zmax and (k- yc+0.5<zmin1 or k- yc+0.5>zmin2) and scidata[k, x]>1*backgr:
			Iminor.append(scidata[k, x])
			z.append(k- yc+1.)
			z1.append(k+1.)


	plt.plot(z_interp,I_interp,'*')
	plt.plot(z,I,'o')
	plt.show()
	exit()


	dataToFit = RealData(r, I)
	mo = Model(bulge_f)
	fitting = ODR(dataToFit, mo, [10**(0.4*(m0-meb+5.*log10(pix2sec))),reb,n])
	fitting.set_job()
	fit_result = fitting.run()
	a = fit_result.beta[0]
	b = fit_result.beta[1]
	c = fit_result.beta[2]
	eps = fabs(median(fit_result.eps))
	#print -2.5*log10(a)+m0+5.*log10(pix2sec),b,c

	print '\n'
	print 'm0d = %.2f [mag arcsec^-2]' % (m0d)
	print 'z0 = %.2f [arcsec]' % (z0*0.396)
	print 'meb = %.2f [mag arcsec^-2]' % (-2.5*log10(a)+m0+5.*log10(pix2sec))
	print 'reb = %.2f [arcsec]' % (b*pix2sec)
	print 'n = %.2f ' % (c)
	return m0d,z0,-2.5*log10(a)+m0+5.*log10(pix2sec),b,c


	plt.figure(99)
	plt.plot(np.array(r1)*pix2sec,I1)
	plt.show()


    K-corrections calculator in Python. See http://kcor.sai.msu.ru for the
    reference. Available filter-colour combinations must be present in the
    `coeff` dictionary keys.

    @type   filter_name: string
    @param  filter_name: Name of the filter to calculate K-correction for, e.g.
                         'u', 'g', 'r' for some of the SDSS filters, or 'J2',
                         'H2', 'Ks2' for 2MASS filters (must be present in
                         `coeff` dictionary)
    @type      redshift: float
    @param     redshift: Redshift of a galaxy, should be between 0.0 and 0.5 (no
                         check is made, however)
    @type   colour_name: string
    @param  colour_name: Human name of the colour, e.g. 'u - g', 'g - r',
                         'V - Rc', 'J2 - Ks2' (must be present in `coeff` dictionary)
    @type  colour_value: float
    @param colour_value: Value of the galaxy's colour, specified in colour_name
    @rtype:              float
    @return:             K-correction in specified filter for given redshift and
                         colour
    @author:             Chilingarian, I., Melchior. A.-L., and Zolotukhin, I.
    @license:            Simplified BSD license, see http://kcor.sai.msu.ru/license.txt

    Usage example:

        >>> calc_kcor('g', 0.2, 'g - r', 1.1)
        0.60969373400000026
        >>> calc_kcor('Ic', 0.4, 'V - Ic', 2.0)
        0.310069919999993
        >>> calc_kcor('H', 0.5, 'H - K', 0.1)
        -0.21574611249999176


The unitless Hubble expansion rate at redshift z.

    In David Hogg's (arXiv:astro-ph/9905116v4) formalism, this is
    equivalent to E(z), defined in his eq. 14.

    Modified (JBJ, 29-Feb-2012) to include scalar w parameter


The value of the Hubble constant at redshift z.

    Units are s^-1

    In David Hogg's (arXiv:astro-ph/9905116v4) formalism, this is
    equivalent to H_0 * E(z) (see his eq. 14).


The value of the Hubble distance at redshift z.

    Units are Mpc.

    In David Hogg's (arXiv:astro-ph/9905116v4) formalism, this is
    equivalent to D_H / E(z) = c / (H_0 E(z)) [see his eq. 14], which
    appears in the definitions of many other distance measures.


The derivative of the comoving distance with redshift: dd_c/dz.

    See equation 15 of David Hogg's arXiv:astro-ph/9905116v4

    Units are Mpc.


The line-of-sight comoving distance (in Mpc) to redshift z.

    See equation 15 of David Hogg's arXiv:astro-ph/9905116v4

    Units are Mpc.

    Optionally calculate the integral from z0 to z.

    Returns
    -------

    d_co: ndarray
       Comoving distance in Mpc.

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> d_co = cd.comoving_distance(6., **cosmo)
    >>> print "Comoving distance to z=6 is %.1f Mpc" % (d_co)
    Comoving distance to z=6 is 8017.8 Mpc


Returns comoving_distance_transverse.

    Units are Mpc.

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> d_M = cd.proper_motion_distance(6., **cosmo)
    >>> print "Transverse comoving distance to z=6 is %.1f Mpc" % (d_M)
    Transverse comoving distance to z=6 is 8017.8 Mpc


The transverse comoving distance (in Mpc) to redshift z.

    This is also called the proper motion distance, D_M.

    See equation 16 of David Hogg's arXiv:astro-ph/9905116v4

    Units are Mpc.

    This is the distance d_m, such that the comoving distance between
    two events at the same redshift, but separated on the sky by some
    angle delta_theta is d_m * delta_theta.

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> d_M = cd.comoving_distance_transverse(6., **cosmo)
    >>> print "Transverse comoving distance to z=6 is %.1f Mpc" % (d_M)
    Transverse comoving distance to z=6 is 8017.8 Mpc


The angular-diameter distance (Mpc) to redshift z.

    Optionally find the angular diameter distance between objects at
    z0 and z (only implemented for omega_k_0 >= 0).

    See equations 18-19 of David Hogg's arXiv:astro-ph/9905116v4

    Units are Mpc.

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> d_a = cd.angular_diameter_distance(6., **cosmo)
    >>> print "Angular diameter distance = %.1f Mpc" % (d_a)
    Angular diameter distance = 1145.4 Mpc


The luminosity distance to redshift z.

    Units are Mpc.

    See, for example, David Hogg's arXiv:astro-ph/9905116v4


The differential comoving volume element dV_c/dz/dSolidAngle.

    Dimensions are volume per unit redshift per unit solid angle.

    Units are Mpc**3 Steradians^-1.

    See David Hogg's arXiv:astro-ph/9905116v4, equation 28.

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> dVc = cd.diff_comoving_volume(6.0, **cosmo)
    >>> print "dV/dz/dSolidAngle at z=6 is %.3g Mpc**3" % (dVc)
    dV/dz/dSolidAngle at z=6 is 2.63e+10 Mpc**3


The comoving volume out to redshift z.

    See David Hogg's arXiv:astro-ph/9905116v4, equation 29.

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> Vc = cd.comoving_volume(6.0, **cosmo)
    >>> print "Vc = %.3g Mpc**3" % (Vc)
    Vc = 2.16e+12 Mpc**3

    >>> import cosmolopy.distance as cd
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.0, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> Vc = cd.comoving_volume(6.0, **cosmo)
    >>> print "Vc = %.3g Mpc**3" % (Vc)
    Vc = 1.68e+12 Mpc**3


The derivative of the lookback time with redshift: dt_L/dz.

    See equation 30 of David Hogg's arXiv:astro-ph/9905116v4

    Units are seconds.


The lookback time (in s) to redshift z.

    See equation 30 of David Hogg's arXiv:astro-ph/9905116v4

    Units are s.

    Optionally calculate the integral from z0 to z.

    Returns
    -------

    t_look: ndarray
       Lookback time in seconds.


The age of the universe as seen at redshift z.

    Age at z is lookback time at z'->Infinity minus lookback time at z.

    See also: lookback_time.

    Units are s.

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> import cosmolopy.constants as cc
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> t = cd.age(6.0, **cosmo)
    >>> print "age at z=6.0 = %.3g Gyr" % (t/cc.Gyr_s)
    age at z=6.0 = 0.892 Gyr


The age of the universe assuming a flat cosmology.

    Units are s.

    Analytical formula from Peebles, p. 317, eq. 13.2.

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> import cosmolopy.constants as cc
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> t = cd.age_flat(6.0, **cosmo)
    >>> print "age at z=6.0 is %.3g Gyr" % (t/cc.Gyr_s)
    age at z=6.0 is 0.892 Gyr


Return an interpolation function that will give distance as a
    funtion of z

    If return_inverse is True, will also return a function giving z as
    a function of distance.

    Inputs
    ------

    function -- the distance function to interpolate (can be any
    callable that takes a redshift argument plus cosmology keywords).

    k -- spline order (`scipy.interpolate.InterpolatedUnivariateSpline`)

    Returns
    -------

    distfunc

    or

    distfunc, zfunc

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> import cosmolopy.constants as cc
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> distfunc, redfunc = cd.quick_distance_function(cd.luminosity_distance, return_inverse=True, **cosmo)
    >>> d = distfunc(6.3333)
    >>> z = redfunc(d)
    >>> "%.1g" % (distfunc(6.3333)/cd.luminosity_distance(6.3333, **cosmo) - 1.0)
    '-2e-16'
    >>> "%.1g" % (z/6.3333 - 1.0)
    '0'


Return an interpolation function that will give age as a funtion of z

    Units are s.

    If return_inverse is True, will also return a function giving z as
    a function of age.

    Returns
    -------

    agefunc

    or

    agefunc, redfunc

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> import cosmolopy.constants as cc
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> agefunc = cd.quick_age_function(**cosmo)
    >>> t = agefunc(6.0)
    >>> print "age at z=6.0 is %.3g Gyr" % (t/cc.Gyr_s)
    age at z=6.0 is 0.892 Gyr


Return an interpolation function giving z as a funtion of age
    of the universe.

    Units of time are s.

    Returns
    -------

    redfunc

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> import cosmolopy.constants as cc
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> redfunc = cd.quick_redshift_age_function(**cosmo)
    >>> z = redfunc(1.0 * cc.Gyr_s)
    >>> print "When age=1.0Gyr z=%.2f" % (z)
    When age=1.0Gyr z=5.49


The light travel distance to redshift z.

    Units are Mpc.

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> dlookback = cd.light_travel_distance(3.0, 2.0, **cosmo)
    >>> print "Lookback distance from z=2 to 3 is %.2g Mpc" % (dlookback)
    Lookback distance from z=2 to 3 is 3.3e+02 Mpc


The redshift corresponding to a given light travel distance.

    Units are the same as light_travel_distance (Mpc).

    Examples
    --------

    >>> import cosmolopy.distance as cd
    >>> import cosmolopy.constants as cc
    >>> cosmo = {'omega_M_0' : 0.3, 'omega_lambda_0' : 0.7, 'h' : 0.72}
    >>> cosmo = cd.set_omega_k_0(cosmo)
    >>> z = cd.redshift_d_light(10. * cc.c_light_Mpc_Gyr, **cosmo)
    Optimization terminated successfully.
             Current function value: 0.000112
             Iterations: 26
             Function evaluations: 52
    >>> print "Redshift for a lookback time of 10Gyr is z=%.3f" % (z)
    Redshift for a lookback time of 10Gyr is z=2.025


	med = mean(y_interp)
	stand = std(y_interp)

	x2 = []
	y2 = []
	for k in range(len(y_interp)):
		if fabs(y_interp[k]-med)<1.*stand:
			x2.append(x_interp[k])
			y2.append(y_interp[k])


Function finds radius r for which the surface brightness of the disk is
    equal to the surface brightness of the bulge.


Finds thex fourier spectrum of an image


	print "fitsio"
	print "set imtype=hhh"
	print "strfits %s \"\" gal.hhh xdim=yes oldiraf=yes force=yes" % (file_in)
	print "bye"


	import time
	import multiprocessing

	def ell_running():
		subprocess.call("cl < ell.cl -o", shell=True)

	downloader = multiprocessing.Process(target=ell_running)
	downloader.start()
	timeout = 0.5
	time.sleep(timeout)
	downloader.terminate()

	#http://pastebin.com/89Wfduxq


	kk = 0
	while kk<=2:
		Ell = []
		BB4 = []
		for k in range(len(sma)):
			if sma[k]>=radius-step and sma[k]<=radius+step and ell[k]!=0 and B4[k]!=0:
				Ell.append(ell[k])
				BB4.append(B4[k])
				kk = kk + 1
		step = step+1

	if type(Ell)==np.ndarray:
		ellip = mean(Ell)
		bb4 = mean(BB4)
	else:
		ellip = median(Ell)
		bb4 = median(BB4)


	sma = np.array(sma,dtype='float')
	inten = np.array(inten,dtype='float')
	inten_err = np.array(inten_err,dtype='float')
	ell = np.array(ell,dtype='float')
	errell = np.array(errell,dtype='float')
	PA = np.array(PA,dtype='float')
	errPA = np.array(errPA,dtype='float')
	x0 = np.array(x0,dtype='float')
	y0 = np.array(y0,dtype='float')
	B4 = np.array(B4,dtype='float')
	errB4 = np.array(errB4,dtype='float')


Function to re-write an SNANA sim file given parameter inputs. New file is labelled with processor ID.
    Input: om=Omega_m, ol=Omega_lambda, w0=w0, beta=color parameter, alph = stretch parameter, nid = processor ID


Function to write SNANA fit file and label it with processor ID
    Input: nid = processor ID


Function to launch SNANA sim using subprocess
    Input: node_id = processor ID
    summary_file: name out sim summary file, once this exists sim is done and we exit the func
    Returns: error message from func check_abort


Function which checks for words "abort" or "ABORT" in sim summary file
    Input: SNANA sim summary file
    Returns: sim_ok flag = True or False


Function to launch SNANA fitting program using split_and_fit
    Input: node_id = Processor ID, sim_root_file = ROOT file from fit


Function to check the output of SNANA fit completed
    Input: node_id = processor ID, merge_file = merge file
    Returns: Boolean True or False depending on if "Done." appears in merge file


Checks for specific parameter names and then returns ordered list for sampler
    Input: theta - list of parameters to be varied
            param_names - parsed names for each parameter
    Returns: theta_om , theta_w0, theta_alpha, theta_beta


require minNumEpochs in at least minNumFilters with SNR>minSNR


function to generate t0 from uniform dist


Function to generate random c and x1 from either Normal or skew normal distributions


function to read snana like simlib file


create dict specific to DES fields, areas are in deg^2,
		survey time is specified from GENRANGE_PEAKMJD, zmin, zmax and zcut are specified in SNANA GENRANGE_REDSHIFT & DNDZ


Method to create inverse spline to discrete cumulative distribution function
		to allow drawing random variables.
		Warning: user should check that spline faithfully matches actual cdf.


returns los comoving distance in Mpc/h


Light Curve metric. Create a dict with keys=SimID_4LCs, value=[[DataID_4LCs,pkmjd-rescale,zrescale]]
        input:
                dLC: instance of lightcurves for the data
                sLC: instance of lightcurves for one sim
        returns:
                sim_dict: dict of key,value = SimID_4LCs, value=[[DataID_4LCs,pkmjd-rescale,zrescale]]


 Light Curve metric. Function to find the observed difference PDF all bands for each SIM-DATA pair.
            This is compared with the expected distribution from the ref PDF to calculate the chi^2
        Input: dataLC - instance of data LC class
                simLC - instance of sim LC class
        Returns: TS/real_ddof - chi^2 per degree of freedom


Light Curve metric. Function to obtain a sim SN LC and adjust it to match data pkmjd and redshift in each band.
        Input: scid - id of the sim SN
                val - list of data id, pkmjd correction, z correction
                d_mjd - epochs of data LC
                sLC - instance of sim SN LC class
        Returns: list of lists of splined sim SN fluxes at same epochs as data in each band


Tripp metric using snana simulations


Tripp metric using sncosmo simulations


This is the main function the abc sampler calls for every particle.
        Given a parameter set theta, a sim is run with these parameters and fit
.
        Input: theta = array of parameters to be varied specified in params.ini
        Returns: instance of LightCurves for a simulation using theta, which is passed to dist_metric


Function to initialize instance of the sampler, specify the forward model simulation and begin sampling.


creates spline to full LC given cid for SN and band
		   input:
			x,y,z array for spline (optional) if not provided spline is for MJD and FLUXCAL
		   returns:
			spline for LC


Override method to raise error
        Parameters
        ----------
        message: string
            error message


        Allows to set a default subparser

        This trick is there to maintain the previous way of calling
        MontePython.py


    Check if the input is integer positive
    Parameters
    ----------
    string: string
        string to parse

    output: int
        return the integer


    Check if the file exists. If not raise an error

    Parameters
    ----------
    fname: string
        file name to parse

    Returns
    -------
    fname : string


    Extract from the docstring the keys and description, return it as a dict

    Parameters
    ----------
    docstring : str
    key_symbol : str
        identifies the key of an argument/option
    description_symbol : str
        identify the description of an argument/option

    output
    ------
    helpdic : dict
        help strings for the parser


    Create a custom help action.

    It expects *split_string* to appear in groups of three.
    If the option string is '-h', then uses the short description
    between the first two *split_string*.
    If the option string is '-h', then uses all that is between
    the first and the third *split_string*, stripping the first one.

    Parameters
    ----------
    split_string: str
        string to use to select the help string and how to select them.
        They must appear in groups of *3*

    output
    ------
    CustomHelp: class definition


    Add a parser to the subparser *sp* with *name*.

    All the logic common to all subparsers should go here

    Parameters
    ----------
    sp: subparser instance
    name: str
        name of the subparser
    kwargs: dict
        keywords to pass to the subparser

    output
    ------
    sparser: Argparse instance
        new subparser


        Decorator that wraps the function that implement the parser, parses the
        `__doc__` and construct a dictionary with the help strings.  The
        dictionary is added as an attribute of `func` and can be accessed in
        the function

        Parameters
        ----------
        func: function
            function with the docs to be parsed

        Returns
        ------
        func: function
            function with the dictionary added. *key_symbol* and
            *description_symbol* strings are removed


    Create the argument parser and returns it
    Parameters
    ----------
    kwargs: dictionary
        keyword to pass to the parser
    output
    ------
    p: MpArgumentParser instance
        parser with some keyword added


    Check some basic organization of the folder, and exit the program in case
    something goes wrong.

    Keyword Arguments
    -----------------
    custom_command : str
        For testing purposes, instead of reading the command line argument,
        read instead the given string. It should ommit the start of the
        command, so e.g.: '-N 10 -o toto/'


    Initialisation routine

    This function recovers the input from the command line arguments, from
    :mod:`parser_mp`, the parameter files.

    It then extracts the path of the used Monte Python code, and proceeds to
    initialise a :class:`data` instance, a cosmological code instance.

    Parameters
    ----------
        custom_command: str
            allows for testing the code


    Read the configuration file, filling a dictionary

    Returns
    -------
    path : dict
        contains the absolute path to the location of the code, the data, the
        cosmological code, and potential likelihood codes (clik for Planck,
        etc)


    From the cosmological module name, initialise the proper Boltzmann code

    .. note::

        Only CLASS is currently wrapped, but a python wrapper of CosmoMC should
        enter here.


Main call to prepare the information for the MultiNest run.


    Main call to run the PolyChord sampler.

    Note the unusual set-up here, with the two following functions, `prior` and
    `loglike` having their docstrings written in the encompassing function.
    This trick was necessary as PolyChord required these two functions to be
    defined with a given number of parameters, so we could not add `data`. By
    defining them inside the run function, this problem was by-passed.

    .. function:: prior

        Generate the prior function for PolyChord

        It should transform the input unit cube into the parameter cube. This
        function actually wraps the method :func:`map_from_unit_interval()
        <prior.Prior.map_from_unit_interval>` of the class :class:`Prior
        <prior.Prior>`.

        Parameters
        ----------
        cube : list
            Contains the current point in unit parameter space that has been
            selected within the PolyChord part.
        Returns
        -------
        theta : list
            The transformed physical parameters

    .. function:: loglike

        Generate the Likelihood function for PolyChord

        Parameters
        ----------
        theta : array
            Contains the current point in the correct parameter space after
            transformation from :func:`prior`.
        Returns
        -------
        logl : float
            The loglikelihood of theta
        phi : list
            The derived parameters


Please see the encompassing function docstring


    Translate the output of PolyChord into readable output for Monte Python

    This routine will be called by the module :mod:`analyze`.

    If mode separation has been performed (i.e., multimodal=True), it creates
    'mode_#' subfolders containing a chain file with the corresponding samples
    and a 'log.param' file in which the starting point is the best fit of the
    nested sampling, and the same for the sigma. The minimum and maximum value
    are cropped to the extent of the modes in the case of the parameters used
    for the mode separation, and preserved in the rest.

    The mono-modal case is treated as a special case of the multi-modal one.


        Placeholder to remind that this function needs to be defined for a
        new likelihood.

        Raises
        ------
        NotImplementedError


        Extract the information from the log.param concerning this likelihood.

        If the log.param is used, check that at least one item for each
        likelihood is recovered. Otherwise, it means the log.param does not
        contain information on the likelihood. This happens when the first run
        fails early, before calling the likelihoods, and the program did not
        log the information. This check might not be completely secure, but it
        is better than nothing.

        .. warning::

            This checks relies on the fact that a likelihood should always have
            at least **one** line of code written in the likelihood.data file.
            This should be always true, but in case a run fails with the error
            message described below, think about it.

        .. warning::

            As of version 2.0.2, you can specify likelihood options in the
            parameter file. They have complete priority over the ones specified
            in the `likelihood.data` file, and it will be reflected in the
            `log.param` file.


        Ensure that the arguments of dictionary are defined to the correct
        value in the cosmological code

        .. warning::

            So far there is no way to enforce a parameter where `smaller is
            better`. A bigger value will always overried any smaller one
            (`cl_max`, etc...)

        Parameters
        ----------
        data : dict
            Initialized instance of :class:`data`
        dictionary : dict
            Desired precision for some cosmological parameters


        Interface with CosmoHammer

        Parameters
        ----------
        ctx : Context
                Contains several dictionaries storing data and cosmological
                information


        Add to a class the content of a shared dictionary of attributes

        The purpose of this method is to set some attributes globally for a Pk
        likelihood, that are shared amongst all the redshift bins (in
        WiggleZ.data for instance, a few flags and numbers are defined that
        will be transfered to wigglez_a, b, c and d


        Extract Python variables from the configuration file

        This routine performs the equivalent to the program "inih" used in the
        original c++ library.


        extract the matrix from the path

        This routine uses the blazing fast pandas library (0.10 seconds to load
        a 740x740 matrix). If not installed, it uses a custom routine that is
        twice as slow (but still 4 times faster than the straightforward
        numpy.loadtxt method)

        .. note::

            the length of the matrix is stored on the first line... then it has
            to be unwrapped. The pandas routine read_table understands this
            immediatly, though.


        Read the file jla_lcparams.txt containing the SN data

        .. note::

            the length of the resulting array should be equal to the length of
            the covariance matrices stored in C00, etc...


    Performing the Importance Sampling

    The idea is to start from an existing run, constraining a certain model I,
    given a set of experiments. The new run will constrain the same model I,
    but adding one or several new experiments. In the case where it is expected
    that the final posterior distribution should not differ too greatly between
    the two parameter extractions, then using Importance Sampling can speed up
    significantly the second one.

    Instead of properly sampling randomly the parameter space, it instead reads
    the chains from the previous run, recompute the cosmology at this point,
    then adds the log-likelihood contributed by the new experiments to the
    previous ones. As an input of the method, with the flag
    `--IS-starting-folder`, you can thus specify either a folder containing a
    Monte Python run, or a set of chains that you want to be converted.

    The code will automatically compute the minimum amount of things. For
    instance, if the first run had all the Planck likelihoods, and the second,
    all the Planck likelihoods plus a prior on :math:`H_0`, it would be absurd
    to recompute also the cosmological perturbations: the only needed quantity
    is a background quantity.

    The new chains will hence store the same points in parameter space, but
    with a different value of the likelihood, and also of the multiplicity -
    that will become non-integer. Indeed, the multiplicity is also a probe of
    the posterior, and this new, higher likelihood should have had a higher
    multiplicity.


Translate the input to the output

    .. note::

        If the keyword argument `ignore_likelihood` is set to true, the
        previous value of the likelihood is discarded.


    Depending on the choice of sampler, dispatch the appropriate information

    The :mod:`mcmc` module is used as previously, except the call to
    :func:`mcmc.chain`, or :func:`MultiNest.run` is now within
    this function, instead of from within :mod:`MontePython`.

    In the long term, this function should contain any potential hybrid scheme.


    Pick up the last accepted values from an input chain as a starting point

    Function used only when the restart flag is set. It will simply read the
    last line of an input chain, using the tail command from the extended
    :class:`io_mp.File` class.

    .. warning::
        That method was not tested since the adding of derived parameters. The
        method :func:`read_args_from_bestfit` is the prefered one.

    .. warning::
        This method works because of the particular presentation of the chain,
        and the use of tabbings (not spaces). Please keep this in mind if you
        are having difficulties

    Parameters
    ----------
    chain : str
        Name of the input chain provided with the command line.


    Deduce the starting point either from the input file, or from a best fit
    file.

    Parameters
    ----------
    bestfit : str
        Name of the bestfit file from the command line.


    Transfer the 'current' point in the varying parameters to the last accepted
    one.


    Ensure that all varying parameters are bound and flat

    It is a necessary condition to use the code with MultiNest, PolyChord or the
    Cosmo Hammer.


    Compute the likelihood, given the current point in parameter space.

    This function now performs a test before calling the cosmological model
    (**new in version 1.2**). If any cosmological parameter changed, the flag
    :code:`data.need_cosmo_update` will be set to :code:`True`, from the
    routine :func:`check_for_slow_step <data.Data.check_for_slow_step>`.

    Returns
    -------
    loglike : float
        The log of the likelihood (:math:`\\frac{-\chi^2}2`) computed from the
        sum of the likelihoods of the experiments specified in the input
        parameter file.

        This function returns :attr:`data.boundary_loglike
        <data.data.boundary_loglike>`, defined in the module :mod:`data` if
        *i)* the current point in the parameter space has hit a prior edge, or
        *ii)* the cosmological module failed to compute the model. This value
        is chosen to be extremly small (large negative value), so that the step
        will always be rejected.


    Main call to run the MultiNest sampler.

    Note the unusual set-up here, with the two following functions, `prior` and
    `loglike` having their docstrings written in the encompassing function.
    This trick was necessary as MultiNest required these two functions to be
    defined with a given number of parameters, so we could not add `data`. By
    defining them inside the run function, this problem was by-passed.

    .. function:: prior

        Generate the prior function for MultiNest

        It should transform the input unit cube into the parameter cube. This
        function actually wraps the method :func:`map_from_unit_interval()
        <prior.Prior.map_from_unit_interval>` of the class :class:`Prior
        <prior.Prior>`.

        Parameters
        ----------
        cube : array
            Contains the current point in unit parameter space that has been
            selected within the MultiNest part.
        ndim : int
            Number of varying parameters
        nparams : int
            Total number of parameters, including the derived ones (not used,
            so hidden in `*args`)

    .. function:: loglike

        Generate the Likelihood function for MultiNest

        Parameters
        ----------
        cube : array
            Contains the current point in the correct parameter space after
            transformation from :func:`prior`.
        ndim : int
            Number of varying parameters
        nparams : int
            Total number of parameters, including the derived ones (not used,
            so hidden in `*args`)


    Translate the output of MultiNest into readable output for Monte Python

    This routine will be called by the module :mod:`analyze`.

    If mode separation has been performed (i.e., multimodal=True), it creates
    'mode_#' subfolders containing a chain file with the corresponding samples
    and a 'log.param' file in which the starting point is the best fit of the
    nested sampling, and the same for the sigma. The minimum and maximum value
    are cropped to the extent of the modes in the case of the parameters used
    for the mode separation, and preserved in the rest.

    The mono-modal case is treated as a special case of the multi-modal one.


    Rewrite chains with more derived parameters

    Starting from an existing folder, with some chains, constraining a certain
    model, and having some derived parameters, the idea is to recompute the
    cosmological code to follow additional derived parameters.


Reading the input point, and computing the new derived values


    Copy and extend the log.param from the starting to the target folder

    while adding new derived parameters


    Write the first lines of the log.param

    Writes the beginning of log.param, starting with the header with the
    cosmological code version and potential git hash and branch name, and then
    recopies entirely the input parameter file.


    Write down the interpreted .data file of the input likelihood to log.param

    .. warning::

        Since version 2.0.2, the lines are not copied verbatim, they are first
        interpreted, then copied. This allows for overriding of parameters from
        the input.param file.


    Write down the `cosmo_arguments` used to log.param

    Third function called when writing log.param. It is understood here that
    all the other parameters for the cosmological modules are set to their
    default value directly in the program.

    It is written as an update for the dictionary cosmo_arguments (i.e. as
    :code:`dict.update()` and not as :code:`dict =`) in order not to erase
    previously initialized data.


    Log the .conf file to log.param

    Fourth and last function called when writing log.param. Only useful if you
    have several versions of your cosmological code installed in different
    locations, or different versions of Clik. But, as you never know what might
    go wrong, it is logged everytime !

    TODO: should the root be still logged? (@packaging)


Log the parameter names to <date_today>_<N>_.paramnames for GetDist compatibility.


    Will print the parameter names. In the code, :code:`out` is simply the
    standard output, as this information will not be printed on the output
    file.

    Indeed, you will be able to recover these information from the log.param.

    .. warning::

        Please pay attention to the fact that, once launched, the order of the
        parameters in log.param is crucial, as is it the only place where it is
        stored.


    Print the last accepted values to :code:`out`

    Parameters
    ----------
    out : list
        Array containing both standard output and the output file.

        This way, if you run in interactive mode, you will be able to monitor
        the progress of the chain.
    N : int
        Multiplicity of the point, `i.e.` number of times the code stayed at
        this particular place.
    loglkl : float
        Value of the (- log likelihood) at this point

    .. note::

        It is the `last_accepted` point that is printed, and **not** the
        `current` one (obviously, as one does not know yet the multiplicity of
        the current one !)


Closes and reopen the output file to write any buffered quantities


    Automatically create a new name for the chain.

    This routine takes care of organising the folder for you. It will
    automatically generate names for the new chains according to the date,
    number of points chosen.

    .. warning::

        The way these names are generated (with the proper number of _, __, -,
        and their placement) is exploited in the rest of the code in various
        places.  Please keep that in mind if ever you are in the mood of
        changing things here.


    Return the string formatted according to its status

    The input is a potentially long message, describing the problem.
    According to the severity of its status (so far, 'error' will exit the
    program, whereas 'warning' and 'info' will go through anyway).

    Standard length has been defined globally, as well as the ascii-art
    dictionary of arrays START_LINE.


Imitates the classic tail command


    Lock a given file to prevent other instances of the code to write to the
    same file.

    .. warning::

        in the process of being tested


    Unlock a previously locked file.

    .. warning::

        in the process of being tested


Custom implementation of `showwarning` from :mod:`warnings`


        Initializes the ordered dictionary :attr:`mcmc_parameters` from
        the input parameter file.

        It uses :meth:`read_file`, and initializes instances of
        :class:`parameter` to actually fill in :attr:`mcmc_parameters`.


        Given an array of experiments, return an ordered dict of instances

        .. Note::

            in the __init__ method, experiments is naturally self.experiments,
            but it is useful to keep it as a parameter, for the case of
            importance sampling.


        Execute all lines concerning the Data class from a parameter file

        All lines starting with `data.` will be replaced by `self.`, so the
        current instance of the class will contain all the information.

        .. note::

            A rstrip() was added at the end, because of an incomprehensible bug
            on some systems that imagined some inexistent characters at the end
            of the line... Now should work

        .. note::

            A security should be added to protect from obvious attacks.

        Parameters
        ----------
        param : str
            Name of the parameter file
        structure : str
            Name of the class entries we want to execute (mainly, data, or any
            other likelihood)

        Keyword Arguments
        -----------------
        field : str
            If nothing is specified, this routine will execute all the lines
            corresponding to the `structure` parameters. If you specify a
            specific field, like `path`, only this field will be read and
            executed.
        separate : bool
            If this flag is set to True, a container class will be created for
            the structure field, so instead of appending to the namespace of
            the data instance, it will append to a sub-namespace named in the
            same way that the desired structure. This is used to extract custom
            values from the likelihoods, allowing to specify values for the
            likelihood directly in the parameter file.


        Regroup mcmc parameters by blocks of same speed

        This method divides all varying parameters from :attr:`mcmc_parameters`
        into as many categories as there are likelihoods, plus one (the slow
        block of cosmological parameters).

        It creates the attribute :attr:`block_parameters`, to be used in the
        module :mod:`mcmc`.

        .. note::

            It does not compute by any mean the real speed of each parameter,
            instead, every parameter belonging to the same likelihood will
            be considered as fast as its neighbour.

        .. warning::

            It assumes that the nuisance parameters are already written
            sequentially, and grouped together (not necessarily in the order
            described in :attr:`experiments`). If you mix up the different
            nuisance parameters in the .param file, this routine will not
            method as intended. It also assumes that the cosmological
            parameters are written at the beginning of the file.


Create the list of varied parameters given the oversampling


Extract version and subversion from an existing log.param


        Check whether the value of cosmological parameters were
        changed, and if no, skip computation of the cosmology.


        Put in :attr:`cosmo_arguments` the current values of
        :attr:`mcmc_parameters`

        This method is called at every step in the Markov chain, to update the
        dictionary. In the Markov chain, the scale is not remembered, so one
        has to apply it before giving it to the cosmological code.

        .. note::

            When you want to define new parameters in the Markov chain that do
            not have a one to one correspondance to a cosmological name, you
            can redefine its behaviour here. You will find in the source
            several such examples.

        .. note::

            For complex CLASS parameters, that expect a string of numbers
            separated with commas, you can now use the name of the argument,
            for instance :code:`m_ncdm`, then append a double underscore and a
            number. So if you run with two cosmological parameters,
            :code:`m_ncdm__1` and :code:`m_ncdm__2`, this function will
            automatically concatenate the two and feed class :code:`m_ncdm`.
            You still have to make sure that the other variables are properly
            set, like :code:`N_ncdm` to 2, in this example.


        Static method to call for checking if a folder was already initialised

        This method can be used to speed up the mpi initialisation in
        :mod:`run`. If a process finds that the folder is already a proper
        Monte Python one, it sends directly a 'go' signal to its next in line.

        .. warning::

            This method assumes that the last lines of the log.param are the
            path indication. If this would ever change, adjust this method
            accordingly.


        Draw a random point from the prior range considering the prior type

        Returns
        -------
        value : float
            A random sample inside the prior region


Check for a value being in or outside the prior range


Checks whether the allowed parameter range is finite


        Linearly maps a value of the interval [0,1] to the parameter range.

        For the sake of speed, assumes the parameter to be bound to a finite range, \
        which should have been previously checked with :func:`is_bound`


    Run a Markov chain of fixed length with a Metropolis Hastings algorithm.

    Main function of this module, this is the actual Markov chain procedure.
    After having selected a starting point in parameter space defining the
    first **last accepted** one, it will, for a given amount of steps :

    + choose randomly a new point following the *proposal density*,
    + compute the cosmological *observables* through the cosmological module,
    + compute the value of the *likelihoods* of the desired experiments at this
      point,
    + *accept/reject* this point given its likelihood compared to the one of
      the last accepted one.

    Every time the code accepts :code:`data.write_step` number of points
    (quantity defined in the input parameter file), it will write the result to
    disk (flushing the buffer by forcing to exit the output file, and reopen it
    again.

    .. note::

        to use the code to set a fiducial file for certain fixed parameters,
        you can use two solutions. The first one is to put all input 1-sigma
        proposal density to zero (this method still works, but is not
        recommended anymore). The second one consist in using the flag "-f 0",
        to force a step of zero amplitude.


    Main function, does the entire analysis.

    It calls in turn all the other routines from this module. To limit the
    arguments of each function to a reasonnable size, a :class:`Information`
    instance is used. This instance is initialized in this function, then
    appended by the other routines.


    Scan the whole input folder, and include all chains in it.

    Since you can decide to analyze some file(s), or a complete folder, this
    function first needs to separate between the two cases.

    .. warning::
        If someday you change the way the chains are named, remember to change
        here too, because this routine assumes the chains have a double
        underscore in their names.

    .. note::
        Only files ending with .txt will be selected, to keep compatibility
        with CosmoMC format

    .. note::
        New in version 2.0.0: if you ask to analyze a MultiNest
        sub-folder (i.e. something that ends in `NS` with capital letters), the
        analyze module will translate the output from MultiNest to
        standard chains for Monte Python, and stops. You can then run the
        `-- info` flag on the whole folder. **This procedure is not necessary
        if the run was complete, but only if the MultiNest run was killed
        before completion**.

    Parameters
    ----------
    files : list
        list of potentially only one element, containing the files to analyze.
        This can be only one file, or the encompassing folder, files
    info : Information instance
        Used to store the result


    Compute convergence for the desired chains, using Gelman-Rubin diagnostic

    Chains have been stored in the info instance of :class:`Information`. Note
    that the G-R diagnostic can be computed for a single chain, albeit it will
    most probably give absurd results. To do so, it separates the chain into
    three subchains.


    computes the marginalized posterior distributions, and optionnally plots
    them

    Parameters
    ----------
    information_instances : list
        list of information objects, initialised on the given folders, or list
        of file, in input. For each of these instance, plot the 1d and 2d
        posterior distribution, depending on the flags stored in the instances,
        comming from command line arguments or read from a file.


Extract the contours for the 2d plots (Karim Benabed)


Extract minimum credible intervals (method from Jan Haman) FIXME


Write one horizontal line of output


Small routine to accomodate the absence of the interpolate module


Store the posterior distribution to a file


Recover a stored 1d posterior


Store the histogram information to a file, to plot it later


    Read the histogram information that was stored in a file.

    To use it, call something like this:

    .. code::

        x_centers, y_centers, extent, hist = read_histogram_2d_from_file(path)
        fig, ax = plt.subplots()
        ax.contourf(
            y_centers, x_centers, hist, extent=extent,
            levels=ctr_level(hist, [0.68, 0.95]),
            zorder=5, cma=plt.cm.autumn_r)
        plt.show()


    Execute the methods "convert" from the different sampling algorithms

    Returns True if something was made, False otherwise


    Separate the input files in folder

    Given all input arguments to the command line files entry, separate them in
    a list of lists, grouping them by folders. The number of identified folders
    will determine the number of information instances to create


    Distinguish the cases when analyze is called with files or folder

    Note that this takes place chronologically after the function
    `separate_files`


    Return the array on the RHS of the line

    >>> extract_array("toto = ['one', 'two']\n")
    ['one', 'two']
    >>> extract_array('toto = ["one", 0.2]\n')
    ['one', 0.2]


    Return the key and value of the dictionary element contained in line

    >>> extract_dict("something['toto'] = [0, 1, 2, -2, 'cosmo']")
    'toto', [0, 1, 2, -2, 'cosmo']


Reading the log.param, store in the Information instance the names


    Finding the global maximum of likelihood

    min_minus_lkl will be appended with all the maximum likelihoods of files,
    then will be replaced by its own maximum. This way, the global
    maximum likelihood will be used as a reference, and not each chain's
    maximum.


Create an array with all the points from the chains, after removing non-markovian, burn-in and fixed fraction


Define what we call a comment in MontePython chain files


        Perform substitutions of parameters for analyzing

        .. note::

            for arbitrary combinations of parameters, the prior will not
            necessarily be flat.


Write vertical info file


Write a tex table containing the main results


    Main call of the function

    It recovers the initialised instances of cosmo Class, :class:`Data` and the
    NameSpace containing the command line arguments, feeding into the sampler.

    Parameters
    ----------
        custom_command: str
            allows for testing the code


    Launch a simple MPI run, with no communication of covariance matrix

    Each process will make sure to initialise the folder if needed. Then and
    only then, it will send the signal to its next in line to proceed. This
    allows for initialisation over an arbitrary cluster geometry (you can have
    a single node with many cores, and all the chains living there, or many
    nodes with few cores). The speed loss due to the time spend checking if the
    folder is created should be negligible when running decently sized chains.

    Each process will send the number that it found to be the first available
    to its friends, so that the gathering of information post-run is made
    easier. If a chain number is specified, this will be used as the first
    number, and then incremented afterwards with the rank of the process.


    Tentative covmat update run

    Not reachable yet by any option.


    Wrapper around the init function to handle errors

    KeyWord Arguments
    -----------------
    custom_command : str
        testing purposes
    comm : MPI.Intracomm
        object that helps communicating between the processes
    nprocs : int
        number of processes


Translate a command corresponding to a run into one for analysis


Make sure that the command uses the covariance matrix from the folder


Sample with the CosmoHammer


    Translate the output of the Cosmo Hammer into Monte Python chains

    This function will be called by the module :mod:`analyze`.


Writes the walker positions and the likelihood to the disk


        Helper function to read in the full data vector from public KiDS-450
        release and to bring it into the input format used in the original
        CFHTLenS likelihood.


        Helper function to read in the full covariance matrix from the public
        KiDS-450 release and to bring it into format of self.xi_obs.


Fitting formula for baryon feedback after equation 10 and Table 2 from J. Harnois-Deraps et al. 2014 (arXiv.1407.4301)


        # Recover the non_linear scale computed by halofit. If no scale was
        # affected, set the scale to one, and make sure that the nuisance
        # parameter epsilon is set to zero
        k_sigma = np.zeros(self.nzmax, 'float64')
        if (cosmo.nonlinear_method == 0):
            k_sigma[:] = 1.e6
        else:
            k_sigma = cosmo.nonlinear_scale(self.z_p, self.nzmax)

        # Define the alpha function, that will characterize the theoretical
        # uncertainty. Chosen to be 0.001 at low k, raise between 0.1 and 0.2
        # to self.theoretical_error
        alpha = np.zeros((self.nlmax, self.nzmax), 'float64')
        if self.theoretical_error != 0:
            for index_l in xrange(self.nlmax):
                k = (self.l[index_l] + 0.5) / r
                alpha[index_l, :] = np.log(1. + k[:] / k_sigma[:]) / (1. + np.log(1. + k[:] / k_sigma[:])) * self.theoretical_error

        # recover the e_th_nu part of the error function
        # Omega_nu must be subtracted from Omega_m if it contains all species!
        e_th_nu = self.coefficient_f_nu * cosmo.Omega_nu / (Omega_m - cosmo.Omega_nu)

        # Compute the Error E_th_nu function
        if 'epsilon' in self.use_nuisance:
            E_th_nu = np.zeros((self.nlmax, self.nzmax), 'float64')
            for index_l in xrange(1, self.nlmax):
                E_th_nu[index_l, :] = np.log(1. + self.l[index_l] / k_sigma[:] * r[:]) / (1. + np.log(1. + self.l[index_l] / k_sigma[:] * r[:])) * e_th_nu

        # Add the error function, with the nuisance parameter, to P_nl_th, if
        # the nuisance parameter exists
                for index_l in xrange(self.nlmax):
                    epsilon = data.mcmc_parameters['epsilon']['current'] * (data.mcmc_parameters['epsilon']['scale'])
                    pk[index_l, :] *= (1. + epsilon * E_th_nu[index_l, :])


        Helper function to read in the full data vector from public KiDS+VIKING-450
        release and to bring it into the input format used in the original
        CFHTLenS likelihood.


        Helper function to read in the full covariance matrix from the public
        KiDS+VIKING-450 release and to bring it into format of self.xi_obs.


        This function takes xi_pm as read in from the data file and constructs
        the xi_pm vector in its observed ordering:
         xi_obs = {xi_p(theta1, z1xz1)... xi_p(thetaK, z1xz1), xi_m(theta1, z1xz1)...
                   xi_m(thetaK, z1xz1);... xi_p(theta1, zNxzN)... xi_p(thetaK, zNxzN),
                   xi_m(theta1, zNxzN)... xi_m(thetaK, zNxN)}


        This function takes a xi_pm vector in the observed ordering (as it
        comes out of the __get_xi_obs-function for example) and splits it again
        in its xi_p and xi_m parts.


        #print(pk)
        # Recover the non_linear scale computed by halofit. If no scale was
        # affected, set the scale to one, and make sure that the nuisance
        # parameter epsilon is set to zero
        k_sigma = np.zeros(self.nzmax, 'float64')
        if (cosmo.nonlinear_method == 0):
            k_sigma[:] = 1.e6
        else:
            k_sigma = cosmo.nonlinear_scale(self.z_p, self.nzmax)

        # Define the alpha function, that will characterize the theoretical
        # uncertainty. Chosen to be 0.001 at low k, raise between 0.1 and 0.2
        # to self.theoretical_error
        alpha = np.zeros((self.nlmax, self.nzmax), 'float64')
        if self.theoretical_error != 0:
            for index_l in xrange(self.nlmax):
                k = (self.l[index_l] + 0.5) / r[1:]
                alpha[index_l, 1:] = np.log(1. + k[1:] / k_sigma[1:]) / (1. + np.log(1. + k[1:] / k_sigma[1:])) * self.theoretical_error

        # recover the e_th_nu part of the error function
        # Omega_nu must be subtracted from Omega_m if it contains all species!
        e_th_nu = self.coefficient_f_nu * cosmo.Omega_nu / (Omega_m - cosmo.Omega_nu)

        # Compute the Error E_th_nu function
        if 'epsilon' in self.use_nuisance:
            E_th_nu = np.zeros((self.nlmax, self.nzmax), 'float64')
            for index_l in xrange(1, self.nlmax):
                E_th_nu[index_l, 1:] = np.log(1. + self.l[index_l] / k_sigma[1:] * r[1:]) / (1. + np.log(1. + self.l[index_l] / k_sigma[1:] * r[1:])) * e_th_nu

        # Add the error function, with the nuisance parameter, to P_nl_th, if
        # the nuisance parameter exists
                for index_l in xrange(self.nlmax):
                    epsilon = data.mcmc_parameters['epsilon']['current'] * (data.mcmc_parameters['epsilon']['scale'])
                    pk[index_l, 1:] *= (1. + epsilon * E_th_nu[index_l, 1:])


        This function plots observational data with the spectroscopic notation:
        [X/Y] = log10(n_X/n_Y) - log10(n_X/n_Y)_solar where 'n_X' and 'n_Y' are
        the number densities of elements X and Y.

        Parameters
        ---------

        galaxy : string

            Name of the target galaxy.  The code then automatically selects
            the corresponding data sets (when available).

            Choices : 'milky_way', 'sculptor', 'carina', 'fornax'

            Default value : 'milky_way'

        xaxis : string

            Elements on the x axis in the form of '[X/Y]'.

            Default value : '[Fe/H]'

        yaxis : string

            Elements on the y axis in the form of '[X/Y]'.

            Default value : '[Mg/Fe]'

        norm : string

            Common solar normalization used to scale all the data.  Use the
            list_solar_norm() function for a list of available normalizations.
            When not specified, each data uses the solar normalization of the
            reference paper.

            Example : norm='Anders_Grevesse_1989'

        obs : string array

            Personal selection of observational data.  Use the list_ref_papers()
            function for a list of availble data sets.  When not specified, all
            the available data for the selected galaxy will be plotted.

            Example : obs=['milky_way_data/Venn_et_al_2004_stellab',
            'milky_way_data/Hinkel_et_al_2014_stellab']

        show_err : boolean

            If True, show error bars when available in the code.

            Default value : False

        show_mean_err : boolean

            If True, print the mean X and Y errors when error bars are available
            in the code.

            Default value : False

        return_xy : boolean

            If True, return the X and Y axis arrays instead of plotting the data.

            Default value = False

            Example : x, y = stellab.plot_spectro(return_xy=True)

        fsize : 2D float array

            Figure dimension/size.

        fontsize : integer

            Font size of the numbers on the X and Y axis.

        rspace : float

            Extra space on the right for the legend.

        bspace : float

            Extra space at the bottom for the Y axis label.

        labelsize : integer

            Font size of the X and Y axis labels.

        legend_fontsize : integer

            Font size of the legend.

        Examples
        ----------

        >>> stellab.plot_spectro(yaxis='[Ti/H]',xaxis='[Mg/H]',galaxy='sculptor',norm='Anders_Grevesse_1989',show_err=True)


        Internal function in order to get standardized figure font sizes.
        It is used in the plotting functions.


This function plots the list of solar normalizations available.


        This function prints lists of available data sets.

        Parameters
        ---------

        galaxy : string

            Name of the target galaxy for which data sets will be displayed.
            If empty includes data sets of all available galaxies.

            Choices : 'milky_way', 'sculptor', 'carina', 'fornax'

            Default value : ''


        Plots abundance distribution [Elements/Fe] vs Z

        Parameters
        ---------

        elements : array
        find_elements : array
            Plot only


        Helping function to plot the abundance distribution [Elements/Fe] vs Z

        Parameters
        ---------

        elements : array
            list of elements to be plotted
        abunds : array
            abundances as [X/Fe]
        label_on : boolean
            if true plots the element label for each element


        Write stellar data table for the stellab database. Format as for
        files found in stellab_data and read in by stellab.

        Parameters
        ---------

        data : list
            List of stellar data such as abundances. Each list element
            contains list entries for a star.

        attr : list
            List of types of stellar data such as [Fe/H] for each star.
        filename : string
            Name of data file to be written


        Calculate interpolation coefficients to interpolate the stellar
        initial composition (X0) in between metallicities. This assumes
        that the initial composition is the same for all masses at a given
        metallicity.

        log10(X0) = fct(log10(Z))


        This function checks for incompatible input entries and stops
        the simulation if needed.


        This function reads decay_file and create the decay_info array
        to be used when radioactive isotopes are used.


        This function reads the yield files and creates the decay_info
        array from them to include all isotopes.


Simply read the isotopes in path and add them to the set "allIsotopes"


        This function reads the radioactive isotopes yields using the
        decay_file and decay_info parameters to define which isosoptes
        are considered.


Take care of absolute paths


        Define the dictionaries storing information about
        chemical elements


Sort list of isotopes by atomic number, then by mass number


This function reads the isotopes yields table for different sites


Get the mass and metallicities of the input stellar yields


        Interpolate the mass-dependent yields table of massive
        popIII yields.  This will create arrays containing interpolation
        coefficients.  The chemical evolution calculations will then
        only use these coefficients instead of the yields table.

        Interpolation laws
        ==================

          Interpolation across stellar mass M
            log10(yields) = a_M * M + b_M

          Interpolation (total mass) across stellar mass
            M_ej = a_ej * M + b_ej

        Results
        =======

          a_M and b_M coefficients
          ------------------------
            y_coef_M_pop3[i_coef][i_M_low][i_iso]
              - i_coef : 0 and 1 for a_M and b_M, respectively
              - i_M_low : Index of the lower mass limit where
                          the interpolation occurs
              - i_iso : Index of the isotope


        Interpolate the metallicity- and mass-dependent yields
        table of massive and AGB stars.  This will create arrays
        containing interpolation coefficients.  The chemical
        evolution calculations will then only use these
        coefficients instead of the yields table.

        Interpolation laws
        ==================

          Interpolation across stellar mass M
            log10(yields) = a_M * M + b_M

          Interpolation (total mass) across stellar mass
            M_ej = a_ej * M + b_ej

          Interpolation of a_M and b_M across metallicity Z
            x_M    = a_Z * log10(Z) + b_Z
            x_M_ej = a_Z * log10(Z) + b_Z

          The functions first calculate a_M and b_M for each Z,
          and then interpolate these coefficients across Z.

        Results
        =======

          a_M and b_M coefficients
          ------------------------
            y_coef_M[i_coef][i_Z][i_M_low][i_iso]
              - i_coef : 0 and 1 for a_M and b_M, respectively
              - i_Z : Metallicity index available in the table
              - i_M_low : Index of the lower mass limit where
                          the interpolation occurs
              - i_iso : Index of the isotope

          a_Z and b_Z coefficients for x_M
          --------------------------------
            y_coef_Z_xM[i_coef][i_Z_low][i_M_low][i_iso]
              - i_coef : 0 and 1 for a_Z and b_Z, respectively
              - i_Z_low : Index of the lower metallicity limit where
                          the interpolation occurs
              - i_M_low : Index of the lower mass limit where
                          the interpolation occurs
              - i_iso : Index of the isotope

        Note
        ====

          self.Z_table is in decreasing order
          but y_coef_... arrays have metallicities in increasing order


        Declare the arrays that will contain the interpolation
        coefficients used in the chemical evolution calculation.


        Create the boundary stellar masses array representing
        the mass points in between which there will be yields
        interpolations.  This is for massive PopIII stars.


        Create the boundary stellar masses array representing
        the mass points in between which there will be yields
        interpolations.  This is for massive and AGB stars.


        Get the lower and upper boundary yields in between
        which there will be a yields interpolation.  This is
        for massive PopIII star yields.

        Argument
        ========

          i_M : Index of the lower mass limit where the
                interpolation occurs.  This is taken from
                the self.inter_M_points array.


        Get the lower and upper boundary yields in between
        which there will be a yields interpolation.  This is
        for massive and AGB star yields.

        Argument
        ========

          i_Z : Metallicity index of the yields table
          i_M : Index of the lower mass limit where the
                interpolation occurs.  This is taken from
                the self.inter_M_points array.


        Calculate the interpolation coefficients for interpolating
        in between two given yields of different mass.

        Interpolation law
        =================

          log10(yields) = a_M * M + b_M
          M_ej = a_ej * M + b_ej

        Argument
        ========

          m_low : Lower stellar mass boundary (yields)
          m_upp : Upper stellar mass boundary (yields)
          yields_low : Yields associated to m_low (yields)
          yields_upp : Yields associated to m_upp (yields)
          m_low_ej : Lower stellar mass boundary (total mass)
          m_upp_ej : Upper stellar mass boundary (total mass)
          yields_low_ej : Yields associated to m_low (total mass)
          yields_upp_ej : Yields associated to m_upp (total mass)


        Calculate the interpolation coefficients for interpolating
        in between two given lifetimes at different mass.

        Interpolation law
        =================

          log10(tau) = a_M * log10(M) + b_M

        Argument
        ========

          m_low : Lower stellar mass boundary
          m_upp : Upper stellar mass boundary
          tau_low : Lifetime associated to m_low
          tau_upp : Lifetime associated to m_upp


        Scale yields according to the total ejected mass vs initial
        mass relation.  This will keep the relative chemical composition
        of the yields.

        Interpolation law
        =================

          M_ej = a * M_initial + b

        Argument
        ========

          m_low : Initial mass of the lower-mass boundary model
          m_upp : Initial mass of the upper-mass boundary model
          yields_low : Yields of the lower-mass boundary model
          yields_upp : Yields of the upper-mass boundary model
          the_m_scale : Initial mass to which the_yields will be scaled
          the_yields : Yields that need to be scaled
          the_yields_m_tot : Total mass of the yields that need to be scaled


        Extrapolate yields for stellar masses larger than what
        is provided in the yields table.

        Extrapolation choices (input parameter)
        =====================

          copy : This will apply the yields of the most massive model
                 to all more massive stars.

          scale : This will scale the yields of the most massive model
                  using the relation between the total ejected mass and
                  the initial stellar mass.  The later relation is taken
                  from the interpolation of the two most massive models.

          extrapolate : This will extrapolate the yields of the most massive
                        model using the interpolation coefficients taken from
                        the interpolation of the two most massive models.

        Arguments
        =========

          table_ehm : Yields table
          Z_ehm : Metallicity of the yields table
          m_extra : Mass to which the yields will be extrapolated
          is_radio : Whether these are radioactive yields


        Calculate the interpolation coefficients for interpolating
        the mass-interpolation coefficients in between two given
        metallicities.

        Interpolation laws
        ==================

          log10(yields) = a_M * M + b_M
          x_M = a_Z * log10(Z) + b_Z

          The function calculates a_Z and b_Z for either a_M or b_M

        Argument
        ========

          x_M_low : Lower mass-interpolation coefficient limit (yields)
          x_M_upp : Upper mass-interpolation coefficient limit (yields)
          x_M_ej_low : Lower mass-interpolation coefficient limit (total mass)
          x_M_ej_upp : Upper mass-interpolation coefficient limit (total mass)
          Z_low : Lower-metallicity limit of the interpolation
          Z_upp : Upper-metallicity limit of the interpolation


        Calculate the interpolation coefficients for interpolating
        the mass-interpolation lifetime coefficients in between two
        given metallicities.

        Interpolation laws
        ==================

          log10(tau) = a_M * log10(M) + b_M
          x_M = a_Z * Z + b_Z

          The function calculates a_Z and b_Z for either a_M or b_M

        Argument
        ========

          x_M_low : Lower mass-interpolation coefficient limit
          x_M_upp : Upper mass-interpolation coefficient limit
          Z_low : Lower-metallicity limit of the interpolation
          Z_upp : Upper-metallicity limit of the interpolation


        Interpolate the mass-dependent lifetimes of PopIII stars.
        This will create arrays containing interpolation coefficients.
        The chemical evolution calculations will then only use these
        coefficients instead of the tabulated lifetimes.

        Interpolation laws
        ==================

          Interpolation across stellar mass M
            log10(tau) = a_M * log10(M) + b_M

        Results
        =======

          a_M and b_M coefficients
          ------------------------
            tau_coef_M_pop3[i_coef][i_M_low]
              - i_coef : 0 and 1 for a_M and b_M, respectively
              - i_M_low : Index of the lower mass limit where
                          the interpolation occurs

        Note
        ====

          self.Z_table is in decreasing order
          but y_coef_... arrays have metallicities in increasing order


        Interpolate the metallicity- and mass-dependent lifetimes
        of massive and AGB stars.  This will create arrays containing
        interpolation coefficients.  The chemical evolution calculations
        will then only use these coefficients instead of the tabulated
        lifetimes.

        Interpolation laws
        ==================

          Interpolation across stellar mass M
            log10(tau) = a_M * log10(M) + b_M
            log10(M) = a_M * log10(tau) + b_M

          Interpolation of a_M and b_M across metallicity Z
            x_M = a_Z * Z + b_Z

          The functions first calculate a_M and b_M for each Z,
          and then interpolate these coefficients across Z.

        Results
        =======

          a_M and b_M coefficients
          ------------------------
            tau_coef_M[i_coef][i_Z][i_M_low]
              - i_coef : 0 and 1 for a_M and b_M, respectively
              - i_Z : Metallicity index available in the table
              - i_M_low : Index of the lower mass limit where
                          the interpolation occurs

          a_Z and b_Z coefficients for x_M
          --------------------------------
            y_coef_Z_xM_tau[i_coef][i_Z_low][i_M_low]
              - i_coef : 0 and 1 for a_Z and b_Z, respectively
              - i_Z_low : Index of the lower metallicity limit where
                          the interpolation occurs
              - i_M_low : Index of the lower mass limit where
                          the interpolation occurs

        Note
        ====

          self.Z_table is in decreasing order
          but y_coef_... arrays have metallicities in increasing order


        Calculate the interpolation coefficients to extract
        the mass of stars based on their lifetimes.

        Interpolation laws
        ==================

          Interpolation across stellar lifetime tau
            log10(M) = a_tau * log10(tau) + b_tau

          Interpolation of a_M and b_M across metallicity Z
            x_M = a_Z * Z + b_Z

        Results
        =======

          a_tau and b_tau coefficients
          ----------------------------
            tau_coef_M_pop3_inv[i_coef][i_tau_low]
              - i_coef : 0 and 1 for a_tau and b_tau, respectively
              - i_tau_low : Index of the lower lifetime limit where
                            the interpolation occurs

          a_Z and b_Z coefficients for x_tau
          ----------------------------------
            tau_coef_Z_xM_pop3_inv[i_coef][i_Z_low][i_tau_low]
              - i_coef : 0 and 1 for a_Z and b_Z, respectively
              - i_tau_low : Index of the lower lifetime limit where
                            the interpolation occurs

        Note
        ====

          self.Z_table is in decreasing order
          but y_coef_... arrays have metallicities in increasing order


        Calculate the interpolation coefficients to extract
        the mass of stars from metallicity- and mass-dependent
        lifetimes.  This will fix lifetime intervals that will
        be common to all metallicities.  This will accelerate
        the mass search during the chemical evolution calculation.

        Interpolation laws
        ==================

          Interpolation across stellar lifetime tau
            log10(M) = a_tau * log10(tau) + b_tau

          Interpolation of a_M and b_M across metallicity Z
            x_M = a_Z * Z + b_Z

        Results
        =======

          a_tau and b_tau coefficients
          ----------------------------
            tau_coef_M_inv[i_coef][i_Z][i_tau_low]
              - i_coef : 0 and 1 for a_tau and b_tau, respectively
              - i_Z : Metallicity index available in the table
              - i_tau_low : Index of the lower lifetime limit where
                            the interpolation occurs

          a_Z and b_Z coefficients for x_tau
          ----------------------------------
            tau_coef_Z_xM_inv[i_coef][i_Z_low][i_tau_low]
              - i_coef : 0 and 1 for a_Z and b_Z, respectively
              - i_Z_low : Index of the lower metallicity limit where
                          the interpolation occurs
              - i_tau_low : Index of the lower lifetime limit where
                            the interpolation occurs

        Note
        ====

          self.Z_table is in decreasing order
          but y_coef_... arrays have metallicities in increasing order


        Create the lifetime points in between which there will be
        interpolations.  This is for PopIII stars.


        Create the lifetime points in between which there will be
        interpolations.  This is for metallicity-dependent models.


        Return the interpolated mass of a given lifetime.
        This is for PopIII stars

        Interpolation law
        =================

            log10(M) = a_M * log10(tau) + b_M

        Arguments
        =========

          the_tau : Lifetime [yr]


        Return the interpolated mass of a given metallicity
        that has a given lifetime.

        Interpolation law
        =================

            log10(M) = a_M * log10(tau) + b_M

        Arguments
        =========

          i_Z : Metallicity index of the yields table
          the_tau : Lifetime [yr]


        This function returns the initial gas reservoir, ymgal, containing
        the mass of all the isotopes considered by the stellar yields.


This function calculates and returns the duration of every timestep.


        This function declares and returns all the arrays containing information
        about the evolution of the stellar ejecta, the gas reservoir, the star
        formation rate, and the number of core-collapse SNe, SNe Ia, neutron star
        mergers, and white dwarfs.

        Argument
        ========

          ymgal : Initial gas reservoir. This function extends it to all timesteps
          nb_iso_gsa : Number of isotopes (can different if stable or radio isotopes)


        Create an array to make the connection between radioactive isotopes
        and the stable isotopes they are decaying into.  For example, if Al-26
        decays into Mg-26, the array will contain the Mg-26 index in the stable
        ymgal array.


Create a timesteps array from the dt_split_info array.


        This function calculates the coefficients for the fraction of white
        dwarfs fit in the form of f_wd = a*lg(t)**2 + b*lg(t) + c.  Only
        progenitor stars for SNe Ia are considered.


        This function executes a part of a single timestep with the simulation
        managed by either OMEGA or SYGMA.  It converts gas into stars, calculates
        the stellar ejecta of the new simple stellar population (if any), and adds
        its contribution to the total ejecta coming from all stellar populations.

        Argument
        ========

          i : Index of the current timestep
          f_esc_yields: Fraction of non-contributing stellar ejecta
          mass_sampled : Stars sampled in the IMF by an external program
          scale_cor : Envelope correction for the IMF


        Correct the mass of the different gas reservoirs "ymgal"
        for the mass lock into stars.

        Argument
        ========

          i : Index of the current timestep
          f_lock_remain: Mass fraction of gas remaining after star formation


        Add stellar ejecta to the gas components.

        Argument
        ========

          i : Index of the current timestep


        This function adds the state of current timestep into the history class.

        Argument
        ========

          i : Index of the current timestep

        Note
        ====

          This function is decoupled from evol_stars() because OMEGA modifies
          the quantities between evol_stars() and the update of the history class.


        This function adds the total stellar ejecta to the history class as well
        as converting isotopes into chemical elements.


          For each upcoming timestep, including the current one,
          calculate the yields ejected by the new stellar population
          that will be deposited in the gas at that timestep.  This
          function updates the "mdot" arrays, which will eventually
          be added to the "ymgal" arrays, corresponding to the gas
          component arrays.

        Argument
        ========

          i : Index of the timestep after the current timestep
          f_esc_yields: Fraction of non-contributing stellar ejecta
          mass_sampled : Stars sampled in the IMF by an external program
          scale_cor : Envelope correction for the IMF
          dm_imf : Mass interval resolution of the IMF.  Stars within a
                   specific mass interval will have the same yields


        Calculate the new IMF mass bin resolution.  This is based on
        the input resolution (dm_imf), but adapted to have an integer
        number of IMF bins that fits within the stellar mass interval
        defined by a given stellar lifetime interval.

        Arguments
        =========

          dm_imf : Mass interval resolution of the IMF.  Stars within a
                   specific mass interval will have the same yields.
          t_lower : Lower age limit of the stellar populations.
          i_cse : Index of the "future" timestep (see __calculate_stellar_ejecta).


        Add the IMF-weighted stellar yields in the ejecta "mdot" arrays.
        Keep track of the contribution of low-mass and massive stars.

        Argument
        ========

          nb_stars : Number of stars in the IMF that eject the yields
          the_yields : Yields of the IMF-central-mass-bin star
          the_m_cen : Central stellar mass of the IMF bin
          i_cse : Index of the "future" timestep (see __calculate_stellar_ejecta)
          i : Index of the timestep where the stars originally formed
          lower_mass: lower limit of the imf mass bin
          upper_mass: upper limit of the imf mass bin
              both the upper and lower limit must be provided to calculate the
              fractional number of SNe before the imf cut-off


        Add the contribution of enrichment sources other than
        massive stars (wind + SNe) and AGB stars to the ejecta
        "mdot" array.

        Argument
        ========

          i : Index of the timestep where the stars originally formed


        This function calculates the factor that must be multiplied to
        the input stellar yields, given the mass bin implied for the
        considered timestep and the stellar masses sampled by an external
        program.

        Argument
        ========

          minm1 : Minimum stellar mass having ejecta in this timestep j
          maxm1 : Minimum stellar mass having ejecta in this timestep j
          mass_sampled : Stellar mass sampled by an external program
          func_total_ejecta : Relation between M_tot_ej and stellar mass
          m_table : Mass of the star in the table providing the yields


        This function calculates the envelope correction that must be
        applied to the IMF.  This correction can be used the increase
        or reduce the number of stars in a particular mass bin, without
        creating a new IMF.  It returns the scalefactor_factor, that will
        be multiplied to scalefactor (e.g., 1.0 --> no correction)

        Argument
        ========

          minm1 : Minimum stellar mass having ejecta in this timestep j
          maxm1 : Minimum stellar mass having ejecta in this timestep j
          scale_cor : Envelope correction for the IMF


        This function decays radioactive isotopes present in the
        radioactive gas component and add the stable decayed product
        inside the stable gas component.  This is using a simple
        decay routine where an unstable isotope decay to only one
        stable isotope.

        Argument
        ========

          i : Index of the current timestep.
          Reminder, here 'i' is the upper-time boundary of the timestep


        This function import and initialize the decay module
        used to decay unstable isotopes.  Declare arrays used
        for the communication between the fortran decay code
        and NuPyCEE


        This function decays radioactive isotopes present in the
        radioactive gas component and add the stable decayed product
        inside the stable gas component.  This is using the decay
        module to account for all decay channels.

        Argument
        ========

          i : Index of the current timestep.
          Reminder, here 'i' is the upper-time boundary of the timestep


        Decay the current radioactive abundances using
        the decay module.

        Argument
        ========

          i : Index of the current timestep.
          dt_decay: Duration of the decay [yr]


        Calculate and return the initial abundance of radioactive
        isotopes in the format required by the fortran decay module.

        Argument
        ========

          i : Index of the current timestep.


        This function calculates the contribution of SNe Ia in the stellar ejecta,
        and adds it to the mdot array.

        Argument
        ========

          i : Index of the current timestep.


        This function calculates the contribution of neutron star mergers
        on the stellar ejecta and adds it to the mdot array.

        Arguments
        =========

            i : index of the current timestep


        This function returns the number of neutron star mergers occurring within a given time
        interval using the Dominik et al. (2012) delay-time distribution function.

        Arguments
        =========

            timemin : Lower boundary of time interval.
            timemax : Upper boundary of time interval.


        This function returns the number of NSMs that occur within
        a specific time interval for the input DTD array.

        Arguments
        =========

            timemin : Lower time intervall of the OMEGA timestep
            timemax : Upper time intervall of the OMEGA timestep
            i_Z_temp : Index of the considered Z in the DTD array


        This function returns the rate of neutron star mergers occurring at a given
        stellar lifetime. It uses the delay time distribution
        of Dominik et al. (2012).

        Arguments
        =========

            t : lifetime of stellar population in question
            Z : metallicity of stellar population in question


        This function normalizes the Dominik et al. (2012) delay time distribution
        to appropriately compute the total number of neutron star mergers in an SSP.

        Arguments
        =========

            lifetime_min : minimum stellar lifetime


This function normalize the DTD of all input delayed extra sources.


        This function calculates the contribution of delayed extra source
        and adds it to the mdot array.

        Arguments
        =========

            i : index of the current timestep


        This function returns the yields, metallicities, and Z boundary indexes
        for a considered delayed extra source (according to the ISM metallicity).

        Arguments
        =========

          i_extra : index of the extra source
          return_radio : whether to calculate radioactive yields


        This function returns the yields, metallicities, and Z boundary indexes
        for a considered delayed extra source (according to the ISM metallicity).

        Arguments
        =========

          timemin : Lower boundary of the time interval.
          timemax : Upper boundary of the time interval.
          i_extra : Index of the extra source.
          iZ_low  : Lower index of the provided input Z in the delayed extra yields table.
          iZ_up   : Upper index of the provided input Z in the delayed extra yields table.
          yextra_low : Delayed extra yields of the lower Z.
          yextra_up  : Delayed extra yields of the upper Z.
          Z_extra : List of provided Z in the delayed extra yields table.


        This function returns the integrated number of delayed extra source within
        a given OMEGA time interval for a given source and metallicity

        Arguments
        =========

          timemin : Lower boundary of the OMEGA time interval.
          timemax : Upper boundary of the OMEGA time interval.
          i_extra : Index of the extra source.
          iZZ     : Index of the provided input Z in the delayed extra yields table.


        This function returns the integrated number of delayed extra source within
        a given time interval for a given source and metallicity.

        Note: There is no normalization here, as this function is actualy used for
              the normalization process.

        Arguments
        =========

          t_min_temp : Lower boundary of the delayed extra input time interval.
          t_max_temp : Upper boundary of the delayed extra time interval.
          i_extra  : Index of the extra source.
          iZZ      : Index of the provided input Z in the delayed extra yields table.
          i_search : Index of the lower input timestep interval