Example #1
0
def f2n(f):
    """Converts a frequency in Hertz to the corresponding O-mode density in m^-3
    
    Parameters
    -----------
    f : The input frequency in Hertz
    
    Returns
    -----------
    The corresponding density in m^-3
    
    """
    k = 4.0 * np.pi**2 * codata.value('electron mass') * codata.value('electric constant') / codata.value('elementary charge')**2
    return k * f**2
Example #2
0
def n2f(n):
    """Converts a density in m^-3 to the corresponding O-mode frequency in Hz
    
    Parameters
    -----------
    n : The input density in m^-3
    
    Returns
    -----------
    The corresponding frequency in Hertz
    
    """
    k = 4.0 * np.pi**2 * codata.value('electron mass') * codata.value('electric constant') / codata.value('elementary charge')**2
    return np.sqrt(n/k)
Example #3
0
def calculate_surface_energy(stoich,
                             data,
                             SE,
                             adsorbant,
                             thermochem,
                             T,
                             P,
                             coverage=None):
    """Calculate the surface energy at a specific temperature
    and pressure.

    Parameters
    ----------
    stoich : dictionary
        information about the stoichiometric surface
    data : list
        list of dictionaries containing information on the "adsorbed" surfaces
    SE : float
        surface energy of the stoichiomteric surface
    adsorbant : float
        dft energy of adsorbing species
    coverage : array like
        Numpy array containing the different coverages of adsorbant.
    thermochem : array like
        Numpy array containing thermochemcial data downloaded from NIST_JANAF
        for the adsorbing species.
    T : float
        Temperature to calculate surface energy
    P : float
        Pressure to calculate the surface energy
    coverage : array like (default None)
        Coverage of adsorbed specied on the surface.

    Returns
    -------
    SEs : array like
        surface energies for each surface at T/P
    """
    if coverage is None:
        coverage = ut.calculate_coverage(data)
    R = codata.value('molar gas constant')
    N_A = codata.value('Avogadro constant')
    lnP = np.log(10**P)
    adsorbant = temperature_correction(T, thermochem, adsorbant)
    AE = pt.adsorption_energy(data, stoich, adsorbant)
    SEs = np.array([SE])
    for i in range(0, len(data)):
        S = SE + (coverage[i] / N_A) * (AE[i] - (lnP * (T * R)))
        SEs = np.append(SEs, S)
    return SEs
Example #4
0
def calculate_surface_energy(AE, lnP, T, coverage, SE, nsurfaces):
    r"""Calculates the surface energy as a function of pressure and
    temperature for each surface system according to

    .. math::
        \gamma_{adsorbed, T, p} = \gamma_{bare} + (C(E_{ads, T} -
        RTln(\frac{p}{p^o})

    where :math:`\gamma_{adsorbed, T, p}` is the surface energy of the surface
    with adsorbed species at a given temperature and pressure,
    :math:`\gamma_{bare}` is the suface energy of the bare surface,
    C is the coverage of adsorbed species, :math:`E_{ads, T}` is the
    adsorption energy, R is the gas constant, T is the temperature, and
    :math:`\frac{p}{p^o}` is the partial pressure.

    Parameters
    ----------
    AE : list
        list of adsorption energies
    lnP : array like
        full pressure range
    T : array like
        full temperature range
    coverage : array like
        surface coverage of adsorbing species in each calculation
    SE : float
        surface energy of stoichiomteric surface
    data : list
        list of dictionaries containing info on each surface
    nsurfaces : int
        total number of surface

    Returns
    -------
    SE_array : array like
        array of integers corresponding to lowest surface energies
    """
    R = codata.value('molar gas constant')
    N_A = codata.value('Avogadro constant')
    SEABS = np.array([])
    xnew = ut.build_xgrid(T, lnP)
    ynew = ut.build_ygrid(T, lnP)
    for i in range(0, (nsurfaces - 1)):
        SE_Abs_1 = (SE + (coverage[i] / N_A) * (AE[i] - (ynew * (xnew * R))))
        SEABS = np.append(SEABS, SE_Abs_1)
    surface_energy_array = np.zeros(lnP.size * T.size)
    surface_energy_array = surface_energy_array + SE
    SEABS = np.insert(SEABS, 0, surface_energy_array)
    phase_data, SE = ut.get_phase_data(SEABS, nsurfaces)
    return phase_data, SE
Example #5
0
def pressure(chemical_potential, t):
    r"""Converts chemical potential at a specific
    temperature (T) to a pressure value.

    .. math::
        P = \frac{\mu}{k * T}

    where P is the pressure, :math:`\mu` is the chemcial potential, k is the
    Boltzmann constant and T is the temperature.

    Parameters
    ----------
    chemical_potential : array like
        delta mu values
    t : int
        temperature

    Returns
    -------
    pressure : array like
        pressure values as a function of chemcial potential
    """
    k = codata.value('Boltzmann constant in eV/K')
    pressure = chemical_potential / (k * t * 2.203)
    return pressure
Example #6
0
def b2f(b):
    """Converts a magnetic field in Tesla to the corresponding cyclotronic frequency in Hz
    
    Parameters
    -----------
    b : float
        The input magnetic field in Tesla
    
    Returns
    -----------
    f : float
        The corresponding cyclotronic frequency in Hertz
    """
    k = codata.value('elementary charge') / (2.0 * np.pi *
                                             codata.value('electron mass'))
    f = k * b
    return f
Example #7
0
def f2b(f):
    """Converts a cyclotronic frequency in Hz into its corresponding Magnetic field
    
    Parameters
    -----------
    f : float
        The input frequency in Hz
    
    Returns
    -----------
    b : float
        The corresponding magnetic field in Tesla
    """
    k = 2.0 * np.pi * codata.value('electron mass') / codata.value(
        'elementary charge')
    b = k * f
    return b
Example #8
0
def raycrs(lam, co2):
    """
    Rayleigh cross section
        lam : um
        co2 : ppm
    """
    Avogadro = codata.value('Avogadro constant')
    Ns = Avogadro / 22.4141 * 273.15 / 288.15 * 1e-3
    nn2 = n_air(lam, co2)**2
    return (24 * np.pi**3 * (nn2 - 1)**2 / (lam * 1e-4)**4 / Ns**2 /
            (nn2 + 2)**2 * Fair(lam, co2))
def cross_section(I_A, I_B, m_B, T_B):
    #a_0=codata.value('Bohr radius')#m
    a_0 = 5.291E-9  #cm
    hbar = 6.582E-16  #eV s
    m_p = sp.constants.proton_mass
    m_n = sp.constants.neutron_mass
    m_e = sp.constants.electron_mass
    pi = sp.constants.pi
    e = sp.constants.elementary_charge
    k = sp.constants.Boltzmann
    amu = codata.value('atomic mass constant')  #kg

    Ibar = (I_A + I_B) / 2  #eV
    if Ibar < 0: return 0.0  #it would be unbound/continuum
    DeltaE = abs(I_A - I_B)  #eV
    omega = DeltaE / hbar  #/s
    gamma = np.sqrt(Ibar / 13.6)
    f = 1

    v = np.sqrt((2 * T_B * 1.6E-19) / (m_B * amu)) * 10**2

    a_0 = format(a_0, '.12f')
    hbar = format(hbar, '.19f')
    omega = format(omega, '.2f')
    gamma = format(gamma, '.19f')
    Ibar = format(Ibar, '.19f')
    v = format(v, '.19f')

    s1 = ("(Sin[Sqrt[(2*Pi)/(" + str(gamma) + "*" + str(a_0) + ")]*(2*"
          "" + str(Ibar) + ")/(" + str(hbar) + "*" + str(v) + ")"
          "*b^(3/2)*(1 + " + str(a_0) + "/(" + str(gamma) + "*b))*"
          "Exp[(-" + str(gamma) + "*b)/" + str(a_0) + "]]^2)*"
          "(Sech[(" + str(omega) + "/" + str(v) + ")*Sqrt[(" + str(a_0) +
          "*Pi*b)/(2*" + str(gamma) + ")]]^2)*2*Pi*b")

    #if calculation of extremely small cross-sections is needed then MinRecursion can be increased and timeout set to 0
    s2 = "Sqrt[" + str(
        f
    ) + "*NIntegrate[" + s1 + ", {b, 0, Infinity}, MaxRecursion -> 200, MinRecursion -> 10]]"

    print(gamma, Ibar, omega, v)

    result = runMath(s2)**2

    if result != None:
        return result
    else:
        return 0.0
Example #10
0
def u2m(m):
    """
    Converts a mass given in (unified) atomic mass units (u) to a mass given in
    (electron Volt)/(speed of light)^2 (eV/c^2)
    through the simple relation 1u = 931.494061(21) MeV/c^2 (Source: wikipedia)
    
    :type m: float
    :param m: Mass of particle in atomic mass units.

    :rtype: float
    :returns: Mass of particle in MeV/c^2.
    """
    #nc = codata.value('speed of light in vacuum')**2 * 1e-16
    #return np.float(m) * codata.value('atomic mass constant energy equivalent in MeV') / (nc * 1e4)
    return np.float(m) * codata.value(
        'atomic mass constant energy equivalent in MeV')
Example #11
0
def rod(lam, co2=400., lat=45., z=0., P=1013.25):
    """
    Rayleigh optical depth calculation for Bodhaine, 99
        lam : um
        co2 : ppm
        lat : deg (scalar)
        z : m
        P : hPa

    Example: rod(0.4, 400., 45., 0., 1013.25)
    """
    Avogadro = codata.value('Avogadro constant')
    zs = 0.73737 * z + 5517.56  # effective mass-weighted altitude
    G = g(lat, zs)
    # air pressure at the pixel (i.e. at altitude) in hPa
    Psurf = (
        P * (1. - 0.0065 * z / 288.15)**5.255
    ) * 1000.  # air pressure at pixel location in dyn / cm2, which is hPa * 1000
    return raycrs(lam, co2) * Psurf * Avogadro / ma(co2) / G
Example #12
0
    def __init__(self, beam_type=None):
        """
        Initialize Beam-Object and set type
        
        :param beam_type:   Beam type to be used with this instance of the object
        """

        if beam_type == None:
            self.beam_type = par.BEAM_TYPE
        else:
            self.beam_type = beam_type

        self.e = codata.value('elementary charge')

        if self.beam_type == 'constant':
            self.J_e = par.BEAM_CURRENT_DENSITY / self.e
        else:
            self.I_e = par.BEAM_CURRENT / self.e
            self.Wz = par.SCAN_WIDTH
            self.xc = par.BEAM_CENTER
            self.fwhm = par.FWHM
            if self.beam_type == 'error function': self.Wx = par.ERF_BEAM_WIDTH
Example #13
0
def compare_results(file_list, parameter_change_list, bary_starname,
                    orbital_parameters, objects, servaldir):
    """
    Compares result files to find the best rv scatter around literature fit returns change in parameter that yielded best results
    
    file_list: list of `str`
        list containing the file paths of the files to be compared
    parameter_change_list: list of `int`
        list containing the parameter exponent shifts used to create the files in file_list
    orbital_parameters : list of `float`
        orbital_parameters = [K, P, e, omega, T0]
        parameters of the keplerian fit to be used as "true" baseline
    """
    sigma_list = np.zeros(len(file_list)) + 100  # 100 is a fudge factor
    plots = True
    if plots:
        rec_loop_directory, key_name = os.path.split(
            os.path.split(file_list[0])
            [0])  # HACK go  up 2 directories to loop directory
        plot_directory = rec_loop_directory + "/compare_plots"
        os.makedirs(plot_directory, exist_ok=True)

        pp = PdfPages(plot_directory + "/" + key_name + ".pdf")
        fig = plt.figure(figsize=(15, 9), dpi=200)
        mpl.rc('font', size=16)
        plt.clf()
        fig.clf()
        ax1 = plt.gca()

    for f, fil in enumerate(file_list):
        #assumes order of file_listand parameter_change_list are matched. (maybe extract from file name?)
        wobble_res = h5py.File(fil, 'r')
        w_dates = wobble_res['dates'][()]
        w_dates_utc = wobble_res['dates_utc'][()]

        w_RVs = wobble_res['star_time_rvs'][()]
        w_RVs_original = w_RVs
        w_RVs_er = wobble_res['star_time_sigmas'][()]

        #barycorr for wobble_orig
        from scipy.constants import codata
        lightvel = codata.value('speed of light in vacuum')  #for barycorr
        # CAHA Coordinates for barycorr
        _lat = 37.2236
        _lon = -2.54625
        _elevation = 2168.

        w_RVs_original_barycorr = np.zeros(len(w_dates))
        for n in tqdm(range(len(w_RVs_original_barycorr))):
            w_RVs_original_barycorr[n] = bary.get_BC_vel(
                w_dates_utc[n],
                starname=bary_starname,
                lat=_lat,
                longi=_lon,
                alt=_elevation,
                zmeas=w_RVs_original[n] / lightvel)[0]

        #Serval Correction
        #read in SERVAL
        ser_rvc = np.loadtxt(servaldir + objects[1] + "/" + objects[1] +
                             ".rvc.dat")
        # remove entries with nan in drift
        ind_finitedrift = np.isfinite(ser_rvc[:, 3])
        ser_rvc = ser_rvc[ind_finitedrift]
        ser_corr = -ser_rvc[:, 8] - ser_rvc[:, 3]
        #match wobble and serval
        indices_serval = []
        indices_wobble = []
        for n in range(len(w_dates)):
            ind_jd = np.where(
                np.abs(ser_rvc[:, 0] - w_dates[n]) == np.nanmin(
                    np.abs(ser_rvc[:, 0] - w_dates[n])))[0][0]
            if (ser_rvc[ind_jd, 0] - w_dates[n]
                ) * 24 * 60 < 20.:  #only takes matches closer than 20 minutes
                indices_serval.append(ind_jd)
                indices_wobble.append(n)
        print("#serval_ind:" + str(len(indices_serval)),
              "#wobble_ind:" + str(len(indices_wobble)))
        #now set up all the data according to the indices
        ser_rvc = ser_rvc[indices_serval]
        ser_corr = ser_corr[indices_serval]

        w_dates = w_dates[indices_wobble]
        w_dates_utc = w_dates_utc[indices_wobble]
        w_RVs_original_barycorr = w_RVs_original_barycorr[
            indices_wobble] + ser_corr
        w_RVs_er = w_RVs_er[indices_wobble]

        def fit_func(t, T0_offset):
            return rv.radial_velocity(t, orbital_parameters[0],
                                      orbital_parameters[1],
                                      orbital_parameters[2],
                                      orbital_parameters[3],
                                      orbital_parameters[4] + T0_offset)

        #fit to Wobble
        xdata = w_dates
        ydata = w_RVs_original_barycorr - np.nanmean(w_RVs_original_barycorr)
        popt, pcov = sp.optimize.curve_fit(fit_func,
                                           xdata,
                                           ydata,
                                           sigma=w_RVs_er,
                                           absolute_sigma=True)
        print("T0_offset Wobble = ", popt)
        T0_offset = popt[0]

        #make these weighted (maybe: thsi may not be a good idea if residuals are not strongly correlated to error (as with wobble results))
        sigma_wob = np.nanstd(
            sigma_clip(w_RVs_original_barycorr -
                       np.nanmean(w_RVs_original_barycorr) -
                       fit_func(w_dates, T0_offset),
                       sigma=5))
        sigma_list[f] = sigma_wob

        sigma_wob_noclip = np.nanstd(w_RVs_original_barycorr -
                                     np.nanmean(w_RVs_original_barycorr) -
                                     fit_func(w_dates, T0_offset))
        if plots:
            #fit to serval:
            xdata = ser_rvc[:, 0]
            ydata = ser_rvc[:, 1] - np.nanmean(ser_rvc[:, 1])
            popt_s, pcov_s = sp.optimize.curve_fit(fit_func,
                                                   xdata,
                                                   ydata,
                                                   sigma=ser_rvc[:, 2],
                                                   absolute_sigma=True)
            print("T0_offset Serval = ", popt_s)
            T0_offset_s = popt_s[0]

            sigma_ser = np.nanstd(
                sigma_clip(ser_rvc[:, 1] - np.nanmean(ser_rvc[:, 1]) -
                           fit_func(ser_rvc[:, 0], T0_offset_s),
                           sigma=5))

            sigma_ser_noclip = np.nanstd(ser_rvc[:, 1] -
                                         np.nanmean(ser_rvc[:, 1]) -
                                         fit_func(ser_rvc[:, 0], T0_offset_s))

            xlst = np.linspace(w_dates[0],
                               w_dates[0] + orbital_parameters[1] * 0.99999,
                               num=100)
            ylst = [
                rv.radial_velocity(t, orbital_parameters[0],
                                   orbital_parameters[1],
                                   orbital_parameters[2],
                                   orbital_parameters[3],
                                   orbital_parameters[4] + T0_offset)
                for t in xlst
            ]
            #sort by xlst
            pltlst = [[xlst[j], ylst[j]] for j in range(len(xlst))]

            def mod_sort(elem):
                return elem[0] % orbital_parameters[1]

            pltlst = sorted(pltlst, key=mod_sort)
            pltlst = np.asarray(pltlst)
            pltlst = [pltlst[:, 0], pltlst[:, 1]]

            ax1.plot(pltlst[0] % orbital_parameters[1],
                     pltlst[1],
                     "r-",
                     label="literature orbit (Wobble T0_offset)")
            ax1.errorbar(
                (w_dates) % orbital_parameters[1],
                (w_RVs_original_barycorr -
                 np.nanmean(w_RVs_original_barycorr)),
                yerr=w_RVs_er,
                fmt="x",
                label="Wobble_Corr, clipped_sigma = {0:.3f}, noclip = {1:.3f} "
                .format(sigma_wob, sigma_wob_noclip))
            ax1.errorbar(
                (ser_rvc[:, 0]) % orbital_parameters[1],
                ser_rvc[:, 1] - np.nanmean(ser_rvc[:, 1]),
                yerr=ser_rvc[:, 2],
                fmt="x",
                label="SERVAL_Corr, clipped_sigma = {0:.3f}, noclip = {1:.3f}".
                format(sigma_ser, sigma_ser_noclip),
                color="C2")
            ax1.set_ylabel("RVs [m/s]")
            ax1.set_xlabel('jd')
            # add the parameter change to the title
            title_pre = os.path.split(os.path.split(fil)[0])[1]
            plt.title(title_pre + ", Phased (" + str(orbital_parameters[1]) +
                      "d) RVs for " + objects[0] + " (" + objects[2] + ") " +
                      " - " + objects[1] + ";")
            plt.grid(True)
            plt.tight_layout()
            plt.legend(shadow=True)
            plt.savefig(pp, format='pdf')
            plt.clf()
            fig.clf()
            ax1 = plt.gca()

    if plots:  # include some nice progress plots. TODO make it not crudely placed inside this function?
        plt.close(fig)
        pp.close()

    best_index = np.argmin(sigma_list)
    return parameter_change_list[best_index]
import numpy as np
import pandas as pd
from scipy.constants import codata
from RF_mathematica import *

hc=codata.value('inverse meter-electron volt relationship')*1E+2 #eV.cm

def iter_calc(l2, react_S_B, react_L_B, I_B, term, J, L, S, level, skipped_level, second_ce, df_double_ce, ele_B, ele_A, prod_S_A, react_S_A, react_L_A, charge_state, T_B, dist):

	ele_sym_B=ele_B.symbol
	ele_sym_A=ele_A.symbol
	I_A=ele_A.ionenergies[1]
	m_B=ele_B.mass

	try:
		if second_ce:
			raise ValueError("second_ce true")

		levels_pops_detunes_f = open('results/Z'+str(ele_B.atomic_number)+'/levels_pops_detunes'+ele_sym_B+"I"*charge_state+"_"+ele_sym_A+"_"+str(T_B)+"_"+str(dist),'rb')
		levels_pops_detunes=np.array(list(np.loadtxt(levels_pops_detunes_f, delimiter=';',dtype=float)))

		levels_cs_f = open('results/Z'+str(ele_B.atomic_number)+'/levels_cs'+ele_sym_B+"I"*charge_state+"_"+ele_sym_A+"_"+str(T_B)+"_"+str(dist),'rb')
		levels_cs=np.array(list(np.loadtxt(levels_cs_f, delimiter=';',dtype=float)))

		levels_pops_detunes_initial=levels_pops_detunes

		return 0.0, levels_pops_detunes, levels_cs, df_double_ce

	except Exception as exception:
		print(exception)
		#all of  below
Example #15
0
#INTERFACE WITH ADMX DB
db = admx_db_interface.ADMXDB()
db.hostname = "admxdb01.fnal.gov"

receiver_shape_file = get_intermediate_data_file_name(
    run_definition["nibbles"][target_nibble], "receiver_shape.h5")
start_time = run_definition["nibbles"][target_nibble]["start_time"]
stop_time = run_definition["nibbles"][target_nibble]["stop_time"]
timestamp_cut_yaml = run_definition["timestamp_cuts"]
#Correct this to pick the correct receiver shape file
f = h5py.File(receiver_shape_file, "r")
receiver_shape = load_dataseries_from_hdf5(f, "receiver_shape")
f.close()

#Boltzmann's Constant
kboltz = codata.value('Boltzmann constant')


def calculate_chi2(y, yfit, uncertainties):
    residuals = np.subtract(y, yfit)
    norm_residuals = np.divide(residuals, uncertainties)
    chi2 = np.multiply(norm_residuals, norm_residuals)
    total_chi2 = np.sum(chi2)
    return total_chi2


#Actual DB Query
max_lines = 100000
#max_lines=50
query = "SELECT A.timestamp, B.start_frequency_channel_one,B.stop_frequency_channel_one,B.frequency_resolution_channel_one,B.power_spectrum_channel_one,B.sampling_rate,B.integration_time,A.q_channel_one,A.mode_frequency_channel_one,A.digitizer_log_reference,A.notes from axion_scan_log as A INNER JOIN digitizer_log as B ON A.digitizer_log_reference=B.digitizer_log_id WHERE A.timestamp < '" + str(
    stop_time) + "' AND A.timestamp>'" + str(
from utils import Utils

import numpy as np

from scipy.signal import argrelextrema    
from scipy.constants import codata

# constants
c = codata.value("speed of light in vacuum") * 10e9 # in nm per s

LASER_WAVELENGTH = 532 # nm

class Calibrator():
    def __init__(self, laser_x, laser_y, scaling, plot_cb = None):
        self.laser_x = laser_x
        self.laser_y = laser_y
        self.scaling = scaling
        self.plot_cb = plot_cb

    def get_calibration(self, x):
        delta, dt_max = self.calculate_calibration()
        return delta, dt_max

    def calculate_calibration(self):
        measured_pos = argrelextrema(np.array(self.laser_y), np.greater)[0]
        measured_pos_idx = np.arange(measured_pos.size)

        # argrelexrema only returns the indecies within the 
        # dataset that contain the maximums. Here we extract them.
        measured_pos_x = []
        measured_pos_y = []
Example #17
0
from scipy.constants import codata

filedir = os.path.dirname(__file__)
codedir = os.path.join(filedir, '..', '..', 'code')
sys.path.insert(0, codedir)

import beam


if __name__ == '__main__':
    
    f_beam_y = list()
    
    #initialize required Parameters (f_beam should have the same max. value for
    #                                 all of the three beam types)
    e = codata.value('elementary charge')
    J = 0.001
    I_gauss = 1.06*1e-12
    I_erf = 10*1e-12
    Wz = 1000
    Wx = 1000
    xc = 0
    fwhm = 100
    x_array = np.linspace(-600, 600, 1201)
    
    #calculate f_beam in the given x range
    f_beam_y.append(np.full(len(x_array), J/e))
    f_beam_y.append(beam.gauss_beam(I_gauss/e , Wz, xc, fwhm, x_array))
    f_beam_y.append(beam.erf_beam(I_erf/e, Wz, Wx, xc, fwhm, x_array))
    
    #plot the different beam types
def compare_results(file_list, parameter_change_list, bary_starname,
                    orbital_parameters, objects, servaldir, serval_T0_offset):
    """
    Compares result files to find the best rv scatter around literature fit returns change in parameter that yielded best results
    
    file_list: list of `str`
        list containing the file paths of the files to be compared
    parameter_change_list: list of `int`
        list containing the parameter exponent shifts used to create the files in file_list
    orbital_parameters_mult : list of `float`
        orbital_parameters = [K, P, e, omega, T0]
        parameters of the keplerian fit to be used as "true" baseline
    """
    #orbital_parameters = orbital_parameters_mult[0] #HACK to select only the first planet for backward compatibility WONT WORK

    sigma_list = np.zeros(len(file_list)) + 100  # 100 is a fudge factor
    plots = True
    if plots:
        rec_loop_directory, key_name = os.path.split(
            os.path.split(file_list[0])
            [0])  # HACK go  up 2 directories to loop directory
        plot_directory = rec_loop_directory + "/compare_plots"
        os.makedirs(plot_directory, exist_ok=True)

        pp = PdfPages(plot_directory + "/" + key_name + ".pdf")
        fig = plt.figure(figsize=(15, 9), dpi=200)
        mpl.rc('font', size=16)
        plt.clf()
        fig.clf()
        ax1 = plt.gca()

    for f, fil in enumerate(file_list):
        #assumes order of file_listand parameter_change_list are matched. (maybe extract from file name?)
        wobble_res = h5py.File(fil, 'r')
        w_dates = wobble_res['dates'][()]
        w_dates_utc = wobble_res['dates_utc'][()]

        w_RVs = wobble_res['star_time_rvs'][()]
        w_RVs_original = w_RVs
        w_RVs_er = wobble_res['star_time_sigmas'][()]

        #barycorr for wobble_orig
        from scipy.constants import codata
        lightvel = codata.value('speed of light in vacuum')  #for barycorr
        # CAHA Coordinates for barycorr
        _lat = 37.2236
        _lon = -2.54625
        _elevation = 2168.

        w_RVs_original_barycorr = np.zeros(len(w_dates))
        for n in tqdm(range(len(w_RVs_original_barycorr))):
            w_RVs_original_barycorr[n] = bary.get_BC_vel(
                w_dates_utc[n],
                starname=bary_starname,
                lat=_lat,
                longi=_lon,
                alt=_elevation,
                zmeas=w_RVs_original[n] / lightvel)[0]

        #Serval Correction
        #read in SERVAL
        #ser_rvc = np.loadtxt(servaldir+objects[1]+"/"+objects[1]+".rvc.dat")
        #Use avcn  instead
        ser_avcn = np.loadtxt(servaldir + objects[1] + "/" + objects[1] +
                              ".avcn.dat")
        ser_rvc = ser_avcn  #HACK to make code below continue to function just wrote avcn data over rvc
        # remove entries with nan in drift
        ind_finitedrift = np.isfinite(ser_rvc[:, 3])
        ser_rvc = ser_rvc[ind_finitedrift]
        #8 sa drift, 3 drift, 9 NZP
        ser_corr = -ser_rvc[:, 8] - ser_rvc[:, 3] - ser_rvc[:,
                                                            9]  # use with avcn
        #optionally remove drift correction if this has been performed during data file generation
        correct_w_for_drift = False
        if correct_w_for_drift == False:
            ser_corr_wob = ser_corr + ser_rvc[:, 3]
        #match wobble and serval
        indices_serval = []
        indices_wobble = []
        for n in range(len(w_dates)):
            ind_jd = np.where(
                np.abs(ser_rvc[:, 0] - w_dates[n]) == np.nanmin(
                    np.abs(ser_rvc[:, 0] - w_dates[n])))[0][0]
            if (ser_rvc[ind_jd, 0] - w_dates[n]
                ) * 24 * 60 < 20.:  #only takes matches closer than 20 minutes
                indices_serval.append(ind_jd)
                indices_wobble.append(n)
        print("#serval_ind:" + str(len(indices_serval)),
              "#wobble_ind:" + str(len(indices_wobble)))
        #now set up all the data according to the indices
        ser_rvc = ser_rvc[indices_serval]
        ser_corr = ser_corr[indices_serval]
        ser_corr_wob = ser_corr_wob[indices_serval]

        w_dates = w_dates[indices_wobble]
        w_dates_utc = w_dates_utc[indices_wobble]
        w_RVs_original_barycorr = w_RVs_original_barycorr[
            indices_wobble] + ser_corr_wob
        w_RVs_er = w_RVs_er[indices_wobble]

        #def fit_func(t, T0_offset):
        #return rv.radial_velocity(t , orbital_parameters[0], orbital_parameters[1], orbital_parameters[2],orbital_parameters[3], orbital_parameters[4] + T0_offset)
        #NOTE imported from compare_ws 25.oct.2019
        #def keplarian_rv_mult(t):
        #total_rv = 0
        #for parameters in orbital_parameters_mult:
        #total_rv = total_rv + rv.radial_velocity_M0(t , parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5])
        #return total_rv

        #def fit_func_mult(t, T0_offset):
        #return keplarian_rv_mult(t + T0_offset)

        # For single planet work e.g. phase sychronized data

        def keplarian_rv(t):
            parameters = orbital_parameters_mult[0]
            return rv.radial_velocity_M0(t, parameters[0], parameters[1],
                                         parameters[2], parameters[3],
                                         parameters[4], parameters[5])

        def fit_func(t, T0_offset):
            return keplarian_rv(t + T0_offset)

        ##untested attemt to make compatible with multiplanet systems: WONT WORK
        #if len(orbital_parameters_mult) >1:
        #fit_func_mult = fit_func

        #fit to Wobble
        # EDIT 30.07.2019 catch optimize warning as error and use serval fited T0_offset instead
        with warnings.catch_warnings():
            warnings.simplefilter("error", OptimizeWarning)
            try:
                #fit to Wobble
                xdata = w_dates
                ydata = w_RVs_original_barycorr - np.nanmean(
                    w_RVs_original_barycorr)
                popt, pcov = sp.optimize.curve_fit(fit_func,
                                                   xdata,
                                                   ydata,
                                                   sigma=w_RVs_er,
                                                   absolute_sigma=True,
                                                   p0=serval_T0_offset)
                print("T0_offset Wobble = ", popt)
                T0_offset = popt[0]
                T0_source = "Wobble"
            except OptimizeWarning:
                ## fit T0_offset to serval instead if error in fitting
                ## Note: breaks if this throws an exception again -> do once globally and import result
                ##fit to Serval
                #xdata = ser_rvc[:,0]
                #ydata = ser_rvc[:,1] - np.nanmean(ser_rvc[:,1])
                #popt, pcov = sp.optimize.curve_fit(fit_func, xdata, ydata,  sigma = ser_rvc[:,2], absolute_sigma = True)
                #print("T0_offset Serval (wobble_fit_err) = ", popt)
                T0_offset = serval_T0_offset
                T0_source = "SERVAL (wob_fit_err)"
                print("T0_offset Serval (wobble_fit_err) = ", T0_offset)

        #make these weighted (maybe: thsi may not be a good idea if residuals are not strongly correlated to error (as with wobble results))
        sigma_wob = np.nanstd(
            sigma_clip(w_RVs_original_barycorr -
                       np.nanmean(w_RVs_original_barycorr) -
                       fit_func(w_dates, T0_offset),
                       sigma=5))
        sigma_list[f] = sigma_wob

        sigma_wob_noclip = np.nanstd(w_RVs_original_barycorr -
                                     np.nanmean(w_RVs_original_barycorr) -
                                     fit_func(w_dates, T0_offset))
        if plots:
            #fit to serval:
            xdata = ser_rvc[:, 0]
            ydata = ser_rvc[:, 1] - np.nanmean(ser_rvc[:, 1])
            popt_s, pcov_s = sp.optimize.curve_fit(fit_func,
                                                   xdata,
                                                   ydata,
                                                   sigma=ser_rvc[:, 2],
                                                   absolute_sigma=True,
                                                   p0=serval_T0_offset)
            print("T0_offset Serval = ", popt_s)
            T0_offset_s = popt_s[0]

            sigma_ser = np.nanstd(
                sigma_clip(ser_rvc[:, 1] - np.nanmean(ser_rvc[:, 1]) -
                           fit_func(ser_rvc[:, 0], T0_offset_s),
                           sigma=5))

            sigma_ser_noclip = np.nanstd(ser_rvc[:, 1] -
                                         np.nanmean(ser_rvc[:, 1]) -
                                         fit_func(ser_rvc[:, 0], T0_offset_s))

            sigma_wob_Soffset = np.nanstd(
                sigma_clip(w_RVs_original_barycorr -
                           np.nanmean(w_RVs_original_barycorr) -
                           fit_func(w_dates, T0_offset_s),
                           sigma=5))
            sigma_list[f] = sigma_wob

            sigma_wob_noclip_Soffset = np.nanstd(
                w_RVs_original_barycorr - np.nanmean(w_RVs_original_barycorr) -
                fit_func(w_dates, T0_offset_s))

            xlst = np.linspace(w_dates[0],
                               w_dates[0] + orbital_parameters[1] * 0.99999,
                               num=100)
            ylst = [fit_func(t, T0_offset) for t in xlst]
            #sort by xlst
            pltlst = [[xlst[j], ylst[j]] for j in range(len(xlst))]

            def mod_sort(elem):
                return elem[0] % orbital_parameters[1]

            pltlst = sorted(pltlst, key=mod_sort)
            pltlst = np.asarray(pltlst)
            pltlst = [pltlst[:, 0], pltlst[:, 1]]

            ax1.plot(pltlst[0] % orbital_parameters[1],
                     pltlst[1],
                     "r-",
                     label="literature orbit (" + T0_source + "T0_offset)")
            ax1.errorbar(
                (w_dates) % orbital_parameters[1],
                (w_RVs_original_barycorr -
                 np.nanmean(w_RVs_original_barycorr)),
                yerr=w_RVs_er,
                fmt="x",
                label="Wobble_Corr, clipped_sigma = {0:.3f}, noclip = {1:.3f} "
                .format(sigma_wob, sigma_wob_noclip))
            ax1.errorbar(
                (ser_rvc[:, 0]) % orbital_parameters[1],
                ser_rvc[:, 1] - np.nanmean(ser_rvc[:, 1]),
                yerr=ser_rvc[:, 2],
                fmt="x",
                label="SERVAL_Corr, clipped_sigma = {0:.3f}, noclip = {1:.3f}".
                format(sigma_ser, sigma_ser_noclip),
                color="C2")
            ax1.plot(
                [], [],
                ' ',
                label=
                "Wobble_Corr_SERVAL_fit, clipped_sigma = {0:.3f}, noclip = {1:.3f} "
                .format(sigma_wob_Soffset, sigma_wob_noclip_Soffset))
            ax1.set_ylabel("RVs [m/s]")
            ax1.set_xlabel('jd')
            # add the parameter change to the title
            title_pre = os.path.split(os.path.split(fil)[0])[1]
            plt.title(title_pre + ", Phased (" + str(orbital_parameters[1]) +
                      "d) RVs for " + objects[0] + " (" + objects[2] + ") " +
                      " - " + objects[1] + ";")
            plt.grid(True)
            plt.tight_layout()
            plt.legend(shadow=True)
            plt.savefig(pp, format='pdf')
            plt.clf()
            fig.clf()
            ax1 = plt.gca()

    if plots:  # include some nice progress plots. TODO make it not crudely placed inside this function?
        plt.close(fig)
        pp.close()

    best_index = np.argmin(sigma_list)
    return parameter_change_list[best_index]
def test_basic_table_parse():
    c = 'speed of light in vacuum'
    assert_equal(codata.value(c), constants.c)
    assert_equal(codata.value(c), constants.speed_of_light)
Example #20
0
def test_basic_table_parse():
    c = 'speed of light in vacuum'
    assert_equal(codata.value(c), constants.c)
    assert_equal(codata.value(c), constants.speed_of_light)
Example #21
0
def test_2002_vs_2006():
    assert_almost_equal(codata.value('magn. flux quantum'),
                        codata.value('mag. flux quantum'))
Example #22
0
    if Type == 'RKS':
        Species, ContributionMatrix, Eigenvalues, Occupations = ReadMOComposition(Content, LenContent, Type,
                                                                                  BasisDimension)
        EigenvaluesB = None
        OccupationsB = None
        ContributionMatrixB = None

    elif Type == 'UKS':
        Species, ContributionMatrix, Eigenvalues, Occupations, \
        ContributionMatrixB, EigenvaluesB, OccupationsB = ReadMOComposition(
            Content, LenContent, Type, BasisDimension)

    try:
        from scipy.constants import codata
        HaToeV = codata.value('Hartree energy in eV')
    except ImportError:
        HaToeV = 27.21138602

    Eigenvalues *= HaToeV
    if Type == 'UKS':
        EigenvaluesB *= HaToeV

    fig, ax = plt.subplots()

    PlotParameters = PlotTotalDOS(args, fig, ax, Type, Eigenvalues, Occupations, EigenvaluesB=EigenvaluesB,
                          OccupationsB=OccupationsB)

    SpeciesToPlot = {}

    for key in Species.iterkeys():
Example #23
0
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.constants import codata
c = codata.value('speed of light in vacuum')


def f(x, k, b):
    return k + b * x


x = np.array([5437.0, 6240.0, 7600.0, 15280.0]) * 1e-10
x = c / x
y = np.array([0.08, 0.08, 0.12, 0.48]) * 1e-6
y_err = np.array([0.02, 0.04, 0.03, 0.01]) * 1e-6
log_yerr_up = np.log(y + y_err) - np.log(y)
log_yerr_do = np.log(y) - np.log(y - y_err)
popt, pcov = curve_fit(f, np.log(x), np.log(y), p0=(2.0, -1.0), sigma=y_err)
print(popt)
perr = np.sqrt(np.diag(pcov))
print(perr)
beta = popt[1]
print(1.97 * (beta + 2.3))
print(1.97 * perr[1])
x_test = np.linspace(-2.5, 2.0, 50)
y1 = 1.71 * (10**(0.4 * 1.97 * (x_test + 2.3)) - 1)
y2 = 1.71 * (10**(0.4 * 0.91 * (x_test + 2.3)) - 1)
fig = plt.figure()
plt.plot(np.log(x), np.log(y), 'bo', label='data')
plt.errorbar(np.log(x), np.log(y), yerr=[log_yerr_do, log_yerr_up], fmt='bo')
def popsim(ele_sym_A, ele_sym_B, T_B, dist, sidepeaks_transition,
           sidepeaks_collinear, time_steps, database, charge_state, double_ce):

    print(sidepeaks_transition)
    sidepeaks_sim = bool(sidepeaks_transition)
    print(sidepeaks_sim)

    try:
        ele_num_B = int(ele_sym_B)
        ele_sym_B = element(ele_num_B).symbol

    except:
        pass

    ele_A = element(ele_sym_A)  #e.g. Na, K, Li
    ele_B = element(ele_sym_B)

    if not os.path.exists("results/Z" + str(ele_B.atomic_number)):
        os.makedirs("results/Z" + str(ele_B.atomic_number))

    row = np.where(atomionspins[:, 1] == ele_sym_A)

    react_L_A = float(atomionspins[:, 2][row][0])  #I
    react_S_A = float(atomionspins[:, 3][row][0])
    prod_L_A = float(atomionspins[:, 4][row][0])  # II
    prod_S_A = float(atomionspins[:, 5][row][0])

    row = np.where(atomionspins[:, 1] == ele_sym_B)

    react_L_B = float(atomionspins[:, 4][row][0])  # II
    react_S_B = float(atomionspins[:, 5][row][0])

    show_notrans = 0

    m_B = ele_B.mass
    I_A = ele_A.ionenergies[1]

    B_string = ele_sym_B + 'I' * charge_state

    if dist != 0:
        I_B, term, J, L, S, level, skipped_level, E_k_probs = load_levels_lines(
            B_string, 0, dist, database, ele_B, charge_state, I_A)
    else:
        I_B, term, J, L, S, level, skipped_level = load_levels_lines(
            B_string, 0, dist, database, ele_B, charge_state, I_A)

    print(B_string + " levels and lines loaded")

    df_double_ce = pd.DataFrame()

    tot_cs, levels_pops_detunes, levels_cs, df_double_ce = iter_calc(
        [0.0], react_S_B, react_L_B, I_B, term, J, L, S, level, skipped_level,
        0, df_double_ce, ele_B, ele_A, prod_S_A, react_S_A, react_L_A,
        charge_state, T_B, dist)

    levels_pops_detunes_initial = levels_pops_detunes

    I_B2, term2, J2, L2, S2, level2, skipped_level2 = I_B, term, J, L, S, level, skipped_level  #save charge state 2 for iteration

    second_ce_levels, second_ce_cs = [], []
    if double_ce:
        if dist == 0:
            for i, l2 in enumerate(level2):
                I_B, term, J, L, S, level, skipped_level = load_levels_lines(
                    B_string, 1, dist, database, ele_B, charge_state, I_A)
                print(
                    "##################################################################################"
                )
                print(
                    "##################################################################################"
                )
                print(str(l2), str(term2[i]), str(S2[i]), str(L2[i]),
                      str(I_B - float(l2) * hc))
                tot_cs, levels_pops_detunes, levels_cs, df_double_ce = iter_calc(
                    l2, S2[i], L2[i], I_B - float(l2) * hc, term, J, L, S,
                    level, skipped_level, 1, df_double_ce, ele_B, ele_A,
                    prod_S_A, react_S_A, react_L_A, charge_state, T_B, dist)
                print("Total CS:", tot_cs)
                second_ce_levels.append(l2)
                second_ce_cs.append(tot_cs)

            file_string = 'results/Z' + str(
                ele_B.atomic_number
            ) + '/second_ce/levels_pops_detunes' + ele_sym_B + "I" * charge_state + "_" + ele_sym_A + "_" + str(
                T_B) + "_" + str(dist)
            df_double_ce.to_csv(file_string)

            second_ce_levels_css = np.array(list(
                zip(second_ce_levels, second_ce_cs)),
                                            dtype=float)
            np.savetxt('results/Z' + str(ele_B.atomic_number) +
                       '/second_ce_levels_css' + ele_sym_B +
                       "I" * charge_state + "_" + ele_sym_A + "_" + str(T_B) +
                       "_" + str(dist),
                       second_ce_levels_css,
                       delimiter=';')
        else:
            print("can't do double cec with dist !=0 ")

    ##################evolve population###################
    if not sidepeaks_sim:
        levels_pops_detunes = levels_pops_detunes[:, [
            0, 1
        ]]  # remove energy differences column

    evolved_level = []
    unevolved_level = []

    amu = codata.value('atomic mass constant')  #kg
    velocity = np.sqrt((2 * T_B * 1.6E-19) / (m_B * amu)) * 10**2
    c = codata.value('speed of light in vacuum') * 10**2  #cm
    flight_time = dist / velocity
    print("flight time:", flight_time)

    print(ele_sym_A, ":", ele_A.description)
    print(ele_sym_B, ":", ele_B.description)

    E_k_probs.sort()
    E_k_probs = list(E_k_probs for E_k_probs, _ in itertools.groupby(
        E_k_probs))  # remove possible duplicates

    if flight_time != 0:

        dt = (flight_time / time_steps)

        for step in range(0, time_steps):
            print("time step:", step)
            #times previous step by time increment
            # cs_norm_evol_previous=list(cs_norm_evol)
            levels_pops_detunes_previous = levels_pops_detunes

            #first decrease population of the upper level energies here
            for index1, level_pop_detune1 in enumerate(
                    levels_pops_detunes):  #go through uppers
                level1 = level_pop_detune1[0]  #upper level
                pop1 = level_pop_detune1[1]  #upper pop
                if sidepeaks_sim: eloss1 = level_pop_detune1[2]

                for E_k_prob in E_k_probs:
                    upper_energy = E_k_prob[0]
                    lower_energy = E_k_prob[1]
                    this_A = E_k_prob[2]

                    if round(upper_energy, 2) == round(
                            level1, 2
                    ):  #find decays from this upper, round incase diff databases

                        if round(lower_energy, 2) in np.around(
                                levels_pops_detunes[:, 0], decimals=2
                        ):  # maintains precision of NIST database for lower energy
                            index3 = np.where(
                                np.around(levels_pops_detunes[:, 0],
                                          decimals=2) == round(
                                              lower_energy, 2))
                            lower_energy = float(
                                levels_pops_detunes[:, 0][index3][0])

                        if sidepeaks_sim:
                            index2 = np.array(
                                np.where(
                                    np.all(levels_pops_detunes[:, [0, 2]] ==
                                           np.array([
                                               lower_energy,
                                               level1 - eloss1 - lower_energy
                                           ]),
                                           axis=1)))

                            if index2.size == 1:
                                levels_pops_detunes[:, 1][
                                    index2] = levels_pops_detunes[:, 1][
                                        index2] + pop1 * (
                                            1 - np.exp(-dt * this_A)
                                        )  #add pop into lower level
                            elif index2.size == 0:
                                newrow = np.array([
                                    lower_energy, pop1 *
                                    (1 - np.exp(-dt * this_A)),
                                    (level1 - eloss1 - lower_energy)
                                ],
                                                  dtype=float)
                                levels_pops_detunes = np.vstack(
                                    (levels_pops_detunes, newrow))

                            else:
                                print("index 2 size error", index2)

                            pop1 = pop1 * np.exp(
                                -dt * this_A)  #decay upper level pop
                            levels_pops_detunes[:, 1][index1] = pop1 * np.exp(
                                -dt * this_A)

                        else:
                            if lower_energy in levels_pops_detunes[:,
                                                                   0]:  #adds pop to lower level if exiting level
                                index2 = np.where(
                                    levels_pops_detunes[:, 0] == lower_energy)
                                levels_pops_detunes[:, 1][
                                    index2] = levels_pops_detunes[:, 1][
                                        index2] + pop1 * (
                                            1 - np.exp(-dt * this_A)
                                        )  #adds decayed pop to lower level
                            else:
                                newrow = np.array(
                                    [
                                        lower_energy, pop1 *
                                        (1 - np.exp(-dt * this_A))
                                    ],
                                    dtype=float)  #creates new pop if new level
                                levels_pops_detunes = np.vstack(
                                    (levels_pops_detunes, newrow))

                            # if upper_energy==39625.506:
                            # 	print("upper_energy, lower_energy, pop1, pop1*np.exp(-dt*this_A), this_A")
                            # 	print(upper_energy, lower_energy, pop1, pop1*np.exp(-dt*this_A), this_A)
                            # 	print(step, step*dt)

                            pop1 = pop1 * np.exp(
                                -dt * this_A)  #decay upper level pop
                            levels_pops_detunes[:, 1][index1] = pop1

        print(levels_pops_detunes)
        print("sum of pops:", sum(levels_pops_detunes[:, 1]))
        print("final states populated")
    else:
        print("no time of flight population change")

    if sidepeaks_sim:
        levels_pops_detunes_sorted = cumsum_diff(
            levels_pops_detunes[:, [0, 1]]
        )  #get rid of seperate entries for displaying populations
        levels_pops_detunes_sorted = levels_pops_detunes_sorted[
            levels_pops_detunes_sorted[:, 1].argsort()[::-1]]
    else:
        levels_pops_detunes_sorted = levels_pops_detunes
        levels_pops_detunes_sorted = levels_pops_detunes_sorted[
            levels_pops_detunes_sorted[:, 1].argsort()[::-1]]

    levels_pops_detunes_sorted = levels_pops_detunes_sorted.astype(float)

    print("top 10 populations:", levels_pops_detunes_sorted[:10])

    np.savetxt('results/Z' + str(ele_B.atomic_number) +
               '/levels_pops_detunes_sorted' + ele_sym_B + "I" * charge_state +
               "_" + ele_sym_A + "_" + str(T_B) + "_" + str(dist),
               levels_pops_detunes_sorted,
               delimiter=';',
               fmt="%.5f")

    fig, ax = plt.subplots(figsize=(6, 10))

    # if show_notrans:
    # 	unevolved_level=list(set(energy_levels_evol)-set(evolved_level))
    # 	if len(unevolved_level)>0:
    # 		plt.axvline(x=unevolved_level[1], color='m', linestyle='-', label="No transitions from level (no info)")
    # 		for ulevel in unevolved_level[2:]: plt.axvline(x=ulevel, color='m', linestyle='-')

    if len(skipped_level) > 0:
        ax.plot([0, 1], [skipped_level[0], skipped_level[0]],
                color='g',
                linestyle='--',
                label="Skipped initial population (unknown spin)")
        for slevel in skipped_level[1:]:
            ax.plot([0, 1], [slevel, slevel], color='g', linestyle='--')

    ax.plot(levels_pops_detunes_initial[:, 1],
            levels_pops_detunes_initial[:, 0],
            'ro',
            label="Initial population")

    for pt in levels_pops_detunes_initial[:, [0, 1]]:
        ax.plot([0, pt[1]], [pt[0], pt[0]], color='r')

    if flight_time != 0:

        ax.plot(levels_pops_detunes_sorted[:, 1],
                levels_pops_detunes_sorted[:, 0],
                'bs',
                label="Final population")
        #
        for pt in levels_pops_detunes_sorted[:, [0, 1]]:
            ax.plot([0, pt[1]], [pt[0], pt[0]], color='b')

    ax.set_ylabel("Energy level (cm-1)", fontsize=14)
    ax.set_xlabel("Normalised population", fontsize=14)
    ax.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    ax.plot([0, max(levels_pops_detunes_sorted[:, 1])], [(I_B - I_A) / hc,
                                                         (I_B - I_A) / hc],
            color='k',
            linestyle='--',
            label="CE entry energy")

    ##resonance plot##

    if 1:  #plot bare cross_section
        try:
            energy_levels, bare_cross_sections = levels_cs[:, 0], levels_cs[:,
                                                                            1]
            bare_cs_norm_before = [
                float(i) / sum(bare_cross_sections)
                for i in bare_cross_sections
            ]  # this norm is without f factor..

            bare_cs = [float(c) for c in bare_cross_sections]
            bare_el = [float(e) for e in energy_levels]
            extra_els = np.linspace(min(bare_el), max(bare_el), 30)

            for el in extra_els:
                I_B_ex = I_B - float(el) * hc
                try:
                    cs = cross_section(I_A, I_B_ex, m_B, T_B)
                    bare_cs.append(float(cs))
                    bare_el.append(float(el))
                    print("el", "cs", el, cs)
                except:
                    print("problem with", el, "cm-1")
                # if cs < 2.0E-10: #to reduce the amount of time wasted on calculation for the plot
                # 	break

            print("bare_cs_norm_before", bare_cs_norm_before)
            print("bare_cs", bare_cs)

            #values.index(min(values))

            bare_cs_norm_after = [float(i) / sum(bare_cs) for i in bare_cs]

            # scale_ref=bare_cs_norm_before.index(max(bare_cs_norm_before))

            # scale_ratio=bare_cs_norm_after[scale_ref]/(bare_cs_norm_before[scale_ref]*levels_pops_detunes_initial[:,1][scale_ref]) #levels_pops_detunes_initial[:,1][scale_ref] for f factor norm

            # max_pop=max(levels_pops_detunes_sorted[:,1])
            max_cs_i = bare_cs_norm_before.index(max(bare_cs_norm_before))
            # cs_i=bare_cs_norm_before[0]
            scale_ratio = max(
                levels_pops_detunes_sorted[:, 1]) / bare_cs_norm_after[
                    max_cs_i]  #)*levels_pops_detunes_initial[:,1][0]

            print("scale_ratio", scale_ratio)

            # scale_ratio=float(bare_cs_norm_before[-1])/float(bare_cross_sections[-1])

            # bare_cs_norm=[float(i)*scale_ratio for i in bare_cs]

            bare_cs_norm = [
                scale_ratio * float(i) / sum(bare_cs) for i in bare_cs
            ]

            bare_el, bare_cs_norm = (list(t) for t in zip(
                *sorted(zip(bare_el, bare_cs_norm))))
            ax.plot(bare_cs_norm, bare_el, '--', label="Bare cross-section")

        except Exception as exception:
            print(exception)

    ax.legend(numpoints=1, loc="upper right")

    mpld3.save_html(fig=fig,
                    fileobj='results/Z' + str(ele_B.atomic_number) + '/fig_' +
                    ele_sym_B + "I" * charge_state + "_" + ele_sym_A + "_" +
                    str(T_B) + "_" + str(dist) + '.html')
    fig.savefig('results/Z' + str(ele_B.atomic_number) + '/fig_' + ele_sym_B +
                "I" * charge_state + "_" + ele_sym_A + "_" + str(T_B) + "_" +
                str(dist) + '.pdf')
    plt.show()

    if sidepeaks_sim:
        plt.show()

    print("finished popsim")

    # change energy of beam by the energy loss of previous transitions (make sure includes chains)
    # and then dopplershift transition along with a scan range.. make last column beam energy instead?

    if sidepeaks_sim:
        try:
            E_line_rest = sidepeaks_transition[1] - sidepeaks_transition[0]
            transition_detuning_pops_f = open(
                'results/Z' + str(ele_B.atomic_number) +
                '/transition_detuning_pops' + ele_sym_B + "I" * charge_state +
                "_" + ele_sym_A + "_" + str(T_B) + "_" + str(dist) + "_" +
                str(E_line_rest), 'rb')
            transition_detuning_pops = np.loadtxt(transition_detuning_pops_f,
                                                  delimiter=';',
                                                  dtype=float)
            # print(transition_detuning_pops)
        except Exception as exception:
            print(exception)
            #work out doppler shift of all transitions from lower levels,
            #keep/plot those with range matching near what we want and keep track of seperate transitions

            cm_to_MHz = 29.9792458 * 10**3  #1 cm^-1=29.9792458 GHz in vacuum

            E_line_rest = sidepeaks_transition[1] - sidepeaks_transition[
                0]  #transition cm-^1

            velocity = np.sqrt(
                (2 * (T_B) * 1.6E-19) /
                (m_B *
                 amu))  #shifts energy of beam in eV then converts to velocity
            beta = velocity / (c * 10**(-2))
            if sidepeaks_collinear:
                E_line = E_line_rest * np.sqrt((1 + beta) / (1 - beta))
            else:
                E_line = E_line_rest * np.sqrt((1 - beta) / (1 + beta))

            only_same_transition = True

            transition_detuning_pops = []

            for index1, level_pop_detune1 in enumerate(
                    levels_pops_detunes):  #where equals lower level..
                level1 = level_pop_detune1[0]
                pop1 = level_pop_detune1[1]
                eloss1 = level_pop_detune1[2]

                if only_same_transition and (level1
                                             == sidepeaks_transition[0]):

                    velocity = np.sqrt(
                        (2 * (T_B - eloss1 * hc) * 1.6E-19) / (m_B * amu)
                    )  #shifts energy of beam in eV then converts to velocity #BEAM ENERGY IN JOULES NOT eV!!
                    beta = velocity / (c * 10**(-2))

                    if sidepeaks_collinear:
                        E_line_detune = E_line_rest * np.sqrt(
                            (1 + beta) / (1 - beta))
                    else:
                        E_line_detune = E_line_rest * np.sqrt(
                            (1 - beta) / (1 + beta))

                    detuning = (float(E_line_detune) - float(E_line)
                                ) * cm_to_MHz  #detuning from transition in MHz

                    if abs(detuning) < 10000:  #10 GHz scan range
                        print([E_line, detuning, pop1])
                        transition_detuning_pops.append(
                            [E_line, detuning, pop1])
                    else:
                        # print("detuning",abs(detuning), eloss1*hc ,"eV, too big?")
                        pass

                else:

                    for E_k_prob in (
                            E_k_prob for E_k_prob in E_k_probs
                            if round(E_k_prob[1], 2) == round(level1, 2)
                    ):  #where lower energy is transition within 2 d.p. Finds upper levels that transition into this lower.
                        this_transition = E_k_prob[0] - E_k_prob[
                            1]  #upper-lower

                        velocity = np.sqrt(
                            (2 * (T_B - eloss1 * hc) * 1.6E-19) / (m_B * amu)
                        )  #shifts energy of beam in eV then converts to velocity #BEAM ENERGY IN JOULES NOT eV!!
                        beta = velocity / (c * 10**(-2))

                        if sidepeaks_collinear:
                            this_transition_detune = this_transition * np.sqrt(
                                (1 + beta) / (1 - beta))
                        else:
                            this_transition_detune = this_transition * np.sqrt(
                                (1 - beta) / (1 + beta))

                        detuning = (
                            float(this_transition_detune) - float(E_line)
                        ) * cm_to_MHz  #detuning from transition in MHz

                        if abs(detuning) < 10000:  #10 GHz scan range
                            print([this_transition, detuning, pop1])
                            transition_detuning_pops.append(
                                [this_transition, detuning, pop1])

                        else:
                            # print("detuning",abs(detuning), eloss1*hc ,"eV, too big?")
                            pass

            transition_detuning_pops = np.array(transition_detuning_pops)

            transition_detuning_pops[:,
                                     2] = transition_detuning_pops[:,
                                                                   2] / transition_detuning_pops[:, 2].max(
                                                                       axis=0)

            np.savetxt('results/Z' + str(ele_B.atomic_number) +
                       '/transition_detuning_pops' + ele_sym_B +
                       "I" * charge_state + "_" + ele_sym_A + "_" + str(T_B) +
                       "_" + str(dist) + "_" + str(E_line_rest),
                       transition_detuning_pops,
                       delimiter=';',
                       fmt='%1.3f')

        print(transition_detuning_pops)
        transition_detuning_pops = transition_detuning_pops[
            transition_detuning_pops[:, 0].argsort()]  #sort into transitions

        transitions_legend = {}

        for transition_detuning_pop in transition_detuning_pops:
            key = transition_detuning_pop[0]
            if key in transitions_legend:
                transitions_legend[key] = np.vstack(
                    (transitions_legend[key],
                     np.array([
                         transition_detuning_pop[1], transition_detuning_pop[2]
                     ])))  # updates if exists, else adds
            else:
                transitions_legend[key] = np.array(
                    [[transition_detuning_pop[1], transition_detuning_pop[2]]])

        print(transitions_legend)

        colors = cm.rainbow(np.linspace(0, 1, len(transitions_legend)))

        fig, ax = plt.subplots(figsize=(7, 5))
        axes = [ax, ax.twiny()]  #, ax.twinx()

        for col_i, key in enumerate(transitions_legend):

            axes[0].plot(transitions_legend[key][:, 0],
                         transitions_legend[key][:, 1],
                         'ro',
                         label=str(round(key, 2)) + "transition",
                         c=colors[col_i])

            for pt in transitions_legend[key][:, [0, 1]]:
                # plot (x,y) pairs.
                # vertical line: 2 x,y pairs: (a,0) and (a,b)
                axes[0].plot([pt[0], pt[0]], [0, pt[1]], color=colors[col_i])

        binning_MHz = 10
        #binning sidepeak data
        no_bins = int(transition_detuning_pops[:, 1].max() -
                      transition_detuning_pops[:, 1].min()) / binning_MHz
        binned_detunes = scipy.stats.binned_statistic(
            transition_detuning_pops[:, 1],
            transition_detuning_pops[:, 2],
            bins=no_bins,
            statistic="sum")
        binned_detunes_bins = [(a + b) / 2 for a, b in zip(
            binned_detunes.bin_edges[0:], binned_detunes.bin_edges[1:])]

        detune_counts = []
        for detune_i, detune in enumerate(transition_detuning_pops[:, 1]):
            detune_counts.append(
                [detune] *
                int(transition_detuning_pops[:, 2][detune_i] * 1000))

        # detune_counts=list(np.array(detune_counts).flat)
        # print("detune_counts", detune_counts)
        detune_counts = [item for sublist in detune_counts for item in sublist]

        #binning sidepeak data
        axes[0].bar(binned_detunes_bins,
                    binned_detunes.statistic,
                    label=str(binning_MHz) + " MHz binning",
                    align='center',
                    alpha=0.4,
                    width=(binned_detunes_bins[1] -
                           binned_detunes_bins[0]))  # A bar chart

        # X_plot = np.linspace(min(transition_detuning_pops[:,1])-50, max(transition_detuning_pops[:,1])+50, 1000)
        # kde = KernelDensity(kernel='gaussian', bandwidth=4).fit(np.array(detune_counts).reshape((-1, 1)))
        # log_dens = kde.score_samples(np.array(X_plot).reshape((-1, 1)))
        # plt.fill(X_plot, np.exp(log_dens)*1000.0/(35*1.75), fc='#AAAAFF')

        # sidepeak_model=ConstantModel()
        # for detune_i, detune in enumerate(transition_detuning_pops[:,1]):
        # 	sidepeak_model=sidepeak_model + LorentzianModel() # amplitude=np.array([transition_detuning_pops[:,2][detune_i]], sigma=[10.0], center=[detune]
        #
        # print(sidepeak_model.param_names)
        #
        # print("X_plot, sidepeak_model(X_plot)", X_plot, sidepeak_model(X_plot))
        # plt.plot(X_plot, sidepeak_model(X_plot))

        axes[0].set_xlabel("Detuning (MHz)", fontsize=20)
        axes[1].set_xlabel('Detuning (eV)', fontsize=20)
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
        plt.ylabel("Norm. Population", fontsize=20)
        plt.legend(numpoints=1, loc=2)
        plt.xlim((-200, +200))

        # ax1Ticks = axes[0].get_xticks()
        # ax2Ticks = ax1Ticks
        #
        # def tick_function(X):
        # 	V = X + 49
        # 	return [str(z) for z in V]
        #
        # axes[1].set_xticks(ax2Ticks)
        # axes[1].set_xbound(axes[0].get_xbound())
        # axes[1].set_xticklabels(tick_function(ax2Ticks))

        ax = plt.gca()
        ax.get_xaxis().get_major_formatter().set_scientific(False)

        plt.show()
Example #25
0
print(nu_real_840)
print(nu_real_1260)
print(nu_real_1680)

print("jetz nu ideal")
nu_ideal_420 = T(420, params1[0], params1[1],
                 params1[2]) / (T(420, params1[0], params1[1], params1[2]) -
                                T(420, params2[0], params2[1], params2[2]))
print(nu_ideal_420)
nu_ideal_840 = T(840, params1[0], params1[1],
                 params1[2]) / (T(840, params1[0], params1[1], params1[2]) -
                                T(840, params2[0], params2[1], params2[2]))
print(nu_ideal_840)
nu_ideal_1260 = T(1260, params1[0], params1[1],
                  params1[2]) / (T(1260, params1[0], params1[1], params1[2]) -
                                 T(1260, params2[0], params2[1], params2[2]))
print(nu_ideal_1260)
nu_ideal_1680 = T(1680, params1[0], params1[1],
                  params1[2]) / (T(1680, params1[0], params1[1], params1[2]) -
                                 T(1680, params2[0], params2[1], params2[2]))
print(nu_ideal_1680)

#def linreg(x, A, B):
#   return - x/
print(codata.value("molar gas constant"))

plt.plot(1 / T1, np.log(p1), "kx", label="Messwerte")
plt.xlabel(r'1/$T_{1}$ [1/K]')
plt.ylabel(r'log($p_{1}$)')
plt.legend(loc="best")
plt.show()
Example #26
0
_y_as = 21.13  # MeV
_y_w = 2.3

A = [48, 132, 70]
Z = [20, 50, 28]
N = [28, 82, 42]
#A = [4, 134, 96]
#Z = [2, 52, 38]
#N = [2, 82, 58]
rad = [
    _y_r0 * (A[0])**(1.0 / 3.0), _y_r0 * (A[1])**(1.0 / 3.0),
    _y_r0 * (A[2])**(1.0 / 3.0)
]
mff = [
    np.float(A[0]) *
    codata.value('atomic mass constant energy equivalent in MeV'),
    np.float(A[1]) *
    codata.value('atomic mass constant energy equivalent in MeV'),
    np.float(A[2]) *
    codata.value('atomic mass constant energy equivalent in MeV')
]

_y_I1 = float(N[0] - Z[0]) / float(A[0])
_y_I2 = float(N[1] - Z[1]) / float(A[1])
_y_I3 = float(N[2] - Z[2]) / float(A[2])
_y_zeta1 = rad[0] / _y_a
_y_zeta2 = rad[1] / _y_a
_y_zeta3 = rad[2] / _y_a
_y_g1 = _y_zeta1 * np.cosh(_y_zeta1) - np.sinh(_y_zeta1)
_y_g2 = _y_zeta2 * np.cosh(_y_zeta2) - np.sinh(_y_zeta2)
_y_g3 = _y_zeta3 * np.cosh(_y_zeta3) - np.sinh(_y_zeta3)
Example #27
0
from scipy.constants import codata

# TODO: would be nice to make this a frozen-dict
physical_constants = {
    "k_boltzmann": codata.value("Boltzmann constant"),
    "gravity_acceleration": codata.value("standard acceleration of gravity"),
}
Example #28
0
from scipy.constants import codata

# from http://docs.scipy.org/doc/scipy-0.13.0/reference/constants.html#scipy.constants.physical_constants
hbar = codata.value("Planck constant over 2 pi")
c0 = codata.value("speed of light in vacuum")
muBohr = codata.value("Bohr magneton")
amu = codata.value("atomic mass constant")

g_Earth = 9.81 # m/s
Created on Thu Mar  7 11:36:17 2019

@author: cmatthe
"""
#%% imports
import matplotlib.pyplot as plt  #for plt
from matplotlib.backends.backend_pdf import PdfPages  # for PdfPages: suspiciously abscent in akaminskis code
#I suspect there is a hidden standart import for example also for numpy?
# perhaps in  sys.path.append('/home/akaminsk/pythontests')
import matplotlib as mpl  #missing in akaminski
import h5py
import numpy as np
from tqdm import tqdm
import barycorrpy as bary
from scipy.constants import codata
lightvel = codata.value('speed of light in vacuum')  #for barycorr

import pickle  # for writing barycorr results into a binary file

#%%

# CAHA Coordinates for barycorr
_lat = 37.2236
_lon = -2.54625
_elevation = 2168.

kt = 'Kt3_stitched_redata'
pp = PdfPages("wobble_servalcomparison_GJ876_" + kt + "_sanity.pdf")
fig = plt.figure(figsize=(15, 9), dpi=200)
mpl.rc('font', size=16)
plt.clf()
Example #30
0
 def __init__(self):
     self.GF = codata.value('Fermi coupling constant')  # in GeV^-2
     self.GammaZ = GZ
     self.MassZ = Mz
     self.p = 0.2e-9  # in GeV
     self.m = 0.1e-9  # in GeV
Example #31
0
def test_2002_vs_2006():
    assert_almost_equal(codata.value('magn. flux quantum'),
                        codata.value('mag. flux quantum'))
Example #32
0
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preview'] = True
# read file from command line (use np.loadtxt, output ndarray)
if len(sys.argv) != 2:
    print("Please inform the filename.")
    exit(1)

fname = sys.argv[1]
try:
    data = np.loadtxt(fname, dtype='float')
except IOError:
    print("File '%s' does not exit.", fname)
    exit(1)

# scientific constants
c = codata.value('speed of light in vacuum') * 100  # cgs
h = codata.value('Planck constant') * 1e7  # cgs
k = codata.value('Boltzmann constant') * 1e7  # cgs


# fitting curve
def gray(wavelength, T, logN, b):
    freq = c / wavelength
    return logN + np.log(2 * h / c**2) + (b + 3) * np.log(freq) - np.log(
        np.exp(h * freq / k / T) - 1) - b * np.log(230e9)


# select data
x = data[np.where((data[:, 0] > 6e5) & (data[:, 0] < 1e7))[0], 0]  # wavelenth
y = data[np.where((data[:, 0] > 6e5) & (data[:, 0] < 1e7))[0],
         1]  # flux density
Example #33
0
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 27 11:50:49 2015

@author: Anonymous
"""
from __future__ import division
import numpy as np
from scipy.constants import codata
from scipy.constants import h, hbar, c, mu_0, epsilon_0, m_e, e 
k_B = codata.value('Boltzmann constant')
a_0 = codata.value('atomic unit of length') 
mu_B = codata.value('Bohr magneton')
u = codata.value('atomic mass constant')
Ry = codata.value('Rydberg constant')
m_Rb87 = 86.909180520*u
alpha = codata.value('fine-structure constant')
Ry_Rb87 = Ry/(1+m_e/m_Rb87) # Rydberg constant with mass correction

#from para import *

# calculate quantum defect
#delta_0 = np.array([3.1311804, 2.6548849, 2.6416737,1.34809171, 1.34646572, 0.0165192, 0.0165437, 0])
#delta_2 = np.array([0.1784, 0.2900, 0.2950, - 0.60286, - 0.59600, - 0.085, - 0.086, 0])
delta_0, delta_2 = np.zeros(8), np.zeros(8)
def delta(n, lj):
    """
    delta(n.lj)
    Quantum defect for given n and lj for n>20, cf T.Gallager "Rydberg Atoms"
    """
    return delta_0[lj] + delta_2[lj]/((n - delta_0[lj])**2)
Example #34
0
    e_mob = 120.0  # electron mobility - m2/V.s [3]
    h_mob = 1.0  # hole mobility - m2/V.s  [3]
    tau_e = 1e-10  # electron lifetime - s [3]
    tau_h = 1e-6  # hole lifetime - s [3]
    m0 = 9.11e-31  # electron mass - kg [3]
    me = 0.014 * m0  # used semiconductor electron effective mass [3]
    mh = 0.43 * m0  # used semiconductor hole effective mass [3]
    na = 1e16  # positive or negative dopping - m-3
    b = (
        1.0
    )  # b=1 when the diffusion current is dominantand b=2 when the recombination current dominates - Derinaki's book page 251
    s = 5e4  # surface recombination velocity -> http://www.ioffe.ru/SVA/NSM/Semicond/InSb/electric.html#Recombination
    R0 = 1e10  # measured resistivity  - ohm

    # IMPORTANT CONSTANTS
    q = codata.value("elementary charge")  # C
    etha2 = 0.45  # quantum efficieny table 3.3 dereniak's book [3]
    h = codata.value("Planck constant")  # J.s
    c = codata.value("speed of light in vacuum")  # m/s
    k = codata.value("Boltzmann constant")  # J/K
    sigma = codata.value("Stefan-Boltzmann constant")  # W/(m2 K4)
    sigma_photon = 1.52e15  # boltzmann constant for photons- photons/(s.m2.K3)
    epsilon = 1.0  # source emissivity

    if T_source > T_bkg:
        r = np.sqrt(A_source / np.pi)  # source radius if it is a circle and plane source
    else:
        r = np.sqrt(A_bkg / np.pi)  # source radius if it is a circle and plane source

    # DEFINING THE WAVELENGTH VECTOR
    lambda_vector = np.linspace(lambda_initial, lambda_final, 1000)
def compare_results(file_list, parameter_change_list, bary_starname, orbital_parameters, objects, servaldir):
    """
    Compares result files to find the best rv scatter around literature fit returns change in parameter that yielded best results
    
    file_list: list of `str`
        list containing the file paths of the files to be compared
    parameter_change_list: list of `int`
        list containing the parameter exponent shifts used to create the files in file_list
    orbital_parameters : list of `float`
        orbital_parameters = [K, P, e, omega, T0]
        parameters of the keplerian fit to be used as "true" baseline
    """
    sigma_list = np.zeros(len(file_list)) + 100 # 100 is a fudge factor
    for f, fil in enumerate(file_list):
        #assumes order of file_listand parameter_change_list are matched. (maybe extract from file name?)
        wobble_res = h5py.File(fil,'r')
        w_dates = wobble_res['dates'][()] 
        w_dates_utc = wobble_res['dates_utc'][()]
        
        w_RVs = wobble_res['star_time_rvs'][()]
        w_RVs_original = w_RVs
        w_RVs_er = wobble_res['star_time_sigmas'][()]
        
        #barycorr for wobble_orig
        from scipy.constants import codata 
        lightvel = codata.value('speed of light in vacuum') #for barycorr
        # CAHA Coordinates for barycorr
        _lat = 37.2236
        _lon = -2.54625
        _elevation = 2168.
        
        w_RVs_original_barycorr = np.zeros(len(w_dates))
        for n in tqdm(range(len(w_RVs_original_barycorr))):
            w_RVs_original_barycorr[n]=bary.get_BC_vel(w_dates_utc[n], starname=bary_starname, lat=_lat, longi=_lon, alt=_elevation, zmeas=w_RVs_original[n]/lightvel)[0]
            
        #Serval Correction 
        #read in SERVAL
        ser_rvc = np.loadtxt(servaldir+objects[1]+"/"+objects[1]+".rvc.dat")
        # remove entries with nan in drift
        ind_finitedrift = np.isfinite(ser_rvc[:,3])
        ser_rvc = ser_rvc[ind_finitedrift]
        ser_corr = - ser_rvc[:,8] - ser_rvc[:,3]
        #match wobble and serval
        indices_serval = [] 
        indices_wobble = []
        for n in range(len(w_dates)):
            ind_jd = np.where(np.abs(ser_rvc[:,0]-w_dates[n]) == np.nanmin(np.abs(ser_rvc[:,0]-w_dates[n])))[0][0]
            if (ser_rvc[ind_jd,0]-w_dates[n])*24*60<20.: #only takes matches closer than 20 minutes
                indices_serval.append(ind_jd)
                indices_wobble.append(n)
        print("#serval_ind:"+str(len(indices_serval)), "#wobble_ind:"+str(len(indices_wobble)))
        #now set up all the data according to the indices
        ser_rvc = ser_rvc[indices_serval]
        ser_corr = ser_corr[indices_serval]
        
        w_dates = w_dates[indices_wobble]
        w_dates_utc = w_dates_utc[indices_wobble]
        w_RVs_original_barycorr = w_RVs_original_barycorr[indices_wobble]       + ser_corr
        w_RVs_er = w_RVs_er[indices_wobble]
        
        def fit_func(t, T0_offset):
                return rv.radial_velocity(t , orbital_parameters[0], orbital_parameters[1], orbital_parameters[2],orbital_parameters[3], orbital_parameters[4] + T0_offset)
            
        #fit to Wobble
        xdata = w_dates
        ydata = w_RVs_original_barycorr-np.nanmean(w_RVs_original_barycorr)
        popt, pcov = sp.optimize.curve_fit(fit_func, xdata, ydata,  sigma = w_RVs_er, absolute_sigma = True)
        print("T0_offset Wobble = ", popt)
        T0_offset = popt[0]
        
        #make these weighted (maybe: thsi may not be a good idea if residuals are not strongly correlated to error (as with wobble results))
        sigma_wob = np.nanstd(sigma_clip(
        w_RVs_original_barycorr - np.nanmean(w_RVs_original_barycorr) - fit_func(w_dates, T0_offset)
        ,sigma = 5))
        sigma_list[f] = sigma_wob
        
        #TODO include some nice progress plots
        
    best_index = np.argmin(sigma_list)
    return parameter_change_list[best_index]
Example #36
0
def main():
    """
    This class generates initial conditions for classical charged particle
    trajectory calculations that are distributed according to the probability
    of creating a pair at a given point in space-time.

    We proceed as follows:
        • Read the HDF5 file containing the temporal electromagnetic field.
        • Find the maximum value of the pair production integrand across the
            whole space and scale it.
        • Draw initial conditions for each time step by generating a random
            number r for each spatial point on the grid and instantiating a particle
            if scaledProbability > r until nParticles have been drawn.

    Author: Joey Dumont     <*****@*****.**>
    """

    # Start the timer.
    start_time = time.perf_counter()

    # Command line arguments
    parser = ap.ArgumentParser(
        description="Generate the initial conditions for the simulation.")
    parser.add_argument(
        "--directory",
        type=str,
        default=None,
        help=
        "Directory containing the HDF5 with the electromagnetic field data.")
    parser.add_argument(
        "--fileTime",
        type=str,
        default="Field_reflected_time.hdf5",
        help=
        "Name of the HDF5 file with the temporal electromagnetic field data.")
    parser.add_argument("--fileFreq", type=str, default="Field_reflected.hdf5")
    parser.add_argument("--config",
                        type=str,
                        default="configStrattoLinear.xml",
                        help="Name of the XML configuration file.")
    parser.add_argument("--radial",
                        type=bool,
                        default=False,
                        help="Specifies the polarization of the beam.")

    # Parse arguments
    args = parser.parse_args()

    # Chosen shape for the simulation
    configFile = args.config

    # Parse arguments
    tree = ET.parse(configFile)
    config = tree.getroot()

    wavelength_element = config.find("./integration_salamin/lambda")
    if (wavelength_element == None):
        wavelength_element = config.find("./spectrum/lambda_c")
    wavelength = float(wavelength_element.text)

    # -- Electronic units.
    EL_UNITS_LENGTH = 2.0 * np.pi / wavelength
    EL_UNITS_TIME = 2.0 * np.pi * codata.value(
        'speed of light in vacuum') / wavelength

    numpart = int(config.find("./generate_initial_conditions/numpart").text)

    # We instantiate the Analysis3D object of interest and find the maximum pair density.
    if args.radial:
        pairProductionAnalysis = AnalysisRadial.AnalysisRadial(
            freq_field=args.directory + args.fileFreq,
            time_field=args.directory + args.fileTime)
    else:
        pairProductionAnalysis = Analysis3D.Analysis3D(
            freq_field=args.directory + args.fileFreq,
            time_field=args.directory + args.fileTime)

    maxIndices, maxDensities = pairProductionAnalysis.FindMaximumValues(
        pairProductionAnalysis.PairDensity)
    maxDensity = np.amax(maxDensities)

    # We now scale the number of particles per time slices w.r.t the relative strength of maxDensities.
    maxDensities = maxDensities / np.sum(np.abs(maxDensities))
    numpart_slices = np.ceil(maxDensities * numpart)
    numpart_slices = numpart_slices.astype(int)
    print(numpart_slices)

    # We prepare the arrays that will hold the initial positions and time values.
    x = np.zeros((numpart))
    y = np.zeros((numpart))
    z = np.zeros((numpart))
    t = np.zeros((numpart))

    particle_counter = 0
    for i in range(pairProductionAnalysis.size_time):
        particle_counter_slice = 0
        loop_counter = 0
        loop_max = 10 * numpart
        while (not (particle_counter_slice >= numpart_slices[i])
               and loop_counter < loop_max):

            # -- Uniform numbers for this temporal slice.
            random_numbers = np.random.uniform(
                size=pairProductionAnalysis.size_flat)

            # -- Pair density for this slice. Scaled to be a "PDF".
            pairDensity = pairProductionAnalysis.PairDensityTime(i) / np.sum(
                np.abs(pairProductionAnalysis.PairDensityTime(i)))

            for j in range(pairProductionAnalysis.size_flat):
                if (particle_counter_slice >= numpart_slices[i]):
                    break
                if (pairDensity.flat[j] > random_numbers[j]):
                    indices = np.unravel_index(j, pairDensity.shape)

                    if args.radial:
                        r = pairProductionAnalysis.coord_r[
                            indices[0]] * pairProductionAnalysis.UNIT_LENGTH
                        theta = 2.0 * np.pi * np.random.random()
                        z_si = pairProductionAnalysis.coord_z[
                            indices[1]] * pairProductionAnalysis.UNIT_LENGTH
                    else:
                        r = pairProductionAnalysis.coord_r[
                            indices[0]] * pairProductionAnalysis.UNIT_LENGTH
                        theta = pairProductionAnalysis.coord_theta[indices[1]]
                        z_si = pairProductionAnalysis.coord_z[
                            indices[2]] * pairProductionAnalysis.UNIT_LENGTH

                    t_si = pairProductionAnalysis.time[i]

                    x[particle_counter] = r * np.cos(theta) * EL_UNITS_LENGTH
                    y[particle_counter] = r * np.sin(theta) * EL_UNITS_LENGTH
                    z[particle_counter] = z_si * EL_UNITS_LENGTH
                    t[particle_counter] = t_si * EL_UNITS_TIME
                    particle_counter += 1
                    particle_counter_slice += 1

                    px = py = pz = 0.0
                    # Create file
                    of = open("init_conds.txt", 'w')
                    for pid in range(numpart):  # Loop on particle indices
                        # Write positions
                        of.write(
                            str(x[pid]) + " " + str(y[pid]) + " " +
                            str(z[pid]) + " ")
                        # Write momenta
                        of.write(str(px) + " " + str(py) + " " + str(pz) + " ")

                        # Write initial time.
                        of.write(str(t[pid]) + "\n")

                    of.close()

                    print("Allocated particle {} at x={}, y={}, z={} at t={}".
                          format(particle_counter, x[particle_counter - 1],
                                 y[particle_counter - 1],
                                 z[particle_counter - 1],
                                 t[particle_counter - 1]))
                    loop_counter += 1

    px = py = pz = 0.0

    # Create file
    of = open("init_conds.txt", 'w')

    for pid in range(numpart):  # Loop on particle indices
        # Write positions
        of.write(str(x[pid]) + " " + str(y[pid]) + " " + str(z[pid]) + " ")

        # Write momenta
        of.write(str(px) + " " + str(py) + " " + str(pz) + " ")

        # Write initial time.
        of.write(str(t[pid]) + "\n")

    of.close()

    # -- Stop timer.
    end_time = time.perf_counter()

    print(end_time - start_time)