radis.misc package

Submodules

Module contents

Misc. and support functions

exception DatabankNotFound[source]

Bases: FileNotFoundError

Used when a line database is not found in radis.rc.

class DatabaseProgressPrinter(database_name: str, molecule: str, verbose: int = 1, version: str = '')[source]

Bases: object

Unified progress output for database fetch operations.

Provides consistent formatting across all database operations (HITRAN, HITEMP, ExoMol, GEISA) with configurable verbose levels.

Parameters:
  • database_name (str) – Name of the database (e.g., “HITEMP”, “ExoMol”, “HITRAN”, “GEISA”)

  • molecule (str) – Molecule being fetched (e.g., “CO2”, “H2O”)

  • verbose (int or bool) – Verbosity level: - 0 or False: Silent (no output) - 1 or True: Normal output (default) - 2+: Detailed/debug output

Example

printer = DatabaseProgressPrinter("HITEMP", "CO2", verbose=1)
printer.header("Fetching 2024 database")
printer.section("Downloading")
printer.info("3 files needed, 2 cached")
with printer.progress_bar(3, "Downloading chunks") as pbar:
    for i in range(3):
        # download work
        pbar.update(1)
printer.success("Complete: Added HITEMP-CO2-2024 to radis.json")
HEADER_WIDTH = 80[source]
complete(database_entry: str = '')[source]

Print completion message.

Parameters:

database_entry (str) – Name of database entry added to radis.json

download_progress(total_bytes: int, desc: str = 'Downloading') tqdm[source]

Return a progress bar configured for download operations.

Parameters:
  • total_bytes (int) – Total download size in bytes

  • desc (str) – Description text

Returns:

Progress bar configured for byte downloads

Return type:

tqdm

download_summary(files_needed: int, files_total: int, files_cached: int = 0)[source]

Print download summary.

Parameters:
  • files_needed (int) – Number of files that need to be downloaded

  • files_total (int) – Total number of files

  • files_cached (int) – Number of files already cached

header(action: str = '', details: str = '')[source]

Print operation header with visual separator.

Parameters:
  • action (str) – Action being performed (e.g., “Fetching”, “Downloading”)

  • details (str, optional) – Additional details for the header

info(message: str, level: int = 1, indent: int = 0)[source]

Print info message if verbose >= level.

Parameters:
  • message (str) – Message to display

  • level (int) – Minimum verbose level required to show message

  • indent (int) – Indentation level (0=none, 1=bullet, 2=sub-bullet)

lines_progress(total_lines: int | None, desc: str = 'Parsing lines') tqdm[source]

Return a progress bar configured for line parsing operations.

Parameters:
  • total_lines (int or None) – Total number of lines expected (None if unknown)

  • desc (str) – Description text

Returns:

Progress bar configured for line parsing

Return type:

tqdm

parsing_progress(total_files: int, desc: str = 'Processing files') tqdm[source]

Return a progress bar configured for file parsing operations.

Parameters:
  • total_files (int) – Total number of files to process

  • desc (str) – Description text

Returns:

Progress bar configured for file processing

Return type:

tqdm

parsing_summary(lines_loaded: int, time_elapsed: float | None = None)[source]

Print parsing summary.

Parameters:
  • lines_loaded (int) – Number of lines loaded

  • time_elapsed (float, optional) – Time taken in seconds

progress_bar(total: int, desc: str = '', unit: str = 'file', unit_scale: bool = False, unit_divisor: int = 1024, leave: bool = True, position: int = 0, disable: bool | None = None) tqdm[source]

Return a configured tqdm progress bar.

Parameters:
  • total (int) – Total number of iterations

  • desc (str) – Description text for the progress bar

  • unit (str) – Unit name (e.g., “file”, “line”, “B” for bytes)

  • unit_scale (bool) – If True, scale units automatically (useful for bytes)

  • unit_divisor (int) – Divisor for unit scaling (default 1024 for bytes)

  • leave (bool) – If True, keep progress bar after completion

  • position (int) – Position for nested progress bars

  • disable (bool or None) – If True, disable progress bar. If None, use verbose level.

Returns:

Configured progress bar instance

Return type:

tqdm

section(title: str, level: int = 1)[source]

Start a new section (Download, Parse, etc.).

Parameters:
  • title (str) – Section title (e.g., “Download”, “Parsing”, “Processing”)

  • level (int) – Minimum verbose level to show this section

success(message: str)[source]

Print success message.

Parameters:

message (str) – Success message to display

warning(message: str)[source]

Print warning message.

Parameters:

message (str) – Warning message to display

class NotInstalled(name, info='')[source]

Bases: object

A class to deal with optional packages. Will raise an error only if the package is used (but not if imported only)

Examples

some function = NotInstalled("you should install C drivers")
a = some_function   # no error
a()             # will raise the NotInstalled error and display the message
class ProgressBar(N, active=True, t0=None)[source]

Bases: object

Writes completion status and expended time.

Set it up by creating the object, then calling update() and done().

Parameters:
  • N (int) – (expected) number of iterations

  • active (bool) – if False, do not show anything (tip : feed it a verbose argument)

Other Parameters:

t0 (float) – initializes starting time at t0 (useful for successive loops)

Example

add a progress bar in a loop:

pb = ProgressBar(N)
for i, ... in enumerate(...):
    (...)
    pb.update(i)
pb.done()

See test in progress_bar.py

done()[source]

Close the Progress bar.

set_active(active=True)[source]

Option to activate/deactivate the ProgressBar.

Used not to make it appear on small processes (based on a condition) without changing most of the code

update(i, modulo=1, message='')[source]

Update the completion status i/N and time spent.

Parameters:
  • i (int) – current iteration

  • modulo (int) – if higher than 1, skip some iterations.

  • message (str) – add a custom message. Tip: evaluate your own variables with f’{my_variable}’ strings

Example

array_allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=True)[source]

Returns whether a and b are all close (element wise). If not the same size, returns False (instead of crashing like the numpy version). Cf numpy.allclose docs for more information.

Parameters:
  • a, b (arrays)

  • rtol (float)

  • atol (float)

  • equal_nan (bool) – whether to consider NaN’s as equal. Contrary to the numpy version this one is set to True by default

autoturn(data, key=-1)[source]

Turns array data. key value:

  • 0 don’t transpose

  • 1 : transpose

  • -1 : auto : make sure the vectors are along the longest dimension

bining(I, ymin=None, ymax=None, axis=1)[source]

Averages a I multi-dimensional array (typically an image) along the y axis bining(I) corresponds to I.mean(axis=1) NaN are not taken into account.

Parameters:
  • I (numpy array) – intensity

  • ymin (int [0-I.shape[1]]) – If None, 0 is used. Default None.

  • ymax (int [0-I.shape[1]]) – If None, I.shape[1] is used. Default None.

  • axis (int) – Default 1

calc_diff(t1, v1, t2, v2)[source]

Subtract two vectors that may have slightly offset abscissa interpolating the correct values.

Parameters:
  • t1, v1 (array_like) – first vector and its abscissa

  • t2, v2 (array_like) – second vector and its abscissa

Returns:

tdiff, vdiff – subtracted vector and its abscissa

Return type:

array_like

centered_diff(w)[source]

Return w[i+1]-w[i-1]/2, same size as w.

Similar to numpy.diff(), but does not change the array size.

compare_dict(d1, d2, verbose='if_different', compare_as_paths=[], compare_as_close=[], return_string=False, df1_str='Left', df2_str='Right', ignore_keys=[])[source]

Returns ratio of equal keys [0-1] If verbose, also print all keys and values on 2 columns :Parameters: d1, d2 (dict) – two dictionaries to compare

Other Parameters:
  • compare_as_paths (list of keys) – compare the values corresponding to given keys as path (irrespective of forward / backward slashes, or case )

  • compare_as_close (list of keys) – compare with np.isclose(a,b) rather than a==b

  • verbose (boolean, or 'if_different') – 'if_different' means results will be shown only if there is a difference.

  • return_string (boolean) – if True, returns message instead of just printing it (useful in error messages) Default False

  • ignore_keys (list) – do not compare these keys

Returns:

  • out (float [0-1]) – ratio of matching keys

  • if return_string

  • out, string (float [0-1], str) – ratio of matching keys and comparison message

compare_lists(l1, l2, verbose='if_different', return_string=False, l1_str='Left', l2_str='Right', print_index=False)[source]

Compare 2 lists of elements that may not be of the same length, irrespective of order. Returns the ratio of elements [0-1] present in both lists. If verbose, prints the differences

Parameters:
  • l1, l2 (list-like)

  • verbose (boolean, or ‘if_different’) – ‘if_different’ means results will be shown only if there is a difference. function is called twice

Other Parameters:
  • verbose (boolean, or 'if_different') – 'if_different' means results will be shown only if there is a difference.

  • return_string (boolean) – if True, returns message instead of just printing it (useful in error messages) Default False

Returns:

out – ratio of matching keys

Return type:

float [0-1]

compare_paths(p1, p2)[source]

Compare 2 paths p1 and p2.

count_nans(a)[source]

NaN are good but only in India.

curve_add(w1, I1, w2, I2, is_sorted=False, kind='linear')[source]

Add curve (w2, I2) from (w1, I1) Linearly interpolates if the two ranges dont match. Fills out of bound parameters with nan.

Similar to OriginPro’s “Simple Curve Math Subtract”

Note

for higher accuracy, choose (w2, I2) has the curve with the highest resolution

Parameters:
  • w1, I1 (array) – range and values for first curve

  • w2, I2 (array) – range and values for 2nd curve

  • is_sorted (boolean) – (optional) if True, doesnt sort input arrays

  • kind (str) – interpolation kind. Default ‘linear’. See scipy.interpolate.interp1d

Returns:

w1, Iadd – sum I1 + I2 interpolated on the first range w1

Return type:

array

curve_distance(w1, I1, w2, I2, discard_out_of_bounds=True)[source]

Get a regularized euclidian distance from curve (w1, I1) to curve (w2, I2)

\[D(w_1)[i] = \sqrt{ \sum_j (\hat{I_1}[i] - \hat{I_2}[j] )^2 + (\hat{w_1}[i] - \hat{w_2}[j])^2}\]

Where values are normalized as:

\[\hat{A} = \frac{A}{max(A) - min(A)}\]

This regularized Euclidian distance minimizes the effect of a small shift in between the two curves in case of stiff curves (like a spectrum bandhead can be)

No interpolation needed neither.

Distances for out of bounds values is set to nan

Warning

This is a distance on both the waverange and the intensity axis. It may be used to compensate for a small offset in your experimental spectrum (due to wavelength calibration, for instance) but can lead to wrong fits easily. Plus, it is very cost-intensive!

Parameters:
  • w1, I1 (array) – range and values for first curve

  • w2, I2 (array) – range and values for 2nd curve

  • discard_out_of_bounds (boolean) – if True, distance for out of bound values is set to nan. Else, it will be the distance from the last point.

Returns:

w1, Idist – minimal distance from I1 to I2, for each point in (w1, I1)

Return type:

array

curve_divide(w1, I1, w2, I2, is_sorted=False, kind='linear', interpolation=1)[source]

Divides curve (w1, I1) by (w2, I2) Linearly interpolates if the two ranges dont match. Fills out of bound parameters with nan.

Similar to OriginPro’s “Simple Curve Math Subtract”

Note

for higher accuracy, choose (w2, I2) has the curve with the highest resolution

Parameters:
  • w1, I1 (array) – range and values for first curve

  • w2, I2 (array) – range and values for 2nd curve

Other Parameters:
  • is_sorted (boolean) – (optional) if True, assumes that both input arrays are sorted already. Default False.

  • kind (str) – interpolation kind. Default ‘linear’. See scipy.interpolate.interp1d

  • interpolation (int, optional) – If 1, interpolate on w1, I1. Else, on w2, I2. Default 1

Returns:

w1, Idiv – Division I1 / I2 interpolated on the first or second range according to reverseInterpolation

Return type:

array

curve_multiply(w1, I1, w2, I2, is_sorted=False, kind='linear')[source]

Multiply curve (w2, I2) with (w1, I1) Linearly interpolates if the two ranges dont match. Fills out of bound parameters with nan.

Similar to OriginPro’s “Simple Curve Math Subtract”

Note

for higher accuracy, choose (w2, I2) has the curve with the highest resolution

Parameters:
  • w1, I1 (array) – range and values for first curve

  • w2, I2 (array) – range and values for 2nd curve

  • is_sorted (boolean) – (optional) if True, doesnt sort input arrays

  • kind (str) – interpolation kind. Default ‘linear’. See scipy.interpolate.interp1d

Returns:

w1, Iproduct – product I1 * I2 interpolated on the first range w1

Return type:

array

curve_substract(w1, I1, w2, I2, is_sorted=False, kind='linear')[source]

Subtracts curve (w2, I2) from (w1, I1) Linearly interpolates if the two ranges dont match. Fills out of bound parameters with nan.

Similar to OriginPro’s “Simple Curve Math Subtract”

Note

for higher accuracy, choose (w2, I2) has the curve with the highest resolution

Parameters:
  • w1, I1 (array) – range and values for first curve

  • w2, I2 (array) – range and values for 2nd curve

  • is_sorted (boolean) – (optional) if True, doesnt sort input arrays

  • kind (str) – interpolation kind. Default ‘linear’. See scipy.interpolate.interp1d

Returns:

w1, Idiff – difference I1 - I2 interpolated on the first range w1

Return type:

array

evenly_distributed(w, atolerance=1e-05)[source]

Make sure array w is evenly distributed.

Parameters:
  • w (numpy array) – array to test

  • atolerance (float) – absolute tolerance

Returns:

outTrue or False if w is evenly distributed.

Return type:

bool

exec_file(afile, globalz=None, localz=None)[source]
export(var={'__builtins__': {'ArithmeticError': <class 'ArithmeticError'>, 'AssertionError': <class 'AssertionError'>, 'AttributeError': <class 'AttributeError'>, 'BaseException': <class 'BaseException'>, 'BaseExceptionGroup': <class 'BaseExceptionGroup'>, 'BlockingIOError': <class 'BlockingIOError'>, 'BrokenPipeError': <class 'BrokenPipeError'>, 'BufferError': <class 'BufferError'>, 'BytesWarning': <class 'BytesWarning'>, 'ChildProcessError': <class 'ChildProcessError'>, 'ConnectionAbortedError': <class 'ConnectionAbortedError'>, 'ConnectionError': <class 'ConnectionError'>, 'ConnectionRefusedError': <class 'ConnectionRefusedError'>, 'ConnectionResetError': <class 'ConnectionResetError'>, 'DeprecationWarning': <class 'DeprecationWarning'>, 'EOFError': <class 'EOFError'>, 'Ellipsis': Ellipsis, 'EncodingWarning': <class 'EncodingWarning'>, 'EnvironmentError': <class 'OSError'>, 'Exception': <class 'Exception'>, 'ExceptionGroup': <class 'ExceptionGroup'>, 'False': False, 'FileExistsError': <class 'FileExistsError'>, 'FileNotFoundError': <class 'FileNotFoundError'>, 'FloatingPointError': <class 'FloatingPointError'>, 'FutureWarning': <class 'FutureWarning'>, 'GeneratorExit': <class 'GeneratorExit'>, 'IOError': <class 'OSError'>, 'ImportError': <class 'ImportError'>, 'ImportWarning': <class 'ImportWarning'>, 'IndentationError': <class 'IndentationError'>, 'IndexError': <class 'IndexError'>, 'InterruptedError': <class 'InterruptedError'>, 'IsADirectoryError': <class 'IsADirectoryError'>, 'KeyError': <class 'KeyError'>, 'KeyboardInterrupt': <class 'KeyboardInterrupt'>, 'LookupError': <class 'LookupError'>, 'MemoryError': <class 'MemoryError'>, 'ModuleNotFoundError': <class 'ModuleNotFoundError'>, 'NameError': <class 'NameError'>, 'None': None, 'NotADirectoryError': <class 'NotADirectoryError'>, 'NotImplemented': NotImplemented, 'NotImplementedError': <class 'NotImplementedError'>, 'OSError': <class 'OSError'>, 'OverflowError': <class 'OverflowError'>, 'PendingDeprecationWarning': <class 'PendingDeprecationWarning'>, 'PermissionError': <class 'PermissionError'>, 'ProcessLookupError': <class 'ProcessLookupError'>, 'PythonFinalizationError': <class 'PythonFinalizationError'>, 'RecursionError': <class 'RecursionError'>, 'ReferenceError': <class 'ReferenceError'>, 'ResourceWarning': <class 'ResourceWarning'>, 'RuntimeError': <class 'RuntimeError'>, 'RuntimeWarning': <class 'RuntimeWarning'>, 'StopAsyncIteration': <class 'StopAsyncIteration'>, 'StopIteration': <class 'StopIteration'>, 'SyntaxError': <class 'SyntaxError'>, 'SyntaxWarning': <class 'SyntaxWarning'>, 'SystemError': <class 'SystemError'>, 'SystemExit': <class 'SystemExit'>, 'TabError': <class 'TabError'>, 'TimeoutError': <class 'TimeoutError'>, 'True': True, 'TypeError': <class 'TypeError'>, 'UnboundLocalError': <class 'UnboundLocalError'>, 'UnicodeDecodeError': <class 'UnicodeDecodeError'>, 'UnicodeEncodeError': <class 'UnicodeEncodeError'>, 'UnicodeError': <class 'UnicodeError'>, 'UnicodeTranslateError': <class 'UnicodeTranslateError'>, 'UnicodeWarning': <class 'UnicodeWarning'>, 'UserWarning': <class 'UserWarning'>, 'ValueError': <class 'ValueError'>, 'Warning': <class 'Warning'>, 'ZeroDivisionError': <class 'ZeroDivisionError'>, '_IncompleteInputError': <class '_IncompleteInputError'>, '__annotations__': {}, '__build_class__': <built-in function __build_class__>, '__debug__': True, '__doc__': "Built-in functions, types, exceptions, and other objects.\n\nThis module provides direct access to all 'built-in'\nidentifiers of Python; for example, builtins.len is\nthe full name for the built-in function len().\n\nThis module is not normally accessed explicitly by most\napplications, but can be useful in modules that provide\nobjects with the same name as a built-in value, but in\nwhich the built-in of that name is also needed.", '__import__': <built-in function __import__>, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__name__': 'builtins', '__package__': '', '__spec__': ModuleSpec(name = 'builtins', loader=<class '_frozen_importlib.BuiltinImporter'>, origin='built-in'), 'abs': <built-in function abs>, 'aiter': <built-in function aiter>, 'all': <built-in function all>, 'anext': <built-in function anext>, 'any': <built-in function any>, 'ascii': <built-in function ascii>, 'bin': <built-in function bin>, 'bool': <class 'bool'>, 'breakpoint': <built-in function breakpoint>, 'bytearray': <class 'bytearray'>, 'bytes': <class 'bytes'>, 'callable': <built-in function callable>, 'chr': <built-in function chr>, 'classmethod': <class 'classmethod'>, 'compile': <built-in function compile>, 'complex': <class 'complex'>, 'copyright': Copyright (c) 2001 Python Software Foundation. All Rights Reserved.  Copyright (c) 2000 BeOpen.com. All Rights Reserved.  Copyright (c) 1995-2001 Corporation for National Research Initiatives. All Rights Reserved.  Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. All Rights Reserved., 'credits': Thanks to CWI, CNRI, BeOpen, Zope Corporation, the Python Software Foundation, and a cast of thousands for supporting Python development.  See www.python.org for more information., 'delattr': <built-in function delattr>, 'dict': <class 'dict'>, 'dir': <built-in function dir>, 'divmod': <built-in function divmod>, 'enumerate': <class 'enumerate'>, 'eval': <built-in function eval>, 'exec': <built-in function exec>, 'exit': Use exit() or Ctrl-D (i.e. EOF) to exit, 'filter': <class 'filter'>, 'float': <class 'float'>, 'format': <built-in function format>, 'frozenset': <class 'frozenset'>, 'getattr': <built-in function getattr>, 'globals': <built-in function globals>, 'hasattr': <built-in function hasattr>, 'hash': <built-in function hash>, 'help': Type help() for interactive help, or help(object) for help about object., 'hex': <built-in function hex>, 'id': <built-in function id>, 'input': <built-in function input>, 'int': <class 'int'>, 'isinstance': <built-in function isinstance>, 'issubclass': <built-in function issubclass>, 'iter': <built-in function iter>, 'len': <built-in function len>, 'license': Type license() to see the full license text, 'list': <class 'list'>, 'locals': <built-in function locals>, 'map': <class 'map'>, 'max': <built-in function max>, 'memoryview': <class 'memoryview'>, 'min': <built-in function min>, 'next': <built-in function next>, 'object': <class 'object'>, 'oct': <built-in function oct>, 'open': <built-in function open>, 'ord': <built-in function ord>, 'pow': <built-in function pow>, 'print': <built-in function print>, 'property': <class 'property'>, 'quit': Use quit() or Ctrl-D (i.e. EOF) to exit, 'range': <class 'range'>, 'repr': <built-in function repr>, 'reversed': <class 'reversed'>, 'round': <built-in function round>, 'set': <class 'set'>, 'setattr': <built-in function setattr>, 'slice': <class 'slice'>, 'sorted': <built-in function sorted>, 'staticmethod': <class 'staticmethod'>, 'str': <class 'str'>, 'sum': <built-in function sum>, 'super': <class 'super'>, 'tuple': <class 'tuple'>, 'type': <class 'type'>, 'vars': <built-in function vars>, 'zip': <class 'zip'>}, '__cached__': '/home/docs/checkouts/readthedocs.org/user_builds/radis/checkouts/latest/radis/misc/__pycache__/debug.cpython-314.pyc', '__doc__': 'Created on Sun Jan  3 17:52:04 2016.\n\n@author: Erwan\n\nDebug functions\n', '__file__': '/home/docs/checkouts/readthedocs.org/user_builds/radis/checkouts/latest/radis/misc/debug.py', '__loader__': <_frozen_importlib_external.SourceFileLoader object>, '__name__': 'radis.misc.debug', '__package__': 'radis.misc', '__spec__': ModuleSpec(name = 'radis.misc.debug', loader=<_frozen_importlib_external.SourceFileLoader object>, origin='/home/docs/checkouts/readthedocs.org/user_builds/radis/checkouts/latest/radis/misc/debug.py'), 'export': <function export>, 'printdbg': <function printdbg>})[source]

Export local variables. Useful for debugging.

Debugging inside a function may be tedious because you can’t access the local variables. One of the option is to use the ipython magic:

%debug

Or the pdb equivalent:

import pdb
pdb.pm()

Another option is to insert this export() call in the troubled function, before the exception occurs.

Examples

debug_export(locals())

Note: you can also use ‘globals().update(locals())’ directly in your function to debug

Note

  • seems not to work for functions nested in functions

  • 01/05 : doesn’t seem to work at all.. @Erwan

find_first(arr, threshold)[source]

Return the index of the first element of the array arr whose value is more than the threshold.

find_nearest(array, searched, return_bool=False)[source]

Return the closest elements in array for each element in ‘searched’ array. In case of multiple elements in array having equal difference with searched element, one with least index is returned. Also returns a boolean array with indices of elements occurring in output list set to true.

Examples

from numpy import array
find_nearest(array([1,2,3,4]), array([2.1,2]), True)

>>> (array([2, 2]), array([False, True, False, False]))

find_nearest(np.array([1,2,3,4]), np.array([2.6,2]), True)

>>> (array([3, 2]), array([False,  True,  True, False]))

find_nearest(np.array([1, 3]), np.array([2]))

>>> array([1])

find_nearest(np.array([3, 1]), np.array([2]))

>>> array([3])
getDatabankEntries(dbname, get_extra_keys=[], configpath='/home/docs/radis.json')[source]

Read ~/radis.json config file and returns a dictionary of entries.

Parameters:
  • dbname (str) – database name in ~/radis.json config file

  • get_extra_keys (list) – read additional parameters on top of the usual Databank format keys :

Notes

Databank format:

"MY-HITEMP-CO2": {              # your databank name: use this in calc_spectrum()
                                # or SpectrumFactory.load_databank()
"info": "HITEMP 2010 databank"  # whatever you want
"path": [                       # no "", multipath allowed
    "D:\Databases\HITEMP-CO2\hitemp_07",
    "D:\Databases\HITEMP-CO2\hitemp_08",
    "D:\Databases\HITEMP-CO2\hitemp_09"
],
"format": "hitemp"              # 'hitran' (HITRAN / HITEMP), 'cdsd-hitemp', 'cdsd-4000'
                                # Databank text file format. More info in
                                # SpectrumFactory.load_databank function.

# Optional:

"parfunc":                      # path or 'USE_HAPI'
                                # path to tabulated partition functions. If
                                # `USE_HAPI`, then HAPI (HITRAN Python
                                interface) [1]_ is used to retrieve them (valid
                                if your databank is HITRAN data). HAPI
                                is embedded into RADIS. Check the version.

"levels_iso1":                  # path to energy levels (needed for non-eq)
                                # calculations.
"levels_iso2":                  # etc
"levels_iso4":                  # etc

"levelsfmt":                    # 'cdsd'
}                               # how to read the previous file.

References

getDatabankList(configpath='/home/docs/radis.json')[source]

Get all databanks available in :ref:`~/radis.json

getProjectRoot()[source]

Return the full path of the project root.

get_progress_printer(database_name: str, molecule: str, verbose: int = 1, version: str = '') DatabaseProgressPrinter[source]

Create a DatabaseProgressPrinter instance.

Parameters:
  • database_name (str) – Name of the database

  • molecule (str) – Molecule being fetched

  • verbose (int) – Verbosity level

  • version (str) – Database version

Returns:

Configured printer instance

Return type:

DatabaseProgressPrinter

is_float(a)[source]

Returns True if a has float-like type: float, np.float64, np.int64, etc.)

is_sorted(a)[source]

Returns whether a is sorted in ascending order.

From B.M. answer on StackOverflow: https://stackoverflow.com/a/47004533/5622825

is_sorted_backward(a)[source]

Returns whether a is sorted in descending order.

See also

is_sorted()

key_max_val(d)[source]

Return the dictionary key with max value.

list_if_float(a)[source]
logspace(xmin, xmax, npoints)[source]

Returns points from xmin to xmax regularly distributed on a logarithm space.

Numpy’s numpy.logspace() does the same from 10**xmin to 10**xmax

make_folders(path, folders)[source]

Make folders if not there :Parameters: * path (str) – where to create folders

  • folders (list or str) – folders to create

merge_lists(lists)[source]

Merge a list of lists and return a list with unique elements.

nantrapz(I, w, dx=1.0, axis=-1)[source]

Returns trapezoid() (I, w) discarding nan.

norm(a, normby=None, how='max')[source]

Normalize a numpy array with its maximum. Or normalize it with another vector. Works if array contains nans.

Parameters:

normby (array, or None) – if array, norm with this other array’s maximum. If None, normalize with its maximum.

norm_on(a, w, wmin=None, wmax=None, how='max')[source]

Normalize a on a specific range of w

Parameters:
  • a (array) – array

  • w (array) – x-axis array

Other Parameters:
  • wmin, wmax (float) – crop range

  • how (‘mean’, ‘max’) – how to normalize

Returns:

a_norm – normalized array

Return type:

array

partition(pred, iterable)[source]

Use a predicate to partition entries into false entries and true entries :returns: Returns two lists :rtype: positive, and negative

Example

>>> partition(is_odd, range(10))
--> [0 2 4 6 8], [1 3 5 7 9]
remove_duplicates(l)[source]

Remove duplicates from a list, without changing the order.

Note that if the order doesn’t matter you could just do set(l)

resample(xspace, vector, xspace_new, k=1, ext='error', energy_threshold='default', print_conservation=True)[source]

Resample (xspace, vector) on a new space (xspace_new) of evenly distributed data and whose bounds are taken as the same as xspace.

Uses spline interpolation to create the intermediary points. Number of points is the same as the initial xspace, times a resolution factor. Verifies energy conservation on the intersecting range at the end.

Parameters:
  • xspace (array) – space on which vector was generated

  • vector (array) – quantity to resample

  • xspace_new (array) – space on which to resample

Other Parameters:
  • resfactor (array) – xspace vector to resample on

  • k (int) – order of spline interpolation. 3: cubic, 1: linear. Default 1.

  • ext (‘error’, ‘extrapolate’, 0, 1) – Controls the value returned for elements of xspace_new not in the interval defined by xspace. If ‘error’, raise a ValueError. If ‘extrapolate’, well, extrapolate. If ‘0’ or 0, then fill with 0. If 1, fills with 1. Default ‘error’.

  • energy_threshold (float or None or 'default') -- if energy conservation (integrals on the intersecting range) is above this threshold, raise an error. If ``None, dont check for energy conservation. If 'default', look up the value in radis.config [“RESAMPLING_TOLERANCE_THRESHOLD”] Default 'default'

  • print_conservation (boolean) – if True, prints energy conservation

Returns:

array

Return type:

resampled vector on evenly spaced array. Number of element is conserved.

Notes

Note that depending upon the from_space > to_space operation, sorting may be reversed.

Examples

Resample a Spectrum radiance on an evenly spaced wavenumber space:

w_nm, I_nm = s.get('radiance')
w_cm, I_cm = resample_even(nm2cm(w_nm), I_nm)

See also

resample()

resample_even(xspace, vector, resfactor=2, k=1, ext='error', energy_threshold=0.001, print_conservation=True)[source]

Resample (xspace, vector) on a new space (xspace_new) of evenly distributed data and whose bounds are taken as the same as xspace.

Uses spline interpolation to create the intermediary points. Number of points is the same as the initial xspace, times a resolution factor. Verifies energy conservation at the end.

Parameters:
  • xspace (array) – space on which vector was generated

  • vector (array) – quantity to resample

  • resfactor (float) – increase of resolution. If 1, output vector has the same number of points as the input vector. Default 2.

  • k (int) – order of spline interpolation. 3: cubic, 1: linear. Default 1.

  • ext (‘error’, ‘extrapolate’, 0) – Controls the value returned for elements of xspace_new not in the interval defined by xspace. If ‘error’, raise a ValueError. If ‘extrapolate’, well, extrapolate. If ‘0’ or 0, then fill with 0. Default ‘error’.

  • energy_threshold (float) – if energy conservation (integrals) is above this threshold, raise an error

  • print_conservation (boolean) – if True, prints energy conservation

Returns:

  • xspace_new (array) – evenly spaced mapping of xspace (same min, same max)

  • vector_new (array) – resampled vector on evenly spaced array. Number of element is conserved.

  • Note that depending upon the from_space > to_space operation, sorting may

  • be reversed.

Examples

Resample a Spectrum radiance on an evenly spaced wavenumber space:

w_nm, I_nm = s.get('radiance')
w_cm, I_cm = resample_even(nm2cm(w_nm), I_nm)

You can also use resample_even() directly

scale_to(a, b, k=1)[source]

Scale function a to k*b.