Debian Codegraph @

gavo/base/spectral.py

raw
1 """
2 Spectral-related functions.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 from gavo.base import unitconv
12 from gavo.base import osinter
13 from gavo.utils import excs
14
15 from gavo.utils.dachstypes import Callable, Dict, Tuple
16
17
18 ######################## specconv
19
20 def toStdSpecUnit(fromUnit: str) -> Tuple[str, float]:
21 """returns a pair of (standard unit, factor) to turn fromUnit into
22 one of J, Hz, or m.
23
24 Unconvertable units raise a UfuncError.
25 """
26 for stdUnit in ["J", "Hz", "m"]:
27 try:
28 factor = unitconv.computeConversionFactor(fromUnit, stdUnit)
29 except unitconv.IncompatibleUnits:
30 continue
31 return stdUnit, factor
32
33 raise unitconv.IncompatibleUnits(
34 f"{fromUnit} is not a spectral unit understood here")
35
36
37 SPEC_CONVERSION = {
38 ("J", "m"): "h*c/(({expr})*{f})",
39 ("J", "Hz"): "({expr})*{f}/h",
40 ("J", "J"): "({expr})*{f}",
41 ("Hz", "m"): "c/({expr})/{f}",
42 ("Hz", "Hz"): "{f}*({expr})",
43 ("Hz", "J"): "h*{f}*({expr})",
44 ("m", "m"): "{f}*({expr})",
45 ("m", "Hz"): "c/({expr})/{f}",
46 ("m", "J"): "h*c/({expr})/{f}",}
47
48
49 def getSpecExpr(fromUnit: str, toUnit: str) -> str:
50 """returns an expression that turns a value in fromUnit to one in toUnit.
51
52 The value in fromUnit is represented by a {} so you can just .format
53 the expression it is in into the resulting string.
54 """
55 fromStd, fromFactor = toStdSpecUnit(fromUnit)
56 toStd, toFactor = toStdSpecUnit(toUnit)
57 convExpr = SPEC_CONVERSION[fromStd, toStd
58 ].replace("h", str(unitconv.PLANCK_H)
59 ).replace("c", str(unitconv.LIGHT_C))
60 return "{}/{}".format(
61 convExpr.format(f=fromFactor, expr="{}"),
62 toFactor)
63
64
65 def getSpecConverter(fromUnit: str, toUnit: str) -> Callable[[float], float]:
66 """Returns a function converting spectral values in fromUnit to toUnit.
67 """
68 return eval("lambda x: "+getSpecExpr(fromUnit, toUnit).format("x"))
69
70
71 ########### our filter library
72
73 NM = 1e-9
74
75 def getFilterMap() -> Tuple[
76 Dict[str, Tuple[float, float, float]],
77 Dict[str, str]]:
78 """returns a pair for filter_def, aliases mapping.
79
80 This parses from the built-in data/filters.txt; filter_def maps
81 filter names to tuples of lower, central, long wavelength in metres.
82 (we may add further fields later, so it's safer to [:3] these results).
83
84 Aliases just maps common filter names to our canontical names
85 for these filters.
86 """
87 filterMap, aliases = {}, {}
88
89 with osinter.openDistFile("data/filters.txt", encoding="utf-8") as f:
90 for index, line in enumerate(f):
91 if not line:
92 break
93 line = line.strip()
94 if line.startswith("#"):
95 continue
96 parts = line.split("\t")
97 primary = parts[0].strip()
98 if primary.startswith("="):
99 primary = primary[1:].strip()
100 for p in parts[1:]:
101 aliases[p.strip()] = primary
102 else:
103 try:
104 filterMap[primary] = (
105 float(parts[1])*NM, float(parts[2])*NM, float(parts[3])*NM)
106 except IndexError:
107 raise excs.ReportableError("Bad filtermap: filters.txt,"
108 " line %d."%(index+1))
109
110 return filterMap, aliases