radas 1!1.0.0__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.
radas-1!1.0.0/LICENSE ADDED
@@ -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.
radas-1!1.0.0/PKG-INFO ADDED
@@ -0,0 +1,146 @@
1
+ Metadata-Version: 2.4
2
+ Name: radas
3
+ Version: 1!1.0.0
4
+ Summary: Plasma radiated power calculated using OpenADAS
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Author: Commonwealth Fusion Systems
8
+ Requires-Python: >=3.12
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: Scientific/Engineering :: Physics
18
+ Requires-Dist: click (>=8.3.2,<9.0.0)
19
+ Requires-Dist: fortranformat (>=2.0.3,<3.0.0)
20
+ Requires-Dist: matplotlib (>=3.10.8,<4.0.0)
21
+ Requires-Dist: meson (>=1.10.2,<2.0.0)
22
+ Requires-Dist: ninja (>=1.13.0,<2.0.0)
23
+ Requires-Dist: numpy (>=2.4.4,<3.0.0)
24
+ Requires-Dist: pandas (>=3.0.2,<4.0.0)
25
+ Requires-Dist: pint (>=0.25.3,<0.26.0)
26
+ Requires-Dist: pint-xarray (>=0.6.1,<0.7.0)
27
+ Requires-Dist: pyyaml (>=6.0.3,<7.0.0)
28
+ Requires-Dist: scipy (>=1.17.1,<2.0.0)
29
+ Requires-Dist: xarray (>=2026.2.0)
30
+ Description-Content-Type: text/markdown
31
+
32
+ # RADAS: radiated power curves from OpenADAS
33
+
34
+ This Python library downloads atomic data from OpenADAS, performs simple calculations and stores the result as a NetCDF file for use in other programs.
35
+
36
+ ## Installing via PyPi (quick start)
37
+
38
+ `radas` is on PyPi. You should be able to install it using
39
+ ```
40
+ pip install radas
41
+ ```
42
+
43
+ Once you've installed `radas` into your environment, you should be able to run
44
+ ```
45
+ radas --help
46
+ ```
47
+ 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
48
+ ```
49
+ radas -s hydrogen -s helium -s lithium
50
+ ```
51
+
52
+ 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`).
53
+
54
+ ## Development installation
55
+
56
+ If you want to develop `radas`, excellent! For contributing to `radas`, we ask that you
57
+ 1. use Issues to ask questions, request features and discuss planned improvements,
58
+ 2. use Pull Requests to merge code into `main` (mark work-in-progress with `draft` in the title),
59
+ 3. write `pytest` tests for new functionality (ideally aiming to cover all new lines of code).
60
+
61
+ ### Installation
62
+
63
+ 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).
64
+
65
+ Once you have poetry installed, you can install `radas` by running
66
+ ```
67
+ poetry install
68
+ ```
69
+
70
+ Because we've added `in-project = true` in `poetry.toml`, the project will install in the `.venv` in the repository directory.
71
+
72
+ ### Usage
73
+
74
+ Once you have installed `radas`, you should be able to run the following snippet
75
+ ```
76
+ poetry run radas --species=hydrogen
77
+ ```
78
+ where `--species` can be
79
+ * a specific species such as `hydrogen` or `tungsten`
80
+ * `all` which runs all species which have available data
81
+ * `none` which only regenerates the output plots from existing NetCDF files
82
+
83
+ If anything goes wrong, the script will drop into an `ipdb` interpreter so you can debug any issues.
84
+
85
+ #### What's going on under the hood?
86
+
87
+ The above snippet executes `run_radas_cli` in `radas/cli.py`, which performs the following steps
88
+
89
+ 1. Connect to [OpenADAS](https://open.adas.ac.uk/)
90
+ 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`.
91
+ 5. Process the downloaded data files and store them in xarray Dataset (in `read_rate_coeffs.py`).
92
+ 6. Calculate the fractional abundance of each charge state according to the coronal approximation (in `coronal_equilibrium.py`).
93
+ 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).
94
+ 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`).
95
+ 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).
96
+ 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).
97
+
98
+ ### Configuration
99
+
100
+ `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
101
+ ```
102
+ globals:
103
+ evolution_start:
104
+ value: <Time to start time-evolution>
105
+ units: "s"
106
+
107
+ evolution_stop:
108
+ value: <Time to stop time-evolution>
109
+ units: "s"
110
+
111
+ ne_tau:
112
+ value: <Values of ne * tau to generate output for>
113
+ units: "m^-3 s"
114
+
115
+ data_file_config:
116
+ adf11: #or other reader class, but usually we want ADF11
117
+ <what to call the dataset in the output>:
118
+ prefix: <letters used to identify the dataset>
119
+ code: <code used to identify the dataset for the ADAS reader>
120
+ stored_units: "cm**3 / s"
121
+ desired_units: "m**3 / s"
122
+
123
+ species:
124
+ <species name>:
125
+ atomic_symbol: <symbol>
126
+ atomic_number: <atomic number>
127
+ data_files:
128
+ <dataset matching "what to call the dataset in the output" above>: <year to download>
129
+ ```
130
+
131
+ ### Testing
132
+
133
+ To make sure everything is working, run
134
+ ```
135
+ poetry run pytest
136
+ ```
137
+ to execute all of the tests in the `tests` folder.
138
+
139
+ ### Pushing to PyPi
140
+
141
+ **We have transitioned from a date-based versioning scheme (YYYY.MM.patch) to Semantic Versioning with an Epoch.**
142
+
143
+ To update the version of `radas` at [pypi.org/project/radas/](https://pypi.org/project/radas/), you should edit `pyproject.toml` and set `version="1!major.minor.patch"`. You must include the `1!` prefix (the epoch) so that any version takes precedence over the previous date-based versions. Use major versions to indicate breaking changes, such as changing the name of the CLI functions. Use minor versions to indicate non-breaking changes, such as adding new optional functionality. Use patches to make minor fixes.
144
+
145
+ Once you've merged a new version into `main`, make a new release [on Github](https://github.com/cfs-energy/radas/releases/new) and tag it using the form `v1!X.Y.Z`. Github Actions will automatically push this to PyPI.
146
+
@@ -0,0 +1,114 @@
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
+ ### Installation
31
+
32
+ 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).
33
+
34
+ Once you have poetry installed, you can install `radas` by running
35
+ ```
36
+ poetry install
37
+ ```
38
+
39
+ Because we've added `in-project = true` in `poetry.toml`, the project will install in the `.venv` in the repository directory.
40
+
41
+ ### Usage
42
+
43
+ Once you have installed `radas`, you should be able to run the following snippet
44
+ ```
45
+ poetry run radas --species=hydrogen
46
+ ```
47
+ where `--species` can be
48
+ * a specific species such as `hydrogen` or `tungsten`
49
+ * `all` which runs all species which have available data
50
+ * `none` which only regenerates the output plots from existing NetCDF files
51
+
52
+ If anything goes wrong, the script will drop into an `ipdb` interpreter so you can debug any issues.
53
+
54
+ #### What's going on under the hood?
55
+
56
+ The above snippet executes `run_radas_cli` in `radas/cli.py`, which performs the following steps
57
+
58
+ 1. Connect to [OpenADAS](https://open.adas.ac.uk/)
59
+ 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`.
60
+ 5. Process the downloaded data files and store them in xarray Dataset (in `read_rate_coeffs.py`).
61
+ 6. Calculate the fractional abundance of each charge state according to the coronal approximation (in `coronal_equilibrium.py`).
62
+ 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).
63
+ 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`).
64
+ 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).
65
+ 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).
66
+
67
+ ### Configuration
68
+
69
+ `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
70
+ ```
71
+ globals:
72
+ evolution_start:
73
+ value: <Time to start time-evolution>
74
+ units: "s"
75
+
76
+ evolution_stop:
77
+ value: <Time to stop time-evolution>
78
+ units: "s"
79
+
80
+ ne_tau:
81
+ value: <Values of ne * tau to generate output for>
82
+ units: "m^-3 s"
83
+
84
+ data_file_config:
85
+ adf11: #or other reader class, but usually we want ADF11
86
+ <what to call the dataset in the output>:
87
+ prefix: <letters used to identify the dataset>
88
+ code: <code used to identify the dataset for the ADAS reader>
89
+ stored_units: "cm**3 / s"
90
+ desired_units: "m**3 / s"
91
+
92
+ species:
93
+ <species name>:
94
+ atomic_symbol: <symbol>
95
+ atomic_number: <atomic number>
96
+ data_files:
97
+ <dataset matching "what to call the dataset in the output" above>: <year to download>
98
+ ```
99
+
100
+ ### Testing
101
+
102
+ To make sure everything is working, run
103
+ ```
104
+ poetry run pytest
105
+ ```
106
+ to execute all of the tests in the `tests` folder.
107
+
108
+ ### Pushing to PyPi
109
+
110
+ **We have transitioned from a date-based versioning scheme (YYYY.MM.patch) to Semantic Versioning with an Epoch.**
111
+
112
+ To update the version of `radas` at [pypi.org/project/radas/](https://pypi.org/project/radas/), you should edit `pyproject.toml` and set `version="1!major.minor.patch"`. You must include the `1!` prefix (the epoch) so that any version takes precedence over the previous date-based versions. Use major versions to indicate breaking changes, such as changing the name of the CLI functions. Use minor versions to indicate non-breaking changes, such as adding new optional functionality. Use patches to make minor fixes.
113
+
114
+ Once you've merged a new version into `main`, make a new release [on Github](https://github.com/cfs-energy/radas/releases/new) and tag it using the form `v1!X.Y.Z`. Github Actions will automatically push this to PyPI.
@@ -0,0 +1,62 @@
1
+ [tool.poetry]
2
+ name = "radas"
3
+ # As of version 1!1.0.0, this project has switched to a PEP 440 epoch-based
4
+ # versioning scheme. The 1! prefix is mandatory. Because our previous versioning
5
+ # used a date-based format (e.g., 2025.6.2), package managers will treat
6
+ # Semantic Versioning (i.e. 1.0.0) as an "older" release. The epoch ensures that
7
+ # the new versioning takes precedence over all legacy YYYY.MM.version releases.
8
+ version = "1!1.0.0"
9
+ description = "Plasma radiated power calculated using OpenADAS"
10
+ authors = ["Commonwealth Fusion Systems"]
11
+ readme = "README.md"
12
+ license = "MIT"
13
+ classifiers = [
14
+ "Development Status :: 5 - Production/Stable",
15
+ "Intended Audience :: Science/Research",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Programming Language :: Python :: 3.14",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: Scientific/Engineering :: Physics",
22
+ ]
23
+
24
+ [tool.poetry.scripts]
25
+ radas = 'radas.cli:run_radas_cli'
26
+ run_radas = 'radas.cli:run_radas_cli'
27
+ radas_config = 'radas.cli:write_config_template'
28
+
29
+ [tool.poetry.dependencies]
30
+ python = ">=3.12"
31
+ numpy = "^2.4.4"
32
+ scipy = "^1.17.1"
33
+ matplotlib = "^3.10.8"
34
+ pint = "^0.25.3"
35
+ pyyaml = "^6.0.3"
36
+ # Since xarray uses year.month.version, allow the "major" version to increase.
37
+ xarray = ">=2026.2.0"
38
+ pint-xarray = "^0.6.1"
39
+ pandas = "^3.0.2"
40
+ click = "^8.3.2"
41
+ meson = "^1.10.2"
42
+ ninja = "^1.13.0"
43
+ fortranformat = "^2.0.3"
44
+
45
+ [tool.poetry.group.dev.dependencies]
46
+ pytest = "^9.0.3"
47
+ pytest-order = "^1.3.0"
48
+ pytest-cov = "^7.1.0"
49
+ coverage = "^7.13.5"
50
+ ipdb = "^0.13.13"
51
+
52
+ [build-system]
53
+ requires = ["poetry-core>=2.0.0"]
54
+ build-backend = "poetry.core.masonry.api"
55
+
56
+ [tool.pytest.ini_options]
57
+ markers = [
58
+ "slow: marks tests as slow (deselect with '-m \"not slow\"')",
59
+ ]
60
+ addopts = "--cov=radas --cov-branch --cov-report term --cov-report xml:coverage.xml --import-mode=importlib"
61
+ pythonpath = ["."]
62
+ testpaths = ["tests"]
@@ -0,0 +1,39 @@
1
+ from .unit_handling import (
2
+ DimensionalityError,
3
+ UnitStrippedWarning,
4
+ ureg,
5
+ Quantity,
6
+ convert_units,
7
+ magnitude,
8
+ dimensionless_magnitude,
9
+ )
10
+
11
+ from .cli import (
12
+ run_radas_cli,
13
+ run_radas,
14
+ run_radas_computation,
15
+ write_config_template,
16
+ )
17
+
18
+ from .read_rate_coeffs import read_rate_coeff
19
+ from .coronal_equilibrium import calculate_coronal_fractional_abundances
20
+ from .radiated_power import calculate_Lz
21
+ from .time_evolution import calculate_time_evolution
22
+
23
+ __all__ = [
24
+ "DimensionalityError",
25
+ "UnitStrippedWarning",
26
+ "ureg",
27
+ "Quantity",
28
+ "convert_units",
29
+ "magnitude",
30
+ "dimensionless_magnitude",
31
+ "run_radas_cli",
32
+ "run_radas",
33
+ "run_radas_computation",
34
+ "read_rate_coeff",
35
+ "calculate_coronal_fractional_abundances",
36
+ "calculate_Lz",
37
+ "calculate_time_evolution",
38
+ "write_config_template",
39
+ ]
@@ -0,0 +1,9 @@
1
+ from .determine_adas_dataset_type import determine_reader_class_and_config
2
+ from .download_adas_datasets import download_species_data
3
+ from .read_adf11_file import read_adf11_file
4
+
5
+ __all__ = [
6
+ "determine_reader_class_and_config",
7
+ "download_species_data",
8
+ "read_adf11_file",
9
+ ]
@@ -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,51 @@
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, file_to_download 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
+ if isinstance(file_to_download, int):
24
+ species_key = species_config["atomic_symbol"].lower()
25
+ year = file_to_download
26
+ elif isinstance(file_to_download, list) and len(file_to_download) == 2:
27
+ species_key = file_to_download[0].lower()
28
+ year = file_to_download[1]
29
+ else:
30
+ raise NotImplementedError(f"Could not process entry: {file_to_download} for {species_name} {dataset_type}")
31
+
32
+ year_key = f"{year}"[-2:]
33
+ dataset_prefix = dataset_config["prefix"].lower()
34
+
35
+ output_filename = data_file_dir / f"{species_name}_{dataset_type}.dat"
36
+ query_path = f"{url_base}/download/{reader_class}/{dataset_prefix}{year_key}/{dataset_prefix}{year_key}_{species_key}.dat"
37
+
38
+ if not output_filename.exists():
39
+ if verbose >= 2:
40
+ print(f"Downloading {query_path} to {output_filename}")
41
+ urllib.request.urlretrieve(query_path, output_filename)
42
+ else:
43
+ if verbose >= 2:
44
+ print(f"Reusing {query_path} ({output_filename} already exists)")
45
+
46
+ if "OPEN-ADAS Error" in output_filename.read_text():
47
+ output_filename.unlink()
48
+ if verbose:
49
+ print(
50
+ f"Failed to download the {year} {dataset_prefix} for {species_name}"
51
+ )
@@ -0,0 +1,67 @@
1
+ import numpy as np
2
+ from fortranformat import FortranRecordReader as FReader
3
+
4
+ def read_single_values(list_of_lines, format_spec, start_at_line):
5
+ """
6
+ Makes a 'generator', which is a special Python object that returns a value each time that it is called.
7
+
8
+ This generator reads each line in the list of lines, and tries to format it according to format_spec
9
+ For instance, the default format '5e16.9' will try to read 5 fortran-formatted floats in exponential format
10
+ with a width of 16 characters and 9 characters after the decimal point
11
+ Where there are less than 5 numbers on a line, the fortran reader will return 'None'. These are skipped (not
12
+ returned by the generator)
13
+
14
+ The generator returns the next value according to the specified format, and also the line number and position being read
15
+ """
16
+ for line_number, line in enumerate(list_of_lines):
17
+ if line_number < start_at_line:
18
+ continue
19
+
20
+ try:
21
+ values = FReader(f"({format_spec})").read(line)
22
+ except ValueError as e:
23
+ message = (
24
+ f"fortranformat could not read line {line_number}: {line} with format ({format_spec})\n"
25
+ "Make sure that your format_spec has the correct number of elements, the correct spacing and the correct format for the line.\n"
26
+ "See https://docs.oracle.com/cd/E19957-01/805-4939/6j4m0vn9f/index.html for reference.\n"
27
+ f"fortranformat error was: {e}"
28
+ )
29
+ raise ValueError(message) from e
30
+
31
+
32
+ for value_position, value in enumerate(values):
33
+ if value is not None:
34
+ yield value, line_number, value_position
35
+
36
+ def read_1d_array(generator, number_of_values):
37
+ """
38
+ Take number_of_values from the generator and write it into a 1D array
39
+ """
40
+ array = np.zeros(number_of_values)
41
+ line_number, value_position = 0, 0
42
+
43
+ for i in range(number_of_values):
44
+ value, line_number, value_position = next(generator)
45
+
46
+ if i == 0:
47
+ assert value_position == 0, \
48
+ "Arrays are always defined as starting on a new line, but the first element in this array is not at position 0"
49
+
50
+ array[i] = value
51
+
52
+ return array, line_number, value_position
53
+
54
+ def read_2d_array(generator, rows, columns, fortran_order_arrays=False):
55
+ """
56
+ Take rows*columns from the generator and write it into a 2D array of
57
+ shape (rows, columns), or (columns, rows) if transpose = True
58
+ """
59
+ number_of_values = rows * columns
60
+ array, line_number, value_position = read_1d_array(generator, number_of_values)
61
+
62
+ if fortran_order_arrays:
63
+ array = array.reshape((rows, columns))
64
+ else:
65
+ array = array.reshape((columns, rows))
66
+
67
+ return array, line_number, value_position
@@ -0,0 +1,59 @@
1
+ from pathlib import Path
2
+ import importlib.util
3
+ from .fortran_reader import FReader, read_single_values, read_1d_array, read_2d_array
4
+ import numpy as np
5
+
6
+
7
+ def load_library(library_name: str, filepath: Path):
8
+ spec = importlib.util.spec_from_file_location(library_name, filepath)
9
+
10
+ library = importlib.util.module_from_spec(spec)
11
+ spec.loader.exec_module(library)
12
+
13
+ return library
14
+
15
+
16
+ def read_adf11_file(
17
+ data_file_dir, species_name, dataset_type
18
+ ) -> dict:
19
+ """Open and read an ADF11 OpenADAS file.
20
+
21
+ Uses the format specification from https://www.adas.ac.uk/man/appxa-11.pdf
22
+ """
23
+
24
+
25
+ filename = data_file_dir / f"{species_name}_{dataset_type}.dat"
26
+ if not filename.exists():
27
+ raise FileNotFoundError(f"{filename} does not exist.")
28
+
29
+ f = filename.read_text().split("\n")
30
+
31
+ IZMAX, IDMAXD, ITMAXD, IZ1MIN, IZ1MAX = FReader("5i5").read(f[0])
32
+
33
+ # Initialise the value reader
34
+
35
+ # IMPORTANT: do not reinitialise the reader, since otherwise we'll loose the position of the reader
36
+ # Note that line_numbers will be reported from the read-offset
37
+ value_reader = read_single_values(f, start_at_line=2, format_spec="8f10.5")
38
+
39
+ DDENSD, line_number, _ = read_1d_array(value_reader, number_of_values=IDMAXD)
40
+ DTEVD, line_number, _ = read_1d_array(value_reader, number_of_values=ITMAXD)
41
+
42
+ DRCOFD = np.zeros((IZMAX, ITMAXD, IDMAXD))
43
+
44
+ for IZ1 in range(IZMAX):
45
+ value_reader = read_single_values(f, start_at_line=line_number + 2, format_spec="8f10.5")
46
+ DRCOFD[IZ1, :, :], line_number, _ = read_2d_array(value_reader, rows=IDMAXD, columns=ITMAXD, fortran_order_arrays=False)
47
+
48
+ data = dict(
49
+ IZMAX = IZMAX,
50
+ IDMAXD = IDMAXD,
51
+ ITMAXD = ITMAXD,
52
+ IZ1MIN = IZ1MIN,
53
+ IZ1MAX = IZ1MAX,
54
+ DDENSD = DDENSD,
55
+ DTEVD = DTEVD,
56
+ DRCOFD = DRCOFD,
57
+ )
58
+
59
+ return data