radas 2024.3.0a2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Commonwealth Fusion Systems
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,167 @@
1
+ Metadata-Version: 2.1
2
+ Name: radas
3
+ Version: 2024.3.0a2
4
+ Summary: Plasma radiated power calculated using OpenADAS
5
+ Author: Commonwealth Fusion Systems
6
+ Requires-Python: >=3.9,<3.13
7
+ Classifier: Development Status :: 5 - Production/Stable
8
+ Classifier: Intended Audience :: Science/Research
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Topic :: Scientific/Engineering :: Physics
17
+ Requires-Dist: Pint (>=0.21,<0.22)
18
+ Requires-Dist: click (>=8.1,<9.0)
19
+ Requires-Dist: matplotlib (>=3.6,<4.0)
20
+ Requires-Dist: numpy (>=1.22,<2.0)
21
+ Requires-Dist: pint-xarray (>=0.3)
22
+ Requires-Dist: pyyaml (>=6.0,<7.0)
23
+ Requires-Dist: scipy (>=1.8,<2.0)
24
+ Requires-Dist: xarray (>=2023)
25
+ Description-Content-Type: text/markdown
26
+
27
+ # RADAS: radiated power curves from OpenADAS
28
+
29
+ This Python library downloads atomic data from OpenADAS, performs simple calculations and stores the result as a NetCDF file for use in other programs.
30
+
31
+ ## Installing via PyPi (quick start)
32
+
33
+ `radas` is on PyPi. You should be able to install it using
34
+ ```
35
+ pip install radas
36
+ ```
37
+
38
+ Once you've installed `radas` into your environment, you should be able to run
39
+ ```
40
+ radas --help
41
+ ```
42
+ to get an overview of the CLI options. Every option has a sensible default, so you can just run `radas` at the command line and it will generate a processed NetCDF for every species that has `data_files` defined in `config.yaml`. This can take some time (especially for high-Z impurities such as tungsten). If you'd just like to run a few species, you can specify these on the command line like
43
+ ```
44
+ radas -s hydrogen -s helium -s lithium
45
+ ```
46
+
47
+ If you want to change the years of the databases downloaded, you will need to change the `config.yaml` file. To get a copy of this, run `radas_config` to get a copy of the `config.yaml` file in your current working directory. You can edit this file (see the configuration section below) and then use it by passing it as the `-c` or `--config` argument to `radas` (i.e. `radas -s hydrogen -c ./config.yaml`).
48
+
49
+ ## Development installation
50
+
51
+ If you want to develop `radas`, excellent! For contributing to `radas`, we ask that you
52
+ 1. use Issues to ask questions, request features and discuss planned improvements,
53
+ 2. use Pull Requests to merge code into `main` (mark work-in-progress with `draft` in the title),
54
+ 3. write `pytest` tests for new functionality (ideally aiming to cover all new lines of code).
55
+
56
+ ### Prerequisites
57
+
58
+ * Python 3.9 or later
59
+ * A Fortran compiler, such as `gfortran`
60
+ * The `poetry` packaging and dependency manager
61
+
62
+ ### Installation
63
+
64
+ The project is installed using [poetry](https://python-poetry.org/). If you haven't already installed poetry, the installation instructions can be found [here](https://python-poetry.org/docs/#installing-with-the-official-installer).
65
+
66
+ Once you have poetry installed, you can install `radas` by running
67
+ ```
68
+ poetry install --with dev
69
+ ```
70
+
71
+ Because we've added `in-project = true` in `poetry.toml`, the project will install in the `.venv` in the repository directory.
72
+
73
+ ### Usage
74
+
75
+ Once you have installed `radas`, you should be able to run the following snippet
76
+ ```
77
+ poetry run radas --species=hydrogen --plot
78
+ ```
79
+ where `--species` can be
80
+ * a specific species such as `hydrogen` or `tungsten`
81
+ * `all` which runs all species which have available data
82
+ * `none` which doesn't perform any analysis, but can be combined with `--plot` to generate the output plots from existing NetCDF files
83
+
84
+ If anything goes wrong, the script will drop into an `ipdb` interpreter so you can debug any issues.
85
+
86
+ #### What's going on under the hood?
87
+
88
+ The above snippet executes `run_radas_cli` in `radas/cli.py`, which performs the following steps
89
+
90
+ 1. Connect to [OpenADAS](https://open.adas.ac.uk/)
91
+ 2. Download the datasets listed in `radas/config.yaml` under `species:hydrogen:data_files` (where the values are the years to download) and store them in `radas/.data_files`.
92
+ 3. Download the fortran source for the dataset readers and store them in `radas/readers`.
93
+ 4. Compile the readers using a fortran compiler with `f2py`.
94
+ 5. Use the compiled readers to read the downloaded data files and store them in xarray Dataset (in `read_rate_coeffs.py`).
95
+ 6. Calculate the fractional abundance of each charge state according to the coronal approximation (in `coronal_equilibrium.py`).
96
+ 7. Calculate the coronal mean charge ($\langle Z \rangle$) and radiated power coefficient ($L_z$) as a function of the plasma temperature and density (in `cli.py` for the mean charge and in `radiated_power.py` for the radiated power).
97
+ 8. Time-integrate equations for the abundance of each charge state to give the fractional abundance as a function of time $n_z(t)$ for different refuelling rates (characterized by $n_e \tau$ where $\tau$ is a particle residence time, in `time_evolution.py`).
98
+ 9. Calculate the equilibrium ($t \to \infty$) mean charge ($\langle Z \rangle$) and radiated power coefficient ($L_z$) as a function of the plasma temperature and density (reusing the same functions as for the coronal values).
99
+ 10. Store all of the results in a NetCDF in the `output` folder and make a figure comparing the computed curves to data from *Mavrin, J. Fus. Eng., 2017* (where available).
100
+
101
+ ### Configuration
102
+
103
+ `radas` is configured using the `config.yaml` file provided in the `radas` source repository. You can edit this file directly, or can point the CLI to another configuration YAML file using the `--config` argument. Regardless of which approach you choose, the `config.yaml` file must have the following structure
104
+ ```
105
+ globals:
106
+ evolution_start:
107
+ value: <Time to start time-evolution>
108
+ units: "s"
109
+
110
+ evolution_stop:
111
+ value: <Time to stop time-evolution>
112
+ units: "s"
113
+
114
+ ne_tau:
115
+ value: <Values of ne * tau to generate output for>
116
+ units: "m^-3 s"
117
+
118
+ data_file_config:
119
+ adf11: #or other reader class, but usually we want ADF11
120
+ <what to call the dataset in the output>:
121
+ prefix: <letters used to identify the dataset>
122
+ code: <code used to identify the dataset for the ADAS reader>
123
+ stored_units: "cm**3 / s"
124
+ desired_units: "m**3 / s"
125
+
126
+ species:
127
+ <species name>:
128
+ atomic_symbol: <symbol>
129
+ atomic_number: <atomic number>
130
+ data_files:
131
+ <dataset matching "what to call the dataset in the output" above>: <year to download>
132
+ ```
133
+
134
+ ### Testing
135
+
136
+ To make sure everything is working, run
137
+ ```
138
+ poetry run pytest
139
+ ```
140
+ to execute all of the tests in the `tests` folder.
141
+
142
+ ### Pushing to PyPi
143
+
144
+ To publish the repository to the [PyPi](pypi.org) package index, you can follow the instructions at [RealPython](https://realpython.com/pypi-publish-python-package/), adapted slightly for the poetry project.
145
+
146
+ First, you should edit `pyproject.toml` and set `version="YYYY.MM.V"`, where `YYYY` is the year, `MM` is the month and `V` is a version tag (reset at zero each month). Then, you can publish to PyPi by running the following
147
+ ```
148
+ # Clean up any previous distributions
149
+ rm -rf ./dist
150
+
151
+ # Install the project
152
+ poetry lock
153
+ poetry install --with dev
154
+ # Make sure the tests all pass!
155
+ poetry run pytest
156
+
157
+ # Build and check the distribution
158
+ poetry build
159
+ poetry run twine check dist/*
160
+
161
+ # Test on https://test.pypi.org/ first!
162
+ poetry run twine upload -r testpypi dist/*
163
+
164
+ # Publish the package to the real Python Package Index
165
+ poetry run twine upload dist/*
166
+ ```
167
+
@@ -0,0 +1,140 @@
1
+ # RADAS: radiated power curves from OpenADAS
2
+
3
+ This Python library downloads atomic data from OpenADAS, performs simple calculations and stores the result as a NetCDF file for use in other programs.
4
+
5
+ ## Installing via PyPi (quick start)
6
+
7
+ `radas` is on PyPi. You should be able to install it using
8
+ ```
9
+ pip install radas
10
+ ```
11
+
12
+ Once you've installed `radas` into your environment, you should be able to run
13
+ ```
14
+ radas --help
15
+ ```
16
+ to get an overview of the CLI options. Every option has a sensible default, so you can just run `radas` at the command line and it will generate a processed NetCDF for every species that has `data_files` defined in `config.yaml`. This can take some time (especially for high-Z impurities such as tungsten). If you'd just like to run a few species, you can specify these on the command line like
17
+ ```
18
+ radas -s hydrogen -s helium -s lithium
19
+ ```
20
+
21
+ If you want to change the years of the databases downloaded, you will need to change the `config.yaml` file. To get a copy of this, run `radas_config` to get a copy of the `config.yaml` file in your current working directory. You can edit this file (see the configuration section below) and then use it by passing it as the `-c` or `--config` argument to `radas` (i.e. `radas -s hydrogen -c ./config.yaml`).
22
+
23
+ ## Development installation
24
+
25
+ If you want to develop `radas`, excellent! For contributing to `radas`, we ask that you
26
+ 1. use Issues to ask questions, request features and discuss planned improvements,
27
+ 2. use Pull Requests to merge code into `main` (mark work-in-progress with `draft` in the title),
28
+ 3. write `pytest` tests for new functionality (ideally aiming to cover all new lines of code).
29
+
30
+ ### Prerequisites
31
+
32
+ * Python 3.9 or later
33
+ * A Fortran compiler, such as `gfortran`
34
+ * The `poetry` packaging and dependency manager
35
+
36
+ ### Installation
37
+
38
+ The project is installed using [poetry](https://python-poetry.org/). If you haven't already installed poetry, the installation instructions can be found [here](https://python-poetry.org/docs/#installing-with-the-official-installer).
39
+
40
+ Once you have poetry installed, you can install `radas` by running
41
+ ```
42
+ poetry install --with dev
43
+ ```
44
+
45
+ Because we've added `in-project = true` in `poetry.toml`, the project will install in the `.venv` in the repository directory.
46
+
47
+ ### Usage
48
+
49
+ Once you have installed `radas`, you should be able to run the following snippet
50
+ ```
51
+ poetry run radas --species=hydrogen --plot
52
+ ```
53
+ where `--species` can be
54
+ * a specific species such as `hydrogen` or `tungsten`
55
+ * `all` which runs all species which have available data
56
+ * `none` which doesn't perform any analysis, but can be combined with `--plot` to generate the output plots from existing NetCDF files
57
+
58
+ If anything goes wrong, the script will drop into an `ipdb` interpreter so you can debug any issues.
59
+
60
+ #### What's going on under the hood?
61
+
62
+ The above snippet executes `run_radas_cli` in `radas/cli.py`, which performs the following steps
63
+
64
+ 1. Connect to [OpenADAS](https://open.adas.ac.uk/)
65
+ 2. Download the datasets listed in `radas/config.yaml` under `species:hydrogen:data_files` (where the values are the years to download) and store them in `radas/.data_files`.
66
+ 3. Download the fortran source for the dataset readers and store them in `radas/readers`.
67
+ 4. Compile the readers using a fortran compiler with `f2py`.
68
+ 5. Use the compiled readers to read the downloaded data files and store them in xarray Dataset (in `read_rate_coeffs.py`).
69
+ 6. Calculate the fractional abundance of each charge state according to the coronal approximation (in `coronal_equilibrium.py`).
70
+ 7. Calculate the coronal mean charge ($\langle Z \rangle$) and radiated power coefficient ($L_z$) as a function of the plasma temperature and density (in `cli.py` for the mean charge and in `radiated_power.py` for the radiated power).
71
+ 8. Time-integrate equations for the abundance of each charge state to give the fractional abundance as a function of time $n_z(t)$ for different refuelling rates (characterized by $n_e \tau$ where $\tau$ is a particle residence time, in `time_evolution.py`).
72
+ 9. Calculate the equilibrium ($t \to \infty$) mean charge ($\langle Z \rangle$) and radiated power coefficient ($L_z$) as a function of the plasma temperature and density (reusing the same functions as for the coronal values).
73
+ 10. Store all of the results in a NetCDF in the `output` folder and make a figure comparing the computed curves to data from *Mavrin, J. Fus. Eng., 2017* (where available).
74
+
75
+ ### Configuration
76
+
77
+ `radas` is configured using the `config.yaml` file provided in the `radas` source repository. You can edit this file directly, or can point the CLI to another configuration YAML file using the `--config` argument. Regardless of which approach you choose, the `config.yaml` file must have the following structure
78
+ ```
79
+ globals:
80
+ evolution_start:
81
+ value: <Time to start time-evolution>
82
+ units: "s"
83
+
84
+ evolution_stop:
85
+ value: <Time to stop time-evolution>
86
+ units: "s"
87
+
88
+ ne_tau:
89
+ value: <Values of ne * tau to generate output for>
90
+ units: "m^-3 s"
91
+
92
+ data_file_config:
93
+ adf11: #or other reader class, but usually we want ADF11
94
+ <what to call the dataset in the output>:
95
+ prefix: <letters used to identify the dataset>
96
+ code: <code used to identify the dataset for the ADAS reader>
97
+ stored_units: "cm**3 / s"
98
+ desired_units: "m**3 / s"
99
+
100
+ species:
101
+ <species name>:
102
+ atomic_symbol: <symbol>
103
+ atomic_number: <atomic number>
104
+ data_files:
105
+ <dataset matching "what to call the dataset in the output" above>: <year to download>
106
+ ```
107
+
108
+ ### Testing
109
+
110
+ To make sure everything is working, run
111
+ ```
112
+ poetry run pytest
113
+ ```
114
+ to execute all of the tests in the `tests` folder.
115
+
116
+ ### Pushing to PyPi
117
+
118
+ To publish the repository to the [PyPi](pypi.org) package index, you can follow the instructions at [RealPython](https://realpython.com/pypi-publish-python-package/), adapted slightly for the poetry project.
119
+
120
+ First, you should edit `pyproject.toml` and set `version="YYYY.MM.V"`, where `YYYY` is the year, `MM` is the month and `V` is a version tag (reset at zero each month). Then, you can publish to PyPi by running the following
121
+ ```
122
+ # Clean up any previous distributions
123
+ rm -rf ./dist
124
+
125
+ # Install the project
126
+ poetry lock
127
+ poetry install --with dev
128
+ # Make sure the tests all pass!
129
+ poetry run pytest
130
+
131
+ # Build and check the distribution
132
+ poetry build
133
+ poetry run twine check dist/*
134
+
135
+ # Test on https://test.pypi.org/ first!
136
+ poetry run twine upload -r testpypi dist/*
137
+
138
+ # Publish the package to the real Python Package Index
139
+ poetry run twine upload dist/*
140
+ ```
@@ -0,0 +1,70 @@
1
+ [tool.poetry]
2
+ name = "radas"
3
+ # Version is year.month.version
4
+ version = "2024.3.0a2"
5
+ description = "Plasma radiated power calculated using OpenADAS"
6
+ authors = ["Commonwealth Fusion Systems"]
7
+ readme = "README.md"
8
+ classifiers = [
9
+ "Development Status :: 5 - Production/Stable",
10
+ "Intended Audience :: Science/Research",
11
+ "Programming Language :: Python :: 3",
12
+ "Programming Language :: Python :: 3.9",
13
+ "Programming Language :: Python :: 3.10",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ "Programming Language :: Python :: 3 :: Only",
17
+ "Topic :: Scientific/Engineering :: Physics",
18
+ "License :: OSI Approved :: MIT License",
19
+ ]
20
+
21
+ [tool.poetry.scripts]
22
+ radas = 'radas.cli:run_radas_cli'
23
+ run_radas = 'radas.cli:run_radas_cli'
24
+ radas_config = 'radas.cli:write_config_template'
25
+
26
+ [tool.poetry.dependencies]
27
+ python = "<3.13,>=3.9"
28
+ numpy = "^1.22"
29
+ scipy = "^1.8"
30
+ matplotlib = "^3.6"
31
+ Pint = "^0.21"
32
+ pyyaml = "^6.0"
33
+ xarray = ">=2023"
34
+ pint-xarray = ">=0.3"
35
+ click = "^8.1"
36
+
37
+ [tool.poetry.group.dev.dependencies]
38
+ twine = ">=4.0"
39
+ black = ">=23.0"
40
+ ipdb = "^0.13"
41
+ pytest = "^7.2"
42
+ pytest-order = "^1.1"
43
+ pytest-cov = "^4.1"
44
+ coverage = ">=7.2"
45
+ ipykernel = ">=6.20"
46
+
47
+ [build-system]
48
+ requires = ["poetry-core"]
49
+ build-backend = "poetry.core.masonry.api"
50
+
51
+ [tool.pytest.ini_options]
52
+ markers = [
53
+ "slow: marks tests as slow (deselect with '-m \"not slow\"')",
54
+ ]
55
+ addopts = "--cov=radas --cov-branch --cov-report term --cov-report xml:coverage.xml --import-mode=importlib"
56
+ pythonpath = [
57
+ ".",
58
+ "radas",
59
+ ]
60
+ testpaths = [
61
+ "tests",
62
+ ]
63
+
64
+ [tool.coverage.run]
65
+ omit = [
66
+ # These are built and executed at runtime. This is done in
67
+ # a temporary repository. The temporary copies of the reader
68
+ # are covered instead of the actual source files.
69
+ "radas/adas_interface/source_files/*"
70
+ ]
@@ -0,0 +1,41 @@
1
+ from .unit_handling import (
2
+ DimensionalityError,
3
+ UnitStrippedWarning,
4
+ ureg,
5
+ Quantity,
6
+ suppress_downcast_warning,
7
+ convert_units,
8
+ magnitude,
9
+ dimensionless_magnitude,
10
+ )
11
+
12
+ from .cli import (
13
+ run_radas_cli,
14
+ run_radas,
15
+ run_radas_computation,
16
+ write_config_template,
17
+ )
18
+
19
+ from .read_rate_coeffs import read_rate_coeff
20
+ from .coronal_equilibrium import calculate_coronal_fractional_abundances
21
+ from .radiated_power import calculate_Lz
22
+ from .time_evolution import calculate_time_evolution
23
+
24
+ __all__ = [
25
+ "DimensionalityError",
26
+ "UnitStrippedWarning",
27
+ "ureg",
28
+ "Quantity",
29
+ "suppress_downcast_warning",
30
+ "convert_units",
31
+ "magnitude",
32
+ "dimensionless_magnitude",
33
+ "run_radas_cli",
34
+ "run_radas",
35
+ "run_radas_computation",
36
+ "read_rate_coeff",
37
+ "calculate_coronal_fractional_abundances",
38
+ "calculate_Lz",
39
+ "calculate_time_evolution",
40
+ "write_config_template",
41
+ ]
@@ -0,0 +1,13 @@
1
+ from .compile_with_f2py import compile_with_f2py
2
+ from .determine_adas_dataset_type import determine_reader_class_and_config
3
+ from .download_adas_datasets import download_species_data
4
+ from .prepare_adas_readers import prepare_adas_fortran_interface
5
+ from .read_adf11_file import read_adf11_file
6
+
7
+ __all__ = [
8
+ "compile_with_f2py",
9
+ "determine_reader_class_and_config",
10
+ "download_species_data",
11
+ "prepare_adas_fortran_interface",
12
+ "read_adf11_file",
13
+ ]
@@ -0,0 +1,38 @@
1
+ from pathlib import Path
2
+ import subprocess
3
+
4
+
5
+ def compile_with_f2py(
6
+ files_to_compile: list[str],
7
+ module_name: str,
8
+ output_folder: Path,
9
+ ) -> Path:
10
+ """Compiles a list of fortran files into a module."""
11
+ from ..shared import library_extensions
12
+
13
+ def compile_fortran_files(quiet: bool):
14
+ command = (
15
+ ["python3", "-m", "numpy.f2py", "-c"]
16
+ + files_to_compile
17
+ + ["-m", module_name]
18
+ )
19
+
20
+ return subprocess.run(command, capture_output=quiet, check=not quiet)
21
+
22
+ result = compile_fortran_files(True)
23
+
24
+ if not result.returncode == 0:
25
+ # If the first compile attempt fails, do it again
26
+ # and this time print output
27
+ compile_fortran_files(False)
28
+
29
+ library_found = []
30
+ for file in Path(".").iterdir():
31
+ if file.name.startswith(module_name) and file.suffix in library_extensions:
32
+ output_name = output_folder / f"{module_name}{file.suffix}"
33
+ library_found.append(output_name)
34
+ file.rename(output_name)
35
+
36
+ assert len(library_found) > 0, f"Could not find compiled library for {module_name}"
37
+ assert len(library_found) == 1, f"Found multiple compiled objects for {module_name}"
38
+ return library_found[0]
@@ -0,0 +1,8 @@
1
+ def determine_reader_class_and_config(data_file_config, dataset_type):
2
+ """Examines the data_file_config to determine which reader class to use to read a specific dataset_type."""
3
+ for reader_key, reader_config in data_file_config.items():
4
+ for dataset_key, dataset_config in reader_config.items():
5
+ if dataset_key == dataset_type:
6
+ return reader_key, dataset_config
7
+
8
+ raise NotImplementedError(f"Cannot identify reader for {dataset_type}.")
@@ -0,0 +1,43 @@
1
+ from pathlib import Path
2
+ import urllib.request
3
+ from .determine_adas_dataset_type import determine_reader_class_and_config
4
+
5
+
6
+ def download_species_data(
7
+ data_file_dir: Path,
8
+ species_name: str,
9
+ species_config: dict,
10
+ data_file_config: dict,
11
+ verbose: int,
12
+ url_base: str = "https://open.adas.ac.uk",
13
+ ):
14
+ """Downloads all of the data files for a specific species."""
15
+ data_file_dir.mkdir(exist_ok=True, parents=True)
16
+
17
+ for dataset_type, year in species_config["data_files"].items():
18
+
19
+ reader_class, dataset_config = determine_reader_class_and_config(
20
+ data_file_config, dataset_type
21
+ )
22
+
23
+ year_key = f"{year}"[-2:]
24
+ dataset_prefix = dataset_config["prefix"].lower()
25
+ species_key = species_config["atomic_symbol"].lower()
26
+
27
+ output_filename = data_file_dir / f"{species_name}_{dataset_type}.dat"
28
+ query_path = f"{url_base}/download/{reader_class}/{dataset_prefix}{year_key}/{dataset_prefix}{year_key}_{species_key}.dat"
29
+
30
+ if not output_filename.exists():
31
+ if verbose >= 2:
32
+ print(f"Downloading {query_path} to {output_filename}")
33
+ urllib.request.urlretrieve(query_path, output_filename)
34
+ else:
35
+ if verbose >= 2:
36
+ print(f"Reusing {query_path} ({output_filename} already exists)")
37
+
38
+ if "OPEN-ADAS Error" in output_filename.read_text():
39
+ output_filename.unlink()
40
+ if verbose:
41
+ print(
42
+ f"Failed to download the {year} {dataset_prefix} for {species_name}"
43
+ )
@@ -0,0 +1,99 @@
1
+ import urllib.request
2
+ import shutil
3
+ from pathlib import Path
4
+ from .compile_with_f2py import compile_with_f2py
5
+
6
+
7
+ def prepare_adas_fortran_interface(reader_dir: Path, config: dict, verbose: int):
8
+ from ..shared import (
9
+ fortran_file_handling_source,
10
+ library_extensions,
11
+ )
12
+
13
+ fortran_file_handling_library = None
14
+ for file in reader_dir.iterdir():
15
+ if (
16
+ file.name.startswith("fortran_file_handling")
17
+ and file.suffix in library_extensions
18
+ ):
19
+ fortran_file_handling_library = file
20
+
21
+ if fortran_file_handling_library is None:
22
+ if verbose:
23
+ print(f"Compiling {reader_dir / 'fortran_file_handling.f90'}")
24
+ (reader_dir / "fortran_file_handling.f90").write_text(
25
+ fortran_file_handling_source.read_text()
26
+ )
27
+
28
+ fortran_file_handling_library = compile_with_f2py(
29
+ files_to_compile=[reader_dir / "fortran_file_handling.f90"],
30
+ module_name="fortran_file_handling",
31
+ output_folder=reader_dir,
32
+ )
33
+ elif verbose:
34
+ print(f"Reusing {fortran_file_handling_library}")
35
+
36
+ adf_file_reader = dict()
37
+ for reader_name in config.keys():
38
+ adf_file_reader[reader_name] = None
39
+
40
+ (reader_dir / reader_name).mkdir(exist_ok=True, parents=True)
41
+ for file in (reader_dir / reader_name).iterdir():
42
+ if file.name.startswith(reader_name) and file.suffix in library_extensions:
43
+ adf_file_reader[reader_name] = file
44
+
45
+ if adf_file_reader[reader_name] is None:
46
+ build_adas_file_reader(reader_dir, reader_name, verbose=verbose)
47
+ elif verbose:
48
+ print(f"Reusing {reader_name}_reader")
49
+
50
+
51
+ def build_adas_file_reader(
52
+ reader_dir: Path,
53
+ reader_name: str,
54
+ verbose: int,
55
+ url_base: str = "https://open.adas.ac.uk",
56
+ ):
57
+ """Builds an ADAS file reader by wrapping fortran code using f2py."""
58
+ from ..shared import reader_pyf_source
59
+
60
+ assert reader_name.startswith(
61
+ "adf"
62
+ ), f"Reader should be of the format adfXX where XX is an integer"
63
+
64
+ reader_int = int(reader_name.lstrip("adf"))
65
+ output_folder = reader_dir / reader_name
66
+ (output_folder / f"xxdata_{reader_int}.pyf").write_text(
67
+ reader_pyf_source[reader_name].read_text()
68
+ )
69
+
70
+ archive_file = f"xxdata_{reader_int}.tar.gz"
71
+ query_path = f"{url_base}/code/{archive_file}"
72
+ output_filename = output_folder / archive_file
73
+
74
+ if not output_filename.exists():
75
+ if verbose:
76
+ print(f"Downloading {query_path} to {output_filename}")
77
+ urllib.request.urlretrieve(query_path, output_filename)
78
+ if verbose:
79
+ print(f"Unpacking {output_filename} into {output_folder}")
80
+ shutil.unpack_archive(output_filename, output_folder)
81
+ else:
82
+ if verbose:
83
+ print(f"Reusing {query_path} ({output_filename} already exists)")
84
+
85
+ fortran_files = [
86
+ str(file)
87
+ for file in (output_folder / f"xxdata_{reader_int}").iterdir()
88
+ if (file.suffix == ".for") and not (file.stem == "test")
89
+ ]
90
+
91
+ fortran_files = fortran_files + [str(output_folder / f"xxdata_{reader_int}.pyf")]
92
+
93
+ if verbose:
94
+ print(f"Compiling {reader_name}")
95
+ compile_with_f2py(
96
+ files_to_compile=fortran_files,
97
+ module_name=f"{reader_name}_reader",
98
+ output_folder=output_folder,
99
+ )