astroplasma
A Cloudy database with functions to quickly interpolate physical state of astrophysical plasma without detailed Plasma modelling
Science Score: 26.0%
This score indicates how likely this project is to be science-related based on various indicators:
-
○CITATION.cff file
-
✓codemeta.json file
Found codemeta.json file -
✓.zenodo.json file
Found .zenodo.json file -
○DOI references
-
○Academic publication links
-
○Academic email domains
-
○Institutional organization owner
-
○JOSS paper metadata
-
○Scientific vocabulary similarity
Low similarity (17.0%) to scientific vocabulary
Keywords
Repository
A Cloudy database with functions to quickly interpolate physical state of astrophysical plasma without detailed Plasma modelling
Basic Info
Statistics
- Stars: 6
- Watchers: 1
- Forks: 3
- Open Issues: 3
- Releases: 1
Topics
Metadata Files
README.md


A Cloudy database with functions to quickly interpolate the physical state of astrophysical plasma without detailed plasma modeling
Running Cloudy models on the fly, especially when there are a lot of models to run with different parameters, can become extremely expensive. AstroPlasma aims to provide a workaround using a library of pre-computed cloudy models to generate most of the common plasma properties for a large range of parameter space by interpolation. Owing to a simple and easy-to-use interface, AstroPlasma also provides an abstraction layer enabling the user to get the plasma properties without worrying much about the details of plasma modeling. We find this extremely useful while building models and predicting observables like column densities in different kinds of astrophysical systems.
|
|
|
Install
This is just a one-time process. AstroPlasma has been tested with Python 3.10
Get the AstroPlasma code:
git clone https://github.com/dutta-alankar/AstroPlasma.git
Setting up dependencies
Change to the code directory
cd AstroPlasma
Prepare Python virtual environment
The instructions here can be followed to set up a virtual environment (named .venv here) and install AstroPlasma and its dependencies:
python -m venv .venv
source .venv/bin/activate
python -m pip install --editable .
Install the dependencies:
For user,
bash
python -m pip install -r requirements/requirements.txt
For developer,
bash
python -m pip install -r requirements/requirements-dev.txt
For running Cloudy scripts,
bash
python -m pip install -r requirements/requirements-all.txt
Note:
Python.hfrom thepython3.10-devpackage must be available for installingmpi4pydependency required by theCloudyscripts.
At any point later, in order to use AstroPlasma, just activate this virtual environment:
source venv/bin/activate
Alternative setup using poetry
Alternatively, one can use poetry to install and setup AstroPlasma
Install
poetryfollowing the installation instructions here.Do the following depending on requirements: - For user,
poetry install- For developer,poetry install --with dev,test- For runningCloudyscripts,poetry install --with cloudy_run. Note thatPython.hfrom thepython3.10-devpackage must be available for installingmpi4pydependency required by theCloudyscripts. Later at any time activate the virtual environment usingpoetry shellfrom inside the repo. As a one-time process, installAstroPlasmain this virtual environment usingpython -m pip install --editable ..
Download the database
Once AstroPlasma and its dependencies are set up, the simplest way to get the entire database locally is to run the following script in Python with the virtual environment activated. Before running the following script, the environment variable export PARALLEL_DOWNLOAD_JOBS=8 needs to be set. Here, one can replace 8 with any number that sets how many files in the database will be downloaded from the web simultaneously.
python
from astro_plasma import download_all
download_all()
Alternatively, one can use a custom data location as well. Please see the relevant Note provided near the end of this README.
User Guide
The following are code snippets that demonstrate the basic usage of AstroPlasma
Info: A
jupyter-notebookof this User Guide can be found in theexample-scriptsdirectory.
Ionization modeling
This is how one would use astro_plasma to calculate the ionization state of any typical astrophysical plasma. This would be useful in any modeling that depends on calculating the ionization of the plasma. Determining temperature from density and calculating the free electron density in the plasma are a few examples of applications of AstroPlasma.
```python
Import AstroPlasma Ionization module
from astroplasma import Ionization from astroplasma.core.utils import AtmElement # for element naming using symbols (optional) ```
Let us calculate ionization fraction of $\bf{OVI\ (O^{5+}})$
In AstroPlasma elements are labeled by their atomic number.
- Atomic number of the desired element is passed to the element argument in several functions of AstroPlasma. For example, Oxygen corresponds to element=8.
- For the ionization state, AstroPlasma labels them according to the value passed to the ion argument. For example, ionization state III, corresponds to ion=3.
- Summarizing, to know the ionization state of $\bf{OVI}$, one needs to pass element=8 and ion=6.
python
fIon = Ionization.interpolate_ion_frac
Now, we are going to define typical physical values that characterize an astrophysical plasma.
python
nH = 1.2e-04 # Hydrogen number density in cm^-3
temperature = 4.2e+05 # Temperature of the plasma in kelvin
metallicity = 0.99 # Metallicity of plasma with respect to solar
redshift = 0.001 # Cosmological redshift
mode = "CIE"
Note: The mode passed in the above code refers to the equilibrium state of the plasma. Right now, AstroPlasma only supports two equilibrium conditions, namely, collisional ionization equilibrium (CIE in code) and photo-ionization equilibrium (PIE in code).
For photo-ionization equilibrium, the photo-ionizing backgrounds that are used in the calculation of the Cloudy interpolation tables are Haardt-Madau (2012) extra-galactic UV/X-ray diffuse background and Cosmic Microwave Background (CMB) at any given redshift.
```python
Let's get the ionization of OVI
element = AtmElement.Oxygen ion = 6 fOVI = fIon(nH = nH, temperature = temperature, metallicity = metallicity, redshift = redshift, element = element, ion = ion, mode = mode, ) # This value is in log10 fOVI = pow(10, fOVI) print(f"f_OVI = {fOVI:.3e}") ```
Note:
- The ionization fraction returned by AstroPlasma is on the log10 scale.
- Currently, we do not support vectorization of these functions and indivdual values must be passed and not arrays. This can lead to errors or un-defined behavior.
- You can provide element and ion in 4 ways
```python
# Using atomic number and ion count (int version of roman)
fIon(element=8, ion=6) # OVI
# Using the symbol of the element fIon(element='O', ion=6) # OVI
# Using AtmElement for element fIon(element=AtmElement.Oxygen, ion=6) # OVI
# Using element and ion in one string # In this case explicit value of ion will be ignored fIon(element='OVI') ```
Note We recommend using the last two methods as we think it is the most convenient to use and read.
One can also caluculate other plasma quantities as follows
The total free electron density
```python numdens = Ionization.interpolatenum_dens
ne = numdens(nH = nH, temperature = temperature, metallicity = metallicity, redshift = redshift, mode = mode, parttype = "electron", ) print(f"Free electron density = {ne:.3e} cm^-3") ```
In order to get
- total particle number density, use part_type = "all"
- total ion number density, use part_type = "ion"
- total neutral particle number density, use part_type = "neutral"
- any particular ion number density, use element = "<element_name>" (similar to fIon)
```python numdens = Ionization.interpolatenum_dens
n = numdens(nH = nH, temperature = temperature, metallicity = metallicity, redshift = redshift, mode = mode, parttype = "all", ) ni = numdens(nH = nH, temperature = temperature, metallicity = metallicity, redshift = redshift, mode = mode, parttype = "ion", ) nn = numdens(nH = nH, temperature = temperature, metallicity = metallicity, redshift = redshift, mode = mode, parttype = "neutral", )
nHI = num_dens(nH = nH, temperature = temperature, metallicity = metallicity, redshift = redshift, mode = mode, element = "HI", )
print(f"Total particle density = {n:.3e} cm^-3") print(f"Total ion density = {ni:.3e} cm^-3") print(f"Total neutral particle density = {nn:.3e} cm^-3") print(f"Total HI particle density = {nHI:.3e} cm^-3") ```
Although it is straightforward to obtain mean particle mass, we provide functions to do so for the convenience of the user. We use the following relation for calculating these quantities.
$$\rho = n \mu mp = ne \mue mp = ni \mui mp = nH m_H X^{-1}$$
```python meanmass = Ionization.interpolatemu
mu = meanmass(nH = nH, temperature = temperature, metallicity = metallicity, redshift = redshift, mode = mode, parttype = "all", ) mue = meanmass(nH = nH, temperature = temperature, metallicity = metallicity, redshift = redshift, mode = mode, parttype = "electron", ) mui = meanmass(nH = nH, temperature = temperature, metallicity = metallicity, redshift = redshift, mode = mode, parttype = "ion", ) print(f"Mean particle mass = {mu:.2f} mp") print(f"Mean free electron mass = {mue:.2f} mp") print(f"Mean ion mass = {mui:.2f} mp") ```
Emission spectrum
AstroPlasma can be used in determing the emission spectrum emitted from a one-zone plasma. Here's the code that does that. This can be used as a starting point for modeling plasma emission from astrophysical objects like the circumgalactic medium or galaxy clusters by stacking emission from multiple such one-zones.
```python
Import AstroPlasma EmissionSpectrum module
from astro_plasma import EmissionSpectrum ```
```python genspectrum = EmissionSpectrum.interpolatespectrum
Generate spectrum
spectrum = gen_spectrum(nH = nH, temperature = temperature, metallicity = metallicity, redshift = redshift, mode = mode ) ```
Let us plot the spectrum generated by AstroPlasma
```python import matplotlib import matplotlib.pyplot as plt
plt.loglog(spectrum[:,0], spectrum[:,1])
plt.xlabel(r"Energy (keV)")
plt.ylabel(r"Emissivity $4 \pi \nu j_{\nu}$ ($erg\ cm^{-3} s^{-1}$)")
plt.xlim(xmin = 1.0e-10, xmax=3.2)
plt.show()
```
Note:
AstroPlasmaassumes by default that the data is located at<module_location>/data/<ionization/emission>. The user can change this to something else usingIonization.base_dir = "<new_ionization_data_location_dir>"orEmissionSpectrum.base_dir = "<new_emission_data_location_dir>", where these new directories must contain the validhdf5data files.Note: One can also use the
pypoetrytool to install and create anin-placevirtual environment for this repo.Note: We haven't made the server online yet. As a temporary measure, please download and use the data hosted here:
https://indianinstituteofscience-my.sharepoint.com/:f:/g/personal/alankardutta_iisc_ac_in/EhdL9SYY45FOq7zjrWGD0NQBcy3pn6oTP2B9pGhxPwLnkQ?e=E956ug
Downloading files on demand
We made it easy for you in the code to download only the required files on the go using our built-in service (Cloudy Interpolator web application).
To activate this feature, you should create a .env file in the project root directory and provide the following information.
sh
ASTROPLASMA_SERVER=http://web-server-url-here
Alternatively, you can export the environment variable
```sh
bash / sh
export ASTROPLASMA_SERVER=http://web-server-url-here
csh
setenv ASTROPLASMA_SERVER http://web-server-url-here ```
All the environment variables you can configure (either in env file or via export)
|Environment Variable|Description|
|:----:|:----:|
|ASTROPLASMASERVER|Base URL of the web server to enable file downloading. To get this information, you can open issue here|
|PARALLELDOWNLOADJOBS|Parallel jobs spawned to download the files. The default value is 3. You can increase or decrease based on the download bandwidth of your network connection.|
|CHUNKSIZE|Download the chunk size of the dataset files. The default is 4096. If your download is aborted because of the unstable network, try decreasing this value.|
Note to contributors
If you wish to contribute, fork this repo and open pull requests to the dev branch of this repo. Once everything gets tested and is found working, the new code will be merged with the master branch.
For a successful merge, the code must at least pass all the pre-existing tests. It is recommended to run pre-commit locally before pushing your changes to the repo for a proposed PR. To do so just run pre-commit run --all-files.
Note It is recommended that the git pre-commit hook be installed using
pre-commit installto check all the staged files.
Instructions on generating Cloudy database
All the codes required to generate the Cloudy database are in the cloudy-codes directory. This part of the code is not as clean and user-friendly as the rest of AstroPlasma because it is unnecessary for an average user. Although I plan to improve this as well in the near future. I have tested this using Cloudy 17 (link here to know more on Cloudy)
Setting up and compiling Cloudy
- export
CLOUDY_DATA_PATHto thedatadirectory ofCloudy(for example,c17.03/data) - I have tested my building the library using Makefiles in
source/sys_gcc_shareddirectory ofCloudy. Runmakefrom inside this directory. Ifmakesucceeds thencloudy.exeand a shared librarylibcloudy.sowill get compiled.
Using Cloudy with codes hosted in AstroPlasma repo
AstroPlasmahas three directories insidecloudy-codesionFrac: Generates the ionization database.emmSpec: Generates the emission spectra database (TODO: Work required to make compiled executable enabling faster calculation to generate the database).coolingFunction: Generates cooling function for optically thin radiative cooling in equilibrium. This is an extra feature not directly used inAstroPlasma
- Generating ionization data
- Copy
libcloudy.sotoAstroPlasma/cloudy-codes/ionFrac/src - From inside
AstroPlasma/cloudy-codes/ionFrac/srcdirectory, executebash ./compile-script.sh. This will compile and generate the executables that creates the ionization data. - export
AstroPlasma/cloudy-codes/ionFrac/srctoLD_LIBRARY_PATH - Inside the
AstroPlasma/cloudy-codes/ionFrac/generateIonFraction-parallel.pyscript, change the parameters (total_size,batch_dim,nH,temperature,metallicity,redshift) to desired resolution and range. - Now one can run this script in parallel using
mpiexec -n <nproc> python generateIonFraction-parallel.py. I have tested this usingPython 3.11.6withmpi4py,numpy,h5pyandcoloramapackages installed. Note for cluster usres: A sampleslurmcommand that can be copied and executed from the terminal of a cluster is also provided inslurm-python-job. However, this needed tweaking according to the specifics of the cluster. Since this job runs interactively, it is advisable to use something like gnuscreenortmuxto run this in a detached terminal, as using these tools, interruptions in the connection to the cluster won't kill the job. Also, the user needs to make sure that the binaries compiled should be compiled for the compute nodes and not the login nodes if they are of different configurations. One can see the progress of the run in the log files generated by slurm. For example,tail -F ~/AstroPlasma/cloudy-codes/ionFrac/IonCloudy-2325.logenables you to see the running job status with jobID2325in this example. - Upon successful run, several ascii files with
ionizationin their name will get generated in a directory calledautothat is created inAstroPlasma/cloudy-codes/ionFrac/src. The finalhdf5files for the database is created in thedatadirectory inAstroPlasma/cloudy-codes/ionFrac/src. This directory should be copied toAstroPlasma/astro_plasma/data/and renamed asionization.
- Copy
- Generating emission data
- The steps are similar to the above. But in this case, both
libcloudy.soandcloudy.exefiles need to be copied toAstroPlasma/cloudy-codes/emmSpec/from thesource/sys_gcc_shareddirectory ofCloudy.
- The steps are similar to the above. But in this case, both
- Generating optically thin radiative Cooling table
- This is not used by
AstroPlasmaas of now but is a useful feature ofCloudyand hence included in the repo. - Copy
libcloudy.sotoAstroPlasma/cloudy-codes/coolingFunction/ - From inside
AstroPlasma/cloudy-codes/coolingFunction/directory, executebash ./compile-script.sh. This will compile and generate the executables that can create the cooling tables. - Currently, there are two types of cooling tables available: one with plasma in equilibrium background radiation (PIE) and one without any background radiation (CIE). If you are unsure which one to use, I would recommend PIE.
- export
AstroPlasma/cloudy-codes/coolingFunctiontoLD_LIBRARY_PATH. - To generate the cooling table run
./hazy_coolingcurve_<PIE/CIE> <metallicity> <dT (log_10)> <True/False (progressbar display)>. For example,./hazy_coolingcurve_PIE 0.3 0.1 Truewill create a cooling table for plasma with 0.3 solar metallicity. The temperature spacing in the table is set to 0.1 dex in this example. The table always starts from 10 K and runs till 109 K.Truein command line arguments shows the progress bar as the code runs. - The name of the cooling table created is
cooltable_<PIE/CIE>_Z=<metallicity>.dat. - Useful to note that the cooling loss rate from the tabulated Λ(T) in the file is nH2Λ(T), where nH=ρXH/mH. Here ρ is density and nH is total Hydrogen number density of the plasma. Usually, XH=0.7154. The unit of Λ(T) in the table is erg cm3 s-1. The photoionization background considered here is
Haardt-Madau 2012at redshift 0.
- This is not used by
Good luck generating the database! I understand that this can be daunting and non-intuitive for a beginner. If you encounter any issues, please don't hesitate to contact me for help!
Owner
- Name: Alankar Dutta
- Login: dutta-alankar
- Kind: user
- Location: Bangalore, Karnataka, India
- Company: Indian Institute of Science
- Website: alankardutta.com
- Repositories: 2
- Profile: https://github.com/dutta-alankar
Graduate student in Astrophysics
CodeMeta (codemeta.json)
{
"@context": "https://doi.org/10.5063/schema/codemeta-2.0",
"@type": "SoftwareSourceCode",
"license": "https://spdx.org/licenses/MIT",
"codeRepository": "git+https://github.com/dutta-alankar/AstroPlasma",
"dateCreated": "2023-01-05",
"issueTracker": "https://github.com/dutta-alankar/AstroPlasma/issues",
"name": "AstroPlasma",
"description": "Running Cloudy models on the fly, especially when there are lot of models to run with different parameters can become extremely expensive. `AstroPlasma` aims to provide a workaround by using a library of pre-computed cloudy models to generate most of the common plasma properties for a large range of parameter space by interpolation. Owing to a simple and easy to use interface, `AstroPlasma` also provides an abstraction layer enabling the user to get the plasma properties without worrying much about the details of plasma modelling. We find this extremely useful while building models and predicting observables like column densities in different kinds of astrophysical systems.",
"applicationCategory": "Astronomy",
"funding": "DST/SJF/PSA- 03/2016-17",
"developmentStatus": "active",
"funder": {
"@type": "Organization",
"name": "Indian Institute of Science, National Supercomputing Misssion India, MoE (PMRF) India"
},
"keywords": [
"Plasma modeling",
"Cloudy",
"Spectral synthesis"
],
"programmingLanguage": [
"Python 3",
"C++"
],
"relatedLink": [
"https://github.com/dutta-alankar/MultiphaseGalacticHaloModel"
],
"author": [
{
"@type": "Person",
"@id": "http://orcid.org/0000-0002-9287-4033",
"givenName": "Alankar",
"familyName": "Dutta",
"email": "alankardutta@iisc.ac.in",
"affiliation": {
"@type": "Organization",
"name": "Department of Physics, Indian Institute of Science, Bangalore, India"
}
},
{
"@type": "Person",
"givenName": "Gurkirat",
"familyName": "Singh",
"email": "tbhaxor@proton.me",
"affiliation": {
"@type": "Organization",
"name": "Department of Physics, Indian Institute of Science, Bangalore, India"
}
}
],
"contributor": [
{
"@type": "Person",
"givenName": "Ritali",
"familyName": "Ghosh",
"email": "ritalighosh@iisc.ac.in",
"affiliation": {
"@type": "Organization",
"name": "Department of Physics, Indian Institute of Science, Bangalore, India"
}
}
]
}
GitHub Events
Total
- Issues event: 1
- Watch event: 1
- Issue comment event: 1
- Push event: 5
- Pull request event: 2
- Pull request review event: 1
Last Year
- Issues event: 1
- Watch event: 1
- Issue comment event: 1
- Push event: 5
- Pull request event: 2
- Pull request review event: 1
Dependencies
- black 23.7.0 develop
- cfgv 3.4.0 develop
- click 8.1.7 develop
- contourpy 1.1.0 develop
- cycler 0.11.0 develop
- distlib 0.3.7 develop
- filelock 3.12.3 develop
- fonttools 4.42.1 develop
- identify 2.5.27 develop
- importlib-resources 6.0.1 develop
- kiwisolver 1.4.5 develop
- matplotlib 3.7.2 develop
- mpi4py 3.1.4 develop
- mypy 1.5.1 develop
- mypy-extensions 1.0.0 develop
- nodeenv 1.8.0 develop
- packaging 23.1 develop
- pathspec 0.11.2 develop
- pillow 10.0.0 develop
- platformdirs 3.10.0 develop
- pre-commit 3.4.0 develop
- pyparsing 3.0.9 develop
- python-dateutil 2.8.2 develop
- pyyaml 6.0.1 develop
- ruff 0.0.261 develop
- setuptools 68.1.2 develop
- six 1.16.0 develop
- tomli 2.0.1 develop
- types-requests 2.31.0.2 develop
- types-urllib3 1.26.25.14 develop
- typing-extensions 4.7.1 develop
- virtualenv 20.24.4 develop
- zipp 3.16.2 develop
- certifi 2023.7.22
- charset-normalizer 3.2.0
- colorama 0.4.6
- h5py 3.9.0
- idna 3.4
- numpy 1.24.4
- python-dotenv 1.0.0
- requests 2.31.0
- scipy 1.9.3
- tqdm 4.66.1
- urllib3 1.26.16
- h5py ^3.7.0
- numpy ^1.24.1
- python ^3.8
- python-dotenv 1.0.0
- requests ^2.28.1
- scipy 1.9.3
- tqdm ^4.65.0
- urllib3 ^1.26.15
- black ==23.7.0 development
- cfgv ==3.4.0 development
- click ==8.1.7 development
- colorama ==0.4.6 development
- distlib ==0.3.7 development
- filelock ==3.12.3 development
- identify ==2.5.27 development
- mypy ==1.5.1 development
- mypy-extensions ==1.0.0 development
- nodeenv ==1.8.0 development
- packaging ==23.1 development
- pathspec ==0.11.2 development
- platformdirs ==3.10.0 development
- pre-commit ==3.4.0 development
- pyyaml ==6.0.1 development
- ruff ==0.0.261 development
- setuptools ==68.1.2 development
- tomli ==2.0.1 development
- types-requests ==2.31.0.2 development
- types-urllib3 ==1.26.25.14 development
- typing-extensions ==4.7.1 development
- virtualenv ==20.24.4 development
- certifi ==2023.7.22
- charset-normalizer ==3.2.0
- colorama ==0.4.6
- h5py ==3.9.0
- idna ==3.4
- numpy ==1.24.4
- python-dotenv ==1.0.0
- requests ==2.31.0
- scipy ==1.9.3
- tqdm ==4.66.1
- urllib3 ==1.26.16