Git Product home page Git Product logo

ndradex's Introduction

ndRADEX

Release Python Downloads DOI Tests

Multidimensional grid RADEX calculator

Overview

ndRADEX is a Python package which can run RADEX, non-LTE molecular radiative transfer code, with multiple grid parameters. The output will be multidimensional arrays provided by xarray, which would be useful for parameter search of physical conditions in comparison with observed values.

Features

  • Grid calculation: ndRADEX has a simple run() function, where all parameters of RADEX can be griddable (i.e., they can be list-like with length of more than one).
  • Builtin RADEX: ndRADEX provides builtin RADEX binaries in the package, which are automatically downloaded and built on the first import. This also enables us to do RADEX calculations in the cloud such as Google Colaboratory.
  • Multiprocessing: ndRADEX supports multiprocessing RADEX run by default. At least twice speedup is expected compared to single processing.
  • Handy I/O: The output of ndRADEX is a xarray's Dataset, a standard multidimensional data structure as well as pandas. You can handle it in the same manner as NumPy and pandas (i.e., element-wise operation, save/load data, plotting, etc).

Requirements

  • Python 3.8-3.11 (tested by the author)
  • gfortran (necessary to build RADEX)

Installation

You can install ndRADEX with pip:

$ pip install ndradex

Usages

Within Python, import the package like:

>>> import ndradex

Single RADEX calculation

The main function of ndRADEX is ndradex.run(). For example, to get RADEX results of CO(1-0) with kinetic temperature of 100.0 K, CO column density of 1e15 cm^-2, and H2 density of 1e3 cm^-3:

>>> ds = ndradex.run("co.dat", "1-0", 100.0, 1e15, 1e3)

where "co.dat" is a name of LAMDA datafile and "1-0" is a name of transition. The available values are listed in List of available LAMDA datafiles and transitions. Note that you do not need to any download datafiles: ndRADEX automatically manage this.

In this case, other parameters like line width, background temperature are default values defined in the function. The geometry of escape probability is uniform ("uni") by default. You can change these values with custom config (see customizations below).

The output is a xarray's Dataset with no dimension:

>>> print(ds)
<xarray.Dataset>
Dimensions:      ()
Coordinates:
    QN_ul        <U3 '1-0'
    T_kin        int64 100
    N_mol        float64 1e+15
    n_H2         float64 1e+03
    T_bg         float64 2.73
    dv           float64 1.0
    geom         <U3 'uni'
    description  <U9 'LAMDA(CO)'
Data variables:
    E_u          float64 5.5
    freq         float64 115.3
    wavel        float64 2.601e+03
    T_ex         float64 132.5
    tau          float64 0.009966
    T_r          float64 1.278
    pop_u        float64 0.4934
    pop_l        float64 0.1715
    I            float64 1.36
    F            float64 2.684e-08

You can access each result value like:

>>> flux = ds["F"].values

Grid RADEX calculation

As a natural extension, you can run grid RADEX calculation like:

>>> ds = ndradex.run("co.dat", ["1-0", "2-1"], T_kin=[100.0, 200.0, 300.0],
                     N_mol=1e15, n_H2=[1e3, 1e4, 1e5, 1e6, 1e7])

There are 13 parameters which can be griddable: QN_ul (transition name), T_kin (kinetic temperature), N_mol (column density), n_H2 (H2 density), n_pH2 (para-H2 density), n_oH2 (ortho-H2 density), n_e (electron density), n_H (atomic hydrogen density), n_He (Helium density), n_Hp (ionized hydrogen density), T_bg (background temperature), dv (line width), and geom (photon escape geometry).

The output of this example is a xarray's Dataset with three dimensions of (QN_ul, T_kin, n_H2):

>>> print(ds)
<xarray.Dataset>
Dimensions:      (QN_ul: 2, T_kin: 3, n_H2: 5)
Coordinates:
  * QN_ul        (QN_ul) <U3 '1-0' '2-1'
  * T_kin        (T_kin) int64 100 200 300
    N_mol        float64 1e+15
  * n_H2         (n_H2) float64 1e+03 1e+04 1e+05 1e+06 1e+07
    T_bg         float64 2.73
    dv           float64 1.0
    geom         <U3 'uni'
    description  <U9 'LAMDA(CO)'
Data variables:
    E_u          (QN_ul, T_kin, n_H2) float64 5.5 5.5 5.5 5.5 ... 16.6 16.6 16.6
    freq         (QN_ul, T_kin, n_H2) float64 115.3 115.3 115.3 ... 230.5 230.5
    wavel        (QN_ul, T_kin, n_H2) float64 2.601e+03 2.601e+03 ... 1.3e+03
    T_ex         (QN_ul, T_kin, n_H2) float64 132.5 -86.52 127.6 ... 316.6 301.6
    tau          (QN_ul, T_kin, n_H2) float64 0.009966 -0.005898 ... 0.0009394
    T_r          (QN_ul, T_kin, n_H2) float64 1.278 0.5333 ... 0.3121 0.2778
    pop_u        (QN_ul, T_kin, n_H2) float64 0.4934 0.201 ... 0.04972 0.04426
    pop_l        (QN_ul, T_kin, n_H2) float64 0.1715 0.06286 ... 0.03089 0.02755
    I            (QN_ul, T_kin, n_H2) float64 1.36 0.5677 ... 0.3322 0.2957
    F            (QN_ul, T_kin, n_H2) float64 2.684e-08 1.12e-08 ... 4.666e-08

For more information, run help(ndradex.run) to see the docstrings.

Save and load results

You can save and load the dataset like:

# save results to a netCDF file
>>> ndradex.save_dataset(ds, "results.nc")

# load results from a netCDF file
>>> ds = ndradex.load_dataset("results.nc")

Customization

For the first time you import ndRADEX, the custom configuration file is created as ~/.config/ndradex/config.toml. By editing this, you can customize the following two settings of ndRADEX. Note that you can change the path of configuration directory by setting an environment variable, NDRADEX_DIR.

Changing default values

As mentioned above, you can change the default values of the run() function like:

# config.toml

[defaults]
T_bg = 10.0  # change default background temp to 10.0 K
geom = "lvg"  # change default geometry to LVG
timeout = 60.0
n_procs = 8

You can also change the number of multiprocesses (n_procs) and timeout (timeout) here.

Setting datafile aliases

Sometimes datafile names are not intuitive (for example, name of CS datafile is [email protected]). For convenience, you can define aliases of datafile names like:

# config.toml

[lamda.aliaes]
CS = "[email protected]"
CO = "~/your/local/co.dat"
H13CN = "https://home.strw.leidenuniv.nl/~moldata/datafiles/[email protected]"

As shown in the second and third examples, you can also specify a local file path or a URL on the right hand. After the customization, you can use these aliases in the run() function:

>>> ds = ndradex.run("CS", "1-0", ...)  # equiv to [email protected]

ndradex's People

Contributors

astropenguin avatar dependabot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

ndradex's Issues

Handle invalid RADEX output values

The format of RADEX output values can sometimes be invalid (e.g., 1.928+104; E or e is missed) and is interpreted as not float but an object by the pandas.read_csv() function. ndRADEX should handle these values as NaN.

Fix pyproject.toml

  • Fix missing README setting
  • Fix wrong Python dependencies (>3.8, <3.12>=3.8, <3.12)

Linting and formatting

  • Install black and Flake8 as dev packages
  • Lint all code by Flake8
  • Format all codes by black

TypeError: ufunc 'isnan' not supported for the input types,

UPDATE: I changed in File "/home/user/.local/lib/python3.6/site-packages/ndradex/grid.py", line 228, where is said if np.any(np.isnan(coord)): I wrote if np.any(pd.isnull(coord)) , and seems like it's fixed it.


I'm running ndradex, with spyder,
and I get the following error:

`100%|██████████| 1/1 [00:00<00:00, 27.19it/s]

Traceback (most recent call last):

File "", line 1, in
runfile('/media/user/radex/prueba_pyradex.py', wdir='/media/user/radex')

File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
execfile(filename, namespace)

File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

File "/media/user/radex/prueba_pyradex.py", line 11, in
ds = nd.run('co', '1-0', 100, 1e15, 1e3)

File "/home/user/.local/lib/python3.6/site-packages/ndradex/utils.py", line 30, in wrapper
return func(*bound.args, **bound.kwargs)

File "/home/user/.local/lib/python3.6/site-packages/ndradex/grid.py", line 169, in run
return finalize(dataset, squeeze)

File "/home/user/.local/lib/python3.6/site-packages/ndradex/grid.py", line 228, in finalize
if np.any(np.isnan(coord)):

File "/home/user/.local/lib/python3.6/site-packages/xarray/core/arithmetic.py", line 69, in array_ufunc
dask='allowed')

File "/home/user/.local/lib/python3.6/site-packages/xarray/core/computation.py", line 969, in apply_ufunc
keep_attrs=keep_attrs)

File "/home/user/.local/lib/python3.6/site-packages/xarray/core/computation.py", line 217, in apply_dataarray_vfunc
result_var = func(*data_vars)

File "/home/user/.local/lib/python3.6/site-packages/xarray/core/computation.py", line 564, in apply_variable_ufunc
result_data = func(*input_data)

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''`

How can I fix this?

Update radex module

  • Do not use Union[Sequence[str], str] for input. Accept only Sequence[str] as a valid type.
  • Use pathlib.Path for outfile of RADEX.

Fix LAMDA property for calculating critical densities

Hi,
The following minimal example shows that the result for the computation of critical densities is different by several orders of magnitude between astroquery.lamda.utils.ncrit and ndradex.db.LAMDA.n_crit even thought ndradex uses astroquery.lamda.utils.ncrit and the tables seem to be identical.

Pierre

T_kin = 30

from ndradex.db import LAMDA
ncrit_from_ndradex = LAMDA('hco+@xpol').n_crit['1-0'](T_kin)

from astroquery.lamda.utils import ncrit
from astroquery.lamda import Lamda
tables = Lamda.query('hco+@xpol')
ncrit_from_astroquery = ncrit(tables,2,1,T_kin)

print("ncrit_from_ndradex: {:e}, ncrit_from_astroquery: {:e}".format(ncrit_from_ndradex,ncrit_from_astroquery.value))

Add consts module

Add consts module for dynamically making constants (this is processed in __init__.py).

ndradex 0.3.1 error after succesful installation

After updating ndradex (succesfully), when doing import ndradex I get:

File "/home/user/.local/lib/python3.8/site-packages/ndradex/init.py", line 29, in
radex.build()

File "/home/user/.local/lib/python3.8/site-packages/ndradex/radex.py", line 100, in build
sprun(

File "/usr/lib/python3.8/subprocess.py", line 516, in run
raise CalledProcessError(retcode, process.args,

CalledProcessError: Command '['make', 'build', 'RADEX_LOGFILE=/dev/null', 'RADEX_MAXITER=999999']' returned non-zero exit status 2.

The previous versions of ndradex were working fine until I had to update astropy and numpy.

Is this a problem of my installation, or a problem of ndradex?

Thanks!

Release v0.2.1

  • Update package versions
  • Update CI budge in README.md
  • Remove config.toml in MANIFEST.in
  • Update year period in LICENSE
  • Fix PyPI workflow (add sdist script)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.