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
Binary file added docs/source/images/steps_1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/source/images/steps_2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
47 changes: 47 additions & 0 deletions docs/source/tendencies.rst
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,53 @@ Parameters
.. warning::
This tendency does **not** accept the common ``start``, ``duration``, or ``end`` parameters. These are derived directly from the required ``time`` list.

.. _steps-tendency:

Steps Tendency
==============

Defines a a sequence of steps, each held constant from its time point until the next one
(or until the end of the tendency for the last step). This is a compact alternative to
writing out a sequence of :ref:`Constant Tendencies <constant-value-types>`.

Parameters
----------
* ``time``: A list of the start times of each step. Must be strictly monotonically increasing and must have at least 1 point.
* ``value``: A list of the values held during each step. Must have the same length as ``time``.
Just like the :ref:`Constant Tendency <constant-value-types>`, the ``value`` list may contain numbers or strings:
* ``duration``, ``end``: See :ref:`Common Time Parameters <available-tendencies>`.
Either may be used to specify when the last step ends.
If both are omitted, the tendency simply stops at the last point in the ``time`` list.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bit misleading, since we'll do constant extrapolation at the end of the tendency regardless right?


.. image:: images/steps_1.png
:alt: Example plot of a Steps Tendency
:width: 400px
:align: center

.. code-block:: yaml

- {type: steps, time: [0, 2, 4], value: [1, 3, 5], end: 6}

The same tendency can equivalently be written using ``duration`` instead of ``end``:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But only because the first time value is 0?


.. code-block:: yaml

- {type: steps, time: [0, 2, 4], value: [1, 3, 5], duration: 6}

Just like the :ref:`Constant Tendency <constant-value-types>`, the ``value`` list may contain numbers or strings:

.. image:: images/steps_2.png
:alt: Example plot of a Steps Tendency containing string values
:width: 400px
:align: center

.. code-block:: yaml

- {type: steps, time: [0, 10, 20], value: [ohmic, nbi, ec], end: 30}

.. warning::
This tendency does not accept the common ``start`` parameter. The start of the tendency is always derived from the first point in ``time``.

Periodic Tendencies
===================

Expand Down
185 changes: 185 additions & 0 deletions tests/tendencies/test_steps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
import numpy as np
import pytest

from waveform_editor.tendencies.steps import StepsTendency


def test_empty():
"""Test empty tendency."""
tendency = StepsTendency()
assert tendency.annotations

tendency = StepsTendency(user_time=[0, 2, 4])
assert tendency.annotations

tendency = StepsTendency(user_value=[1, 2, 3])
assert tendency.annotations


def test_filled():
"""Test value of a filled tendency."""
tendency = StepsTendency(user_time=[0, 2, 4], user_value=[1, 3, 5], user_end=6)
assert np.all(tendency.time == np.array([0, 2, 4]))
assert list(tendency.value) == [1, 3, 5]
assert tendency.value_type is int
assert tendency.start == 0
assert tendency.end == 6
assert not tendency.annotations


def test_string_values():
"""Test a tendency with string values."""
tendency = StepsTendency(
user_time=[0, 10, 20], user_value=["ohmic", "nbi", "ec"], user_end=30
)
assert list(tendency.value) == ["ohmic", "nbi", "ec"]
assert tendency.value_type is str
assert not tendency.annotations

_, values = tendency.get_value(np.array([0, 5, 10, 15, 20, 25, 30]))
assert list(values) == ["ohmic", "ohmic", "nbi", "nbi", "ec", "ec", "ec"]


def test_int_float_mixing():
"""Test that mixing int and float values in a single steps tendency"""
tendency = StepsTendency(user_time=[0, 2, 4], user_value=[1, 2.5, 3], user_end=6)
assert tendency.value_type is float
assert not tendency.annotations


def test_mixed_value_types_not_supported():
"""Test that mixing string and numerical values is not allowed."""
tendency = StepsTendency(user_time=[0, 10], user_value=[1, "ec"], user_end=20)
assert tendency.annotations


def test_unsupported_value_type():
"""Test that a value which is not an int, float, or str is not supported."""
tendency = StepsTendency(user_time=[0, 10], user_value=[1, [2, 3]], user_end=20)
assert tendency.annotations


def test_duration_instead_of_end():
"""Test that `duration` can be used instead of `end`."""
tendency = StepsTendency(user_time=[0, 2, 4], user_value=[1, 3, 5], user_duration=6)
assert tendency.end == 6
assert not tendency.annotations


def test_duration_and_end_consistent():
"""Test that providing both `duration` and `end` is fine if consistent."""
tendency = StepsTendency(
user_time=[0, 2, 4], user_value=[1, 3, 5], user_duration=6, user_end=6
)
assert tendency.end == 6
assert not tendency.annotations


def test_duration_and_end_inconsistent():
"""Test that providing inconsistent `duration` and `end` results in an error."""
tendency = StepsTendency(
user_time=[0, 2, 4], user_value=[1, 3, 5], user_duration=6, user_end=10
)
assert tendency.annotations


def test_neither_duration_nor_end_given():
"""Test that omitting both `duration` and `end` makes the tendency stop at its
last time point."""
tendency = StepsTendency(user_time=[0, 2, 4], user_value=[1, 3, 5])
assert tendency.end == 4
assert tendency.duration == 4
assert not tendency.annotations

_, values = tendency.get_value(np.array([0, 1, 2, 3, 4]))
assert list(values) == [1, 1, 3, 3, 5]


def test_end_not_after_last_time():
"""Test invalid end and duration values."""
tendency = StepsTendency(user_time=[0, 10], user_value=[1, 2], user_end=10)
assert tendency.annotations

tendency = StepsTendency(user_time=[0, 10], user_value=[1, 2], user_end=5)
assert tendency.annotations

tendency = StepsTendency(user_time=[0, 10], user_value=[1, 2], user_duration=5)
assert tendency.annotations


def test_mismatched_lengths():
"""Test that time and value arrays must have the same length."""
tendency = StepsTendency(user_time=[0, 10, 20], user_value=[1, 2], user_end=30)
assert tendency.annotations


def test_empty_arrays():
"""Test that time and value arrays must contain at least one element."""
tendency = StepsTendency(user_time=[], user_value=[], user_end=10)
assert tendency.annotations


def test_non_monotonic_time():
"""Test that the time array must be monotonically increasing."""
tendency = StepsTendency(user_time=[0, 10, 5], user_value=[1, 2, 3], user_end=20)
assert tendency.annotations

tendency = StepsTendency(user_time=[0, 10, 10], user_value=[1, 2, 3], user_end=20)
assert tendency.annotations


def test_start_not_allowed():
"""Test that `start` may not be provided"""
tendency = StepsTendency(
user_time=[0, 10], user_value=[1, 2], user_end=20, user_start=5
)
assert tendency.annotations


def test_start_and_end_values():
"""Test the start and end values and their derivatives."""
tendency = StepsTendency(user_time=[0, 2, 4], user_value=[1, 3, 5], user_end=6)
assert tendency.start_value == 1
assert tendency.end_value == 5
assert tendency.start_derivative == 0
assert tendency.end_derivative == 0
assert not tendency.annotations


def test_generate():
"""Check the generated values."""
tendency = StepsTendency(user_time=[0, 2, 4], user_value=[1, 3, 5], user_end=6)
time, values = tendency.get_value()
assert np.all(time == [0, 2, 2, 4, 4, 6])
assert list(values) == [1, 1, 3, 3, 5, 5]
assert not tendency.annotations


def test_get_value_at_times():
"""Check the value assignment at arbitrary time points."""
tendency = StepsTendency(user_time=[0, 2, 4], user_value=[1, 3, 5], user_end=6)
_, values = tendency.get_value(np.array([0, 1, 1.99, 2, 3, 4, 5, 6]))
assert list(values) == [1, 1, 1, 3, 3, 5, 5, 5]


def test_get_value_outside_bounds():
"""Check the generated values outside of the time array"""
tendency = StepsTendency(user_time=[1, 2, 3], user_value=[2, 4, 8], user_end=4)
_, values = tendency.get_value(np.array([-1, 0, 4.5, 5]))
assert list(values) == [2, 2, 8, 8]


def test_get_derivative():
"""Check that the derivative is always zero."""
tendency = StepsTendency(user_time=[0, 2, 4], user_value=[1, 3, 5], user_end=6)
derivatives = tendency.get_derivative(np.array([0, 1, 2, 3, 4, 5, 6]))
assert np.all(derivatives == 0)


@pytest.mark.parametrize("value", [[1, 2, 3], [1.5, 2.5, 3.5], ["a", "b", "c"]])
def test_value_types(value):
"""Test that int, float, and str steps are all supported."""
tendency = StepsTendency(user_time=[0, 2, 4], user_value=value, user_end=6)
assert not tendency.annotations
assert tendency.value_type is type(value[0])
assert list(tendency.value) == value
48 changes: 48 additions & 0 deletions tests/test_waveform.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from waveform_editor.tendencies.linear import LinearTendency
from waveform_editor.tendencies.periodic.sine_wave import SineWaveTendency
from waveform_editor.tendencies.smooth import SmoothTendency
from waveform_editor.tendencies.steps import StepsTendency
from waveform_editor.waveform import Waveform

DD_VERSION = "3.42.0"
Expand Down Expand Up @@ -297,6 +298,53 @@ def test_multiple_tendencies_mixed():
assert waveform.annotations


def test_steps_tendency_chained():
"""Test a steps tendency chained with a constant tendency in a waveform."""
waveform = Waveform(
waveform=[
{
"user_type": "steps",
"user_time": [0, 2, 4],
"user_value": [1, 3, 5],
"user_end": 6,
"line_number": 1,
},
{
"user_type": "constant",
"user_duration": 2,
"line_number": 2,
},
]
)
assert not waveform.annotations
assert isinstance(waveform.tendencies[0], StepsTendency)
assert isinstance(waveform.tendencies[1], ConstantTendency)
# The constant tendency without an explicit value inherits the last step's value
assert waveform.tendencies[1].value == 5

times, values = waveform.get_value(np.linspace(0, 8, 9))
assert np.allclose(values, [1, 1, 3, 3, 5, 5, 5, 5, 5])


def test_steps_tendency_string_values():
"""Test a steps tendency with string values."""
waveform = Waveform(
waveform=[
{
"user_type": "steps",
"user_time": [0, 10, 20],
"user_value": ["ohmic", "nbi", "ec"],
"user_end": 30,
"line_number": 1,
},
]
)
assert not waveform.annotations
assert waveform.value_type is str
_, values = waveform.get_value(np.array([0, 15, 25]))
assert list(values) == ["ohmic", "nbi", "ec"]


def test_dtype_flt_dd_path():
"""Test float field types."""

Expand Down
19 changes: 11 additions & 8 deletions waveform_editor/derived_waveform.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from asteval import Interpreter

from waveform_editor.base_waveform import BaseWaveform
from waveform_editor.tendencies.util import merge_value_types

NUMPY_UFUNCS = {}
for name in np.__all__:
Expand Down Expand Up @@ -115,9 +116,10 @@ def rename_dependency(self, old_name, new_name):
self.prepare_expression()

def _validate_dependencies(self):
"""Warn if a dependency doesn't exist, or if the dependencies that do
exist don't have a compatible type. Mixing int and float dependencies
is allowed and results in a float-typed derived waveform.
"""Warn if a dependency doesn't exist, if a dependency is string-typed, or
if the dependencies that do exist don't have a compatible type. Mixing int
and float dependencies is allowed and results in a float-typed derived
waveform.
"""
if not self.dependencies:
return
Expand All @@ -138,17 +140,18 @@ def _validate_dependencies(self):
self.annotations.add(
0, "Derived waveforms cannot depend on string-typed waveforms.\n"
)
elif dependency_types <= {int, float}:
self.value_type = float if float in dependency_types else int
elif len(dependency_types) == 1:
self.value_type = dependency_types.pop()
else:
return

merged_type = merge_value_types(dependency_types)
if merged_type is None:
type_names = sorted(t.__name__ for t in dependency_types)
self.annotations.add(
0,
"All dependencies of a derived waveform must have the same "
f"type, or be a mix of int and float. Found: {type_names}\n",
)
else:
self.value_type = merged_type

def _build_eval_context(self, time: np.ndarray) -> dict:
"""Build the evaluation context dictionary with dependencies resolved.
Expand Down
Loading
Loading