Skip to content

Commit

Permalink
πŸ‘½ ⬆️ Upgrade process to open source version (#2522)
Browse files Browse the repository at this point in the history
* 🚧 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 <james.cook1@ukaea.uk>

* 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 <james.cook1@ukaea.uk>

---------

Co-authored-by: je-cook <81617086+je-cook@users.noreply.github.com>
Co-authored-by: james <james.cook1@ukaea.uk>

* 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 <james.cook1@ukaea.uk>
Co-authored-by: je-cook <81617086+je-cook@users.noreply.github.com>

* ⬆️ 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 <james.cook1@ukaea.uk>

* 🎨 + marker for coils with no current

* 🎨 Make xxw easier to decipher

---------

Co-authored-by: CoronelBuendia <matti.coleman@gmail.com>

---------

Co-authored-by: CoronelBuendia <matti.coleman@gmail.com>
  • Loading branch information
je-cook and CoronelBuendia committed Nov 2, 2023
1 parent a396f2b commit 0e08d7f
Show file tree
Hide file tree
Showing 51 changed files with 4,749 additions and 581 deletions.
1 change: 1 addition & 0 deletions .github/workflows/examples.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ jobs:
# to the CI runners
python ./scripts/run_examples.py \
-e 'plasmod_example' \
-e 'process_example' \
-e 'solver_example' \
-e 'equilibria/fem_fixed_boundary' \
-e 'codes/ext_code_script'
17 changes: 17 additions & 0 deletions bluemira/base/parameter_frame/_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,20 @@ def _validate_parameter_field(field, member_type: Type) -> Tuple[Type, ...]:
def _validate_units(param_data: Dict, value_type: Iterable[Type]):
try:
quantity = pint.Quantity(param_data["value"], param_data["unit"])
except ValueError:
try:
quantity = pint.Quantity(f'{param_data["value"]}*{param_data["unit"]}')
except pint.errors.PintError as pe:
if param_data["value"] is None:
quantity = pint.Quantity(
1 if param_data["unit"] in (None, "") else param_data["unit"]
)
param_data["source"] = f"{param_data.get('source', '')}\nMAD UNIT 🀯 😭:"
else:
raise ValueError("Unit conversion failed") from pe
else:
param_data["value"] = quantity.magnitude
param_data["unit"] = quantity.units
except KeyError as ke:
raise ValueError("Parameters need a value and a unit") from ke
except TypeError:
Expand Down Expand Up @@ -434,6 +448,9 @@ def _validate_units(param_data: Dict, value_type: Iterable[Type]):

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

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


def _remake_units(dimensionality: Union[Dict, pint.util.UnitsContainer]) -> pint.Unit:
"""Reconstruct unit from its dimensionality"""
Expand Down
10 changes: 8 additions & 2 deletions bluemira/builders/coil_supports.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from typing import Dict, List, Optional, Tuple, Type, Union

import numpy as np
import numpy.typing as npt

from bluemira.base.builder import Builder
from bluemira.base.components import Component, PhysicalComponent
Expand All @@ -38,7 +39,7 @@
from bluemira.builders.tools import apply_component_display_options
from bluemira.display.palettes import BLUE_PALETTE
from bluemira.geometry.compound import BluemiraCompound
from bluemira.geometry.constants import VERY_BIG
from bluemira.geometry.constants import D_TOLERANCE, VERY_BIG
from bluemira.geometry.coordinates import Coordinates, get_intersect
from bluemira.geometry.error import GeometryError
from bluemira.geometry.face import BluemiraFace
Expand Down Expand Up @@ -621,7 +622,9 @@ def bounds() -> Tuple[np.ndarray, np.ndarray]:
return np.array([0, 0]), np.array([1, 1])

@staticmethod
def f_L_to_wire(wire: BluemiraWire, x_norm: List[float]): # noqa: N802
def f_L_to_wire( # noqa: N802
wire: BluemiraWire, x_norm: Union[List[float], npt.NDArray]
):
"""
Convert a pair of normalised L values to a wire
"""
Expand Down Expand Up @@ -667,6 +670,9 @@ def constrain_koz(self, x_norm: np.ndarray) -> np.ndarray:
-------
KOZ constraint array
"""
if np.isnan(x_norm).any():
bluemira_warn(f"NaN in x_norm {x_norm}")
x_norm = np.array([0, D_TOLERANCE])
straight_line = self.f_L_to_wire(self.wire, x_norm)
straight_points = straight_line.discretize(ndiscr=self.n_koz_discr).xz.T
return signed_distance_2D_polygon(straight_points, self.koz_points)
Expand Down
2 changes: 2 additions & 0 deletions bluemira/codes/_freecadapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,8 @@ def offset_wire(
raise FreeCADError(msg) from None

fix_wire(wire)
if not wire.isClosed() and not open_wire:
raise FreeCADError("offset failed to close wire")
return wire


Expand Down
6 changes: 4 additions & 2 deletions bluemira/codes/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,11 @@ def _map_external_outputs_to_bluemira_params(
for bm_name, mapping in self.params.mappings.items():
if not (mapping.recv or recv_all):
continue
output_value = self._get_output_or_raise(external_outputs, mapping.name)
output_value = self._get_output_or_raise(external_outputs, mapping.out_name)
if mapping.unit is None:
bluemira_warn(f"{mapping.name} from code {self._name} has no known unit")
bluemira_warn(
f"{mapping.out_name} from code {self._name} has no known unit"
)
value = output_value
elif output_value is None:
value = output_value
Expand Down
16 changes: 11 additions & 5 deletions bluemira/codes/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ def defaults(self) -> Dict:
"""

@classmethod
def from_defaults(cls, data: Dict) -> MappedParameterFrame:
def from_defaults(
cls, data: Dict, source: str = "bluemira codes default"
) -> MappedParameterFrame:
"""
Create ParameterFrame with default values for external codes.
Expand All @@ -62,7 +64,7 @@ def from_defaults(cls, data: Dict) -> MappedParameterFrame:
new_param_dict[bm_map_name] = {
"value": data.get(param_map.name, None),
"unit": param_map.unit,
"source": "bluemira codes default",
"source": source,
}

return cls.from_dict(new_param_dict)
Expand Down Expand Up @@ -130,6 +132,7 @@ class ParameterMapping:
"""

name: str
out_name: Optional[str] = None
send: bool = True
recv: bool = True
unit: Optional[str] = None
Expand All @@ -140,14 +143,17 @@ def __post_init__(self):
"""
Freeze the dataclass
"""
self._frozen = ("name", "unit", "_frozen")
if self.out_name is None:
self.out_name = self.name
self._frozen = ("name", "out_name", "unit", "_frozen")

def to_dict(self) -> Dict:
"""
Convert this object to a dictionary with attributes as values.
"""
return {
"name": self.name,
"out_name": self.out_name,
"send": self.send,
"recv": self.recv,
"unit": self.unit,
Expand Down Expand Up @@ -179,10 +185,10 @@ def __setattr__(self, attr: str, value: Union[bool, str]):
Value of attribute
"""
if (
attr not in ["send", "recv", "name", "unit", "_frozen"]
attr not in ["send", "recv", "name", "out_name", "unit", "_frozen"]
or attr in self._frozen
):
raise KeyError(f"{attr} cannot be set for a {self.__class__.__name__}")
raise KeyError(f"{attr} cannot be set for a {type(self).__name__}")
if attr in ["send", "recv"] and not isinstance(value, bool):
raise ValueError(f"{attr} must be a bool")
super().__setattr__(attr, value)
4 changes: 2 additions & 2 deletions bluemira/codes/plasmod/params.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from copy import deepcopy
from dataclasses import asdict, dataclass
from enum import Enum
from typing import ClassVar, Dict, Union
from typing import Dict, Union

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

_mappings: ClassVar = deepcopy(mappings)
_mappings = deepcopy(mappings)
_defaults = PlasmodInputs()

@property
Expand Down
Loading

0 comments on commit 0e08d7f

Please sign in to comment.