Skip to content

Material Handler

material_handler

Handles the processing of material data from various sources.

Parameters:

Name Type Description Default
links str or list

The link(s) to the material data source(s).

required

Returns:

Type Description
dict

A dictionary containing the processed material data and information.

Source code in yasfpy/functions/material_handler.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def material_handler(links):
    """
    Handles the processing of material data from various sources.

    Args:
        links (str or list): The link(s) to the material data source(s).

    Returns:
        (dict): A dictionary containing the processed material data and information.

    """
    if not isinstance(links, list):
        links = [links]

    data = dict(ref_idx=pd.DataFrame(columns=["wavelength", "n", "k"]), material=None)
    for link in links:
        link = link.strip()
        if link[:4] == "http":
            if "refractiveindex.info" in link:
                df, material = handle_refractiveindex_info(link)
                data["ref_idx"] = pd.concat([data["ref_idx"], df])
                data["material"] = material
            elif "http://eodg.atm.ox.ac.uk" in link:
                df, material = handle_eodg(link)
                data["ref_idx"] = pd.concat([data["ref_idx"], df])
                data["material"] = material
            else:
                print("No matching handler found for url")
        else:
            if ".csv" in link:
                df, material = handle_csv(link)
                data["ref_idx"] = pd.concat([data["ref_idx"], df])
                data["material"] = material
            else:
                print("No matching handler found for file type")
    # data['ref_idx'] = data['ref_idx'].sort_values(by=['wavelength'])
    return data

handle_refractiveindex_info

Retrieves refractive index data from a given URL and processes it.

Parameters:

Name Type Description Default
url str

The URL to retrieve the refractive index data from.

required

Returns:

Type Description
tuple

A tuple containing the processed data as a pandas DataFrame and the material name.

Raises:

Type Description
Exception

If the data retrieval fails.

Source code in yasfpy/functions/material_handler.py
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def handle_refractiveindex_info(url):
    """
    Retrieves refractive index data from a given URL and processes it.

    Args:
        url (str): The URL to retrieve the refractive index data from.

    Returns:
        (tuple): A tuple containing the processed data as a pandas DataFrame and the material name.

    Raises:
        Exception: If the data retrieval fails.

    """
    url_split = url.replace("=", "/").split("/")
    material = unquote(url_split[-2])

    if np.any([("data_csv" in part) or ("data_txt" in part) for part in url_split]):
        print("Please use the [Full database record] option for refractiveindex.info!")
        print("Reverting url:")
        print(f" from: {url}")
        url_split[3] = "database"
        url = "/".join(url_split)
        print(f" to:   {url}")

    # req = urllib.request.Request(url)
    # with urllib.request.urlopen(req) as resp:
    resp = req.get(url)
    if resp.status_code >= 400:
        raise Exception(f"Failed to retrieve data from {url}")
    # data = resp.read()
    # data = data.decode("utf-8")
    data = resp.text
    data_yml = yaml.safe_load(data)
    header_yml = ["wavelength", "n", "k"]
    data = pd.DataFrame(columns=["wavelength", "n", "k"])
    for line in data_yml["DATA"]:
        df = None
        if "tabulated" in line["type"].lower():
            # elif line['type'].lower()[-2:] == ' n':
            #   header_yml=['wavelength', 'n']
            if line["type"].lower()[-2:] == " k":
                header_yml = ["wavelength", "k", "n"]
            df = pd.read_csv(
                io.StringIO(line["data"]),
                delim_whitespace=True,
                header=None,
                names=header_yml,
            )
        elif "formula" in line["type"].lower():
            if line["type"].lower() == "formula 1":
                wavelengths = [float(c) for c in line["wavelength_range"].split()]
                wavelengths = np.arange(wavelengths[0], wavelengths[1], 0.1)
                coefficients = np.array(
                    [float(c) for c in line["coefficients"].split()]
                )
                ref_idx = lambda x: np.sqrt(
                    1
                    + np.sum(
                        [
                            coefficients[i]
                            * x**2
                            / (x**2 - coefficients[i + 1] ** 2)
                            for i in range(1, len(coefficients), 2)
                        ],
                        axis=0,
                    )
                )
                df = pd.DataFrame(columns=["wavelength", "n", "k"])
                df["wavelength"] = wavelengths
                df["n"] = ref_idx(wavelengths)

        if df is not None:
            df = df.fillna(0)
            data = pd.concat([data, df])

    return data, material

handle_eodg

Handles the EODG material data retrieval from a given URL.

Parameters:

Name Type Description Default
url str

The URL of the EODG material data.

required

Returns:

Type Description
tuple

A tuple containing the retrieved material data and the material name.

Raises:

Type Description
Exception

If the data retrieval from the URL fails.

Source code in yasfpy/functions/material_handler.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def handle_eodg(url):
    """
    Handles the EODG material data retrieval from a given URL.

    Args:
        url (str): The URL of the EODG material data.

    Returns:
        (tuple): A tuple containing the retrieved material data and the material name.

    Raises:
        Exception: If the data retrieval from the URL fails.
    """
    url_split = url.split("/")
    material = unquote(url_split[6])

    resp = req.get(url)
    if resp.status_code >= 400:
        raise Exception(f"Failed to retrieve data from {url}")
    data = resp.text
    data_format = [
        s.lower() for s in re.search(r"#FORMAT=(.*)\n", data).group(1).split()
    ]
    header_yml = ["wavelength", "n", "k"]
    if "n" not in data_format:
        header_yml = ["wavelength", "k", "n"]

    data = re.sub(r"^#.*\n", "", data, flags=re.MULTILINE)
    data = pd.read_csv(
        io.StringIO(data), delim_whitespace=True, header=None, names=header_yml
    )
    data = data.fillna(0)
    if "wavn" in data_format:
        data["wavelength"] = 1e4 / data["wavelength"]
        data = data.iloc[::-1]

    return data, material

handle_csv

Read a CSV file containing material data and extract the material name and data.

Parameters:

Name Type Description Default
path str

The path to the CSV file.

required

Returns:

Type Description
tuple

A tuple containing the material data as a pandas DataFrame and the material name.

Source code in yasfpy/functions/material_handler.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def handle_csv(path):
    """
    Read a CSV file containing material data and extract the material name and data.

    Args:
        path (str): The path to the CSV file.

    Returns:
        (tuple): A tuple containing the material data as a pandas DataFrame and the material name.
    """
    name = re.split(r"\._-", path)
    material = unquote(name[0])
    data = pd.read_csv(
        path, delim_whitespace=False, header=0, names=["wavelength", "n", "k"]
    )
    return data, material

Comments