Skip to content

Unsteady heat support #2388

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
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
60 changes: 60 additions & 0 deletions tests/test_components/test_heat_charge.py
Original file line number Diff line number Diff line change
Expand Up @@ -1559,3 +1559,63 @@ def test_fossum():
"""Check that fossum model can be defined."""

_ = td.FossumCarrierLifetime(tau_300=3.3e-6, alpha_T=-0.5, N0=7.1e15, A=1, B=0, C=1, alpha=1)


def test_unsteady_parameters():
"""Test that unsteady parameters are set correctly."""

_ = td.UnsteadyHeatAnalysis(
initial_temperature=300,
unsteady_spec=td.UnsteadySpec(time_step=0.1, total_time_steps=1),
)

# test non-positive initial temperature raises error
with pytest.raises(pd.ValidationError):
_ = td.UnsteadyHeatAnalysis(
initial_temperature=0,
unsteady_spec=td.UnsteadySpec(time_step=0.1, total_time_steps=1),
)

# test negative time step raises error
with pytest.raises(pd.ValidationError):
_ = td.UnsteadyHeatAnalysis(
initial_temperature=10,
unsteady_spec=td.UnsteadySpec(time_step=-0.1, total_time_steps=1),
)

# test negative total time steps raises error
with pytest.raises(pd.ValidationError):
_ = td.UnsteadyHeatAnalysis(
initial_temperature=10,
unsteady_spec=td.UnsteadySpec(time_step=0.1, total_time_steps=-1),
)


def test_unsteady_heat_analysis(heat_simulation):
"""Test that the validators for unsteady heat analysis are working."""

unsteady_analysis_spec = td.UnsteadyHeatAnalysis(
initial_temperature=300,
unsteady_spec=td.UnsteadySpec(time_step=0.1, total_time_steps=1),
)

temp_mnt = td.TemperatureMonitor(
center=(0, 0, 0),
size=(td.inf, td.inf, td.inf),
name="temperature",
unstructured=True,
interval=2,
)

# this should work since the monitor is unstructured
unsteady_sim = heat_simulation.updated_copy(
analysis_spec=unsteady_analysis_spec, monitors=[temp_mnt]
)

with pytest.raises(pd.ValidationError):
temp_mnt = temp_mnt.updated_copy(unstructured=False)
_ = unsteady_sim.updated_copy(monitors=[temp_mnt])

with pytest.raises(pd.ValidationError):
temp_mnt = temp_mnt.updated_copy(unstructured=True, interval=0)
_ = unsteady_sim.updated_copy(monitors=[temp_mnt])
14 changes: 12 additions & 2 deletions tests/test_data/test_datasets.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
np.random.seed(4)


@pytest.mark.parametrize("dataset_type_ind", [0, 1])
@pytest.mark.parametrize("dataset_type_ind", [0, 1, 2])
@pytest.mark.parametrize("ds_name", ["test123", None])
def test_triangular_dataset(tmp_path, ds_name, dataset_type_ind, no_vtk=False):
import tidy3d as td
Expand All @@ -26,6 +26,11 @@ def test_triangular_dataset(tmp_path, ds_name, dataset_type_ind, no_vtk=False):
values_type = td.IndexedVoltageDataArray
extra_dims = {"voltage": [0, 1, 2]}

if dataset_type_ind == 2:
dataset_type = td.TriangularGridDataset
values_type = td.IndexedTimeDataArray
extra_dims = {"t": [0, 1, 2]}

# basic create
tri_grid_points = td.PointDataArray(
[[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]],
Expand Down Expand Up @@ -322,7 +327,7 @@ def operation(arr):
assert result.name == ds_name


@pytest.mark.parametrize("dataset_type_ind", [0, 1])
@pytest.mark.parametrize("dataset_type_ind", [0, 1, 2])
@pytest.mark.parametrize("ds_name", ["test123", None])
def test_tetrahedral_dataset(tmp_path, ds_name, dataset_type_ind, no_vtk=False):
import tidy3d as td
Expand All @@ -338,6 +343,11 @@ def test_tetrahedral_dataset(tmp_path, ds_name, dataset_type_ind, no_vtk=False):
values_type = td.IndexedVoltageDataArray
extra_dims = {"voltage": [0, 1, 2]}

if dataset_type_ind == 2:
dataset_type = td.TetrahedralGridDataset
values_type = td.IndexedTimeDataArray
extra_dims = {"t": [0, 1, 2]}

# basic create
tet_grid_points = td.PointDataArray(
[
Expand Down
5 changes: 5 additions & 0 deletions tidy3d/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
)
from tidy3d.components.spice.sources.dc import DCCurrentSource, DCVoltageSource
from tidy3d.components.spice.sources.types import VoltageSourceType
from tidy3d.components.tcad.analysis.heat_simulation_type import UnsteadyHeatAnalysis, UnsteadySpec
from tidy3d.components.tcad.boundary.specification import (
HeatBoundarySpec,
HeatChargeBoundarySpec,
Expand Down Expand Up @@ -126,6 +127,7 @@
FluxTimeDataArray,
HeatDataArray,
IndexedDataArray,
IndexedTimeDataArray,
IndexedVoltageDataArray,
ModeAmpsDataArray,
ModeIndexDataArray,
Expand Down Expand Up @@ -598,6 +600,8 @@ def set_logging_level(level: str) -> None:
"UniformHeatSource",
"HeatSource",
"HeatFromElectricSource",
"UnsteadyHeatAnalysis",
"UnsteadySpec",
"UniformUnstructuredGrid",
"DistanceUnstructuredGrid",
"TemperatureData",
Expand Down Expand Up @@ -628,6 +632,7 @@ def set_logging_level(level: str) -> None:
"PointDataArray",
"CellDataArray",
"IndexedDataArray",
"IndexedTimeDataArray",
"IndexedVoltageDataArray",
"SteadyVoltageDataArray",
"TriangularGridDataset",
Expand Down
19 changes: 18 additions & 1 deletion tidy3d/components/data/data_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1236,6 +1236,22 @@ class IndexedVoltageDataArray(DataArray):
_dims = ("index", "voltage")


class IndexedTimeDataArray(DataArray):
"""Stores a two-dimensional array with coordinates ``index`` and ``t``, where
``index`` is usually associated with ``PointDataArray`` and ``t`` indicates at what
simulated time the data was obtained.

Example
-------
>>> indexed_array = IndexedTimeDataArray(
... (1+1j) * np.random.random((3,2)), coords=dict(index=np.arange(3), t=[0, 1])
... )
"""

__slots__ = ()
_dims = ("index", "t")


class SpatialVoltageDataArray(AbstractSpatialDataArray):
"""Spatial distribution with voltage mapping.

Expand Down Expand Up @@ -1286,7 +1302,8 @@ class SpatialVoltageDataArray(AbstractSpatialDataArray):
CellDataArray,
IndexedDataArray,
IndexedVoltageDataArray,
IndexedTimeDataArray,
]
DATA_ARRAY_MAP = {data_array.__name__: data_array for data_array in DATA_ARRAY_TYPES}

IndexedDataArrayTypes = Union[IndexedDataArray, IndexedVoltageDataArray]
IndexedDataArrayTypes = Union[IndexedDataArray, IndexedVoltageDataArray, IndexedTimeDataArray]
Empty file.
64 changes: 64 additions & 0 deletions tidy3d/components/tcad/analysis/heat_simulation_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Dealing with time specifications for DeviceSimulation"""

import pydantic.v1 as pd

from ....constants import KELVIN, SECOND
from ...base import Tidy3dBaseModel


class UnsteadySpec(Tidy3dBaseModel):
"""Defines an unsteady specification

Example
--------
>>> import tidy3d as td
>>> time_spec = td.UnsteadySpec(
... time_step=0.01,
... total_time_steps=200,
... output_fr=50,
... )
"""

time_step: pd.PositiveFloat = pd.Field(
...,
title="Time-step",
description="Time step taken for each iteration of the time integration loop.",
units=SECOND,
)

total_time_steps: pd.PositiveInt = pd.Field(
...,
title="Total time steps",
description="Specifies the total number of time steps run during the simulation.",
)


class UnsteadyHeatAnalysis(Tidy3dBaseModel):
"""
Configures relevant unsteady-state heat simulation parameters.

Example
-------
>>> import tidy3d as td
>>> time_spec = td.UnsteadyHeatAnalysis(
... initial_temperature=300,
... unsteady_spec=td.UnsteadySpec(
... time_step=0.01,
... total_time_steps=200,
... output_fr=50,
... ),
... )
"""

initial_temperature: pd.PositiveFloat = pd.Field(
...,
title="Initial temperature.",
description="Initial value for the temperature field.",
units=KELVIN,
)

unsteady_spec: UnsteadySpec = pd.Field(
...,
title="Unsteady specification",
description="Time step and total time steps for the unsteady simulation.",
)
17 changes: 0 additions & 17 deletions tidy3d/components/tcad/data/monitor_data/heat.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from tidy3d.components.base import skip_if_fields_missing
from tidy3d.components.data.data_array import (
DataArray,
IndexedDataArray,
SpatialDataArray,
)
from tidy3d.components.data.utils import TetrahedralGridDataset, TriangularGridDataset
Expand Down Expand Up @@ -75,22 +74,6 @@ def warn_no_data(cls, val, values):

return val

@pd.validator("temperature", always=True)
@skip_if_fields_missing(["monitor"])
def check_correct_data_type(cls, val, values):
"""Issue error if incorrect data type is used"""

mnt = values.get("monitor")

if isinstance(val, TetrahedralGridDataset) or isinstance(val, TriangularGridDataset):
if not isinstance(val.values, IndexedDataArray):
raise ValueError(
f"Monitor {mnt} of type 'TemperatureMonitor' cannot be associated with data arrays "
"of type 'IndexVoltageDataArray'."
)

return val

def field_name(self, val: str = "") -> str:
"""Gets the name of the fields to be plot."""
if val == "abs^2":
Expand Down
11 changes: 11 additions & 0 deletions tidy3d/components/tcad/monitors/heat.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
"""Objects that define how data is recorded from simulation."""

import pydantic.v1 as pd

from tidy3d.components.tcad.monitors.abstract import HeatChargeMonitor


class TemperatureMonitor(HeatChargeMonitor):
"""Temperature monitor."""

interval: pd.PositiveInt = pd.Field(
1,
title="Interval",
description="Sampling rate of the monitor: number of time steps between each measurement. "
"Set ``interval`` to 1 for the highest possible resolution in time. "
"Higher integer values down-sample the data by measuring every ``interval`` time steps. "
"This can be useful for reducing data storage as needed by the application.",
)
37 changes: 34 additions & 3 deletions tidy3d/components/tcad/simulation/heat_charge.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,16 @@
from tidy3d.exceptions import SetupError
from tidy3d.log import log

from ..analysis.heat_simulation_type import UnsteadyHeatAnalysis

HEAT_CHARGE_BACK_STRUCTURE_STR = "<<<HEAT_CHARGE_BACKGROUND_STRUCTURE>>>"

HeatBCTypes = (TemperatureBC, HeatFluxBC, ConvectionBC)
HeatSourceTypes = (UniformHeatSource, HeatSource, HeatFromElectricSource)
ChargeSourceTypes = ()
ElectricBCTypes = (VoltageBC, CurrentBC, InsulatingBC)

AnalysisSpecType = ElectricalAnalysisType
AnalysisSpecType = Union[ElectricalAnalysisType, UnsteadyHeatAnalysis]


class TCADAnalysisTypes(str, Enum):
Expand Down Expand Up @@ -834,6 +836,30 @@ def estimate_charge_mesh_size(cls, values):
)
return values

@pd.root_validator(skip_on_failure=True)
def check_temperature_monitor_in_unsteady_cases(cls, values):
"""Make sure that the temperature monitor is unstructured in unsteady cases."""

analysis_type = values.get("analysis_spec")
if isinstance(analysis_type, UnsteadyHeatAnalysis):
monitors = values.get("monitors")
for mnt in monitors:
if isinstance(mnt, TemperatureMonitor):
if not mnt.unstructured:
raise SetupError(
f"Unsteady simulations require the temperature monitor '{mnt.name}' to be unstructured."
)
# additionaly check that the SolidSpec has capacitance defined
# NOTE: not sure this is needed. Is capacitance a required field in SolidMedium?
structures = values.get("structures")
for structure in structures:
if isinstance(structure.medium.heat, SolidMedium):
if structure.medium.heat_spec.capacity is None:
raise SetupError(
f"Unsteady simulations require the medium '{structure.medium.name}' to have a capacitance defined."
)
return values

@equal_aspect
@add_ax_if_none
def plot_property(
Expand Down Expand Up @@ -1629,8 +1655,13 @@ def _get_simulation_types(self) -> list[TCADAnalysisTypes]:

# NOTE: for the time being, if a simulation has SemiconductorMedium
# then we consider it of being a 'TCADAnalysisTypes.CHARGE'
if self._check_if_semiconductor_present(self.structures):
return [TCADAnalysisTypes.CHARGE]
if isinstance(self.analysis_spec, ElectricalAnalysisType):
if self._check_if_semiconductor_present(self.structures):
return [TCADAnalysisTypes.CHARGE]

# check if unsteady heat
if isinstance(self.analysis_spec, UnsteadyHeatAnalysis):
return [TCADAnalysisTypes.HEAT]

heat_source_present = any(isinstance(s, HeatSourceTypes) for s in self.sources)

Expand Down