-
Notifications
You must be signed in to change notification settings - Fork 107
adding graph timeseries #807
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
Changes from all commits
f650998
dc51e7c
5d0fa4b
efe9527
a96f38d
12680c2
07b8b60
3a97775
827dcf6
f47a978
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| Graph Time Series Condition | ||
| ============================= | ||
|
|
||
| .. currentmodule:: pina.condition.graph_time_series_condition | ||
|
|
||
| .. automodule:: pina._src.condition.graph_time_series_condition | ||
|
|
||
| .. autoclass:: pina._src.condition.graph_time_series_condition.GraphTimeSeriesCondition | ||
| :members: | ||
| :show-inheritance: |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| Time Series Condition | ||
| ======================= | ||
|
|
||
| .. currentmodule:: pina.condition.time_series_condition | ||
|
|
||
| .. automodule:: pina._src.condition.time_series_condition | ||
|
|
||
| .. autoclass:: pina._src.condition.time_series_condition.TimeSeriesCondition | ||
| :members: | ||
| :show-inheritance: |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| """Module for the TimeSeriesCondition class.""" | ||
|
|
||
| import torch | ||
| from pina._src.core.utils import check_consistency, check_positive_integer | ||
| from pina._src.data.manager.data_manager import _DataManager | ||
| from pina._src.condition.time_series_condition import TimeSeriesCondition | ||
| from pina._src.core.label_tensor import LabelTensor | ||
| from pina._src.condition.base_condition import BaseCondition | ||
| from torch_geometric.data import Data | ||
| from pina._src.core.graph import Graph | ||
|
|
||
|
|
||
| class GraphTimeSeriesCondition(TimeSeriesCondition): | ||
| """ | ||
| The :class:`TimeSeriesCondition` class represents an autoregressive time | ||
| series condition defined by temporal ``input`` data. The input is expected | ||
| to have shape ``[trajectories, time_steps, *features]``, where the second | ||
| dimension corresponds to the temporal evolution of each trajectory. | ||
|
|
||
| During training, the condition automatically extracts overlapping temporal | ||
| windows from the trajectories. The parameter ``unroll_length`` defines the | ||
| number of consecutive time steps contained in each temporal window, while | ||
| ``n_windows`` controls how many temporal windows are created from the | ||
| available trajectories. | ||
|
|
||
| Internally, the unrolled data is stored as a tensor of shape | ||
| ``[trajectories, n_windows, unroll_length, *features]``. | ||
|
|
||
| Supported data types include :class:`~pina.label_tensor.LabelTensor` and | ||
| :class:`torch.Tensor`. | ||
|
|
||
| :Example: | ||
|
|
||
| >>> from pina import Condition, LabelTensor | ||
| >>> import torch | ||
|
|
||
| >>> data = LabelTensor(torch.rand(5, 10, 2), labels=["u", "v"]) | ||
| >>> condition = Condition(input=data, unroll_length=5, n_windows=3) | ||
| """ | ||
|
|
||
| # Available fields and input data types | ||
| __fields__ = ["input", "unroll_length", "n_windows", "key", "randomize"] | ||
| _avail_input_cls = (Data, Graph) | ||
|
|
||
| def __new__(cls, input, n_windows, unroll_length, key="x", randomize=False): | ||
| # Check consistency | ||
| check_consistency(input, cls._avail_input_cls) | ||
| check_consistency(randomize, bool) | ||
| check_consistency(key, str) | ||
| check_positive_integer(n_windows, strict=True) | ||
| check_positive_integer(unroll_length, strict=True) | ||
|
|
||
| return BaseCondition.__new__(cls) | ||
|
|
||
| def store_data(self, **kwargs): | ||
| """ | ||
| Store the unrolled time-series input data. | ||
|
|
||
| The method extracts the time-series input data and creates the temporal | ||
| windows based on the specified ``unroll_length`` and ``n_windows``. | ||
|
|
||
| :param dict kwargs: The keyword arguments containing the data to be | ||
| stored. | ||
| :return: A dictionary-like structure containing the stored data. | ||
| :rtype: _DataManager | ||
| """ | ||
| # Extract unrolling parameters from kwargs | ||
| unroll_length = kwargs.get("unroll_length") | ||
| n_windows = kwargs.get("n_windows") | ||
| randomize = kwargs.get("randomize", False) | ||
| key = kwargs.get("key", "x") | ||
| graph = kwargs.get("input") | ||
|
|
||
| # Create unrolled windows from the input data | ||
| if not hasattr(graph, key): | ||
| raise ValueError( | ||
| f"The provided graph does not have the specified key '{key}'." | ||
| ) | ||
|
|
||
| unrolled_data = self._unroll( | ||
| data=graph.__getattribute__(key), | ||
| n_windows=n_windows, | ||
| unroll_length=unroll_length, | ||
| randomize=randomize, | ||
| ) | ||
| graph.__setattr__(key, unrolled_data) | ||
|
|
||
| return _DataManager(input=graph) | ||
|
|
||
| def evaluate(self, batch, solver): | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This method appears to be identical to the one defined in
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. now some small differences in accessing the node data, I would keep it otherwise several |
||
| """ | ||
| Evaluate the residual of the condition on the given batch using the | ||
| solver. | ||
|
|
||
| This method computes the per-step residuals through autoregressive | ||
| unrolling. A forward pass of the solver's model is performed at each | ||
| time step, and the per-step residuals (predicted - target) are | ||
| returned as a stacked tensor. | ||
|
|
||
| The returned tensor preserves all per-step residual values without | ||
| reduction or loss aggregation. | ||
|
|
||
| :param dict batch: The batch containing the data required by the | ||
| condition evaluation. | ||
| :param SolverInterface solver: The solver used to perform the forward | ||
| pass and compute the residual. The solver provides access to the | ||
| model and its parameters, which may be necessary for evaluating the | ||
| condition residual. | ||
| :raises ValueError: If the input tensor in the batch has less than 4 | ||
| dimensions. | ||
| :return: The stacked per-step residual tensor of shape | ||
| ``[time_steps - 1, trajectories, windows, *features]``. | ||
| :rtype: torch.Tensor | LabelTensor | ||
| """ | ||
| # Raise error if input tensor does not have at least 4 dimensions | ||
| if batch["input"].x.dim() < 4: | ||
| raise ValueError( | ||
| "The provided input tensor must have at least 4 dimensions:" | ||
| " [trajectories, windows, time_steps, *features]." | ||
| f" Got shape {batch['input'].shape}." | ||
| ) | ||
|
|
||
| # Copy the kwargs to avoid modifying the original settings | ||
| kwargs = solver._kwargs.copy() | ||
|
|
||
| # Extract the initial state and initialize the step-wise residuals list | ||
| current_state = batch["input"].x[:, :, 0, :] | ||
| residuals = [] | ||
|
|
||
| # Iterate over the time steps | ||
| for step in range(1, batch["input"].x.shape[2]): | ||
|
|
||
| # Pre-process, forward, and post-process the current state | ||
| processed_input = solver.preprocess_step(current_state, **kwargs) | ||
| output = solver.forward(processed_input) | ||
| predicted_state = solver.postprocess_step(output, **kwargs) | ||
|
|
||
| # Retrieve the target and compute the step-wise residual | ||
| target_state = batch["input"].x[:, :, step, :] | ||
| step_residual = predicted_state - target_state | ||
| residuals.append(step_residual) | ||
|
|
||
| # Update the current state for the next iteration | ||
| current_state = predicted_state | ||
|
|
||
| # Stack the step-wise residuals | ||
| return torch.stack(residuals).as_subclass(torch.Tensor) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -91,7 +91,7 @@ def _check_type_consistency(self, **kwargs): | |
| self._check_edge_index_consistency(edge_index) | ||
| if "x" in kwargs: | ||
| x = kwargs["x"] | ||
| self._check_x_consistency(x, pos) | ||
| # self._check_x_consistency(x, pos) | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why is this check bypassed?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. For time-series, you typically have 3D tensor: n_nodes, n_timestep, n_features (even more sometimes...)
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we delete the |
||
| if "edge_attr" in kwargs: | ||
| edge_attr = kwargs["edge_attr"] | ||
| self._check_edge_attr_consistency(edge_attr, edge_index) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I noticed there is neither a
rstfile forTime Series Conditionnor a reference in the_code.rstfile. Is it possibile to add it in this PR, instead of opening a new one?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yes