Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions examples/example_solver_intensity.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def test_solve(dct, Trep, tol=1.0e-06, mxi=64):

# Test 1 : compute max intensity
Trep = 99.0
df = test_solve(dct, Trep, tol=1.0e-03, mxi=16)
dictionary = test_solve(dct, Trep, tol=1.0e-03, mxi=16)

# Test 2 : check balance and consistency
tol = 1.0e-06
Expand All @@ -81,16 +81,19 @@ def test_solve(dct, Trep, tol=1.0e-06, mxi=64):
fig, ax = plt.subplots(nrows=2, ncols=5)
for i, d in enumerate(mdl):
slv = d["model"]
df = slv.steady_intensity(Trep, tol=tol, maxiter=mxi, return_power=True)
df["pb"] = (
df["P_joule"] + df["P_solar"] - df["P_convection"] - df["P_radiation"]
dictionary = slv.steady_intensity(Trep, tol=tol, maxiter=mxi, return_power=True)
dictionary["pb"] = (
dictionary["P_joule"]
+ dictionary["P_solar"]
- dictionary["P_convection"]
- dictionary["P_radiation"]
)
slv.dc["transit"] = df["I_max"].values
df["TIrep"] = slv.steady_temperature(return_power=False)["T_surf"]
slv.dc["transit"] = dictionary["I_max"]
dictionary["TIrep"] = slv.steady_temperature(return_power=False)["T_surf"]

ax[0, i].hist(df["pb"], bins=100)
ax[0, i].hist(dictionary["pb"], bins=100)
ax[0, i].grid(True)
ax[1, i].hist(np.abs(1.0 - df["TIrep"] / Trep), bins=100)
ax[1, i].hist(np.abs(1.0 - dictionary["TIrep"] / Trep), bins=100)
ax[1, i].grid(True)
ax[0, i].set_title(d["label"])

Expand Down
10 changes: 5 additions & 5 deletions examples/example_transient.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@
for i, key in enumerate(slv):
elm = slv[key]
elm.dc["transit"] = transit
df = elm.steady_temperature()
dct = elm.steady_temperature()
elm.dc["transit"] = np.nan
cl = "C%d" % (i % 10,)
T1 = df["T_surf"].values
T1 = dct["T_surf"]
T2 = elm.transient_temperature(t, T0=np.array(T1[0]), transit=transit)["T_surf"]
plt.plot(t, T1, "--", c=cl, label="%s - steady" % (key,))
plt.plot(t, T2, "-", c=cl, label="%s - transient" % (key,))
Expand All @@ -83,14 +83,14 @@
plt.figure()
elm = slv["rte"]
elm.dc["transit"] = transit
df = elm.steady_temperature(return_avg=True, return_core=True)
dct = elm.steady_temperature(return_avg=True, return_core=True)
elm.dc["transit"] = np.nan
cl = "C0"
dg = elm.transient_temperature(
t, T0=T1[0], transit=transit, return_avg=True, return_core=True
)
plt.fill_between(t, df["T_surf"], df["T_core"], fc=cl, alpha=0.33)
plt.plot(t, df["T_avg"], "--", c=cl, label="%s - steady" % (key,))
plt.fill_between(t, dct["T_surf"], dct["T_core"], fc=cl, alpha=0.33)
plt.plot(t, dct["T_avg"], "--", c=cl, label="%s - steady" % (key,))

plt.fill_between(t, dg["T_surf"], dg["T_core"], fc=cl, alpha=0.33)
plt.plot(t, dg["T_avg"], "-", c=cl, label="%s - transient" % (key,))
Expand Down
4 changes: 2 additions & 2 deletions examples/example_transient2.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,11 @@
elm = slv[key]
elm.dc["transit"] = transit[:, 1]
elm.dc["Ta"] = elm.dc["Ta"][1]
df = elm.steady_temperature()
dictionary = elm.steady_temperature()
elm.dc["transit"] = np.nan
elm.dc["Ta"] = dct["Ta"]
cl = "C%d" % (i % 10,)
T1 = df["T_surf"].values
T1 = dictionary["T_surf"]
T2 = elm.transient_temperature(t, T0=np.array(T1[0]), transit=transit)
for j in range(3):
plt.plot(t, T2["T_surf"][:, j], "-", c=cl, label="%s - transient" % (key,))
Expand Down
39 changes: 37 additions & 2 deletions src/thermohl/solver/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,17 +267,52 @@ def balance(self, T: floatArrayLike) -> floatArrayLike:
)

@abstractmethod
def steady_temperature(self) -> pd.DataFrame:
def steady_temperature(self) -> dict[str, np.ndarray]:
raise NotImplementedError

@abstractmethod
def transient_temperature(self) -> Dict[str, Any]:
raise NotImplementedError

@abstractmethod
def steady_intensity(self) -> pd.DataFrame:
def steady_intensity(self) -> dict[str, np.ndarray]:
raise NotImplementedError

@staticmethod
def format_output(
columns_names: list[str], data: list[np.ndarray]
) -> dict[str, np.ndarray]:
if len(columns_names) != len(data):
raise ValueError(
f"columns_names and data must have the same length but len(columns_names)={len(columns_names)} and len(data)={len(data)}"
)

return {columns_names[i]: data[i] for i in range(len(columns_names))}

def add_error_and_power_if_needed(self, T, err, output, return_err, return_power):
self.add_error_if_needed(err, output, return_err)
self.add_powers_if_needed(T, output, return_power)

@staticmethod
def add_error_if_needed(err, output, return_err):
if return_err:
output[Solver.Names.err] = err

def add_powers_if_needed(
self, temperature_average, output, return_power, temperature_surface=None
):
if return_power:
temperature_surface = (
temperature_surface
if temperature_surface is not None
else temperature_average
)
output[Solver.Names.pjle] = self.jh.value(temperature_average)
output[Solver.Names.psol] = self.sh.value(temperature_surface)
output[Solver.Names.pcnv] = self.cc.value(temperature_surface)
output[Solver.Names.prad] = self.rc.value(temperature_surface)
output[Solver.Names.ppre] = self.pc.value(temperature_surface)


def reshape(input_array: numberArrayLike, nb_row: int, nb_columns: int) -> numberArray:
"""
Expand Down
39 changes: 10 additions & 29 deletions src/thermohl/solver/slv1t.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from typing import Dict, Any, Optional

import numpy as np
import pandas as pd

from thermohl import floatArrayLike, floatArray
from thermohl.solver.base import Solver as Solver_
Expand All @@ -27,7 +26,7 @@ def steady_temperature(
maxiter: int = DP.maxiter,
return_err: bool = False,
return_power: bool = True,
) -> pd.DataFrame:
) -> dict[str, np.ndarray]:
"""
Compute steady-state temperature.

Expand All @@ -40,7 +39,7 @@ def steady_temperature(
return_power (bool, optional): Return power term values. The default is True.

Returns:
pandas.DataFrame: A DataFrame with temperature and other results (depending on inputs) in the columns.
dict[str, np.ndarray]: A dictionary with temperature and other results (depending on inputs) in the keys.

"""

Expand All @@ -50,19 +49,10 @@ def steady_temperature(
)

# format output
df = pd.DataFrame(data=T, columns=[Solver_.Names.temp])
result = self.format_output([Solver_.Names.temp], [T])
self.add_error_and_power_if_needed(T, err, result, return_err, return_power)

if return_err:
df[Solver_.Names.err] = err

if return_power:
df[Solver_.Names.pjle] = self.jh.value(T)
df[Solver_.Names.psol] = self.sh.value(T)
df[Solver_.Names.pcnv] = self.cc.value(T)
df[Solver_.Names.prad] = self.rc.value(T)
df[Solver_.Names.ppre] = self.pc.value(T)

return df
return result

def transient_temperature(
self,
Expand Down Expand Up @@ -169,7 +159,7 @@ def steady_intensity(
maxiter: int = DP.maxiter,
return_err: bool = False,
return_power: bool = True,
) -> pd.DataFrame:
) -> dict[str, np.ndarray]:
"""Compute steady-state max intensity.

Compute the maximum intensity that can be run in a conductor without
Expand All @@ -185,7 +175,7 @@ def steady_intensity(
return_power (bool, optional): Return power term values. The default is True.

Returns:
pandas.DataFrame: A dataframe with maximum intensity and other results (depending on inputs) in the columns.
dict[str, np.array]: A dictionary with intensity and other results (depending on inputs) in the keys.

"""

Expand Down Expand Up @@ -213,16 +203,7 @@ def fun(i: floatArray) -> floatArrayLike:
self.args.transit = transit

# format output
df = pd.DataFrame(data=A, columns=[Solver_.Names.transit])

if return_err:
df[Solver_.Names.err] = err

if return_power:
df[Solver_.Names.pjle] = self.jh.value(T)
df[Solver_.Names.psol] = self.sh.value(T)
df[Solver_.Names.pcnv] = self.cc.value(T)
df[Solver_.Names.prad] = self.rc.value(T)
df[Solver_.Names.ppre] = self.pc.value(T)
result = self.format_output([Solver_.Names.transit], [A])
self.add_error_and_power_if_needed(T_, err, result, return_err, return_power)

return df
return result
53 changes: 18 additions & 35 deletions src/thermohl/solver/slv3t.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from typing import Tuple, Type, Optional, Dict, Any, Callable

import numpy as np
import pandas as pd

from thermohl import floatArrayLike, floatArray, strListLike, intArray
from thermohl.power import PowerTerm
Expand Down Expand Up @@ -190,7 +189,7 @@ def steady_temperature(
maxiter: int = DP.maxiter,
return_err: bool = False,
return_power: bool = True,
) -> pd.DataFrame:
) -> dict[str, np.ndarray]:
"""
Compute the steady-state temperature distribution.

Expand All @@ -203,7 +202,7 @@ def steady_temperature(
return_power (bool): If True, power-related values are included in the returned DataFrame.

Returns:
pd.DataFrame: DataFrame containing the steady-state temperatures and optionally the error and power-related values.
dict[str, np.ndarray]: Dictionary containing the steady-state temperatures and optionally the error and power-related values.
"""

# if no guess provided, use ambient temp
Expand All @@ -229,21 +228,12 @@ def steady_temperature(

# format output
z = self.average(x, y)
df = pd.DataFrame(
{Solver_.Names.tsurf: x, Solver_.Names.tavg: z, Solver_.Names.tcore: y}
result = self.format_output(
[Solver_.Names.tsurf, Solver_.Names.tavg, Solver_.Names.tcore], [x, z, y]
)
self.add_error_and_power_if_needed(x, err, result, return_err, return_power)

if return_err:
df[Solver_.Names.err] = err

if return_power:
df[Solver_.Names.pjle] = self.joule(x, y)
df[Solver_.Names.psol] = self.sh.value(x)
df[Solver_.Names.pcnv] = self.cc.value(x)
df[Solver_.Names.prad] = self.rc.value(x)
df[Solver_.Names.ppre] = self.pc.value(x)

return df
return result

def _morgan_transient(self):
"""Morgan coefficients for transient temperature."""
Expand Down Expand Up @@ -459,7 +449,7 @@ def steady_intensity(
return_err: bool = False,
return_temp: bool = True,
return_power: bool = True,
) -> pd.DataFrame:
) -> dict[str, np.ndarray]:
"""
Compute the steady-state intensity for a given temperature profile.

Expand All @@ -473,7 +463,7 @@ def steady_intensity(
return_power (bool): If True, return the power profiles in the output DataFrame. Default is True.

Returns:
pd.DataFrame: DataFrame containing the steady-state intensity and optionally the error, temperature profiles, and power profiles.
dict[str, np.ndarray]: A dictionary with intensity and other results (depending on inputs) in the keys.
"""

Tmax, newtheader = self._steady_intensity_header(T, target)
Expand All @@ -499,7 +489,7 @@ def morgan(i: floatArray, tg: floatArray) -> floatArray:
x, y, cnt, err = quasi_newton_2d(
balance,
morgan,
r[Solver_.Names.transit].values,
r[Solver_.Names.transit],
Tmax,
relative_tolerance=tol,
max_iterations=maxiter,
Expand All @@ -510,25 +500,18 @@ def morgan(i: floatArray, tg: floatArray) -> floatArray:
print(f"rstat_analytic max err is {np.max(err):.3E} in {cnt:d} iterations")

# format output
df = pd.DataFrame({Solver_.Names.transit: x})

if return_err:
df["err"] = err
result = self.format_output([Solver_.Names.transit], [x])
self.add_error_if_needed(err, result, return_err)

if return_temp or return_power:
ts, tc = newtheader(x, y)
ta = self.average(ts, tc)

if return_temp:
df[Solver_.Names.tsurf] = ts
df[Solver_.Names.tavg] = ta
df[Solver_.Names.tcore] = tc

if return_power:
df[Solver_.Names.pjle] = self.jh.value(ta)
df[Solver_.Names.psol] = self.sh.value(ts)
df[Solver_.Names.pcnv] = self.cc.value(ts)
df[Solver_.Names.prad] = self.rc.value(ts)
df[Solver_.Names.ppre] = self.pc.value(ts)

return df
result[Solver_.Names.tsurf] = ts
result[Solver_.Names.tavg] = ta
result[Solver_.Names.tcore] = tc

self.add_powers_if_needed(ta, result, return_power, temperature_surface=ts)

return result
Loading