Skip to content

Commit 0e08d7f

Browse files
πŸ‘½ ⬆️ Upgrade process to open source version (#2522)
* 🚧 First attempt at updating process to open source version * πŸ‘½οΈ Data removal/moved * πŸ‘½οΈ Non existant filepath changed * 🎨 Add back install script * 🎨 New url * 🎨 Main * πŸ› Working env and process for OS version * 🎨 Update logflush * βœ… Fix tests * 🚨 Comment out thermalshields * πŸ› Resolve conflict * WIP: Python API to PROCESS (#2616) * πŸ‘½οΈ Data removal/moved * πŸ‘½οΈ Non existant filepath changed * add NLopt version correction to install-process.sh * fix PROCESS radial build plot * fix PROCESS plotting better * first pass PROCESS inputs * first pass PROCESS inputs * formatting * finish constraint equations * iteration variables * iteration variables * iteration variables * start on bounds * to_invariable * bounds * fix constraints and change input values * start adding starting point and change dr_tk_cas etc * add fatigue variables * fix PROCESS to run but problems with pulse length and BB pumping power * slight progress * some cleanup * still not there * PROCESS documentation no longer has teh descriptions of ixc and icc RIP * PROCESS documentation no longer has teh descriptions of ixc and icc RIP * PROCESS documentation no longer has teh descriptions of ixc and icc RIP * minor * itvar numbers * pause * constraint equation mapping * objective equation mapping * objective equation mapping * duplication defense * favlue mapping * output * example * fuller example * add missing plasma models * missed one * add TF coil models * more switches * add eq var mapping file * move template builder to api.py * put template builder in separate file * split out model mappings * PROCESSModel * self not cls * flake8 flag for hack * flake8 flag for hack * docstring * incorporate mechanics into template builder * need to restart PC * start piping into example * slow an dsteady progress * pause before rebase * match install script * CHEEKY NOQA * whoops * typos and input additions * typos and input additions * more missing inputs * impurity handling * more or less done with the PROCESS API * inputs and tk_ts duplicaiton * string bound weirdness * remove spurious int * add missing fimp * fix missing primary pumping model * add mode bloody switches * Constraint enum * objective enum * pipe through and clean up * update radial build example * fix typing * tuple --------- Co-authored-by: james <[email protected]> * PROCESS API enhancement: required input values listed for model selections (#2659) * add model selection mechanics * do one and move to example * add template builder mechanics * concision * undo test mods * also check variables * populate some cases * minor * minor * start on constraint equation fancy enums * why do i have to do this * its the weekend and i am CS fatigue * fold in constraints * tuples not lists * finish constraints but a number of inconsistencies in PROCESS documentation * adjust_variable * warning fixes and catch typos and bugs * more honing in on IN.DAT * cpttf_mak removed * model requires_values tuple * better tuples of one * missing inputs for constraints * more missing inputs - not making this easy.. * remove ffuspow * add taulimit * taulimit * missing tuple of one * missing tuple of one part 2 * picky ruff * add test for bad var name * add test for repeated variable * add another warning test * check it was added too * check bad name adjust * test warn on overwrite * test impurity shenanigans * test warn on missing input model * test warn on overwrite model * was missing an assert * check for missing itvars * better check of existence for constraint itv warning * tuples of one * 24 is not used wtf * 55 not used * missing inputs * more not used * oacddp no longer used?! * missing fvale mapping * some sanity stuff but still not working * the longest it ever took to fail * missed a tuple of one * fix install script and add tests * match up EUDEMO run * update align some defaults * get rid of obsolete PROCESS names * adding endless names * remove wrong / obsolete names * the journey to nowhere continues * more names * divertor variables * PF stuff * physics * physics * TF reshuffle * final ordering clean up * final clean * final clean * couple minor tweaks * final tweak * explicitly apply default bounds to variables * typo * all bounds * start on None * nums to None * lists to None * ixc icc bounds None * default bounds * remove non default models * truly default bounds * constraint ordering * defaults * full defaults from ref IN.DAT * working but feels fragile * work on integration test * work on integration test * nearly there * remove fpinj as default f-value * test inclusion * value tweaks in raial build and runs * πŸš‘οΈ Fixing PROCESS InDat writer (#2690) * πŸš‘οΈ Fixing PROCESS InDat writer * πŸ› Need to import Parameter for dynamic typechecking * βœ… Add test for template writing * βœ… Test from params too * 🎨 Add option to get params out * βœ… Fix template builder tests * πŸ› Fix params that were not sent * 🎨 Use self as it is self * 🚧 WIP None avoidance * 🎨 Add back params * ♻️ Cleanup * βœ… Fix impurities test * βœ… Fix tests * πŸ› Skip tests if process not installed * πŸ“Œ Upgrade env and fix test * 🎨 Update env * πŸ› Fix env * πŸ“ Improve documentation * πŸ› Fix runtitle * 🏷️ Optional * 🎨 Add runtitle * πŸ—οΈ Fix impurity data reading * πŸ“ In eV not keV * πŸ“ Docs * 🎨 Use old env * πŸ› ClassVar breaks stuff * πŸ› Bad rebase * 🚨 Fix formatting * 🚧 TMP environment changes * πŸ› Fix radial build * πŸ› Sort PROCESS iteration variables * Add PROCESS API example (#2740) * minor * complete example CBA to make a converging one that isnt EU-DEMO * preamble * add example to TOC t ree * update impurities id * udpate example * improve example * update fimp( to fimp() * πŸ‘· Exclude process example from examples CI --------- Co-authored-by: james <[email protected]> --------- Co-authored-by: je-cook <[email protected]> Co-authored-by: james <[email protected]> * Update PROCESS v3 (OS) mappings for EU-DEMO (#2749) * first pass mappings * long_name not long name * populate PROCESS params * unit issue * finish process params descriptions * πŸ’© Enable really bad units * mapping fixes * start on special ase mechanics * shield + vv shenanigans * finish applying hacks * add q_0 to test params * add mslimit to test data * add sigma cs * add missing params to test data * move q out of OUT mapping * add proper TODOO * ✨ Allow different in and out names for external codes (#2750) * ✨ Allow different in and out names for external codes * βœ… Add tests * 🚧 A horrible hack for value=None unit=crap * 🍻 Actually it might be ok * manually turn shldith send back on --------- Co-authored-by: james <[email protected]> Co-authored-by: je-cook <[email protected]> * ⬆️ Use new process release * 🚧 Get EUDEMO running (#2752) * 🚧 WIP get eudemo working * 🎨 Neater offset fix * 🎨 Safe xxw * πŸ™ˆ 'stabilise' coil supports optimisation * PROCESS inputs tweaks for EU-DEMO (#2771) * safety factor to 3.5 * CS fatigue inputs to SS316LN * CS fatigue inputs to SS316LN * working set? * 🎨 Jc converges --------- Co-authored-by: james <[email protected]> * 🎨 + marker for coils with no current * 🎨 Make xxw easier to decipher --------- Co-authored-by: CoronelBuendia <[email protected]> --------- Co-authored-by: CoronelBuendia <[email protected]>
1 parent a396f2b commit 0e08d7f

File tree

51 files changed

+4749
-581
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+4749
-581
lines changed

β€Ž.github/workflows/examples.ymlβ€Ž

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ jobs:
3535
# to the CI runners
3636
python ./scripts/run_examples.py \
3737
-e 'plasmod_example' \
38+
-e 'process_example' \
3839
-e 'solver_example' \
3940
-e 'equilibria/fem_fixed_boundary' \
4041
-e 'codes/ext_code_script'

β€Žbluemira/base/parameter_frame/_frame.pyβ€Ž

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,20 @@ def _validate_parameter_field(field, member_type: Type) -> Tuple[Type, ...]:
405405
def _validate_units(param_data: Dict, value_type: Iterable[Type]):
406406
try:
407407
quantity = pint.Quantity(param_data["value"], param_data["unit"])
408+
except ValueError:
409+
try:
410+
quantity = pint.Quantity(f'{param_data["value"]}*{param_data["unit"]}')
411+
except pint.errors.PintError as pe:
412+
if param_data["value"] is None:
413+
quantity = pint.Quantity(
414+
1 if param_data["unit"] in (None, "") else param_data["unit"]
415+
)
416+
param_data["source"] = f"{param_data.get('source', '')}\nMAD UNIT 🀯 😭:"
417+
else:
418+
raise ValueError("Unit conversion failed") from pe
419+
else:
420+
param_data["value"] = quantity.magnitude
421+
param_data["unit"] = quantity.units
408422
except KeyError as ke:
409423
raise ValueError("Parameters need a value and a unit") from ke
410424
except TypeError:
@@ -434,6 +448,9 @@ def _validate_units(param_data: Dict, value_type: Iterable[Type]):
434448

435449
param_data["unit"] = f"{unit:~P}"
436450

451+
if "MAD UNIT" in param_data.get("source", ""):
452+
param_data["source"] += f"{quantity.magnitude}{param_data['unit']}"
453+
437454

438455
def _remake_units(dimensionality: Union[Dict, pint.util.UnitsContainer]) -> pint.Unit:
439456
"""Reconstruct unit from its dimensionality"""

β€Žbluemira/builders/coil_supports.pyβ€Ž

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from typing import Dict, List, Optional, Tuple, Type, Union
2929

3030
import numpy as np
31+
import numpy.typing as npt
3132

3233
from bluemira.base.builder import Builder
3334
from bluemira.base.components import Component, PhysicalComponent
@@ -38,7 +39,7 @@
3839
from bluemira.builders.tools import apply_component_display_options
3940
from bluemira.display.palettes import BLUE_PALETTE
4041
from bluemira.geometry.compound import BluemiraCompound
41-
from bluemira.geometry.constants import VERY_BIG
42+
from bluemira.geometry.constants import D_TOLERANCE, VERY_BIG
4243
from bluemira.geometry.coordinates import Coordinates, get_intersect
4344
from bluemira.geometry.error import GeometryError
4445
from bluemira.geometry.face import BluemiraFace
@@ -621,7 +622,9 @@ def bounds() -> Tuple[np.ndarray, np.ndarray]:
621622
return np.array([0, 0]), np.array([1, 1])
622623

623624
@staticmethod
624-
def f_L_to_wire(wire: BluemiraWire, x_norm: List[float]): # noqa: N802
625+
def f_L_to_wire( # noqa: N802
626+
wire: BluemiraWire, x_norm: Union[List[float], npt.NDArray]
627+
):
625628
"""
626629
Convert a pair of normalised L values to a wire
627630
"""
@@ -667,6 +670,9 @@ def constrain_koz(self, x_norm: np.ndarray) -> np.ndarray:
667670
-------
668671
KOZ constraint array
669672
"""
673+
if np.isnan(x_norm).any():
674+
bluemira_warn(f"NaN in x_norm {x_norm}")
675+
x_norm = np.array([0, D_TOLERANCE])
670676
straight_line = self.f_L_to_wire(self.wire, x_norm)
671677
straight_points = straight_line.discretize(ndiscr=self.n_koz_discr).xz.T
672678
return signed_distance_2D_polygon(straight_points, self.koz_points)

β€Žbluemira/codes/_freecadapi.pyβ€Ž

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,8 @@ def offset_wire(
595595
raise FreeCADError(msg) from None
596596

597597
fix_wire(wire)
598+
if not wire.isClosed() and not open_wire:
599+
raise FreeCADError("offset failed to close wire")
598600
return wire
599601

600602

β€Žbluemira/codes/interface.pyβ€Ž

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -236,9 +236,11 @@ def _map_external_outputs_to_bluemira_params(
236236
for bm_name, mapping in self.params.mappings.items():
237237
if not (mapping.recv or recv_all):
238238
continue
239-
output_value = self._get_output_or_raise(external_outputs, mapping.name)
239+
output_value = self._get_output_or_raise(external_outputs, mapping.out_name)
240240
if mapping.unit is None:
241-
bluemira_warn(f"{mapping.name} from code {self._name} has no known unit")
241+
bluemira_warn(
242+
f"{mapping.out_name} from code {self._name} has no known unit"
243+
)
242244
value = output_value
243245
elif output_value is None:
244246
value = output_value

β€Žbluemira/codes/params.pyβ€Ž

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,9 @@ def defaults(self) -> Dict:
4747
"""
4848

4949
@classmethod
50-
def from_defaults(cls, data: Dict) -> MappedParameterFrame:
50+
def from_defaults(
51+
cls, data: Dict, source: str = "bluemira codes default"
52+
) -> MappedParameterFrame:
5153
"""
5254
Create ParameterFrame with default values for external codes.
5355
@@ -62,7 +64,7 @@ def from_defaults(cls, data: Dict) -> MappedParameterFrame:
6264
new_param_dict[bm_map_name] = {
6365
"value": data.get(param_map.name, None),
6466
"unit": param_map.unit,
65-
"source": "bluemira codes default",
67+
"source": source,
6668
}
6769

6870
return cls.from_dict(new_param_dict)
@@ -130,6 +132,7 @@ class ParameterMapping:
130132
"""
131133

132134
name: str
135+
out_name: Optional[str] = None
133136
send: bool = True
134137
recv: bool = True
135138
unit: Optional[str] = None
@@ -140,14 +143,17 @@ def __post_init__(self):
140143
"""
141144
Freeze the dataclass
142145
"""
143-
self._frozen = ("name", "unit", "_frozen")
146+
if self.out_name is None:
147+
self.out_name = self.name
148+
self._frozen = ("name", "out_name", "unit", "_frozen")
144149

145150
def to_dict(self) -> Dict:
146151
"""
147152
Convert this object to a dictionary with attributes as values.
148153
"""
149154
return {
150155
"name": self.name,
156+
"out_name": self.out_name,
151157
"send": self.send,
152158
"recv": self.recv,
153159
"unit": self.unit,
@@ -179,10 +185,10 @@ def __setattr__(self, attr: str, value: Union[bool, str]):
179185
Value of attribute
180186
"""
181187
if (
182-
attr not in ["send", "recv", "name", "unit", "_frozen"]
188+
attr not in ["send", "recv", "name", "out_name", "unit", "_frozen"]
183189
or attr in self._frozen
184190
):
185-
raise KeyError(f"{attr} cannot be set for a {self.__class__.__name__}")
191+
raise KeyError(f"{attr} cannot be set for a {type(self).__name__}")
186192
if attr in ["send", "recv"] and not isinstance(value, bool):
187193
raise ValueError(f"{attr} must be a bool")
188194
super().__setattr__(attr, value)

β€Žbluemira/codes/plasmod/params.pyβ€Ž

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
from copy import deepcopy
2626
from dataclasses import asdict, dataclass
2727
from enum import Enum
28-
from typing import ClassVar, Dict, Union
28+
from typing import Dict, Union
2929

3030
from bluemira.base.parameter_frame import Parameter
3131
from bluemira.codes.params import MappedParameterFrame
@@ -126,7 +126,7 @@ class PlasmodSolverParams(MappedParameterFrame):
126126
v_burn: Parameter[float]
127127
"""Target loop voltage (if lower than -1e-3, ignored)-> plasma loop voltage [V]."""
128128

129-
_mappings: ClassVar = deepcopy(mappings)
129+
_mappings = deepcopy(mappings)
130130
_defaults = PlasmodInputs()
131131

132132
@property

0 commit comments

Comments
Β (0)