Skip to content

Commit 441e641

Browse files
committed
Added time derivative variable subtype and more latex improvements
1 parent c3146e7 commit 441e641

8 files changed

+121
-34
lines changed

RMK_support/common_variables.py

+51-1
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,60 @@
44
from .variable_container import Variable, node
55
from .derivations import Species
66
from . import derivations
7-
from .remkit_context import RMKContext
87
from abc import ABC, abstractmethod
98

109

10+
def timeDerivative(
11+
name: str, timeNorm: float, variable: Variable, **kwargs
12+
) -> Variable:
13+
"""Generate a time derivative of a given variable as a variable, making sure units and grids are correct.
14+
15+
Args:
16+
name (str): Variable name for the time derivative
17+
timeNorm (float): Time normalisation
18+
variable (Variable): Variable whose derivative should be taken
19+
20+
Returns:
21+
Variable: Variable with correct time derivative units
22+
"""
23+
24+
for key in [
25+
"units",
26+
"unitSI",
27+
"normSI",
28+
"isOnDualGrid",
29+
"isDistribution",
30+
"isSingleHarmonic",
31+
"isScalar",
32+
"subtype",
33+
]:
34+
assert key not in kwargs, key + " not allowed in time derivative variable call"
35+
36+
latexWrapped = "$" in variable.unitsSI
37+
unitSI = variable.unitsSI.replace("$", "") + "/s"
38+
if latexWrapped:
39+
unitSI = "$" + unitSI + "$"
40+
var = Variable(
41+
name,
42+
variable.grid,
43+
**kwargs,
44+
units=variable.unitsNorm + " / time norm.",
45+
unitSI=unitSI,
46+
normSI=variable.normSI / timeNorm,
47+
isOnDualGrid=variable.isOnDualGrid,
48+
isScalar=variable.isScalar,
49+
isDistribution=variable.isDistribution,
50+
isSingleHarmonics=variable.isSingleHarmonic,
51+
subtype=variable.subtype + "_time_derivative"
52+
)
53+
54+
return var
55+
56+
57+
# cyclic import workaround
58+
from .remkit_context import RMKContext
59+
60+
1161
def density(name: str, context: RMKContext, **kwargs) -> Variable:
1262
"""Generate a density variable based on normalisation data within a RMKContext. Accepts regular Variable kwargs, except for those having to do with units, which are set automatically.
1363

RMK_support/dashboard_support.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from typing_extensions import Self
1010
import param # type: ignore
1111
from warnings import warn
12-
import matplotlib.pyplot as plt
12+
import matplotlib.pyplot as plt # type: ignore
1313

1414

1515
def fluidVarX(var: Variable, time: int) -> hv.Curve:
@@ -603,18 +603,20 @@ def load_dist_curves(x: int, time: int, harmonic: int):
603603

604604
return pn.Row(pn.Column(self.param, pos, t, h), pn.panel(dmap))
605605

606-
def quickDash(vars:VariableContainer,runPaths: Dict[str, str]):
607606

608-
hv.extension('matplotlib')
609-
plt.rcParams['figure.dpi'] = 150
610-
hv.output(size=150,dpi=150)
607+
def quickDash(vars: VariableContainer, runPaths: Dict[str, str]):
611608

612-
loader = LazyLoader(vars,runPaths)
609+
hv.extension("matplotlib")
610+
plt.rcParams["figure.dpi"] = 150
611+
hv.output(size=150, dpi=150)
612+
613+
loader = LazyLoader(vars, runPaths)
613614

614615
element1 = ElementDisplay(loader)
615616
element2 = ElementDisplay(loader)
616617

617-
return pn.Row(element1.layout,element2.layout)
618+
return pn.Row(element1.layout, element2.layout)
619+
618620

619621
class ReMKiT1DDashboard:
620622
def __init__(self, data: xr.Dataset, gridObj: Grid):

RMK_support/derivations.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ def addLatexToDoc(self, doc: tex.Document, **kwargs):
230230
"$"
231231
+ species.latex()
232232
+ "$"
233-
+ f": ID: {species.speciesID}; A: {species.atomicA:.4e}; Z: {species.charge:.2f}; Associated vars: "
233+
+ f": ID: {species.speciesID}; A: {species.atomicA:.4e}; Z: {species.charge:.2f} \\newline Associated vars: "
234234
+ ", ".join(associatedVarNames)
235235
)
236236
)

RMK_support/remkit_context.py

+37-10
Original file line numberDiff line numberDiff line change
@@ -792,6 +792,9 @@ def loadSimulation(
792792

793793
def addTermDiagnostics(self, *args: Variable):
794794
"""Add diagnostic variables for all terms evolving given variables. **NOTE**: Does not detect terms generated by TermGenerators - to include these use GroupEvaluators."""
795+
796+
from . import common_variables as cv
797+
795798
for var in args:
796799
terms = self.models.getTermsThatEvolveVar(var)
797800
if not len(terms):
@@ -800,19 +803,43 @@ def addTermDiagnostics(self, *args: Variable):
800803
+ var.name
801804
+ " has no terms that evolve it"
802805
)
803-
806+
if var.isStationary or var.unitsSI == "":
807+
if var.isStationary:
808+
warnings.warn(
809+
var.name
810+
+ " is stationary - cannot determine term units for diagnostics"
811+
)
812+
else:
813+
warnings.warn(
814+
var.name
815+
+ " doesn't have SI units set - cannot determine term units for diagnostics"
816+
)
804817
for pair in terms:
805818
model, term = pair
806-
self.variables.add(
807-
Variable(
808-
model + "_" + term,
809-
self.grid,
810-
isDerived=True,
811-
isDistribution=var.isDistribution,
812-
isOnDualGrid=var.isOnDualGrid,
813-
isCommunicated=False,
819+
820+
if var.isStationary or var.unitsSI == "":
821+
822+
self.variables.add(
823+
Variable(
824+
model + "_" + term,
825+
self.grid,
826+
isDerived=True,
827+
isDistribution=var.isDistribution,
828+
isOnDualGrid=var.isOnDualGrid,
829+
isCommunicated=False,
830+
)
814831
)
815-
)
832+
else:
833+
self.variables.add(
834+
cv.timeDerivative(
835+
model + "_" + term,
836+
self.norms["time"],
837+
var,
838+
isDerived=True,
839+
isCommunicated=False,
840+
)
841+
)
842+
816843
self.manipulators.add(
817844
TermEvaluator(
818845
model + "_" + term, [pair], self.variables[model + "_" + term]

RMK_support/tests/test_common_variables.py

+5
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,8 @@ def test_standard_variable_factory(context):
7878
assert factory.species["density"].name == "nn"
7979
assert factory.species["temperature"].name == "Tn"
8080
assert factory.species["heatflux"].name == "qn"
81+
82+
dndt = cv.timeDerivative("dndt", rk.norms["time"], n)
83+
assert dndt.units == "norm. density / time norm."
84+
assert dndt.normConst == rk.normDensity / rk.norms["time"]
85+
assert dndt.unitsSI == "$m^{-3}/s$"

RMK_support/tests/test_examples.py

+14-13
Original file line numberDiff line numberDiff line change
@@ -56,20 +56,21 @@ def test_solkit_fluid_janev():
5656
heatingPower = 3.5464790894703255
5757

5858
# these tests only check for latex construction errors
59+
with pytest.warns(UserWarning):
5960

60-
rk = solkit_mijin_thesis.generatorSKThesis(
61-
dx0=dx0 / 4,
62-
dxN=dxN / 4,
63-
Nx=256,
64-
Nh=17,
65-
lmax=1,
66-
mpiProcs=16,
67-
initialTimestep=2.0,
68-
nu=0.8 / 1.09345676,
69-
heatingPower=heatingPower,
70-
includedJanevTransitions=["ex", "deex", "ion", "recomb3b"],
71-
numNeutrals=10,
72-
)
61+
rk = solkit_mijin_thesis.generatorSKThesis(
62+
dx0=dx0 / 4,
63+
dxN=dxN / 4,
64+
Nx=256,
65+
Nh=17,
66+
lmax=1,
67+
mpiProcs=16,
68+
initialTimestep=2.0,
69+
nu=0.8 / 1.09345676,
70+
heatingPower=heatingPower,
71+
includedJanevTransitions=["ex", "deex", "ion", "recomb3b"],
72+
numNeutrals=10,
73+
)
7374

7475
rk.setPETScOptions(
7576
cliOpts="-pc_type bjacobi -sub_pc_factor_shift_type nonzero",

RMK_support/tests/test_remkit_context.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,7 @@ def test_wrapper(grid: Grid):
219219
a, b = (Variable(name, rk.grid) for name in "ab")
220220

221221
cDeriv = dv.NodeDerivation("cDeriv", node=vc.node(a) + vc.node(b))
222-
c = Variable("c", rk.grid, isDerived=True, derivation=cDeriv)
222+
c = Variable("c", rk.grid, isDerived=True, derivation=cDeriv, unitSI="$c$")
223223

224224
rk.variables.add(a, b, c)
225225

@@ -350,7 +350,8 @@ def test_wrapper(grid: Grid):
350350
# Now add term diagnostic manipulators for the model terms
351351

352352
# Terms with evolved variables can have term diagnostics
353-
rk.addTermDiagnostics(*[a, b])
353+
with pytest.warns(UserWarning):
354+
rk.addTermDiagnostics(*[a, b])
354355

355356
# Adding a term diagnostic for a non-evolved term should raise a warning
356357
with pytest.warns(

RMK_support/variable_container.py

+1
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,7 @@ def latex(self, latexRemap: Dict[str, str] = {}) -> str:
722722
result += "single harmonic"
723723
if self.isStationary:
724724
result += ", stationary"
725+
result += "\\newline Subtype: " + self.subtype.replace("_", r"\_")
725726

726727
return result
727728

0 commit comments

Comments
 (0)