Exemplo n.º 1
0
def execute(args):
    
    if args.skip1 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase( Test_import_gas_data)
        unittest.TextTestRunner(verbosity=1).run(suite)    
    else:
        DEBUG.verbose("Skipping :" + suite_list[0], True)
Exemplo n.º 2
0
def get_n_k(paf,
            wl_um=[],
            um_range=[0.3, 0.6],
            n_steps=100,
            interpolate_kind="default",
            verbose=0):
    """
    Import a file from RefractiveIndex.info and output the refractive index for the desired wavelengths. 
    
    
    INPUT:
    paf (str): path and filename
    wl_um (ndarray): wavelength axis, in micrometer
    um_range (list with 2 elements): if wl_um is not given, it will plot a range.
    n_steps (int): number of steps to plot the range.
    ax (plt axis): if False, it will make a new figure
    interpolate_kind (str): for tabulated data, the type of interpolation
    
    """
    temp = paf.split("/")
    DEBUG.verbose("Importing data for %s by %s" % (temp[-2], temp[-1][:-4]),
                  verbose_level=1)

    db_record = RIRY.import_refractive_index(paf=paf, verbose=verbose)
    DEBUG.verbose("  Imported data", verbose_level=0)

    if len(wl_um) == 0:
        wl_um = numpy.linspace(um_range[0], um_range[1], num=n_steps)
    n, k = n_k_for_wavelengths(db_record, wl_um, verbose=verbose)

    if type(n) == int:
        return 0, 0, 0

    return wl_um, n, k
Exemplo n.º 3
0
def import_transmission_data_raw(compound_name, verbose=0):
    """
    Takes a name for a material and outputs the wavelength axis (in eV) and the absorption for 1 micron.
    
    INPUT:
    material: name of material. The data for the gas has to be in '/Data/TransmissionSpectra/' and in the python file there. 
    
    OUTPUT:
    - wl_nm (ndarray): wavelength axis
    - tr_norm (ndarray): transmission, normalized to 1 mm
    
    CHANGELOG:
    
    """
    # find path
    path = NPCTools.Data.TransmissionSpectra.TransmissionSpectraData.data_path(
    )

    # convert to title case
    compound_name = compound_name.lower()
    files_list = NPCTools.Data.TransmissionSpectra.TransmissionSpectraData.files_list(
    )

    # find the name in the list
    mat = [item for item in files_list if compound_name in item["compound"]]

    # if not name was found, throw an error
    if len(mat) == 0:
        DEBUG.printError("Compound %s not found" % compound_name,
                         inspect.stack())
        return [0], [0]
    else:
        mat = mat[0]

    if verbose > 0:
        s = "TransmissionSpectra.py:import_transmission_data: Found this item for element %s: %s" % (
            compound_name, str(mat))
        DEBUG.verbose(s, verbose, 1)

    print("Importing data for compound %s" % (compound_name))

    # import data
    data = numpy.loadtxt(path + "/" + mat["filename"],
                         comments="#",
                         delimiter=",")
    wl = data[:, 0]
    tr = data[:, 1]

    if mat["wl_unit"] == "nm":
        wl_nm = wl
        wl_um = wl / 1000
    elif mat["wl_unit"] == "um":
        wl_nm = 1000 * wl
        wl_um = wl

    if mat["tr_unit"] == "pct":
        tr /= 100

    return wl_nm, tr
Exemplo n.º 4
0
def import_transmission_data(compound_name, verbose=0):
    """
    Takes a name for a material and outputs the wavelength axis (in eV) and the absorption for 1 micron.
    
    INPUT:
    material: name of material. The data for the gas has to be in '/Data/HenkeSolidTransmission/' and in the python file there. 
    
    OUTPUT:
    - e_ev (ndarray): ev axis
    - tr_norm (ndarray): transmission, normalized to 1 micron
    
    CHANGELOG:
    
    """
    # find path
    path = NPCTools.Data.HenkeSolidTransmission.HenkeSolidData.data_path()

    # convert to title case
    compound_name = compound_name.title()
    files_list = NPCTools.Data.HenkeSolidTransmission.HenkeSolidData.files_list(
    )

    # find the name in the list
    mat = [item for item in files_list if compound_name in item["compound"]]

    # if not name was found, throw an error
    if len(mat) == 0:
        DEBUG.printError("Compound %s not found" % compound_name,
                         inspect.stack())
        return [0], [0]
    else:
        mat = mat[0]

    if verbose > 0:
        s = "HenkeSolids.py:import_transmission_data: Found this item for element %s: %s" % (
            compound_name, str(mat))
        DEBUG.verbose(s, verbose, 1)

    print("Importing data for compound %s" % (compound_name))

    # import data
    data = numpy.loadtxt(path + "/" + mat["filename"], skiprows=2)
    e_ev = data[:, 0]
    tr = data[:, 1]

    # normalize
    ab = numpy.log10(tr)
    ab /= mat["um"]
    tr_norm = 10**ab

    return e_ev, tr_norm
Exemplo n.º 5
0
def execute(args):

    if args.skip1 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase(
            Test_coefficient_file)
        unittest.TextTestRunner(verbosity=1).run(suite)
    else:
        DEBUG.verbose("Skipping :" + suite_list[0], True)

    if args.skip2 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase(Test_data_n_file)
        unittest.TextTestRunner(verbosity=1).run(suite)
    else:
        DEBUG.verbose("Skipping :" + suite_list[1], True)

    if args.skip3 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase(Test_data_nk_file)
        unittest.TextTestRunner(verbosity=1).run(suite)
    else:
        DEBUG.verbose("Skipping :" + suite_list[2], True)

    if args.skip4 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase(
            Test_string_to_ncol)
        unittest.TextTestRunner(verbosity=1).run(suite)
    else:
        DEBUG.verbose("Skipping :" + suite_list[3], True)
Exemplo n.º 6
0
def get_reflectance(paf1="air",
                    paf2="",
                    wl_um=[],
                    um_range=[0.3, 0.6],
                    a_deg=[],
                    a_range=(0, 90),
                    n_steps=100,
                    interpolate_kind="default",
                    verbose=0):
    """
    Import a file from RefractiveIndex.info and output the refractive index for the desired wavelengths. 
    
    
    INPUT:
    paf (str): path and filename
    wl_um (ndarray): wavelength axis, in micrometer
    um_range (list with 2 elements): if wl_um is not given, it will plot a range.
    n_steps (int): number of steps to plot the range.
    ax (plt axis): if False, it will make a new figure
    interpolate_kind (str): for tabulated data, the type of interpolation
    
    """
    if len(wl_um) == 0:
        wl_um = numpy.linspace(um_range[0], um_range[1], num=n_steps)

    # material 1
    if paf1 in ["", "air"]:
        n1 = numpy.ones(len(wl_um))
    elif type(paf1) == float:
        n1 = numpy.ones(len(wl_um)) * paf1
    else:
        temp = paf1.split("/")
        DEBUG.verbose("Importing data for %s by %s" %
                      (temp[-2], temp[-1][:-4]),
                      verbose_level=1)
        db_record = RIRY.import_refractive_index(paf=paf1, verbose=verbose)
        DEBUG.verbose("  Imported data", verbose_level=0)
        n1 = ri_for_wavelengths(db_record, wl_um, verbose=verbose)

    # material 1
    if paf2 in ["", "air"]:
        n2 = numpy.ones(len(wl_um))
    elif type(paf2) == float:
        n2 = numpy.ones(len(wl_um)) * paf2
    else:
        temp = paf2.split("/")
        DEBUG.verbose("Importing data for %s by %s" %
                      (temp[-2], temp[-1][:-4]),
                      verbose_level=1)
        db_record = RIRY.import_refractive_index(paf=paf2, verbose=verbose)
        DEBUG.verbose("  Imported data", verbose_level=0)
        n2 = ri_for_wavelengths(db_record, wl_um, verbose=verbose)

    a_deg, Rs, Rp = EQ.reflectance(n1,
                                   n2,
                                   a_deg=[],
                                   a_range=a_range,
                                   n_steps=-1)

    return wl_um, a_deg, Rs, Rp
Exemplo n.º 7
0
def interpolate_data(original_x, original_y, new_x, interpolate_kind = "default", verbose = 0):
    """
    Interpolate data 
    
    kind = Specifies the kind of interpolation as a string ('linear', 'nearest', 'zero', 'slinear', 'quadratic, 'cubic', where 'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of first, second or third order) or as an integer specifying the order of the spline interpolator to use. Default is 'linear'
    """    
    
    if interpolate_kind == "default":
        interpolate_kind = "linear"
    
    DEBUG.verbose("  Interpolating data using %s" % (interpolate_kind), verbose_level = 1)
    
    f = interp1d(original_x, original_y, kind = interpolate_kind)
    new_y = f(new_x)    

    return new_y
Exemplo n.º 8
0
def import_absorption_data(gas_name, verbose=0):
    """
    Takes a name for a gas and outputs the wavelength axis (in eV) and the absorption for 1 mbar and 1 cm path length.
    
    INPUT:
    gas_name: name of gas. The data for the gas has to be in '/Data/HenkeGasTransmission/' and in the python file there. 
    
    OUTPUT:
    - ev (ndarray): ev axis
    - absorption (ndarray): absorption, normalized to 1 mbar and 1 cm
    
    CHANGELOG:
    
    """
    # find path
    path = NPCTools.Data.HenkeGasTransmission.HenkeGasData.data_path()

    # convert to title case
    gas_name = gas_name.title()
    files_list = NPCTools.Data.HenkeGasTransmission.HenkeGasData.files_list()
    gas = [item for item in files_list if item["gas"] == gas_name]

    if len(gas) == 0:
        DEBUG.printError("Gas %s not found" % gas_name, inspect.stack())
        return [0], [0]
    else:
        gas = gas[0]

    if verbose > 0:
        s = "HenkeGas.py:import_absorption_data: Found this item for gas %s: %s" % (
            gas_name, str(gas))
        DEBUG.verbose(s, verbose, 1)

    print("Importing data for %s gas" % (gas_name))

    data = numpy.loadtxt(path + "/" + gas["filename"], skiprows=2)
    ev = data[:, 0]
    transmission = data[:, 1]
    absorption = numpy.log10(transmission)

    # normalize to 1 mbar and 1 cm
    absorption /= gas["mbar"]
    absorption /= gas["cm"]

    return ev, absorption
Exemplo n.º 9
0
def n_k_for_wavelengths(db_record,
                        wl_um,
                        interpolate_kind="default",
                        verbose=0):
    """
    Calculate the refractive index and extinction coefficient for wavelengths wl_um. The input is the data from refractiveindex.info and comes as one of 9 equations (not all of them are implemented) or as a table of values. For the latter interpolation will be used to get the values for the asked wavelengths. 
    
    db_record is the dictionary.
      
    """

    if "type" not in db_record:
        raise KeyError(
            "ri_for_wavelengths(): The database record does not have a key 'type'."
        )

    wl_um = CF.make_numpy_ndarray(wl_um)

    if db_record["type"] == "tabulated nk":

        if wl_um[0] < db_record["data"][:, 0][0]:
            raise ValueError(
                "Error, wavelength %1.2f micron is too low! It should be above %1.2f micron."
                % (wl_um[0], db_record["data"][:, 0][0]))
        elif wl_um[-1] > db_record["data"][:, 0][-1]:
            raise ValueError(
                "Error, wavelength %1.2f micron is too high! It should be below %1.2f micron."
                % (wl_um[-1], db_record["data"][:, 0][-1]))

        DEBUG.verbose("  Tabulated data (type nk)", verbose_level=1)
        n = MATH.interpolate_data(db_record["data"][:, 0],
                                  db_record["data"][:, 1], wl_um)
        k = MATH.interpolate_data(db_record["data"][:, 0],
                                  db_record["data"][:, 2], wl_um)

    else:
        raise NotImplementedError(
            "Importing n and k are only implemented for tabulated records.")

    return n, k
Exemplo n.º 10
0
def execute(args):
    
    if args.skip1 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase(Test_debug)
        unittest.TextTestRunner(verbosity=1).run(suite)    
    else:
        DEBUG.verbose("Skipping :" + suite_list[0], True)
        
    if args.skip2 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase(Test_format_print)
        unittest.TextTestRunner(verbosity=1).run(suite)    
    else:
        DEBUG.verbose("Skipping: " + suite_list[1], True)
        
    if args.skip3 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase(Test_format_key)
        unittest.TextTestRunner(verbosity=1).run(suite)    
    else:
        DEBUG.verbose("Skipping: " + suite_list[2], True)  
Exemplo n.º 11
0
def execute(args):
    
    if args.skip1 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase( Test_make_numpy_ndarray)
        unittest.TextTestRunner(verbosity=1).run(suite)    
    else:
        DEBUG.verbose("Skipping :" + suite_list[0], True)
        
    if args.skip2 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase( Test_string_with_numbers_to_list)
        unittest.TextTestRunner(verbosity=1).run(suite)    
    else:
        DEBUG.verbose("Skipping :" + suite_list[1], True)

    if args.skip3 == False:
        suite = unittest.TestLoader().loadTestsFromTestCase( Test_find_index_for_value)
        unittest.TextTestRunner(verbosity=1).run(suite)    
    else:
        DEBUG.verbose("Skipping :" + suite_list[2], True)
Exemplo n.º 12
0
def fit(x_array, y_array, function, A_start, return_all = False):
    """
    Fit data
    
    20101209/RB: started
    20130131/RB: imported in Crocodile, added example to doc-string

    INPUT:
    x_array: the array with time or something
    y-array: the array with the values that have to be fitted
    function: one of the functions, in the format as in the file "Equations"
    A_start: a starting point for the fitting
    return_all: the function used to return only the final result. The leastsq method does however return more data, which may be useful for debugging. When the this flag is True, it will return these extras as well. For legacy purposes the default is False. See reference of leastsq method for the extra output: http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.leastsq.html
    
    OUTPUT:
    A_final: the final parameters of the fitting
    When return_all == True:
    - cov_x (ndarray): Uses the fjac and ipvt optional outputs to construct an estimate of the jacobian around the solution. None if a singular matrix encountered (indicates very flat curvature in some direction). This matrix must be multiplied by the residual variance to get the covariance of the parameter estimates - see curve_fit.
    - infodict (dict): a dictionary of optional outputs with the key s:
        - "nfev" : the number of function calls
        - "fvec" : the function evaluated at the output
        - "fjac" : A permutation of the R matrix of a QR
                 factorization of the final approximate
                 Jacobian matrix, stored column wise.
                 Together with ipvt, the covariance of the
                 estimate can be approximated.
        - "ipvt" : an integer array of length N which defines
                 a permutation matrix, p, such that
                 fjac*p = q*r, where r is upper triangular
                 with diagonal elements of nonincreasing
                 magnitude. Column j of p is column ipvt(j)
                 of the identity matrix.
        - "qtf"  : the vector (transpose(q) * fvec).
    - mesg (str): A string message giving information about the cause of failure.
    - ier (int): An integer flag. If it is equal to 1, 2, 3 or 4, the solution was found. Otherwise, the solution was not found. In either case, the optional output variable "mesg" gives more information.


    EXAMPLE:
    Fit some data to this function from Crocodile.Resources.Equations:
    def linear(A, t):
        return A[0] + A[1] * t  
    
    ### 
    x = x-axis
    y = some data
    A = [0,1] # initial guess
    A_final = fit(x, y, Crocodile.Resources.Equations.linear, A)
    ###
    
    WARNING:
    Always check the result, it might sometimes be sensitive to a good starting point.

    """
    if scipy_import:
        param = (x_array, y_array, function)
    
        A_final, cov_x, infodict, mesg, ier = leastsq(minimize, A_start, args=param, full_output=True)

        if return_all:
            return A_final, cov_x, infodict, mesg, ier
        else:
            return A_final
    else:
        DEBUG.printError("Scipy.leastsq is not loaded. Fit is not done", inspect.stack())
        return False
Exemplo n.º 13
0
 def printError(self, string, location=[]):
     DEBUG.printError(string, location)
Exemplo n.º 14
0
def import_transmission_data(compound_name, wl_range=(), verbose=0):
    """
    Takes a name for a material and outputs the wavelength axis (in eV) and the absorption for 1 micron.
    
    INPUT:
    material: name of material. The data for the gas has to be in '/Data/TransmissionSpectra/' and in the python file there. 
    
    OUTPUT:
    - wl_nm (ndarray): wavelength axis
    - tr_norm (ndarray): transmission, normalized to 1 mm
    
    CHANGELOG:
    
    """
    # find path
    path = NPCTools.Data.TransmissionSpectra.TransmissionSpectraData.data_path(
    )

    # convert to title case
    compound_name = compound_name.lower()
    files_list = NPCTools.Data.TransmissionSpectra.TransmissionSpectraData.files_list(
    )

    # find the name in the list
    mat = [item for item in files_list if compound_name in item["compound"]]

    # if not name was found, throw an error
    if len(mat) == 0:
        DEBUG.printError("Compound %s not found" % compound_name,
                         inspect.stack())
        return [0], [0]
    else:
        mat = mat[0]

    if verbose > 0:
        s = "TransmissionSpectra.py:import_transmission_data: Found this item for element %s: %s" % (
            compound_name, str(mat))
        DEBUG.verbose(s, verbose, 1)

    print("Importing data for compound %s" % (compound_name))

    # import data
    data = numpy.loadtxt(path + "/" + mat["filename"],
                         comments="#",
                         delimiter=",")
    wl = data[:, 0]
    tr = data[:, 1]

    if wl[0] > wl[-1]:
        wl = wl[::-1]
        tr = tr[::-1]

    if mat["wl_unit"] == "nm":
        wl_nm = wl
        wl_um = wl / 1000
    elif mat["wl_unit"] == "um":
        wl_nm = 1000 * wl
        wl_um = wl

    temp = numpy.where(wl_um <= wl_range[0])[0]
    if len(temp) > 0:
        wl_nm = wl_nm[temp[-1]:]
        wl_um = wl_um[temp[-1]:]
        tr = tr[temp[-1]:]

    temp = numpy.where(wl_um >= wl_range[1])[0]
    if len(temp) > 0:
        wl_nm = wl_nm[:temp[0]]
        wl_um = wl_um[:temp[0]]
        tr = tr[:temp[0]]

    a_deg = [0]

    path_to_ri_database = "/Users/rbloem/Developer/NPCTools/Data/RefractiveIndexDB/"
    paf = path_to_ri_database + mat["refractive_index_path"]

    # air -> material
    wl_um, a_deg, Rs, Rp = RI.get_reflectance(paf2=paf,
                                              wl_um=wl_um,
                                              a_deg=a_deg)

    Rs = Rs[0, :]
    Rp = Rp[0, :]

    if mat["tr_unit"] == "pct":
        tr /= 100

    R = (1 - Rs)**2
    absorption_component = tr / R  #(1 - R)
    abs = -numpy.log10(absorption_component)
    abs_mm = abs / mat["mm"]

    numpy.putmask(abs_mm, abs_mm < 0, 0)

    return wl_nm, abs_mm, Rs, Rp
Exemplo n.º 15
0
 def printWarning(self, string, location=[]):
     DEBUG.printWarning(string, location)
Exemplo n.º 16
0
def ri_for_wavelengths(db_record,
                       wl_um,
                       interpolate_kind="default",
                       verbose=0):
    """
    Calculate the refractive index for wavelengths wl_um. The input is the data from refractiveindex.info and comes as one of 9 equations (not all of them are implemented) or as a table of values. For the latter interpolation will be used to get the values for the asked wavelengths. 
    
    db_record is the dictionary.
      
    """

    if "type" not in db_record:
        raise KeyError(
            "ri_for_wavelengths(): The database record does not have a key 'type'."
        )

    wl_um = CF.make_numpy_ndarray(wl_um)

    error_string = "Calculation of the refractive index is not implemented for "

    # check the range
    if "formula" in db_record["type"]:

        #         temp = numpy.where(wl_um < db_record["range"][0])[0]
        #         print(temp)
        #         wl_um[temp] = numpy.nan
        #
        #         temp = numpy.where(wl_um > db_record["range"][1])[0]
        #         print(temp)
        #         wl_um[temp] = numpy.nan
        print(db_record["range"][0])
        if wl_um[0] < db_record["range"][0]:
            raise ValueError(
                "Error, wavelength %1.2f micron is too low! It should be above %1.2f micron."
                % (wl_um[0], db_record["range"][0]))
        elif wl_um[-1] > db_record["range"][1]:
            raise ValueError(
                "Error, wavelength %1.2f micron is too high! It should be below %1.2f micron."
                % (wl_um[-1], db_record["range"][-1]))

    if "tabulated" in db_record["type"]:
        if wl_um[0] < db_record["data"][:, 0][0]:
            raise ValueError(
                "Error, wavelength %1.2f micron is too low! It should be above %1.2f micron."
                % (wl_um[0], db_record["data"][:, 0][0]))
        elif wl_um[-1] > db_record["data"][:, 0][-1]:
            raise ValueError(
                "Error, wavelength %1.2f micron is too high! It should be below %1.2f micron."
                % (wl_um[-1], db_record["data"][:, 0][-1]))

    if db_record["type"] == "formula 1":
        DEBUG.verbose("  Using formula 1 to calculate refractive indices",
                      verbose_level=1)
        n_terms = int(len(db_record["coefficients"]) / 2 - 0.5)
        ri = numpy.ones(len(wl_um)) + db_record["coefficients"][0]
        l = wl_um**2
        for i in range(n_terms):
            ri += (db_record["coefficients"][2 * i + 1] *
                   l) / (l - db_record["coefficients"][2 * i + 2]**2)
        ri = numpy.sqrt(ri)
        if verbose >= 1:
            for i in range(len(wl_um)):
                print(i, wl_um[i], ri[i])

    elif db_record["type"] == "formula 2":
        DEBUG.verbose("  Using formula 2 to calculate refractive indices",
                      verbose_level=1)
        n_terms = int(len(db_record["coefficients"]) / 2 - 0.5)
        ri = numpy.ones(len(wl_um)) + db_record["coefficients"][0]
        l = wl_um**2
        for i in range(n_terms):
            ri += (db_record["coefficients"][2 * i + 1] *
                   l) / (l - db_record["coefficients"][2 * i + 2])
        ri = numpy.sqrt(ri)

        if verbose >= 1:
            for i in range(len(wl_um)):
                print(i, wl_um[i], ri[i])

    elif db_record["type"] == "formula 3":
        DEBUG.verbose("  Using formula 3 to calculate refractive indices",
                      verbose_level=1)
        n_terms = int(len(db_record["coefficients"]) / 2 - 0.5)
        ri = numpy.zeros(len(wl_um)) + db_record["coefficients"][0]
        for i in range(n_terms):
            ri += db_record["coefficients"][
                2 * i + 1] * wl_um**db_record["coefficients"][2 * i + 2]
        ri = numpy.sqrt(ri)
        if verbose >= 1:
            for i in range(len(wl_um)):
                print(i, wl_um[i], ri[i])

    elif db_record["type"] == "formula 4":
        DEBUG.verbose("  Using formula 4 to calculate refractive indices",
                      verbose_level=1)
        ri = numpy.zeros(len(wl_um)) + db_record["coefficients"][0]
        n_coeff = len(db_record["coefficients"])
        if n_coeff >= 5:
            ri += (db_record["coefficients"][1] *
                   wl_um**db_record["coefficients"][2]) / (
                       wl_um**2 - db_record["coefficients"][3]**
                       db_record["coefficients"][4])
        if n_coeff >= 9:
            ri += (db_record["coefficients"][5] *
                   wl_um**db_record["coefficients"][6]) / (
                       wl_um**2 - db_record["coefficients"][7]**
                       db_record["coefficients"][8])
        n_terms = int((len(db_record["coefficients"]) - 9) / 2)
        for i in range(n_terms):
            ri += db_record["coefficients"][
                2 * i + 9] * wl_um**db_record["coefficients"][2 * i + 10]
        ri = numpy.sqrt(ri)
        if verbose >= 1:
            for i in range(len(wl_um)):
                print(i, wl_um[i], ri[i])

    elif db_record["type"] == "formula 5":
        DEBUG.verbose("  Using formula 5 to calculate refractive indices",
                      verbose_level=1)
        n_terms = int(len(db_record["coefficients"]) / 2 - 0.5)
        ri = numpy.zeros(len(wl_um)) + db_record["coefficients"][0]
        for i in range(n_terms):
            ri += db_record["coefficients"][
                2 * i + 1] * wl_um**db_record["coefficients"][2 * i + 2]
        if verbose >= 1:
            for i in range(len(wl_um)):
                print(i, wl_um[i], ri[i])

    elif db_record["type"] == "formula 6":
        DEBUG.verbose("  Using formula 6 to calculate refractive indices",
                      verbose_level=1)
        n_terms = int(len(db_record["coefficients"]) / 2 - 0.5)
        ri = numpy.ones(len(wl_um)) + db_record["coefficients"][0]
        l = wl_um**-2
        for i in range(n_terms):
            ri += (db_record["coefficients"][2 * i + 1]) / (
                db_record["coefficients"][2 * i + 2] - l)
        if verbose >= 1:
            for i in range(len(wl_um)):
                print(i, wl_um[i], ri[i])

    elif db_record["type"] == "formula 7":
        DEBUG.verbose("  Using formula 7 to calculate refractive indices",
                      verbose_level=1)
        l = wl_um**2
        n_terms = len(db_record["coefficients"]) - 3
        t1 = db_record["coefficients"][1] / (l - 0.028)
        t2 = db_record["coefficients"][2] * (1 / (l - 0.028))**2
        ri = db_record["coefficients"][0] + t1 + t2
        for i in range(n_terms):
            ri += db_record["coefficients"][i + 3] * l**(i + 1)
        if verbose >= 1:
            for i in range(len(wl_um)):
                print(i, wl_um[i], ri[i])

    elif db_record["type"] == "formula 8":
        raise NotImplementedError(error_string + "formula 8")

    elif db_record["type"] == "formula 9":
        raise NotImplementedError(error_string + "formula 9")

    elif db_record["type"] == "tabulated n":
        DEBUG.verbose("  Tabulated data (type n)", verbose_level=1)
        ri = MATH.interpolate_data(db_record["data"][:, 0],
                                   db_record["data"][:, 1], wl_um)

    elif db_record["type"] == "tabulated nk":
        DEBUG.verbose("  Tabulated data (type nk)", verbose_level=1)
        ri = MATH.interpolate_data(db_record["data"][:, 0],
                                   db_record["data"][:, 1], wl_um)

    else:
        raise ValueError(
            "The type of data in the database record is unknown (usually formula 1-9 or tabulated data). Type here is %s."
            % db_record["type"])

    return ri
Exemplo n.º 17
0
def gvd_for_wavelengths(db_record,
                        wl_um,
                        interpolate_kind="default",
                        verbose=0):
    """
    Calculate the GVD for wavelengths wl_um. The GVD is calculated as the second derivative of the refractive index with respect to the wavelength. The input is the data from refractiveindex.info and comes as one of 9 equations (not all of them are implemented) or as a table of values. 
    
    For the equations, the second derivatives were calculated using WolframAlpha. 
    """

    if "type" not in db_record:
        raise KeyError(
            "gvd_for_wavelengths: The database record does not have a key 'type'."
        )

    wl_um = CF.make_numpy_ndarray(wl_um)

    error_string = "GVD is not implemented for "

    # check the range
    if "formula" in db_record["type"]:
        if wl_um[0] < db_record["range"][0]:
            raise ValueError(
                "Error, wavelength %1.2f micron is too low! It should be above %1.2f micron."
                % (wl_um[0], db_record["range"][0]))
        elif wl_um[-1] > db_record["range"][1]:
            raise ValueError(
                "Error, wavelength %1.2f micron is too high! It should be below %1.2f micron."
                % (wl_um[-1], db_record["range"][-1]))

    if "tabulated" in db_record["type"]:
        raise NotImplementedError(
            "GVD can't be calculated for tabulated data.")

    if db_record["type"] == "formula 1":
        DEBUG.verbose(
            "  Using formula 1 to calculate group velocity dispersion",
            verbose_level=1)
        gvd = EQ.gvd_formula_1(wl_um, db_record["coefficients"])
        gvd = (1e21 * gvd * wl_um**3) / (2 * numpy.pi * (CONST.c_ms)**2)

    elif db_record["type"] == "formula 2":
        """
        Formula 2 is the same as formula 1, but some given coefficients are already squared. The square root of these coefficients is taken and the GVD equation for formula 1 is used. 
        """
        DEBUG.verbose(
            "  Using formula 2 to calculate group velocity dispersion",
            verbose_level=1)
        s = numpy.copy(db_record["coefficients"])
        for i in range(len(s)):
            if i > 0 and i % 2 == 0:
                s[i] = numpy.sqrt(s[i])
        gvd = EQ.gvd_formula_1(wl_um, s)
        gvd = (1e21 * gvd * wl_um**3) / (2 * numpy.pi * (CONST.c_ms)**2)

    elif db_record["type"] == "formula 3":
        DEBUG.verbose(
            "  Using formula 3 to calculate group velocity dispersion",
            verbose_level=1)
        gvd = EQ.gvd_formula_3(wl_um, db_record["coefficients"])
        gvd = (1e21 * gvd * wl_um**3) / (2 * numpy.pi * (CONST.c_ms)**2)

    elif db_record["type"] == "formula 4":
        DEBUG.verbose(
            "  Using formula 4 to calculate group velocity dispersion",
            verbose_level=1)
        gvd = EQ.gvd_formula_4(wl_um, db_record["coefficients"])
        gvd = (1e21 * gvd * wl_um**3) / (2 * numpy.pi * (CONST.c_ms)**2)

    elif db_record["type"] == "formula 5":
        DEBUG.verbose(
            "  Using formula 5 to calculate group velocity dispersion",
            verbose_level=1)
        gvd = EQ.gvd_formula_5(wl_um, db_record["coefficients"])
        gvd = (1e21 * gvd * wl_um**3) / (2 * numpy.pi * (CONST.c_ms)**2)

    elif db_record["type"] == "formula 6":
        DEBUG.verbose(
            "  Using formula 6 to calculate group velocity dispersion",
            verbose_level=1)
        gvd = EQ.gvd_formula_6(wl_um, db_record["coefficients"])
        gvd = (1e21 * gvd * wl_um**3) / (2 * numpy.pi * (CONST.c_ms)**2)

    elif db_record["type"] == "formula 7":
        DEBUG.verbose(
            "  Using formula 7 to calculate group velocity dispersion",
            verbose_level=1)
        gvd = EQ.gvd_formula_7(wl_um, db_record["coefficients"])
        gvd = (1e21 * gvd * wl_um**3) / (2 * numpy.pi * (CONST.c_ms)**2)

    elif db_record["type"] == "formula 8":
        raise NotImplementedError(error_string + "formula 8")

    elif db_record["type"] == "formula 9":
        raise NotImplementedError(error_string + "formula 9")

    else:
        raise ValueError(
            "The type of data in the database record is unknown (usually formula 1-9). Type here is %s."
            % db_record["type"])

    return wl_um, gvd
Exemplo n.º 18
0
 def verbose(self, string, flag_verbose):
     DEBUG.verbose(string, flag_verbose)