Files
spectro/spectro.py
T
2026-10-09 10:53:44 +08:00

106 lines
3.1 KiB
Python

import math
class LightDir:
alpha = -1
beta = -1
gamma = -1
def __init__(self, a, b, g):
self.alpha = a
self.beta = b
self.gamma = g
class LightWaveVec:
wavenum = 0.0
direction = LightDir(-1, -1, -1)
def __init__(self, wave_num, wave_dir):
self.wavenum = wave_num
self.direction = wave_dir
def diffracted_light(incident_light, diffraction_order, grating_constant, is_reflected_grating=True):
ans = []
in_alpha = incident_light.direction.alpha
dif_beta = incident_light.direction.beta
dif_wavenum = incident_light.wavenum
# The case of tmp_gamma == 1 or tmp_alpha == 0 are almost invisible in matplotlib
# I guess it's OK to ignore them when they appear as 1.0000001 or -0.000001
# I KNOW IT'S NOT OK NOW
def try_diffract(cos_gamma):
# FLOAT ERROR
if math.fabs(cos_gamma) <= 1 + 1e-12:
cos_gamma = max(-1.0, min(1.0, cos_gamma))
if (math.fabs(cos_gamma) <= 1): # to ensure diffracted light can be solved
dif_gamma = math.acos(cos_gamma)
cos2_alpha = 1 - math.cos(dif_beta)**2 - math.cos(dif_gamma)**2
# FLOAT ERROR
if cos2_alpha >= -1e-12:
cos2_alpha = max(cos2_alpha, 0.0)
if (cos2_alpha >= 0): # to ensure diffracted light can be solved
if (is_reflected_grating):
dif_alpha = math.acos(- math.copysign(
math.sqrt(cos2_alpha), math.cos(in_alpha)))
else:
dif_alpha = math.acos(math.copysign(
math.sqrt(cos2_alpha), math.cos(in_alpha)))
ans.append(LightWaveVec(dif_wavenum, LightDir(
dif_alpha,
dif_beta,
dif_gamma
)))
# wavelen = 2pi/wavenum
cos_gamma_1 = math.cos(incident_light.direction.gamma) + \
diffraction_order \
* (2*math.pi / incident_light.wavenum) \
/ grating_constant
try_diffract(cos_gamma_1)
# when diffraction_order is 0, cos_gamma_2 equals to cos_gamma_1
if (diffraction_order != 0):
cos_gamma_2 = math.cos(incident_light.direction.gamma) - \
diffraction_order \
* (2*math.pi / incident_light.wavenum) \
/ grating_constant
try_diffract(cos_gamma_2)
return ans
def wavelen(gamma_i, gamma_r, diffraction_order, grating_constant):
return math.fabs(grating_constant
/ diffraction_order
* (math.cos(gamma_r) - math.cos(gamma_i)))
"""
example:
beta_i = 51.9086765665 / 180 * math.pi
gamma_i = 104.1539440993 / 180 * math.pi
alpha_i = LightDir.another_abs(beta_i, gamma_i)
light_i = LightWaveVec(2*math.pi/(370 * 10**-9),
LightDir(alpha_i, beta_i, gamma_i))
k = 1
d = 1400 * 10**-9
light_r = LightWaveVec.diffracted_light(light_i, k, d)
for l in light_r:
print("alpha_x:", math.cos(l.direction.alpha))
print("beta_y:", math.cos(l.direction.beta))
print("gamma_z:", math.cos(l.direction.gamma))
"""