diff --git a/.github/workflows/process.yml b/.github/workflows/process.yml index ed60185904..698459855a 100644 --- a/.github/workflows/process.yml +++ b/.github/workflows/process.yml @@ -178,7 +178,6 @@ jobs: uses: Fusion-Power-Plant-Framework/fppf-actions/setup-hatch@main with: python-version: ${{ env.python-version }} - - run: hatch run python scripts/vardes.py - run: git config --global --add safe.directory '*' - name: Download STF_TF.json files uses: actions/download-artifact@v4 diff --git a/.gitignore b/.gitignore index 93f469d2f4..a6236b708a 100644 --- a/.gitignore +++ b/.gitignore @@ -46,10 +46,8 @@ process/io/python_fortran_dicts.json fortran.py .coverage dist/* -documentation/io/vardes.md lcov_results/ env/ -env_process/ .venv *.DAT !scenario_examples/*/*.DAT diff --git a/documentation/examples b/documentation/examples deleted file mode 120000 index a6573af9c9..0000000000 --- a/documentation/examples +++ /dev/null @@ -1 +0,0 @@ -../examples \ No newline at end of file diff --git a/documentation/python/process.io.md b/documentation/python/process.io.md deleted file mode 100644 index d4a708633f..0000000000 --- a/documentation/python/process.io.md +++ /dev/null @@ -1,23 +0,0 @@ -# process.io - -::: process.io.configuration - -::: process.io.in_dat - -::: process.io.mfile_comparison - -::: process.io.mfile - -::: process.io.ndscan_funcs - -::: process.io.obsolete_vars - -::: process.io.plot_proc - -::: process.io.plot_sankey - - - -::: process.io.process_funcs - -::: process.io.python_fortran_dicts \ No newline at end of file diff --git a/documentation/python/process.md b/documentation/python/process.md deleted file mode 100644 index 9a707e67d4..0000000000 --- a/documentation/python/process.md +++ /dev/null @@ -1,15 +0,0 @@ -# process - -::: process.main - -::: process.caller - -::: process.evaluators - -::: process.optimiser - -::: process.scan - -::: process.vmcon - -::: process.final \ No newline at end of file diff --git a/documentation/scripts/gen_api_ref.py b/documentation/scripts/gen_api_ref.py new file mode 100644 index 0000000000..38eb4f7986 --- /dev/null +++ b/documentation/scripts/gen_api_ref.py @@ -0,0 +1,37 @@ +# SPDX-FileCopyrightText: 2023-present The Bluemira Developers +# +# SPDX-License-Identifier: LGPL-2.1-or-later +"""Generate the API reference pages and navigation.""" + +from pathlib import Path + +import mkdocs_gen_files +from mkdocs_gen_files.nav import Nav + +nav = Nav() + +root = Path(__file__).parent.parent.parent +package_name = "process" +src = root / package_name +reference = Path("source", "reference") + +for path in sorted(src.rglob("*.py")): + module_path = path.relative_to(root).with_suffix("") + doc_path = path.relative_to(root).with_suffix(".md") + full_doc_path = Path(reference, doc_path) + + parts = tuple(module_path.parts) + + if parts[-1] in {"__init__", "__main__", "_version"}: + continue + + p = ".".join(parts) + nav[parts] = doc_path.as_posix() + + with mkdocs_gen_files.open(full_doc_path, "w") as fd: + fd.write(f"::: {p}") + + mkdocs_gen_files.set_edit_path(full_doc_path, path.relative_to(root)) + +with mkdocs_gen_files.open(Path(reference, "overview.md"), "w") as nav_file: + nav_file.writelines(nav.build_literate_nav()) diff --git a/documentation/scripts/plotting_scripts/menard_beta_norm_plot.py b/documentation/scripts/plotting_scripts/menard_beta_norm_plot.py index 98eb0a9f34..5d079b4964 100644 --- a/documentation/scripts/plotting_scripts/menard_beta_norm_plot.py +++ b/documentation/scripts/plotting_scripts/menard_beta_norm_plot.py @@ -11,13 +11,13 @@ y_range=(2, 8), width=400, height=400, - title="Menard Normalized Beta Limit", + title="Menard Normalised Beta Limit", ) plot.xaxis.axis_label = r"Aspect ratio, \ $$[A]$$" -plot.yaxis.axis_label = r"Normalized beta limit, \ $$[\beta_N]$$" +plot.yaxis.axis_label = r"Normalised beta limit, \ $$[\beta_N]$$" plot.line("x", "y", source=source, line_width=3, line_alpha=0.6) # Save the plot as HTML -output_file("menard_beta_norm.html", title="Menard Normalized Beta Limit") +output_file("menard_beta_norm.html", title="Menard Normalised Beta Limit") save(plot) diff --git a/documentation/scripts/plotting_scripts/original_beta_norm_plot.py b/documentation/scripts/plotting_scripts/original_beta_norm_plot.py index ad0bf9e4f1..38a8407fa4 100644 --- a/documentation/scripts/plotting_scripts/original_beta_norm_plot.py +++ b/documentation/scripts/plotting_scripts/original_beta_norm_plot.py @@ -11,13 +11,13 @@ y_range=(2, 15), width=400, height=400, - title="Original Normalized Beta Limit", + title="Original Normalised Beta Limit", ) plot.xaxis.axis_label = r"Aspect ratio, \ $$[A]$$" -plot.yaxis.axis_label = r"Normalized beta limit, \ $$[\beta_N]$$" +plot.yaxis.axis_label = r"Normalised beta limit, \ $$[\beta_N]$$" plot.line("x", "y", source=source, line_width=3, line_alpha=0.6) # Save the plot as HTML -output_file("original_beta_norm.html", title="Original Normalized Beta Limit") +output_file("original_beta_norm.html", title="Original Normalised Beta Limit") save(plot) diff --git a/documentation/scripts/plotting_scripts/profile_hastie_current.py b/documentation/scripts/plotting_scripts/profile_hastie_current.py index 3a1644a89d..a7c08ac3d2 100644 --- a/documentation/scripts/plotting_scripts/profile_hastie_current.py +++ b/documentation/scripts/plotting_scripts/profile_hastie_current.py @@ -16,7 +16,7 @@ height=400, title="PROCESS vs Hastie Current Profile", ) -plot.xaxis.axis_label = "Normalized Plasma Radius" +plot.xaxis.axis_label = "Normalised Plasma Radius" plot.yaxis.axis_label = "Current Density, J" plot.line( diff --git a/documentation/scripts/plotting_scripts/profile_parabolic_plot.py b/documentation/scripts/plotting_scripts/profile_parabolic_plot.py index 2a1fc471ed..f6f232ff10 100644 --- a/documentation/scripts/plotting_scripts/profile_parabolic_plot.py +++ b/documentation/scripts/plotting_scripts/profile_parabolic_plot.py @@ -15,7 +15,7 @@ height=400, title="Parabolic Profile | L-mode", ) -plot.xaxis.axis_label = r"Normalized Radius, $$ \rho $$" +plot.xaxis.axis_label = r"Normalised Radius, $$ \rho $$" plot.yaxis.axis_label = r"Density, $$n_e$$" plot.line("x", "y", source=source, line_width=3, line_alpha=0.6) diff --git a/documentation/scripts/plotting_scripts/profile_pedestal_plot.py b/documentation/scripts/plotting_scripts/profile_pedestal_plot.py index e31b6f88e5..576cd55783 100644 --- a/documentation/scripts/plotting_scripts/profile_pedestal_plot.py +++ b/documentation/scripts/plotting_scripts/profile_pedestal_plot.py @@ -29,7 +29,7 @@ height=400, title="Pedestal Profile | H-mode", ) -plot.xaxis.axis_label = r"Normalized Radius, $$ \rho $$" +plot.xaxis.axis_label = r"Normalised Radius, $$ \rho $$" plot.yaxis.axis_label = r"Density, $$n_e$$" plot.line("x", "y", source=source, line_width=3, line_alpha=0.6) diff --git a/documentation/scripts/sort_vardes.py b/documentation/scripts/sort_vardes.py deleted file mode 100644 index bbef41d9cd..0000000000 --- a/documentation/scripts/sort_vardes.py +++ /dev/null @@ -1,34 +0,0 @@ -""" - -Script to tidy up vardes.md for the GitLab Page - -J. Morris -10/08/19 -UKAEA - -""" - -import sys - -with open(sys.argv[1]) as vardes: - lines = vardes.readlines() - -new_lines = [] - -for counter, line in enumerate(lines): - if "PROCESS Variable Descriptor File : dated" in line: - date = line.split("dated")[-1].replace(" ", "") - new_date = date[:4] + "." + date[4:6] + "." + date[6:] - new_line = f"# PROCESS Variable Descriptions {new_date}\n" - elif counter == 3: - new_line = "## Introduction" - elif "###" in line: - new_line = line.split("]")[0].replace("[", "").replace(r"\_", " ") - else: - new_line = line - - new_lines.append(new_line) - -with open(sys.argv[1], "w") as new_vardes: - new_vardes.writelines(new_lines) - new_vardes.close() diff --git a/documentation/cost-models/cost-models.md b/documentation/source/cost-models/cost-models.md similarity index 95% rename from documentation/cost-models/cost-models.md rename to documentation/source/cost-models/cost-models.md index 1947ea324c..4b3f0221fa 100644 --- a/documentation/cost-models/cost-models.md +++ b/documentation/source/cost-models/cost-models.md @@ -4,7 +4,7 @@ Two cost models are available, determined by the switch `cost_model`. ## 1990 cost model (`cost_model = 0`) -This combines methods[^1] used in the TETRA code [^2] and the Generomak[^3] scheme. The costs are split into accounting categories[^4]. The best references for the algorithms used are[^5], and source file `costs.f90` in the code itself. The majority of the costed items have a unit cost associated with them. These values scale with (for example) power output, volume, component mass etc., and many are avaiable to be changed via the input file. All costs and their algorithms correspond to 1990 dollars. +This combines methods[^1] used in the TETRA code [^2] and the Generomak[^3] scheme. The costs are split into accounting categories[^4]. The best references for the algorithms used are[^5], and source file `costs.f90` in the code itself. The majority of the costed items have a unit cost associated with them. These values scale with (for example) power output, volume, component mass etc., and many are available to be changed via the input file. All costs and their algorithms correspond to 1990 dollars. The unit costs of the components of the fusion power core are relevant to "first-of-a-kind" items. That is to say, the items are assumed to be relatively expensive to build as they are effectively prototypes and specialised tools and machines have perhaps been made specially to create them. However, if a "production line" has been set up, and R & D progress has allowed more experience to be gained in constructing the power core components, the cost will be reduced as a result. Variable `fkind` may be used to multiply the raw unit costs of the fusion power core items (by a factor less than one) to simulate this cost reduction for an *Nth*-of-a-kind device. In other systems studies of fusion power plants[^6], values for this multiplier have ranged from 0.5 to 0.8. @@ -14,7 +14,7 @@ The first wall, blanket, divertor, centrepost (if present) and current drive sys If the switch `ireactor = 0`, no cost of electricity calculation is performed. If `ireactor = 1`, then the cost of electricity is evaluated, with the value quoted in units of $/MWh. -The net electric power is calculated in routine `POWER` It is possible that the net electric power can become negative due to a high recirculating power. Switch `ipnet` determines whether the net electric power is scaled to always reamin positive (`ipnet = 0`, or whether it is allowed to become negative (`ipnet = 1`), in which case no cost of electricity calculation is performed. +The net electric power is calculated in routine `POWER` It is possible that the net electric power can become negative due to a high recirculating power. Switch `ipnet` determines whether the net electric power is scaled to always remain positive (`ipnet = 0`, or whether it is allowed to become negative (`ipnet = 1`), in which case no cost of electricity calculation is performed. ## 2015 Kovari model (`cost_model = 1`) diff --git a/documentation/development/add-vars.md b/documentation/source/development/add-vars.md similarity index 91% rename from documentation/development/add-vars.md rename to documentation/source/development/add-vars.md index d3299bb05f..67206c71cb 100644 --- a/documentation/development/add-vars.md +++ b/documentation/source/development/add-vars.md @@ -58,7 +58,7 @@ To add a `PROCESS` iteration variable please follow the steps below, in addition 1. The parameter `ipnvars` in module `numerics` of `numerics.f90` will normally be greater than the actual number of iteration variables, and does not need to be changed. 2. Append a new iteration number key to the end of the `ITERATION_VARIABLES` dictionary in `iteration_variables.py`. The associated variable is the corresponding key value. 3. Set the variable origin file and then the associated lower and upper bounds -4. Update the `lablxc` derscription in `numerics.f90`. +4. Update the `lablxc` description in `numerics.f90`. It should be noted that iteration variables must not be reset elsewhere in the code. That is, they may only be assigned new values when originally @@ -110,7 +110,7 @@ After following the instruction to add an input variable, you can make the varia 2. Add a short description of the new scanning variable in the `nsweep` comment in `scan_variables.py`, alongside its identification number. -3. Update the `SCAN_VARIABLES` dictionary in the `scan.py` file by adding a new case statement connecting the variable to the scan integer switch, the variable name and a short description. +3. Update the `ScanVariables` enum in the `scan.py` file by adding a new case statement connecting the variable to the scan integer switch, the variable name and a short description. 4. Add a comment in the corresponding variable file in the data_structure directory, eg, `data_structure/[XX]_variables.py`, to add the variable description indicating the scan switch number. @@ -130,12 +130,12 @@ After following the instruction to add an input variable, you can make the varia `SCAN_VARIABLES` case example: ```python - SCAN_VARIABLES = { - 1: ScanVariable("aspect", "Aspect_ratio"), - 2: ScanVariable("pflux_div_heat_load_max_mw", "Div_heat_limit_(MW/m2)"), + class ScanVariables(Enum): + aspect: ScanVariable("aspect", "Aspect_ratio", 1), + pflux_div_heat_load_max_mw: ScanVariable("pflux_div_heat_load_max_mw", "Div_heat_limit_(MW/m2)", 2), ... - 54: ScanVariable("Bc2(0K)", "GL_NbTi Bc2(0K)"), - 55: ScanVariable("dr_shld_inboard", "Inboard neutronic shield"), + Bc2_0K: ScanVariable("Bc2(0K)", "GL_NbTi Bc2(0K)", 54), + dr_shld_inboard : ScanVariable("dr_shld_inboard", "Inboard neutronic shield", 55), ``` --------------- @@ -170,4 +170,4 @@ def my_constraint_function(): value = ... error = ... return ConstraintResult(normalised_residual, value, error) -``` \ No newline at end of file +``` diff --git a/documentation/development/ci-guide.md b/documentation/source/development/ci-guide.md similarity index 100% rename from documentation/development/ci-guide.md rename to documentation/source/development/ci-guide.md diff --git a/documentation/development/debugging.md b/documentation/source/development/debugging.md similarity index 98% rename from documentation/development/debugging.md rename to documentation/source/development/debugging.md index 4b3a8e5942..aab5462a69 100644 --- a/documentation/development/debugging.md +++ b/documentation/source/development/debugging.md @@ -3,7 +3,7 @@ Debugging allows you stop a program mid-execution (called 'breaking') and explore the current state (e.g. print the current value of variables or attributes). In Python, this is done using `pdb` which comes as-standard with Python. First, you must decide where in the code you would like to break. When debugging, a useful way to -decide is to look at the terminal for where the error may have occured and break there. To insert a +decide is to look at the terminal for where the error may have occurred and break there. To insert a breakpoint in the code, insert the following code where you want the code to break: ```python diff --git a/documentation/development/git-usage.md b/documentation/source/development/git-usage.md similarity index 100% rename from documentation/development/git-usage.md rename to documentation/source/development/git-usage.md diff --git a/documentation/development/numba.md b/documentation/source/development/numba.md similarity index 100% rename from documentation/development/numba.md rename to documentation/source/development/numba.md diff --git a/documentation/development/pre-commit.md b/documentation/source/development/pre-commit.md similarity index 100% rename from documentation/development/pre-commit.md rename to documentation/source/development/pre-commit.md diff --git a/documentation/development/standards.md b/documentation/source/development/standards.md similarity index 95% rename from documentation/development/standards.md rename to documentation/source/development/standards.md index 34a142e130..d4c4773068 100644 --- a/documentation/development/standards.md +++ b/documentation/source/development/standards.md @@ -8,7 +8,7 @@ You can check if your code meets the `ruff` standards by running: 2. `pre-commit run --all-files` !!! Info "ruff automatic fixes" - Many problems that `ruff` can detect it can also safely fix. Simply run `ruff check --fix` and it will try and automatically fix the mistakes, rewritting your source code. + Many problems that `ruff` can detect it can also safely fix. Simply run `ruff check --fix` and it will try and automatically fix the mistakes, rewriting your source code. -------------------- @@ -601,7 +601,7 @@ ii | `b_t_onaxis` | Toroidal field on-axis | T | | `b_t_max` | Max toroidal field | T | | `nd_electron_vol` | Volume average electron density | m-3 | -| `temp_electron_vol_eV` | Volume avgerage electron temperature | eV | +| `temp_electron_vol_eV` | Volume average electron temperature | eV | | `m_steel` | Mass of steel | kg | | `m_steel_tonne` | Mass of steel | tonne | | `e_neutron_eV` | Energy of neutron | eV | @@ -634,26 +634,39 @@ The docstring style is that of the [Sphinx type](https://www.sphinx-doc.org/en/m If writing in new Python functions please use the docstring template below. ```python -def function_name(param1, param2): +def function_name(param1: Any, param2: Any) -> Any: """ Brief description of what the function does. Detailed description of the function. This can include information about the algorithm, any important notes, and other relevant details. - :param type param1: Description of the first parameter. - :param type param2: Description of the second parameter. - :returns: Description of the return value. - :rtype: return_type - :raises ExceptionType: Description of the exception raised (if any). - - :notes: - - Additional notes about the function. - - Any important considerations or caveats. - - :references: - - Reference 1: Description of the reference. - - Reference 2: Description of the reference. + Parameters + ---------- + param1: + Description of the first parameter. + param2: + Description of the second parameter. + + Returns + ------- + : + Description of the return value. + + Raises + ------ + ExceptionType + Description of the exception raised (if any). + + Notes + ----- + - Additional notes about the function. + - Any important considerations or caveats. + + References + ---------- + - Reference 1: Description of the reference. + - Reference 2: Description of the reference. """ ``` @@ -700,4 +713,4 @@ class ExampleClass: - Use inline comments sparingly. -- Comments above apply to code below. \ No newline at end of file +- Comments above apply to code below. diff --git a/documentation/development/testing.md b/documentation/source/development/testing.md similarity index 100% rename from documentation/development/testing.md rename to documentation/source/development/testing.md diff --git a/documentation/development/versioning.md b/documentation/source/development/versioning.md similarity index 100% rename from documentation/development/versioning.md rename to documentation/source/development/versioning.md diff --git a/documentation/eng-models/blanket_overview.md b/documentation/source/eng-models/blanket_overview.md similarity index 96% rename from documentation/eng-models/blanket_overview.md rename to documentation/source/eng-models/blanket_overview.md index a04afb1a77..71ea951c26 100644 --- a/documentation/eng-models/blanket_overview.md +++ b/documentation/source/eng-models/blanket_overview.md @@ -48,7 +48,7 @@ Using the Reynolds number we calculate the Darcy friction factor using the Haala For the radius of the pipe bend we assume it to be 3 times the radius of the coolant channel. -The elbow coefficients for the 90 and 180 degree bends $\left(f_{\text{90,elbow}}, f_{\text{180,elbow}}\right)$ are clalculated via [`elbow_coeff()`](#pipe-bend-elbow-coefficient--elbow_coeff). +The elbow coefficients for the 90 and 180 degree bends $\left(f_{\text{90,elbow}}, f_{\text{180,elbow}}\right)$ are calculated via [`elbow_coeff()`](#pipe-bend-elbow-coefficient--elbow_coeff). The pressure drop for the straights along the entire pipe length is the same as above: diff --git a/documentation/eng-models/buildings.md b/documentation/source/eng-models/buildings.md similarity index 100% rename from documentation/eng-models/buildings.md rename to documentation/source/eng-models/buildings.md diff --git a/documentation/eng-models/ccfe_hcpb.md b/documentation/source/eng-models/ccfe_hcpb.md similarity index 100% rename from documentation/eng-models/ccfe_hcpb.md rename to documentation/source/eng-models/ccfe_hcpb.md diff --git a/documentation/eng-models/central-solenoid.md b/documentation/source/eng-models/central-solenoid.md similarity index 99% rename from documentation/eng-models/central-solenoid.md rename to documentation/source/eng-models/central-solenoid.md index 8346dfb1ad..354aa3ae10 100644 --- a/documentation/eng-models/central-solenoid.md +++ b/documentation/source/eng-models/central-solenoid.md @@ -80,7 +80,7 @@ $$ where $\alpha = \frac{r_{\text{CS,outer}}}{r_{\text{CS,inner}}}$, is the ratio of the outer and inner radii of the solenoid and $\beta = \frac{z_{\text{CS,half}}}{r_{\text{CS,outer}}}$, is the ratio of the solenoid half height to its inboard radius. -The peak field at the bore of the central solenoid will not be the same as that felt by the conductors inside the structures. We require to know the peak field on the conductor if we are to design a superconducting central solenoid that has enough margin. Fits to data[^1] for different ranges of $\beta$ have been calulated as follows: +The peak field at the bore of the central solenoid will not be the same as that felt by the conductors inside the structures. We require to know the peak field on the conductor if we are to design a superconducting central solenoid that has enough margin. Fits to data[^1] for different ranges of $\beta$ have been calculated as follows: - $\beta > 3.0$ diff --git a/documentation/eng-models/cryostat-and-vacuum-system.md b/documentation/source/eng-models/cryostat-and-vacuum-system.md similarity index 100% rename from documentation/eng-models/cryostat-and-vacuum-system.md rename to documentation/source/eng-models/cryostat-and-vacuum-system.md diff --git a/documentation/eng-models/divertor.md b/documentation/source/eng-models/divertor.md similarity index 98% rename from documentation/eng-models/divertor.md rename to documentation/source/eng-models/divertor.md index c031cbb91d..7eb1d26c5d 100644 --- a/documentation/eng-models/divertor.md +++ b/documentation/source/eng-models/divertor.md @@ -95,7 +95,7 @@ $$ The main assumption of the Peng gaseous divertor model is that the power radiated to the divertor is equally radiated in the divertor box across all three surfaces. This may not truly be the case in reality. -The interactive graph below can be used to investigate how changing the key prameters changes the divertor configuration. The grey box represents the first wall, the far right red line represents the right hand edge of the divertor region ($r_{\text{outer}}$), the far left red line represents the left hand edge of the divertor region ($r_{\text{inner}}$) and the blue line represents the bottom of the divertor region ($\Delta z_{\text{plasma,div}}$). +The interactive graph below can be used to investigate how changing the key parameters changes the divertor configuration. The grey box represents the first wall, the far right red line represents the right hand edge of the divertor region ($r_{\text{outer}}$), the far left red line represents the left hand edge of the divertor region ($r_{\text{inner}}$) and the blue line represents the bottom of the divertor region ($\Delta z_{\text{plasma,div}}$). ------------- diff --git a/documentation/eng-models/fw-blanket.md b/documentation/source/eng-models/fw-blanket.md similarity index 98% rename from documentation/eng-models/fw-blanket.md rename to documentation/source/eng-models/fw-blanket.md index 5dd5fc460a..d1ca05bcaa 100644 --- a/documentation/eng-models/fw-blanket.md +++ b/documentation/source/eng-models/fw-blanket.md @@ -269,22 +269,22 @@ $$ ### Model Switches There are three blanket model options, chosen by the user to match their selected blanket design using the switch 'i_blkt_dual_coolant' (default=0): - 0. Solid breeder - nuclear heating in the blanket is exctrated by the primary coolant. + 0. Solid breeder - nuclear heating in the blanket is extracted by the primary coolant. 1. Liquid metal breeder, single-coolant - - nuclear heating in the blanket is exctrated by the primary coolant. + - nuclear heating in the blanket is extracted by the primary coolant. - liquid metal is circulated for tritium extraction, specified by number of circulations/day. 2. Liquid metal breeder, dual-coolant - nuclear heating in the liquid breeder/coolant is extracted by the liquid breeder/coolant. - nuclear heating in the blanket structure is extracted by the primary coolant The default assuption for all blanket models is that the first wall and breeding blanket have the same coolant (flow = FW inlet -> FW outlet -> BB inlet-> BB outlet). -It is possible to choose a different coolant for the FW and breeding blanket, in which case the mechanical pumping powers for the FW and BB are calculated seperately. +It is possible to choose a different coolant for the FW and breeding blanket, in which case the mechanical pumping powers for the FW and BB are calculated separately. The model has three mechanical pumping power options, chosen by the user to match their selected blanket design using the switch 'i_fw_blkt_shared_coolant' (default=0): 0. Same coolant for FW and BB ('i_fw_coolant_type`=`i_blkt_coolant_type`) 1. Different coolant for FW and BB ('i_fw_coolant_type`/=`i_blkt_coolant_type`) !!! Note "Note" - For the dual-coolant blanket the 'i_fw_blkt_shared_coolant' switch is relavent for the blanket structure coolant and not the liquid metal breeder/coolant choice. + For the dual-coolant blanket the 'i_fw_blkt_shared_coolant' switch is relevant for the blanket structure coolant and not the liquid metal breeder/coolant choice. The user can select the number poloidal and toroidal modules for the IB and OB BB. The 'i_blkt_module_segmentation' switch can be set to 1 for a single-module-segment blanket (default=0): 0. Multi-module segment diff --git a/documentation/eng-models/heating_and_current_drive/NBI/culham_nb.md b/documentation/source/eng-models/heating_and_current_drive/NBI/culham_nb.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/NBI/culham_nb.md rename to documentation/source/eng-models/heating_and_current_drive/NBI/culham_nb.md diff --git a/documentation/eng-models/heating_and_current_drive/NBI/iter_nb.md b/documentation/source/eng-models/heating_and_current_drive/NBI/iter_nb.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/NBI/iter_nb.md rename to documentation/source/eng-models/heating_and_current_drive/NBI/iter_nb.md diff --git a/documentation/eng-models/heating_and_current_drive/NBI/nbi_overview.md b/documentation/source/eng-models/heating_and_current_drive/NBI/nbi_overview.md similarity index 98% rename from documentation/eng-models/heating_and_current_drive/NBI/nbi_overview.md rename to documentation/source/eng-models/heating_and_current_drive/NBI/nbi_overview.md index 0f200e1469..65e86a3360 100644 --- a/documentation/eng-models/heating_and_current_drive/NBI/nbi_overview.md +++ b/documentation/source/eng-models/heating_and_current_drive/NBI/nbi_overview.md @@ -100,7 +100,7 @@ It is recommended that only one of these two constraint equations is used | $\mathtt{rnfe}$ | Iron density /$n_{\text{e}}$ | -Both the [ITER](./iter_nb.md) and [Culham](culham_nb.md) NBI models both use the `sigbeam` method to calculate the stopping cross section[^1]. It finds a suitable analytic epressing for $\sigma_s^{(Z)}(E,n_{\text{e}},T_{\text{e}},Z_{\text{eff}})$ for fitting $\sigma_s$ data for a single impurity $(\text{Z)}$ plasma: +Both the [ITER](./iter_nb.md) and [Culham](culham_nb.md) NBI models both use the `sigbeam` method to calculate the stopping cross section[^1]. It finds a suitable analytic expression for $\sigma_s^{(Z)}(E,n_{\text{e}},T_{\text{e}},Z_{\text{eff}})$ for fitting $\sigma_s$ data for a single impurity $(\text{Z)}$ plasma: diff --git a/documentation/eng-models/heating_and_current_drive/RF/culham_electron_cyclotron.md b/documentation/source/eng-models/heating_and_current_drive/RF/culham_electron_cyclotron.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/culham_electron_cyclotron.md rename to documentation/source/eng-models/heating_and_current_drive/RF/culham_electron_cyclotron.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/culham_lower_hybrid.md b/documentation/source/eng-models/heating_and_current_drive/RF/culham_lower_hybrid.md similarity index 97% rename from documentation/eng-models/heating_and_current_drive/RF/culham_lower_hybrid.md rename to documentation/source/eng-models/heating_and_current_drive/RF/culham_lower_hybrid.md index c6ed5d4d37..3247ac1f7b 100644 --- a/documentation/eng-models/heating_and_current_drive/RF/culham_lower_hybrid.md +++ b/documentation/source/eng-models/heating_and_current_drive/RF/culham_lower_hybrid.md @@ -14,10 +14,10 @@ AEA FUS 172: Physics Assessment for the European Reactor Study[^1] 5. Calculate the local toroidal magnetic field, `blocal`, using the formula `b_plasma_toroidal_on_axis * rmajor / (rmajor - rpenet)`. Here, `b_plasma_toroidal_on_axis` is the toroidal magnetic field at the magnetic axis, and `rmajor` is the major radius of the plasma. 6. Calculate the parallel refractive index, `nplacc`, which is needed for plasma access. It uses the local density `dlocal` and the local magnetic field `blocal` to calculate a fraction `frac`. `nplacc` is then obtained by adding `frac` to the square root of `1.0 + frac * frac`. 7. Calculate the local inverse aspect ratio, `epslh`, by dividing `rpenet` by `rmajor`. -8. Calculate the LH normalized efficiency, `x`, using the formula `24.0 / (nplacc * sqrt(tlocal))`. +8. Calculate the LH normalised efficiency, `x`, using the formula `24.0 / (nplacc * sqrt(tlocal))`. 9. Calculate several intermediate terms, `term01`, `term02`, `term03`, and `term04`, using different formulas involving `nplacc`, `physics_variables.zeff`, `tlocal`, `epslh`, and `x`. 10. Calculate the current drive efficiency, `gamlh`, using the formula `term01 * term02 * (1.0e0 - term03 / term04)`. -11. Return the current drive efficiency normalized by the product of `0.1e0 * dlocal` and `physics_variables.rmajor`. +11. Return the current drive efficiency normalised by the product of `0.1e0 * dlocal` and `physics_variables.rmajor`. [^1]: T. C. Hender, M. K. Bevir, M. Cox, R. J. Hastie, P. J. Knight, C. N. Lashmore-Davies, B. Lloyd, G. P. Maddison, A. W. Morris, M. R. O'Brien, M.F. Turner abd H. R. Wilson, *"Physics Assessment for the European Reactor Study"*, AEA Fusion Report AEA FUS 172 (1992) diff --git a/documentation/eng-models/heating_and_current_drive/RF/cutoff_ecrh.md b/documentation/source/eng-models/heating_and_current_drive/RF/cutoff_ecrh.md similarity index 93% rename from documentation/eng-models/heating_and_current_drive/RF/cutoff_ecrh.md rename to documentation/source/eng-models/heating_and_current_drive/RF/cutoff_ecrh.md index 7b6770e2c7..915aca5ac0 100644 --- a/documentation/eng-models/heating_and_current_drive/RF/cutoff_ecrh.md +++ b/documentation/source/eng-models/heating_and_current_drive/RF/cutoff_ecrh.md @@ -4,8 +4,8 @@ | Input | Description | |-------|-------------| -| `nd_plasma_electrons_vol_avg`, $n_{\text{e}}$ | Avergae electron temperature $\left[10^{19}\text{m}^{-3}\right]$ | -| `temp_plasma_electron_vol_avg_kev`, $T_{\text{e}}$ | Avergae electron temperature $\left[\text{keV}\right]$ | +| `nd_plasma_electrons_vol_avg`, $n_{\text{e}}$ | Average electron temperature $\left[10^{19}\text{m}^{-3}\right]$ | +| `temp_plasma_electron_vol_avg_kev`, $T_{\text{e}}$ | Average electron temperature $\left[\text{keV}\right]$ | | `rmajor`, $R_0$ | Major radius $\left[\text{m}\right]$ | | `b_plasma_toroidal_on_axis`, $B_{\text{T}}$ | Toroidal magnetic field $\left[\text{T}\right]$ | | `zeff`, $Z_{\text{eff}}$ | Effective charge | diff --git a/documentation/eng-models/heating_and_current_drive/RF/ebw_freethy.md b/documentation/source/eng-models/heating_and_current_drive/RF/ebw_freethy.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/ebw_freethy.md rename to documentation/source/eng-models/heating_and_current_drive/RF/ebw_freethy.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/ebw_overview.md b/documentation/source/eng-models/heating_and_current_drive/RF/ebw_overview.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/ebw_overview.md rename to documentation/source/eng-models/heating_and_current_drive/RF/ebw_overview.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/ec_overview.md b/documentation/source/eng-models/heating_and_current_drive/RF/ec_overview.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/ec_overview.md rename to documentation/source/eng-models/heating_and_current_drive/RF/ec_overview.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/ecrh_gamma.md b/documentation/source/eng-models/heating_and_current_drive/RF/ecrh_gamma.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/ecrh_gamma.md rename to documentation/source/eng-models/heating_and_current_drive/RF/ecrh_gamma.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/ehst_lower_hybrid.md b/documentation/source/eng-models/heating_and_current_drive/RF/ehst_lower_hybrid.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/ehst_lower_hybrid.md rename to documentation/source/eng-models/heating_and_current_drive/RF/ehst_lower_hybrid.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/fenstermacher_electron_cyclotron_resonance.md b/documentation/source/eng-models/heating_and_current_drive/RF/fenstermacher_electron_cyclotron_resonance.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/fenstermacher_electron_cyclotron_resonance.md rename to documentation/source/eng-models/heating_and_current_drive/RF/fenstermacher_electron_cyclotron_resonance.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/fenstermacher_lower_hybrid.md b/documentation/source/eng-models/heating_and_current_drive/RF/fenstermacher_lower_hybrid.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/fenstermacher_lower_hybrid.md rename to documentation/source/eng-models/heating_and_current_drive/RF/fenstermacher_lower_hybrid.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/ic_model.md b/documentation/source/eng-models/heating_and_current_drive/RF/ic_model.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/ic_model.md rename to documentation/source/eng-models/heating_and_current_drive/RF/ic_model.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/ic_overview.md b/documentation/source/eng-models/heating_and_current_drive/RF/ic_overview.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/ic_overview.md rename to documentation/source/eng-models/heating_and_current_drive/RF/ic_overview.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/lhcd_overview.md b/documentation/source/eng-models/heating_and_current_drive/RF/lhcd_overview.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/lhcd_overview.md rename to documentation/source/eng-models/heating_and_current_drive/RF/lhcd_overview.md diff --git a/documentation/eng-models/heating_and_current_drive/RF/rf_overview.md b/documentation/source/eng-models/heating_and_current_drive/RF/rf_overview.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/RF/rf_overview.md rename to documentation/source/eng-models/heating_and_current_drive/RF/rf_overview.md diff --git a/documentation/eng-models/heating_and_current_drive/heating-and-current-drive.md b/documentation/source/eng-models/heating_and_current_drive/heating-and-current-drive.md similarity index 100% rename from documentation/eng-models/heating_and_current_drive/heating-and-current-drive.md rename to documentation/source/eng-models/heating_and_current_drive/heating-and-current-drive.md diff --git a/documentation/eng-models/heating_and_current_drive/images/JET_rf_panel_1984.jpg b/documentation/source/eng-models/heating_and_current_drive/images/JET_rf_panel_1984.jpg similarity index 100% rename from documentation/eng-models/heating_and_current_drive/images/JET_rf_panel_1984.jpg rename to documentation/source/eng-models/heating_and_current_drive/images/JET_rf_panel_1984.jpg diff --git a/documentation/eng-models/heating_and_current_drive/images/ebw_coupling.png b/documentation/source/eng-models/heating_and_current_drive/images/ebw_coupling.png similarity index 100% rename from documentation/eng-models/heating_and_current_drive/images/ebw_coupling.png rename to documentation/source/eng-models/heating_and_current_drive/images/ebw_coupling.png diff --git a/documentation/eng-models/heating_and_current_drive/images/portsize.png b/documentation/source/eng-models/heating_and_current_drive/images/portsize.png similarity index 100% rename from documentation/eng-models/heating_and_current_drive/images/portsize.png rename to documentation/source/eng-models/heating_and_current_drive/images/portsize.png diff --git a/documentation/eng-models/image.png b/documentation/source/eng-models/image.png similarity index 100% rename from documentation/eng-models/image.png rename to documentation/source/eng-models/image.png diff --git a/documentation/eng-models/images/2nd_gen_rebco_zero_strain.html b/documentation/source/eng-models/images/2nd_gen_rebco_zero_strain.html similarity index 100% rename from documentation/eng-models/images/2nd_gen_rebco_zero_strain.html rename to documentation/source/eng-models/images/2nd_gen_rebco_zero_strain.html diff --git a/documentation/eng-models/images/2nd_gen_rebco_zero_strain.png b/documentation/source/eng-models/images/2nd_gen_rebco_zero_strain.png similarity index 100% rename from documentation/eng-models/images/2nd_gen_rebco_zero_strain.png rename to documentation/source/eng-models/images/2nd_gen_rebco_zero_strain.png diff --git a/documentation/eng-models/images/Bi_2212_zero_strain.html b/documentation/source/eng-models/images/Bi_2212_zero_strain.html similarity index 100% rename from documentation/eng-models/images/Bi_2212_zero_strain.html rename to documentation/source/eng-models/images/Bi_2212_zero_strain.html diff --git a/documentation/eng-models/images/Bi_2212_zero_strain.png b/documentation/source/eng-models/images/Bi_2212_zero_strain.png similarity index 100% rename from documentation/eng-models/images/Bi_2212_zero_strain.png rename to documentation/source/eng-models/images/Bi_2212_zero_strain.png diff --git a/documentation/eng-models/images/Durham_NbTi_zero_strain.html b/documentation/source/eng-models/images/Durham_NbTi_zero_strain.html similarity index 100% rename from documentation/eng-models/images/Durham_NbTi_zero_strain.html rename to documentation/source/eng-models/images/Durham_NbTi_zero_strain.html diff --git a/documentation/eng-models/images/Durham_NbTi_zero_strain.png b/documentation/source/eng-models/images/Durham_NbTi_zero_strain.png similarity index 100% rename from documentation/eng-models/images/Durham_NbTi_zero_strain.png rename to documentation/source/eng-models/images/Durham_NbTi_zero_strain.png diff --git a/documentation/eng-models/images/Durham_REBCO_zero_strain.html b/documentation/source/eng-models/images/Durham_REBCO_zero_strain.html similarity index 100% rename from documentation/eng-models/images/Durham_REBCO_zero_strain.html rename to documentation/source/eng-models/images/Durham_REBCO_zero_strain.html diff --git a/documentation/eng-models/images/Durham_REBCO_zero_strain.png b/documentation/source/eng-models/images/Durham_REBCO_zero_strain.png similarity index 100% rename from documentation/eng-models/images/Durham_REBCO_zero_strain.png rename to documentation/source/eng-models/images/Durham_REBCO_zero_strain.png diff --git a/documentation/eng-models/images/Hazelton_Zhai_REBCO_zero_strain.png b/documentation/source/eng-models/images/Hazelton_Zhai_REBCO_zero_strain.png similarity index 100% rename from documentation/eng-models/images/Hazelton_Zhai_REBCO_zero_strain.png rename to documentation/source/eng-models/images/Hazelton_Zhai_REBCO_zero_strain.png diff --git a/documentation/eng-models/images/eutf4_Nb3Sn_zero_strain.html b/documentation/source/eng-models/images/eutf4_Nb3Sn_zero_strain.html similarity index 100% rename from documentation/eng-models/images/eutf4_Nb3Sn_zero_strain.html rename to documentation/source/eng-models/images/eutf4_Nb3Sn_zero_strain.html diff --git a/documentation/eng-models/images/eutf4_Nb3Sn_zero_strain.png b/documentation/source/eng-models/images/eutf4_Nb3Sn_zero_strain.png similarity index 100% rename from documentation/eng-models/images/eutf4_Nb3Sn_zero_strain.png rename to documentation/source/eng-models/images/eutf4_Nb3Sn_zero_strain.png diff --git a/documentation/eng-models/images/old_NbTi_zero_strain.html b/documentation/source/eng-models/images/old_NbTi_zero_strain.html similarity index 100% rename from documentation/eng-models/images/old_NbTi_zero_strain.html rename to documentation/source/eng-models/images/old_NbTi_zero_strain.html diff --git a/documentation/eng-models/images/old_NbTi_zero_strain.png b/documentation/source/eng-models/images/old_NbTi_zero_strain.png similarity index 100% rename from documentation/eng-models/images/old_NbTi_zero_strain.png rename to documentation/source/eng-models/images/old_NbTi_zero_strain.png diff --git a/documentation/eng-models/images/western_superconducting_Nb3Sn_zero_strain.html b/documentation/source/eng-models/images/western_superconducting_Nb3Sn_zero_strain.html similarity index 100% rename from documentation/eng-models/images/western_superconducting_Nb3Sn_zero_strain.html rename to documentation/source/eng-models/images/western_superconducting_Nb3Sn_zero_strain.html diff --git a/documentation/eng-models/images/western_superconducting_Nb3Sn_zero_strain.png b/documentation/source/eng-models/images/western_superconducting_Nb3Sn_zero_strain.png similarity index 100% rename from documentation/eng-models/images/western_superconducting_Nb3Sn_zero_strain.png rename to documentation/source/eng-models/images/western_superconducting_Nb3Sn_zero_strain.png diff --git a/documentation/eng-models/machine-build.md b/documentation/source/eng-models/machine-build.md similarity index 100% rename from documentation/eng-models/machine-build.md rename to documentation/source/eng-models/machine-build.md diff --git a/documentation/eng-models/pf-coil.md b/documentation/source/eng-models/pf-coil.md similarity index 98% rename from documentation/eng-models/pf-coil.md rename to documentation/source/eng-models/pf-coil.md index 8160d2b04b..abf79e8df8 100644 --- a/documentation/eng-models/pf-coil.md +++ b/documentation/source/eng-models/pf-coil.md @@ -48,7 +48,7 @@ The four possible values of `i_pf_location(j)` correspond to the following PF co R = R_0 + \texttt{rpf2} \times \delta \times a $$ - Due to the nautre of the TF coils not being top-down symmetric for single null cases the positioning slightly differs if the coil is above or below the midplane. + Due to the nature of the TF coils not being top-down symmetric for single null cases the positioning slightly differs if the coil is above or below the midplane. For above the midplane: diff --git a/documentation/eng-models/plant-availability.md b/documentation/source/eng-models/plant-availability.md similarity index 98% rename from documentation/eng-models/plant-availability.md rename to documentation/source/eng-models/plant-availability.md index e0a1a513d1..db46fa38f4 100644 --- a/documentation/eng-models/plant-availability.md +++ b/documentation/source/eng-models/plant-availability.md @@ -4,7 +4,7 @@ Switch `i_plant_availability` is used to control how the overall plant availabil If `i_plant_availability = 0`, the input value of `f_t_plant_available` is used. -If `i_plant_availability = 1`, a model by N. Taylor and D. Ward[^1] is used instead, in which `f_t_plant_available` is calculated taking into account the time taken to replace certain components of the fusion power core, and various unplanned unavailability fractions which may be set by the user, as summerised in Table 1. +If `i_plant_availability = 1`, a model by N. Taylor and D. Ward[^1] is used instead, in which `f_t_plant_available` is calculated taking into account the time taken to replace certain components of the fusion power core, and various unplanned unavailability fractions which may be set by the user, as summarised in Table 1. ------------------ @@ -122,7 +122,7 @@ where $t_{\text{burn}}$ is the burn time and $t_{\text{cycle}}$ is the full cycl -------------- -All availability models in PROCESS require the calculation of the centerpost lifetime, which is detailed here. +All availability models in PROCESS require the calculation of the centrepost lifetime, which is detailed here. !!! Note "Note" The centrepost lifetime is calculated in full-power years (FPY). diff --git a/documentation/eng-models/power-conversion-and-heat-dissipation-systems.md b/documentation/source/eng-models/power-conversion-and-heat-dissipation-systems.md similarity index 100% rename from documentation/eng-models/power-conversion-and-heat-dissipation-systems.md rename to documentation/source/eng-models/power-conversion-and-heat-dissipation-systems.md diff --git a/documentation/eng-models/power-requirements.md b/documentation/source/eng-models/power-requirements.md similarity index 100% rename from documentation/eng-models/power-requirements.md rename to documentation/source/eng-models/power-requirements.md diff --git a/documentation/eng-models/shield.md b/documentation/source/eng-models/shield.md similarity index 100% rename from documentation/eng-models/shield.md rename to documentation/source/eng-models/shield.md diff --git a/documentation/eng-models/structural-components.md b/documentation/source/eng-models/structural-components.md similarity index 100% rename from documentation/eng-models/structural-components.md rename to documentation/source/eng-models/structural-components.md diff --git a/documentation/eng-models/superconductors.md b/documentation/source/eng-models/superconductors.md similarity index 99% rename from documentation/eng-models/superconductors.md rename to documentation/source/eng-models/superconductors.md index cbf303c754..e1d4ae15c4 100644 --- a/documentation/eng-models/superconductors.md +++ b/documentation/source/eng-models/superconductors.md @@ -355,7 +355,7 @@ The fit values are: - $u: 33450.0$ - $v: -176577.0$ -The output of the model only gives the critical current ($I_c$) and not the critical current density ($J_c$). Therefore the value is multiplied by the tape paramters to find the critical current density in the REBCO strand +The output of the model only gives the critical current ($I_c$) and not the critical current density ($J_c$). Therefore the value is multiplied by the tape parameters to find the critical current density in the REBCO strand $$ J_c = I_c \frac{w_{\text{tape}} \times \Delta x_{\text{REBCO}}}{w_{\text{tape}} \times \Delta x_{\text{tape}} } @@ -509,4 +509,4 @@ Indico, 2017. https://indico.cern.ch/event/588810/contributions/2473740/ (access [^10]: Y. Zhai, D. van der Laan, P. Connolly, and C. Kessel, “Conceptual design of HTS magnets for fusion nuclear science facility,” Fusion Engineering and Design, vol. 168, p. 112611, Jul. 2021, doi: https://doi.org/10.1016/j.fusengdes.2021.112611. ‌ ‌ -‌ \ No newline at end of file +‌ diff --git a/documentation/eng-models/tf-coil-resistive.md b/documentation/source/eng-models/tf-coil-resistive.md similarity index 100% rename from documentation/eng-models/tf-coil-resistive.md rename to documentation/source/eng-models/tf-coil-resistive.md diff --git a/documentation/eng-models/tf-coil-superconducting.md b/documentation/source/eng-models/tf-coil-superconducting.md similarity index 99% rename from documentation/eng-models/tf-coil-superconducting.md rename to documentation/source/eng-models/tf-coil-superconducting.md index a5c771ba49..1c4f03cbd5 100644 --- a/documentation/eng-models/tf-coil-superconducting.md +++ b/documentation/source/eng-models/tf-coil-superconducting.md @@ -255,7 +255,7 @@ $$ P(t)dt = \sum_i c_{P,i}\rho_{i} V_{i} dT $$ -Where $P(t)$ is the power deposited in the copper through Joule heating at time t, and the sum on the RHS is over the conductor consitutents (copper, helium, superconductor), where $V_{i}$ is the volume of said constituent. This can be rewritten as: +Where $P(t)$ is the power deposited in the copper through Joule heating at time t, and the sum on the RHS is over the conductor constituents (copper, helium, superconductor), where $V_{i}$ is the volume of said constituent. This can be rewritten as: $$ \int J(t)^2 dt = \int_{T_{0}}^{T_{max}} \sum_i f_{i}\dfrac{c_{P,i}\rho_{i}}{\nu_{Cu}} dT @@ -263,7 +263,7 @@ $$ The LHS is solved analytically, assuming that the current is at the operational value $J_{op}$ for some quench detection time $t_{detection}$ and then decays exponentially with a time constant $\tau_{discharge}$. The RHS is solved numerically by integration of the temperature-dependent material properties over $dT$. -The resistivity of copper, $\nu_{Cu}$, is an extremely important parameter in this model. The residual-resistance-ratio (RRR) of the copper can be specified, and magneto-resistive and irradiation-induced increases in resistivity are accounted for. The magnetic field at which the copper resisitivity is calculated is kept constant at $B_{TF,peak}$. This is conservative, and to simplify the implementation (keeping the separation of the $t$ and $T$ integrations). +The resistivity of copper, $\nu_{Cu}$, is an extremely important parameter in this model. The residual-resistance-ratio (RRR) of the copper can be specified, and magneto-resistive and irradiation-induced increases in resistivity are accounted for. The magnetic field at which the copper resistivity is calculated is kept constant at $B_{TF,peak}$. This is conservative, and to simplify the implementation (keeping the separation of the $t$ and $T$ integrations). Formally this gives: diff --git a/documentation/eng-models/tf-coil.md b/documentation/source/eng-models/tf-coil.md similarity index 98% rename from documentation/eng-models/tf-coil.md rename to documentation/source/eng-models/tf-coil.md index e0710eb2dc..ca33896dae 100644 --- a/documentation/eng-models/tf-coil.md +++ b/documentation/source/eng-models/tf-coil.md @@ -28,7 +28,7 @@ Resistive coils can benefit in having a larger outboard conductor area than the inboard one, to reduce resistive heating without increasing the plasma major radius or increasing its aspect ratio. For this reason, thicker outboard can be set using the f_dr_tf_outboard_inboard user input defined as the ratio between -ouboard and inboard TF coil legs. The possibility of having different coil +outboard and inboard TF coil legs. The possibility of having different coil thicknesses is only available for resistive coils and f_dr_tf_outboard_inboard would have no effect if superconducting coils are selected (`i_tf_sup = 1`) @@ -63,7 +63,7 @@ Two different plasma side casing shapes can be selected using the `i_tf_case_geo ## Topology of TF coils and Central Solenoid The engineering models are based on a topology like that used in ITER: the central solenoid and the TF coils are not linked: the central solenoid can be inserted or removed without cutting the TF coils. -However, an option does exist wich permits the alternative topology, in which the inboard legs of the TF coils pass through the middle of the central solenoid. This layout is used in MAST, where the copper TF coils can be dismantled to allow the central solenoid to be inserted or removed. +However, an option does exist which permits the alternative topology, in which the inboard legs of the TF coils pass through the middle of the central solenoid. This layout is used in MAST, where the copper TF coils can be dismantled to allow the central solenoid to be inserted or removed. The topology is set as follows: - `i_tf_inside_cs = 0` (default) ITER-like topology: the central solenoid and the TF coils are not linked. @@ -452,7 +452,7 @@ $$ this configuration in theory. The radial and toroidal stress calculations are made assuming no vertical tension. A constant vertical stress is then estimated *a posteriori* by dividing the inboard vertical tension by the - support sutructure area to obtain the 3 normal stress necessary to for the + support structure area to obtain the 3 normal stress necessary to for the *TRESCA* yield stress estimate as described in [1]. Although using un-adapted model hypothesis this model is still used by default as it has been validated on FEA analysis and benchmarked with the *MADMAX* *CEA* @@ -472,7 +472,7 @@ $$ complete this model is not yet used by default as more FEA validations are needed. `i_tf_stress_model = 0` is the older model, which is O(n^3) in the number of layers and fails if there is a solid dr_bore. - `i_tf_stress_model = 2` is the newr model, which is O(n) and accepts a solid + `i_tf_stress_model = 2` is the newer model, which is O(n) and accepts a solid dr_bore, but is otherwise identical to the older model `i_tf_stress_model = 0`.

@@ -729,22 +729,22 @@ selected with the `i_tf_bucking` integer switch. -

**Bucked and wedged (`i_tf_bucking == 2,3`):** the TF coil uses the CS coil as centering forces structural support. This design allows to substantially - reduce the thickness of the TF coil individual suport structure if a large + reduce the thickness of the TF coil individual support structure if a large CS coil is present. As the CS coil current generates a beneficial CS radial outward forces, the most critical instant for structural support is the moment when no current flows in the CS coil. The CS coil is therefore - represented as an additionnal stress layer with `e.m.` no body forces. - The layer strctural properties are defined using using similar smearing/ + represented as an additional stress layer with `e.m.` no body forces. + The layer structural properties are defined using using similar smearing/ unsmeating procedure as the TF coil, as detailed in issue [4]. The maximum between the CS stress from the this model and the on calculated in the `pfcoil` module is taken as the CS coil stress limit (constraint 72). A fast version, neglecting the interface layer properties is implemented (`i_tf_bucking == 2`). And a more complete one, taking explicitly the Kapton - interface into account in the stress calcualtions (`i_tf_bucking == 3`) is + interface into account in the stress calculations (`i_tf_bucking == 3`) is also implemented. Before using this design option, the user must know two major potential issues not captured by *PROCESS*. The first is the fatigue introduced by the CS on the TF coil. The second is the nature of the CS-TF - coil interface that has to allow vertical slinding at cryogenic temperatures, + coil interface that has to allow vertical sliding at cryogenic temperatures, as the CS vertical size reduces when energized and the TF coil vertical tension makes TF grow taller with current flowing in it. The CS and the TF coil are therefore strain insulated, therefore all the vertical tension is @@ -824,7 +824,7 @@ and the maximum field (on coil toroidal direction) respectively, measured at the mid-plane plasma outer limit (separatrix). To prevent intolerable fast particles losses and plasma instabilities, -$\delta$ must be limited to a few percent, approximatively \( \delta \in +$\delta$ must be limited to a few percent, approximately \( \delta \in [0.5-1]\) . If intolerable, the plasma ripple can be reduced with many different techniques, for example the TF coil shape, stabilisation coils can be added, more coils can be used or the coil outboard radius can be increased. @@ -880,7 +880,7 @@ $$ $$ -with \(x\) the lateral thickness of the winding pack normalized to the coil +with \(x\) the lateral thickness of the winding pack normalised to the coil dimensions defined as: diff --git a/documentation/eng-models/vacuum-vessel.md b/documentation/source/eng-models/vacuum-vessel.md similarity index 100% rename from documentation/eng-models/vacuum-vessel.md rename to documentation/source/eng-models/vacuum-vessel.md diff --git a/documentation/source/examples b/documentation/source/examples new file mode 120000 index 0000000000..d15735c1df --- /dev/null +++ b/documentation/source/examples @@ -0,0 +1 @@ +../../examples \ No newline at end of file diff --git a/documentation/fusion-devices/inertial.md b/documentation/source/fusion-devices/inertial.md similarity index 100% rename from documentation/fusion-devices/inertial.md rename to documentation/source/fusion-devices/inertial.md diff --git a/documentation/fusion-devices/spherical-tokamak.md b/documentation/source/fusion-devices/spherical-tokamak.md similarity index 100% rename from documentation/fusion-devices/spherical-tokamak.md rename to documentation/source/fusion-devices/spherical-tokamak.md diff --git a/documentation/fusion-devices/stellarator.md b/documentation/source/fusion-devices/stellarator.md similarity index 99% rename from documentation/fusion-devices/stellarator.md rename to documentation/source/fusion-devices/stellarator.md index aad1b1c691..4687498df3 100644 --- a/documentation/fusion-devices/stellarator.md +++ b/documentation/source/fusion-devices/stellarator.md @@ -34,7 +34,7 @@ The user can switch between these models by using the switch variable `istell`: - `istell=5`: A W7-X variation with 30 coils - `istell-6`: Use the `stella_conf.json` file. -The stellarator version of PROCESS assumes the coil-set itself to be **fixed in shape** and can only scale the *overall* size of the machine in major radius `rmajor`. There is no capability in PROCESS to seperately scale the minor coil radius -- in other words: the coil aspect ratio is fixed. Also the number of coils is considered fixed and is given by the configuration. +The stellarator version of PROCESS assumes the coil-set itself to be **fixed in shape** and can only scale the *overall* size of the machine in major radius `rmajor`. There is no capability in PROCESS to separately scale the minor coil radius -- in other words: the coil aspect ratio is fixed. Also the number of coils is considered fixed and is given by the configuration. ## Input File Specifications @@ -88,7 +88,7 @@ The model call is in the following order 1. Stellarator New Configuration setup (`stnewconfig`) 2. Stellarator Geometry (`stgeom`) - 3. Stellarator Physics Loop Routine (containing steps requiring to evalute the physics model at different operation points) (`stopt`) + 3. Stellarator Physics Loop Routine (containing steps requiring to evaluate the physics model at different operation points) (`stopt`) 4. Stellarator Physics (`stphys`) 5. Stellarator radial and toroidal build (`stbild`) 6. Stellarator Structure Mass (`ststrc`) @@ -156,7 +156,7 @@ Here $\bar{\iota}$ is the rotational transform, which is equivalent to the recip As no 1D solver options are available for stellarators yet, PROCESS prints several neoclassics parameters as obtained from the 1/$\nu$ regime. The two most important parameters are `q_PROCESS` and `total_q_neo_e`. -`q_PROCESS` is the heat flux that PROCESS obtaines from the 0D confinement time scalings. +`q_PROCESS` is the heat flux that PROCESS obtains from the 0D confinement time scalings. `total_q_neo_e` is the estimated total neoclassical flux as obtained from the 1/$\nu$ electron transport regime, multiplied by a factor of 4 (2 for the ion contribution and another factor of 2 for the radial electrical field influence). The user should check if `q_PROCESS>total_q_neo_e`. If not, the design point is likely not feasible. diff --git a/documentation/images/2D_contour_plot_example.png b/documentation/source/images/2D_contour_plot_example.png similarity index 100% rename from documentation/images/2D_contour_plot_example.png rename to documentation/source/images/2D_contour_plot_example.png diff --git a/documentation/images/HSR3.png b/documentation/source/images/HSR3.png similarity index 100% rename from documentation/images/HSR3.png rename to documentation/source/images/HSR3.png diff --git a/documentation/images/HSR4.png b/documentation/source/images/HSR4.png similarity index 100% rename from documentation/images/HSR4.png rename to documentation/source/images/HSR4.png diff --git a/documentation/images/HSR5.png b/documentation/source/images/HSR5.png similarity index 100% rename from documentation/images/HSR5.png rename to documentation/source/images/HSR5.png diff --git a/documentation/images/Overall-power-flow.png b/documentation/source/images/Overall-power-flow.png similarity index 100% rename from documentation/images/Overall-power-flow.png rename to documentation/source/images/Overall-power-flow.png diff --git a/documentation/images/Parameters-of-the-Process-Divertor-Model.png b/documentation/source/images/Parameters-of-the-Process-Divertor-Model.png similarity index 100% rename from documentation/images/Parameters-of-the-Process-Divertor-Model.png rename to documentation/source/images/Parameters-of-the-Process-Divertor-Model.png diff --git a/documentation/images/README_image.PNG b/documentation/source/images/README_image.PNG similarity index 100% rename from documentation/images/README_image.PNG rename to documentation/source/images/README_image.PNG diff --git a/documentation/images/ST_geom.png b/documentation/source/images/ST_geom.png similarity index 100% rename from documentation/images/ST_geom.png rename to documentation/source/images/ST_geom.png diff --git a/documentation/images/SankeyPowerFlow_from_large_tokamak.png b/documentation/source/images/SankeyPowerFlow_from_large_tokamak.png similarity index 100% rename from documentation/images/SankeyPowerFlow_from_large_tokamak.png rename to documentation/source/images/SankeyPowerFlow_from_large_tokamak.png diff --git a/documentation/images/Sudo_scaling.png b/documentation/source/images/Sudo_scaling.png similarity index 100% rename from documentation/images/Sudo_scaling.png rename to documentation/source/images/Sudo_scaling.png diff --git a/documentation/images/Test_suite_folder_structure.svg b/documentation/source/images/Test_suite_folder_structure.svg similarity index 100% rename from documentation/images/Test_suite_folder_structure.svg rename to documentation/source/images/Test_suite_folder_structure.svg diff --git a/documentation/images/Test_suite_folder_structure.tex b/documentation/source/images/Test_suite_folder_structure.tex similarity index 100% rename from documentation/images/Test_suite_folder_structure.tex rename to documentation/source/images/Test_suite_folder_structure.tex diff --git a/documentation/images/VMCON_flow_chart.svg b/documentation/source/images/VMCON_flow_chart.svg similarity index 100% rename from documentation/images/VMCON_flow_chart.svg rename to documentation/source/images/VMCON_flow_chart.svg diff --git a/documentation/images/VMCON_flow_chart.tex b/documentation/source/images/VMCON_flow_chart.tex similarity index 100% rename from documentation/images/VMCON_flow_chart.tex rename to documentation/source/images/VMCON_flow_chart.tex diff --git a/documentation/images/adas_radiation.png b/documentation/source/images/adas_radiation.png similarity index 100% rename from documentation/images/adas_radiation.png rename to documentation/source/images/adas_radiation.png diff --git a/documentation/images/blender images/initial_collage.png b/documentation/source/images/blender images/initial_collage.png similarity index 100% rename from documentation/images/blender images/initial_collage.png rename to documentation/source/images/blender images/initial_collage.png diff --git a/documentation/images/breakpoint.png b/documentation/source/images/breakpoint.png similarity index 100% rename from documentation/images/breakpoint.png rename to documentation/source/images/breakpoint.png diff --git a/documentation/images/build_d.png b/documentation/source/images/build_d.png similarity index 100% rename from documentation/images/build_d.png rename to documentation/source/images/build_d.png diff --git a/documentation/images/build_e.png b/documentation/source/images/build_e.png similarity index 100% rename from documentation/images/build_e.png rename to documentation/source/images/build_e.png diff --git a/documentation/images/build_e_snd.png b/documentation/source/images/build_e_snd.png similarity index 100% rename from documentation/images/build_e_snd.png rename to documentation/source/images/build_e_snd.png diff --git a/documentation/images/conductor_coordinates.png b/documentation/source/images/conductor_coordinates.png similarity index 100% rename from documentation/images/conductor_coordinates.png rename to documentation/source/images/conductor_coordinates.png diff --git a/documentation/images/current_vs_time.png b/documentation/source/images/current_vs_time.png similarity index 100% rename from documentation/images/current_vs_time.png rename to documentation/source/images/current_vs_time.png diff --git a/documentation/images/first_wall.png b/documentation/source/images/first_wall.png similarity index 100% rename from documentation/images/first_wall.png rename to documentation/source/images/first_wall.png diff --git a/documentation/images/force-on-vessel-proportional-to-current-and-field.png b/documentation/source/images/force-on-vessel-proportional-to-current-and-field.png similarity index 100% rename from documentation/images/force-on-vessel-proportional-to-current-and-field.png rename to documentation/source/images/force-on-vessel-proportional-to-current-and-field.png diff --git a/documentation/images/ford_example_1.png b/documentation/source/images/ford_example_1.png similarity index 100% rename from documentation/images/ford_example_1.png rename to documentation/source/images/ford_example_1.png diff --git a/documentation/images/helias5b.png b/documentation/source/images/helias5b.png similarity index 100% rename from documentation/images/helias5b.png rename to documentation/source/images/helias5b.png diff --git a/documentation/images/lagrange_multipliers-eps-converted-to.png b/documentation/source/images/lagrange_multipliers-eps-converted-to.png similarity index 100% rename from documentation/images/lagrange_multipliers-eps-converted-to.png rename to documentation/source/images/lagrange_multipliers-eps-converted-to.png diff --git a/documentation/images/plasma_geometry.png b/documentation/source/images/plasma_geometry.png similarity index 100% rename from documentation/images/plasma_geometry.png rename to documentation/source/images/plasma_geometry.png diff --git a/documentation/images/plasma_inboard_surface_area.png b/documentation/source/images/plasma_inboard_surface_area.png similarity index 100% rename from documentation/images/plasma_inboard_surface_area.png rename to documentation/source/images/plasma_inboard_surface_area.png diff --git a/documentation/images/plasma_outboard_surface_area.png b/documentation/source/images/plasma_outboard_surface_area.png similarity index 100% rename from documentation/images/plasma_outboard_surface_area.png rename to documentation/source/images/plasma_outboard_surface_area.png diff --git a/documentation/images/plotly_sankey.png b/documentation/source/images/plotly_sankey.png similarity index 100% rename from documentation/images/plotly_sankey.png rename to documentation/source/images/plotly_sankey.png diff --git a/documentation/images/powerflow2.png b/documentation/source/images/powerflow2.png similarity index 100% rename from documentation/images/powerflow2.png rename to documentation/source/images/powerflow2.png diff --git a/documentation/images/powerflow3.png b/documentation/source/images/powerflow3.png similarity index 100% rename from documentation/images/powerflow3.png rename to documentation/source/images/powerflow3.png diff --git a/documentation/images/radial-build.png b/documentation/source/images/radial-build.png similarity index 100% rename from documentation/images/radial-build.png rename to documentation/source/images/radial-build.png diff --git a/documentation/images/radial_build_plot.png b/documentation/source/images/radial_build_plot.png similarity index 100% rename from documentation/images/radial_build_plot.png rename to documentation/source/images/radial_build_plot.png diff --git a/documentation/images/radiation.png b/documentation/source/images/radiation.png similarity index 100% rename from documentation/images/radiation.png rename to documentation/source/images/radiation.png diff --git a/documentation/images/sankey-power-flow.png b/documentation/source/images/sankey-power-flow.png similarity index 100% rename from documentation/images/sankey-power-flow.png rename to documentation/source/images/sankey-power-flow.png diff --git a/documentation/images/selectDebugger.png b/documentation/source/images/selectDebugger.png similarity index 100% rename from documentation/images/selectDebugger.png rename to documentation/source/images/selectDebugger.png diff --git a/documentation/images/stack_scan_plot_example.png b/documentation/source/images/stack_scan_plot_example.png similarity index 100% rename from documentation/images/stack_scan_plot_example.png rename to documentation/source/images/stack_scan_plot_example.png diff --git a/documentation/images/stellartor_windingpack.png b/documentation/source/images/stellartor_windingpack.png similarity index 100% rename from documentation/images/stellartor_windingpack.png rename to documentation/source/images/stellartor_windingpack.png diff --git a/documentation/images/stelldiv.png b/documentation/source/images/stelldiv.png similarity index 100% rename from documentation/images/stelldiv.png rename to documentation/source/images/stelldiv.png diff --git a/documentation/images/tf-shape-definition.png b/documentation/source/images/tf-shape-definition.png similarity index 100% rename from documentation/images/tf-shape-definition.png rename to documentation/source/images/tf-shape-definition.png diff --git a/documentation/images/tfcoil_SC_WP_option.png b/documentation/source/images/tfcoil_SC_WP_option.png similarity index 100% rename from documentation/images/tfcoil_SC_WP_option.png rename to documentation/source/images/tfcoil_SC_WP_option.png diff --git a/documentation/images/tfcoil_SC_inboard_structure.png b/documentation/source/images/tfcoil_SC_inboard_structure.png similarity index 100% rename from documentation/images/tfcoil_SC_inboard_structure.png rename to documentation/source/images/tfcoil_SC_inboard_structure.png diff --git a/documentation/images/tfcoil_SC_plasma_case_option.png b/documentation/source/images/tfcoil_SC_plasma_case_option.png similarity index 100% rename from documentation/images/tfcoil_SC_plasma_case_option.png rename to documentation/source/images/tfcoil_SC_plasma_case_option.png diff --git a/documentation/images/tfcoil_SC_stress_layers.png b/documentation/source/images/tfcoil_SC_stress_layers.png similarity index 100% rename from documentation/images/tfcoil_SC_stress_layers.png rename to documentation/source/images/tfcoil_SC_stress_layers.png diff --git a/documentation/images/tfcoil_SC_turn.png b/documentation/source/images/tfcoil_SC_turn.png similarity index 100% rename from documentation/images/tfcoil_SC_turn.png rename to documentation/source/images/tfcoil_SC_turn.png diff --git a/documentation/images/tfcoil_SC_turn_diag.png b/documentation/source/images/tfcoil_SC_turn_diag.png similarity index 100% rename from documentation/images/tfcoil_SC_turn_diag.png rename to documentation/source/images/tfcoil_SC_turn_diag.png diff --git a/documentation/images/tfcoil_code_structure.png b/documentation/source/images/tfcoil_code_structure.png similarity index 100% rename from documentation/images/tfcoil_code_structure.png rename to documentation/source/images/tfcoil_code_structure.png diff --git a/documentation/images/tfcoil_res_inboard_geom.png b/documentation/source/images/tfcoil_res_inboard_geom.png similarity index 100% rename from documentation/images/tfcoil_res_inboard_geom.png rename to documentation/source/images/tfcoil_res_inboard_geom.png diff --git a/documentation/images/tfcoil_res_turn.png b/documentation/source/images/tfcoil_res_turn.png similarity index 100% rename from documentation/images/tfcoil_res_turn.png rename to documentation/source/images/tfcoil_res_turn.png diff --git a/documentation/images/tfcoil_ripple_on_coil_contours.png b/documentation/source/images/tfcoil_ripple_on_coil_contours.png similarity index 100% rename from documentation/images/tfcoil_ripple_on_coil_contours.png rename to documentation/source/images/tfcoil_ripple_on_coil_contours.png diff --git a/documentation/images/tfcoil_ripple_on_coil_filaments.png b/documentation/source/images/tfcoil_ripple_on_coil_filaments.png similarity index 100% rename from documentation/images/tfcoil_ripple_on_coil_filaments.png rename to documentation/source/images/tfcoil_ripple_on_coil_filaments.png diff --git a/documentation/images/tfcoil_ripple_plasma.png b/documentation/source/images/tfcoil_ripple_plasma.png similarity index 100% rename from documentation/images/tfcoil_ripple_plasma.png rename to documentation/source/images/tfcoil_ripple_plasma.png diff --git a/documentation/images/tfcoil_ripple_plasma_fit.png b/documentation/source/images/tfcoil_ripple_plasma_fit.png similarity index 100% rename from documentation/images/tfcoil_ripple_plasma_fit.png rename to documentation/source/images/tfcoil_ripple_plasma_fit.png diff --git a/documentation/images/tokamak_tfcoil.png b/documentation/source/images/tokamak_tfcoil.png similarity index 100% rename from documentation/images/tokamak_tfcoil.png rename to documentation/source/images/tokamak_tfcoil.png diff --git a/documentation/images/ukaea-logo.png b/documentation/source/images/ukaea-logo.png similarity index 100% rename from documentation/images/ukaea-logo.png rename to documentation/source/images/ukaea-logo.png diff --git a/documentation/images/vertical-build.png b/documentation/source/images/vertical-build.png similarity index 100% rename from documentation/images/vertical-build.png rename to documentation/source/images/vertical-build.png diff --git a/documentation/img/Closed_Loop-Cooling_Pond.png b/documentation/source/img/Closed_Loop-Cooling_Pond.png similarity index 100% rename from documentation/img/Closed_Loop-Cooling_Pond.png rename to documentation/source/img/Closed_Loop-Cooling_Pond.png diff --git a/documentation/img/Cooling_Tower_Effluent_Source.png b/documentation/source/img/Cooling_Tower_Effluent_Source.png similarity index 100% rename from documentation/img/Cooling_Tower_Effluent_Source.png rename to documentation/source/img/Cooling_Tower_Effluent_Source.png diff --git a/documentation/img/Cooling_tower.png b/documentation/source/img/Cooling_tower.png similarity index 100% rename from documentation/img/Cooling_tower.png rename to documentation/source/img/Cooling_tower.png diff --git a/documentation/img/Dry_Cooling-Air_Condenser.png b/documentation/source/img/Dry_Cooling-Air_Condenser.png similarity index 100% rename from documentation/img/Dry_Cooling-Air_Condenser.png rename to documentation/source/img/Dry_Cooling-Air_Condenser.png diff --git a/documentation/img/Hybrid-Plume_Abatement.png b/documentation/source/img/Hybrid-Plume_Abatement.png similarity index 100% rename from documentation/img/Hybrid-Plume_Abatement.png rename to documentation/source/img/Hybrid-Plume_Abatement.png diff --git a/documentation/img/Once_Through-Cooling_Pond.png b/documentation/source/img/Once_Through-Cooling_Pond.png similarity index 100% rename from documentation/img/Once_Through-Cooling_Pond.png rename to documentation/source/img/Once_Through-Cooling_Pond.png diff --git a/documentation/img/Once_Through.png b/documentation/source/img/Once_Through.png similarity index 100% rename from documentation/img/Once_Through.png rename to documentation/source/img/Once_Through.png diff --git a/documentation/img/Wet_Cooling-Mechanical_Draft.png b/documentation/source/img/Wet_Cooling-Mechanical_Draft.png similarity index 100% rename from documentation/img/Wet_Cooling-Mechanical_Draft.png rename to documentation/source/img/Wet_Cooling-Mechanical_Draft.png diff --git a/documentation/img/Wet_Cooling-Natural_Draft.png b/documentation/source/img/Wet_Cooling-Natural_Draft.png similarity index 100% rename from documentation/img/Wet_Cooling-Natural_Draft.png rename to documentation/source/img/Wet_Cooling-Natural_Draft.png diff --git a/documentation/index.md b/documentation/source/index.md similarity index 100% rename from documentation/index.md rename to documentation/source/index.md diff --git a/documentation/installation/installation.md b/documentation/source/installation/installation.md similarity index 100% rename from documentation/installation/installation.md rename to documentation/source/installation/installation.md diff --git a/documentation/installation/vs-code.md b/documentation/source/installation/vs-code.md similarity index 100% rename from documentation/installation/vs-code.md rename to documentation/source/installation/vs-code.md diff --git a/documentation/io/input-guide.md b/documentation/source/io/input-guide.md similarity index 87% rename from documentation/io/input-guide.md rename to documentation/source/io/input-guide.md index 749c844f50..0fcff23c1a 100644 --- a/documentation/io/input-guide.md +++ b/documentation/source/io/input-guide.md @@ -8,6 +8,9 @@ If the code encounters a problem reading the input file, it will stop immediatel with an error message. The last line of the output file `OUT.DAT` may give an indication of where in the input file the problem lies. +!!! Info "Variable Descriptions" + A full list of inputs variables is given in the PROCESS data structure API documentation [here](../../source/reference/process/data_structure/blanket_library). + ## File Naming Convention The default PROCESS input file name is `IN.DAT`. The user can provide a named @@ -47,7 +50,7 @@ icc = 2 * Global power balance (consistency equation) !!! Info "Constraints" A full list of constraints is given on the variable description page in the row labelled - `lablcc` [here](vardes.md#numerics). + `lablcc` [here](../../source/reference/process/data_structure/numerics/#process.data_structure.numerics.lablcc). See [solver](../solver/solver-guide.md) page for more info ## Iteration Variables @@ -80,7 +83,7 @@ the default, if no value is specified), will be used as the starting value. !!! Note "Iteration Variables" A full list of iteration variables is given on the variable description page in the row labelled - `lablxc` [here](vardes.md#numerics). + `lablxc` [here](../../source/reference/process/data_structure/numerics/#process.data_structure.numerics.lablxc). (See [solver](../solver/solver-guide.md) page for more info) ## Bounds @@ -131,7 +134,7 @@ epsvmc = 1.0e-8 * Error tolerance for vmcon !!! Info "Figure of Merit" A full list of figures of merit is given on the variable description page in the row labelled - `lablmm` [here](vardes.md#numerics). + `lablmm` [here](../../source/reference/process/data_structure/numerics/#process.data_structure.numerics.lablmm). ## Input Variables @@ -149,8 +152,7 @@ one can add a `*` to the beginning of the line, as below: ``` !!! Info "Variable Descriptions" - A full list of inputs variables is given in the PROCESS `html` documentation - file `vardes.html` and on the variable description page [here](vardes.md). + A full list of inputs variables is given in the PROCESS data structure API documentation [here](../../source/reference/process/data_structure/blanket_library). ## Scan @@ -166,7 +168,7 @@ isweep = 4 sweep = 2.8, 2.9, 3.0, 3.1 ``` -where `nsweep` is the scan variable chosen (see [variable descriptions](vardes.md)), +where `nsweep` is the scan variable chosen (see [variable descriptions](../../source/reference/process/scan/#process.scan.ScanVariables)), `isweep` is the number of scan points and `sweep` is the array of scan values. In this example, PROCESS runs for each of the four values given of the plasma aspect ratio variable `aspect`. @@ -198,7 +200,7 @@ Scan variables should not be confused with iteration variables. !!! Info "Scanning" For obvious reasons, the active scanning variable or variables must not also be active iteration variables. - A full list of scan variables is [here](vardes.md#scan_module). + A full list of scan variables is [here](../../source/reference/process/scan/#process.scan.ScanVariables). ## Examples diff --git a/documentation/io/output-guide.md b/documentation/source/io/output-guide.md similarity index 100% rename from documentation/io/output-guide.md rename to documentation/source/io/output-guide.md diff --git a/documentation/io/python-lib-guide.md b/documentation/source/io/python-lib-guide.md similarity index 100% rename from documentation/io/python-lib-guide.md rename to documentation/source/io/python-lib-guide.md diff --git a/documentation/io/utilities.md b/documentation/source/io/utilities.md similarity index 98% rename from documentation/io/utilities.md rename to documentation/source/io/utilities.md index 091f592a6a..8a1ec5020d 100644 --- a/documentation/io/utilities.md +++ b/documentation/source/io/utilities.md @@ -133,7 +133,7 @@ for the reference year of the inflation used. | Power flows | | :------------------------------------------------------------------------------------------------------------------------------------------------- | | Nominal neutron wall load[^2] | -| Normalised radius of the 'core' region $\rho_{core}$ used in the radiation correction of the onfinement scaling[^3] [^4] | +| Normalised radius of the 'core' region $\rho_{core}$ used in the radiation correction of the confinement scaling[^3] [^4] | | The electron density at the pedestal top, $n_{\text{e,ped}}$ | | The normalised radius $\rho=r/a$ at the pedestal top | | The helium fraction relative to the electron density | @@ -153,7 +153,7 @@ for the reference year of the inflation used. | Physics | | :-------------------------------------------------------------------------------------------------------------------------------------------- | | Plasma current, $I_{\text{P}}$ | -| Vaccuum magnetic field at in the plasma centre, $B_{\text{T}}(R_0)$ | +| Vacuum magnetic field at in the plasma centre, $B_{\text{T}}(R_0)$ | | Safety factor at the 95% flux surface, $q_{95}$ | | Definitions of $\beta$ as given in [^1] | | Volume averaged electron temperature $\langle T_e\rangle$ and density $\langle n_e\rangle$ | @@ -183,7 +183,7 @@ for the reference year of the inflation used. | Inboard TF nose case thickness | | Inboard TF minimum distance between side case and WP | | Radial width of inboard TF leg | -| Thickness of insualtion surrounding WP | +| Thickness of insulation surrounding WP | | Number of turns in WP | | WP current density | | Radial width of WP | @@ -241,7 +241,7 @@ plots in the `SIG_TF_plots/` folder, created if not existing. ### Discussion of the stress modelling assumptions -In case of a resisitive coil, the stress is calculated from a generalized plane strain model, hence providing vertical +In case of a resistive coil, the stress is calculated from a generalized plane strain model, hence providing vertical stress radial distribution, alongside the radial and the toroidal ones. This is not the case for superconducting magnets as a plane stress modelling is used for now. The reason is that a transverse orthotropic formulation of the generalized plane strain is needed to correctly take the difference of the casing in the vertical direction properly. This will be @@ -331,7 +331,7 @@ python process/io/plot_scans.py [-h] [-f path/to/MFILE(s)] [-yv output vars] [-y | `-sf, --save_format` | Output format (default='pdf') | | `-as, --axis_font_size` | Axis label font size selection (default=18) | | `-ln, --label_name` | Label names for plot legend. If multiple input files used then list the same number of label names eg: -nl 'leg1 leg2', (default = MFile file name) | -| `-2DC, --two_dimensional_contour` | Option to plot 2D scans as a coloured contour plot instead of a line plot. Note: Non convergent points will show up with a value of zero Note: The scan paramters must both be in increasing orderl | +| `-2DC, --two_dimensional_contour` | Option to plot 2D scans as a coloured contour plot instead of a line plot. Note: Non convergent points will show up with a value of zero Note: The scan parameters must both be in increasing order | | `-stc, --stack_plots` | Option to plot multiple 1D plots in a column of subplots. Variables will be plotted in order of input | diff --git a/documentation/physics-models/current_vs_time.png b/documentation/source/physics-models/current_vs_time.png similarity index 100% rename from documentation/physics-models/current_vs_time.png rename to documentation/source/physics-models/current_vs_time.png diff --git a/documentation/physics-models/detailed_physics.md b/documentation/source/physics-models/detailed_physics.md similarity index 100% rename from documentation/physics-models/detailed_physics.md rename to documentation/source/physics-models/detailed_physics.md diff --git a/documentation/physics-models/fusion_reactions/beam_reactions.md b/documentation/source/physics-models/fusion_reactions/beam_reactions.md similarity index 100% rename from documentation/physics-models/fusion_reactions/beam_reactions.md rename to documentation/source/physics-models/fusion_reactions/beam_reactions.md diff --git a/documentation/physics-models/fusion_reactions/deuterium_branching_plot.png b/documentation/source/physics-models/fusion_reactions/deuterium_branching_plot.png similarity index 100% rename from documentation/physics-models/fusion_reactions/deuterium_branching_plot.png rename to documentation/source/physics-models/fusion_reactions/deuterium_branching_plot.png diff --git a/documentation/physics-models/fusion_reactions/plasma_bosch_hale.md b/documentation/source/physics-models/fusion_reactions/plasma_bosch_hale.md similarity index 100% rename from documentation/physics-models/fusion_reactions/plasma_bosch_hale.md rename to documentation/source/physics-models/fusion_reactions/plasma_bosch_hale.md diff --git a/documentation/physics-models/fusion_reactions/plasma_reactions.md b/documentation/source/physics-models/fusion_reactions/plasma_reactions.md similarity index 100% rename from documentation/physics-models/fusion_reactions/plasma_reactions.md rename to documentation/source/physics-models/fusion_reactions/plasma_reactions.md diff --git a/documentation/physics-models/plasma_beta/plasma_alpha_beta_contribution.md b/documentation/source/physics-models/plasma_beta/plasma_alpha_beta_contribution.md similarity index 100% rename from documentation/physics-models/plasma_beta/plasma_alpha_beta_contribution.md rename to documentation/source/physics-models/plasma_beta/plasma_alpha_beta_contribution.md diff --git a/documentation/physics-models/plasma_beta/plasma_beta.md b/documentation/source/physics-models/plasma_beta/plasma_beta.md similarity index 100% rename from documentation/physics-models/plasma_beta/plasma_beta.md rename to documentation/source/physics-models/plasma_beta/plasma_beta.md diff --git a/documentation/physics-models/plasma_composition.md b/documentation/source/physics-models/plasma_composition.md similarity index 100% rename from documentation/physics-models/plasma_composition.md rename to documentation/source/physics-models/plasma_composition.md diff --git a/documentation/physics-models/plasma_confinement.md b/documentation/source/physics-models/plasma_confinement.md similarity index 100% rename from documentation/physics-models/plasma_confinement.md rename to documentation/source/physics-models/plasma_confinement.md diff --git a/documentation/physics-models/plasma_current/bootstrap_current.md b/documentation/source/physics-models/plasma_current/bootstrap_current.md similarity index 99% rename from documentation/physics-models/plasma_current/bootstrap_current.md rename to documentation/source/physics-models/plasma_current/bootstrap_current.md index 8704199b1b..2bad25d1f3 100644 --- a/documentation/physics-models/plasma_current/bootstrap_current.md +++ b/documentation/source/physics-models/plasma_current/bootstrap_current.md @@ -272,7 +272,7 @@ $$ 1 \times 10^6 \times \frac{-B_{0}\left[\rho\right]_{-1}\left[\frac{1}{q}\right]_{-1}}{0.2\pi R_0}\right) $$ -In this case square brackets denote array variables equal in length to $\rho_{\text{max}}$ representing the normalized radius elements across the profile. The $-1$ subscript denotes the previous array element in the summation. +In this case square brackets denote array variables equal in length to $\rho_{\text{max}}$ representing the normalised radius elements across the profile. The $-1$ subscript denotes the previous array element in the summation. It is not known fully if the $\left(\sigma_{\text {neo }}\left\langle E_{\|} B\right\rangle-I(\psi) p(\psi)\right)$ term is properly implemented into the `PROCESS` version. The $R_{pe}$ value is assumingly taken to be 0.5 as it is stated to approximately to be in Sauter et.al[^4]. diff --git a/documentation/physics-models/plasma_current/diamagnetic_current.md b/documentation/source/physics-models/plasma_current/diamagnetic_current.md similarity index 100% rename from documentation/physics-models/plasma_current/diamagnetic_current.md rename to documentation/source/physics-models/plasma_current/diamagnetic_current.md diff --git a/documentation/physics-models/plasma_current/inductive_plasma_current.md b/documentation/source/physics-models/plasma_current/inductive_plasma_current.md similarity index 99% rename from documentation/physics-models/plasma_current/inductive_plasma_current.md rename to documentation/source/physics-models/plasma_current/inductive_plasma_current.md index b32a95eb9d..80baa9bec9 100644 --- a/documentation/physics-models/plasma_current/inductive_plasma_current.md +++ b/documentation/source/physics-models/plasma_current/inductive_plasma_current.md @@ -69,7 +69,7 @@ $$ \overbrace{\Phi_{\text{ind,internal,ramp}}}^{\texttt{vs_plasma_internal}} = I_{\text{p}} \times \underbrace{\left[\frac{\mu_0 R l_i}{2}\right]}_{\texttt{ind_plasma_internal}} $$ -Here $l_i$ is known as the normalized internal inductance defined for circular cross section plasmas with minor radius $a$: +Here $l_i$ is known as the normalised internal inductance defined for circular cross section plasmas with minor radius $a$: $$ l_i = \frac{\langle B_{\text{p}}^2 \rangle }{B_{\text{p}}^2(a)} diff --git "a/documentation/physics-models/plasma_current/pfirsch_schl\303\274ter_current_drive.md" "b/documentation/source/physics-models/plasma_current/pfirsch_schl\303\274ter_current_drive.md" similarity index 100% rename from "documentation/physics-models/plasma_current/pfirsch_schl\303\274ter_current_drive.md" rename to "documentation/source/physics-models/plasma_current/pfirsch_schl\303\274ter_current_drive.md" diff --git a/documentation/physics-models/plasma_current/plasma_current.md b/documentation/source/physics-models/plasma_current/plasma_current.md similarity index 100% rename from documentation/physics-models/plasma_current/plasma_current.md rename to documentation/source/physics-models/plasma_current/plasma_current.md diff --git a/documentation/physics-models/plasma_current/plasma_inductance.md b/documentation/source/physics-models/plasma_current/plasma_inductance.md similarity index 100% rename from documentation/physics-models/plasma_current/plasma_inductance.md rename to documentation/source/physics-models/plasma_current/plasma_inductance.md diff --git a/documentation/physics-models/plasma_current/plasma_resistive_heating.md b/documentation/source/physics-models/plasma_current/plasma_resistive_heating.md similarity index 100% rename from documentation/physics-models/plasma_current/plasma_resistive_heating.md rename to documentation/source/physics-models/plasma_current/plasma_resistive_heating.md diff --git a/documentation/physics-models/plasma_density.md b/documentation/source/physics-models/plasma_density.md similarity index 100% rename from documentation/physics-models/plasma_density.md rename to documentation/source/physics-models/plasma_density.md diff --git a/documentation/physics-models/plasma_geometry.md b/documentation/source/physics-models/plasma_geometry.md similarity index 100% rename from documentation/physics-models/plasma_geometry.md rename to documentation/source/physics-models/plasma_geometry.md diff --git a/documentation/physics-models/plasma_h_mode.md b/documentation/source/physics-models/plasma_h_mode.md similarity index 100% rename from documentation/physics-models/plasma_h_mode.md rename to documentation/source/physics-models/plasma_h_mode.md diff --git a/documentation/physics-models/plasma_overview.md b/documentation/source/physics-models/plasma_overview.md similarity index 80% rename from documentation/physics-models/plasma_overview.md rename to documentation/source/physics-models/plasma_overview.md index 44f11bc531..9cbf90645b 100644 --- a/documentation/physics-models/plasma_overview.md +++ b/documentation/source/physics-models/plasma_overview.md @@ -2,7 +2,7 @@ !!! warning " Documentation re-write" - The plasma documenation is slowly going through an update to ensure each section is properly decribed and up to date. Each section of the plasma now has its own dedicated page + The plasma documentation is slowly going through an update to ensure each section is properly described and up to date. Each section of the plasma now has its own dedicated page ## Introduction diff --git a/documentation/physics-models/plasma_power_balance.md b/documentation/source/physics-models/plasma_power_balance.md similarity index 100% rename from documentation/physics-models/plasma_power_balance.md rename to documentation/source/physics-models/plasma_power_balance.md diff --git a/documentation/physics-models/plasma_radiation.md b/documentation/source/physics-models/plasma_radiation.md similarity index 99% rename from documentation/physics-models/plasma_radiation.md rename to documentation/source/physics-models/plasma_radiation.md index 8606e658a0..a4ec7603a7 100644 --- a/documentation/physics-models/plasma_radiation.md +++ b/documentation/source/physics-models/plasma_radiation.md @@ -66,7 +66,7 @@ For the regime above $40 \ \text{keV}$ whichc an be seen by the dashed lines in The radiation emission is numerically integrated over the plasma profile, using the corresponding temperature and density distributions. Emission is only considered from within the separatrix, as the PROCESS model does not account for the scrape-off layer. -The plasma inside the separatrix is divided into two regions: the “core” and the “edge,” separated by a normalized minor radius defined by the user. +The plasma inside the separatrix is divided into two regions: the “core” and the “edge,” separated by a normalised minor radius defined by the user. Radiation is calculated separately for the core and edge regions, except for synchrotron radiation, which is assumed to originate solely from the core. -------------- @@ -200,7 +200,7 @@ A comparison of the different reflection functions can be seen in the graph belo -The power loss due to synchrotron radiation grows as the aspect ratio decreases. At high aspect ratios $(A > 6)$, although $P_{\text{syn}}$ increases with $R$, the normalized synchrotron loss saturates. This is due to the fact that the magnetic field inhomogeneity vanishes for large $A$. For the above reason a $G$ correction factor is implemented.This gives an root mean square error of 6.2% with respect to a secondary +The power loss due to synchrotron radiation grows as the aspect ratio decreases. At high aspect ratios $(A > 6)$, although $P_{\text{syn}}$ increases with $R$, the normalised synchrotron loss saturates. This is due to the fact that the magnetic field inhomogeneity vanishes for large $A$. For the above reason a $G$ correction factor is implemented.This gives an root mean square error of 6.2% with respect to a secondary dataset consisting of 640 complete computations for the same range of variables variables above and for an aspect ratio interval of $1.5 diff --git a/documentation/solver/solver-guide.md b/documentation/source/solver/solver-guide.md similarity index 95% rename from documentation/solver/solver-guide.md rename to documentation/source/solver/solver-guide.md index e75513d3a7..25d5cd088a 100644 --- a/documentation/solver/solver-guide.md +++ b/documentation/source/solver/solver-guide.md @@ -111,7 +111,7 @@ Switch `ioptimz` should be set to 1 for optimisation mode. If `ioptimz = 0`, a non-optimisation pass is performed first. Occasionally this provides a feasible set of initial conditions that aids convergence of the optimiser, but it is recommended to use `ioptimz = 1`. -Enable all the relevant consistency equations, and it is advisable to enable the corresponding iterations variables shown first as corresponding itvs in the vardes.html file. A number of limit equations (inequality constraints) can also be activated. For limit equations, the corresponding f-value must be selected as an iteration variable. In optimisation more, the number of iteration variables is unlimited. +Enable all the relevant consistency equations, and it is advisable to enable the corresponding iterations variables. A number of limit equations (inequality constraints) can also be activated. For limit equations, the corresponding f-value must be selected as an iteration variable. In optimisation more, the number of iteration variables is unlimited. It may still be difficult, if not impossible, to reconcile the fusion power and the net electric power with the required values. This may well be due to the power conversion efficiency values being used. @@ -161,4 +161,4 @@ ixc = 4 * temp_plasma_electron_vol_avg_kev ixc = 6 * nd_plasma_electrons_vol_avg ... ``` -The beta and plasma power balance equality constraints are recommended to ensure model consistency, and the `temp_plasma_electron_vol_avg_kev` and `nd_plasma_electrons_vol_avg` iteration variables used to solve them. \ No newline at end of file +The beta and plasma power balance equality constraints are recommended to ensure model consistency, and the `temp_plasma_electron_vol_avg_kev` and `nd_plasma_electrons_vol_avg` iteration variables used to solve them. diff --git a/documentation/unique-models/buildings_sizes.md b/documentation/source/unique-models/buildings_sizes.md similarity index 95% rename from documentation/unique-models/buildings_sizes.md rename to documentation/source/unique-models/buildings_sizes.md index 541aee668f..9b4570b15d 100644 --- a/documentation/unique-models/buildings_sizes.md +++ b/documentation/source/unique-models/buildings_sizes.md @@ -9,7 +9,7 @@ The routine documented here estimates the sizes (footprints and volumes) of buil Calculation of the lateral size of the reactor building is driven by the radial width of the largest component, which is assumed to be one of a) PF coil maximum radius, b) cryostat radius, c) TF coil outer radius. Space is included for biological shielding around the reactor. -The 'key-width' used in estimating the reactor building size is defined to include the radial width of the largest component twice (to allow space for manoeuvring components during construction), a set clearance distance around the reactor, a transportation clearance between components, and a clearance to the building wall for crane operation. This key-width is then used to estimate the length and width of the reactor building, allowing for the necessity of laying down the largest component during construction. +The 'key-width' used in estimating the reactor building size is defined to include the radial width of the largest component twice (to allow space for manoeuvering components during construction), a set clearance distance around the reactor, a transportation clearance between components, and a clearance to the building wall for crane operation. This key-width is then used to estimate the length and width of the reactor building, allowing for the necessity of laying down the largest component during construction. The estimate of the vertical clearance required around the reactor include the set reactor clearance distance, a transportation clearance between components, clearance from the TF coil to the cryostat, clearance beneath the TF coil, a clearance to the ceiling for crane operation, and a crane arm height. The height of the reactor building is estimated on the assumption that the TF coil is the tallest single component and that twice this height is required to allow for construction/maintenance access, and this is added to the required vertical clearance. @@ -32,7 +32,7 @@ The architecture used in this estimation is that of a basement directly beneath This building provides hot cell facilities to maintain or dismantle highly radioactive components. These estimates assume all in-vessel components used through the life of the plant will need storage. The storage area required is derived from the sizes and number of components, allowing for a margin in component numbers as set by the quantity safety factor. Footprints and volumes required for storage include a set hot separation distance. The estimation of this facility size include: -- The tokomak is toroidally segmented based on number of TF coils +- The tokamak is toroidally segmented based on number of TF coils - Each component will be stored with the largest dimension oriented horizontally - Component height is the largest dimension diff --git a/documentation/unique-models/water_use.md b/documentation/source/unique-models/water_use.md similarity index 100% rename from documentation/unique-models/water_use.md rename to documentation/source/unique-models/water_use.md diff --git a/documentation/usage/FAQs.md b/documentation/source/usage/FAQs.md similarity index 96% rename from documentation/usage/FAQs.md rename to documentation/source/usage/FAQs.md index d76a7c456e..09b2f01a70 100644 --- a/documentation/usage/FAQs.md +++ b/documentation/source/usage/FAQs.md @@ -20,7 +20,7 @@ This should take less than or around 5 seconds. Users have experienced this taki ```bash nano ~/.bashrc ``` - - You will see the following line near the bottom, whihc was inserted when downloading and installing Xlaunch: + - You will see the following line near the bottom, which was inserted when downloading and installing Xlaunch: ```bash export DISPLAY=$(awk '/nameserver / {print $2; exit}' /etc/resolv.conf 2>/dev/null):0 ``` diff --git a/documentation/usage/examples.md b/documentation/source/usage/examples.md similarity index 100% rename from documentation/usage/examples.md rename to documentation/source/usage/examples.md diff --git a/documentation/usage/plotting.md b/documentation/source/usage/plotting.md similarity index 100% rename from documentation/usage/plotting.md rename to documentation/source/usage/plotting.md diff --git a/documentation/usage/running-process.md b/documentation/source/usage/running-process.md similarity index 98% rename from documentation/usage/running-process.md rename to documentation/source/usage/running-process.md index 3b1a5688dc..86844903ad 100644 --- a/documentation/usage/running-process.md +++ b/documentation/source/usage/running-process.md @@ -8,7 +8,7 @@ There are a number of ways to run PROCESS. The first two are determined by the If the optimisation fails to converge, a third option is available by using the command line option `-v` (VaryRun), together with a configuration file. PROCESS is run repeatedly in optimisation mode (`ioptimz` = 1 must be set), but a new input file is written each time, with different, randomly selected *initial* values of the iteration variables. The factor within which the initial values of the iteration variables are changed is `FACTOR` (in the configuration file). For example, `FACTOR = 1.1` will vary the initial values randomly by up to 10%. This is repeated until PROCESS converges, or until the maximum number of PROCESS runs (`NITER`) is reached. Sometimes this procedure will generate a converged solution when a single optimisation run does not. -A SCAN is available in any of these modes. One input variable can be scanned (`scan_dim = 1`) or two input variables (`scan_dim = 2`). A scan variable must not be an iteration variable. For details, see [scan_module](https://ukaea.github.io/PROCESS/io/vardes/?h=scan#scan_module). +A SCAN is available in any of these modes. One input variable can be scanned (`scan_dim = 1`) or two input variables (`scan_dim = 2`). A scan variable must not be an iteration variable. For details, see ScanVariables in the [scan module](../../source/reference/process/scan). -------------- diff --git a/documentation/usage/troubleshooting.md b/documentation/source/usage/troubleshooting.md similarity index 99% rename from documentation/usage/troubleshooting.md rename to documentation/source/usage/troubleshooting.md index fb9b3ab068..019c217257 100644 --- a/documentation/usage/troubleshooting.md +++ b/documentation/source/usage/troubleshooting.md @@ -15,7 +15,7 @@ the nature of the error and its location (line in the code). In addition, PROCESS will log recoverable errors and warnings (and other information) to the process.log file and, for serious logs, the terminal. Logs (errors and warnings) that occur during the output phase are captured -and written to the OUTFile and terminal in the run summary. The ouput phase is when the models are run to write the +and written to the OUTFile and terminal in the run summary. The output phase is when the models are run to write the results into the MFile, and occurs at the final iteration of an optimising run or when running an evaluation. These logs can be classified into two types: 1. **Warning**: provides information that the user should be aware about but that is not an error. For example, if the users diff --git a/documentation/stylesheets/vardes.css b/documentation/stylesheets/vardes.css deleted file mode 100644 index 9d4bb49acc..0000000000 --- a/documentation/stylesheets/vardes.css +++ /dev/null @@ -1,147 +0,0 @@ -table { - /* border-spacing: 10px; */ - border-collapse: collapse; -} - -table.vardes { - table-layout: fixed; - width: 100%; - border-collapse: collapse; - border: 1px solid; -} - -th { - font-weight: bold; -} - -th, -td { - padding: 10px; - border: 1px solid; -} -hr { - border: 0; - height: 0.1px; /* Adjust the height to change the thickness */ - background: rgba(128, 128, 128, 0.25); /* Adjust the color and transparency as needed */ -} - -html { - font-size: 1.3rem; -} - -.md-typeset h1 { - font-weight: bold; - color: var(--md-default-fg-color) !important; -} - -.md-typeset h2 { - font-weight: bold; -} - -/* .md-nav__link--passed, .md-nav__link[for] { - color: var(--md-default-fg-color); -} */ - -.md-nav__link[for] { - color: var(--md-default-fg-color) !important; -} - -.md-nav__title { - color: var(--md-default-fg-color) !important; -} - -.vardes tbody { - display: table; - width: 100%; -} - -.vardes .col1 { - width: 20%; -} - -.vardes .col2 { - width: 12%; -} - -.vardes .col3 { - width: 13%; -} - -.vardes .col4 { - width: 45%; -} - -/*-------------------- IMAGES --------------------*/ - -.logo { - width: 200px; -} - -@media only screen and (max-width: 767px) { - .logo { - width: 35%; - } -} - -.image { - width: 75%; -} - -@media only screen and (max-width: 767px) { - .image { - width: 100%; - } -} - -/* Indentation. */ -div.doc-contents:not(.first) { - padding-left: 25px; - border-left: 4px solid rgba(230, 230, 230); - margin-bottom: 60px; -} - -div.doc-class>.doc-heading { - background-color: #e7f2fa; - border-top: 3px solid #e0301c; - padding: 10px; -} - -div.doc-class>.doc-heading::before { - content: "class"; - color: dimgray; - font-style: italic; - font-size: 1rem; -} - -div.doc-method>h4::before { - content: "method"; - color: dimgray; - font-style: italic; - font-size: 0.8rem; -} - -div.doc-function>.doc-heading { - background-color: #e7f2fa; - border-top: 3px solid #e0301c; - padding: 10px; -} - -div.doc-function>.doc-heading::before { - content: "function"; - color: dimgray; - font-style: italic; - font-size: 1rem; -} - -div.doc-module>.doc-heading { - background-color: #e7f2fa; - border-top: 6px solid #e0301c; - padding: 10px; -} - -div.doc-module>.doc-heading::before { - content: "module"; - color: dimgray; - font-style: italic; - font-size: 1.2rem; -} diff --git a/mkdocs.yml b/mkdocs.yml index 29da05e6af..6ccdc0a653 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -1,6 +1,6 @@ --- site_name: PROCESS -docs_dir: documentation/ +docs_dir: documentation/source nav: - Getting Started: - About: index.md @@ -20,7 +20,6 @@ nav: - Output: io/output-guide.md - Python Libraries: io/python-lib-guide.md - Utilities: io/utilities.md - - Variable Descriptions: io/vardes.md - Development: - Git: - Usage: development/git-usage.md @@ -131,10 +130,7 @@ nav: - Stellarator Model: fusion-devices/stellarator.md - Inertial Fusion Energy Model: fusion-devices/inertial.md - Publications: publications.md - - Source Documentation: - - process: python/process.md - - process.io: python/process.io.md - - process.utilities: python/process.utilities.md + - Source Documentation: source/reference/ repo_url: https://github.com/UKAEA/PROCESS repo_name: UKAEA/PROCESS @@ -207,6 +203,11 @@ markdown_extensions: plugins: - autorefs - search + - gen-files: + scripts: + - documentation/scripts/gen_api_ref.py + - literate-nav: + nav_file: overview.md - glightbox: touchNavigation: true effect: zoom @@ -219,14 +220,13 @@ plugins: - mkdocs-jupyter: execute: true ignore: [scripts/**/*.py] - -# - mkdocstrings: -# handlers: -# python: -# selection: -# docstring_style: restructured-text -# rendering: -# show_source: false -# show_root_heading: true - -extra_css: [stylesheets/vardes.css] + - mkdocstrings: + handlers: + python: + options: + docstring_style: numpy + show_if_no_docstring: true + members_order: source + filters: + - '!^_' # Ignore private members starting with underscore + - '!log' diff --git a/process/__init__.py b/process/__init__.py index 945c7b0f48..7a63d88a2c 100644 --- a/process/__init__.py +++ b/process/__init__.py @@ -2,7 +2,7 @@ from importlib.metadata import version # setup the package "root" logger, every other logger in PROCESS -# will inherit from this (implicity, based on the namespace) +# will inherit from this (implicitly, based on the namespace) root_logger = logging.getLogger(__name__) root_logger.setLevel(logging.DEBUG) diff --git a/process/availability.py b/process/availability.py index 43c0499c28..58a55775cf 100644 --- a/process/availability.py +++ b/process/availability.py @@ -37,13 +37,13 @@ class Availability: """Module containing plant availability routines - author: P J Knight, CCFE, Culham Science Centre + This module contains routines for calculating the plant availability and component lifetimes for a fusion power plant. """ - def __init__(self) -> None: + def __init__(self): self.outfile = constants.NOUT # output file unit def run(self, output: bool = False): @@ -57,8 +57,10 @@ def run(self, output: bool = False): 2 | Morris model (2015) 3 | ST model (2023) - :param output: indicate whether output should be written to the output file, or not (default = False) - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not (default = False) """ if cv.i_plant_availability == 3: @@ -74,14 +76,16 @@ def run(self, output: bool = False): def avail(self, output: bool): """Routine to calculate component lifetimes and the overall plant availability - author: P J Knight, CCFE, Culham Science Centre + This routine calculates the component lifetimes and the overall plant availability. F/PL/PJK/PROCESS/CODE/043 - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not """ # Full power lifetime (in years) @@ -329,15 +333,17 @@ def avail(self, output: bool): def avail_2(self, output: bool): """Routine to calculate component lifetimes and the overall plant availability - author: J Morris, CCFE, Culham Science Centre + This routine calculates the component lifetimes and the overall plant availability using an updated model linked to the 2014 EUROfusion RAMI task 2014 EUROfusion RAMI report, "Availability in PROCESS" - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not """ # Plant Availability @@ -486,18 +492,22 @@ def avail_2(self, output: bool): def calc_u_planned(self, output: bool) -> float: """Calculates the planned unavailability of the plant - author: J Morris, CCFE, Culham Science Centre + This routine calculates the planned unavailability of the plant, using the methodology outlined in the 2014 EUROfusion RAMI report. 2014 EUROfusion RAMI report, "Availability in PROCESS" - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not - :returns: planned unavailability of plant - :rtype: float + Returns + ------- + float + planned unavailability of plant """ # Full power lifetimes (in years) ! @@ -623,18 +633,22 @@ def calc_u_planned(self, output: bool) -> float: def calc_u_unplanned_magnets(self, output: bool) -> float: """Calculates the unplanned unavailability of the magnets - author: J Morris, CCFE, Culham Science Centre + This routine calculates the unplanned unavailability of the magnets, using the methodology outlined in the 2014 EUROfusion RAMI report. 2014 EUROfusion RAMI report, "Availability in PROCESS" - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not - :returns: unplanned unavailability of magnets - :rtype: float + Returns + ------- + float + unplanned unavailability of magnets """ # Magnet temperature margin limit (K) @@ -704,13 +718,17 @@ def calc_u_unplanned_magnets(self, output: bool) -> float: def calc_u_unplanned_divertor(self, output: bool) -> float: """Calculates the unplanned unavailability of the divertor - author: J Morris, CCFE, Culham Science Centre - :param output: indicate whether output should be written to the output file, or not - :type output: boolean - :returns: unplanned unavailability of the divertor - :rtype: float + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not + + Returns + ------- + float + unplanned unavailability of the divertor """ # Calculate cycle limit in terms of days @@ -797,15 +815,19 @@ def calc_u_unplanned_divertor(self, output: bool) -> float: def calc_u_unplanned_fwbs(self, output: bool) -> float: """Calculates the unplanned unavailability of the first wall and blanket - author: J Morris, CCFE, Culham Science Centre + 2014 EUROfusion RAMI report, "Availability in PROCESS" - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not - :returns: unplanned unavailability of first wall and blanket - :rtype: float + Returns + ------- + float + unplanned unavailability of first wall and blanket """ # Calculate cycle limit in terms of days @@ -887,18 +909,22 @@ def calc_u_unplanned_fwbs(self, output: bool) -> float: def calc_u_unplanned_bop(self, output: bool) -> float: """Calculates the unplanned unavailability of the balance of plant - author: J Morris, CCFE, Culham Science Centre + This routine calculates the unplanned unavailability of the balance of plant, using the methodology outlined in the 2014 EUROfusion RAMI report. 2014 EUROfusion RAMI report, "Availability in PROCESS" - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not - :returns: unplanned unavailability of balance of plant - :rtype: float + Returns + ------- + float + unplanned unavailability of balance of plant """ # Balance of plant failure rate (failures per hour) @@ -947,15 +973,17 @@ def calc_u_unplanned_bop(self, output: bool) -> float: def calc_u_unplanned_hcd(self) -> float: """Calculates the unplanned unavailability of the heating and current drive system - author: J Morris, CCFE, Culham Science Centre + This routine calculates the unplanned unavailability of the heating and current drive system, using the methodology outlined in the 2014 EUROfusion RAMI report. 2014 EUROfusion RAMI report, "Availability in PROCESS" - :returns: unplanned unavailability of hcd - :rtype: float + Returns + ------- + float + unplanned unavailability of hcd """ # Currently just a fixed value until more information available or Q. @@ -965,7 +993,7 @@ def calc_u_unplanned_hcd(self) -> float: def calc_u_unplanned_vacuum(self, output: bool) -> float: """Calculates the unplanned unavailability of the vacuum system - author: J Morris, CCFE, Culham Science Centre + This routine calculates the unplanned unavailability of the vacuum system, using the methodology outlined in the 2014 EUROfusion @@ -973,11 +1001,15 @@ def calc_u_unplanned_vacuum(self, output: bool) -> float: 2014 EUROfusion RAMI report, "Availability in PROCESS" - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not - :returns: unplanned unavailability of vacuum system - :rtype: float + Returns + ------- + float + unplanned unavailability of vacuum system """ # Number of shutdowns @@ -1060,8 +1092,7 @@ def calc_u_unplanned_vacuum(self, output: bool) -> float: return u_unplanned_vacuum def avail_st(self, output: bool): - """ - Calculate the availability for a plant with a Spherical Tokamak. + """Calculate the availability for a plant with a Spherical Tokamak. This routine calculates the availability of a plant by considering various factors such as the lifetime of different components, planned and unplanned unavailability, and maintenance cycles. @@ -1092,6 +1123,11 @@ def avail_st(self, output: bool): ------ - The method assumes certain constants and reference points for calculations. - The method modifies the lifetimes of components to account for the calculated availability. + + Parameters + ---------- + output: bool + indicate whether output should be written to the output file, or no """ ref_powfmw = 2.0e3 # (MW) fusion power for EU-DEMO @@ -1352,8 +1388,10 @@ def cp_lifetime(): This routine calculates the lifetime of the centrepost, either for superconducting or aluminium/resistive magnets. - :returns: CP lifetime - :rtype: float + Returns + ------- + float + CP lifetime """ # SC magnets CP lifetime # Rem : only the TF maximum fluence is considered for now @@ -1379,8 +1417,11 @@ def divertor_lifetime(): """Calculate Divertor Lifetime This routine calculates the lifetime of the divertor based on the allowable divertor heat fluence. - :returns: Divertor lifetime - :rtype: float + + Returns + ------- + float + Divertor lifetime """ # Divertor lifetime # Either 0.0, calculated from allowable divertor fluence and heat load, or lifetime of the plant diff --git a/process/blanket_library.py b/process/blanket_library.py index 9dc4c575b2..857fb6312a 100644 --- a/process/blanket_library.py +++ b/process/blanket_library.py @@ -1,7 +1,4 @@ -"""This library contains routines that can be shared by the blanket modules used in PROCESS. - -author: G Graham, CCFE, Culham Science Centre -""" +"""This library contains routines that can be shared by the blanket modules used in PROCESS.""" import logging @@ -32,7 +29,7 @@ # LT Low Temperature # HT High Temperature # MMS Multi Module Segment -# SMS Single Modle Segment +# SMS Single Module Segment # IB Inboard # OB Outboard # HCD Heating & Current Drive @@ -40,18 +37,18 @@ class BlanketLibrary: - def __init__(self, fw) -> None: + def __init__(self, fw): self.outfile = constants.NOUT self.fw = fw def component_volumes(self): """Calculate the blanket, shield, vacuum vessel and cryostat volumes - author: J. Morris, CCFE, Culham Science Centre + Calculate the blanket, shield, vacuum vessel and cryostat volumes """ - # N.B. icomponent is a switch used to specify selected component: blanket=0, sheild=1, vacuum vessel=2 - # Replaced seperate subroutines for blnkt, shld and vv with fuction/subroutine with icomponent switch. + # N.B. icomponent is a switch used to specify selected component: blanket=0, shield=1, vacuum vessel=2 + # Replaced separate subroutines for blnkt, shld and vv with fuction/subroutine with icomponent switch. # Calculate half-height # Blanket @@ -71,8 +68,11 @@ def component_volumes(self): def component_half_height(self, icomponent: int): """Calculate the blanket, shield or vacuum vessel half-height Based on blanket_half_height, shield_half_height, vv_half_height - original author: J. Morris, CCFE, Culham Science Centre - author: G. Graham, CCFE, Culham Science Centre + + Parameters + ---------- + icomponent: int : + """ # Calculate component internal lower half-height (m) # Blanket @@ -103,8 +103,6 @@ def component_half_height(self, icomponent: int): def dshaped_component(self): """Calculate component surface area and volume using dshaped scheme Based on dshaped_blanket, dshaped_shield, dshaped_vv - original author: J. Morris, CCFE, Culham Science Centre - author: G. Graham, CCFE, Culham Science Centre """ # Calculate major radius to outer edge of inboard ... # ... section (m) @@ -147,8 +145,6 @@ def dshaped_component(self): def elliptical_component(self): """Calculate component surface area and volume using elliptical scheme Based on elliptical_blanket, elliptical_shield, elliptical_vv - original author: J. Morris, CCFE, Culham Science Centre - author: G. Graham, CCFE, Culham Science Centre """ # Major radius to centre of inboard and outboard ellipses (m) # (coincident in radius with top of plasma) @@ -195,7 +191,7 @@ def elliptical_component(self): def apply_coverage_factors(self): """Apply coverage factors to volumes - author: J. Morris, CCFE, Culham Science Centre + Apply coverage factors to volumes """ # Apply blanket coverage factors @@ -245,13 +241,16 @@ def primary_coolant_properties(self, output: bool): Uses middle value of input and output temperatures of coolant. Curently have H20 and He options. - original author: P. J. Knight, CCFE - adapted from previous version of pumppower function by: G Graham, CCFE References: see pumppower function description + + Parameters + ---------- + output: bool + """ # Make sure that, if the inputs for the FW and blanket inputs are different, - # the i_fw_blkt_shared_coolant variable is appropriately set for seperate coolants + # the i_fw_blkt_shared_coolant variable is appropriately set for separate coolants if ( fwbs_variables.i_fw_coolant_type == "Helium" and fwbs_variables.i_blkt_coolant_type == 2 @@ -436,8 +435,7 @@ def primary_coolant_properties(self, output: bool): ) def set_blanket_module_geometry(self): - """ - Sets the geometry parameters for blanket modules, including coolant channel dimensions, + """Sets the geometry parameters for blanket modules, including coolant channel dimensions, module segmentation, and flow lengths, based on the current configuration and input variables. The method performs the following steps: @@ -449,8 +447,10 @@ def set_blanket_module_geometry(self): in radial, toroidal, and poloidal directions, and checks for geometric constraints. - Calculates total flow lengths for primary coolant channels, used in pressure drop calculations. - Raises: - Error: If the poloidal segment length is less than three times the minimum liquid breeder pipe width. + Raises + ------ + Error + If the poloidal segment length is less than three times the minimum liquid breeder pipe width. """ if fwbs_variables.i_blanket_type == 5: @@ -472,7 +472,7 @@ def set_blanket_module_geometry(self): # Using the total perimeter of the machine, segment the outboard # blanket into nblktmodp*nblktmodt modules, all assumed to be the same size - # If SMS blanket then do not have seperate poloidal modules.... + # If SMS blanket then do not have separate poloidal modules.... # Should not need this as n_blkt_inboard_modules_poloidal is input but make sure here. if fwbs_variables.i_blkt_module_segmentation == 1: fwbs_variables.n_blkt_inboard_modules_poloidal = 1 @@ -561,8 +561,7 @@ def set_blanket_module_geometry(self): ) def thermo_hydraulic_model_pressure_drop_calculations(self, output: bool): - """ - Function that calculates the pressure drops for the thermo-hydraulic model + """Function that calculates the pressure drops for the thermo-hydraulic model when i_p_coolant_pumping = 2. Within are calculations necessary for the deltap_tot function but not required @@ -571,6 +570,11 @@ def thermo_hydraulic_model_pressure_drop_calculations(self, output: bool): Returns the pressure drops as a list with the number of entries dependent upon the switches i_blkt_dual_coolant and i_blkt_inboard. + + Parameters + ---------- + output: bool + """ npoltoti = 0 npoltoto = 0 @@ -1011,7 +1015,7 @@ def thermo_hydraulic_model_pressure_drop_calculations(self, output: bool): def blanket_module_poloidal_height(self): """Calculations for blanket module poloidal height - author: J. Morris, CCFE, Culham Science Centre + Calculations for blanket module poloidal height for D shaped and elliptical machines """ if ( @@ -1134,7 +1138,7 @@ def liquid_breeder_properties(self, output: bool = False): Uses middle value of input and output temperatures of Liquid Metal Breeder/Coolant Curently have PbLi but can expand with e.g., Lithium - author: G Graham, CCFE + References: @@ -1147,6 +1151,11 @@ def liquid_breeder_properties(self, output: bool = False): [Mar2019] Martelli et al. (2019), Literature review of lead-lithium thermophysical properties, Fusion Engineering and Design, 138, 183-195. + + Parameters + ---------- + output: bool + (Default value = False) """ # Use mid temp @@ -1386,14 +1395,19 @@ def liquid_breeder_properties(self, output: bool = False): def flow_velocity(self, i_channel_shape, mass_flow_rate, flow_density): """Calculate the coolant flow velocity (m/s) for given pipe mass flow rate and pipe size/shape. N.B. Assumed that primary BB and FW coolants have same pipe radius (= radius_fw_channel). - author: G. Graham, CCFE - :param i_channel_shape: Switch for circular or rectangular channel crossection. + + Parameters + ---------- + i_channel_shape : + Switch for circular or rectangular channel crossection. Shape depends on whether primary or secondary coolant. 1: circle (primary) 2: rectangle (secondary) - :param mass_flow_rate: Coolant mass flow rate per pipe (kg/s) - :param flow_density: Coolant density + mass_flow_rate : + Coolant mass flow rate per pipe (kg/s) + flow_density : + Coolant density """ if i_channel_shape == 1: @@ -1415,13 +1429,11 @@ def flow_velocity(self, i_channel_shape, mass_flow_rate, flow_density): ) def thermo_hydraulic_model(self, output: bool): - """ - Thermo-hydraulic model for first wall and blanket + """Thermo-hydraulic model for first wall and blanket ONLY CALLED if i_p_coolant_pumping = 2 or 3 Calculations for detailed powerflow model i_thermal_electric_conversion > 1 - original author: J. Morris, CCFE, Culham Science Centre Dual-coolant modifications and generalisation refactor: G. Graham, CCFE Three options: @@ -1456,6 +1468,11 @@ def thermo_hydraulic_model(self, output: bool): inlet temp (K) temp_fw_coolant_in temp_blkt_coolant_in inlet_temp_liq outlet temp (K) temp_fw_coolant_out temp_blkt_coolant_out outlet_temp_liq pressure (Pa) pres_fw_coolant pres_blkt_coolant blpressure_liq + + Parameters + ---------- + output: bool + """ ###################################################### # Pre calculations needed for thermo-hydraulic model # @@ -1516,7 +1533,7 @@ def thermo_hydraulic_model(self, output: bool): # FW and BB Mass Flow ########### # Make sure that, if the inputs for the FW and blanket inputs are different, - # the i_fw_blkt_shared_coolant variable is appropriately set for seperate coolants + # the i_fw_blkt_shared_coolant variable is appropriately set for separate coolants if ( fwbs_variables.i_fw_coolant_type == "Helium" and fwbs_variables.i_blkt_coolant_type == 2 @@ -2135,37 +2152,41 @@ def total_pressure_drop( nopolchan: int, label: str, ) -> float: - """ - Calculate the total pressure drop (Pa) for coolant flow in the first wall (FW) and breeding blanket (BZ). + """Calculate the total pressure drop (Pa) for coolant flow in the first wall (FW) and breeding blanket (BZ). This includes frictional losses and, for liquid breeder coolants, magnetohydrodynamic (MHD) losses. - :param output: Whether to write output to file. - :type output: bool - :param icoolpump: Switch for coolant type (1=primary He/H2O, 2=secondary PbLi/Li). - :type icoolpump: int - :param flow_velocity: Coolant flow velocity (m/s). - :type flow_velocity: float - :param len_pipe: Total flow length along pipe (m). - :type len_pipe: float - :param n_pipe_90_deg_bends: Number of 90 degree bends in pipe. - :type n_pipe_90_deg_bends: int - :param n_pipe_180_deg_bends: Number of 180 degree bends in pipe. - :type n_pipe_180_deg_bends: int - :param den_coolant: Coolant density (kg/m³). - :type den_coolant: float - :param visc_coolant_dynamic: Coolant dynamic viscosity (Pa s). - :type visc_coolant_dynamic: float - :param coolant_electrical_conductivity: Coolant electrical conductivity (A V⁻¹ m⁻¹). - :type coolant_electrical_conductivity: float - :param pol_channel_length: Length of poloidal channel section (m). - :type pol_channel_length: float - :param nopolchan: Number of poloidal channel sections. - :type nopolchan: int - :param label: Description label for output. - :type label: str - :return: Total pressure drop (Pa). - :rtype: float + Parameters + ---------- + output : bool + Whether to write output to file. + icoolpump : int + Switch for coolant type (1=primary He/H2O, 2=secondary PbLi/Li). + flow_velocity : float + Coolant flow velocity (m/s). + len_pipe : float + Total flow length along pipe (m). + n_pipe_90_deg_bends : int + Number of 90 degree bends in pipe. + n_pipe_180_deg_bends : int + Number of 180 degree bends in pipe. + den_coolant : float + Coolant density (kg/m³). + visc_coolant_dynamic : float + Coolant dynamic viscosity (Pa s). + coolant_electrical_conductivity : float + Coolant electrical conductivity (A V⁻¹ m⁻¹). + pol_channel_length : float + Length of poloidal channel section (m). + nopolchan : int + Number of poloidal channel sections. + label : str + Description label for output. + + Returns + ------- + float + Total pressure drop (Pa). """ radius_pipe_90_deg_bend, radius_pipe_180_deg_bend = ( @@ -2234,41 +2255,53 @@ def liquid_breeder_mhd_pressure_drop( drop is the sum of contributions. This is only used for secondary coolant/breeder so rectangular flow channels are assumed. - author: G Graham, CCFE - - :param vel: liquid metal coolant/breeder flow velocity (m/s) - :param vsc: liquid metal visosity - :param conduct_liq: liquid metal conductivity - :param l_channel: length long poloidal sections of channel - :param num_pol: number long poloidal sections of channel - :param label: description of calculation - - References: - - [Miy1986] Miyazaki et al. (1986), Magneto-Hydro-Dynamic Pressure Drop of Lithium - Flow in Rectangular Ducts, Fusion Technology, 10:3P2A, 830-836, DOI: 10.13182/FST10-830 - - [Mal1995] Malang and Mattas (1995), Comparison of lithium and the eutectic - lead-lithium alloy, two candidate liquid metal breeder materials - for self-cooled blankets, Fusion Engineering and Design 27, 399-406 - [Iba2013] Ibano et al (2013), Nutronics and pumping power analysis on the - Tokamak reactor for the fusion-biomass hybrid concept, - Fusion Engineering and Design, 88 - [Sho2018] Shoki et al (2018), MHD pressure drop measurement of PbLi flow - in double-bended pipe, Fusion Engineering and Design, 136, 17-23 + Parameters + ---------- + vel : + liquid metal coolant/breeder flow velocity (m/s) + vsc : + liquid metal visosity + conduct_liq : + liquid metal conductivity + l_channel : + length long poloidal sections of channel + num_pol : + number long poloidal sections of channel + label : + description of calculation + output: bool + (Default value = False) + + References + ---------- + + [Miy1986] Miyazaki et al. (1986), Magneto-Hydro-Dynamic Pressure Drop of Lithium + Flow in Rectangular Ducts, Fusion Technology, 10:3P2A, 830-836, DOI: 10.13182/FST10-830 + + [Mal1995] Malang and Mattas (1995), Comparison of lithium and the eutectic + lead-lithium alloy, two candidate liquid metal breeder materials + for self-cooled blankets, Fusion Engineering and Design 27, 399-406 + + [Iba2013] Ibano et al (2013), Nutronics and pumping power analysis on the + Tokamak reactor for the fusion-biomass hybrid concept, + Fusion Engineering and Design, 88 + + [Sho2018] Shoki et al (2018), MHD pressure drop measurement of PbLi flow + in double-bended pipe, Fusion Engineering and Design, 136, 17-23 + + [Klu2019] Kluber et al. (2019), Numerical simulations of 3D magnetohydrodynamic + flows in dual-coolant lead lithium blankets, Fusion Engineering and Design, + 146, 684-687 + + [Sua2021] MHD effects in geometrical sigularities on high velocity breeding + blanket designs. Part II, ENR-PRD.BB-T007-D002, EFDA_D_2PDT9U. + Also, see asssociated paper: Suarez et al. (2021), On the use of CFD + to obtain head loss coefficients in hydraulic systems and it's appliaction + to liquid metal flows in nuclear fusion reactor blankets, Plasma. Phys. + Control fusion, 63, 124002 - [Klu2019] Kluber et al. (2019), Numerical simulations of 3D magnetohydrodynamic - flows in dual-coolant lead lithium blankets, Fusion Engineering and Design, - 146, 684-687 - - [Sua2021] MHD effects in geometrical sigularities on high velocity breeding - blanket designs. Part II, ENR-PRD.BB-T007-D002, EFDA_D_2PDT9U. - Also, see asssociated paper: Suarez et al. (2021), On the use of CFD - to obtain head loss coefficients in hydraulic systems and it's appliaction - to liquid metal flows in nuclear fusion reactor blankets, Plasma. Phys. - Control fusion, 63, 124002 """ # Magnetic feild strength in IB or OB blanket if label == "Inboard blanket breeder liquid": @@ -2366,7 +2399,12 @@ def liquid_breeder_mhd_pressure_drop( def calculate_pipe_bend_radius(self, i_ps: int): """Set the pipe bend radius based on the coolant type. - :param i_ps: switch for primary or secondary coolant + Parameters + ---------- + i_ps : + switch for primary or secondary coolant + i_ps: int : + """ # If primary coolant or secondary coolant (See DCLL) radius_pipe_90_deg_bend = ( @@ -2392,24 +2430,36 @@ def coolant_friction_pressure_drop( label: str, output: bool = False, ): - """ - Pressure drops are calculated for a pipe with a number of 90 + """Pressure drops are calculated for a pipe with a number of 90 and 180 degree bends. The pressure drop due to frictional forces along the total straight length of the pipe is calculated, then the pressure drop due to the bends is calculated. The total pressure drop is the sum of all contributions. - :param i_ps: switch for primary or secondary coolant - :param radius_pipe_90_deg_bend: radius of 90 degree bend in pipe (m) - :param radius_pipe_180_deg_bend: radius of 180 degree bend in pipe (m) - :param n_pipe_90_deg_bends: number of 90 degree bends in the pipe - :param n_pipe_180_deg_bends: number of 180 degree bends in the pipe - :param len_pipe: total flow length along pipe (m) - :param den_coolant: coolant density (kg/m³) - :param visc_coolant: coolant viscosity (Pa s) - :param vel_coolant: coolant flow velocity (m/s) - :param label: component name - :param output: boolean of whether to write data to output file + Parameters + ---------- + i_ps : + switch for primary or secondary coolant + radius_pipe_90_deg_bend : + radius of 90 degree bend in pipe (m) + radius_pipe_180_deg_bend : + radius of 180 degree bend in pipe (m) + n_pipe_90_deg_bends : + number of 90 degree bends in the pipe + n_pipe_180_deg_bends : + number of 180 degree bends in the pipe + len_pipe : + total flow length along pipe (m) + den_coolant : + coolant density (kg/m³) + visc_coolant : + coolant viscosity (Pa s) + vel_coolant : + coolant flow velocity (m/s) + label : + component name + output : + boolean of whether to write data to output file :Notes: Darcy-Weisbach Equation (straight pipe): @@ -2542,9 +2592,12 @@ def coolant_friction_pressure_drop( def pipe_hydraulic_diameter(self, i_channel_shape): """Caculate the hydraulic diameter (m) for a given coolant pipe size/shape. - author: G. Graham - :param i_channel_shape: switch for circular or rectangular channel crossection. + + Parameters + ---------- + i_channel_shape : + switch for circular or rectangular channel crossection. Shape depends on whether primary or secondary coolant """ # If primary coolant then circular channels assumed @@ -2571,24 +2624,28 @@ def elbow_coeff( darcy_friction: float, dia_pipe: float, ) -> float: - """ - Calculates elbow bend coefficients for pressure drop calculations. - - :param radius_pipe_elbow: Pipe elbow radius (m) - :type radius_pipe_elbow: float - :param deg_pipe_elbow: Pipe elbow angle (degrees) - :type deg_pipe_elbow: float - :param darcy_friction: Darcy friction factor - :type darcy_friction: float - :param dia_pipe: Pipe diameter (m) - :type dia_pipe: float - :return: Elbow coefficient for pressure drop calculation - :rtype: float - - :References: + """Calculates elbow bend coefficients for pressure drop calculations. + + Parameters + ---------- + radius_pipe_elbow : float + Pipe elbow radius (m) + deg_pipe_elbow : float + Pipe elbow angle (degrees) + darcy_friction : float + Darcy friction factor + dia_pipe : float + Pipe diameter (m) + + Returns + ------- + float + Elbow coefficient for pressure drop calculation + + References + ---------- - [Ide1969] Idel'Cik, I. E. (1969), Memento des pertes de charge, - Collection de la Direction des Etudes et Recherches d'Electricité de France. - + Collection de la Direction des Etudes et Recherches d'Electricité de France. """ if deg_pipe_elbow == 90: @@ -2638,33 +2695,38 @@ def coolant_pumping_power( den_coolant: float, label: str, ) -> float: - """ - Calculate the coolant pumping power in MW for the first wall (FW) or breeding blanket (BZ) coolant. - - :param output: Whether to write data to output file. - :type output: bool - :param i_liquid_breeder: Switch for primary coolant or secondary coolant/breeder (1=primary He/H2O, 2=secondary PbLi/Li). - :type i_liquid_breeder: int - :param temp_coolant_pump_outlet: Pump outlet temperature (K). - :type temp_coolant_pump_outlet: float - :param temp_coolant_pump_inlet: Pump inlet temperature (K). - :type temp_coolant_pump_inlet: float - :param pressure: Outlet (pump inlet) coolant pressure (Pa). - :type pressure: float - :param dpres_coolant: Coolant pressure drop (Pa). - :type dpres_coolant: float - :param mflow_coolant_total: Total coolant mass flow rate in (kg/s). - :type mflow_coolant_total: float - :param primary_coolant_switch: Name of FW/blanket coolant (e.g., "Helium" or "Water") if icoolpump=1. - :type primary_coolant_switch: str - :param den_coolant: Density of coolant or liquid breeder (kg/m³). - :type den_coolant: float - :param label: Description label for output. - :type label: str - :return: Pumping power in MW. - :rtype: float - - :references: + """Calculate the coolant pumping power in MW for the first wall (FW) or breeding blanket (BZ) coolant. + + Parameters + ---------- + output : bool + Whether to write data to output file. + i_liquid_breeder : int + Switch for primary coolant or secondary coolant/breeder (1=primary He/H2O, 2=secondary PbLi/Li). + temp_coolant_pump_outlet : float + Pump outlet temperature (K). + temp_coolant_pump_inlet : float + Pump inlet temperature (K). + pressure : float + Outlet (pump inlet) coolant pressure (Pa). + dpres_coolant : float + Coolant pressure drop (Pa). + mflow_coolant_total : float + Total coolant mass flow rate in (kg/s). + primary_coolant_switch : str + Name of FW/blanket coolant (e.g., "Helium" or "Water") if icoolpump=1. + den_coolant : float + Density of coolant or liquid breeder (kg/m³). + label : str + Description label for output. + + Returns + ------- + float + Pumping power in MW. + + References + ---------- - Idel'Cik, I. E. (1969), Memento des pertes de charge - S.P. Sukhatme (2005), A Textbook on Heat Transfer """ @@ -2808,38 +2870,41 @@ def set_pumping_powers_as_fractions( p_div_nuclear_heat_total_mw: float, p_div_rad_total_mw: float, ) -> tuple[float, float, float, float]: - """ - Calculate mechanical pumping powers as fractions of thermal power in each component. - - :param f_p_fw_coolant_pump_total_heat: Fraction for FW coolant pump. - :type f_p_fw_coolant_pump_total_heat: float - :param f_p_blkt_coolant_pump_total_heat: Fraction for blanket coolant pump. - :type f_p_blkt_coolant_pump_total_heat: float - :param f_p_shld_coolant_pump_total_heat: Fraction for shield coolant pump. - :type f_p_shld_coolant_pump_total_heat: float - :param f_p_div_coolant_pump_total_heat: Fraction for divertor coolant pump. - :type f_p_div_coolant_pump_total_heat: float - :param p_fw_nuclear_heat_total_mw: Total FW nuclear heating (MW). - :type p_fw_nuclear_heat_total_mw: float - :param psurffwi: Inboard FW surface heating (MW). - :type psurffwi: float - :param psurffwo: Outboard FW surface heating (MW). - :type psurffwo: float - :param p_blkt_nuclear_heat_total_mw: Total blanket nuclear heating (MW). - :type p_blkt_nuclear_heat_total_mw: float - :param p_shld_nuclear_heat_mw: Shield nuclear heating (MW). - :type p_shld_nuclear_heat_mw: float - :param p_cp_shield_nuclear_heat_mw: CP shield nuclear heating (MW). - :type p_cp_shield_nuclear_heat_mw: float - :param p_plasma_separatrix_mw: Plasma separatrix power (MW). - :type p_plasma_separatrix_mw: float - :param p_div_nuclear_heat_total_mw: Divertor nuclear heating (MW). - :type p_div_nuclear_heat_total_mw: float - :param p_div_rad_total_mw: Divertor radiative power (MW). - :type p_div_rad_total_mw: float - - :return: Tuple of pumping powers (MW) for FW, blanket, shield, and divertor. - :rtype: tuple[float, float, float, float] + """Calculate mechanical pumping powers as fractions of thermal power in each component. + + Parameters + ---------- + f_p_fw_coolant_pump_total_heat : float + Fraction for FW coolant pump. + f_p_blkt_coolant_pump_total_heat : float + Fraction for blanket coolant pump. + f_p_shld_coolant_pump_total_heat : float + Fraction for shield coolant pump. + f_p_div_coolant_pump_total_heat : float + Fraction for divertor coolant pump. + p_fw_nuclear_heat_total_mw : float + Total FW nuclear heating (MW). + psurffwi : float + Inboard FW surface heating (MW). + psurffwo : float + Outboard FW surface heating (MW). + p_blkt_nuclear_heat_total_mw : float + Total blanket nuclear heating (MW). + p_shld_nuclear_heat_mw : float + Shield nuclear heating (MW). + p_cp_shield_nuclear_heat_mw : float + CP shield nuclear heating (MW). + p_plasma_separatrix_mw : float + Plasma separatrix power (MW). + p_div_nuclear_heat_total_mw : float + Divertor nuclear heating (MW). + p_div_rad_total_mw : float + Divertor radiative power (MW). + + Returns + ------- + tuple[float, float, float, float] + Tuple of pumping powers (MW) for FW, blanket, shield, and divertor. """ p_fw_coolant_pump_mw = f_p_fw_coolant_pump_total_heat * ( p_fw_nuclear_heat_total_mw + psurffwi + psurffwo @@ -2864,7 +2929,7 @@ def set_pumping_powers_as_fractions( def eshellarea(rshell, rmini, rmino, zminor): """Routine to calculate the inboard, outboard and total surface areas of a toroidal shell comprising two elliptical sections - author: P J Knight, CCFE, Culham Science Centre + rshell : input real : major radius of centre of both ellipses (m) rmini : input real : horizontal distance from rshell to inboard elliptical shell (m) @@ -2876,6 +2941,17 @@ def eshellarea(rshell, rmini, rmino, zminor): atot : output real : total surface area of shell (m3) This routine calculates the surface area of the inboard and outboard sections of a toroidal shell defined by two co-centred semi-ellipses. + + Parameters + ---------- + rshell : + + rmini : + + rmino : + + zminor : + """ # Inboard section @@ -2892,24 +2968,26 @@ def eshellarea(rshell, rmini, rmino, zminor): def dshellarea( rmajor: float, rminor: float, zminor: float ) -> tuple[float, float, float]: - """ - Calculate the inboard, outboard, and total surface areas of a D-shaped toroidal shell. - - :param rmajor: Major radius of inboard straight section (m) - :type rmajor: float - :param rminor: Horizontal width of shell (m) - :type rminor: float - :param zminor: Vertical half-height of shell (m) - :type zminor: float + """Calculate the inboard, outboard, and total surface areas of a D-shaped toroidal shell. - :return: Tuple containing: + The inboard section is assumed to be a cylinder. + The outboard section is defined by a semi-ellipse, centred on the major radius of the inboard section. + Parameters + ---------- + rmajor : float + Major radius of inboard straight section (m) + rminor : float + Horizontal width of shell (m) + zminor : float + Vertical half-height of shell (m) + + Returns + ------- + tuple[float, float, float] + Tuple containing: - ain: Surface area of inboard straight section (m²) - aout: Surface area of outboard curved section (m²) - atot: Total surface area of shell (m²) - :rtype: tuple[float, float, float] - - The inboard section is assumed to be a cylinder. - The outboard section is defined by a semi-ellipse, centred on the major radius of the inboard section. """ # Area of inboard cylindrical shell ain = 4.0 * zminor * np.pi * rmajor @@ -2924,25 +3002,40 @@ def dshellarea( def eshellvol(rshell, rmini, rmino, zminor, drin, drout, dz): """Routine to calculate the inboard, outboard and total volumes of a toroidal shell comprising two elliptical sections - author: P J Knight, CCFE, Culham Science Centre - rshell : input real : major radius of centre of both ellipses (m) - rmini : input real : horizontal distance from rshell to outer edge - of inboard elliptical shell (m) - rmino : input real : horizontal distance from rshell to inner edge - of outboard elliptical shell (m) - zminor : input real : vertical internal half-height of shell (m) - drin : input real : horiz. thickness of inboard shell at midplane (m) - drout : input real : horiz. thickness of outboard shell at midplane (m) - dz : input real : vertical thickness of shell at top/bottom (m) - vin : output real : volume of inboard section (m3) - vout : output real : volume of outboard section (m3) - vtot : output real : total volume of shell (m3) + This routine calculates the volume of the inboard and outboard sections of a toroidal shell defined by two co-centred semi-ellipses. Each section's internal and external surfaces are in turn defined by two semi-ellipses. The volumes of each section are calculated as the difference in those of the volumes of revolution enclosed by their inner and outer surfaces. + + Parameters + ---------- + rshell : + major radius of centre of both ellipses (m) + rmini : + horizontal distance from rshell to outer edge of inboard elliptical shell (m) + rmino : + horizontal distance from rshell to inner edge of outboard elliptical shell (m) + zminor : + vertical internal half-height of shell (m) + drin : + horiz. thickness of inboard shell at midplane (m) + drout : + horiz. thickness of outboard shell at midplane (m) + dz : + vertical thickness of shell at top/bottom (m) + + Returns + ------- + vin : + volume of inboard section (m3) + vout: + volume of outboard section (m3) + vtot: + total volume of shell (m3) + ------- """ # Inboard section @@ -2988,17 +3081,7 @@ def eshellvol(rshell, rmini, rmino, zminor, drin, drout, dz): def dshellvol(rmajor, rminor, zminor, drin, drout, dz): """Routine to calculate the inboard, outboard and total volumes of a D-shaped toroidal shell - author: P J Knight, CCFE, Culham Science Centre - rmajor : input real : major radius to outer point of inboard - straight section of shell (m) - rminor : input real : horizontal internal width of shell (m) - zminor : input real : vertical internal half-height of shell (m) - drin : input real : horiz. thickness of inboard shell at midplane (m) - drout : input real : horiz. thickness of outboard shell at midplane (m) - dz : input real : vertical thickness of shell at top/bottom (m) - vin : output real : volume of inboard straight section (m3) - vout : output real : volume of outboard curved section (m3) - vtot : output real : total volume of shell (m3) + This routine calculates the volume of the inboard and outboard sections of a D-shaped toroidal shell defined by the above input parameters. The inboard section is assumed to be a cylinder of uniform thickness. @@ -3006,6 +3089,31 @@ def dshellvol(rmajor, rminor, zminor, drin, drout, dz): by two semi-ellipses, centred on the outer edge of the inboard section; its volume is calculated as the difference in those of the volumes of revolution enclosed by the two surfaces. + + Parameters + ---------- + rmajor : + major radius to outer point of inboardstraight section of shell (m) + rminor : + horizontal internal width of shell (m) + zminor : + vertical internal half-height of shell (m) + drin : + horiz. thickness of inboard shell at midplane (m) + drout : + horiz. thickness of outboard shell at midplane (m) + dz : + vertical thickness of shell at top/bottom (m) + + Returns + ------- + vin : + volume of inboard straight section (m3) + vout: + volume of outboard curved section (m3) + vtot: + total volume of shell (m3) + """ # Volume of inboard cylindrical shell vin = 2.0 * (zminor + dz) * np.pi * (rmajor**2 - (rmajor - drin) ** 2) @@ -3048,19 +3156,23 @@ def calculate_blanket_outboard_module_geometry( rminor: float, dr_fw_plasma_gap_outboard: float, ) -> float: - """ - Calculate the mid-plane toroidal circumference and segment length of the outboard blanket. - - :param n_blkt_outboard_modules_toroidal: Number of outboard blanket modules in the toroidal direction. - :type n_blkt_outboard_modules_toroidal: int - :param rmajor: Major radius (m). - :type rmajor: float - :param rminor: Minor radius (m). - :type rminor: float - :param dr_fw_plasma_gap_outboard: Outboard first wall to plasma gap (m). - :type dr_fw_plasma_gap_outboard: float - :return: Length of outboard blanket segment in the toroidal direction (m). - :rtype: float + """Calculate the mid-plane toroidal circumference and segment length of the outboard blanket. + + Parameters + ---------- + n_blkt_outboard_modules_toroidal : int + Number of outboard blanket modules in the toroidal direction. + rmajor : float + Major radius (m). + rminor : float + Minor radius (m). + dr_fw_plasma_gap_outboard : float + Outboard first wall to plasma gap (m). + + Returns + ------- + float + Length of outboard blanket segment in the toroidal direction (m). """ return ( 2.0 * np.pi * (rmajor + rminor + dr_fw_plasma_gap_outboard) @@ -3087,19 +3199,23 @@ def calculate_blanket_inboard_module_geometry( rminor: float, dr_fw_plasma_gap_inboard: float, ) -> float: - """ - Calculate the mid-plane toroidal circumference and segment length of the inboard blanket. - - :param n_blkt_inboard_modules_toroidal: Number of inboard blanket modules in the toroidal direction. - :type n_blkt_inboard_modules_toroidal: int - :param rmajor: Major radius (m). - :type rmajor: float - :param rminor: Minor radius (m). - :type rminor: float - :param dr_fw_plasma_gap_inboard: Inboard first wall to plasma gap (m). - :type dr_fw_plasma_gap_inboard: float - :return: Length of inboard blanket segment in the toroidal direction (m). - :rtype: float + """Calculate the mid-plane toroidal circumference and segment length of the inboard blanket. + + Parameters + ---------- + n_blkt_inboard_modules_toroidal : int + Number of inboard blanket modules in the toroidal direction. + rmajor : float + Major radius (m). + rminor : float + Minor radius (m). + dr_fw_plasma_gap_inboard : float + Inboard first wall to plasma gap (m). + + Returns + ------- + float + Length of inboard blanket segment in the toroidal direction (m). """ return ( 2.0 * np.pi * (rmajor + rminor + dr_fw_plasma_gap_inboard) diff --git a/process/build.py b/process/build.py index 20609b8ff5..adf808e250 100644 --- a/process/build.py +++ b/process/build.py @@ -25,7 +25,7 @@ def __init__(self): self.outfile = constants.NOUT self.mfile = constants.MFILE - def run(self) -> None: + def run(self): self.calculate_radial_build(output=False) self.calculate_vertical_build(output=False) @@ -54,28 +54,31 @@ def calculate_beam_port_size( dx_beam_duct: float, dx_beam_shield: float, ) -> tuple[float, float]: - """ - Calculates the maximum possible tangency radius for adequate beam access. - - :param f_radius_beam_tangency_rmajor: Fraction of rmajor for beam tangency - :type f_radius_beam_tangency_rmajor: float - :param rmajor: Major radius - :type rmajor: float - :param n_tf_coils: Number of TF coils - :type n_tf_coils: int - :param dx_tf_inboard_out_toroidal: Toroidal width of outboard TF coil - :type dx_tf_inboard_out_toroidal: float - :param dr_tf_outboard: Radial thickness of outboard TF coil leg - :type dr_tf_outboard: float - :param r_tf_outboard_mid: Major radius of centre of outboard TF coil - :type r_tf_outboard_mid: float - :param dx_beam_duct: Width of beam duct - :type dx_beam_duct: float - :param dx_beam_shield: Shielding width on both sides of beam duct - :type dx_beam_shield: float - - :returns: Tuple containing (radius_beam_tangency, radius_beam_tangency_max) - :rtype: tuple[float, float] + """Calculates the maximum possible tangency radius for adequate beam access. + + Parameters + ---------- + f_radius_beam_tangency_rmajor : float + Fraction of rmajor for beam tangency + rmajor : float + Major radius + n_tf_coils : int + Number of TF coils + dx_tf_inboard_out_toroidal : float + Toroidal width of outboard TF coil + dr_tf_outboard : float + Radial thickness of outboard TF coil leg + r_tf_outboard_mid : float + Major radius of centre of outboard TF coil + dx_beam_duct : float + Width of beam duct + dx_beam_shield : float + Shielding width on both sides of beam duct + + Returns + ------- + tuple[float, float] + Tuple containing (radius_beam_tangency, radius_beam_tangency_max) """ # Have kept the single letter variable names to match the original code and documentation diagram. @@ -127,18 +130,17 @@ def calculate_beam_port_size( return radius_beam_tangency, radius_beam_tangency_max - def calculate_vertical_build(self, output: bool) -> None: - """ - Determines the vertical build of the machine. + def calculate_vertical_build(self, output: bool): + """Determines the vertical build of the machine. This method calculates various parameters related to the vertical build of the machine, such as thicknesses, radii, and areas. Results can be outputted with the `output` flag. - :param output: Flag indicating whether to output results - :type output: bool - :returns: None + Parameters + ---------- + output : bool + Flag indicating whether to output results """ - # Set the X-point heights for the top and bottom of the plasma # Assumes top-down plasma symmetry build_variables.z_plasma_xpoint_upper = ( @@ -849,18 +851,22 @@ def calculate_vertical_build(self, output: bool) -> None: ) def divgeom(self, output: bool): - """ - Divertor geometry calculation - author: J Galambos, ORNL - author: P J Knight, CCFE, Culham Science Centre - divht : output real : divertor height (m) - self.outfile : input integer : output file unit - iprint : input integer : switch for writing to output file (1=yes) + """Divertor geometry calculation + This subroutine determines the divertor geometry. The inboard (i) and outboard (o) plasma surfaces are approximated by arcs, and followed past the X-point to determine the maximum height. TART option: Peng SOFT paper + + Parameters + ---------- + output: bool + + Returns + ------- + divht: + divertor height (m) """ if physics_variables.itart == 1: return 1.75e0 * physics_variables.rminor @@ -1532,8 +1538,7 @@ def plasma_outboard_edge_toroidal_ripple( dx_tf_wp_insulation: float, dx_tf_wp_insertion_gap: float, ) -> tuple[float, float, int]: - """ - Plasma outboard toroidal field (TF) ripple calculation. + """Plasma outboard toroidal field (TF) ripple calculation. This routine computes the TF ripple amplitude at the midplane outboard plasma edge and the minimum radius of the TF coil centre that would @@ -1542,44 +1547,49 @@ def plasma_outboard_edge_toroidal_ripple( includes a simplified analytical picture-frame coil model for i_tf_shape == 2. - :param ripple_b_tf_plasma_edge_max: Maximum allowed ripple at plasma edge (percent) - :type ripple_b_tf_plasma_edge_max: float - :param r_tf_outboard_mid: Radius to the centre of the outboard TF coil leg (m) - :type r_tf_outboard_mid: float - :param n_tf_coils: Number of TF coils - :type n_tf_coils: int - :param rmajor: Plasma major radius (m) - :type rmajor: float - :param rminor: Plasma minor radius (m) - :type rminor: float - :param r_tf_wp_inboard_inner: Inner winding-pack inboard radius (m) - :type r_tf_wp_inboard_inner: float - :param r_tf_wp_inboard_centre: Centre winding-pack inboard radius (m) - :type r_tf_wp_inboard_centre: float - :param r_tf_wp_inboard_outer: Outer winding-pack inboard radius (m) - :type r_tf_wp_inboard_outer: float - :param dx_tf_wp_primary_toroidal: Primary toroidal winding-pack thickness (m) - :type dx_tf_wp_primary_toroidal: float - :param i_tf_shape: TF coil shape switch (2 => picture-frame analytical model) - :type i_tf_shape: int - :param i_tf_sup: TF coil support flag (1 => superconducting) - :type i_tf_sup: int - :param dx_tf_wp_insulation: Winding-pack insulation thickness (m) - :type dx_tf_wp_insulation: float - :param dx_tf_wp_insertion_gap: Winding-pack insertion gap (m) - :type dx_tf_wp_insertion_gap: float - - :returns: Tuple containing: - - ripple: Calculated ripple at plasma edge (percent) - - r_tf_outboard_midmin: Minimum r_tf_outboard_mid that yields the specified maximum ripple (m) - - flag: Applicability flag (0 = OK, non-zero = fitted-range concern) - :rtype: tuple[float, float, int] - - :notes: - - Fitted coefficients originate from parametric MAGINT runs (M. Kovari, 2014). - - Picture-frame coil analytical model (Ken McClements, 2022) is used when - `i_tf_shape == 2` and gives approximate results (within ~10% of numerical). - - The routine sets an applicability flag when fitted-range assumptions are exceeded. + Parameters + ---------- + ripple_b_tf_plasma_edge_max : float + Maximum allowed ripple at plasma edge (percent) + r_tf_outboard_mid : float + Radius to the centre of the outboard TF coil leg (m) + n_tf_coils : int + Number of TF coils + rmajor : float + Plasma major radius (m) + rminor : float + Plasma minor radius (m) + r_tf_wp_inboard_inner : float + Inner winding-pack inboard radius (m) + r_tf_wp_inboard_centre : float + Centre winding-pack inboard radius (m) + r_tf_wp_inboard_outer : float + Outer winding-pack inboard radius (m) + dx_tf_wp_primary_toroidal : float + Primary toroidal winding-pack thickness (m) + i_tf_shape : int + TF coil shape switch (2 => picture-frame analytical model) + i_tf_sup : int + TF coil support flag (1 => superconducting) + dx_tf_wp_insulation : float + Winding-pack insulation thickness (m) + dx_tf_wp_insertion_gap : float + Winding-pack insertion gap (m) + + Returns + ------- + tuple[float, float, int] + Tuple containing: + - ripple: Calculated ripple at plasma edge (percent) + - r_tf_outboard_midmin: Minimum r_tf_outboard_mid that yields the specified maximum ripple (m) + - flag: Applicability flag (0 = OK, non-zero = fitted-range concern) + + Notes + ----- + - Fitted coefficients originate from parametric MAGINT runs (M. Kovari, 2014). + - Picture-frame coil analytical model (Ken McClements, 2022) is used when + `i_tf_shape == 2` and gives approximate results (within ~10% of numerical). + - The routine sets an applicability flag when fitted-range assumptions are exceeded. """ if i_tf_sup == 1: # Minimal inboard WP radius [m] @@ -1668,19 +1678,16 @@ def plasma_outboard_edge_toroidal_ripple( return ripple, r_tf_outboard_midmin, flag - def calculate_radial_build(self, output: bool) -> None: - """ - This method determines the radial build of the machine. + def calculate_radial_build(self, output: bool): + """This method determines the radial build of the machine. It calculates various parameters related to the build of the machine, such as thicknesses, radii, and areas. Results can be outputted with the `output` flag. - Args: - output (bool): Flag indicating whether to output the results - - Returns: - None - + Parameters + ---------- + output : bool + Flag indicating whether to output the results """ if fwbs_variables.blktmodel > 0: diff --git a/process/buildings.py b/process/buildings.py index 95e7364ead..5e2f3595d2 100644 --- a/process/buildings.py +++ b/process/buildings.py @@ -21,14 +21,13 @@ class Buildings: - """author: J. Morris, P. Knight, R. Chapman (UKAEA) + """ This module contains routines for calculating the - parameters of the fusion power plant buildings. """ - def __init__(self) -> None: - """author: J. Morris, P. Knight, R. Chapman (UKAEA) + def __init__(self): + """ This routine calls the buildings calculations. """ @@ -108,29 +107,9 @@ def bldgs( helpow, ): """Determines the sizes of the plant buildings - author: P J Knight, CCFE, Culham Science Centre - author: P C Shipe, ORNL - pfr : input/output real : largest PF coil outer radius, m - pfm : : input real : largest PF coil mass, tonne - tfro : input real : outer radius of TF coil, m - tfri : input real : inner radius of TF coil, m - tfh : input real : full height of TF coil, m - tfm : input real : mass of one TF coil, tonne - tfno : input real : number of tf coils - shro : input real : outer radius of attached shield, m - shri : input real : inner radius of attached shield, m - shh : input real : height of attached shield, m - shm : input real : total mass of attached shield, kg - crr : input real : outer radius of common cryostat, m - helpow : input real : total cryogenic load, W - iprint : input integer : switch for writing to output file (1=yes) - outfile : input integer : output file unit - cryv : output real : volume of cryogenic building, m3 - vrci : output real : inner volume of reactor building, m3 - rbv : output real : outer volume of reactor building, m3 - rmbv : output real : volume of reactor maintenance building, m3 - wsv : output real : volume of warm shop, m3 - elev : output real : volume of electrical buildings, m3 + + + This routine determines the size of the plant buildings. The reactor building and maintenance building are sized based on the tokamak dimensions. The cryogenic building volume is @@ -138,8 +117,52 @@ def bldgs( sizes are input from other modules or by the user. This routine was modified to include fudge factors (fac1,2,...) to fit the ITER design, September 1990 (J. Galambos). - This routine was included in PROCESS in January 1992 by - P. C. Shipe. + + Parameters + ---------- + output: + + pfr : + largest PF coil outer radius, m + pfm : + largest PF coil mass, tonne + tfro : + outer radius of TF coil, m + tfri : + inner radius of TF coil, m + tfh : + full height of TF coil, m + tfm : + mass of one TF coil, tonne + n_tf_coils : + number of tf coils + shro : + outer radius of attached shield, m + shri : + inner radius of attached shield, m + shh : + height of attached shield, m + shm : + total mass of attached shield, kg + crr : + outer radius of common cryostat, m + helpow : + total cryogenic load, W + + Returns + ------- + cryv: + volume of cryogenic building, m3 + vrci: + inner volume of reactor building, m3 + rbv: + outer volume of reactor building, m3 + rmbv: + volume of reactor maintenance building, m3 + wsv: + volume of warm shop, m3 + elev: + volume of electrical buildings, m3 """ # Reactor building @@ -173,10 +196,10 @@ def bldgs( # Laydown length (m) layl = max(crr, pfr) - # Diagnoal length (m) + # Diagonal length (m) hy = bmr + buildings_variables.rxcl + sectl + buildings_variables.trcl + layl - # Angle between diagnoal length and floor (m) + # Angle between diagonal length and floor (m) ang = (buildings_variables.wrbi - buildings_variables.trcl - layl) / hy # Cap angle at 1 @@ -383,7 +406,16 @@ def bldgs_sizes(self, output, tf_radial_dim, tf_vertical_dim): some are derived from footprints/volumes based on assessment of other power plants and/or similar facilities. !! - author: R Chapman, UKAEA + + + Parameters + ---------- + output : + + tf_radial_dim : + + tf_vertical_dim : + """ buildings_total_vol = 0.0e0 diff --git a/process/caller.py b/process/caller.py index 7ed29c6687..b7192f9746 100644 --- a/process/caller.py +++ b/process/caller.py @@ -24,7 +24,7 @@ class Caller: """Calls physics and engineering models.""" - def __init__(self, models: Models) -> None: + def __init__(self, models: Models): """Initialise all physics and engineering models. To ensure that, at the start of a run, all physics/engineering @@ -42,12 +42,17 @@ def check_agreement( ) -> bool: """Compare previous and current arrays for agreement within a tolerance. - :param previous: value(s) from previous models evaluation - :type previous: float | np.ndarray - :param current: value(s) from current models evaluation - :type current: float | np.ndarray - :return: whether values agree or not - :rtype: bool + Parameters + ---------- + previous : float | np.ndarray + value(s) from previous models evaluation + current : float | np.ndarray + value(s) from current models evaluation + + Returns + ------- + bool + whether values agree or not """ # Check for same shape: mfile length can change between iterations if isinstance(previous, float) or previous.shape == current.shape: @@ -59,14 +64,23 @@ def call_models(self, xc: np.ndarray, m: int) -> tuple[float, np.ndarray]: Ensure objective function and constraints are idempotent before returning. - :param xc: optimisation parameters - :type xc: np.ndarray - :param m: number of constraints - :type m: int - :raises RuntimeError: if values are non-idempotent after successive - evaluations - :return: objective function and constraints - :rtype: Tuple[float, np.ndarray] + Parameters + ---------- + xc : np.ndarray + optimisation parameters + m : int + number of constraints + + Returns + ------- + Tuple[float, np.ndarray] + objective function and constraints + + Raises + ------ + RuntimeError + if values are non-idempotent after successive + evaluations """ objf_prev = None conf_prev = None @@ -107,7 +121,7 @@ def call_models(self, xc: np.ndarray, m: int) -> tuple[float, np.ndarray]: "converged (don't produce idempotent values)." ) - def call_models_and_write_output(self, xc: np.ndarray, ifail: int) -> None: + def call_models_and_write_output(self, xc: np.ndarray, ifail: int): """Evaluate models until results are idempotent, then write output files. Ensure all outputs in mfile are idempotent before returning, by @@ -115,12 +129,18 @@ def call_models_and_write_output(self, xc: np.ndarray, ifail: int) -> None: optimisation, or in a non-optimising evaluation. Writes OUT.DAT and MFILE.DAT with final results. - :param xc: optimisation parameter - :type xc: np.ndarray - :param ifail: return code of solver - :type ifail: int - :raises RuntimeError: if values are non-idempotent after successive - evaluations + Parameters + ---------- + xc : np.ndarray + optimisation parameter + ifail : int + return code of solver + + Raises + ------ + RuntimeError + if values are non-idempotent after successive + evaluations """ # TODO The only way to ensure idempotence in all outputs is by comparing # mfiles at this stage @@ -214,14 +234,17 @@ def call_models_and_write_output(self, xc: np.ndarray, ifail: int) -> None: OutputFileManager.close_idempotence_files() raise - def _call_models_once(self, xc: np.ndarray) -> None: + def _call_models_once(self, xc: np.ndarray): """Call the physics and engineering models. This method is the principal caller of all the physics and engineering models. Some are Fortran subroutines within modules, others will be methods on Python model objects. - :param xc: Array of optimisation parameters - :type xc: np.array + + Parameters + ---------- + xc : np.array + Array of optimisation parameters """ # Number of active iteration variables nvars = len(xc) @@ -357,13 +380,15 @@ def _call_models_once(self, xc: np.ndarray) -> None: # FISPACT and LOCA model (not used)- removed -def write_output_files(models: Models, ifail: int) -> None: +def write_output_files(models: Models, ifail: int): """Evaluate models and write output files (OUT.DAT and MFILE.DAT). - :param models: physics and engineering models - :type models: Models - :param ifail: solver return code - :type ifail: int + Parameters + ---------- + models : Models + physics and engineering models + ifail : int + solver return code """ n = data_structure.numerics.nvar x = data_structure.numerics.xcm[:n] diff --git a/process/confinement_time.py b/process/confinement_time.py index 28ee76fd54..eeda7ec7e2 100644 --- a/process/confinement_time.py +++ b/process/confinement_time.py @@ -4,46 +4,52 @@ def neo_alcator_confinement_time( dene20: float, rminor: float, rmajor: float, qstar: float ) -> float: - """ - Calculate the Nec-Alcator(NA) OH scaling confinement time + """Calculate the Nec-Alcator(NA) OH scaling confinement time - Parameters: - dene20 (float): Volume averaged electron density in units of 10**20 m**-3 - rminor (float): Plasma minor radius [m] - rmajor (float): Plasma major radius [m] - qstar (float): Equivalent cylindrical edge safety factor + Parameters + ---------- + dene20 : + Volume averaged electron density in units of 10**20 m**-3 + rminor : + Plasma minor radius [m] + rmajor : + Plasma major radius [m] + qstar : + Equivalent cylindrical edge safety factor - Returns: - float: Neo-Alcator confinement time [s] + Returns + ------- + : + float: Neo-Alcator confinement time [s] - Notes: References: - N. A. Uckan, International Atomic Energy Agency, Vienna (Austria)and ITER Physics Group, - "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. - + "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. """ return 0.07e0 * dene20 * rminor * rmajor * rmajor * qstar def mirnov_confinement_time(rminor: float, kappa95: float, pcur: float) -> float: - """ - Calculate the Mirnov scaling (H-mode) confinement time - - Parameters: - hfact (float): H-factor - rminor (float): Plasma minor radius [m] - kappa95 (float): Plasma elongation at 95% flux surface - pcur (float): Plasma current [MA] - - Returns: - float: Mirnov scaling confinement time [s] - - Notes: + """Calculate the Mirnov scaling (H-mode) confinement time + + Parameters + ---------- + rminor : + Plasma minor radius [m] + kappa95 : + Plasma elongation at 95% flux surface + pcur : + Plasma current [MA] + + Returns + ------- + : + float: Mirnov scaling confinement time [s] References: - N. A. Uckan, International Atomic Energy Agency, Vienna (Austria)and ITER Physics Group, - "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. + "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. """ return 0.2e0 * rminor * np.sqrt(kappa95) * pcur @@ -57,26 +63,34 @@ def merezhkin_muhkovatov_confinement_time( afuel: float, ten: float, ) -> float: - """ - Calculate the Merezhkin-Mukhovatov (MM) OH/L-mode scaling confinement time + """Calculate the Merezhkin-Mukhovatov (MM) OH/L-mode scaling confinement time + + Parameters + ---------- + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa95 : + Plasma elongation at 95% flux surface + qstar : + Equivalent cylindrical edge safety factor + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + afuel : + Fuel atomic mass number + ten : + Electron temperature [keV] + + Returns + ------- + : + float: Merezhkin-Mukhovatov confinement time [s] - Parameters: - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa95 (float): Plasma elongation at 95% flux surface - qstar (float): Equivalent cylindrical edge safety factor - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - afuel (float): Fuel atomic mass number - ten (float): Electron temperature [keV] - - Returns: - float: Merezhkin-Mukhovatov confinement time [s] - - Notes: References: - N. A. Uckan, International Atomic Energy Agency, Vienna (Austria)and ITER Physics Group, - "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. + "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. """ return ( 3.5e-3 @@ -97,24 +111,29 @@ def shimomura_confinement_time( kappa95: float, afuel: float, ) -> float: - """ - Calculate the Shimomura (S) optimized H-mode scaling confinement time - - Parameters: - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - kappa95 (float): Plasma elongation at 95% flux surface - afuel (float): Fuel atomic mass number - - Returns: - float: Shimomura confinement time [s] - - Notes: + """Calculate the Shimomura (S) optimized H-mode scaling confinement time + + Parameters + ---------- + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + kappa95 : + Plasma elongation at 95% flux surface + afuel : + Fuel atomic mass number + + Returns + ------- + : + float: Shimomura confinement time [s] References: - N. A. Uckan, International Atomic Energy Agency, Vienna (Austria)and ITER Physics Group, - "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. + "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. """ return ( 0.045e0 @@ -136,30 +155,39 @@ def kaye_goldston_confinement_time( rminor: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Kaye-Goldston (KG) L-mode scaling confinement time - - Parameters: - hfact (float): H-factor - kappa95 (float): Plasma elongation at 95% flux surface - pcur (float): Plasma current [MA] - n20 (float): Line averaged electron density in units of 10**20 m**-3 - rmajor (float): Plasma major radius [m] - afuel (float): Fuel atomic mass number - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - rminor (float): Plasma minor radius [m] - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: Kaye-Goldston confinement time [s] + """Calculate the Kaye-Goldston (KG) L-mode scaling confinement time + + Parameters + ---------- + kappa95 : + Plasma elongation at 95% flux surface + pcur : + Plasma current [MA] + n20 : + Line averaged electron density in units of 10**20 m**-3 + rmajor : + Plasma major radius [m] + afuel : + Fuel atomic mass number + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + rminor : + Plasma minor radius [m] + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: Kaye-Goldston confinement time [s] Notes: - An isotope correction factor (M_i/1.5)^0.5 is added to the original scaling to reflect the fact - that the empirical fits to the data were from experiments with H and D mixture, M_i = 1.5 + that the empirical fits to the data were from experiments with H and D mixture, M_i = 1.5 References: - N. A. Uckan, International Atomic Energy Agency, Vienna (Austria)and ITER Physics Group, - "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. + "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. """ return ( 0.055e0 @@ -182,29 +210,38 @@ def iter_89p_confinement_time( afuel: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the ITER Power scaling - ITER 89-P (L-mode) confinement time - - Parameters: - pcur (float): Plasma current [MA] - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa (float): Plasma elongation - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - afuel (float): Fuel atomic mass number - p_plasma_loss_mw (float): Net Heating power [MW] + """Calculate the ITER Power scaling - ITER 89-P (L-mode) confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa : + Plasma elongation + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + afuel : + Fuel atomic mass number + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: ITER 89-P confinement time [s] - Returns: - float: ITER 89-P confinement time [s] - - Notes: References: - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 - N. A. Uckan, International Atomic Energy Agency, Vienna (Austria)and ITER Physics Group, - "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. + "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. """ return ( 0.048e0 @@ -229,27 +266,34 @@ def iter_89_0_confinement_time( afuel: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the ITER Offset linear scaling - ITER 89-O (L-mode) confinement time - - Parameters: - pcur (float): Plasma current [MA] - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa (float): Plasma elongation - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - afuel (float): Fuel atomic mass number - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: ITER 89-O confinement time [s] - - Notes: + """Calculate the ITER Offset linear scaling - ITER 89-O (L-mode) confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa : + Plasma elongation + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + afuel : + Fuel atomic mass number + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: ITER 89-O confinement time [s] References: - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 - """ term1 = ( 0.04e0 @@ -284,24 +328,34 @@ def rebut_lallia_confinement_time( b_plasma_toroidal_on_axis: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Rebut-Lallia offset linear scaling (L-mode) confinement time - - Parameters: - rminor (float): Plasma minor radius [m] - rmajor (float): Plasma major radius [m] - kappa (float): Plasma elongation at 95% flux surface - afuel (float): Fuel atomic mass number - pcur (float): Plasma current [MA] - zeff (float): Effective charge - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: Rebut-Lallia confinement time [s] + """Calculate the Rebut-Lallia offset linear scaling (L-mode) confinement time + + Parameters + ---------- + rminor : + Plasma minor radius [m] + rmajor : + Plasma major radius [m] + kappa : + Plasma elongation at 95% flux surface + afuel : + Fuel atomic mass number + pcur : + Plasma current [MA] + zeff : + Effective charge + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: Rebut-Lallia confinement time [s] - Notes: References: - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 @@ -328,26 +382,31 @@ def goldston_confinement_time( afuel: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Goldston scaling (L-mode) confinement time - - Parameters: - pcur (float): Plasma current [MA] - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa95 (float): Plasma elongation at 95% flux surface - afuel (float): Fuel atomic mass number - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: Goldston confinement time [s] - - Notes: + """Calculate the Goldston scaling (L-mode) confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa95 : + Plasma elongation at 95% flux surface + afuel : + Fuel atomic mass number + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: Goldston confinement time [s] References: - N. A. Uckan, International Atomic Energy Agency, Vienna (Austria)and ITER Physics Group, "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. - """ return ( 0.037e0 @@ -371,28 +430,37 @@ def t10_confinement_time( zeff: float, pcur: float, ) -> float: - """ - Calculate the T-10 scaling confinement time - - Parameters: - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - rmajor (float): Plasma major radius [m] - qstar (float): Equivalent cylindrical edge safety factor - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - rminor (float): Plasma minor radius [m] - kappa95 (float): Plasma elongation at 95% flux surface - p_plasma_loss_mw (float): Net Heating power [MW] - zeff (float): Effective charge - pcur (float): Plasma current [MA] - - Returns: - float: T-10 confinement time [s] - - Notes: + """Calculate the T-10 scaling confinement time + + Parameters + ---------- + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + rmajor : + Plasma major radius [m] + qstar : + Equivalent cylindrical edge safety factor + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + rminor : + Plasma minor radius [m] + kappa95 : + Plasma elongation at 95% flux surface + p_plasma_loss_mw : + Net Heating power [MW] + zeff : + Effective charge + pcur : + Plasma current [MA] + + Returns + ------- + : + float: T-10 confinement time [s] References: - N. A. Uckan, International Atomic Energy Agency, Vienna (Austria)and ITER Physics Group, - "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. + "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. """ denfac = dnla20 * rmajor * qstar / (1.3e0 * b_plasma_toroidal_on_axis) denfac = min(1.0e0, denfac) @@ -420,29 +488,39 @@ def jaeri_confinement_time( zeff: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the JAERI / Odajima-Shimomura L-mode scaling confinement time - - Parameters: - kappa95 (float): Plasma elongation at 95% flux surface - rminor (float): Plasma minor radius [m] - afuel (float): Fuel atomic mass number - n20 (float): Line averaged electron density in units of 10**20 m**-3 - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - rmajor (float): Plasma major radius [m] - qstar (float): Equivalent cylindrical edge safety factor - zeff (float): Effective charge - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: JAERI confinement time [s] - - Notes: + """Calculate the JAERI / Odajima-Shimomura L-mode scaling confinement time + + Parameters + ---------- + kappa95 : + Plasma elongation at 95% flux surface + rminor : + Plasma minor radius [m] + afuel : + Fuel atomic mass number + n20 : + Line averaged electron density in units of 10**20 m**-3 + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + rmajor : + Plasma major radius [m] + qstar : + Equivalent cylindrical edge safety factor + zeff : + Effective charge + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: JAERI confinement time [s] References: - N. A. Uckan, International Atomic Energy Agency, Vienna (Austria)and ITER Physics Group, - "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. + "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. """ gjaeri = ( zeff**0.4e0 @@ -475,27 +553,36 @@ def kaye_big_confinement_time( afuel: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Kaye-Big scaling confinement time - - Parameters: - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - kappa95 (float): Plasma elongation at 95% flux surface - pcur (float): Plasma current [MA] - n20 (float): Line averaged electron density in units of 10**20 m**-3 - afuel (float): Fuel atomic mass number - p_plasma_loss_mw (float): Net Heating power [MW] + """Calculate the Kaye-Big scaling confinement time + + Parameters + ---------- + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + kappa95 : + Plasma elongation at 95% flux surface + pcur : + Plasma current [MA] + n20 : + Line averaged electron density in units of 10**20 m**-3 + afuel : + Fuel atomic mass number + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: Kaye-Big confinement time [s] - Returns: - float: Kaye-Big confinement time [s] - - Notes: References: - N. A. Uckan, International Atomic Energy Agency, Vienna (Austria)and ITER Physics Group, - "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. + "ITER physics design guidelines: 1989", no. No. 10. Feb. 1990. """ return ( 0.105e0 @@ -520,23 +607,32 @@ def iter_h90_p_confinement_time( afuel: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the ITER H-mode scaling - ITER H90-P confinement time - - Parameters: - pcur (float): Plasma current [MA] - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa (float): Plasma elongation - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - afuel (float): Fuel atomic mass number - p_plasma_loss_mw (float): Net Heating power [MW] + """Calculate the ITER H-mode scaling - ITER H90-P confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa : + Plasma elongation + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + afuel : + Fuel atomic mass number + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: ITER H90-P confinement time [s] - Returns: - float: ITER H90-P confinement time [s] - - Notes: References: - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 @@ -563,22 +659,29 @@ def riedel_l_confinement_time( b_plasma_toroidal_on_axis: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Riedel scaling (L-mode) confinement time - - Parameters: - pcur (float): Plasma current [MA] - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa95 (float): Plasma elongation at 95% flux surface - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: Riedel confinement time [s] - - Notes: + """Calculate the Riedel scaling (L-mode) confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa95 : + Plasma elongation at 95% flux surface + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: Riedel confinement time [s] References: - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 @@ -605,23 +708,31 @@ def christiansen_confinement_time( p_plasma_loss_mw: float, afuel: float, ) -> float: - """ - Calculate the Christiansen et al scaling (L-mode) confinement time - - Parameters: - pcur (float): Plasma current [MA] - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa95 (float): Plasma elongation at 95% flux surface - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - afuel (float): Fuel atomic mass number - - Returns: - float: Christiansen confinement time [s] - - Notes: + """Calculate the Christiansen et al scaling (L-mode) confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa95 : + Plasma elongation at 95% flux surface + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + afuel : + Fuel atomic mass number + + Returns + ------- + : + float: Christiansen confinement time [s] References: - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 @@ -647,26 +758,32 @@ def lackner_gottardi_confinement_time( b_plasma_toroidal_on_axis: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Lackner-Gottardi scaling (L-mode) confinement time - - Parameters: - pcur (float): Plasma current [MA] - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa95 (float): Plasma elongation at 95% flux surface - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: Lackner-Gottardi confinement time [s] - - Notes: + """Calculate the Lackner-Gottardi scaling (L-mode) confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa95 : + Plasma elongation at 95% flux surface + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: Lackner-Gottardi confinement time [s] References: - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 - """ qhat = ( (1.0e0 + kappa95**2) @@ -696,22 +813,30 @@ def neo_kaye_confinement_time( b_plasma_toroidal_on_axis: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Neo-Kaye scaling (L-mode) confinement time + """Calculate the Neo-Kaye scaling (L-mode) confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa95 : + Plasma elongation at 95% flux surface + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: Neo-Kaye confinement time [s] - Parameters: - pcur (float): Plasma current [MA] - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa95 (float): Plasma elongation at 95% flux surface - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: Neo-Kaye confinement time [s] - - Notes: References: - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 @@ -738,23 +863,31 @@ def riedel_h_confinement_time( afuel: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Riedel scaling (H-mode) confinement time - - Parameters: - pcur (float): Plasma current [MA] - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa95 (float): Plasma elongation at 95% flux surface - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - afuel (float): Fuel atomic mass number - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: Riedel H-mode confinement time [s] - - Notes: + """Calculate the Riedel scaling (H-mode) confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa95 : + Plasma elongation at 95% flux surface + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + afuel : + Fuel atomic mass number + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: Riedel H-mode confinement time [s] References: - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 @@ -780,27 +913,32 @@ def iter_h90_p_amended_confinement_time( p_plasma_loss_mw: float, kappa: float, ) -> float: - """ - Calculate the amended ITER H90-P confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - afuel (float): Fuel atomic mass number - rmajor (float): Plasma major radius [m] - p_plasma_loss_mw (float): Net Heating power [MW] - kappa (float): Plasma elongation - - Returns: + """Calculate the amended ITER H90-P confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + afuel : + Fuel atomic mass number + rmajor : + Plasma major radius [m] + p_plasma_loss_mw : + Net Heating power [MW] + kappa : + Plasma elongation + + Returns + ------- + : float: Amended ITER H90-P confinement time [s] - Notes: - - References: - - J. P. Christiansen et al., “Global energy confinement H-mode database for ITER,” - Nuclear Fusion, vol. 32, no. 2, pp. 291-338, Feb. 1992, - doi: https://doi.org/10.1088/0029-5515/32/2/i11. - ‌ + References: + - J. P. Christiansen et al., “Global energy confinement H-mode database for ITER,” + Nuclear Fusion, vol. 32, no. 2, pp. 291-338, Feb. 1992, + doi: https://doi.org/10.1088/0029-5515/32/2/i11. """ return ( 0.082e0 @@ -819,26 +957,31 @@ def sudo_et_al_confinement_time( b_plasma_toroidal_on_axis: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Sudo et al. scaling confinement time - - Parameters: - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: + """Calculate the Sudo et al. scaling confinement time + + Parameters + ---------- + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : float: Sudo et al. confinement time [s] - Notes: - - References: - - S. Sudo et al., “Scalings of energy confinement and density limit in stellarator/heliotron devices,” - Nuclear Fusion, vol. 30, no. 1, pp. 11-21, Jan. 1990, - doi: https://doi.org/10.1088/0029-5515/30/1/002. - ‌""" + References: + - S. Sudo et al., “Scalings of energy confinement and density limit in stellarator/heliotron devices,” + Nuclear Fusion, vol. 30, no. 1, pp. 11-21, Jan. 1990, + doi: https://doi.org/10.1088/0029-5515/30/1/002. + """ return ( 0.17e0 @@ -857,24 +1000,29 @@ def gyro_reduced_bohm_confinement_time( rminor: float, rmajor: float, ) -> float: - """ - Calculate the Gyro-reduced Bohm scaling confinement time - - Parameters: - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rminor (float): Plasma minor radius [m] - rmajor (float): Plasma major radius [m] - - Returns: - float: Gyro-reduced Bohm confinement time [s] - - Notes: + """Calculate the Gyro-reduced Bohm scaling confinement time + + Parameters + ---------- + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rminor : + Plasma minor radius [m] + rmajor : + Plasma major radius [m] + + Returns + ------- + : + float: Gyro-reduced Bohm confinement time [s] References: - Goldston, R. J., H. Biglari, and G. W. Hammett. "E x B/B 2 vs. μ B/B as the Cause of Transport in Tokamaks." - Bull. Am. Phys. Soc 34 (1989): 1964. + Bull. Am. Phys. Soc 34 (1989): 1964. """ return ( 0.25e0 @@ -894,27 +1042,32 @@ def lackner_gottardi_stellarator_confinement_time( p_plasma_loss_mw: float, q: float, ) -> float: - """ - Calculate the Lackner-Gottardi stellarator scaling confinement time - - Parameters: - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - q (float): Edge safety factor - - Returns: + """Calculate the Lackner-Gottardi stellarator scaling confinement time + + Parameters + ---------- + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + q : + Edge safety factor + + Returns + ------- + : float: Lackner-Gottardi stellarator confinement time [s] - Notes: - - References: - - K. Lackner and N. A. O. Gottardi, “Tokamak confinement in relation to plateau scaling,” - Nuclear Fusion, vol. 30, no. 4, pp. 767-770, Apr. 1990, - doi: https://doi.org/10.1088/0029-5515/30/4/018. - ‌ + References: + - K. Lackner and N. A. O. Gottardi, “Tokamak confinement in relation to plateau scaling,” + Nuclear Fusion, vol. 30, no. 4, pp. 767-770, Apr. 1990, + doi: https://doi.org/10.1088/0029-5515/30/4/018. """ return ( 0.17e0 @@ -937,28 +1090,35 @@ def iter_93h_confinement_time( aspect: float, kappa: float, ) -> float: - """ - Calculate the ITER-93H scaling ELM-free confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - afuel (float): Fuel atomic mass number - rmajor (float): Plasma major radius [m] - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - aspect (float): Aspect ratio - kappa (float): Plasma elongation - - Returns: - float: ITER-93H confinement time [s] - - Notes: + """Calculate the ITER-93H scaling ELM-free confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + afuel : + Fuel atomic mass number + rmajor : + Plasma major radius [m] + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + aspect : + Aspect ratio + kappa : + Plasma elongation + + Returns + ------- + : + float: ITER-93H confinement time [s] References: - K. Thomsen et al., “ITER H mode confinement database update,” vol. 34, no. 1, pp. 131-167, Jan. 1994, doi: https://doi.org/10.1088/0029-5515/34/1/i10. - """ return ( 0.036e0 @@ -983,29 +1143,36 @@ def iter_h97p_confinement_time( kappa: float, afuel: float, ) -> float: - """ - Calculate the ELM-free ITER H-mode scaling - ITER H97-P confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - rmajor (float): Plasma major radius [m] - aspect (float): Aspect ratio - kappa (float): Plasma elongation - afuel (float): Fuel atomic mass number - - Returns: + """Calculate the ELM-free ITER H-mode scaling - ITER H97-P confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + rmajor : + Plasma major radius [m] + aspect : + Aspect ratio + kappa : + Plasma elongation + afuel : + Fuel atomic mass number + + Returns + ------- + : float: ITER H97-P confinement time [s] - Notes: - - References: - - I. C. Database and M. W. G. (presented Cordey), “Energy confinement scaling and the extrapolation to ITER,” - Plasma Physics and Controlled Fusion, vol. 39, no. 12B, pp. B115-B127, Dec. 1997, - doi: https://doi.org/10.1088/0741-3335/39/12b/009. - ‌ + References: + - I. C. Database and M. W. G. (presented Cordey), “Energy confinement scaling and the extrapolation to ITER,” + Plasma Physics and Controlled Fusion, vol. 39, no. 12B, pp. B115-B127, Dec. 1997, + doi: https://doi.org/10.1088/0741-3335/39/12b/009. """ return ( 0.031e0 @@ -1030,28 +1197,36 @@ def iter_h97p_elmy_confinement_time( kappa: float, afuel: float, ) -> float: - """ - Calculate the ELMy ITER H-mode scaling - ITER H97-P(y) confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - rmajor (float): Plasma major radius [m] - aspect (float): Aspect ratio - kappa (float): Plasma elongation - afuel (float): Fuel atomic mass number - - Returns: - float: ITER H97-P(y) confinement time [s] - - Notes: + """Calculate the ELMy ITER H-mode scaling - ITER H97-P(y) confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + rmajor : + Plasma major radius [m] + aspect : + Aspect ratio + kappa : + Plasma elongation + afuel : + Fuel atomic mass number + + Returns + ------- + : + float: ITER H97-P(y) confinement time [s] References: - I. C. Database and M. W. G. (presented Cordey), “Energy confinement scaling and the extrapolation to ITER,” - Plasma Physics and Controlled Fusion, vol. 39, no. 12B, pp. B115-B127, Dec. 1997, - doi: https://doi.org/10.1088/0741-3335/39/12b/009. + Plasma Physics and Controlled Fusion, vol. 39, no. 12B, pp. B115-B127, Dec. 1997, + doi: https://doi.org/10.1088/0741-3335/39/12b/009. - International Atomic Energy Agency, Vienna (Austria), "Technical basis for the ITER final design report, cost review and safety analysis (FDR)", no.16. Dec. 1998. @@ -1079,30 +1254,39 @@ def iter_96p_confinement_time( afuel: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the ITER-96P (= ITER-97L) L-mode scaling confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - kappa95 (float): Plasma elongation at 95% flux surface - rmajor (float): Plasma major radius [m] - aspect (float): Aspect ratio - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - afuel (float): Fuel atomic mass number - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: + """Calculate the ITER-96P (= ITER-97L) L-mode scaling confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + kappa95 : + Plasma elongation at 95% flux surface + rmajor : + Plasma major radius [m] + aspect : + Aspect ratio + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + afuel : + Fuel atomic mass number + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : float: ITER-96P confinement time [s] - Notes: - - The thermal energy confinement time is given below + Notes: + - The thermal energy confinement time is given below - References: - - S. B. Kaye et al., “ITER L mode confinement database,” - Nuclear Fusion, vol. 37, no. 9, pp. 1303-1328, Sep. 1997, - doi: https://doi.org/10.1088/0029-5515/37/9/i10. - ‌ + References: + - S. B. Kaye et al., “ITER L mode confinement database,” + Nuclear Fusion, vol. 37, no. 9, pp. 1303-1328, Sep. 1997, + doi: https://doi.org/10.1088/0029-5515/37/9/i10. """ return ( 0.023e0 @@ -1127,26 +1311,33 @@ def valovic_elmy_confinement_time( kappa: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Valovic modified ELMy-H mode scaling confinement time - - Parameters: - hfact (float): H-factor - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - afuel (float): Fuel atomic mass number - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - kappa (float): Plasma elongation - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: Valovic modified ELMy-H mode confinement time [s] - - Notes: - - References: + """Calculate the Valovic modified ELMy-H mode scaling confinement time + + Parameters + ---------- + hfact : + H-factor + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + afuel : + Fuel atomic mass number + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + kappa : + Plasma elongation + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: Valovic modified ELMy-H mode confinement time [s] """ return ( 0.067e0 @@ -1171,23 +1362,31 @@ def kaye_confinement_time( afuel: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Kaye PPPL Workshop April 1998 L-mode scaling confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - kappa (float): Plasma elongation - rmajor (float): Plasma major radius [m] - aspect (float): Aspect ratio - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - afuel (float): Fuel atomic mass number - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: - float: Kaye PPPL Workshop confinement time [s] - - Notes: + """Calculate the Kaye PPPL Workshop April 1998 L-mode scaling confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + kappa : + Plasma elongation + rmajor : + Plasma major radius [m] + aspect : + Aspect ratio + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + afuel : + Fuel atomic mass number + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : + float: Kaye PPPL Workshop confinement time [s] References: - Kaye PPPL Workshop April 1998 @@ -1215,26 +1414,31 @@ def iter_pb98py_confinement_time( aspect: float, afuel: float, ) -> float: - """ - Calculate the ITERH-PB98P(y) ELMy H-mode scaling confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - kappa (float): Plasma elongation - aspect (float): Aspect ratio - afuel (float): Fuel atomic mass number - - Returns: - float: ITERH-PB98P(y) ELMy H-mode confinement time [s] - - Notes: - - References: - + """Calculate the ITERH-PB98P(y) ELMy H-mode scaling confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + kappa : + Plasma separatrix elongation + aspect : + Aspect ratio + afuel : + Fuel atomic mass number + + Returns + ------- + : + float: ITERH-PB98P(y) ELMy H-mode confinement time [s] """ return ( 0.0615e0 @@ -1259,21 +1463,31 @@ def iter_ipb98y_confinement_time( aspect: float, afuel: float, ) -> float: - """ - Calculate the IPB98(y) ELMy H-mode scaling confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - kappa (float): Plasma separatrix elongation - aspect (float): Aspect ratio - afuel (float): Fuel atomic mass number - - Returns: - float: IPB98(y) ELMy H-mode confinement time [s] + """Calculate the IPB98(y) ELMy H-mode scaling confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + kappa : + IPB sprcific plasma separatrix elongation + aspect : + Aspect ratio + afuel : + Fuel atomic mass number + + Returns + ------- + : + float: IPB98(y) ELMy H-mode confinement time [s] Notes: - Unlike the other IPB98 scaling laws, the IPB98(y) scaling law uses the true separatrix elongation. @@ -1284,8 +1498,7 @@ def iter_ipb98y_confinement_time( Nuclear Fusion, vol. 39, no. 12, pp. 2175-2249, Dec. 1999, doi: https://doi.org/10.1088/0029-5515/39/12/302. - None Otto Kardaun, N. K. Thomsen, and None Alexander Chudnovskiy, “Corrections to a sequence of papers in Nuclear Fusion,” - Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. - + Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. """ return ( 0.0365e0 @@ -1310,21 +1523,31 @@ def iter_ipb98y1_confinement_time( aspect: float, afuel: float, ) -> float: - """ - Calculate the IPB98(y,1) ELMy H-mode scaling confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - kappa_ipb (float): IPB sprcific plasma separatrix elongation - aspect (float): Aspect ratio - afuel (float): Fuel atomic mass number - - Returns: - float: IPB98(y,1) ELMy H-mode confinement time [s] + """Calculate the IPB98(y,1) ELMy H-mode scaling confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + kappa_ipb : + IPB specific plasma separatrix elongation + aspect : + Aspect ratio + afuel : + Fuel atomic mass number + + Returns + ------- + : + float: IPB98(y,1) ELMy H-mode confinement time [s] Notes: - See correction paper below for more information about the re-definition of the elongation used. @@ -1334,8 +1557,7 @@ def iter_ipb98y1_confinement_time( Nuclear Fusion, vol. 39, no. 12, pp. 2175-2249, Dec. 1999, doi: https://doi.org/10.1088/0029-5515/39/12/302. - None Otto Kardaun, N. K. Thomsen, and None Alexander Chudnovskiy, “Corrections to a sequence of papers in Nuclear Fusion,” - Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. - + Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. """ return ( 0.0503e0 @@ -1360,21 +1582,31 @@ def iter_ipb98y2_confinement_time( aspect: float, afuel: float, ) -> float: - """ - Calculate the IPB98(y,2) ELMy H-mode scaling confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - kappa_ipb (float): IPB specific plasma separatrix elongation - aspect (float): Aspect ratio - afuel (float): Fuel atomic mass number - - Returns: - float: IPB98(y,2) ELMy H-mode confinement time [s] + """Calculate the IPB98(y,2) ELMy H-mode scaling confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + kappa_ipb : + IPB specific plasma separatrix elongation + aspect : + Aspect ratio + afuel : + Fuel atomic mass number + + Returns + ------- + : + float: IPB98(y,2) ELMy H-mode confinement time [s] Notes: - See correction paper below for more information about the re-definition of the elongation used. @@ -1384,7 +1616,7 @@ def iter_ipb98y2_confinement_time( Nuclear Fusion, vol. 39, no. 12, pp. 2175-2249, Dec. 1999, doi: https://doi.org/10.1088/0029-5515/39/12/302. - None Otto Kardaun, N. K. Thomsen, and None Alexander Chudnovskiy, “Corrections to a sequence of papers in Nuclear Fusion,” - Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. + Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. """ return ( 0.0562e0 @@ -1409,21 +1641,31 @@ def iter_ipb98y3_confinement_time( aspect: float, afuel: float, ) -> float: - """ - Calculate the IPB98(y,3) ELMy H-mode scaling confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - kappa_ipb (float): IPB specific plasma separatrix elongation - aspect (float): Aspect ratio - afuel (float): Fuel atomic mass number - - Returns: - float: IPB98(y,3) ELMy H-mode confinement time [s] + """Calculate the IPB98(y,3) ELMy H-mode scaling confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + kappa_ipb : + IPB specific plasma separatrix elongation + aspect : + Aspect ratio + afuel : + Fuel atomic mass number + + Returns + ------- + : + float: IPB98(y,3) ELMy H-mode confinement time [s] Notes: - See correction paper below for more information about the re-definition of the elongation used. @@ -1433,7 +1675,7 @@ def iter_ipb98y3_confinement_time( Nuclear Fusion, vol. 39, no. 12, pp. 2175-2249, Dec. 1999, doi: https://doi.org/10.1088/0029-5515/39/12/302. - None Otto Kardaun, N. K. Thomsen, and None Alexander Chudnovskiy, “Corrections to a sequence of papers in Nuclear Fusion,” - Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. + Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. """ return ( 0.0564e0 @@ -1458,21 +1700,31 @@ def iter_ipb98y4_confinement_time( aspect: float, afuel: float, ) -> float: - """ - Calculate the IPB98(y,4) ELMy H-mode scaling confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - kappa_ipb (float): IPB specific plasma separatrix elongation - aspect (float): Aspect ratio - afuel (float): Fuel atomic mass number - - Returns: - float: IPB98(y,4) ELMy H-mode confinement time [s] + """Calculate the IPB98(y,4) ELMy H-mode scaling confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + kappa_ipb : + IPB specific plasma separatrix elongation + aspect : + Aspect ratio + afuel : + Fuel atomic mass number + + Returns + ------- + : + float: IPB98(y,4) ELMy H-mode confinement time [s] Notes: - See correction paper below for more information about the re-definition of the elongation used. @@ -1482,7 +1734,7 @@ def iter_ipb98y4_confinement_time( Nuclear Fusion, vol. 39, no. 12, pp. 2175-2249, Dec. 1999, doi: https://doi.org/10.1088/0029-5515/39/12/302. - None Otto Kardaun, N. K. Thomsen, and None Alexander Chudnovskiy, “Corrections to a sequence of papers in Nuclear Fusion,” - Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. + Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. """ return ( 0.0587e0 @@ -1505,26 +1757,31 @@ def iss95_stellarator_confinement_time( p_plasma_loss_mw: float, iotabar: float, ) -> float: - """ - Calculate the ISS95 stellarator scaling confinement time - - Parameters: - rminor (float): Plasma minor radius [m] - rmajor (float): Plasma major radius [m] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - iotabar (float): Rotational transform - - Returns: + """Calculate the ISS95 stellarator scaling confinement time + + Parameters + ---------- + rminor : + Plasma minor radius [m] + rmajor : + Plasma major radius [m] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + iotabar : + Rotational transform + + Returns + ------- + : float: ISS95 stellarator confinement time [s] - Notes: - - References: - - U. Stroth et al., “Energy confinement scaling from the international stellarator database,” - vol. 36, no. 8, pp. 1063-1077, Aug. 1996, doi: https://doi.org/10.1088/0029-5515/36/8/i11. - ‌ + References: + - U. Stroth et al., “Energy confinement scaling from the international stellarator database,” + vol. 36, no. 8, pp. 1063-1077, Aug. 1996, doi: https://doi.org/10.1088/0029-5515/36/8/i11. """ return ( 0.079e0 @@ -1545,26 +1802,31 @@ def iss04_stellarator_confinement_time( p_plasma_loss_mw: float, iotabar: float, ) -> float: - """ - Calculate the ISS04 stellarator scaling confinement time - - Parameters: - rminor (float): Plasma minor radius [m] - rmajor (float): Plasma major radius [m] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - iotabar (float): Rotational transform - - Returns: + """Calculate the ISS04 stellarator scaling confinement time + + Parameters + ---------- + rminor : + Plasma minor radius [m] + rmajor : + Plasma major radius [m] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + iotabar : + Rotational transform + + Returns + ------- + : float: ISS04 stellarator confinement time [s] - Notes: - - References: - - H. Yamada et al., “Characterization of energy confinement in net-current free plasmas using the extended International Stellarator Database,” - vol. 45, no. 12, pp. 1684-1693, Nov. 2005, doi: https://doi.org/10.1088/0029-5515/45/12/024. - ‌ + References: + - H. Yamada et al., “Characterization of energy confinement in net-current free plasmas using the extended International Stellarator Database,” + vol. 45, no. 12, pp. 1684-1693, Nov. 2005, doi: https://doi.org/10.1088/0029-5515/45/12/024. """ return ( 0.134e0 @@ -1587,29 +1849,36 @@ def ds03_confinement_time( aspect: float, afuel: float, ) -> float: - """ - Calculate the DS03 beta-independent H-mode scaling confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - kappa95 (float): Plasma elongation at 95% flux surface - aspect (float): Aspect ratio - afuel (float): Fuel atomic mass number - - Returns: + """Calculate the DS03 beta-independent H-mode scaling confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + kappa95 : + Plasma elongation at 95% flux surface + aspect : + Aspect ratio + afuel : + Fuel atomic mass number + + Returns + ------- + : float: DS03 beta-independent H-mode confinement time [s] - Notes: - - References: - - T. C. Luce, C. C. Petty, and J. G. Cordey, “Application of dimensionless parameter scaling techniques to the design and interpretation of magnetic fusion experiments,” - Plasma Physics and Controlled Fusion, vol. 50, no. 4, p. 043001, Mar. 2008, - doi: https://doi.org/10.1088/0741-3335/50/4/043001. - ‌ + References: + - T. C. Luce, C. C. Petty, and J. G. Cordey, “Application of dimensionless parameter scaling techniques to the design and interpretation of magnetic fusion experiments,” + Plasma Physics and Controlled Fusion, vol. 50, no. 4, p. 043001, Mar. 2008, + doi: https://doi.org/10.1088/0741-3335/50/4/043001. """ return ( 0.028e0 @@ -1632,30 +1901,37 @@ def murari_confinement_time( b_plasma_toroidal_on_axis: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Murari H-mode energy confinement scaling time - - Parameters: - pcur (float): Plasma current [MA] - rmajor (float): Plasma major radius [m] - kappa_ipb (float): IPB specific plasma separatrix elongation - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: + """Calculate the Murari H-mode energy confinement scaling time + + Parameters + ---------- + pcur : + Plasma current [MA] + rmajor : + Plasma major radius [m] + kappa_ipb : + IPB specific plasma separatrix elongation + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : float: Murari confinement time [s] - Notes: - - This scaling uses the IPB defintiion of elongation, see reference for more information. + Notes: + - This scaling uses the IPB defintiion of elongation, see reference for more information. - References: - - A. Murari, E. Peluso, Michela Gelfusa, I. Lupelli, and P. Gaudio, “A new approach to the formulation and validation of scaling expressions for plasma confinement in tokamaks,” - Nuclear Fusion, vol. 55, no. 7, pp. 073009-073009, Jun. 2015, doi: https://doi.org/10.1088/0029-5515/55/7/073009. + References: + - A. Murari, E. Peluso, Michela Gelfusa, I. Lupelli, and P. Gaudio, “A new approach to the formulation and validation of scaling expressions for plasma confinement in tokamaks,” + Nuclear Fusion, vol. 55, no. 7, pp. 073009-073009, Jun. 2015, doi: https://doi.org/10.1088/0029-5515/55/7/073009. - - None Otto Kardaun, N. K. Thomsen, and None Alexander Chudnovskiy, “Corrections to a sequence of papers in Nuclear Fusion,” - Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. - ‌ + - None Otto Kardaun, N. K. Thomsen, and None Alexander Chudnovskiy, “Corrections to a sequence of papers in Nuclear Fusion,” + Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. """ return ( 0.0367 @@ -1679,31 +1955,39 @@ def petty08_confinement_time( kappa_ipb: float, aspect: float, ) -> float: - """ - Calculate the beta independent dimensionless Petty08 confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - kappa_ipb (float): IPB specific plasma separatrix elongation - aspect (float): Aspect ratio - - Returns: + """Calculate the beta independent dimensionless Petty08 confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + kappa_ipb : + IPB specific plasma separatrix elongation + aspect : + Aspect ratio + + Returns + ------- + : float: Petty08 confinement time [s] - Notes: - - This scaling uses the IPB defintiion of elongation, see reference for more information. + Notes: + - This scaling uses the IPB defintiion of elongation, see reference for more information. - References: - - C. C. Petty, “Sizing up plasmas using dimensionless parameters,” - Physics of Plasmas, vol. 15, no. 8, Aug. 2008, doi: https://doi.org/10.1063/1.2961043. + References: + - C. C. Petty, “Sizing up plasmas using dimensionless parameters,” + Physics of Plasmas, vol. 15, no. 8, Aug. 2008, doi: https://doi.org/10.1063/1.2961043. - - None Otto Kardaun, N. K. Thomsen, and None Alexander Chudnovskiy, “Corrections to a sequence of papers in Nuclear Fusion,” - Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. - ‌ + - None Otto Kardaun, N. K. Thomsen, and None Alexander Chudnovskiy, “Corrections to a sequence of papers in Nuclear Fusion,” + Nuclear Fusion, vol. 48, no. 9, pp. 099801-099801, Aug. 2008, doi: https://doi.org/10.1088/0029-5515/48/9/099801. """ return ( 0.052e0 @@ -1730,32 +2014,42 @@ def lang_high_density_confinement_time( afuel: float, kappa_ipb: float, ) -> float: - """ - Calculate the high density relevant confinement time - - Parameters: - plasma_current (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - nd_plasma_electron_line (float): Line averaged electron density [m**-3] - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - rminor (float): Plasma minor radius [m] - q (float): Safety factor - qstar (float): Equivalent cylindrical edge safety factor - aspect (float): Aspect ratio - afuel (float): Fuel atomic mass number - kappa_ipb (float): Plasma elongation at 95% flux surface - - Returns: + """Calculate the high density relevant confinement time + + Parameters + ---------- + plasma_current : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + nd_plasma_electron_line : + Line averaged electron density [m**-3] + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + rminor : + Plasma minor radius [m] + q : + Safety factor + qstar : + Equivalent cylindrical edge safety factor + aspect : + Aspect ratio + afuel : + Fuel atomic mass number + kappa_ipb : + Plasma elongation at 95% flux surface + + Returns + ------- + : float: High density relevant confinement time [s] - Notes: - - References: - - P. T. Lang, C. Angioni, R. M. M. Dermott, R. Fischer, and H. Zohm, “Pellet Induced High Density Phases during ELM Suppression in ASDEX Upgrade,” - 24th IAEA Conference Fusion Energy, 2012, Oct. 2012, - Available: https://www.researchgate.net/publication/274456104_Pellet_Induced_High_Density_Phases_during_ELM_Suppression_in_ASDEX_Upgrade - ‌ + References: + - P. T. Lang, C. Angioni, R. M. M. Dermott, R. Fischer, and H. Zohm, “Pellet Induced High Density Phases during ELM Suppression in ASDEX Upgrade,” + 24th IAEA Conference Fusion Energy, 2012, Oct. 2012, + Available: https://www.researchgate.net/publication/274456104_Pellet_Induced_High_Density_Phases_during_ELM_Suppression_in_ASDEX_Upgrade """ qratio = q / qstar n_gw = 1.0e14 * plasma_current / (np.pi * rminor * rminor) @@ -1782,24 +2076,27 @@ def hubbard_nominal_confinement_time( dnla20: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Hubbard 2017 I-mode confinement time scaling - nominal - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: + """Calculate the Hubbard 2017 I-mode confinement time scaling - nominal + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : float: Hubbard confinement time [s] - Notes: - - References: - - A. E. Hubbard et al., “Physics and performance of the I-mode regime over an expanded operating space on Alcator C-Mod,” - Nuclear Fusion, vol. 57, no. 12, p. 126039, Oct. 2017, doi: https://doi.org/10.1088/1741-4326/aa8570. - ‌ + References: + - A. E. Hubbard et al., “Physics and performance of the I-mode regime over an expanded operating space on Alcator C-Mod,” + Nuclear Fusion, vol. 57, no. 12, p. 126039, Oct. 2017, doi: https://doi.org/10.1088/1741-4326/aa8570. """ return ( 0.014e0 @@ -1816,24 +2113,27 @@ def hubbard_lower_confinement_time( dnla20: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Hubbard 2017 I-mode confinement time scaling - lower - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: + """Calculate the Hubbard 2017 I-mode confinement time scaling - lower + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : float: Hubbard confinement time [s] - Notes: - - References: - - A. E. Hubbard et al., “Physics and performance of the I-mode regime over an expanded operating space on Alcator C-Mod,” - Nuclear Fusion, vol. 57, no. 12, p. 126039, Oct. 2017, doi: https://doi.org/10.1088/1741-4326/aa8570. - ‌ + References: + - A. E. Hubbard et al., “Physics and performance of the I-mode regime over an expanded operating space on Alcator C-Mod,” + Nuclear Fusion, vol. 57, no. 12, p. 126039, Oct. 2017, doi: https://doi.org/10.1088/1741-4326/aa8570. """ return ( 0.014e0 @@ -1850,24 +2150,27 @@ def hubbard_upper_confinement_time( dnla20: float, p_plasma_loss_mw: float, ) -> float: - """ - Calculate the Hubbard 2017 I-mode confinement time scaling - upper - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - - Returns: + """Calculate the Hubbard 2017 I-mode confinement time scaling - upper + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + + Returns + ------- + : float: Hubbard confinement time [s] - Notes: - - References: - - A. E. Hubbard et al., “Physics and performance of the I-mode regime over an expanded operating space on Alcator C-Mod,” - Nuclear Fusion, vol. 57, no. 12, p. 126039, Oct. 2017, doi: https://doi.org/10.1088/1741-4326/aa8570. - ‌ + References: + - A. E. Hubbard et al., “Physics and performance of the I-mode regime over an expanded operating space on Alcator C-Mod,” + Nuclear Fusion, vol. 57, no. 12, p. 126039, Oct. 2017, doi: https://doi.org/10.1088/1741-4326/aa8570. """ return ( 0.014e0 @@ -1888,35 +2191,43 @@ def menard_nstx_confinement_time( aspect: float, afuel: float, ) -> float: - """ - Calculate the Menard NSTX ELMy H-mode scaling confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - kappa_ipb (float): IPB specific plasma separatrix elongation - aspect (float): Aspect ratio - afuel (float): Fuel atomic mass number - - Returns: + """Calculate the Menard NSTX ELMy H-mode scaling confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + kappa_ipb : + IPB specific plasma separatrix elongation + aspect : + Aspect ratio + afuel : + Fuel atomic mass number + + Returns + ------- + : float: Menard NSTX ELMy H-mode confinement time [s] - Notes: - - "The leading NSTX confinement scaling coefficient is chosen such that the ITER and ST energy confinement times are - identical for a reference NSTX scenario" - - Assumes IPB98(y,2) exponents are applicable where the ST exponents are not yet determined, i.e. - the species mass, major radius, inverse aspect ratio and elongation. Hence here we use the IPB98(y,2) definition - of elongation. - - References: - - J. E. Menard, “Compact steady-state tokamak performance dependence on magnet and core physics limits,” - Philosophical Transactions of the Royal Society A, vol. 377, no. 2141, pp. 20170440-20170440, Feb. 2019, - doi: https://doi.org/10.1098/rsta.2017.0440. - ‌ + Notes: + - "The leading NSTX confinement scaling coefficient is chosen such that the ITER and ST energy confinement times are + identical for a reference NSTX scenario" + - Assumes IPB98(y,2) exponents are applicable where the ST exponents are not yet determined, i.e. + the species mass, major radius, inverse aspect ratio and elongation. Hence here we use the IPB98(y,2) definition + of elongation. + References: + - J. E. Menard, “Compact steady-state tokamak performance dependence on magnet and core physics limits,” + Philosophical Transactions of the Royal Society A, vol. 377, no. 2141, pp. 20170440-20170440, Feb. 2019, + doi: https://doi.org/10.1098/rsta.2017.0440. """ return ( 0.095e0 @@ -1941,30 +2252,39 @@ def menard_nstx_petty08_hybrid_confinement_time( aspect: float, afuel: float, ) -> float: - """ - Calculate the Menard NSTX-Petty hybrid confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Line averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - kappa_ipb (float): IPB specific plasma separatrix elongation - aspect (float): Aspect ratio - afuel (float): Fuel atomic mass number - - Returns: - float: Menard NSTX-Petty hybrid confinement time [s] + """Calculate the Menard NSTX-Petty hybrid confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Line averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + kappa_ipb : + IPB specific plasma separatrix elongation + aspect : + Aspect ratio + afuel : + Fuel atomic mass number + + Returns + ------- + : + float: Menard NSTX-Petty hybrid confinement time [s] Notes: - Assuming a linear interpolation in (1/aspect) between the two scalings References: - J. E. Menard, “Compact steady-state tokamak performance dependence on magnet and core physics limits,” - Philosophical Transactions of the Royal Society A, vol. 377, no. 2141, pp. 20170440-20170440, Feb. 2019, - doi: https://doi.org/10.1098/rsta.2017.0440. - ‌ + Philosophical Transactions of the Royal Society A, vol. 377, no. 2141, pp. 20170440-20170440, Feb. 2019, + doi: https://doi.org/10.1098/rsta.2017.0440. """ # Equivalent to A > 2.5, use Petty scaling if (1.0e0 / aspect) <= 0.4e0: @@ -2021,26 +2341,30 @@ def nstx_gyro_bohm_confinement_time( rmajor: float, dnla20: float, ) -> float: - """ - Calculate the NSTX gyro-Bohm confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Net Heating power [MW] - rmajor (float): Plasma major radius [m] - dnla20 (float): Line averaged electron density in units of 10**20 m**-3 - - Returns: + """Calculate the NSTX gyro-Bohm confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Net Heating power [MW] + rmajor : + Plasma major radius [m] + dnla20 : + Line averaged electron density in units of 10**20 m**-3 + + Returns + ------- + : float: NSTX gyro-Bohm confinement time [s] - Notes: - - References: - - P. F. Buxton, L. Connor, A. E. Costley, Mikhail Gryaznevich, and S. McNamara, - “On the energy confinement time in spherical tokamaks: implications for the design of pilot plants and fusion reactors,” - vol. 61, no. 3, pp. 035006-035006, Jan. 2019, doi: https://doi.org/10.1088/1361-6587/aaf7e5. - ‌ + References: + - P. F. Buxton, L. Connor, A. E. Costley, Mikhail Gryaznevich, and S. McNamara, + “On the energy confinement time in spherical tokamaks: implications for the design of pilot plants and fusion reactors,” + vol. 61, no. 3, pp. 035006-035006, Jan. 2019, doi: https://doi.org/10.1088/1361-6587/aaf7e5. """ return ( 0.21e0 @@ -2063,22 +2387,33 @@ def itpa20_confinement_time( eps: float, aion: float, ) -> float: - """ - Calculate the ITPA20 Issue #3164 confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - dnla19 (float): Central line-averaged electron density in units of 10**19 m**-3 - p_plasma_loss_mw (float): Thermal power lost due to transport through the LCFS [MW] - rmajor (float): Plasma major radius [m] - triang (float): Triangularity - kappa_ipb (float): IPB specific plasma separatrix elongation - eps (float): Inverse aspect ratio - aion (float): Average mass of all ions (amu) - - Returns: - float: ITPA20 confinement time [s] + """Calculate the ITPA20 Issue #3164 confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + dnla19 : + Central line-averaged electron density in units of 10**19 m**-3 + p_plasma_loss_mw : + Thermal power lost due to transport through the LCFS [MW] + rmajor : + Plasma major radius [m] + triang : + Triangularity + kappa_ipb : + IPB specific plasma separatrix elongation + eps : + Inverse aspect ratio + aion : + Average mass of all ions (amu) + + Returns + ------- + : + float: ITPA20 confinement time [s] Notes: - Mass term is the effective mass of the plasma, so we assume the total ion mass here @@ -2086,7 +2421,7 @@ def itpa20_confinement_time( References: - G. Verdoolaege et al., “The updated ITPA global H-mode confinement database: description and analysis,” - Nuclear Fusion, vol. 61, no. 7, pp. 076006-076006, Jan. 2021, doi: https://doi.org/10.1088/1741-4326/abdb91. + Nuclear Fusion, vol. 61, no. 7, pp. 076006-076006, Jan. 2021, doi: https://doi.org/10.1088/1741-4326/abdb91. """ return ( 0.053 @@ -2112,21 +2447,31 @@ def itpa20_il_confinement_time( triang: float, kappa_ipb: float, ) -> float: - """ - Calculate the ITPA20-IL Issue #1852 confinement time - - Parameters: - pcur (float): Plasma current [MA] - b_plasma_toroidal_on_axis (float): Toroidal magnetic field [T] - p_plasma_loss_mw (float): Thermal power lost due to transport through the LCFS [MW] - dnla19 (float): Central line-averaged electron density in units of 10**19 m**-3 - aion (float): Average mass of all ions (amu) - rmajor (float): Plasma major radius [m] - triang (float): Triangularity - kappa_ipb (float): IPB specific plasma separatrix elongation - - Returns: - float: ITPA20-IL confinement time [s] + """Calculate the ITPA20-IL Issue #1852 confinement time + + Parameters + ---------- + pcur : + Plasma current [MA] + b_plasma_toroidal_on_axis : + Toroidal magnetic field [T] + p_plasma_loss_mw : + Thermal power lost due to transport through the LCFS [MW] + dnla19 : + Central line-averaged electron density in units of 10**19 m**-3 + aion : + Average mass of all ions (amu) + rmajor : + Plasma major radius [m] + triang : + Triangularity + kappa_ipb : + IPB specific plasma separatrix elongation + + Returns + ------- + : + float: ITPA20-IL confinement time [s] Notes: - Mass term is the effective mass of the plasma, so we assume the total ion mass here diff --git a/process/constraints.py b/process/constraints.py index 786f9e48d3..2c6abf3b69 100644 --- a/process/constraints.py +++ b/process/constraints.py @@ -74,12 +74,15 @@ def register_constraint( The decorator should wrap a function with no argument which returns a ConstraintResult. - :param name: the name of the constraint and how it can be indexed from the registry - :type name: Hashable - :param units: the units of the constraint written to the output files - :type units: str - :param symbol: the symbol of the constraint written to the output files - :type symbol: str + Parameters + ---------- + name : Hashable + the name of the constraint and how it can be indexed from the registry + units : str + the units of the constraint written to the output files + symbol : str + the symbol of the constraint written to the output files + """ def wrapper(func: Callable[[], ConstraintResult]): @@ -98,20 +101,31 @@ def get_constraint(cls, name: Hashable): """Retrieves a constraint registration from the registry given its name. Returns None if no constraint with the name exists. - :param name: the name of the constraint - :type name: Hashable - :returns: the constraint registration object - :rtype: ConstraintRegistration | None + Parameters + ---------- + name : Hashable + the name of the constraint + + Returns + ------- + ConstraintRegistration | None + the constraint registration object """ return cls._constraint_registry.get(name) @classmethod def evaluate_constraint(cls, name: Hashable): """Evalutes a constraint with a given name. - :param name: the name of the constraint - :type name: Hashable - :returns: the result of evaluating the constraint - :rtype: ConstraintResult | None + + Parameters + ---------- + name : Hashable + the name of the constraint + + Returns + ------- + ConstraintResult | None + the result of evaluating the constraint """ registration = cls.get_constraint(name) @@ -125,8 +139,6 @@ def evaluate_constraint(cls, name: Hashable): def constraint_equation_1(): """Relationship between beta, temperature (keV) and density - author: J Morris - beta_total_vol_avg: total plasma beta beta_{ft}: fast alpha beta component beta_{NBI}: neutral beam beta component @@ -167,7 +179,7 @@ def constraint_equation_1(): @ConstraintManager.register_constraint(2, "MW/m3", "=") def constraint_equation_2(): - """author: J. Morris + """ i_rad_loss: switch for radiation loss term usage in power balance (see User Guide): - 0 total power lost is scaling power plus radiation (needed for i_plasma_pedestal=2,3) @@ -297,7 +309,6 @@ def constraint_equation_3(): @ConstraintManager.register_constraint(4, "MW/m3", "=") def constraint_equation_4(): """Global power balance equation for electrons - author: P B Lloyd, CCFE, Culham Science Centre i_rad_loss: switch for radiation loss term usage in power balance - 0 total power lost is scaling power plus radiation (needed for i_plasma_pedestal=2,3) @@ -353,7 +364,6 @@ def constraint_equation_4(): @ConstraintManager.register_constraint(5, "/m3", "<=") def constraint_equation_5(): """Equation for density upper limit - author: P B Lloyd, CCFE, Culham Science Centre fdene: density limit scale nd_plasma_electrons_vol_avg: electron density (/m3) @@ -401,7 +411,6 @@ def constraint_equation_5(): @ConstraintManager.register_constraint(6, "", "<=") def constraint_equation_6(): """Equation for epsilon beta-poloidal upper limit - author: P B Lloyd, CCFE, Culham Science Centre beta_poloidal_eps_max: maximum (eps*beta_poloidal) eps: inverse aspect ratio @@ -492,7 +501,6 @@ def constraint_equation_9(): @ConstraintManager.register_constraint(11, "m", "=") def constraint_equation_11(): """Equation for radial build - author: P B Lloyd, CCFE, Culham Science Centre rbld: sum of thicknesses to the major radius (m) rmajor: plasma major radius (m) @@ -511,7 +519,6 @@ def constraint_equation_11(): @ConstraintManager.register_constraint(12, "V.sec", ">=") def constraint_equation_12(): """Equation for volt-second capability lower limit - author: P B Lloyd, CCFE, Culham Science Centre vs_plasma_total_required: total V-s needed (Wb) vs_plasma_total_required (lower limit) is positive; vs_cs_pf_total_pulse (available) is negative @@ -535,8 +542,6 @@ def constraint_equation_12(): def constraint_equation_13(): """Equation for burn time lower limit - author: P B Lloyd, CCFE, Culham Science Centre - t_plant_pulse_burn: burn time (s) (calculated if i_pulsed_plant=1) t_burn_min: minimum burn time (s) """ @@ -553,7 +558,6 @@ def constraint_equation_13(): @ConstraintManager.register_constraint(14, "", "=") def constraint_equation_14(): """Equation to fix number of NBI decay lengths to plasma centre - author: P B Lloyd, CCFE, Culham Science Centre n_beam_decay_lengths_core: neutral beam e-decay lengths to plasma centre n_beam_decay_lengths_core_required: permitted neutral beam e-decay lengths to plasma centre @@ -574,7 +578,6 @@ def constraint_equation_14(): @ConstraintManager.register_constraint(15, "MW", ">=") def constraint_equation_15(): """Equation for L-H power threshold limit to enforce H-mode - author: P B Lloyd, CCFE, Culham Science Centre f_h_mode_margin: a margin on the constraint p_l_h_threshold_mw: L-H mode power threshold (MW) @@ -603,7 +606,6 @@ def constraint_equation_15(): @ConstraintManager.register_constraint(16, "MW", ">=") def constraint_equation_16(): """Equation for net electric power lower limit - author: P B Lloyd, CCFE, Culham Science Centre p_plant_electric_net_mw: net electric power (MW) p_plant_electric_net_required_mw: required net electric power (MW) @@ -621,7 +623,6 @@ def constraint_equation_16(): @ConstraintManager.register_constraint(17, "MW/m3", "<=") def constraint_equation_17(): """Equation for radiation power upper limit - author: P B Lloyd, CCFE, Culham Science Centre f_p_alpha_plasma_deposited: fraction of alpha power deposited in plasma p_hcd_injected_total_mw: total auxiliary injected power (MW) @@ -660,7 +661,6 @@ def constraint_equation_17(): @ConstraintManager.register_constraint(18, "MW/m2", "<=") def constraint_equation_18(): """Equation for divertor heat load upper limit - author: P B Lloyd, CCFE, Culham Science Centre pflux_div_heat_load_max_mw: heat load limit (MW/m2) pflux_div_heat_load_mw: divertor heat load (MW/m2) @@ -680,7 +680,6 @@ def constraint_equation_18(): @ConstraintManager.register_constraint(19, "MVA", "<=") def constraint_equation_19(): """Equation for MVA (power) upper limit: resistive TF coil set - author: P B Lloyd, CCFE, Culham Science Centre p_cp_resistive_mw: peak resistive TF coil inboard leg power (total) (MW) p_tf_leg_resistive_mw: TF coil outboard leg resistive power (total) (MW) @@ -700,7 +699,6 @@ def constraint_equation_19(): @ConstraintManager.register_constraint(20, "m", "<=") def constraint_equation_20(): """Equation for neutral beam tangency radius upper limit - author: P B Lloyd, CCFE, Culham Science Centre radius_beam_tangency_max: maximum tangency radius for centreline of beam (m) radius_beam_tangency: neutral beam centreline tangency radius (m) @@ -720,7 +718,6 @@ def constraint_equation_20(): @ConstraintManager.register_constraint(21, "", ">=") def constraint_equation_21(): """Equation for minor radius lower limit - author: P B Lloyd, CCFE, Culham Science Centre rminor: plasma minor radius (m) aplasmin: minimum minor radius (m) @@ -768,7 +765,6 @@ def constraint_equation_22(): @ConstraintManager.register_constraint(23, "m", "<=") def constraint_equation_23(): """Equation for conducting shell radius / rminor upper limit - author: P B Lloyd, CCFE, Culham Science Centre rminor: plasma minor radius (m) dr_fw_plasma_gap_outboard: gap between plasma and first wall, outboard side (m) @@ -804,7 +800,6 @@ def constraint_equation_23(): @ConstraintManager.register_constraint(24, "", "<=") def constraint_equation_24(): """Equation for beta upper limit - author: P B Lloyd, CCFE, Culham Science Centre i_beta_component: switch for beta limit scaling (constraint equation 24): - 0 apply limit to total beta; @@ -886,7 +881,6 @@ def constraint_equation_24(): @ConstraintManager.register_constraint(25, "T", "<=") def constraint_equation_25(): """Equation for peak toroidal field upper limit - author: P B Lloyd, CCFE, Culham Science Centre b_tf_inboard_max: maximum peak toroidal field (T) b_tf_inboard_peak_symmetric: mean peak field at TF coil (T) @@ -906,7 +900,6 @@ def constraint_equation_25(): @ConstraintManager.register_constraint(26, "A/m2", "<=") def constraint_equation_26(): """Equation for Central Solenoid current density upper limit at EOF - author: P B Lloyd, CCFE, Culham Science Centre fjohc: margin for central solenoid current at end-of-flattop j_cs_critical_flat_top_end: allowable central solenoid current density at end of flat-top (A/m2) @@ -926,7 +919,6 @@ def constraint_equation_26(): @ConstraintManager.register_constraint(27, "A/m2", "<=") def constraint_equation_27(): """Equation for Central Solenoid current density upper limit at BOP - author: P B Lloyd, CCFE, Culham Science Centre fjohc0: margin for central solenoid current at beginning of pulse j_cs_critical_pulse_start: allowable central solenoid current density at beginning of pulse (A/m2) @@ -946,7 +938,6 @@ def constraint_equation_27(): @ConstraintManager.register_constraint(28, "", ">=") def constraint_equation_28(): """Equation for fusion gain (big Q) lower limit - author: P B Lloyd, CCFE, Culham Science Centre big_q_plasma: Fusion gain; P_fusion / (P_injection + P_ohmic) big_q_plasma_min: minimum fusion gain Q @@ -976,7 +967,6 @@ def constraint_equation_28(): @ConstraintManager.register_constraint(29, "m", "=") def constraint_equation_29(): """Equation for inboard major radius: This is a consistency equation - author: P B Lloyd, CCFE, Culham Science Centre rmajor: plasma major radius (m) (iteration variable 3) rminor: plasma minor radius (m) @@ -1000,7 +990,6 @@ def constraint_equation_29(): @ConstraintManager.register_constraint(30, "MW", "<=") def constraint_equation_30(): """Equation for injection power upper limit - author: P B Lloyd, CCFE, Culham Science Centre p_hcd_injected_total_mw: total auxiliary injected power (MW) p_hcd_injected_max: Maximum allowable value for injected power (MW) @@ -1018,7 +1007,6 @@ def constraint_equation_30(): @ConstraintManager.register_constraint(31, "Pa", "<=") def constraint_equation_31(): """Equation for TF coil case stress upper limit (SCTF) - author: P B Lloyd, CCFE, Culham Science Centre sig_tf_case_max: Allowable maximum shear stress in TF coil case (Tresca criterion) (Pa) sig_tf_case: Constrained stress in TF coil case (Pa) @@ -1036,7 +1024,6 @@ def constraint_equation_31(): @ConstraintManager.register_constraint(32, "Pa", "<=") def constraint_equation_32(): """Equation for TF coil conduit stress upper limit (SCTF) - author: P B Lloyd, CCFE, Culham Science Centre sig_tf_wp_max: Allowable maximum shear stress in TF coil conduit (Tresca criterion) (Pa) sig_tf_wp: Constrained stress in TF conductor conduit (Pa) @@ -1054,7 +1041,7 @@ def constraint_equation_32(): @ConstraintManager.register_constraint(33, "A/m2", "<=") def constraint_equation_33(): """Equation for TF coil operating/critical J upper limit (SCTF) - author: P B Lloyd, CCFE, Culham Science Centre + args : output structure : residual error; constraint value; fiooic: margin for TF coil operating current / critical @@ -1080,7 +1067,6 @@ def constraint_equation_33(): @ConstraintManager.register_constraint(34, "V", "<=") def constraint_equation_34(): """Equation for TF coil dump voltage upper limit (SCTF) - author: P B Lloyd, CCFE, Culham Science Centre v_tf_coil_dump_quench_max_kv: max voltage across TF coil during quench (kV) v_tf_coil_dump_quench_kv: voltage across a TF coil during quench (kV) @@ -1098,7 +1084,6 @@ def constraint_equation_34(): @ConstraintManager.register_constraint(35, "A/m2", "<=") def constraint_equation_35(): """Equation for TF coil J_wp/J_prot upper limit (SCTF) - author: P B Lloyd, CCFE, Culham Science Centre j_tf_wp_quench_heat_max: allowable TF coil winding pack current density, for dump temperature rise protection (A/m2) @@ -1117,7 +1102,6 @@ def constraint_equation_35(): @ConstraintManager.register_constraint(36, "K", ">=") def constraint_equation_36(): """Equation for TF coil s/c temperature margin lower limit (SCTF) - author: P B Lloyd, CCFE, Culham Science Centre temp_tf_superconductor_margin: TF coil temperature margin (K) temp_tf_superconductor_margin_min: minimum allowable temperature margin : TF coils (K) @@ -1135,7 +1119,6 @@ def constraint_equation_36(): @ConstraintManager.register_constraint(37, "1E20 A/Wm2", "<=") def constraint_equation_37(): """Equation for current drive gamma upper limit - author: P B Lloyd, CCFE, Culham Science Centre eta_cd_norm_hcd_primary_max: maximum current drive gamma eta_cd_norm_hcd_primary: normalised current drive efficiency (1.0e20 A/W-m2) @@ -1155,7 +1138,6 @@ def constraint_equation_37(): @ConstraintManager.register_constraint(39, "K", "<=") def constraint_equation_39(): """Equation for first wall temperature upper limit - author: P B Lloyd, CCFE, Culham Science Centre temp_fw_max: maximum temperature of first wall material (K) (i_thermal_electric_conversion>1) temp_fw_peak: peak first wall temperature (K) @@ -1179,7 +1161,6 @@ def constraint_equation_39(): @ConstraintManager.register_constraint(40, "MW", ">=") def constraint_equation_40(): """Equation for auxiliary power lower limit - author: P B Lloyd, CCFE, Culham Science Centre p_hcd_injected_total_mw: total auxiliary injected power (MW) p_hcd_injected_min_mw: minimum auxiliary power (MW) @@ -1199,7 +1180,6 @@ def constraint_equation_40(): @ConstraintManager.register_constraint(41, "sec", ">=") def constraint_equation_41(): """Equation for plasma current ramp-up time lower limit - author: P B Lloyd, CCFE, Culham Science Centre t_plant_pulse_plasma_current_ramp_up: plasma current ramp-up time for current initiation (s) t_current_ramp_up_min: minimum plasma current ramp-up time (s) @@ -1219,7 +1199,6 @@ def constraint_equation_41(): @ConstraintManager.register_constraint(42, "sec", ">=") def constraint_equation_42(): """Equation for cycle time lower limit - author: P B Lloyd, CCFE, Culham Science Centre t_plant_pulse_total: full cycle time (s) t_cycle_min: minimum cycle time (s) @@ -1244,7 +1223,6 @@ def constraint_equation_42(): @ConstraintManager.register_constraint(43, "deg C", "=") def constraint_equation_43(): """Equation for average centrepost temperature: This is a consistency equation (TART) - author: P B Lloyd, CCFE, Culham Science Centre temp_cp_average: average temp of TF coil inboard leg conductor (C)e tcpav2: centrepost average temperature (C) (for consistency) @@ -1270,7 +1248,6 @@ def constraint_equation_43(): @ConstraintManager.register_constraint(44, "deg C", "<=") def constraint_equation_44(): """Equation for centrepost temperature upper limit (TART) - author: P B Lloyd, CCFE, Culham Science Centre temp_cp_max: maximum peak centrepost temperature (K) temp_cp_peak: peak centrepost temperature (K) @@ -1295,14 +1272,14 @@ def constraint_equation_44(): @ConstraintManager.register_constraint(45, "", ">=") def constraint_manager_45(): """Equation for edge safety factor lower limit (TART) - author: P B Lloyd, CCFE, Culham Science Centre q95 : safety factor 'near' plasma edge (unless i_plasma_current = 2 (ST current scaling), in which case q = mean edge safety factor qbar) q95_min: lower limit for edge safety factor itart : input integer : switch for spherical tokamak (ST) models: - 0 use conventional aspect ratio models; - - 1 use spherical tokamak models""" + - 1 use spherical tokamak models + """ if data_structure.physics_variables.itart == 0: raise ProcessValueError("Do not use constraint 45 if itart=0") @@ -1320,7 +1297,6 @@ def constraint_manager_45(): @ConstraintManager.register_constraint(46, "", "<=") def constraint_equation_46(): """Equation for Ip/Irod upper limit (TART) - author: P B Lloyd, CCFE, Culham Science Centre eps: inverse aspect ratio c_tf_total: total (summed) current in TF coils (A) @@ -1351,7 +1327,6 @@ def constraint_equation_46(): @ConstraintManager.register_constraint(48, "", "<=") def constraint_equation_48(): """Equation for poloidal beta upper limit - author: P B Lloyd, CCFE, Culham Science Centre beta_poloidal_max: maximum poloidal beta beta_poloidal: poloidal beta @@ -1370,10 +1345,7 @@ def constraint_equation_48(): @ConstraintManager.register_constraint(50, "Hz", "<=") def constraint_equation_50(): - """IFE option: Equation for repetition rate upper limit - author: P B Lloyd, CCFE, Culham Science Centre - author: S I Muldrew, CCFE, Culham Science Centre - """ + """IFE option: Equation for repetition rate upper limit""" cc = data_structure.ife_variables.reprat / data_structure.ife_variables.rrmax - 1.0 return ConstraintResult( cc, @@ -1385,7 +1357,6 @@ def constraint_equation_50(): @ConstraintManager.register_constraint(51, "V.s", "=") def constraint_equation_51(): """Equation to enforce startup flux = available startup flux - author: P B Lloyd, CCFE, Culham Science Centre vs_plasma_res_ramp: resistive losses in startup V-s (Wb) vs_plasma_ind_ramp: internal and external plasma inductance V-s (Wb)) @@ -1408,7 +1379,6 @@ def constraint_equation_51(): @ConstraintManager.register_constraint(52, "", ">=") def constraint_equation_52(): """Equation for tritium breeding ratio lower limit - author: P B Lloyd, CCFE, Culham Science Centre The tritium breeding ratio is only calculated when using the IFE model. @@ -1433,7 +1403,6 @@ def constraint_equation_52(): @ConstraintManager.register_constraint(53, "neutron/m2", "<=") def constraint_equation_53(): """Equation for fast neutron fluence on TF coil upper limit - author: P B Lloyd, CCFE, Culham Science Centre nflutfmax: max fast neutron fluence on TF coil (n/m2) nflutf: peak fast neutron fluence on TF coil superconductor (n/m2) @@ -1453,7 +1422,6 @@ def constraint_equation_53(): @ConstraintManager.register_constraint(54, "MW/m3", "<=") def constraint_equation_54(): """Equation for peak TF coil nuclear heating upper limit - author: P B Lloyd, CCFE, Culham Science Centre ptfnucmax: maximum nuclear heating in TF coil (MW/m3) ptfnucpm3: nuclear heating in the TF coil (MW/m3) (blktmodel>0) @@ -1473,7 +1441,6 @@ def constraint_equation_54(): @ConstraintManager.register_constraint(56, "MW/m", "<=") def constraint_equation_56(): """Equation for power through separatrix / major radius upper limit - author: P B Lloyd, CCFE, Culham Science Centre pseprmax: maximum ratio of power crossing the separatrix to plasma major radius (Psep/R) (MW/m) p_plasma_separatrix_mw: power to be conducted to the divertor region (MW) @@ -1497,7 +1464,6 @@ def constraint_equation_56(): @ConstraintManager.register_constraint(59, "", "<=") def constraint_equation_59(): """Equation for neutral beam shine-through fraction upper limit - author: P B Lloyd, CCFE, Culham Science Centre f_p_beam_shine_through_max: maximum neutral beam shine-through fraction f_p_beam_shine_through: neutral beam shine-through fraction @@ -1517,7 +1483,6 @@ def constraint_equation_59(): @ConstraintManager.register_constraint(60, "K", ">=") def constraint_equation_60(): """Equation for Central Solenoid s/c temperature margin lower limit - author: P B Lloyd, CCFE, Culham Science Centre temp_cs_superconductor_margin: Central solenoid temperature margin (K) temp_cs_superconductor_margin_min: Minimum allowable temperature margin : CS (K) @@ -1535,7 +1500,6 @@ def constraint_equation_60(): @ConstraintManager.register_constraint(61, "", ">=") def constraint_equation_61(): """Equation for availability lower limit - author: P B Lloyd, CCFE, Culham Science Centre f_t_plant_available: Total plant availability fraction avail_min: Minimum availability @@ -1555,7 +1519,6 @@ def constraint_equation_61(): @ConstraintManager.register_constraint(62, "", ">=") def constraint_equation_62(): """Lower limit on f_alpha_energy_confinement the ratio of alpha particle to energy confinement times - author: P B Lloyd, CCFE, Culham Science Centre t_alpha_confinement: alpha particle confinement time (s) t_energy_confinement: global thermal energy confinement time (sec) @@ -1583,7 +1546,6 @@ def constraint_equation_62(): @ConstraintManager.register_constraint(63, "", "<=") def constraint_equation_63(): """Upper limit on n_iter_vacuum_pumps (i_vacuum_pumping = simple) - author: P B Lloyd, CCFE, Culham Science Centre tfno: number of TF coils (default = 50 for stellarators) n_iter_vacuum_pumps: number of high vacuum pumps (real number), each with the throughput @@ -1603,7 +1565,6 @@ def constraint_equation_63(): @ConstraintManager.register_constraint(64, "", "<=") def constraint_equation_64(): """Upper limit on Zeff - author: P B Lloyd, CCFE, Culham Science Centre zeff_max: maximum value for Zeff n_charge_plasma_effective_vol_avg: plasma effective charge @@ -1623,7 +1584,6 @@ def constraint_equation_64(): @ConstraintManager.register_constraint(65, "Pa", "<=") def constraint_equation_65(): """Upper limit on stress of the vacuum vessel that occurs when the TF coil quenches. - author: Timothy Nunn, UKAEA max_vv_stress: Maximum permitted stress of the VV (Pa) vv_stress_quench: Stress of the VV (Pa) @@ -1643,7 +1603,6 @@ def constraint_equation_65(): @ConstraintManager.register_constraint(66, "MW", "<=") def constrain_equation_66(): """Upper limit on rate of change of energy in poloidal field - author: P B Lloyd, CCFE, Culham Science Centre maxpoloidalpower: Maximum permitted absolute rate of change of stored energy in poloidal field (MW) peakpoloidalpower: Peak absolute rate of change of stored energy in poloidal field (MW) (11/01/16) @@ -1663,7 +1622,6 @@ def constrain_equation_66(): @ConstraintManager.register_constraint(67, "MW/m2", "<=") def constraint_equation_67(): """Simple upper limit on radiation wall load - author: P B Lloyd, CCFE, Culham Science Centre pflux_fw_rad_max: Maximum permitted radiation wall load (MW/m^2) pflux_fw_rad_max_mw: Peak radiation wall load (MW/m^2) @@ -1683,7 +1641,6 @@ def constraint_equation_67(): @ConstraintManager.register_constraint(68, "MWT/m", "<=") def constraint_equation_68(): """Upper limit on Psep scaling (PsepB/qAR) - author: P B Lloyd, CCFE, Culham Science Centre psepbqarmax: maximum permitted value of ratio of Psep*Bt/qAR (MWT/m) p_plasma_separatrix_mw: Power to conducted to the divertor region (MW) @@ -1741,7 +1698,6 @@ def constraint_equation_68(): @ConstraintManager.register_constraint(72, "Pa", "<=") def constraint_equation_72(): """Upper limit on central Solenoid Tresca yield stress - author: P B Lloyd, CCFE, Culham Science Centre In the case if the bucked and wedged option ( i_tf_bucking >= 2 ) the constrained stress is the largest the largest stress of the @@ -1795,7 +1751,6 @@ def constraint_equation_72(): def constraint_equation_73(): """Lower limit to ensure separatrix power is greater than the L-H power + auxiliary power Related to constraint 15 - author: P B Lloyd, CCFE, Culham Science Centre p_l_h_threshold_mw: L-H mode power threshold (MW) p_plasma_separatrix_mw: power to be conducted to the divertor region (MW) @@ -1816,7 +1771,6 @@ def constraint_equation_73(): def constraint_equation_74(): """Upper limit to ensure TF coil quench temperature < temp_croco_quench_max ONLY used for croco HTS coil - author: P B Lloyd, CCFE, Culham Science Centre temp_croco_quench: CroCo strand: Actual temp reached during a quench (K) temp_croco_quench_max: CroCo strand: maximum permitted temp during a quench (K) @@ -1837,7 +1791,6 @@ def constraint_equation_74(): def constraint_equation_75(): """Upper limit to ensure that TF coil current / copper area < Maximum value ONLY used for croco HTS coil - author: P B Lloyd, CCFE, Culham Science Centre copperA_m2: TF coil current / copper area (A/m2) copperA_m2_max: Maximum TF coil current / copper area (A/m2) @@ -1857,7 +1810,6 @@ def constraint_equation_75(): @ConstraintManager.register_constraint(76, "m-3", "<=") def constraint_equation_76(): """Upper limit for Eich critical separatrix density model: Added for issue 558 - author: P B Lloyd, CCFE, Culham Science Centre Eich critical separatrix density model Added for issue 558 with ref to http://iopscience.iop.org/article/10.1088/1741-4326/aaa340/pdf @@ -1901,7 +1853,6 @@ def constraint_equation_76(): @ConstraintManager.register_constraint(77, "A/turn", "<=") def constraint_equation_77(): """Equation for maximum TF current per turn upper limit - author: P B Lloyd, CCFE, Culham Science Centre c_tf_turn_max : allowable TF coil current per turn [A/turn] c_tf_turn : TF coil current per turn [A/turn] @@ -1921,7 +1872,6 @@ def constraint_equation_77(): @ConstraintManager.register_constraint(78, "", ">=") def constraint_equation_78(): """Equation for Reinke criterion, divertor impurity fraction lower limit - author: P B Lloyd, CCFE, Culham Science Centre fzmin : input : minimum impurity fraction from Reinke model fzactual : input : actual impurity fraction @@ -1941,7 +1891,6 @@ def constraint_equation_78(): @ConstraintManager.register_constraint(79, "A/turn", "<=") def constraint_equation_79(): """Equation for maximum CS field - author: P B Lloyd, CCFE, Culham Science Centre b_cs_limit_max: Central solenoid max field limit [T] b_cs_peak_pulse_start: maximum field in central solenoid at beginning of pulse (T) @@ -1970,7 +1919,7 @@ def constraint_equation_79(): @ConstraintManager.register_constraint(80, "MW", ">=") def constraint_equation_80(): """Equation for p_plasma_separatrix_mw lower limit - author: J Morris, Culham Science Centre + args : output structure : residual error; constraint value; residual error in physical units; output string; units string Lower limit p_plasma_separatrix_mw @@ -1993,7 +1942,7 @@ def constraint_equation_80(): @ConstraintManager.register_constraint(81, "m-3", ">=") def constraint_equation_81(): """Lower limit to ensure central density is larger that the pedestal one - author: S Kahn, Culham Science Centre + args : output structure : residual error; constraint value; residual error in physical units; output string; units string Lower limit nd_plasma_electron_on_axis > nd_plasma_pedestal_electron @@ -2019,7 +1968,6 @@ def constraint_equation_81(): @ConstraintManager.register_constraint(82, "m", ">=") def constraint_equation_82(): """Equation for toroidal consistency of stellarator build - author: J Lion, IPP Greifswald toroidalgap: minimal gap between two stellarator coils dx_tf_inboard_out_toroidal: total toroidal width of a tf coil @@ -2037,7 +1985,6 @@ def constraint_equation_82(): @ConstraintManager.register_constraint(83, "m", ">=") def constraint_equation_83(): """Equation for radial consistency of stellarator build - author: J Lion, IPP Greifswald available_radial_space: avaible space in radial direction as given by each s.-configuration required_radial_space: required space in radial direction @@ -2057,7 +2004,6 @@ def constraint_equation_83(): @ConstraintManager.register_constraint(84, "", ">=") def constraint_equation_84(): """Equation for the lower limit of beta - author: J Lion, IPP Greifswald beta_vol_avg_min: Lower limit for beta beta: plasma beta @@ -2077,7 +2023,6 @@ def constraint_equation_84(): @ConstraintManager.register_constraint(85, "years", "=") def constraint_equation_85(): """Equality constraint for the centerpost (CP) lifetime - Author : S Kahn Depending on the chosen option i_cp_lifetime: - 0 : The CP full power year lifelime is set by the user (cplife_input) @@ -2131,7 +2076,6 @@ def constraint_equation_85(): @ConstraintManager.register_constraint(86, "m", "<=") def constraint_equation_86(): """Upper limit on the turn edge length in the TF winding pack - Author : S Kahn dx_tf_turn_general: TF coil turn edge length including turn insulation [m] t_turn_tf_max: TF turn edge length including turn insulation upper limit [m] @@ -2151,7 +2095,6 @@ def constraint_equation_86(): @ConstraintManager.register_constraint(87, "MW", "<=") def constraint_equation_87(): """Equation for TF coil cryogenic power upper limit - author: S. Kahn, CCFE, Culham Science Centre p_cryo_plant_electric_mw: cryogenic plant power (MW) p_cryo_plant_electric_max_mw: Maximum cryogenic plant power (MW) @@ -2172,7 +2115,6 @@ def constraint_equation_87(): @ConstraintManager.register_constraint(88, "", "<=") def constraint_equation_88(): """Equation for TF coil vertical strain upper limit (absolute value) - author: CPS Swanson, PPPL, USA str_wp_max: Allowable maximum TF coil vertical strain str_wp: Constrained TF coil vertical strain @@ -2190,7 +2132,6 @@ def constraint_equation_88(): @ConstraintManager.register_constraint(89, "A/m2", "<=") def constraint_equation_89(): """Upper limit to ensure that the Central Solenoid [OH] coil current / copper area < Maximum value - author: G Turkington, CCFE, Culham Science Centre copperaoh_m2: CS coil current at EOF / copper area [A/m2] copperaoh_m2_max: maximum coil current / copper area [A/m2] @@ -2210,7 +2151,6 @@ def constraint_equation_89(): @ConstraintManager.register_constraint(90, "", ">=") def constraint_equation_90(): """Lower limit for CS coil stress load cycles - author: A. Pearce, G Turkington CCFE, Culham Science Centre n_cycle: Allowable number of cycles for CS n_cycle_min: Minimum required cycles for CS @@ -2240,7 +2180,6 @@ def constraint_equation_91(): """Lower limit to ensure ECRH te is greater than required te for ignition at lower values for n and B. Or if the design point is ECRH heatable (if i_plasma_ignited==0) stellarators only (but in principle usable also for tokamaks). - author: J Lion, IPP Greifswald max_gyrotron_frequency: Max. av. gyrotron frequency te0_ecrh_achievable: Max. achievable electron temperature at ignition point @@ -2272,7 +2211,6 @@ def constraint_equation_91(): @ConstraintManager.register_constraint(92, "", "=") def constraint_equation_92(): """Equation for checking is D/T ratio is consistent, and sums to 1. - author: G Turkington, UKAEA f_plasma_fuel_deuterium: fraction of deuterium ions f_plasma_fuel_tritium: fraction of tritium ions @@ -2294,9 +2232,17 @@ def constraint_equation_92(): def constraint_eqns(m: int, ieqn: int): """Evaluates the constraints given the current state of PROCESS. - :param m: The number of constraints to evaluate - :param ieqn: Evaluates the 'ieqn'th constraint equation (index starts at 1) - or all equations if <= 0 + Parameters + ---------- + m : + The number of constraints to evaluate + ieqn : + Evaluates the 'ieqn'th constraint equation (index starts at 1) + or all equations if <= 0 + m: int : + + ieqn: int : + """ if ieqn > 0: diff --git a/process/coolprop_interface.py b/process/coolprop_interface.py index 20b7b8a1a8..6e6d9698cc 100644 --- a/process/coolprop_interface.py +++ b/process/coolprop_interface.py @@ -64,12 +64,19 @@ def of( ): """Calculates the fluid properties of a fluid given its temperature and pressure. - :param fluid_name: the name of the fluid to calculate properties for, e.g. 'Helium' or 'Water'. - :param temperature: the current temperature [K] of the fluid to calculate the properties with respect to. - :param pressure: the current pressure [Pa] of the fluid to calculate the properties with respect to. - :param entropy: the current entropy [J/kg/K] of the fluid to calculate the properties with respect to. - :param vapor_quality: the molar vapor quality [mol/mol] of the fluid to calculate the properties with respect to. - `[0, 1]`, where `0` is a saturated liquid and `1` is a saturated vapor. + Parameters + ---------- + fluid_name : + the name of the fluid to calculate properties for, e.g. 'Helium' or 'Water'. + temperature : + the current temperature [K] of the fluid to calculate the properties with respect to. + pressure : + the current pressure [Pa] of the fluid to calculate the properties with respect to. + entropy : + the current entropy [J/kg/K] of the fluid to calculate the properties with respect to. + vapor_quality : + the molar vapor quality [mol/mol] of the fluid to calculate the properties with respect to. + `[0, 1]`, where `0` is a saturated liquid and `1` is a saturated vapor. """ coolprop_inputs = [] diff --git a/process/costs.py b/process/costs.py index ffe54a254e..c20f075e10 100644 --- a/process/costs.py +++ b/process/costs.py @@ -33,9 +33,8 @@ def __init__(self): self.outfile = constants.NOUT def run(self): - """ - Cost accounting for a fusion power plant - author: P J Knight, CCFE, Culham Science Centre + """Cost accounting for a fusion power plant + This routine performs the cost accounting for a fusion power plant. The direct costs are calculated based on parameters input @@ -46,7 +45,7 @@ def run(self):

The code is arranged in the order of the standard accounts. """ # Convert FPY component lifetimes to calendar years - # for replacment components + # for replacement components self.convert_fpy_to_calendar() self.acc21() @@ -927,11 +926,8 @@ def output(self): ) def acc22(self): - """ - Account 22 : Fusion power island - author: P J Knight, CCFE, Culham Science Centre - author: J Morris, CCFE, Culham Science Centre - None + """Account 22 : Fusion power island + This routine evaluates the Account 22 (fusion power island - the tokamak itself plus auxiliary power systems, etc.) costs. """ @@ -987,10 +983,7 @@ def acc22(self): ) def acc221(self): - """ - Account 221 : Reactor - author: P J Knight, CCFE, Culham Science Centre - None + """Account 221 : Reactor This routine evaluates the Account 221 (reactor) costs. These include the first wall, blanket, shield, support structure and divertor plates. @@ -1028,10 +1021,7 @@ def acc221(self): ) def acc222(self): - """ - Account 222 : Magnets, including cryostat - author: P J Knight, CCFE, Culham Science Centre - None + """Account 222 : Magnets, including cryostat This routine evaluates the Account 222 (magnet) costs, including the costs of associated cryostats. """ @@ -1057,10 +1047,7 @@ def acc222(self): ) def acc225(self): - """ - Account 225 : Power conditioning - author: P J Knight, CCFE, Culham Science Centre - None + """Account 225 : Power conditioning This routine evaluates the Account 225 (power conditioning) costs. """ if ife_variables.ife == 1: @@ -1085,10 +1072,7 @@ def acc225(self): ) def acc21(self): - """ - Account 21 : Structures and site facilities - author: P J Knight, CCFE, Culham Science Centre - None + """Account 21 : Structures and site facilities This routine evaluates the Account 21 (structures and site facilities) costs. Building costs are scaled with volume according to algorithms @@ -1206,10 +1190,7 @@ def acc21(self): ) def acc2211(self): - """ - Account 221.1 : First wall - author: P J Knight, CCFE, Culham Science Centre - None + """Account 221.1 : First wall This routine evaluates the Account 221.1 (first wall) costs. The first wall cost is scaled linearly with surface area from TFCX. If ifueltyp = 1, the first wall cost is treated as a fuel cost, @@ -1272,10 +1253,7 @@ def acc2211(self): cost_variables.fwallcst = 0.0e0 def acc2212(self): - """ - Account 221.2 : Blanket - author: P J Knight, CCFE, Culham Science Centre - None + """Account 221.2 : Blanket This routine evaluates the Account 221.2 (blanket) costs. If ifueltyp = 1, the blanket cost is treated as a fuel cost, rather than as a capital cost. @@ -1398,10 +1376,7 @@ def acc2212(self): cost_variables.blkcst = 0.0e0 def acc2213(self): - """ - Account 221.3 : Shield - author: P J Knight, CCFE, Culham Science Centre - None + """Account 221.3 : Shield This routine evaluates the Account 221.3 (shield) costs. """ cmlsa = [0.5000e0, 0.7500e0, 0.8750e0, 1.0000e0] @@ -1463,10 +1438,7 @@ def acc2213(self): cost_variables.c2213 = cost_variables.c22131 + cost_variables.c22132 def acc2214(self): - """ - Account 221.4 : Reactor structure - author: P J Knight, CCFE, Culham Science Centre - None + """Account 221.4 : Reactor structure This routine evaluates the Account 221.4 (reactor structure) costs. The structural items are costed as standard steel elements. """ @@ -1481,10 +1453,7 @@ def acc2214(self): cost_variables.c2214 = cost_variables.fkind * cost_variables.c2214 def acc2215(self): - """ - Account 221.5 : Divertor - author: P J Knight, CCFE, Culham Science Centre - None + """Account 221.5 : Divertor This routine evaluates the Account 221.5 (divertor) costs. The cost of the divertor blade is scaled linearly with surface area from TFCX. The graphite armour is assumed to @@ -1514,10 +1483,7 @@ def acc2215(self): cost_variables.divcst = 0.0e0 def acc2221(self): - """ - Account 222.1 : TF magnet assemblies - author: P J Knight, CCFE, Culham Science Centre - None + """Account 222.1 : TF magnet assemblies This routine evaluates the Account 222.1 (TF magnet) costs. Copper magnets are costed from the TFCX data base ($/kg). Superconductor magnets are costed using a new method devised @@ -1671,10 +1637,7 @@ def acc2221(self): ) def acc2222(self): - """ - Account 222.2 : PF magnet assemblies - author: P J Knight, CCFE, Culham Science Centre - None + """Account 222.2 : PF magnet assemblies This routine evaluates the Account 222.2 (PF magnet) costs. Conductor costs previously used an algorithm devised by R. Hancox, January 1994, under contract to Culham, which took into @@ -1916,10 +1879,7 @@ def acc2222(self): ) def acc2223(self): - """ - Account 222.3 : Vacuum vessel - author: P J Knight, CCFE, Culham Science Centre - None + """Account 222.3 : Vacuum vessel This routine evaluates the Account 222.3 (vacuum vessel) costs. """ cmlsa = [0.6900e0, 0.8450e0, 0.9225e0, 1.0000e0] @@ -1930,10 +1890,7 @@ def acc2223(self): ) def acc223(self): - """ - Account 223 : Power injection - author: P J Knight, CCFE, Culham Science Centre - None + """Account 223 : Power injection This routine evaluates the Account 223 (power injection) costs. The costs are from TETRA, updated to 1990$. Nominal TIBER values are used pending system designs. Costs are @@ -2058,10 +2015,7 @@ def acc223(self): cost_variables.cdcost = cost_variables.c223 def acc224(self): - """ - Account 224 : Vacuum system - author: P J Knight, CCFE, Culham Science Centre - None + """Account 224 : Vacuum system This routine evaluates the Account 224 (vacuum system) costs. The costs are scaled from TETRA reactor code runs. """ @@ -2131,10 +2085,7 @@ def acc224(self): ) def acc2251(self): - """ - Account 225.1 : TF coil power conditioning - author: P J Knight, CCFE, Culham Science Centre - None + """Account 225.1 : TF coil power conditioning This routine evaluates the Account 225.1 (TF coil power conditioning) costs. Costs are developed based on the major equipment specification @@ -2213,10 +2164,7 @@ def acc2251(self): ) def acc2252(self): - """ - Account 225.2 : PF coil power conditioning - author: P J Knight, CCFE, Culham Science Centre - None + """Account 225.2 : PF coil power conditioning This routine evaluates the Account 225.2 (PF coil power conditioning) costs. Costs are taken from the equipment specification of the @@ -2295,10 +2243,7 @@ def acc2252(self): ) def acc226(self): - """ - Account 226 : Heat transport system - author: P J Knight, CCFE, Culham Science Centre - None + """Account 226 : Heat transport system This routine evaluates the Account 226 (heat transport system) costs. Costs are estimated from major equipment and heat transport system loops developed in the heatpwr module of the code. @@ -2308,10 +2253,7 @@ def acc226(self): ) def acc2261(self): - """ - Account 2261 : Reactor cooling system - author: J Morris, CCFE, Culham Science Centre - None + """Account 2261 : Reactor cooling system This routine evaluates the Account 2261 - """ cmlsa = [0.4000e0, 0.7000e0, 0.8500e0, 1.0000e0] @@ -2354,10 +2296,7 @@ def acc2261(self): cost_variables.c2261 = cost_variables.chx + cost_variables.cpp def acc2262(self): - """ - Account 2262 : Auxiliary component cooling - author: J Morris, CCFE, Culham Science Centre - None + """Account 2262 : Auxiliary component cooling This routine evaluates the Account 2262 - Auxiliary component cooling """ cmlsa = 0.4000e0, 0.7000e0, 0.8500e0, 1.0000e0 @@ -2396,10 +2335,7 @@ def acc2262(self): cost_variables.c2262 = cost_variables.cppa def acc2263(self): - """ - Account 2263 : Cryogenic system - author: J Morris, CCFE, Culham Science Centre - None + """Account 2263 : Cryogenic system This routine evaluates the Account 2263 - Cryogenic system """ cmlsa = 0.4000e0, 0.7000e0, 0.8500e0, 1.0000e0 @@ -2419,10 +2355,7 @@ def acc2263(self): ) def acc227(self): - """ - Account 227 : Fuel handling - author: P J Knight, CCFE, Culham Science Centre - None + """Account 227 : Fuel handling This routine evaluates the Account 227 (fuel handling) costs. Costs are scaled from TETRA reactor code runs. """ @@ -2434,10 +2367,7 @@ def acc227(self): ) def acc2271(self): - """ - Account 2271 : Fuelling system - author: J Morris, CCFE, Culham Science Centre - None + """Account 2271 : Fuelling system This routine evaluates the Account 2271 - Fuelling system """ cost_variables.c2271 = 1.0e-6 * cost_variables.ucf1 @@ -2446,10 +2376,7 @@ def acc2271(self): cost_variables.c2271 = cost_variables.fkind * cost_variables.c2271 def acc2272(self): - """ - Account 2272 : Fuel processing and purification - author: J Morris, CCFE, Culham Science Centre - None + """Account 2272 : Fuel processing and purification This routine evaluates the Account 2272 - Fuel processing """ if ife_variables.ife != 1: @@ -2487,10 +2414,7 @@ def acc2272(self): cost_variables.c2272 = cost_variables.fkind * cost_variables.c2272 def acc2273(self): - """ - Account 2273 : Atmospheric recovery systems - author: J Morris, CCFE, Culham Science Centre - None + """Account 2273 : Atmospheric recovery systems This routine evaluates the Account 2273 - Atmospheric recovery systems """ cfrht = 1.0e5 @@ -2511,10 +2435,7 @@ def acc2273(self): cost_variables.c2273 = cost_variables.fkind * cost_variables.c2273 def acc2274(self): - """ - Account 2274 : Nuclear building ventilation - author: J Morris, CCFE, Culham Science Centre - None + """Account 2274 : Nuclear building ventilation This routine evaluates the Account 2274 - Nuclear building ventilation """ cost_variables.c2274 = ( @@ -2527,11 +2448,8 @@ def acc2274(self): cost_variables.c2274 = cost_variables.fkind * cost_variables.c2274 def acc228(self): - """ - Account 228 : Instrumentation and control - author: P J Knight, CCFE, Culham Science Centre - author: J Morris, CCFE, Culham Science Centre - None + """Account 228 : Instrumentation and control + This routine evaluates the Account 228 (instrumentation and control) costs. Costs are based on TFCX and INTOR. @@ -2540,22 +2458,16 @@ def acc228(self): cost_variables.c228 = cost_variables.fkind * cost_variables.c228 def acc229(self): - """ - Account 229 : Maintenance equipment - author: P J Knight, CCFE, Culham Science Centre - author: J Morris, CCFE, Culham Science Centre - None + """Account 229 : Maintenance equipment + This routine evaluates the Account 229 (maintenance equipment) costs. """ cost_variables.c229 = 1.0e-6 * cost_variables.ucme cost_variables.c229 = cost_variables.fkind * cost_variables.c229 def acc23(self): - """ - Account 23 : Turbine plant equipment - author: P J Knight, CCFE, Culham Science Centre - author: J Morris, CCFE, Culham Science Centre - None + """Account 23 : Turbine plant equipment + This routine evaluates the Account 23 (turbine plant equipment) costs. """ @@ -2569,11 +2481,8 @@ def acc23(self): ) def acc24(self): - """ - Account 24 : Electric plant equipment - author: P J Knight, CCFE, Culham Science Centre - author: J Morris, CCFE, Culham Science Centre - None + """Account 24 : Electric plant equipment + This routine evaluates the Account 24 (electric plant equipment) costs. """ cost_variables.c24 = ( @@ -2585,10 +2494,7 @@ def acc24(self): ) def acc241(self): - """ - Account 241 : Electric plant equipment - switchyard - author: J Morris, CCFE, Culham Science Centre - None + """Account 241 : Electric plant equipment - switchyard This routine evaluates the Account 241 - switchyard """ cmlsa = 0.5700e0, 0.7850e0, 0.8925e0, 1.0000e0 @@ -2599,10 +2505,7 @@ def acc241(self): ) def acc242(self): - """ - Account 242 : Electric plant equipment - Transformers - author: J Morris, CCFE, Culham Science Centre - None + """Account 242 : Electric plant equipment - Transformers This routine evaluates the Account 242 - Transformers """ cmlsa = 0.5700e0, 0.7850e0, 0.8925e0, 1.0000e0 @@ -2619,10 +2522,7 @@ def acc242(self): cost_variables.c242 = cost_variables.c242 * cmlsa[cost_variables.lsa - 1] def acc243(self): - """ - Account 243 : Electric plant equipment - Low voltage - author: J Morris, CCFE, Culham Science Centre - None + """Account 243 : Electric plant equipment - Low voltage This routine evaluates the Account 243 - Low voltage """ cmlsa = 0.5700e0, 0.7850e0, 0.8925e0, 1.0000e0 @@ -2639,10 +2539,7 @@ def acc243(self): ) def acc244(self): - """ - Account 244 : Electric plant equipment - Diesel generators - author: J Morris, CCFE, Culham Science Centre - None + """Account 244 : Electric plant equipment - Diesel generators This routine evaluates the Account 244 - Diesel generators """ cmlsa = [0.5700e0, 0.7850e0, 0.8925e0, 1.0000e0] @@ -2653,10 +2550,7 @@ def acc244(self): ) def acc245(self): - """ - Account 245 : Electric plant equipment - Aux facility power - author: J Morris, CCFE, Culham Science Centre - None + """Account 245 : Electric plant equipment - Aux facility power This routine evaluates the Account 245 - Aux facility power """ cmlsa = 0.5700e0, 0.7850e0, 0.8925e0, 1.0000e0 @@ -2667,11 +2561,8 @@ def acc245(self): ) def acc25(self): - """ - Account 25 : Miscellaneous plant equipment - author: P J Knight, CCFE, Culham Science Centre - author: J Morris, CCFE, Culham Science Centre - None + """Account 25 : Miscellaneous plant equipment + This routine evaluates the Account 25 (miscellaneous plant equipment) costs, such as waste treatment. """ @@ -2682,11 +2573,8 @@ def acc25(self): ) def acc26(self): - """ - Account 26 : Heat rejection system - author: P J Knight, CCFE, Culham Science Centre - author: J Morris, CCFE, Culham Science Centre - None + """Account 26 : Heat rejection system + This routine evaluates the Account 26 (heat rejection system) costs. Costs are scaled with the total plant heat rejection based on commercial systems. @@ -2717,11 +2605,8 @@ def acc26(self): ) def acc9(self): - """ - Account 9 : Indirect cost and contingency allowances - author: P J Knight, CCFE, Culham Science Centre - author: J Morris, CCFE, Culham Science Centre - None + """Account 9 : Indirect cost and contingency allowances + This routine evaluates the Account 9 (indirect cost and contingency allowances) costs. The cost modelling is based on the commercial plant model of a @@ -2745,10 +2630,7 @@ def acc9(self): ) def acc2253(self): - """ - Account 225.3 : Energy storage - author: P J Knight, CCFE, Culham Science Centre - None + """Account 225.3 : Energy storage This routine evaluates the Account 225.3 (energy storage) costs. """ cost_variables.c2253 = 0.0e0 @@ -2848,9 +2730,8 @@ def acc2253(self): cost_variables.c2253 = cost_variables.fkind * cost_variables.c2253 def coelc(self): - """ - Routine to calculate the cost of electricity for a fusion power plant - author: P J Knight, CCFE, Culham Science Centre + """Routine to calculate the cost of electricity for a fusion power plant + outfile : input integer : output file unit This routine performs the calculation of the cost of electricity @@ -3169,11 +3050,9 @@ def coelc(self): ) @staticmethod - def convert_fpy_to_calendar() -> None: - """ - Routine to convert component lifetimes in FPY to calendar years. + def convert_fpy_to_calendar(): + """Routine to convert component lifetimes in FPY to calendar years. Required for replacement component costs. - Author: J Foster, CCFE, Culham Campus """ # FW/Blanket and HCD if fwbs_variables.life_blkt_fpy < cost_variables.life_plant: diff --git a/process/costs_2015.py b/process/costs_2015.py index 77f33b2afe..0eb279d69f 100644 --- a/process/costs_2015.py +++ b/process/costs_2015.py @@ -27,18 +27,13 @@ def __init__(self): self.outfile = constants.NOUT def run(self): - """ - Cost accounting for a fusion power plant - author: J Morris, CCFE, Culham Science Centre - outfile : input integer : output file unit - iprint : input integer : switch for writing to output file (1=yes) + """Cost accounting for a fusion power plant + This routine performs the cost accounting for a fusion power plant. PROCESS Costs Paper (M. Kovari, J. Morris) """ self.outfile = self.outfile - # ############################################### - # Calculate building costs self.calc_building_costs() @@ -139,10 +134,7 @@ def run(self): return def calc_fwbs_costs(self): - """ - Function to calculate the cost of the first wall, blanket and shield - author: J Morris, CCFE, Culham Science Centre - None + """Function to calculate the cost of the first wall, blanket and shield This routine calculates the cost of the first wall, blanket and shield coils for a fusion power plant based on the costings in the PROCESS costs paper. PROCESS Costs Paper (M. Kovari, J. Morris) @@ -318,10 +310,7 @@ def calc_fwbs_costs(self): ) def output(self): - """ - Function to output the costs calculations - author: J Morris, CCFE, Culham Science Centre - None + """Function to output the costs calculations This routine outputs the costs to output file PROCESS Costs Paper (M. Kovari, J. Morris) """ @@ -463,10 +452,7 @@ def output(self): ) def calc_building_costs(self): - """ - Function to calculate the cost of all buildings. - author: J Morris, CCFE, Culham Science Centre - None + """Function to calculate the cost of all buildings. This routine calculates the building costs for a fusion power plant based on the costings in the PROCESS costs Paper. Buildings have a different scaling law, with fixed cost per unit volume. @@ -606,10 +592,7 @@ def calc_building_costs(self): ) def calc_land_costs(self): - """ - Function to calculate the cost of land for the power plant - author: J Morris, CCFE, Culham Science Centre - None + """Function to calculate the cost of land for the power plant Land also uses a unit cost, but area is scaled. PROCESS Costs Paper (M. Kovari, J. Morris) """ @@ -682,10 +665,7 @@ def calc_land_costs(self): ) def calc_tf_coil_costs(self): - """ - Function to calculate the cost of the TF coils for the power plant - author: J Morris, CCFE, Culham Science Centre - None + """Function to calculate the cost of the TF coils for the power plant This routine calculates the cost of the TF coils for a fusion power plant based on the costings in the PROCESS costs Paper. PROCESS Costs Paper (M. Kovari, J. Morris) @@ -796,10 +776,7 @@ def calc_tf_coil_costs(self): ) def calc_remote_handling_costs(self): - """ - Function to calculate the cost of the remote handling facilities - author: J Morris, CCFE, Culham Science Centre - None + """Function to calculate the cost of the remote handling facilities PROCESS Costs Paper (M. Kovari, J. Morris) """ for i in range(27, 31): @@ -846,10 +823,7 @@ def calc_remote_handling_costs(self): ) def calc_n_plant_and_vv_costs(self): - """ - Function to calculate the cost of the nitrogen plant and vacuum vessel - author: J Morris, CCFE, Culham Science Centre - None + """Function to calculate the cost of the nitrogen plant and vacuum vessel This routine calculates the cost of the nitrogen plant and vacuum vessel for a fusion power plant based on the costings in the PROCESS costs paper. PROCESS Costs Paper (M. Kovari, J. Morris) @@ -895,10 +869,7 @@ def calc_n_plant_and_vv_costs(self): ) def calc_energy_conversion_system(self): - """ - Function to calculate the cost of the energy conversion system - author: J Morris, CCFE, Culham Science Centre - None + """Function to calculate the cost of the energy conversion system This routine calculates the cost of the energy conversion system for a fusion power plant based on the costings in the PROCESS costs paper. PROCESS Costs Paper (M. Kovari, J. Morris) @@ -919,10 +890,7 @@ def calc_energy_conversion_system(self): ) def calc_remaining_subsystems(self): - """ - Function to calculate the cost of the remaining subsystems - author: J Morris, CCFE, Culham Science Centre - None + """Function to calculate the cost of the remaining subsystems This routine calculates the cost of the remaining subsystems for a fusion power plant based on the costings in the PROCESS costs paper. PROCESS Costs Paper (M. Kovari, J. Morris) @@ -1288,19 +1256,31 @@ def calc_remaining_subsystems(self): ) def value_function(self, x): - """ - Value function - author: J Morris, CCFE, Culham Science Centre - None + """Value function Function for separative work unit calculation for enrichment cost PROCESS Costs Paper (M. Kovari, J. Morris) + + Parameters + ---------- + x : + """ return (1.0e0 - 2.0e0 * x) * np.log((1.0e0 - x) / x) def ocost(self, file, descr, vname, value): - """ - Routine to print out the code, description and value + """Routine to print out the code, description and value of a cost item from array s in costs_2015 + + Parameters + ---------- + file : + + descr : + + vname : + + value : + """ # Local variables @@ -1321,9 +1301,19 @@ def ocost(self, file, descr, vname, value): po.ovarrf(file, descr, vname, value) def ocost_vname(self, file, descr, vname, value): - """ - Routine to print out the code, description and value + """Routine to print out the code, description and value of a cost item not in the array s in costs_2015 + + Parameters + ---------- + file : + + descr : + + vname : + + value : + """ # character(len=70) :: dum70 diff --git a/process/cryostat.py b/process/cryostat.py index 754ae6d5aa..9f248bfc68 100644 --- a/process/cryostat.py +++ b/process/cryostat.py @@ -12,28 +12,26 @@ class Cryostat: - def __init__(self) -> None: + def __init__(self): self.outfile = constants.NOUT - def run(self) -> None: + def run(self): """Run the cryostat calculations. This method runs the cryostat calculations, including the calculation of the cryostat geometry. - """ # Calculate cryostat geometry self.external_cryo_geometry() @staticmethod - def external_cryo_geometry() -> None: + def external_cryo_geometry(): """Calculate cryostat geometry. This method calculates the geometry of the cryostat, including the inboard radius, the vertical clearance between the uppermost PF coil and the cryostat lid, the half-height of the cryostat, the vertical clearance between the TF coil and the cryostat, the cryostat volume, the vacuum vessel mass, and the sum of internal vacuum vessel and cryostat masses. - """ # Cryostat radius [m] @@ -85,13 +83,8 @@ def external_cryo_geometry() -> None: fwbs_variables.vol_vv + fwbs_variables.vol_cryostat ) * fwbs_variables.den_steel - def cryostat_output(self) -> None: - """ - Outputs the cryostat geometry details to the output file. - - Returns: - None - """ + def cryostat_output(self): + """Outputs the cryostat geometry details to the output file.""" po.oheadr(self.outfile, "Cryostat build") po.ovarrf( @@ -110,7 +103,7 @@ def cryostat_output(self) -> None: ) po.ovarrf( self.outfile, - "Cryostat intenral half height (m)", + "Cryostat internal half height (m)", "(z_cryostat_half_inside)", fwbs_variables.z_cryostat_half_inside, "OP ", diff --git a/process/cs_fatigue.py b/process/cs_fatigue.py index b0e7c7ba4d..10d3a1cdd3 100644 --- a/process/cs_fatigue.py +++ b/process/cs_fatigue.py @@ -17,7 +17,21 @@ def ncycle( dz_cs_turn_conduit, dr_cs_turn_conduit, ): - """ """ + """ + + Parameters + ---------- + max_hoop_stress : + + residual_stress : + + t_crack_vertical : + + dz_cs_turn_conduit : + + dr_cs_turn_conduit : + + """ # Default Parameters for SS 316LN from # X. Sarasola et al, IEEE Transactions on Applied Superconductivity, # vol. 30, no. 4, pp. 1-5, June 2020, Art no. 4200705 diff --git a/process/current_drive.py b/process/current_drive.py index 48f1213fe4..402eb4b810 100644 --- a/process/current_drive.py +++ b/process/current_drive.py @@ -24,10 +24,18 @@ def __init__(self, plasma_profile: PlasmaProfile): def iternb(self): """Routine to calculate ITER Neutral Beam current drive parameters - author: P J Knight, CCFE, Culham Science Centre - effnbss : output real : neutral beam current drive efficiency (A/W) - f_p_beam_injected_ions : output real : fraction of NB power given to ions - fshine : output real : shine-through fraction of beam + + Returns + ------- + effnbss: + neutral beam current drive efficiency (A/W) + f_p_beam_injected_ions: + fraction of NB power given to ions + fshine: + shine-through fraction of beam + + Notes + ----- This routine calculates the current drive parameters for a neutral beam system, based on the 1990 ITER model. ITER Physics Design Guidelines: 1989 [IPDG89], N. A. Uckan et al, @@ -109,10 +117,18 @@ def iternb(self): def culnbi(self): """Routine to calculate Neutral Beam current drive parameters - author: P J Knight, CCFE, Culham Science Centre - effnbss : output real : neutral beam current drive efficiency (A/W) - f_p_beam_injected_ions : output real : fraction of NB power given to ions - fshine : output real : shine-through fraction of beam + + Returns + ------- + effnbss: + neutral beam current drive efficiency (A/W) + f_p_beam_injected_ions: + fraction of NB power given to ions + fshine: + shine-through fraction of beam + + Notes + ----- This routine calculates Neutral Beam current drive parameters using the corrections outlined in AEA FUS 172 to the ITER method.

The result cannot be guaranteed for devices with aspect ratios far @@ -222,20 +238,8 @@ def etanb2( """Routine to find neutral beam current drive efficiency using the ITER 1990 formulation, plus correction terms outlined in Culham Report AEA FUS 172 - author: P J Knight, CCFE, Culham Science Centre - m_beam_amu : input real : beam ion mass (amu) - alphan : input real : density profile factor - alphat : input real : temperature profile factor - aspect : input real : aspect ratio - nd_plasma_electrons_vol_avg : input real : volume averaged electron density (m**-3) - nd_plasma_electron_line : input real : line averaged electron density (m**-3) - e_beam_kev : input real : neutral beam energy (keV) - f_radius_beam_tangency_rmajor : input real : R_tangent / R_major for neutral beam injection - fshine : input real : shine-through fraction of beam - rmajor : input real : plasma major radius (m) - rminor : input real : plasma minor radius (m) - temp_plasma_electron_density_weighted_kev : input real : density weighted average electron temperature (keV) - zeff : input real : plasma effective charge + + This routine calculates the current drive efficiency in A/W of a neutral beam system, based on the 1990 ITER model, plus correction terms outlined in Culham Report AEA FUS 172. @@ -243,6 +247,35 @@ def etanb2( AEA FUS 172: Physics Assessment for the European Reactor Study ITER Physics Design Guidelines: 1989 [IPDG89], N. A. Uckan et al, ITER Documentation Series No.10, IAEA/ITER/DS/10, IAEA, Vienna, 1990 + + Parameters + ---------- + m_beam_amu: + beam ion mass (amu) + alphan: + density profile factor + alphat: + temperature profile factor + aspect: + aspect ratio + nd_plasma_electrons_vol_avg: + volume averaged electron density (m**-3) + nd_plasma_electron_line: + line averaged electron density (m**-3) + e_beam_kev: + neutral beam energy (keV) + f_radius_beam_tangency_rmajor: + R_tangent / R_major for neutral beam injection + fshine: + shine-through fraction of beam + rmajor: + plasma major radius (m) + rminor: + plasma minor radius (m) + temp_plasma_electron_density_weighted_kev: + density weighted average electron temperature (keV) + zeff: + plasma effective charge """ # Charge of beam ions zbeam = 1.0 @@ -285,7 +318,6 @@ def etanb2( # Normalisation to allow results to be valid for # non-ITER plasma size and density: - # Line averaged electron density (10**20 m**-3) normalised to ITER nnorm = 1.0 @@ -349,20 +381,37 @@ def etanb( ): """Routine to find neutral beam current drive efficiency using the ITER 1990 formulation - author: P J Knight, CCFE, Culham Science Centre - m_beam_amu : input real : beam ion mass (amu) - alphan : input real : density profile factor - alphat : input real : temperature profile factor - aspect : input real : aspect ratio - nd_plasma_electrons_vol_avg : input real : volume averaged electron density (m**-3) - ebeam : input real : neutral beam energy (keV) - rmajor : input real : plasma major radius (m) - temp_plasma_electron_density_weighted_kev : input real : density weighted average electron temp. (keV) - zeff : input real : plasma effective charge + + Parameters + ---------- + m_beam_amu: + beam ion mass (amu) + alphan: + density profile factor + alphat: + temperature profile factor + aspect: + aspect ratio + nd_plasma_electrons_vol_avg: + volume averaged electron density (m**-3) + ebeam: + neutral beam energy (keV) + rmajor: + plasma major radius (m) + temp_plasma_electron_density_weighted_kev: + density weighted average electron temp. (keV) + zeff: + plasma effective charge + + Notes + ----- This routine calculates the current drive efficiency of a neutral beam system, based on the 1990 ITER model. ITER Physics Design Guidelines: 1989 [IPDG89], N. A. Uckan et al, ITER Documentation Series No.10, IAEA/ITER/DS/10, IAEA, Vienna, 1990 + + + """ zbeam = 1.0 @@ -402,15 +451,27 @@ def etanb( def sigbeam(self, eb, te, ne, rnhe, rnc, rno, rnfe): """Calculates the stopping cross-section for a hydrogen - beam in a fusion plasma - author: P J Knight, CCFE, Culham Science Centre - eb : input real : beam energy (kev/amu) - te : input real : electron temperature (keV) - ne : input real : electron density (10^20m-3) - rnhe : input real : alpha density / ne - rnc : input real : carbon density /ne - rno : input real : oxygen density /ne - rnfe : input real : iron density /ne + beam in a fusion plasma + + Parameters + ---------- + eb: + beam energy (kev/amu) + te: + electron temperature (keV) + ne: + electron density (10^20m-3) + rnhe: + alpha density / ne + rnc: + carbon density /ne + rno: + oxygen density /ne + rnfe: + iron density /ne + + Notes + ----- This function calculates the stopping cross-section (m^-2) for a hydrogen beam in a fusion plasma. Janev, Boley and Post, Nuclear Fusion 29 (1989) 2125 @@ -503,17 +564,33 @@ def cfnbi( xlmbda, ): """Routine to calculate the fraction of the fast particle energy - coupled to the ions - author: P J Knight, CCFE, Culham Science Centre - afast : input real : mass of fast particle (units of proton mass) - efast : input real : energy of fast particle (keV) - te : input real : density weighted average electron temp. (keV) - ne : input real : volume averaged electron density (m**-3) - nd : input real : deuterium beam density (m**-3) - nt : input real : tritium beam density (m**-3) - n_charge_plasma_effective_mass_weighted_vol_avg : input real : mass weighted plasma effective charge - xlmbda : input real : ion-electron coulomb logarithm - f_p_beam_injected_ions : output real : fraction of fast particle energy coupled to ions + coupled to the ions + + Parameters + ---------- + afast: + mass of fast particle (units of proton mass) + efast: + energy of fast particle (keV) + te: + density weighted average electron temp. (keV) + ne: + volume averaged electron density (m**-3) + nd: + deuterium beam density (m**-3) + nt: + tritium beam density (m**-3) + n_charge_plasma_effective_mass_weighted_vol_avg: + mass weighted plasma effective charge + xlmbda: + ion-electron coulomb logarithm + + Returns + ------- + f_p_beam_injected_ions: + fraction of fast particle energy coupled to ions + Notes + ----- This routine calculates the fast particle energy coupled to the ions in the neutral beam system. """ @@ -556,16 +633,24 @@ def cfnbi( def xlmbdabi(self, mb, mth, eb, t, nelec): """Calculates the Coulomb logarithm for ion-ion collisions - author: P J Knight, CCFE, Culham Science Centre - mb : input real : mass of fast particle (units of proton mass) - mth : input real : mass of background ions (units of proton mass) - eb : input real : energy of fast particle (keV) - t : input real : density weighted average electron temp. (keV) - nelec : input real : volume averaged electron density (m**-3) + This function calculates the Coulomb logarithm for ion-ion collisions where the relative velocity may be large compared with the background ('mt') thermal velocity. Mikkelson and Singer, Nuc Tech/Fus, 4, 237 (1983) + + Parameters + ---------- + mb: + mass of fast particle (units of proton mass) + mth: + mass of background ions (units of proton mass) + eb: + energy of fast particle (keV) + t: + density weighted average electron temp. (keV) + nelec: + volume averaged electron density (m**-3) """ x1 = (t / 10.0) * (eb / 1000.0) * mb / (nelec / 1e20) @@ -581,12 +666,15 @@ def __init__(self, plasma_profile: PlasmaProfile): def culecd(self): """Routine to calculate Electron Cyclotron current drive efficiency - author: M R O'Brien, CCFE, Culham Science Centre - author: P J Knight, CCFE, Culham Science Centre - effrfss : output real : electron cyclotron current drive efficiency (A/W) + This routine calculates the current drive parameters for a electron cyclotron system, based on the AEA FUS 172 model. AEA FUS 172: Physics Assessment for the European Reactor Study + + Returns + ------- + : + electron cyclotron current drive efficiency (A/W) """ rrr = 1.0e0 / 3.0e0 @@ -642,19 +730,11 @@ def culecd(self): def eccdef(self, tlocal, epsloc, zlocal, cosang, coulog): """Routine to calculate Electron Cyclotron current drive efficiency - author: M R O'Brien, CCFE, Culham Science Centre - author: P J Knight, CCFE, Culham Science Centre - tlocal : input real : local electron temperature (keV) - epsloc : input real : local inverse aspect ratio - zlocal : input real : local plasma effective charge - cosang : input real : cosine of the poloidal angle at which ECCD takes - place (+1 outside, -1 inside) - coulog : input real : local coulomb logarithm for ion-electron collisions - ecgam : output real : normalised current drive efficiency (A/W m**-2) + This routine calculates the current drive parameters for a electron cyclotron system, based on the AEA FUS 172 model. It works out the ECCD efficiency using the formula due to Cohen - quoted in the ITER Physics Design Guidelines : 1989 + quoted in the ITER Physics Design Guidelines: 1989 (but including division by the Coulomb Logarithm omitted from IPDG89). We have assumed gamma**2-1 << 1, where gamma is the relativistic factor. The notation follows that in IPDG89. @@ -664,6 +744,25 @@ def eccdef(self, tlocal, epsloc, zlocal, cosang, coulog): AEA FUS 172: Physics Assessment for the European Reactor Study ITER Physics Design Guidelines: 1989 [IPDG89], N. A. Uckan et al, ITER Documentation Series No.10, IAEA/ITER/DS/10, IAEA, Vienna, 1990 + + Parameters + ---------- + tlocal: + local electron temperature (keV) + epsloc: + local inverse aspect ratio + zlocal: + local plasma effective charge + cosang: + cosine of the poloidal angle at which ECCD takes + place (+1 outside, -1 inside) + coulog: + local coulomb logarithm for ion-electron collisions + + Returns + ------- + ecgam: + normalised current drive efficiency (A/W m**-2) """ mcsq = ( constants.ELECTRON_MASS * 2.9979e8**2 / (1.0e3 * constants.ELECTRON_VOLT) @@ -718,28 +817,28 @@ def electron_cyclotron_fenstermacher( dene20: float, dlamee: float, ) -> float: - """ - Routine to calculate Fenstermacher Electron Cyclotron heating efficiency. - - :param temp_plasma_electron_density_weighted_kev: Density weighted average electron temperature keV. - :type temp_plasma_electron_density_weighted_kev: float - :param zeff: Plasma effective charge. - :type zeff: float - :param rmajor: Major radius of the plasma in meters. - :type rmajor: float - :param dene20: Volume averaged electron density in 1x10^20 m^-3. - :type dene20: float - :param dlamee: Electron collision frequency in 1/s. - :type dlamee: float - - :return: The calculated electron cyclotron heating efficiency in A/W. - :rtype: float - - :notes: - - :references: - - T.C. Hender et al., 'Physics Assessment of the European Reactor Study', AEA FUS 172, 1992. - + """Routine to calculate Fenstermacher Electron Cyclotron heating efficiency. + + Parameters + ---------- + temp_plasma_electron_density_weighted_kev: float + Density weighted average electron temperature keV. + zeff: float + Plasma effective charge. + rmajor: float + Major radius of the plasma in meters. + dene20: float + Volume averaged electron density in 1x10^20 m^-3. + dlamee: float + Electron collision frequency in 1/s. + + Returns + ------- + float + The calculated electron cyclotron heating efficiency in A/W. + + references: + - T.C. Hender et al., 'Physics Assessment of the European Reactor Study', AEA FUS 172, 1992. """ return (0.21e0 * temp_plasma_electron_density_weighted_kev) / ( @@ -756,37 +855,40 @@ def electron_cyclotron_freethy( n_ecrh_harmonic: int, i_ecrh_wave_mode: int, ) -> float: - """ - Calculate the Electron Cyclotron current drive efficiency using the Freethy model. + """Calculate the Electron Cyclotron current drive efficiency using the Freethy model. This function computes the ECCD efficiency based on the electron temperature, effective charge, major radius, electron density, magnetic field, harmonic number, and wave mode. - :param te: Volume averaged electron temperature in keV. - :type te: float - :param zeff: Plasma effective charge. - :type zeff: float - :param rmajor: Major radius of the plasma in meters. - :type rmajor: float - :param nd_plasma_electrons_vol_avg: Volume averaged electron density in m^-3. - :type nd_plasma_electrons_vol_avg: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field in Tesla. - :type b_plasma_toroidal_on_axis: float - :param n_ecrh_harmonic: Cyclotron harmonic number (fundamental used as default). - :type n_ecrh_harmonic: int - :param i_ecrh_wave_mode: Wave mode switch (0 for O-mode, 1 for X-mode). - :type i_ecrh_wave_mode: int - - :return: The calculated absolute ECCD efficiency in A/W. - :rtype: float - - :notes: - - Plasma coupling only occurs if the plasma cut-off is below the cyclotron harmonic. - - The density factor accounts for this behavior. - - :references: - - Freethy, S., PROCESS issue #2994. + Parameters + ---------- + te: float + Volume averaged electron temperature in keV. + zeff: float + Plasma effective charge. + rmajor: float + Major radius of the plasma in meters. + nd_plasma_electrons_vol_avg: float + Volume averaged electron density in m^-3. + b_plasma_toroidal_on_axis: float + Toroidal magnetic field in Tesla. + n_ecrh_harmonic: int + Cyclotron harmonic number (fundamental used as default). + i_ecrh_wave_mode: int + Wave mode switch (0 for O-mode, 1 for X-mode). + + Returns + ------- + float + The calculated absolute ECCD efficiency in A/W. + + notes: + - Plasma coupling only occurs if the plasma cut-off is below the cyclotron harmonic. + - The density factor accounts for this behavior. + + references: + - Freethy, S., PROCESS issue #2994. """ # Cyclotron frequency @@ -835,12 +937,7 @@ def electron_cyclotron_freethy( def legend(self, zlocal, arg): """Routine to calculate Legendre function and its derivative - author: M R O'Brien, CCFE, Culham Science Centre - author: P J Knight, CCFE, Culham Science Centre - zlocal : input real : local plasma effective charge - arg : input real : argument of Legendre function - palpha : output real : value of Legendre function - palphap : output real : derivative of Legendre function + This routine calculates the Legendre function palpha of argument arg and order alpha = -0.5 + i sqrt(xisq), @@ -856,6 +953,20 @@ def legend(self, zlocal, arg): gam2 are the Gamma functions of arguments 0.5*(1+alpha) and 0.5*(2+alpha) respectively. Abramowitz and Stegun, equation 8.12.1 + + Parameters + ---------- + zlocal: + local plasma effective charge + arg: + argument of Legendre function + + Returns + ------- + palphap: + derivative of Legendre function + palpha: + value of Legendre function """ if abs(arg) > (1.0e0 + 1.0e-10): raise ProcessValueError("Invalid argument", arg=arg) @@ -906,30 +1017,35 @@ def ion_cyclotron_ipdg89( rmajor: float, dene20: float, ) -> float: - """ - Routine to calculate IPDG89 Ion Cyclotron heating efficiency. + """Routine to calculate IPDG89 Ion Cyclotron heating efficiency. This function computes the ion cyclotron heating efficiency based on the electron temperature, effective charge, major radius, and electron density. - :param temp_plasma_electron_density_weighted_kev: Density weighted average electron temperature keV. - :type temp_plasma_electron_density_weighted_kev: float - :param zeff: Plasma effective charge. - :type zeff: float - :param rmajor: Major radius of the plasma in meters. - :type rmajor: float - :param nd_plasma_electrons_vol_avg: Volume averaged electron density in 1x10^20 m^-3. - :type nd_plasma_electrons_vol_avg: float - - :return: The calculated ion cyclotron heating efficiency in A/W. - :rtype: float - - :notes: + Parameters + ---------- + temp_plasma_electron_density_weighted_kev: float + Density weighted average electron temperature keV. + zeff: float + Plasma effective charge. + rmajor: float + Major radius of the plasma in meters. + nd_plasma_electrons_vol_avg: float + Volume averaged electron density in 1x10^20 m^-3. + + Returns + ------- + float + The calculated ion cyclotron heating efficiency in A/W. + + Notes + ----- - The 0.1 term is to convert the temperature into 10 keV units - - The original formula is for the normalised current drive efficnecy - hence the addition of the density and majro radius terms to get back to an absolute value + - The original formula is for the normalised current drive efficiency + hence the addition of the density and majro radius terms to get back to an absolute value - :references: + References + ---------- - N.A. Uckan and ITER Physics Group, 'ITER Physics Design Guidelines: 1989', https://inis.iaea.org/collection/NCLCollectionStore/_Public/21/068/21068960.pdf @@ -955,34 +1071,39 @@ def electron_bernstein_freethy( n_ecrh_harmonic: int, xi_ebw: float, ) -> float: - """ - Calculate the Electron Bernstein Wave (EBW) current drive efficiency using the Freethy model. + """Calculate the Electron Bernstein Wave (EBW) current drive efficiency using the Freethy model. This function computes the EBW current drive efficiency based on the electron temperature, major radius, electron density, magnetic field, harmonic number, and scaling factor. - :param te: Volume averaged electron temperature in keV. - :type te: float - :param rmajor: Major radius of the plasma in meters. - :type rmajor: float - :param dene20: Volume averaged electron density in units of 10^20 m^-3. - :type dene20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field in Tesla. - :type b_plasma_toroidal_on_axis: float - :param n_ecrh_harmonic: Cyclotron harmonic number (fundamental used as default). - :type n_ecrh_harmonic: int - :param xi_ebw: Scaling factor for EBW efficiency. - :type xi_ebw: float - - :return: The calculated absolute EBW current drive efficiency in A/W. - :rtype: float - - :notes: - - EBWs can only couple to plasma if the cyclotron harmonic is above the plasma density cut-off. - - The density factor accounts for this behavior. - - :references: - - Freethy, S., PROCESS issue #1262. + Parameters + ---------- + te: float + Volume averaged electron temperature in keV. + rmajor: float + Major radius of the plasma in meters. + dene20: float + Volume averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis: float + Toroidal magnetic field in Tesla. + n_ecrh_harmonic: int + Cyclotron harmonic number (fundamental used as default). + xi_ebw: float + Scaling factor for EBW efficiency. + + Returns + ------- + float + The calculated absolute EBW current drive efficiency in A/W. + + Notes + ----- + - EBWs can only couple to plasma if the cyclotron harmonic is above the plasma density cut-off. + - The density factor accounts for this behavior. + + References + ---------- + - Freethy, S., PROCESS issue #1262. """ # Normalised current drive efficiency gamma @@ -1028,8 +1149,8 @@ def __init__(self, plasma_profile: PlasmaProfile): def cullhy(self): """Routine to calculate Lower Hybrid current drive efficiency - author: P J Knight, CCFE, Culham Science Centre - effrfss : output real : lower hybrid current drive efficiency (A/W) + + effrfss: output real: lower hybrid current drive efficiency (A/W) This routine calculates the current drive parameters for a lower hybrid system, based on the AEA FUS 172 model. AEA FUS 172: Physics Assessment for the European Reactor Study @@ -1099,8 +1220,8 @@ def cullhy(self): def lhrad(self): """Routine to calculate Lower Hybrid wave absorption radius - author: P J Knight, CCFE, Culham Science Centre - rratio : output real : minor radius of penetration / rminor + + rratio: output real: minor radius of penetration / rminor This routine determines numerically the minor radius at which the damping of Lower Hybrid waves occurs, using a Newton-Raphson method. AEA FUS 172: Physics Assessment for the European Reactor Study @@ -1161,10 +1282,21 @@ def lhrad(self): def lheval(self, drfind, rratio): """Routine to evaluate the difference between electron energy expressions required to find the Lower Hybrid absorption radius - author: P J Knight, CCFE, Culham Science Centre - drfind : input real : correction to parallel refractive index - rratio : input real : guess for radius of penetration / rminor - ediff : output real : difference between the E values (keV) + + Parameters + ---------- + drfind: + correction to parallel refractive index + rratio: + guess for radius of penetration / rminor + + Returns + ------- + ediff: + difference between the E values (keV) + + Notes + ----- This routine evaluates the difference between the values calculated from the two equations for the electron energy E, given in AEA FUS 172, p.58. This difference is used to locate the Lower Hybrid @@ -1225,26 +1357,31 @@ def lheval(self, drfind, rratio): def lower_hybrid_fenstermacher( self, te: float, rmajor: float, dene20: float ) -> float: - """ - Calculate the lower hybrid frequency using the Fenstermacher formula. + """Calculate the lower hybrid frequency using the Fenstermacher formula. This function computes the lower hybrid frequency based on the electron temperature, major radius, and electron density. - :param te: Volume averaged electron temperature in keV. - :type te: float - :param rmajor: Major radius of the plasma in meters. - :type rmajor: float - :param dene20: Volume averaged electron density in units of 10^20 m^-3. - :type dene20: float - - :return: The calculated absolute current drive efficiency in A/W. - :rtype: float - - :notes: - - This forumla was originally in the Oak RidgeSystems Code, attributed to Fenstermacher + Parameters + ---------- + te: float + Volume averaged electron temperature in keV. + rmajor: float + Major radius of the plasma in meters. + dene20: float + Volume averaged electron density in units of 10^20 m^-3. + + Returns + ------- + float + The calculated absolute current drive efficiency in A/W. + + Notes + ----- + - This forumla was originally in the Oak RidgeSystems Code, attributed to Fenstermacher and is used in the AEA FUS 172 report. - :references: + References + ---------- - T.C. Hender et al., 'Physics Assessment of the European Reactor Study', AEA FUS 172, 1992. - R.L.Reid et al, Oak Ridge Report ORNL/FEDC-87-7, 1988 @@ -1255,29 +1392,32 @@ def lower_hybrid_fenstermacher( def lower_hybrid_ehst( self, te: float, beta: float, rmajor: float, dene20: float, zeff: float ) -> float: - """ - Calculate the Lower Hybrid current drive efficiency using the Ehst model. + """Calculate the Lower Hybrid current drive efficiency using the Ehst model. This function computes the current drive efficiency based on the electron temperature, beta, major radius, electron density, and effective charge. - :param te: Volume averaged electron temperature in keV. - :type te: float - :param beta: Plasma beta value (ratio of plasma pressure to magnetic pressure). - :type beta: float - :param rmajor: Major radius of the plasma in meters. - :type rmajor: float - :param dene20: Volume averaged electron density in units of 10^20 m^-3. - :type dene20: float - :param zeff: Plasma effective charge. - :type zeff: float - - :return: The calculated absolute current drive efficiency in A/W. - :rtype: float - - :notes: - - :references: + Parameters + ---------- + te: float + Volume averaged electron temperature in keV. + beta: float + Plasma beta value (ratio of plasma pressure to magnetic pressure). + rmajor: float + Major radius of the plasma in meters. + dene20: float + Volume averaged electron density in units of 10^20 m^-3. + zeff: float + Plasma effective charge. + + Returns + ------- + float + The calculated absolute current drive efficiency in A/W. + + + References + ---------- - Ehst, D.A., and Karney, C.F.F., "Lower Hybrid Current Drive in Tokamaks", Nuclear Fusion, 31(10), 1933-1949, 1991. """ @@ -1312,17 +1452,21 @@ def __init__( self.neutral_beam = neutral_beam self.electron_bernstein = electron_bernstein - def cudriv(self) -> None: - """ - Calculate the current drive power requirements. + def cudriv(self): + """Calculate the current drive power requirements. This method computes the power requirements of the current drive system using a choice of models for the current drive efficiency. - :param output: Flag indicating whether to write results to the output file. - :type output: bool + Parameters + ---------- + output: bool + Flag indicating whether to write results to the output file. - :raises ProcessValueError: If an invalid current drive switch is encountered. + Raises + ------ + ProcessValueError + If an invalid current drive switch is encountered. """ current_drive_variables.p_hcd_ecrh_injected_total_mw = 0.0e0 @@ -1357,64 +1501,79 @@ def cudriv(self) -> None: # Define a dictionary of lambda functions for current drive efficiency models hcd_models = { - 1: lambda: self.lower_hybrid.lower_hybrid_fenstermacher( - physics_variables.temp_plasma_electron_vol_avg_kev, - physics_variables.rmajor, - dene20, - ) - * current_drive_variables.feffcd, - 2: lambda: self.ion_cyclotron.ion_cyclotron_ipdg89( - temp_plasma_electron_density_weighted_kev=physics_variables.temp_plasma_electron_density_weighted_kev, - zeff=physics_variables.n_charge_plasma_effective_vol_avg, - rmajor=physics_variables.rmajor, - dene20=dene20, - ) - * current_drive_variables.feffcd, - 3: lambda: self.electron_cyclotron.electron_cyclotron_fenstermacher( - temp_plasma_electron_density_weighted_kev=physics_variables.temp_plasma_electron_density_weighted_kev, - rmajor=physics_variables.rmajor, - dene20=dene20, - dlamee=physics_variables.dlamee, - ) - * current_drive_variables.feffcd, - 4: lambda: self.lower_hybrid.lower_hybrid_ehst( - te=physics_variables.temp_plasma_electron_vol_avg_kev, - beta=physics_variables.beta_total_vol_avg, - rmajor=physics_variables.rmajor, - dene20=dene20, - zeff=physics_variables.n_charge_plasma_effective_vol_avg, - ) - * current_drive_variables.feffcd, + 1: lambda: ( + self.lower_hybrid.lower_hybrid_fenstermacher( + physics_variables.temp_plasma_electron_vol_avg_kev, + physics_variables.rmajor, + dene20, + ) + * current_drive_variables.feffcd + ), + 2: lambda: ( + self.ion_cyclotron.ion_cyclotron_ipdg89( + temp_plasma_electron_density_weighted_kev=physics_variables.temp_plasma_electron_density_weighted_kev, + zeff=physics_variables.n_charge_plasma_effective_vol_avg, + rmajor=physics_variables.rmajor, + dene20=dene20, + ) + * current_drive_variables.feffcd + ), + 3: lambda: ( + self.electron_cyclotron.electron_cyclotron_fenstermacher( + temp_plasma_electron_density_weighted_kev=physics_variables.temp_plasma_electron_density_weighted_kev, + rmajor=physics_variables.rmajor, + dene20=dene20, + dlamee=physics_variables.dlamee, + ) + * current_drive_variables.feffcd + ), + 4: lambda: ( + self.lower_hybrid.lower_hybrid_ehst( + te=physics_variables.temp_plasma_electron_vol_avg_kev, + beta=physics_variables.beta_total_vol_avg, + rmajor=physics_variables.rmajor, + dene20=dene20, + zeff=physics_variables.n_charge_plasma_effective_vol_avg, + ) + * current_drive_variables.feffcd + ), 5: lambda: ( self.neutral_beam.iternb()[0] * current_drive_variables.feffcd ), 6: lambda: self.lower_hybrid.cullhy() * current_drive_variables.feffcd, - 7: lambda: self.electron_cyclotron.culecd() - * current_drive_variables.feffcd, + 7: lambda: ( + self.electron_cyclotron.culecd() * current_drive_variables.feffcd + ), 8: lambda: ( self.neutral_beam.culnbi()[0] * current_drive_variables.feffcd ), - 10: lambda: current_drive_variables.eta_cd_norm_ecrh - / (dene20 * physics_variables.rmajor), - 12: lambda: self.electron_bernstein.electron_bernstein_freethy( - te=physics_variables.temp_plasma_electron_vol_avg_kev, - rmajor=physics_variables.rmajor, - dene20=dene20, - b_plasma_toroidal_on_axis=physics_variables.b_plasma_toroidal_on_axis, - n_ecrh_harmonic=current_drive_variables.n_ecrh_harmonic, - xi_ebw=current_drive_variables.xi_ebw, - ) - * current_drive_variables.feffcd, - 13: lambda: self.electron_cyclotron.electron_cyclotron_freethy( - te=physics_variables.temp_plasma_electron_vol_avg_kev, - zeff=physics_variables.n_charge_plasma_effective_vol_avg, - rmajor=physics_variables.rmajor, - nd_plasma_electrons_vol_avg=physics_variables.nd_plasma_electrons_vol_avg, - b_plasma_toroidal_on_axis=physics_variables.b_plasma_toroidal_on_axis, - n_ecrh_harmonic=current_drive_variables.n_ecrh_harmonic, - i_ecrh_wave_mode=current_drive_variables.i_ecrh_wave_mode, - ) - * current_drive_variables.feffcd, + 10: lambda: ( + current_drive_variables.eta_cd_norm_ecrh + / (dene20 * physics_variables.rmajor) + ), + 12: lambda: ( + self.electron_bernstein.electron_bernstein_freethy( + te=physics_variables.temp_plasma_electron_vol_avg_kev, + rmajor=physics_variables.rmajor, + dene20=dene20, + b_plasma_toroidal_on_axis=physics_variables.b_plasma_toroidal_on_axis, + n_ecrh_harmonic=current_drive_variables.n_ecrh_harmonic, + xi_ebw=current_drive_variables.xi_ebw, + ) + * current_drive_variables.feffcd + ), + 13: lambda: ( + self.electron_cyclotron.electron_cyclotron_freethy( + te=physics_variables.temp_plasma_electron_vol_avg_kev, + zeff=physics_variables.n_charge_plasma_effective_vol_avg, + rmajor=physics_variables.rmajor, + nd_plasma_electrons_vol_avg=physics_variables.nd_plasma_electrons_vol_avg, + b_plasma_toroidal_on_axis=physics_variables.b_plasma_toroidal_on_axis, + n_ecrh_harmonic=current_drive_variables.n_ecrh_harmonic, + i_ecrh_wave_mode=current_drive_variables.i_ecrh_wave_mode, + ) + * current_drive_variables.feffcd + ), } # Assign outputs for models that return multiple values @@ -1953,33 +2112,37 @@ def calculate_dimensionless_current_drive_efficiency( c_hcd_driven: float, p_hcd_injected: float, ) -> float: - """ - Calculate the dimensionless current drive efficiency, ζ. - - This function computes the dimensionless current drive efficiency - based on the average electron density, major radius, and electron temperature. - - :param nd_plasma_electrons_vol_avg: Volume averaged electron density in m^-3. - :type nd_plasma_electrons_vol_avg: float - :param rmajor: Major radius of the plasma in meters. - :type rmajor: float - :param temp_plasma_electron_vol_avg_kev: Volume averaged electron temperature in keV. - :type temp_plasma_electron_vol_avg_kev: float - :param c_hcd_driven: Current driven by the heating and current drive system. - :type c_hcd_driven: float - :param p_hcd_injected: Power injected by the heating and current drive system. - :type p_hcd_injected: float - :return: The calculated dimensionless current drive efficiency. - :rtype: float - - :references: - - E. Poli et al., “Electron-cyclotron-current-drive efficiency in DEMO plasmas,” - Nuclear Fusion, vol. 53, no. 1, pp. 013011-013011, Dec. 2012, - doi: https://doi.org/10.1088/0029-5515/53/1/013011. - ‌ - - T. C. Luce et al., “Generation of Localized Noninductive Current by Electron Cyclotron Waves on the DIII-D Tokamak,” - Physical Review Letters, vol. 83, no. 22, pp. 4550-4553, Nov. 1999, - doi: https://doi.org/10.1103/physrevlett.83.4550. + """Calculate the dimensionless current drive efficiency, ζ. + + This function computes the dimensionless current drive efficiency + based on the average electron density, major radius, and electron temperature. + + Parameters + ---------- + nd_plasma_electrons_vol_avg: + Volume averaged electron density in m^-3. + rmajor: + Major radius of the plasma in meters. + temp_plasma_electron_vol_avg_kev: + Volume averaged electron temperature in keV. + c_hcd_driven: + Current driven by the heating and current drive system. + p_hcd_injected: + Power injected by the heating and current drive system. + + Returns + ------- + float + The calculated dimensionless current drive efficiency. + + References + ---------- + - E. Poli et al., “Electron-cyclotron-current-drive efficiency in DEMO plasmas,” + Nuclear Fusion, vol. 53, no. 1, pp. 013011-013011, Dec. 2012, + doi: https://doi.org/10.1088/0029-5515/53/1/013011. + - T. C. Luce et al., “Generation of Localized Noninductive Current by Electron Cyclotron Waves on the DIII-D Tokamak,” + Physical Review Letters, vol. 83, no. 22, pp. 4550-4553, Nov. 1999, + doi: https://doi.org/10.1103/physrevlett.83.4550. """ return ( @@ -1992,8 +2155,7 @@ def calculate_dimensionless_current_drive_efficiency( ) def output_current_drive(self): - """ - Output the current drive information to the output file. + """Output the current drive information to the output file. This method writes the current drive information to the output file. """ diff --git a/process/data_structure/blanket_library.py b/process/data_structure/blanket_library.py index b4e240243a..2cd99c3645 100644 --- a/process/data_structure/blanket_library.py +++ b/process/data_structure/blanket_library.py @@ -5,7 +5,7 @@ - component_masses - thermo_hydraulic_model -author: G Graham, CCFE, Culham Science Centre + Acronyms for this module: diff --git a/process/data_structure/ccfe_hcpb_module.py b/process/data_structure/ccfe_hcpb_module.py index 3d9e9d0737..78b820c33e 100644 --- a/process/data_structure/ccfe_hcpb_module.py +++ b/process/data_structure/ccfe_hcpb_module.py @@ -1,4 +1,4 @@ -"""author: J Morris (UKAEA) +""" This module contains the PROCESS CCFE HCPB blanket model based on CCFE HCPB model from the PROCESS engineering paper PROCESS Engineering paper (M. Kovari et al.) diff --git a/process/data_structure/cost_variables.py b/process/data_structure/cost_variables.py index 0c772c94bd..26f2799078 100644 --- a/process/data_structure/cost_variables.py +++ b/process/data_structure/cost_variables.py @@ -699,7 +699,6 @@ UCCO: float = 350.0 - """unit cost for control buildings (M$/m3)""" @@ -772,7 +771,6 @@ UCFPR: float = 4.4e7 - """cost of 60g/day tritium processing unit ($)""" diff --git a/process/data_structure/current_drive_variables.py b/process/data_structure/current_drive_variables.py index 9fc62d5001..1b7f8ed51f 100644 --- a/process/data_structure/current_drive_variables.py +++ b/process/data_structure/current_drive_variables.py @@ -1,4 +1,4 @@ -"""author: J. Morris (UKAEA) +""" Module containing global variables relating to the current drive system """ diff --git a/process/data_structure/dcll_variables.py b/process/data_structure/dcll_variables.py index 57dd20c3ff..47b5822032 100644 --- a/process/data_structure/dcll_variables.py +++ b/process/data_structure/dcll_variables.py @@ -1,6 +1,6 @@ """This module contains the Dual Coolant Lead Lithium (DCLL) specific submods of PROCESSS. -author: G. Graham, CCFE + Acronyms for this module: diff --git a/process/data_structure/first_wall_variables.py b/process/data_structure/first_wall_variables.py index ff50d35ab5..ff4ec2fd49 100644 --- a/process/data_structure/first_wall_variables.py +++ b/process/data_structure/first_wall_variables.py @@ -20,7 +20,7 @@ """Outboard first wall surface area [m^2]""" -def init_first_wall_variables() -> None: +def init_first_wall_variables(): """Initializes first wall variables to None""" global \ a_fw_total_full_coverage, \ diff --git a/process/data_structure/fwbs_variables.py b/process/data_structure/fwbs_variables.py index 37361a5d6d..2470a036e3 100644 --- a/process/data_structure/fwbs_variables.py +++ b/process/data_structure/fwbs_variables.py @@ -1,4 +1,4 @@ -"""author: J. Morris (UKAEA), M. Kovari (UKAEA) +""" Module containing global variables relating to the first wall, blanket and shield components ### References diff --git a/process/data_structure/heat_transport_variables.py b/process/data_structure/heat_transport_variables.py index c80a10ac1a..5b3a16eba2 100644 --- a/process/data_structure/heat_transport_variables.py +++ b/process/data_structure/heat_transport_variables.py @@ -1,4 +1,4 @@ -"""author: J. Morris, M. Kovari (UKAEA) +""" This module contains global variables relating to the heat transport system of a fusion power plant, and also those for a hydrogen production plant. ### References diff --git a/process/data_structure/ife_variables.py b/process/data_structure/ife_variables.py index 24000a9f7c..f6708f3b26 100644 --- a/process/data_structure/ife_variables.py +++ b/process/data_structure/ife_variables.py @@ -1,6 +1,6 @@ """Module containing global variables relating to the inertial fusion energy model -author: S. Muldrew (UKAEA) + Default IFE builds and material volumes are those for the SOMBRERO device. The 2-dimensional arrays have indices (region, material), where 'region' @@ -606,7 +606,6 @@ def init_ife_variables(): zu5, \ zu6, \ zu7 - """Initialise IFE variables""" bldr = 1.0 bldrc = 1.0 diff --git a/process/data_structure/neoclassics_variables.py b/process/data_structure/neoclassics_variables.py index b1ec8a9a74..606ed4df93 100644 --- a/process/data_structure/neoclassics_variables.py +++ b/process/data_structure/neoclassics_variables.py @@ -1,5 +1,5 @@ """Module containing neoclassical computations -author: J Lion, IPP Greifswald + Formulas used are described in: Beidler (2013), https://doi.org/10.1088/0029-5515/51/7/076001 """ @@ -53,7 +53,7 @@ d11_plateau: list[float] = None """Toroidal monoenergetic transport coefficient as given by the stellarator -input json file as function of nu_star, normalized by the banana value. +input json file as function of nu_star, normalised by the banana value. """ d111: list[float] = None diff --git a/process/data_structure/numerics.py b/process/data_structure/numerics.py index 768a9eafcf..d08cc11ff9 100644 --- a/process/data_structure/numerics.py +++ b/process/data_structure/numerics.py @@ -492,7 +492,6 @@ def init_numerics(): vlam, \ force_vmcon_inequality_satisfication, \ force_vmcon_inequality_tolerance - """Initialise module variables""" ioptimz = 1 minmax = 7 diff --git a/process/data_structure/pf_power_variables.py b/process/data_structure/pf_power_variables.py index 4151c1a566..9e72cfe806 100644 --- a/process/data_structure/pf_power_variables.py +++ b/process/data_structure/pf_power_variables.py @@ -1,4 +1,4 @@ -"""author: J. Morris, M. Kovari (UKAEA) +""" Module containing global variables relating to the PF coil power conversion system """ diff --git a/process/data_structure/physics_variables.py b/process/data_structure/physics_variables.py index bd3724da92..7f6adaa126 100644 --- a/process/data_structure/physics_variables.py +++ b/process/data_structure/physics_variables.py @@ -1,10 +1,10 @@ """Module containing tokamak plasma physics routines -author: P J Knight, CCFE, Culham Science Centre + N/A This module contains all the primary plasma physics routines for a tokamak device. -author: J. Morris (UKAEA) + Module containing global variables relating to the plasma physics """ @@ -423,11 +423,11 @@ gradient_length_ne: float = None -"""Max. normalized gradient length in el. density (i_plasma_pedestal==0 only)""" +"""Max. normalised gradient length in el. density (i_plasma_pedestal==0 only)""" gradient_length_te: float = None -"""Max. normalized gradient length in el. temperature (i_plasma_pedestal==0 only)""" +"""Max. normalised gradient length in el. temperature (i_plasma_pedestal==0 only)""" beta_poloidal_eps_max: float = None diff --git a/process/data_structure/scan_variables.py b/process/data_structure/scan_variables.py index 437b6fcb4b..e289bedffb 100644 --- a/process/data_structure/scan_variables.py +++ b/process/data_structure/scan_variables.py @@ -1,5 +1,5 @@ """Module containing routines to perform a parameter scan -author: P J Knight, CCFE, Culham Science Centre + None This module contains routines to perform a parameter scan over a range of values of a particular scanning variable. diff --git a/process/data_structure/superconducting_tf_coil_variables.py b/process/data_structure/superconducting_tf_coil_variables.py index 891abe413b..dbdefa2895 100644 --- a/process/data_structure/superconducting_tf_coil_variables.py +++ b/process/data_structure/superconducting_tf_coil_variables.py @@ -1,7 +1,7 @@ """Module containing superconducting TF coil routines -author: P J Knight, CCFE, Culham Science Centre -author: J Morris, CCFE, Culham Science Centre -author: S Kahn, CCFE, Culham Science Centre + + + N/A This module contains routines for calculating the parameters of a superconducting TF coil system for a diff --git a/process/data_structure/tfcoil_variables.py b/process/data_structure/tfcoil_variables.py index e7b11ebca2..3b757b99a4 100644 --- a/process/data_structure/tfcoil_variables.py +++ b/process/data_structure/tfcoil_variables.py @@ -1,4 +1,4 @@ -"""author: J. Morris, M. Kovari, S. Kahn (UKAEA) +""" Module containing global variables relating to the toroidal field coil systems ### References - ITER Magnets design description document DDD11-2 v2 2 (2009) diff --git a/process/dcll.py b/process/dcll.py index 5a85b3b662..23904296a5 100644 --- a/process/dcll.py +++ b/process/dcll.py @@ -20,7 +20,7 @@ class DCLL(InboardBlanket, OutboardBlanket): """This module contains the Dual Coolant Lead Lithium (DCLL) specific submods of PROCESSS. - author: G. Graham, CCFE + Acronyms for this module: @@ -51,7 +51,7 @@ class DCLL(InboardBlanket, OutboardBlanket): FIC switch: 0 = no FIC, Eurofer; 1 = FCIs, perfect electrical insulator, 2 = FCIs, with specified conductance i_blkt_liquid_breeder_channel_type = 0, 1, or 2 - Liquid metal duct wall conductance initilized at Eurofer value in fwbs_variables, or can input other value, used for i_blkt_liquid_breeder_channel_type = 0 or 2 + Liquid metal duct wall conductance initialised at Eurofer value in fwbs_variables, or can input other value, used for i_blkt_liquid_breeder_channel_type = 0 or 2 (bz_channel_conduct_liq) Choose if FW and BB structure are on the same pumping system (unless have diffent coolants), default is same coolant with flow IN->FW->BB->OUT @@ -123,17 +123,22 @@ def run(self, output: bool): self.write_output() def dcll_neutronics_and_power(self, output: bool): - """This is a tempory module that will use results from CCFE Bluemira nutronics work (once completed). + """This is a temporary module that will use results from CCFE Bluemira nutronics work (once completed). Database will provide values for power deposition in FW & BB, BB TBR, and nuron fluence at TF coil for different thicknesses of BB and meterial fractions. - For now we use the same method as KIT HCLL and the user can select approprite fractional + For now we use the same method as KIT HCLL and the user can select appropriate fractional values from DCLL nutronics studies as inputs. See fwbs_variables: - pnuc_fw_ratio_dcll - pnuc_blkt_ratio_dcll - f_nuc_pow_bz_struct - f_nuc_pow_bz_liq + + Parameters + ---------- + output: bool + """ if divertor_variables.n_divertors == 2: @@ -172,7 +177,7 @@ def dcll_neutronics_and_power(self, output: bool): * covf ) - # HCD Apperatus + # HCD Apparatus # No nuclear heating of the H & CD fwbs_variables.p_fw_hcd_nuclear_heat_mw = 0 @@ -467,6 +472,11 @@ def dcll_masses(self, output: bool): Side walls = 2.0D-2 m, 85.54% EUROfer, 14.46% He Top walls = 2.0D-2 m, 85.54% EUROfer, 14.46% He Bottom walls = 2.0D-2 m, 85.54% EUROfer, 14.46% He + + Parameters + ---------- + output: bool + """ # If there are FCIs then how much of the radial build is FCI? if fwbs_variables.i_blkt_liquid_breeder_channel_type > 0: diff --git a/process/divertor.py b/process/divertor.py index f833b2fc6e..c5e247049f 100644 --- a/process/divertor.py +++ b/process/divertor.py @@ -14,26 +14,25 @@ class Divertor: """Module containing divertor routines - author: P J Knight, CCFE, Culham Science Centre This module contains routines relevant for calculating the divertor parameters for a fusion power plant. """ - def __init__(self) -> None: + def __init__(self): self.outfile = constants.NOUT # output file unit - def run(self, output: bool) -> None: + def run(self, output: bool): """Routine to call the divertor model - author: J Galambos, ORNL - author: P J Knight, CCFE, Culham Science Centre This subroutine calls the divertor routine. This routine scales dimensions, powers and field levels which are used as input to the Harrison divertor model. - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not """ fwbs.p_div_nuclear_heat_total_mw = self.incident_neutron_power( @@ -99,50 +98,48 @@ def divtart( dz_divertor: float, ) -> float: """Tight aspect ratio tokamak divertor model - author: P J Knight, CCFE, Culham Science Centre This method calculates the divertor heat load for a tight aspect ratio machine, assuming that the power is evenly distributed around the divertor chamber by the action of a gaseous target. Each divertor is modeled as approximately triangular in the R,Z plane. - :param rmajor: Plasma major radius (m) - :type rmajor: float - - :param rminor: Plasma minor radius (m) - :type rminor: float - - :param triang: Plasma triangularity - :type triang: float - - :param dr_fw_plasma_gap_inboard: Inboard scrape-off width (m) - :type dr_fw_plasma_gap_inboard: float - - :param dz_xpoint_divertor: Vertical distance from X-point to divertor (m) - :type dz_xpoint_divertor: float - - :param p_plasma_separatrix_mw: Power to the divertor (MW) - :type p_plasma_separatrix_mw: float - - :param output: Indicates whether output should be written to the output file - :type output: bool - - :param i_single_null: 1 for single null configuration, 0 for double null - :type i_single_null: int - - :param dz_divertor: Vertical height of the divertor (m) - :type dz_divertor: float - - :returns: Divertor heat load for a tight aspect ratio machine (MW/m2) - :rtype: float - - :notes: + Parameters + ---------- + rmajor : float + Plasma major radius (m) + rminor : float + Plasma minor radius (m) + triang : float + Plasma triangularity + dr_fw_plasma_gap_inboard : float + Inboard scrape-off width (m) + dz_xpoint_divertor : float + Vertical distance from X-point to divertor (m) + p_plasma_separatrix_mw : float + Power to the divertor (MW) + output : bool + Indicates whether output should be written to the output file + i_single_null : int + 1 for single null configuration, 0 for double null + dz_divertor : float + Vertical height of the divertor (m) + + Returns + ------- + float + Divertor heat load for a tight aspect ratio machine (MW/m2) + + + Notes + ----- - This model assumes a tight aspect ratio tokamak with a gaseous target divertor. The divertor chamber is modeled as triangular in the R,Z plane, and the heat load is calculated based on the total divertor surface area. - The method accounts for both single null and double null configurations. - :references: + References + ---------- - Y.-K. M. Peng, J. B. Hicks, AEA Fusion, Culham (UK), "Engineering feasibility of tight aspect ratio Tokamak (spherical torus) reactors". 1990. https://inis.iaea.org/records/ey2rf-dah04 @@ -241,7 +238,6 @@ def divwade( output: bool, ) -> float: """Divertor heat load model (Wade 2020) - author: J A Foster, CCFE, Culham Science Centre This subroutine calculates the divertor heat flux for any machine, with either a single null or double null configuration. @@ -249,52 +245,35 @@ def divwade( to calculate the SOL width. This is then used with a flux expansion factor to calculate the wetted area and then the heat flux. - :param rmajor: plasma major radius (m) - :type rmajor: float - - :param rminor: plasma minor radius (m) - :type rminor: float - - :param aspect: tokamak aspect ratio - :type aspect: float - - :param b_plasma_toroidal_on_axis: toroidal field (T) - :type b_plasma_toroidal_on_axis: float - - :param b_plasma_poloidal_average: poloidal field (T) - :type b_plasma_poloidal_average: float - - :param p_plasma_separatrix_mw: power to divertor (MW) - :type p_plasma_separatrix_mw: float - - :param f_div_flux_expansion: plasma flux expansion in divertor - :type f_div_flux_expansion: float - - :param nd_plasma_separatrix_electron: electron density at separatrix (m-3) - :type nd_plasma_separatrix_electron: float - - :param deg_div_field_plate: field line angle wrt divertor target plate (degrees) - :type deg_div_field_plate: float - - :param rad_fraction_sol: SOL radiation fraction - :type rad_fraction_sol: float - - :param f_p_div_lower: fraction of power to the lower divertor in double null configuration - :type f_p_div_lower: float - - :returns: divertor heat load for a tight aspect ratio machine - :rtype: float - - :param output: indicate whether output should be written to the output file, or not - :type output: boolean - - :notes: - - :references: - - - - + Parameters + ---------- + rmajor : float + plasma major radius (m) + rminor : float + plasma minor radius (m) + aspect : float + tokamak aspect ratio + b_plasma_toroidal_on_axis : float + toroidal field (T) + b_plasma_poloidal_average : float + poloidal field (T) + p_plasma_separatrix_mw : float + power to divertor (MW) + f_div_flux_expansion : float + plasma flux expansion in divertor + nd_plasma_separatrix_electron : float + electron density at separatrix (m-3) + deg_div_field_plate : float + field line angle wrt divertor target plate (degrees) + rad_fraction_sol : float + SOL radiation fraction + f_p_div_lower : float + fraction of power to the lower divertor in double null configuration + + Returns + ------- + float + divertor heat load for a tight aspect ratio machine """ # Radius on midplane @@ -383,17 +362,21 @@ def incident_radiation_power( f_ster_div_single: float, n_divertors: int, ) -> float: - """ - Calculates the total incident radiation power on the divertor box. - - :param p_plasma_rad_mw: Total plasma radiated power in megawatts (MW). - :type p_plasma_rad_mw: float - :param f_ster_div_single: Fraction of the solid angle subtended by a single divertor. - :type f_ster_div_single: float - :param n_divertors: Number of divertors. - :type n_divertors: int - :returns: Total incident radiation power on the divertor box in megawatts (MW). - :rtype: float + """Calculates the total incident radiation power on the divertor box. + + Parameters + ---------- + p_plasma_rad_mw : float + Total plasma radiated power in megawatts (MW). + f_ster_div_single : float + Fraction of the solid angle subtended by a single divertor. + n_divertors : int + Number of divertors. + + Returns + ------- + float + Total incident radiation power on the divertor box in megawatts (MW). """ return p_plasma_rad_mw * f_ster_div_single * n_divertors @@ -404,17 +387,21 @@ def incident_neutron_power( f_ster_div_single: float, n_divertors: int, ) -> float: - """ - Calculates the total incident neutron power on the divertor box. - - :param p_plasma_neutron_mw: Total plasma neutron power in megawatts (MW). - :type p_plasma_neutron_mw: float - :param f_ster_div_single: Fraction of the solid angle subtended by a single divertor. - :type f_ster_div_single: float - :param n_divertors: Number of divertors. - :type n_divertors: int - :returns: Total incident radiation power on the divertor box in megawatts (MW). - :rtype: float + """Calculates the total incident neutron power on the divertor box. + + Parameters + ---------- + p_plasma_neutron_mw : float + Total plasma neutron power in megawatts (MW). + f_ster_div_single : float + Fraction of the solid angle subtended by a single divertor. + n_divertors : int + Number of divertors. + + Returns + ------- + float + Total incident radiation power on the divertor box in megawatts (MW). """ return p_plasma_neutron_mw * f_ster_div_single * n_divertors @@ -423,7 +410,7 @@ def incident_neutron_power( class LowerDivertor(Divertor): """Module containing lower divertor routines""" - def run(self, output: bool) -> None: + def run(self, output: bool): super().run(output=output) dv.p_div_lower_nuclear_heat_mw = self.incident_neutron_power( @@ -442,7 +429,7 @@ def run(self, output: bool) -> None: class UpperDivertor(Divertor): """Module containing upper divertor routines""" - def run(self, output: bool) -> None: + def run(self, output: bool): super().run(output=output) dv.p_div_upper_nuclear_heat_mw = self.incident_neutron_power( diff --git a/process/evaluators.py b/process/evaluators.py index 4eb8b53e35..e19d5ccd3a 100644 --- a/process/evaluators.py +++ b/process/evaluators.py @@ -36,17 +36,23 @@ def fcnvmc1(self, _n, m, xv, ifail): n-dimensional point of interest xv. Note that the equality constraints must precede the inequality constraints in conf. - :param n: number of variables - :type n: int - :param m: number of constraints - :type m: int - :param xv: scaled variable values, length n - :type xv: numpy.array - :param ifail: ifail error flag - :type ifail: int - :return: tuple containing: objfn objective function, conf(m) constraint - functions - :rtype: tuple + + Parameters + ---------- + _n : int + number of variables + m : int + number of constraints + xv : numpy.array + scaled variable values, length n + ifail : int + ifail error flag + + Returns + ------- + tuple + tuple containing: objfn objective function, conf(m) constraint + functions """ # Output array for constraint functions conf = np.zeros(m, dtype=np.float64, order="F") @@ -86,18 +92,23 @@ def fcnvmc2(self, n, m, xv, lcnorm): constraints in conf. The constraint gradients or normals are returned as the columns of cnorm. - :param n: number of variables - :type n: int - :param m: number of constraints - :type m: int - :param xv: scaled variable names, size n - :type xv: numpy.array - :param lcnorm: number of columns in cnorm - :type lcnorm: int - :return: fgrdm (numpy.array (n)) gradient of the objective function - cnorm (numpy.array (lcnorm, m)) constraint gradients, i.e. cnorm[i, j] is - the derivative of constraint j w.r.t. variable i - :rtype: tuple + Parameters + ---------- + n : int + number of variables + m : int + number of constraints + xv : numpy.array + scaled variable names, size n + lcnorm : int + number of columns in cnorm + + Returns + ------- + tuple + fgrdm (numpy.array (n)) gradient of the objective function + cnorm (numpy.array (lcnorm, m)) constraint gradients, i.e. cnorm[i, j] is + the derivative of constraint j w.r.t. variable i """ xfor = np.zeros(n, dtype=np.float64, order="F") xbac = np.zeros(n, dtype=np.float64, order="F") diff --git a/process/exceptions.py b/process/exceptions.py index b33cef2a66..ddac8d30ee 100644 --- a/process/exceptions.py +++ b/process/exceptions.py @@ -19,7 +19,6 @@ def __str__(self): class ProcessValidationError(ProcessError): """Exception raised when validating PROCESS input. - E.g. initial values, constraint/variable combinations, switch combinations""" diff --git a/process/final.py b/process/final.py index 9295730f13..901c6b297a 100644 --- a/process/final.py +++ b/process/final.py @@ -15,12 +15,14 @@ def finalise(models, ifail: int, non_idempotent_msg: str | None = None): Writes to OUT.DAT and MFILE.DAT. - :param models: physics and engineering model objects - :type models: process.main.Models - :param ifail: error flag - :type ifail: int - :param non_idempotent_msg: warning about non-idempotent variables, defaults to None - :type non_idempotent_msg: None | str, optional + Parameters + ---------- + models : process.main.Models + physics and engineering model objects + ifail : int + error flag + non_idempotent_msg : None | str, optional + warning about non-idempotent variables, defaults to None """ if ifail == 1: po.oheadr(constants.NOUT, "Final Feasible Point") diff --git a/process/fusion_reactions.py b/process/fusion_reactions.py index 26da81726a..6627b38317 100644 --- a/process/fusion_reactions.py +++ b/process/fusion_reactions.py @@ -61,8 +61,7 @@ class FusionReactionRate: - """ - Calculate the fusion reaction rate for each reaction case (DT, DHE3, DD1, DD2). + """Calculate the fusion reaction rate for each reaction case (DT, DHE3, DD1, DD2). This class provides methods to numerically integrate over the plasma cross-section to find the core plasma fusion power for different fusion reactions. The reactions @@ -77,71 +76,35 @@ class FusionReactionRate: fusion power. Attributes: - plasma_profile (PlasmaProfile): The parameterized temperature and density profiles of the plasma. - sigmav_dt_average (float): Average fusion reaction rate for D-T. - dhe3_power_density (float): Fusion power density produced by the D-3He reaction. - dd_power_density (float): Fusion power density produced by the D-D reactions. - dt_power_density (float): Fusion power density produced by the D-T reaction. - alpha_power_density (float): Power density of alpha particles produced. - pden_non_alpha_charged_mw (float): Power density of charged particles produced. - neutron_power_density (float): Power density of neutrons produced. - fusion_rate_density (float): Fusion reaction rate density. - alpha_rate_density (float): Alpha particle production rate density. - proton_rate_density (float): Proton production rate density. - f_dd_branching_trit (float): The rate of tritium producing D-D reactions to 3He ones. - - Methods: - deuterium_branching(ion_temperature: float) -> float: - Calculate the relative rate of tritium producing D-D reactions to 3He ones based on the volume averaged ion temperature. - - dt_reaction() -> None: - Calculate the fusion reaction rate and power density for the deuterium-tritium (D-T) fusion reaction. - - dhe3_reaction() -> None: - Calculate the fusion reaction rate and power density for the deuterium-helium-3 (D-3He) fusion reaction. - - dd_helion_reaction() -> None: - Calculate the fusion reaction rate and power density for the deuterium-deuterium (D-D) fusion reaction, specifically the branch that produces helium-3 (3He) and a neutron (n). - - dd_triton_reaction() -> None: - Calculate the fusion reaction rate and power density for the deuterium-deuterium (D-D) fusion reaction, specifically the branch that produces tritium (T) and a proton (p). - - sum_fusion_rates(alpha_power_add: float, charged_power_add: float, neutron_power_add: float, fusion_rate_add: float, alpha_rate_add: float, proton_rate_add: float) -> None: - Sum the fusion rate at the end of each reaction. - - calculate_fusion_rates() -> None: - Initiate all the fusion rate calculations. - - set_physics_variables() -> None: - Set the required physics variables in the physics_variables and physics_module modules. + plasma_profile (PlasmaProfile): The parameterized temperature and density profiles of the plasma. + sigmav_dt_average (float): Average fusion reaction rate for D-T. + dhe3_power_density (float): Fusion power density produced by the D-3He reaction. + dd_power_density (float): Fusion power density produced by the D-D reactions. + dt_power_density (float): Fusion power density produced by the D-T reaction. + alpha_power_density (float): Power density of alpha particles produced. + pden_non_alpha_charged_mw (float): Power density of charged particles produced. + neutron_power_density (float): Power density of neutrons produced. + fusion_rate_density (float): Fusion reaction rate density. + alpha_rate_density (float): Alpha particle production rate density. + proton_rate_density (float): Proton production rate density. + f_dd_branching_trit (float): The rate of tritium producing D-D reactions to 3He ones. References: - H.-S. Bosch and G. M. Hale, “Improved formulas for fusion cross-sections and thermal reactivities,” Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, doi: https://doi.org/10.1088/0029-5515/32/4/i07. - """ - def __init__(self, plasma_profile: PlasmaProfile) -> None: + def __init__(self, plasma_profile: PlasmaProfile): """ Initialize the FusionReactionRate class with the given plasma profile. - Parameters: - plasma_profile (PlasmaProfile): The parameterized temperature and density profiles of the plasma. - - Attributes: - plasma_profile (PlasmaProfile): The parameterized temperature and density profiles of the plasma. - sigmav_dt_average (float): Average fusion reaction rate for D-T. - dhe3_power_density (float): Fusion power density produced by the D-3He reaction. - dd_power_density (float): Fusion power density produced by the D-D reactions. - dt_power_density (float): Fusion power density produced by the D-T reaction. - alpha_power_density (float): Power density of alpha particles produced. - pden_non_alpha_charged_mw (float): Power density of charged particles produced. - neutron_power_density (float): Power density of neutrons produced. - fusion_rate_density (float): Fusion reaction rate density. - alpha_rate_density (float): Alpha particle production rate density. - proton_rate_density (float): Proton production rate density. - f_dd_branching_trit (float): The rate of tritium producing D-D reactions to 3He ones. + Parameters + ---------- + plasma_profile: + The parameterized temperature and density profiles of the plasma. + + """ self.plasma_profile = plasma_profile self.sigmav_dt_average = 0.0 @@ -157,24 +120,22 @@ def __init__(self, plasma_profile: PlasmaProfile) -> None: self.f_dd_branching_trit = 0.0 def deuterium_branching(self, ion_temperature: float) -> float: - """ - Calculate the relative rate of tritium producing D-D reactions to 3He ones based on the volume averaged ion temperature + """Calculate the relative rate of tritium producing D-D reactions to 3He ones based on the volume averaged ion temperature - Parameters: - ion_temperature (float): Volume averaged ion temperature in keV - - The method updates the following attributes: - -f_dd_branching_trit: The rate of tritium producing D-D reactions to 3He ones + Parameters + ---------- + ion_temperature : + float - Notes: - - For ion temperatures between 0.5 keV and 200 keV. - - The deviation of the fit from the R-matrix branching ratio is always smaller than 0.5%. + Notes + ----- + For ion temperatures between 0.5 keV and 200 keV. + The deviation of the fit from the R-matrix branching ratio is always smaller than 0.5%. References: - H.-S. Bosch and G. M. Hale, “Improved formulas for fusion cross-sections and thermal reactivities,” Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, doi: https://doi.org/10.1088/0029-5515/32/4/i07. - ‌ """ # Divide by 2 to get the branching ratio for the D-D reaction that produces tritium as the output # is just the ratio of the two normalized cross sections @@ -186,7 +147,7 @@ def deuterium_branching(self, ion_temperature: float) -> float: + 6.9855e-9 * ion_temperature**4 ) / 2.0 - def dt_reaction(self) -> None: + def dt_reaction(self): """D + T --> 4He + n reaction This method calculates the fusion reaction rate and power density for the @@ -204,8 +165,7 @@ def dt_reaction(self) -> None: - self.alpha_rate_density: Alpha particle production rate density. - self.proton_rate_density: Proton production rate density. - Returns: - None + """ # Initialize Bosch-Hale constants for the D-T reaction dt = BoschHaleConstants(**REACTION_CONSTANTS_DT) @@ -286,7 +246,7 @@ def dt_reaction(self) -> None: proton_rate_density, ) - def dhe3_reaction(self) -> None: + def dhe3_reaction(self): """D + 3He --> 4He + p reaction This method calculates the fusion reaction rate and power density for the @@ -303,8 +263,7 @@ def dhe3_reaction(self) -> None: - self.alpha_rate_density: Alpha particle production rate density. - self.proton_rate_density: Proton production rate density. - Returns: - None + """ # Initialize Bosch-Hale constants for the D-3He reaction dhe3 = BoschHaleConstants(**REACTION_CONSTANTS_DHE3) @@ -382,7 +341,7 @@ def dhe3_reaction(self) -> None: proton_rate_density, ) - def dd_helion_reaction(self) -> None: + def dd_helion_reaction(self): """D + D --> 3He + n reaction This method calculates the fusion reaction rate and power density for the @@ -400,8 +359,7 @@ def dd_helion_reaction(self) -> None: - self.alpha_rate_density: Alpha particle production rate density. - self.proton_rate_density: Proton production rate density. - Returns: - None + """ # Initialize Bosch-Hale constants for the D-D reaction dd1 = BoschHaleConstants(**REACTION_CONSTANTS_DD1) @@ -482,7 +440,7 @@ def dd_helion_reaction(self) -> None: proton_rate_density, ) - def dd_triton_reaction(self) -> None: + def dd_triton_reaction(self): """D + D --> T + p reaction This method calculates the fusion reaction rate and power density for the @@ -500,8 +458,7 @@ def dd_triton_reaction(self) -> None: - self.alpha_rate_density: Alpha particle production rate density. - self.proton_rate_density: Proton production rate density. - Returns: - None + """ # Initialize Bosch-Hale constants for the D-D reaction dd2 = BoschHaleConstants(**REACTION_CONSTANTS_DD2) @@ -585,22 +542,29 @@ def sum_fusion_rates( fusion_rate_add: float, alpha_rate_add: float, proton_rate_add: float, - ) -> None: + ): """Sum the fusion rate at the end of each reaction. This method updates the cumulative fusion power densities and reaction rates for alpha particles, charged particles, neutrons, and protons. - Parameters: - alpha_power_add (float): Alpha particle fusion power per unit volume [MW/m3]. - charged_power_add (float): Other charged particle fusion power per unit volume [MW/m3]. - neutron_power_add (float): Neutron fusion power per unit volume [MW/m3]. - fusion_rate_add (float): Fusion reaction rate per unit volume [reactions/m3/s]. - alpha_rate_add (float): Alpha particle production rate per unit volume [/m3/s]. - proton_rate_add (float): Proton production rate per unit volume [/m3/s]. + Parameters + ---------- + alpha_power_add : + Alpha particle fusion power per unit volume [MW/m3]. + charged_power_add : + Other charged particle fusion power per unit volume [MW/m3]. + neutron_power_add : + Neutron fusion power per unit volume [MW/m3] + fusion_rate_add : + Fusion reaction rate per unit volume [reactions/m3/s]. + alpha_rate_add : + Alpha particle production rate per unit volume [/m3/s]. + proton_rate_add : + Proton production rate per unit volume [/m3/s]. + + - Returns: - None """ self.alpha_power_density += alpha_power_add self.pden_non_alpha_charged_mw += charged_power_add @@ -609,9 +573,8 @@ def sum_fusion_rates( self.alpha_rate_density += alpha_rate_add self.proton_rate_density += proton_rate_add - def calculate_fusion_rates(self) -> None: - """ - Initiate all the fusion rate calculations. + def calculate_fusion_rates(self): + """Initiate all the fusion rate calculations. This method sequentially calculates the fusion reaction rates and power densities for the following reactions: @@ -623,23 +586,20 @@ def calculate_fusion_rates(self) -> None: It updates the instance attributes for the cumulative power densities and reaction rates for alpha particles, charged particles, neutrons, and protons. - Returns: - None + """ self.dt_reaction() self.dhe3_reaction() self.dd_helion_reaction() self.dd_triton_reaction() - def set_physics_variables(self) -> None: - """ - Set the required physics variables in the physics_variables and physics_module modules. + def set_physics_variables(self): + """Set the required physics variables in the physics_variables and physics_module modules. This method updates the global physics variables and module variables with the current instance's fusion power densities and reaction rates. - Returns: - None + """ physics_variables.pden_plasma_alpha_mw = self.alpha_power_density physics_variables.pden_non_alpha_charged_mw = self.pden_non_alpha_charged_mw @@ -674,20 +634,25 @@ class BoschHaleConstants: def fusion_rate_integral( plasma_profile: PlasmaProfile, reaction_constants: BoschHaleConstants ) -> np.ndarray: - """ - Evaluate the integrand for the fusion power integration. + """Evaluate the integrand for the fusion power integration. + + Parameters + ---------- + plasma_profile : + Parameterised temperature and density profiles. + reactionconstants : + Bosch-Hale reaction constants. - Parameters: - plasma_profile (PlasmaProfile): Parameterised temperature and density profiles. - reactionconstants (BoschHaleConstants): Bosch-Hale reaction constants. - Returns: + Returns + ------- + : np.ndarray: Integrand for the fusion power. References: - H.-S. Bosch and G. M. Hale, “Improved formulas for fusion cross-sections and thermal reactivities,” - Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, - doi: https://doi.org/10.1088/0029-5515/32/4/i07. + Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, + doi: https://doi.org/10.1088/0029-5515/32/4/i07. """ # Since the electron temperature profile is only calculated directly, we scale the ion temperature @@ -720,8 +685,7 @@ def fusion_rate_integral( def bosch_hale_reactivity( ion_temperature_profile: np.ndarray, reaction_constants: BoschHaleConstants ) -> np.ndarray: - """ - Calculate the volumetric fusion reaction rate 〈sigmav〉 (m^3/s) for one of four nuclear reactions using + """Calculate the volumetric fusion reaction rate 〈sigmav〉 (m^3/s) for one of four nuclear reactions using the Bosch-Hale parametrization. The valid range of the fit is 0.2 keV < t < 100 keV except for D-3He where it is 0.5 keV < t < 190 keV. @@ -732,17 +696,22 @@ def bosch_hale_reactivity( 3. D-D 1st reaction 4. D-D 2nd reaction - Parameters: - ion_temperature_profile (np.ndarray): Plasma ion temperature profile in keV. - reaction_constants (BoschHaleConstants): Bosch-Hale reaction constants. + Parameters + ---------- + ion_temperature_profile : + Plasma ion temperature profile in keV. + reaction_constants : + Bosch-Hale reaction constants. - Returns: + Returns + ------- + : np.ndarray: Volumetric fusion reaction rate 〈sigmav〉 in m^3/s for each point in the ion temperature profile. References: - H.-S. Bosch and G. M. Hale, “Improved formulas for fusion cross-sections and thermal reactivities,” - Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, - doi: https://doi.org/10.1088/0029-5515/32/4/i07. + Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, + doi: https://doi.org/10.1088/0029-5515/32/4/i07. """ theta1 = ( ion_temperature_profile @@ -795,37 +764,44 @@ def set_fusion_powers( vol_plasma: float, pden_plasma_alpha_mw: float, ) -> tuple: - """ - - This function computes various fusion power metrics based on the provided plasma parameters. - - Parameters: - f_alpha_electron (float): Fraction of alpha energy to electrons. - f_alpha_ion (float): Fraction of alpha energy to ions. - p_beam_alpha_mw (float): Alpha power from hot neutral beam ions (MW). - pden_non_alpha_charged_mw (float): Other charged particle fusion power per unit volume (MW/m^3). - pden_plasma_neutron_mw (float): Neutron fusion power per unit volume just from plasma (MW/m^3). - vol_plasma (float): Plasma volume (m^3). - pden_plasma_alpha_mw (float): Alpha power per unit volume just from plasma (MW/m^3). - - Returns: + """This function computes various fusion power metrics based on the provided plasma parameters. + + Parameters + ---------- + f_alpha_electron : + float + f_alpha_ion : + float + p_beam_alpha_mw : + float + pden_non_alpha_charged_mw : + float + pden_plasma_neutron_mw : + float + vol_plasma : + float + pden_plasma_alpha_mw : + float + + Returns + ------- + : tuple: A tuple containing the following elements: - - pden_neutron_total_mw (float): Neutron fusion power per unit volume from plasma and beams [MW/m^3]. - - p_plasma_alpha_mw (float): Alpha fusion power from only the plasma [MW]. - - p_alpha_total_mw (float): Total alpha fusion power from plasma and beams [MW]. - - p_plasma_neutron_mw (float): Neutron fusion power from only the plasma [MW]. - - p_neutron_total_mw (float): Total neutron fusion power from plasma and beams [MW]. - - p_non_alpha_charged_mw (float): Other total charged particle fusion power [MW]. - - pden_alpha_total_mw (float): Alpha power per unit volume, from beams and plasma [MW/m^3]. - - f_pden_alpha_electron_mw (float): Alpha power per unit volume to electrons [MW/m^3]. - - f_pden_alpha_ions_mw (float): Alpha power per unit volume to ions [MW/m^3]. - - p_charged_particle_mw (float): Charged particle fusion power [MW]. - - p_fusion_total_mw (float): Total fusion power [MW]. + - pden_neutron_total_mw (float): Neutron fusion power per unit volume from plasma and beams [MW/m^3]. + - p_plasma_alpha_mw (float): Alpha fusion power from only the plasma [MW]. + - p_alpha_total_mw (float): Total alpha fusion power from plasma and beams [MW]. + - p_plasma_neutron_mw (float): Neutron fusion power from only the plasma [MW]. + - p_neutron_total_mw (float): Total neutron fusion power from plasma and beams [MW]. + - p_non_alpha_charged_mw (float): Other total charged particle fusion power [MW]. + - pden_alpha_total_mw (float): Alpha power per unit volume, from beams and plasma [MW/m^3]. + - f_pden_alpha_electron_mw (float): Alpha power per unit volume to electrons [MW/m^3]. + - f_pden_alpha_ions_mw (float): Alpha power per unit volume to ions [MW/m^3]. + - p_charged_particle_mw (float): Charged particle fusion power [MW]. + - p_fusion_total_mw (float): Total fusion power [MW]. References: - N.A. Uckan and ITER Physics Group, 'ITER Physics Design Guidelines: 1989' - ITER Documentation Series No.10, IAEA/ITER/DS/10, IAEA, Vienna, 1990 - """ # Alpha power @@ -915,55 +891,74 @@ def beam_fusion( vol_plasma: float, n_charge_plasma_effective_mass_weighted_vol_avg: float, ) -> tuple: - """ - Routine to calculate beam slowing down properties. - - This function computes the neutral beam beta component, hot beam ion density, - and alpha power from hot neutral beam ions based on the provided plasma parameters. - - Parameters: - beamfus0 (float): Multiplier for beam-background fusion calculation. - betbm0 (float): Leading coefficient for neutral beam beta fraction. - b_plasma_poloidal_average (float): Poloidal field (T). - b_plasma_toroidal_on_axis (float): Toroidal field on axis (T). - c_beam_total (float): Neutral beam current (A). - nd_plasma_electrons_vol_avg (float): Electron density (m^-3). - nd_plasma_fuel_ions_vol_avg (float): Fuel ion density (m^-3). - ion_electron_coulomb_log (float): Ion-electron coulomb logarithm. - e_beam_kev (float): Neutral beam energy (keV). - f_deuterium_plasma (float): Deuterium fraction of main plasma. - f_tritium_plasma (float): Tritium fraction of main plasma. - f_beam_tritium (float): Tritium fraction of neutral beam. - sigmav_dt_average (float): Profile averaged for D-T (m^3/s). - temp_plasma_electron_density_weighted_kev (float): Density-weighted electron temperature (keV). - temp_plasma_ion_density_weighted_kev (float): Density-weighted ion temperature (keV). - vol_plasma (float): Plasma volume (m^3). - n_charge_plasma_effective_mass_weighted_vol_avg (float): Mass weighted plasma effective charge. - - Returns: - tuple: A tuple containing the following elements: - - beta_beam (float): Neutral beam beta component. - - nd_beam_ions_out (float): Hot beam ion density (m^-3). - - p_beam_alpha_mw (float): Alpha power from hot neutral beam ions (MW). - - Notes: - - The function uses the Bosch-Hale parametrization to compute the reactivity. - - The critical energy for electron/ion slowing down of the beam ion is calculated - for both deuterium and tritium neutral beams. - - The function integrates the hot beam fusion reaction rate integrand over the - range of beam velocities up to the critical velocity. - - References: - - H.-S. Bosch and G. M. Hale, “Improved formulas for fusion cross-sections and thermal reactivities,” - Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, - doi: https://doi.org/10.1088/0029-5515/32/4/i07. - - - J. W. Sheffield, “The physics of magnetic fusion reactors,” vol. 66, no. 3, pp. 1015-1103, - Jul. 1994, doi: https://doi.org/10.1103/revmodphys.66.1015. - - - Deng Baiquan and G. A. Emmert, “Fast ion pressure in fusion plasma,” Nuclear Fusion and Plasma Physics, - vol. 9, no. 3, pp. 136-141, 2022, Available: https://fti.neep.wisc.edu/fti.neep.wisc.edu/pdf/fdm718.pdf - ‌ + """Routine to calculate beam slowing down properties. + + This function computes the neutral beam beta component, hot beam ion density, + and alpha power from hot neutral beam ions based on the provided plasma parameters. + + Parameters + ---------- + beamfus0: + Multiplier for beam-background fusion calculation. + betbm0: + Leading coefficient for neutral beam beta fraction. + b_plasma_poloidal_average: + Poloidal field (T). + b_plasma_toroidal_on_axis: + Toroidal field on axis (T). + c_beam_total: + Neutral beam current (A). + nd_plasma_electrons_vol_avg: + Electron density (m^-3). + nd_plasma_fuel_ions_vol_avg: + Fuel ion density (m^-3). + ion_electron_coulomb_log: + Ion-electron coulomb logarithm. + e_beam_kev: + Neutral beam energy (keV). + f_deuterium_plasma: + Deuterium fraction of main plasma. + f_tritium_plasma: + Tritium fraction of main plasma. + f_beam_tritium: + Tritium fraction of neutral beam. + sigmav_dt_average: + Profile averaged for D-T (m^3/s). + temp_plasma_electron_density_weighted_kev: + Density-weighted electron temperature (keV). + temp_plasma_ion_density_weighted_kev: + Density-weighted ion temperature (keV). + vol_plasma: + Plasma volume (m^3). + n_charge_plasma_effective_mass_weighted_vol_avg: + Mass weighted plasma effective charge. + + Returns + ------- + : + tuple: A tuple containing the following elements: + - beta_beam (float): Neutral beam beta component. + - nd_beam_ions_out (float): Hot beam ion density (m^-3). + - p_beam_alpha_mw (float): Alpha power from hot neutral beam ions (MW). + + Notes: + - The function uses the Bosch-Hale parametrization to compute the reactivity. + - The critical energy for electron/ion slowing down of the beam ion is calculated + for both deuterium and tritium neutral beams. + - The function integrates the hot beam fusion reaction rate integrand over the + range of beam velocities up to the critical velocity. + + References: + - H.-S. Bosch and G. M. Hale, “Improved formulas for fusion cross-sections and thermal reactivities,” + Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, + doi: https://doi.org/10.1088/0029-5515/32/4/i07. + + - J. W. Sheffield, “The physics of magnetic fusion reactors,” vol. 66, no. 3, pp. 1015-1103, + Jul. 1994, doi: https://doi.org/10.1103/revmodphys.66.1015. + + - Deng Baiquan and G. A. Emmert, “Fast ion pressure in fusion plasma,” Nuclear Fusion and Plasma Physics, + vol. 9, no. 3, pp. 136-141, 2022, Available: https://fti.neep.wisc.edu/fti.neep.wisc.edu/pdf/fdm718.pdf + ‌ """ # Beam ion slowing down time given by Deng Baiquan and G. A. Emmert 1987 @@ -1044,54 +1039,66 @@ def beamcalc( vol_plasma: float, svdt: float, ) -> tuple[float, float, float, float]: - """ - Calculate neutral beam alpha power and ion energy. + """Calculate neutral beam alpha power and ion energy. This function computes the alpha power generated from the interaction between hot beam ions and thermal ions in the plasma, as well as the hot beam ion density and average hot beam ion energy. - Parameters: - nd (float): Thermal deuterium density (m^-3). - nt (float): Thermal tritium density (m^-3). - e_beam_kev (float): Beam energy (keV). - critical_energy_deuterium (float): Critical energy for electron/ion slowing down of the beam ion (deuterium neutral beam) (keV). - critical_energy_tritium (float): Critical energy for beam slowing down (tritium neutral beam) (keV). - beam_slow_time (float): Beam ion slowing down time on electrons (s). - f_beam_tritium (float): Beam tritium fraction (0.0 = deuterium beam). - c_beam_total (float): Beam current (A). - temp_plasma_ion_vol_avg_kev (float): Thermal ion temperature (keV). - vol_plasma (float): Plasma volume (m^3). - svdt (float): Profile averaged for D-T (m^3/s). - - Returns: + Parameters + ---------- + nd : + Thermal deuterium density (m^-3). + nt : + Thermal tritium density (m^-3). + e_beam_kev : + Beam energy (keV). + critical_energy_deuterium : + Critical energy for electron/ion slowing down of the beam ion (deuterium neutral beam) (keV). + critical_energy_tritium : + Critical energy for beam slowing down (tritium neutral beam) (keV). + beam_slow_time : + Beam ion slowing down time on electrons (s). + f_beam_tritium : + Beam tritium fraction (0.0 = deuterium beam). + c_beam_total : + Beam current (A). + temp_plasma_ion_vol_avg_kev : + Thermal ion temperature (keV). + vol_plasma : + Plasma volume (m^3). + svdt : + Profile averaged for D-T (m^3/s). + + Returns + ------- + : tuple[float, float, float, float]: A tuple containing the following elements: - - Alpha power from deuterium beam-background fusion (MW). - - Alpha power from tritium beam-background fusion (MW). - - Hot beam ion density (m^-3). - - Average hot beam ion energy (keV). + - Alpha power from deuterium beam-background fusion (MW). + - Alpha power from tritium beam-background fusion (MW). + - Hot beam ion density (m^-3). + - Average hot beam ion energy (keV). Notes: - The function uses the Bosch-Hale parametrization to compute the reactivity. - The critical energy for electron/ion slowing down of the beam ion is calculated - for both deuterium and tritium neutral beams. + for both deuterium and tritium neutral beams. - The function integrates the hot beam fusion reaction rate integrand over the - range of beam velocities up to the critical velocity. + range of beam velocities up to the critical velocity. References: - H.-S. Bosch and G. M. Hale, “Improved formulas for fusion cross-sections and thermal reactivities,” - Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, - doi: https://doi.org/10.1088/0029-5515/32/4/i07. + Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, + doi: https://doi.org/10.1088/0029-5515/32/4/i07. - Deng Baiquan and G. A. Emmert, “Fast ion pressure in fusion plasma,” Nuclear Fusion and Plasma Physics, - vol. 9, no. 3, pp. 136-141, 2022, Available: https://fti.neep.wisc.edu/fti.neep.wisc.edu/pdf/fdm718.pdf + vol. 9, no. 3, pp. 136-141, 2022, Available: https://fti.neep.wisc.edu/fti.neep.wisc.edu/pdf/fdm718.pdf - Wesson, J. (2011) Tokamaks. 4th Edition, 2011 Oxford Science Publications, - International Series of Monographs on Physics, Volume 149. + International Series of Monographs on Physics, Volume 149. - J. W. Sheffield, “The physics of magnetic fusion reactors,” vol. 66, no. 3, pp. 1015-1103, - Jul. 1994, doi: https://doi.org/10.1103/revmodphys.66.1015. - + Jul. 1994, doi: https://doi.org/10.1103/revmodphys.66.1015. """ # D and T beam current fractions @@ -1228,31 +1235,35 @@ def beamcalc( def fast_ion_pressure_integral(e_beam_kev: float, critical_energy: float) -> float: - """ - Calculate the fraction of initial beam energy given to the ions. + """Calculate the fraction of initial beam energy given to the ions. This function computes the fraction of initial beam energy given to the ions. based on the neutral beam energy and the critical energy for electron/ion slowing down of the beam ion. - Parameters: - e_beam_kev (float): Neutral beam energy (keV). - critical_energy (float): Critical energy for electron/ion slowing down of the beam ion (keV). + Parameters + ---------- + e_beam_kev : + Neutral beam energy (keV). + critical_energy : + Critical energy for electron/ion slowing down of the beam ion (keV). - Returns: + Returns + ------- + : float: Fraction of initial beam energy given to the ions. Notes: - The function uses the ratio of the beam energy to the critical energy to compute - the hot ion energy parameter. + the hot ion energy parameter. - The calculation involves logarithmic and arctangent functions to account for - the energy distribution of the hot ions. + the energy distribution of the hot ions. References: - Deng Baiquan and G. A. Emmert, “Fast ion pressure in fusion plasma,” Nuclear Fusion and Plasma Physics, - vol. 9, no. 3, pp. 136-141, 2022, Available: https://fti.neep.wisc.edu/fti.neep.wisc.edu/pdf/fdm718.pdf + vol. 9, no. 3, pp. 136-141, 2022, Available: https://fti.neep.wisc.edu/fti.neep.wisc.edu/pdf/fdm718.pdf - W.A Houlberg, “Thermalization of an Energetic Heavy Ion in a Multi-species Plasma,” University of Wisconsin Fusion Technology Institute, - Report UWFDM-103 1974, Available: https://fti.neep.wisc.edu/fti.neep.wisc.edu/pdf/fdm103.pdf + Report UWFDM-103 1974, Available: https://fti.neep.wisc.edu/fti.neep.wisc.edu/pdf/fdm103.pdf """ xcs = e_beam_kev / critical_energy @@ -1276,32 +1287,41 @@ def alpha_power_beam( temp_plasma_ion_vol_avg_kev: float, sigmav_dt: float, ) -> float: - """ - Calculate alpha power from beam-background fusion. + """Calculate alpha power from beam-background fusion. This function computes the alpha power generated from the interaction between hot beam ions and thermal ions in the plasma. - Parameters: - beam_ion_desnity (float): Hot beam ion density (m^-3). - plasma_ion_desnity (float): Thermal ion density (m^-3). - sigv (float): Hot beam fusion reaction rate (m^3/s). - vol_plasma (float): Plasma volume (m^3). - temp_plasma_ion_vol_avg_kev (float): Thermal ion temperature (keV). - sigmav_dt (float): Profile averaged for D-T (m^3/s). - - Returns: + Parameters + ---------- + beam_ion_desnity : + Hot beam ion density (m^-3). + plasma_ion_desnity : + Thermal ion density (m^-3). + sigv : + Hot beam fusion reaction rate (m^3/s). + vol_plasma : + Plasma volume (m^3). + temp_plasma_ion_vol_avg_kev : + Thermal ion temperature (keV). + sigmav_dt : + Profile averaged for D-T (m^3/s). + + Returns + ------- + : float: Alpha power from beam-background fusion (MW). - Notes: - - The function uses the Bosch-Hale parametrization to compute the reactivity. - - The ratio of the profile-averaged to the reactivity at the given - thermal ion temperature is used to scale the alpha power. + Notes + ----- + - The function uses the Bosch-Hale parametrization to compute the reactivity. + - The ratio of the profile-averaged to the reactivity at the given + thermal ion temperature is used to scale the alpha power. References: - - H.-S. Bosch and G. M. Hale, “Improved formulas for fusion cross-sections and thermal reactivities,” - Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, - doi: https://doi.org/10.1088/0029-5515/32/4/i07. + - H.-S. Bosch and G. M. Hale, “Improved formulas for fusion cross-sections and thermal reactivities,” + Nuclear Fusion, vol. 32, no. 4, pp. 611-631, Apr. 1992, + doi: https://doi.org/10.1088/0029-5515/32/4/i07. """ # Calculate the reactivity ratio ratio = ( @@ -1326,28 +1346,32 @@ def alpha_power_beam( def beam_reaction_rate( relative_mass_ion: float, critical_velocity: float, beam_energy_keV: float ) -> float: - """ - Calculate the hot beam fusion reaction rate. + """Calculate the hot beam fusion reaction rate. This function computes the fusion reaction rate for hot beam ions using the critical velocity for electron/ion slowing down and the neutral beam energy. - Parameters: - relative_mass_ion (float): Relative atomic mass of the ion (e.g., approx 2.0 for D, 3.0 for T). - critical_velocity (float): Critical velocity for electron/ion slowing down of the beam ion [m/s]. - beam_energy_keV(float): Neutral beam energy [keV]. - - Returns: + Parameters + ---------- + relative_mass_ion : + Relative atomic mass of the ion (e.g., approx 2.0 for D, 3.0 for T). + critical_velocity : + Critical velocity for electron/ion slowing down of the beam ion [m/s]. + beam_energy_keV : + Neutral beam energy [keV]. + + Returns + ------- + : float: Hot beam fusion reaction rate (m^3/s). - Notes: - - The function integrates the hot beam fusion reaction rate integrand - over the range of beam velocities up to the critical velocity. - - The integration is performed using the quad function from scipy.integrate. + Notes + ----- + - The function integrates the hot beam fusion reaction rate integrand + over the range of beam velocities up to the critical velocity. + - The integration is performed using the quad function from scipy.integrate. - References: - - P J Knight, CCFE, Culham Science Centre """ # Find the speed of the beam particle when it has the critical energy. @@ -1374,28 +1398,32 @@ def beam_reaction_rate( def _hot_beam_fusion_reaction_rate_integrand( velocity_ratio: float, critical_velocity: float ) -> float: - """ - Integrand function for the hot beam fusion reaction rate. + """Integrand function for the hot beam fusion reaction rate. This function computes the integrand for the hot beam fusion reaction rate based on the ratio of beam velocity to the critical velocity and the critical velocity for electron/ion slowing down of the beam ion. - Parameters: - velocity_ratio (float): Ratio of beam velocity to the critical velocity. - critical_velocity (float): Critical velocity for electron/ion slowing down of the beam ion (m/s). + Parameters + ---------- + velocity_ratio : + Ratio of beam velocity to the critical velocity. + critical_velocity : + Critical velocity for electron/ion slowing down of the beam ion (m/s). + - Returns: + Returns + ------- + : float: Value of the integrand for the hot beam fusion reaction rate. - Notes: - - The function uses the ratio of the beam velocity to the critical velocity - to compute the integrand. - - The integrand involves the fusion reaction cross-section and the critical - velocity for electron/ion slowing down of the beam ion. + Notes + ----- + - The function uses the ratio of the beam velocity to the critical velocity + to compute the integrand. + - The integrand involves the fusion reaction cross-section and the critical + velocity for electron/ion slowing down of the beam ion. - References: - - P J Knight, CCFE, Culham Science Centre """ intgeral_term = (velocity_ratio**3) / (1.0 + velocity_ratio**3) @@ -1412,8 +1440,7 @@ def _hot_beam_fusion_reaction_rate_integrand( def _beam_fusion_cross_section(vrelsq: float) -> float: - """ - Calculate the fusion reaction cross-section. + """Calculate the fusion reaction cross-section. This function computes the fusion reaction cross-section based on the square of the speed of the beam ion (keV/amu). The functional form of @@ -1421,20 +1448,23 @@ def _beam_fusion_cross_section(vrelsq: float) -> float: for a tritium beam at 500 keV the energy used in the cross-section function is 333 keV. - Parameters: - vrelsq (float): Square of the speed of the beam ion (keV/amu). + Parameters + ---------- + vrelsq : + Square of the speed of the beam ion (keV/amu). - Returns: - float: Fusion reaction cross-section (cm^2). + Returns + ------- + : + Fusion reaction cross-section (cm^2). - Notes: - - The cross-section is limited at low and high beam energies. - - For beam kinetic energy less than 10 keV, the cross-section is set to 1.0e-27 cm^2. - - For beam kinetic energy greater than 10,000 keV, the cross-section is set to 8.0e-26 cm^2. - - The cross-section is calculated using a functional form with parameters a1 to a5. + Notes + ----- + The cross-section is limited at low and high beam energies. + For beam kinetic energy less than 10 keV, the cross-section is set to 1.0e-27 cm^2. + For beam kinetic energy greater than 10,000 keV, the cross-section is set to 8.0e-26 cm^2. + The cross-section is calculated using a functional form with parameters a1 to a5. - References: - - None """ a1 = 45.95 a2 = 5.02e4 diff --git a/process/fw.py b/process/fw.py index 028dd47c21..807d9e815b 100644 --- a/process/fw.py +++ b/process/fw.py @@ -20,7 +20,7 @@ class FirstWall: - def __init__(self) -> None: + def __init__(self): self.outfile = constants.NOUT self.blanket_library = BlanketLibrary(fw=self) @@ -105,7 +105,29 @@ def calculate_first_wall_half_height( dr_fw_inboard: float, dr_fw_outboard: float, ) -> float: - """Calculate the half-height of the first wall.""" + """Calculate the half-height of the first wall. + + Parameters + ---------- + z_plasma_xpoint_lower: + + dz_xpoint_divertor: + + dz_divertor: + + dz_blkt_upper: + + z_plasma_xpoint_upper: + + dz_fw_plasma_gap: + + n_divertors: int : + + dr_fw_inboard: + + dr_fw_outboard: + + """ # Half-height of first wall (internal surface) z_bottom = ( @@ -161,7 +183,23 @@ def calculate_elliptical_first_wall_areas( dr_fw_plasma_gap_inboard: float, dr_fw_plasma_gap_outboard: float, ) -> tuple[float, float, float]: - """Calculate the first wall areas for an elliptical cross-section.""" + """Calculate the first wall areas for an elliptical cross-section. + + Parameters + ---------- + rmajor: + + rminor: + + triang: + + dz_fw_half: + + dr_fw_plasma_gap_inboard: + + dr_fw_plasma_gap_outboard: + + """ # Cross-section is assumed to be defined by two ellipses # Major radius to centre of inboard and outboard ellipses @@ -201,20 +239,23 @@ def apply_first_wall_coverage_factors( ) -> tuple[float, float, float]: """Apply first wall coverage factors to calculate actual first wall areas. - :param n_divertors: Number of divertors (1 or 2). - :type n_divertors: int - :param f_ster_div_single: Fractional area of first wall sterically blocked by single divertor. - :type f_ster_div_single: float - :param f_a_fw_outboard_hcd: Fractional area of outboard first wall covered by high heat flux components. - :type f_a_fw_outboard_hcd: float - :param a_fw_inboard_full_coverage: First wall inboard area assuming 100% coverage (m^2). - :type a_fw_inboard_full_coverage: float - :param a_fw_outboard_full_coverage: First wall outboard area assuming 100% coverage (m^2). - :type a_fw_outboard_full_coverage: float - - :returns: Contains first wall inboard area, outboard area, and total area (m^2). - :rtype: tuple[float, float, float] - + Parameters + ---------- + n_divertors : int + Number of divertors (1 or 2). + f_ster_div_single : float + Fractional area of first wall sterically blocked by single divertor. + f_a_fw_outboard_hcd : float + Fractional area of outboard first wall covered by high heat flux components. + a_fw_inboard_full_coverage : float + First wall inboard area assuming 100% coverage (m^2). + a_fw_outboard_full_coverage : float + First wall outboard area assuming 100% coverage (m^2). + + Returns + ------- + tuple[float, float, float] + Contains first wall inboard area, outboard area, and total area (m^2). """ if n_divertors == 2: # Double null configuration @@ -258,26 +299,28 @@ def fw_temp( pnuc_deposited: float, label: str, ) -> tuple: - """ - Thermo-hydraulic calculations for the first wall. - - :param output: Flag to indicate if output is required. - :type output: bool - :param radius_fw_channel: First wall coolant channel radius (m). - :type radius_fw_channel: float - :param dr_fw: First wall thickness (m). - :type dr_fw: float - :param a_fw: Area of first wall section under consideration (m^2). - :type a_fw: float - :param prad_incident: Radiation surface heat flux on first wall (MW). - :type prad_incident: float - :param pnuc_deposited: Nuclear power deposited in FW (MW). - :type pnuc_deposited: float - :param label: Information string. - :type label: str - - :returns: Contains peak first wall temperature (K), coolant specific heat capacity at constant pressure (J/kg/K), - :rtype: tuple + """Thermo-hydraulic calculations for the first wall. + + Parameters + ---------- + output: + Flag to indicate if output is required. + radius_fw_channel: + First wall coolant channel radius (m). + dr_fw: + First wall thickness (m). + a_fw: + Area of first wall section under consideration (m^2). + prad_incident: + Radiation surface heat flux on first wall (MW). + pnuc_deposited: + Nuclear power deposited in FW (MW). + label: + Information string. + + Returns + ------- + tuple Detailed thermal hydraulic model for the blanket (first wall + breeding zone). Given the heating incident on the first wall, and the coolant outlet temperature, @@ -286,6 +329,7 @@ def fw_temp( The calculation of the maximum temperature is described by Gardner: "Temperature distribution in the first wall", K:\\Power Plant Physics and Technology\\ PROCESS\\PROCESS References & Systems Codes\\Pulsed option - Gardner. This is in turn taken from "Methods of First Wall Structural Analysis with Application to the Long Pulse Commercial Tokamak Reactor Design", R.J. LeClaire, MIT, PFC/RR-84-9. + Contains peak first wall temperature (K), coolant specific heat capacity at constant pressure (J/kg/K), """ # First wall volume (inboard or outboard depending on arguments) (m^3) @@ -556,18 +600,24 @@ def fw_temp( ) def fw_thermal_conductivity(self, temp: float) -> float: - """ - Calculates the thermal conductivity of the first wall material (Eurofer97). + """Calculates the thermal conductivity of the first wall material (Eurofer97). - :param temp: Property temperature in Kelvin (K). - :type temp: float - :return: Thermal conductivity of Eurofer97 in W/m/K. - :rtype: float + Parameters + ---------- + temp: + Property temperature in Kelvin (K). - :notes: - Valid up to about 800 K + Returns + ------- + : + Thermal conductivity of Eurofer97 in W/m/K. - :references: + Notes + ----- + Valid up to about 800 K + + References + ---------- - A. A. Tavassoli et al., “Materials design data for reduced activation martensitic steel type EUROFER,” Journal of Nuclear Materials, vol. 329-333, pp. 257-262, Aug. 2004, doi: https://doi.org/10.1016/j.jnucmat.2004.04.020. @@ -593,32 +643,39 @@ def heat_transfer( thermcond_coolant: float, roughness_fw_channel: float, ) -> float: - """ - Calculate heat transfer coefficient using Gnielinski correlation. - - :param mflux_coolant: Coolant mass flux in a single channel (kg/m^2/s). - :type mflux_coolant: float - :param den_coolant: Coolant density (average of inlet and outlet) (kg/m^3). - :type den_coolant: float - :param radius_channel: Coolant pipe radius (m). - :type radius_channel: float - :param heatcap_coolant: Coolant specific heat capacity (average of inlet and outlet) (J/kg/K). - :type heatcap_coolant: float - :param visc_coolant: Coolant viscosity (average of inlet and outlet) (Pa.s). - :type visc_coolant: float - :param thermcond_coolant: Thermal conductivity of coolant (average of inlet and outlet) (W/m.K). - :type thermcond_coolant: float - :param roughness_fw_channel: Roughness of the first wall coolant channel (m). - :type roughness_fw_channel: float - :return: Heat transfer coefficient (W/m^2K). - :rtype: float - - :notes: - Gnielinski correlation. Ignore the distinction between wall and - bulk temperatures. Valid for: 3000 < Re < 5e6, 0.5 < Pr < 2000 - - :references: + """Calculate heat transfer coefficient using Gnielinski correlation. + + Parameters + ---------- + mflux_coolant: + Coolant mass flux in a single channel (kg/m^2/s). + den_coolant: + Coolant density (average of inlet and outlet) (kg/m^3). + radius_channel: + Coolant pipe radius (m). + heatcap_coolant: + Coolant specific heat capacity (average of inlet and outlet) (J/kg/K). + visc_coolant: + Coolant viscosity (average of inlet and outlet) (Pa.s). + thermcond_coolant: + Thermal conductivity of coolant (average of inlet and outlet) (W/m.K). + roughness_fw_channel: + Roughness of the first wall coolant channel (m). + + Returns + ------- + : + Heat transfer coefficient (W/m^2K). + + Notes + ----- + Gnielinski correlation. Ignore the distinction between wall and + bulk temperatures. Valid for: 3000 < Re < 5e6, 0.5 < Pr < 2000 + + References + ---------- - https://en.wikipedia.org/wiki/Nusselt_number#Gnielinski_correlation + """ # Calculate pipe diameter (m) diameter = 2 * radius_channel @@ -667,24 +724,29 @@ def heat_transfer( def darcy_friction_haaland( self, reynolds: float, roughness_fw_channel: float, radius_fw_channel: float ) -> float: - """ - Calculate Darcy friction factor using the Haaland equation. - - :param reynolds: Reynolds number. - :type reynolds: float - :param roughness_fw_channel: Roughness of the first wall coolant channel (m). - :type roughness_fw_channel: float - :param radius_fw_channel: Radius of the first wall coolant channel (m). - :type radius_fw_channel: float - - :return: Darcy friction factor. - :rtype: float - - :Notes: + """Calculate Darcy friction factor using the Haaland equation. + + Parameters + ---------- + reynolds + Reynolds number. + roughness_fw_channel + Roughness of the first wall coolant channel (m). + radius_fw_channel + Radius of the first wall coolant channel (m). + + Returns + ------- + : + Darcy friction factor. + + Notes + ----- The Haaland equation is an approximation to the implicit Colebrook-White equation. It is used to calculate the Darcy friction factor for turbulent flow in pipes. - :References: + References + ---------- - https://en.wikipedia.org/wiki/Darcy_friction_factor_formulae#Haaland_equation """ @@ -703,29 +765,30 @@ def calculate_total_fw_channels( len_fw_channel: float, dx_fw_module: float, ) -> tuple[int, int]: - """ - Calculate the total number of first wall channels for inboard and outboard sections. - - Args: - a_fw_inboard (float): Area of the inboard first wall section (m^2). - a_fw_outboard (float): Area of the outboard first wall section (m^2). - len_fw_channel (float): Length of each first wall channel (m). - dx_fw_module (float): Toroidal width of each first wall module (m). - - Returns: - tuple: Number of inboard and outboard first wall channels. + """Calculate the total number of first wall channels for inboard and outboard sections. + + Parameters + ---------- + a_fw_inboard: + Area of the inboard first wall section (m^2). + a_fw_outboard: + Area of the outboard first wall section (m^2). + len_fw_channel: + Length of each first wall channel (m). + dx_fw_module: + Toroidal width of each first wall module (m). + + Returns + ------- + tuple + Number of inboard and outboard first wall channels. """ n_fw_inboard_channels = a_fw_inboard / (len_fw_channel * dx_fw_module) n_fw_outboard_channels = a_fw_outboard / (len_fw_channel * dx_fw_module) return int(n_fw_inboard_channels), int(n_fw_outboard_channels) def output_fw_geometry(self): - """ - Outputs the first wall geometry details to the output file. - - Returns: - None - """ + """Outputs the first wall geometry details to the output file.""" po.oheadr(self.outfile, "First wall build") po.ovarrf( @@ -798,12 +861,7 @@ def output_fw_geometry(self): ) def output_fw_pumping(self): - """ - Outputs the first wall pumping details to the output file. - - Returns: - None - """ + """Outputs the first wall pumping details to the output file.""" po.oheadr(self.outfile, "First wall pumping") po.ovarst( diff --git a/process/geometry/blanket_geometry.py b/process/geometry/blanket_geometry.py index d6b3e0e2d2..3bdf42c889 100644 --- a/process/geometry/blanket_geometry.py +++ b/process/geometry/blanket_geometry.py @@ -24,32 +24,37 @@ def blanket_geometry_single_null( ) -> ArbitraryGeometry: """Calculates radial and vertical distances for the geometry of the blanket in a single null configuration - :param radx_outer: outboard radius of outer surface of blanket - :type radx_outer: float - :param rminx_outer: inboard radius of outer surface of blanket - :type rminx_outer: float - :param radx_inner: outboard radius of inner surface of blanket - :type radx_inner: float - :param rminx_inner: inboard radius of inner surface of blanket - :type rminx_inner: float - :param cumulative_upper: cumulative vertical thicknesses of components above the midplane - :type cumulative_upper: dict - :param triang: plasma triangularity - :type triang: float - :param cumulative_lower: cumulative vertical thicknesses of components below the midplane - :type cumulative_lower: dict - :param dz_blkt_upper: top blanket vertical thickness - :type dz_blkt_upper: float - :param c_shldith: inboard shield thickness - :type c_shldith: float - :param c_blnkoth: outboard blanket radial thickness - :type c_blnkoth: float - :param dr_blkt_inboard: inboard blanket radial thickness - :type dr_blkt_inboard: float - :param dr_blkt_outboard: outboard blanket radial thickness - :type dr_blkt_outboard: float - :return: dataclass returning radial and vertical coordinates - :rtype: ArbitraryGeometry + Parameters + ---------- + radx_outer: + outboard radius of outer surface of blanket + rminx_outer: + inboard radius of outer surface of blanket + radx_inner: + outboard radius of inner surface of blanket + rminx_inner: + inboard radius of inner surface of blanket + cumulative_upper: + cumulative vertical thicknesses of components above the midplane + triang: + plasma triangularity + cumulative_lower: + cumulative vertical thicknesses of components below the midplane + dz_blkt_upper: + top blanket vertical thickness + c_shldith: + inboard shield thickness + c_blnkoth: + outboard blanket radial thickness + dr_blkt_inboard: + inboard blanket radial thickness + dr_blkt_outboard: + outboard blanket radial thickness + + Returns + ------- + ArbitraryGeometry + dataclass returning radial and vertical coordinates """ # Upper blanket outer surface kapx = cumulative_upper["dz_blkt_upper"] / rminx_outer @@ -108,22 +113,27 @@ def blanket_geometry_lower( ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Calculates radial and vertical distances for the geometry of section of blanket below the midplane - :param triang: plasma triangularity - :type triang: float - :param dz_blkt_upper: top blanket vertical thickness - :type dz_blkt_upper: float - :param c_shldith: inboard shield thickness - :type c_shldith: float - :param c_blnkoth: outboard blanket radial thickness - :type c_blnkoth: float - :param dr_blkt_inboard: inboard blanket radial thickness - :type dr_blkt_inboard: float - :param dr_blkt_outboard: outboard blanket radial thickness - :type dr_blkt_outboard: float - :param divgap: divertor structure vertical thickness - :type divgap: float - :return: tuple containing the R coordinates for the outboard, Z coordinates for the outboard, R coordinates for the inboard, Z coordinates for the inboard of the blanket geometry below the midplane - :rtype: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] + Parameters + ---------- + triang: + plasma triangularity + dz_blkt_upper: + top blanket vertical thickness + c_shldith: + inboard shield thickness + c_blnkoth: + outboard blanket radial thickness + dr_blkt_inboard: + inboard blanket radial thickness + dr_blkt_outboard: + outboard blanket radial thickness + divgap: + divertor structure vertical thickness + + Returns + ------- + : + tuple containing the R coordinates for the outboard, Z coordinates for the outboard, R coordinates for the inboard, Z coordinates for the inboard of the blanket geometry below the midplane """ # Lower blanket rs1, rs2, rs3, rs4, zs1, zs2, zs3, zs4 = dhgap_vertices( @@ -157,22 +167,27 @@ def blanket_geometry_double_null( """Calculates radial and vertical distances for the geometry of blanket in a double null configuration In a double null configuration, the geometry of the lower blanket is reflected across the midplane to create the section of blanket above the midplane - :param cumulative_lower: cumulative vertical thicknesses of components below the midplane - :type cumulative_lower: dict - :param triang: plasma triangularity - :type triang: float - :param dz_blkt_upper: top blanket vertical thickness - :type dz_blkt_upper: float - :param c_shldith: inboard shield thickness - :type c_shldith: float - :param c_blnkoth: outboard blanket radial thickness - :type c_blnkoth: float - :param dr_blkt_inboard: inboard blanket radial thickness - :type dr_blkt_inboard: float - :param dr_blkt_outboard: outboard blanket radial thickness - :type dr_blkt_outboard: float - :return: dataclass returning radial and vertical coordinates - :rtype: ArbitraryGeometry + Parameters + ---------- + cumulative_lower: + cumulative vertical thicknesses of components below the midplane + triang: + plasma triangularity + dz_blkt_upper: + top blanket vertical thickness + c_shldith: + inboard shield thickness + c_blnkoth: + outboard blanket radial thickness + dr_blkt_inboard: + inboard blanket radial thickness + dr_blkt_outboard: + outboard blanket radial thickness + + Returns + ------- + ArbitraryGeometry + dataclass returning radial and vertical coordinates """ # Lower blanket divgap = cumulative_lower["dz_divertor"] diff --git a/process/geometry/cryostat_geometry.py b/process/geometry/cryostat_geometry.py index 2af9f9a96a..8687cf0c26 100644 --- a/process/geometry/cryostat_geometry.py +++ b/process/geometry/cryostat_geometry.py @@ -10,14 +10,19 @@ def cryostat_geometry( ) -> list[RectangleGeometry]: """Calculates rectangular geometries of the cryostat - :param r_cryostat_inboard: cryostat internal radius - :type r_cryostat_inboard: float - :param dr_cryostat: external cryostat thickness - :type dr_cryostat: float - :param z_cryostat_half_inside: cryostat internal half-height - :type z_cryostat_half_inside: float - :return: list of RectangleGeometry - dataclass returning rectangular geometry parameters - :rtype: List[RectangleGeometry] + Parameters + ---------- + r_cryostat_inboard: + cryostat internal radius + dr_cryostat: + external cryostat thickness + z_cryostat_half_inside: + cryostat internal half-height + + Returns + ------- + : + list of RectangleGeometry - dataclass returning rectangular geometry parameters """ # The cryostat is represented by 4 rectangular sections as follows: diff --git a/process/geometry/firstwall_geometry.py b/process/geometry/firstwall_geometry.py index f9f7df6710..cbcce86b9a 100644 --- a/process/geometry/firstwall_geometry.py +++ b/process/geometry/firstwall_geometry.py @@ -25,34 +25,39 @@ def first_wall_geometry_single_null( ) -> ArbitraryGeometry: """Calculates radial and vertical distances for the geometry of first wall in a single null configuration - :param radx_outer: outboard radius of outer surface of first wall - :type radx_outer: float - :param rminx_outer: inboard radius of outer surface of first wall - :type rminx_outer: float - :param radx_inner: outboard radius of inner surface of first wall - :type radx_inner: float - :param rminx_inner: inboard radius of inner surface of first wall - :type rminx_inner: float - :param cumulative_upper: cumulative vertical thicknesses of components above the midplane - :type cumulative_upper: dict - :param triang: plasma triangularity - :type triang: float - :param cumulative_lower: cumulative vertical thicknesses of components below the midplane - :type cumulative_lower: dict - :param dz_blkt_upper: top blanket vertical thickness - :type dz_blkt_upper: float - :param c_blnkith: inboard blanket vertical thickness - :type c_blnkith: float - :param c_fwoth: outboard first wall vertical thickness - :type c_fwoth: float - :param dr_fw_inboard: inboard first wall radial thickness - :type dr_fw_inboard: float - :param dr_fw_outboard: outboard first wall radial thickness - :type dr_fw_outboard: float - :param tfwvt: top first wall vertical thickness - :type tfwvt: float - :return: dataclass returning radial and vertical coordinates - :rtype: ArbitraryGeometry + Parameters + ---------- + radx_outer: + outboard radius of outer surface of first wall + rminx_outer: + inboard radius of outer surface of first wall + radx_inner: + outboard radius of inner surface of first wall + rminx_inner: + inboard radius of inner surface of first wall + cumulative_upper: + cumulative vertical thicknesses of components above the midplane + triang: + plasma triangularity + cumulative_lower: + cumulative vertical thicknesses of components below the midplane + dz_blkt_upper: + top blanket vertical thickness + c_blnkith: + inboard blanket vertical thickness + c_fwoth: + outboard first wall vertical thickness + dr_fw_inboard: + inboard first wall radial thickness + dr_fw_outboard: + outboard first wall radial thickness + tfwvt: + top first wall vertical thickness + + Returns + ------- + ArbitraryGeometry + dataclass returning radial and vertical coordinates """ # Upper first wall: outer surface kapx = cumulative_upper["dz_fw_upper"] / rminx_outer @@ -110,22 +115,28 @@ def first_wall_geometry_lower( ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Calculates radial and vertical distances for the geometry of section of first wall below the midplane - :param triang: plasma triangularity - :type triang: float - :param c_blnkith: inboard blanket vertical thickness - :type c_blnkith: float - :param c_fwoth: outboard first wall vertical thickness - :type c_fwoth: float - :param dr_fw_inboard: inboard first wall radial thickness - :type dr_fw_inboard: float - :param dr_fw_outboard: outboard first wall radial thickness - :type dr_fw_outboard: float - :param tfwvt: top first wall vertical thickness - :type tfwvt: float - :param top_point: top point for plotdhgap, equal to - :type top_point: float - :return: tuple containing the R coordinates for the outboard, Z coordinates for the outboard, R coordinates for the inboard, Z coordinates for the inboard of the first wall geometry below the midplane - :rtype: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] + Parameters + ---------- + triang: + plasma triangularity + c_blnkith: + inboard blanket vertical thickness + c_fwoth: + outboard first wall vertical thickness + dr_fw_inboard: + inboard first wall radial thickness + dr_fw_outboard: + outboard first wall radial thickness + tfwvt: + top first wall vertical thickness + top_point: + top point for plotdhgap, equal to + + Returns + ------- + : + tuple containing the R coordinates for the outboard, Z coordinates for the outboard, + R coordinates for the inboard, Z coordinates for the inboard of the first wall geometry below the midplane """ # Lower first wall rs1, rs2, rs3, rs4, zs1, zs2, zs3, zs4 = dhgap_vertices( @@ -160,24 +171,29 @@ def first_wall_geometry_double_null( """Calculates radial and vertical distances for the geometry of first wall in a double null configuration In a double null configuration, the geometry of the lower first wall is reflected across the midplane to create the section of first wall above the midplane - :param cumulative_lower: cumulative vertical thicknesses of components below the midplane - :type cumulative_lower: dict - :param triang: plasma triangularity - :type triang: float - :param dz_blkt_upper: top blanket vertical thickness - :type dz_blkt_upper: float - :param c_blnkith: inboard blanket vertical thickness - :type c_blnkith: float - :param c_fwoth: outboard first wall vertical thickness - :type c_fwoth: float - :param dr_fw_inboard: inboard first wall radial thickness - :type dr_fw_inboard: float - :param dr_fw_outboard: outboard first wall radial thickness - :type dr_fw_outboard: float - :param tfwvt: top first wall vertical thickness - :type tfwvt: float - :return: dataclass returning radial and vertical coordinates - :rtype: ArbitraryGeometry + Parameters + ---------- + cumulative_lower: + cumulative vertical thicknesses of components below the midplane + triang: + plasma triangularity + dz_blkt_upper: + top blanket vertical thickness + c_blnkith: + inboard blanket vertical thickness + c_fwoth: + outboard first wall vertical thickness + dr_fw_inboard: + inboard first wall radial thickness + dr_fw_outboard: + outboard first wall radial thickness + tfwvt: + top first wall vertical thickness + + Returns + ------- + ArbitraryGeometry + dataclass returning radial and vertical coordinates """ # Lower first wall divgap = cumulative_lower["dz_divertor"] diff --git a/process/geometry/geometry_parameterisations.py b/process/geometry/geometry_parameterisations.py index 5a89eafb8c..39592832c7 100644 --- a/process/geometry/geometry_parameterisations.py +++ b/process/geometry/geometry_parameterisations.py @@ -25,7 +25,8 @@ class RectangleGeometry: class ArbitraryGeometry: """Holds radial and vertical coordinates for arbitrary reactor component shapes - Example: a triangular shaped component with vertices [(0,0), (1,0), (0,1)] would be represented by ArbitraryGeometry(rs=[0,1,0], zs=[0,0,1])""" + Example: a triangular shaped component with vertices [(0,0), (1,0), (0,1)] would be represented by ArbitraryGeometry(rs=[0,1,0], zs=[0,0,1]) + """ rs: np.ndarray """outboard and inboard radial coordinates""" diff --git a/process/geometry/pfcoil_geometry.py b/process/geometry/pfcoil_geometry.py index 2b993725f0..3e39ac2ddd 100644 --- a/process/geometry/pfcoil_geometry.py +++ b/process/geometry/pfcoil_geometry.py @@ -18,22 +18,27 @@ def pfcoil_geometry( ) -> tuple[np.ndarray, np.ndarray, RectangleGeometry]: """Calculates radial and vertical distances for the geometry of the pf coils and central coil - :param coils_r: list of pf coil radii - :type coils_r: List[float] - :param coils_z: list of pf coil vertical positions - :type coils_z: List[float] - :param coils_dr: list of pf coil radial thicknesses - :type coils_dr: List[float] - :param coils_dz: list of pf coil vertical thicknesses - :type coils_dz: List[float] - :param dr_bore: central solenoid inboard radius - :type dr_bore: float - :param dr_cs: central solenoid thickness - :type dr_cs: float - :param ohdz: central solenoid vertical thickness - :type ohdz: float - :return: tuple containing radial and vertical coordinates for pf coils, and dataclass returning coordinates representing a rectangular geometry used to plot the central coil - :rtype: Tuple[np.ndarray, np.ndarray, RectangleGeometry] + Parameters + ---------- + coils_r: + list of pf coil radii + coils_z: + list of pf coil vertical positions + coils_dr: + list of pf coil radial thicknesses + coils_dz: + list of pf coil vertical thicknesses + dr_bore: + central solenoid inboard radius + dr_cs: + central solenoid thickness + ohdz: + central solenoid vertical thickness + + Returns + ------- + : + tuple containing radial and vertical coordinates for pf coils, and dataclass returning coordinates representing a rectangular geometry used to plot the central coil """ r_points = [] z_points = [] diff --git a/process/geometry/plasma_geometry.py b/process/geometry/plasma_geometry.py index f6f338c657..d9e64426c0 100644 --- a/process/geometry/plasma_geometry.py +++ b/process/geometry/plasma_geometry.py @@ -29,30 +29,33 @@ def plasma_geometry( i_plasma_shape: int, square: float, ) -> PlasmaGeometry: - """ - Calculates radial and vertical distances and plasma elongation for the geometry of the plasma. + """Calculates radial and vertical distances and plasma elongation for the geometry of the plasma. This function computes the radial and vertical coordinates of the plasma boundary, as well as the plasma elongation, based on the given major radius, minor radius, triangularity, and elongation at 95% of the plasma surface. It also considers whether the plasma configuration is single null or double null. - :param rmajor: Plasma major radius. - :type rmajor: float - :param rminor: Plasma minor radius. - :type rminor: float - :param triang: Plasma triangularity at separatrix. - :type triang: float - :param kappa: Plasma elongation at separatrix. - :type kappa: float - :param i_single_null: Switch for single null (1) or double null (0) plasma configuration. - :type i_single_null: int - :param i_plasma_shape: Switch for plasma shape (0 for double arc, 1 for Sauter). - :type i_plasma_shape: int - :param square: Square term for Sauter plasma shape. - :type square: float - :returns: A dataclass containing the plasma elongation and the radial and vertical coordinates of the plasma. - :rtype: PlasmaGeometry - + Parameters + ---------- + rmajor: + Plasma major radius. + rminor: + Plasma minor radius. + triang: + Plasma triangularity at separatrix. + kappa: + Plasma elongation at separatrix. + i_single_null: + Switch for single null (1) or double null (0) plasma configuration. + i_plasma_shape: + Switch for plasma shape (0 for double arc, 1 for Sauter). + square: + Square term for Sauter plasma shape. + + Returns + ------- + PlasmaGeometry + A dataclass containing the plasma elongation and the radial and vertical coordinates of the plasma. """ # Original PROCESS double arc plasma shape diff --git a/process/geometry/shield_geometry.py b/process/geometry/shield_geometry.py index 8d2dd056bd..99a83839a7 100644 --- a/process/geometry/shield_geometry.py +++ b/process/geometry/shield_geometry.py @@ -19,22 +19,25 @@ def shield_geometry_single_null( ) -> ArbitraryGeometry: """Calculates radial and vertical distances for the geometry of shield in a single null configuration - :param cumulative_upper: cumulative vertical thicknesses of components above the midplane - :type cumulative_upper: dict - :param radx_far: outboard radius of outer surface of shield - :type radx_far: float - :param rminx_far: inboard radius of outer surface of shield - :type rminx_far: float - :param radx_near: outboard radius of inner surface of shield - :type radx_near: float - :param rminx_near: inboard radius of inner surface of shield - :type rminx_near: float - :param triang: plasma triangularity - :type triang: float - :param cumulative_lower: cumulative vertical thicknesses of components below the midplane - :type cumulative_lower: dict - :return: dataclass returning radial and vertical coordinates - :rtype: ArbitraryGeometry + Parameters + ---------- + cumulative_upper: + cumulative vertical thicknesses of components above the midplane + radx_far: + outboard radius of outer surface of shield + rminx_far: + inboard radius of outer surface of shield + radx_near: + outboard radius of inner surface of shield + rminx_near: + inboard radius of inner surface of shield + triang: + plasma triangularity + + Returns + ------- + ArbitraryGeometry + dataclass returning radial and vertical coordinates """ # Upper shield # Side furthest from plasma @@ -88,20 +91,25 @@ def shield_geometry_lower( ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Calculates radial and vertical distances for the geometry of section of shield below the midplane - :param cumulative_lower: cumulative vertical thicknesses of components below the midplane - :type cumulative_lower: dict - :param radx_far: outboard radius of outer surface of shield - :type radx_far: float - :param rminx_far: inboard radius of outer surface of shield - :type rminx_far: float - :param radx_near: outboard radius of inner surface of shield - :type radx_near: float - :param rminx_near: inboard radius of inner surface of shield - :type rminx_near: float - :param triang: plasma triangularity - :type triang: float - :return: tuple containing the R coordinates for the outboard, Z coordinates for the outboard, R coordinates for the inboard, Z coordinates for the inboard of the shield geometry below the midplane - :rtype: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] + Parameters + ---------- + cumulative_lower: + cumulative vertical thicknesses of components below the midplane + radx_far: + outboard radius of outer surface of shield + rminx_far: + inboard radius of outer surface of shield + radx_near: + outboard radius of inner surface of shield + rminx_near: + inboard radius of inner surface of shield + triang: + plasma triangularity + + Returns + ------- + Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] + tuple containing the R coordinates for the outboard, Z coordinates for the outboard, R coordinates for the inboard, Z coordinates for the inboard of the shield geometry below the midplane """ # Side furthest from plasma kapx = cumulative_lower["dz_shld_lower"] / rminx_far @@ -125,20 +133,25 @@ def shield_geometry_double_null( """Calculates radial and vertical distances for the geometry of shield in a double null configuration In a double null configuration, the geometry of the lower shield is reflected across the midplane to create the section of shield above the midplane - :param cumulative_lower: cumulative vertical thicknesses of components below the midplane - :type cumulative_lower: dict - :param radx_far: outboard radius of outer surface of shield - :type radx_far: float - :param rminx_far: inboard radius of outer surface of shield - :type rminx_far: float - :param radx_near: outboard radius of inner surface of shield - :type radx_near: float - :param rminx_near: inboard radius of inner surface of shield - :type rminx_near: float - :param triang: plasma triangularity - :type triang: float - :return: dataclass returning radial and vertical coordinates - :rtype: ArbitraryGeometry + Parameters + ---------- + cumulative_lowe: + cumulative vertical thicknesses of components below the midplane + radx_far: + outboard radius of outer surface of shield + rminx_far: + inboard radius of outer surface of shield + radx_near: + outboard radius of inner surface of shield + rminx_near: + inboard radius of inner surface of shield + triang: + plasma triangularity + + Returns + ------- + ArbitraryGeometry + dataclass returning radial and vertical coordinates """ # Lower shield ( diff --git a/process/geometry/tfcoil_geometry.py b/process/geometry/tfcoil_geometry.py index d0ab9711cb..efa062d59c 100644 --- a/process/geometry/tfcoil_geometry.py +++ b/process/geometry/tfcoil_geometry.py @@ -22,28 +22,33 @@ def tfcoil_geometry_rectangular_shape( ) -> list[RectangleGeometry]: """Calculates rectangular geometries for tf coils in a picture frame/rectangular shape parametrization - :param x1: radial location of arc point 1 - :type x1: float - :param x2: radial location of arc point 2 - :type x2: float - :param x4: radial location of arc point 4 - :type x4: float - :param x5: radial location of arc point 5 - :type x5: float - :param y1: vertical location of arc point 1 - :type y1: float - :param y2: vertical location of arc point 2 - :type y2: float - :param y4: vertical location of arc point 4 - :type y4: float - :param y5: vertical location of arc point 5 - :type y5: float - :param dr_tf_inboard: inboard tf coil thickness - :type dr_tf_inboard: float - :param offset_in: an increase in the thickness of the geometry on the inside - :type offset_in: float - :return: list of RectangleGeometry - dataclass returning rectangular geometry parameters - :rtype: List[RectangleGeometry] + Parameters + ---------- + x1: + radial location of arc point 1 + x2: + radial location of arc point 2 + x4: + radial location of arc point 4 + x5: + radial location of arc point 5 + y1: + vertical location of arc point 1 + y2: + vertical location of arc point 2 + y4: + vertical location of arc point 4 + y5: + vertical location of arc point 5 + dr_tf_inboard: + inboard tf coil thickness + offset_in: + an increase in the thickness of the geometry on the inside + + Returns + ------- + : + list of RectangleGeometry - dataclass returning rectangular geometry parameters """ # In this geometry, the tf coil is represented by 4 rectangular sections as follows: return [ @@ -93,34 +98,39 @@ def tfcoil_geometry_d_shape( ) -> tuple[list[RectangleGeometry], list[list[tuple[float, float]]]]: """Calculates radial and vertical distances for the geometry of the tf coils in a D-shape parametrization - :param x1: radial location of arc point 1 - :type x1: float - :param x2: radial location of arc point 2 - :type x2: float - :param x3: radial location of arc point 3 - :type x3: float - :param x4: radial location of arc point 4 - :type x4: float - :param x5: radial location of arc point 5 - :type x5: float - :param y1: vertical location of arc point 1 - :type y1: float - :param y2: vertical location of arc point 2 - :type y2: float - :param y4: vertical location of arc point 4 - :type y4: float - :param y5: vertical location of arc point 5 - :type y5: float - :param dr_tf_inboard: inboard tf coil thickness - :type dr_tf_inboard: float - :param rtangle: angle used in tf coil parametrization - :type rtangle: float - :param rtangle2: angle used in tf coil parametrization - :type rtangle2: float - :param offset_in: an increase in the thickness of the geometry on the inside - :type offset_in: float - :return: radial and vertical coordinates for tf coils - :rtype: Tuple[List[RectangleGeometry], List[List[Tuple[float, float]]]] + Parameters + ---------- + x1: + radial location of arc point 1 + x2: + radial location of arc point 2 + x3: + radial location of arc point 3 + x4: + radial location of arc point 4 + x5: + radial location of arc point 5 + y1: + vertical location of arc point 1 + y2: + vertical location of arc point 2 + y4: + vertical location of arc point 4 + y5: + vertical location of arc point 5 + dr_tf_inboard: + inboard tf coil thickness + rtangle: + angle used in tf coil parametrization + rtangle2: + angle used in tf coil parametrization + offset_in: + an increase in the thickness of the geometry on the inside + + Returns + ------- + : + radial and vertical coordinates for tf coils """ return_rects = [] return_verts = [] diff --git a/process/geometry/utils.py b/process/geometry/utils.py index 2a5c594f7a..8890fab4b3 100644 --- a/process/geometry/utils.py +++ b/process/geometry/utils.py @@ -10,16 +10,21 @@ def dh_vertices( ) -> tuple[np.ndarray, np.ndarray]: """Returns the radial and vertical coordinates which, when plotted, plots half a thin D-section, centred on z = 0 - :param r0: major radius of centre - :type r0: float - :param a: horizontal radius - :type a: float - :param triang: plasma triangularity - :type triang: float - :param kap: plasma elongation - :type kap: float - :return: tuple containing radial and vertical coordinates which, when plotted, plots a half thin D-section with a gap - :rtype: Tuple[np.ndarray, np.ndarray] + Parameters + ---------- + r0: + major radius of centre + a: + horizontal radius + triang: + plasma triangularity + kap: + plasma elongation + + Returns + ------- + : + tuple containing radial and vertical coordinates which, when plotted, plots a half thin D-section with a gap """ angs = np.linspace(0, np.pi, 50, endpoint=True) rs = r0 + a * np.cos(angs + triang * np.sin(1.0 * angs)) @@ -47,22 +52,27 @@ def dhgap_vertices( ]: """Returns the radial and vertical coordinates which, when plotted, plots a half thick D-section with a gap - :param inpt: inner point - :type inpt: float - :param outpt: outer point - :type outpt: float - :param inthk: inner thickness - :type inthk: float - :param outthk: outer thickness - :type outthk: float - :param toppt: top point - :type toppt: float - :param topthk: top thickness - :type topthk: float - :param triang: plasma triangularity - :type triang: float - :return: tuple containing radial and vertical coordinates which, when plotted, plots a half thick D-section with a gap - :rtype: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,] + Parameters + ---------- + inpt: + inner point + outpt: + outer point + inthk: + inner thickness + outthk: + outer thickness + toppt: + top point + topthk: + top thickness + triang: + plasma triangularity + + Returns + ------- + : + tuple containing radial and vertical coordinates which, when plotted, plots a half thick D-section with a gap """ arc = np.pi / 4.0 r01 = (inpt + outpt) / 2.0 @@ -97,24 +107,29 @@ def ellips_fill_vertices( ) -> list[tuple[float, float]]: """Returns the vertices of a shape which, when filled, fills the space between two concentric ellipse sectors - :param a1: horizontal radius to be filled, defaults to 0 - :type a1: float, optional - :param a2: horizontal radius to be filled, defaults to 0 - :type a2: float, optional - :param b1: vertical radius to be filled, defaults to 0 - :type b1: float, optional - :param b2: vertical radius to be filled, defaults to 0 - :type b2: float, optional - :param x0: x coordinate of centre of ellipses, defaults to 0 - :type x0: float, optional - :param y0: y coordinate of centre of ellipses, defaults to 0 - :type y0: float, optional - :param ang1: polar angle at start, defaults to 0 - :type ang1: float, optional - :param ang2: polar angle at end, defaults to np.pi/2 - :type ang2: float, optional - :return: list containing (R,Z) coordinates which, when plotted, fill space between ellipses - :rtype: List[Tuple[float, float]] + Parameters + ---------- + a1: + horizontal radius to be filled, defaults to 0 + a2: + horizontal radius to be filled, defaults to 0 + b1: + vertical radius to be filled, defaults to 0 + b2: + vertical radius to be filled, defaults to 0 + x0: + x coordinate of centre of ellipses, defaults to 0 + y0: + y coordinate of centre of ellipses, defaults to 0 + ang1: + polar angle at start, defaults to 0 + ang2: + polar angle at end, defaults to np.pi/2 + + Returns + ------- + : + list containing (R,Z) coordinates which, when plotted, fill space between ellipses """ angs = np.linspace(ang1, ang2, endpoint=True) r1 = ((np.cos(angs) / a1) ** 2 + (np.sin(angs) / b1) ** 2) ** (-0.5) diff --git a/process/geometry/vacuum_vessel_geometry.py b/process/geometry/vacuum_vessel_geometry.py index fce5ed6a4d..78d6a5e89d 100644 --- a/process/geometry/vacuum_vessel_geometry.py +++ b/process/geometry/vacuum_vessel_geometry.py @@ -21,26 +21,31 @@ def vacuum_vessel_geometry_single_null( ) -> ArbitraryGeometry: """Calculates radial and vertical distances for the geometry of the vacuum vessel in a single null configuration - :param cumulative_upper: cumulative vertical thicknesses of components above the midplane - :type cumulative_upper: dict - :param upper: vertical thicknesses of components above the midplane - :type upper: dict - :param triang: plasma triangularity - :type triang: float - :param radx_outer: outboard radius of outer surface of vacuum vessel - :type radx_outer: float - :param rminx_outer: inboard radius of outer surface of vacuum vessel - :type rminx_outer: float - :param radx_inner: outboard radius of inner surface of vacuum vessel - :type radx_inner: float - :param rminx_inner: inboard radius of inner surface of vacuum vessel - :type rminx_inner: float - :param cumulative_lower: cumulative vertical thicknesses of components below the midplane - :type cumulative_lower: dict - :param lower: vertical thicknesses of components below the midplane - :type lower: dict - :return: dataclass returning radial and vertical coordinates - :rtype: ArbitraryGeometry + Parameters + ---------- + cumulative_upper: + cumulative vertical thicknesses of components above the midplane + upper: + vertical thicknesses of components above the midplane + triang: + plasma triangularity + radx_outer: + outboard radius of outer surface of vacuum vessel + rminx_outer: + inboard radius of outer surface of vacuum vessel + radx_inner: + outboard radius of inner surface of vacuum vessel + rminx_inner: + inboard radius of inner surface of vacuum vessel + cumulative_lower: + cumulative vertical thicknesses of components below the midplane + lower: + vertical thicknesses of components below the midplane + + Returns + ------- + ArbitraryGeometry + dataclass returning radial and vertical coordinates """ # Upper vacuum vessel kapx = cumulative_upper["dz_vv_upper"] / rminx_outer @@ -100,22 +105,27 @@ def vacuum_vessel_geometry_lower( ) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Calculates radial and vertical distances for the geometry of section of vacuum vessel below the midplane - :param cumulative_lower: cumulative vertical thicknesses of components below the midplane - :type cumulative_lower: dict - :param lower: vertical thicknesses of components below the midplane - :type lower: dict - :param triang: plasma triangularity - :type triang: float - :param radx_outer: outboard radius of outer surface of vacuum vessel - :type radx_outer: float - :param rminx_outer: inboard radius of outer surface of vacuum vessel - :type rminx_outer: float - :param radx_inner: outboard radius of inner surface of vacuum vessel - :type radx_inner: float - :param rminx_inner: inboard radius of inner surface of vacuum vessel - :type rminx_inner: float - :return: tuple containing the R coordinates for the outboard, Z coordinates for the outboard, R coordinates for the inboard, Z coordinates for the inboard of the vacuum vessel geometry below the midplane - :rtype: Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray] + Parameters + ---------- + cumulative_lower: + cumulative vertical thicknesses of components below the midplane + lower: + vertical thicknesses of components below the midplane + triang: + plasma triangularity + radx_outer: + outboard radius of outer surface of vacuum vessel + rminx_outer: + inboard radius of outer surface of vacuum vessel + radx_inner: + outboard radius of inner surface of vacuum vessel + rminx_inner: + inboard radius of inner surface of vacuum vessel + + Returns + ------- + : + tuple containing the R coordinates for the outboard, Z coordinates for the outboard, R coordinates for the inboard, Z coordinates for the inboard of the vacuum vessel geometry below the midplane """ kapx = cumulative_lower["dz_vv_lower"] / rminx_outer rs_lower_outboard, zs_lower_outboard = dh_vertices( @@ -144,22 +154,27 @@ def vacuum_vessel_geometry_double_null( """Calculates radial and vertical distances for the geometry of vacuum vessel in a double null configuration In a double null configuration, the geometry of the lower vacuum vessel is reflected across the midplane to create the section of vacuum vessel above the midplane - :param cumulative_lower: cumulative vertical thicknesses of components below the midplane - :type cumulative_lower: dict - :param lower: vertical thicknesses of components below the midplane - :type lower: dict - :param triang: plasma triangularity - :type triang: float - :param radx_outer: outboard radius of outer surface of vacuum vessel - :type radx_outer: float - :param rminx_outer: inboard radius of outer surface of vacuum vessel - :type rminx_outer: float - :param radx_inner: outboard radius of inner surface of vacuum vessel - :type radx_inner: float - :param rminx_inner: inboard radius of inner surface of vacuum vessel - :type rminx_inner: float - :return: dataclass returning radial and vertical coordinates - :rtype: ArbitraryGeometry + Parameters + ---------- + cumulative_lower: + cumulative vertical thicknesses of components below the midplane + lower: + vertical thicknesses of components below the midplane + triang: + plasma triangularity + radx_outer: + outboard radius of outer surface of vacuum vessel + rminx_outer: + inboard radius of outer surface of vacuum vessel + radx_inner: + outboard radius of inner surface of vacuum vessel + rminx_inner: + inboard radius of inner surface of vacuum vessel + + Returns + ------- + ArbitraryGeometry + dataclass returning radial and vertical coordinates """ # Lower vacuum vessel ( diff --git a/process/hcpb.py b/process/hcpb.py index 855fb1ae62..598f2f3e18 100644 --- a/process/hcpb.py +++ b/process/hcpb.py @@ -33,7 +33,8 @@ class CCFE_HCPB(OutboardBlanket, InboardBlanket): based on CCFE HCPB model from the PROCESS engineering paper PROCESS Engineering paper (M. Kovari et al.) - :References: + References + ---------- - M. Kovari et al., “PROCESS: A systems code for fusion power plants - Part 2: Engineering,” Fusion Engineering and Design, vol. 104, pp. 9-20, Mar. 2016, doi: https://doi.org/10.1016/j.fusengdes.2016.01.007. @@ -85,8 +86,8 @@ def run(self, output: bool): # Solid angle fraction of neutrons that hit the centrepost shield [-] # Calculating the CP solid angle coverage fraction # Rem : This calculation considered the shield flaring - # while the MCNP based neutronincs considers a - # cylindre + # while the MCNP based neutronics considers a + # cylinder f_geom_cp = self.st_cp_angle_fraction( h_sh_max_r, build_variables.r_sh_inboard_out, @@ -120,7 +121,7 @@ def run(self, output: bool): self.component_masses() # Calculate the nuclear heating - # Rem : The heating power will be normalized to the neutron power using + # Rem : The heating power will be normalised to the neutron power using # the divertor and the centrepost (for itart == 1), self.nuclear_heating_magnets(output=output) @@ -152,7 +153,7 @@ def run(self, output: bool): ) # Normalisation of the nuclear heating - # The nuclear heating are noramalized assuming no energy multiplication + # The nuclear heating are normalised assuming no energy multiplication # in the divertor and the centrepost # Assume that all the neutrons are absorbed. (Not applicable for very thin blankets) # Rem SK : This calculation effectively only uses the angular fractions to get @@ -160,7 +161,7 @@ def run(self, output: bool): # Split neutron power to main wall between fw, bkt, shld and TF with same # fractions as before. - # Total nuclear power deposited in the blancket sector (MW) + # Total nuclear power deposited in the blanket sector (MW) ccfe_hcpb_module.pnuc_tot_blk_sector = ( fwbs_variables.p_fw_nuclear_heat_total_mw + fwbs_variables.p_blkt_nuclear_heat_total_mw @@ -254,7 +255,7 @@ def run(self, output: bool): def component_masses(self): """Calculations for component masses - author: J. Morris, CCFE, Culham Science Centre + This model used to be in the blanket library. However, it only appears to contain code relevant to hcpb. @@ -433,11 +434,15 @@ def component_masses(self): def nuclear_heating_magnets(self, output: bool): """Nuclear heating in the magnets for CCFE HCPB model - author: Michael Kovari, CCFE, Culham Science Centre - author: J. Morris, CCFE, Culham Science Centre + This subroutine calculates the nuclear heating in the coils. PROCESS Engineering paper (M. Kovari et al.) + + Parameters + ---------- + output: bool + """ # Model factors and coefficients @@ -589,23 +594,26 @@ def nuclear_heating_fw( fw_armour_u_nuc_heating: float, p_fusion_total_mw: float, ) -> float: - """ - Calculate the nuclear heating in the first wall (FW) for the CCFE HCPB model. - - :param m_fw_total: Total mass of the first wall (kg). - :type m_fw_total: float - :param fw_armour_u_nuc_heating: Unit nuclear heating of the FW and armour (W/kg per W of fusion power). - :type fw_armour_u_nuc_heating: float - :param p_fusion_total_mw: Total fusion power (MW). - :type p_fusion_total_mw: float - - :returns: Total nuclear heating in the first wall (MW). - :rtype: float - - :raises ProcessValueError: If the calculated nuclear heating is negative. - - - This subroutine calculates the nuclear heating in the FW. + """Calculate the nuclear heating in the first wall (FW) for the CCFE HCPB model. + + Parameters + ---------- + m_fw_total: + Total mass of the first wall (kg). + fw_armour_u_nuc_heating: + Unit nuclear heating of the FW and armour (W/kg per W of fusion power). + p_fusion_total_mw: + Total fusion power (MW). + + Returns + ------- + : + Total nuclear heating in the first wall (MW). + + Raises + ------ + ProcessValueError + If the calculated nuclear heating is negative. """ # Total nuclear heating in FW (MW) @@ -626,21 +634,25 @@ def nuclear_heating_fw( def nuclear_heating_blanket( self, m_blkt_total: float, p_fusion_total_mw: float ) -> tuple[float, float]: - """ - Calculates the nuclear heating in the blanket for the CCFE HCPB model. - - :param m_blkt_total: Total mass of the blanket in kilograms. - :type m_blkt_total: float - :param p_fusion_total_mw: Total fusion power in megawatts. - :type p_fusion_total_mw: float - - :returns: - - p_blkt_nuclear_heat_total_mw (float): Total nuclear heating in the blanket (MW). + """Calculates the nuclear heating in the blanket for the CCFE HCPB model. + + Parameters + ---------- + m_blkt_total: + Total mass of the blanket in kilograms. + p_fusion_total_mw: + Total fusion power in megawatts. + + Returns + ------- + : + p_blkt_nuclear_heat_total_mw (float): Total nuclear heating in the blanket (MW). - exp_blanket (float): Exponential blanket factor (dimensionless). - :rtype: tuple[float, float] - - :raises ProcessValueError: If the calculated nuclear heating is less than 1 MW. + Raises + ------ + ProcessValueError + If the calculated nuclear heating is less than 1 MW. """ # Blanket nuclear heating coefficient and exponent a = 0.764 @@ -672,34 +684,37 @@ def nuclear_heating_shield( x_blanket: float, p_fusion_total_mw: float, ) -> tuple[float, float, float, float]: - """ - Calculate the nuclear heating in the shield for the CCFE HCPB model. - - :param itart: Indicator for spherical tokamak (1 if ST, else 0). - :type itart: int - :param dr_shld_outboard: Outboard shield thickness (m). - :type dr_shld_outboard: float - :param dr_shld_inboard: Inboard shield thickness (m). - :type dr_shld_inboard: float - :param shield_density: Shield smeared density (kg/m^3). - :type shield_density: float - :param whtshld: Shield mass (kg). - :type whtshld: float - :param x_blanket: Blanket line density (tonne/m^2). - :type x_blanket: float - :param p_fusion_total_mw: Total fusion power (MW). - :type p_fusion_total_mw: float - - :returns: - - p_shld_nuclear_heat_mw (float): Total nuclear heating in shield (MW). - - exp_shield1 (float): First exponential factor for shield heating. - - exp_shield2 (float): Second exponential factor for shield heating. - - shld_u_nuc_heating (float): Unit nuclear heating of shield (W/kg/GW of fusion power) x mass. - :rtype: tuple[float, float, float, float] + """Calculate the nuclear heating in the shield for the CCFE HCPB model. This method calculates the nuclear heating in the shield using empirical coefficients and exponents, based on the shield's geometry, density, and the total fusion power. The calculation distinguishes between spherical tokamak and conventional configurations for the average shield thickness. + + Parameters + ---------- + itart: + Indicator for spherical tokamak (1 if ST, else 0). + dr_shld_outboard: + Outboard shield thickness (m). + dr_shld_inboard: + Inboard shield thickness (m). + shield_density: + Shield smeared density (kg/m^3). + whtshld: + Shield mass (kg). + x_blanket: + Blanket line density (tonne/m^2). + p_fusion_total_mw: + Total fusion power (MW). + + Returns + ------- + : + p_shld_nuclear_heat_mw (float): Total nuclear heating in shield (MW). + - exp_shield1 (float): First exponential factor for shield heating. + - exp_shield2 (float): Second exponential factor for shield heating. + - shld_u_nuc_heating (float): Unit nuclear heating of shield (W/kg/GW of fusion power) x mass. + """ # Shield nuclear heating coefficients and exponents @@ -730,8 +745,11 @@ def nuclear_heating_shield( def powerflow_calc(self, output: bool): """Calculations for powerflow - author: J. Morris, CCFE, Culham Science Centre - Calculations for powerflow + + Parameters + ---------- + output: + """ # Radiation power incident on HCD apparatus (MW) @@ -961,19 +979,28 @@ def powerflow_calc(self, output: bool): ) def st_cp_angle_fraction(self, z_cp_top, r_cp_mid, r_cp_top, rmajor): - """Author : S. Kahn, CCFE, Culham science centre + """ Estimates the CP angular solid angle coverage fration Equation (1-3) from ref : P. Guest THE-REVIEW OF SCIENTIFIC INSTRUMENTS, vol 32, n 2 (1960) Initial, but undocumented calculation kept as commented section without any talor expansion approximation - :param z_cp_top: Centrepost shield half height [m] - :param r_cp_top: Centrepost top radius [m] - :param r_cp_mid: Centrepost mid-plane radius [m] - :param rmajor: Plasma major radius [m] - - :returns: Solid angle fraction covered by the CP [-] + Parameters + ---------- + z_cp_top : + Centrepost shield half height [m] + r_cp_top : + Centrepost top radius [m] + r_cp_mid : + Centrepost mid-plane radius [m] + rmajor : + Plasma major radius [m] + + Returns + ------- + type + Solid angle fraction covered by the CP [-] """ n_integral = 10 @@ -986,7 +1013,7 @@ def st_cp_angle_fraction(self, z_cp_top, r_cp_mid, r_cp_top, rmajor): # * atan(r_cp_outer/(rmajor-r_cp_outer) )/pi # ------------------- - # Major radius normalized to the CP average radius [-] + # Major radius normalised to the CP average radius [-] rho_maj = 2.0 * rmajor / (r_cp_mid + r_cp_top) # Average CP extent in the toroidal plane [rad] @@ -1028,7 +1055,7 @@ def st_cp_angle_fraction(self, z_cp_top, r_cp_mid, r_cp_top, rmajor): return 0.25 * cp_sol_angle / np.pi def st_tf_centrepost_fast_neut_flux(self, p_neutron_total_mw, sh_width, rmajor): - """Author S Kahn + """ Routine calculating the fast neutron (E > 0.1 MeV) flux reaching the TF at the centerpost. These calcualtion are made from a CP only MCNP fit with a variable tungsten carbyde shield with 13% water cooling. The @@ -1038,9 +1065,14 @@ def st_tf_centrepost_fast_neut_flux(self, p_neutron_total_mw, sh_width, rmajor): of 16.6 cm, close to the "15 - 16 cm" of Menard et al. 2016. (This is an e-folding lenth of 7.22 cm.) - :param p_neutron_total_mw: neutron fusion power [MW] - :param sh_width: Neutron shield width [m] - :param rmajor: Plasma major radius [m] + Parameters + ---------- + p_neutron_total_mw : + neutron fusion power [MW] + sh_width : + Neutron shield width [m] + rmajor : + Plasma major radius [m] """ # Fraction of fast neutrons originating from the outer wall reflection [-] f_neut_flux_out_wall = 1 @@ -1077,8 +1109,7 @@ def st_tf_centrepost_fast_neut_flux(self, p_neutron_total_mw, sh_width, rmajor): return neut_flux_cp def st_centrepost_nuclear_heating(self, pneut, sh_width): - """Author : P J Knight, CCFE, Culham Science Centre - Author : S Kahn, CCFE, Culham Science Centre + """ Estimates the nuclear power absorbed by the ST centrepost magnet This routine calculates the neutron power absorbed by a copper spherical tokamak centrepost. @@ -1089,12 +1120,19 @@ def st_centrepost_nuclear_heating(self, pneut, sh_width): J D Galambos, STAR Code : Spherical Tokamak Analysis and Reactor Code, unpublished internal Oak Ridge document - :param pneut: 14 MeV plasma neutron power generated by the plasma [MW] - :param sh_width: Thickeness of the centrepost neutron shield [m] - - :returns: (Nuclear nuclear heat deposited in the centrepost TF coil [MW], - Nuclear nuclear heat deposited in the centrepost shield [MW], - Total nuclear heat deposited in the centrepost shield [MW]) + Parameters + ---------- + pneut : + 14 MeV plasma neutron power generated by the plasma [MW] + sh_width : + Thickeness of the centrepost neutron shield [m] + + Returns + ------- + type + Nuclear nuclear heat deposited in the centrepost TF coil [MW], + Nuclear nuclear heat deposited in the centrepost shield [MW], + Total nuclear heat deposited in the centrepost shield [MW]) """ # Outer wall reflection TF nuclear heating enhancement factor [-] f_pnuc_cp_tf = 1 diff --git a/process/ife.py b/process/ife.py index d9e1d6ff7f..d60abd78ef 100644 --- a/process/ife.py +++ b/process/ife.py @@ -1,5 +1,5 @@ """Module containing Inertial Fusion Energy device routines -author: P J Knight, CCFE, Culham Science Centre + This module contains routines for calculating the parameters of an Inertial Fusion Energy power plant. @@ -36,13 +36,13 @@ class IFE: """Module containing Inertial Fusion Energy device routines - author: P J Knight, CCFE, Culham Science Centre + N/A This module contains routines for calculating the parameters of an Inertial Fusion Energy power plant. """ - def __init__(self, availability, costs) -> None: + def __init__(self, availability, costs): """Initialises the IFE module's variables :param availability: a pointer to the availability model, allowing use of availability's variables/methods @@ -58,14 +58,17 @@ def __init__(self, availability, costs) -> None: def run(self, output: bool): """Routine to output the physics and engineering information relevant to inertial fusion energy power plants - author: P J Knight, CCFE, Culham Science Centre + This routine outputs the physics and engineering information relevant to inertial fusion energy power plants. F/MI/PJK/LOGBOOK12, p.66 - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output: + indicate whether output should be written to the output file, or not + """ # Device build self.ifebld(output=output) @@ -111,13 +114,15 @@ def run(self, output: bool): def ifebld(self, output: bool = False): """Routine to create the build of an inertial fusion energy device and to calculate the material volumes for the device core - author: P J Knight, CCFE, Culham Science Centre + This routine constructs the build of an inertial fusion energy device and calculates the material volumes for the device core. - :param output: boolean to control writing of output to outfile/mfile - :type output: bool + Parameters + ---------- + output: + boolean to control writing of output to outfile/mfile """ match ife_variables.ifetyp: case 1: @@ -257,8 +262,6 @@ def osibld(self): """Routine to create the build of an inertial fusion energy device, based on the design of the OSIRIS study, and to calculate the material volumes for the device core - author: P J Knight, CCFE, Culham Science Centre - None This routine constructs the build of an inertial fusion energy device, based on the design of the OSIRIS study, and to calculate the material volumes for the device core. @@ -279,8 +282,6 @@ def sombld(self): """Routine to create the build of an inertial fusion energy device, based on the design of the SOMBRERO study, and to calculate the material volumes for the device core - author: P J Knight, CCFE, Culham Science Centre - None This routine constructs the build of an inertial fusion energy device, based on the design of the SOMBRERO study, and to calculate the material volumes for the device core. @@ -810,8 +811,6 @@ def hylbld(self): def bld2019(self): """Routine to create the build of a 2019 inertial fusion energy device, and to calculate the material volumes for the device core - author: S I Muldrew, CCFE, Culham Science Centre - None This routine constructs the build of a modern inertial fusion energy device, assumed to be cylindrically-symmetric, with a pool at bottom and top corners and with a lower shield at the centre. See diagram @@ -1127,8 +1126,6 @@ def bld2019(self): def genbld(self): """Routine to create the build of a generic inertial fusion energy device, and to calculate the material volumes for the device core - author: P J Knight, CCFE, Culham Science Centre - None This routine constructs the build of a generic inertial fusion energy device, assumed to be cylindrically-symmetric, and to calculate the material volumes for the device core. @@ -1336,11 +1333,16 @@ def genbld(self): def ifephy(self, output: bool = False): """Routine to calculate the physics parameters of an Inertial Fusion Energy power plant - author: P J Knight, CCFE, Culham Science Centre + This routine calculates the physics parameters of an Inertial Fusion Energy power plant. F/MI/PJK/LOGBOOK12, pp.68,85 + + Parameters + ---------- + output: bool + (Default value = False) """ match ife_variables.ifedrv: case -1: @@ -1468,12 +1470,25 @@ def ifephy(self, output: bool = False): def driver(self, edrive, gainve, etave): """Routine to calculate parameters of a generic driver suitable for inertial fusion energy - author: P J Knight, CCFE, Culham Science Centre - edrive : input real : Driver energy (J) - gainve(10) : input real array : Gain vs energy data - etave(10) : input real array : Driver efficiency vs energy data - gain : output real : Target gain - etadrv : output real : Driver efficiency + + Parameters + ---------- + edrive: + Driver energy (J) + gainve(10): + Gain vs energy data + etave(10): + Driver efficiency vs energy data + + Returns + ------- + gain : + Target gain + etadrv : + Driver efficiency + + Notes + ----- This routine calculates the parameters of a generic driver suitable for inertial fusion energy. Gain and driver efficiency data are interpolated from input data. @@ -1508,10 +1523,21 @@ def driver(self, edrive, gainve, etave): def lasdrv(self, edrive): """Routine to calculate parameters of a laser driver suitable for inertial fusion energy - author: P J Knight, CCFE, Culham Science Centre - edrive : input real : Driver energy (J) - gain : output real : Target gain - etadrv : output real : Driver efficiency + + Parameters + ---------- + edrive: + Driver energy (J) + + Returns + ------- + gain : output + Target gain + etadrv : output + Driver efficiency + + Notes + ----- This routine calculates the parameters of a laser driver suitable for inertial fusion energy. Gain and driver efficiency data are taken from Figures 1 and 2 of @@ -1555,10 +1581,21 @@ def lasdrv(self, edrive): def iondrv(self, edrive): """Routine to calculate parameters of a heavy ion driver suitable for inertial fusion energy - author: P J Knight, CCFE, Culham Science Centre - edrive : input real : Driver energy (J) - gain : output real : Target gain - etadrv : output real : Driver efficiency + + Parameters + ---------- + edrive: + Driver energy (J) + + Returns + ------- + gain : output + Target gain + etadrv : output + Driver efficiency + + Notes + ----- This routine calculates the parameters of a heavy ion driver suitable for inertial fusion energy. @@ -1609,7 +1646,7 @@ def iondrv(self, edrive): def ifestr(self): """Routine to calculate the support structural masses for the core of an Inertial Fusion Energy power plant - author: P J Knight, CCFE, Culham Science Centre + This routine calculates the support structural masses for the core of an Inertial Fusion Energy power plant. @@ -1625,7 +1662,7 @@ def ifestr(self): def ifetgt(self): """Routine to calculate the power requirements of the target delivery system and the target factory - author: P J Knight, CCFE, Culham Science Centre + This routine calculates the power requirements of the target delivery system and the target factory, for an Inertial Fusion Energy power plant. @@ -1640,13 +1677,16 @@ def ifetgt(self): def ifefbs(self, output: bool = False): """Routine to calculate the first wall, blanket and shield volumes, masses and other parameters, for an Inertial Fusion Energy device - author: P J Knight, CCFE, Culham Science Centre - outfile : input integer : output file unit - iprint : input integer : switch for writing to output file (1=yes) + This routine calculates the first wall, blanket and shield volumes, masses and other parameters, for an Inertial Fusion Energy device. F/MI/PJK/LOGBOOK12, p.86 Moir et al., Fusion Technology, vol.25 (1994) p.5 + + Parameters + ---------- + output: bool + (Default value = False) """ # Material densities @@ -1803,8 +1843,6 @@ def ifefbs(self, output: bool = False): def ifepw1(self): """Routine to calculate the first part of the heat transport and plant power balance constituents, for an IFE power plant - author: P J Knight, CCFE, Culham Science Centre - None This routine calculates the first part of the heat transport and plant power balance constituents, for an IFE power plant. F/MI/PJK/LOGBOOK12, pp.67,89 @@ -1889,14 +1927,17 @@ def ifepw2(self, output: bool = False): """Routine to calculate the rest of the IFE heat transport and plant power balance constituents, not already calculated in IFEPW1 or IFEACP - author: P J Knight, CCFE, Culham Science Centre - outfile : input integer : output file unit - iprint : input integer : switch for writing to output file (1=yes) + This routine calculates the rest of the IFE heat transport and plant power balance constituents, not already calculated in routines IFEPW1 or IFEACP. F/MI/PJK/LOGBOOK12, p.67 + + Parameters + ---------- + output: bool + (Default value = False) """ # Facility heat removal (p_plant_electric_base_total_mw calculated in IFEACP) heat_transport_variables.fachtmw = ( @@ -2076,10 +2117,14 @@ def ifepw2(self, output: bool = False): def ifeacp(self, output: bool = False): """Routine to calculate AC power requirements for an IFE power plant - author: P J Knight, CCFE, Culham Science Centre This routine calculates the AC power requirements for an IFE power plant. F/MI/PJK/LOGBOOK12, p.68 + + Parameters + ---------- + output: bool + (Default value = False) """ # Facility base load, MW (loads not dependent on floor area) @@ -2207,12 +2252,15 @@ def ifeacp(self, output: bool = False): def ifebdg(self, output: bool = False): """Routine to calculate the volumes of the buildings required for an Inertial Fusion Energy power plant - author: P J Knight, CCFE, Culham Science Centre - outfile : input integer : output file unit - iprint : input integer : switch for writing to output file (1=yes) + This routine calculates the volumes of the buildings required for an Inertial Fusion Energy power plant. The method is based closely on that for tokamaks etc. in routine + + Parameters + ---------- + output: bool + (Default value = False) """ # Reactor building # ================ @@ -2401,7 +2449,7 @@ def ifebdg(self, output: bool = False): def ifevac(self): """Routine to calculate parameters of the vacuum system for an Inertial Fusion Energy power plant - author: P J Knight, CCFE, Culham Science Centre + This routine calculates the parameters of the vacuum system for an Inertial Fusion Energy power plant.

The calculated values are hard-wired; they are based loosely diff --git a/process/impurity_radiation.py b/process/impurity_radiation.py index de0de2d26a..4a1f0db81f 100644 --- a/process/impurity_radiation.py +++ b/process/impurity_radiation.py @@ -16,10 +16,8 @@ def initialise_imprad(): - """ - Initialises the impurity radiation data structure - author: H Lux, CCFE, Culham Science Centre - None + """Initialises the impurity radiation data structure + This routine initialises the impurity radiation data. """ @@ -235,31 +233,38 @@ def init_imp_element( f_nd_species_electron: float, len_tab: int, error: int, -) -> None: - """ - Initialise the impurity radiation data for a species. - - :param n_species_index: Position of species in impurity array - :type n_species_index: int - :param name_label: Species name - :type name_label: str - :param z: Species charge number - :type z: int - :param m_species_amu: Species atomic mass (amu) - :type m_species_amu: float - :param f_nd_species_electron: Number density / electron density - :type f_nd_species_electron: float - :param len_tab: Length of temperature and Lz tables - :type len_tab: int - :param error: Error flag; 0 = okay, 1 = missing impurity data - :type error: int - :raises ProcessValueError: If illegal impurity number is provided - :raises FileNotFoundError: If impurity data files are missing - :raises ProcessError: If required data cannot be located in files +): + """Initialise the impurity radiation data for a species. This routine initialises the impurity radiation data structure for a given impurity species. The Lz versus temperature data are read in from file. + + Parameters + ---------- + n_species_index : int + Position of species in impurity array + name_label : str + Species name + z : int + Species charge number + m_species_amu : float + Species atomic mass (amu) + f_nd_species_electron : float + Number density / electron density + len_tab : int + Length of temperature and Lz tables + error : int + Error flag; 0 = okay, 1 = missing impurity data + + Raises + ------ + ProcessValueError + If illegal impurity number is provided + FileNotFoundError + If impurity data files are missing + ProcessError + If required data cannot be located in files """ if error == 1: @@ -344,14 +349,19 @@ def z2index(zimp): def fradcore(rho, radius_plasma_core_norm, f_p_plasma_core_rad_reduction): """Finds the fraction of radiation from the core that is subtracted in impurity radiation model. - :param rho: normalised minor radius - :type rho: numpy.array - :param radius_plasma_core_norm: normalised radius defining the 'core' region - :type radius_plasma_core_norm: float - :param f_p_plasma_core_rad_reduction: fraction of radiation from the core region - :type f_p_plasma_core_rad_reduction: float - :return: fradcore - array filled with the f_p_plasma_core_rad_reduction - :rtype: numpy.array + Parameters + ---------- + rho : numpy.array + normalised minor radius + radius_plasma_core_norm : float + normalised radius defining the 'core' region + f_p_plasma_core_rad_reduction : float + fraction of radiation from the core region + + Returns + ------- + numpy.array + fradcore - array filled with the f_p_plasma_core_rad_reduction """ fradcore = np.zeros(len(rho)) rho_mask = rho < radius_plasma_core_norm @@ -363,12 +373,17 @@ def fradcore(rho, radius_plasma_core_norm, f_p_plasma_core_rad_reduction): def zav_of_te(imp_element_index, teprofile): """Calculates electron temperature dependent average atomic number - :param imp_element_index: Impurity element index - :type imp_element_index: int - :param teprofile: temperature profile - :type teprofile: numpy.array - :return: zav_of_te - electron temperature dependent average atomic number - :rtype: numpy.array + Parameters + ---------- + imp_element_index : int + Impurity element index + teprofile : numpy.array + temperature profile + + Returns + ------- + numpy.array + zav_of_te - electron temperature dependent average atomic number """ # less_than_imp_temp_mask = teprofile values less than impurity temperature. greater_than_imp_temp_mask = teprofile values higher than impurity temperature. return _zav_of_te_compiled( @@ -420,14 +435,19 @@ def _zav_of_te_compiled( def pimpden(imp_element_index, neprofile, teprofile): """Calculates the impurity radiation density (W/m3) - :param imp_element_index: Impurity element index - :type imp_element_index: int - :param neprofile: electron density profile - :type neprofile: numpy.array - :param teprofile: electron temperature profile - :type teprofile: numpy.array - :return: pimpden - total impurity radiation density (W/m3) - :rtype: numpy.array + Parameters + ---------- + imp_element_index : int + Impurity element index + neprofile : numpy.array + electron density profile + teprofile : numpy.array + electron temperature profile + + Returns + ------- + numpy.array + pimpden - total impurity radiation density (W/m3) """ # less_than_imp_temp_mask = teprofile values less than impurity temperature. greater_than_imp_temp_mask = teprofile values higher than impurity temperature. bins = impurity_radiation_module.temp_impurity_keV_array[imp_element_index] @@ -486,6 +506,11 @@ def pimpden(imp_element_index, neprofile, teprofile): def element2index(element: str): """Returns the index of the `element` in the impurity array with a given name + + Parameters + ---------- + element: str : + """ try: return ( @@ -503,7 +528,8 @@ class ImpurityRadiation: """This class calculates the impurity radiation losses for given temperature and density profiles. The considers the total impurity radiation from the core (pden_impurity_core_rad_total_mw) and total impurity radiation (pden_impurity_rad_total_mw) [MW/(m^3)]. The class is used to sum the impurity radiation loss from each impurity - element to find the total impurity radiation loss.""" + element to find the total impurity radiation loss. + """ def __init__(self, plasma_profile): """ @@ -529,22 +555,19 @@ def map_imprad_profile(self): list(map(self.imprad_profile, self.imp)) def imprad_profile(self, imp_element_index): - """ - This routine calculates the impurity radiation losses for given temperature and density profiles. + """This routine calculates the impurity radiation losses for given temperature and density profiles. + + Parameters + ---------- + imp_element_index : Int + Index used to access different impurity radiation elements + References: Bremsstrahlung equation from Johner, L(z) data (coronal equilibrium) from Marco Sertoli, Asdex-U, ref. Kallenbach et al. Johner, Fusion Science and Technology 59 (2011), pp 308-349 Sertoli, private communication Kallenbach et al., Plasma Phys. Control. Fus. 55(2013) 124041 - Authors: - R Kemp, CCFE, Culham Science Centre - H Lux, CCFE, Culham Science Centre - P J Knight, CCFE, Culham Science Centre - G Turkington, CCFFE, Culham Science Centre - - :param imp_element_index: Index used to access different impurity radiation elements - :type imp_element_index: Int """ pimp = pimpden( @@ -580,7 +603,8 @@ def calculate_radiation_loss_profiles(self): def integrate_radiation_loss_profiles(self): """Integrate the radiation loss profiles using the Simpson rule. - Store the total values for each aspect of impurity radiation loss.""" + Store the total values for each aspect of impurity radiation loss. + """ # 2.0e-6 converts from W/m^3 to MW/m^3 and also accounts for both sides of the plasma self.pden_impurity_rad_total_mw = 2.0e-6 * integrate.simpson( diff --git a/process/init.py b/process/init.py index 64ec0d08a5..58be94e8af 100644 --- a/process/init.py +++ b/process/init.py @@ -64,8 +64,7 @@ def init_process(): """Routine that calls the initialisation routines - author: P J Knight, CCFE, Culham Science Centre - None + This routine calls the main initialisation routines that set the default values for the global variables, reads in data from the input file, and checks the run parameters for consistency. @@ -300,8 +299,7 @@ def init_all_module_vars(): def check_process(inputs): # noqa: ARG001 """Routine to reset specific variables if certain options are being used - author: P J Knight, CCFE, Culham Science Centre - None + This routine performs a sanity check of the input variables and ensures other dependent variables are given suitable values. """ @@ -611,7 +609,7 @@ def check_process(inputs): # noqa: ARG001 and data_structure.physics_variables.i_plasma_pedestal ): warn( - "REINKE IMPURITY MODEL: The Martin LH threshold scale is not being used and is recommned for the Reinke model", + "REINKE IMPURITY MODEL: The Martin LH threshold scale is not being used and is recommended for the Reinke model", stacklevel=2, ) diff --git a/process/input.py b/process/input.py index a286a478ff..5bcb0c29a9 100644 --- a/process/input.py +++ b/process/input.py @@ -1261,14 +1261,16 @@ def __post_init__(self): data_structure.rebco_variables, float, range=(1e-08, 0.0001), - additional_actions=lambda _n, rt, _i, _c: rt <= 1e-6 - or warn( - ( - "the relationship between REBCO layer thickness and current density is not linear." - "REBCO layer thicknesses > 1um should be considered an aggressive extrapolation of" - "current HTS technology and any results must be considered speculative." - ), - stacklevel=1, + additional_actions=lambda _n, rt, _i, _c: ( + rt <= 1e-6 + or warn( + ( + "the relationship between REBCO layer thickness and current density is not linear." + "REBCO layer thicknesses > 1um should be considered an aggressive extrapolation of" + "current HTS technology and any results must be considered speculative." + ), + stacklevel=1, + ) ), ), "redun_vacp": InputVariable( @@ -2271,13 +2273,23 @@ def validate_variable( ) -> ValidInputTypes: """Validate an input. - :param name: the name of the input. - :param value: the value of the input variable. - :param array_index: the array index of the variable in the input file. - :param config: the config of the variable that describes how to validate and process it. - :param line_number: line number of current line being parsed for error reporting. - - :returns: the input value with the correct type. + Parameters + ---------- + name : + the name of the input. + value : + the value of the input variable. + array_index : + the array index of the variable in the input file. + config : + the config of the variable that describes how to validate and process it. + line_number : + line number of current line being parsed for error reporting. + + Returns + ------- + : + the input value with the correct type. """ # check that if the variable should be an array, then an array index is provided # EXCEPT for if check_array is False. This should only be the case when parsing @@ -2324,9 +2336,14 @@ def validate_variable( def set_scalar_variable(name: str, value: ValidInputTypes, config: InputVariable): """Set a scalar (not part of an array) variable in the `config.module`. - :param name: the name of the input. - :param value: the value of the input variable. - :param config: the config of the variable that describes how to validate and process it. + Parameters + ---------- + name : + the name of the input. + value : + the value of the input variable. + config : + the config of the variable that describes how to validate and process it. """ current_value = getattr(config.module, name, ...) @@ -2347,10 +2364,16 @@ def set_array_variable(name: str, value: str, array_index: int, config: InputVar The way PROCESS input files are structured, each element of the array is provided on one line so this function just needs to set the `value` at `array_index` (-1) because of Fortran-based indexing. - :param name: the name of the input. - :param value: the value of the input variable. - :param array_index: the array index of the variable in the input file. - :param config: the config of the variable that describes how to validate and process it. + Parameters + ---------- + name : + the name of the input. + value : + the value of the input variable. + array_index : + the array index of the variable in the input file. + config : + the config of the variable that describes how to validate and process it. """ current_array = getattr(config.module, name, ...) shape = current_array.shape diff --git a/process/io/configuration.py b/process/io/configuration.py index d9818775d3..18cb17361a 100644 --- a/process/io/configuration.py +++ b/process/io/configuration.py @@ -26,7 +26,13 @@ def data(self): @data.setter def data(self, value): - """Validate the configuration is provided in a specific format.""" + """Validate the configuration is provided in a specific format. + + Parameters + ---------- + value : + + """ self.data_validate(value) self._data = value @@ -35,7 +41,13 @@ def data(self): del self._data def data_validate(self, value): - """Check that value corresponds to a specific data format.""" + """Check that value corresponds to a specific data format. + + Parameters + ---------- + value : + + """ if not isinstance(value, dict) and value is not None: raise ValueError("Configuration data must be specified as a dictionary") @@ -69,7 +81,15 @@ def _lowercase(self, objekt): return objekt def _search_config_for(self, config, *keys): - """Recursively search config (a dict) for keys.""" + """Recursively search config (a dict) for keys. + + Parameters + ---------- + config : + + *keys : + + """ try: search_key = keys[0].lower() if isinstance(keys[0], str) else keys[0] value = config[search_key] @@ -88,13 +108,21 @@ def _search_config_for(self, config, *keys): def get(self, *config_keys, default=None): """ - Return configured value corresponding to config_keys if possible. - For nested configs, sequential items in config_keys can be used. - For example, if the configuration is: - {"a": "b", "c": {1: "hello", 2: {"x": "alpha", "z": "beta"}}} - you can access the value of "z" by calling get("c", 2, "z"). + Parameters + ---------- + *config_keys : + + default : + (Default value = None) + Returns + ------- + type + For nested configs, sequential items in config_keys can be used. + For example, if the configuration is: + {"a": "b", "c": {1: "hello", 2: {"x": "alpha", "z": "beta"}}} + you can access the value of "z" by calling get("c", 2, "z"). """ try: diff --git a/process/io/costs_bar.py b/process/io/costs_bar.py index 90d25343c8..b093cab4d9 100644 --- a/process/io/costs_bar.py +++ b/process/io/costs_bar.py @@ -3,12 +3,6 @@ Code to produce costs bar chart. Can take multiple input files. -Stuart Muldrew (stuart.muldrew@ukaea.uk) -11/09/2018 - -History -04/04/2019 SIM Added comp_step - """ # Imported libraries @@ -21,12 +15,9 @@ import process.io.mfile as mf -def comp_orig(args, mfile_list: list[str], inflate: float) -> None: - """ - - Plot bar chart for the orginal 1990 cost model. +def comp_orig(args, mfile_list: list[str], inflate: float): + """Plot bar chart for the orginal 1990 cost model. Two plots produced: (1) Breakdown of the direct costs and (2) Direct, indirect, etc. - """ # Setup figures labels = [ @@ -134,11 +125,7 @@ def comp_orig(args, mfile_list: list[str], inflate: float) -> None: def comp_new(args, mfile_list: list[str], inflate: float): - """ - - Plot bar chart for the new 2014 cost model. - - """ + """Plot bar chart for the new 2014 cost model.""" # Setup figures labels = [ "Land and Buildings", @@ -224,7 +211,6 @@ def main(args=None): parser = argparse.ArgumentParser( description="Displays the cost breakdown as a bar chart. " "Multiple MFILEs can be given and will be plotted on the same chart. " - "For more information contact Stuart.Muldrew@ukaea.uk" ) parser.add_argument( diff --git a/process/io/costs_pie.py b/process/io/costs_pie.py index 11e77ce910..e82902fd9e 100644 --- a/process/io/costs_pie.py +++ b/process/io/costs_pie.py @@ -1,12 +1,5 @@ """ Code to display the cost breakdown as a pie chart - -Stuart Muldrew (stuart.muldrew@ukaea.uk) -06/09/2018 - -History -04/04/2019 SIM Added step_cost_model - """ # Imported libraries @@ -18,11 +11,8 @@ def orig_cost_model(m_file, args): - """ - - Plot pie chart for the orginal 1990 cost model. + """Plot pie chart for the orginal 1990 cost model. Two plots produced: (1) Breakdown of the direct costs and (2) Direct, indirect, etc. - """ # Read Cost Values c21 = m_file.data["c21"].get_scan(-1) # Site and Buildings @@ -131,11 +121,7 @@ def orig_cost_model(m_file, args): def new_cost_model(m_file, args): - """ - - Plot pie chart for the new 2014 cost model. - - """ + """Plot pie chart for the new 2014 cost model.""" # Read Cost Values s09 = m_file.data["s09"].get_scan(-1) # Buildings s13 = m_file.data["s13"].get_scan(-1) # Land @@ -193,7 +179,6 @@ def main(args=None): # Setup command line arguments parser = argparse.ArgumentParser( description="Displays the cost breakdown as a pie chart. " - "For more information contact Stuart.Muldrew@ukaea.uk" ) parser.add_argument( diff --git a/process/io/data_structure_dicts.py b/process/io/data_structure_dicts.py index 0dbff28738..81cf0230ae 100644 --- a/process/io/data_structure_dicts.py +++ b/process/io/data_structure_dicts.py @@ -18,7 +18,7 @@ from process.init import init_all_module_vars from process.input import INPUT_VARIABLES from process.iteration_variables import ITERATION_VARIABLES -from process.scan import SCAN_VARIABLES +from process.scan import ScanVariables INPUT_TYPE_MAP = {int: "int", float: "real", str: "string"} @@ -90,10 +90,16 @@ def to_type(string): looks to see if it begins with a integer and returns that (since some lines have clarification text after the number). If this also fails, return string.strip() - Args: - string --> String to be converted - Returns: - value --> Either a float, int or string depending on input + + Parameters + ---------- + string : + + + Returns + ------- + : + Either a float, int or string depending on input """ try: @@ -116,13 +122,20 @@ def to_type(string): def grep(file, regexp, flags=re.UNICODE): """Implements an in-python grep. Returns the lines that match as a list. - Args: - file --> Name of file to be read - regexp --> Regular expression to search for - flags --> re flags to use in search. Default is re.U which has - no effect - Returns: - lines --> List of matching lines + + Parameters + ---------- + file: + Name of file to be read + regexp: + Regular expression to search for + flags: + re flags to use in search. Default is re.U which has + + Returns + ------- + lines: + List of matching lines """ lines = [] @@ -142,12 +155,20 @@ def slice_file(file, re1, re2): to re1 in the file marks the start of the slice, the first match to re2 after that marks the end of the slice. The list of lines returned includes the two bounding lines. - Args: - file --> Name of file to read through - re1 --> Starting regular expression - re2 --> Ending regular expression - Returns: - lines --> List of lines from file between re1 and re2 inclusive + + Parameters + ---------- + file : + Name of file to read through + re1 : + Starting regular expression + re2 : + Ending regular expression + + Returns + ------- + : + lines:List of lines from file between re1 and re2 inclusive """ with open(file, encoding="utf-8") as file: @@ -179,10 +200,17 @@ def remove_comments(line): removing everything after the first '!' in the line. This will cause problems in the case of '!' characters contained within strings so am assuming this won't happen. Need to change this. - Args: - line --> Line to strip comments from + + Parameters + ---------- + line: + Line to strip comments from + Returns - modified_line --> Line with comments removed + ------- + modified_line: + Line with comments removed + """ if "!" in line: line = line[: line.find("!")] @@ -203,7 +231,7 @@ def dict_ixc2nsweep(): """ name_to_nsweep = { - var.variable_name: nsweep for nsweep, var in SCAN_VARIABLES.items() + sv.value.variable_name: sv.value.variable_num for sv in ScanVariables } # create a dictionary that maps iteration variable names to ixc_no @@ -219,7 +247,8 @@ def dict_ixc2nsweep(): def dict_nsweep2ixc(): """Returns a dict mapping nsweep_no to ixc_no; the inverse of - dict_ixc2nsweep""" + dict_ixc2nsweep + """ # Use dict_ixc2nsweep from output_dict to produce dict_nsweep2ixc ixc2nsweep = output_dict["DICT_IXC2NSWEEP"] @@ -279,7 +308,7 @@ def dict_input_bounds(): def dict_nsweep2varname(): - return {str(nsweep): var.variable_name for nsweep, var in SCAN_VARIABLES.items()} + return {sv.value.variable_num: sv.value.variable_name for sv in ScanVariables} def dict_ixc_full(): diff --git a/process/io/in_dat.py b/process/io/in_dat.py index e1c1daa8cf..3f27f5a6ff 100644 --- a/process/io/in_dat.py +++ b/process/io/in_dat.py @@ -3,10 +3,6 @@ File for reading IN.DATs Version 2 (mainly for use with IN.DAT created from UI) -James Morris -CCFE -11/12/14 - Notes: + 24/11/2021: Global dictionary variables moved within the functions to avoid cyclic dependencies. This is because the dicts @@ -32,8 +28,15 @@ def fortran_python_scientific(var_value): """Convert FORTRAN scientific notation to Python notation - :param var_value: variable value - :return: value with 'd/D' notation swapped for 'e/E' notation + Parameters + ---------- + var_value: + variable value + + Returns + ------- + : + value with 'd/D' notation swapped for 'e/E' notation """ return var_value.replace("D", "e").replace("d", "e") @@ -41,8 +44,15 @@ def fortran_python_scientific(var_value): def remove_empty_lines(lines): """Function to remove empty lines from list. - :param lines: list of lines (type=list) - :return: list of lines with empty lines removed (type=list) + Parameters + ---------- + lines: + list of lines (type=list) + + Returns + ------- + : + list of lines with empty lines removed (type=list) """ return [line for line in lines if line.strip(" ") != "\n"] @@ -50,16 +60,31 @@ def remove_empty_lines(lines): def is_title(line): """Function to determine if line is title line - :param line: line from IN.DAT - :return: True/False if line is a title or header. + Parameters + ---------- + line: + line from IN.DAT + + Returns + ------- + : + True/False if line is a title or header. """ return line[:2] == "*-" or line[:3] == "***" or line[0] == "$" def is_comment(line): """Function to determine if line is a commented line - :param line: line from IN.DAT - :return: True/False if line is a commented line + + Parameters + ---------- + line: + line from IN.DAT + + Returns + ------- + : + True/False if line is a commented line """ return line[0] == "*" @@ -67,8 +92,15 @@ def is_comment(line): def is_iteration_variable(name): """Function to determine if item is an iteration variable - :param name: Name of the variable - :return: True/False if 'ixc' is in name + Parameters + ---------- + name: + Name of the variable + + Returns + ------- + : + True/False if 'ixc' is in name """ return "ixc" in name @@ -76,8 +108,15 @@ def is_iteration_variable(name): def is_constraint_equation(name): """Function to determine if item is constraint equation - :param name: Name of the variable - :return: True/False if 'icc' is in name + Parameters + ---------- + name: + Name of the variable + + Returns + ------- + : + True/False if 'icc' is in name """ return "icc" in name @@ -85,8 +124,15 @@ def is_constraint_equation(name): def is_bound(name): """Function to determine if item is a bound - :param name: Name of the variable - :return: True/False if 'bound' is in name + Parameters + ---------- + name: + Name of the variable + + Returns + ------- + : + True/False if 'bound' is in name """ return "bound" in name @@ -94,8 +140,15 @@ def is_bound(name): def is_array(name): """Function to determine if item is an array - :param name: Name of the variable - :return: True/False if name is of an array + Parameters + ---------- + name: + Name of the variable + + Returns + ------- + : + True/False if name is of an array """ # Load dicts from dicts JSON file dicts = get_dicts() @@ -112,8 +165,15 @@ def is_array(name): def find_line_type(line): """Function to find line type - :param line: Line to find type of - :return: Return string describing the line type + Parameters + ---------- + line: + Line to find type of + + Returns + ------- + : + Return string describing the line type """ # Split variable name from line @@ -150,8 +210,15 @@ def find_line_type(line): def find_parameter_group(name): """Function to find the module which the parameter belongs to. - :param name: Parameter name - :return: Return the module the parameter belongs to + Parameters + ---------- + name: + Parameter name + + Returns + ------- + : + Return the module the parameter belongs to """ # Load dicts from dicts JSON file dicts = get_dicts() @@ -166,9 +233,13 @@ def find_parameter_group(name): def write_title(title, out_file): """Function to write title line to file with fixed width - :param title: The name of the section - :param out_file: Output file for new IN.DAT - :return: Nothing + Parameters + ---------- + title: + The name of the section + out_file: + Output file for new IN.DAT + """ out_file.write("\n") @@ -186,9 +257,17 @@ def get_constraint_equations(data): Use the constraint equation numbers from IN.DAT to find the comment associated with them in the source dictionary, then return both. - :param dict data: Data dictionary for the IN.DAT information - :return: dict of the constraint numbers and their comments - :rtype: dict + Parameters + ---------- + dict: + data: Data dictionary for the IN.DAT information + data : + + + Returns + ------- + dict + dict of the constraint numbers and their comments """ constraints = {} @@ -214,9 +293,13 @@ def get_constraint_equations(data): def write_constraint_equations(data, out_file): """Function to write constraint equation information to file - :param data: Data dictionary for the IN.DAT information - :param out_file: Output file for new IN.DAT - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + out_file: + Output file for new IN.DAT + """ # Header @@ -230,7 +313,7 @@ def write_constraint_equations(data, out_file): out_file.write(constraint_line) -def get_iteration_variables(data): +def get_iteration_variables(data: dict): """Create the iteration variable information. Use the iteration variable numbers from IN.DAT to find the comment @@ -238,9 +321,15 @@ def get_iteration_variables(data): from the IN.DAT file to see if upper and/or lower bounds are present, and what the value is. Return all this information for each variable. - :param dict data: Data dictionary for the IN.DAT information - :return: variable number, comment, upper and/or lower bounds if present - :rtype: dict + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + + Returns + ------- + : + variable number, comment, upper and/or lower bounds if present """ variables = {} @@ -281,9 +370,12 @@ def get_iteration_variables(data): def write_iteration_variables(data, out_file): """Function to write iteration variable information to file - :param data: Data dictionary for the IN.DAT information - :param out_file: Output file for new IN.DAT - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + out_file: + Output file for new IN.DAT """ # Header @@ -318,11 +410,18 @@ def get_parameters(data, use_string_values=True): new IN.DAT files. If False, store the values as their original type, e.g. int, float etc. This is used for validating the input file. - :param dict data: Data dictionary for the IN.DAT information - :param bool use_string_values: If True, store all parameter values as - strings. If False, preserve parameter value type. - :return: dict of parameters containing names, values and comments - :rtype: dict + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + use_string_values: + If True, store all parameter values as + strings. If False, preserve parameter value type. + + Returns + ------- + dict + dict of parameters containing names, values and comments """ # Load dicts from dicts JSON file dicts = get_dicts() @@ -426,9 +525,13 @@ def get_parameters(data, use_string_values=True): def write_parameters(data, out_file): """Write parameters to file - :param data: Data dictionary for the IN.DAT information - :param out_file: Output file for new IN.DAT - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + out_file: + Output file for new IN.DAT + """ filter_list = ["f_nd_impurity_electrons(", "zref(", "imp_rich", "vmec"] # Special parameters that require different formatting @@ -466,9 +569,13 @@ def write_parameters(data, out_file): def add_iteration_variable(data, variable_number): """Function to add iteration variable to IN.DAT data dictionary - :param data: Data dictionary for the IN.DAT information - :param variable_number: Iteration variable number to add - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + variable_number: + Iteration variable number to add + """ # Check the variable number is not already in the iteration variable list @@ -483,9 +590,13 @@ def add_iteration_variable(data, variable_number): def remove_iteration_variable(data, variable_number): """Function to remove iteration variable from the IN.DAT data dictionary - :param data: Data dictionary for the IN.DAT information - :param variable_number: Iteration variable number to remove - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + variable_number: + Iteration variable number to remove + """ # Check the variable is in the iteration variable list @@ -499,9 +610,13 @@ def remove_iteration_variable(data, variable_number): def add_constraint_equation(data, equation_number): """Function to add constraint equation to the IN.DAT data dictionary - :param data: Data dictionary for the IN.DAT information - :param equation_number: Constraint equation number to add - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + equation_number: + Constraint equation number to add + """ # Check the constraint is not already in the constraint equation list @@ -517,9 +632,13 @@ def remove_constraint_equation(data, equation_number): """Function to remove a constraint equation from the IN.DAT data dictionary - :param data: Data dictionary for the IN.DAT information - :param equation_number: Constraint equation number to remove - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + equation_number: + Constraint equation number to remove + """ # Check the constraint is in @@ -534,10 +653,15 @@ def remove_constraint_equation(data, equation_number): def add_parameter(data, parameter_name, parameter_value): """Function to add/change parameter to the IN.DAT data dictionary - :param data: Data dictionary for the IN.DAT information - :param parameter_name: Name of the parameter to add - :param parameter_value: Value of the parameter to add - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + parameter_name: + Name of the parameter to add + parameter_value: + Value of the parameter to add + """ # Load dicts from dicts JSON file dicts = get_dicts() @@ -579,9 +703,13 @@ def add_parameter(data, parameter_name, parameter_value): def remove_parameter(data, parameter_name): """Function to remove parameter from the IN.DAT data dictionary - :param data: Data dictionary for the IN.DAT information - :param parameter_name: Name of the parameter to remove - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + parameter_name: + Name of the parameter to remove + """ # Check that the parameter exists in the data dictionary @@ -597,11 +725,16 @@ def remove_parameter(data, parameter_name): def change_array(data, name, array_id, array_val): """Function to change value in generic array - :param data: Data dictionary for the IN.DAT information - :param name: generic array name - :param array_id: generic array index - :param array_val: generic array value - :return: + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + name: + generic array name + array_id: + generic array index + array_val: + generic array value """ data[name].value[array_id] = array_val @@ -618,12 +751,18 @@ def add_bound(data, bound, bound_type, bound_value): """Function to add/change a bound to the bounds entry in the IN.dat data dictionary - :param data: Data dictionary for the IN.DAT information - :param bound: Bound number associated with iteration variable number to - change - :param bound_type: States whether bound is upper of lower bound - :param bound_value: New value of the bound - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + bound: + Bound number associated with iteration variable number to + change + bound_type: + States whether bound is upper of lower bound + bound_value: + New value of the bound + """ # Put bound type into lower cases for consistency @@ -648,11 +787,16 @@ def remove_bound(data, bound, bound_type): """Function to remove a bound from the bounds entry in the IN.DAT data dictionary - :param data: Data dictionary for the IN.DAT information - :param bound: Bound number associated with iteration variable number to - change - :param bound_type: States whether bound is upper or lower bound - :return: Nothing + Parameters + ---------- + data: + Data dictionary for the IN.DAT information + bound: + Bound number associated with iteration variable number to + change + bound_type: + States whether bound is upper or lower bound + """ # use local variable for cleanliness @@ -676,9 +820,17 @@ def fortran_float_to_py(f: str) -> str: def parameter_type(name, value): """Function to return value in correct format for altering values etc. - :param name: Name of parameter to check type - :param value: Value of parameter to format - :return: Formatted value + Parameters + ---------- + name: + Name of parameter to check type + value: + Value of parameter to format + + Returns + ------- + : + Formatted value """ # Load dicts from dicts JSON file dicts = get_dicts() @@ -747,10 +899,18 @@ def parameter_type(name, value): def variable_constraint_type_check(item_number, var_type): """Function to put input into correct format for altering values etc. - :param item_number: Number associated with variable or constraint - :param var_type: States whether item is iteration variable or constraint - equation - :return: Formatted item_number + Parameters + ---------- + item_number: + Number associated with variable or constraint + var_type: + States whether item is iteration variable or constraint + equation + + Returns + ------- + : + Formatted item_number """ # Check if item is in string format @@ -807,9 +967,17 @@ def variable_constraint_type_check(item_number, var_type): def variable_bound_check(bound_number, bound_type): """Function to put bound_number and bound_type into correct format - :param bound_number: Bound number to check - :param bound_type: States whether bound is upper or lower bound - :return: Formatted bound number and bound type + Parameters + ---------- + bound_number: + Bound number to check + bound_type: + States whether bound is upper or lower bound + + Returns + ------- + : + Formatted bound number and bound type """ # put bound type into lower case for consistency @@ -854,18 +1022,24 @@ def variable_bound_check(bound_number, bound_type): class INVariable: - def __init__(self, name, value, v_type, parameter_group, comment): - """Class to stores the information of a single variable from the + """Class to stores the information of a single variable from the IN.DAT file - :param name: Item name - :param value: Item value - :param v_type: Type of item - :param parameter_group: PROCESS variable group item belongs to - :param comment: Comment for item - :return: Nothing - """ + Parameters + ---------- + name: + Item name + value: + Item value + v_type: + Type of item + parameter_group: + PROCESS variable group item belongs to + comment: + Comment for item + """ + def __init__(self, name, value, v_type, parameter_group, comment): self.name = name self.value = value self.v_type = v_type @@ -889,28 +1063,30 @@ def __repr__(self): @property def get_value(self): - """Return value in correct format""" + """ """ if self.v_type != "Bound": return parameter_type(self.name, self.value) return self.value class InDat: - """ - Class 'InDat' for handling IN.DAT data. It handles + """Class 'InDat' for handling IN.DAT data. It handles - - Reading IN.DAT files - - Writing IN.DAT files - - Storing information in dictionary for use in other codes - - Alterations to IN.DAT + - Reading IN.DAT files + - Writing IN.DAT files + - Storing information in dictionary for use in other codes + - Alterations to IN.DAT """ def __init__(self, filename="IN.DAT", start_line=0): """Initialise class - :param filename: Name of input IN.DAT - :param start_line: Line to start reading from - :return: Nothing + Parameters + ---------- + filename: + Name of input IN.DAT + start_line: + Line to start reading from """ self.filename = filename @@ -968,9 +1144,13 @@ def process_line(self, line_type, line): """Function to process the line and return the appropriate INVariable object - :param line_type: Type of information the line contains - :param line: Line from IN.DAT to process - :return: Nothing + Parameters + ---------- + line_type: + Type of information the line contains + line: + Line from IN.DAT to process + """ # Load dicts from dicts JSON file @@ -1041,8 +1221,11 @@ def process_line(self, line_type, line): def process_parameter(self, line): """Function to process parameter entries in IN.DAT - :param line: Line from IN.DAT to process - :return: Nothing + Parameters + ---------- + line: + Line from IN.DAT to process + """ # Load dicts from dicts JSON file dicts = get_dicts() @@ -1101,8 +1284,11 @@ def process_parameter(self, line): def process_constraint_equation(self, line): """Function to process constraint equation entry in IN.DAT - :param line: Line from IN.DAT to process - :return: Nothing + Parameters + ---------- + line: + Line from IN.DAT to process + """ # Remove comment from line to make things easier @@ -1148,8 +1334,11 @@ def process_constraint_equation(self, line): def process_iteration_variables(self, line): """Function to process iteration variables entry in IN.DAT - :param line: Line from IN.DAT to process - :return: Nothing + Parameters + ---------- + line: + Line from IN.DAT to process + """ # Remove comment from line to make things easier @@ -1193,8 +1382,11 @@ def process_iteration_variables(self, line): def process_bound(self, line): """Function to process bound entries in IN.DAT - :param line: Line from IN.DAT to process - :return: Nothing + Parameters + ---------- + line: + Line from IN.DAT to process + """ # Initialise bound type @@ -1237,9 +1429,17 @@ def process_bound(self, line): def process_array(self, line, empty_array): """Function to process generic array - :param line: Line from IN.DAT to process - :param empty_array: Default array for this array name - :return: nothing + Parameters + ---------- + line: + Line from IN.DAT to process + empty_array: + Default array for this array name + + Returns + ------- + type + nothing """ # TODO This is a mess after the Fortran module variable # re-initialisation work. It is hard to see how this can be improved @@ -1325,16 +1525,22 @@ def add_duplicate_variable(self, name): If a var is initialised more than once in the input file, the last value persists, but the overwriting is recorded here. - :param name: The name of the variable being duplicated - :type var: str + + Parameters + ---------- + name: + The name of the variable being duplicated """ self.duplicates.append(name) def add_iteration_variable(self, variable_number): """Function to add iteration variable to IN.DAT data dictionary - :param variable_number: Iteration variable number to add - :return: Nothing + Parameters + ---------- + variable_number: + Iteration variable number to add + """ # format iteration variable number @@ -1347,8 +1553,11 @@ def add_iteration_variable(self, variable_number): def remove_iteration_variable(self, variable_number): """Function to remove iteration variable to IN.DAT data dictionary - :param variable_number: Iteration variable number to remove - :return: Nothing + Parameters + ---------- + variable_number: + Iteration variable number to remove + """ # format iteration variable number @@ -1361,8 +1570,11 @@ def remove_iteration_variable(self, variable_number): def add_constraint_equation(self, equation_number): """Function to add constraint equation to IN.DAT data dictionary - :param equation_number: Constraint equation number to add - :return: Nothing + Parameters + ---------- + equation_number: + Constraint equation number to add + """ # format constraint equation number @@ -1377,8 +1589,11 @@ def remove_constraint_equation(self, equation_number): """Function to remove a constraint equation from IN.DAT data dictionary - :param equation_number: Constraint equation number to remove - :return: Nothing + Parameters + ---------- + equation_number: + Constraint equation number to remove + """ # format constraint equation number @@ -1392,9 +1607,13 @@ def remove_constraint_equation(self, equation_number): def add_parameter(self, parameter_name, parameter_value): """Function to add/change parameter to IN.DAT data dictionary - :param parameter_name: Name of parameter to add/change - :param parameter_value: Value of parameter to add/change - :return: Nothing + Parameters + ---------- + parameter_name: + Name of parameter to add/change + parameter_value: + Value of parameter to add/change + """ # add/change parameter to/in IN.DAT data dictionary @@ -1403,10 +1622,14 @@ def add_parameter(self, parameter_name, parameter_value): def change_array(self, array_name, array_index, array_value): """Function to change value in generic array - :param array_name: name of generic array to change - :param array_index: index of generic array to change - :param array_value: value to change array entry to - :return: + Parameters + ---------- + array_name: + name of generic array to change + array_index: + index of generic array to change + array_value: + value to change array entry to """ # change generic array value in IN.DAT data dictionary @@ -1415,8 +1638,11 @@ def change_array(self, array_name, array_index, array_value): def remove_parameter(self, parameter_name): """Function to remove parameter from IN.DAT data dictionary - :param parameter_name: Name of parameter to remove - :return: Nothing + Parameters + ---------- + parameter_name: + Name of parameter to remove + """ # remove parameter from IN.DAT data dictionary @@ -1425,10 +1651,15 @@ def remove_parameter(self, parameter_name): def add_bound(self, bound, bound_type, bound_value): """Function to add/change a bound in IN.DAT data dictionary - :param bound: Bound number to add/change - :param bound_type: States whether bound is upper or lower bound - :param bound_value: Value of bound to add/change - :return: Nothing + Parameters + ---------- + bound: + Bound number to add/change + bound_type: + States whether bound is upper or lower bound + bound_value: + Value of bound to add/change + """ # format bound number and bound type @@ -1440,9 +1671,13 @@ def add_bound(self, bound, bound_type, bound_value): def remove_bound(self, bound, bound_type): """Function to remove a bound from IN.DAT data dictionary - :param bound: Bound number to remove - :param bound_type: States whether bound is upper or lower bound - :return: Nothing + Parameters + ---------- + bound: + Bound number to remove + bound_type: + States whether bound is upper or lower bound + """ # format bound number and bound type @@ -1452,7 +1687,13 @@ def remove_bound(self, bound, bound_type): remove_bound(self.data, bound, bound_type) def write_in_dat(self, output_filename="new_IN.DAT"): - """Function to write data to output file called 'output_filename'""" + """Function to write data to output file called 'output_filename' + + Parameters + ---------- + output_filename: + (Default value = "new_IN.DAT") + """ # create and open output file with open(output_filename, "w") as output: @@ -1524,10 +1765,15 @@ def __init__(self, filename="IN.DAT"): def get_param(self, var_name): """Get a parameter's dict from the data. - :param var_name: The name of the parameter to be returned - :type var_name: str - :return: Dictionary of parameter's information, or None if not found - :rtype: dict + Parameters + ---------- + var_name: + The name of the parameter to be returned + + Returns + ------- + dict + Dictionary of parameter's information, or None if not found """ modules = self.data["parameters"] @@ -1541,10 +1787,15 @@ def get_param(self, var_name): def is_param_defined(self, var_name): """Check if a parameter is defined or not in the input data. - :param var_name: Name of the parameter to be checked - :type var_name: str - :return: True if defined, False if not - :rtype: bool + Parameters + ---------- + var_name: + Name of the parameter to be checked + + Returns + ------- + bool + True if defined, False if not """ defined = False @@ -1556,10 +1807,15 @@ def is_param_defined(self, var_name): def get_param_value(self, var_name): """Gets the value of a parameter from the input data. - :param var_name: The name of the parameter - :type var_name: str - :return: Value of that parameter; can be any type. None if not found. - :rtype: int, float + Parameters + ---------- + var_name: + The name of the parameter + + Returns + ------- + int, float + Value of that parameter; can be any type. None if not found. """ value = None var_dict = self.get_param(var_name) diff --git a/process/io/mfile.py b/process/io/mfile.py index 0d58df57b6..08007e48b9 100644 --- a/process/io/mfile.py +++ b/process/io/mfile.py @@ -4,9 +4,6 @@ process.io.mfile. -James Morris -CCFE - Notes: + 12/03/2014: Initial version + 12/03/2014: Added MFILE variable class @@ -23,7 +20,6 @@ generation script imports, and inspects, process. Compatible with PROCESS version 286 - """ import json @@ -70,10 +66,12 @@ def __getattr__(self, name): def set_scan(self, scan_number, scan_value): """Sets the class attribute self.scan# where # is scan number - Arguments: - scan_number --> scan number - scan_value --> value of parameter for scan - + Parameters + ---------- + scan_number : + scan number + scan_value : + value of parameter for scan """ self[f"scan{scan_number:02}"] = scan_value if scan_number > self.latest_scan: @@ -83,11 +81,15 @@ def get_scan(self, scan_number): """Returns the value of a specific scan. For scan = -1 or None the last scan is given. - Arguments: - scan_number --> scan number to return [-1/None = last scan] + Parameters + ---------- + scan_number : + scan number to return - Returns: - [single scan requested] + Returns + ------- + type + [single scan requested] """ if scan_number is None or scan_number == -1: @@ -97,9 +99,10 @@ def get_scan(self, scan_number): def get_scans(self): """Returns a list of scan values in order of scan number - Returns: - [List of all scans for variable] + Returns + ------- + [List of all scans for variable] """ return [v for k, v in sorted(filter(lambda x: "scan" in x[0], self.items()))] @@ -196,8 +199,9 @@ def __repr__(self): class MFile: + """Class object to store the MFile Objects""" + def __init__(self, filename="MFILE.DAT"): - """Class object to store the MFile Objects""" self.filename = filename self.data = DefaultOrderedDict() self.mfile_lines = [] @@ -210,11 +214,27 @@ def __init__(self, filename="MFILE.DAT"): self.parse_mfile() def get_variables(self, *variables: str, scan: int = -1) -> list[Any]: - """Get a number of variables from a single scan""" + """Get a number of variables from a single scan + + Parameters + ---------- + *variables: + + scan: + (Default value = -1) + """ return [self.get(v, scan=scan) for v in variables] def get(self, variable: str, *, scan: int = -1) -> Any: - """Get variable data from a given scan""" + """Get variable data from a given scan + + Parameters + ---------- + variable: + + scan: + (Default value = -1) + """ return self.data[variable].get_scan(scan) def open_mfile(self): @@ -238,6 +258,11 @@ def parse_mfile(self): def add_line(self, line): """Function to read the line from MFILE and add to the appropriate class or create a new class if it is the first instance of it. + + Parameters + ---------- + line : + """ if "#" in line[:2]: combined = " ".join(line[1:-1]) @@ -274,7 +299,23 @@ class or create a new class if it is the first instance of it. self.add_to_mfile_variable(var_des, var_name, var_value, var_unit, var_flag) def add_to_mfile_variable(self, des, name, value, unit, flag, scan=None): - """Function to add value to MFile class for that name/description""" + """Function to add value to MFile class for that name/description + + Parameters + ---------- + des : + + name : + + value : + + unit : + + flag : + + scan : + (Default value = None) + """ var_key = des.lower().replace("_", " ") if name == "" else name.lower() if var_key in self.data: @@ -297,7 +338,17 @@ def add_to_mfile_variable(self, des, name, value, unit, flag, scan=None): self.data[var_key].set_scan(1, value) def write_to_json(self, keys_to_write=None, scan=-1, verbose=False): - """Write MFILE object to JSON file""" + """Write MFILE object to JSON file + + Parameters + ---------- + keys_to_write : + (Default value = None) + scan : + (Default value = -1) + verbose : + (Default value = False) + """ if keys_to_write is None: keys_to_write = self.data.keys() @@ -338,10 +389,18 @@ def sort_value(value_words: list[str]) -> str | float: """Parse value section of a line in MFILE. value_words is a list of strings, which is then parsed. - :param value_words: value of var in MFILE as list of strings - :type value_words: List[str] - :return: string or float representation of value list - :rtype: Union[str, float] + + Parameters + ---------- + value_words : List[str] + value of var in MFILE as list of strings + value_words: list[str] : + + + Returns + ------- + Union[str, float] + string or float representation of value list """ if any(c in value_words[0] for c in ['"', "'"]): # First "word" begins with ": return words as single str @@ -357,7 +416,13 @@ def sort_value(value_words: list[str]) -> str | float: def sort_brackets(var): - """Function to sort bracket madness on variable name.""" + """Function to sort bracket madness on variable name. + + Parameters + ---------- + var : + + """ if var != "": tmp_name = var.lstrip("(").split(")") if len(tmp_name) > 2: @@ -367,7 +432,13 @@ def sort_brackets(var): def clean_line(line): - """Cleans an MFILE line into the three parts we care about""" + """Cleans an MFILE line into the three parts we care about + + Parameters + ---------- + line : + + """ return [item.strip("_ \n") for item in line.split(" ") if item != ""] @@ -377,13 +448,17 @@ def search_keys(dictionary, variable): Puts everything into lower case before searching. - Argument: - dictionary --> dictionary to search in - variable --> variable name to search for - - Returns: - matches --> List of matches to the searched for variable - + Parameters + ---------- + dictionary : + dictionary to search in + variable : + variable name to search for + + Returns + ------- + : + List of matches to the searched for variable """ return [key for key in dictionary if variable.lower() in key.lower()] @@ -394,20 +469,30 @@ def search_des(dictionary, description): Puts everything into lower case before searching. - Argument: - dictionary --> dictionary to search in - variable --> variable name to search for - - Returns: - matches --> List of matches to the searched for description - + Parameters + ---------- + dictionary : + dictionary to search in + variable : + variable name to search for + + Returns + ------- + : + List of matches to the searched for description """ descriptions = [dictionary[key].var_descript.lower() for key in dictionary.data] return [item for item in descriptions if description.lower() in item.lower()] def get_unit(variable_desc): - """Returns the unit from a variable description if possible, else None.""" + """Returns the unit from a variable description if possible, else None. + + Parameters + ---------- + variable_desc : + + """ candidate = variable_desc.rsplit("_", 1)[-1] if candidate.startswith("(") and candidate.endswith(")"): return candidate[1:-1] @@ -415,7 +500,13 @@ def get_unit(variable_desc): def is_number(val): - """Check MFILE data entry""" + """Check MFILE data entry + + Parameters + ---------- + val : + + """ try: float(val) return True diff --git a/process/io/mfile2dict.py b/process/io/mfile2dict.py index b14c2c5197..c9a4e87ec0 100644 --- a/process/io/mfile2dict.py +++ b/process/io/mfile2dict.py @@ -1,16 +1,3 @@ -############################################################################### -# # -# MFILE to Python Dictionary Conversion # -# # -# Converts data from a PROCESS MFILE to a Python Dictionary with the # -# option to then write the result to a file. The format of the output is # -# determined by the specified file type which can be JSON, TOML, YAML or # -# a Pickle file. If TOMLKit is available the output contains docstrings. # -# # -# @author : K. Zarebski # -# @date : last modified 2021-02-22 # -# # -############################################################################### import logging import os import re @@ -24,14 +11,9 @@ class MFILEParser(abc.MutableMapping): - def __init__(self, input_mfile: str = ""): - """Parse an MFILE and extract output values. + """Parse an MFILE and extract output values.""" - Parameters - ---------- - input_mfile : str, optional - MFILE to search, by default "" - """ + def __init__(self, input_mfile: str = ""): self._input_file = input_mfile self._mfile_data: OrderedDict = OrderedDict() self._logger = logging.getLogger(self.__class__.__name__) @@ -61,7 +43,7 @@ def get_info_dict(self): Returns ------- - Dict[str, Dict[str, Any]] + : retrieve the full information dictionary containing values and descriptions of extracted parameters """ @@ -92,15 +74,11 @@ def _line_string_search(self, lines: list[str], search_str: str) -> list[int]: Parameters ---------- - lines : List[str] + lines : list of file lines to search - search_str : str + search_str: search term to look for - Returns - ------- - List[int] - list of indexes for matching lines """ return [i for i, line in enumerate(lines) if search_str in line] @@ -112,13 +90,8 @@ def _find_var_val_from_str(self, value_str: str) -> Any: Parameters ---------- - value_str : str + value_str : value as a string - - Returns - ------- - Any - the value in the appropriate form """ for type_str in ["OP", "IP", "ITV"]: value_str = value_str.replace(type_str, "") @@ -136,13 +109,8 @@ def _get_values(self, lines: list[str]) -> dict[str, Any]: Parameters ---------- - lines : List[str] + lines : list of file lines to be parsed - - Returns - ------- - Dict[str, Any] - dictionary containing variable name, value and description """ # Compile regex for converting underscores which are spaces into # a space character @@ -209,18 +177,14 @@ def parse(self, mfile_addr: str) -> dict: Parameters ---------- - mfile_addr : str + mfile_addr : address of MFILE to parse Returns ------- - Dict + : dictionary of output values - Raises - ------ - FileNotFoundError - if the input file does not exist """ if not os.path.exists(mfile_addr): raise FileNotFoundError( @@ -345,7 +309,7 @@ def _key_update(key): self._logger.info("Extraction completed successfully") return self._mfile_data - def write(self, output_filename: str) -> None: + def write(self, output_filename: str): """Write output to file. Parameters diff --git a/process/io/mfile_comparison.py b/process/io/mfile_comparison.py index 18a2898a46..bf1967dc14 100644 --- a/process/io/mfile_comparison.py +++ b/process/io/mfile_comparison.py @@ -4,16 +4,10 @@ The tool does not work for MFiles that are not the result of a full PROCESS run (ie if an error or exception occured). -James Morris -14/04/15 - -CCFE - Notes: + 24/11/2021: Global dictionary variables moved within the functions to avoid cyclic dependencies. This is because the dicts generation script imports, and inspects, process. - """ import argparse @@ -280,8 +274,10 @@ class BColors: def main(arg): """Main function for comparing MFILEs - :param arg: List of arguments - :return: + Parameters + ---------- + arg : + List of arguments """ print_counter = 0 diff --git a/process/io/mfile_to_csv.py b/process/io/mfile_to_csv.py index 55f7abe3fd..60afaeeedc 100644 --- a/process/io/mfile_to_csv.py +++ b/process/io/mfile_to_csv.py @@ -1,10 +1,6 @@ """ Code to read from a PROCESS MFILE and write values into a csv -Author: R Chapman (rhian.chapman@ukaea.uk) -Date: 26/05/2021 -Updated: 06/06/2022 - Input files: mfile (default MFILE.DAT) as output from PROCESS variable list (default mfile_to_csv_vars.json) as defined by user @@ -14,7 +10,6 @@ Output file: .csv will be saved to the directory of the input file - """ # == import modules == @@ -33,10 +28,15 @@ def parse_args(args): """Parse supplied arguments. - :param args: arguments to parse - :type args: list, None - :return: parsed arguments - :rtype: Namespace + Parameters + ---------- + args : list, None + arguments to parse + + Returns + ------- + Namespace + parsed arguments """ parser = argparse.ArgumentParser( description="Read from a PROCESS MFILE and write values into a csv." @@ -62,10 +62,17 @@ def parse_args(args): def get_vars(vfile="mfile_to_csv_vars.json"): """Returns variable names from identified file. - :param args: input JSON filename - :type args: string - :return: variable names - :rtype: list + Parameters + ---------- + args : string + input JSON filename + vfile : + (Default value = "mfile_to_csv_vars.json") + + Returns + ------- + list + variable names """ print("Fetching list of variables from", vfile) @@ -75,10 +82,19 @@ def get_vars(vfile="mfile_to_csv_vars.json"): def read_mfile(mfilename="MFILE.DAT", variables=None): """Returns specified variable values from identified file. - :param args: input filename, variable names - :type args: string, list - :return: variable descriptions, names, and values - :rtype: list of tuples + Parameters + ---------- + args : string, list + input filename, variable names + mfilename : + (Default value = "MFILE.DAT") + variables : + (Default value = None) + + Returns + ------- + list of tuples + variable descriptions, names, and values """ if variables is None: variables = [] @@ -105,10 +121,17 @@ def read_mfile(mfilename="MFILE.DAT", variables=None): def get_savenamepath(mfilename="MFILE.DAT"): """Returns path/filename.csv for file saving. - :param args: input filename - :type args: string - :return: output filename - :rtype: pathlib.PurePosixPath + Parameters + ---------- + args : string + input filename + mfilename : + (Default value = "MFILE.DAT") + + Returns + ------- + pathlib.PurePosixPath + output filename """ # Either save it locally or output the csv file to the directory of the input file @@ -121,8 +144,14 @@ def get_savenamepath(mfilename="MFILE.DAT"): def write_to_csv(csv_outfile, output_data=None): """Write to csv file. - :param args: input filename, variable data - :type args: string, list of tuples + Parameters + ---------- + args : string, list of tuples + input filename, variable data + csv_outfile : + + output_data : + (Default value = None) """ if output_data is None: output_data = [] @@ -138,8 +167,10 @@ def write_to_csv(csv_outfile, output_data=None): def main(args=None): """Extract certain variables from an MFILE.DAT and output to CSV. - :param args: optional command-line args for testing, defaults to None - :type args: list, optional + Parameters + ---------- + args : list, optional + optional command-line args for testing, defaults to None """ # read from command line inputs args = parse_args(args) diff --git a/process/io/plot_plotly_sankey.py b/process/io/plot_plotly_sankey.py index bea9fdb676..396aad3957 100644 --- a/process/io/plot_plotly_sankey.py +++ b/process/io/plot_plotly_sankey.py @@ -13,9 +13,6 @@ def main(args=None): - ########################################################### - # Usage - if not PLOT_SANKEY: print( "\nPlotly is not installed, unable to create sankey diagram!\n" @@ -25,8 +22,7 @@ def main(args=None): return parser = argparse.ArgumentParser( - description="Program to plot\ - the power flow in PROCESS using a Sankey diagram." + description="Program to plot the power flow in PROCESS using a Sankey diagram." ) parser.add_argument("-e", "--end", default="pdf", help="file format, default = pdf") @@ -37,9 +33,6 @@ def main(args=None): args = parser.parse_args(args) - ######################################################### - # main program - plot_power_balance_sankey(args.mfile) diff --git a/process/io/plot_proc.py b/process/io/plot_proc.py index 67ab13a497..c1a37ea178 100644 --- a/process/io/plot_proc.py +++ b/process/io/plot_proc.py @@ -2,15 +2,9 @@ PROCESS plot_proc using process_io_lib functions and MFILE.DAT -James Morris -13/04/2014 -CCFE -Revised by Michael Kovari, 7/1/2016 - 24/11/2021: Global dictionary variables moved within the functions to avoid cyclic dependencies. This is because the dicts generation script imports, and inspects, process. - """ import argparse @@ -87,10 +81,15 @@ class RadialBuild: def parse_args(args): """Parse supplied arguments. - :param args: arguments to parse - :type args: list, None - :return: parsed arguments - :rtype: Namespace + Parameters + ---------- + args : list, None + arguments to parse + + Returns + ------- + Namespace + parsed arguments """ # Setup command line arguments parser = argparse.ArgumentParser( @@ -214,12 +213,16 @@ def plot_plasma( ): """Plots the plasma boundary arcs. - Arguments: - axis --> axis object to plot to - mfile --> MFILE data object - scan --> scan number to use - colour_scheme --> colour scheme to use for plots - + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE data object + scan : + scan number to use + colour_scheme : + colour scheme to use for plots """ (r_0, a, triang, kappa, i_single_null, i_plasma_shape, plasma_square) = ( @@ -276,10 +279,14 @@ def plot_plasma( def plot_centre_cross(axis: plt.Axes, mfile: mf.MFile, scan: int): """Function to plot centre cross on plot - Arguments: - axis --> axis object to plot to - mfile --> MFILE data object - scan --> scan number to use + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE data object + scan : + scan number to use """ rmajor = mfile.get("rmajor", scan=scan) axis.plot( @@ -293,14 +300,19 @@ def cumulative_radial_build(section, mfile: mf.MFile, scan: int): """Function for calculating the cumulative radial build up to and including the given section. - Arguments: - section --> section of the radial build to go up to - mfile --> MFILE data object - scan --> scan number to use - - Returns: - cumulative_build --> cumulative radial build up to section given + Parameters + ---------- + section : + section of the radial build to go up to + mfile : + MFILE data object + scan : + scan number to use + Returns + ------- + : + cumulative_build:cumulative radial build up to section given """ complete = False cumulative_build = 0 @@ -328,16 +340,21 @@ def cumulative_radial_build2(section, mfile: mf.MFile, scan: int): """Function for calculating the cumulative radial build up to and including the given section. - Arguments: - section --> section of the radial build to go up to - mfile --> MFILE data object - scan --> scan number to use + Parameters + ---------- + section : + section of the radial build to go up to + mfile : + MFILE data object + scan : + scan number to use - Returns: + Returns + ------- + : cumulative_build --> cumulative radial build up to and including - section given + section given previous --> cumulative radial build up to section given - """ cumulative_build = 0 build = 0 @@ -369,12 +386,18 @@ def poloidal_cross_section( ): """Function to plot poloidal cross-section - Arguments: - axis --> axis object to add plot to - mfile --> MFILE data object - scan --> scan number to use - colour_scheme --> colour scheme to use for plots - + Parameters + ---------- + axis : + axis object to add plot to + mfile : + MFILE data object + scan : + scan number to use + demo_ranges: + + colour_scheme : + colour scheme to use for plots """ axis.set_xlabel("R / m") @@ -407,19 +430,21 @@ def poloidal_cross_section( # --- -def plot_main_power_flow( - axis: plt.Axes, mfile: mf.MFile, scan: int, fig: plt.Figure -) -> None: - """ - Plots the main power flow diagram for the fusion reactor, including plasma, heating and current drive, +def plot_main_power_flow(axis: plt.Axes, mfile: mf.MFile, scan: int, fig: plt.Figure): + """Plots the main power flow diagram for the fusion reactor, including plasma, heating and current drive, first wall, blanket, vacuum vessel, divertor, coolant pumps, turbine, generator, and auxiliary systems. Annotates the diagram with power values and draws arrows to indicate power flows. - Args: - axis (plt.Axes): The matplotlib axis object to plot on. - mfile (mf.MFile): The MFILE data object containing power flow parameters. - scan (int): The scan number to use for extracting data. - fig (plt.Figure): The matplotlib figure object for additional annotations. + Parameters + ---------- + axis: + The matplotlib axis object to plot on. + mfile: + The MFILE data object containing power flow parameters. + scan: + The scan number to use for extracting data. + fig: + The matplotlib figure object for additional annotations. """ axis.text( @@ -2369,17 +2394,22 @@ def plot_main_plasma_information( scan: int, colour_scheme: Literal[1, 2], fig: plt.Figure, -) -> None: - """ - Plots the main plasma information including plasma shape, geometry, currents, heating, +): + """Plots the main plasma information including plasma shape, geometry, currents, heating, confinement, and other relevant plasma parameters. - Args: - axis (plt.Axes): The matplotlib axis object to plot on. - mfile (mf.MFile): The MFILE data object containing plasma parameters. - scan (int): The scan number to use for extracting data. - colour_scheme (int): The colour scheme to use for plots. - fig (plt.Figure): The matplotlib figure object for additional annotations. + Parameters + ---------- + axis : plt.Axes + The matplotlib axis object to plot on. + mfile : mf.MFile + The MFILE data object containing plasma parameters. + scan : int + The scan number to use for extracting data. + colour_scheme : int + The colour scheme to use for plots. + fig : plt.Figure + The matplotlib figure object for additional annotations. """ # Import key variables triang = mfile.get("triang", scan=scan) @@ -3025,8 +3055,6 @@ def plot_main_plasma_information( transform=fig.transFigure, ) - # ================================================= - # Add magnetic field information textstr_fields = ( f"$\\mathbf{{Magnetic\\ fields:}}$\n\n" @@ -3062,8 +3090,6 @@ def plot_main_plasma_information( transform=fig.transFigure, ) - # =========================================== - # Add radiation information textstr_radiation = ( f" $\\mathbf{{Radiation:}}$\n\n" @@ -3102,8 +3128,6 @@ def plot_main_plasma_information( transform=fig.transFigure, ) - # ============================================ - # Add L-H threshold information textstr_lh = ( f"$\\mathbf{{L-H \\ threshold:}}$\n\n" @@ -3125,8 +3149,6 @@ def plot_main_plasma_information( }, ) - # ====================================== - # Add density limit information textstr_density_limit = ( f"$\\mathbf{{Density \\ limit:}}$\n\n" @@ -3149,15 +3171,8 @@ def plot_main_plasma_information( ) -def plot_current_profiles_over_time(axis: plt.Axes, mfile: mf.MFile, scan: int) -> None: - """ - Plots the current profiles over time for PF circuits, CS coil, and plasma. - - Arguments: - axis (plt.Axes): Axis object to plot to. - mfile (mf.MFile): MFILE data object. - scan (int): Scan number to use. - """ +def plot_current_profiles_over_time(axis: plt.Axes, mfile: mf.MFile, scan: int): + """Plots the current profiles over time for PF circuits, CS coil, and plasma.""" t_plant_pulse_coil_precharge = mfile.get("t_plant_pulse_coil_precharge", scan=scan) t_plant_pulse_plasma_current_ramp_up = mfile.get( "t_plant_pulse_plasma_current_ramp_up", scan=scan @@ -3256,19 +3271,9 @@ def plot_current_profiles_over_time(axis: plt.Axes, mfile: mf.MFile, scan: int) def plot_system_power_profiles_over_time( - axis: plt.Axes, - mfile: mf.MFile, - scan: int, - fig, -) -> None: - """ - Plots the power profiles over time for various systems. - - Arguments: - axis (plt.Axes): Axis object to plot to. - mfile (mf.MFile): MFILE data object. - scan (int): Scan number to use. - """ + axis: plt.Axes, mfile: mf.MFile, scan: int, fig +): + """Plots the power profiles over time for various systems.""" t_precharge = mfile.get("t_plant_pulse_coil_precharge", scan=scan) t_current_ramp_up = mfile.get("t_plant_pulse_plasma_current_ramp_up", scan=scan) @@ -3423,12 +3428,7 @@ def plot_system_power_profiles_over_time( fontsize=9, verticalalignment="top", transform=fig.transFigure, - bbox={ - "boxstyle": "round", - "facecolor": "grey", - "alpha": 1.0, - "linewidth": 2, - }, + bbox={"boxstyle": "round", "facecolor": "grey", "alpha": 1.0, "linewidth": 2}, ) @@ -3455,11 +3455,7 @@ def plot_cryostat( def color_key(axis: plt.Axes, mfile: mf.MFile, scan: int, colour_scheme: Literal[1, 2]): - """Function to plot the colour key - Arguments: - axis --> object to add plot to - colour_scheme --> colour scheme to use for plots - """ + """Function to plot the colour key""" axis.set_ylim([0, 10]) axis.set_xlim([0, 10]) @@ -3528,13 +3524,7 @@ def toroidal_cross_section( demo_ranges: bool, colour_scheme: Literal[1, 2], ): - """Function to plot toroidal cross-section - Arguments: - axis --> axis object to add plot to - mfile --> MFILE data object - scan --> scan number to use - colour_scheme --> colour scheme to use for plots - """ + """Function to plot toroidal cross-section""" axis.set_xlabel("x / m") axis.set_ylabel("y / m") @@ -3741,13 +3731,20 @@ def TF_outboard(axis: plt.Axes, item, n_tf_coils, r3, r4, w, facecolor): def arc(axis: plt.Axes, r, theta1=0, theta2=rtangle, style="solid"): """Plots an arc. - Arguments - - axis: plot object - r: radius - theta1: starting polar angle - theta2: finishing polar angle - + Parameters + ---------- + axis : + plot object + r : + radius + theta1 : + starting polar angle (Default value = 0) + theta2 : + finishing polar angle (Default value = rtangle) + axis: plt.Axes : + + style : + (Default value = "solid") """ angs = np.linspace(theta1, theta2) xs = r * np.cos(angs) @@ -3758,11 +3755,18 @@ def arc(axis: plt.Axes, r, theta1=0, theta2=rtangle, style="solid"): def arc_fill(axis: plt.Axes, r1, r2, color="pink"): """Fills the space between two quarter circles. - Arguments + Parameters + ---------- + axis : + plot object + r1 : + r2 radii to be filled + axis: plt.Axes : - axis: plot object - r1, r2 radii to be filled + r2 : + color : + (Default value = "pink") """ angs = np.linspace(0, rtangle, endpoint=True) xs1 = r1 * np.cos(angs) @@ -3781,8 +3785,17 @@ def arc_fill(axis: plt.Axes, r1, r2, color="pink"): def plot_n_profiles(prof, demo_ranges: bool, mfile: mf.MFile, scan: int): """Function to plot density profile - Arguments: - prof --> axis object to add plot to + + Parameters + ---------- + prof : + axis object to add plot to + demo_ranges: bool : + + mfile: mf.MFile : + + scan: int : + """ nd_alphas = mfile.get("nd_plasma_alphas_vol_avg", scan=scan) nd_protons = mfile.get("nd_plasma_protons_vol_avg", scan=scan) @@ -3997,8 +4010,15 @@ def plot_n_profiles(prof, demo_ranges: bool, mfile: mf.MFile, scan: int): def plot_jprofile(prof, mfile: mf.MFile, scan: int): """Function to plot density profile - Arguments: - prof --> axis object to add plot to + + Parameters + ---------- + prof : + axis object to add plot to + mfile: mf.MFile : + + scan: int : + """ alphaj = mfile.get("alphaj", scan=scan) j_plasma_0 = mfile.get("j_plasma_on_axis", scan=scan) @@ -4065,8 +4085,17 @@ def plot_jprofile(prof, mfile: mf.MFile, scan: int): def plot_t_profiles(prof, demo_ranges: bool, mfile: mf.MFile, scan: int): """Function to plot temperature profile - Arguments: - prof --> axis object to add plot to + + Parameters + ---------- + prof : + axis object to add plot to + demo_ranges: bool : + + mfile: mf.MFile : + + scan: int : + """ prof.set_xlabel(r"$\rho \quad [r/a]$") @@ -4178,8 +4207,16 @@ def plot_t_profiles(prof, demo_ranges: bool, mfile: mf.MFile, scan: int): def plot_qprofile(prof, demo_ranges: bool, mfile: mf.MFile, scan: int): """Function to plot q profile, formula taken from Nevins bootstrap model. - Arguments: - prof --> axis object to add plot to + Parameters + ---------- + prof : + axis object to add plot to + demo_ranges: bool : + + mfile: mf.MFile : + + scan: int : + """ prof.set_xlabel(r"$\rho \quad [r/a]$") prof.set_ylabel("$q$") @@ -4240,9 +4277,14 @@ def plot_qprofile(prof, demo_ranges: bool, mfile: mf.MFile, scan: int): def read_imprad_data(_skiprows, data_path): """Function to read all data needed for creation of radiation profile - Arguments: - skiprows --> number of rows to skip when reading impurity data files - data_path --> path to impurity data + Parameters + ---------- + skiprows : + number of rows to skip when reading impurity data files + data_path : + path to impurity data + _skiprows : + """ label = [ "H_", @@ -4365,11 +4407,22 @@ def profiles_with_pedestal(mfile, scan: int): def plot_radprofile(prof, mfile: mf.MFile, scan: int, impp, demo_ranges: bool): """Function to plot radiation profile, formula taken from ???. - Arguments: - prof --> axis object to add plot to - mfile --> MFILE.DAT object - scan --> scan number to use - impp --> impurity path + Parameters + ---------- + prof : + axis object to add plot to + mfile : + MFILE + scan : + scan number to use + impp : + impurity path + mfile: mf.MFile : + + scan: int : + + demo_ranges: bool : + """ prof.set_xlabel(r"$\rho \quad [r/a]$") @@ -4469,9 +4522,8 @@ def plot_radprofile(prof, mfile: mf.MFile, scan: int, impp, demo_ranges: bool): # --- -def plot_rad_contour(axis: "mpl.axes.Axes", mfile: "Any", scan: int, impp: str) -> None: - """ - Plots the contour of line and bremsstrahlung radiation density for a plasma cross-section. +def plot_rad_contour(axis: "mpl.axes.Axes", mfile: "Any", scan: int, impp: str): + """Plots the contour of line and bremsstrahlung radiation density for a plasma cross-section. This function reads impurity and plasma profile data, computes the radiation density profile, interpolates it onto a 2D grid, and plots the upper and lower half contours on the provided axis. @@ -4604,11 +4656,18 @@ def plot_vacuum_vessel_and_divertor( ): """Function to plot vacuum vessel and divertor boxes - Arguments: - axis --> axis object to plot to - mfile --> MFILE data object - scan --> scan number to use - colour_scheme --> colour scheme to use for plots + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE data object + scan : + scan number to use + radial_build : + + colour_scheme : + colour scheme to use for plots """ cumulative_upper = radial_build.cumulative_upper cumulative_lower = radial_build.cumulative_lower @@ -4801,11 +4860,19 @@ def plot_vacuum_vessel_and_divertor( def plot_shield(axis: plt.Axes, mfile: mf.MFile, scan: int, radial_build, colour_scheme): """Function to plot shield - Arguments: - axis --> axis object to plot to - mfile --> MFILE data object - scan --> scan number to use - colour_scheme --> colour scheme to use for plots + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE data object + scan : + scan number to use + radial_build : + + colour_scheme : + colour scheme to use for plots + """ cumulative_upper = radial_build.cumulative_upper cumulative_lower = radial_build.cumulative_lower @@ -4862,17 +4929,21 @@ def plot_shield(axis: plt.Axes, mfile: mf.MFile, scan: int, radial_build, colour ) -def plot_blanket( - axis: plt.Axes, mfile: mf.MFile, scan, radial_build, colour_scheme -) -> None: +def plot_blanket(axis: plt.Axes, mfile: mf.MFile, scan, radial_build, colour_scheme): """Function to plot blanket - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - colour_scheme --> colour scheme to use for plots - + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use + radial_build : + + colour_scheme : + colour scheme to use for plots """ cumulative_upper = radial_build.cumulative_upper cumulative_lower = radial_build.cumulative_lower @@ -5217,12 +5288,18 @@ def plot_firstwall( ): """Function to plot first wall - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - colour_scheme --> colour scheme to use for plots - + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use + radial_build : + + colour_scheme : + colour scheme to use for plots """ cumulative_upper = radial_build.cumulative_upper cumulative_lower = radial_build.cumulative_lower @@ -5319,12 +5396,16 @@ def plot_tf_coils( ): """Function to plot TF coils - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - colour_scheme --> colour scheme to use for plots - + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use + colour_scheme : + colour scheme to use for plots """ # Arc points @@ -5421,10 +5502,8 @@ def plot_tf_coils( ) -def plot_superconducting_tf_wp(axis: plt.Axes, mfile: mf.MFile, scan: int, fig) -> None: - """ - Plots inboard TF coil and winding pack. - Author: C. Ashe +def plot_superconducting_tf_wp(axis: plt.Axes, mfile: mf.MFile, scan: int, fig): + """Plots inboard TF coil and winding pack. Parameters ---------- @@ -5434,10 +5513,6 @@ def plot_superconducting_tf_wp(axis: plt.Axes, mfile: mf.MFile, scan: int, fig) Object containing data for the plot. scan : int Scan number to use. - - Returns - ------- - None """ # Import the TF variables @@ -6125,10 +6200,8 @@ def plot_superconducting_tf_wp(axis: plt.Axes, mfile: mf.MFile, scan: int, fig) axis.legend(loc="upper left") -def plot_resistive_tf_wp(axis: plt.Axes, mfile: mf.MFile, scan: int, fig) -> None: - """ - Plots inboard TF coil and winding pack. - Author: C. Ashe +def plot_resistive_tf_wp(axis: plt.Axes, mfile: mf.MFile, scan: int, fig): + """Plots inboard TF coil and winding pack. Parameters ---------- @@ -6138,10 +6211,6 @@ def plot_resistive_tf_wp(axis: plt.Axes, mfile: mf.MFile, scan: int, fig) -> Non Object containing data for the plot. scan : int Scan number to use. - - Returns - ------- - None """ # Import the TF variables @@ -6518,7 +6587,7 @@ def plot_resistive_tf_wp(axis: plt.Axes, mfile: mf.MFile, scan: int, fig) -> Non ) -def plot_resistive_tf_info(axis: plt.Axes, mfile: mf.MFile, scan: int, fig) -> None: +def plot_resistive_tf_info(axis: plt.Axes, mfile: mf.MFile, scan: int, fig): # Add info about the steel casing surrounding the WP textstr_casing = ( f"$\\mathbf{{Casing:}}$\n \n" @@ -6639,12 +6708,8 @@ def plot_resistive_tf_info(axis: plt.Axes, mfile: mf.MFile, scan: int, fig) -> N ) -def plot_tf_cable_in_conduit_turn( - axis: plt.Axes, fig, mfile: mf.MFile, scan: int -) -> None: - """ - Plots inboard TF coil CICC individual turn structure. - Author: C. Ashe +def plot_tf_cable_in_conduit_turn(axis: plt.Axes, fig, mfile: mf.MFile, scan: int): + """Plots inboard TF coil CICC individual turn structure. Parameters ---------- @@ -6654,10 +6719,6 @@ def plot_tf_cable_in_conduit_turn( Object containing data for the plot. scan : int Scan number to use. - - Returns - ------- - None """ def _pack_strands_rectangular_with_obstacles( @@ -6671,7 +6732,29 @@ def _pack_strands_rectangular_with_obstacles( corner_radius, f_a_tf_turn_cable_copper, ): - """Pack circular strands in rectangular space with cooling pipe obstacle""" + """Pack circular strands in rectangular space with cooling pipe obstacle + + Parameters + ---------- + cable_space_bounds : + + pipe_center : + + pipe_radius : + + strand_diameter : + + void_fraction : + + n_strands : + + axis : + + corner_radius : + + f_a_tf_turn_cable_copper : + + """ x, y, width, height = cable_space_bounds @@ -7211,9 +7294,19 @@ def _pack_strands_rectangular_with_obstacles( ) -def plot_cable_in_conduit_cable(axis: plt.Axes, fig, mfile: mf.MFile, scan: int) -> None: - """ - Plots TF coil CICC cable cross-section. +def plot_cable_in_conduit_cable(axis: plt.Axes, fig, mfile: mf.MFile, scan: int): + """Plots TF coil CICC cable cross-section. + + Parameters + ---------- + axis: plt.Axes : + + fig : + + mfile: mf.MFile : + + scan: int : + """ dia_tf_turn_superconducting_cable = mfile.get( @@ -7300,11 +7393,16 @@ def plot_pf_coils( ): """Function to plot PF coils - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - colour_scheme --> colour scheme to use for plots + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use + colour_scheme : + colour scheme to use for plots """ coils_r = [] @@ -7389,12 +7487,16 @@ def plot_pf_coils( def plot_info(axis: plt.Axes, data, mfile: mf.MFile, scan: int): """Function to plot data in written form on a matplotlib plot. - Arguments: - axis --> axis object to plot to - data --> plot information - mfile --> MFILE.DAT object - scan --> scan number to use - + Parameters + ---------- + axis : + axis object to plot to + data : + plot information + mfile : + MFILE + scan : + scan number to use """ eqpos = 0.75 for i in range(len(data)): @@ -7462,11 +7564,14 @@ def plot_info(axis: plt.Axes, data, mfile: mf.MFile, scan: int): def plot_header(axis: plt.Axes, mfile: mf.MFile, scan: int): """Function to plot header info: date, rutitle etc - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use """ xmin = 0 xmax = 1 @@ -7579,11 +7684,14 @@ def plot_header(axis: plt.Axes, mfile: mf.MFile, scan: int): def plot_geometry_info(axis: plt.Axes, mfile: mf.MFile, scan: int): """Function to plot geometry info - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use """ xmin = 0 xmax = 1 @@ -7625,11 +7733,14 @@ def plot_geometry_info(axis: plt.Axes, mfile: mf.MFile, scan: int): def plot_physics_info(axis: plt.Axes, mfile: mf.MFile, scan: int): """Function to plot geometry info - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use """ xmin = 0 xmax = 1 @@ -7699,11 +7810,14 @@ def plot_physics_info(axis: plt.Axes, mfile: mf.MFile, scan: int): def plot_magnetics_info(axis: plt.Axes, mfile: mf.MFile, scan: int): """Function to plot magnet info - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use """ # Check for Copper magnets i_tf_sup = int(mfile.get("i_tf_sup", scan=scan)) if "i_tf_sup" in mfile.data else 1 @@ -7825,11 +7939,14 @@ def plot_magnetics_info(axis: plt.Axes, mfile: mf.MFile, scan: int): def plot_power_info(axis: plt.Axes, mfile: mf.MFile, scan: int): """Function to plot power info - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use """ xmin = 0 @@ -7914,11 +8031,14 @@ def plot_power_info(axis: plt.Axes, mfile: mf.MFile, scan: int): def plot_current_drive_info(axis: plt.Axes, mfile: mf.MFile, scan: int): """Function to plot current drive info - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use """ xmin = 0 @@ -8172,10 +8292,14 @@ def plot_current_drive_info(axis: plt.Axes, mfile: mf.MFile, scan: int): def plot_bootstrap_comparison(axis: plt.Axes, mfile: mf.MFile, scan: int): """Function to plot a scatter box plot of bootstrap current fractions. - Arguments: - axis --> axis object to plot to - mfile --> MFILE data object - scan --> scan number to use + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE data object + scan : + scan number to use """ boot_ipdg = mfile.get("f_c_plasma_bootstrap_iter89", scan=scan) @@ -8255,16 +8379,19 @@ def plot_bootstrap_comparison(axis: plt.Axes, mfile: mf.MFile, scan: int): axis.set_facecolor("#f0f0f0") -def plot_h_threshold_comparison( - axis: plt.Axes, mfile: mf.MFile, scan: int, u_seed=None -) -> None: - """ - Function to plot a scatter box plot of L-H threshold power comparisons. +def plot_h_threshold_comparison(axis: plt.Axes, mfile: mf.MFile, scan: int, u_seed=None): + """Function to plot a scatter box plot of L-H threshold power comparisons. - Arguments: - axis (plt.Axes): Axis object to plot to. - mfile (mf.MFile): MFILE data object. - scan (int): Scan number to use. + Parameters + ---------- + axis : + Axis object to plot to. + mfile : + MFILE data object. + scan : + Scan number to use. + u_seed : + (Default value = None) """ iter_nominal = mfile.get("l_h_threshold_powers(1)", scan=scan) iter_upper = mfile.get("l_h_threshold_powers(2)", scan=scan) @@ -8388,14 +8515,19 @@ def plot_h_threshold_comparison( def plot_confinement_time_comparison( axis: plt.Axes, mfile: mf.MFile, scan: int, u_seed=None -) -> None: - """ - Function to plot a scatter box plot of confinement time comparisons. +): + """Function to plot a scatter box plot of confinement time comparisons. - Arguments: - axis (plt.Axes): Axis object to plot to. - mfile (mf.MFile): MFILE data object. - scan (int): Scan number to use. + Parameters + ---------- + axis : + Axis object to plot to. + mfile : + MFILE data object. + scan : + Scan number to use. + u_seed : + (Default value = None) """ rminor = mfile.get("rminor", scan=scan) rmajor = mfile.get("rmajor", scan=scan) @@ -8721,11 +8853,8 @@ def plot_confinement_time_comparison( axis.set_facecolor("#f0f0f0") -def plot_radial_build( - axis: plt.Axes, mfile: mf.MFile, colour_scheme: Literal[1, 2] -) -> None: - """ - Plots the radial build of a fusion device on the given matplotlib axis. +def plot_radial_build(axis: plt.Axes, mfile: mf.MFile, colour_scheme: Literal[1, 2]): + """Plots the radial build of a fusion device on the given matplotlib axis. This function visualizes the different layers/components of the machine's radial build (such as central solenoid, toroidal field coils, vacuum vessel, shields, blankets, etc.) @@ -8743,14 +8872,11 @@ def plot_radial_build( mfile : mf.MFile An object containing the machine build data, with required fields for each radial component and the "i_tf_inside_cs" flag. - - Returns - ------- - None - This function modifies the provided axis in-place and does not return a value. + colour_scheme: Notes ----- + This function modifies the provided axis in-place and does not return a value. - Components with zero thickness are omitted from the plot. - The legend displays the name and thickness (in meters) of each component. """ @@ -8909,9 +9035,8 @@ def plot_radial_build( def plot_lower_vertical_build( axis: plt.Axes, mfile: mf.MFile, colour_scheme: Literal[1, 2] -) -> None: - """ - Plots the lower vertical build of a fusion device on the given matplotlib axis. +): + """Plots the lower vertical build of a fusion device on the given matplotlib axis. This function visualizes the different layers/components of the machine's vertical build (such as plasma, first wall, divertor, shield, vacuum vessel, thermal shield, TF coil, etc.) @@ -8920,21 +9045,18 @@ def plot_lower_vertical_build( Parameters ---------- - axis : matplotlib.axes.Axes + axis : The matplotlib axis on which to plot the vertical build. - mfile : mf.MFile + mfile : An object containing the machine build data, with required fields for each vertical component. - colour_scheme : int + colour_scheme : Colour scheme index to use for component colors. - Returns - ------- - None - This function modifies the provided axis in-place and does not return a value. Notes ----- + This function modifies the provided axis in-place and does not return a value. - Components with zero thickness are omitted from the plot. - The legend displays the name and thickness (in meters) of each component. """ @@ -9019,9 +9141,8 @@ def plot_lower_vertical_build( def plot_upper_vertical_build( axis: plt.Axes, mfile: mf.MFile, colour_scheme: Literal[1, 2] -) -> None: - """ - Plots the upper vertical build of a fusion device on the given matplotlib axis. +): + """Plots the upper vertical build of a fusion device on the given matplotlib axis. This function visualizes the different layers/components of the machine's vertical build (such as plasma, first wall, divertor, shield, vacuum vessel, thermal shield, TF coil, etc.) @@ -9030,21 +9151,17 @@ def plot_upper_vertical_build( Parameters ---------- - axis : matplotlib.axes.Axes + axis: The matplotlib axis on which to plot the vertical build. - mfile : mf.MFile + mfile: An object containing the machine build data, with required fields for each vertical component. - colour_scheme : int + colour_scheme: Colour scheme index to use for component colors. - Returns - ------- - None - This function modifies the provided axis in-place and does not return a value. - Notes ----- + This function modifies the provided axis in-place and does not return a value. - Components with zero thickness are omitted from the plot. - The legend displays the name and thickness (in meters) of each component. """ @@ -9175,14 +9292,17 @@ def plot_upper_vertical_build( axis.title.set_text("Upper Vertical Build") -def plot_density_limit_comparison(axis: plt.Axes, mfile: mf.MFile, scan: int) -> None: - """ - Function to plot a scatter box plot of different density limit comparisons. +def plot_density_limit_comparison(axis: plt.Axes, mfile: mf.MFile, scan: int): + """Function to plot a scatter box plot of different density limit comparisons. - Arguments: - axis (plt.Axes): Axis object to plot to. - mfile (mf.MFile): MFILE data object. - scan (int): Scan number to use. + Parameters + ---------- + axis : + Axis object to plot to. + mfile : + MFILE data object. + scan : + Scan number to use. """ old_asdex = mfile.get("nd_plasma_electron_max_array(1)", scan=scan) borrass_iter_i = mfile.get("nd_plasma_electron_max_array(2)", scan=scan) @@ -9263,12 +9383,19 @@ def plot_cs_coil_structure( ): """Function to plot the coil structure of the CS. - Arguments: - axis --> axis object to plot to - mfile --> MFILE.DAT object - scan --> scan number to use - demo_ranges --> whether to use demo ranges for the plot - colour_scheme --> colour scheme to use for the plot + Parameters + ---------- + axis : + axis object to plot to + mfile : + MFILE + scan : + scan number to use + demo_ranges : + whether to use demo ranges for the plot + colour_scheme : + colour scheme to use for the plot (Default value = 1) + """ # Get CS coil parameters dr_cs = mfile.get("dr_cs", scan=scan) @@ -9977,7 +10104,17 @@ def plot_tf_coil_structure(axis: plt.Axes, mfile: mf.MFile, scan: int, colour_sc def plot_iteration_variables(axis: plt.Axes, m_file: mf.MFile, scan: int): - """Plot the iteration variables and where they lay in their bounds on a given axes""" + """Plot the iteration variables and where they lay in their bounds on a given axes + + Parameters + ---------- + axis: plt.Axes : + + m_file: mf.MFile : + + scan: int : + + """ # Get total number of iteration variables n_itvars = int(m_file.get("nvar", scan=scan)) @@ -10044,7 +10181,7 @@ def plot_iteration_variables(axis: plt.Axes, m_file: mf.MFile, scan: int): label="Final Value" if n_plot == 0 else "", ) - # Plot scatter point for normalized relative change + # Plot scatter point for normalised relative change axis.scatter( norm_relative_change, n_plot, @@ -10130,11 +10267,17 @@ def plot_iteration_variables(axis: plt.Axes, m_file: mf.MFile, scan: int): def plot_tf_stress(axis: plt.Axes, mfile: mf.MFile): - """ - Function to plot the TF coil stress from the SIG_TF.json file. + """Function to plot the TF coil stress from the SIG_TF.json file. Input file: SIG_TF.json + + Parameters + ---------- + axis: plt.Axes : + + mfile: mf.MFile : + """ # Step 1 : Data extraction @@ -10595,7 +10738,17 @@ def plot_tf_stress(axis: plt.Axes, mfile: mf.MFile): def plot_blkt_pipe_bends(fig, m_file, scan: int): - """Plot the blanket pipe bends on the given axis, with axes in mm.""" + """Plot the blanket pipe bends on the given axis, with axes in mm. + + Parameters + ---------- + fig : + + m_file : + + scan: int : + + """ ax_90 = fig.add_subplot(331) ax_180 = fig.add_subplot(334) @@ -10677,7 +10830,17 @@ def plot_blkt_pipe_bends(fig, m_file, scan: int): def plot_fw_90_deg_pipe_bend(ax, m_file, scan: int): - """Plot the first wall pipe 90 degree bend on the given axis, with axes in mm.""" + """Plot the first wall pipe 90 degree bend on the given axis, with axes in mm. + + Parameters + ---------- + ax : + + m_file : + + scan: int : + + """ # Get pipe radius from m_file, fallback to 0.1 m r = m_file.get("radius_fw_channel", scan=scan) @@ -10841,7 +11004,7 @@ def plot_fusion_rate_profiles(axis: plt.Axes, fig, mfile: mf.MFile, scan: int): # ================================================= - # Compute cumulative integral (trapezoidal) of the total fusion rate profile vs normalized radius + # Compute cumulative integral (trapezoidal) of the total fusion rate profile vs normalised radius rho_c = np.linspace(0.0, 1.0, len(fusrat_plasma_total_profile)) y_total = np.asarray(fusrat_plasma_total_profile, dtype=float) @@ -11126,14 +11289,22 @@ def plot_cover_page( radial_build: RadialBuild, colour_scheme: Literal[1, 2], ): - """ - Plots a cover page for the PROCESS run, including run title, date, user, and summary info. + """Plots a cover page for the PROCESS run, including run title, date, user, and summary info. + + Parameters + ---------- + axis : plt.Axes + The matplotlib axis object to plot on. + mfile : mf.MFile + The MFILE data object containing run info. + scan : int + The scan number to use for extracting data. + fig : plt.Figure + The matplotlib figure object for additional annotations. + radial_build: + + colour_scheme: - Args: - axis (plt.Axes): The matplotlib axis object to plot on. - mfile (mf.MFile): The MFILE data object containing run info. - scan (int): The scan number to use for extracting data. - fig (plt.Figure): The matplotlib figure object for additional annotations. """ axis.axis("off") title = mfile.get("runtitle", scan=-1) @@ -11390,7 +11561,7 @@ def plot_plasma_pressure_gradient_profiles(axis: plt.Axes, mfile: mf.MFile, scan pres_plasma_profile_fuel_kpa = np.array(pres_plasma_profile_fuel) / 1000.0 pres_plasma_profile_total_kpa = np.array(pres_plasma_profile_total) / 1000.0 - # Calculate the normalized radius + # Calculate the normalised radius rho = np.linspace(0, 1, len(pres_plasma_profile_kpa)) # Compute gradients using numpy.gradient @@ -11413,27 +11584,26 @@ def plot_plasma_pressure_gradient_profiles(axis: plt.Axes, mfile: mf.MFile, scan axis.legend() -def plot_plasma_poloidal_pressure_contours( - axis: plt.Axes, mfile: mf.MFile, scan: int -) -> None: - """ - Plot plasma poloidal pressure contours inside the plasma boundary. - - :param axis: Matplotlib axis object to plot on. - :type axis: matplotlib.axes.Axes - :param mfile: MFILE data object containing plasma and geometry data. - :type mfile: mf.MFile - :param scan: Scan number to use for extracting data. - :type scan: int +def plot_plasma_poloidal_pressure_contours(axis: plt.Axes, mfile: mf.MFile, scan: int): + """Plot plasma poloidal pressure contours inside the plasma boundary. This function visualizes the poloidal pressure distribution inside the plasma boundary by interpolating the pressure profile onto a grid defined by the plasma geometry. The pressure is shown as filled contours, with the plasma boundary overlaid. + + Parameters + ---------- + axis : matplotlib.axes.Axes + Matplotlib axis object to plot on. + mfile : mfile: mf.MFile + MFILE data object containing plasma and geometry data. + scan : int + Scan number to use for extracting data. """ n_plasma_profile_elements = int(mfile.get("n_plasma_profile_elements", scan=scan)) - # Get pressure profile (function of normalized radius rho, 0..1) + # Get pressure profile (function of normalised radius rho, 0..1) pres_plasma_electron_profile = [ mfile.get(f"pres_plasma_electron_profile{i}", scan=scan) for i in range(n_plasma_profile_elements) @@ -11565,21 +11735,22 @@ def plot_corc_cable_geometry( dx_croco_strand_tape_stack: float, n_croco_strand_hts_tapes: int, ): - """ - Plot the geometry of a CroCo strand cable. - - :param axis: The matplotlib axis to plot on. - :type axis: matplotlib.axes._axes.Axes - :param dia_croco_strand: Diameter of the CroCo strand (in meters). - :type dia_croco_strand: float - :param dx_croco_strand_copper: Thickness of the copper layer (in meters). - :type dx_croco_strand_copper: float - :param dr_hts_tape: Radius of the HTS tape stack (in meters). - :type dr_hts_tape: float - :param dx_croco_strand_tape_stack: Height of the HTS tape stack (in meters). - :type dx_croco_strand_tape_stack: float - :param n_croco_strand_hts_tapes: Number of HTS tape layers in the stack. - :type n_croco_strand_hts_tapes: int + """Plot the geometry of a CroCo strand cable. + + Parameters + ---------- + axis : matplotlib.axes._axes.Axes + The matplotlib axis to plot on. + dia_croco_strand : float + Diameter of the CroCo strand (in meters). + dx_croco_strand_copper : float + Thickness of the copper layer (in meters). + dr_hts_tape : float + Radius of the HTS tape stack (in meters). + dx_croco_strand_tape_stack : float + Height of the HTS tape stack (in meters). + n_croco_strand_hts_tapes : int + Number of HTS tape layers in the stack. """ # Plot a circle with the given diameter and copper edges circle = Circle( @@ -11714,7 +11885,7 @@ def plot_fusion_rate_contours( fig2, mfile: mf.MFile, scan: int, -) -> None: +): fusrat_plasma_dt_profile = [] fusrat_plasma_dd_triton_profile = [] fusrat_plasma_dd_helion_profile = [] @@ -11890,7 +12061,7 @@ def plot_beta_profiles(axis: plt.Axes, mfile: mf.MFile, scan: int): axis.set_ylim(bottom=0.0) -def plot_plasma_outboard_toroidal_ripple_map(fig, mfile: mf.MFile, scan: int) -> None: +def plot_plasma_outboard_toroidal_ripple_map(fig, mfile: mf.MFile, scan: int): r_tf_outboard_mid = mfile.get("r_tf_outboard_mid", scan=scan) n_tf_coils = mfile.get("n_tf_coils", scan=scan) rmajor = mfile.get("rmajor", scan=scan) @@ -12390,7 +12561,17 @@ def plot_ebw_ecrh_coupling_graph(axis: plt.Axes, mfile: mf.MFile, scan: int): def plot_debye_length_profile(axis: plt.Axes, mfile_data: mf.MFile, scan: int): - """Plot the Debye length profile on the given axis.""" + """Plot the Debye length profile on the given axis. + + Parameters + ---------- + axis : + + mfile_data : + + scan : + + """ len_plasma_debye_electron_profile = [ mfile_data.data[f"len_plasma_debye_electron_profile{i}"].get_scan(scan) for i in range(int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan))) @@ -12419,7 +12600,17 @@ def plot_debye_length_profile(axis: plt.Axes, mfile_data: mf.MFile, scan: int): def plot_velocity_profile(axis, mfile_data, scan): - """Plot the electron thermal velocity profile on the given axis.""" + """Plot the electron thermal velocity profile on the given axis. + + Parameters + ---------- + axis : + + mfile_data : + + scan : + + """ vel_plasma_electron_profile = [ mfile_data.data[f"vel_plasma_electron_profile{i}"].get_scan(scan) for i in range(int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan))) @@ -12465,7 +12656,17 @@ def plot_velocity_profile(axis, mfile_data, scan): def plot_electron_frequency_profile(axis, mfile_data, scan): - """Plot the electron thermal frequency profile on the given axis.""" + """Plot the electron thermal frequency profile on the given axis. + + Parameters + ---------- + axis : + + mfile_data : + + scan : + + """ freq_plasma_electron_profile = [ mfile_data.data[f"freq_plasma_electron_profile{i}"].get_scan(scan) for i in range(int(mfile_data.data["n_plasma_profile_elements"].get_scan(scan))) @@ -12540,7 +12741,17 @@ def plot_ion_frequency_profile(axis, mfile_data, scan): def plot_plasma_coloumb_logarithms(axis, mfile_data, scan): - """Plot the plasma coloumb logarithms on the given axis.""" + """Plot the plasma coloumb logarithms on the given axis. + + Parameters + ---------- + axis : + + mfile_data : + + scan : + + """ plasma_coulomb_log_electron_electron_profile = [ mfile_data.data[f"plasma_coulomb_log_electron_electron_profile{i}"].get_scan( scan @@ -12592,7 +12803,17 @@ def plot_plasma_coloumb_logarithms(axis, mfile_data, scan): def plot_equality_constraint_equations(axis: plt.Axes, m_file_data: mf.MFile, scan: int): - """Plot the equality constraints for a solution and their normalised residuals""" + """Plot the equality constraints for a solution and their normalised residuals + + Parameters + ---------- + axis: plt.Axes : + + m_file_data: mf.MFile : + + scan: int : + + """ y_labels = [] y_pos = [] @@ -12628,7 +12849,7 @@ def plot_equality_constraint_equations(axis: plt.Axes, m_file_data: mf.MFile, sc # Remove trailing underscores and replace underscores between words with spaces var_label = var_label.rstrip("_").replace("_", " ") - # Plot the normalized residual as a bar + # Plot the normalised residual as a bar axis.barh( n_plot, con_norm_residual, @@ -12673,7 +12894,17 @@ def plot_equality_constraint_equations(axis: plt.Axes, m_file_data: mf.MFile, sc def plot_inequality_constraint_equations(axis: plt.Axes, m_file: mf.MFile, scan: int): - """Plot the inequality constraints for a solution and where they lay within their bounds""" + """Plot the inequality constraints for a solution and where they lay within their bounds + + Parameters + ---------- + axis: plt.Axes : + + m_file: mf.MFile : + + scan: int : + + """ y_labels = [] y_pos = [] @@ -12707,7 +12938,7 @@ def plot_inequality_constraint_equations(axis: plt.Axes, m_file: mf.MFile, scan: # Unit type of the constraint con_units = m_file.data[f"ineq_units_con{n:03d}"].get_scan(scan).strip("'`") - # Add a vertical line at the normalized constraint bounds of 0 and 1 + # Add a vertical line at the normalised constraint bounds of 0 and 1 axis.axvline( 0.0, color="red", @@ -12732,16 +12963,16 @@ def plot_inequality_constraint_equations(axis: plt.Axes, m_file: mf.MFile, scan: # Calculate the normalised constraint threshold depending if the constraint is an upper # or lower limit if con_symbol == "'<='": - normalized_value = 1 - con_residual_norm - bar_left = normalized_value - bar_width = 1 - normalized_value + normalised_value = 1 - con_residual_norm + bar_left = normalised_value + bar_width = 1 - normalised_value else: - normalized_value = con_residual_norm + normalised_value = con_residual_norm bar_left = 0 - bar_width = normalized_value + bar_width = normalised_value # If the constraint value is very close to the bound then plot a square marker at the bound - if np.isclose(normalized_value, 1.0, atol=1e-3): + if np.isclose(normalised_value, 1.0, atol=1e-3): axis.plot( 1, n_plot, @@ -12750,7 +12981,7 @@ def plot_inequality_constraint_equations(axis: plt.Axes, m_file: mf.MFile, scan: markersize=8, zorder=5, ) - elif np.isclose(normalized_value, 0.0, atol=1e-3): + elif np.isclose(normalised_value, 0.0, atol=1e-3): axis.plot( 0, n_plot, @@ -12784,8 +13015,8 @@ def plot_inequality_constraint_equations(axis: plt.Axes, m_file: mf.MFile, scan: fontsize=8, color=( "orange" - if np.isclose(normalized_value, 1.0, atol=1e-3) - or np.isclose(normalized_value, 0.0, atol=1e-3) + if np.isclose(normalised_value, 1.0, atol=1e-3) + or np.isclose(normalised_value, 0.0, atol=1e-3) else "green" ), bbox={ @@ -12800,7 +13031,7 @@ def plot_inequality_constraint_equations(axis: plt.Axes, m_file: mf.MFile, scan: if con_symbol == "'<='": # Add the constraint symbol and bound as text axis.text( - 1.02, # Position text slightly to the right of the normalized bound + 1.02, # Position text slightly to the right of the normalised bound n_plot, f"$\\leq$ {con_bound:,.8g} {con_units}", va="center", @@ -12810,7 +13041,7 @@ def plot_inequality_constraint_equations(axis: plt.Axes, m_file: mf.MFile, scan: ) else: # con_symbol == ">=" axis.text( - -0.025, # Position text slightly to the left of the normalized bound + -0.025, # Position text slightly to the left of the normalised bound n_plot, f"$\\geq$ {con_bound:,.8g} {con_units}", va="center", @@ -12843,12 +13074,20 @@ def main_plot( ): """Function to create radial and vertical build plot on given figure. - Arguments: - fig1 --> figure object to add plot to. - fig2 --> figure object to add plot to. - m_file --> MFILE.DAT data to read - scan --> scan to read from MFILE.DAT - imp --> path to impurity data + Parameters + ---------- + figs : + figure object to add plot to + m_file : + MFILE + scan : + scan to read from MFILE + imp : + path to impurity data + demo_ranges: bool : + (Default value = False) + colour_scheme: + """ # Checking the impurity data folder diff --git a/process/io/plot_sankey.py b/process/io/plot_sankey.py index 0520c8da48..c819a55bee 100644 --- a/process/io/plot_sankey.py +++ b/process/io/plot_sankey.py @@ -1,12 +1,8 @@ """ Code to display the power flow of a PROCESS run in a Sankey diagram -Author: H. Lux (Hanni.Lux@ukaea.uk) -Updated 20/08/219: A. Brown (adam.brown@ukaea.uk) - Input file: MFILE.DAT - """ import argparse @@ -18,12 +14,8 @@ def main(args=None): - ########################################################### - # Usage - parser = argparse.ArgumentParser( - description="Program to plot\ - the power flow in PROCESS using a Sankey diagram." + description="Program to plot the power flow in PROCESS using a Sankey diagram." ) parser.add_argument("-e", "--end", default="pdf", help="file format, default = pdf") @@ -34,9 +26,6 @@ def main(args=None): args = parser.parse_args(args) - ######################################################### - # main program - plot_sankey(args.mfile) # Get directory of mfile diff --git a/process/io/plot_scans.py b/process/io/plot_scans.py index 931a80f19b..2eb1362ea5 100644 --- a/process/io/plot_scans.py +++ b/process/io/plot_scans.py @@ -40,10 +40,15 @@ def parse_args(args): """Parse supplied arguments. - :param args: arguments to parse - :type args: list, None - :return: parsed arguments - :rtype: Namespace + Parameters + ---------- + args : list, None + arguments to parse + + Returns + ------- + Namespace + parsed arguments """ parser = argparse.ArgumentParser( description="Plot optimization information", @@ -240,8 +245,10 @@ def parse_args(args): def main(args=None): """Main plot scans script. - :param args: optional command-line args from test function, defaults to None - :type args: list, optional + Parameters + ---------- + args : list, optional + optional command-line args from test function, defaults to None """ args = parse_args(args) diff --git a/process/io/plot_solutions.py b/process/io/plot_solutions.py index 3b9c1f7bca..5492209b83 100644 --- a/process/io/plot_solutions.py +++ b/process/io/plot_solutions.py @@ -93,19 +93,24 @@ def plot_mfile_solutions( ) -> tuple[mpl.figure.Figure, pd.DataFrame]: """Plot multiple solutions, optionally normalised by a given solution. - :param runs_metadata: list of RunMetadata objects - :type runs_metadata: Sequence[RunMetadata] - :param plot_title: title of plot - :type plot_title: str - :param normalising_tag: tag for solution to normalise with. If provided, - normalise, otherwise don't, defaults to None - :type normalising_tag: str, optional - :param rmse: plot RMS errors relative to reference solution, defaults to False - :type rmse: bool, optional - :param normalisation_type: opt param normalisation to use: one of ["init", "range", None], defaults to "init" - :type normalisation_type: str, optional - :return: figure and dataframe of solutions - :rtype: Tuple[mpl.figure.Figure, pd.DataFrame] + Parameters + ---------- + runs_metadata : Sequence[RunMetadata] + list of RunMetadata objects + plot_title : str + title of plot + normalising_tag : str, optional + tag for solution to normalise with. If provided, + normalise, otherwise don't, defaults to None + rmse : bool, optional + plot RMS errors relative to reference solution, defaults to False + normalisation_type : str, optional + opt param normalisation to use: one of ["init", "range", None], defaults to "init" + + Returns + ------- + Tuple[mpl.figure.Figure, pd.DataFrame] + figure and dataframe of solutions """ if normalisation_type is not None and normalising_tag is not None: warn( @@ -182,10 +187,15 @@ def _extract_mfile_data(mfile_path: Path) -> dict: Also include the names of the optimisation parameters. - :param mfile_path: mfile to extract data from - :type mfile_path: pathlib.Path - :return: dict of all data in mfile - :rtype: dict + Parameters + ---------- + mfile_path: + mfile to extract data from + + Returns + ------- + dict + dict of all data in mfile """ mfile = MFile(str(mfile_path)) mfile_data = {} @@ -205,10 +215,16 @@ def _create_df_from_run_metadata(runs_metadata: Sequence[RunMetadata]) -> pd.Dat """Create a dataframe from multiple mfiles. Uses RunMetadata objects. - :param runs_metadata: scenarios and solvers that have been run - :type runs_metadata: Sequence[RunMetadata] - :return: dataframe of all results - :rtype: pandas.DataFrame + + Parameters + ---------- + runs_metadata + scenarios and solvers that have been run + + Returns + ------- + pandas.DataFrame + dataframe of all results """ results = [] for run_metadata in runs_metadata: @@ -227,12 +243,17 @@ def _separate_norm_solution( ) -> tuple[pd.DataFrame]: """Separate solutions df into normalising row and rows to be normalised. - :param results_df: multiple solutions dataframe - :type results_df: pd.DataFrame - :param normalising_tag: tag to identify row to normalise with - :type normalising_tag: str - :return: normalising row, rows to be normalised - :rtype: Tuple[pd.DataFrame] + Parameters + ---------- + results_df: + multiple solutions dataframe + normalising_tag: + tag to identify row to normalise with + + Returns + ------- + Tuple[pd.DataFrame] + normalising row, rows to be normalised """ # Split results into normalising and non-normalising solutions normalising_soln = results_df[results_df[TAG] == normalising_tag] @@ -248,14 +269,19 @@ def _filter_opt_params( ) -> pd.DataFrame: """Filter optimsation parameters in or out of results. - :param results: multiple solutions - :type results: pd.DataFrame - :param opt_param_value_pattern: normalisation type for opt params in mfile - :type opt_param_value_pattern: str - :param filter_in: include opt params, defaults to True - :type filter_in: bool, optional - :return: multiple solutions with opt params filtered in or out - :rtype: pd.DataFrame + Parameters + ---------- + results: + multiple solutions + opt_param_value_pattern: + normalisation type for opt params in mfile + filter_in: + include opt params, defaults to True + + Returns + ------- + pd.DataFrame + multiple solutions with opt params filtered in or out """ is_opt_param = results.columns.str.contains(opt_param_value_pattern) if filter_in: @@ -273,14 +299,19 @@ def _normalise_diffs( ) -> pd.DataFrame: """Normalise differences of multiple solutions with a normalising solution. - :param results_df: dataframe of two solutions (same scenario, different solvers) - :type results_df: pandas.DataFrame - :param opt_param_value_pattern: normalisation type for opt params in mfile - :type opt_param_value_pattern: str - :param normalising_tag: tag to normalise other solutions with - :type normalising_tag: str - :return: normalised differences - :rtype: pandas.DataFrame + Parameters + ---------- + results_df: + dataframe of two solutions (same scenario, different solvers) + opt_param_value_pattern: + normalisation type for opt params in mfile + normalising_tag: + tag to normalise other solutions with + + Returns + ------- + pandas.DataFrame + normalised differences """ normalising_soln, non_normalising_solns = _separate_norm_solution( results_df, normalising_tag @@ -327,17 +358,22 @@ def _filter_vars_of_interest( ) -> pd.DataFrame: """Filter variables of interest from full results for all solutions. - :param results_df: full results for all solutions - :type results_df: pandas.DataFrame - :param opt_param_value_pattern: normalisation type for opt params in mfile, - set if plotting opt params, defaults to None - :type opt_param_value_pattern: str | None, optional - :param constraints: filter in constraint values, defaults to False - :type constraints: bool, optional - :param extra_var_names: other variables of interest to filter, defaults to None - :type extra_var_names: List[str], optional - :return: variables of interest - :rtype: pandas.DataFrame + Parameters + ---------- + results_df + full results for all solutions + opt_param_value_pattern + normalisation type for opt params in mfile, + set if plotting opt params, defaults to None + constraints + filter in constraint values, defaults to False + extra_var_names + other variables of interest to filter, defaults to None + + Returns + ------- + pandas.DataFrame + variables of interest """ if extra_var_names is None: extra_var_names = [] @@ -367,20 +403,26 @@ def _plot_solutions( ) -> mpl.figure.Figure: """Plot multiple solutions, optionally normalised by a given solution. - :param diffs_df: normalised diffs for optimisation parameters and objective function - :type diffs_df: pandas.DataFrame - :param normalisation_type: opt param normalisation to use: ["init", "range", None] - :type normalisation_type: str | None - :param opt_param_value_pattern: normalisation type for opt params in mfile - :type opt_param_value_pattern: str - :param plot_title: title of plot - :type plot_title: str - :param normalising_tag: tag for normalising solution, if any - :type normalising_tag: Union[str, None] - :param rmse_df: RMS errors relative to reference solution - :type rmse_df: pd.DataFrame - :return: figure containing varying numbers of axes - :rtype: mpl.figure.Figure + Parameters + ---------- + diffs_df: + normalised diffs for optimisation parameters and objective function + normalisation_type: + opt param normalisation to use: ["init", "range", None] + opt_param_value_pattern: + normalisation type for opt params in mfile + plot_title: + title of plot + normalising_tag: + tag for normalising solution, if any + rmse_df: + RMS errors relative to reference solution + + + Returns + ------- + mpl.figure.Figure + figure containing varying numbers of axes """ # Separate optimisation parameters and objective dfs opt_params_df = diffs_df.filter( @@ -606,14 +648,20 @@ def _rms_errors( """Calculate RMS errors between different solutions. Summarise solution differences in single number. - :param results_df: df containing multiple solutions - :type results_df: pandas.DataFrame - :param opt_param_value_pattern: normalisation type for opt params in mfile - :type opt_param_value_pattern: str - :param normalising_tag: tag to calculate RMSEs against - :type normalising_tag: str - :return: RMS errors for each solution - :rtype: pandas.DataFrame + + Parameters + ---------- + results_df: + df containing multiple solutions + opt_param_value_pattern: + normalisation type for opt params in mfile + normalising_tag: + tag to calculate RMSEs against + + Returns + ------- + : + RMS errors for each solution """ normalising_soln, _ = _separate_norm_solution(results_df, normalising_tag) # Reference solution to calculate RMS errors against @@ -644,12 +692,17 @@ def _rms_errors( def _plot_solutions_constraints(df: pd.DataFrame, title: str) -> mpl.figure.Figure: """Create plot from constraint values df. - :param df: constraint values for each mfile - :type df: pd.DataFrame - :param title: plot title - :type title: str - :return: created figure - :rtype: mpl.figure.Figure + Parameters + ---------- + df: + constraint values for each mfile + title: + plot title + + Returns + ------- + mpl.figure.Figure + created figure """ # Replace constraint numbers with descriptions df = df.rename(mapper=CONSTRAINT_NUMS, axis="columns") @@ -677,12 +730,17 @@ def plot_mfile_solutions_constraints( ) -> tuple[mpl.figure.Figure, pd.DataFrame]: """Plot constraint values in mfiles. - :param runs_metadata: list of RunMetadata objects - :type runs_metadata: Sequence[RunMetadata] - :param title: plot title - :type title: str - :return: figure and dataframe of solutions - :rtype: Tuple[mpl.figure.Figure, pd.DataFrame] + Parameters + ---------- + runs_metadata: + list of RunMetadata objects + title: + plot title + + Returns + ------- + : + figure and dataframe of solutions """ # Create dataframe from runs metadata: mfile data with a tag for each run results_df = _create_df_from_run_metadata(runs_metadata) diff --git a/process/io/plot_stress_tf.py b/process/io/plot_stress_tf.py index baaa33ccb8..c7466ddbc8 100644 --- a/process/io/plot_stress_tf.py +++ b/process/io/plot_stress_tf.py @@ -2,8 +2,6 @@ Code generating the TF coil inboard mid-plane stress/strain summary plots The whole radial distribution is displayed -Author: S. Kahn (sebastien.kahn@ukaea.uk) - Input file: SIG_TF.json """ diff --git a/process/io/process_config.py b/process/io/process_config.py index daa0b5cfa2..e26f0dd452 100644 --- a/process/io/process_config.py +++ b/process/io/process_config.py @@ -1,15 +1,7 @@ """ -Author: Hanni Lux (Hanni.Lux@ccfe.ac.uk) - Interfaces for Configuration values for programs - run_process.py - test_process.py - -Compatible with PROCESS version 382 - -24/11/2021: Global dictionary variables moved within the functions - to avoid cyclic dependencies. This is because the dicts - generation script imports, and inspects, process. """ import logging @@ -34,37 +26,24 @@ class ProcessConfig: - """ - Configuration parameters for PROCESS runs - - filename - Configuration file name - - wdir - Working directory - - or_in_dat - Original IN.DAT file - - process - PROCESS binary - - niter - (Maximum) number of iterations - - u_seed - User specified seed value for the random number generator - - factor - Multiplication factor adjusting the range in which the original - iteration variables should get varied - - comment - additional comment to be written into README.txt - - """ + """Configuration parameters for PROCESS runs""" filename = None + """Configuration file name""" configfileexists = True wdir = "." + """Working directory""" or_in_dat = "IN.DAT" - process = "process.exe" + """Original IN.DAT file""" niter = 10 + """(Maximum) number of iterations""" u_seed = None + """User specified seed value for the random number generator""" factor = 1.5 + """Multiplication factor adjusting the range in which the original +iteration variables should get varied""" comment = " " + """additional comment to be written into README.txt""" def echo(self): """echos the attributes of the class""" @@ -72,7 +51,6 @@ def echo(self): if self.wdir != ".": print(f"Working directory: {self.wdir}") print(f"Original IN.DAT: {self.or_in_dat}") - print(f"PROCESS binary: {self.process}") print(f"Number of iterations {self.niter}") if self.u_seed is not None: @@ -101,8 +79,7 @@ def prepare_wdir(self): os.chdir(self.wdir) subprocess.call( [ - "rm -f OUT.DAT MFILE.DAT README.txt\ - SolverTest.out process.log *.pdf uncertainties.nc time.info" + "rm -f OUT.DAT MFILE.DAT README.txt SolverTest.out process.log *.pdf uncertainties.nc time.info" ], shell=True, ) @@ -240,10 +217,6 @@ def set_attributes(self): ) raise - buf = self.get_attribute("process") - if buf is not None: - self.process = buf - buf = self.get_attribute("niter") if buf is not None: self.niter = int(buf) @@ -262,14 +235,15 @@ def set_attributes(self): if not self.get_comment(): print(f"No comment in config file {self.filename}") - def run_process(self, input_path, solver="vmcon"): + def run_process(self, input_path: Path, solver: str = "vmcon"): """Perform a single run of PROCESS, catching any errors. - :param input_path: the input file to run on - :type input_path: pathlib.Path - :param solver: which solver to use, as specified in solver.py, defaults - to "vmcon" - :type solver: str, optional + Parameters + ---------- + input_path : + the input file to run on + solver : + which solver to use, as specified in solver.py, defaults to "vmcon" """ with open("process.log", "w") as logfile: print("PROCESS run started ...", end="") @@ -295,43 +269,25 @@ def run_process(self, input_path, solver="vmcon"): print("finished.") -################################################################################ -# class RunProcessConfig(ProcessConfig) -################################################################################ - - class RunProcessConfig(ProcessConfig): - """ - Configuration parameters of the run_process.py program - - no_allowed_unfeasible - the number of allowed unfeasible points in a sweep - - create_itervar_diff - boolean to indicate the creation of a summary file - of the iteration variable values at each stage - - add_ixc - List of iteration variables to be added to IN.DAT - - del_ixc - List of iteration variables to be deleted from IN.DAT - - add_icc - List of constrained equations to be added to IN.DAT - - del_icc - List of constrained equations to be deleted from IN.DAT - - dictvar - Dictionary mapping variable name to new value (replaces old - or gets appended) - - del_var - List of variables to be deleted from IN.DAT - - """ + """Configuration parameters of the run_process.py program""" no_allowed_unfeasible = 0 + """the number of allowed unfeasible points in a sweep""" create_itervar_diff = False + """boolean to indicate the creation of a summary file of the iteration variable values at each stage""" add_ixc: ClassVar = [] + """ List of iteration variables to be added to IN.DAT""" del_ixc: ClassVar = [] + """List of iteration variables to be deleted from IN.DAT""" add_icc: ClassVar = [] + """List of constrained equations to be added to IN.DAT""" del_icc: ClassVar = [] + """List of constrained equations to be deleted from IN.DAT""" dictvar: ClassVar = {} + """Dictionary mapping variable name to new value (replaces old or gets appended)""" del_var: ClassVar = [] + """List of variables to be deleted from IN.DAT""" def __init__(self, filename="run_process.conf"): """ @@ -356,8 +312,7 @@ def __init__(self, filename="run_process.conf"): self.create_itervar_diff = False else: print( - "WARNING: Value for create_itervar_diff\ - is not defined!", + "WARNING: Value for create_itervar_diff is not defined!", file=stderr, ) @@ -374,8 +329,7 @@ def __init__(self, filename="run_process.conf"): self.set_dictvar() def get_attribute_csv_list(self, attributename): - """ - get class attribute list from configuration file + """get class attribute list from configuration file expects comma separated values """ @@ -459,10 +413,7 @@ def echo(self): print(f"no. allowed UNFEASIBLE points {self.no_allowed_unfeasible:d}") if self.create_itervar_diff: - print( - "Set to create a summary file of the iteration variable\ - values!" - ) + print("Set to create a summary file of the iteration variable values!") if self.add_ixc != []: print("add_ixc", self.add_ixc) @@ -520,8 +471,7 @@ def modify_ixc(self): # check that there is no variable in both lists if set(self.add_ixc).intersection(self.del_ixc) != set(): print( - "Error: You are trying to add and delete \ - the same variable from ixc!", + "Error: You are trying to add and delete the same variable from ixc!", file=stderr, ) exit() @@ -542,8 +492,7 @@ def modify_icc(self): # check that there is no variable in both lists if set(self.add_icc).intersection(self.del_icc) != set(): print( - "Error: You are trying to add and delete the same \ - variable from icc!", + "Error: You are trying to add and delete the same variable from icc!", file=stderr, ) exit() diff --git a/process/io/process_funcs.py b/process/io/process_funcs.py index 8a0c8f312a..bc4a2cff26 100644 --- a/process/io/process_funcs.py +++ b/process/io/process_funcs.py @@ -1,13 +1,5 @@ """ A selection of functions for using the PROCESS code - -Author: Hanni Lux (Hanni.Lux@ccfe.ac.uk) - -Compatible with PROCESS version 368 - -24/11/2021: Global dictionary variables moved within the functions - to avoid cyclic dependencies. This is because the dicts - generation script imports, and inspects, process. """ import logging @@ -25,8 +17,7 @@ def get_neqns_itervars(wdir="."): - """ - returns the number of equations and a list of variable + """Returns the number of equations and a list of variable names of all iteration variables """ # Load dicts from dicts JSON file @@ -45,12 +36,8 @@ def get_neqns_itervars(wdir="."): return in_dat.number_of_constraints, itervars -############################### - - def update_ixc_bounds(wdir="."): - """ - updates the lower and upper bounds in DICT_IXC_BOUNDS + """updates the lower and upper bounds in DICT_IXC_BOUNDS from IN.DAT """ # Load dicts from dicts JSON file @@ -68,22 +55,23 @@ def update_ixc_bounds(wdir="."): dicts["DICT_IXC_BOUNDS"][name]["ub"] = float(value["u"]) -############################### - - def get_variable_range(itervars, factor, wdir="."): - """ - Returns the lower and upper bounds of the variable range + """Returns the lower and upper bounds of the variable range for each iteration variable. - itervars - string list of all iteration variable names - factor - defines the variation range for non-f-values by - setting them to value * factor and value / factor - respectively while taking their process bounds - into account. - For f-values the allowed range is equal to their process bounds. + Parameters + ---------- + itervars : + string list of all iteration variable names + factor : + defines the variation range for non-f-values by + setting them to value * factor and value / factor + respectively while taking their process bounds + into account. + wdir : + (Default value = ".") """ # Load dicts from dicts JSON file dicts = get_dicts() @@ -141,12 +129,10 @@ def get_variable_range(itervars, factor, wdir="."): return lbs, ubs -############################### - - def check_in_dat(): """Tests IN.DAT during setup: - 1)Are ixc bounds outside of allowed input ranges?""" + 1)Are ixc bounds outside of allowed input ranges? + """ # Load dicts from dicts JSON file dicts = get_dicts() @@ -211,15 +197,16 @@ def check_in_dat(): in_dat.write_in_dat(output_filename="IN.DAT") -############################### - - def check_logfile(logfile="process.log"): - """ - Checks the log file of the PROCESS output. + """Checks the log file of the PROCESS output. Stops, if an error occured that needs to be fixed before rerunning. XXX should be deprecated!! and replaced by check_input_error! + + Parameters + ---------- + logfile : + (Default value = "process.log") """ with open(logfile) as outlogfile: @@ -234,8 +221,7 @@ def check_logfile(logfile="process.log"): def check_input_error(wdir="."): - """ - Checks, if an input error has occurred. + """Checks, if an input error has occurred. Stops as a consequence. Will also fail if the MFILE.DAT isn't found. """ @@ -261,12 +247,8 @@ def check_input_error(wdir="."): raise -######################################## - - def process_stopped(wdir="."): - """ - Checks the process Mfile whether it has + """Checks the process Mfile whether it has prematurely stopped. """ # Check for MFILE @@ -288,12 +270,8 @@ def process_stopped(wdir="."): return error_status >= 3 -######################################## - - def process_warnings(wdir="."): - """ - Checks the process Mfile whether any + """Checks the process Mfile whether any warnings have occurred. """ @@ -303,9 +281,6 @@ def process_warnings(wdir="."): return error_status >= 2 -############################################ - - def mfile_exists(): """checks whether MFILE.DAT exists""" @@ -318,12 +293,8 @@ def mfile_exists(): return False -############################################ - - def no_unfeasible_mfile(wdir="."): - """ - returns the number of unfeasible points + """returns the number of unfeasible points in a scan in MFILE.DAT """ @@ -345,17 +316,20 @@ def no_unfeasible_mfile(wdir="."): return 100000 -################################ - - def vary_iteration_variables(itervars, lbs, ubs, generator): - """ - Routine to change the iteration variables in IN.DAT + """Routine to change the iteration variables in IN.DAT within given bounds. - itervars - string list of all iteration variable names - lbs - float list of lower bounds for variables - ubs - float list of upper bounds for variables - generator - Generator numpy generator to create random numbers + + Parameters + ---------- + itervars : + string list of all iteration variable names + lbs : + float list of lower bounds for variables + ubs : + float list of upper bounds for variables + generator : + Generator numpy generator to create random numbers """ in_dat = InDat() @@ -372,12 +346,8 @@ def vary_iteration_variables(itervars, lbs, ubs, generator): return new_values -################################### - - def get_solution_from_mfile(neqns, nvars, wdir="."): - """ - returns + """returns ifail - error_value of VMCON/PROCESS the objective functions the square root of the sum of the squares of the constraints @@ -410,9 +380,6 @@ def get_solution_from_mfile(neqns, nvars, wdir="."): return ifail, objective_function, constraints, table_sol, table_res -############################################ - - def get_from_indat_or_default(in_dat, varname): """quick function to get variable value from IN.DAT or PROCESS default value""" diff --git a/process/io/sankey_funcs.py b/process/io/sankey_funcs.py index db8d16505c..54094b2f5f 100644 --- a/process/io/sankey_funcs.py +++ b/process/io/sankey_funcs.py @@ -1,10 +1,5 @@ """ Library of Sankey plotting routine - -Author: Hanni Lux (Hanni.Lux@ukaea.uk) - Matti Coleman (Matti.Coleman@ukaea.uk) - -Updated 13/09/2019: Adam Brown (adam.brown@ukaea.uk) """ import matplotlib.pyplot as plt @@ -343,7 +338,6 @@ def plot_full_sankey( if _ == 0 and sqrt(sum(first_wall) ** 2) > 0.1: print("FIRST_WALL power balance =", sum(first_wall)) exit() - """# -------------------------------------- BLANKET - 6 -------------------------------------- # Blanket - Energy mult., Energy Mult., pumping power, Blanket @@ -370,7 +364,6 @@ def plot_full_sankey( if diff > 0.1: print("The difference between [1][1] and [3][0] =", diff) exit()""" - """# --------------------------------------- SHIELD - 7 -------------------------------------- # Neutrons, Coolant pumping, Total power @@ -387,7 +380,6 @@ def plot_full_sankey( if sqrt(sum(SHIELD)**2) > 0.1: print("SHIELD power balance =", sum(SHIELD)) exit()""" - """# ------------------------------------ PRIMARY HEAT - 7 ----------------------------------- # 1st wall, Blanket, Shield, Divertor, Total thermal power @@ -404,7 +396,6 @@ def plot_full_sankey( if sqrt(sum(HEAT)**2) > 0.1: print("PRIMARY power balance =", sum(HEAT)) exit()""" - """# ------------------------------- ELECTRICITY CONVERSION - 8 ------------------------------ # Total thermal, Elctricty conversion loss, Gross Electricity @@ -423,7 +414,6 @@ def plot_full_sankey( exit()""" # ------------------------------ RECIRCULATED ELECTRICITY - 9 ----------------------------- - """# ---------------------------------------- HCD - 11 ---------------------------------------- # HCD loss + injected, -injected, -HCD loss @@ -454,7 +444,6 @@ def plot_full_sankey( # Munipulating the positioning of the branch labels # -ve to left and down; +ve to right and up # pos[0] = x-axis; pos[1] = y-axis - """for d in diagrams: y = 0 for t in d.texts: @@ -505,9 +494,6 @@ def plot_full_sankey( y += 1""" -#################################################################################################### - - def plot_sankey(mfilename="MFILE.DAT"): # Plot simplified power flow Sankey Diagram # ------------------------------- Pulling values from the MFILE ------------------------------- diff --git a/process/io/write_new_in_dat.py b/process/io/write_new_in_dat.py index abf1cd0a54..80fefedb2d 100644 --- a/process/io/write_new_in_dat.py +++ b/process/io/write_new_in_dat.py @@ -3,8 +3,6 @@ Modifies the PROCESS input file IN.DAT so all the iteration variables are given their values from the output file MFILE.DAT. -James Morris 30/04/2014 based on code by Michael Kovari 9/8/13 and -J C Rivas, 16/7/2013 """ import argparse @@ -17,13 +15,17 @@ def feasible_point(filename, position): """Function to check for feasible solution before creating new IN.DAT, or to determine the first or last feasible point in a scan - Args: - filename --> name of MFILE.DAT to read - position --> e.g first or last - - Returns: - scanPoint --> scan number to use when writing new file - + Parameters + ---------- + filename : + name of MFILE.DAT to read + position : + e.g first or last + + Returns + ------- + scanPoint: + scan number to use when writing new file """ mfile_data = mf.MFile(filename) finished = False @@ -63,14 +65,18 @@ def get_iteration_variables(filename, scan): """Function to get a list of the iteration variables and their values from MFILE.DAT - Args: - filename --> name of MFILE.DAT to read - scan --> scan number to use - - Returns: - iteration_vars --> dictionary of iteration variables in MFILE and their - values. - + Parameters + ---------- + filename: + name of MFILE.DAT to read + scan: + scan number to use + + Returns + ------- + iteration_vars: + dictionary of iteration variables in MFILE and their + values. """ mfile_data = mf.MFile(filename) iteration_vars = {} @@ -88,11 +94,13 @@ def replace_iteration_variables(iteration_vars, in_data): """Function to replace the iteration variables in IN.DAT if the variable is not defined in IN.DAT it will add the variable to the end of the file. - Args: - iteration_vars --> dictionary of iteration variables from MFILE.DAT and - their values - in_data --> IN.DAT data object. - + Parameters + ---------- + iteration_vars: + dictionary of iteration variables from MFILE.DAT and + their values + in_data: + IN.DAT data object. """ for variable_name, variable_value in iteration_vars.items(): diff --git a/process/iteration_variables.py b/process/iteration_variables.py index edafcdbbd6..6c00fc45cb 100644 --- a/process/iteration_variables.py +++ b/process/iteration_variables.py @@ -298,6 +298,13 @@ def check_iteration_variable(iteration_variable_value, name: str = ""): """Check that the iteration variable value is valid (not a weird number or too small). Raises an error upon encountering an invalid value, otherwise does nothing. + + Parameters + ---------- + iteration_variable_value : + + name: str : + (Default value = "") """ if abs(iteration_variable_value) <= 1e-12: error_msg = f"Iteration variable {name} is 0 (or very close)" @@ -379,8 +386,13 @@ def load_iteration_variables(): def set_scaled_iteration_variable(xc, nn: int): """Converts scaled iteration variables back to their real values and sets them in the code. - :param xc: scaled iteration variable values - :param nn: number of iteration variables + Parameters + ---------- + xc : + scaled iteration variable values + nn : + number of iteration variables + """ for i in range(nn): diff --git a/process/l_h_transition.py b/process/l_h_transition.py index 865d98819b..713f9686a0 100644 --- a/process/l_h_transition.py +++ b/process/l_h_transition.py @@ -1,21 +1,24 @@ def calculate_iter1996_nominal( dnla20: float, b_plasma_toroidal_on_axis: float, rmajor: float ) -> float: - """ - Calculate the nominal ITER-1996 L-H transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :return: The ITER-1996 L-H transition power threshold [MW] - :rtype: float - - :notes: - - :references: + """Calculate the nominal ITER-1996 L-H transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + + Returns + ------- + float + The ITER-1996 L-H transition power threshold [MW] + + References + ---------- - T. Takizuka and International Atomic Energy Agency, Vienna (Austria), "Threshold power and energy confinement for ITER". 1996. @@ -29,21 +32,24 @@ def calculate_iter1996_nominal( def calculate_iter1996_upper( dnla20: float, b_plasma_toroidal_on_axis: float, rmajor: float ) -> float: - """ - Calculate the upper variant ITER-1996 L-H transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :return: The ITER-1996 L-H transition power threshold [MW] - :rtype: float - - :notes: - - :references: + """Calculate the upper variant ITER-1996 L-H transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + + Returns + ------- + float + The ITER-1996 L-H transition power threshold [MW] + + References + ---------- - T. Takizuka and International Atomic Energy Agency, Vienna (Austria), "Threshold power and energy confinement for ITER". 1996. @@ -57,21 +63,24 @@ def calculate_iter1996_upper( def calculate_iter1996_lower( dnla20: float, b_plasma_toroidal_on_axis: float, rmajor: float ) -> float: - """ - Calculate the lower variant ITER-1996 L-H transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :return: The ITER-1996 L-H transition power threshold [MW] - :rtype: float - - :notes: - - :references: + """Calculate the lower variant ITER-1996 L-H transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + + Returns + ------- + float + The ITER-1996 L-H transition power threshold [MW] + + References + ---------- - T. Takizuka and International Atomic Energy Agency, Vienna (Austria), "Threshold power and energy confinement for ITER". 1996. @@ -85,21 +94,24 @@ def calculate_iter1996_lower( def calculate_snipes1997_iter( dnla20: float, b_plasma_toroidal_on_axis: float, rmajor: float ) -> float: - """ - Calculate the Snipes 1997 ITER L-H transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :return: The Snipes 1997 L-H transition power threshold [MW] - :rtype: float - - :notes: - - :references: + """Calculate the Snipes 1997 ITER L-H transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + + Returns + ------- + float + The Snipes 1997 L-H transition power threshold [MW] + + References + ---------- - J. A. Snipes and the ITER H-mode Threshold Database Working Group, "An Analysis of the H-mode Threshold in ITER," Controlled Fusion and Plasma Physics, 24th EPS Conference, Berchtesgaden, June 9th-13th 1997, vol.21A, part III, p.961. @@ -112,23 +124,26 @@ def calculate_snipes1997_iter( def calculate_snipes1997_kappa( dnla20: float, b_plasma_toroidal_on_axis: float, rmajor: float, kappa: float ) -> float: - """ - Calculate the Snipes 1997 ITER L-H transition power threshold with kappa factor. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :param kappa: Plasma elongation - :type kappa: float - :return: The Snipes 1997 L-H transition power threshold with kappa factor [MW] - :rtype: float - - :notes: - - :references: + """Calculate the Snipes 1997 ITER L-H transition power threshold with kappa factor. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + kappa : float + Plasma elongation + + Returns + ------- + float + The Snipes 1997 L-H transition power threshold with kappa factor [MW] + + References + ---------- - J. A. Snipes and the ITER H-mode Threshold Database Working Group, "An Analysis of the H-mode Threshold in ITER," Controlled Fusion and Plasma Physics, 24th EPS Conference, Berchtesgaden, June 9th-13th 1997, vol.21A, part III, p.961. @@ -150,31 +165,36 @@ def calculate_martin08_nominal( a_plasma_surface: float, m_ions_total_amu: float, ) -> float: - """ - Calculate the nominal Martin L-H transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param a_plasma_surface: Plasma surface area [m^2] - :type a_plasma_surface: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :return: The Martin L-H transition power threshold [MW] - :rtype: float - - :notes: - - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; - "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be - reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - - :references: - - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” - Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, - doi: https://doi.org/10.1088/1742-6596/123/1/012033. - ‌ + """Calculate the nominal Martin L-H transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + a_plasma_surface : float + Plasma surface area [m^2] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + + Returns + ------- + float + The Martin L-H transition power threshold [MW] + + Notes + ----- + - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; + "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be + reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + + References + ---------- + - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” + Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, + doi: https://doi.org/10.1088/1742-6596/123/1/012033. """ return ( 0.0488 @@ -191,29 +211,34 @@ def calculate_martin08_upper( a_plasma_surface: float, m_ions_total_amu: float, ) -> float: - """ - Calculate the upper Martin L-H transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param a_plasma_surface: Plasma surface area [m^2] - :type a_plasma_surface: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :return: The Martin L-H transition power threshold [MW] - :rtype: float - - :notes: - - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; - "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be - reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - :references: - - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” - Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, - doi: https://doi.org/10.1088/1742-6596/123/1/012033. - ‌ + """Calculate the upper Martin L-H transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + a_plasma_surface : float + Plasma surface area [m^2] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + + Returns + ------- + float + The Martin L-H transition power threshold [MW] + + Notes + ----- + - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; + "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be + reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + References + ---------- + - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” + Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, + doi: https://doi.org/10.1088/1742-6596/123/1/012033. """ return ( 0.05166240355 @@ -230,30 +255,35 @@ def calculate_martin08_lower( a_plasma_surface: float, m_ions_total_amu: float, ) -> float: - """ - Calculate the lower Martin L-H transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param a_plasma_surface: Plasma surface area [m^2] - :type a_plasma_surface: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :return: The Martin L-H transition power threshold [MW] - :rtype: float - - :notes: - - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; - "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be - reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - :references: - - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” - Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, - doi: https://doi.org/10.1088/1742-6596/123/1/012033. - ‌ + """Calculate the lower Martin L-H transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + a_plasma_surface : float + Plasma surface area [m^2] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + + Returns + ------- + float + The Martin L-H transition power threshold [MW] + + Notes + ----- + - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; + "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be + reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + References + ---------- + - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” + Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, + doi: https://doi.org/10.1088/1742-6596/123/1/012033. """ return ( 0.04609619059 @@ -271,32 +301,37 @@ def calculate_snipes2000_nominal( rminor: float, m_ions_total_amu: float, ) -> float: - """ - Calculate the nominal Snipes 2000 L-H transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :param rminor: Plasma minor radius [m] - :type rminor: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :return: The Snipes 2000 L-H transition power threshold [MW] - :rtype: float - - :notes: - - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; - "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium - results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - :references: - - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” - Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, - doi: https://doi.org/10.1088/0741-3335/42/5a/336. - ‌ + """Calculate the nominal Snipes 2000 L-H transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + rminor : float + Plasma minor radius [m] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + + Returns + ------- + float + The Snipes 2000 L-H transition power threshold [MW] + + Notes + ----- + - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; + "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium + results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + References + ---------- + - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” + Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, + doi: https://doi.org/10.1088/0741-3335/42/5a/336. """ return ( 1.42 @@ -315,32 +350,38 @@ def calculate_snipes2000_upper( rminor: float, m_ions_total_amu: float, ) -> float: - """ - Calculate the upper Snipes 2000 L-H transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :param rminor: Plasma minor radius [m] - :type rminor: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :return: The Snipes 2000 L-H transition power threshold [MW] - :rtype: float - - :notes: - - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; - "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium - results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - :references: - - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” - Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, - doi: https://doi.org/10.1088/0741-3335/42/5a/336. - ‌ + """Calculate the upper Snipes 2000 L-H transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + rminor : float + Plasma minor radius [m] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + + Returns + ------- + float + The Snipes 2000 L-H transition power threshold [MW] + + Notes + ----- + - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; + "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium + results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + References + ---------- + - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” + Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, + doi: https://doi.org/10.1088/0741-3335/42/5a/336. + """ return ( 1.547 @@ -359,32 +400,38 @@ def calculate_snipes2000_lower( rminor: float, m_ions_total_amu: float, ) -> float: - """ - Calculate the lower Snipes 2000 L-H transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :param rminor: Plasma minor radius [m] - :type rminor: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :return: The Snipes 2000 L-H transition power threshold [MW] - :rtype: float - - :notes: - - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; - "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium - results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - :references: - - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” - Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, - doi: https://doi.org/10.1088/0741-3335/42/5a/336. - ‌ + """Calculate the lower Snipes 2000 L-H transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + rminor : float + Plasma minor radius [m] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + + Returns + ------- + float + The Snipes 2000 L-H transition power threshold [MW] + + Notes + ----- + - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; + "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium + results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + References + ---------- + - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” + Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, + doi: https://doi.org/10.1088/0741-3335/42/5a/336. + """ return ( 1.293 @@ -402,30 +449,36 @@ def calculate_snipes2000_closed_divertor_nominal( rmajor: float, m_ions_total_amu: float, ) -> float: - """ - Calculate the nominal Snipes 2000 Closed Divertor L-H transition power threshold with CD factor. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :return: The Snipes 2000 L-H transition power threshold with CD factor [MW] - :rtype: float - - :notes: - - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; - "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium - results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - :references: - - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” - Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, - doi: https://doi.org/10.1088/0741-3335/42/5a/336. - ‌ + """Calculate the nominal Snipes 2000 Closed Divertor L-H transition power threshold with CD factor. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + + Returns + ------- + float + The Snipes 2000 L-H transition power threshold with CD factor [MW] + + Notes + ----- + - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; + "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium + results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + References + ---------- + - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” + Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, + doi: https://doi.org/10.1088/0741-3335/42/5a/336. + """ return ( 0.8 @@ -442,30 +495,36 @@ def calculate_snipes2000_closed_divertor_upper( rmajor: float, m_ions_total_amu: float, ) -> float: - """ - Calculate the upper Snipes 2000 Closed Divertor L-H transition power threshold with CD factor. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :return: The Snipes 2000 L-H transition power threshold with CD factor [MW] - :rtype: float - - :notes: - - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; - "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium - results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - :references: - - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” - Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, - doi: https://doi.org/10.1088/0741-3335/42/5a/336. - ‌ + """Calculate the upper Snipes 2000 Closed Divertor L-H transition power threshold with CD factor. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + + Returns + ------- + float + The Snipes 2000 L-H transition power threshold with CD factor [MW] + + Notes + ----- + - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; + "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium + results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + References + ---------- + - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” + Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, + doi: https://doi.org/10.1088/0741-3335/42/5a/336. + """ return ( 0.867 @@ -482,30 +541,36 @@ def calculate_snipes2000_closed_divertor_lower( rmajor: float, m_ions_total_amu: float, ) -> float: - """ - Calculate the lower Snipes 2000 Closed Divertor L-H transition power threshold with CD factor. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius [m] - :type rmajor: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :return: The Snipes 2000 L-H transition power threshold with CD factor [MW] - :rtype: float - - :notes: - - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; - "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium - results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - :references: - - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” - Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, - doi: https://doi.org/10.1088/0741-3335/42/5a/336. - ‌ + """Calculate the lower Snipes 2000 Closed Divertor L-H transition power threshold with CD factor. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + rmajor : float + Plasma major radius [m] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + + Returns + ------- + float + The Snipes 2000 L-H transition power threshold with CD factor [MW] + + Notes + ----- + - A scaling with the total ion mass is used in this model. Snipes cites that P_LH scales with 1/m_i. It is stated; + "This results in a 20% reduction in the threshold power for a 50/50 D-T mixture compared with the pure deuterium + results above". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + References + ---------- + - J. A. Snipes and the I. H-mode. T. Group, “Latest results on the H-mode threshold using the international H-mode threshold database,” + Plasma Physics and Controlled Fusion, vol. 42, no. 5A, pp. A299-A308, May 2000, + doi: https://doi.org/10.1088/0741-3335/42/5a/336. + """ return ( 0.733 @@ -517,67 +582,85 @@ def calculate_snipes2000_closed_divertor_lower( def calculate_hubbard2012_nominal(plasma_current: float, dnla20: float) -> float: - """ - Calculate the nominal Hubbard 2012 L-I transition power threshold. - - :param plasma_current: Plasma current [A] - :type plasma_current: float - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :return: The Hubbard 2012 L-I transition power threshold [MW] - :rtype: float - - :notes: - - :references: - - A. E. Hubbard et al., “Threshold conditions for transitions to I-mode and H-mode with unfavourable ion grad B drift direction,” - Nuclear Fusion, vol. 52, no. 11, pp. 114009-114009, Oct. 2012, - doi: https://doi.org/10.1088/0029-5515/52/11/114009. - ‌ + """Calculate the nominal Hubbard 2012 L-I transition power threshold. + + Parameters + ---------- + plasma_current : float + Plasma current [A] + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + + Returns + ------- + float + The Hubbard 2012 L-I transition power threshold [MW] + + Notes + ----- + + References + ---------- + - A. E. Hubbard et al., “Threshold conditions for transitions to I-mode and H-mode with unfavourable ion grad B drift direction,” + Nuclear Fusion, vol. 52, no. 11, pp. 114009-114009, Oct. 2012, + doi: https://doi.org/10.1088/0029-5515/52/11/114009. + """ return 2.11 * (plasma_current / 1e6) ** 0.94 * dnla20**0.65 def calculate_hubbard2012_upper(plasma_current: float, dnla20: float) -> float: - """ - Calculate the upper Hubbard 2012 L-I transition power threshold. - - :param plasma_current: Plasma current [A] - :type plasma_current: float - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :return: The Hubbard 2012 L-I transition power threshold [MW] - :rtype: float - - :notes: - - :references: - - A. E. Hubbard et al., “Threshold conditions for transitions to I-mode and H-mode with unfavourable ion grad B drift direction,” - Nuclear Fusion, vol. 52, no. 11, pp. 114009-114009, Oct. 2012, - doi: https://doi.org/10.1088/0029-5515/52/11/114009. - ‌ + """Calculate the upper Hubbard 2012 L-I transition power threshold. + + Parameters + ---------- + plasma_current : float + Plasma current [A] + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + + Returns + ------- + float + The Hubbard 2012 L-I transition power threshold [MW] + + Notes + ----- + + References + ---------- + - A. E. Hubbard et al., “Threshold conditions for transitions to I-mode and H-mode with unfavourable ion grad B drift direction,” + Nuclear Fusion, vol. 52, no. 11, pp. 114009-114009, Oct. 2012, + doi: https://doi.org/10.1088/0029-5515/52/11/114009. + """ return 2.11 * (plasma_current / 1e6) ** 1.18 * dnla20**0.83 def calculate_hubbard2012_lower(plasma_current: float, dnla20: float) -> float: - """ - Calculate the lower Hubbard 2012 L-I transition power threshold. - - :param plasma_current: Plasma current [A] - :type plasma_current: float - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :return: The Hubbard 2012 L-I transition power threshold [MW] - :rtype: float - - :notes: - - :references: - - A. E. Hubbard et al., “Threshold conditions for transitions to I-mode and H-mode with unfavourable ion grad B drift direction,” - Nuclear Fusion, vol. 52, no. 11, pp. 114009-114009, Oct. 2012, - doi: https://doi.org/10.1088/0029-5515/52/11/114009. - ‌ + """Calculate the lower Hubbard 2012 L-I transition power threshold. + + Parameters + ---------- + plasma_current : float + Plasma current [A] + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + + Returns + ------- + float + The Hubbard 2012 L-I transition power threshold [MW] + + Notes + ----- + + References + ---------- + - A. E. Hubbard et al., “Threshold conditions for transitions to I-mode and H-mode with unfavourable ion grad B drift direction,” + Nuclear Fusion, vol. 52, no. 11, pp. 114009-114009, Oct. 2012, + doi: https://doi.org/10.1088/0029-5515/52/11/114009. + """ return 2.11 * (plasma_current / 1e6) ** 0.7 * dnla20**0.47 @@ -585,26 +668,32 @@ def calculate_hubbard2012_lower(plasma_current: float, dnla20: float) -> float: def calculate_hubbard2017( dnla20: float, a_plasma_surface: float, b_plasma_toroidal_on_axis: float ) -> float: - """ - Calculate the Hubbard 2017 L-I transition power threshold. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param a_plasma_surface: Plasma surface area [m^2] - :type a_plasma_surface: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :return: The Hubbard 2017 L-I transition power threshold [MW] - :rtype: float - - :notes: - - The scaling is given in the caption of Figure 6 in the reference. - - :references: - - A. E. Hubbard et al., “Physics and performance of the I-mode regime over an expanded operating space on Alcator C-Mod,” - Nuclear Fusion, vol. 57, no. 12, p. 126039, Oct. 2017, - doi: https://doi.org/10.1088/1741-4326/aa8570. - ‌ + """Calculate the Hubbard 2017 L-I transition power threshold. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + a_plasma_surface : float + Plasma surface area [m^2] + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + + Returns + ------- + float + The Hubbard 2017 L-I transition power threshold [MW] + + Notes + ----- + - The scaling is given in the caption of Figure 6 in the reference. + + References + ---------- + - A. E. Hubbard et al., “Physics and performance of the I-mode regime over an expanded operating space on Alcator C-Mod,” + Nuclear Fusion, vol. 57, no. 12, p. 126039, Oct. 2017, + doi: https://doi.org/10.1088/1741-4326/aa8570. + """ return 0.162 * dnla20 * a_plasma_surface * b_plasma_toroidal_on_axis**0.26 @@ -616,39 +705,45 @@ def calculate_martin08_aspect_nominal( m_ions_total_amu: float, aspect: float, ) -> float: - """ - Calculate the nominal Martin L-H transition power threshold with aspect ratio correction from T Takizuka. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param a_plasma_surface: Plasma surface area [m^2] - :type a_plasma_surface: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :param aspect: Plasma aspect ratio - :type aspect: float - :return: The Martin L-H transition power threshold [MW] - :rtype: float - - :notes: - - Thus will return an aspect ratio correction of the aspect ratio is less than or equal to 2.7. - if not the usual Martin 2008 scaling will be returned. - - - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; - "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be - reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - :references: - - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” - Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, - doi: https://doi.org/10.1088/1742-6596/123/1/012033. - - - T. Takizuka et.al, “Roles of aspect ratio, absolute B and effective Z of the H-mode power threshold in tokamaks of the ITPA database,” - Plasma Physics and Controlled Fusion, vol. 46, no. 5A, pp. A227-A233, Apr. 2004, - doi: https://doi.org/10.1088/0741-3335/46/5a/024. - ‌ + """Calculate the nominal Martin L-H transition power threshold with aspect ratio correction from T Takizuka. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + a_plasma_surface : float + Plasma surface area [m^2] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + aspect : float + Plasma aspect ratio + + Returns + ------- + float + The Martin L-H transition power threshold [MW] + + Notes + ----- + - Thus will return an aspect ratio correction of the aspect ratio is less than or equal to 2.7. + if not the usual Martin 2008 scaling will be returned. + + - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; + "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be + reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + References + ---------- + - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” + Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, + doi: https://doi.org/10.1088/1742-6596/123/1/012033. + + - T. Takizuka et.al, “Roles of aspect ratio, absolute B and effective Z of the H-mode power threshold in tokamaks of the ITPA database,” + Plasma Physics and Controlled Fusion, vol. 46, no. 5A, pp. A227-A233, Apr. 2004, + doi: https://doi.org/10.1088/0741-3335/46/5a/024. + """ if aspect <= 2.7: @@ -673,39 +768,45 @@ def calculate_martin08_aspect_upper( m_ions_total_amu: float, aspect: float, ) -> float: - """ - Calculate the upper Martin L-H transition power threshold with aspect ratio correction from T Takizuka. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param a_plasma_surface: Plasma surface area [m^2] - :type a_plasma_surface: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :param aspect: Plasma aspect ratio - :type aspect: float - :return: The Martin L-H transition power threshold [MW] - :rtype: float - - :notes: - - Thus will return an aspect ratio correction of the aspect ratio is less than or equal to 2.7. - if not the usual Martin 2008 scaling will be returned. - - - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; - "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be - reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - :references: - - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” - Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, - doi: https://doi.org/10.1088/1742-6596/123/1/012033. - - - T. Takizuka et.al, “Roles of aspect ratio, absolute B and effective Z of the H-mode power threshold in tokamaks of the ITPA database,” - Plasma Physics and Controlled Fusion, vol. 46, no. 5A, pp. A227-A233, Apr. 2004, - doi: https://doi.org/10.1088/0741-3335/46/5a/024. - ‌ + """Calculate the upper Martin L-H transition power threshold with aspect ratio correction from T Takizuka. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + a_plasma_surface : float + Plasma surface area [m^2] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + aspect : float + Plasma aspect ratio + + Returns + ------- + float + The Martin L-H transition power threshold [MW] + + Notes + ----- + - Thus will return an aspect ratio correction of the aspect ratio is less than or equal to 2.7. + if not the usual Martin 2008 scaling will be returned. + + - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; + "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be + reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + References + ---------- + - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” + Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, + doi: https://doi.org/10.1088/1742-6596/123/1/012033. + + - T. Takizuka et.al, “Roles of aspect ratio, absolute B and effective Z of the H-mode power threshold in tokamaks of the ITPA database,” + Plasma Physics and Controlled Fusion, vol. 46, no. 5A, pp. A227-A233, Apr. 2004, + doi: https://doi.org/10.1088/0741-3335/46/5a/024. + """ if aspect <= 2.7: @@ -730,39 +831,45 @@ def calculate_martin08_aspect_lower( m_ions_total_amu: float, aspect: float, ) -> float: - """ - Calculate the lower Martin L-H transition power threshold with aspect ratio correction from T Takizuka. - - :param dnla20: Line averaged electron density in units of 10^20 m^-3. - :type dnla20: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field [T] - :type b_plasma_toroidal_on_axis: float - :param a_plasma_surface: Plasma surface area [m^2] - :type a_plasma_surface: float - :param m_ions_total_amu: Total ion mass in atomic mass units [amu] - :type m_ions_total_amu: float - :param aspect: Plasma aspect ratio - :type aspect: float - :return: The Martin L-H transition power threshold [MW] - :rtype: float - - :notes: - - Thus will return an aspect ratio correction of the aspect ratio is less than or equal to 2.7. - if not the usual Martin 2008 scaling will be returned. - - - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; - "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be - reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. - - :references: - - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” - Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, - doi: https://doi.org/10.1088/1742-6596/123/1/012033. - - - T. Takizuka et.al, “Roles of aspect ratio, absolute B and effective Z of the H-mode power threshold in tokamaks of the ITPA database,” - Plasma Physics and Controlled Fusion, vol. 46, no. 5A, pp. A227-A233, Apr. 2004, - doi: https://doi.org/10.1088/0741-3335/46/5a/024. - ‌ + """Calculate the lower Martin L-H transition power threshold with aspect ratio correction from T Takizuka. + + Parameters + ---------- + dnla20 : float + Line averaged electron density in units of 10^20 m^-3. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field [T] + a_plasma_surface : float + Plasma surface area [m^2] + m_ions_total_amu : float + Total ion mass in atomic mass units [amu] + aspect : float + Plasma aspect ratio + + Returns + ------- + float + The Martin L-H transition power threshold [MW] + + Notes + ----- + - Thus will return an aspect ratio correction of the aspect ratio is less than or equal to 2.7. + if not the usual Martin 2008 scaling will be returned. + + - A scaling with the total ion mass is used in this model. Martin 08 shows that P_LH scales with 1/m_i. It is stated; + "When this mass dependence is applied to the deuterium-tritium discharges for ITER, the above predicted values of P_LH can be + reduced by ~ 20%". We thus apply a (2/m_i) addition so that for a 50/50 D-T mixture (M_i = 2.5 amu), the predicted values is 20% lower. + + References + ---------- + - Y. R. Martin, T. Takizuka, and the I. C. H-mode. T. D. Group, “Power requirement for accessing the H-mode in ITER,” + Journal of Physics: Conference Series, vol. 123, p. 012033, Jul. 2008, + doi: https://doi.org/10.1088/1742-6596/123/1/012033. + + - T. Takizuka et.al, “Roles of aspect ratio, absolute B and effective Z of the H-mode power threshold in tokamaks of the ITPA database,” + Plasma Physics and Controlled Fusion, vol. 46, no. 5A, pp. A227-A233, Apr. 2004, + doi: https://doi.org/10.1088/0741-3335/46/5a/024. + """ if aspect <= 2.7: diff --git a/process/log.py b/process/log.py index f4368806db..616f1c76fd 100644 --- a/process/log.py +++ b/process/log.py @@ -21,7 +21,7 @@ class ProcessLogHandler(Handler): """ def __init__(self, capturing=True): - """Intantiates a ProcessLogHandler. + """Instantiates a ProcessLogHandler. :param capturing: capture and store emitted logs? :type capturning: bool @@ -64,8 +64,11 @@ def render_warnings(self): def show_errors(file_unit: int): """Write the rendered captured logs to the terminal/OUTFile - :param file_unit: a number describing the output medium (terminal, OUTFile) - :type file_unit: int + Parameters + ---------- + file_unit : int + a number describing the output medium (terminal, OUTFile) + """ warning_string = ( "******************************************** Errors and Warnings *********************************************" diff --git a/process/main.py b/process/main.py index c03af14e2d..59a3c0d336 100644 --- a/process/main.py +++ b/process/main.py @@ -10,8 +10,6 @@ "program". Power Reactor Optimisation Code for Environmental and Safety Studies -P J Knight, CCFE, Culham Science Centre -J Morris, CCFE, Culham Science Centre This is a systems code that evaluates various physics and engineering aspects of a fusion power plant subject to given @@ -45,7 +43,7 @@ import logging import os from pathlib import Path -from typing import Protocol +from typing import Any, Protocol import process import process.data_structure as data_structure @@ -120,21 +118,22 @@ class Process: """The main Process class.""" - def __init__(self, args=None): + def __init__(self, args: list[Any] | None = None): """Run Process. :param args: Arguments to parse, defaults to None - :type args: list, optional """ self.parse_args(args) self.run_mode() self.post_process() - def parse_args(self, args): + def parse_args(self, args: list[Any] | None): """Parse the command-line arguments, such as the input filename. - :param args: Arguments to parse - :type args: list + Parameters + ---------- + args : + Arguments to parse """ parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, @@ -279,13 +278,15 @@ class VaryRun: README.txt - contains comments from config file """ - def __init__(self, config_file, solver="vmcon"): + def __init__(self, config_file: str, solver: str = "vmcon"): """Initialise and perform a VaryRun. - :param config_file: config file for run parameters - :type config_file: str - :param solver: which solver to use, as specified in solver.py - :type solver: str, optional + Parameters + ---------- + config_file: + config file for run parameters + solver: + which solver to use, as specified in solver.py """ # Store the absolute path to the config file immediately: various # dir changes happen in old run_process code @@ -295,7 +296,10 @@ def __init__(self, config_file, solver="vmcon"): def run(self): """Perform a VaryRun by running multiple SingleRuns. - :raises FileNotFoundError: if input file doesn't exist + Raises + ------ + FileNotFoundError + if input file doesn't exist """ # The input path for the varied input file input_path = self.config_file.parent / "IN.DAT" @@ -368,12 +372,17 @@ def run(self): class SingleRun: """Perform a single run of PROCESS.""" - def __init__(self, input_file, solver="vmcon", *, update_obsolete=False): + def __init__( + self, input_file: str, solver: str = "vmcon", *, update_obsolete: bool = False + ): """Read input file and initialise variables. - :param input_file: input file named IN.DAT - :type input_file: str - :param solver: which solver to use, as specified in solver.py - :type solver: str, optional + + Parameters + ---------- + input_file: + input file named IN.DAT + solver: + which solver to use, as specified in solver.py """ self.input_file = input_file @@ -509,16 +518,11 @@ def append_input(self): mfile_file.write("***********************************************") mfile_file.writelines(input_lines) - def validate_input(self, replace_obsolete=False): - """ - Checks the input IN.DAT file for any obsolete variables in the OBS_VARS dict contained + def validate_input(self, replace_obsolete: bool = False): + """Checks the input IN.DAT file for any obsolete variables in the OBS_VARS dict contained within obsolete_variables.py. If obsolete variables are found, and if `replace_obsolete` is set to True, they are either removed or replaced by their updated names as specified in the OBS_VARS dictionary. - - Parameters: - replace_obsolete (bool): If True, modifies the IN.DAT file to replace or comment out - obsolete variables. If False, only reports obsolete variables. """ obsolete_variables = ov.OBS_VARS @@ -746,7 +750,13 @@ def costs(self, value: CostsProtocol): def setup_loggers(working_directory_log_path: Path | None = None): - """A function that adds our handlers to the appropriate logger object.""" + """A function that adds our handlers to the appropriate logger object. + + Parameters + ---------- + working_directory_log_path: Path | None : + (Default value = None) + """ # Remove all of the existing handlers from the 'process' package logger logger.handlers.clear() @@ -771,7 +781,7 @@ def setup_loggers(working_directory_log_path: Path | None = None): logger.addHandler(logging_file_input_location_handler) -def main(args=None): +def main(args: list[Any] | None = None): """Run Process. The args parameter is used to control command-line arguments when running @@ -779,8 +789,10 @@ def main(args=None): used instead of command-line arguments by argparse. This allows testing of different command-line arguments from the test suite. - :param args: Arguments to parse, defaults to None - :type args: list, optional + Parameters + ---------- + args : + Arguments to parse, defaults to None """ Process(args) diff --git a/process/objectives.py b/process/objectives.py index cd54a9e459..b99e125e07 100644 --- a/process/objectives.py +++ b/process/objectives.py @@ -35,26 +35,28 @@ def objective_function(minmax: int) -> float: """Calculate the specified objective function - :param minimax: the ID and sign of the figure of merit to evaluate. - A negative value indicates maximisation. - A positive value indicates minimisation. - * 1: Major radius - * 3: Neutron wall load - * 4: TF coil + PF coil power - * 5: Fusion gain - * 6: Cost of electricity - * 7: Direct/constructed/capital cost - * 8: Aspect ratio - * 9: Divertor heat load - * 10: Toroidal field on axis - * 11: Injected power - * 14: Pulse length - * 15: Plant availability - * 16: Major radius/burn time - * 17: Net electrical output - * 18: NULL, f(x) = 1 - * 19: Major radius/burn time - :type minimax: int + Parameters + ---------- + minimax : int + the ID and sign of the figure of merit to evaluate. + A negative value indicates maximisation. + A positive value indicates minimisation. + * 1: Major radius + * 3: Neutron wall load + * 4: TF coil + PF coil power + * 5: Fusion gain + * 6: Cost of electricity + * 7: Direct/constructed/capital cost + * 8: Aspect ratio + * 9: Divertor heat load + * 10: Toroidal field on axis + * 11: Injected power + * 14: Pulse length + * 15: Plant availability + * 16: Major radius/burn time + * 17: Net electrical output + * 18: NULL, f(x) = 1 + * 19: Major radius/burn time """ figure_of_merit = abs(minmax) diff --git a/process/output.py b/process/output.py index f840421766..48eaa89d88 100644 --- a/process/output.py +++ b/process/output.py @@ -7,10 +7,13 @@ def write(models, _outfile): Write the program results to a file, in a tidy format. - :param models: physics and engineering model objects - :type models: process.main.Models - :param outfile: Fortran output unit identifier - :type outfile: int + Parameters + ---------- + models : process.main.Models + physics and engineering model objects + _outfile : int + Fortran output unit identifier + """ # ensure we are capturing warnings that occur in the 'output' stage as these are warnings # that occur at our solution point. So we clear existing warnings diff --git a/process/pfcoil.py b/process/pfcoil.py index bb60dbf7ea..8d298c17e3 100644 --- a/process/pfcoil.py +++ b/process/pfcoil.py @@ -30,7 +30,7 @@ class PFCoil: """Calculate poloidal field coil system parameters.""" - def __init__(self, cs_fatigue) -> None: + def __init__(self, cs_fatigue): """Initialise Fortran module variables.""" self.outfile = constants.NOUT # output file unit self.mfile = constants.MFILE # mfile file unit @@ -60,9 +60,7 @@ def output_induct(self): def pfcoil(self): """Routine to perform calculations for the PF and Central Solenoid coils. - author: P J Knight, CCFE, Culham Science Centre - author: R Kemp, CCFE, Culham Science Centre - None + This subroutine performs the calculations for the PF and Central Solenoid coils, to determine their size, location, current waveforms, stresses etc. @@ -1077,25 +1075,29 @@ def place_pf_above_cs( dr_tf_inboard: float, z_cs_coil_upper: float, ) -> tuple[np.ndarray, np.ndarray]: - """ - Calculate the placement of PF coils stacked above the Central Solenoid. - - :param n_pf_coils_in_group: Array containing the number of coils in each PF group. - :type n_pf_coils_in_group: np.ndarray - :param n_pf_group: Index of the PF coil group. - :type n_pf_group: int - :param r_cs_middle: Radial coordinate of CS coil centre (m). - :type r_cs_middle: float - :param dr_pf_cs_middle_offset: Radial offset for PF coil placement (m). - :type dr_pf_cs_middle_offset: float - :param z_tf_inside_half: Half-height of the TF bore (m). - :type z_tf_inside_half: float - :param dr_tf_inboard: Thickness of the TF inboard leg (m). - :type dr_tf_inboard: float - :param z_cs_coil_upper: Upper z coordinate of the CS coil (m). - :type z_cs_coil_upper: float - :return: Tuple of arrays containing the radial and vertical coordinates of PF coils in the group. - :rtype: tuple[np.ndarray, np.ndarray] + """Calculate the placement of PF coils stacked above the Central Solenoid. + + Parameters + ---------- + n_pf_coils_in_group : np.ndarray + Array containing the number of coils in each PF group. + n_pf_group : int + Index of the PF coil group. + r_cs_middle : float + Radial coordinate of CS coil centre (m). + dr_pf_cs_middle_offset : float + Radial offset for PF coil placement (m). + z_tf_inside_half : float + Half-height of the TF bore (m). + dr_tf_inboard : float + Thickness of the TF inboard leg (m). + z_cs_coil_upper : float + Upper z coordinate of the CS coil (m). + + Returns + ------- + tuple[np.ndarray, np.ndarray] + Tuple of arrays containing the radial and vertical coordinates of PF coils in the group. """ # Initialise as empty arrays; will be resized in the loop @@ -1141,39 +1143,42 @@ def place_pf_above_tf( rpf2: float, zref: np.ndarray, ) -> tuple[np.ndarray, np.ndarray, int]: - """ - Calculates and places poloidal field (PF) coils above the toroidal field (TF) coils for a given group. - - :param n_pf_coils_in_group: Array containing the number of PF coils in each group. - :type n_pf_coils_in_group: np.ndarray - :param n_pf_group: Index of the PF coil group to process. - :type n_pf_group: int - :param rmajor: Major radius of the device. - :type rmajor: float - :param triang: Triangularity parameter for coil placement. - :type triang: float - :param rminor: Minor radius of the device. - :type rminor: float - :param itart: Flag indicating ST configuration. - :type itart: int - :param itartpf: Flag indicating PF coil configuration for ST. - :type itartpf: int - :param z_tf_inside_half: Half-height of the TF coil inside region. - :type z_tf_inside_half: float - :param dz_tf_upper_lower_midplane: Height difference parameter for PF coil placement. - :type dz_tf_upper_lower_midplane: float - :param z_tf_top: Top z-coordinate of the TF coil. - :type z_tf_top: float - :param top_bottom: Indicator for coil placement above (+1) or below (-1) the midplane. - :type top_bottom: int - :param rpf2: Radial offset parameter for PF coil placement. - :type rpf2: float - :param zref: Array of reference z-coordinates for PF coil placement. - :type zref: np.ndarray - - :returns: Tuple containing arrays of radial and vertical positions of PF coil middles for the specified group, - and the updated top_bottom indicator. - :rtype: tuple[np.ndarray, np.ndarray, int] + """Calculates and places poloidal field (PF) coils above the toroidal field (TF) coils for a given group. + + Parameters + ---------- + n_pf_coils_in_group : np.ndarray + Array containing the number of PF coils in each group. + n_pf_group : int + Index of the PF coil group to process. + rmajor : float + Major radius of the device. + triang : float + Triangularity parameter for coil placement. + rminor : float + Minor radius of the device. + itart : int + Flag indicating ST configuration. + itartpf : int + Flag indicating PF coil configuration for ST. + z_tf_inside_half : float + Half-height of the TF coil inside region. + dz_tf_upper_lower_midplane : float + Height difference parameter for PF coil placement. + z_tf_top : float + Top z-coordinate of the TF coil. + top_bottom : int + Indicator for coil placement above (+1) or below (-1) the midplane. + rpf2 : float + Radial offset parameter for PF coil placement. + zref : np.ndarray + Array of reference z-coordinates for PF coil placement. + + Returns + ------- + tuple[np.ndarray, np.ndarray, int] + Tuple containing arrays of radial and vertical positions of PF coil middles for the specified group, + and the updated top_bottom indicator. """ # Initialise as empty arrays; will be resized in the loop r_pf_coil_middle_group_array = np.zeros(( @@ -1219,26 +1224,29 @@ def place_pf_outside_tf( i_r_pf_outside_tf_placement: int, r_pf_outside_tf_midplane: float, ) -> tuple[np.ndarray, np.ndarray]: - """ - Calculates the radial and vertical positions of poloidal field (PF) coils placed outside the toroidal field (TF) coil. - - :param n_pf_coils_in_group: Array containing the number of PF coils in each group. - :type n_pf_coils_in_group: np.ndarray - :param n_pf_group: Index of the PF coil group to process. - :type n_pf_group: int - :param rminor: Minor radius of the device. - :type rminor: float - :param zref: Reference vertical positions for each PF coil group. - :type zref: np.ndarray - :param i_tf_shape: Integer flag indicating TF coil shape (2 for picture frame, others for D-shape). - :type i_tf_shape: int - :param i_r_pf_outside_tf_placement: Placement switch for PF coil radius (1 for constant/stacked, 0 for following TF curve). - :type i_r_pf_outside_tf_placement: int - :param r_pf_outside_tf_midplane: Radial position of PF coil at the midplane. - :type r_pf_outside_tf_midplane: float - - :returns: Tuple containing arrays of radial and vertical positions of PF coil centers for the specified group. - :rtype: tuple[np.ndarray, np.ndarray] + """Calculates the radial and vertical positions of poloidal field (PF) coils placed outside the toroidal field (TF) coil. + + Parameters + ---------- + n_pf_coils_in_group : np.ndarray + Array containing the number of PF coils in each group. + n_pf_group : int + Index of the PF coil group to process. + rminor : float + Minor radius of the device. + zref : np.ndarray + Reference vertical positions for each PF coil group. + i_tf_shape : int + Integer flag indicating TF coil shape (2 for picture frame, others for D-shape). + i_r_pf_outside_tf_placement : int + Placement switch for PF coil radius (1 for constant/stacked, 0 for following TF curve). + r_pf_outside_tf_midplane : float + Radial position of PF coil at the midplane. + + Returns + ------- + tuple[np.ndarray, np.ndarray] + Tuple containing arrays of radial and vertical positions of PF coil centers for the specified group. """ # Initialise as empty arrays; will be resized in the loop @@ -1289,24 +1297,27 @@ def place_pf_generally( zref: np.ndarray, rref: np.ndarray, ) -> tuple[np.ndarray, np.ndarray]: - """ - Calculates the radial and vertical positions of poloidal field (PF) coils placed in a general location. - - :param n_pf_coils_in_group: Array containing the number of PF coils in each group. - :type n_pf_coils_in_group: numpy.ndarray - :param n_pf_group: Index of the PF coil group to process. - :type n_pf_group: int - :param rminor: Minor radius of the device. - :type rminor: float - :param rmajor: Major radius of the device. - :type rmajor: float - :param zref: Reference vertical positions for each PF coil group. - :type zref: numpy.ndarray - :param rref: Reference radial positions for each PF coil group. - :type rref: numpy.ndarray - - :returns: Tuple containing arrays of radial and vertical positions of PF coil centers for the specified group. - :rtype: tuple[numpy.ndarray, numpy.ndarray] + """Calculates the radial and vertical positions of poloidal field (PF) coils placed in a general location. + + Parameters + ---------- + n_pf_coils_in_group : numpy.ndarray + Array containing the number of PF coils in each group. + n_pf_group : int + Index of the PF coil group to process. + rminor : float + Minor radius of the device. + rmajor : float + Major radius of the device. + zref : numpy.ndarray + Reference vertical positions for each PF coil group. + rref : numpy.ndarray + Reference radial positions for each PF coil group. + + Returns + ------- + tuple[numpy.ndarray, numpy.ndarray] + Tuple containing arrays of radial and vertical positions of PF coil centers for the specified group. """ r_pf_coil_middle_group_array: np.ndarray = np.zeros(( pfcoil_variables.n_pf_coil_groups, @@ -1355,71 +1366,56 @@ def efc( ): """Calculates field coil currents. - author: P J Knight, CCFE, Culham Science Centre - author: D Strickler, ORNL - author: J Galambos, ORNL - author: P C Shipe, ORNL This routine calculates the currents required in a group of ring coils to produce a fixed field at prescribed locations. Additional ring coils with fixed currents are also allowed. - :param npts: number of data points at which field is to be fixed; should - be <= nptsmx - :type npts: int - :param rpts: coords of data points (m) - :type rpts: np.ndarray - :param zpts: coords of data points (m) - :type zpts: np.ndarray - :param brin: field components at data points (T) - :type brin: np.ndarray - :param bzin: field components at data points (T) - :type bzin: np.ndarray - :param nfix: number of coils with fixed currents, <= nfixmx - :type nfix: int - :param rfix: coordinates of coils with fixed currents (m) - :type rfix: np.ndarray - :param zfix: coordinates of coils with fixed currents (m) - :type zfix: np.ndarray - :param cfix: Fixed currents (A) - :type cfix: np.ndarray - :param n_pf_coil_groups: number of coil groups, where all coils in a group have the - same current, <= n_pf_groups_max - :type n_pf_coil_groups: int - :param n_pf_coils_in_group: number of coils in each group, each value <= n_pf_coils_in_group_max - :type n_pf_coils_in_group: np.ndarray - :param r_pf_coil_middle_group_array: coords R(i,j), Z(i,j) of coil j in group i (m) - :type r_pf_coil_middle_group_array: np.ndarray - :param z_pf_coil_middle_group_array: coords R(i,j), Z(i,j) of coil j in group i (m) - :type z_pf_coil_middle_group_array: np.ndarray - :param alfa: smoothing parameter (0 = no smoothing, 1.0D-9 = large - smoothing) - :type alfa: float - :param bfix: work array - :type bfix: np.ndarray - :param gmat: work array - :type gmat: np.ndarray - :param bvec: work array - :type bvec: np.ndarray - :param rc: work array - :type rc: np.ndarray - :param zc: work array - :type zc: np.ndarray - :param cc: work array - :type cc: np.ndarray - :param xc: work array - :type xc: np.ndarray - :param umat: work array - :type umat: np.ndarray - :param vmat: work array - :type vmat: np.ndarray - :param sigma: work array - :type sigma: np.ndarray - :param work2: work array - :type work2: np.ndarray - :return: sum of squares of elements of residual vector, solution vector - of coil currents in each group (A) - :rtype: tuple[float, np.ndarray] + Parameters + ---------- + npts : int + number of data points at which field is to be fixed; should + be <= nptsmx + rpts : np.ndarray + coords of data points (m) + zpts : np.ndarray + coords of data points (m) + brin : np.ndarray + field components at data points (T) + bzin : np.ndarray + field components at data points (T) + nfix : int + number of coils with fixed currents, <= nfixmx + rfix : np.ndarray + coordinates of coils with fixed currents (m) + zfix : np.ndarray + coordinates of coils with fixed currents (m) + cfix : np.ndarray + Fixed currents (A) + n_pf_coil_groups : int + number of coil groups, where all coils in a group have the + same current, <= n_pf_groups_max + n_pf_coils_in_group : np.ndarray + number of coils in each group, each value <= n_pf_coils_in_group_max + r_pf_coil_middle_group_array : np.ndarray + coords R(i,j), Z(i,j) of coil j in group i (m) + z_pf_coil_middle_group_array : np.ndarray + coords R(i,j), Z(i,j) of coil j in group i (m) + alfa : float + smoothing parameter (0 = no smoothing, 1.0D-9 = large + smoothing) + bfix : np.ndarray + work array + gmat : np.ndarray + work array + bvec : np.ndarray + work array + + Returns + ------- + tuple[float, np.ndarray] + sum of squares of elements of residual vector, solution vector + of coil currents in each group (A) """ lrow1 = bfix.shape[0] lcol1 = gmat.shape[1] @@ -1517,26 +1513,26 @@ def solv(self, n_pf_groups_max, n_pf_coil_groups, nrws, gmat, bvec): This routine solves the matrix equation for calculating the currents in a group of ring coils. - author: P J Knight, CCFE, Culham Science Centre - author: D Strickler, ORNL - author: J Galambos, ORNL - author: P C Shipe, ORNL - - :param n_pf_groups_max: maximum number of PF coil groups - :type n_pf_groups_max: int - :param n_pf_coil_groups: number of coil groups, where all coils in a group have the - same current, <= n_pf_groups_max - :type n_pf_coil_groups: int - :param nrws: actual number of rows to use - :type nrws: int - :param gmat: work array - :type gmat: numpy.ndarray - :param bvec: work array - :type bvec: numpy.ndarray - :return: solution vector of coil currents - in each group (A) (ccls), rest are work arrays - :rtype: tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, - numpy.ndarray, numpy.ndarray] + + Parameters + ---------- + n_pf_groups_max : int + maximum number of PF coil groups + n_pf_coil_groups : int + number of coil groups, where all coils in a group have the + same current, <= n_pf_groups_max + nrws : int + actual number of rows to use + gmat : numpy.ndarray + work array + bvec : numpy.ndarray + work array + + Returns + ------- + : + solution vector of coil currents + in each group (A) (ccls), rest are work arrays """ ccls = np.zeros(n_pf_groups_max) work2 = np.zeros(n_pf_groups_max) @@ -1562,7 +1558,7 @@ def solv(self, n_pf_groups_max, n_pf_coil_groups, nrws, gmat, bvec): def vsec(self): """Calculation of volt-second capability of PF system. - author: P J Knight, CCFE, Culham Science Centre + This routine calculates the volt-second capability of the PF coil system. """ @@ -1670,12 +1666,14 @@ def vsec(self): def induct(self, output): """Calculates PF coil set mutual inductance matrix. - author: P J Knight, CCFE, Culham Science Centre + This routine calculates the mutual inductances between all the PF coils. - :param output: switch for writing to output file - :type output: bool + Parameters + ---------- + output : bool + switch for writing to output file """ nohmax = 200 nplas = 1 @@ -1978,7 +1976,7 @@ def induct(self, output): def outpf(self): """Routine to write output from PF coil module to file. - author: P J Knight, CCFE, Culham Science Centre + This routine writes the PF coil information to the output file. """ op.oheadr(self.outfile, "Central Solenoid and PF Coils") @@ -2705,8 +2703,6 @@ def outpf(self): def outvolt(self): """Writes volt-second information to output file. - author: P J Knight, CCFE, Culham Science Centre - author: R Kemp, CCFE, Culham Science Centre This routine writes the PF coil volt-second data to the output file. """ @@ -2866,20 +2862,26 @@ def outvolt(self): def selfinductance(self, a, b, c, n): """Calculates the selfinductance using Bunet's formula. - author: M. Kovari, CCFE + This routine calculates the self inductance in Henries Radiotron Designers Handbook (4th Edition) chapter 10 - :param a: mean radius of coil (m) - :type a: float - :param b: length of coil (m) (given as l in the reference) - :type b: float - :param c: radial winding thickness (m) - :type c: float - :param N: number of turns - :type N: float - :return selfinductance: the self inductance in Henries - :rtype: float + Parameters + ---------- + a : float + mean radius of coil (m) + b : float + length of coil (m) (given as l in the reference) + c : float + radial winding thickness (m) + n : float + number of turns + + + Returns + ------- + : + the self inductance in Henries """ return ( (1.0e-6 / 0.0254e0) @@ -2891,7 +2893,7 @@ def selfinductance(self, a, b, c, n): def waveform(self): """Sets up the PF coil waveforms. - author: P J Knight, CCFE, Culham Science Centre + This routine sets up the PF coil current waveforms. f_c_pf_cs_peak_time_array[i,j] is the current in coil i, at time j, normalized to the peak current in that coil at any time. @@ -2962,7 +2964,7 @@ def waveform(self): class CSCoil: """Calculate central solenoid coil system parameters.""" - def __init__(self, cs_fatigue) -> None: + def __init__(self, cs_fatigue): """Initialise Fortran module variables.""" self.outfile = constants.NOUT # output file unit`` self.mfile = constants.MFILE # mfile file unit @@ -2975,18 +2977,23 @@ def calculate_cs_geometry( dr_cs: float, dr_bore: float, ) -> tuple[float, float, float, float, float, float, float, float, float]: - """ - Calculate the geometry of the Central Solenoid (CS) coil. - - :param z_tf_inside_half: Half-height of the TF bore (m) - :type z_tf_inside_half: float - :param f_z_cs_tf_internal: Fractional height of CS relative to TF bore - :type f_z_cs_tf_internal: float - :param dr_cs: Thickness of the CS coil (m) - :type dr_cs: float - :param dr_bore: Radius of the TF bore (m) - :type dr_bore: float - :return: Tuple containing: + """Calculate the geometry of the Central Solenoid (CS) coil. + + Parameters + ---------- + z_tf_inside_half : float + Half-height of the TF bore (m) + f_z_cs_tf_internal : float + Fractional height of CS relative to TF bore + dr_cs : float + Thickness of the CS coil (m) + dr_bore : float + Radius of the TF bore (m) + + Returns + ------- + tuple[float, float, float, float, float, float, float, float] + Tuple containing: - z_cs_coil_upper: Upper Z coordinate of CS coil (m) - z_cs_coil_lower: Lower Z coordinate of CS coil (m) - r_cs_coil_middle: Radial coordinate of CS coil centre (m) @@ -2995,7 +3002,6 @@ def calculate_cs_geometry( - r_cs_coil_inner: Inner radius of CS coil (m) - a_cs_poloidal: Total poloidal cross-sectional area of CS coil (m²) - dz_cs_full: Full height of CS coil (m) - :rtype: tuple[float, float, float, float, float, float, float, float] """ # Central Solenoid mean radius @@ -3046,34 +3052,39 @@ def calculate_cs_turn_geometry_eu_demo( radius_cs_turn_corners: float, f_a_cs_turn_steel: float, ) -> tuple[float, float, float, float, float]: - """ - Calculate the geometry of a CS (Central Solenoid) turn using the EU DEMO stadium-shaped model. - - :param a_cs_turn: Poloidal area of a CS turn (m^2) - :type a_cs_turn: float - :param f_dr_dz_cs_turn: Length-to-height ratio of the CS turn - :type f_dr_dz_cs_turn: float - :param radius_cs_turn_corners: Radius of curved outer corner (m) - :type radius_cs_turn_corners: float - :param f_a_cs_turn_steel: Fraction of steel area in the CS turn - :type f_a_cs_turn_steel: float - :return: Tuple containing: + """Calculate the geometry of a CS (Central Solenoid) turn using the EU DEMO stadium-shaped model. + + Parameters + ---------- + a_cs_turn : float + Poloidal area of a CS turn (m^2) + f_dr_dz_cs_turn : float + Length-to-height ratio of the CS turn + radius_cs_turn_corners : float + Radius of curved outer corner (m) + f_a_cs_turn_steel : float + Fraction of steel area in the CS turn + + Returns + ------- + : + Tuple containing: - dz_cs_turn: Depth/width of CS turn conduit (m) - dr_cs_turn: Length of CS turn conduit (m) - radius_cs_turn_cable_space: Radius of CS turn cable space (m) - dr_cs_turn_conduit: Radial thickness of steel conduit (m) - dz_cs_turn_conduit: Vertical thickness of steel conduit (m) - :rtype: tuple[float, float, float, float, float] - :notes: + Notes + ----- - The calculation assumes a stadium-shaped cross-section for the CS turn. - If the calculated conduit thickness is negative or too small, it is set to a minimum value of 1 mm. - :references: + References + ---------- - R. Wesche et al., “Central solenoid winding pack design for DEMO,” Fusion Engineering and Design, vol. 124, pp. 82-85, Apr. 2017, doi: https://doi.org/10.1016/j.fusengdes.2017.04.052. - """ # Vertical height of CS turn conduit/turn dz_cs_turn = (a_cs_turn / f_dr_dz_cs_turn) ** 0.5 @@ -3121,31 +3132,34 @@ def place_cs_filaments( f_j_cs_start_pulse_end_flat_top: float, nfxf: int, ): - """ - Places central solenoid (CS) filaments and assigns their positions and currents. + """Places central solenoid (CS) filaments and assigns their positions and currents. This function calculates the radial (R) and vertical (Z) positions, as well as the current values, for a set of CS filaments based on the provided parameters. Each filament is placed symmetrically about the midplane, and currents are assigned according to the flat-top end current and scaling factors. - :param n_cs_current_filaments: Number of CS current filaments to place (per side). - :type n_cs_current_filaments: int - :param r_cs_middle: Radial coordinate of the middle of the CS. - :type r_cs_middle: float - :param z_cs_inside_half: Half-height of the CS in the vertical (Z) direction. - :type z_cs_inside_half: float - :param c_cs_flat_top_end: Flat-top end current for the CS. - :type c_cs_flat_top_end: float - :param f_j_cs_start_pulse_end_flat_top: Scaling factor for the CS current at the start of the pulse and flat-top end. - :type f_j_cs_start_pulse_end_flat_top: float - :param nfxf: Number of flux loops or scaling factor for current distribution. - :type nfxf: int - - :returns: Tuple containing: + Parameters + ---------- + n_cs_current_filaments : int + Number of CS current filaments to place (per side). + r_cs_middle : float + Radial coordinate of the middle of the CS. + z_cs_inside_half : float + Half-height of the CS in the vertical (Z) direction. + c_cs_flat_top_end : float + Flat-top end current for the CS. + f_j_cs_start_pulse_end_flat_top : float + Scaling factor for the CS current at the start of the pulse and flat-top end. + nfxf : int + Number of flux loops or scaling factor for current distribution. + + Returns + ------- + tuple[list[float], list[float], list[float]] + Tuple containing: - r_pf_cs_current_filaments (list of float): Radial positions of the CS filaments. - z_pf_cs_current_filaments (list of float): Vertical positions of the CS filaments. - c_pf_cs_current_filaments (list of float): Current values assigned to each CS filament. - :rtype: tuple[list[float], list[float], list[float]] """ r_pf_cs_current_filaments = np.zeros(pfcoil_variables.NFIXMX) z_pf_cs_current_filaments = np.zeros(pfcoil_variables.NFIXMX) @@ -3181,10 +3195,7 @@ def place_cs_filaments( ) def ohcalc(self): - """Routine to perform calculations for the Central Solenoid. - - author: P J Knight, CCFE, Culham Science Centre - """ + """Routine to perform calculations for the Central Solenoid.""" ( pfcoil_variables.z_pf_coil_upper[pfcoil_variables.n_cs_pf_coils - 1], @@ -3558,23 +3569,26 @@ def calculate_cs_self_peak_magnetic_field( r_cs_outer: float, dz_cs_half: float, ) -> float: - """ - Calculates the maximum field of a solenoid of circular winding and rectangular cross-section. - - :param j_cs: Overall current density (A/m²) - :type j_cs: float - :param r_cs_inner: Solenoid inner radius (m) - :type r_cs_inner: float - :param r_cs_outer: Solenoid outer radius (m) - :type r_cs_outer: float - :param dz_cs_half: Solenoid half height (m) - :type dz_cs_half: float - :return: Maximum field of solenoid (T) - :rtype: float - - :notes: - - :references: + """Calculates the maximum field of a solenoid of circular winding and rectangular cross-section. + + Parameters + ---------- + j_cs : float + Overall current density (A/m²) + r_cs_inner : float + Solenoid inner radius (m) + r_cs_outer : float + Solenoid outer radius (m) + dz_cs_half : float + Solenoid half height (m) + + Returns + ------- + float + Maximum field of solenoid (T) + + References + ---------- - Fits are taken from the figure on p.22 of M. Wilson's book "Superconducting Magnets", Clarendon Press, Oxford, N.Y., 1983, ISBN 13: 9780198548102 @@ -3695,28 +3709,35 @@ def calculate_cs_self_peak_midplane_axial_stress( dz_cs_half: float, c_cs_peak: float, ) -> tuple[float, float]: - """ - Calculate axial stress and axial force for the central solenoid. - - :param float r_cs_outer: Outer radius of the central solenoid (m). - :param float r_cs_inner: Inner radius of the central solenoid (m). - :param float dz_cs_half: Half-height of the central solenoid (m). - :param float c_cs_peak: Peak CS coil current (A). - - :returns: A tuple containing the unsmeared axial stress and the axial force. - :rtype: tuple(float, float) - The first element is the unsmeared axial stress in MPa. - The second element is the axial force in newtons (N). + """Calculate axial stress and axial force for the central solenoid. + + Parameters + ---------- + r_cs_outer: + Outer radius of the central solenoid (m). + r_cs_inner: + Inner radius of the central solenoid (m). + dz_cs_half: + Half-height of the central solenoid (m). + c_cs_peak: + Peak CS coil current (A). + + Returns + ------- + tuple(float, float) + A tuple containing the unsmeared axial stress and the axial force. + The first element is the unsmeared axial stress in MPa. + The second element is the axial force in newtons (N). :note: The axial force is computed using elliptic-integral based terms and the unsmeared axial stress is obtained by dividing the axial force by the effective steel area associated with the CS turns. - :references: + References + ---------- - Case Studies in Superconducting Magnets. Boston, MA: Springer US, 2009. doi: https://doi.org/10.1007/b112047. - """ # kb term for elliptical integrals @@ -3767,14 +3788,18 @@ def calculate_cs_self_peak_midplane_axial_stress( def hoop_stress(self, r): """Calculation of hoop stress of central solenoid. - author: J Morris, CCFE, Culham Science Centre This routine calculates the hoop stress of the central solenoid from "Superconducting magnets", M. N. Wilson OUP - :param r: radial position a < r < b - :type r: float - :return: hoop stress (MPa) - :rtype: float + Parameters + ---------- + r : float + radial position a < r < b + + Returns + ------- + float + hoop stress (MPa) """ a = pfcoil_variables.r_pf_coil_inner[pfcoil_variables.n_cs_pf_coils - 1] @@ -3836,28 +3861,30 @@ def hoop_stress(self, r): def peak_b_field_at_pf_coil( n_coil: int, n_coil_group: int, t_b_field_peak: int ) -> tuple[float, float, float, float]: - """ - Calculates the peak magnetic field components at the inner and outer edges of a given PF coil. - - :param n_coil: Coil number (1-based index) - :type n_coil: int - :param n_coil_group: Group number (1-based index) - :type n_coil_group: int - :param t_b_field_peak: Time point at which the field is highest - :type t_b_field_peak: int - - :returns: Tuple containing: + """Calculates the peak magnetic field components at the inner and outer edges of a given PF coil. + + Parameters + ---------- + n_coil : int + Coil number (1-based index) + n_coil_group : int + Group number (1-based index) + t_b_field_peak : int + Time point at which the field is highest + + Returns + ------- + tuple[float, float, float, float] + Tuple containing: - b_pf_inner_radial (float): Radial field at inner edge (T) - b_pf_outer_radial (float): Radial field at outer edge (T) - b_pf_inner_vertical (float): Vertical field at inner edge (T) - b_pf_outer_vertical (float): Vertical field at outer edge (T) - :rtype: tuple[float, float, float, float] - :notes: - This routine calculates the peak magnetic field components at the inner and outer edges of a given PF coil. - The calculation includes the effects from all the coils and the plasma. - - :author: P J Knight, CCFE, Culham Science Centre + Notes + ----- + This routine calculates the peak magnetic field components at the inner and outer edges of a given PF coil. + The calculation includes the effects from all the coils and the plasma. """ if bv.iohcl != 0 and n_coil == pfcoil_variables.n_cs_pf_coils: # Peak field is to be calculated at the Central Solenoid itself, @@ -4067,7 +4094,6 @@ def superconpf(bmax, fhe, fcu, jwp, isumat, fhts, strain, thelium, bcritsc, tcri This routine calculates the superconductor critical winding pack current density for the PF coils, plus the temperature margin. It is based on the TF coil version, supercon. - author: P J Knight, CCFE, Culham Science Centre N.B. critical current density for a super conductor (j_crit_sc) is for the superconducting strands/tape, not including copper. @@ -4077,38 +4103,43 @@ def superconpf(bmax, fhe, fcu, jwp, isumat, fhts, strain, thelium, bcritsc, tcri superconducting strands AND any addtional copper, such as REBCO tape support. - :param bmax: peak field at conductor (T) - :type bmax: float - :param fhe: fraction of cable space that is for He cooling - :type fhe: float - :param fcu: fraction of cable conductor that is copper - :type fcu: float - :param jwp: actual winding pack current density (A/m2) - :type jwp: float - :param isumat: switch for conductor type - 1 = ITER Nb3Sn, standard parameters, - 2 = Bi-2212 High Temperature Superconductor, - 3 = NbTi, - 4 = ITER Nb3Sn, user-defined parameters - 5 = WST Nb3Sn parameterisation - 7 = Durham Ginzbug-Landau Nb-Ti parameterisation - :type isumat: int - :param fhts: Adjustment factor (<= 1) to account for strain, - radiation damage, fatigue or AC losses - :type fhts: float - :param strain: Strain on superconductor at operation conditions - :type strain: float - :param thelium: He temperature at peak field point (K) - :type thelium: float - :param bcritsc: Critical field at zero temperature and strain (T) (isumat=4 only) - :type bcritsc: float - :param tcritsc: Critical temperature at zero field and strain (K) (isumat=4 only) - :type tcritsc: float - :return: Critical winding pack current density (A/m2) (j_crit_wp), - Critical cable current density (A/m2) (j_crit_cable) - Superconducting strand non-copper critical current density (A/m2) (j_crit_sc) - Temperature margin (K) (tmarg) - :rtype: tuple[float, float, float, float] + Parameters + ---------- + bmax : float + peak field at conductor (T) + fhe : float + fraction of cable space that is for He cooling + fcu : float + fraction of cable conductor that is copper + jwp : float + actual winding pack current density (A/m2) + isumat : int + switch for conductor type + 1 = ITER Nb3Sn, standard parameters, + 2 = Bi-2212 High Temperature Superconductor, + 3 = NbTi, + 4 = ITER Nb3Sn, user-defined parameters + 5 = WST Nb3Sn parameterisation + 7 = Durham Ginzbug-Landau Nb-Ti parameterisation + fhts : float + Adjustment factor (<= 1) to account for strain, + radiation damage, fatigue or AC losses + strain : float + Strain on superconductor at operation conditions + thelium : float + He temperature at peak field point (K) + bcritsc : float + Critical field at zero temperature and strain (T) (isumat=4 only) + tcritsc : float + Critical temperature at zero field and strain (K) (isumat=4 only) + + Returns + ------- + tuple[float, float, float, float] + Critical winding pack current density (A/m2) (j_crit_wp), + Critical cable current density (A/m2) (j_crit_cable) + Superconducting strand non-copper critical current density (A/m2) (j_crit_sc) + Temperature margin (K) (tmarg) """ # Find critical current density in superconducting strand, jcritstr @@ -4268,34 +4299,35 @@ def calculate_b_field_at_point( r_test_point: float, z_test_point: float, ) -> tuple[np.ndarray, float, float, float]: - """ - Calculate the magnetic field and mutual inductance at a point due to currents in circular poloidal conductor loops. - - P J Knight, CCFE, Culham Science Centre - - D Strickler, ORNL - - J Galambos, ORNL - - :param r_current_loop: Array of R coordinates of current loops (m) - :type r_current_loop: np.ndarray - :param z_current_loop: Array of Z coordinates of current loops (m) - :type z_current_loop: np.ndarray - :param c_current_loop: Array of currents in loops (A) - :type c_current_loop: np.ndarray - :param r_test_point: R coordinate of the test point (m) - :type r_test_point: float - :param z_test_point: Z coordinate of the test point (m) - :type z_test_point: float - - :returns: Tuple containing: + """Calculate the magnetic field and mutual inductance at a point due to currents in circular poloidal conductor loops. + + Parameters + ---------- + r_current_loop : np.ndarray + Array of R coordinates of current loops (m) + z_current_loop : np.ndarray + Array of Z coordinates of current loops (m) + c_current_loop : np.ndarray + Array of currents in loops (A) + r_test_point : float + R coordinate of the test point (m) + z_test_point : float + Z coordinate of the test point (m) + + Returns + ------- + tuple[np.ndarray, float, float, float] + Tuple containing: - ind_mutual_array: Mutual inductances (H) between each loop and the test point - b_test_point_radial: Radial field component at the test point (T) - b_test_point_vertical: Vertical field component at the test point (T) - web_test_point_poloidal: Poloidal flux at the test point (Wb) - :rtype: tuple[np.ndarray, float, float, float] - :notes: - - This routine calculates the magnetic field components and the poloidal flux at a given (R, Z) point, - given the locations and currents of a set of conductor loops. The mutual inductances between the loops - and a poloidal filament at the (R, Z) point of interest are also computed. + Notes + ----- + - This routine calculates the magnetic field components and the poloidal flux at a given (R, Z) point, + given the locations and currents of a set of conductor loops. The mutual inductances between the loops + and a poloidal filament at the (R, Z) point of interest are also computed. """ # Elliptic integral coefficients @@ -4399,36 +4431,37 @@ def calculate_b_field_at_point( def rsid(npts, brin, bzin, nfix, n_pf_coil_groups, ccls, bfix, gmat): """Computes the norm of the residual vectors. - author: P J Knight, CCFE, Culham Science Centre - author: D Strickler, ORNL - author: J Galambos, ORNL - author: P C Shipe, ORNL This routine calculates the residuals from the matrix equation for calculation of the currents in a group of ring coils. - :param npts: number of data points at which field is to be fixed; - should be <= nptsmx - :type npts: int - :param brin: field components at data points (T) - :type brin: numpy.ndarray - :param bzin: field components at data points (T) - :type bzin: numpy.ndarray - :param nfix: number of coils with fixed currents, <= nfixmx - :type nfix: int - :param n_pf_coil_groups: number of coil groups, where all coils in a group have the - same current, <= n_pf_groups_max - :type n_pf_coil_groups: int - :param ccls: coil currents in each group (A) - :type ccls: numpy.ndarray - :param bfix: work array - :type bfix: numpy.ndarray - :param gmat: work array - :type gmat: numpy.ndarray - :return: sum of squares of radial field residues (brssq), radial field - residue norm (brnrm), sum of squares of vertical field residues (bzssq), - vertical field residue norm (bznrm), sum of squares of elements of - residual vector (ssq) - :rtype: tuple[float, float, float, float, float] + Parameters + ---------- + npts : int + number of data points at which field is to be fixed; + should be <= nptsmx + brin : numpy.ndarray + field components at data points (T) + bzin : numpy.ndarray + field components at data points (T) + nfix : int + number of coils with fixed currents, <= nfixmx + n_pf_coil_groups : int + number of coil groups, where all coils in a group have the + same current, <= n_pf_groups_max + ccls : numpy.ndarray + coil currents in each group (A) + bfix : numpy.ndarray + work array + gmat : numpy.ndarray + work array + + Returns + ------- + tuple[float, float, float, float, float] + sum of squares of radial field residues (brssq), radial field + residue norm (brnrm), sum of squares of vertical field residues (bzssq), + vertical field residue norm (bznrm), sum of squares of elements of + residual vector (ssq) """ brnrm = 0.0e0 brssq = 0.0e0 @@ -4468,31 +4501,33 @@ def rsid(npts, brin, bzin, nfix, n_pf_coil_groups, ccls, bfix, gmat): def fixb(lrow1, npts, rpts, zpts, nfix, rfix, zfix, cfix): """Calculates the field from the fixed current loops. - author: P J Knight, CCFE, Culham Science Centre - author: D Strickler, ORNL - author: J Galambos, ORNL This routine calculates the fields at the points specified by (rpts,zpts) from the set of coils with fixed currents. - :param lrow1: row length of array bfix; should be >= nptsmx - :type lrow1: int - :param npts: number of data points at which field is to be fixed; - should be <= nptsmx - :type npts: int - :param rpts: coords of data points (m) - :type rpts: numpy.ndarray - :param zpts: coords of data points (m) - :type zpts: numpy.ndarray - :param nfix: number of coils with fixed currents, <= nfixmx - :type nfix: int - :param rfix: coordinates of coils with fixed currents (m) - :type rfix: numpy.ndarray - :param zfix: coordinates of coils with fixed currents (m) - :type zfix: numpy.ndarray - :param cfix: Fixed currents (A) - :type cfix: numpy.ndarray - :return: Fields at data points (T) - :rtype: numpy.ndarray + Parameters + ---------- + lrow1 : int + row length of array bfix; should be >= nptsmx + npts : int + number of data points at which field is to be fixed; + should be <= nptsmx + rpts : numpy.ndarray + coords of data points (m) + zpts : numpy.ndarray + coords of data points (m) + nfix : int + number of coils with fixed currents, <= nfixmx + rfix : numpy.ndarray + coordinates of coils with fixed currents (m) + zfix : numpy.ndarray + coordinates of coils with fixed currents (m) + cfix : numpy.ndarray + Fixed currents (A) + + Returns + ------- + numpy.ndarray + Fields at data points (T) """ bfix = np.zeros(lrow1) @@ -4536,46 +4571,49 @@ def mtrx( Set up the matrix equation to calculate the currents in a group of ring coils. - author: P J Knight, CCFE, Culham Science Centre - author: D Strickler, ORNL - author: J Galambos, ORNL - - :param lrow1: row length of arrays bfix, bvec, gmat, umat, vmat; should - be >= (2*nptsmx + n_pf_groups_max) - :type lrow1: int - :param lcol1: column length of arrays gmat, umat, vmat; should be >= - n_pf_groups_max - :type lcol1: int - :param npts: number of data points at which field is to be fixed; should - be <= nptsmx - :type npts: int - :param rpts: coords of data points (m) - :type rpts: numpy.ndarray - :param zpts: coords of data points (m) - :type zpts: numpy.ndarray - :param brin: field components at data points (T) - :type brin: numpy.ndarray - :param bzin: field components at data points (T) - :type bzin: numpy.ndarray - :param n_pf_coil_groups: number of coil groups, where all coils in a group have the - same current, <= n_pf_groups_max - :type n_pf_coil_groups: int - :param n_pf_coils_in_group: number of coils in each group, each value <= n_pf_coils_in_group_max - :type n_pf_coils_in_group: numpy.ndarray - :param r_pf_coil_middle_group_array: coords R(i,j), Z(i,j) of coil j in group i (m) - :type r_pf_coil_middle_group_array: numpy.ndarray - :param z_pf_coil_middle_group_array: coords R(i,j), Z(i,j) of coil j in group i (m) - :type z_pf_coil_middle_group_array: numpy.ndarray - :param alfa: smoothing parameter (0 = no smoothing, 1.0D-9 = large - smoothing) - :type alfa: float - :param bfix: Fields at data points (T) - :type bfix: numpy.ndarray - :return: actual number of rows to use, work array, work array, - Coordinates of conductor loops (m), Coordinates of conductor loops (m), - Currents in conductor loops (A), Mutual inductances (H) - :rtype: tuple[int, numpy.ndarray, numpy.ndarray, numpy.ndarray - numpy.ndarray, numpy.ndarray, numpy.ndarray] + + Parameters + ---------- + lrow1 : int + row length of arrays bfix, bvec, gmat, umat, vmat; should + be >= (2*nptsmx + n_pf_groups_max) + lcol1 : int + column length of arrays gmat, umat, vmat; should be >= + n_pf_groups_max + npts : int + number of data points at which field is to be fixed; should + be <= nptsmx + rpts : numpy.ndarray + coords of data points (m) + zpts : numpy.ndarray + coords of data points (m) + brin : numpy.ndarray + field components at data points (T) + bzin : numpy.ndarray + field components at data points (T) + n_pf_coil_groups : int + number of coil groups, where all coils in a group have the + same current, <= n_pf_groups_max + n_pf_coils_in_group : numpy.ndarray + number of coils in each group, each value <= n_pf_coils_in_group_max + r_pf_coil_middle_group_array : numpy.ndarray + coords R(i,j), Z(i,j) of coil j in group i (m) + z_pf_coil_middle_group_array : numpy.ndarray + coords R(i,j), Z(i,j) of coil j in group i (m) + alfa : float + smoothing parameter (0 = no smoothing, 1.0D-9 = large + smoothing) + bfix : numpy.ndarray + Fields at data points (T) + n_pf_coils_in_group_max : + + + Returns + ------- + : + actual number of rows to use, work array, work array, + Coordinates of conductor loops (m), Coordinates of conductor loops (m), + Currents in conductor loops (A), Mutual inductances (H) """ bvec = np.zeros(lrow1) gmat = np.zeros((lrow1, lcol1)) diff --git a/process/physics.py b/process/physics.py index 3398a75568..ba51114262 100644 --- a/process/physics.py +++ b/process/physics.py @@ -46,18 +46,32 @@ def rether( ): """Routine to find the equilibration power between the ions and electrons - author: P J Knight, CCFE, Culham Science Centre - alphan : input real : density profile index - alphat : input real : temperature profile index - nd_plasma_electrons_vol_avg : input real : electron density (/m3) - dlamie : input real : ion-electron coulomb logarithm - te : input real : electron temperature (keV) - temp_plasma_ion_vol_avg_kev : input real : ion temperature (keV) - n_charge_plasma_effective_mass_weighted_vol_avg : input real : mass weighted plasma effective charge - pden_ion_electron_equilibration_mw : output real : ion/electron equilibration power (MW/m3) This routine calculates the equilibration power between the ions and electrons. Unknown origin + + Parameters + ---------- + alphan : + density profile index + alphat : + temperature profile index + nd_plasma_electrons_vol_avg : + electron density (/m3) + dlamie : + ion-electron coulomb logarithm + te : + electron temperature (keV) + temp_plasma_ion_vol_avg_kev : + ion temperature (keV) + n_charge_plasma_effective_mass_weighted_vol_avg : + mass weighted plasma effective charge + + Returns + ------- + pden_ion_electron_equilibration_mw : + ion/electron equilibration power (MW/m3) + """ profie = (1.0 + alphan) ** 2 / ( (2.0 * alphan - 0.5 * alphat + 1.0) * np.sqrt(1.0 + alphat) @@ -82,28 +96,37 @@ def rether( def _plascar_bpol( aspect: float, eps: float, kappa: float, delta: float ) -> tuple[float, float, float, float]: - """ - Calculate the poloidal field coefficients for determining the plasma current + """Calculate the poloidal field coefficients for determining the plasma current and poloidal field. - Parameters: - - aspect: float, plasma aspect ratio - - eps: float, inverse aspect ratio - - kappa: float, plasma elongation - - delta: float, plasma triangularity - - Returns: - - Tuple[float, float, float, float], coefficients ff1, ff2, d1, d2 This internal function calculates the poloidal field coefficients, which is used to calculate the poloidal field and the plasma current. - References: - - Peng, Y. K. M., Galambos, J. D., & Shipe, P. C. (1992). - 'Small Tokamaks for Fusion Technology Testing'. Fusion Technology, 21(3P2A), - 1729-1738. https://doi.org/10.13182/FST92-A29971 - - J D Galambos, STAR Code : Spherical Tokamak Analysis and Reactor Code, - unpublished internal Oak Ridge document + Parameters + ---------- + aspect : + plasma aspect ratio + eps : + inverse aspect ratio + kappa : + plasma elongation + delta : + plasma triangularity + + Returns + ------- + : + coefficients ff1, ff2, d1, d2 + + References + ---------- + - Peng, Y. K. M., Galambos, J. D., & Shipe, P. C. (1992). + 'Small Tokamaks for Fusion Technology Testing'. Fusion Technology, 21(3P2A), + 1729-1738. https://doi.org/10.13182/FST92-A29971 + - J D Galambos, STAR Code : Spherical Tokamak Analysis and Reactor Code, + unpublished internal Oak Ridge document + """ # Original coding, only suitable for TARTs [STAR Code] @@ -146,35 +169,50 @@ def calculate_poloidal_field( perim: float, rmu0: float, ) -> float: - """ - Function to calculate poloidal field from the plasma current - - Parameters: - - i_plasma_current: int, current scaling model to use - - ip: float, plasma current (A) - - q95: float, 95% flux surface safety factor - - aspect: float, plasma aspect ratio - - eps: float, inverse aspect ratio - - b_plasma_toroidal_on_axis: float, toroidal field on axis (T) - - kappa: float, plasma elongation - - delta: float, plasma triangularity - - perim: float, plasma perimeter (m) - - rmu0: float, vacuum permeability (H/m) - - Returns: - - float, poloidal field in Tesla + """Function to calculate poloidal field from the plasma current This function calculates the poloidal field from the plasma current in Tesla, using a simple calculation using Ampere's law for conventional tokamaks, or for TARTs, a scaling from Peng, Galambos and Shipe (1992). - References: - - J D Galambos, STAR Code : Spherical Tokamak Analysis and Reactor Code, - unpublished internal Oak Ridge document - - Peng, Y. K. M., Galambos, J. D., & Shipe, P. C. (1992). - 'Small Tokamaks for Fusion Technology Testing'. Fusion Technology, 21(3P2A), - 1729-1738. https://doi.org/10.13182/FST92-A29971 + Parameters + ---------- + i_plasma_current : + current scaling model to use + ip : + plasma current (A) + q95 : + 95% flux surface safety factor + aspect : + plasma aspect ratio + eps : + inverse aspect ratio + b_plasma_toroidal_on_axis : + toroidal field on axis (T) + kappa : + plasma elongation + delta : + plasma triangularity + perim : + plasma perimeter (m) + rmu0 : + vacuum permeability (H/m) + + Returns + ------- + : + poloidal field in Tesla + + + References + ---------- + - J D Galambos, STAR Code : Spherical Tokamak Analysis and Reactor Code, + unpublished internal Oak Ridge document + - Peng, Y. K. M., Galambos, J. D., & Shipe, P. C. (1992). + 'Small Tokamaks for Fusion Technology Testing'. Fusion Technology, 21(3P2A), + 1729-1738. https://doi.org/10.13182/FST92-A29971 + """ # Use Ampere's law using the plasma poloidal cross-section if i_plasma_current != 2: @@ -191,20 +229,22 @@ def calculate_poloidal_field( def calculate_current_coefficient_peng( eps: float, len_plasma_poloidal: float, rminor: float ) -> float: - """ - Calculate the plasma current scaling coefficient for the Peng scaling from the STAR code. - - :param eps: Plasma inverse aspect ratio. - :type eps: float - :param len_plasma_poloidal: Plasma poloidal perimeter length [m]. - :type len_plasma_poloidal: float - :param rminor: Plasma minor radius [m]. - :type rminor: float + """Calculate the plasma current scaling coefficient for the Peng scaling from the STAR code. + + Parameters + ---------- + eps : float + Plasma inverse aspect ratio. + len_plasma_poloidal : float + Plasma poloidal perimeter length [m]. + rminor : float + Plasma minor radius [m]. + + Returns + ------- + float + The plasma current scaling coefficient. - :return: The plasma current scaling coefficient. - :rtype: float - - :references: None """ return ( @@ -223,32 +263,45 @@ def calculate_plasma_current_peng( kappa: float, delta: float, ) -> float: - """ - Function to calculate plasma current (Peng scaling from the STAR code) - - Parameters: - - q95: float, 95% flux surface safety factor - - aspect: float, plasma aspect ratio - - eps: float, inverse aspect ratio - - rminor: float, plasma minor radius (m) - - b_plasma_toroidal_on_axis: float, toroidal field on axis (T) - - kappa: float, plasma elongation - - delta: float, plasma triangularity - - Returns: - - float, plasma current in MA + """Function to calculate plasma current (Peng scaling from the STAR code) This function calculates the plasma current in MA, using a scaling from Peng, Galambos and Shipe (1992). It is primarily used for Tight Aspect Ratio Tokamaks and is selected via i_plasma_current=2. - References: - - J D Galambos, STAR Code : Spherical Tokamak Analysis and Reactor Code, - unpublished internal Oak Ridge document - - Peng, Y. K. M., Galambos, J. D., & Shipe, P. C. (1992). - 'Small Tokamaks for Fusion Technology Testing'. Fusion Technology, 21(3P2A), - 1729-1738. https://doi.org/10.13182/FST92-A29971 + Parameters + ---------- + q95 : + 95% flux surface safety factor + aspect : + plasma aspect ratio + eps : + inverse aspect ratio + rminor : + plasma minor radius (m) + b_plasma_toroidal_on_axis : + toroidal field on axis (T) + kappa : + plasma elongation + delta : + plasma triangularity + + + Returns + ------- + : + plasma current in MA + + + References + ---------- + - J D Galambos, STAR Code : Spherical Tokamak Analysis and Reactor Code, + unpublished internal Oak Ridge document + - Peng, Y. K. M., Galambos, J. D., & Shipe, P. C. (1992). + 'Small Tokamaks for Fusion Technology Testing'. Fusion Technology, 21(3P2A), + 1729-1738. https://doi.org/10.13182/FST92-A29971 + """ # Transform q95 to qbar @@ -275,23 +328,31 @@ def calculate_plasma_current_peng( def calculate_current_coefficient_ipdg89( eps: float, kappa95: float, triang95: float ) -> float: - """ - Calculate the fq coefficient from the IPDG89 guidlines used in the plasma current scaling. - - Parameters: - - eps: float, plasma inverse aspect ratio - - kappa95: float, plasma elongation 95% - - triang95: float, plasma triangularity 95% - - Returns: - - float, the fq plasma current coefficient + """Calculate the fq coefficient from the IPDG89 guidlines used in the plasma current scaling. This function calculates the fq coefficient used in the IPDG89 plasma current scaling, based on the given plasma parameters. - References: - - N.A. Uckan and ITER Physics Group, 'ITER Physics Design Guidelines: 1989' - - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 + Parameters + ---------- + eps : + plasma inverse aspect ratio + kappa95 : + plasma elongation 95% + triang95 : + plasma triangularity 95% + + Returns + ------- + : + the fq plasma current coefficient + + + References + ---------- + - N.A. Uckan and ITER Physics Group, 'ITER Physics Design Guidelines: 1989' + - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 + """ return ( 0.5 @@ -305,22 +366,30 @@ def calculate_current_coefficient_ipdg89( def calculate_current_coefficient_todd( eps: float, kappa95: float, triang95: float, model: int ) -> float: - """ - Calculate the fq coefficient used in the two Todd plasma current scalings. - - Parameters: - - eps: float, plasma inverse aspect ratio - - kappa95: float, plasma elongation 95% - - triang95: float, plasma triangularity 95% - - Returns: - - float, the fq plasma current coefficient + """Calculate the fq coefficient used in the two Todd plasma current scalings. This function calculates the fq coefficient based on the given plasma parameters for the two Todd scalings. - References: - - D.C.Robinson and T.N.Todd, Plasma and Contr Fusion 28 (1986) 1181 - - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 + Parameters + ---------- + eps : + plasma inverse aspect ratio + kappa95 : + plasma elongation 95% + triang95 : + plasma triangularity 95% + model: + + Returns + ------- + : + the fq plasma current coefficient + + References + ---------- + - D.C.Robinson and T.N.Todd, Plasma and Contr Fusion 28 (1986) 1181 + - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 + """ # Calculate the Todd scaling based on the model base_scaling = ( @@ -346,29 +415,42 @@ def calculate_current_coefficient_hastie( pres_plasma_on_axis: float, rmu0: float, ) -> float: - """ - Routine to calculate the f_q coefficient for the Connor-Hastie model used for scaling the plasma current. - - Parameters: - - alphaj: float, the current profile index - - alphap: float, the pressure profile index - - b_plasma_toroidal_on_axis: float, the toroidal field on axis (T) - - delta95: float, the plasma triangularity 95% - - eps: float, the inverse aspect ratio - - kappa95: float, the plasma elongation 95% - - pres_plasma_on_axis: float, the central plasma pressure (Pa) - - rmu0: float, the vacuum permeability (H/m) - - Returns: - - float, the F coefficient + """Routine to calculate the f_q coefficient for the Connor-Hastie model used for scaling the plasma current. This routine calculates the f_q coefficient used for scaling the plasma current, using the Connor-Hastie scaling + + Parameters + ---------- + alphaj : + the current profile index + alphap : + the pressure profile index + b_plasma_toroidal_on_axis : + the toroidal field on axis (T) + delta95 : + the plasma triangularity 95% + eps : + the inverse aspect ratio + kappa95 : + the plasma elongation 95% + pres_plasma_on_axis : + the central plasma pressure (Pa) + rmu0 : + the vacuum permeability (H/m) + + Returns + ------- + : + the F coefficient + + Reference: - - J.W.Connor and R.J.Hastie, Culham Lab Report CLM-M106 (1985). - https://scientific-publications.ukaea.uk/wp-content/uploads/CLM-M106-1.pdf - - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 + - J.W.Connor and R.J.Hastie, Culham Lab Report CLM-M106 (1985). + https://scientific-publications.ukaea.uk/wp-content/uploads/CLM-M106-1.pdf + - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 + """ # Exponent in Connor-Hastie current profile lamda = alphaj @@ -423,21 +505,27 @@ def calculate_current_coefficient_sauter( kappa: float, triang: float, ) -> float: - """ - Routine to calculate the f_q coefficient for the Sauter model used for scaling the plasma current. - - Parameters: - - eps: float, inverse aspect ratio - - kappa: float, plasma elongation at the separatrix - - triang: float, plasma triangularity at the separatrix - - Returns: - - float, the fq coefficient + """Routine to calculate the f_q coefficient for the Sauter model used for scaling the plasma current. + + Parameters + ---------- + eps : + inverse aspect ratio + kappa : + plasma elongation at the separatrix + triang : + plasma triangularity at the separatrix + + Returns + ------- + : + the fq coefficient Reference: - - O. Sauter, Geometric formulas for system codes including the effect of negative triangularity, - Fusion Engineering and Design, Volume 112, 2016, Pages 633-645, - ISSN 0920-3796, https://doi.org/10.1016/j.fusengdes.2016.04.033. + - O. Sauter, Geometric formulas for system codes including the effect of negative triangularity, + Fusion Engineering and Design, Volume 112, 2016, Pages 633-645, + ISSN 0920-3796, https://doi.org/10.1016/j.fusengdes.2016.04.033. + """ w07 = 1.0 # zero squareness - can be modified later if required @@ -455,22 +543,30 @@ def calculate_current_coefficient_sauter( def calculate_current_coefficient_fiesta( eps: float, kappa: float, triang: float ) -> float: - """ - Calculate the fq coefficient used in the FIESTA plasma current scaling. + """Calculate the fq coefficient used in the FIESTA plasma current scaling. - Parameters: - - eps: float, plasma inverse aspect ratio - - kappa: float, plasma elongation at the separatrix - - triang: float, plasma triangularity at the separatrix + This function calculates the fq coefficient based on the given plasma parameters for the FIESTA scaling. - Returns: - - float, the fq plasma current coefficient + Parameters + ---------- + eps : + plasma inverse aspect ratio + kappa : + plasma elongation at the separatrix + triang : + plasma triangularity at the separatrix + + Returns + ------- + : + the fq plasma current coefficient - This function calculates the fq coefficient based on the given plasma parameters for the FIESTA scaling. - References: - - S.Muldrew et.al,“PROCESS”: Systems studies of spherical tokamaks, Fusion Engineering and Design, - Volume 154, 2020, 111530, ISSN 0920-3796, https://doi.org/10.1016/j.fusengdes.2020.111530. + References + ---------- + - S.Muldrew et.al,“PROCESS”: Systems studies of spherical tokamaks, Fusion Engineering and Design, + Volume 154, 2020, 111530, ISSN 0920-3796, https://doi.org/10.1016/j.fusengdes.2020.111530. + """ return 0.538 * (1.0 + 2.440 * eps**2.736) * kappa**2.154 * triang**0.060 @@ -495,28 +591,44 @@ def _nevins_integral( q95: float, beta_toroidal: float, ) -> float: - """ - Integrand function for Nevins et al bootstrap current scaling. - - Parameters: - - y: float, abscissa of integration, normalized minor radius - - nd_plasma_electrons_vol_avg: float, volume averaged electron density (/m^3) - - te: float, volume averaged electron temperature (keV) - - b_plasma_toroidal_on_axis: float, toroidal field on axis (T) - - rminor: float, plasma minor radius (m) - - rmajor: float, plasma major radius (m) - - zeff: float, plasma effective charge - - alphat: float, temperature profile index - - alphan: float, density profile index - - q0: float, normalized safety factor at the magnetic axis - - q95: float, normalized safety factor at 95% of the plasma radius - - beta_toroidal: float, Toroidal plasma beta - - Returns: - - float, the integrand value + """Integrand function for Nevins et al bootstrap current scaling. This function calculates the integrand function for the Nevins et al bootstrap current scaling. + Parameters + ---------- + y : + abscissa of integration, normalized minor radius + nd_plasma_electrons_vol_avg : + volume averaged electron density (/m^3) + te : + volume averaged electron temperature (keV) + b_plasma_toroidal_on_axis : + toroidal field on axis (T) + rminor : + plasma minor radius (m) + rmajor : + plasma major radius (m) + zeff : + plasma effective charge + alphat : + temperature profile index + alphan : + density profile index + q0 : + normalized safety factor at the magnetic axis + q95 : + normalized safety factor at 95% of the plasma radius + beta_toroidal : + Toroidal plasma beta + + + Returns + ------- + type + - float, the integrand value + + Reference: See appendix of: Keii Gi, Makoto Nakamura, Kenji Tobita, Yasushi Ono, Bootstrap current fraction scaling for a tokamak reactor design study, @@ -567,44 +679,58 @@ def _nevins_integral( @nb.jit(nopython=True, cache=True) def diamagnetic_fraction_hender(beta: float) -> float: - """ - Calculate the diamagnetic fraction based on the Hender fit. + """Calculate the diamagnetic fraction based on the Hender fit. + + Parameters + ---------- + beta : + the plasma beta value - Parameters: - - beta: float, the plasma beta value + Returns + ------- + : + the diamagnetic fraction - Returns: - - float, the diamagnetic fraction """ return beta / 2.8 @nb.jit(nopython=True, cache=True) def diamagnetic_fraction_scene(beta: float, q95: float, q0: float) -> float: - """ - Calculate the diamagnetic fraction based on the SCENE fit by Tim Hender. - - Parameters: - - beta: float, the plasma beta value - - q95: float, the normalized safety factor at 95% of the plasma radius - - q0: float, the normalized safety factor at the magnetic axis - - Returns: - - float, the diamagnetic fraction + """Calculate the diamagnetic fraction based on the SCENE fit by Tim Hender. + + Parameters + ---------- + beta : + the plasma beta value + q95 : + the normalized safety factor at 95% of the plasma radius + q0 : + the normalized safety factor at the magnetic axis + + Returns + ------- + : + the diamagnetic fraction """ return beta * (0.1 * q95 / q0 + 0.44) * 0.414 @nb.jit(nopython=True, cache=True) def ps_fraction_scene(beta: float) -> float: - """ - Calculate the Pfirsch-Schlüter fraction based on the SCENE fit by Tim Hender 2019. + """Calculate the Pfirsch-Schlüter fraction based on the SCENE fit by Tim Hender 2019. + + Parameters + ---------- + beta : + the plasma beta value - Parameters: - - beta: float, the plasma beta value - Returns: - - float, the Pfirsch-Schlüter current fraction + Returns + ------- + : + the Pfirsch-Schlüter current fraction + """ return -9e-2 * beta @@ -618,26 +744,32 @@ def ps_fraction_scene(beta: float) -> float: def _coulomb_logarithm_sauter( radial_elements: int, tempe: np.ndarray, ne: np.ndarray ) -> np.ndarray: - """ - Calculate the Coulomb logarithm used in the arrays for the Sauter bootstrap current scaling. - - Parameters: - - radial_elements: np.ndarray, the radial element indexes in the range 1 to nr - - tempe: np.ndarray, the electron temperature array - - ne: np.ndarray, the electron density array - - Returns: - - np.ndarray, the Coulomb logarithm at each array point + """Calculate the Coulomb logarithm used in the arrays for the Sauter bootstrap current scaling. This function calculates the Coulomb logarithm, which is valid for e-e collisions (T_e > 0.01 keV) and for e-i collisions (T_e > 0.01*Zeff^2) (Alexander, 9/5/1994). + Parameters + ---------- + radial_elements : + the radial element indexes in the range 1 to nr + tempe : + the electron temperature array + ne : + the electron density array + + Returns + ------- + type + - np.ndarray, the Coulomb logarithm at each array point + Reference: - - C. A. Ordonez, M. I. Molina; - Evaluation of the Coulomb logarithm using cutoff and screened Coulomb interaction potentials. - Phys. Plasmas 1 August 1994; 1 (8): 2515-2518. https://doi.org/10.1063/1.870578 - - Y. R. Shen, “Recent advances in nonlinear optics,” Reviews of Modern Physics, vol. 48, no. 1, - pp. 1-32, Jan. 1976, doi: https://doi.org/10.1103/revmodphys.48.1. + - C. A. Ordonez, M. I. Molina; + Evaluation of the Coulomb logarithm using cutoff and screened Coulomb interaction potentials. + Phys. Plasmas 1 August 1994; 1 (8): 2515-2518. https://doi.org/10.1063/1.870578 + - Y. R. Shen, “Recent advances in nonlinear optics,” Reviews of Modern Physics, vol. 48, no. 1, + pp. 1-32, Jan. 1976, doi: https://doi.org/10.1103/revmodphys.48.1. + """ return ( 15.9 - 0.5 * np.log(ne[radial_elements - 1]) + np.log(tempe[radial_elements - 1]) @@ -648,21 +780,28 @@ def _coulomb_logarithm_sauter( def _electron_collisions_sauter( radial_elements: np.ndarray, tempe: np.ndarray, ne: np.ndarray ) -> np.ndarray: - """ - Calculate the frequency of electron-electron collisions used in the arrays for the Sauter bootstrap current scaling. + """Calculate the frequency of electron-electron collisions used in the arrays for the Sauter bootstrap current scaling. + + This function calculates the frequency of electron-electron collisions - Parameters: - - radial_elements: np.ndarray, the radial element index in the range 1 to nr - - tempe: np.ndarray, the electron temperature array - - ne: np.ndarray, the electron density array + Parameters + ---------- + radial_elements : + the radial element indexes in the range 1 to nr + tempe : + the electron temperature array + ne : + the electron density array - Returns: - - float, the frequency of electron-electron collisions (Hz) + Returns + ------- + : + the frequency of electron-electron collisions (Hz) - This function calculates the frequency of electron-electron collisions Reference: - - Yushmanov, 25th April 1987 (?), updated by Pereverzev, 9th November 1994 (?) + - Yushmanov, 25th April 1987 (?), updated by Pereverzev, 9th November 1994 (?) + """ return ( 670.0 @@ -682,23 +821,33 @@ def _electron_collisionality_sauter( tempe: np.ndarray, ne: np.ndarray, ) -> np.ndarray: - """ - Calculate the electron collisionality used in the arrays for the Sauter bootstrap current scaling. - - Parameters: - - radial_elements: np.ndarray, the radial element index in the range 1 to nr - - rmajor: float, the plasma major radius (m) - - zeff: np.ndarray, the effective charge array - - inverse_q: np.ndarray, inverse safety factor profile - - sqeps: np.ndarray, the square root of the inverse aspect ratio array - - tempe: np.ndarray, the electron temperature array - - ne: np.ndarray, the electron density array - - Returns: - - np.ndarray, the relative frequency of electron collisions + """Calculate the electron collisionality used in the arrays for the Sauter bootstrap current scaling. + + Parameters + ---------- + radial_elements : + the radial element index in the range 1 to nr + rmajor : + the plasma major radius (m) + zeff : + the effective charge array + inverse_q : + inverse safety factor profile + sqeps : + the square root of the inverse aspect ratio array + tempe : + the electron temperature array + ne : + the electron density array + + Returns + ------- + : + the relative frequency of electron collisions Reference: - - Yushmanov, 30th April 1987 (?) + - Yushmanov, 30th April 1987 (?) + """ return ( _electron_collisions_sauter(radial_elements, tempe, ne) @@ -722,23 +871,27 @@ def _ion_collisions_sauter( tempi: np.ndarray, amain: np.ndarray, ) -> np.ndarray: - """ - Calculate the full frequency of ion collisions used in the arrays for the Sauter bootstrap current scaling. - - Parameters: - - radial_elements: np.ndarray, the radial element indexes in the range 1 to nr - - zeff: np.ndarray, the effective charge array - - ni: np.ndarray, the ion density array - - tempi: np.ndarray, the ion temperature array - - amain: np.ndarray, the atomic mass of the main ion species array - - Returns: - - np.ndarray, the full frequency of ion collisions (Hz) + """Calculate the full frequency of ion collisions used in the arrays for the Sauter bootstrap current scaling. This function calculates the full frequency of ion collisions using the Coulomb logarithm of 15. - Reference: - - None + Parameters + ---------- + radial_elements : + the radial element indexes in the range 1 to nr + zeff : + the effective charge array + ni : + the ion density array + tempi : + the ion temperature array + amain : + the atomic mass of the main ion species array + + Returns + ------- + : + the full frequency of ion collisions (Hz) """ return ( zeff[radial_elements - 1] ** 4 @@ -762,24 +915,31 @@ def _ion_collisionality_sauter( zeff: np.ndarray, ni: np.ndarray, ) -> float: - """ - Calculate the ion collisionality to be used in the Sauter bootstrap current scaling. - - Parameters: - - radial_elements: np.ndarray, the radial element indexes in the range 1 to nr - - rmajor: float, the plasma major radius (m) - - inverse_q: np.ndarray, inverse safety factor profile - - sqeps: np.ndarray, the square root of the inverse aspect ratio profile - - tempi: np.ndarray, the ion temperature profile (keV) - - amain: np.ndarray, the atomic mass of the main ion species profile - - zeff: np.ndarray, the effective charge of the main ion species - - ni: np.ndarray, the ion density profile (/m^3) - - Returns: - - float, the ion collisionality - - Reference: - - None + """Calculate the ion collisionality to be used in the Sauter bootstrap current scaling. + + Parameters + ---------- + radial_elements : + the radial element indexes in the range 1 to nr + rmajor : + the plasma major radius (m) + inverse_q : + inverse safety factor profile + sqeps : + the square root of the inverse aspect ratio profile + tempi : + the ion temperature profile (keV) + amain : + the atomic mass of the main ion species profile + zeff : + the effective charge of the main ion species + ni : + the ion density profile (/m^3) + + Returns + ------- + : + the ion collisionality """ return ( 3.2e-6 @@ -809,36 +969,53 @@ def _calculate_l31_coefficient( zeff: np.ndarray, sqeps: np.ndarray, ) -> float: - """ - L31 coefficient before Grad(ln(ne)) in the Sauter bootstrap scaling. - - Parameters: - - radial_elements: np.ndarray, radial element indexes in range 2 to nr - - number_of_elements: int, maximum value of radial_elements - - rmajor: float, plasma major radius (m) - - b_plasma_toroidal_on_axis: float, toroidal field on axis (T) - - triang: float, plasma triangularity - - ne: np.ndarray, electron density profile (/m^3) - - ni: np.ndarray, ion density profile (/m^3) - - tempe: np.ndarray, electron temperature profile (keV) - - tempi: np.ndarray, ion temperature profile (keV) - - inverse_q: np.ndarray, inverse safety factor profile - - rho: np.ndarray, normalized minor radius profile - - zeff: np.ndarray, effective charge profile - - sqeps: np.ndarray, square root of inverse aspect ratio profile - - Returns: - - float, the coefficient scaling grad(ln(ne)) in the Sauter bootstrap current scaling. - - This function calculates the coefficient scaling grad(ln(ne)) in the Sauter bootstrap current scaling. + """L31 coefficient before Grad(ln(ne)) in the Sauter bootstrap scaling. + + + Parameters + ---------- + radial_elements : + radial element indexes in range 2 to nr + number_of_elements : + maximum value of radial_elements + rmajor : + plasma major radius (m) + b_plasma_toroidal_on_axis : + toroidal field on axis (T) + triang : + plasma triangularity + ne : + electron density profile (/m^3) + ni : + ion density profile (/m^3) + tempe : + electron temperature profile (keV) + tempi : + ion temperature profile (keV) + inverse_q : + inverse safety factor profile + rho : + normalized minor radius profile + zeff : + effective charge profile + sqeps : + square root of inverse aspect ratio profile + + Returns + ------- + type + - float, the coefficient scaling grad(ln(ne)) in the Sauter bootstrap current scaling. + + This function calculates the coefficient scaling grad(ln(ne)) in the Sauter bootstrap current scaling. Reference: - - O. Sauter, C. Angioni, Y. R. Lin-Liu; - Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime. - Phys. Plasmas 1 July 1999; 6 (7): 2834-2839. https://doi.org/10.1063/1.873240 - - O. Sauter, C. Angioni, Y. R. Lin-Liu; Erratum: - Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime - [Phys. Plasmas 6, 2834 (1999)]. Phys. Plasmas 1 December 2002; 9 (12): 5140. https://doi.org/10.1063/1.1517052 + - O. Sauter, C. Angioni, Y. R. Lin-Liu; + Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime. + Phys. Plasmas 1 July 1999; 6 (7): 2834-2839. https://doi.org/10.1063/1.873240 + - O. Sauter, C. Angioni, Y. R. Lin-Liu; Erratum: + Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime + [Phys. Plasmas 6, 2834 (1999)]. Phys. Plasmas 1 December 2002; 9 (12): 5140. https://doi.org/10.1063/1.1517052 + """ # Prevents first element being 0 charge_profile = zeff[radial_elements - 1] @@ -894,36 +1071,55 @@ def _calculate_l31_32_coefficient( zeff: np.ndarray, sqeps: np.ndarray, ) -> float: - """ - L31 & L32 coefficient before Grad(ln(Te)) in the Sauter bootstrap scaling. - - Parameters: - - radial_elements: np.ndarray, radial element indexes in range 2 to nr - - number_of_elements: int, maximum value of radial_elements - - rmajor: float, plasma major radius (m) - - b_plasma_toroidal_on_axis: float, toroidal field on axis (T) - - triang: float, plasma triangularity - - ne: np.ndarray, electron density profile (/m^3) - - ni: np.ndarray, ion density profile (/m^3) - - tempe: np.ndarray, electron temperature profile (keV) - - tempi: np.ndarray, ion temperature profile (keV) - - inverse_q: np.ndarray, inverse safety factor profile - - rho: np.ndarray, normalized minor radius profile - - zeff: np.ndarray, effective charge profile - - sqeps: np.ndarray, square root of inverse aspect ratio profile - - Returns: - - float, the L31 & L32 coefficient scaling grad(ln(Te)) in the Sauter bootstrap current scaling. + """L31 & L32 coefficient before Grad(ln(Te)) in the Sauter bootstrap scaling. This function calculates the coefficient scaling grad(ln(Te)) in the Sauter bootstrap current scaling. + + Parameters + ---------- + radial_elements : + radial element indexes in range 2 to nr + number_of_elements : + maximum value of radial_elements + rmajor : + plasma major radius (m) + b_plasma_toroidal_on_axis : + toroidal field on axis (T) + triang : + plasma triangularity + ne : + electron density profile (/m^3) + ni : + ion density profile (/m^3) + tempe : + electron temperature profile (keV) + tempi : + ion temperature profile (keV) + inverse_q : + inverse safety factor profile + rho : + normalized minor radius profile + zeff : + effective charge profile + sqeps : + square root of inverse aspect ratio profile + + + Returns + ------- + : + the L31 & L32 coefficient scaling grad(ln(Te)) in the Sauter bootstrap current scaling. + + Reference: - - O. Sauter, C. Angioni, Y. R. Lin-Liu; - Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime. - Phys. Plasmas 1 July 1999; 6 (7): 2834-2839. https://doi.org/10.1063/1.873240 - - O. Sauter, C. Angioni, Y. R. Lin-Liu; Erratum: - Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime - [Phys. Plasmas 6, 2834 (1999)]. Phys. Plasmas 1 December 2002; 9 (12): 5140. https://doi.org/10.1063/1.1517052 + - O. Sauter, C. Angioni, Y. R. Lin-Liu; + Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime. + Phys. Plasmas 1 July 1999; 6 (7): 2834-2839. https://doi.org/10.1063/1.873240 + - O. Sauter, C. Angioni, Y. R. Lin-Liu; Erratum: + Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime + [Phys. Plasmas 6, 2834 (1999)]. Phys. Plasmas 1 December 2002; 9 (12): 5140. https://doi.org/10.1063/1.1517052 + """ # Prevents first element being 0 @@ -1058,38 +1254,59 @@ def _calculate_l34_alpha_31_coefficient( rho: np.ndarray, zeff: np.ndarray, ) -> float: - """ - L34, alpha and L31 coefficient before Grad(ln(Ti)) in the Sauter bootstrap scaling. - - Parameters: - - radial_elements: np.ndarray, radial element indexes in range 2 to nr - - number_of_elements: int, maximum value of radial_elements - - rmajor: float, plasma major radius (m) - - b_plasma_toroidal_on_axis: float, toroidal field on axis (T) - - triang: float, plasma triangularity - - inverse_q: np.ndarray, inverse safety factor profile - - sqeps: np.ndarray, square root of inverse aspect ratio profile - - tempi: np.ndarray, ion temperature profile (keV) - - tempe: np.ndarray, electron temperature profile (keV) - - amain: float, atomic mass of the main ion - - zmain: float, charge of the main ion - - ni: np.ndarray, ion density profile (/m^3) - - ne: np.ndarray, electron density profile (/m^3) - - rho: np.ndarray, normalized minor radius profile - - zeff: np.ndarray, effective charge profile - - Returns: - - float, the the L34, alpha and L31 coefficient scaling grad(ln(Ti)) in the Sauter bootstrap current scaling. + """L34, alpha and L31 coefficient before Grad(ln(Ti)) in the Sauter bootstrap scaling. This function calculates the coefficient scaling grad(ln(Ti)) in the Sauter bootstrap current scaling. + + Parameters + ---------- + radial_elements : + radial element indexes in range 2 to nr + number_of_elements : + maximum value of radial_elements + rmajor : + plasma major radius (m) + b_plasma_toroidal_on_axis : + toroidal field on axis (T) + triang : + plasma triangularity + inverse_q : + inverse safety factor profile + sqeps : + square root of inverse aspect ratio profile + tempi : + ion temperature profile (keV) + tempe : + electron temperature profile (keV) + amain : + atomic mass of the main ion + zmain : + charge of the main ion + ni : + ion density profile (/m^3) + ne : + electron density profile (/m^3) + rho : + normalized minor radius profile + zeff : + effective charge profile + + + Returns + ------- + : + the L34, alpha and L31 coefficient scaling grad(ln(Ti)) in the Sauter bootstrap current scaling. + + Reference: - - O. Sauter, C. Angioni, Y. R. Lin-Liu; - Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime. - Phys. Plasmas 1 July 1999; 6 (7): 2834-2839. https://doi.org/10.1063/1.873240 - - O. Sauter, C. Angioni, Y. R. Lin-Liu; Erratum: - Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime - [Phys. Plasmas 6, 2834 (1999)]. Phys. Plasmas 1 December 2002; 9 (12): 5140. https://doi.org/10.1063/1.1517052 + - O. Sauter, C. Angioni, Y. R. Lin-Liu; + Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime. + Phys. Plasmas 1 July 1999; 6 (7): 2834-2839. https://doi.org/10.1063/1.873240 + - O. Sauter, C. Angioni, Y. R. Lin-Liu; Erratum: + Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime + [Phys. Plasmas 6, 2834 (1999)]. Phys. Plasmas 1 December 2002; 9 (12): 5140. https://doi.org/10.1063/1.1517052 + """ # Prevents first element being 0 charge_profile = zeff[radial_elements - 1] @@ -1210,24 +1427,32 @@ def _beta_poloidal_sauter( inverse_q: np.ndarray, rho: np.ndarray, ) -> np.ndarray: - """ - Calculate the local beta poloidal using only electron profiles for the Sauter bootstrap current scaling. - - Parameters: - - radial_elements: np.ndarray, radial element indexes in range 1 to nr - - nr: int, maximum value of radial_elements - - rmajor: float, plasma major radius (m) - - b_plasma_toroidal_on_axis: float, toroidal field on axis (T) - - ne: np.ndarray, electron density profile (/m^3) - - tempe: np.ndarray, electron temperature profile (keV) - - inverse_q: np.ndarray, inverse safety factor profile - - rho: np.ndarray, normalized minor radius profile - - Returns: - - np.ndarray, the local beta poloidal - - Reference: - - None + """Calculate the local beta poloidal using only electron profiles for the Sauter bootstrap current scaling. + + Parameters + ---------- + radial_elements : + radial element indexes in range 1 to nr + nr : + maximum value of radial_elements + rmajor : + plasma major radius (m) + b_plasma_toroidal_on_axis : + toroidal field on axis (T) + ne : + electron density profile (/m^3) + tempe : + electron temperature profile (keV) + inverse_q : + inverse safety factor profile + rho : + normalized minor radius profile + + + Returns + ------- + : + the local beta poloidal """ return ( np.where( @@ -1263,26 +1488,35 @@ def _beta_poloidal_total_sauter( inverse_q: np.ndarray, rho: np.ndarray, ) -> np.ndarray: - """ - Calculate the local beta poloidal including ion pressure for the Sauter bootstrap current scaling. - - Parameters: - - radial_elements: np.ndarray, radial element indexes in range 1 to nr - - nr: int, maximum value of radial_elements - - rmajor: float, plasma major radius (m) - - b_plasma_toroidal_on_axis: float, toroidal field on axis (T) - - ne: np.ndarray, electron density profile (/m^3) - - ni: np.ndarray, ion density profile (/m^3) - - tempe: np.ndarray, electron temperature profile (keV) - - tempi: np.ndarray, ion temperature profile (keV) - - inverse_q: np.ndarray, inverse safety factor profile - - rho: np.ndarray, normalized minor radius profile - - Returns: - - np.ndarray, the local total beta poloidal - - Reference: - - None + """Calculate the local beta poloidal including ion pressure for the Sauter bootstrap current scaling. + + Parameters + ---------- + radial_elements : + radial element indexes in range 1 to nr + nr : + maximum value of radial_elements + rmajor : + plasma major radius (m) + b_plasma_toroidal_on_axis : + toroidal field on axis (T) + ne : + electron density profile (/m^3) + ni : + ion density profile (/m^3) + tempe : + electron temperature profile (keV) + tempi : + ion temperature profile (keV) + inverse_q : + inverse safety factor profile + rho : + normalized minor radius profile + + Returns + ------- + : + the local total beta poloidal """ return ( np.where( @@ -1322,34 +1556,40 @@ def _beta_poloidal_total_sauter( def _trapped_particle_fraction_sauter( radial_elements: np.ndarray, triang: float, sqeps: np.ndarray, fit: int = 0 ) -> np.ndarray: - """ - Calculates the trapped particle fraction to be used in the Sauter bootstrap current scaling. - - Parameters: - - radial_elements: list, radial element index in range 1 to nr - - triang: float, plasma triangularity - - sqeps: list, square root of local aspect ratio - - fit: int, fit method (1 = ASTRA method, 2 = Equation from Sauter 2002, 3 = Equation from Sauter 2016) - - Returns: - - list, trapped particle fraction - - This function calculates the trapped particle fraction at a given radius. - - References: - Used in this paper: - - O. Sauter, C. Angioni, Y. R. Lin-Liu; - Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime. - Phys. Plasmas 1 July 1999; 6 (7): 2834-2839. https://doi.org/10.1063/1.873240 + """Calculates the trapped particle fraction to be used in the Sauter bootstrap current scaling. + Parameters + ---------- + radial_elements : + radial element index in range 1 to nr + triang : + plasma triangularity + sqeps : + square root of local aspect ratio + fit : + fit method (1 = ASTRA method, 2 = Equation from Sauter 2002, 3 = Equation from Sauter 2016) + + Returns + ------- + type + - list, trapped particle fraction + + This function calculates the trapped particle fraction at a given radius. + + References + ---------- + Used in this paper: + - O. Sauter, C. Angioni, Y. R. Lin-Liu; + Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime. + Phys. Plasmas 1 July 1999; 6 (7): 2834-2839. https://doi.org/10.1063/1.873240 - - O. Sauter, R. J. Buttery, R. Felton, T. C. Hender, D. F. Howell, and contributors to the E.-J. Workprogramme, - “Marginal-limit for neoclassical tearing modes in JET H-mode discharges,” - Plasma Physics and Controlled Fusion, vol. 44, no. 9, pp. 1999-2019, Aug. 2002, - doi: https://doi.org/10.1088/0741-3335/44/9/315. + - O. Sauter, R. J. Buttery, R. Felton, T. C. Hender, D. F. Howell, and contributors to the E.-J. Workprogramme, + “Marginal-limit for neoclassical tearing modes in JET H-mode discharges,” + Plasma Physics and Controlled Fusion, vol. 44, no. 9, pp. 1999-2019, Aug. 2002, + doi: https://doi.org/10.1088/0741-3335/44/9/315. - - O. Sauter, Geometric formulas for system codes including the effect of negative triangularity, - Fusion Engineering and Design, Volume 112, 2016, Pages 633-645, ISSN 0920-3796, - https://doi.org/10.1016/j.fusengdes.2016.04.033. + - O. Sauter, Geometric formulas for system codes including the effect of negative triangularity, + Fusion Engineering and Design, Volume 112, 2016, Pages 633-645, ISSN 0920-3796, + https://doi.org/10.1016/j.fusengdes.2016.04.033. """ # Prevent first element from being zero @@ -1396,13 +1636,11 @@ def __init__(self, plasma_profile, current_drive, plasma_beta, plasma_inductance self.inductance = plasma_inductance def physics(self): - """ - Routine to calculate tokamak plasma physics information - author: P J Knight, CCFE, Culham Science Centre - None + """Routine to calculate tokamak plasma physics information This routine calculates all the primary plasma physics parameters for a tokamak fusion reactor. - :References: + References + ---------- - M. Kovari et al, 2014, "PROCESS": A systems code for fusion power plants - Part 1: Physics https://www.sciencedirect.com/science/article/pii/S0920379614005961 - H. Zohm et al, 2013, On the Physics Guidelines for a Tokamak DEMO @@ -2523,26 +2761,31 @@ def physics(self): @staticmethod def calculate_current_profile_index_wesson(qstar: float, q0: float) -> float: - """ - Calculate the Wesson current profile index. - - :param qstar: Cylindrical safety factor. - :type qstar: float - :param q0: Safety factor on axis. - :type q0: float - - - :return: The Wesson current profile index. - :rtype: float - - :Notes: + """Calculate the Wesson current profile index. + + Parameters + ---------- + qstar : float + Cylindrical safety factor. + q0 : float + Safety factor on axis. + + Returns + ------- + float + The Wesson current profile index. + + Notes + ----- - It is recommended to use this method with the other Wesson relations for normalised beta and normalised internal inductance. - This relation is only true for the cyclindrical plasma approximation. - :References: + References + ---------- - Wesson, J. (2011) Tokamaks. 4th Edition, 2011 Oxford Science Publications, International Series of Monographs on Physics, Volume 149. + """ return qstar / q0 - 1.0 @@ -2561,42 +2804,71 @@ def calculate_density_limit( a_plasma_surface: float, zeff: float, ) -> tuple[np.ndarray, float]: - """ - Calculate the density limit using various models. - - Args: - b_plasma_toroidal_on_axis (float): Toroidal field on axis (T). - i_density_limit (int): Switch denoting which formula to enforce. - p_plasma_separatrix_mw (float): Power flowing to the edge plasma via charged particles (MW). - p_hcd_injected_total_mw (float): Power injected into the plasma (MW). - plasma_current (float): Plasma current (A). - prn1 (float): Edge density / average plasma density. - qcyl (float): Equivalent cylindrical safety factor (qstar). - q95 (float): Safety factor at 95% surface. - rmajor (float): Plasma major radius (m). - rminor (float): Plasma minor radius (m). - a_plasma_surface (float): Plasma surface area (m^2). - zeff (float): Plasma effective charge. - - Returns: - Tuple[np.ndarray, float]: A tuple containing: - - nd_plasma_electron_max_array (np.ndarray): Average plasma density limit using seven different models (m^-3). - - nd_plasma_electrons_max (float): Enforced average plasma density limit (m^-3). - - Raises: - ValueError: If i_density_limit is not between 1 and 7. - - Notes: + """Calculate the density limit using various models. + + Parameters + ---------- + b_plasma_toroidal_on_axis : float + Toroidal field on axis (T). + i_density_limit : int + Switch denoting which formula to enforce. + p_plasma_separatrix_mw : float + Power flowing to the edge plasma via charged particles (MW). + p_hcd_injected_total_mw : float + Power injected into the plasma (MW). + plasma_current : float + Plasma current (A). + prn1 : float + Edge density / average plasma density. + qcyl : float + Equivalent cylindrical safety factor (qstar). + q95 : float + Safety factor at 95% surface. + rmajor : float + Plasma major radius (m). + rminor : float + Plasma minor radius (m). + a_plasma_surface : float + Plasma surface area (m^2). + zeff : float + Plasma effective charge. + + Returns + ------- + Tuple[np.ndarray, float] + A tuple containing: + - nd_plasma_electron_max_array (np.ndarray): Average plasma density limit using seven different models (m^-3). + - nd_plasma_electrons_max (float): Enforced average plasma density limit (m^-3). + + Raises + ------ + ValueError + If i_density_limit is not between 1 and 7. + Notes + ----- + ValueError + If i_density_limit is not between 1 and 7. + Notes + ----- + This routine calculates several different formulae for the density limit and enforces the one chosen by the user. + ValueError + If i_density_limit is not between 1 and 7. + Notes + ----- This routine calculates several different formulae for the density limit and enforces the one chosen by the user. For i_density_limit = 1-5, 8, we scale the sepatrix density limit output by the ratio of the separatrix to volume averaged density - References: - - AEA FUS 172: Physics Assessment for the European Reactor Study - - - N.A. Uckan and ITER Physics Group, 'ITER Physics Design Guidelines: 1989 - + References + ---------- + - AEA FUS 172 + Physics Assessment for the European Reactor Study + - N.A. Uckan and ITER Physics Group, 'ITER Physics Design Guidelines + 1989 + - N.A. Uckan and ITER Physics Group, 'ITER Physics Design Guidelines + 1989 - M. Bernert et al., “The H-mode density limit in the full tungsten ASDEX Upgrade tokamak,” - vol. 57, no. 1, pp. 014038-014038, Nov. 2014, doi: https://doi.org/10.1088/0741-3335/57/1/014038. ‌ + vol. 57, no. 1, pp. 014038-014038, Nov. 2014, doi: https://doi.org/10.1088/0741-3335/57/1/014038. ‌ + """ if i_density_limit < 1 or i_density_limit > 7: @@ -2704,11 +2976,8 @@ def calculate_density_limit( ] @staticmethod - def plasma_composition() -> None: - """ - Calculates various plasma component fractional makeups. - - Author: P J Knight, CCFE, Culham Science Centre + def plasma_composition(): + """Calculates various plasma component fractional makeups. This subroutine determines the various plasma component fractional makeups. It is the replacement for the original routine betcom(), and is used in conjunction @@ -2727,11 +2996,6 @@ def plasma_composition() -> None: - Calculates the fraction of alpha energy to ions and electrons. - Calculates the average atomic masses of injected fuel species and neutral beams. - Calculates the density weighted mass and mass weighted plasma effective charge. - - Notes: - - - References: """ # Alpha ash portion @@ -3025,32 +3289,46 @@ def phyaux( ) -> tuple[float, float, float, float, float, float, float, float]: """Auxiliary physics quantities - Args: - aspect (float): Plasma aspect ratio. - nd_plasma_electrons_vol_avg (float): Electron density (/m3). - te (float): Volume avergaed electron temperature (keV). - nd_plasma_fuel_ions_vol_avg (float): Fuel ion density (/m3). - fusden_total (float): Fusion reaction rate from plasma and beams (/m3/s). - fusden_alpha_total (float): Alpha particle production rate (/m3/s). - plasma_current (float): Plasma current (A). - sbar (float): Exponent for aspect ratio (normally 1). - nd_plasma_alphas_vol_avg (float): Alpha ash density (/m3). - t_energy_confinement (float): Global energy confinement time (s). - vol_plasma (float): Plasma volume (m3). - - Returns: - tuple: A tuple containing: - - burnup (float): Fractional plasma burnup. - - ntau (float): Plasma average n-tau (s/m3). - - nTtau (float): Plasma triple product nT-tau (s/m3). - - figmer (float): Physics figure of merit. - - fusrat (float): Number of fusion reactions per second. - - molflow_plasma_fuelling_required (float): Fuelling rate for D-T (nucleus-pairs/sec). - - rndfuel (float): Fuel burnup rate (reactions/s). - - t_alpha_confinement (float): Alpha particle confinement time (s). - - f_alpha_energy_confinement (float): Fraction of alpha energy confinement. - - This subroutine calculates extra physics related items needed by other parts of the code. + Parameters + ---------- + aspect : float + Plasma aspect ratio. + nd_plasma_electrons_vol_avg : float + Electron density (/m3). + te : float + Volume avergaed electron temperature (keV). + nd_plasma_fuel_ions_vol_avg : float + Fuel ion density (/m3). + fusden_total : float + Fusion reaction rate from plasma and beams (/m3/s). + fusden_alpha_total : float + Alpha particle production rate (/m3/s). + plasma_current : float + Plasma current (A). + sbar : float + Exponent for aspect ratio (normally 1). + nd_plasma_alphas_vol_avg : float + Alpha ash density (/m3). + t_energy_confinement : float + Global energy confinement time (s). + vol_plasma : float + Plasma volume (m3). + + Returns + ------- + tuple + A tuple containing: + - burnup (float): Fractional plasma burnup. + - ntau (float): Plasma average n-tau (s/m3). + - nTtau (float): Plasma triple product nT-tau (s/m3). + - figmer (float): Physics figure of merit. + - fusrat (float): Number of fusion reactions per second. + - molflow_plasma_fuelling_required (float): Fuelling rate for D-T (nucleus-pairs/sec). + - rndfuel (float): Fuel burnup rate (reactions/s). + - t_alpha_confinement (float): Alpha particle confinement time (s). + - f_alpha_energy_confinement (float): Fraction of alpha energy confinement. + This subroutine calculates extra physics related items needed by other parts of the code. + """ figmer = 1e-6 * plasma_current * aspect**sbar @@ -3117,30 +3395,40 @@ def plasma_ohmic_heating( vol_plasma: float, zeff: float, ) -> tuple[float, float, float, float]: - """ - Calculate the ohmic heating power and related parameters. - - Args: - f_c_plasma_inductive (float): Fraction of plasma current driven inductively. - kappa95 (float): Plasma elongation at 95% surface. - plasma_current (float): Plasma current (A). - rmajor (float): Major radius (m). - rminor (float): Minor radius (m). - temp_plasma_electron_density_weighted_kev (float): Density weighted average electron temperature (keV). - vol_plasma (float): Plasma volume (m^3). - zeff (float): Plasma effective charge. - - Returns: - Tuple[float, float, float, float]: Tuple containing: - - pden_plasma_ohmic_mw (float): Ohmic heating power per unit volume (MW/m^3). - - p_plasma_ohmic_mw (float): Total ohmic heating power (MW). - - f_res_plasma_neo (float): Neo-classical resistivity enhancement factor. - - res_plasma (float): Plasma resistance (ohm). - - Notes: - - References: - - ITER Physics Design Guidelines: 1989 [IPDG89], N. A. Uckan et al, + """Calculate the ohmic heating power and related parameters. + + Parameters + ---------- + f_c_plasma_inductive : float + Fraction of plasma current driven inductively. + kappa95 : float + Plasma elongation at 95% surface. + plasma_current : float + Plasma current (A). + rmajor : float + Major radius (m). + rminor : float + Minor radius (m). + temp_plasma_electron_density_weighted_kev : float + Density weighted average electron temperature (keV). + vol_plasma : float + Plasma volume (m^3). + zeff : float + Plasma effective charge. + + Returns + ------- + Tuple[float, float, float, float] + Tuple containing: + - pden_plasma_ohmic_mw (float): Ohmic heating power per unit volume (MW/m^3). + - p_plasma_ohmic_mw (float): Total ohmic heating power (MW). + - f_res_plasma_neo (float): Neo-classical resistivity enhancement factor. + - res_plasma (float): Plasma resistance (ohm). + + References + ---------- + - ITER Physics Design Guidelines + 1989 [IPDG89], N. A. Uckan et al, """ # Density weighted electron temperature in 10 keV units @@ -3203,52 +3491,91 @@ def calculate_plasma_current( ) -> tuple[float, float, float, float, float]: """Calculate the plasma current. - Args: - alphaj (float): Current profile index. - alphap (float): Pressure profile index. - b_plasma_toroidal_on_axis (float): Toroidal field on axis (T). - eps (float): Inverse aspect ratio. - i_plasma_current (int): Current scaling model to use. - 1 = Peng analytic fit - 2 = Peng divertor scaling (TART,STAR) - 3 = Simple ITER scaling - 4 = IPDG89 scaling - 5 = Todd empirical scaling I - 6 = Todd empirical scaling II - 7 = Connor-Hastie model - 8 = Sauter scaling (allowing negative triangularity) - 9 = FIESTA ST scaling - kappa (float): Plasma elongation. - kappa95 (float): Plasma elongation at 95% surface. - pres_plasma_on_axis (float): Central plasma pressure (Pa). - len_plasma_poloidal (float): Plasma perimeter length (m). - q95 (float): Plasma safety factor at 95% flux (= q-bar for i_plasma_current=2). - ind_plasma_internal_norm (float): Plasma normalised internal inductance. - rmajor (float): Major radius (m). - rminor (float): Minor radius (m). - triang (float): Plasma triangularity. - triang95 (float): Plasma triangularity at 95% surface. - - Returns: - Tuple[float, float, float,]: Tuple containing b_plasma_poloidal_average, qstar, plasma_current, - - Raises: - ValueError: If invalid value for i_plasma_current is provided. - - Notes: - This routine calculates the plasma current based on the edge safety factor q95. - It will also make the current profile parameters consistent with the q-profile if required. - - References: - - J D Galambos, STAR Code : Spherical Tokamak Analysis and Reactor Code, unpublished internal Oak Ridge document + This routine calculates the plasma current based on the edge safety factor q95. + It will also make the current profile parameters consistent with the q-profile if required. + + Parameters + ---------- + alphaj : float + Current profile index. + alphap : float + Pressure profile index. + b_plasma_toroidal_on_axis : float + Toroidal field on axis (T). + eps : float + Inverse aspect ratio. + i_plasma_current : int + Current scaling model to use. + 1 = Peng analytic fit + 2 = Peng divertor scaling (TART,STAR) + 3 = Simple ITER scaling + 4 = IPDG89 scaling + 5 = Todd empirical scaling I + 6 = Todd empirical scaling II + 7 = Connor-Hastie model + 8 = Sauter scaling (allowing negative triangularity) + 9 = FIESTA ST scaling + kappa : float + Plasma elongation. + kappa95 : float + Plasma elongation at 95% surface. + pres_plasma_on_axis : float + Central plasma pressure (Pa). + len_plasma_poloidal : float + Plasma perimeter length (m). + q95 : float + Plasma safety factor at 95% flux (= q-bar for i_plasma_current=2). + ind_plasma_internal_norm : float + Plasma normalised internal inductance. + rmajor : float + Major radius (m). + rminor : float + Minor radius (m). + triang : float + Plasma triangularity. + triang95 : float + Plasma triangularity at 95% surface. + + Returns + ------- + Tuple[float, float, float,] + Tuple containing b_plasma_poloidal_average, qstar, plasma_current, + + Raises + ------ + ValueError + If invalid value for i_plasma_current is provided. + ValueError + If invalid value for i_plasma_current is provided. + ValueError + If invalid value for i_plasma_current is provided. + + References + ---------- + - J D Galambos, STAR Code + Spherical Tokamak Analysis and Reactor Code, unpublished internal Oak Ridge document + - J D Galambos, STAR Code + Spherical Tokamak Analysis and Reactor Code, unpublished internal Oak Ridge document - Peng, Y. K. M., Galambos, J. D., & Shipe, P. C. (1992). - 'Small Tokamaks for Fusion Technology Testing'. Fusion Technology, 21(3P2A), - 1729-1738. https://doi.org/10.13182/FST92-A29971 - - ITER Physics Design Guidelines: 1989 [IPDG89], N. A. Uckan et al, ITER Documentation Series No.10, IAEA/ITER/DS/10, IAEA, Vienna, 1990 - - M. Kovari et al, 2014, "PROCESS": A systems code for fusion power plants - Part 1: Physics + 'Small Tokamaks for Fusion Technology Testing'. Fusion Technology, 21(3P2A), + 1729-1738. https://doi.org/10.13182/FST92-A29971 + - ITER Physics Design Guidelines + 1989 [IPDG89], N. A. Uckan et al, ITER Documentation Series No.10, IAEA/ITER/DS/10, IAEA, Vienna, 1990 + - M. Kovari et al, 2014, "PROCESS" + A systems code for fusion power plants - Part 1: Physics + - M. Kovari et al, 2014, "PROCESS" + A systems code for fusion power plants - Part 1: Physics + - H. Zohm et al, 2013, On the Physics Guidelines for a Tokamak DEMO + - M. Kovari et al, 2014, "PROCESS" + A systems code for fusion power plants - Part 1: Physics + - H. Zohm et al, 2013, On the Physics Guidelines for a Tokamak DEMO + - T. Hartmann, 2013, Development of a modular systems code to analyse the implications of physics assumptions on the design of a demonstration fusion power plant + - M. Kovari et al, 2014, "PROCESS" + A systems code for fusion power plants - Part 1: Physics - H. Zohm et al, 2013, On the Physics Guidelines for a Tokamak DEMO - T. Hartmann, 2013, Development of a modular systems code to analyse the implications of physics assumptions on the design of a demonstration fusion power plant - Sauter, Geometric formulas for systems codes..., FED 2016 + """ # Aspect ratio aspect_ratio = 1.0 / eps @@ -3432,13 +3759,10 @@ def calculate_effective_charge_ionisation_profiles(self): def outplas(self): """Subroutine to output the plasma physics information - author: P J Knight, CCFE, Culham Science Centre self.outfile : input integer : Fortran output unit identifier This routine writes the plasma physics information to a file, in a tidy format. """ - - # ############################################### # Dimensionless plasma parameters. See reference below. physics_variables.nu_star = ( 1 @@ -5822,9 +6146,8 @@ def outplas(self): reinke_variables.fzactual, ) - def output_confinement_comparison(self, istell: int) -> None: - """ - Routine to calculate ignition margin for different confinement scalings and equivalent confinement times for H=1. + def output_confinement_comparison(self, istell: int): + """Routine to calculate ignition margin for different confinement scalings and equivalent confinement times for H=1. This routine calculates the ignition margin at the final point with different scalings and outputs the results to a file. @@ -5842,11 +6165,11 @@ def output_confinement_comparison(self, istell: int) -> None: - `calculate_confinement_time`: Calculates confinement-related parameters. - `find_other_h_factors`: Calculates the H-factor for a given confinement time. - Parameters: - - istell (int): Indicator for stellarator (0 for tokamak, >=1 for stellarator). + Parameters + ---------- + istell : + Indicator for stellarator (0 for tokamak, >=1 for stellarator). - Returns: - - None """ po.oheadr(self.outfile, "Energy confinement times, and required H-factors :") @@ -5938,27 +6261,38 @@ def bootstrap_fraction_iter89( rmajor: float, vol_plasma: float, ) -> float: - """ - Calculate the bootstrap-driven fraction of the plasma current. - - Args: - aspect (float): Plasma aspect ratio. - beta (float): Plasma total beta. - b_plasma_toroidal_on_axis (float): Toroidal field on axis (T). - plasma_current (float): Plasma current (A). - q95 (float): Safety factor at 95% surface. - q0 (float): Central safety factor. - rmajor (float): Plasma major radius (m). - vol_plasma (float): Plasma volume (m3). - - Returns: - float: The bootstrap-driven fraction of the plasma current. + """Calculate the bootstrap-driven fraction of the plasma current. This function performs the original ITER calculation of the plasma current bootstrap fraction. + Parameters + ---------- + aspect : float + Plasma aspect ratio. + beta : float + Plasma total beta. + b_plasma_toroidal_on_axis : float + Toroidal field on axis (T). + plasma_current : float + Plasma current (A). + q95 : float + Safety factor at 95% surface. + q0 : float + Central safety factor. + rmajor : float + Plasma major radius (m). + vol_plasma : float + Plasma volume (m3). + + Returns + ------- + float + The bootstrap-driven fraction of the plasma current. + Reference: - - ITER Physics Design Guidelines: 1989 [IPDG89], N. A. Uckan et al, - - ITER Documentation Series No.10, IAEA/ITER/DS/10, IAEA, Vienna, 1990 + - ITER Physics Design Guidelines: 1989 [IPDG89], N. A. Uckan et al, + - ITER Documentation Series No.10, IAEA/ITER/DS/10, IAEA, Vienna, 1990 + """ # Calculate the bootstrap current coefficient @@ -5990,27 +6324,41 @@ def bootstrap_fraction_wilson( rmajor: float, rminor: float, ) -> float: - """ - Bootstrap current fraction from Wilson et al scaling - - Args: - alphaj (float): Current profile index. - alphap (float): Pressure profile index. - alphat (float): Temperature profile index. - betpth (float): Thermal component of poloidal beta. - q0 (float): Safety factor on axis. - q95 (float): Edge safety factor. - rmajor (float): Major radius (m). - rminor (float): Minor radius (m). - - Returns: - float: The bootstrap current fraction. + """Bootstrap current fraction from Wilson et al scaling This function calculates the bootstrap current fraction using the numerically fitted algorithm written by Howard Wilson. + Parameters + ---------- + alphaj : float + Current profile index. + alphap : float + Pressure profile index. + alphat : float + Temperature profile index. + betpth : float + Thermal component of poloidal beta. + q0 : float + Safety factor on axis. + q95 : float + Edge safety factor. + rmajor : float + Major radius (m). + rminor : float + Minor radius (m). + + Returns + ------- + float + The bootstrap current fraction. + Reference: - - AEA FUS 172: Physics Assessment for the European Reactor Study, 1989 + - AEA FUS 172 + Physics Assessment for the European Reactor Study, 1989 + - AEA FUS 172 + Physics Assessment for the European Reactor Study, 1989 - H. R. Wilson, Nuclear Fusion 32 (1992) 257 + """ term1 = np.log(0.5) @@ -6101,36 +6449,49 @@ def bootstrap_fraction_nevins( te: float, zeff: float, ) -> float: - """ - Calculate the bootstrap current fraction from Nevins et al scaling. - - Args: - alphan (float): Density profile index. - alphat (float): Temperature profile index. - beta_toroidal (float): Toroidal plasma beta. - b_plasma_toroidal_on_axis (float): Toroidal field on axis (T). - nd_plasma_electrons_vol_avg (float): Electron density (/m3). - plasma_current (float): Plasma current (A). - q0 (float): Central safety factor. - q95 (float): Safety factor at 95% surface. - rmajor (float): Plasma major radius (m). - rminor (float): Plasma minor radius (m). - te (float): Volume averaged plasma temperature (keV). - zeff (float): Plasma effective charge. - - Returns: - float: The bootstrap current fraction. + """Calculate the bootstrap current fraction from Nevins et al scaling. This function calculates the bootstrap current fraction using the Nevins et al method. - Reference: See appendix of: - Keii Gi, Makoto Nakamura, Kenji Tobita, Yasushi Ono, - Bootstrap current fraction scaling for a tokamak reactor design study, - Fusion Engineering and Design, Volume 89, Issue 11, 2014, Pages 2709-2715, - ISSN 0920-3796, https://doi.org/10.1016/j.fusengdes.2014.07.009. + Parameters + ---------- + alphan : float + Density profile index. + alphat : float + Temperature profile index. + beta_toroidal : float + Toroidal plasma beta. + b_plasma_toroidal_on_axis : float + Toroidal field on axis (T). + nd_plasma_electrons_vol_avg : float + Electron density (/m3). + plasma_current : float + Plasma current (A). + q0 : float + Central safety factor. + q95 : float + Safety factor at 95% surface. + rmajor : float + Plasma major radius (m). + rminor : float + Plasma minor radius (m). + te : float + Volume averaged plasma temperature (keV). + zeff : float + Plasma effective charge. + + Returns + ------- + float + The bootstrap current fraction. - Nevins, W. M. "Summary report: ITER specialists' meeting on heating and current drive." - ITER-TN-PH-8-4, June 1988. 1988. + Reference: See appendix of: + Keii Gi, Makoto Nakamura, Kenji Tobita, Yasushi Ono, + Bootstrap current fraction scaling for a tokamak reactor design study, + Fusion Engineering and Design, Volume 89, Issue 11, 2014, Pages 2709-2715, + ISSN 0920-3796, https://doi.org/10.1016/j.fusengdes.2014.07.009. + Nevins, W. M. "Summary report: ITER specialists' meeting on heating and current drive." + ITER-TN-PH-8-4, June 1988. 1988. """ # Calculate peak electron beta at plasma centre, this is not the form used in the paper @@ -6176,24 +6537,28 @@ def bootstrap_fraction_nevins( def bootstrap_fraction_sauter(plasma_profile: float) -> float: """Calculate the bootstrap current fraction from the Sauter et al scaling. - Args: - plasma_profile (PlasmaProfile): The plasma profile object. + This function calculates the bootstrap current fraction using the Sauter, Angioni, and Lin-Liu scaling. - Returns: - float: The bootstrap current fraction. + Parameters + ---------- + plasma_profile : PlasmaProfile + The plasma profile object. - This function calculates the bootstrap current fraction using the Sauter, Angioni, and Lin-Liu scaling. + Returns + ------- + float + The bootstrap current fraction. Reference: - - O. Sauter, C. Angioni, Y. R. Lin-Liu; - Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime. - Phys. Plasmas 1 July 1999; 6 (7): 2834-2839. https://doi.org/10.1063/1.873240 - - O. Sauter, C. Angioni, Y. R. Lin-Liu; Erratum: - Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime - [Phys. Plasmas 6, 2834 (1999)]. Phys. Plasmas 1 December 2002; 9 (12): 5140. https://doi.org/10.1063/1.1517052 + - O. Sauter, C. Angioni, Y. R. Lin-Liu; + Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime. + Phys. Plasmas 1 July 1999; 6 (7): 2834-2839. https://doi.org/10.1063/1.873240 + - O. Sauter, C. Angioni, Y. R. Lin-Liu; Erratum: + Neoclassical conductivity and bootstrap current formulas for general axisymmetric equilibria and arbitrary collisionality regime + [Phys. Plasmas 6, 2834 (1999)]. Phys. Plasmas 1 December 2002; 9 (12): 5140. https://doi.org/10.1063/1.1517052 + Note: + The code was supplied by Emiliano Fable, IPP Garching (private communication). - Note: - The code was supplied by Emiliano Fable, IPP Garching (private communication). """ # Radial points from 0 to 1 seperated by 1/profile_size @@ -6325,34 +6690,46 @@ def bootstrap_fraction_sakai( eps: float, ind_plasma_internal_norm: float, ) -> float: - """ - Calculate the bootstrap fraction using the Sakai formula. - - Parameters: - beta_poloidal (float): Plasma poloidal beta. - q95 (float): Safety factor at 95% of the plasma radius. - q0 (float): Safety factor at the magnetic axis. - alphan (float): Density profile index - alphat (float): Temperature profile index - eps (float): Inverse aspect ratio. - ind_plasma_internal_norm (float): Plasma normalised internal inductance - - Returns: - float: The calculated bootstrap fraction. - - Notes: - The profile assumed for the alphan and alpat indexes is only a parabolic profile without a pedestal (L-mode). - The Root Mean Squared Error for the fitting database of this formula was 0.025 - Concentrating on the positive shear plasmas using the ACCOME code equilibria with the fully non-inductively driven - conditions with neutral beam (NB) injection only are calculated. - The electron temperature and the ion temperature were assumed to be equal - This can be used for all apsect ratios. - The diamagnetic fraction is included in this formula. - - References: - Ryosuke Sakai, Takaaki Fujita, Atsushi Okamoto, Derivation of bootstrap current fraction scaling formula for 0-D system code analysis, - Fusion Engineering and Design, Volume 149, 2019, 111322, ISSN 0920-3796, - https://doi.org/10.1016/j.fusengdes.2019.111322. + """Calculate the bootstrap fraction using the Sakai formula. + + Parameters + ---------- + beta_poloidal : + Plasma poloidal beta. + q95 : + Safety factor at 95% of the plasma radius. + q0 : + Safety factor at the magnetic axis. + alphan : + Density profile index + alphat : + Temperature profile index + eps : + Inverse aspect ratio. + ind_plasma_internal_norm : + Plasma normalised internal inductance + + Returns + ------- + : + The calculated bootstrap fraction. + + Notes + ----- + The profile assumed for the alphan and alpat indexes is only a parabolic profile without a pedestal (L-mode). + The Root Mean Squared Error for the fitting database of this formula was 0.025 + Concentrating on the positive shear plasmas using the ACCOME code equilibria with the fully non-inductively driven + conditions with neutral beam (NB) injection only are calculated. + The electron temperature and the ion temperature were assumed to be equal + This can be used for all apsect ratios. + The diamagnetic fraction is included in this formula. + + References + ---------- + Ryosuke Sakai, Takaaki Fujita, Atsushi Okamoto, Derivation of bootstrap current fraction scaling formula for 0-D system code analysis, + Fusion Engineering and Design, Volume 149, 2019, 111322, ISSN 0920-3796, + https://doi.org/10.1016/j.fusengdes.2019.111322. + """ # Sakai states that the ACCOME dataset used has the toridal diamagnetic current included in the bootstrap current # So the diamganetic current should not be calculated with this. i_diamagnetic_current = 0 @@ -6373,26 +6750,34 @@ def bootstrap_fraction_aries( average_density: float, inverse_aspect: float, ) -> float: - """ - Calculate the bootstrap fraction using the ARIES formula. - - Parameters: - beta_poloidal (float): Plasma poloidal beta. - ind_plasma_internal_norm (float): Plasma normalized internal inductance. - core_density (float): Core plasma density. - average_density (float): Average plasma density. - inverse_aspect (float): Inverse aspect ratio. - - Returns: - float: The calculated bootstrap fraction. - - Notes: + """Calculate the bootstrap fraction using the ARIES formula. + Parameters + ---------- + beta_poloidal : + Plasma poloidal beta. + ind_plasma_internal_norm : + Plasma normalized internal inductance. + core_density : + Core plasma density. + average_density : + Average plasma density. + inverse_aspect : + Inverse aspect ratio. + + Returns + ------- + : + The calculated bootstrap fraction. + + Notes + ----- - The source reference does not provide any info about the derivation of the formula. It is only stated - References: + References + ---------- - Zoran Dragojlovic et al., “An advanced computational algorithm for systems analysis of tokamak power plants,” - Fusion Engineering and Design, vol. 85, no. 2, pp. 243-265, Apr. 2010, - doi: https://doi.org/10.1016/j.fusengdes.2010.02.015. + Fusion Engineering and Design, vol. 85, no. 2, pp. 243-265, Apr. 2010, + doi: https://doi.org/10.1016/j.fusengdes.2010.02.015. """ # Using the standard variable naming from the ARIES paper @@ -6416,28 +6801,36 @@ def bootstrap_fraction_andrade( average_pressure: float, inverse_aspect: float, ) -> float: - """ - Calculate the bootstrap fraction using the Andrade et al formula. - - Parameters: - beta_poloidal (float): Plasma poloidal beta. - core_pressure (float): Core plasma pressure. - average_pressure (float): Average plasma pressure. - inverse_aspect (float): Inverse aspect ratio. - - Returns: - float: The calculated bootstrap fraction. - - Notes: + """Calculate the bootstrap fraction using the Andrade et al formula. + + Parameters + ---------- + beta_poloidal : + Plasma poloidal beta. + core_pressure : + Core plasma pressure. + average_pressure : + Average plasma pressure. + inverse_aspect : + Inverse aspect ratio. + + Returns + ------- + : + The calculated bootstrap fraction. + + Notes + ----- - Based off 350 plasma profiles from Experimento Tokamak Esferico (ETE) spherical tokamak - A = 1.5, R_0 = 0.3m, I_p = 200kA, B_0=0.4T, beta = 4-10%. Profiles taken as Gaussian shaped functions. - Errors mostly up to the order of 10% are obtained when both expressions are compared with the equilibrium estimates for the - bootstrap current in ETE + bootstrap current in ETE - References: + References + ---------- - M. C. R. Andrade and G. O. Ludwig, “Scaling of bootstrap current on equilibrium and plasma profile parameters in tokamak plasmas,” - Plasma Physics and Controlled Fusion, vol. 50, no. 6, pp. 065001-065001, Apr. 2008, - doi: https://doi.org/10.1088/0741-3335/50/6/065001. + Plasma Physics and Controlled Fusion, vol. 50, no. 6, pp. 065001-065001, Apr. 2008, + doi: https://doi.org/10.1088/0741-3335/50/6/065001. """ @@ -6456,29 +6849,37 @@ def bootstrap_fraction_hoang( current_index: float, inverse_aspect: float, ) -> float: - """ - Calculate the bootstrap fraction using the Hoang et al formula. - - Parameters: - beta_poloidal (float): Plasma poloidal beta. - pressure_index (float): Pressure profile index. - current_index (float): Current profile index. - inverse_aspect (float): Inverse aspect ratio. - - Returns: - float: The calculated bootstrap fraction. - - Notes: + """Calculate the bootstrap fraction using the Hoang et al formula. + Parameters + ---------- + beta_poloidal : + Plasma poloidal beta. + pressure_index : + Pressure profile index. + current_index : + Current profile index. + inverse_aspect : + Inverse aspect ratio. + + Returns + ------- + : + The calculated bootstrap fraction. + + Notes + ----- - Based off of TFTR data calculated using the TRANSP plasma analysis code - 170 discharges which was assembled to study the tritium influx and transport in discharges with D-only neutral beam - injection (NBI) + injection (NBI) - Contains L-mode, supershots, reversed shear, enhanced reversed shear and increased li discharges - Discharges with monotonic flux profiles with reversed shear are also included - Is applied to circular cross-section plasmas - References: + References + ---------- - G. T. Hoang and R. V. Budny, “The bootstrap fraction in TFTR,” AIP conference proceedings, - Jan. 1997, doi: https://doi.org/10.1063/1.53414. + Jan. 1997, doi: https://doi.org/10.1063/1.53414. + """ # Using the standard variable naming from the Hoang et.al. paper @@ -6503,33 +6904,42 @@ def bootstrap_fraction_wong( inverse_aspect: float, elongation: float, ) -> float: - """ - Calculate the bootstrap fraction using the Wong et al formula. - - Parameters: - beta_poloidal (float): Plasma poloidal beta. - density_index (float): Density profile index. - temperature_index (float): Temperature profile index. - inverse_aspect (float): Inverse aspect ratio. - elongation (float): Plasma elongation. - - Returns: - float: The calculated bootstrap fraction. - - Notes: + """Calculate the bootstrap fraction using the Wong et al formula. + Parameters + ---------- + beta_poloidal : + Plasma poloidal beta. + density_index : + Density profile index. + temperature_index : + Temperature profile index. + inverse_aspect : + Inverse aspect ratio. + elongation : + Plasma elongation. + + Returns + ------- + : + The calculated bootstrap fraction. + + Notes + ----- - Data is based off of equilibria from Miller et al. - A: 1.2 - 3.0 and stable to n ballooning and low n kink modes at a bootstrap fraction of 99% for kappa = 2, 2.5 and 3 - The results were parameterized as a function of aspect ratio and elongation - The parametric dependency of beta_p and beta_T are based on fitting of the DIII-D high equivalent DT yield results - Parabolic profiles should be used for best results as the pressure peaking value is calculated as the product of a parabolic - temperature and density profile + temperature and density profile - References: + References + ---------- - C.-P. Wong, J. C. Wesley, R. D. Stambaugh, and E. T. Cheng, “Toroidal reactor designs as a function of aspect ratio and elongation,” - vol. 42, no. 5, pp. 547-556, May 2002, doi: https://doi.org/10.1088/0029-5515/42/5/307. + vol. 42, no. 5, pp. 547-556, May 2002, doi: https://doi.org/10.1088/0029-5515/42/5/307. - Miller, R L, "Stable bootstrap-current driven equilibria for low aspect ratio tokamaks". - Switzerland: N. p., 1996. Web.https://fusion.gat.com/pubs-ext/MISCONF96/A22433.pdf + Switzerland: N. p., 1996. Web.https://fusion.gat.com/pubs-ext/MISCONF96/A22433.pdf + """ # Using the standard variable naming from the Wong et.al. paper f_peak = 2.0 / scipy.special.beta(0.5, density_index + temperature_index + 1) @@ -6548,35 +6958,47 @@ def bootstrap_fraction_gi_I( # noqa: N802 q95: float, q0: float, ) -> float: - """ - Calculate the bootstrap fraction using the first scaling from the Gi et al formula. - - Parameters: - beta_poloidal (float): Plasma poloidal beta. - pressure_index (float): Pressure profile index. - temperature_index (float): Temperature profile index. - inverse_aspect (float): Inverse aspect ratio. - effective_charge (float): Plasma effective charge. - q95 (float): Safety factor at 95% of the plasma radius. - q0 (float): Safety factor at the magnetic axis. - - Returns: - float: The calculated bootstrap fraction. - - Notes: - - Scaling found by solving the Hirshman-Sigmar bootstrap modelusing the matrix inversion method - - Method was done to put the scaling into parameters compatible with the TPC systems code - - Uses the ACCOME code to create bootstrap current fractions without using the itrative calculations of the - curent drive and equilibrium models in the scan - - R = 5.0 m, A = 1.3 - 5.0, kappa = 2, traing = 0.3, alpha_n = 0.1 - 0.8, alpha_t = 1.0 - 3.0, Z_eff = 1.2 - 3.0 - - Uses parabolic plasma profiles only. - - Scaling 1 has better accuracy than Scaling 2. However, Scaling 1 overestimated the f_BS value for reversed shear - equilibrium. + """Calculate the bootstrap fraction using the first scaling from the Gi et al formula. + + Parameters + ---------- + beta_poloidal : + Plasma poloidal beta. + pressure_index : + Pressure profile index. + temperature_index : + Temperature profile index. + inverse_aspect : + Inverse aspect ratio. + effective_charge : + Plasma effective charge. + q95 : + Safety factor at 95% of the plasma radius. + q0 : + Safety factor at the magnetic axis. + + Returns + ------- + : + The calculated bootstrap fraction. + + Notes + ----- + - Scaling found by solving the Hirshman-Sigmar bootstrap modelusing the matrix inversion method + - Method was done to put the scaling into parameters compatible with the TPC systems code + - Uses the ACCOME code to create bootstrap current fractions without using the itrative calculations of the + current drive and equilibrium models in the scan + - R = 5.0 m, A = 1.3 - 5.0, kappa = 2, traing = 0.3, alpha_n = 0.1 - 0.8, alpha_t = 1.0 - 3.0, Z_eff = 1.2 - 3.0 + - Uses parabolic plasma profiles only. + - Scaling 1 has better accuracy than Scaling 2. However, Scaling 1 overestimated the f_BS value for reversed shear + equilibrium. + + References + ---------- + - K. Gi, M. Nakamura, Kenji Tobita, and Y. Ono, “Bootstrap current fraction scaling for a tokamak reactor design study,” + Fusion Engineering and Design, vol. 89, no. 11, pp. 2709-2715, Aug. 2014, + doi: https://doi.org/10.1016/j.fusengdes.2014.07.009. - References: - - K. Gi, M. Nakamura, Kenji Tobita, and Y. Ono, “Bootstrap current fraction scaling for a tokamak reactor design study,” - Fusion Engineering and Design, vol. 89, no. 11, pp. 2709-2715, Aug. 2014, - doi: https://doi.org/10.1016/j.fusengdes.2014.07.009. """ # Using the standard variable naming from the Gi et.al. paper @@ -6600,33 +7022,43 @@ def bootstrap_fraction_gi_II( # noqa: N802 inverse_aspect: float, effective_charge: float, ) -> float: - """ - Calculate the bootstrap fraction using the second scaling from the Gi et al formula. - - Parameters: - beta_poloidal (float): Plasma poloidal beta. - pressure_index (float): Pressure profile index. - temperature_index (float): Temperature profile index. - inverse_aspect (float): Inverse aspect ratio. - effective_charge (float): Plasma effective charge. - - Returns: - float: The calculated bootstrap fraction. - - Notes: + """Calculate the bootstrap fraction using the second scaling from the Gi et al formula. + + Parameters + ---------- + beta_poloidal : + Plasma poloidal beta. + pressure_index : + Pressure profile index. + temperature_index : + Temperature profile index. + inverse_aspect : + Inverse aspect ratio. + effective_charge : + Plasma effective charge. + + Returns + ------- + : + The calculated bootstrap fraction. + + Notes + ----- - Scaling found by solving the Hirshman-Sigmar bootstrap modelusing the matrix inversion method - Method was done to put the scaling into parameters compatible with the TPC systems code - Uses the ACCOME code to create bootstrap current fractions without using the itrative calculations of the - curent drive and equilibrium models in the scan + curent drive and equilibrium models in the scan - R = 5.0 m, A = 1.3 - 5.0, kappa = 2, traing = 0.3, alpha_n = 0.1 - 0.8, alpha_t = 1.0 - 3.0, Z_eff = 1.2 - 3.0 - Uses parabolic plasma profiles only. - This scaling has the q profile dependance removed to obtain a scaling formula with much more flexible variables than - that by a single profile factor for internal current profile. + that by a single profile factor for internal current profile. - References: + References + ---------- - K. Gi, M. Nakamura, Kenji Tobita, and Y. Ono, “Bootstrap current fraction scaling for a tokamak reactor design study,” - Fusion Engineering and Design, vol. 89, no. 11, pp. 2709-2715, Aug. 2014, - doi: https://doi.org/10.1016/j.fusengdes.2014.07.009. + Fusion Engineering and Design, vol. 89, no. 11, pp. 2709-2715, Aug. 2014, + doi: https://doi.org/10.1016/j.fusengdes.2014.07.009. + """ # Using the standard variable naming from the Gi et.al. paper @@ -6651,37 +7083,43 @@ def bootstrap_fraction_sugiyama_l_mode( q95: float, q0: float, ) -> float: - """ - Calculate the bootstrap fraction using the L-mode scaling from the Sugiyama et al formula. - - :param eps: Inverse aspect ratio. - :type eps: float - :param beta_poloidal: Plasma poloidal beta. - :type beta_poloidal: float - :param alphan: Density profile index. - :type alphan: float - :param alphat: Temperature profile index. - :type alphat: float - :param zeff: Plasma effective charge. - :type zeff: float - :param q95: Safety factor at 95% of the plasma radius. - :type q95: float - :param q0: Safety factor at the magnetic axis. - :type q0: float - - :returns: The calculated bootstrap fraction. - :rtype: float - - :notes: + """Calculate the bootstrap fraction using the L-mode scaling from the Sugiyama et al formula. + + Parameters + ---------- + eps : float + Inverse aspect ratio. + beta_poloidal : float + Plasma poloidal beta. + alphan : float + Density profile index. + alphat : float + Temperature profile index. + zeff : float + Plasma effective charge. + q95 : float + Safety factor at 95% of the plasma radius. + q0 : float + Safety factor at the magnetic axis. + + Returns + ------- + float + The calculated bootstrap fraction. + + Notes + ----- - This scaling is derived for L-mode plasmas. - Ion and electron temperature are the same - Z_eff has a uniform profile, with only fully stripped carbon impurity - :references: + References + ---------- - S. Sugiyama, T. Goto, H. Utoh, and Y. Sakamoto, “Improvement of core plasma power and current balance models for tokamak systems code considering H-mode plasma profiles,” Fusion Engineering and Design, vol. 216, p. 115022, Jul. 2025, doi: https://doi.org/10.1016/j.fusengdes.2025.115022. + """ return ( @@ -6709,49 +7147,55 @@ def bootstrap_fraction_sugiyama_h_mode( n_greenwald: float, temp_plasma_pedestal_kev: float, ) -> float: - """ - Calculate the bootstrap fraction using the H-mode scaling from the Sugiyama et al formula. - - :param eps: Inverse aspect ratio. - :type eps: float - :param beta_poloidal: Plasma poloidal beta. - :type beta_poloidal: float - :param alphan: Density profile index. - :type alphan: float - :param alphat: Temperature profile index. - :type alphat: float - :param tbeta: Second temperature profile index. - :type tbeta: float - :param zeff: Plasma effective charge. - :type zeff: float - :param q95: Safety factor at 95% of the plasma radius. - :type q95: float - :param q0: Safety factor at the magnetic axis. - :type q0: float - :param radius_plasma_pedestal_density_norm: Normalised plasma radius of density pedestal. - :type radius_plasma_pedestal_density_norm: float - :param nd_plasma_pedestal_electron: Electron number density at the pedestal [m^-3]. - :type nd_plasma_pedestal_electron: float - :param n_greenwald: Greenwald density limit [m^-3]. - :type n_greenwald: float - :param temp_plasma_pedestal_kev: Electron temperature at the pedestal [keV]. - :type temp_plasma_pedestal_kev: float - - :returns: The calculated bootstrap fraction. - :rtype: float - - :notes: + """Calculate the bootstrap fraction using the H-mode scaling from the Sugiyama et al formula. + + Parameters + ---------- + eps : float + Inverse aspect ratio. + beta_poloidal : float + Plasma poloidal beta. + alphan : float + Density profile index. + alphat : float + Temperature profile index. + tbeta : float + Second temperature profile index. + zeff : float + Plasma effective charge. + q95 : float + Safety factor at 95% of the plasma radius. + q0 : float + Safety factor at the magnetic axis. + radius_plasma_pedestal_density_norm : float + Normalised plasma radius of density pedestal. + nd_plasma_pedestal_electron : float + Electron number density at the pedestal [m^-3]. + n_greenwald : float + Greenwald density limit [m^-3]. + temp_plasma_pedestal_kev : float + Electron temperature at the pedestal [keV]. + + Returns + ------- + float + The calculated bootstrap fraction. + + Notes + ----- - This scaling is derived for H-mode plasmas. - The temperature and density pedestal positions are the same - Separatrix temperature and density are zero - Ion and electron temperature are the same - Z_eff has a uniform profile, with only fully stripped carbon impurity - :references: + References + ---------- - S. Sugiyama, T. Goto, H. Utoh, and Y. Sakamoto, “Improvement of core plasma power and current balance models for tokamak systems code considering H-mode plasma profiles,” Fusion Engineering and Design, vol. 216, p. 115022, Jul. 2025, doi: https://doi.org/10.1016/j.fusengdes.2025.115022. + """ return ( @@ -6769,25 +7213,35 @@ def bootstrap_fraction_sugiyama_h_mode( ) def find_other_h_factors(self, i_confinement_time: int) -> float: - """ - Function to find H-factor for the equivalent confinement time in other scalings. + """Function to find H-factor for the equivalent confinement time in other scalings. - Args: - i_confinement_time (int): Index of the confinement time scaling to use. + Parameters + ---------- + i_confinement_time : int + Index of the confinement time scaling to use. + + Returns + ------- + float + The calculated H-factor. - Returns: - float: The calculated H-factor. """ def fhz(hfact: float) -> float: - """ - Function used to find power balance. + """Function used to find power balance. + + Parameters + ---------- + hfact : float + H-factor to be used in the calculation. + hfact: float : + - Args: - hfact (float): H-factor to be used in the calculation. + Returns + ------- + float + The difference between the calculated power and the required power for balance. - Returns: - float: The difference between the calculated power and the required power for balance. """ ( ptrez, @@ -6879,43 +7333,74 @@ def calculate_confinement_time( vol_plasma: float, zeff: float, ) -> tuple[float, float, float, float, float, float, float]: - """ - Calculate the confinement times and the transport power loss terms. - - :param m_fuel_amu: Average mass of fuel (amu) - :param p_alpha_total_mw: Alpha particle power (MW) - :param aspect: Aspect ratio - :param b_plasma_toroidal_on_axis: Toroidal field on axis (T) - :param nd_plasma_ions_total_vol_avg: Total ion density (/m3) - :param nd_plasma_electrons_vol_avg: Volume averaged electron density (/m3) - :param nd_plasma_electron_line: Line-averaged electron density (/m3) - :param eps: Inverse aspect ratio - :param hfact: H factor on energy confinement scalings - :param i_confinement_time: Switch for energy confinement scaling to use - :param i_plasma_ignited: Switch for ignited calculation - :param kappa: Plasma elongation - :param kappa95: Plasma elongation at 95% surface - :param p_non_alpha_charged_mw: Non-alpha charged particle fusion power (MW) - :param p_hcd_injected_total_mw: Auxiliary power to ions and electrons (MW) - :param plasma_current: Plasma current (A) - :param pden_plasma_core_rad_mw: Total core radiation power (MW/m3) - :param q95: Edge safety factor (tokamaks), or rotational transform iotabar (stellarators) - :param qstar: Equivalent cylindrical edge safety factor - :param rmajor: Plasma major radius (m) - :param rminor: Plasma minor radius (m) - :param temp_plasma_electron_density_weighted_kev: Density weighted average electron temperature (keV) - :param temp_plasma_ion_density_weighted_kev: Density weighted average ion temperature (keV) - :param vol_plasma: Plasma volume (m3) - :param a_plasma_poloidal: Plasma cross-sectional area (m2) - :param zeff: Plasma effective charge - - :return: Tuple containing: + """Calculate the confinement times and the transport power loss terms. + + Parameters + ---------- + m_fuel_amu : + Average mass of fuel (amu) + p_alpha_total_mw : + Alpha particle power (MW) + aspect : + Aspect ratio + b_plasma_toroidal_on_axis : + Toroidal field on axis (T) + nd_plasma_ions_total_vol_avg : + Total ion density (/m3) + nd_plasma_electrons_vol_avg : + Volume averaged electron density (/m3) + nd_plasma_electron_line : + Line-averaged electron density (/m3) + eps : + Inverse aspect ratio + hfact : + H factor on energy confinement scalings + i_confinement_time : + Switch for energy confinement scaling to use + i_plasma_ignited : + Switch for ignited calculation + kappa : + Plasma elongation + kappa95 : + Plasma elongation at 95% surface + p_non_alpha_charged_mw : + Non-alpha charged particle fusion power (MW) + p_hcd_injected_total_mw : + Auxiliary power to ions and electrons (MW) + plasma_current : + Plasma current (A) + pden_plasma_core_rad_mw : + Total core radiation power (MW/m3) + q95 : + Edge safety factor (tokamaks), or rotational transform iotabar (stellarators) + qstar : + Equivalent cylindrical edge safety factor + rmajor : + Plasma major radius (m) + rminor : + Plasma minor radius (m) + temp_plasma_electron_density_weighted_kev : + Density weighted average electron temperature (keV) + temp_plasma_ion_density_weighted_kev : + Density weighted average ion temperature (keV) + vol_plasma : + Plasma volume (m3) + a_plasma_poloidal : + Plasma cross-sectional area (m2) + zeff : + Plasma effective charge + + Returns + ------- + type + Tuple containing: - pden_electron_transport_loss_mw (float): Electron transport power (MW/m3) - pden_ion_transport_loss_mw (float): Ion transport power (MW/m3) - t_electron_energy_confinement (float): Electron energy confinement time (s) - t_ion_energy_confinement (float): Ion energy confinement time (s) - t_energy_confinement (float): Global energy confinement time (s) - p_plasma_loss_mw (float): Heating power (MW) assumed in calculation + """ # ======================================================================== @@ -7752,26 +8237,30 @@ def calculate_plasma_masses( vol_plasma: float, nd_plasma_electrons_vol_avg: float, ) -> tuple[float, float, float, float, float]: - """ - Calculate the plasma masses. - - :param m_fuel_amu: Average mass of fuel (amu). - :type m_fuel_amu: float - :param m_ions_total_amu: Average mass of all ions (amu). - :type m_ions_total_amu: float - :param nd_plasma_ions_total_vol_avg: Total ion density (/m3). - :type nd_plasma_ions_total_vol_avg: float - :param nd_plasma_fuel_ions_vol_avg: Fuel ion density (/m3). - :type nd_plasma_fuel_ions_vol_avg: float - :param nd_plasma_alphas_vol_avg: Alpha ash density (/m3). - :type nd_plasma_alphas_vol_avg: float - :param vol_plasma: Plasma volume (m3). - :type vol_plasma: float - :param nd_plasma_electrons_vol_avg: Volume averaged electron density (/m3). - :type nd_plasma_electrons_vol_avg: float - - :returns: A tuple containing: - :rtype: tuple[float, float, float, float, float] + """Calculate the plasma masses. + + Parameters + ---------- + m_fuel_amu : float + Average mass of fuel (amu). + m_ions_total_amu : float + Average mass of all ions (amu). + nd_plasma_ions_total_vol_avg : float + Total ion density (/m3). + nd_plasma_fuel_ions_vol_avg : float + Fuel ion density (/m3). + nd_plasma_alphas_vol_avg : float + Alpha ash density (/m3). + vol_plasma : float + Plasma volume (m3). + nd_plasma_electrons_vol_avg : float + Volume averaged electron density (/m3). + + Returns + ------- + tuple[float, float, float, float, float] + A tuple containing: + """ # Calculate mass of fuel ions @@ -7803,11 +8292,15 @@ def calculate_plasma_masses( def res_diff_time(rmajor, res_plasma, kappa95): """Calculates resistive diffusion time - Author: James Morris (UKAEA) + Parameters + ---------- + rmajor : + plasma major radius (m) + res_plasma : + plasma resistivity (Ohms) + kappa95 : + plasma elongation at 95% flux surface - :param rmajor: plasma major radius (m) - :param res_plasma: plasma resistivity (Ohms) - :param kappa95: plasma elongation at 95% flux surface """ return 2 * constants.RMU0 * rmajor / (res_plasma * kappa95) @@ -7824,30 +8317,34 @@ def l_h_threshold_power( aspect: float, plasma_current: float, ) -> list[float]: - """ - L-mode to H-mode power threshold calculation. - - :param nd_plasma_electron_line: Line-averaged electron density (/m3) - :type nd_plasma_electron_line: float - :param b_plasma_toroidal_on_axis: Toroidal field on axis (T) - :type b_plasma_toroidal_on_axis: float - :param rmajor: Plasma major radius (m) - :type rmajor: float - :param rminor: Plasma minor radius (m) - :type rminor: float - :param kappa: Plasma elongation - :type kappa: float - :param a_plasma_surface: Plasma surface area (m2) - :type a_plasma_surface: float - :param m_ions_total_amu: Average mass of all ions (amu) - :type m_ions_total_amu: float - :param aspect: Aspect ratio - :type aspect: float - :param plasma_current: Plasma current (A) - :type plasma_current: float - - :returns: Array of power thresholds - :rtype: list[float] + """L-mode to H-mode power threshold calculation. + + Parameters + ---------- + nd_plasma_electron_line : float + Line-averaged electron density (/m3) + b_plasma_toroidal_on_axis : float + Toroidal field on axis (T) + rmajor : float + Plasma major radius (m) + rminor : float + Plasma minor radius (m) + kappa : float + Plasma elongation + a_plasma_surface : float + Plasma surface area (m2) + m_ions_total_amu : float + Average mass of all ions (amu) + aspect : float + Aspect ratio + plasma_current : float + Plasma current (A) + + Returns + ------- + list[float] + Array of power thresholds + """ dnla20 = 1e-20 * nd_plasma_electron_line @@ -8018,19 +8515,29 @@ def l_h_threshold_power( def reinke_tsep(b_plasma_toroidal_on_axis, flh, qstar, rmajor, eps, fgw, kappa, lhat): """Function for calculating upstream temperature(keV) in Reinke model - author: H Lux, CCFE/UKAEA - b_plasma_toroidal_on_axis : input real : toroidal field on axis (T) - flh : input real : fraction of Psep/P_LH - qstar : input real : safety factor similar to q95 (see #707) - rmajor : input real : major radius (m) - eps : input real : inverse aspect ratio - fgw : input real : ratio of volume averaged density to n_GW - kappa : input real : elongation - lhat : input real : connection length factor This function calculates the upstream temperature in the divertor/SoL model used for the Reinke citerion. Issue #707 M.L. Reinke 2017 Nucl. Fusion 57 034004 + + Parameters + ---------_ + b_plasma_toroidal_on_axis : + toroidal field on axis (T) + flh : + fraction of Psep/P_LH + qstar : + safety factor similar to q95 (see #707) + rmajor : + major radius (m) + eps : + inverse aspect ratio + fgw : + ratio of volume averaged density to n_GW + kappa : + elongation + lhat : + connection length factor """ kappa_0 = 2.0e3 # Stangeby W/m/eV^(7/2) @@ -8066,7 +8573,12 @@ def __init__(self): self.mfile = constants.MFILE def get_beta_norm_max_value(self, model: BetaNormMaxModel) -> float: - """Get the beta norm max value (β_N_max) for the specified model.""" + """Get the beta norm max value (β_N_max) for the specified model. + + Parameters + ---------- + model: BetaNormMaxModel : + """ model_map = { BetaNormMaxModel.USER_INPUT: physics_variables.beta_norm_max, BetaNormMaxModel.WESSON: physics_variables.beta_norm_max_wesson, @@ -8077,10 +8589,8 @@ def get_beta_norm_max_value(self, model: BetaNormMaxModel) -> float: } return model_map[model] - def run(self) -> None: - """ - Calculate plasma beta values. - """ + def run(self): + """Calculate plasma beta values.""" # ----------------------------------------------------- # Normalised Beta Limit @@ -8248,81 +8758,99 @@ def run(self) -> None: def calculate_plasma_beta( pres_plasma: float | np.ndarray, b_field: float | np.ndarray ) -> float | np.ndarray: - """ - Calculate the plasma beta (β) for a given pressure and field. - - :param pres_plasma: Plasma pressure (in Pascals). - :type pres_plasma: float | np.ndarray - :param b_field: Magnetic field strength (in Tesla). - :type b_field: float | np.ndarray - :returns: The plasma beta (dimensionless). - :rtype: float | np.ndarray + """Calculate the plasma beta (β) for a given pressure and field. Plasma beta is the ratio of plasma pressure to magnetic pressure. + + Parameters + ---------- + pres_plasma : float | np.ndarray + Plasma pressure (in Pascals). + b_field : float | np.ndarray + Magnetic field strength (in Tesla). + + Returns + ------- + float | np.ndarray + The plasma beta (dimensionless). """ return 2 * constants.RMU0 * pres_plasma / (b_field**2) @staticmethod def calculate_beta_norm_max_wesson(ind_plasma_internal_norm: float) -> float: - """ - Calculate the Wesson normalsied beta upper limit. + """Calculate the Wesson normalsied beta upper limit. - :param ind_plasma_internal_norm: Plasma normalised internal inductance - :type ind_plasma_internal_norm: float + Parameters + ---------- + ind_plasma_internal_norm : float + Plasma normalised internal inductance - :return: The Wesson normalised beta upper limit. - :rtype: float - :Notes: - - It is recommended to use this method with the other Wesson relations for normalsied internal - inductance and current profile index. - - This fit is derived from the DIII-D database for β_N >= 2.5 + Returns + ------- + float + The Wesson normalised beta upper limit. - :References: - - Wesson, J. (2011) Tokamaks. 4th Edition, 2011 Oxford Science Publications, - International Series of Monographs on Physics, Volume 149. + Notes + ----- + - It is recommended to use this method with the other Wesson relations for normalsied internal + inductance and current profile index. + - This fit is derived from the DIII-D database for β_N >= 2.5 + + References + ---------- + - Wesson, J. (2011) Tokamaks. 4th Edition, 2011 Oxford Science Publications, + International Series of Monographs on Physics, Volume 149. + + - T. T. S et al., “Profile Optimization and High Beta Discharges and Stability of High Elongation Plasmas in the DIII-D Tokamak,” + Osti.gov, Oct. 1990. https://www.osti.gov/biblio/6194284 (accessed Dec. 19, 2024). - - T. T. S et al., “Profile Optimization and High Beta Discharges and Stability of High Elongation Plasmas in the DIII-D Tokamak,” - Osti.gov, Oct. 1990. https://www.osti.gov/biblio/6194284 (accessed Dec. 19, 2024). """ return 4 * ind_plasma_internal_norm @staticmethod def calculate_beta_norm_max_original(eps: float) -> float: - """ - Calculate the original scaling law normalsied beta upper limit. - - :param eps: Plasma normalised internal inductance - :type eps: float + """Calculate the original scaling law normalsied beta upper limit. - :return: The original scaling law normalised beta upper limit. - :rtype: float + Parameters + ---------- + eps : float + Plasma normalised internal inductance - :Notes: + Returns + ------- + float - :References: + References + ---------- + The original scaling law normalised beta upper limit. """ return 2.7 * (1.0 + 5.0 * eps**3.5) @staticmethod def calculate_beta_norm_max_menard(eps: float) -> float: - """ - Calculate the Menard normalsied beta upper limit. + """Calculate the Menard normalsied beta upper limit. - :param eps: Plasma normalised internal inductance - :type eps: float + Parameters + ---------- + eps : float + Plasma normalised internal inductance - :return: The Menard normalised beta upper limit. - :rtype: float + Returns + ------- + float + The Menard normalised beta upper limit. - :Notes: + Notes + ----- - Found as a reasonable fit to the computed no wall limit at f_BS ≈ 50% - Uses maximum κ data from NSTX at A = 1.45, A = 1.75. Along with record β_T data from DIII-D at A = 2.9 and high κ. - :References: + References + ---------- - # J. E. Menard et al., “Fusion nuclear science facilities and pilot plants based on the spherical tokamak,” Nuclear Fusion, vol. 56, no. 10, p. 106023, Aug. 2016, doi: https://doi.org/10.1088/0029-5515/56/10/106023. @@ -8334,27 +8862,39 @@ def calculate_beta_norm_max_menard(eps: float) -> float: def calculate_beta_norm_max_thloreus( c_beta: float, pres_plasma_on_axis: float, pres_plasma_vol_avg: float ) -> float: - """ - Calculate the E. Tholerus normalized beta upper limit. + """Calculate the E. Tholerus normalized beta upper limit. + + Parameters + ---------- + c_beta : float + Pressure peaking factor coefficient. + pres_plasma_on_axis : float + Central plasma pressure (Pa). + pres_plasma_vol_avg : float + Volume-averaged plasma pressure (Pa). + c_beta: float : + + pres_plasma_on_axis: float : - :param c_beta: Pressure peaking factor coefficient. - :type c_beta: float - :param pres_plasma_on_axis: Central plasma pressure (Pa). - :type pres_plasma_on_axis: float - :param pres_plasma_vol_avg: Volume-averaged plasma pressure (Pa). - :type pres_plasma_vol_avg: float + pres_plasma_vol_avg: float : - :return: The E. Tholerus normalized beta upper limit. - :rtype: float - :Notes: + Returns + ------- + float + The E. Tholerus normalized beta upper limit. + + Notes + ----- - This method calculates the normalized beta upper limit based on the pressure peaking factor (Fp), which is defined as the ratio of the peak pressure to the average pressure. - The formula is derived from operational space studies of flat-top plasma in the STEP power plant. - :References: + References + ---------- - E. Tholerus et al., “Flat-top plasma operational space of the STEP power plant,” Nuclear Fusion, Aug. 2024, doi: https://doi.org/10.1088/1741-4326/ad6ea2. + """ return 3.7 + ( (c_beta / (pres_plasma_on_axis / pres_plasma_vol_avg)) @@ -8367,24 +8907,30 @@ def calculate_beta_norm_max_stambaugh( kappa: float, aspect: float, ) -> float: - """ - Calculate the Stambaugh normalized beta upper limit. + """Calculate the Stambaugh normalized beta upper limit. - :param f_c_plasma_bootstrap: Bootstrap current fraction. - :type f_c_plasma_bootstrap: float - :param kappa: Plasma separatrix elongation. - :type kappa: float - :param aspect: Plasma aspect ratio. - :type aspect: float + Parameters + ---------- + f_c_plasma_bootstrap : float + Bootstrap current fraction. + kappa : float + Plasma separatrix elongation. + aspect : float + Plasma aspect ratio. - :return: The Stambaugh normalized beta upper limit. - :rtype: float - :Notes: + Returns + ------- + float + The Stambaugh normalized beta upper limit. + + Notes + ----- - This method calculates the normalized beta upper limit based on the Stambaugh scaling. - The formula is derived from empirical fits to high-performance, steady-state tokamak equilibria. - :References: + References + ---------- - R. D. Stambaugh et al., “Fusion Nuclear Science Facility Candidates,” Fusion Science and Technology, vol. 59, no. 2, pp. 279-307, Feb. 2011, doi: https://doi.org/10.13182/fst59-279. @@ -8392,6 +8938,7 @@ def calculate_beta_norm_max_stambaugh( - Y. R. Lin-Liu and R. D. Stambaugh, “Optimum equilibria for high performance, steady state tokamaks,” Nuclear Fusion, vol. 44, no. 4, pp. 548-554, Mar. 2004, doi: https://doi.org/10.1088/0029-5515/44/4/009. + """ return ( f_c_plasma_bootstrap @@ -8406,20 +8953,27 @@ def calculate_normalised_beta( ) -> float: """Calculate normalised beta (β_N). - :param beta: Plasma beta (fraction). - :type beta: float - :param rminor: Plasma minor radius (m). - :type rminor: float - :param c_plasma: Plasma current (A). - :type c_plasma: float - :param b_field: Magnetic field (T). - :type b_field: float - :return: Normalised beta. - :rtype: float - - :Notes: - - 1.0e8 is a conversion factor to get beta_N in standard units, as plasma current is normally in MA and - beta is in percentage instead of fraction. + Parameters + ---------- + beta : float + Plasma beta (fraction). + rminor : float + Plasma minor radius (m). + c_plasma : float + Plasma current (A). + b_field : float + Magnetic field (T). + + Returns + ------- + float + Normalised beta. + + Notes + ----- + - 1.0e8 is a conversion factor to get beta_N in standard units, as plasma current is normally in MA and + beta is in percentage instead of fraction. + """ return 1.0e8 * (beta * rminor * b_field) / c_plasma @@ -8432,15 +8986,19 @@ def calculate_plasma_energy_from_beta( E_plasma = 1.5 * β * B² / (2 * μ_0) * V - :param beta: Plasma beta (fraction). - :type beta: float - :param b_field: Magnetic field (T). - :type b_field: float - :param vol_plasma: Plasma volume (m³). - :type vol_plasma: float - :return: Plasma energy (J). - :rtype: float - + Parameters + ---------- + beta : float + Plasma beta (fraction). + b_field : float + Magnetic field (T). + vol_plasma : float + Plasma volume (m³). + + Returns + ------- + float + Plasma energy (J). """ return (1.5e0 * beta * b_field**2) / (2.0e0 * constants.RMU0) * vol_plasma @@ -8452,25 +9010,30 @@ def calculate_beta_limit_from_norm( plasma_current: float, rminor: float, ) -> float: - """ - Calculate the maximum allowed beta (β) from a given normalised (β_N). - - :param b_plasma_toroidal_on_axis: Toroidal B-field on plasma axis [T]. - :type b_plasma_toroidal_on_axis: float - :param beta_norm_max: Troyon-like g coefficient. - :type beta_norm_max: float - :param plasma_current: Plasma current [A]. - :type plasma_current: float - :param rminor: Plasma minor axis [m]. - :type rminor: float - :return: Beta limit as defined below. - :rtype: float + """Calculate the maximum allowed beta (β) from a given normalised (β_N). This subroutine calculates the beta limit using the algorithm documented in AEA FUS 172. The limit applies to beta defined with respect to the total B-field. Switch i_beta_component determines which components of beta to include. - Notes: + Parameters + ---------- + b_plasma_toroidal_on_axis : float + Toroidal B-field on plasma axis [T]. + beta_norm_max : float + Troyon-like g coefficient. + plasma_current : float + Plasma current [A]. + rminor : float + Plasma minor axis [m]. + + Returns + ------- + float + Beta limit as defined below. + + Notes + ----- - If i_beta_component = 0, then the limit is applied to the total beta. - If i_beta_component = 1, then the limit is applied to the thermal beta only. - If i_beta_component = 2, then the limit is applied to the thermal + neutral beam beta components. @@ -8478,13 +9041,13 @@ def calculate_beta_limit_from_norm( - The default value for the g coefficient is beta_norm_max = 3.5. - References: + References + ---------- - F. Troyon et.al, “Beta limit in tokamaks. Experimental and computational status,” Plasma Physics and Controlled Fusion, vol. 30, no. 11, pp. 1597-1609, Oct. 1988, doi: https://doi.org/10.1088/0741-3335/30/11/019. - T.C.Hender et.al., 'Physics Assesment of the European Reactor Study', AEA FUS 172, 1992 - """ # Multiplied by 0.01 to convert from % to fraction @@ -8501,16 +9064,21 @@ def calculate_poloidal_beta( ) -> float: """Calculates total poloidal beta (β_p) - :type b_plasma_total: float - :param b_plasma_poloidal_average: The average poloidal magnetic field of the plasma (in Tesla). - :type b_plasma_poloidal_average: float - :param beta: The plasma beta, a dimensionless parameter representing the ratio of plasma pressure to magnetic pressure. - :type beta: float - :return: The calculated total poloidal beta. - :rtype: float - - :references: - - J.P. Freidberg, "Plasma physics and fusion energy", Cambridge University Press (2007) + Parameters + ---------- + b_plasma_poloidal_average : float + The average poloidal magnetic field of the plasma (in Tesla). + beta : float + The plasma beta, a dimensionless parameter representing the ratio of plasma pressure to magnetic pressure. + + Returns + ------- + float + The calculated total poloidal beta. + + References + ---------- + - J.P. Freidberg, "Plasma physics and fusion energy", Cambridge University Press (2007) Page 270 ISBN 0521851076 """ @@ -8529,40 +9097,45 @@ def fast_alpha_beta( pden_plasma_alpha_mw: float, i_beta_fast_alpha: int, ) -> float: - """ - Calculate the fast alpha beta (β_fast_alpha) component. + """Calculate the fast alpha beta (β_fast_alpha) component. This function computes the fast alpha beta contribution based on the provided plasma parameters. - :param b_plasma_poloidal_average: Poloidal field (T). - :type b_plasma_poloidal_average: float - :param b_plasma_toroidal_on_axis: Toroidal field on axis (T). - :type b_plasma_toroidal_on_axis: float - :param nd_plasma_electrons_vol_avg: Electron density (m⁻³). - :type nd_plasma_electrons_vol_avg: float - :param nd_plasma_fuel_ions_vol_avg: Fuel ion density (m⁻³). - :type nd_plasma_fuel_ions_vol_avg: float - :param nd_plasma_ions_total_vol_avg: Total ion density (m⁻³). - :type nd_plasma_ions_total_vol_avg: float - :param temp_plasma_electron_density_weighted_kev: Density-weighted electron temperature (keV). - :type temp_plasma_electron_density_weighted_kev: float - :param temp_plasma_ion_density_weighted_kev: Density-weighted ion temperature (keV). - :type temp_plasma_ion_density_weighted_kev: float - :param pden_alpha_total_mw: Alpha power per unit volume, from beams and plasma (MW/m³). - :type pden_alpha_total_mw: float - :param pden_plasma_alpha_mw: Alpha power per unit volume just from plasma (MW/m³). - :type pden_plasma_alpha_mw: float - :param i_beta_fast_alpha: Switch for fast alpha pressure method. - :type i_beta_fast_alpha: int - - :return: Fast alpha beta component. - :rtype: float - - :Notes: + Parameters + ---------- + b_plasma_poloidal_average : float + Poloidal field (T). + b_plasma_toroidal_on_axis : float + Toroidal field on axis (T). + nd_plasma_electrons_vol_avg : float + Electron density (m⁻³). + nd_plasma_fuel_ions_vol_avg : float + Fuel ion density (m⁻³). + nd_plasma_ions_total_vol_avg : float + Total ion density (m⁻³). + temp_plasma_electron_density_weighted_kev : float + Density-weighted electron temperature (keV). + temp_plasma_ion_density_weighted_kev : float + Density-weighted ion temperature (keV). + pden_alpha_total_mw : float + Alpha power per unit volume, from beams and plasma (MW/m³). + pden_plasma_alpha_mw : float + Alpha power per unit volume just from plasma (MW/m³). + i_beta_fast_alpha : int + Switch for fast alpha pressure method. + + Returns + ------- + float + Fast alpha beta component. + + Notes + ----- - For IPDG89 scaling applicability is Z_eff = 1.5, T_i/T_e = 1, 〈T〉 = 5-20 keV - :References: + References + ---------- - N.A. Uckan and ITER Physics Group, 'ITER Physics Design Guidelines: 1989', https://inis.iaea.org/collection/NCLCollectionStore/_Public/21/068/21068960.pdf @@ -8935,7 +9508,12 @@ def run(self): ) from None def get_ind_internal_norm_value(self, model: IndInternalNormModel) -> float: - """Get the normalised internal inductance (l_i) for the specified model.""" + """Get the normalised internal inductance (l_i) for the specified model. + + Parameters + ---------- + model: IndInternalNormModel : + """ model_map = { IndInternalNormModel.USER_INPUT: physics_variables.ind_plasma_internal_norm, IndInternalNormModel.WESSON: physics_variables.ind_plasma_internal_norm_wesson, @@ -8959,30 +9537,36 @@ def calculate_volt_second_requirements( ) -> tuple[float, float, float, float, float, float]: """Calculate the volt-second requirements and related parameters for plasma physics. - :param csawth: Coefficient for sawteeth effects - :type csawth: float - :param eps: Inverse aspect ratio - :type eps: float - :param f_c_plasma_inductive: Fraction of plasma current produced inductively - :type f_c_plasma_inductive: float - :param ejima_coeff: Ejima coefficient for resistive start-up V-s component - :type ejima_coeff: float - :param kappa: Plasma elongation - :type kappa: float - :param rmajor: Plasma major radius (m) - :type rmajor: float - :param res_plasma: Plasma resistance (ohm) - :type res_plasma: float - :param plasma_current: Plasma current (A) - :type plasma_current: float - :param t_plant_pulse_fusion_ramp: Heating time (s) - :type t_plant_pulse_fusion_ramp: float - :param t_plant_pulse_burn: Burn time (s) - :type t_plant_pulse_burn: float - :param ind_plasma_internal_norm: Plasma normalized internal inductance - :type ind_plasma_internal_norm: float - - :return: A tuple containing: + Parameters + ---------- + csawth : float + Coefficient for sawteeth effects + eps : float + Inverse aspect ratio + f_c_plasma_inductive : float + Fraction of plasma current produced inductively + ejima_coeff : float + Ejima coefficient for resistive start-up V-s component + kappa : float + Plasma elongation + rmajor : float + Plasma major radius (m) + res_plasma : float + Plasma resistance (ohm) + plasma_current : float + Plasma current (A) + t_plant_pulse_fusion_ramp : float + Heating time (s) + t_plant_pulse_burn : float + Burn time (s) + ind_plasma_internal_norm : float + Plasma normalized internal inductance + + + Returns + ------- + tuple[float, float, float, float, float, float] + A tuple containing: - vs_plasma_internal: Internal plasma volt-seconds (Wb) - ind_plasma_internal: Plasma inductance (H) - vs_plasma_burn_required: Volt-seconds needed during flat-top (heat+burn) (Wb) @@ -8990,11 +9574,9 @@ def calculate_volt_second_requirements( - ind_plasma_total,: Internal and external plasma inductance V-s (Wb) - vs_res_ramp: Resistive losses in start-up volt-seconds (Wb) - vs_plasma_total_required: Total volt-seconds needed (Wb) - :rtype: tuple[float, float, float, float, float, float] - :notes: - - :references: + References + ---------- - S. Ejima, R. W. Callis, J. L. Luxon, R. D. Stambaugh, T. S. Taylor, and J. C. Wesley, “Volt-second analysis and consumption in Doublet III plasmas,” Nuclear Fusion, vol. 22, no. 10, pp. 1313-1319, Oct. 1982, doi: @@ -9008,6 +9590,7 @@ def calculate_volt_second_requirements( - S. P. Hirshman and G. H. Neilson, “External inductance of an axisymmetric plasma,” The Physics of Fluids, vol. 29, no. 3, pp. 790-793, Mar. 1986, doi: https://doi.org/10.1063/1.865934. + """ # Plasma internal inductance @@ -9078,22 +9661,26 @@ def calculate_normalised_internal_inductance_iter_3( vol_plasma: float, rmajor: float, ) -> float: - """ - Calculate the normalised internal inductance using ITER-3 scaling li(3). - - :param b_plasma_poloidal_vol_avg: Volume-averaged poloidal magnetic field (T). - :type b_plasma_poloidal_vol_avg: float - :param c_plasma: Plasma current (A). - :type c_plasma: float - :param vol_plasma: Plasma volume (m^3). - :type vol_plasma: float - :param rmajor: Plasma major radius (m). - :type rmajor: float - - :returns: The li(3) normalised internal inductance. - :rtype: float - - :references: + """Calculate the normalised internal inductance using ITER-3 scaling li(3). + + Parameters + ------------ + b_plasma_poloidal_vol_avg : float + Volume-averaged poloidal magnetic field (T). + c_plasma : float + Plasma current (A). + vol_plasma : float + Plasma volume (m^3). + rmajor : float + Plasma major radius (m). + + Returns + -------- + float + The li(3) normalised internal inductance. + + References + ----------- - T. C. Luce, D. A. Humphreys, G. L. Jackson, and W. M. Solomon, “Inductive flux usage and its optimization in tokamak operation,” Nuclear Fusion, vol. 54, no. 9, p. 093005, Jul. 2014, @@ -9102,7 +9689,7 @@ def calculate_normalised_internal_inductance_iter_3( - G. L. Jackson et al., “ITER startup studies in the DIII-D tokamak,” Nuclear Fusion, vol. 48, no. 12, p. 125002, Nov. 2008, doi: https://doi.org/10.1088/0029-5515/48/12/125002. - ‌ + """ return ( @@ -9114,45 +9701,57 @@ def calculate_normalised_internal_inductance_iter_3( @staticmethod def calculate_internal_inductance_menard(kappa: float) -> float: - """ - Calculate the Menard plasma normalized internal inductance. + """Calculate the Menard plasma normalized internal inductance. - :param kappa: Plasma separatrix elongation. - :type kappa: float + Parameters + ---------- + kappa : float + Plasma separatrix elongation. - :return: The Menard plasma normalised internal inductance. - :rtype: float + Returns + ------- + float + The Menard plasma normalised internal inductance. - :Notes: + Notes + ----- - This relation is based off of data from NSTX for l_i in the range of 0.4-0.85 - - This model is only recommneded to be used for ST's with kappa > 2.5 + - This model is only recommended to be used for ST's with kappa > 2.5 - :References: + References + ---------- - J. E. Menard et al., “Fusion nuclear science facilities and pilot plants based on the spherical tokamak,” Nuclear Fusion, vol. 56, no. 10, p. 106023, Aug. 2016, doi: https://doi.org/10.1088/0029-5515/56/10/106023. + """ return 3.4 - kappa @staticmethod def calculate_internal_inductance_wesson(alphaj: float) -> float: - """ - Calculate the Wesson plasma normalized internal inductance. + """Calculate the Wesson plasma normalized internal inductance. - :param alphaj: Current profile index. - :type alphaj: float + Parameters + ---------- + alphaj : float + Current profile index. - :return: The Wesson plasma normalised internal inductance. - :rtype: float + Returns + ------- + float + The Wesson plasma normalised internal inductance. - :Notes: + Notes + ----- - It is recommended to use this method with the other Wesson relations for normalised beta and current profile index. - This relation is only true for the cyclindrical plasma approximation with parabolic profiles. - :References: + References + ---------- - Wesson, J. (2011) Tokamaks. 4th Edition, 2011 Oxford Science Publications, International Series of Monographs on Physics, Volume 149. + """ return np.log(1.65 + 0.89 * alphaj) @@ -9462,16 +10061,20 @@ def calculate_debye_length( temp_plasma_species_kev: float | np.ndarray, nd_plasma_species: float | np.ndarray, ) -> float | np.ndarray: - """ - Calculate the Debye length for a plasma. + """Calculate the Debye length for a plasma. + + Parameters + ---------- + temp_plasma_species_kev : float | np.ndarray + Species temperature in keV. + nd_plasma_species : float | np.ndarray + Species number density (/m^3). - :param temp_plasma_species_kev: Species temperature in keV. - :type temp_plasma_species_kev: float | np.ndarray - :param nd_plasma_species: Species number density (/m^3). - :type nd_plasma_species: float | np.ndarray + Returns + ------- + float | np.ndarray + Debye length in meters. - :returns: Debye length in meters. - :rtype: float | np.ndarray """ return ( (constants.EPSILON0 * temp_plasma_species_kev * constants.KILOELECTRON_VOLT) @@ -9480,12 +10083,18 @@ def calculate_debye_length( @staticmethod def calculate_lorentz_factor(velocity: float | np.ndarray) -> float | np.ndarray: - """ - Calculate the Lorentz factor for a given velocity. - :param velocity: Velocity in m/s. - :type velocity: float | np.ndarray - :returns: Lorentz factor (dimensionless). - :rtype: float | np.ndarray + """Calculate the Lorentz factor for a given velocity. + + Parameters + ---------- + velocity : float | np.ndarray + Velocity in m/s. + + Returns + ------- + float | np.ndarray + Lorentz factor (dimensionless). + """ return 1 / (1 - (velocity / constants.SPEED_LIGHT) ** 2) ** 0.5 @@ -9493,14 +10102,20 @@ def calculate_lorentz_factor(velocity: float | np.ndarray) -> float | np.ndarray def calculate_relativistic_particle_speed( e_kinetic: float | np.ndarray, mass: float ) -> float | np.ndarray: - """ - Calculate the speed of a particle given its kinetic energy and mass using relativistic mechanics. - :param e_kinetic: Kinetic energy in Joules. - :type e_kinetic: float | np.ndarray - :param mass: Mass of the particle in kg. - :type mass: float - :returns: Speed of the particle in m/s. - :rtype: float | np.ndarray + """Calculate the speed of a particle given its kinetic energy and mass using relativistic mechanics. + + Parameters + ---------- + e_kinetic : float | np.ndarray + Kinetic energy in Joules. + mass : float + Mass of the particle in kg. + + Returns + ------- + float | np.ndarray + Speed of the particle in m/s. + """ return ( constants.SPEED_LIGHT @@ -9511,14 +10126,20 @@ def calculate_relativistic_particle_speed( def calculate_coulomb_log_from_impact( self, impact_param_max: float, impact_param_min: float ) -> float: - """ - Calculate the Coulomb logarithm from maximum and minimum impact parameters. - :param impact_param_max: Maximum impact parameter in meters. - :type impact_param_max: float - :param impact_param_min: Minimum impact parameter in meters. - :type impact_param_min: float - :returns: Coulomb logarithm (dimensionless). - :rtype: float + """Calculate the Coulomb logarithm from maximum and minimum impact parameters. + + Parameters + ---------- + impact_param_max : float + Maximum impact parameter in meters. + impact_param_min : float + Minimum impact parameter in meters. + + Returns + ------- + float + Coulomb logarithm (dimensionless). + """ return np.log(impact_param_max / impact_param_min) @@ -9529,19 +10150,23 @@ def calculate_classical_distance_of_closest_approach( m_reduced: float, vel_relative: float | np.ndarray, ) -> float | np.ndarray: - """ - Calculate the classical distance of closest approach for two charged particles. - - :param charge1: Charge of particle 1 in units of elementary charge. - :type charge1: float - :param charge2: Charge of particle 2 in units of elementary charge. - :type charge2: float - :param m_reduced: Reduced mass of the two-particle system in kg. - :type m_reduced: float - :param vel_relative: Relative velocity of the two particles in m/s. - :type vel_relative: float | np.ndarray - :returns: Distance of closest approach in meters. - :rtype: float | np.ndarray + """Calculate the classical distance of closest approach for two charged particles. + + Parameters + ---------- + charge1 : + Charge of particle 1 in units of elementary charge. + charge2 : + Charge of particle 2 in units of elementary charge. + m_reduced: + Reduced mass of the two-particle system in kg. + vel_relative: + Relative velocity of the two particles in m/s. + + Returns + ------- + float | np.ndarray + Distance of closest approach in meters. """ return (charge1 * charge2 * constants.ELECTRON_CHARGE**2) / ( @@ -9552,16 +10177,22 @@ def calculate_classical_distance_of_closest_approach( def calculate_debroglie_wavelength( mass: float, velocity: float | np.ndarray ) -> float | np.ndarray: - """ - Calculate the de Broglie wavelength of a particle. - :param mass: Mass of the particle in kg. - :type mass: float - :param velocity: Velocity of the particle in m/s. - :type velocity: float | np.ndarray - :returns: de Broglie wavelength in meters. - :rtype: float | np.ndarray + """Calculate the de Broglie wavelength of a particle. + + Parameters + ---------- + mass : float + Mass of the particle in kg. + velocity : float | np.ndarray + Velocity of the particle in m/s. + + Returns + ------- + float | np.ndarray + de Broglie wavelength in meters. :note: Reduced Planck constant (h-bar) is used in the calculation as this is for scattering. + """ return (constants.PLANCK_CONSTANT / (2 * np.pi)) / (mass * velocity) @@ -9569,16 +10200,22 @@ def calculate_debroglie_wavelength( def calculate_plasma_frequency( nd_particle: float | np.ndarray, m_particle: float, z_particle: float ) -> float | np.ndarray: - """ - Calculate the plasma frequency for a particle species. - :param nd_particle: Number density of the particle species (/m^3). - :type nd_particle: float | np.ndarray - :param m_particle: Mass of the particle species (kg). - :type m_particle: float - :param Z_particle: Charge state of the particle species (dimensionless). - :type Z_particle: float - :returns: Plasma frequency in Hz. - :rtype: float | np.ndarray + """Calculate the plasma frequency for a particle species. + + Parameters + ---------- + nd_particle : float | np.ndarray + Number density of the particle species (/m^3). + m_particle : float + Mass of the particle species (kg). + Z_particle : float + Charge state of the particle species (dimensionless). + + Returns + ------- + float | np.ndarray + Plasma frequency in Hz. + """ return ( ( @@ -9592,16 +10229,22 @@ def calculate_plasma_frequency( def calculate_larmor_frequency( b_field: float | np.ndarray, m_particle: float, z_particle: float ) -> float | np.ndarray: - """ - Calculate the Larmor frequency for a particle species. - :param b_field: Magnetic field strength (T). - :type b_field: float | np.ndarray - :param m_particle: Mass of the particle species (kg). - :type m_particle: float - :param Z_particle: Charge state of the particle species (dimensionless). - :type Z_particle: float - :returns: Larmor frequency in Hz. - :rtype: float | np.ndarray + """Calculate the Larmor frequency for a particle species. + + Parameters + ---------- + b_field : float | np.ndarray + Magnetic field strength (T). + m_particle : float + Mass of the particle species (kg). + Z_particle : float + Charge state of the particle species (dimensionless). + + Returns + ------- + float | np.ndarray + Larmor frequency in Hz. + """ return (z_particle * constants.ELECTRON_CHARGE * b_field) / ( 2 * np.pi * m_particle @@ -9611,12 +10254,17 @@ def calculate_larmor_frequency( def calculate_reduced_mass(mass1: float, mass2: float) -> float: """ Calculate the reduced mass of two particles. - :param mass1: Mass of particle 1 (kg). - :type mass1: float - :param mass2: Mass of particle 2 (kg). - :type mass2: float - :returns: Reduced mass (kg). - :rtype: float + + Parameters + ---------- + mass1: + Mass of particle 1 (kg). + mass2: + Mass of particle 2 (kg). + + Returns + ------- + Reduced mass (kg). """ return (mass1 * mass2) / (mass1 + mass2) @@ -9626,12 +10274,17 @@ def calculate_average_relative_velocity( ) -> float | np.ndarray: """ Calculate the average relative velocity between two particles. - :param velocity_1: Velocity of particle 1 (m/s). - :type velocity_1: float | np.ndarray - :param velocity_2: Velocity of particle 2 (m/s). - :type velocity_2: float | np.ndarray - :returns: Average relative velocity (m/s). - :rtype: float | np.ndarray + + Parameters + ---------- + velocity_1: + Velocity of particle 1 (m/s). + velocity_2: + Velocity of particle 2 (m/s). + + Returns + ------- + Average relative velocity (m/s). """ return np.sqrt(velocity_1**2 + velocity_2**2) diff --git a/process/physics_functions.py b/process/physics_functions.py index de5382776f..003ecb63f2 100644 --- a/process/physics_functions.py +++ b/process/physics_functions.py @@ -34,53 +34,56 @@ def calculate_radiation_powers( kappa: float, vol_plasma: float, ) -> RadpwrData: - """ - Calculate the radiation powers in MW/m^3 by calling relevant routines. + """Calculate the radiation powers in MW/m^3 by calling relevant routines. This function computes the radiation power densities for the plasma, including impurity radiation and synchrotron radiation. It returns a dataclass containing the calculated radiation power densities. - :param plasma_profile: The parameterized temperature and density profiles of the plasma. - :type plasma_profile: PlasmaProfile - :param nd_plasma_electron_on_axis: Central electron density (m^-3). - :type nd_plasma_electron_on_axis: float - :param rminor: Minor radius of the plasma (m). - :type rminor: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field (T). - :type b_plasma_toroidal_on_axis: float - :param aspect: Aspect ratio of the plasma. - :type aspect: float - :param alphan: Alpha parameter for density profile. - :type alphan: float - :param alphat: Alpha parameter for temperature profile. - :type alphat: float - :param tbeta: Beta parameter for temperature profile. - :type tbeta: float - :param temp_plasma_electron_on_axis_kev: Central electron temperature (keV). - :type temp_plasma_electron_on_axis_kev: float - :param f_sync_reflect: Fraction of synchrotron radiation reflected. - :type f_sync_reflect: float - :param rmajor: Major radius of the plasma (m). - :type rmajor: float - :param kappa: Elongation of the plasma. - :type kappa: float - :param vol_plasma: Plasma volume (m^3). - :type vol_plasma: float - - :returns: A dataclass containing the following radiation power densities: - - pden_plasma_sync_mw (float): Synchrotron radiation power per unit volume (MW/m^3). - - pden_plasma_core_rad_mw (float): Total core radiation power per unit volume (MW/m^3). - - pden_plasma_outer_rad_mw (float): Edge radiation power per unit volume (MW/m^3). - - pden_plasma_rad_mw (float): Total radiation power per unit volume (MW/m^3). - :rtype: RadpwrData - - :references: + Parameters + ---------- + plasma_profile : PlasmaProfile + The parameterized temperature and density profiles of the plasma. + nd_plasma_electron_on_axis : float + Central electron density (m^-3). + rminor : float + Minor radius of the plasma (m). + b_plasma_toroidal_on_axis : float + Toroidal magnetic field (T). + aspect : float + Aspect ratio of the plasma. + alphan : float + Alpha parameter for density profile. + alphat : float + Alpha parameter for temperature profile. + tbeta : float + Beta parameter for temperature profile. + temp_plasma_electron_on_axis_kev : float + Central electron temperature (keV). + f_sync_reflect : float + Fraction of synchrotron radiation reflected. + rmajor : float + Major radius of the plasma (m). + kappa : float + Elongation of the plasma. + vol_plasma : float + Plasma volume (m^3). + + Returns + ------- + RadpwrData + A dataclass containing the following radiation power densities: + - pden_plasma_sync_mw (float): Synchrotron radiation power per unit volume (MW/m^3). + - pden_plasma_core_rad_mw (float): Total core radiation power per unit volume (MW/m^3). + - pden_plasma_outer_rad_mw (float): Edge radiation power per unit volume (MW/m^3). + - pden_plasma_rad_mw (float): Total radiation power per unit volume (MW/m^3). + + References + ---------- - F. Albajar, J. Johner, and G. Granata, “Improved calculation of synchrotron radiation losses in realistic tokamak plasmas,” Nuclear Fusion, vol. 41, no. 6, pp. 665-678, Jun. 2001, doi: https://doi.org/10.1088/0029-5515/41/6/301. - I. Fidone, G Giruzzi, and G. Granata, “Synchrotron radiation loss in tokamaks of arbitrary geometry,” Nuclear Fusion, vol. 41, no. 12, pp. 1755-1758, Dec. 2001, doi: https://doi.org/10.1088/0029-5515/41/12/102. - """ imp_rad = impurity.ImpurityRadiation(plasma_profile) imp_rad.calculate_imprad() @@ -135,46 +138,50 @@ def psync_albajar_fidone( kappa: float, vol_plasma: float, ) -> float: - """ - Calculate the synchrotron radiation power in MW/m^3. + """Calculate the synchrotron radiation power in MW/m^3. This function computes the synchrotron radiation power density for the plasma based on the plasma shape, major and minor radii, electron density, and temperature profiles. - :param nd_plasma_electron_on_axis: Central electron density (m^-3). - :type nd_plasma_electron_on_axis: float - :param rminor: Minor radius of the plasma (m). - :type rminor: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field (T). - :type b_plasma_toroidal_on_axis: float - :param aspect: Aspect ratio of the plasma. - :type aspect: float - :param alphan: Alpha parameter for density profile. - :type alphan: float - :param alphat: Alpha parameter for temperature profile. - :type alphat: float - :param tbeta: Beta parameter for temperature profile. - :type tbeta: float - :param temp_plasma_electron_on_axis_kev: Central electron temperature (keV). - :type temp_plasma_electron_on_axis_kev: float - :param f_sync_reflect: Fraction of synchrotron radiation reflected. - :type f_sync_reflect: float - :param rmajor: Major radius of the plasma (m). - :type rmajor: float - :param kappa: Elongation of the plasma. - :type kappa: float - :param vol_plasma: Plasma volume (m^3). - :type vol_plasma: float - - :returns: Synchrotron radiation power per unit volume (MW/m^3). - :rtype: float - - :references: - - F. Albajar, J. Johner, and G. Granata, “Improved calculation of synchrotron radiation losses in realistic tokamak plasmas,” - Nuclear Fusion, vol. 41, no. 6, pp. 665-678, Jun. 2001, doi: https://doi.org/10.1088/0029-5515/41/6/301. - - - I. Fidone, G Giruzzi, and G. Granata, “Synchrotron radiation loss in tokamaks of arbitrary geometry,” - Nuclear Fusion, vol. 41, no. 12, pp. 1755-1758, Dec. 2001, doi: https://doi.org/10.1088/0029-5515/41/12/102. + Parameters + ---------- + nd_plasma_electron_on_axis : float + Central electron density (m^-3). + rminor : float + Minor radius of the plasma (m). + b_plasma_toroidal_on_axis : float + Toroidal magnetic field (T). + aspect : float + Aspect ratio of the plasma. + alphan : float + Alpha parameter for density profile. + alphat : float + Alpha parameter for temperature profile. + tbeta : float + Beta parameter for temperature profile. + temp_plasma_electron_on_axis_kev : float + Central electron temperature (keV). + f_sync_reflect : float + Fraction of synchrotron radiation reflected. + rmajor : float + Major radius of the plasma (m). + kappa : float + Elongation of the plasma. + vol_plasma : float + Plasma volume (m^3). + + Returns + ------- + float + Synchrotron radiation power per unit volume (MW/m^3). + + References + ---------- + - F. Albajar, J. Johner, and G. Granata, “Improved calculation of synchrotron radiation losses in realistic tokamak plasmas,” + Nuclear Fusion, vol. 41, no. 6, pp. 665-678, Jun. 2001, doi: https://doi.org/10.1088/0029-5515/41/6/301. + + - I. Fidone, G Giruzzi, and G. Granata, “Synchrotron radiation loss in tokamaks of arbitrary geometry,” + Nuclear Fusion, vol. 41, no. 12, pp. 1755-1758, Dec. 2001, doi: https://doi.org/10.1088/0029-5515/41/12/102. """ # Variable names are created to closely match those from the reference papers. diff --git a/process/plasma_geometry.py b/process/plasma_geometry.py index 18b0d064e5..268306d7d2 100644 --- a/process/plasma_geometry.py +++ b/process/plasma_geometry.py @@ -12,22 +12,18 @@ class PlasmaGeom: def __init__(self): self.outfile = constants.NOUT - def plasma_geometry(self) -> None: - """ - Plasma geometry parameters - - :author: P J Knight, CCFE, Culham Science Centre + def plasma_geometry(self): + """Plasma geometry parameters This method calculates the plasma geometry parameters based on various shaping terms and input values. It updates the `physics_variables` with calculated values for kappa, triangularity, surface area, volume, etc. - :references: + References + ---------- - J D Galambos, STAR Code : Spherical Tokamak Analysis and Reactor Code, unpublished internal Oak Ridge document - H. Zohm et al, On the Physics Guidelines for a Tokamak DEMO, FTP/3-3, Proc. IAEA Fusion Energy Conference, October 2012, San Diego - - :returns: None """ xsi = 0.0e0 @@ -302,31 +298,35 @@ def plasma_geometry(self) -> None: def plasma_angles_arcs( a: float, kappa: float, triang: float ) -> tuple[float, float, float, float]: - """ - Routine to find parameters used for calculating geometrical + """Routine to find parameters used for calculating geometrical properties for double-null plasmas. - :author: P J Knight, CCFE, Culham Science Centre + This function finds plasma geometrical parameters, using the + revolution of two intersecting arcs around the device centreline. + This calculation is appropriate for plasmas with a separatrix. - :param a: Plasma minor radius (m) - :type a: float - :param kappa: Plasma separatrix elongation - :type kappa: float - :param tri: Plasma separatrix triangularity - :type tri: float - :returns: A tuple containing: + Parameters + ---------- + a : float + Plasma minor radius (m) + kappa : float + Plasma separatrix elongation + tri : float + Plasma separatrix triangularity + + Returns + ------- + tuple + A tuple containing: - xi (float): Radius of arc describing inboard surface (m) - thetai (float): Half-angle of arc describing inboard surface - xo (float): Radius of arc describing outboard surface (m) - thetao (float): Half-angle of arc describing outboard surface - :rtype: tuple - This function finds plasma geometrical parameters, using the - revolution of two intersecting arcs around the device centreline. - This calculation is appropriate for plasmas with a separatrix. - :references: + References + ---------- - F/MI/PJK/LOGBOOK14, p.42 - F/PL/PJK/PROCESS/CODE/047 """ @@ -348,20 +348,23 @@ def plasma_angles_arcs( def plasma_poloidal_perimeter( xi: float, thetai: float, xo: float, thetao: float ) -> float: - """ - Calculate the poloidal perimeter of the plasma. - - :param xi: Radius of arc describing inboard surface (m) - :type xi: float - :param thetai: Half-angle of arc describing inboard surface - :type thetai: float - :param xo: Radius of arc describing outboard surface (m) - :type xo: float - :param thetao: Half-angle of arc describing outboard surface - :type thetao: float - - :returns: Poloidal perimeter (m) - :rtype: float + """Calculate the poloidal perimeter of the plasma. + + Parameters + ---------- + xi : float + Radius of arc describing inboard surface (m) + thetai : float + Half-angle of arc describing inboard surface + xo : float + Radius of arc describing outboard surface (m) + thetao : float + Half-angle of arc describing outboard surface + + Returns + ------- + float + Poloidal perimeter (m) """ return 2.0e0 * (xo * thetao + xi * thetai) @@ -369,33 +372,37 @@ def plasma_poloidal_perimeter( def plasma_surface_area( rmajor: float, rminor: float, xi: float, thetai: float, xo: float, thetao: float ) -> tuple[float, float]: - """ - Plasma surface area calculation - :author: P J Knight, CCFE, Culham Science Centre - - :param rmajor: Plasma major radius (m) - :type rmajor: float - :param rminor: Plasma minor radius (m) - :type rminor: float - :param xi: Radius of arc describing inboard surface (m) - :type xi: float - :param thetai: Half-angle of arc describing inboard surface - :type thetai: float - :param xo: Radius of arc describing outboard surface (m) - :type xo: float - :param thetao: Half-angle of arc describing outboard surface - :type thetao: float - - :returns: A tuple containing: - - xsi (float): Inboard surface area (m^2) - - xso (float): Outboard surface area (m^2) - :rtype: tuple + """Plasma surface area calculation This function finds the plasma surface area, using the revolution of two intersecting arcs around the device centreline. This calculation is appropriate for plasmas with a separatrix. - :references: + Parameters + ---------- + rmajor : float + Plasma major radius (m) + rminor : float + Plasma minor radius (m) + xi : float + Radius of arc describing inboard surface (m) + thetai : float + Half-angle of arc describing inboard surface + xo : float + Radius of arc describing outboard surface (m) + thetao : float + Half-angle of arc describing outboard surface + + Returns + ------- + tuple + A tuple containing: + - xsi (float): Inboard surface area (m^2) + - xso (float): Outboard surface area (m^2) + + + References + ---------- - F/MI/PJK/LOGBOOK14, p.43 """ fourpi = 4.0e0 * np.pi @@ -412,31 +419,34 @@ def plasma_surface_area( def plasma_volume( rmajor: float, rminor: float, xi: float, thetai: float, xo: float, thetao: float ) -> float: - """ - Plasma volume calculation - :author: P J Knight, CCFE, Culham Science Centre - - :param rmajor: Plasma major radius (m) - :type rmajor: float - :param rminor: Plasma minor radius (m) - :type rminor: float - :param xi: Radius of arc describing inboard surface (m) - :type xi: float - :param thetai: Half-angle of arc describing inboard surface - :type thetai: float - :param xo: Radius of arc describing outboard surface (m) - :type xo: float - :param thetao: Half-angle of arc describing outboard surface - :type thetao: float - - :returns: Plasma volume (m^3) - :rtype: float - + """Plasma volume calculation This function finds the plasma volume, using the revolution of two intersecting arcs around the device centreline. This calculation is appropriate for plasmas with a separatrix. - :references: + Parameters + ---------- + rmajor : float + Plasma major radius (m) + rminor : float + Plasma minor radius (m) + xi : float + Radius of arc describing inboard surface (m) + thetai : float + Half-angle of arc describing inboard surface + xo : float + Radius of arc describing outboard surface (m) + thetao : float + Half-angle of arc describing outboard surface + + Returns + ------- + float + Plasma volume (m^3) + + + References + ---------- - F/MI/PJK/LOGBOOK14, p.43 """ @@ -476,27 +486,31 @@ def plasma_volume( def plasma_cross_section( xi: float, thetai: float, xo: float, thetao: float ) -> float: - """ - Plasma cross-sectional area calculation - :author: P J Knight, CCFE, Culham Science Centre - - :param xi: Radius of arc describing inboard surface (m) - :type xi: float - :param thetai: Half-angle of arc describing inboard surface - :type thetai: float - :param xo: Radius of arc describing outboard surface (m) - :type xo: float - :param thetao: Half-angle of arc describing outboard surface - :type thetao: float - - :returns: Plasma cross-sectional area (m^2) - :rtype: float + """Plasma cross-sectional area calculation This function finds the plasma cross-sectional area, using the revolution of two intersecting arcs around the device centreline. This calculation is appropriate for plasmas with a separatrix. - :references: + Parameters + ---------- + xi : float + Radius of arc describing inboard surface (m) + thetai : float + Half-angle of arc describing inboard surface + xo : float + Radius of arc describing outboard surface (m) + thetao : float + Half-angle of arc describing outboard surface + + Returns + ------- + float + Plasma cross-sectional area (m^2) + + + References + ---------- - F/MI/PJK/LOGBOOK14, p.41 """ @@ -508,33 +522,36 @@ def plasma_cross_section( def sauter_geometry( a: float, r0: float, kappa: float, triang: float, square: float ) -> tuple[float, float, float, float, float]: - """ - Calculate the plasma geometry parameters using the Sauter geometry model. - - :param a: Plasma minor radius (m) - :type a: float - :param r0: Plasma major radius (m) - :type r0: float - :param kappa: Plasma separatrix elongation - :type kappa: float - :param triang: Plasma separatrix triangularity - :type triang: float - :param square: Plasma squareness - :type square: float - - :returns: A tuple containing: + """Calculate the plasma geometry parameters using the Sauter geometry model. + + Parameters + ---------- + a : float + Plasma minor radius (m) + r0 : float + Plasma major radius (m) + kappa : float + Plasma separatrix elongation + triang : float + Plasma separatrix triangularity + square : float + Plasma squareness + + Returns + ------- + tuple + A tuple containing: - len_plasma_poloidal (float): Poloidal perimeter - a_plasma_surface (float): Surface area - a_plasma_poloidal (float): Cross-section area - vol_plasma (float): Plasma volume - :rtype: tuple - :notes: - :references: + References + ---------- - O. Sauter, “Geometric formulas for system codes including the effect of negative triangularity,” - Fusion Engineering and Design, vol. 112, pp. 633-645, Nov. 2016, - doi: https://doi.org/10.1016/j.fusengdes.2016.04.033. + Fusion Engineering and Design, vol. 112, pp. 633-645, Nov. 2016, + doi: https://doi.org/10.1016/j.fusengdes.2016.04.033. """ # Calculate w07 parameter from paper from squareness assuming top-down symmetry @@ -578,33 +595,36 @@ def sauter_geometry( def surfa(a: float, r: float, k: float, d: float) -> tuple[float, float]: - """ - Plasma surface area calculation - - :author: P J Knight, CCFE, Culham Science Centre - - :param a: Plasma minor radius (m) - :type a: float - :param r: Plasma major radius (m) - :type r: float - :param k: Plasma separatrix elongation - :type k: float - :param d: Plasma separatrix triangularity - :type d: float - - :returns: A tuple containing: - - sa (float): Plasma total surface area (m^2) - - so (float): Plasma outboard surface area (m^2) - :rtype: tuple + """Plasma surface area calculation This function finds the plasma surface area, using the revolution of two intersecting arcs around the device centreline. This calculation is appropriate for plasmas with a separatrix. It was the original method in PROCESS. - :references: + Parameters + ---------- + a : float + Plasma minor radius (m) + r : float + Plasma major radius (m) + k : float + Plasma separatrix elongation + d : float + Plasma separatrix triangularity + + Returns + ------- + tuple + A tuple containing: + - sa (float): Plasma total surface area (m^2) + - so (float): Plasma outboard surface area (m^2) + + + References + ---------- - J D Galambos, STAR Code : Spherical Tokamak Analysis and Reactor Code, - unpublished internal Oak Ridge document + unpublished internal Oak Ridge document """ radco = a * (1.0e0 + (k**2 + d**2 - 1.0e0) / (2.0e0 * (1.0e0 + d))) b = k * a @@ -623,26 +643,29 @@ def surfa(a: float, r: float, k: float, d: float) -> tuple[float, float]: def perim(a: float, kap: float, tri: float) -> float: - """ - Plasma poloidal perimeter calculation - - :author: P J Knight, CCFE, Culham Science Centre - - :param a: Plasma minor radius (m) - :type a: float - :param kap: Plasma separatrix elongation - :type kap: float - :param tri: Plasma separatrix triangularity - :type tri: float - - :returns: Plasma poloidal perimeter (m) - :rtype: float + """Plasma poloidal perimeter calculation This function finds the plasma poloidal perimeter, using the revolution of two intersecting arcs around the device centreline. This calculation is appropriate for plasmas with a separatrix. - :references: + Parameters + ---------- + a : float + Plasma minor radius (m) + kap : float + Plasma separatrix elongation + tri : float + Plasma separatrix triangularity + + Returns + ------- + float + Plasma poloidal perimeter (m) + + + References + ---------- - F/PL/PJK/PROCESS/CODE/047 """ @@ -662,28 +685,31 @@ def perim(a: float, kap: float, tri: float) -> float: def fvol(r: float, a: float, kap: float, tri: float) -> float: - """ - Plasma volume calculation - - :author: P J Knight, CCFE, Culham Science Centre - - :param r: Plasma major radius (m) - :type r: float - :param a: Plasma minor radius (m) - :type a: float - :param kap: Plasma separatrix elongation - :type kap: float - :param tri: Plasma separatrix triangularity - :type tri: float - - :returns: Plasma volume (m^3) - :rtype: float + """Plasma volume calculation This function finds the plasma volume, using the revolution of two intersecting arcs around the device centreline. This calculation is appropriate for plasmas with a separatrix. - :references: + Parameters + ---------- + r : float + Plasma major radius (m) + a : float + Plasma minor radius (m) + kap : float + Plasma separatrix elongation + tri : float + Plasma separatrix triangularity + + Returns + ------- + float + Plasma volume (m^3) + + + References + ---------- - F/MI/PJK/LOGBOOK14, p.41 - F/PL/PJK/PROCESS/CODE/047 """ @@ -716,26 +742,28 @@ def fvol(r: float, a: float, kap: float, tri: float) -> float: def xsect0(a: float, kap: float, tri: float) -> float: - """ - Plasma cross-sectional area calculation - - :author: P J Knight, CCFE, Culham Science Centre - - :param a: Plasma minor radius (m) - :type a: float - :param kap: Plasma separatrix elongation - :type kap: float - :param tri: Plasma separatrix triangularity - :type tri: float - - :returns: Plasma cross-sectional area (m^2) - :rtype: float + """Plasma cross-sectional area calculation This function finds the plasma cross-sectional area, using the revolution of two intersecting arcs around the device centreline. This calculation is appropriate for plasmas with a separatrix. - :references: + Parameters + ---------- + a : float + Plasma minor radius (m) + kap : float + Plasma separatrix elongation + tri : float + Plasma separatrix triangularity + + Returns + ------- + float + Plasma cross-sectional area (m^2) + + References + ---------- - F/MI/PJK/LOGBOOK14, p.41 - F/PL/PJK/PROCESS/CODE/047 """ diff --git a/process/plasma_profiles.py b/process/plasma_profiles.py index 0eb20084c7..3ccc54acf3 100644 --- a/process/plasma_profiles.py +++ b/process/plasma_profiles.py @@ -12,26 +12,11 @@ class PlasmaProfile: - """ - Plasma profile class. Initiates the electron density and electron temperature profiles and + """Plasma profile class. Initiates the electron density and electron temperature profiles and handles the required physics variables. - - Attributes: - profile_size (int): The size of the plasma profile. - outfile (str): The output file path. - neprofile (NeProfile): An instance of the NeProfile class. - teprofile (TeProfile): An instance of the TeProfile class. - - Methods: - run(): Subroutine to execute PlasmaProfile functions. - parameterise_plasma(): Initializes the density and temperature profile averages and peak values. - parabolic_paramterisation(): Parameterizes plasma profiles in the case where i_plasma_pedestal=0. - pedestal_parameterisation(): Instance temperature and density profiles then integrate them, setting physics variables temp_plasma_electron_density_weighted_kev and temp_plasma_ion_density_weighted_kev. - calculate_profile_factors(): Calculate and set the central pressure (pres_plasma_thermal_on_axis) using the ideal gas law and the pressure profile index (alphap). - calculate_parabolic_profile_factors(): The gradient information for i_plasma_pedestal = 0. """ - def __init__(self) -> None: + def __init__(self): """ Initialize the PlasmaProfile class. @@ -48,34 +33,20 @@ def __init__(self) -> None: self.neprofile = profiles.NeProfile(self.profile_size) self.teprofile = profiles.TeProfile(self.profile_size) - def run(self) -> None: - """ - Subroutine to execute PlasmaProfile functions. + def run(self): + """Subroutine to execute PlasmaProfile functions. This method calls the parameterise_plasma() method to initialize the plasma profiles. - - Returns: - None """ self.parameterise_plasma() - def parameterise_plasma(self) -> None: - """ - This routine initializes the density and temperature + def parameterise_plasma(self): + """This routine initializes the density and temperature profile averages and peak values, given the main parameters describing these profiles. - Args: - None - - Returns: - None - - Authors: - P J Knight, CCFE, Culham Science Centre - References: - T&M/PKNIGHT/LOGBOOK24, pp.4-7 + T&M/PKNIGHT/LOGBOOK24, pp.4-7 """ # Volume-averaged ion temperature @@ -97,18 +68,11 @@ def parameterise_plasma(self) -> None: self.pedestal_parameterisation() self.calculate_profile_factors() - def parabolic_paramterisation(self) -> None: - """ - Parameterise plasma profiles in the case where i_plasma_pedestal == 0. + def parabolic_paramterisation(self): + """Parameterise plasma profiles in the case where i_plasma_pedestal == 0. This routine calculates the parameterization of plasma profiles in the case where i_plasma_pedestal=0. It sets the necessary physics variables for the parabolic profile case. - - Args: - None - - Returns: - None """ # Reset pedestal values to agree with original parabolic profiles if ( @@ -190,17 +154,10 @@ def parabolic_paramterisation(self) -> None: * (1.0 + physics_variables.alphan) ) - def pedestal_parameterisation(self) -> None: - """ - Instance temperature and density profiles then integrate them, setting physics variables temp_plasma_electron_density_weighted_kev and temp_plasma_ion_density_weighted_kev. + def pedestal_parameterisation(self): + """Instance temperature and density profiles then integrate them, setting physics variables temp_plasma_electron_density_weighted_kev and temp_plasma_ion_density_weighted_kev. This routine instances temperature and density profiles and integrates them to calculate the values of the physics variables `temp_plasma_electron_density_weighted_kev` and `temp_plasma_ion_density_weighted_kev`. - - Args: - None - - Returns: - None """ # Run TeProfile and NeProfile class methods: # Re-caluclate core and profile values @@ -256,18 +213,11 @@ def pedestal_parameterisation(self) -> None: / physics_variables.nd_plasma_electrons_vol_avg, ) # Preventing division by zero later - def calculate_profile_factors(self) -> None: - """ - Calculate and set the central pressure (pres_plasma_thermal_on_axis) using the ideal gas law and the pressure profile index (alphap). + def calculate_profile_factors(self): + """Calculate and set the central pressure (pres_plasma_thermal_on_axis) using the ideal gas law and the pressure profile index (alphap). This method calculates the central pressure (pres_plasma_thermal_on_axis) using the ideal gas law and the pressure profile index (alphap). It sets the value of the physics variable `pres_plasma_thermal_on_axis`. - - Args: - None - - Returns: - None """ # Central pressure (Pa), from ideal gas law : p = nkT @@ -338,21 +288,14 @@ def calculate_profile_factors(self) -> None: ) @staticmethod - def calculate_parabolic_profile_factors() -> None: - """ - Calculate the gradient information for i_plasma_pedestal = 0. + def calculate_parabolic_profile_factors(): + """Calculate the gradient information for i_plasma_pedestal = 0. This function calculates the gradient information for the plasma profiles at the pedestal region when the value of i_plasma_pedestal is 0. It is used by the stellarator routines. The function uses analytical parametric formulas to calculate the gradient information. The maximum normalized radius (rho_max) is obtained by equating the second derivative to zero. - - Args: - None - - Returns: - None """ if physics_variables.i_plasma_pedestal == 0: if physics_variables.alphat > 1.0: diff --git a/process/power.py b/process/power.py index 32f40ce3ce..9f98f4defe 100644 --- a/process/power.py +++ b/process/power.py @@ -34,9 +34,8 @@ def __init__(self): self.mfile = constants.MFILE def pfpwr(self, output: bool): - """ - PF coil power supply requirements - author: P J Knight, CCFE, Culham Science Centre + """PF coil power supply requirements + outfile : input integer : output file unit iprint : input integer : switch for writing to output (1=yes) This routine calculates the MVA, power and energy requirements @@ -46,6 +45,11 @@ def pfpwr(self, output: bool): The reactive (inductive) components use waves to calculate the dI/dt at the time periods. None + + Parameters + ---------- + output: bool + """ powpfii = np.zeros((pfcoil_variables.NGC2,)) cktr = np.zeros((pfcoil_variables.NGC2,)) @@ -397,16 +401,20 @@ def pfpwr(self, output: bool): # write(self.outfile,50)(times_variables.t_pulse_cumulative(time),time=1,6) def acpow(self, output: bool): - """ - AC power requirements - author: P J Knight, CCFE, Culham Science Centre - author: P C Shipe, ORNL + """AC power requirements + + outfile : input integer : output file unit iprint : input integer : switch for writing to output (1=yes) The routine was drastically shortened on 23/01/90 (ORNL) from the original TETRA routine to provide only the total power needs for the plant. Included in STORAC in January 1992 by P.C. Shipe. None + + Parameters + ---------- + output: bool + """ ptfmw = heat_transport_variables.p_tf_electric_supplies_mw ppfmw = 1.0e-3 * pf_power_variables.srcktpm @@ -516,11 +524,8 @@ def acpow(self, output: bool): # po.ovarre(self.outfile,'Total low voltage power (MW)','(tlvpmw)',tlvpmw) def component_thermal_powers(self): - """ - Calculates the first part of the heat transport + """Calculates the first part of the heat transport and plant power balance constituents - author: P J Knight, CCFE, Culham Science Centre - None This routine calculates the first part of the heat transport and plant power balance constituents. None @@ -728,9 +733,8 @@ def component_thermal_powers(self): heat_transport_variables.p_plant_primary_heat_mw / 1000.0e0 ) - def calculate_cryo_loads(self) -> None: - """ - Calculates and updates the cryogenic heat loads for the system. + def calculate_cryo_loads(self): + """Calculates and updates the cryogenic heat loads for the system. This method computes the various cryogenic heat loads, including conduction/radiation, nuclear heating, AC losses, and resistive losses in current leads. It also updates @@ -1317,15 +1321,13 @@ def output_plant_electric_powers(self): power_variables.e_plant_net_electric_pulse_kwh, ) - def plant_electric_production(self) -> None: - """ - This method completes the calculation of the plant's electrical and thermal power flows, + def plant_electric_production(self): + """This method completes the calculation of the plant's electrical and thermal power flows, including secondary heat, recirculating power, net and gross electric power, and various efficiency measures. If `output` is True, the method writes a comprehensive summary of the plant's power and heat transport balance, assumptions, and efficiency metrics to the specified output file. - """ if physics_variables.itart == 1 and tfcoil_variables.i_tf_sup == 0: power_variables.p_cp_coolant_pump_elec_mw = ( @@ -1467,9 +1469,8 @@ def cryo( c_tf_turn, n_tf_coils, ): - """ - Calculates cryogenic loads - author: P J Knight, CCFE, Culham Science Centre + """Calculates cryogenic loads + itfsup : input integer : Switch denoting whether TF coils are superconducting tfcryoarea : input real : Surface area of toroidal shells covering TF coils (m2) @@ -1484,6 +1485,25 @@ def cryo( helpow : output real : Helium heat removal at cryo temperatures (W) This routine calculates the cryogenic heat load. D. Slack memo SCMDG 88-5-1-059, LLNL ITER-88-054, Aug. 1988 + + Parameters + ---------- + i_tf_sup : + + tfcryoarea : + + coldmass : + + p_tf_nuclear_heat_mw : + + ensxpfm : + + t_plant_pulse_plasma_present : + + c_tf_turn : + + n_tf_coils : + """ power_variables.qss = 4.3e-4 * coldmass if i_tf_sup == 1: @@ -1519,9 +1539,8 @@ def cryo( + power_variables.qcl, ) - def output_cryogenics(self) -> None: - """ - Outputs cryogenic system heat loads and related parameters to the output file. + def output_cryogenics(self): + """Outputs cryogenic system heat loads and related parameters to the output file. This method prints the breakdown of cryogenic heat loads, including conduction/radiation, nuclear heating, AC losses, resistive losses in current leads, miscellaneous allowances, @@ -1600,10 +1619,9 @@ def output_cryogenics(self) -> None: ) def plant_thermal_efficiency(self, eta_turbine): - """ - Calculates the thermal efficiency of the power conversion cycle - author: P J Knight, CCFE, Culham Science Centre - author: C Harrington, CCFE, Culham Science Centre + """Calculates the thermal efficiency of the power conversion cycle + + eta_turbine : input/output real : thermal to electric conversion efficiency This routine calculates the thermal efficiency of the power conversion cycle. This gives the gross power of the plant, i.e. the primary coolant pumping @@ -1616,6 +1634,11 @@ def plant_thermal_efficiency(self, eta_turbine): between eta_turbine and temp_blkt_coolant_out again obtained from previous studies. C. Harrington, K:Power Plant Physics and Technology PROCESS blanket_model New Power Module Harrington Cycle correlations Cycle correlations.xls + + Parameters + ---------- + eta_turbine : + """ if fwbs_variables.i_thermal_electric_conversion == 0: # CCFE HCPB Model @@ -1713,9 +1736,13 @@ def plant_thermal_efficiency(self, eta_turbine): return eta_turbine def plant_thermal_efficiency_2(self, etath_liq): - """ - Calculates the thermal efficiency of the power conversion cycle + """Calculates the thermal efficiency of the power conversion cycle for the liquid metal breeder + + Parameters + ---------- + etath_liq : + """ if fwbs_variables.secondary_cycle_liq == 2: # User input used, eta_turbine not changed @@ -1746,15 +1773,19 @@ def plant_thermal_efficiency_2(self, etath_liq): ) def tfpwr(self, output: bool): - """ - TF coil power supply requirements for resistive coils - author: P J Knight, CCFE, Culham Science Centre + """TF coil power supply requirements for resistive coils + outfile : input integer : output file unit iprint : input integer : switch for writing to output (1=yes) This routine calculates the power conversion requirements for resistive TF coils, or calls tfpwcall if the TF coils are superconducting. None + + Parameters + ---------- + output: bool + """ if tfcoil_variables.i_tf_sup != 1: # Cross-sectional area of bus @@ -1914,16 +1945,20 @@ def tfpwr(self, output: bool): # po.ovarre(outfile,'TF coil reactive power (MW)','(tfreacmw)', tfreacmw) def tfpwcall(self, output: bool): - """ - Calls the TF coil power conversion routine for + """Calls the TF coil power conversion routine for superconducting coils - author: P J Knight, CCFE, Culham Science Centre - author: P C Shipe, ORNL + + outfile : input integer : output file unit iprint : input integer : switch for writing to output (1=yes) This routine calls routine tfcpwr to calculate the power conversion requirements for superconducting TF coils. None + + Parameters + ---------- + output: bool + """ ettfmj = ( tfcoil_variables.e_tf_magnetic_stored_total_gj @@ -1954,18 +1989,28 @@ def tfpwcall(self, output: bool): def tfcpwr( self, output: bool, itfka, rmajor, ntfc, v_tf_coil_dump_quench_kv, ettfmj, rptfc ): - """ - Calculates the TF coil power conversion system parameters + """Calculates the TF coil power conversion system parameters for superconducting coils - author: P J Knight, CCFE, Culham Science Centre - author: P C Shipe, ORNL - This routine calculates the TF power conversion system - parameters: floor space, power supplies, bussing, + + This routine calculates the TF power conversion systemp arameters: + floor space, power supplies, bussing, coil protection equipment, and the associated controls - and instrumentation. It was originally written by G. Gorker, - FEDC/ORNL, April 1987, modified by J. Galambos in 1991 to - run in TETRA, and included in PROCESS in 1992 by P. C. Shipe. - None + and instrumentation. + + Parameters + ---------- + itfka : + + rmajor : + + ntfc : + + v_tf_coil_dump_quench_kv : + + ettfmj : + + rptfc : + """ ncpbkr = 1.0e0 # number of TF coils per circuit breaker @@ -2266,50 +2311,54 @@ def power_profiles_over_time( p_plant_electric_gross_mw: float, p_plant_electric_net_mw: float, ) -> float: - """ - Calculate time-dependent power profiles for different electric systems - - :param t_precharge: Precharge time (s). - :type t_precharge: float - :param t_current_ramp_up: Current ramp-up time (s). - :type t_current_ramp_up: float - :param t_fusion_ramp: Fusion ramp time (s). - :type t_fusion_ramp: float - :param t_burn: Burn time (s). - :type t_burn: float - :param t_ramp_down: Ramp-down time (s). - :type t_ramp_down: float - :param t_between_pulse: Time between pulses (s). - :type t_between_pulse: float - :param p_plant_electric_base_total_mw: Plant base electric load (MW). - :type p_plant_electric_base_total_mw: float - :param p_cryo_plant_electric_mw: Cryogenic plant electric load (MW). - :type p_cryo_plant_electric_mw: float - :param p_tritium_plant_electric_mw: Tritium plant electric load (MW). - :type p_tritium_plant_electric_mw: float - :param vachtmw: Vacuum pumps electric load (MW). - :type vachtmw: float - :param p_tf_electric_supplies_mw: TF coil electric supplies (MW). - :type p_tf_electric_supplies_mw: float - :param p_pf_electric_supplies_mw: PF coil electric supplies (MW). - :type p_pf_electric_supplies_mw: float - :param p_coolant_pump_elec_total_mw: Total coolant pump electric load (MW). - :type p_coolant_pump_elec_total_mw: float - :param p_hcd_electric_total_mw: HCD electric total (MW). - :type p_hcd_electric_total_mw: float - :param p_fusion_total_mw: Fusion power (MW). - :type p_fusion_total_mw: float - :param p_plant_electric_gross_mw: Gross electric power produced (MW). - :type p_plant_electric_gross_mw: float - :param p_plant_electric_net_mw: Net electric power produced (MW). - :type p_plant_electric_net_mw: float - - :notes: - - Assumes step-function changes in power at each phase transition. - - Negative values indicate power consumption (loads). - - :returns: Total net electric energy produced over the pulse (MJ). - :rtype: float + """Calculate time-dependent power profiles for different electric systems + + Parameters + ---------- + t_precharge : float + Precharge time (s). + t_current_ramp_up : float + Current ramp-up time (s). + t_fusion_ramp : float + Fusion ramp time (s). + t_burn : float + Burn time (s). + t_ramp_down : float + Ramp-down time (s). + t_between_pulse : float + Time between pulses (s). + p_plant_electric_base_total_mw : float + Plant base electric load (MW). + p_cryo_plant_electric_mw : float + Cryogenic plant electric load (MW). + p_tritium_plant_electric_mw : float + Tritium plant electric load (MW). + vachtmw : float + Vacuum pumps electric load (MW). + p_tf_electric_supplies_mw : float + TF coil electric supplies (MW). + p_pf_electric_supplies_mw : float + PF coil electric supplies (MW). + p_coolant_pump_elec_total_mw : float + Total coolant pump electric load (MW). + p_hcd_electric_total_mw : float + HCD electric total (MW). + p_fusion_total_mw : float + Fusion power (MW). + p_plant_electric_gross_mw : float + Gross electric power produced (MW). + p_plant_electric_net_mw : float + Net electric power produced (MW). + + Returns + ------- + float + Total net electric energy produced over the pulse (MJ). + + Notes + ----- + - Assumes step-function changes in power at each phase transition. + - Negative values indicate power consumption (loads). """ t_steps = np.cumsum([ diff --git a/process/process_output.py b/process/process_output.py index 9b01a52b2f..9902fa809e 100644 --- a/process/process_output.py +++ b/process/process_output.py @@ -55,10 +55,17 @@ def write(file, string: str): def ocentr(file, string: str, width: int, *, character="*"): """Write a centred header within a line of characters to a file - :param file: the integer unit of the file - :param string: the heading text - :param width: the desired with of the header - :param character: the character to pad the heading with (*) + Parameters + ---------- + file : + the integer unit of the file + string : + the heading text + width : + the desired with of the header + character : + the character to pad the heading with (*) (Default value = "*") + """ write(file, f"{f' {string} ':{character}^{width}}") write(constants.MFILE, f"# {string} #") @@ -67,9 +74,15 @@ def ocentr(file, string: str, width: int, *, character="*"): def ostars(file, width: int, *, character="*"): """Write a line of characters to a file - :param file: the integer unit of the file - :param width: the desired with of the line - :param character: the character to fill the line with (*) + Parameters + ---------- + file : + the integer unit of the file + width : + the desired with of the line + character : + the character to fill the line with (*) (Default value = "*") + """ write(file, character * width) @@ -77,10 +90,16 @@ def ostars(file, width: int, *, character="*"): def oheadr(file, string: str, *, width: int = 110, character="*"): """Write a centred header within a line of characters between two blank lines - :param file: the integer unit of the file - :param string: the heading text - :param width: the desired with of the header - :param character: the character to pad the heading with (*) + Parameters + ---------- + file : + the integer unit of the file + string : + the heading text + width : + the desired with of the header + character : + the character to pad the heading with (*) (Default value = "*") """ oblnkl(file) ocentr(file, string, width, character=character) @@ -90,10 +109,16 @@ def oheadr(file, string: str, *, width: int = 110, character="*"): def oshead(file, string: str, *, width: int = 80, character="*"): """Write a short centred header within a line of characters between two blank lines - :param file: the integer unit of the file - :param string: the heading text - :param width: the desired with of the header - :param character: the character to pad the heading with (*) + Parameters + ---------- + file : + the integer unit of the file + string : + the heading text + width : + the desired with of the header + character : + the character to pad the heading with (*) (Default value = "*") """ oheadr(file, string, width=width, character=character) @@ -101,7 +126,10 @@ def oshead(file, string: str, *, width: int = 80, character="*"): def oblnkl(file): """Write a blank line to a file - :param file: the integer unit of the file + Parameters + ---------- + file : + the integer unit of the file """ write(file, " ") @@ -109,8 +137,12 @@ def oblnkl(file): def osubhd(file, string): """Write a subheading between two blank lines - :param file: the integer unit of the file - :param string: the heading text + Parameters + ---------- + file : + the integer unit of the file + string : + the heading text """ oblnkl(file) write(file, string) @@ -120,8 +152,12 @@ def osubhd(file, string): def ocmmnt(file, string: str): """Write a comment to a file - :param file: the integer unit of the file - :param string: the comment text + Parameters + ---------- + file : + the integer unit of the file + string : + the comment text """ write(file, string) diff --git a/process/profiles.py b/process/profiles.py index db0a45cc4c..d347247578 100644 --- a/process/profiles.py +++ b/process/profiles.py @@ -12,7 +12,7 @@ class Profile(ABC): """Abstract base class used to create and hold profiles (temperature, density)""" - def __init__(self, profile_size: int) -> None: + def __init__(self, profile_size: int): """ Initialize a Profiles object. @@ -25,7 +25,6 @@ def __init__(self, profile_size: int) -> None: - profile_y (ndarray): An array of zeros with length profile_size. - profile_integ (int): The integral of the profile_y array. - profile_dx (int): The step size between consecutive values in profile_x. - """ self.profile_size = profile_size self.profile_x = np.arange(self.profile_size) @@ -33,9 +32,8 @@ def __init__(self, profile_size: int) -> None: self.profile_integ = 0 self.profile_dx = 0 - def normalise_profile_x(self) -> None: - """ - Normalizes the x-dimension of the profile. + def normalise_profile_x(self): + """Normalizes the x-dimension of the profile. This method divides the values in the `profile_x` attribute by the maximum value in the `profile_x` array, resulting in a normalized version of the x-dimension. @@ -47,39 +45,30 @@ def normalise_profile_x(self) -> None: Note: This method modifies the `profile_x` attribute in-place. - Returns: - None + """ self.profile_x = self.profile_x / max(self.profile_x) - def calculate_profile_dx(self) -> None: + def calculate_profile_dx(self): """Calculates the differential between points in the profile. This method calculates the differential between points in the profile by dividing the maximum x value in the profile by the difference in size between the points. The result is stored in the `profile_dx` attribute. - """ self.profile_dx = max(self.profile_x) / (self.profile_size - 1) @abstractmethod - def calculate_profile_y(self) -> None: + def calculate_profile_y(self): """Use a profile function to act on self.profile_x to calculate and set the values of self.profile_y. """ - def integrate_profile_y(self) -> None: - """ - Integrate profile_y values using scipy.integrate.simpson() function. + def integrate_profile_y(self): + """Integrate profile_y values using scipy.integrate.simpson() function. This method calculates the integral of the profile_y values using the Simpson's rule provided by the scipy.integrate.simpson() function. The integral is stored in the self.profile_integ attribute. - - Parameters: - None - - Returns: - None """ self.profile_integ = sp.integrate.simpson( self.profile_y, x=self.profile_x, dx=self.profile_dx @@ -89,18 +78,9 @@ def integrate_profile_y(self) -> None: class NeProfile(Profile): """Electron density profile class. Contains a function to calculate the electron density profile and store the data. - - Attributes: - Inherits attributes from the base class `Profile`. - - Methods: - run(): Subroutine which calls functions and stores neprofile data. - calculate_profile_y(rho, radius_plasma_pedestal_density_norm, n0, nped, nsep, alphan): Calculates the density at each normalised minor radius position. - ncore(radius_plasma_pedestal_density_norm, nped, nsep, nav, alphan): Calculates the core density of a pedestalised profile. - set_physics_variables(): Calculates and sets physics variables required for the profile. """ - def run(self) -> None: + def run(self): """Subroutine which calls profile functions and stores neprofile data.""" self.normalise_profile_x() self.calculate_profile_dx() @@ -123,26 +103,24 @@ def calculate_profile_y( nped: float, nsep: float, alphan: float, - ) -> None: - """ - This routine calculates the density at each normalised minor radius position + ): + """This routine calculates the density at each normalised minor radius position rho for a HELIOS-type density pedestal profile (neprofile). - Authors: - R Kemp, CCFE, Culham Science Centre - H Lux, CCFE, Culham Science Centre - P J Knight, CCFE, Culham Science Centre - - Parameters: - - rho (np.array): Normalised minor radius vector. - - radius_plasma_pedestal_density_norm (float): Normalised minor radius pedestal position. - - n0 (float): Central density (/m3). - - nped (float): Pedestal density (/m3). - - nsep (float): Separatrix density (/m3). - - alphan (float): Density peaking parameter. - - Returns: - None + Parameters + ---------- + rho : + Normalised minor radius vector. + radius_plasma_pedestal_density_norm : + Normalised minor radius pedestal position. + n0 : + Central density (/m3). + nped : + Pedestal density (/m3). + nsep : + Separatrix density (/m3) + alphan : + Density peaking parameter. """ if physics_variables.i_plasma_pedestal == 0: @@ -173,31 +151,33 @@ def ncore( nav: float, alphan: float, ) -> float: - """ - This routine calculates the core density of a pedestalised profile. + """This routine calculates the core density of a pedestalised profile. The solution comes from integrating and summing the two separate density profiles for the core and pedestal region within their bounds. This has to be multiplied by the torus volume element before integration which leads to an added rho term in each part of the profile. When dividing by the volume of integration to get the average density the simplification leads to a factor of 2 having to be multiplied on to each of the integration results. This function for the average density can then be re-arranged to calculate the central plasma density n_0 / ncore. - References: - Jean, J. (2011). HELIOS: A Zero-Dimensional Tool for Next Step and Reactor Studies. Fusion Science and Technology, 59(2), 308-349. https://doi.org/10.13182/FST11-A11650 - Authors: - Kemp, CCFE, Culham Science Centre - H Lux, CCFE, Culham Science Centre - P J Knight, CCFE, Culham Science Centre - C. Ashe, CCFE, Culham Science Centre - - Parameters: - - radius_plasma_pedestal_density_norm (float): The normalised minor radius pedestal position. - - nped (float): The pedestal density (/m3). - - nsep (float): The separatrix density (/m3). - - nav (float): The electron density (/m3). - - alphan (float): The density peaking parameter. - Returns: - - ncore (float): The core density. + Parameters + ---------- + radius_plasma_pedestal_density_norm : + The normalised minor radius pedestal position. + nped : + The pedestal density (/m3). + nsep : + The separatrix density (/m3). + nav : + The electron density (/m3). + alphan : + The density peaking parameter + + Returns + ------- + : + The core density. + References: + Jean, J. (2011). HELIOS: A Zero-Dimensional Tool for Next Step and Reactor Studies. Fusion Science and Technology, 59(2), 308-349. https://doi.org/10.13182/FST11-A11650 """ ncore = ( @@ -229,7 +209,7 @@ def ncore( ncore = 1.0e-6 return ncore - def set_physics_variables(self) -> None: + def set_physics_variables(self): """Calculates and sets physics variables required for the profile.""" if physics_variables.i_plasma_pedestal == 0: @@ -255,7 +235,7 @@ def set_physics_variables(self) -> None: class TeProfile(Profile): """Electron temperature profile class. Contains a function to calculate the temperature profile and store the data.""" - def run(self) -> None: + def run(self): """Subroutine to initialise neprofile and execute calculations.""" self.normalise_profile_x() self.calculate_profile_dx() @@ -280,25 +260,29 @@ def calculate_profile_y( temp_plasma_separatrix_kev: float, alphat: float, tbeta: float, - ) -> None: - """ - Calculates the temperature at a normalised minor radius position rho for a pedestalised profile (teprofile). + ): + """Calculates the temperature at a normalised minor radius position rho for a pedestalised profile (teprofile). If i_plasma_pedestal = 0 the original parabolic profile form is used instead. + + Parameters + ---------- + rho : np.array + Normalised minor radius. + radius_plasma_pedestal_temp_norm : float + Normalised minor radius pedestal position. + t0 : float + Central temperature (keV). + temp_plasma_pedestal_kev : float + Pedestal temperature (keV). + temp_plasma_separatrix_kev : float + Separatrix temperature (keV). + alphat : float + Temperature peaking parameter. + tbeta : float + Second temperature exponent. + References: Jean, J. (2011). HELIOS: A Zero-Dimensional Tool for Next Step and Reactor Studies. Fusion Science and Technology, 59(2), 308-349. https://doi.org/10.13182/FST11-A11650 - Authors: - R Kemp, CCFE, Culham Science Centre - H Lux, CCFE, Culham Science Centre - P J Knight, CCFE, Culham Science Centre - - Args: - rho (np.array): Normalised minor radius. - radius_plasma_pedestal_temp_norm (float): Normalised minor radius pedestal position. - t0 (float): Central temperature (keV). - temp_plasma_pedestal_kev (float): Pedestal temperature (keV). - temp_plasma_separatrix_kev (float): Separatrix temperature (keV). - alphat (float): Temperature peaking parameter. - tbeta (float): Second temperature exponent. """ if physics_variables.i_plasma_pedestal == 0: # profile values of 0 cause divide by 0 errors so ensure the profile value is at least 1e-8 @@ -331,8 +315,7 @@ def tcore( alphat: float, tbeta: float, ) -> float: - """ - This routine calculates the core temperature (keV) + """This routine calculates the core temperature (keV) of a pedestalised profile. The solution comes from integrating and summing the two seprate temperature profiles for the core and pedestal region within their bounds. This has to be multiplied by the torus volume element before integration which leads to an added rho term in each part of the profile. When dividing by the volume of integration to get the average temperature @@ -340,22 +323,26 @@ def tcore( This function for the average temperature can then be re-arranged to calculate the central plasma temeprature T_0 / tcore. References: Jean, J. (2011). HELIOS: A Zero-Dimensional Tool for Next Step and Reactor Studies. Fusion Science and Technology, 59(2), 308-349. https://doi.org/10.13182/FST11-A11650 - Authors: - Kemp, CCFE, Culham Science Centre - H Lux, CCFE, Culham Science Centre - P J Knight, CCFE, Culham Science Centre - C. Ashe, CCFE, Culham Science Centre - - Args: - radius_plasma_pedestal_temp_norm (float): Normalised minor radius pedestal position. - temp_plasma_pedestal_kev (float): Pedestal temperature (keV). - temp_plasma_separatrix_kev (float): Separatrix temperature (keV). - tav (float): Volume average temperature (keV). - alphat (float): Temperature peaking parameter. - tbeta (float): Second temperature exponent. - - Returns: - float: Core temperature. + + Parameters + ---------- + radius_plasma_pedestal_temp_norm : float + Normalised minor radius pedestal position. + temp_plasma_pedestal_kev : float + Pedestal temperature (keV). + temp_plasma_separatrix_kev : float + Separatrix temperature (keV). + tav : float + Volume average temperature (keV). + alphat : float + Temperature peaking parameter. + tbeta : float + Second temperature exponent. + + Returns + ------- + float + Core temperature. """ # Calculate core temperature @@ -385,16 +372,8 @@ def tcore( ) ) - def set_physics_variables(self) -> None: - """ - Calculates and sets physics variables required for the temperature profile. - - Args: - None - - Returns: - None - """ + def set_physics_variables(self): + """Calculates and sets physics variables required for the temperature profile.""" if physics_variables.i_plasma_pedestal == 0: physics_variables.temp_plasma_electron_on_axis_kev = ( physics_variables.temp_plasma_electron_vol_avg_kev diff --git a/process/pulse.py b/process/pulse.py index 46bb439ab1..5ef0abc14d 100644 --- a/process/pulse.py +++ b/process/pulse.py @@ -19,16 +19,16 @@ class Pulse: def __init__(self): self.outfile = constants.NOUT - def run(self, output: bool) -> None: + def run(self, output: bool): """Caller for the pulsed reactor model - author: C A Gardner, AEA Fusion, Culham Laboratory - author: P J Knight, CCFE, Culham Science Centre This calls the routines relevant to a pulsed reactor scenario. Work File Notes F/MPE/MOD/CAG/PROCESS/PULSE - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not """ if pulse_variables.i_pulsed_plant == 1: self.tohswg(output=output) @@ -41,18 +41,18 @@ def run(self, output: bool) -> None: t_plant_pulse_fusion_ramp=times_variables.t_plant_pulse_fusion_ramp, ) - def tohswg(self, output: bool) -> None: + def tohswg(self, output: bool): """Routine to calculate the plasma current ramp-up time - author: C A Gardner, AEA Fusion, Culham Laboratory - author: P J Knight, CCFE, Culham Science Centre This routine calculates the plasma current ramp-up time for a pulsed reactor. Work File Note F/MPE/MOD/CAG/PROCESS/PULSE/0013 Work File Note F/PL/PJK/PROCESS/CODE/050 - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not """ if pulse_variables.i_pulsed_plant != 1: return @@ -157,25 +157,26 @@ def calculate_burn_time( v_plasma_loop_burn: float, t_plant_pulse_fusion_ramp: float, ) -> float: - """ - Calculate the burn time for a pulsed reactor. + """Calculate the burn time for a pulsed reactor. This routine computes the burn time for a pulsed reactor scenario, based on the total Vs available in the CS and PF coils and the plasma loop voltage during burn. It also checks for negative burn time and reports an error if encountered. - :param vs_cs_pf_total_burn: Total volt-seconds in CS and PF coils available for burn (V·s) - :type vs_cs_pf_total_burn: float - :param v_plasma_loop_burn: Plasma loop voltage during burn (V) - :type v_plasma_loop_burn: float - :param t_plant_pulse_fusion_ramp: Time for fusion ramp (s) - :type t_plant_pulse_fusion_ramp: float - :return: Calculated burn time (s) - :rtype: float - - :raises: Reports error 93 if calculated burn time is negative. - + Parameters + ---------- + vs_cs_pf_total_burn : float + Total volt-seconds in CS and PF coils available for burn (V·s) + v_plasma_loop_burn : float + Plasma loop voltage during burn (V) + t_plant_pulse_fusion_ramp : float + Time for fusion ramp (s) + + Returns + ------- + float + Calculated burn time (s) """ t_plant_pulse_burn = ( diff --git a/process/quench.py b/process/quench.py index b4f51ad1d6..985e65598e 100644 --- a/process/quench.py +++ b/process/quench.py @@ -15,19 +15,24 @@ def _copper_specific_heat_capacity(temperature: float) -> float: - """ - Calculates the specific heat capacity of cryogenic copper at a given temperature [J/(kg·K)]. + """Calculates the specific heat capacity of cryogenic copper at a given temperature [J/(kg·K)]. - :author M. Coleman, UKAEA + Parameters + ---------- + temperature: + Temperature [K]. - :param float temperature: Temperature [K]. - :returns: Specific heat capacity of copper at the given temperature [J/(kg·K)]. - :rtype: float + Returns + ------- + float + Specific heat capacity of copper at the given temperature [J/(kg·K)]. - :notes: - - Assumes high-purity copper with negligible impurity effects. + Notes + ----- + Assumes high-purity copper with negligible impurity effects. - :references: + References + ---------- - J. Simon, E. S. Drexler, and R. P. Reed, *NIST Monograph 177*, "Properties of Copper and Copper Alloys at Cryogenic Temperatures", U.S. Government Printing Office, February 1992. https://nvlpubs.nist.gov/nistpubs/Legacy/MONO/nistmonograph177.pdf @@ -40,18 +45,23 @@ def _copper_specific_heat_capacity(temperature: float) -> float: def _copper_rrr_resistivity(temperature: float, rrr: float) -> float: - """ - Calculates the electrical resistivity of cryogenic copper with temperature and RRR + """Calculates the electrical resistivity of cryogenic copper with temperature and RRR dependence [Ω·m]. - :author M. Coleman, UKAEA + Parameters + ---------- + temperature: + Operating temperature [K]. + rrr: + Residual resistivity ratio (dimensionless). - :param float temperature: Operating temperature [K]. - :param float rrr: Residual resistivity ratio (dimensionless). - :returns: Electrical resistivity of copper [Ω·m]. - :rtype: float + Returns + ------- + float + Electrical resistivity of copper [Ω·m]. - :references: + References + ---------- - J. Simon, E. S. Drexler, and R. P. Reed, *NIST Monograph 177*, "Properties of Copper and Copper Alloys at Cryogenic Temperatures", U.S. Government Printing Office, February 1992. https://nvlpubs.nist.gov/nistpubs/Legacy/MONO/nistmonograph177.pdf @@ -89,26 +99,32 @@ def _copper_rrr_resistivity(temperature: float, rrr: float) -> float: def _copper_irradiation_resistivity(fluence: float) -> float: - """ - Calculates the radiation-induced electrical resistivity of copper. + """Calculates the radiation-induced electrical resistivity of copper. Estimates the increase in copper's electrical resistivity [Ω·m] due to neutron irradiation, as a function of total neutron fluence. - :author M. Coleman, UKAEA - :param float fluence: Total neutron fluence [n/m²]. - :returns: Radiation-induced resistivity of copper [Ω·m]. - :rtype: float + Parameters + ---------- + fluence: + Total neutron fluence [n/m²]. + + Returns + ------- + : + Radiation-induced resistivity of copper [Ω·m]. - :notes: - - Fit to data at low-temperature conditions (around 4.6 K). - - Fit to data in fast neutron spectrum (E > 0.1 MeV). - - Damage and transmutation effects therefore both included, but transmutation effects - may be underestimated. - - This is an additive contribution to the base residual resistivity of copper. + Notes + ----- + - Fit to data at low-temperature conditions (around 4.6 K). + - Fit to data in fast neutron spectrum (E > 0.1 MeV). + - Damage and transmutation effects therefore both included, but transmutation effects + may be underestimated. + - This is an additive contribution to the base residual resistivity of copper. - :references: + References + ---------- - M. Kovari, 09/11/2012, internal notes (Excel / Mathcad), Technology Program, WP12, PEX, Super-X Divertor for DEMO. - M. Nakagawa et al., "High-dose neutron-irradiation effects in fcc metals at 4.6 K", *Phys. Rev. B*, 16, 5285 (1977). https://doi.org/10.1103/PhysRevB.16.5285 @@ -126,20 +142,26 @@ def _copper_irradiation_resistivity(fluence: float) -> float: def _copper_magneto_resistivity(resistivity: float, field: float) -> float: - """ - Calculates the electrical resistivity of cryogenic copper due to magnetoresistive effects [Ω·m]. - - :author M. Coleman, UKAEA - - :param float resistivity: Operating resistivity [K]. - :param float field: Operating magnetic field [T]. - :returns: Electrical resistivity of copper [Ω·m]. - :rtype: float - - :notes: + """Calculates the electrical resistivity of cryogenic copper due to magnetoresistive effects [Ω·m]. + + Parameters + ---------- + resistivity: + Operating resistivity [K]. + field: + Operating magnetic field [T]. + + Returns + ------- + : + Electrical resistivity of copper [Ω·m]. + + Notes + ----- - Resistivity increases with magnetic field due to magnetoresistance effects. - :references: + References + ---------- - J. Simon, E. S. Drexler, and R. P. Reed, *NIST Monograph 177*, "Properties of Copper and Copper Alloys at Cryogenic Temperatures", U.S. Government Printing Office, February 1992. https://nvlpubs.nist.gov/nistpubs/Legacy/MONO/nistmonograph177.pdf @@ -161,34 +183,43 @@ def _copper_magneto_resistivity(resistivity: float, field: float) -> float: def _copper_electrical_resistivity( temperature: float, field: float, rrr: float, fluence: float ) -> float: - """ - Calculates the electrical resistivity of cryogenic copper with temperature, RRR, magnetic + """Calculates the electrical resistivity of cryogenic copper with temperature, RRR, magnetic field, and fluence dependence [Ω·m]. - :author M. Coleman, UKAEA - - :param float temperature: Operating temperature [K]. - :param float rrr: Residual resistivity ratio (dimensionless). - :param float field: Operating magnetic field [T]. - :param float fluence: Total end-of-life neutron fluence [n/m²]. - :returns: Electrical resistivity of copper [Ω·m]. - :rtype: float - - :notes: - - Resistivity increases with magnetic field due to magnetoresistance effects. - :references: - - J. Simon, E. S. Drexler, and R. P. Reed, *NIST Monograph 177*, "Properties of Copper and Copper Alloys - at Cryogenic Temperatures", U.S. Government Printing Office, February 1992. - https://nvlpubs.nist.gov/nistpubs/Legacy/MONO/nistmonograph177.pdf - Equation 8-1 - - J. G. Hust, A. B. Lankford, NBSIR 84-3007 "THERMAL CONDUCTIVITY OF ALUMINUM, COPPER, IRON, AND - TUNGSTEN FOR TEMPERATURES FROM 1 K TO THE MELTING POINT", 1984 - https://nvlpubs.nist.gov/nistpubs/Legacy/IR/nbsir84-3007.pdf - - M. Kovari, 09/11/2012, internal notes (Excel / Mathcad), Technology Program, WP12, PEX, Super-X Divertor for DEMO. - - M. Nakagawa et al., "High-dose neutron-irradiation effects in fcc metals at 4.6 K", *Phys. Rev. B*, 16, 5285 (1977). - https://doi.org/10.1103/PhysRevB.16.5285 - Figure 6 + Parameters + ---------- + temperature: + Operating temperature [K]. + rrr: + Residual resistivity ratio (dimensionless). + field: + Operating magnetic field [T]. + fluence: + Total end-of-life neutron fluence [n/m²]. + + Returns + ------- + float + Electrical resistivity of copper [Ω·m]. + + Notes + ----- + - Resistivity increases with magnetic field due to magnetoresistance effects. + + References + ---------- + - J. Simon, E. S. Drexler, and R. P. Reed, *NIST Monograph 177*, "Properties of Copper and Copper Alloys + at Cryogenic Temperatures", U.S. Government Printing Office, February 1992. + https://nvlpubs.nist.gov/nistpubs/Legacy/MONO/nistmonograph177.pdf + Equation 8-1 + - J. G. Hust, A. B. Lankford, NBSIR 84-3007 "THERMAL CONDUCTIVITY OF ALUMINUM, COPPER, IRON, AND + TUNGSTEN FOR TEMPERATURES FROM 1 K TO THE MELTING POINT", 1984 + https://nvlpubs.nist.gov/nistpubs/Legacy/IR/nbsir84-3007.pdf + - M. Kovari, 09/11/2012, internal notes (Excel / Mathcad), Technology Program, WP12, PEX, Super-X Divertor for DEMO. + - M. Nakagawa et al., "High-dose neutron-irradiation effects in fcc metals at 4.6 K", *Phys. Rev. B*, 16, 5285 (1977). + https://doi.org/10.1103/PhysRevB.16.5285 + Figure 6 """ rho_rrr = _copper_rrr_resistivity(temperature, rrr) rho_irr = _copper_irradiation_resistivity(fluence) @@ -196,27 +227,32 @@ def _copper_electrical_resistivity( def _nb3sn_specific_heat_capacity(temperature: float) -> float: - """ - Calculates the specific heat capacity of Nb₃Sn as a function of temperature. + """Calculates the specific heat capacity of Nb₃Sn as a function of temperature. Provides the temperature-dependent specific heat capacity [J/(kg·K)] of the A15 superconductor Nb₃Sn. - :author M. Coleman, UKAEA - - :param float temperature: Temperature [K]. - :returns: Specific heat capacity of Nb₃Sn at the given temperature [J/(kg·K)]. - :rtype: float - - :notes: - - The superconducting part is ignored, which is typical in thermal quench calculations. - - :references: - - EFDA Material Data Compilation for Superconductor Simulation, P. Bauer, H. Rajainmaki, E. Salpietro, EFDA CSU, Garching, 04/18/07. - - ITER DRG1 Annex, Superconducting Material Database, Article 5, N 11 FDR 42 01-07-05 R 0.1. - - V.D. Arp, Stability and Thermal Quenches in Force-Cooled Superconducting Cables, Superconducting MHD Magnet Design Conf., MIT, pp 142-157, 1980. - - G.S. Knapp, S.D. Bader, Z. Fisk, Phonon properties of A-15 superconductors obtained from heat capacity measurements, Phys. Rev. B, 13(9), pp 3783-3789, 1976. - https://doi.org/10.1103/PhysRevB.13.3783 + Parameters + ---------- + temperature: + Temperature [K]. + + Returns + ------- + float + Specific heat capacity of Nb₃Sn at the given temperature [J/(kg·K)]. + + Notes + ----- + - The superconducting part is ignored, which is typical in thermal quench calculations. + + References + ---------- + - EFDA Material Data Compilation for Superconductor Simulation, P. Bauer, H. Rajainmaki, E. Salpietro, EFDA CSU, Garching, 04/18/07. + - ITER DRG1 Annex, Superconducting Material Database, Article 5, N 11 FDR 42 01-07-05 R 0.1. + - V.D. Arp, Stability and Thermal Quenches in Force-Cooled Superconducting Cables, Superconducting MHD Magnet Design Conf., MIT, pp 142-157, 1980. + - G.S. Knapp, S.D. Bader, Z. Fisk, Phonon properties of A-15 superconductors obtained from heat capacity measurements, Phys. Rev. B, 13(9), pp 3783-3789, 1976. + https://doi.org/10.1103/PhysRevB.13.3783 """ gamma: Final[float] = 0.1 # [J/K²/kg] (Grueneisen) beta: Final[float] = 0.001 # [J/K⁴/kg] (Debye) @@ -242,26 +278,34 @@ def _quench_integrals( rrr: float, fluence: float, ) -> tuple[float, float, float]: - """ - Calculates the material property integrals for quench protection. + """Calculates the material property integrals for quench protection. Evaluates the integrals over temperature for helium, copper, and superconductor contributions. These integrals are used in determining current density limits during a quench. - :author M. Coleman, UKAEA - - :param float t_he_peak: Lower temperature bound of integration [K]. - :param float t_max: Upper temperature bound of integration [K]. - :param float field: Magnetic field [T]. - :param float rrr: Residual resistivity ratio of copper. - :param float fluence: Neutron fluence [n/cm²] (for irradiation effects). - :returns: Tuple of integrals for helium, copper, and superconductor contributions (I_He, I_Cu, I_sc). - :rtype: Tuple[float, float, float] - - :notes: - - Integrals assume temperature-dependent material models are defined for the entire range [t_he_peak, t_max]. - - Helium is assumed to be at constant pressure throughout the quench (i.e. some PRV in the - cooling system) + Parameters + ---------- + t_he_peak: + t_he_peak: Lower temperature bound of integration [K]. + t_max: + t_max: Upper temperature bound of integration [K]. + field: + field: Magnetic field [T]. + rrr: + rrr: Residual resistivity ratio of copper. + fluence: + fluence: Neutron fluence [n/cm²] (for irradiation effects). + + Returns + ------- + Tuple[float, float, float] + Tuple of integrals for helium, copper, and superconductor contributions (I_He, I_Cu, I_sc). + + Notes + ----- + - Integrals assume temperature-dependent material models are defined for the entire range [t_he_peak, t_max]. + - Helium is assumed to be at constant pressure throughout the quench (i.e. some PRV in the + cooling system) """ # Helium pressure [Pa] (assumed to be constant throughout quench) - no plans to make input pressure = 6e5 # ITER TF coolant pressure @@ -297,8 +341,7 @@ def calculate_quench_protection_current_density( detection_time: float, fluence: float, ) -> float: - """ - Calculates the current density limited by the protection limit. + """Calculates the current density limited by the protection limit. Simplified 0-D adiabatic heat balance "hotspot criterion" model. @@ -307,29 +350,43 @@ def calculate_quench_protection_current_density( field does not decay over time and accounts for contributions from copper, helium, and superconductor materials using temperature integrals. - :author M. Coleman, UKAEA - - :param float tau_discharge: Quench discharge time constant [s]. - :param float peak_field: Magnetic field at the peak point [T]. - :param float f_cu: Fraction of conductor cross-section that is copper. - :param float f_he: Fraction of cable occupied by helium. - :param float t_he_peak: Peak helium temperature at quench initiation [K]. - :param float t_max: Maximum allowed conductor temperature during quench [K]. - :param float cu_rrr: Residual resistivity ratio of copper. - :param float detection_time: Detection time delay [s]. - :param float fluence: Neutron fluence [n/m²]. - :returns: Maximum allowable winding pack current density [A/m²]. - :rtype: float - - :notes: - - Assumes constant magnetic field over the duration of the quench. - - Assumes the dump resistor has a constant resistance much higher - than that of the TF coil. - - Operates on the current-carring cross-section of a conductor. The - jacket and insulation are ignored. The actual allowable WP current - density must be weighted with the ratio of current-carrying cross-section - vs. total WP cross-section (including jacket and insulation). - - Presently only applicable to LTS TF coil winding packs (Nb3Sn assumed) + + Parameters + ---------- + tau_discharge: + tau_discharge: Quench discharge time constant [s]. + peak_field: + peak_field: Magnetic field at the peak point [T]. + f_cu: + f_cu: Fraction of conductor cross-section that is copper. + f_he: + f_he: Fraction of cable occupied by helium. + t_he_peak: + t_he_peak: Peak helium temperature at quench initiation [K]. + t_max: + t_max: Maximum allowed conductor temperature during quench [K]. + cu_rrr: + cu_rrr: Residual resistivity ratio of copper. + detection_time: + detection_time: Detection time delay [s]. + fluence: + fluence: Neutron fluence [n/m²]. + + Returns + ------- + float + Maximum allowable winding pack current density [A/m²]. + + Notes + ----- + - Assumes constant magnetic field over the duration of the quench. + - Assumes the dump resistor has a constant resistance much higher + than that of the TF coil. + - Operates on the current-carring cross-section of a conductor. The + jacket and insulation are ignored. The actual allowable WP current + density must be weighted with the ratio of current-carrying cross-section + vs. total WP cross-section (including jacket and insulation). + - Presently only applicable to LTS TF coil winding packs (Nb3Sn assumed) """ # Default fluence is too high for this model if (fluence < 0.0) | (fluence > 1.5e23): diff --git a/process/resistive_tf_coil.py b/process/resistive_tf_coil.py index 244789ae65..73576f8341 100644 --- a/process/resistive_tf_coil.py +++ b/process/resistive_tf_coil.py @@ -24,7 +24,13 @@ def __init__(self): self.outfile = constants.NOUT def run(self, output: bool): - """Run main tfcoil subroutine without outputting.""" + """Run main tfcoil subroutine without outputting. + + Parameters + ---------- + output: bool + + """ self.iprint = 0 # Set up TF values share by all coil types @@ -263,9 +269,7 @@ def run(self, output: bool): def res_tf_internal_geom(self): """ - Author : S. Kahn - Resisitve TF turn geometry, equivalent to winding_pack subroutines - + Resistive TF turn geometry, equivalent to winding_pack subroutines """ superconducting_tf_coil_variables.r_tf_wp_inboard_inner = ( build_variables.r_tf_inboard_in + tfcoil_variables.dr_tf_nose_case @@ -441,9 +445,8 @@ def res_tf_internal_geom(self): f"Negative cable space dimension. {superconducting_tf_coil_variables.a_tf_wp_no_insulation=}" ) - def tf_res_heating(self) -> None: - """ - Calculate resistive heating for resistive magnets. + def tf_res_heating(self): + """Calculate resistive heating for resistive magnets. This method calculates the resistive heating for resistive magnets. It considers the following scenarios: @@ -451,7 +454,7 @@ def tf_res_heating(self) -> None: - Sliding joints might have a region of high resistivity. Notes: - - The copper resisitivty is set to be that for GLIDCOP AL-15 at 20°C for copper (i_tf_sup = 0). + - The copper resistivity is set to be that for GLIDCOP AL-15 at 20°C for copper (i_tf_sup = 0). - The coefficient of resistivity is set to be that of pure copper References: @@ -463,7 +466,7 @@ def tf_res_heating(self) -> None: # Resistivity of the Glidcop copper centerpost if tfcoil_variables.i_tf_sup == 0: tfcoil_variables.rho_cp = ( - # 1.86 is the resitivity at `20°C` for GLIDCOP AL-15 + # 1.86 is the resistivity at `20°C` for GLIDCOP AL-15 # 0.00393 is the coefficient of resistivity for copper tfcoil_variables.frhocp * (1.86e0 + 0.00393e0 * (tfcoil_variables.temp_cp_average - 293.15e0)) @@ -650,9 +653,7 @@ def tf_res_heating(self) -> None: tfcoil_variables.p_tf_joints_resistive = 0.0e0 def resistive_tf_coil_areas_and_masses(self): - """ - Calculate the areas and masses of the resistive TF coil - """ + """Calculate the areas and masses of the resistive TF coil""" vol_case = 0.0e0 # Total TF case volume [m3] vol_ins = 0.0e0 # Total leg turn insulation volume [m3] @@ -742,9 +743,6 @@ def resistive_tf_coil_areas_and_masses(self): * tfcoil_variables.n_tf_coils ) - # --- - # ------- - # Copper magnets casing/conductor weights per coil [kg] if tfcoil_variables.i_tf_sup == 0: tfcoil_variables.m_tf_coil_case = ( @@ -851,22 +849,45 @@ def cpost( n_tf_coils, ): """ - author: P J Knight, CCFE, Culham Science Centre Calculates the volume and resistive power losses of a TART centrepost This routine calculates the volume and resistive power losses of a TART centrepost. It is assumed to be tapered - narrowest at the midplane and reaching maximum thickness at the height of the plasma. Above/below the plasma, the centrepost is cylindrical. The shape of the taper is assumed to be an arc of a circle. - P J Knight, CCFE, Culham Science Centre - 21/10/96 PJK Initial version - 08/05/12 PJK Initial F90 version - 16/10/12 PJK Added constants; removed argument pi - 26/06/14 PJK Added error handling - 12/11/19 SK Using fixed cooling cross-section area along the CP - 26/11/19 SK added the coolant area, the conuctor/isulator/outer casing volume - 30/11/20 SK added the ground outer ground insulation volume + F/MI/PJK/LOGBOOK12, pp.33,34 + + Parameters + ---------- + r_tf_inboard_in : + + r_tf_inboard_out : + + r_cp_top : + + ztop : + + hmaxi : + + cas_in_th : + + cas_out_th : + + gr_ins_th : + + ins_th : + + n_tf_coil_turns : + + curr : + + rho : + + fcool : + + n_tf_coils : + """ yy_ins = np.zeros((101,)) # Exact conductor area (to be integrated) yy_cond = np.zeros((101,)) # Turn insulation area (to be integrated) @@ -1118,14 +1139,12 @@ def cpost( class CopperTFCoil(ResistiveTFCoil): - """ - Copper TF coil class for resistive TF coil calculations. + """Copper TF coil class for resistive TF coil calculations. Inherits from ResistiveTFCoil and implements specific methods for copper TF coils. """ class AluminiumTFCoil(ResistiveTFCoil): - """ - Aluminium TF coil class for resistive TF coil calculations. + """Aluminium TF coil class for resistive TF coil calculations. Inherits from ResistiveTFCoil and implements specific methods for aluminium TF coils. """ diff --git a/process/scan.py b/process/scan.py index 63f0ca96fc..8c5ff48cb9 100644 --- a/process/scan.py +++ b/process/scan.py @@ -1,5 +1,6 @@ import logging from dataclasses import astuple, dataclass +from enum import Enum import numpy as np from tabulate import tabulate @@ -37,106 +38,158 @@ class ScanVariable: variable_name: str variable_description: str + variable_num: int def __iter__(self): - return iter(astuple(self)) - - -SCAN_VARIABLES = { - 1: ScanVariable("aspect", "Aspect_ratio"), - 2: ScanVariable("pflux_div_heat_load_max_mw", "Div_heat_limit_(MW/m2)"), - 3: ScanVariable("p_plant_electric_net_required_mw", "Net_electric_power_(MW)"), - 4: ScanVariable("hfact", "Confinement_H_factor"), - 5: ScanVariable("oacdcp", "TF_inboard_leg_J_(MA/m2)"), - 6: ScanVariable("pflux_fw_neutron_max_mw", "Allow._wall_load_(MW/m2)"), - 7: ScanVariable("beamfus0", "Beam_bkgrd_multiplier"), - 9: ScanVariable("temp_plasma_electron_vol_avg_kev", "Electron_temperature_keV"), - 10: ScanVariable("boundu(15)", "Volt-second_upper_bound"), - 11: ScanVariable("beta_norm_max", "Beta_coefficient"), - 12: ScanVariable("f_c_plasma_bootstrap_max", "Bootstrap_fraction"), - 13: ScanVariable("boundu(10)", "H_factor_upper_bound"), - 14: ScanVariable("fiooic", "TFC_Iop_/_Icrit_f-value"), - 16: ScanVariable("rmajor", "Plasma_major_radius_(m)"), - 17: ScanVariable("b_tf_inboard_max", "Max_toroidal_field_(T)"), - 18: ScanVariable("eta_cd_norm_hcd_primary_max", "Maximum_CD_gamma"), - 19: ScanVariable("boundl(16)", "CS_thickness_lower_bound"), - 20: ScanVariable("t_burn_min", "Minimum_burn_time_(s)"), - 22: ScanVariable("f_t_plant_available", "Plant_availability_factor"), - 24: ScanVariable("p_fusion_total_max_mw", "Fusion_power_limit_(MW)"), - 25: ScanVariable("kappa", "Plasma_elongation"), - 26: ScanVariable("triang", "Plasma_triangularity"), - 27: ScanVariable("tbrmin", "Min_tritium_breed._ratio"), - 28: ScanVariable("b_plasma_toroidal_on_axis", "Tor._field_on_axis_(T)"), - 29: ScanVariable("coreradius", "Core_radius"), - 31: ScanVariable( - "f_alpha_energy_confinement_min", "t_alpha_confinement/taueff_lower_limit" - ), - 32: ScanVariable("epsvmc", "VMCON error tolerance"), - 38: ScanVariable("boundu(129)", " Neon upper limit"), - 39: ScanVariable("boundu(131)", " Argon upper limit"), - 40: ScanVariable("boundu(135)", " Xenon upper limit"), - 41: ScanVariable("dr_blkt_outboard", "Outboard blanket thick."), - 42: ScanVariable("f_nd_impurity_electrons(9)", "Argon fraction"), - 44: ScanVariable("sig_tf_case_max", "Allowable_stress_in_tf_coil_case_Tresca_(pa)"), - 45: ScanVariable( - "temp_tf_superconductor_margin_min", "Minimum_allowable_temperature_margin" - ), - 46: ScanVariable("boundu(152)", "Max allowable f_nd_plasma_separatrix_greenwald"), - 48: ScanVariable("n_tf_wp_pancakes", "TF Coil - n_tf_wp_pancakes"), - 49: ScanVariable("n_tf_wp_layers", "TF Coil - n_tf_wp_layers"), - 50: ScanVariable("f_nd_impurity_electrons(13)", "Xenon fraction"), - 51: ScanVariable("f_p_div_lower", "lower_divertor_power_fraction"), - 52: ScanVariable("rad_fraction_sol", "SoL radiation fraction"), - 53: ScanVariable("boundu(157)", "Max allowable fvssu"), - 54: ScanVariable("Bc2(0K)", "GL_NbTi Bc2(0K)"), - 55: ScanVariable("dr_shld_inboard", "Inboard neutronic shield"), - 56: ScanVariable( - "p_cryo_plant_electric_max_mw", "max allowable p_cryo_plant_electric_mw" - ), - 57: ScanVariable("boundl(2)", "b_plasma_toroidal_on_axis minimum"), - 58: ScanVariable("dr_fw_plasma_gap_inboard", "Inboard FW-plasma sep gap"), - 59: ScanVariable("dr_fw_plasma_gap_outboard", "Outboard FW-plasma sep gap"), - 60: ScanVariable("sig_tf_wp_max", "Allowable_stress_in_tf_coil_conduit_Tresca_(pa)"), - 61: ScanVariable("copperaoh_m2_max", "Max CS coil current / copper area"), - 62: ScanVariable("coheof", "CS coil current density at EOF (A/m2)"), - 63: ScanVariable("dr_cs", "CS coil thickness (m)"), - 64: ScanVariable("ohhghf", "CS height (m)"), - 65: ScanVariable("n_cycle_min", "CS stress cycles min"), - 66: ScanVariable("oh_steel_frac", "CS steel fraction"), - 67: ScanVariable("t_crack_vertical", "Initial crack vertical size (m)"), - 68: ScanVariable( - "inlet_temp_liq", "Inlet Temperature Liquid Metal Breeder/Coolant (K)" - ), - 69: ScanVariable( - "outlet_temp_liq", "Outlet Temperature Liquid Metal Breeder/Coolant (K)" - ), - 70: ScanVariable( - "blpressure_liq", "Blanket liquid metal breeder/coolant pressure (Pa)" - ), - 71: ScanVariable( - "n_liq_recirc", "Selected number of liquid metal breeder recirculations per day" - ), - 72: ScanVariable( + return iter(astuple(self)[:2]) + + +class ScanVariables(Enum): + @classmethod + def _missing_(cls, var): + if isinstance(var, int): + for sv in cls: + if sv.value.variable_num == var: + return sv + return super()._missing_(var) + + aspect = ScanVariable("aspect", "Aspect_ratio", 1) + pflux_div_heat_load_max_mw = ScanVariable( + "pflux_div_heat_load_max_mw", "Div_heat_limit_(MW/m2)", 2 + ) + p_plant_electric_net_required_mw = ScanVariable( + "p_plant_electric_net_required_mw", "Net_electric_power_(MW)", 3 + ) + hfact = ScanVariable("hfact", "Confinement_H_factor", 4) + oacdcp = ScanVariable("oacdcp", "TF_inboard_leg_J_(MA/m2)", 5) + pflux_fw_neutron_max_mw = ScanVariable( + "pflux_fw_neutron_max_mw", "Allow._wall_load_(MW/m2)", 6 + ) + beamfus0 = ScanVariable("beamfus0", "Beam_bkgrd_multiplier", 7) + temp_plasma_electron_vol_avg_kev = ScanVariable( + "temp_plasma_electron_vol_avg_kev", "Electron_temperature_keV", 9 + ) + boundu15 = ScanVariable("boundu(15)", "Volt-second_upper_bound", 10) + beta_norm_max = ScanVariable("beta_norm_max", "Beta_coefficient", 11) + f_c_plasma_bootstrap_max = ScanVariable( + "f_c_plasma_bootstrap_max", "Bootstrap_fraction", 12 + ) + boundu10 = ScanVariable("boundu(10)", "H_factor_upper_bound", 13) + fiooic = ScanVariable("fiooic", "TFC_Iop_/_Icrit_f-value", 14) + rmajor = ScanVariable("rmajor", "Plasma_major_radius_(m)", 16) + b_tf_inboard_max = ScanVariable("b_tf_inboard_max", "Max_toroidal_field_(T)", 17) + eta_cd_norm_hcd_primary_max = ScanVariable( + "eta_cd_norm_hcd_primary_max", "Maximum_CD_gamma", 18 + ) + boundl16 = ScanVariable("boundl(16)", "CS_thickness_lower_bound", 19) + t_burn_min = ScanVariable("t_burn_min", "Minimum_burn_time_(s)", 20) + f_t_plant_available = ScanVariable( + "f_t_plant_available", "Plant_availability_factor", 22 + ) + p_fusion_total_max_mw = ScanVariable( + "p_fusion_total_max_mw", "Fusion_power_limit_(MW)", 24 + ) + kappa = ScanVariable("kappa", "Plasma_elongation", 25) + triang = ScanVariable("triang", "Plasma_triangularity", 26) + tbrmin = ScanVariable("tbrmin", "Min_tritium_breed._ratio", 27) + b_plasma_toroidal_on_axis = ScanVariable( + "b_plasma_toroidal_on_axis", "Tor._field_on_axis_(T)", 28 + ) + coreradius = ScanVariable("coreradius", "Core_radius", 29) + f_alpha_energy_confinement_min = ScanVariable( + "f_alpha_energy_confinement_min", "t_alpha_confinement/taueff_lower_limit", 31 + ) + epsvmc = ScanVariable("epsvmc", "VMCON error tolerance", 32) + boundu129 = ScanVariable("boundu(129)", " Neon upper limit", 38) + boundu131 = ScanVariable("boundu(131)", " Argon upper limit", 39) + boundu135 = ScanVariable("boundu(135)", " Xenon upper limit", 40) + dr_blkt_outboard = ScanVariable("dr_blkt_outboard", "Outboard blanket thick.", 41) + f_nd_impurity_electrons9 = ScanVariable( + "f_nd_impurity_electrons(9)", "Argon fraction", 42 + ) + sig_tf_case_max = ScanVariable( + "sig_tf_case_max", "Allowable_stress_in_tf_coil_case_Tresca_(pa)", 44 + ) + temp_tf_superconductor_margin_min = ScanVariable( + "temp_tf_superconductor_margin_min", "Minimum_allowable_temperature_margin", 45 + ) + boundu152 = ScanVariable( + "boundu(152)", "Max allowable f_nd_plasma_separatrix_greenwald", 46 + ) + n_tf_wp_pancakes = ScanVariable("n_tf_wp_pancakes", "TF Coil - n_tf_wp_pancakes", 48) + n_tf_wp_layers = ScanVariable("n_tf_wp_layers", "TF Coil - n_tf_wp_layers", 49) + f_nd_impurity_electrons13 = ScanVariable( + "f_nd_impurity_electrons(13)", "Xenon fraction", 50 + ) + f_p_div_lower = ScanVariable("f_p_div_lower", "lower_divertor_power_fraction", 51) + rad_fraction_sol = ScanVariable("rad_fraction_sol", "SoL radiation fraction", 52) + boundu157 = ScanVariable("boundu(157)", "Max allowable fvssu", 53) + Bc2_0K = ScanVariable("Bc2(0K)", "GL_NbTi Bc2(0K)", 54) + dr_shld_inboard = ScanVariable("dr_shld_inboard", "Inboard neutronic shield", 55) + p_cryo_plant_electric_max_mw = ScanVariable( + "p_cryo_plant_electric_max_mw", "max allowable p_cryo_plant_electric_mw", 56 + ) + boundl2 = ScanVariable("boundl(2)", "b_plasma_toroidal_on_axis minimum", 57) + dr_fw_plasma_gap_inboard = ScanVariable( + "dr_fw_plasma_gap_inboard", "Inboard FW-plasma sep gap", 58 + ) + dr_fw_plasma_gap_outboard = ScanVariable( + "dr_fw_plasma_gap_outboard", "Outboard FW-plasma sep gap", 59 + ) + sig_tf_wp_max = ScanVariable( + "sig_tf_wp_max", "Allowable_stress_in_tf_coil_conduit_Tresca_(pa)", 60 + ) + copperaoh_m2_max = ScanVariable( + "copperaoh_m2_max", "Max CS coil current / copper area", 61 + ) + coheof = ScanVariable("coheof", "CS coil current density at EOF (A/m2)", 62) + dr_cs = ScanVariable("dr_cs", "CS coil thickness (m)", 63) + ohhghf = ScanVariable("ohhghf", "CS height (m)", 64) + n_cycle_min = ScanVariable("n_cycle_min", "CS stress cycles min", 65) + oh_steel_frac = ScanVariable("oh_steel_frac", "CS steel fraction", 66) + t_crack_vertical = ScanVariable( + "t_crack_vertical", "Initial crack vertical size (m)", 67 + ) + inlet_temp_liq = ScanVariable( + "inlet_temp_liq", "Inlet Temperature Liquid Metal Breeder/Coolant (K)", 68 + ) + outlet_temp_liq = ScanVariable( + "outlet_temp_liq", "Outlet Temperature Liquid Metal Breeder/Coolant (K)", 69 + ) + blpressure_liq = ScanVariable( + "blpressure_liq", "Blanket liquid metal breeder/coolant pressure (Pa)", 70 + ) + n_liq_recirc = ScanVariable( + "n_liq_recirc", + "Selected number of liquid metal breeder recirculations per day", + 71, + ) + bz_channel_conduct_liq = ScanVariable( "bz_channel_conduct_liq", "Conductance of liquid metal breeder duct walls (A V-1 m-1)", - ), - 73: ScanVariable( - "pnuc_fw_ratio_dcll", "Ratio of FW nuclear power as fraction of total (FW+BB)" - ), - 74: ScanVariable( + 72, + ) + pnuc_fw_ratio_dcll = ScanVariable( + "pnuc_fw_ratio_dcll", + "Ratio of FW nuclear power as fraction of total (FW+BB)", + 73, + ) + f_nuc_pow_bz_struct = ScanVariable( "f_nuc_pow_bz_struct", - "Fraction of BZ power cooled by primary coolant for dual-coolant balnket", - ), - 75: ScanVariable("dx_fw_module", "dx_fw_module of first wall cooling channels (m)"), - 76: ScanVariable("eta_turbine", "Thermal conversion eff."), - 77: ScanVariable("startupratio", "Gyrotron redundancy"), - 78: ScanVariable("fkind", "Multiplier for Nth of a kind costs"), - 79: ScanVariable( - "eta_ecrh_injector_wall_plug", "ECH wall plug to injector efficiency" - ), - 80: ScanVariable("fcoolcp", "Coolant fraction of TF"), - 81: ScanVariable("n_tf_coil_turns", "Number of turns in TF"), -} + "Fraction of BZ power cooled by primary coolant for dual-coolant blanket", + 74, + ) + dx_fw_module = ScanVariable( + "dx_fw_module", "dx_fw_module of first wall cooling channels (m)", 75 + ) + eta_turbine = ScanVariable("eta_turbine", "Thermal conversion eff.", 76) + startupratio = ScanVariable("startupratio", "Gyrotron redundancy", 77) + fkind = ScanVariable("fkind", "Multiplier for Nth of a kind costs", 78) + eta_ecrh_injector_wall_plug = ScanVariable( + "eta_ecrh_injector_wall_plug", "ECH wall plug to injector efficiency", 79 + ) + fcoolcp = ScanVariable("fcoolcp", "Coolant fraction of TF", 80) + n_tf_coil_turns = ScanVariable("n_tf_coil_turns", "Number of turns in TF", 81) class Scan: @@ -193,8 +246,13 @@ def doopt(self): def post_optimise(self, ifail: int): """Called after calling the optimising equation solver from Python. - author: P J Knight, CCFE, Culham Science Centre + ifail : input integer : error flag + + Parameters + ---------- + ifail: int : + """ numerics.sqsumsq = sum(r**2 for r in numerics.rcm[: numerics.neqns]) ** 0.5 @@ -603,10 +661,15 @@ def post_optimise(self, ifail: int): def verror(self, ifail: int): """Routine to print out relevant messages in the case of an unfeasible result from a VMCON (optimisation) run - author: P J Knight, CCFE, Culham Science Centre + ifail : input integer : error flag This routine prints out relevant messages in the case of an unfeasible result from a VMCON (optimisation) run. + + Parameters + ---------- + ifail: int : + """ if ifail == -1: process_output.ocmmnt(constants.NOUT, "User-terminated execution of VMCON.") @@ -1139,4 +1202,4 @@ def scan_select(self, nwp, swp, iscn): case _: raise ProcessValueError("Illegal scan variable number", nwp=nwp) - return SCAN_VARIABLES[int(nwp)] + return ScanVariables(int(nwp)).value diff --git a/process/shield.py b/process/shield.py index b0cd6f1771..fc505acfd3 100644 --- a/process/shield.py +++ b/process/shield.py @@ -14,10 +14,10 @@ class Shield: - def __init__(self) -> None: + def __init__(self): self.outfile = constants.NOUT - def run(self) -> None: + def run(self): blanket_library.dz_shld_half = self.calculate_shield_half_height( z_plasma_xpoint_lower=build_variables.z_plasma_xpoint_lower, dz_xpoint_divertor=build_variables.dz_xpoint_divertor, @@ -135,7 +135,31 @@ def calculate_shield_half_height( dr_fw_outboard: float, dz_blkt_upper: float, ) -> float: - """Calculate shield half-height.""" + """Calculate shield half-height. + + Parameters + ---------- + z_plasma_xpoint_lower: + + dz_xpoint_divertor: + + dz_divertor: + + n_divertors: int : + + z_plasma_xpoint_upper: + + dr_fw_plasma_gap_inboard: + + dr_fw_plasma_gap_outboard: + + dr_fw_inboard: + + dr_fw_outboard: + + dz_blkt_upper: + + """ z_bottom = z_plasma_xpoint_lower + dz_xpoint_divertor + dz_divertor @@ -171,7 +195,35 @@ def calculate_dshaped_shield_volumes( dr_shld_outboard: float, dz_shld_upper: float, ) -> tuple[float, float, float]: - """Calculate volumes of D-shaped shield segments.""" + """Calculate volumes of D-shaped shield segments. + + Parameters + ---------- + r_shld_inboard_inner: + + dr_shld_inboard: + + dr_fw_inboard: + + dr_fw_plasma_gap_inboard: + + rminor: + + dr_fw_plasma_gap_outboard: + + dr_fw_outboard: + + dr_blkt_inboard: + + dr_blkt_outboard: + + dz_shld_half: + + dr_shld_outboard: + + dz_shld_upper: + + """ r_1 = r_shld_inboard_inner + dr_shld_inboard r_2 = ( @@ -212,7 +264,31 @@ def calculate_dshaped_shield_areas( dr_blkt_outboard: float, dz_shld_half: float, ) -> tuple[float, float, float]: - """Calculate areas of D-shaped shield segments.""" + """Calculate areas of D-shaped shield segments. + + Parameters + ---------- + r_shld_inboard_inner: + + dr_shld_inboard: + + dr_fw_inboard: + + dr_fw_plasma_gap_inboard: + + rminor: + + dr_fw_plasma_gap_outboard: + + dr_fw_outboard: + + dr_blkt_inboard: + + dr_blkt_outboard: + + dz_shld_half: + + """ r_1 = r_shld_inboard_inner + dr_shld_inboard r_2 = ( @@ -245,7 +321,29 @@ def calculate_elliptical_shield_volumes( dr_shld_outboard: float, dz_shld_upper: float, ) -> tuple[float, float, float]: - """Calculate volumes of elliptical shield segments.""" + """Calculate volumes of elliptical shield segments. + + Parameters + ---------- + r_shld_inboard_inner: + + r_shld_outboard_outer: + + rmajor: + + triang: + + dr_shld_inboard: + + rminor: + + dz_shld_half: + + dr_shld_outboard: + + dz_shld_upper: + + """ # Major radius to centre of inboard and outboard ellipses (m) # (coincident in radius with top of plasma) @@ -284,7 +382,27 @@ def calculate_elliptical_shield_areas( dz_shld_half: float, dr_shld_outboard: float, ) -> tuple[float, float, float]: - """Calculate areas of elliptical shield segments.""" + """Calculate areas of elliptical shield segments. + + Parameters + ---------- + r_shld_inboard_inner: + + r_shld_outboard_outer: + + rmajor: + + triang: + + dr_shld_inboard: + + rminor: + + dz_shld_half: + + dr_shld_outboard: + + """ # Major radius to centre of inboard and outboard ellipses (m) # (coincident in radius with top of plasma) @@ -304,7 +422,7 @@ def calculate_elliptical_shield_areas( return a_shld_inboard_surface, a_shld_outboard_surface, a_shld_total_surface - def output_shld_areas_and_volumes(self) -> None: + def output_shld_areas_and_volumes(self): """Output shield areas and volumes to log.""" po.oheadr(self.outfile, "Shield Areas and Volumes") diff --git a/process/solver.py b/process/solver.py index 32611b28b1..177b802bdd 100644 --- a/process/solver.py +++ b/process/solver.py @@ -24,32 +24,34 @@ class _Solver(ABC): - """Base class for different solver implementations. + """Base class for different solver implementations.""" - :param ABC: abstract base class - :type ABC: ABC - """ - - def __init__(self) -> None: + def __init__(self): """Initialise a solver.""" # Exit code for the solver self.ifail = 0 self.tolerance = numerics.epsvmc self.b: float | None = None - def set_evaluators(self, evaluators: Evaluators) -> None: + def set_evaluators(self, evaluators: Evaluators): """Set objective and constraint functions and their gradient evaluators. - :param evaluators: objective and constraint evaluators - :type evaluators: Evaluators + Parameters + ---------- + evaluators : Evaluators + objective and constraint evaluators + """ self.evaluators = evaluators - def set_opt_params(self, x_0: np.ndarray) -> None: + def set_opt_params(self, x_0: np.ndarray): """Define the initial optimisation parameters. - :param x_0: optimisation parameters vector - :type x_0: np.ndarray + Parameters + ---------- + x_0 : np.ndarray + optimisation parameters vector + """ self.x_0 = x_0 @@ -59,19 +61,21 @@ def set_bounds( bndu: np.ndarray, ilower: np.ndarray | None = None, iupper: np.ndarray | None = None, - ) -> None: + ): """Set the bounds on the optimisation parameters. - :param bndl: lower bounds for the optimisation parameters - :type bndl: np.ndarray - :param bndu: upper bounds for the optimisation parameters - :type bndu: np.ndarray - :param ilower: array of 0s and 1s to activate lower bounds on - optimsation parameters in x - :type ilower: np.ndarray, optional - :param iupper: array of 0s and 1s to activate upper bounds on - optimsation parameters in x - :type iupper: np.ndarray, optional + Parameters + ---------- + bndl : np.ndarray + lower bounds for the optimisation parameters + bndu : np.ndarray + upper bounds for the optimisation parameters + ilower : np.ndarray, optional + array of 0s and 1s to activate lower bounds on + optimsation parameters in x + iupper : np.ndarray, optional + array of 0s and 1s to activate upper bounds on + optimsation parameters in x """ self.bndl = bndl self.bndu = bndu @@ -87,30 +91,36 @@ def set_bounds( self.ilower = ilower self.iupper = iupper - def set_constraints(self, m: int, meq: int) -> None: + def set_constraints(self, m: int, meq: int): """Set the total number of constraints and equality constraints. - :param m: number of constraint equations - :type m: int - :param meq: of the constraint equations, how many are equalities - :type meq: int + Parameters + ---------- + m : int + number of constraint equations + meq : int + of the constraint equations, how many are equalities """ self.m = m self.meq = meq - def set_tolerance(self, tolerance: float) -> None: + def set_tolerance(self, tolerance: float): """Set tolerance for solver termination. - :param tolerance: tolerance for solver termination - :type tolerance: float + Parameters + ---------- + tolerance : float + tolerance for solver termination """ self.tolerance = tolerance - def set_b(self, b: float) -> None: + def set_b(self, b: float): """Set the multiplier for the Hessian approximation. - :param b: multiplier for an identity matrix as input for the Hessian b(n,n) - :type b: float + Parameters + ---------- + b : float + multiplier for an identity matrix as input for the Hessian b(n,n) """ self.b = b @@ -118,13 +128,15 @@ def set_b(self, b: float) -> None: def solve(self) -> int: """Run the optimisation. - :return: solver error code - :rtype: int + Returns + ------- + int + solver error code """ class VmconProblem(AbstractProblem): - def __init__(self, evaluator, nequality, ninequality) -> None: + def __init__(self, evaluator, nequality, ninequality): self._evaluator = evaluator self._nequality = nequality self._ninequality = ninequality @@ -153,17 +165,15 @@ def num_inequality(self) -> int: class Vmcon(_Solver): - """New VMCON implementation. - - :param _Solver: Solver base class - :type _Solver: _Solver - """ + """New VMCON implementation.""" def solve(self) -> int: """Optimise using new VMCON. - :return: solver error code - :rtype: int + Returns + ------- + int + solver error code """ problem = VmconProblem(self.evaluators, self.meq, self.m - self.meq) @@ -192,18 +202,24 @@ def _ineq_cons_satisfied( This additional convergence criterion ensures that solutions have satisfied inequality constraints. - :param result: evaluation of current optimisation parameter vector - :type result: Result - :param _x: current optimisation parameter vector - :type _x: np.ndarray - :param _delta: search direction for line search - :type _delta: np.ndarray - :param _lambda_eq: equality Lagrange multipliers - :type _lambda_eq: np.ndarray - :param _lambda_in: inequality Lagrange multipliers - :type _lambda_in: np.ndarray - :return: True if inequality constraints satisfied - :rtype: bool + Parameters + ---------- + result : Result + evaluation of current optimisation parameter vector + _x : np.ndarray + current optimisation parameter vector + _delta : np.ndarray + search direction for line search + _lambda_eq : np.ndarray + equality Lagrange multipliers + _lambda_in : np.ndarray + inequality Lagrange multipliers + + Returns + ------- + bool + True if inequality constraints satisfied + """ # negative constraint value = violated # Check all ineqs are satisfied to within the tolerance @@ -264,7 +280,7 @@ def _ineq_cons_satisfied( class VmconBounded(Vmcon): """A solver that uses VMCON but checks x is in bounds before running""" - def set_opt_params(self, x_0: np.ndarray) -> None: + def set_opt_params(self, x_0: np.ndarray): lower_violated = np.less(x_0, self.bndl) upper_violated = np.greater(x_0, self.bndu) @@ -278,19 +294,20 @@ def set_opt_params(self, x_0: np.ndarray) -> None: class FSolve(_Solver): - """Solve equality constraints to ensure model consistency. - - :param _Solver: Solver base class - :type _Solver: _Solver - """ + """Solve equality constraints to ensure model consistency.""" def evaluate_eq_cons(self, x: np.ndarray) -> np.ndarray: """Evaluate equality constraints. - :param x: parameter vector - :type x: np.ndarray - :return: equality constraint vector - :rtype: np.ndarray + Parameters + ---------- + x : np.ndarray + parameter vector + + Returns + ------- + np.ndarray + equality constraint vector """ # Evaluate equality constraints only _, conf = self.evaluators.fcnvmc1(x.shape[0], self.meq, x, 0) @@ -300,8 +317,10 @@ def evaluate_eq_cons(self, x: np.ndarray) -> np.ndarray: def solve(self) -> int: """Solve equality constraints. - :return: solver error code - :rtype: int + Returns + ------- + int + solver error code """ print("Solving equality constraints using fsolve") self.x, _info, err, msg = fsolve( @@ -324,10 +343,15 @@ def solve(self) -> int: def get_solver(solver_name: str = "vmcon") -> _Solver: """Return a solver instance. - :param solver_name: solver to create, defaults to "vmcon" - :type solver_name: str, optional - :return: solver to use for optimisation - :rtype: _Solver + Parameters + ---------- + solver_name : str, optional + solver to create, defaults to "vmcon" + + Returns + ------- + _Solver + solver to use for optimisation """ solver: _Solver @@ -352,7 +376,13 @@ def load_external_solver(package: str): """Attempts to load a package of name `package`. If a package of the name is available, return the `__process_solver__` - attribute of that package or raise an `AttributeError`.""" + attribute of that package or raise an `AttributeError`. + + Parameters + ---------- + package: str : + + """ module = importlib.import_module(package) solver = getattr(module, "__process_solver__", None) diff --git a/process/solver_handler.py b/process/solver_handler.py index bda4d6b47c..e35f9a668c 100644 --- a/process/solver_handler.py +++ b/process/solver_handler.py @@ -5,17 +5,19 @@ class SolverHandler: - def __init__(self, models, solver_name): - """Creates and runs a solver instance. + """Creates and runs a solver instance. - This may be an optimiser (e.g. VMCON) or an equation solver (e.g. - fsolve). + This may be an optimiser (e.g. VMCON) or an equation solver (e.g. fsolve). - :param models: physics and engineering model objects - :type models: process.main.Models - :param solver_name: which solver to use, as specified in solver.py - :type solver_name: str - """ + Parameters + ---------- + models : process.main.Models + physics and engineering model objects + solver_name : str + which solver to use, as specified in solver.py + """ + + def __init__(self, models, solver_name): self.models = models self.solver_name = solver_name diff --git a/process/stellarator/build.py b/process/stellarator/build.py index f9c688b193..629b943604 100644 --- a/process/stellarator/build.py +++ b/process/stellarator/build.py @@ -13,16 +13,20 @@ def st_build(stellarator, f_output: bool): - """ - Routine to determine the build of a stellarator machine - author: P J Knight, CCFE, Culham Science Centre - author: F Warmer, IPP Greifswald - outfile : input integer : output file unit - iprint : input integer : switch for writing to output file (1=yes) + """Routine to determine the build of a stellarator machine + This routine determines the build of the stellarator machine. The values calculated are based on the mean minor radius, etc., as the actual radial and vertical build thicknesses vary with toroidal angle. + + Parameters + ---------- + stellarator : + + f_output: + + """ if fwbs_variables.blktmodel > 0: build_variables.dr_blkt_inboard = ( diff --git a/process/stellarator/coils/calculate.py b/process/stellarator/coils/calculate.py index c1ebfa8eac..66fc774b6f 100644 --- a/process/stellarator/coils/calculate.py +++ b/process/stellarator/coils/calculate.py @@ -20,17 +20,21 @@ def st_coil(stellarator, output: bool): - """ - This routine calculates the properties of the coils for + """This routine calculates the properties of the coils for a stellarator device. - author: J Lion, IPP Greifswald - outfile : input integer : output file unit - iprint : input integer : switch for writing to output file (1=yes) Some precalculated effective parameters for a stellarator power plant design are used as the basis for the calculations. The coils are assumed to be a fixed shape, but are scaled in size appropriately for the machine being modelled. + + Parameters + ---------- + stellarator : + + output: + + """ r_coil_major = stellarator_variables.r_coil_major r_coil_minor = stellarator_variables.r_coil_minor @@ -222,9 +226,15 @@ def calculate_plasma_facing_coil_area(): def calculate_coil_coil_toroidal_gap(r_coil_major, r_coil_minor): - """ - [m] Minimal distance in toroidal direction between two stellarator coils + """[m] Minimal distance in toroidal direction between two stellarator coils Consistency with coil width is checked in constraint equation 82 + + Parameters + ---------- + r_coil_major : + + r_coil_minor : + """ # [m] Toroidal gap between two coil filaments tfcoil_variables.toroidalgap = ( @@ -243,7 +253,19 @@ def calculate_coil_coil_toroidal_gap(r_coil_major, r_coil_minor): def calculate_coils_summary_variables(coilcurrent, r_coil_major, r_coil_minor, awp_rad): - """Variables for ALL coils.""" + """Variables for ALL coils. + + Parameters + ---------- + coilcurrent : + + r_coil_major : + + r_coil_minor : + + awp_rad : + + """ # [m^2] Total area of all coil legs (midplane) tfcoil_variables.a_tf_inboard_total = ( tfcoil_variables.n_tf_coils * tfcoil_variables.a_tf_leg_outboard @@ -263,7 +285,13 @@ def calculate_coils_summary_variables(coilcurrent, r_coil_major, r_coil_minor, a def calculate_inductnace(r_coil_minor): - """This uses the reference value for the inductance and scales it with a^2/R (toroid inductance scaling)""" + """This uses the reference value for the inductance and scales it with a^2/R (toroid inductance scaling) + + Parameters + ---------- + r_coil_minor : + + """ return ( stellarator_configuration.stella_config_inductance / stellarator_variables.f_st_rmajor @@ -273,7 +301,13 @@ def calculate_inductnace(r_coil_minor): def calculate_stored_magnetic_energy(r_coil_minor): - """[GJ] Total magnetic energy""" + """[GJ] Total magnetic energy + + Parameters + ---------- + r_coil_minor : + + """ tfcoil_variables.e_tf_magnetic_stored_total_gj = ( 0.5e0 * ( @@ -288,9 +322,9 @@ def calculate_stored_magnetic_energy(r_coil_minor): def calculate_winding_pack_geometry(): - """ - Winding Pack Geometry: for one conductor + """Winding Pack Geometry: for one conductor This one conductor will just be multiplied later to fit the winding pack size. + """ # [m] Dimension of square cable space inside insulation # and case of the conduit of each turn @@ -315,10 +349,10 @@ def calculate_winding_pack_geometry(): def calculate_current(): - """ - Recalculate the coil current from global stellarator configuration and variables: + """Recalculate the coil current from global stellarator configuration and variables: coilcurrent = f_b * stella_config_i0 * f_r / f_n Update stellarator_variables.f_i + """ coilcurrent = ( stellarator_variables.f_st_b @@ -491,11 +525,17 @@ def winding_pack_total_size( def calculate_casing(): - """ - Coil case thickness (m). Here assumed to be constant until something better comes up. - case_thickness_constant = tfcoil_variables.dr_tf_nose_case #0.2e0 # ? - Leave this constant for now... Check this## Should be scaled with forces I think. + """Coil case thickness (m). + + Here assumed to be constant until something better comes up. For now assumed to be constant in a bolted plate model. + + case_thickness_constant = tfcoil_variables.dr_tf_nose_case + + #0.2e0 ? + Leave this constant for now... Check this + + ## Should be scaled with forces I think. """ # [m] coil case thickness outboard distance (radial) tfcoil_variables.dr_tf_plasma_case = tfcoil_variables.dr_tf_nose_case diff --git a/process/stellarator/coils/coils.py b/process/stellarator/coils/coils.py index 9599eb9b7e..0511adc94b 100644 --- a/process/stellarator/coils/coils.py +++ b/process/stellarator/coils/coils.py @@ -153,20 +153,31 @@ def jcrit_from_material( def intersect(x1, y1, x2, y2, xin): """Routine to find the x (abscissa) intersection point of two curves each defined by tabulated (x,y) values - author: P J Knight, CCFE, Culham Science Centre - x1(1:n1) : input real array : x values for first curve - y1(1:n1) : input real array : y values for first curve - n1 : length of arrays x1, y1 - x2(1:n2) : input real array : x values for first curve - y2(1:n2) : input real array : y values for first curve - n2 : length of arrays x2, y2 - xin : initial guess for intersection point - x value at point of intersection on exit + This routine estimates the x point (abscissa) at which two curves defined by tabulated (x,y) values intersect, using simple linear interpolation and the Newton-Raphson method. The routine will stop with an error message if no crossing point is found within the x ranges of the two curves. + + Parameters + ---------- + x1 : + x values for first curve + y1 : + y values for first curve + x2 : + x values for first curve + y2 : + y values for first curve + xin : + initial guess for intersection point + + Returns + ------- + : + x value at point of intersection on exit + """ x = xin n1 = len(x1) @@ -247,10 +258,23 @@ def intersect(x1, y1, x2, y2, xin): def bmax_from_awp(wp_width_radial, current, n_tf_coils, r_coil_major, r_coil_minor): """Returns a fitted function for bmax for stellarators - author: J Lion, IPP Greifswald - Returns a fitted function for bmax in dependece + Returns a fitted function for bmax in dependence of the winding pack. The stellarator type config is taken from the parent scope. + + Parameters + ---------- + wp_width_radial : + + current : + + n_tf_coils : + + r_coil_major : + + r_coil_minor : + + """ return ( diff --git a/process/stellarator/coils/forces.py b/process/stellarator/coils/forces.py index e8065afb18..4e840a4eec 100644 --- a/process/stellarator/coils/forces.py +++ b/process/stellarator/coils/forces.py @@ -8,7 +8,13 @@ def calculate_max_force_density(a_tf_wp_no_insulation): - """Calculate the maximum force density in the TF coil winding pack from scaling. [MN/m3]""" + """Calculate the maximum force density in the TF coil winding pack from scaling. [MN/m3] + + Parameters + ---------- + a_tf_wp_no_insulation : + + """ tfcoil_variables.max_force_density = ( stellarator_configuration.stella_config_max_force_density @@ -42,7 +48,13 @@ def calculate_maximum_stress(): def calculate_max_lateral_force_density(a_tf_wp_no_insulation): - """Calculate the maximum lateral force density in the TF coil winding pack from scaling. [MN/m3]""" + """Calculate the maximum lateral force density in the TF coil winding pack from scaling. [MN/m3] + + Parameters + ---------- + a_tf_wp_no_insulation : + + """ return ( stellarator_configuration.stella_config_max_lateral_force_density * stellarator_variables.f_st_i_total @@ -55,7 +67,13 @@ def calculate_max_lateral_force_density(a_tf_wp_no_insulation): def calculate_max_radial_force_density(a_tf_wp_no_insulation): - """Calculate the maximum radial force density in the TF coil winding pack from scaling. [MN/m3]""" + """Calculate the maximum radial force density in the TF coil winding pack from scaling. [MN/m3] + + Parameters + ---------- + a_tf_wp_no_insulation : + + """ return ( stellarator_configuration.stella_config_max_radial_force_density * stellarator_variables.f_st_i_total diff --git a/process/stellarator/coils/mass.py b/process/stellarator/coils/mass.py index 9bae1abe5a..355b2f6540 100644 --- a/process/stellarator/coils/mass.py +++ b/process/stellarator/coils/mass.py @@ -5,15 +5,23 @@ def calculate_coils_mass(a_tf_wp_with_insulation: float, a_tf_wp_no_insulation: float): - """ - Calculates the mass of stellarator coils by aggregating the masses of various coil components. + """Calculates the mass of stellarator coils by aggregating the masses of various coil components. + This function computes the masses of conductor constituents (casing, ground insulation, superconductor, copper), conduit masses (steel and insulation), and then calculates the total conductor and coil masses. - Args: - a_tf_wp_with_insulation (float): Area of the toroidal field coil winding pack with insulation. - a_tf_wp_no_insulation (float): Area of the toroidal field coil winding pack without insulation. - Returns: - None: The function performs calculations and updates external state. + + Parameters + ---------- + a_tf_wp_with_insulation : + Area of the toroidal field coil winding pack with insulation. + a_tf_wp_no_insulation: + Area of the toroidal field coil winding pack without insulation. + + Returns + ------- + : + The function performs calculations and updates external state. + """ # Masses of conductor constituents @@ -32,10 +40,10 @@ def calculate_coils_mass(a_tf_wp_with_insulation: float, a_tf_wp_no_insulation: def casing(): - """ - [kg] Mass of case + """[kg] Mass of case (no need for correction factors as is the case for tokamaks) This is only correct if the winding pack is 'thin' (len_tf_coil>>sqrt(tfcoil_variables.a_tf_coil_inboard_case)). + """ tfcoil_variables.m_tf_coil_case = ( tfcoil_variables.len_tf_coil @@ -46,7 +54,15 @@ def casing(): def ground_insulation(a_tf_wp_with_insulation, a_tf_wp_no_insulation): """Mass of ground-wall insulation [kg] - (assumed to be same density/material as conduit insulation)""" + (assumed to be same density/material as conduit insulation) + + Parameters + ---------- + a_tf_wp_with_insulation : + + a_tf_wp_no_insulation : + + """ tfcoil_variables.m_tf_coil_wp_insulation = ( tfcoil_variables.len_tf_coil * (a_tf_wp_with_insulation - a_tf_wp_no_insulation) @@ -56,7 +72,9 @@ def ground_insulation(a_tf_wp_with_insulation, a_tf_wp_no_insulation): def superconductor(): """[kg] mass of Superconductor - a_tf_wp_coolant_channels is 0 for a stellarator. but keep this term for now.""" + a_tf_wp_coolant_channels is 0 for a stellarator. but keep this term for now. + + """ tfcoil_variables.m_tf_coil_superconductor = ( tfcoil_variables.len_tf_coil * tfcoil_variables.n_tf_coil_turns @@ -92,7 +110,9 @@ def conduit_steel(): def conduit_insulation(): """Conduit insulation mass [kg] - (tfcoil_variables.a_tf_coil_wp_turn_insulation already contains tfcoil_variables.n_tf_coil_turns)""" + (tfcoil_variables.a_tf_coil_wp_turn_insulation already contains tfcoil_variables.n_tf_coil_turns) + + """ tfcoil_variables.m_tf_coil_wp_turn_insulation = ( tfcoil_variables.len_tf_coil * tfcoil_variables.a_tf_coil_wp_turn_insulation diff --git a/process/stellarator/coils/output.py b/process/stellarator/coils/output.py index c6514ca37d..0d2723631f 100644 --- a/process/stellarator/coils/output.py +++ b/process/stellarator/coils/output.py @@ -34,11 +34,63 @@ def write( quench_voltage, ): """Writes stellarator modular coil output to file - author: P J Knight, CCFE, Culham Science Centre - outfile : input integer : output file unit + This routine writes the stellarator modular coil results to the output file. - None + + Parameters + ---------- + stellarator : + + a_tf_wp_no_insulation : + + centering_force_avg_mn : + + centering_force_max_mn : + + centering_force_min_mn : + + coilcoilgap : + + coppera_m2 : + + coppera_m2_max : + + f_a_scu_of_wp : + + f_vv_actual : + + fiooic : + + inductance : + + max_force_density : + + max_force_density_mnm : + + max_lateral_force_density : + + max_radial_force_density : + + min_bending_radius : + + r_coil_major : + + r_coil_minor : + + sig_tf_wp : + + dx_tf_turn_general : + + t_tf_superconductor_quench : + + toroidalgap : + + allowed_quench_voltage : + + quench_voltage : + + """ po.oheadr(stellarator.outfile, "Modular Coils") diff --git a/process/stellarator/coils/quench.py b/process/stellarator/coils/quench.py index c487b98b5c..2108078a79 100644 --- a/process/stellarator/coils/quench.py +++ b/process/stellarator/coils/quench.py @@ -12,11 +12,15 @@ def calculate_quench_protection(coilcurrent): - """ - Calculate quench protecion limits for stellarator coils + """Calculate quench protecion limits for stellarator coils Includes calculation of the vacuum vessel force density, quench protection current density and max dump voltage during quench - coilcurrent : Total coils current (MA) + + Parameters + ---------- + coilcurrent : + Total coils current (MA) + """ # # This copied from the tokamak module: @@ -101,6 +105,15 @@ def calculate_quench_protection(coilcurrent): def calculate_vv_max_force_density_from_W7X_scaling(rad_vv: float) -> float: """Actual VV force density from scaling [MN/m^3] Based on reference values from W-7X. + + Parameters + ---------- + rad_vv: + + Returns + ------- + : + """ force_density_ref = 2.54 # MN/m^3 b_ref = 3.0 # T @@ -133,11 +146,17 @@ def calculate_vv_max_force_density_from_W7X_scaling(rad_vv: float) -> float: def max_dump_voltage(tf_energy_stored: float, t_dump: float, current: float) -> float: - """ - Max volatage during fast discharge of TF coil (V) - tf_energy_stored : Energy stored in one TF coil (J) - t_dump : Dump time (sec) - current : Operating current (A) + """Max volatage during fast discharge of TF coil (V) + + Parameters + ---------- + tf_energy_stored: + Energy stored in one TF coil (J) + t_dump: + Dump time (sec) + current : + Operating current (A) + """ return 2 * (tf_energy_stored / t_dump) / current @@ -145,20 +164,29 @@ def max_dump_voltage(tf_energy_stored: float, t_dump: float, current: float) -> def calculate_quench_protection_current_density( tau_quench, t_detect, f_cu, f_cond, temp, a_cable, a_turn ): - """ - Calculates the current density limited by the protection limit. + """Calculates the current density limited by the protection limit. Simplified 0-D adiabatic heat balance "hotspot criterion" model. This is slightly diffrent that tokamak version (also diffrent from the stellarator paper). We skip the superconduc6tor contribution (this should be more conservative in theory). - tau_quench : Quench time (s) - t_detect : Detection time (s) - f_cu : Copper fraction - f_cond : Conductor fraction - temp : peak helium coolant temperature in TF coils and PF coils (K) - a_cable : Cable space area (per turn) [m2] (Includes the area of voids and central helium channel) - a_turn : TF coil turn cross section area [m2] + + Parameters + ---------- + tau_quench : + Quench time (s) + t_detect : + Detection time (s) + f_cu : + Copper fraction + f_cond : + Conductor fraction + temp : + peak helium coolant temperature in TF coils and PF coils (K) + a_cable : + Cable space area (per turn) [m2] (Includes the area of voids and central helium channel) + a_turn : + TF coil turn cross section area [m2] """ temp_k = [4, 14, 24, 34, 44, 54, 64, 74, 84, 94, 104, 114, 124] q_cu_array_sa2m4 = [ diff --git a/process/stellarator/denisty_limits.py b/process/stellarator/denisty_limits.py index 5b42cef653..09dded2e6b 100644 --- a/process/stellarator/denisty_limits.py +++ b/process/stellarator/denisty_limits.py @@ -15,9 +15,16 @@ def st_denisty_limits(stellarator, f_output): """Routine to reiterate the physics loop - author: J Lion, IPP Greifswald - None + This routine reiterates some physics modules. + + Parameters + ---------- + stellarator : + + f_output : + + """ # Set the required value for icc=5 @@ -48,17 +55,28 @@ def st_denisty_limits(stellarator, f_output): def st_sudo_density_limit(b_plasma_toroidal_on_axis, powht, rmajor, rminor): """Routine to calculate the Sudo density limit in a stellarator - author: P J Knight, CCFE, Culham Science Centre - bt : input real : Toroidal field on axis (T) - bt = b_plasma_toroidal_on_axis - powht : input real : Absorbed heating power (MW) - rmajor : input real : Plasma major radius (m) - rminor : input real : Plasma minor radius (m) - dlimit : output real : Maximum volume-averaged plasma density (/m3) + This routine calculates the density limit for a stellarator. S.Sudo, Y.Takeiri, H.Zushi et al., Scalings of Energy Confinement and Density Limit in Stellarator/Heliotron Devices, Nuclear Fusion vol.30, 11 (1990). + + Parameters + ---------- + b_plasma_toroidal_on_axis : + Toroidal field on axis (T) + powht : + Absored heating power (MW) + rmajor : + Plama major radius (m) + rminor : + Plama minor radius (m) + + Returns + ------- + dlimit : + Maximum volume-averaged plasma density (/m3) + """ arg = powht * b_plasma_toroidal_on_axis / (rmajor * rminor * rminor) @@ -93,12 +111,23 @@ def st_sudo_density_limit(b_plasma_toroidal_on_axis, powht, rmajor, rminor): def st_d_limit_ecrh(gyro_frequency_max, bt_input): """Routine to calculate the density limit due to an ECRH heating scheme on axis depending on an assumed maximal available gyrotron frequency. - author: J Lion, IPP Greifswald - gyro_frequency_max : input real : Maximal available Gyrotron frequency (1/s) NOT (rad/s) - bt : input real : Maximal magnetic field on axis (T) - dlimit_ecrh : output real : Maximum peak plasma density by ECRH constraints (/m3) - bt_max : output real : Maximum allowable b field for ecrh heating (T) + This routine calculates the density limit due to an ECRH heating scheme on axis + + Parameters + ---------- + gyro_frequency_max : + Maximal available Gyrotron frequency (1/s) NOT (rad/s) + bt_input : + Maximal magnetic field on axis (T) + + Returns + ------- + dlimit_ecrh: + Maximum peak plasma density by ECRH constraints (/m3) + bt_max: + Maximum allowable b field for ecrh heating (T) + """ gyro_frequency = min(1.76e11 * bt_input, gyro_frequency_max * 2.0e0 * np.pi) @@ -123,14 +152,28 @@ def st_d_limit_ecrh(gyro_frequency_max, bt_input): def power_at_ignition_point(stellarator, gyro_frequency_max, te0_available): """Routine to calculate if the plasma is ignitable with the current values for the B field. Assumes current ECRH achievable peak temperature (which is inaccurate as the cordey pass should be calculated) - author: J Lion, IPP Greifswald - gyro_frequency_max : input real : Maximal available Gyrotron frequency (1/s) NOT (rad/s) - te0_available : input real : Reachable peak electron temperature, reached by ECRH (KEV) - powerht_out : output real: Heating Power at ignition point (MW) - pscalingmw_out : output real: Heating Power loss at ignition point (MW) + This routine calculates the density limit due to an ECRH heating scheme on axis Assumes current peak temperature (which is inaccurate as the cordey pass should be calculated) Maybe use this: https://doi.org/10.1088/0029-5515/49/8/085026 + + Parameters + ---------- + stellarator : + An object containing stellarator configuration and output handle + gyro_frequency_max : + Maximal available Gyrotron frequency (1/s) NOT (rad/s) + + te0_available : + Reachable peak electron temperature, reached by ECRH (KEV) + + Returns + ------- + powerht_out: + Heating Power at ignition point (MW) + pscalingmw_out: + Heating Power loss at ignition point (MW) + """ te_old = copy(physics_variables.temp_plasma_electron_vol_avg_kev) # Volume averaged physics_variables.te from te0_achievable diff --git a/process/stellarator/divertor.py b/process/stellarator/divertor.py index ae96576dfc..5674910fea 100644 --- a/process/stellarator/divertor.py +++ b/process/stellarator/divertor.py @@ -13,14 +13,18 @@ def st_div(stellarator, f_output: bool): """Routine to call the stellarator divertor model - author: P J Knight, CCFE, Culham Science Centre - author: F Warmer, IPP Greifswald - outfile : input integer : output file unit - iprint : input integer : switch for writing to output file (1=yes) - This routine calls the divertor model for a stellarator, - developed by Felix Warmer. - Stellarator Divertor Model for the Systems - Code PROCESS, F. Warmer, 21/06/2013 + + This routine calls the divertor model for a stellarator + + Parameters + ---------- + stellarator : + An object containing stellarator configuration and output handle + f_output: + + References + ---------- + Stellarator Divertor Model for the Systems Code PROCESS, F. Warmer, 21/06/2013 """ Theta = stellarator_variables.flpitch # ~bmn [rad] field line pitch r = physics_variables.rmajor @@ -102,22 +106,32 @@ def st_div(stellarator, f_output: bool): def output(stellarator, a_eff, l_d, l_w, f_x, l_q, w_r, Delta): - """ - Outputs a summary of divertor-related parameters and results to the stellartor object. - - Parameters: + """Outputs a summary of divertor-related parameters and results to the stellartor object. stellarator: An object containing stellarator configuration and output handle. - a_eff (float): Effective divertor wetted area (m²). - l_d (float): Divertor plate length (m). - l_w (float): Divertor plate width (m). - f_x (float): Flux channel broadening factor. - l_q (float): Power decay width (m). - w_r (float): Island width (m). - Delta (float): Perpendicular distance from X-point to plate (m). The function writes various physical and geometric parameters related to the divertor, including power, angles, heat transport coefficients, resonance numbers, field perturbations, and other relevant quantities, to the output file associated with the stellarator object. + + Parameters + ---------- + stellarator : + An object containing stellarator configuration and output handle + a_eff : + Effective divertor wetted area (m²). + l_d : + Divertor plate length (m). + l_w : + Divertor plate width (m). + f_x : + Flux channel broadening factor. + l_q : + Power decay width (m). + w_r : + Island width (m). + Delta : + Perpendicular distance from X-point to plate (m). + """ po.oheadr(stellarator.outfile, "Divertor") diff --git a/process/stellarator/heating.py b/process/stellarator/heating.py index 012015e340..eb58737774 100644 --- a/process/stellarator/heating.py +++ b/process/stellarator/heating.py @@ -15,12 +15,17 @@ def st_heat(stellarator, f_output: bool): """Routine to calculate the auxiliary heating power in a stellarator - author: P J Knight, CCFE, Culham Science Centre - outfile : input integer : output file unit - iprint : input integer : switch for writing to output file (1=yes) + This routine calculates the auxiliary heating power for a stellarator device. - AEA FUS 172: Physics Assessment for the European Reactor Study + + Parameters + ---------- + stellarator : + + f_output: + + """ f_p_beam_injected_ions = None if stellarator_variables.isthtr == 1: diff --git a/process/stellarator/initialization.py b/process/stellarator/initialization.py index e96967398d..78216aedba 100644 --- a/process/stellarator/initialization.py +++ b/process/stellarator/initialization.py @@ -11,11 +11,10 @@ def st_init(): """Routine to initialise the variables relevant to stellarators - author: P J Knight, CCFE, Culham Science Centre - author: F Warmer, IPP Greifswald This routine initialises the variables relevant to stellarators. Many of these may override the values set in routine + """ if stellarator_variables.istell == 0: return diff --git a/process/stellarator/neoclassics.py b/process/stellarator/neoclassics.py index 393266ab6b..9967701037 100644 --- a/process/stellarator/neoclassics.py +++ b/process/stellarator/neoclassics.py @@ -23,6 +23,15 @@ def no_roots(self): def init_neoclassics(self, r_effin, eps_effin, iotain): """Constructor of the neoclassics object from the effective radius, epsilon effective and iota only. + + Parameters + ---------- + r_effin : + + eps_effin : + + iotain : + """ ( neoclassics_variables.densities, @@ -128,7 +137,13 @@ def init_neoclassics(self, r_effin, eps_effin, iotain): neoclassics_variables.q_flux = self.neoclassics_calc_q_flux() def init_profile_values_from_PROCESS(self, rho): - """Initializes the profile_values object from PROCESS' parabolic profiles""" + """Initialises the profile_values object from PROCESS' parabolic profiles + + Parameters + ---------- + rho : + + """ tempe = ( physics_variables.temp_plasma_electron_on_axis_kev * (1 - rho**2) ** physics_variables.alphat @@ -512,7 +527,14 @@ def neoclassics_calc_nu_star(self): ) def neoclassics_calc_nu_star_fromT(self, iota): - """Calculates the collision frequency""" + """Calculates the collision frequency + + Parameters + ---------- + iota : + + + """ temp = ( np.array([ physics_variables.temp_plasma_electron_vol_avg_kev, @@ -676,6 +698,11 @@ def neoclassics_calc_D11_plateau(self): def neoclassics_calc_d11_mono(self, eps_eff): """Calculates the monoenergetic radial transport coefficients using epsilon effective + + Parameters + ---------- + eps_eff : + """ return ( 4.0 @@ -689,6 +716,11 @@ def calc_integrated_radial_transport_coeffs(self, index: int): """Calculates the integrated radial transport coefficients (index `index`) It uses Gauss laguerre integration https://en.wikipedia.org/wiki/Gauss%E2%80%93Laguerre_quadrature + + Parameters + ---------- + index: + """ return np.sum( 2.0 @@ -702,7 +734,19 @@ def calc_integrated_radial_transport_coeffs(self, index: int): def neoclassics_calc_gamma_flux( self, densities, temperatures, dr_densities, dr_temperatures ): - """Calculates the Energy flux by neoclassical particle transport""" + """Calculates the Energy flux by neoclassical particle transport + + Parameters + ---------- + densities : + + temperatures : + + dr_densities : + + dr_temperatures : + + """ z = np.array([-1.0, 1.0, 1.0, 2.0]) diff --git a/process/stellarator/preset_config.py b/process/stellarator/preset_config.py index 63677135ce..0d62a16045 100644 --- a/process/stellarator/preset_config.py +++ b/process/stellarator/preset_config.py @@ -211,14 +211,19 @@ def load_stellarator_config(istell: int, config_file: Path | None): """Load the appropriate Stellarator machine configuration - given the `istell` switch: - istell = 1: Helias5 machine - istell = 2: Helias4 machine - istell = 3: Helias3 machine - istell = 4: w7x30 machine - istell = 5: w7x50 machine - istell = 6: Init from json + Parameters + ---------- + istell: + istell = 1: Helias5 machine + istell = 2: Helias4 machine + istell = 3: Helias3 machine + istell = 4: w7x30 machine + istell = 5: w7x50 machine + istell = 6: Init from json + config_file: + + """ match istell: case 1: diff --git a/process/stellarator/stellarator.py b/process/stellarator/stellarator.py index ea2c0a539c..da36ef709c 100644 --- a/process/stellarator/stellarator.py +++ b/process/stellarator/stellarator.py @@ -1,5 +1,8 @@ +from __future__ import annotations + import logging from pathlib import Path +from typing import TYPE_CHECKING import numpy as np @@ -34,6 +37,16 @@ from process.stellarator.heating import st_heat from process.stellarator.preset_config import load_stellarator_config +if TYPE_CHECKING: + from process.availability import Availability + from process.buildings import Buildings + from process.costs import Costs + from process.current_drive import CurrentDrive + from process.hcpb import CCFE_HCPB + from process.plasma_profiles import PlasmaProfile + from process.stellarator.neoclassics import Neoclassics + from process.vacuum import Vacuum + logger = logging.getLogger(__name__) # NOTE: a different value of electron_charge was used in the original implementation @@ -44,50 +57,47 @@ class Stellarator: """Module containing stellarator routines - author: P J Knight, CCFE, Culham Science Centre - N/A + This module contains routines for calculating the parameters of the first wall, blanket and shield components of a fusion power plant. + Parameters + ---------- + availability: + A pointer to the availability model, allowing use of availability's variables/methods + buildings: + A pointer to the buildings model, allowing use of buildings's variables/methods + Vacuum: + A pointer to the vacuum model, allowing use of vacuum's variables/methods + costs: + A pointer to the costs model, allowing use of costs' variables/methods + plasma_profile: + A pointer to the plasma_profile model, allowing use of plasma_profile's variables/methods + hcpb: + A pointer to the ccfe_hcpb model, allowing use of ccfe_hcpb's variables/methods + current_drive: + A pointer to the CurrentDrive model, allowing use of CurrentDrives's variables/methods + physics: + A pointer to the Physics model, allowing use of Physics's variables/methods + neoclassics: + A pointer to the Neoclassics model, allowing use of neoclassics's variables/methods """ def __init__( self, - availability, - vacuum, - buildings, - costs, + availability: Availability, + vacuum: Vacuum, + buildings: Buildings, + costs: Costs, power, - plasma_profile, - hcpb, - current_drive, + plasma_profile: PlasmaProfile, + hcpb: CCFE_HCPB, + current_drive: CurrentDrive, physics: Physics, - neoclassics, + neoclassics: Neoclassics, plasma_beta, ) -> None: - """Initialises the Stellarator model's variables - - :param availability: a pointer to the availability model, allowing use of availability's variables/methods - :type availability: process.availability.Availability - :param buildings: a pointer to the buildings model, allowing use of buildings's variables/methods - :type buildings: process.buildings.Buildings - :param Vacuum: a pointer to the vacuum model, allowing use of vacuum's variables/methods - :type Vacuum: process.vacuum.Vacuum - :param costs: a pointer to the costs model, allowing use of costs' variables/methods - :type costs: process.costs.Costs - :param plasma_profile: a pointer to the plasma_profile model, allowing use of plasma_profile's variables/methods - :type plasma_profile: process.plasma_profile.PlasmaProfile - :param hcpb: a pointer to the ccfe_hcpb model, allowing use of ccfe_hcpb's variables/methods - :type hcpb: process.hcpb.CCFE_HCPB - :param current_drive: a pointer to the CurrentDrive model, allowing use of CurrentDrives's variables/methods - :type current_drive: process.current_drive.CurrentDrive - :param physics: a pointer to the Physics model, allowing use of Physics's variables/methods - :type physics: process.physics.Physics - :param neoclassics: a pointer to the Neoclassics model, allowing use of neoclassics's variables/methods - :type neoclassics: process.stellarator.Neoclassics - """ - self.outfile: int = constants.NOUT self.first_call_stfwbs = True @@ -106,13 +116,13 @@ def __init__( def run(self, output: bool): """Routine to call the physics and engineering modules relevant to stellarators - author: P J Knight, CCFE, Culham Science Centre - author: F Warmer, IPP Greifswald This routine is the caller for the stellarator models. - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not """ if output: @@ -182,7 +192,7 @@ def run(self, output: bool): stellarator_variables.first_call = False def st_new_config(self): - """author: J Lion, IPP Greifswald + """ Routine to initialise the stellarator configuration Routine to initialise the stellarator configuration. @@ -197,6 +207,7 @@ def st_new_config(self): (stellarator_configuration.stella_config_rmajor_ref / stellarator_configuration.stella_config_coil_rminor) ) + """ load_stellarator_config( @@ -259,7 +270,6 @@ def st_new_config(self): def st_geom(self): """ - author: J Lion, IPP Greifswald Routine to calculate the plasma volume and surface area for a stellarator using precalculated effective values @@ -268,10 +278,13 @@ def st_geom(self): It is simple scaling based on a Fourier representation based on that described in Geiger documentation. + References + ---------- J. Geiger, IPP Greifswald internal document: 'Darstellung von ineinandergeschachtelten toroidal geschlossenen Flaechen mit Fourierkoeffizienten' ('Representation of nested, closed surfaces with Fourier coefficients') + """ physics_variables.vol_plasma = ( stellarator_variables.f_st_rmajor @@ -299,16 +312,18 @@ def st_geom(self): ) # Used only in the divertor model; approximate as for tokamaks def st_strc(self, output): - """ - Routine to calculate the structural masses for a stellarator - author: P J Knight, CCFE, Culham Science Centre - outfile : input integer : output file unit - iprint : input integer : switch for writing to output file (1=yes) + """Routine to calculate the structural masses for a stellarator + This routine calculates the structural masses for a stellarator. This is the stellarator version of routine STRUCT. In practice, many of the masses are simply set to zero to avoid double-counting of structural components that are specified differently for tokamaks. + + Parameters + ---------- + output : + """ structure_variables.fncmass = 0.0e0 @@ -458,10 +473,8 @@ def blanket_neutronics(self): def st_fwbs(self, output: bool): """Routine to calculate first wall, blanket and shield properties for a stellarator - author: P J Knight, CCFE, Culham Science Centre - author: F Warmer, IPP Greifswald - outfile : input integer : Fortran output unit identifier - iprint : input integer : Switch to write output to file (1=yes) + + This routine calculates a stellarator's first wall, blanket and shield properties. It calculates the nuclear heating in the blanket / shield, and @@ -478,6 +491,12 @@ def st_fwbs(self, output: bool): fwbs), except for the volume calculations, which scale the surface area of the components from that of the plasma. + + Parameters + ---------- + output: + + """ fwbs_variables.life_fw_fpy = min( cost_variables.abktflnc / physics_variables.pflux_fw_neutron_mw, @@ -1696,17 +1715,7 @@ def st_fwbs(self, output: bool): def sc_tf_coil_nuclear_heating_iter90(self): """Superconducting TF coil nuclear heating estimate - author: P J Knight, CCFE, Culham Science Centre - coilhtmx : output real : peak magnet heating (MW/m3) - dpacop : output real : copper stabiliser displacements/atom - htheci : output real : peak TF coil case heating (MW/m3) - nflutf : output real : maximum neutron fluence (n/m2) - pheci : output real : inboard coil case heating (MW) - pheco : output real : outboard coil case heating (MW) - ptfiwp : output real : inboard TF coil winding pack heating (MW) - ptfowp : output real : outboard TF coil winding pack heating (MW) - raddose : output real : insulator dose (rad) - p_tf_nuclear_heat_mw : output real : TF coil nuclear heating (MW) + This subroutine calculates the nuclear heating in the superconducting TF coils, assuming an exponential neutron attenuation through the blanket and shield materials. @@ -1718,6 +1727,29 @@ def sc_tf_coil_nuclear_heating_iter90(self):

  • j = 2 : tungsten shield (not used) Note: Costing and mass calculations elsewhere assume stainless steel only. + + Returns + ------- + coilhtmx : + peak magnet heating (MW/m3) + dpacop : + copper stabiliser displacements/atom + htheci : + peak TF coil case heating (MW/m3) + nflutf : + maximum neutron fluence (n/m2) + pheci : + inboard coil case heating (MW) + pheco : + outboard coil case heating (MW) + ptfiwp : + inboard TF coil winding pack heating (MW) + ptfowp : + outboard TF coil winding pack heating (MW) + raddose : + insulator dose (rad) + p_tf_nuclear_heat_mw : + TF coil nuclear heating (MW) """ ishmat = 0 # stainless steel coil casing is assumed @@ -1885,12 +1917,18 @@ def sc_tf_coil_nuclear_heating_iter90(self): def st_phys(self, output): """Routine to calculate stellarator plasma physics information - author: P J Knight, CCFE, Culham Science Centre - author: F Warmer, IPP Greifswald - None + This routine calculates the physics quantities relevant to a stellarator device. + + Parameters + ---------- + output : + + References + ---------- AEA FUS 172: Physics Assessment for the European Reactor Study + """ # ############################################### # Calculate plasma composition diff --git a/process/structure.py b/process/structure.py index a4ae1154fb..806f1da57b 100644 --- a/process/structure.py +++ b/process/structure.py @@ -18,24 +18,24 @@ class Structure: """Class containing support structure calculations - author: P J Knight, CCFE, Culham Science Centre This class contains routines for calculating the parameters of the support structure for a fusion power plant. """ - def __init__(self) -> None: + def __init__(self): self.outfile = constants.NOUT # output file unit - def run(self, output: bool = False) -> None: + def run(self, output: bool = False): """Structure calculation caller - author: P J Knight, CCFE, Culham Science Centre This subroutine calls the support structure mass calculations. - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not """ # Total weight of the PF coil conductor and its structure @@ -90,66 +90,53 @@ def structure( output, ): """Method to calculate mass of support structure - author: P J Knight, CCFE, Culham Science Centre - author: J Galambos, ORNL - Reprogrammed by J. Galambos to match the ITER (i.e. B. Spears) rules. - :param ai: plasma current (max design value) (A) - :type ai: float - - :param r0: plasma major radius (m) - :type r0: float - - :param a: plasma minor radius (m) - :type a: float - - :param akappa: plasma elongation - :type akappa: float - - :param b0: axial B-field (T) - :type b0: float - - :param itfsup: switch denoting whether TF coils are superconducting - :type itfsup: integer - - :param i_pf_conductor: switch denoting whether PF & CS coils are resistive - :type i_pf_conductor: integer - - :param tf_h_width: TF coil horizontal dr_bore (m) - :type tf_h_width: float - - :param tfhmax: TF coil max height (m) - :type tfhmax: float - - :param shldmass: total mass of shield (kg) - :type shldmass: float - - :param dvrtmass: total mass of divertor and assoc. structure (kg) - :type dvrtmass: float - - :param pfmass: total mass of PF coils plus cases (kg) - :type pfmass: float - - :param tfmass: total mass of TF coils plus cases (kg) - :type tfmass: float - - :param blmass: blanket mass (kg) - :type blmass: float - - :param m_fw_total: first wall mass (kg) - :type m_fw_total: float - - :param m_fw_blkt_div_coolant_total: total water coolant mass (kg) - :type m_fw_blkt_div_coolant_total: float - - :param dewmass: vacuum vessel + cryostat mass (kg) - :type dewmass: float - - :param output: indicate whether output should be written to the output file, or not - :type output: boolean - - :returns: - - fncmass (`float`) mass of outer pf coil support fence (kg) + Programmed to match the ITER (i.e. B. Spears) rules. + + Parameters + ---------- + ai : float + plasma current (max design value) (A) + r0 : float + plasma major radius (m) + a : float + plasma minor radius (m) + akappa : float + plasma elongation + b0 : float + axial B-field (T) + i_tf_sup : + switch denoting whether TF coils are superconducting + i_pf_conductor : integer + switch denoting whether PF & CS coils are resistive + tf_h_width : float + TF coil horizontal dr_bore (m) + tfhmax : float + TF coil max height (m) + shldmass : float + total mass of shield (kg) + dvrtmass : float + total mass of divertor and assoc. structure (kg) + pfmass : float + total mass of PF coils plus cases (kg) + tfmass : float + total mass of TF coils plus cases (kg) + blmass : float + blanket mass (kg) + m_fw_total : float + first wall mass (kg) + m_fw_blkt_div_coolant_total : float + total water coolant mass (kg) + dewmass : float + vacuum vessel + cryostat mass (kg) + output : + indicate whether output should be written to the output file, or not + + + Returns + ------- + type + fncmass (`float`) mass of outer pf coil support fence (kg) - aintmass (`float`) mass of intercoil support (kg) - clgsmass (`float`) coil gravity support mass (kg) - coldmass (`float`) total mass of cryogenic temp. stuff (kg) diff --git a/process/superconducting_tf_coil.py b/process/superconducting_tf_coil.py index 76a7a5bafa..977d0cb7cc 100644 --- a/process/superconducting_tf_coil.py +++ b/process/superconducting_tf_coil.py @@ -43,8 +43,12 @@ def __init__(self): self.outfile = constants.NOUT def run(self, output: bool): - """ - Routine to call the superconductor module for the TF coils + """Routine to call the superconductor module for the TF coils + + Parameters + ---------- + output: bool + """ self.iprint = 0 @@ -432,14 +436,19 @@ def supercon_croco( self, a_tf_turn, b_tf_inboard_peak_symmetric, iop, thelium, output: bool ): """TF superconducting CroCo conductor using REBCO tape - author: M Kovari, CCFE, Culham Science Centre - b_tf_inboard_peak_symmetric : input real : Peak field at conductor (T) - iop : input real : Operating current per turn (A) - thelium : input real : He temperature at peak field point (K) - iprint : input integer : Switch for printing (1 = yes, 0 = no) - outfile : input integer : Fortran output unit identifier - j_tf_wp_critical : output real : Critical winding pack current density (A/m2) - tmarg : output real : Temperature margin (K) + + Parameters + ---------- + a_tf_turn : + + b_tf_inboard_peak_symmetric : + Peak field at conductor (T) + iop : + Operating current per turn (A) + thelium : + He temperature at peak field point (K) + output: + """ j_crit_sc: float = 0.0 @@ -900,26 +909,27 @@ def tf_cable_in_conduit_superconductor_properties( bcritsc: float, tcritsc: float, ) -> tuple[float, float, float, float, float, float, float, float]: - """ - Calculates the properties of the TF superconducting conductor. + """Calculates the properties of the TF superconducting conductor. - :param float a_tf_turn_cable_space: + Parameters + ---------- + a_tf_turn_cable_space: Cable space - inside area (m²). - :param float a_tf_turn: + a_tf_turn: Area per turn (i.e. entire jacketed conductor) (m²). - :param float a_tf_turn_cable_space_effective: + a_tf_turn_cable_space_effective: Effective cable space area per turn (m²). - :param float f_a_tf_turn_cable_space_cooling: + f_a_tf_turn_cable_space_cooling: Fraction of cable space used for cooling. - :param float b_tf_inboard_peak: + b_tf_inboard_peak: Peak field at conductor (T). - :param float f_a_tf_turn_cable_copper: + f_a_tf_turn_cable_copper: Fraction of conductor that is copper. - :param float c_tf_turn: + c_tf_turn: Operating current per turn (A). - :param float j_tf_wp: + j_tf_wp: Actual winding pack current density (A/m²). - :param int i_tf_superconductor: + i_tf_superconductor: Switch for conductor type: - 1: ITER Nb3Sn, standard parameters - 2: Bi-2212 High Temperature Superconductor @@ -929,16 +939,19 @@ def tf_cable_in_conduit_superconductor_properties( - 7: Durham Ginzburg-Landau Nb-Ti parameterisation - 8: Durham Ginzburg-Landau critical surface model for REBCO - 9: Hazelton experimental data + Zhai conceptual model for REBCO - :param float f_strain_scale: + f_strain_scale: Adjustment factor (<= 1) to account for strain, radiation damage, fatigue or AC losses. - :param float temp_tf_coolant_peak_field: + temp_tf_coolant_peak_field: He temperature at peak field point (K). - :param float bcritsc: + bcritsc: Critical field at zero temperature and strain (T) (used only if i_tf_superconductor=4). - :param float tcritsc: + tcritsc: Critical temperature at zero field and strain (K) (used only if i_tf_superconductor=4). - :returns: tuple (float, float, float, float, float, float, float, float, float) + Returns + ------- + type + tuple (float, float, float, float, float, float, float, float, float) - j_tf_wp_critical (float): Critical winding pack current density (A/m²). - j_superconductor_critical (float): Critical current density in superconductor (A/m²). - f_c_tf_turn_operating_critical (float): Ratio of operating / critical current. @@ -948,17 +961,18 @@ def tf_cable_in_conduit_superconductor_properties( - temp_tf_superconductor_critical_zero_field_strain (float): Critical temperature at zero field and strain (K). - c_tf_turn_cables_critical (float): Critical current in cable (A). - :notes: - This routine calculates the superconductor properties for the TF coils. - It was originally programmed by J. Galambos (1991), from algorithms provided by J. Miller. - The routine calculates the critical current density (winding pack) and also the protection - information (for a quench). Not used for the CroCo conductor. - - The critical current density for a superconductor (``j_superconductor_critical``) is for the superconducting - strands/tape, not including copper. The critical current density for a cable (``j_crit_cable``) - accounts for both the fraction of the cable taken up by helium coolant channels, and the cable - conductor copper fraction (i.e., the copper in the superconducting strands and any additional - copper, such as REBCO tape support). + Notes + ----- + This routine calculates the superconductor properties for the TF coils. + It was originally programmed by J. Galambos (1991), from algorithms provided by J. Miller. + The routine calculates the critical current density (winding pack) and also the protection + information (for a quench). Not used for the CroCo conductor. + + The critical current density for a superconductor (``j_superconductor_critical``) is for the superconducting + strands/tape, not including copper. The critical current density for a cable (``j_crit_cable``) + accounts for both the fraction of the cable taken up by helium coolant channels, and the cable + conductor copper fraction (i.e., the copper in the superconducting strands and any additional + copper, such as REBCO tape support). """ # Guard against negative conductor fraction f_a_tf_turn_cable_space_conductor @@ -1316,17 +1330,20 @@ def calculate_cable_in_conduit_strand_count( a_cable_space: float, dia_superconductor_strand: float, ) -> int: - """ - Calculates the maximum number of superconducting strands that can fit into a cable-in-conduit conductor, + """Calculates the maximum number of superconducting strands that can fit into a cable-in-conduit conductor, based on the available cable space, strand diameter, and desired void fraction. - :param a_cable_space: Total cross-sectional area available for the cable (in m²). - :type a_cable_space: float - :param dia_superconductor_strand: Diameter of a single superconducting strand (in meters). - :type dia_superconductor_strand: float - - :returns: The maximum number of strands that can fit in the available space, accounting for the void fraction. - :rtype: int + Parameters + ---------- + a_cable_space : float + Total cross-sectional area available for the cable (in m²). + dia_superconductor_strand : float + Diameter of a single superconducting strand (in meters). + + Returns + ------- + int + The maximum number of strands that can fit in the available space, accounting for the void fraction. """ # Effective area available for strands (excluding voids) @@ -1345,18 +1362,25 @@ def calculate_cable_in_conduit_superconductor_length( len_tf_coil: float, n_tf_turn_superconducting_cables: int, ) -> float: - """ - Calculates the total length of superconducting material required for the TF coils. - - :param int n_tf_coils: Number of TF coils. - :param int n_tf_coil_turns: Total number of turns in the TF coil winding pack. - :param float len_tf_coil: Length of a single TF coil (in meters). - :param int n_tf_turn_superconducting_cables: Number of superconducting cables per turn in the TF coil. - - :returns: Tuple containing: + """Calculates the total length of superconducting material required for the TF coils. + + Parameters + ---------- + n_tf_coils: int : + n_tf_coils: Number of TF coils. + n_tf_coil_turns: int : + n_tf_coil_turns: Total number of turns in the TF coil winding pack. + len_tf_coil: + len_tf_coil: Length of a single TF coil (in meters). + n_tf_turn_superconducting_cables: int : + n_tf_turn_superconducting_cables: Number of superconducting cables per turn in the TF coil. + + Returns + ------- + tuple[float, float] + Tuple containing: - Length of superconductor in one TF coil (in meters). - Total length of superconductor in all TF coils (in meters). - :rtype: tuple[float, float] """ # Length of superconductor in one TF coil @@ -1553,10 +1577,11 @@ def calculate_superconductor_temperature_margin( c0: float, temp_tf_coolant_peak_field: float, ): - """ - Calculate the temperature margin of the TF superconductor. + """Calculate the temperature margin of the TF superconductor. - :param int i_tf_superconductor: + Parameters + ---------- + i_tf_superconductor: Switch for conductor type: - 1: ITER Nb3Sn, standard parameters - 2: Bi-2212 High Temperature Superconductor @@ -1566,22 +1591,25 @@ def calculate_superconductor_temperature_margin( - 7: Durham Ginzburg-Landau Nb-Ti parameterisation - 8: Durham Ginzburg-Landau critical surface model for REBCO - 9: Hazelton experimental data + Zhai conceptual model for REBCO - :param float j_superconductor: + j_superconductor: Current density in superconductor (A/m²). - :param float b_tf_inboard_peak: + b_tf_inboard_peak: Peak field at conductor (T). - :param float strain: + strain: Strain on superconductor. - :param float bc20m: + bc20m: Critical field at zero temperature and strain (T). - :param float tc0m: + tc0m: Critical temperature at zero field and strain (K). - :param float c0: + c0: Constant used in NbTi critical current density calculation (A/m²). - :param float temp_tf_coolant_peak_field: + temp_tf_coolant_peak_field: He temperature at peak field point (K). - :return: temp_tf_superconductor_margin. + Returns + ------- + type + temp_tf_superconductor_margin. """ # ================================================================= @@ -1666,43 +1694,46 @@ def quench_heat_protection_current_density( t_tf_quench_detection: float, nflutfmax: float, ) -> tuple[float, float]: - """ - Calculates the maximum conductor current density limited by the protection limit, + """Calculates the maximum conductor current density limited by the protection limit, and the discharge voltage for a TF coil. - :param c_tf_turn: Operating current (A) - :type c_tf_turn: float - :param e_tf_coil_magnetic_stored: Energy stored in one TF coil (J) - :type e_tf_coil_magnetic_stored: float - :param a_tf_turn_cable_space: Cable space - inside area (m²) - :type a_tf_turn_cable_space: float - :param a_tf_turn: Area per turn (i.e. entire cable) (m²) - :type a_tf_turn: float - :param t_tf_quench_dump: Dump time (s) - :type t_tf_quench_dump: float - :param f_a_tf_turn_cable_space_conductor: Fraction of cable space containing conductor - :type f_a_tf_turn_cable_space_conductor: float - :param f_a_tf_turn_cable_copper: Fraction of conductor that is copper - :type f_a_tf_turn_cable_copper: float - :param temp_tf_coolant_peak_field: Helium temperature at peak field point (K) - :type temp_tf_coolant_peak_field: float - :param temp_tf_conductor_quench_max: Maximum conductor temperature during quench (K) - :type temp_tf_conductor_quench_max: float - :param b_tf_inboard_peak: Peak magnetic field at conductor (T) - :type b_tf_inboard_peak: float - :param cu_rrr: Copper residual-resistance-ratio - :type cu_rrr: float - :param t_tf_quench_detection: Quench detection time (s) - :type t_tf_quench_detection: float - :param nflutfmax: End-of-life neutron fluence in the copper (1/m²) - :type nflutfmax: float - - :returns: - - j_tf_wp_quench_protection_max (float): Winding pack current density from temperature rise protection (A/m²) + Parameters + ---------- + c_tf_turn : float + Operating current (A) + e_tf_coil_magnetic_stored : float + Energy stored in one TF coil (J) + a_tf_turn_cable_space : float + Cable space - inside area (m²) + a_tf_turn : float + Area per turn (i.e. entire cable) (m²) + t_tf_quench_dump : float + Dump time (s) + f_a_tf_turn_cable_space_conductor : float + Fraction of cable space containing conductor + f_a_tf_turn_cable_copper : float + Fraction of conductor that is copper + temp_tf_coolant_peak_field : float + Helium temperature at peak field point (K) + temp_tf_conductor_quench_max : float + Maximum conductor temperature during quench (K) + b_tf_inboard_peak : float + Peak magnetic field at conductor (T) + cu_rrr : float + Copper residual-resistance-ratio + t_tf_quench_detection : float + Quench detection time (s) + nflutfmax : float + End-of-life neutron fluence in the copper (1/m²) + + Returns + ------- + tuple[float, float] + j_tf_wp_quench_protection_max (float): Winding pack current density from temperature rise protection (A/m²) - v_tf_dump_voltage_peak (float): Discharge voltage imposed on a TF coil (V) - :rtype: tuple[float, float] - :references: + References + ---------- - L. Bottura, “Magnet Quench 101,” arXiv (Cornell University), Jan. 2014, doi: https://doi.org/10.48550/arxiv.1401.3927. """ @@ -1735,8 +1766,6 @@ def vv_stress_on_quench(self): """Calculate the Tresca stress [Pa] of the Vacuum Vessel (VV) experienced when the TF coil quenches. - Author: Timothy Nunn, UKAEA - Assumes the current center line (CCL) of the TF coil is the middle of the coil. @@ -1816,31 +1845,35 @@ def peak_b_tf_inboard_with_ripple( r_tf_wp_inboard_centre: float, b_tf_inboard_peak_symmetric: float, ) -> tuple[float, int]: - """ - Calculates the peak toroidal field at the outboard edge of the inboard TF coil winding pack, + """Calculates the peak toroidal field at the outboard edge of the inboard TF coil winding pack, including the effects of ripple. For 16, 18, or 20 coils, uses fitting formulae derived by M. Kovari using MAGINT calculations on coil sets based on a DEMO1 case. For other numbers of coils, uses a 9% increase due to ripple from the axisymmetric calculation. - :param n_tf_coils: Number of TF coils. - :type n_tf_coils: float - :param dx_tf_wp_primary_toroidal: Width of plasma-facing face of winding pack (m). - :type dx_tf_wp_primary_toroidal: float - :param dr_tf_wp_no_insulation: Radial thickness of winding pack with no insulation (e.g. conductor region) (m). - :type dr_tf_wp_no_insulation: float - :param r_tf_wp_inboard_centre: Major radius of centre of winding pack (m). - :type r_tf_wp_inboard_centre: float - :param b_tf_inboard_peak_symmetric: Nominal (axisymmetric) peak toroidal field (T). - :type b_tf_inboard_peak_symmetric: float - - :returns: Tuple containing: + Parameters + ---------- + n_tf_coils : float + Number of TF coils. + dx_tf_wp_primary_toroidal : float + Width of plasma-facing face of winding pack (m). + dr_tf_wp_no_insulation : float + Radial thickness of winding pack with no insulation (e.g. conductor region) (m). + r_tf_wp_inboard_centre : float + Major radius of centre of winding pack (m). + b_tf_inboard_peak_symmetric : float + Nominal (axisymmetric) peak toroidal field (T). + + Returns + ------- + tuple[float] + Tuple containing: - b_tf_inboard_peak_with_ripple (float): Peak toroidal field including ripple (T). - :rtype: tuple[float] - :notes: - - M. Kovari, Toroidal Field Coils - Maximum Field and Ripple - Parametric Calculation, July 2014. + Notes + ----- + - M. Kovari, Toroidal Field Coils - Maximum Field and Ripple - Parametric Calculation, July 2014. """ a = np.zeros((4,)) @@ -1917,8 +1950,16 @@ def peak_b_tf_inboard_with_ripple( def sc_tf_internal_geom(self, i_tf_wp_geom, i_tf_case_geom, i_tf_turns_integer): """ - Author : S. Kahn, CCFE Seting the WP, case and turns geometry for SC magnets + + Parameters + ---------- + i_tf_wp_geom : + + i_tf_case_geom : + + i_tf_turns_integer : + """ # Calculating the WP / ground insulation areas @@ -2158,30 +2199,32 @@ def superconducting_tf_wp_geometry( float, # a_tf_wp_no_insulation float, # a_tf_wp_ground_insulation ]: - """ - Calculates the winding pack (WP) geometry and cross-sectional areas for superconducting toroidal field (TF) coils. + """Calculates the winding pack (WP) geometry and cross-sectional areas for superconducting toroidal field (TF) coils. - :param i_tf_wp_geom: - - 0: Rectangular + Parameters + ---------- + i_tf_wp_geom : int + 0: Rectangular - 1: Double rectangular - 2: Trapezoidal - :type i_tf_wp_geom: int - :param r_tf_inboard_in: Inboard inner radius [m]. - :type r_tf_inboard_in: float - :param dr_tf_nose_case: Radial thickness of nose case [m]. - :type dr_tf_nose_case: float - :param dr_tf_wp_with_insulation: Radial thickness of winding pack including insulation [m]. - :type dr_tf_wp_with_insulation: float - :param tan_theta_coil: Tangent of coil half angle [-]. - :type tan_theta_coil: float - :param dx_tf_side_case_min: Side case thickness [m]. - :type dx_tf_side_case_min: float - :param dx_tf_wp_insulation: Insulation thickness [m]. - :type dx_tf_wp_insulation: float - :param dx_tf_wp_insertion_gap: Insertion gap thickness [m]. - :type dx_tf_wp_insertion_gap: float - - :returns: + r_tf_inboard_in : float + Inboard inner radius [m]. + dr_tf_nose_case : float + Radial thickness of nose case [m]. + dr_tf_wp_with_insulation : float + Radial thickness of winding pack including insulation [m]. + tan_theta_coil : float + Tangent of coil half angle [-]. + dx_tf_side_case_min : float + Side case thickness [m]. + dx_tf_wp_insulation : float + Insulation thickness [m]. + dx_tf_wp_insertion_gap : float + Insertion gap thickness [m]. + + Returns + ------- + tuple[float, float, float, float, float, float, float, float, float, float] Tuple containing: - r_tf_wp_inboard_inner (float): WP inboard inner radius [m] - r_tf_wp_inboard_outer (float): WP inboard outer radius [m] @@ -2194,9 +2237,11 @@ def superconducting_tf_wp_geometry( - a_tf_wp_with_insulation (float): WP cross-sectional area with insulation [m²] - a_tf_wp_no_insulation (float): WP cross-sectional area without insulation [m²] - a_tf_wp_ground_insulation (float): WP ground insulation cross-sectional area [m²] - :rtype: tuple[float, float, float, float, float, float, float, float, float, float] - :raises ValueError: If calculated winding pack area (with or without insulation) is non-positive. + Raises + ------ + ValueError + If calculated winding pack area (with or without insulation) is non-positive. """ r_tf_wp_inboard_inner = r_tf_inboard_in + dr_tf_nose_case @@ -2396,50 +2441,51 @@ def superconducting_tf_case_geometry( dx_tf_side_case_min: float, dr_tf_wp_with_insulation: float, ) -> tuple[float, float, float, float, float, float]: - """ - Setting the case geometry and area for SC magnets - - :param i_tf_wp_geom: Index specifying winding pack geometry (0: rectangular, 1: double rectangular, else: trapezoidal). - :type i_tf_wp_geom: int - :param i_tf_case_geom: Index specifying case geometry (0: circular, else: straight). - :type i_tf_case_geom: int - :param a_tf_inboard_total: Total inboard area for TF coils [m²]. - :type a_tf_inboard_total: float - :param n_tf_coils: Number of TF coils. - :type n_tf_coils: float - :param a_tf_wp_with_insulation: Area of winding pack with insulation [m²]. - :type a_tf_wp_with_insulation: float - :param a_tf_leg_outboard: Outboard leg cross-sectional area [m²]. - :type a_tf_leg_outboard: float - :param rad_tf_coil_inboard_toroidal_half: Half toroidal radius of inboard coil [m]. - :type rad_tf_coil_inboard_toroidal_half: float - :param r_tf_inboard_out: Outer radius of inboard TF coil [m]. - :type r_tf_inboard_out: float - :param tan_theta_coil: Tangent of coil angle theta. - :type tan_theta_coil: float - :param r_tf_wp_inboard_outer: Outer radius of inboard winding pack [m]. - :type r_tf_wp_inboard_outer: float - :param dr_tf_plasma_case: Radial thickness of plasma case [m]. - :type dr_tf_plasma_case: float - :param r_tf_wp_inboard_inner: Inner radius of inboard winding pack [m]. - :type r_tf_wp_inboard_inner: float - :param r_tf_inboard_in: Inner radius of inboard TF coil [m]. - :type r_tf_inboard_in: float - :param dx_tf_side_case_min: Minimum lateral casing thickness [m]. - :type dx_tf_side_case_min: float - :param dr_tf_wp_with_insulation: Radial thickness of winding pack with insulation [m]. - :type dr_tf_wp_with_insulation: float - - :returns: Tuple containing: + """Setting the case geometry and area for SC magnets + + Parameters + ---------- + i_tf_wp_geom : int + Index specifying winding pack geometry (0: rectangular, 1: double rectangular, else: trapezoidal). + i_tf_case_geom : int + Index specifying case geometry (0: circular, else: straight). + a_tf_inboard_total : float + Total inboard area for TF coils [m²]. + n_tf_coils : float + Number of TF coils. + a_tf_wp_with_insulation : float + Area of winding pack with insulation [m²]. + a_tf_leg_outboard : float + Outboard leg cross-sectional area [m²]. + rad_tf_coil_inboard_toroidal_half : float + Half toroidal radius of inboard coil [m]. + r_tf_inboard_out : float + Outer radius of inboard TF coil [m]. + tan_theta_coil : float + Tangent of coil angle theta. + r_tf_wp_inboard_outer : float + Outer radius of inboard winding pack [m]. + dr_tf_plasma_case : float + Radial thickness of plasma case [m]. + r_tf_wp_inboard_inner : float + Inner radius of inboard winding pack [m]. + r_tf_inboard_in : float + Inner radius of inboard TF coil [m]. + dx_tf_side_case_min : float + Minimum lateral casing thickness [m]. + dr_tf_wp_with_insulation : float + Radial thickness of winding pack with insulation [m]. + + Returns + ------- + tuple[float, float, float, float, float] + Tuple containing: - a_tf_coil_inboard_case (float): Inboard case area [m²]. - a_tf_coil_outboard_case (float): Outboard case area [m²]. - a_tf_plasma_case (float): Front casing area [m²]. - a_tf_coil_nose_case (float): Nose casing area [m²]. - dx_tf_side_case_average (float): Average lateral casing thickness [m]. - dx_tf_side_case_peak (float): Peak lateral casing thickness [m]. - :rtype: tuple[float, float, float, float, float] - - :raises: Reports error if calculated casing areas are negative. """ # Total area of inboard TF coil case [m²] @@ -2548,32 +2594,36 @@ def tf_cable_in_conduit_integer_turn_geometry( float, # dx_tf_turn_cable_space float, # dx_tf_turn_cable_space_average ]: - """ - Set the TF WP turn geometry for superconducting magnets using the number of turn rows in the radial direction. + """Set the TF WP turn geometry for superconducting magnets using the number of turn rows in the radial direction. The turns can have any rectangular shape. This calculation checks if a turn can exist (positive cable space) and provides its dimensions, areas, and associated current. - :param dr_tf_wp_with_insulation: Radial thickness of winding pack with insulation [m]. - :type dr_tf_wp_with_insulation: float - :param dx_tf_wp_insulation: Thickness of winding pack insulation [m]. - :type dx_tf_wp_insulation: float - :param dx_tf_wp_insertion_gap: Thickness of winding pack insertion gap [m]. - :type dx_tf_wp_insertion_gap: float - :param n_tf_wp_layers: Number of winding pack layers (radial direction). - :type n_tf_wp_layers: int - :param dx_tf_wp_toroidal_min: Minimum toroidal thickness of winding pack [m]. - :type dx_tf_wp_toroidal_min: float - :param n_tf_wp_pancakes: Number of winding pack pancakes (toroidal direction). - :type n_tf_wp_pancakes: int - :param c_tf_coil: Total TF coil current [A]. - :type c_tf_coil: float - :param dx_tf_turn_steel: Thickness of turn steel [m]. - :type dx_tf_turn_steel: float - :param dx_tf_turn_insulation: Thickness of turn insulation [m]. - :type dx_tf_turn_insulation: float - - :returns: tuple containing: + Parameters + ---------- + dr_tf_wp_with_insulation : float + Radial thickness of winding pack with insulation [m]. + dx_tf_wp_insulation : float + Thickness of winding pack insulation [m]. + dx_tf_wp_insertion_gap : float + Thickness of winding pack insertion gap [m]. + n_tf_wp_layers : int + Number of winding pack layers (radial direction). + dx_tf_wp_toroidal_min : float + Minimum toroidal thickness of winding pack [m]. + n_tf_wp_pancakes : int + Number of winding pack pancakes (toroidal direction). + c_tf_coil : float + Total TF coil current [A]. + dx_tf_turn_steel : float + Thickness of turn steel [m]. + dx_tf_turn_insulation : float + Thickness of turn insulation [m]. + + Returns + ------- + type + tuple containing: - radius_tf_turn_cable_space_corners - dr_tf_turn - dx_tf_turn @@ -2588,8 +2638,6 @@ def tf_cable_in_conduit_integer_turn_geometry( - dr_tf_turn_cable_space - dx_tf_turn_cable_space - dx_tf_turn_cable_space_average - - :raises: Reports error if calculated turn or cable space dimensions are non-positive. """ # Radius of rounded corners in the cable space [m] @@ -2716,7 +2764,6 @@ def tf_cable_in_conduit_integer_turn_geometry( def tf_wp_currents(self): """ - Author : S. Kahn, CCFE Turn engineering turn currents/densities """ tfcoil_variables.j_tf_wp = max( @@ -2744,15 +2791,41 @@ def tf_cable_in_conduit_averaged_turn_geometry( dia_tf_turn_coolant_channel, f_a_tf_turn_cable_space_extra_void, ): - """ - subroutine straight from Python, see comments in tf_averaged_turn_geom_wrapper - Authors : J. Morris, CCFE - Authors : S. Kahn, CCFE + """subroutine straight from Python, see comments in tf_averaged_turn_geom_wrapper Setting the TF WP turn geometry for SC magnets from the number the current per turn. This calculation has two purposes, first to check if a turn can exist (positive cable space) and the second to provide its dimensions, areas and the (float) number of turns + + Parameters + ---------- + j_tf_wp : + + dx_tf_turn_steel : + + dx_tf_turn_insulation : + + i_tf_sc_mat : + + dx_tf_turn_general : + + c_tf_turn : + + i_dx_tf_turn_general_input : + + i_dx_tf_turn_cable_space_general_input : + + dx_tf_turn_cable_space_general : + + layer_ins : + + a_tf_wp_no_insulation : + + dia_tf_turn_coolant_channel : + + f_a_tf_turn_cable_space_extra_void : + """ # Turn dimension is a an input @@ -3005,15 +3078,20 @@ def superconducting_tf_coil_areas_and_masses(self): @staticmethod def lambda_term(tau: float, omega: float) -> float: - """ - The lambda function used inegral in inductance calcuation found + """The lambda function used inegral in inductance calcuation found in Y. Itoh et al. The full form of the functions are given in appendix A. - Author: Alexander Pearce, UKAEA - - :param tau: tau_{s,k} = (R_{s,k} - R_{c,k}) / R_k - :param omega: omega_k = R_{c,k}/R_k - :returns: integral + Parameters + ---------- + tau : + tau_{s,k} = (R_{s,k} - R_{c,k}) / R_k + omega : + omega_k = R_{c,k}/R_k + + Returns + ------- + : + integral """ p = 1.0 - omega**2.0 @@ -3033,19 +3111,27 @@ def lambda_term(tau: float, omega: float) -> float: def _theta_factor_integral( ro_vv: float, ri_vv: float, rm_vv: float, h_vv: float, theta1_vv: float ) -> float: - """ - The calcuation of the theta factor found in Eq 4 of Y. Itoh et al. The + """The calcuation of the theta factor found in Eq 4 of Y. Itoh et al. The full form of the integral is given in appendix A. - Author: Alexander Pearce, UKAEA - - :param ro_vv: the radius of the outboard edge of the VV CCL - :param ri_vv: the radius of the inboard edge of the VV CCL - :param rm_vv: the radius where the maximum height of the VV CCL occurs - :param h_vv: the maximum height of the VV CCL - :param theta1_vv: the polar angle of the point at which one circular arc is - joined to another circular arc in the approximation to the VV CCL - :returns: theta factor. + Parameters + ---------- + ro_vv : + the radius of the outboard edge of the VV CCL + ri_vv : + the radius of the inboard edge of the VV CCL + rm_vv : + the radius where the maximum height of the VV CCL occurs + h_vv : + the maximum height of the VV CCL + theta1_vv : + the polar angle of the point at which one circular arc is + joined to another circular arc in the approximation to the VV CCL + + Returns + ------- + : + theta factor. """ theta2 = np.pi / 2.0 + theta1_vv a = (ro_vv - ri_vv) / 2.0 @@ -3112,8 +3198,6 @@ def vv_stress_on_quench( """Generic model to calculate the Tresca stress of the Vacuum Vessel (VV), experienced when the TF coil quenches. - Author: Timothy Nunn, UKAEA - The current center line (CCL) of a structure is an appoximation of where the poloidal current of a structure acts. This model considers how the current (self-)induced in the following structures @@ -3124,33 +3208,53 @@ def vv_stress_on_quench( 1. the TF coil steel structure 2. the VV - :param H_coil: the maximum height of the TF coil CCL - :param ri_coil: the radius of the inboard edge of the TF coil CCL - :param ro_coil: the radius of the outboard edge of the TF coil CCL - :param rm_coil: the radius where the maximum height of the TF coil CCL occurs - :param ccl_length_coil: the length of the TF coil CCL - :param theta1_coil: the polar angle of the point at which one circular arc is - joined to another circular arc in the approximation to the coil CCL, - using an arbitrary origin of coordinates (Rc2, Zc2). - - :param H_vv: the maximum height of the VV CCL - :param ri_vv: the radius of the inboard edge of the VV CCL - :param ro_vv: the radius of the outboard edge of the VV CCL - :param rm_vv: the radius where the maximum height of the VV CCL occurs - :param theta1_vv: the polar angle of the point at which one circular arc is - joined to another circular arc in the approximation to the VV CCL, - using an arbitrary origin of coordinates (Rc2, Zc2). - - :param n_tf_coils: the number of TF coils - :param n_tf_coil_turns: the number of turns per TF coil - :param s_rp: the cross-sectional area of the radial plates of the TF coil - :param s_cc: the cross-sectional area of the TF coil case - :param taud: the discharge time of the TF coil when quench occurs - :param i_op: the 'normal' operating current of the TF coil - - :param d_vv: the thickness of the vacuum vessel shell - - :returns: the maximum stress experienced by the vacuum vessel + Parameters + ---------- + H_coil : + the maximum height of the TF coil CCL + ri_coil : + the radius of the inboard edge of the TF coil CCL + ro_coil : + the radius of the outboard edge of the TF coil CCL + rm_coil : + the radius where the maximum height of the TF coil CCL occurs + ccl_length_coil : + the length of the TF coil CCL + theta1_coil : + the polar angle of the point at which one circular arc is + joined to another circular arc in the approximation to the coil CCL, + using an arbitrary origin of coordinates (Rc2, Zc2). + H_vv : + the maximum height of the VV CCL + ri_vv : + the radius of the inboard edge of the VV CCL + ro_vv : + the radius of the outboard edge of the VV CCL + rm_vv : + the radius where the maximum height of the VV CCL occurs + theta1_vv : + the polar angle of the point at which one circular arc is + joined to another circular arc in the approximation to the VV CCL, + using an arbitrary origin of coordinates (Rc2, Zc2). + n_tf_coils : + the number of TF coils + n_tf_coil_turns : + the number of turns per TF coil + s_rp : + the cross-sectional area of the radial plates of the TF coil + s_cc : + the cross-sectional area of the TF coil case + taud : + the discharge time of the TF coil when quench occurs + i_op : + the 'normal' operating current of the TF coil + d_vv : + the thickness of the vacuum vessel shell + + Returns + ------- + : + the maximum stress experienced by the vacuum vessel Notes ----- @@ -3224,15 +3328,20 @@ def _inductance_factor( """Calculates the inductance factor for a toroidal structure using surrogate 2 #1866. - Author: Timothy Nunn, UKAEA - - :param H: the maximum height of the structure - :param ri: the radius of the inboard side of the structure CCL - :param ro: the radius of the outboard side of the structure CCL - :param rm: the radius at which `H` occurs - :param theta1: the polar angle of the point at which one circular arc is - joined to another circular arc in the approximation to the structure CCL, - using an arbitrary origin of coordinates (Rc2, Zc2). + Parameters + ---------- + H : + the maximum height of the structure + ri : + the radius of the inboard side of the structure CCL + ro : + the radius of the outboard side of the structure CCL + rm : + the radius at which `H` occurs + theta1 : + the polar angle of the point at which one circular arc is + joined to another circular arc in the approximation to the structure CCL, + using an arbitrary origin of coordinates (Rc2, Zc2). """ # NOTE: the following properties are not those of the plasma but of # the VV/coil structures diff --git a/process/superconductors.py b/process/superconductors.py index 019d2a01cb..b256001cb3 100644 --- a/process/superconductors.py +++ b/process/superconductors.py @@ -10,26 +10,29 @@ def jcrit_rebco(temp_conductor: float, b_conductor: float) -> tuple[float, bool]: - """ - Calculate the critical current density for a "REBCO" 2nd generation HTS superconductor. - - :param temp_conductor: Superconductor temperature in Kelvin (K). - :type temp_conductor: float - :param b_conductor: Magnetic field at the superconductor in Tesla (T). - :type b_conductor: float - :return: A tuple containing: + """Calculate the critical current density for a "REBCO" 2nd generation HTS superconductor. + + Parameters + ---------- + temp_conductor : float + Superconductor temperature in Kelvin (K). + b_conductor : float + Magnetic field at the superconductor in Tesla (T). + + Returns + ------- + tuple[float, bool] + A tuple containing: - j_critical: Critical current density in the superconductor (A/m²). - validity: A boolean indicating whether the input parameters are within the valid range. - :rtype: tuple[float, bool] - - :notes: - - Validity range: - - Temperature: 4.2 K ≤ temp_conductor ≤ 72.0 K - - Magnetic field: - - For temp_conductor < 65 K: 0.0 T ≤ b_conductor ≤ 15.0 T - - For temp_conductor ≥ 65 K: 0.0 T ≤ b_conductor ≤ 11.5 T - :references: + Notes + ----- + - Validity range: + - Temperature: 4.2 K ≤ temp_conductor ≤ 72.0 K + - Magnetic field: + - For temp_conductor < 65 K: 0.0 T ≤ b_conductor ≤ 15.0 T + - For temp_conductor ≥ 65 K: 0.0 T ≤ b_conductor ≤ 11.5 T """ # Critical temperature (K) at zero field and strain. @@ -86,9 +89,18 @@ def jcrit_rebco(temp_conductor: float, b_conductor: float) -> tuple[float, bool] def current_sharing_rebco(bfield, j): """Current sharing temperature for "REBCO" 2nd generation HTS superconductor - b : input real : Magnetic field at superconductor (T) - j : input real : Current density in superconductor (A/m2) - current_sharing_t : output real : Current sharing temperature (K) + + Parameters + ---------- + bfield : + Magnetic field at superconductor (T) + j : + Current density in superconductor (A/m2) + + Returns + ------- + current_sharing_t : + Current sharing temperature (K) """ def deltaj_rebco(temperature): @@ -120,33 +132,39 @@ def itersc( b_c20max: float, temp_c0max: float, ) -> tuple[float, float, float]: - """ - Calculate the critical current density, critical field, and critical temperature + """Calculate the critical current density, critical field, and critical temperature for an ITER Nb₃Sn superconductor using the ITER Nb₃Sn critical surface model. - :param temp_conductor: Superconductor temperature (K). - :type temp_conductor: float - :param b_conductor: Magnetic field at the conductor (T). - :type b_conductor: float - :param strain: Strain in the superconductor. - :type strain: float - :param b_c20max: Upper critical field (T) for the superconductor at zero temperature and strain. - :type b_c20max: float - :param temp_c0max: Critical temperature (K) at zero field and strain. - :type temp_c0max: float - :return: A tuple containing: + Parameters + ---------- + temp_conductor : float + Superconductor temperature (K). + b_conductor : float + Magnetic field at the conductor (T). + strain : float + Strain in the superconductor. + b_c20max : float + Upper critical field (T) for the superconductor at zero temperature and strain. + temp_c0max : float + Critical temperature (K) at zero field and strain. + + Returns + ------- + tuple[float, float, float] + A tuple containing: - j_critical: Critical current density in the superconductor (A/m²). - b_critical: Critical field (T). - temp_critical: Critical temperature (K). - :rtype: tuple[float, float, float] - :notes: - - This routine uses the ITER Nb₃Sn critical surface model. - - The model assumes a strand size of 0.82 mm diameter. + Notes + ----- + - This routine uses the ITER Nb₃Sn critical surface model. + - The model assumes a strand size of 0.82 mm diameter. - :references: - - ITER DDD 11-7: Magnets - conductors (2NBKXY) (2009), - https://user.iter.org/?uid=2NBKXY&action=get_document + References + ---------- + - ITER DDD 11-7: Magnets - conductors (2NBKXY) (2009), + https://user.iter.org/?uid=2NBKXY&action=get_document """ # Scaling constant C [AT/mm²] csc = 19922.0 @@ -199,39 +217,44 @@ def jcrit_nbti( b_c20max: float, temp_c0max: float, ) -> tuple[float, float]: - """ - Calculate the critical current density and critical temperature for a NbTi superconductor strand using the old empirical + """Calculate the critical current density and critical temperature for a NbTi superconductor strand using the old empirical Lubell scaling law. - :param temp_conductor: Superconductor temperature (K). - :type temp_conductor: float - :param b_conductor: Magnetic field at the conductor (T). - :type b_conductor: float - :param c0: Scaling constant (A/m²). - :type c0: float - :param b_c20max: Upper critical field (T) for the superconductor at zero temperature and strain. - :type b_c20max: float - :param temp_c0max: Critical temperature (K) at zero field and strain. - :type temp_c0max: float - :return: A tuple containing: - - jcrit: Critical current density in the superconductor (A/m²). - - tcrit: Critical temperature (K). - :rtype: tuple[float, float] - - :notes: - - If the magnetic field exceeds the upper critical field (bmax > bc20max), - the critical temperature is adjusted to ensure a real (negative) value. - - If the temperature exceeds the critical temperature, the critical surface - is considered exceeded, and the reduced temperature (tbar) becomes negative. - - - This model uses an antiquated scaling law for NbTi, which is not used in the superconductor field for nearly 30 years. - - It is simplistic and linear in J_c (B) (for a fixed temperature), lacking accuracy in both the high and low field regions. - - :references: - - M. Lubell, “Empirical scaling formulas for critical current and critical field for commercial NbTi,” - IEEE Transactions on Magnetics, vol. 19, no. 3, pp. 754-757, May 1983, - doi: https://doi.org/10.1109/tmag.1983.1062311. - ‌ + Parameters + ---------- + temp_conductor : float + Superconductor temperature (K). + b_conductor : float + Magnetic field at the conductor (T). + c0 : float + Scaling constant (A/m²). + b_c20max : float + Upper critical field (T) for the superconductor at zero temperature and strain. + temp_c0max : float + Critical temperature (K) at zero field and strain. + + Returns + ------- + tuple[float, float] + A tuple containing: + - jcrit: Critical current density in the superconductor (A/m²). + - tcrit: Critical temperature (K). + + Notes + ----- + - If the magnetic field exceeds the upper critical field (bmax > bc20max), + the critical temperature is adjusted to ensure a real (negative) value. + - If the temperature exceeds the critical temperature, the critical surface + is considered exceeded, and the reduced temperature (tbar) becomes negative. + + - This model uses an antiquated scaling law for NbTi, which is not used in the superconductor field for nearly 30 years. + - It is simplistic and linear in J_c (B) (for a fixed temperature), lacking accuracy in both the high and low field regions. + + References + ---------- + - M. Lubell, “Empirical scaling formulas for critical current and critical field for commercial NbTi,” + IEEE Transactions on Magnetics, vol. 19, no. 3, pp. 754-757, May 1983, + doi: https://doi.org/10.1109/tmag.1983.1062311. """ bratio = b_conductor / b_c20max @@ -252,8 +275,7 @@ def jcrit_nbti( def bi2212(b_conductor, jstrand, temp_conductor, f_strain): - """ - Fitted parameterization to Bi-2212 superconductor properties. + """Fitted parameterization to Bi-2212 superconductor properties. This function calculates the critical current density and the temperature margin for Bi-2212 superconductor in the TF coils using a fit by M. Kovari to measurements @@ -263,32 +285,42 @@ def bi2212(b_conductor, jstrand, temp_conductor, f_strain): It needs to be operated below about 10K but remains superconducting at much higher fields at that temperature than Nb₃Sn, etc. - :param b_conductor: Magnetic field at conductor (T). - :type b_conductor: float - :param jstrand: Current density in strand (A/m²). - :type jstrand: float - :param temp_conductor: Superconductor temperature (K). - :type temp_conductor: float - :param f_strain: Adjustment factor (≤ 1) to account for strain, radiation damage, - fatigue, or AC losses. - :type f_strain: float - :raises ProcessValueError: If the input parameters are outside the range of validity. - :return: A tuple containing: - - j_critical: Critical current density in strand (A/m²). - - temp_margin: Temperature margin (K). - :rtype: tuple[float, float] - - :notes: - -The model's range of validity is: - T < 20K - Adjusted field b < 104 T - B > 6 T - - :reference: - - D. C. Larbalestier, J. Jiang, U. P. Trociewitz, F. Kametani, and E. E. Hellstrom, - “A transformative superconducting magnet technology for fields well above 30 T using isotropic round wire multifilament Bi2Sr2CaCu2O8-x conductor,” - May 06, 2013. https://www.researchgate.net/publication/236627864_A_transformative_superconducting_magnet_technology_for_fields_well_above_30_T_using_isotropic_round_wire_multifilament_Bi2Sr2CaCu2O8-x_conductor - ‌ + Parameters + ---------- + b_conductor : float + Magnetic field at conductor (T). + jstrand : float + Current density in strand (A/m²). + temp_conductor : float + Superconductor temperature (K). + f_strain : float + Adjustment factor (≤ 1) to account for strain, radiation damage, + fatigue, or AC losses. + + Returns + ------- + tuple[float, float] + A tuple containing: + - j_critical: Critical current density in strand (A/m²). + - temp_margin: Temperature margin (K). + + Notes + ----- + -The model's range of validity is: + T < 20K + Adjusted field b < 104 T + B > 6 T + + References + ----------- + - D. C. Larbalestier, J. Jiang, U. P. Trociewitz, F. Kametani, and E. E. Hellstrom, + “A transformative superconducting magnet technology for fields well above 30 T using isotropic round wire multifilament Bi2Sr2CaCu2O8-x conductor,” + May 06, 2013. https://www.researchgate.net/publication/236627864_A_transformative_superconducting_magnet_technology_for_fields_well_above_30_T_using_isotropic_round_wire_multifilament_Bi2Sr2CaCu2O8-x_conductor + + Raises + ------ + ProcessValueError + If the input parameters are outside the range of validity. """ b = b_conductor / np.exp(-0.168 * (temp_conductor - 4.2)) @@ -331,36 +363,36 @@ def gl_nbti( b_c20max: float, t_c0: float, ) -> tuple[float, float, float]: - """ - Calculate the critical current density, critical field, and critical temperature + """Calculate the critical current density, critical field, and critical temperature of an ITER Nb-Ti strand based on the Ginzburg-Landau theory of superconductivity. - :param temp_conductor: Superconductor temperature [K]. - :type temp_conductor: float - :param b_conductor: Magnetic field at the conductor [T]. - :type b_conductor: float - :param strain: Intrinsic strain in the superconductor [%]. - :type strain: float - :param b_c20max: Strain-dependent upper critical field at zero temperature [T]. - :type b_c20max: float - :param t_c0: Strain-dependent critical temperature at zero strain [K]. - :type t_c0: float - - :return: A tuple containing: + Parameters + ---------- + temp_conductor : float + Superconductor temperature [K]. + b_conductor : float + Magnetic field at the conductor [T]. + strain : float + Intrinsic strain in the superconductor [%]. + b_c20max : float + Strain-dependent upper critical field at zero temperature [T]. + t_c0 : float + Strain-dependent critical temperature at zero strain [K]. + + Returns + ------- + tuple[float, float, float] + A tuple containing: - j_critical : Critical current density in the superconductor [A/m²]. - b_critical : Critical magnetic field [T]. - t_critical : Critical temperature [K]. - :rtype: tuple[float, float, float] - - :notes: - - - :references: - - Model based on: S B L Chislett-Mcdonald, Y. Tsui, E. Surrey, M. Kovari, and D. P. Hampshire, - “The magnetic field, temperature, strain and angular dependence of the critical current density for Nb-Ti,” - Journal of Physics Conference Series, vol. 1559, no. 1, pp. 012063-012063, Jun. 2020, doi: - https://doi.org/10.1088/1742-6596/1559/1/012063. + References + ---------- + - Model based on: S B L Chislett-Mcdonald, Y. Tsui, E. Surrey, M. Kovari, and D. P. Hampshire, + “The magnetic field, temperature, strain and angular dependence of the critical current density for Nb-Ti,” + Journal of Physics Conference Series, vol. 1559, no. 1, pp. 012063-012063, Jun. 2020, doi: + https://doi.org/10.1088/1742-6596/1559/1/012063. """ a_0 = 1102e6 @@ -427,41 +459,42 @@ def gl_rebco( b_c20max: float, t_c0: float, ) -> tuple[float, float, float]: - """ - Calculate the critical current density, critical field, and critical temperature + """Calculate the critical current density, critical field, and critical temperature for a SuperPower REBCO tape based on measurements by P. Branch at Durham University and the Ginzburg-Landau theory of superconductivity - :param temp_conductor: Coolant/superconductor temperature (K). - :type temp_conductor: float - :param b_conductor: Magnetic field at conductor (T). - :type b_conductor: float - :param strain: Intrinsic strain in superconductor (%). - :type strain: float - :param b_c20max: Strain-dependent upper critical field at zero temperature (T). - :type b_c20max: float - :param t_c0: Strain-dependent critical temperature at zero strain (K). - :type t_c0: float - :return: Tuple containing: + Parameters + ---------- + temp_conductor : float + Coolant/superconductor temperature (K). + b_conductor : float + Magnetic field at conductor (T). + strain : float + Intrinsic strain in superconductor (%). + b_c20max : float + Strain-dependent upper critical field at zero temperature (T). + t_c0 : float + Strain-dependent critical temperature at zero strain (K). + + Returns + ------- + tuple[float, float, float] + Tuple containing: - j_critical: Critical current density in superconductor (A/m²). - b_critical: Critical magnetic field (T). - temp_critical: Critical temperature (K). - :rtype: tuple[float, float, float] - - :notes: - - :references: - - Model based on: S B L Chislett-Mcdonald, Y. Tsui, E. Surrey, M. Kovari, and D. P. Hampshire, - “The magnetic field, temperature, strain and angular dependence of the critical current density for Nb-Ti,” - Journal of Physics Conference Series, vol. 1559, no. 1, pp. 012063-012063, Jun. 2020, doi: - https://doi.org/10.1088/1742-6596/1559/1/012063. - - - -Fit to state-of-the-art measurements at 4.2 K:P. Branch, K. Osamura, and D. Hampshire, - “Weak emergence in the angular dependence of the critical current density of the high temperature superconductor coated conductor REBCO,” - Superconductor Science and Technology, vol. 33, no. 10, p. 104006, Sep. 2020, - doi: 10.1088/1361-6668/abaebe. - + References + ---------- + - Model based on: S B L Chislett-Mcdonald, Y. Tsui, E. Surrey, M. Kovari, and D. P. Hampshire, + “The magnetic field, temperature, strain and angular dependence of the critical current density for Nb-Ti,” + Journal of Physics Conference Series, vol. 1559, no. 1, pp. 012063-012063, Jun. 2020, doi: + https://doi.org/10.1088/1742-6596/1559/1/012063. + - + -Fit to state-of-the-art measurements at 4.2 K:P. Branch, K. Osamura, and D. Hampshire, + “Weak emergence in the angular dependence of the critical current density of the high temperature superconductor coated conductor REBCO,” + Superconductor Science and Technology, vol. 33, no. 10, p. 104006, Sep. 2020, + doi: 10.1088/1361-6668/abaebe. """ # Critical current density pre-factor a_0 = 2.95e2 @@ -526,53 +559,58 @@ def hijc_rebco( dx_hts_tape_rebco: float, dx_hts_tape_total: float, ) -> tuple[float, float, float]: - """ - Calculates the critical current density, critical field, and critical temperature + """Calculates the critical current density, critical field, and critical temperature for a high current density REBCO tape based Wolf et al. parameterization with data from Hazelton and Zhai et al. - :param temp_conductor: Superconductor temperature (K). - :type temp_conductor: float - :param b_conductor: Magnetic field at conductor (T). - :type b_conductor: float - :param b_c20max: Upper critical field (T) for superconductor at zero temperature and strain. - :type b_c20max: float - :param t_c0: Critical temperature (K) at zero field and strain. - :type t_c0: float - :param dr_hts_tape: Width of the tape (m). - :type dr_hts_tape: float - :param dx_hts_tape_rebco: Thickness of the REBCO layer (m). - :type dx_hts_tape_rebco: float - :param dx_hts_tape_total: Total thickness of the tape (m). - :type dx_hts_tape_total: float - :return: Tuple containing: + Parameters + ---------- + temp_conductor : float + Superconductor temperature (K). + b_conductor : float + Magnetic field at conductor (T). + b_c20max : float + Upper critical field (T) for superconductor at zero temperature and strain. + t_c0 : float + Critical temperature (K) at zero field and strain. + dr_hts_tape : float + Width of the tape (m). + dx_hts_tape_rebco : float + Thickness of the REBCO layer (m). + dx_hts_tape_total : float + Total thickness of the tape (m). + + Returns + ------- + tuple[float, float, float] + Tuple containing: - j_critical: Critical current density in superconductor (A/m²). - b_critical: Critical field (T). - temp_critical: Critical temperature (K). - :rtype: tuple[float, float, float] - - :notes: - - The parameter A is transformed into a function A(T) based on a Newton polynomial fit - considering A(4.2 K) = 2.2e8, A(20 K) = 2.3e8 and A(65 K) = 3.5e8. - - - A scaling factor of 0.4 was originally applied to j_critical for CORC cables, but is not used here. - - :references: - - Based in part on the parameterization described in: - M. J. Wolf, Nadezda Bagrets, W. H. Fietz, C. Lange, and K.-P. Weiss, - “Critical Current Densities of 482 A/mm2 in HTS CrossConductors at 4.2 K and 12 T,” - IEEE Transactions on Applied Superconductivity, vol. 28, no. 4, pp. 1-4, Jun. 2018, - doi: https://doi.org/10.1109/tasc.2018.2815767. - - - Fit values based on: - D. W. Hazelton, “4th Workshop on Accelerator Magnets in HTS (WAMHTS-4) | 2G HTS Wire Development at SuperPower,” - Indico, 2017. https://indico.cern.ch/event/588810/contributions/2473740/ (accessed May 20, 2025). - - -The high Ic parameterization is a result of modifications based on Ic values observed in: - Y. Zhai, D. van der Laan, P. Connolly, and C. Kessel, “Conceptual design of HTS magnets for fusion nuclear science facility,” - Fusion Engineering and Design, vol. 168, p. 112611, Jul. 2021, - doi: https://doi.org/10.1016/j.fusengdes.2021.112611. + Notes + ----- + - The parameter A is transformed into a function A(T) based on a Newton polynomial fit + considering A(4.2 K) = 2.2e8, A(20 K) = 2.3e8 and A(65 K) = 3.5e8. + + - A scaling factor of 0.4 was originally applied to j_critical for CORC cables, but is not used here. + + References + ---------- + - Based in part on the parameterization described in: + M. J. Wolf, Nadezda Bagrets, W. H. Fietz, C. Lange, and K.-P. Weiss, + “Critical Current Densities of 482 A/mm2 in HTS CrossConductors at 4.2 K and 12 T,” + IEEE Transactions on Applied Superconductivity, vol. 28, no. 4, pp. 1-4, Jun. 2018, + doi: https://doi.org/10.1109/tasc.2018.2815767. + + - Fit values based on: + D. W. Hazelton, “4th Workshop on Accelerator Magnets in HTS (WAMHTS-4) | 2G HTS Wire Development at SuperPower,” + Indico, 2017. https://indico.cern.ch/event/588810/contributions/2473740/ (accessed May 20, 2025). + + -The high Ic parameterization is a result of modifications based on Ic values observed in: + Y. Zhai, D. van der Laan, P. Connolly, and C. Kessel, “Conceptual design of HTS magnets for fusion nuclear science facility,” + Fusion Engineering and Design, vol. 168, p. 112611, Jul. 2021, + doi: https://doi.org/10.1016/j.fusengdes.2021.112611. """ a = 1.4 @@ -640,41 +678,46 @@ def western_superconducting_nb3sn( b_c20max: float, temp_c0max: float, ) -> tuple[float, float, float]: - """ - Calculate the critical current density, critical field, and critical temperature + """Calculate the critical current density, critical field, and critical temperature for a WST Nb₃Sn superconductor using the ITER Nb₃Sn critical surface model. - :param temp_conductor: Superconductor temperature (K). - :type temp_conductor: float - :param b_conductor: Magnetic field at the superconductor (T). - :type b_conductor: float - :param strain: Strain in the superconductor. - :type strain: float - :param b_c20max: Upper critical field (T) for the superconductor at zero temperature and strain. - :type b_c20max: float - :param temp_c0max: Critical temperature (K) at zero field and strain. - :type temp_c0max: float - :return: A tuple containing: + Parameters + ---------- + temp_conductor : float + Superconductor temperature (K). + b_conductor : float + Magnetic field at the superconductor (T). + strain : float + Strain in the superconductor. + b_c20max : float + Upper critical field (T) for the superconductor at zero temperature and strain. + temp_c0max : float + Critical temperature (K) at zero field and strain. + + Returns + ------- + tuple[float, float, float] + A tuple containing: - j_critical: Critical current density in the superconductor (A/m²). - b_crititical: Critical field (T). - temp_critical: Critical temperature (K). - :rtype: tuple[float, float, float] - - :notes: - - This routine uses the WST Nb3Sn critical surface model. - - The scaling constants and parameters are based on the reference below. - - This assumes a strand size of 1.5mm. - - Compared to the EUTF4 (OST) ( European qualification samples for TF conductor), - the performance of the WST at low strain is superior by about 10%. - - :references: - - V. Corato, “EUROFUSION WPMAG-REP(16) 16565 Common operating values for DEMO magnets design for 2016 REPORT.” - Accessed: May 12, 2025. [Online]. - Available: https://scipub.euro-fusion.org/wp-content/uploads/eurofusion/WPMAGREP16_16565_submitted.pdf - - - “Introduction of WST,” 2015. Accessed: May 12, 2025. [Online]. - Available: https://indico.cern.ch/event/340703/contributions/802232/attachments/668814/919331/WST_INTRO_2015-3_for_FCC_WEEK.pdf + Notes + ----- + - This routine uses the WST Nb3Sn critical surface model. + - The scaling constants and parameters are based on the reference below. + - This assumes a strand size of 1.5mm. + - Compared to the EUTF4 (OST) ( European qualification samples for TF conductor), + the performance of the WST at low strain is superior by about 10%. + + References + ---------- + - V. Corato, “EUROFUSION WPMAG-REP(16) 16565 Common operating values for DEMO magnets design for 2016 REPORT.” + Accessed: May 12, 2025. [Online]. + Available: https://scipub.euro-fusion.org/wp-content/uploads/eurofusion/WPMAGREP16_16565_submitted.pdf + + - “Introduction of WST,” 2015. Accessed: May 12, 2025. [Online]. + Available: https://indico.cern.ch/event/340703/contributions/802232/attachments/668814/919331/WST_INTRO_2015-3_for_FCC_WEEK.pdf """ # Scaling constant C [AT/mm²] csc = 83075.0 @@ -722,51 +765,57 @@ def bottura_scaling( b_c20max: float, temp_c0max: float, ) -> tuple[float, float, float]: - """ - Implements the scaling from: + """Implements the scaling from: Jc(B,T,epsilon) Parameterization for the ITER Nb₃Sn Production, - :param csc: Scaling constant C [AT/mm²]. - :type csc: float - :param p: Low field exponent of the pinning force - :type p: float - :param q: High field exponent of the pinning force - :type q: float - :param c_a1: Strain fitting constant C_{a1}. - :type c_a1: float - :param c_a2: Strain fitting constant C_{a2}. - :type c_a2: float - :param epsilon_0a: Residual strain component - :type epsilon_0a: float - :param temp_conductor: Superconductor temperature (K). - :type temp_conductor: float - :param b_conductor: Magnetic field at conductor (T). - :type b_conductor: float - :param epsilon: Strain in superconductor. - :type epsilon: float - :param b_c20max: Upper critical field (T) for superconductor at zero temperature and strain. - :type b_c20max: float - :param temp_c0max: Critical temperature (K) at zero field and strain. - :type temp_c0max: float - :return: A tuple containing: + Parameters + ---------- + csc : float + Scaling constant C [AT/mm²]. + p : float + Low field exponent of the pinning force + q : float + High field exponent of the pinning force + c_a1 : float + Strain fitting constant C_{a1}. + c_a2 : float + Strain fitting constant C_{a2}. + epsilon_0a : float + Residual strain component + temp_conductor : float + Superconductor temperature (K). + b_conductor : float + Magnetic field at conductor (T). + epsilon : float + Strain in superconductor. + b_c20max : float + Upper critical field (T) for superconductor at zero temperature and strain. + temp_c0max : float + Critical temperature (K) at zero field and strain. + + Returns + ------- + tuple[float, float, float] + A tuple containing: - jscaling: Critical current density scaling factor (A/m²). - bcrit: Critical field (T). - tcrit: Critical temperature (K). - :rtype: tuple[float, float, float] - :notes: - - This is a generic scaling proposed for the characterization and production of - ITER Nb₃Sn strands. This is also known as the "ITER-2008 parametrization." + Notes + ----- + - This is a generic scaling proposed for the characterization and production of + ITER Nb₃Sn strands. This is also known as the "ITER-2008 parametrization." - - Parameter ranges are strain (1.5% to 0.4%), temperature (2.35 to 16 K), and field (0.5 to 19 T). - The ITER-2008 parameterization achieves an average accuracy error of 3.8 Amps, with the best at 1.5 Amps and the worst at 7.5 Amps. + - Parameter ranges are strain (1.5% to 0.4%), temperature (2.35 to 16 K), and field (0.5 to 19 T). + The ITER-2008 parameterization achieves an average accuracy error of 3.8 Amps, with the best at 1.5 Amps and the worst at 7.5 Amps. - - The strain function is suitable only in the moderate strain region, down to 0.8%. + - The strain function is suitable only in the moderate strain region, down to 0.8%. - :references: - - L. Bottura and B. Bordini, “$J_{C}(B,T,\varepsilon)$ Parameterization for the ITER ${\rm Nb}_{3}{\rm Sn}$ Production,” - IEEE Transactions on Applied Superconductivity, vol. 19, no. 3, pp. 1521-1524, Jun. 2009, - doi: https://doi.org/10.1109/tasc.2009.2018278. + References + ---------- + - L. Bottura and B. Bordini, “$J_{C}(B,T,\varepsilon)$ Parameterization for the ITER ${\rm Nb}_{3}{\rm Sn}$ Production,” + IEEE Transactions on Applied Superconductivity, vol. 19, no. 3, pp. 1521-1524, Jun. 2009, + doi: https://doi.org/10.1109/tasc.2009.2018278. """ epsilon_sh = (c_a2 * epsilon_0a) / (np.sqrt(c_a1**2 - c_a2**2)) @@ -868,21 +917,25 @@ def calculate_croco_cable_geometry( float, # a_croco_strand float, # dr_hts_tape ]: - """ - Calculate geometry and areas for a CroCo cable strand. - - :param dia_croco_strand: Diameter of CroCo strand (m) - :type dia_croco_strand: float - :param dx_croco_strand_copper: Thickness of copper layer in CroCo strand (m) - :type dx_croco_strand_copper: float - :param dx_hts_tape_rebco: Thickness of REBCO layer in HTS tape (m) - :type dx_hts_tape_rebco: float - :param dx_hts_tape_copper: Thickness of copper layer in HTS tape (m) - :type dx_hts_tape_copper: float - :param dx_hts_tape_hastelloy: Thickness of Hastelloy layer in HTS tape (m) - :type dx_hts_tape_hastelloy: float - - :return: Tuple containing: + """Calculate geometry and areas for a CroCo cable strand. + + Parameters + ---------- + dia_croco_strand : float + Diameter of CroCo strand (m) + dx_croco_strand_copper : float + Thickness of copper layer in CroCo strand (m) + dx_hts_tape_rebco : float + Thickness of REBCO layer in HTS tape (m) + dx_hts_tape_copper : float + Thickness of copper layer in HTS tape (m) + dx_hts_tape_hastelloy : float + Thickness of Hastelloy layer in HTS tape (m) + + Returns + ------- + tuple[float, float, float, float, float, float, float, float] + Tuple containing: - dia_croco_strand_tape_region: Inner diameter of CroCo strand tape region (m) - n_croco_strand_hts_tapes: Number of HTS tapes in CroCo strand - a_croco_strand_copper_total: Total copper area in CroCo strand (m²) @@ -891,7 +944,6 @@ def calculate_croco_cable_geometry( - a_croco_strand_rebco: Total REBCO area in CroCo strand (m²) - a_croco_strand: Total area of CroCo strand (m²) - dr_hts_tape: Width of the tape (m) - :rtype: tuple[float, float, float, float, float, float, float, float] """ # Calculate the inner diameter of the CroCo strand tape region @@ -949,6 +1001,17 @@ def croco(j_crit_sc, conductor_area, dia_croco_strand, dx_croco_strand_copper): """'CroCo' (cross-conductor) strand and cable design for 'REBCO' 2nd generation HTS superconductor Updated 13/11/18 using data from Lewandowska et al 2018. + + Parameters + ---------- + j_crit_sc : + + conductor_area : + + dia_croco_strand : + + dx_croco_strand_copper : + """ ( @@ -1026,28 +1089,7 @@ def superconductor_current_density_margin( tc0m: float, c0: float = 0.0, ) -> float: - """ - Calculate the current density margin for a superconductor. - - :param temp_superconductor: Superconductor Temperature (K) - :type temp_superconductor: float - :param i_superconductor_type: Switch for superconductor material - :type i_superconductor_type: int - :param j_superconductor: Superconductor actual current density (A/m²) - :type j_superconductor: float - :param b_superconductor: Magnetic field at the superconductor (T) - :type b_superconductor: float - :param strain: Superconductor strain - :type strain: float - :param bc20m: Upper critical field (T) - :type bc20m: float - :param tc0m: Critical temperature (K) - :type tc0m: float - :param c0: Scaling constant (A/m²), required for NbTi - :type c0: float, optional - :return: Current density margin (A/m²) - :rtype: float - + """Calculate the current density margin for a superconductor. The current density margin is the difference between the operating current density and the critical current density of a superconductor at a given temperature and field. It is zero at the current-sharing temperature. @@ -1060,6 +1102,31 @@ def superconductor_current_density_margin( 7: Ginzburg-Landau NbTi 8: Ginzburg-Landau REBCO 9: High current density REBCO + + Parameters + ---------- + temp_superconductor : float + Superconductor Temperature (K) + i_superconductor_type : int + Switch for superconductor material + j_superconductor : float + Superconductor actual current density (A/m²) + b_superconductor : float + Magnetic field at the superconductor (T) + strain : float + Superconductor strain + bc20m : float + Upper critical field (T) + tc0m : float + Critical temperature (K) + c0 : float, optional + Scaling constant (A/m²), required for NbTi + + Returns + ------- + float + Current density margin (A/m²) + """ material_functions = { 1: lambda: itersc(temp_superconductor, b_superconductor, strain, bc20m, tc0m)[0], diff --git a/process/tf_coil.py b/process/tf_coil.py index d5fddfd1ad..2867fc9fce 100644 --- a/process/tf_coil.py +++ b/process/tf_coil.py @@ -125,8 +125,7 @@ def tf_global_geometry( r_tf_outboard_mid: float, dr_tf_outboard: float, ) -> tuple[float, float, float, float, float, float, float, float, float]: - """ - Calculate the global geometry of the Toroidal Field (TF) coil. + """Calculate the global geometry of the Toroidal Field (TF) coil. This method computes the overall geometry of the TF coil, including: @@ -135,44 +134,36 @@ def tf_global_geometry( - Radii and widths of the inboard and outboard legs. - Case thicknesses for plasma-facing and sidewall regions. - :param i_tf_case_geom: + Parameters + ---------- + i_tf_case_geom : int Geometry type of the TF coil case (e.g., circular or straight plasma-facing front case). - :type i_tf_case_geom: int - :param i_f_dr_tf_plasma_case: + i_f_dr_tf_plasma_case : bool Whether the plasma-facing case thickness is specified as a fraction of the inboard thickness. - :type i_f_dr_tf_plasma_case: bool - :param f_dr_tf_plasma_case: + f_dr_tf_plasma_case : float Fraction of the inboard thickness used for the plasma-facing case thickness. - :type f_dr_tf_plasma_case: float - :param tfc_sidewall_is_fraction: + tfc_sidewall_is_fraction : bool Whether the sidewall case thickness is specified as a fraction of the inboard radius. - :type tfc_sidewall_is_fraction: bool - :param casths_fraction: + casths_fraction : float Fraction of the inboard radius used for the sidewall case thickness. - :type casths_fraction: float - :param n_tf_coils: + n_tf_coils : int Number of TF coils. - :type n_tf_coils: int - :param dr_tf_inboard: + dr_tf_inboard : float Radial thickness of the inboard leg of the TF coil [m]. - :type dr_tf_inboard: float - :param dr_tf_nose_case: + dr_tf_nose_case : float Thickness of the inboard leg case at the nose region [m]. - :type dr_tf_nose_case: float - :param r_tf_inboard_out: + r_tf_inboard_out : float Outer radius of the inboard leg of the TF coil [m]. - :type r_tf_inboard_out: float - :param r_tf_inboard_in: + r_tf_inboard_in : float Inner radius of the inboard leg of the TF coil [m]. - :type r_tf_inboard_in: float - :param r_tf_outboard_mid: + r_tf_outboard_mid : float Mid-plane radius of the outboard leg of the TF coil [m]. - :type r_tf_outboard_mid: float - :param dr_tf_outboard: + dr_tf_outboard : float Radial thickness of the outboard leg of the TF coil [m]. - :type dr_tf_outboard: float - :returns: + Returns + ------- + tuple A tuple containing: - **rad_tf_coil_inboard_toroidal_half** (*float*): Toroidal angular spacing of each TF coil [radians]. - **tan_theta_coil** (*float*): Tangent of the toroidal angular spacing. @@ -181,7 +172,6 @@ def tf_global_geometry( - **r_tf_outboard_out** (*float*): Outer radius of the outboard leg of the TF coil [m]. - **dx_tf_inboard_out_toroidal** (*float*): Width of the inboard leg at the outer edge in the toroidal direction [m]. - **a_tf_leg_outboard** (*float*): Cross-sectional area of the outboard leg of the TF coil [m²]. - :rtype: tuple """ # The angular space of each TF coil in the toroidal direction [rad] @@ -229,7 +219,7 @@ def tf_global_geometry( # Set directly as input dr_tf_plasma_case = tfcoil_variables.dr_tf_plasma_case - # This ensures that there is sufficent radial space for the WP to not + # This ensures that there is sufficient radial space for the WP to not # clip the edges of the plasma-facing front case if dr_tf_plasma_case < (r_tf_inboard_in + dr_tf_inboard) * ( @@ -244,7 +234,7 @@ def tf_global_geometry( # Warn that the value has be forced to a minimum value at some point in # iteration logger.error( - "dr_tf_plasma_case to small to accommodate the WP, forced to minimum value" + "dr_tf_plasma_case too small to accommodate the WP, forced to minimum value" ) # ====================================================================== @@ -279,26 +269,29 @@ def tf_current( r_b_tf_inboard_peak: float, a_tf_inboard_total: float, ) -> tuple[float, float, float, float]: - """ - Calculate the maximum B field and the corresponding TF current. - - :param n_tf_coils: Number of TF coils. - :type n_tf_coils: int - :param b_plasma_toroidal_on_axis: Toroidal magnetic field at the plasma center [T]. - :type b_plasma_toroidal_on_axis: float - :param rmajor: Major radius of the plasma [m]. - :type rmajor: float - :param r_b_tf_inboard_peak: Radius at which the peak inboard B field occurs [m]. - :type r_b_tf_inboard_peak: float - :param a_tf_inboard_total: Cross-sectional area of the inboard leg of the TF coil [m²]. - :type a_tf_inboard_total: float - - :returns: A tuple containing: + """Calculate the maximum B field and the corresponding TF current. + + Parameters + ---------- + n_tf_coils : int + Number of TF coils. + b_plasma_toroidal_on_axis : float + Toroidal magnetic field at the plasma center [T]. + rmajor : float + Major radius of the plasma [m]. + r_b_tf_inboard_peak : float + Radius at which the peak inboard B field occurs [m]. + a_tf_inboard_total : float + Cross-sectional area of the inboard leg of the TF coil [m²]. + + Returns + ------- + tuple[float, float, float, float] + A tuple containing: - **b_tf_inboard_peak_symmetric** (*float*): Maximum B field on the magnet [T]. - **c_tf_total** (*float*): Total current in TF coils [A]. - **c_tf_coil** (*float*): Current per TF coil [A]. - **oacdcp** (*float*): Global inboard leg average current density in TF coils [A/m²]. - :rtype: tuple[float, float, float, float] """ # Calculation of the maximum B field on the magnet [T] @@ -338,48 +331,50 @@ def tf_coil_shape_inner( r_tf_outboard_mid: float, r_tf_inboard_mid: float, ) -> tuple[float, np.ndarray, np.ndarray, np.ndarray, np.ndarray]: - """ - Calculate the shape of the inside of the TF coil. + """Calculate the shape of the inside of the TF coil. This method approximates the TF coil by a straight inboard section and four elliptical arcs. The model is ad hoc and does not have a physics or engineering basis. - :param i_tf_shape: TF coil shape selection switch. - :type i_tf_shape: int - :param itart: TART (tight aspect ratio tokamak) switch. - :type itart: int - :param i_single_null: Single null switch. - :type i_single_null: int - :param r_tf_inboard_out: Outer radius of the inboard leg of the TF coil [m]. - :type r_tf_inboard_out: float - :param r_cp_top: Centrepost outer radius at the top [m]. - :type r_cp_top: float - :param rmajor: Major radius of the plasma [m]. - :type rmajor: float - :param rminor: Minor radius of the plasma [m]. - :type rminor: float - :param r_tf_outboard_in: Inner radius of the outboard leg of the TF coil [m]. - :type r_tf_outboard_in: float - :param z_tf_inside_half: Maximum inboard edge height [m]. - :type z_tf_inside_half: float - :param z_tf_top: Vertical position of the top of the TF coil [m]. - :type z_tf_top: float - :param dr_tf_inboard: Radial thickness of the inboard leg of the TF coil [m]. - :type dr_tf_inboard: float - :param dr_tf_outboard: Radial thickness of the outboard leg of the TF coil [m]. - :type dr_tf_outboard: float - :param r_tf_outboard_mid: Mid-plane radius of the outboard leg of the TF coil [m]. - :type r_tf_outboard_mid: float - :param r_tf_inboard_mid: Mid-plane radius of the inboard leg of the TF coil [m]. - :type r_tf_inboard_mid: float - - :returns: - - len_tf_coil (float): Total length of the TF coil. + Parameters + ---------- + i_tf_shape : int + TF coil shape selection switch. + itart : int + TART (tight aspect ratio tokamak) switch. + i_single_null : int + Single null switch. + r_tf_inboard_out : float + Outer radius of the inboard leg of the TF coil [m]. + r_cp_top : float + Centrepost outer radius at the top [m]. + rmajor : float + Major radius of the plasma [m]. + rminor : float + Minor radius of the plasma [m]. + r_tf_outboard_in : float + Inner radius of the outboard leg of the TF coil [m]. + z_tf_inside_half : float + Maximum inboard edge height [m]. + z_tf_top : float + Vertical position of the top of the TF coil [m]. + dr_tf_inboard : float + Radial thickness of the inboard leg of the TF coil [m]. + dr_tf_outboard : float + Radial thickness of the outboard leg of the TF coil [m]. + r_tf_outboard_mid : float + Mid-plane radius of the outboard leg of the TF coil [m]. + r_tf_inboard_mid : float + Mid-plane radius of the inboard leg of the TF coil [m]. + + Returns + ------- + tuple[float, np.ndarray, np.ndarray, np.ndarray, np.ndarray] + len_tf_coil (float): Total length of the TF coil. - tfa (np.ndarray): Arc segment lengths in R. - tfb (np.ndarray): Arc segment lengths in Z. - r_tf_arc (np.ndarray): R coordinates of arc points. - z_tf_arc (np.ndarray): Z coordinates of arc points. - :rtype: tuple[float, np.ndarray, np.ndarray, np.ndarray, np.ndarray] """ FSTRAIGHT = 0.6 len_tf_coil = 0.0 @@ -389,7 +384,7 @@ def tf_coil_shape_inner( tfb = np.zeros(4) if i_tf_shape == 1 and itart == 0: - # PROCESS D-shape parametrisation + # PROCESS D-shape parameterisation r_tf_arc[0] = r_tf_inboard_out r_tf_arc[1] = rmajor - 0.2e0 * rminor r_tf_arc[2] = r_tf_outboard_in @@ -478,29 +473,34 @@ def tf_stored_magnetic_energy( c_tf_total: float, n_tf_coils: int, ) -> tuple[float, float, float]: - """ - Calculates the stored magnetic energy in a single TF coil. - - :param ind_tf_coil: Self-inductance of the TF coil [H]. - :type ind_tf_coil: float - :param c_tf_total: Current in all TF coils [A]. - :type c_tf_total: float - :param n_tf_coils: Number of TF coils. - :type n_tf_coils: int + """Calculates the stored magnetic energy in a single TF coil. + + Parameters + ---------- + ind_tf_coil : float + Self-inductance of the TF coil [H]. + c_tf_total : float + Current in all TF coils [A]. + n_tf_coils : int + Number of TF coils. - :returns: Tuple containing: + Returns + ------- + tuple[float, float, float] + Tuple containing: - e_tf_magnetic_stored_total (float): Total stored magnetic energy in all TF coils [J]. - e_tf_magnetic_stored_total_gj (float): Total stored magnetic energy in all TF coils [GJ]. - e_tf_coil_magnetic_stored (float): Stored magnetic energy in a single TF coil [J]. - :rtype: tuple[float, float, float] - :notes: + Notes + ----- - The stored magnetic energy in an inductor is given by: E = (1/2) * L * I^2 where E is the energy [J], L is the inductance [H], and I is the current [A]. - Total energy is for all coils; per-coil energy is divided by n_tf_coils. - :references: + References + ---------- - http://hyperphysics.phy-astr.gsu.edu/hbase/electric/indeng.html - https://en.wikipedia.org/wiki/Inductance#Self-inductance_and_magnetic_energy @@ -519,8 +519,7 @@ def tf_stored_magnetic_energy( def outtf(self): """Writes superconducting TF coil output to file - author: P J Knight, CCFE, Culham Science Centre - outfile : input integer : output file unit + This routine writes the superconducting TF coil results to the output file. PROCESS Superconducting TF Coil Model, J. Morris, CCFE, 1st May 2014 @@ -537,12 +536,12 @@ def outtf(self): if tfcoil_variables.i_tf_sup == 0: po.ocmmnt( - self.outfile, " -> Resitive coil : Water cooled copper (GLIDCOP AL-15)" + self.outfile, " -> resistive coil : Water cooled copper (GLIDCOP AL-15)" ) elif tfcoil_variables.i_tf_sup == 1: po.ocmmnt(self.outfile, " -> Superconducting coil (SC)") elif tfcoil_variables.i_tf_sup == 2: - po.ocmmnt(self.outfile, " -> Reisitive coil : Helium cooled aluminium") + po.ocmmnt(self.outfile, " -> Resistive coil : Helium cooled aluminium") # SC material scaling if tfcoil_variables.i_tf_sup == 1: @@ -1074,7 +1073,7 @@ def outtf(self): po.osubhd(self.outfile, "WP turn information:") po.ovarin( self.outfile, - "Turn parametrisation", + "Turn parameterisation", "(i_tf_turns_integer)", tfcoil_variables.i_tf_turns_integer, ) @@ -2152,14 +2151,17 @@ def circumference(aaa, bbb): An ellipse has the following formula: (x/a)² + (y/b)² = 1 - :param aaa: the value of a in the formula of the ellipse. - :type aaa: float - - :param bbb: the value of b in the formula of the ellipse. - :type bbb: float - - :returns: an approximation of the circumference of the ellipse - :rtype: float + Parameters + ---------- + aaa : float + the value of a in the formula of the ellipse. + bbb : float + the value of b in the formula of the ellipse. + + Returns + ------- + float + an approximation of the circumference of the ellipse """ hh = (aaa - bbb) ** 2 / (aaa + bbb) ** 2 return ( @@ -2169,9 +2171,8 @@ def circumference(aaa, bbb): ) def cntrpst(self): - """ - Evaluates the properties of a TART centrepost - author: P J Knight, CCFE, Culham Science Centre + """Evaluates the properties of a TART centrepost + outfile : input integer : output file unit iprint : input integer : switch for writing to output file (1=yes) This subroutine evaluates the parameters of the centrepost for a @@ -2590,57 +2591,53 @@ def tf_field_and_force( i_cp_joints: int, f_vforce_inboard: float, ) -> tuple[float, float, float, float, float]: - """ - Calculates the Toroidal Field (TF) coil field, forces, vacuum vessel (VV) quench considerations, + """Calculates the Toroidal Field (TF) coil field, forces, vacuum vessel (VV) quench considerations, and resistive magnet resistance/volume. - :param i_tf_sup: TF coil support type (1 = superconducting, 0 = resistive copper, 2 = resistive aluminium) - :type i_tf_sup: int - :param r_tf_wp_inboard_outer: Outer radius of the inboard winding pack [m] - :type r_tf_wp_inboard_outer: float - :param r_tf_wp_inboard_inner: Inner radius of the inboard winding pack [m] - :type r_tf_wp_inboard_inner: float - :param r_tf_outboard_in: Inner radius of the outboard leg [m] - :type r_tf_outboard_in: float - :param dx_tf_wp_insulation: Thickness of winding pack ground insulation [m] - :type dx_tf_wp_insulation: float - :param dx_tf_wp_insertion_gap: Thickness of winding pack insertion gap [m] - :type dx_tf_wp_insertion_gap: float - :param b_tf_inboard_peak_symmetric: Peak inboard magnetic field [T] - :type b_tf_inboard_peak_symmetric: float - :param c_tf_total: Total current in TF coils [A] - :type c_tf_total: float - :param n_tf_coils: Number of TF coils - :type n_tf_coils: int - :param dr_tf_plasma_case: Plasma-facing case thickness [m] - :type dr_tf_plasma_case: float - :param rmajor: Major radius of the plasma [m] - :type rmajor: float - :param b_plasma_toroidal_on_axis: Toroidal magnetic field at plasma center [T] - :type b_plasma_toroidal_on_axis: float - :param r_cp_top: Centrepost outer radius at the top [m] - :type r_cp_top: float - :param itart: TART (tight aspect ratio tokamak) switch (0 = standard, 1 = TART) - :type itart: int - :param i_cp_joints: Centrepost joints switch (1 = with sliding joints, 0 = without) - :type i_cp_joints: int - :param f_vforce_inboard: Inboard vertical tension fraction - :type f_vforce_inboard: float - - :returns: Tuple containing: + Parameters + ---------- + i_tf_sup : int + TF coil support type (1 = superconducting, 0 = resistive copper, 2 = resistive aluminium) + r_tf_wp_inboard_outer : float + Outer radius of the inboard winding pack [m] + r_tf_wp_inboard_inner : float + Inner radius of the inboard winding pack [m] + r_tf_outboard_in : float + Inner radius of the outboard leg [m] + dx_tf_wp_insulation : float + Thickness of winding pack ground insulation [m] + dx_tf_wp_insertion_gap : float + Thickness of winding pack insertion gap [m] + b_tf_inboard_peak_symmetric : float + Peak inboard magnetic field [T] + c_tf_total : float + Total current in TF coils [A] + n_tf_coils : int + Number of TF coils + dr_tf_plasma_case : float + Plasma-facing case thickness [m] + rmajor : float + Major radius of the plasma [m] + b_plasma_toroidal_on_axis : float + Toroidal magnetic field at plasma center [T] + r_cp_top : float + Centrepost outer radius at the top [m] + itart : int + TART (tight aspect ratio tokamak) switch (0 = standard, 1 = TART) + i_cp_joints : ints: int + Centrepost joints switch (1 = with sliding joints, 0 = without) + f_vforce_inboard : float + Inboard vertical tension fraction + + Returns + ------- + tuple[float, float, float, float] + Tuple containing: - cforce (float): Centering force per TF coil [N/m] - vforce (float): Inboard vertical tension [N] - vforce_outboard (float): Outboard vertical tension [N] - vforce_inboard_tot (float): Total inboard vertical force [N] - f_vforce_inboard (float): Inboard vertical tension fraction - :rtype: tuple[float, float, float, float] - - :raises: None - - :notes: - - This method computes the centering and vertical forces on the TF coil, as well as - the vacuum vessel stress during a quench and the resistance/volume for resistive magnets. - - The calculation depends on the coil support type and geometry. """ # Outer/inner WP radius removing the ground insulation layer and the insertion gap [m] @@ -2778,16 +2775,20 @@ def tf_field_and_force( @staticmethod def he_density(temp: float) -> float: - """Author : S. Kahn + """ Subroutine calculating temperature dependent helium density at 100 bar from fit using the following data, valid in [4-50] K Ref : R.D. McCarty, Adv. Cryo. Eng., 1990, 35, 1465-1475. - :param temp: Helium temperature [K] - :type temp: float + Parameters + ---------- + temp : float + Helium temperature [K] - :returns density: Heliyn density [kg/m3] - :type density: float + Returns + ------- + type + density: Heliyn density [kg/m3] """ # Fit range validation @@ -2817,17 +2818,21 @@ def he_density(temp: float) -> float: @staticmethod def he_cp(temp: float) -> float: - """Author : S. Kahn + """ Subroutine calculating temperature dependent thermal capacity at constant pressures at 100 Bar from fit using the following data valid in [4-50] K Ref : R.D. McCarty, Adv. Cryo. Eng., 1990, 35, 1465-1475. - :param temp: Helium temperature [K] - :type temp: float + Parameters + ---------- + temp : float + Helium temperature [K] - :return cp: Themal capacity at constant pressure [K/(kg.K)] - :type cp: float + Returns + ------- + : + Themal capacity at constant pressure [K/(kg.K)] """ # Fit range validation @@ -2860,17 +2865,21 @@ def he_cp(temp: float) -> float: @staticmethod def he_visco(temp: float) -> float: - """Author : S. Kahn + """ Subroutine calculating temperature dependent He viscosity at 100 Bar from fit using the following data, valid in [4-50] K Ref : V.D. Arp,; R.D. McCarty ; Friend, D.G., Technical Note 1334, National Institute of Standards and Technology, Boulder, CO, 1998, 0. - :param temp: Helium temperature [K] - :type temp: float + Parameters + ---------- + temp : float + Helium temperature [K] - :return visco: Themal capacity at constant pressure [Pa.s] - :type visco: float + Returns + ------- + : + Themal capacity at constant pressure [Pa.s] """ if temp < 4.0e0 or temp > 50.0e0: @@ -2900,16 +2909,20 @@ def he_visco(temp: float) -> float: @staticmethod def he_th_cond(temp: float) -> float: - """Author : S. Kahn + """ Subroutine calculating temperature dependent He thermal conductivity at 100 Bar from fit using the following data, valid in [4-50] K Ref : B.A. Hands B.A., Cryogenics, 1981, 21, 12, 697-703. - :param temp: Helium temperature [K] - :type temp: float + Parameters + ---------- + temp : float + Helium temperature [K] - :return th_cond: Themal conductivity [W/(m.K)] - :type th_cond: float + Returns + ------- + : + Themal conductivity [W/(m.K)] """ # Fit range validation @@ -2953,14 +2966,18 @@ def he_th_cond(temp: float) -> float: @staticmethod def al_th_cond(temp: float) -> float: - """Author : S. Kahn + """ Subroutine calculating temperature dependent Al thermal conductivity - :param temp: Helium temperature [K] - :type temp: float + Parameters + ---------- + temp : float + Helium temperature [K] - :return th_cond: Themal conductivity [W/(m.K)] - :type th_cond: float + Returns + ------- + : + Themal conductivity [W/(m.K)] """ # Fiting range verification @@ -3005,43 +3022,46 @@ def tf_coil_self_inductance( r_tf_outboard_mid: float, r_tf_inboard_mid: float, ) -> float: - """ - Calculates the self-inductance of a TF coil. + """Calculates the self-inductance of a TF coil. This function numerically integrates the magnetic field energy to estimate the self-inductance of a toroidal field (TF) coil, using the geometry defined by the arc points and the inboard thickness. - :param dr_tf_inboard: Radial thickness of the inboard leg of the TF coil [m]. - :type dr_tf_inboard: float - :param r_tf_arc: Array of R coordinates of arc points (length 5). - :type r_tf_arc: numpy.ndarray - :param z_tf_arc: Array of Z coordinates of arc points (length 5). - :type z_tf_arc: numpy.ndarray - :param itart: TART (tight aspect ratio tokamak) switch (0 = standard, 1 = TART). - :type itart: int - :param i_tf_shape: TF coil shape selection switch (1 = D-shape, 2 = picture frame). - :type i_tf_shape: int - :param z_tf_inside_half: Maximum inboard edge height [m]. - :type z_tf_inside_half: float - :param dr_tf_outboard: Radial thickness of the outboard leg of the TF coil [m]. - :type dr_tf_outboard: float - :param r_tf_outboard_mid: Mid-plane radius of the outboard leg of the TF coil [m]. - :type r_tf_outboard_mid: float - :param r_tf_inboard_mid: Mid-plane radius of the inboard leg of the TF coil [m]. - :type r_tf_inboard_mid: float - - :returns: Self-inductance of the TF coil [H]. - :rtype: float - - :notes: + Parameters + ---------- + dr_tf_inboard : float + Radial thickness of the inboard leg of the TF coil [m]. + r_tf_arc : numpy.ndarray + Array of R coordinates of arc points (length 5). + z_tf_arc : numpy.ndarray + Array of Z coordinates of arc points (length 5). + itart : int + TART (tight aspect ratio tokamak) switch (0 = standard, 1 = TART). + i_tf_shape : int + TF coil shape selection switch (1 = D-shape, 2 = picture frame). + z_tf_inside_half : float + Maximum inboard edge height [m]. + dr_tf_outboard : float + Radial thickness of the outboard leg of the TF coil [m]. + r_tf_outboard_mid : float + Mid-plane radius of the outboard leg of the TF coil [m]. + r_tf_inboard_mid : float + Mid-plane radius of the inboard leg of the TF coil [m]. + + Returns + ------- + float + Self-inductance of the TF coil [H]. + + Notes + ----- For the D-shaped coil (i_tf_shape == 1) in a standard (non-TART) configuration (itart == 0), the integration is performed over the coil cross-section, including both the inboard and outboard arcs. The field is computed for unit current, and the contribution from the coil's own cross-sectional area is included by taking the field as B(r)/2. Top/bottom symmetry is assumed. - :references: """ NINTERVALS = 100 @@ -3219,15 +3239,146 @@ def stresscl( ): """TF coil stress routine - - author: P J Knight, CCFE, Culham Science Centre - author: J Morris, CCFE, Culham Science Centre - author: S Kahn, CCFE, Culham Science Centre - author: J Galambos, FEDC/ORNL - This subroutine sets up the stress calculations for the TF coil set. PROCESS Superconducting TF Coil Model, J. Morris, CCFE, 1st May 2014 + + Parameters + ---------- + n_tf_layer : + + n_radial_array : + + n_tf_wp_stress_layers : + + i_tf_bucking : + + r_tf_inboard_in : + + dr_bore : + + z_tf_inside_half : + + f_z_cs_tf_internal : + + dr_cs : + + i_tf_inside_cs : + + dr_tf_inboard : + + dr_cs_tf_gap : + + i_pf_conductor : + + j_cs_flat_top_end : + + j_cs_pulse_start : + + c_pf_coil_turn_peak_input : + + n_pf_coils_in_group : + + f_dr_dz_cs_turn : + + radius_cs_turn_corners : + + f_a_cs_turn_steel : + + eyoung_steel : + + poisson_steel : + + eyoung_cond_axial : + + poisson_cond_axial : + + eyoung_cond_trans : + + poisson_cond_trans : + + eyoung_ins : + + poisson_ins : + + dx_tf_turn_insulation : + + eyoung_copper : + + poisson_copper : + + i_tf_sup : + + eyoung_res_tf_buck : + + r_tf_wp_inboard_inner : + + tan_theta_coil : + + rad_tf_coil_inboard_toroidal_half : + + r_tf_wp_inboard_outer : + + a_tf_coil_inboard_steel : + + a_tf_plasma_case : + + a_tf_coil_nose_case : + + dx_tf_wp_insertion_gap : + + dx_tf_wp_insulation : + + n_tf_coil_turns : + + i_tf_turns_integer : + + dx_tf_turn_cable_space_average : + + dr_tf_turn_cable_space : + + dia_tf_turn_coolant_channel : + + f_a_tf_turn_cable_copper : + + dx_tf_turn_steel : + + dx_tf_side_case_average : + + dx_tf_wp_toroidal_average : + + a_tf_coil_inboard_insulation : + + a_tf_wp_steel : + + a_tf_wp_conductor : + + a_tf_wp_with_insulation : + + eyoung_al : + + poisson_al : + + fcoolcp : + + n_tf_graded_layers : + + c_tf_total : + + dr_tf_plasma_case : + + i_tf_stress_model : + + vforce_inboard_tot : + + i_tf_tresca : + + a_tf_coil_inboard_case : + + vforce : + + a_tf_turn_steel : + """ jeff = np.zeros((n_tf_layer,)) # Effective current density [A/m2] @@ -3533,7 +3684,7 @@ def stresscl( # WP effective insulation thickness (SC only) [m] # include groundwall insulation + insertion gap in tfcoil_variables.dx_tf_turn_insulation - # inertion gap is tfcoil_variables.dx_tf_wp_insertion_gap on 4 sides + # insertion gap is tfcoil_variables.dx_tf_wp_insertion_gap on 4 sides t_ins_eff = ( dx_tf_turn_insulation + (dx_tf_wp_insertion_gap + dx_tf_wp_insulation) / n_tf_coil_turns @@ -4092,7 +4243,65 @@ def out_stress( """Subroutine showing the writing the TF midplane stress analysis in the output file and the stress distribution in the SIG_TF.json file used to plot stress distributions - Author : S. Kahn + + Parameters + ---------- + sig_tf_r_max : + + sig_tf_t_max : + + sig_tf_z_max : + + sig_tf_vmises_max : + + s_shear_tf_peak : + + deflect : + + eyoung_axial : + + eyoung_trans : + + eyoung_wp_axial : + + eyoung_wp_trans : + + poisson_wp_trans : + + radial_array : + + s_shear_cea_tf_cond : + + poisson_wp_axial : + + sig_tf_r : + + sig_tf_smeared_r : + + sig_tf_smeared_t : + + sig_tf_smeared_z : + + sig_tf_t : + + s_shear_tf : + + sig_tf_vmises : + + sig_tf_z : + + str_tf_r : + + str_tf_t : + + str_tf_z : + + n_radial_array : + + n_tf_bucking : + + sig_tf_wp_av_z : + """ def table_format_arrays(a, mult=1, delim="\t\t"): @@ -4370,8 +4579,6 @@ def eyoung_parallel( eyoung_j_1, a_1, poisson_j_perp_1, eyoung_j_2, a_2, poisson_j_perp_2 ): """ - Author : C. Swanson, PPPL - January 2022 See Issue #1205 for derivation PDF This subroutine gives the smeared elastic properties of two members that are carrying a force in parallel with each other. @@ -4403,6 +4610,21 @@ def eyoung_parallel( ... etc. So that tripletOUT would eventually have the smeared properties of the total composite member. + + Parameters + ---------- + eyoung_j_1 : + + a_1 : + + poisson_j_perp_1 : + + eyoung_j_2 : + + a_2 : + + poisson_j_perp_2 : + """ poisson_j_perp_3 = (poisson_j_perp_1 * a_1 + poisson_j_perp_2 * a_2) / (a_1 + a_2) eyoung_j_3 = (eyoung_j_1 * a_1 + eyoung_j_2 * a_2) / (a_1 + a_2) @@ -4414,19 +4636,29 @@ def eyoung_parallel( @numba.njit(cache=True) def sigvm(sx: float, sy: float, sz: float, txy: float, txz: float, tyz: float) -> float: """Calculates Von Mises stress in a TF coil - author: P J Knight, CCFE, Culham Science Centre - author: B Reimer, FEDC + This routine calculates the Von Mises combination of stresses (Pa) in a TF coil. - :param sx: In-plane stress in X direction [Pa] - :param sy: In-plane stress in Y direction [Pa] - :param sz: In-plane stress in Z direction [Pa] - :param txy: Out-of-plane stress in X-Y plane [Pa] - :param txz: Out-of-plane stress in X-Z plane [Pa] - :param tyz: Out-of-plane stress in Y-Z plane [Pa] - - :returns: Von Mises combination of stresses (Pa) in a TF coil. + Parameters + ---------- + sx : + In-plane stress in X direction [Pa] + sy : + In-plane stress in Y direction [Pa] + sz : + In-plane stress in Z direction [Pa] + txy : + Out-of-plane stress in X-Y plane [Pa] + txz : + Out-of-plane stress in X-Z plane [Pa] + tyz : + Out-of-plane stress in Y-Z plane [Pa] + + Returns + ------- + : + Von Mises combination of stresses (Pa) in a TF coil. """ return np.sqrt( @@ -4453,8 +4685,7 @@ def extended_plane_strain( n_radial_array, i_tf_bucking, ): - """Author : C. Swanson, PPPL and S. Kahn, CCFE - September 2021 + """ There is a writeup of the derivation of this model on the gitlab server. https://git.ccfe.ac.uk/process/process/-/issues/1414 This surboutine estimates the radial displacement, stresses, and strains of @@ -4479,6 +4710,29 @@ def extended_plane_strain( radius, and is transformed via matrix multiplication into those A,B values at other radii. The constraints are inner products with this vector, and so when stacked form a matrix to invert. + + Parameters + ---------- + nu_t : + + nu_zt : + + ey_t : + + ey_z : + + rad : + + d_curr : + + v_force : + + nlayers : + + n_radial_array : + + i_tf_bucking : + """ # outputs sigr = np.zeros((n_radial_array * nlayers,)) @@ -4940,15 +5194,28 @@ def extended_plane_strain( def plane_stress(nu, rad, ey, j, nlayers, n_radial_array): """Calculates the stresses in a superconductor TF coil inboard leg at the midplane using the plain stress approximation - author: P J Knight, CCFE, Culham Science Centre - author: J Morris, CCFE, Culham Science Centre - author: S Kahn, CCFE, Culham Science Centre + This routine calculates the stresses in a superconductor TF coil inboard leg at midplane.

    A 2 layer plane stress model developed by CCFE is used. The first layer is the steel case inboard of the winding pack, and the second layer is the winding pack itself. PROCESS Superconducting TF Coil Model, J. Morris, CCFE, 1st May 2014 + + Parameters + ---------- + nu : + + rad : + + ey : + + j : + + nlayers : + + n_radial_array : + """ alpha = np.zeros((nlayers,)) beta = np.zeros((nlayers,)) @@ -4985,7 +5252,7 @@ def plane_stress(nu, rad, ey, j, nlayers, n_radial_array): kk = ey / (1 - nu**2) - # Lorentz forces parametrisation coeficients (array equation) + # Lorentz forces parameterisation coeficients (array equation) alpha = 0.5e0 * constants.RMU0 * j**2 / kk inner_layer_curr = 0.0e0 @@ -5147,8 +5414,6 @@ def plane_stress(nu, rad, ey, j, nlayers, n_radial_array): @numba.njit(cache=True) def eyoung_parallel_array(n, eyoung_j_in, a_in, poisson_j_perp_in): """ - Author : C. Swanson, PPPL - January 2022 See Issue #1205 for derivation PDF This subroutine gives the smeared elastic properties of two members that are carrying a force in parallel with each other. @@ -5180,6 +5445,17 @@ def eyoung_parallel_array(n, eyoung_j_in, a_in, poisson_j_perp_in): ... etc. So that tripletOUT would eventually have the smeared properties of the total composite member. + + Parameters + ---------- + n : + + eyoung_j_in : + + a_in : + + poisson_j_perp_in : + """ eyoung_j_out = 0 a_out = 0 @@ -5202,8 +5478,6 @@ def eyoung_parallel_array(n, eyoung_j_in, a_in, poisson_j_perp_in): @numba.njit(cache=True) def eyoung_t_nested_squares(n, eyoung_j_in, l_in, poisson_j_perp_in): """ - Author : C. Swanson, PPPL - January 2022 This subroutine gives the smeared transverse elastic properties of n members whose cross sectional areas are nested squares. It uses the subroutines eyoung_series and @@ -5215,6 +5489,17 @@ def eyoung_t_nested_squares(n, eyoung_j_in, l_in, poisson_j_perp_in): documentation) is composed of several layers under stress in series, and each leg is under stress in parallel with every other leg. + + Parameters + ---------- + n : + + eyoung_j_in : + + l_in : + + poisson_j_perp_in : + """ eyoung_j_working = np.zeros((n,)) l_working = np.zeros((n,)) @@ -5271,8 +5556,6 @@ def eyoung_t_nested_squares(n, eyoung_j_in, l_in, poisson_j_perp_in): @numba.njit(cache=True) def eyoung_series(eyoung_j_1, l_1, poisson_j_perp_1, eyoung_j_2, l_2, poisson_j_perp_2): """ - Author : C. Swanson, PPPL - January 2022 See Issue #1205 for derivation PDF This subroutine gives the smeared elastic properties of two members that are carrying a force in series with each other. @@ -5308,6 +5591,21 @@ def eyoung_series(eyoung_j_1, l_1, poisson_j_perp_1, eyoung_j_2, l_2, poisson_j_ ... etc. So that tripletOUT would eventually have the smeared properties of the total composite member. + + Parameters + ---------- + eyoung_j_1 : + + l_1 : + + poisson_j_perp_1 : + + eyoung_j_2 : + + l_2 : + + poisson_j_perp_2 : + """ if eyoung_j_1 * eyoung_j_2 == 0: diff --git a/process/vacuum.py b/process/vacuum.py index 3f98b8d0c5..45f210b50c 100644 --- a/process/vacuum.py +++ b/process/vacuum.py @@ -22,23 +22,23 @@ class Vacuum: """Module containing vacuum system routines - author: P J Knight, CCFE, Culham Science Centre This module contains routines for calculating the parameters of the vacuum system for a fusion power plant. """ - def __init__(self) -> None: + def __init__(self): self.outfile: int = constants.NOUT - def run(self, output: bool) -> None: + def run(self, output: bool): """Routine to call the vacuum module - author: P J Knight, CCFE, Culham Science Centre - This routine calls the main vacuum package. - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output: + indicate whether output should be written to the output file, or not + """ # (should be) NBI gas load (deuterons/second) @@ -102,13 +102,17 @@ def run(self, output: bool) -> None: def vacuum_simple(self, output) -> float: """Simple model of vacuum pumping system - author: MD Kovari, CCFE, Culham Science Centre - :param output: indicate whether output should be written to the output file, or not - :type output: boolean - :return npump: number of pumps for pumpdown and steady-state - :rtype: float + Parameters + ---------- + output : + + Returns + ------- + npump: + number of pumps for pumpdown and steady-state + indicate whether output should be written to the output file, or not """ # Steady-state model (super simple) @@ -222,67 +226,49 @@ def vacuum( output, ): """Routine to calculate the parameters of the vacuum system - author: P J Knight, CCFE, Culham Science Centre - author: J Haines, FEDC (originator) - author: P Dubois, LLNL - author: J Galambos, ORNL - author: P C Shipe, ORNL - - This routine calculates the parameters of the vacuum system. - - :param pfusmw: Fusion power (MW) - :type pfusmw: float - - :param r0: Major radius (m) - :type r0: float - - :param aw: Minor radius (m) - :type aw: float - - :param dsol: Scrape-off layer average width (m) - :type : float - - :param plasma_sarea: Plasma surface area (m2) - :type : float - - :param plasma_vol: Plasma volume (m3) - :type : float - - :param thshldo: Outboard shield thickness (m) - :type : float - - :param thshldi: Inboard shield thickness (m) - :type : float - - :param thtf: TF coil thickness (m) - :type : float - - :param ritf: Radius of inboard TF leg point nearest plasma (m) - :type : float - :param tfno: Number of TF coils - :type : int - - :param t_plant_pulse_dwell: Dwell time between pulses (s) - :type : float - - :param nplasma: Plasma density (m**-3) - :type : float - - :param ndiv: Number of divertors with pumping (single null = 1, double null = 2 if pumping provided at both locations) - :type : int - - :param qtorus: Gas load from NBI (deuterons/second) - :type : float - - :param gasld: Total D-T gas load (kg/s) - :type : float - - :param output: indicate whether output should be written to the output file, or not - :type output: boolean - - :returns: - - pumpn (`float`) - Number of high vacuum pumps + Parameters + ---------- + pfusmw : float + Fusion power (MW) + r0 : float + Major radius (m) + aw : float + Minor radius (m) + dsol : + Scrape-off layer average width (m) + plasma_sarea : + Plasma surface area (m2) + plasma_vol : + Plasma volume (m3) + thshldo : + Outboard shield thickness (m) + thshldi : + Inboard shield thickness (m) + thtf : + TF coil thickness (m) + ritf : + Radius of inboard TF leg point nearest plasma (m) + n_tf_coils : + Number of TF coils + t_plant_pulse_dwell : + Dwell time between pulses (s) + nplasma : + Plasma density (m**-3) + ndiv : + Number of divertors with pumping (single null = 1, double null = 2 if pumping provided at both locations) + qtorus : + Gas load from NBI (deuterons/second) + gasld : + Total D-T gas load (kg/s) + output : + indicate whether output should be written to the output file, or not + + + Returns + ------- + : + pumpn (`float`) - Number of high vacuum pumps - nduct (`int`) - Number of ducts - dlscalc (`float`) - Duct-length equivalent for costing purposes (m) - mvdsh (`float`) - Mass of a single vacuum duct shield (kg) @@ -409,7 +395,7 @@ def vacuum( l3 = 2.0e0 # Length of ducts from elbow to hi-vac pumps (m) ltot = l1 + l2 + l3 - # ceff and d require initialising to small positive values; they're not + # ceff and d require initialising too small positive values; they're not # always overwritten in the following loop and can cause div by 0 errors # otherwise ceff = np.full(4, 1e-6) @@ -732,10 +718,10 @@ def vacuum( class VacuumVessel: """Class containing vacuum vessel routines""" - def __init__(self) -> None: + def __init__(self): self.outfile = constants.NOUT - def run(self) -> None: + def run(self): blanket_library.dz_vv_half = self.calculate_vessel_half_height( z_tf_inside_half=build_variables.z_tf_inside_half, dz_shld_vv_gap=build_variables.dz_shld_vv_gap, @@ -804,7 +790,33 @@ def calculate_vessel_half_height( dr_fw_inboard: float, dr_fw_outboard: float, ) -> float: - """Calculate vacuum vessel internal half-height (m)""" + """Calculate vacuum vessel internal half-height (m) + + Parameters + ---------- + z_tf_inside_half: + + dz_shld_vv_gap: + + dz_vv_lower: + + n_divertors: int : + + dz_blkt_upper: + + dz_shld_upper: + + z_plasma_xpoint_upper: + + dr_fw_plasma_gap_inboard: + + dr_fw_plasma_gap_outboard: + + dr_fw_inboard: + + dr_fw_outboard: + + """ z_bottom = z_tf_inside_half - dz_shld_vv_gap - dz_vv_lower @@ -835,7 +847,25 @@ def calculate_dshaped_vessel_volumes( dz_vv_upper: float, dz_vv_lower: float, ) -> tuple[float, float, float]: - """Calculate volumes of D-shaped vacuum vessel segments""" + """Calculate volumes of D-shaped vacuum vessel segments + + Parameters + ---------- + r_shld_inboard_inner: + + r_shld_outboard_outer: + + dz_vv_half: + + dr_vv_inboard: + + dr_vv_outboard: + + dz_vv_upper: + + dz_vv_lower: + + """ r_1 = r_shld_inboard_inner r_2 = r_shld_outboard_outer - r_1 @@ -868,7 +898,31 @@ def calculate_elliptical_vessel_volumes( dz_vv_upper: float, dz_vv_lower: float, ) -> tuple[float, float, float]: - """Calculate volumes of elliptical vacuum vessel segments""" + """Calculate volumes of elliptical vacuum vessel segments + + Parameters + ---------- + rmajor: + + rminor: + + triang: + + r_shld_inboard_inner: + + r_shld_outboard_outer: + + dz_vv_half: + + dr_vv_inboard: + + dr_vv_outboard: + + dz_vv_upper: + + dz_vv_lower: + + """ # Major radius to centre of inboard and outboard ellipses (m) # (coincident in radius with top of plasma) r_1 = rmajor - rminor * triang @@ -893,7 +947,7 @@ def calculate_elliptical_vessel_volumes( ) return vol_vv_inboard, vol_vv_outboard, vol_vv - def output_vv_areas_and_volumes(self) -> None: + def output_vv_areas_and_volumes(self): """Output shield areas and volumes to log.""" po.oheadr(self.outfile, "Vacuum Vessel Areas and Volumes") diff --git a/process/water_use.py b/process/water_use.py index bf57fc3bbe..41e64be571 100644 --- a/process/water_use.py +++ b/process/water_use.py @@ -12,14 +12,13 @@ def __init__(self): self.outfile = constants.NOUT def run(self, output: bool): - """ - Routine to call the water usage calculation routines. - author: R Chapman, UKAEA - + """Routine to call the water usage calculation routines. This routine calls the different water usage routines. - :param output: indicate whether output should be written to the output file, or not - :type output: boolean + Parameters + ---------- + output : + indicate whether output should be written to the output file, or not """ rejected_heat = heat_transport_variables.p_plant_primary_heat_mw * ( 1 - heat_transport_variables.eta_turbine @@ -51,10 +50,13 @@ def run(self, output: bool): def cooling_towers(self, wastetherm: float, output: bool): """Water used in cooling towers - author: R Chapman, UKAEA - outfile : input integer : Fortran output unit identifier - iprint : input integer : Switch to write output (1=yes) - wastetherm : input real : thermal energy (MJ) to be cooled by this system + + Parameters + ---------- + wastetherm: + thermal energy (MJ) to be cooled by this system + output: + """ water_usage_variables.evapratio = 1.0e0 - ( ( @@ -83,7 +85,7 @@ def cooling_towers(self, wastetherm: float, output: bool): # find water withdrawn from external source water_usage_variables.waterusetower = 1.4e0 * water_usage_variables.evapvol - # Estimated as a ratio to evaporated water (averaged across obervered dataset) + # Estimated as a ratio to evaporated water (averaged across observed dataset) # as per Diehl et al. USGS Report 2014-5184, http://dx.doi.org/10.3133/sir20145184 # end break @@ -105,11 +107,13 @@ def cooling_water_body(self, wastetherm: float, output: bool): temperatures, windspeeds, and heat loading: http://pubs.usgs.gov/sir/2013/5188/appendix/sir2013-5188_appendix4_fews_version_3.104.xlsx - author: R Chapman, UKAEA - outfile : input integer : Fortran output unit identifier - iprint : input integer : Switch to write output (1=yes) - icool: input integer : switch between different water-body cooling options - wastetherm : input real : thermal energy (MJ) to be cooled by this system + + Parameters + ---------- + wastetherm: + thermal energy (MJ) to be cooled by this system + output: + """ evapsum = 0.0e0 @@ -258,7 +262,7 @@ def cooling_water_body(self, wastetherm: float, output: bool): evapsum = evapsum / icool # water volume withdrawn from external source depends on recirculation or 'once-through' system choice - # Estimated as a ratio to evaporated water (averaged across obervered dataset) + # Estimated as a ratio to evaporated water (averaged across observed dataset) # as per Diehl et al. USGS Report 2014-5184, http://dx.doi.org/10.3133/sir20145184 # recirculating water system: diff --git a/pyproject.toml b/pyproject.toml index bfe99f1b7d..2fbaee4ad8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -69,9 +69,11 @@ docs = [ "mkdocs-glightbox >= 0.3.4", "pymdown-extensions>=6.3", "bokeh>=3.4.0,<4", - "mkdocstrings==0.18.0", + "mkdocstrings[python]==1.0.3", "Jinja2>=3.0", "mkdocs-jupyter>=0.24", + "mkdocs-gen-files", + "mkdocs-literate-nav", ] lint = ["pre-commit>=2.16.0", "ruff==0.9.3", "ty"] all = ["process[test,docs,lint,examples,plotly]"] diff --git a/scripts/vardes.jinja2 b/scripts/vardes.jinja2 deleted file mode 100644 index 780fed61ab..0000000000 --- a/scripts/vardes.jinja2 +++ /dev/null @@ -1,35 +0,0 @@ -# PROCESS Variable Descriptions ---- -## Introduction -Variables marked with an **\*** are private variables and cannot be accessed -outside of their Fortran module scope. - -The PROCESS convention on inputs dictates that module variables which can be set from the -input file should be initialised in a routine called `init_mod` where `mod` is replaced with the -Fortran module name. However, some variables can also be initialised here too and will register as inputs -when they are not. - -Output types signify that these module variables are set by models. This does necessarily mean an "output" -will appear in the MFile/Outfile. ---- -{% for mod, module_vars in mods.items() %} -## {{ mod }} - - - - - - - - - {% for var in module_vars %} - - - - - {% if var.initial is not none %}{% else %}{% endif %} - - - {% endfor %} -
    NameTypeDatatypeDefault ValueDescription
    {{ var.name }}{% if var.private %}*{% endif %}{{ var.typ }}{{ var.datatype }}{{ var.initial }}-{{ var.description }}
    -{% endfor %} diff --git a/scripts/vardes.py b/scripts/vardes.py deleted file mode 100644 index 34da528b32..0000000000 --- a/scripts/vardes.py +++ /dev/null @@ -1,71 +0,0 @@ -import dataclasses -import pickle -from enum import Enum -from pathlib import Path -from typing import Any - -import jinja2 - - -class VariableTypes(str, Enum): - PARAMETER = "Parameter" - INPUT = "Input" - OUTPUT = "Output" - VARIABLE = "Variable" - - def __str__(self) -> str: - return self.value - - -@dataclasses.dataclass -class FortranVariable: - name: str - module: str - description: str - typ: VariableTypes - datatype: str - initial: Any - private: bool - - -def get_variables_and_modules(ford_project: Path): - with open(ford_project, "rb") as ford_pickle: - ford_project = pickle.load(ford_pickle) - - variables: list[FortranVariable] = [] - modules: list[str] = [] - - for mod in ford_project.modules: - for var in mod.variables: - permission = "".join(var.permission).lower() - modules.append(mod.name.lower()) - variables.append( - FortranVariable( - var.name.lower(), - mod.name.lower(), - var.doc, - ( - VariableTypes.PARAMETER - if var.parameter - else VariableTypes.VARIABLE - ), - var.vartype, - var.initial, - permission == "private", - ) - ) - - return variables, modules - - -if __name__ == "__main__": - mods = {"vardes will be fixed in https://github.com/ukaea/PROCESS/issues/3834": []} - - loader = jinja2.FileSystemLoader(searchpath=Path(__file__).resolve().parent) - env = jinja2.Environment(loader=loader) - - vardes_template = env.get_template("vardes.jinja2") - - (Path(__file__).resolve().parent / "../documentation/io/vardes.md").write_text( - vardes_template.render(mods=mods) - ) diff --git a/tests/conftest.py b/tests/conftest.py index 5549efd4b2..743e74515a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -157,7 +157,6 @@ def reinitialise_error_module(): If a subroutine raises an error and writes to error variables, this should be cleaned up when the test finishes to prevent any side-effects. - """ # TODO Perhaps this should be autoused by all tests? Specify use explicitly # for now for known error-raisers diff --git a/tests/examples/test_examples.py b/tests/examples/test_examples.py index adcf4934d4..b0229a419c 100644 --- a/tests/examples/test_examples.py +++ b/tests/examples/test_examples.py @@ -53,7 +53,6 @@ def test_introductory_examples(examples_temp_data): introduction.ex.py uses temp dirs to clean up any produced files itself. :param examples_temp_data: temporary dir containing examples files :type examples_temp_data: Path - """ example_notebook_location = _get_location(examples_temp_data, "introduction") with testbook(example_notebook_location, execute=True, timeout=600): diff --git a/tests/regression/regression_test_assets.py b/tests/regression/regression_test_assets.py index 7ff8ee3fa1..90ea110c92 100644 --- a/tests/regression/regression_test_assets.py +++ b/tests/regression/regression_test_assets.py @@ -26,7 +26,7 @@ class RegressionTestAssetCollector: remote_repository_owner = "timothy-nunn" remote_repository_repo = "process-tracking-data" - def __init__(self) -> None: + def __init__(self): self._hashes = self._git_commit_hashes() self._tracked_mfiles = self._get_tracked_mfiles() diff --git a/tests/regression/test_process_input_files.py b/tests/regression/test_process_input_files.py index fb69c261f6..6a88531ea6 100644 --- a/tests/regression/test_process_input_files.py +++ b/tests/regression/test_process_input_files.py @@ -44,7 +44,7 @@ class MFileVariableDifference: class RegressionTestScenario: - def __init__(self, input_file: Path) -> None: + def __init__(self, input_file: Path): """ Represents an input scenario (input file) to PROCESS that is to be regression tested. diff --git a/tests/system_check.py b/tests/system_check.py index 5cd540ff34..48c9752243 100644 --- a/tests/system_check.py +++ b/tests/system_check.py @@ -3,7 +3,7 @@ not surprising nor massively concerning for numeric scientific software. However, it can be problematic for tests where the results we assert on change from system to system. -We identify systems that will be succeptible to these tiny changes and skip the tests so as not to +We identify systems that will be susceptible to these tiny changes and skip the tests so as not to create failures. We do this by checking the users systems results on an algorithm compared to some known result. This algorithm solves a system of equations that is very ill-conditioned where tiny numeric differences diff --git a/tests/unit/test_ccfe_hcpb.py b/tests/unit/test_ccfe_hcpb.py index bbcd299a6c..74a33afc1c 100644 --- a/tests/unit/test_ccfe_hcpb.py +++ b/tests/unit/test_ccfe_hcpb.py @@ -538,7 +538,6 @@ def test_nuclear_heating_blanket(nuclearheatingblanketparam, ccfe_hcpb): :param nuclearheatingblanketparam: the data used to mock and assert in this test. :type nuclearheatingblanketparam: nuclearheatingblanketparam - """ p_blkt_nuclear_heat_total_mw, exp_blanket = ccfe_hcpb.nuclear_heating_blanket( @@ -632,7 +631,6 @@ def test_nuclear_heating_shield(nuclearheatingshieldparam, ccfe_hcpb): :param nuclearheatingshieldparam: the data used to mock and assert in this test. :type nuclearheatingshieldparam: nuclearheatingshieldparam - """ p_shld_nuclear_heat_mw, exp_shield1, exp_shield2, shld_u_nuc_heating = ( diff --git a/tests/unit/test_cs_fatigue.py b/tests/unit/test_cs_fatigue.py index ec7b2a73ae..1f7bf01259 100644 --- a/tests/unit/test_cs_fatigue.py +++ b/tests/unit/test_cs_fatigue.py @@ -109,7 +109,6 @@ def test_embedded_stress_intensity_factor( :param c: crack length (w - direction). :type c: float - """ k = cs_fatigue_python.embedded_stress_intensity_factor(hoop_stress, t, w, a, c, phi) @@ -149,7 +148,6 @@ def test_surface_stress_intensity_factor( :param c: crack length (w - direction). :type c: float - """ k = cs_fatigue_python.surface_stress_intensity_factor(hoop_stress, t, w, a, c, phi) diff --git a/tests/unit/test_plasma_geom.py b/tests/unit/test_plasma_geom.py index d71ad417ec..eeef55a4da 100644 --- a/tests/unit/test_plasma_geom.py +++ b/tests/unit/test_plasma_geom.py @@ -225,7 +225,6 @@ def test_fvol(r, a, kap, tri, expected_fvol): :param expected_fvol: expected result of the function. :type expected_fvol: float - """ fvol = pg.fvol(r, a, kap, tri) @@ -257,7 +256,6 @@ def test_xsect0(a, kap, tri, expected_xsect0): :param expected_xsect0: expected result of the function. :type expected_xsect0: float - """ xsect0 = pg.xsect0(a, kap, tri) diff --git a/tests/unit/test_sctfcoil.py b/tests/unit/test_sctfcoil.py index d276f3f020..eeff158314 100644 --- a/tests/unit/test_sctfcoil.py +++ b/tests/unit/test_sctfcoil.py @@ -779,7 +779,6 @@ def test_superconducting_tf_wp_geometry(tfwpgeomparam, sctfcoil): :param tfwpgeomparam: the data used to mock and assert in this test. :type tfwpgeomparam: tfwpgeomparam - """ ( @@ -951,7 +950,6 @@ def test_superconducting_tf_case_geometry(tfcasegeomparam, sctfcoil): :param tfcasegeomparam: the data used to mock and assert in this test. :type tfcasegeomparam: tfcasegeomparam - """ ( a_tf_coil_inboard_case, diff --git a/tests/unit/test_shield.py b/tests/unit/test_shield.py index a13cbf8dfe..8c67048691 100644 --- a/tests/unit/test_shield.py +++ b/tests/unit/test_shield.py @@ -58,7 +58,6 @@ def test_elliptical_shield_volumes(shield, elliptical_shield_volumes, expected): :param elliptical_shield_volumes: input parameters for the function :type elliptical_shield_volumes: EllipticalShieldVolumes - """ vol_shield_inboard, vol_shield_outboard, vol_shield = ( @@ -121,7 +120,6 @@ def test_elliptical_shield_areas(shield, elliptical_shield_areas, expected): :param elliptical_shield_areas: input parameters for the function :type elliptical_shield_areas: EllipticalShieldAreas - """ a_shield_inboard, a_shield_outboard, a_shield = ( @@ -189,7 +187,6 @@ def test_dshaped_shield_volumes(shield, dshaped_shield_volumes, expected): :param dshaped_shield_volumes: input parameters for the function :type dshaped_shield_volumes: DShapedShieldVolumes - """ vol_shield_inboard, vol_shield_outboard, vol_shield = ( @@ -257,7 +254,6 @@ def test_dshaped_shield_areas(shield, dshaped_shield_areas, expected): :param dshaped_shield_areas: input parameters for the function :type dshaped_shield_areas: DShapedShieldAreas - """ a_shield_inboard, a_shield_outboard, a_shield = ( diff --git a/tests/unit/test_vacuum.py b/tests/unit/test_vacuum.py index 387f19c7bf..63298880a8 100644 --- a/tests/unit/test_vacuum.py +++ b/tests/unit/test_vacuum.py @@ -166,7 +166,6 @@ def test_elliptical_vessel_volumes(vacuum_vessel, elliptical_vessel_volumes, exp :param elliptical_vessel_volumes: input parameters for the function :type elliptical_vessel_volumes: EllipticalVesselVolumes - """ vol_vv_inboard, vol_vv_outboard, vol_vv = ( @@ -225,7 +224,6 @@ def test_dshaped_vessel_volumes(vacuum_vessel, dshaped_vessel_volumes, expected) :param dshaped_vessel_volumes: input parameters for the function :type dshaped_vessel_volumes: DShapedVesselVolumes - """ vol_vv_inboard, vol_vv_outboard, vol_vv = ( diff --git a/tracking/tracking_data.py b/tracking/tracking_data.py index 02889eb708..8a0e8bfa54 100644 --- a/tracking/tracking_data.py +++ b/tracking/tracking_data.py @@ -145,7 +145,7 @@ class TrackingFile: e.g. starfire_MFILE--