-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuv_plotter.py
More file actions
417 lines (340 loc) · 11.6 KB
/
Copy pathuv_plotter.py
File metadata and controls
417 lines (340 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
50
51
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
129
130
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import csv
import math
import argparse
from pathlib import Path
import numpy as np
import pandas as pd
import cclib
import scipy.constants as constants
import matplotlib.pyplot as plot
from cclib.parser.utils import convertor
def extract_data_from_logs(logfile, correct_wavelength=False, wv_correction=0):
"""Extract excited state energies and oscillator strength from logfile
Fill excited_states with tuples containing wavelength in nm and oscillator strength.
"""
excited_states = list()
parser = cclib.io.ccopen(logfile)
data = parser.parse()
for wv, os in zip(data.etenergies, data.etoscs):
wv = convertor(wv, "wavenumber", "nm")
if correct_wavelength:
wv = wv + wv_correction
excited_states.append((wv, os))
return excited_states
def generate_spectrum(
excited_states, plt_range, grid_size, sigma=0.4, normalization=True
):
"""Generate gaussian functions for each excitation energy, and sum them all
- Generate a range of wavelengths to use to generate the spectrum
- At each point, compute the absorbance including the contribution of all excitations
- Normalize according to the max absorbance if necessary
- Return a 2D line ready to be plotted.
"""
# Generate the range of wavelengths
grid = range(plt_range[0], plt_range[1] + 1, grid_size)
# Generate data for each point
uv_spectrum = list()
electron_charge = 4.803204e-10
electron_mass = 9.10938e-31
cnst = (
math.sqrt(math.pi)
* electron_charge**2
* constants.Avogadro
/ (1000 * math.log(10) * constants.c**2 * electron_mass)
)
cnst = 1.3062974e8
sigma = (
np.power(10, 9) * constants.Planck * constants.c / 1.602176634e-19 / sigma
) # convert to wavenumber
for point in grid:
fit = 0.0
for wv, os in excited_states:
fit += (
cnst
* os
/ sigma
* np.exp(-np.power((10**7 / point - 10**7 / wv) / (sigma), 2))
)
uv_spectrum += [(point, fit)]
# Normalize if requested
if normalization:
max_energy = max(point[1] for point in uv_spectrum) # Retrieve max energy
uv_spectrum = [
(wavelength, energy / max_energy) for (wavelength, energy) in uv_spectrum
]
# Return final spectrum line
return uv_spectrum
def get_colorscheme():
# Setup the CIE standard, from the csv file
cmf = pd.read_csv("CIE-xyzs.csv", index_col=0, sep=";")
cmf.dropna(axis=0, inplace=True)
cmf = cmf.astype(float)
cmf.columns = ["x", "y", "z", "S"]
return cmf
def uvvis_to_xyz_color(
wavelengths, intensities, plot_grid, normalize=True, length=1, concentration=1
):
"""
Generate xyz color coordinates according to CIE 1931 standard, using a D65 illuminant
Input: UV-Vis spectrum with wavelengths in nm and absorbance absolute values
Output: xyz data
"""
cmf = get_colorscheme()
# Truncate the UV-Vis according to the CIE standard
xmin = int(min(cmf.index))
xmax = int(max(cmf.index))
spectrum = pd.DataFrame(np.column_stack((wavelengths, intensities)))
spectrum.columns = ["wavelengths", "intensities"]
truncated_spectrum = spectrum[
(xmin <= spectrum["wavelengths"]) & (spectrum["wavelengths"] <= xmax)
]
# Filter cmf where wavelengths are needed
wv_list = [int(i) for i in truncated_spectrum["wavelengths"]]
truncated_cmf = cmf.loc[wv_list]
# Convert to transmittance
if normalize:
Imin = np.min(truncated_spectrum["intensities"])
Imax = np.max(truncated_spectrum["intensities"])
new_I = (truncated_spectrum["intensities"] - Imin) / (Imax - Imin)
else:
new_I = truncated_spectrum["intensities"] * concentration * length
trs_I = np.power(10, -new_I)
X = np.sum(
trs_I.to_numpy() * truncated_cmf["S"].to_numpy() * truncated_cmf["x"].to_numpy()
)
Y = np.sum(
trs_I.to_numpy() * truncated_cmf["S"].to_numpy() * truncated_cmf["y"].to_numpy()
)
Z = np.sum(
trs_I.to_numpy() * truncated_cmf["S"].to_numpy() * truncated_cmf["z"].to_numpy()
)
den = np.sum(truncated_cmf["S"] * truncated_cmf["y"])
if den != 0.0:
X, Y, Z = X / den, Y / den, Z / den
xyz = [X, Y, Z]
return xyz
def xyz_to_RGB(xyz):
"""
Conversion of xyz coordinates into RGB coordinates.
- xyz: list: xyz coordinates.
return:
- np.array (3,): rgb coordinates.
"""
xyz = np.array(xyz).reshape(-1, 1)
M = np.array(
[
[3.2410, -1.5374, -0.4986],
[-0.9692, 1.8760, 0.0416],
[0.0556, -0.2040, 1.0570],
]
)
norm_rgb = np.dot(M, xyz)
norm_rgb[norm_rgb < 0] = 0
norm_rgb[norm_rgb > 1] = 1
rgb = np.round(norm_rgb * 255, 0)
return rgb.flatten().astype(int)
def xyz_to_Lab(xyz):
"""
Conversion of xyz coordinates into Lab coordinates.
- xyz: list: xyz coordinates.
return:
- np.array (3,): Lab coordinates.
"""
def f(T, eps):
if T > eps:
return np.power(T, 1 / 3)
return np.power(29 / 6, 2) / 3 * T + 4 / 29
eps = np.power(6 / 29, 3)
cmf = get_colorscheme()
Xref = np.sum(cmf["S"] * cmf["x"]) / np.sum(cmf["S"] * cmf["y"])
Yref = 1
Zref = np.sum(cmf["S"] * cmf["z"]) / np.sum(cmf["S"] * cmf["y"])
X, Y, Z = xyz
L = 116 * f(Y / Yref, eps) - 16
a = 500 * (f(X / Xref, eps) - f(Y / Yref, eps))
b = 200 * (f(Y / Yref, eps) - f(Z / Zref, eps))
return [L, a, b]
def parse_arguments():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(
description="UV-Vis Spectrum Plotter - Generate spectra and color coordinates from log files"
)
# File input
parser.add_argument(
"--input-dir",
type=str,
default="data/color-prediction-neutral",
help="Directory containing .log files to process",
)
parser.add_argument(
"--file", type=str, help="Single .log file to process (overrides --input-dir)"
)
# Spectrum generation parameters
parser.add_argument(
"--sigma",
type=float,
default=0.4,
help="Broadening for Gaussian functions, in eV (default: 0.4)",
)
parser.add_argument(
"--plot-range",
type=int,
nargs=2,
default=[250, 800],
metavar=("MIN", "MAX"),
help="Range of spectrum to display in nm (default: 250 800)",
)
parser.add_argument(
"--plot-grid",
type=int,
default=1,
help="Grid precision (distance between two generated points) (default: 1)",
)
parser.add_argument(
"--wv-correction",
type=int,
default=27,
help="Wavelength correction shift in nm (default: 27)",
)
# Color calculation parameters
parser.add_argument(
"--concentration",
type=float,
default=0.000275,
help="Sample concentration (default: 0.000275)",
)
parser.add_argument(
"--path-length",
type=float,
default=0.1,
help="Path length in cm (default: 0.1)",
)
# Output options
parser.add_argument(
"--write-data",
action="store_true",
default=True,
help="Write CSV data files (default: True)",
)
parser.add_argument(
"--no-write-data",
action="store_false",
dest="write_data",
help="Disable writing CSV data files",
)
parser.add_argument(
"--plot-data",
action="store_true",
default=True,
help="Generate plots (default: True)",
)
parser.add_argument(
"--no-plot-data",
action="store_false",
dest="plot_data",
help="Disable generating plots",
)
parser.add_argument(
"--generate-Lab",
action="store_true",
default=True,
help="Generate Lab color coordinates (default: True)",
)
parser.add_argument(
"--no-generate-Lab",
action="store_false",
dest="generate_Lab",
help="Disable generating Lab color coordinates",
)
parser.add_argument(
"--correct-wavelength",
action="store_true",
default=False,
help="Apply wavelength correction (default: False)",
)
parser.add_argument(
"--normalize-data",
action="store_true",
default=False,
help="Normalize data (default: False)",
)
return parser.parse_args()
### Start of main function
def main():
args = parse_arguments()
# List of files to plot
if args.file:
files_root = Path(args.file).parent
files = [Path(args.file)] if Path(args.file).suffix == ".log" else []
else:
files_root = Path(args.input_dir)
files = list()
for file in files_root.iterdir():
if file.is_file() and file.suffix == ".log":
files.append(file)
# General parameters
sigma = args.sigma
plot_range = args.plot_range
plot_grid = args.plot_grid
wv_correction = args.wv_correction
concentration = args.concentration
path_length = args.path_length
# What to do here
write_data = args.write_data
plot_data = args.plot_data
generate_Lab = args.generate_Lab
correct_wavelength = args.correct_wavelength
normalize_data = args.normalize_data
for file in files:
# Extract data and generate the line to plot
data = extract_data_from_logs(
file.as_posix(), correct_wavelength, wv_correction
)
uv_spectrum = generate_spectrum(
data, plot_range, plot_grid, sigma, normalization=normalize_data
)
# Reformat data
wavelengths = [point[0] for point in uv_spectrum]
absorbances = [point[1] for point in uv_spectrum]
absorbance_max_idx = np.argmax(absorbances)
lambda_max = wavelengths[absorbance_max_idx]
if write_data:
csv_file = Path(files_root, file.stem + ".csv")
with open(csv_file, "w") as f:
writer = csv.writer(f, delimiter=";")
writer.writerows(zip(wavelengths, absorbances))
with open(Path(files_root, file.stem + "_max.dat"), "w") as f:
f.write(file.stem + " lambda_max = " + str(lambda_max) + "\n")
if plot_data:
# Setup the plot
fig, ax = plot.subplots()
ax.set_xlabel("Wavelength (nm)")
ax.set_ylabel("Normalized absorbance")
ax.set_xlim(left=plot_range[0], right=plot_range[1])
ax.set_title(file.stem)
ax.plot(wavelengths, absorbances)
fig.show()
# Save image
img_file = Path(files_root, file.stem + ".png")
fig.savefig(img_file, dpi=300)
plot.close()
if generate_Lab:
xyz = uvvis_to_xyz_color(
wavelengths,
absorbances,
plot_grid,
normalize=normalize_data,
length=path_length,
concentration=concentration,
)
rgb = xyz_to_RGB(xyz)
Lab = xyz_to_Lab(xyz)
xyz = [str(float(i)) for i in xyz]
rgb = [str(int(i)) for i in rgb]
Lab = [str(float(i)) for i in Lab]
with open(Path(files_root, file.stem + "_color.dat"), "w") as f:
f.write(file.stem + " xyz = " + ", ".join(xyz) + "\n")
f.write(file.stem + " rgb = " + ", ".join(rgb) + "\n")
f.write(file.stem + " Lab = " + ", ".join(Lab) + "\n")
if __name__ == "__main__":
main()