id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
300
from bisect import bisect_left, bisect_right import itertools import logging from typing import Any, Callable, Dict, Iterable, Mapping, Sequence, Tuple, Union import warnings import numpy as np import pandas as pd from merlion.utils.misc import ValIterOrderedDict from merlion.utils.resample import ( AggregationPolicy, AlignPolicy, MissingValuePolicy, get_date_offset, infer_granularity, reindex_df, to_pd_datetime, to_timestamp, to_offset, ) class UnivariateTimeSeries(pd.Series): """ Please read the `tutorial <tutorials/TimeSeries>` before reading this API doc. This class is a time-indexed ``pd.Series`` which represents a univariate time series. For the most part, it supports all the same features as ``pd.Series``, with the following key differences to iteration and indexing: 1. Iterating over a `UnivariateTimeSeries` is implemented as .. code-block:: python for timestamp, value in univariate: # do stuff... where ``timestamp`` is a Unix timestamp, and ``value`` is the corresponding time series value. 2. Integer index: ``u[i]`` yields the tuple ``(u.time_stamps[i], u.values[i])`` 3. Slice index: ``u[i:j:k]`` yields a new ``UnivariateTimeSeries(u.time_stamps[i:j:k], u.values[i:j:k])`` The class also supports the following additional features: 1. ``univariate.time_stamps`` returns the list of Unix timestamps, and ``univariate.values`` returns the list of the time series values. You may access the ``pd.DatetimeIndex`` directly with ``univariate.index`` (or its ``np.ndarray`` representation with ``univariate.np_time_stamps``), and the ``np.ndarray`` of values with ``univariate.np_values``. 2. ``univariate.concat(other)`` will concatenate the UnivariateTimeSeries ``other`` to the right end of ``univariate``. 3. ``left, right = univariate.bisect(t)`` will split the univariate at the given timestamp ``t``. 4. ``window = univariate.window(t0, tf)`` will return the subset of the time series occurring between timestamps ``t0`` (inclusive) and ``tf`` (non-inclusive) 5. ``series = univariate.to_pd()`` will convert the `UnivariateTimeSeries` into a regular ``pd.Series`` (for compatibility). 6. ``univariate = UnivariateTimeSeries.from_pd(series)`` uses a time-indexed ``pd.Series`` to create a `UnivariateTimeSeries` object directly. .. document special functions .. automethod:: __getitem__ .. automethod:: __iter__ """ def __init__( self, time_stamps: Union[None, Sequence[Union[int, float]]], values: Sequence[float], name: str = None, freq="1h", ): """ :param time_stamps: a sequence of Unix timestamps. You may specify ``None`` if you only have ``values`` with no specific time stamps. :param values: a sequence of univariate values, where ``values[i]`` occurs at time ``time_stamps[i]`` :param name: the name of the univariate time series :param freq: if ``time_stamps`` is not provided, the univariate is assumed to be sampled at frequency ``freq``. ``freq`` may be a string (e.g. ``"1h"``), timedelta, or ``int``/``float`` (in units of seconds). """ is_pd = isinstance(values, pd.Series) if name is None and is_pd: name = values.name if is_pd and isinstance(values.index, pd.DatetimeIndex): super().__init__(values, name=name) elif is_pd and values.index.dtype == "O": super().__init__(values.values, name=name, index=pd.to_datetime(values.index)) else: if time_stamps is None: freq = to_offset(freq) if is_pd and values.index.dtype in ("int64", "float64"): index = pd.to_datetime(0) + freq * values.index else: index = pd.date_range(start=0, periods=len(values), freq=freq) else: index = to_pd_datetime(time_stamps) super().__init__(np.asarray(values), index=index, name=name, dtype=float) if len(self) >= 3 and self.index.freq is None: self.index.freq = pd.infer_freq(self.index) self.index.name = _time_col_name def np_time_stamps(self): """ :rtype: np.ndarray :return: the ``numpy`` representation of this time series's Unix timestamps """ return to_timestamp(self.index.values) def np_values(self): """ :rtype: np.ndarray :return: the ``numpy`` representation of this time series's values """ return super().values def time_stamps(self): """ :rtype: List[float] :return: the list of Unix timestamps for the time series """ return self.np_time_stamps.tolist() def values(self): """ :rtype: List[float] :return: the list of values for the time series. """ return self.np_values.tolist() def t0(self): """ :rtype: float :return: the first timestamp in the univariate time series. """ return self.np_time_stamps[0] def tf(self): """ :rtype: float :return: the final timestamp in the univariate time series. """ return self.np_time_stamps[-1] def is_empty(self): """ :rtype: bool :return: True if the univariate is empty, False if not. """ return len(self) == 0 def __iter__(self): """ The i'th item in the iterator is the tuple ``(self.time_stamps[i], self.values[i])``. """ return itertools.starmap(lambda t, x: (t.item(), x.item()), zip(self.np_time_stamps, self.np_values)) def __getitem__(self, i: Union[int, slice]): """ :param i: integer index or slice :rtype: Union[Tuple[float, float], UnivariateTimeSeries] :return: ``(self.time_stamps[i], self.values[i])`` if ``i`` is an integer. ``UnivariateTimeSeries(self.time_series[i], self.values[i])`` if ``i`` is a slice. """ if isinstance(i, int): return self.np_time_stamps[i].item(), self.np_values[i].item() elif isinstance(i, slice): return UnivariateTimeSeries.from_pd(self.iloc[i]) else: raise KeyError( f"Indexing a `UnivariateTimeSeries` with key {i} of " f"type {type(i).__name__} is not supported. Try " f"using loc[] or iloc[] for more complicated " f"indexing." ) def __eq__(self, other): return self.time_stamps == other.time_stamps and (self.np_values == other.np_values).all() def copy(self, deep=True): """ Copies the `UnivariateTimeSeries`. Simply a wrapper around the ``pd.Series.copy()`` method. """ return UnivariateTimeSeries.from_pd(super().copy(deep=deep)) def concat(self, other): """ Concatenates the `UnivariateTimeSeries` ``other`` to the right of this one. :param UnivariateTimeSeries other: another `UnivariateTimeSeries` :rtype: UnivariateTimeSeries :return: concatenated univariate time series """ return UnivariateTimeSeries.from_pd(pd.concat((self, other)), name=self.name) def bisect(self, t: float, t_in_left: bool = False): """ Splits the time series at the point where the given timestamp occurs. :param t: a Unix timestamp or datetime object. Everything before time ``t`` is in the left split, and everything after time ``t`` is in the right split. :param t_in_left: if ``True``, ``t`` is in the left split. Otherwise, ``t`` is in the right split. :rtype: Tuple[UnivariateTimeSeries, UnivariateTimeSeries] :return: the left and right splits of the time series. """ t = to_pd_datetime(t) if t_in_left: i = bisect_right(self.index, t) else: i = bisect_left(self.index, t) return self[:i], self[i:] def window(self, t0: float, tf: float, include_tf: bool = False): """ :param t0: The timestamp/datetime at the start of the window (inclusive) :param tf: The timestamp/datetime at the end of the window (inclusive if ``include_tf`` is ``True``, non-inclusive otherwise) :param include_tf: Whether to include ``tf`` in the window. :rtype: UnivariateTimeSeries :return: The subset of the time series occurring between timestamps ``t0`` (inclusive) and ``tf`` (included if ``include_tf`` is ``True``, excluded otherwise). """ times = self.index t0, tf = to_pd_datetime(t0), to_pd_datetime(tf) i_0 = bisect_left(times, t0) i_f = bisect_right(times, tf) if include_tf else bisect_left(times, tf) return self[i_0:i_f] def to_dict(self) -> Dict[float, float]: """ :return: A dictionary representing the data points in the time series. """ return dict(zip(self.time_stamps, self.values)) def from_dict(cls, obj: Dict[float, float], name=None): """ :param obj: A dictionary of timestamp - value pairs :param name: the name to assign the output :rtype: UnivariateTimeSeries :return: the `UnivariateTimeSeries` represented by series. """ time_stamps, values = [], [] for point in sorted(obj.items(), key=lambda p: p[0]): time_stamps.append(point[0]) values.append(point[1]) return cls(time_stamps, values, name) def to_pd(self) -> pd.Series: """ :return: A pandas Series representing the time series, indexed by time. """ return pd.Series(self.np_values, index=self.index, name=self.name) def from_pd(cls, series: Union[pd.Series, pd.DataFrame], name=None, freq="1h"): """ :param series: a ``pd.Series``. If it has a``pd.DatetimeIndex``, we will use that index for the timestamps. Otherwise, we will create one at the specified frequency. :param name: the name to assign the output :param freq: if ``series`` is not indexed by time, this is the frequency at which we will assume it is sampled. :rtype: UnivariateTimeSeries :return: the `UnivariateTimeSeries` represented by series. """ if series is None: return None if isinstance(series, TimeSeries) and series.dim == 1: series = list(series.univariates)[0] if isinstance(series, UnivariateTimeSeries): if name is not None: series.name = name return series if isinstance(series, pd.DataFrame) and series.shape[1] == 1: series = series.iloc[:, 0] return cls(time_stamps=None, values=series.astype(float), name=name, freq=freq) def to_ts(self, name=None): """ :name: a name to assign the univariate when converting it to a time series. Can override the existing name. :rtype: TimeSeries :return: A `TimeSeries` representing this univariate time series. """ if self.name is None and name is None: return TimeSeries([self]) else: name = name if self.name is None else self.name return TimeSeries({name: self}) def empty(cls, name=None): """ :rtype: `UnivariateTimeSeries` :return: A Merlion `UnivariateTimeSeries` that has empty timestamps and values. """ return cls([], [], name) The provided code snippet includes necessary dependencies for implementing the `assert_equal_timedeltas` function. Write a Python function `def assert_equal_timedeltas(time_series: UnivariateTimeSeries, granularity, offset=None)` to solve the following problem: Checks that all time deltas in the time series are equal, either to each other, or a pre-specified timedelta (in seconds). Here is the function: def assert_equal_timedeltas(time_series: UnivariateTimeSeries, granularity, offset=None): """ Checks that all time deltas in the time series are equal, either to each other, or a pre-specified timedelta (in seconds). """ if len(time_series) <= 2: return index = time_series.index offset = pd.to_timedelta(0) if offset is None else offset expected = pd.date_range(start=index[0], end=index[-1], freq=granularity) + offset deviation = expected - time_series.index[-len(expected) :] max_deviation = np.abs(deviation.total_seconds().values).max() assert max_deviation < 2e-3, f"Data must have the same time difference between each element of the time series"
Checks that all time deltas in the time series are equal, either to each other, or a pre-specified timedelta (in seconds).
301
from abc import ABC, abstractmethod import copy import logging from typing import Tuple import numpy as np import pandas as pd from scipy.special import gammaln, multigammaln from scipy.linalg import pinv, pinvh from scipy.stats import ( bernoulli, beta, norm, t as student_t, invgamma, multivariate_normal as mvnorm, invwishart, multivariate_t as mvt, ) from merlion.utils import TimeSeries, UnivariateTimeSeries, to_timestamp, to_pd_datetime The provided code snippet includes necessary dependencies for implementing the `_log_pdet` function. Write a Python function `def _log_pdet(a)` to solve the following problem: Log pseudo-determinant of a (possibly singular) matrix A. Here is the function: def _log_pdet(a): """ Log pseudo-determinant of a (possibly singular) matrix A. """ eigval, eigvec = np.linalg.eigh(a) return np.sum(np.log(eigval[eigval > 0]))
Log pseudo-determinant of a (possibly singular) matrix A.
302
from collections import OrderedDict import inspect from typing import List, Union import pandas as pd from merlion.utils.misc import combine_signatures, parse_basic_docstring from merlion.utils.time_series import TimeSeries def df_to_time_series( df: pd.DataFrame, time_col: str = None, timestamp_unit="s", data_cols: Union[str, List[str]] = None ) -> TimeSeries: """ Converts a general ``pandas.DataFrame`` to a `TimeSeries` object. :param df: the dataframe to process :param time_col: the name of the column specifying time. If ``None`` is specified, the existing index is used if it is a ``DatetimeIndex``. Otherwise, the first column is used. :param timestamp_unit: if the time column is in Unix timestamps, this is the unit of the timestamp. :param data_cols: the columns representing the actual data values of interest. """ # Set up the time index if not isinstance(df.index, pd.DatetimeIndex): if time_col is None: time_col = df.columns[0] elif time_col not in df.columns: raise KeyError(f"Expected `time_col` to be in {df.columns}. Got {time_col}.") df[time_col] = pd.to_datetime(df[time_col], unit=None if df[time_col].dtype == "O" else timestamp_unit) df = df.set_index(time_col) df = df.sort_index() # Get only the desired columns from the dataframe if data_cols is not None: data_cols = [data_cols] if not isinstance(data_cols, (list, tuple)) else data_cols if not all(c in df.columns for c in data_cols): raise KeyError(f"Expected each of `data_cols` to be in {df.colums}. Got {data_cols}.") df = df[data_cols] # Convert the dataframe to a time series & return it return TimeSeries.from_pd(df) def combine_signatures(sig1: Union[inspect.Signature, None], sig2: Union[inspect.Signature, None]): """ Utility function which combines the signatures of two functions. """ if sig1 is None: return sig2 if sig2 is None: return sig1 # Get all params from sig1 sig1 = deepcopy(sig1) params = list(sig1.parameters.values()) for n, param in enumerate(params): if param.kind in {inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD}: break else: n = len(params) # Add non-overlapping params from sig2 for param in sig2.parameters.values(): if param.kind in {inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD}: break if param.name not in sig1.parameters: params.insert(n, param) n += 1 return sig1.replace(parameters=params) def parse_basic_docstring(docstring): """ Parse the docstring of a model config's ``__init__``, or other basic docstring. """ docstring_lines = [""] if docstring is None else docstring.split("\n") prefix, suffix, param_dict = [], [], OrderedDict() non_empty_lines = [line for line in docstring_lines if len(line) > 0] indent = 0 if len(non_empty_lines) == 0 else len(re.search(r"^\s*", non_empty_lines[0]).group(0)) for line in docstring_lines: line = line[indent:] match = re.search(r":param\s*(\w+):", line) if match is not None: param = match.group(1) param_dict[param] = [line] elif len(param_dict) == 0: prefix.append(line) elif len(suffix) > 0 or re.match(r"^[^\s]", line): # not starting a param doc, but un-indented --> suffix suffix.append(line) else: param_dict[list(param_dict.keys())[-1]].append(line) return prefix, suffix, param_dict The provided code snippet includes necessary dependencies for implementing the `data_io_decorator` function. Write a Python function `def data_io_decorator(func)` to solve the following problem: Decorator to standardize docstrings for data I/O functions. Here is the function: def data_io_decorator(func): """ Decorator to standardize docstrings for data I/O functions. """ def wrapper(*args, **kwargs): return func(*args, **kwargs) # Parse the docstrings of the base df_to_time_series function & decorated function. prefix, suffix, params = parse_basic_docstring(func.__doc__) base_prefix, base_suffix, base_params = parse_basic_docstring(df_to_time_series.__doc__) # Combine the prefixes. Base prefix starts after the first line break. i_lb = [i for i, line in enumerate(base_prefix) if line == ""][1] prefix = ("\n".join(prefix) if any([line != "" for line in prefix]) else "") + "\n".join(base_prefix[i_lb:]) # The base docstring has no suffix, so just use the function's suffix = "\n".join(suffix) if any([line != "" for line in suffix]) else "" # Combine the parameter lists for param, docstring_lines in base_params.items(): if param not in params: params[param] = "\n".join(docstring_lines).rstrip("\n") # Combine the signatures, but remove some parameters that are specific to the original (as well as kwargs). new_sig_params = [] sig = combine_signatures(inspect.signature(func), inspect.signature(df_to_time_series)) for param in sig.parameters.values(): if param.kind in {inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD}: break if param.name not in ["df"]: new_sig_params.append(param) sig = sig.replace(parameters=new_sig_params) # Update the signature and docstring of the wrapper we are returning. Use only the params in the new signature. wrapper.__signature__ = sig params = OrderedDict((p, params[p]) for p in sig.parameters if p in params) wrapper.__doc__ = (prefix or "") + "\n" + "\n".join(params.values()) + "\n\n" + (suffix or "") return wrapper
Decorator to standardize docstrings for data I/O functions.
303
from collections import OrderedDict import inspect from typing import List, Union import pandas as pd from merlion.utils.misc import combine_signatures, parse_basic_docstring from merlion.utils.time_series import TimeSeries def df_to_time_series( df: pd.DataFrame, time_col: str = None, timestamp_unit="s", data_cols: Union[str, List[str]] = None ) -> TimeSeries: """ Converts a general ``pandas.DataFrame`` to a `TimeSeries` object. :param df: the dataframe to process :param time_col: the name of the column specifying time. If ``None`` is specified, the existing index is used if it is a ``DatetimeIndex``. Otherwise, the first column is used. :param timestamp_unit: if the time column is in Unix timestamps, this is the unit of the timestamp. :param data_cols: the columns representing the actual data values of interest. """ # Set up the time index if not isinstance(df.index, pd.DatetimeIndex): if time_col is None: time_col = df.columns[0] elif time_col not in df.columns: raise KeyError(f"Expected `time_col` to be in {df.columns}. Got {time_col}.") df[time_col] = pd.to_datetime(df[time_col], unit=None if df[time_col].dtype == "O" else timestamp_unit) df = df.set_index(time_col) df = df.sort_index() # Get only the desired columns from the dataframe if data_cols is not None: data_cols = [data_cols] if not isinstance(data_cols, (list, tuple)) else data_cols if not all(c in df.columns for c in data_cols): raise KeyError(f"Expected each of `data_cols` to be in {df.colums}. Got {data_cols}.") df = df[data_cols] # Convert the dataframe to a time series & return it return TimeSeries.from_pd(df) class TimeSeries: """ Please read the `tutorial <tutorials/TimeSeries>` before reading this API doc. This class represents a general multivariate time series as a wrapper around a number of (optionally named) `UnivariateTimeSeries`. A `TimeSeries` object is initialized as ``time_series = TimeSeries(univariates)``, where ``univariates`` is either a list of `UnivariateTimeSeries`, or a dictionary mapping string names to their corresponding `UnivariateTimeSeries` objects. Because the individual ``univariates`` need not be sampled at the same times, an important concept for `TimeSeries` is *alignment*. We say that a `TimeSeries` is *aligned* if all of its univariates have observations sampled at the exact set set of times. One may access the `UnivariateTimeSeries` comprising this `TimeSeries` in four ways: 1. Iterate over the individual univariates using .. code-block:: python for var in time_series.univariates: # do stuff with each UnivariateTimeSeries var 2. Access an individual `UnivariateTimeSeries` by name as ``time_series.univariates[name]``. If you supplied unnamed univariates to the constructor (i.e. using a list), the name of a univariate will just be its index in that list. 3. Get the list of each univariate's name with ``time_series.names``. 4. Iterate over named univariates as .. code-block:: python for name, var in time_series.items(): # do stuff Note that this is equivalent to iterating over ``zip(time_series.names, time_series.univariates)``. This class supports the following additional features as well: 1. Interoperability with ``pandas`` - ``df = time_series.to_pd()`` yields a time-indexed ``pd.DataFrame``, where each column (with the appropriate name) corresponds to a variable. Missing values are ``NaN``. - ``time_series = TimeSeries.from_pd(df)`` takes a time-indexed ``pd.DataFrame`` and returns a corresponding `TimeSeries` object (missing values are handled appropriately). The order of ``time_series.univariates`` is the order of ``df.keys()``. 2. Automated alignment: ``aligned = time_series.align()`` resamples each of ``time_series.univariates`` so that they all have the same timestamps. By default, this is done by taking the union of all timestamps present in any individual univariate time series, and imputing missing values via interpolation. See the method documentation for details on how you may configure the alignment policy. 3. Transparent indexing and iteration for `TimeSeries` which have all univariates aligned (i.e. they all have the same timestamps) - Get the length and shape of the time series (equal to the number of observations in each individual univariate). Note that if the time series is not aligned, we will return the length/shape of an equivalent ``pandas`` dataframe and emit a warning. - Index ``time_series[i] = (times[i], (x1[i], ..., xn[i]))`` (assuming ``time_series`` has ``n`` aligned univariates with timestamps ``times``, and ``xk = time_series.univariates[k-1].values``). Slice returns a `TimeSeries` object and works as one would expect. - Assuming ``time_series`` has ``n`` variables, you may iterate with .. code-block:: python for t_i, (x1_i, ..., xn_i) in time_series: # do stuff Notably, this lets you call ``times, val_vectors = zip(*time_series)`` 4. Time-based queries for any time series - Get the two sub `TimeSeries` before and after a timestamp ``t`` via ``left, right = time_series.bisect(t)`` - Get the sub `TimeSeries` between timestamps ``t0`` (inclusive) and ``tf`` (non-inclusive) via ``window = time_series.window(t0, tf)`` 5. Concatenation: two `TimeSeries` may be concatenated (in time) as ``time_series = time_series_1 + time_series_2``. .. document special functions .. automethod:: __getitem__ .. automethod:: __iter__ """ def __init__( self, univariates: Union[Mapping[Any, UnivariateTimeSeries], Iterable[UnivariateTimeSeries]], *, freq: str = "1h", check_aligned=True, ): # Type/length checking of univariates if isinstance(univariates, Mapping): univariates = ValIterOrderedDict((str(k), v) for k, v in univariates.items()) assert all(isinstance(var, UnivariateTimeSeries) for var in univariates.values()) elif isinstance(univariates, Iterable): univariates = list(univariates) assert all(isinstance(var, UnivariateTimeSeries) for var in univariates) names = [str(var.name) for var in univariates] if len(set(names)) == len(names): names = [str(i) if name is None else name for i, name in enumerate(names)] univariates = ValIterOrderedDict(zip(names, univariates)) else: univariates = ValIterOrderedDict((str(i), v) for i, v in enumerate(univariates)) else: raise TypeError( "Expected univariates to be either a `Sequence[UnivariateTimeSeries]` or a " "`Mapping[Hashable, UnivariateTimeSeries]`." ) assert len(univariates) > 0 # Assign all the individual univariate series the appropriate names for name, var in univariates.items(): var.name = name # Set self.univariates and check if they are perfectly aligned self.univariates = univariates if check_aligned and self.dim > 1: t = self.univariates[self.names[0]].time_stamps self._is_aligned = all(self.univariates[name].time_stamps == t for name in self.names[1:]) else: self._is_aligned = len(univariates) <= 1 # Raise a warning if the univariates are too mis-aligned if check_aligned and not self.is_aligned: all_t0 = [var.index[0] for var in univariates if len(var) > 0] all_tf = [var.index[-1] for var in univariates if len(var) > 0] min_elapsed = min(tf - t0 for t0, tf in zip(all_t0, all_tf)) min_t0, max_t0 = min(all_t0), max(all_t0) min_tf, max_tf = min(all_tf), max(all_tf) if max_t0 - min_t0 > 0.1 * min_elapsed: logger.warning( f"The earliest univariate starts at {min_t0}, but the " f"latest univariate starts at {max_t0}, a difference of " f"{max_t0 - min_t0}. This is more than 10% of the length " f"of the shortest univariate ({min_elapsed}). You may " f"want to check that the univariates cover the same " f"window of time.", stack_info=True, ) if max_tf - min_tf > 0.1 * min_elapsed: logger.warning( f"The earliest univariate ends at {min_tf}, but the " f"latest univariate ends at {max_tf}, a difference of " f"{max_tf - min_tf}. This is more than 10% of the length " f"of the shortest univariate ({min_elapsed}). You may " f"want to check that the univariates cover the same " f"window of time.", stack_info=True, ) def names(self): """:return: The list of the names of the univariates.""" return list(self.univariates.keys()) def items(self): """:return: Iterator over ``(name, univariate)`` tuples.""" return self.univariates.items() def dim(self) -> int: """ :return: The dimension of the time series (the number of variables). """ return len(self.univariates) def rename(self, mapper: Union[Iterable[str], Mapping[str, str], Callable[[str], str]]): """ :param mapper: Dict-like or function transformations to apply to the univariate names. Can also be an iterable of new univariate names. :return: the time series with renamed univariates. """ if isinstance(mapper, Callable): mapper = [mapper(old) for old in self.names] elif isinstance(mapper, Mapping): mapper = [mapper.get(old, old) for old in self.names] univariates = ValIterOrderedDict((new_name, var) for new_name, var in zip(mapper, self.univariates)) return self.__class__(univariates) def is_aligned(self) -> bool: """ :return: Whether all individual variable time series are sampled at the same time stamps, i.e. they are aligned. """ return self._is_aligned def index(self): return to_pd_datetime(self.np_time_stamps) def np_time_stamps(self): """ :rtype: np.ndarray :return: the ``numpy`` representation of this time series's Unix timestamps """ return np.unique(np.concatenate([var.np_time_stamps for var in self.univariates])) def time_stamps(self): """ :rtype: List[float] :return: the list of Unix timestamps for the time series """ return self.np_time_stamps.tolist() def t0(self) -> float: """ :rtype: float :return: the first timestamp in the time series. """ return min(var.t0 for var in self.univariates) def tf(self) -> float: """ :rtype: float :return: the final timestamp in the time series. """ return max(var.tf for var in self.univariates) def _txs_to_vec(txs): """ Helper function that converts [(t_1[i], x_1[i]), ..., (t_k[i], x_k[i])], i.e. [var[i] for var in self.univariates], into the desired output form (t_1[i], (x_1[i], ..., x_k[i])). """ return txs[0][0], tuple(tx[1] for tx in txs) def __iter__(self): """ Only supported if all individual variable time series are sampled at the same time stamps. The i'th item of the iterator is the tuple ``(time_stamps[i], tuple(var.values[i] for var in self.univariates))``. """ if not self.is_aligned: raise RuntimeError( "The univariates comprising this time series are not aligned " "(they have different time stamps), but alignment is required " "to iterate over the time series." ) return map(self._txs_to_vec, zip(*self.univariates)) def __getitem__(self, i: Union[int, slice]): """ Only supported if all individual variable time series are sampled at the same time stamps. :param i: integer index or slice. :rtype: Union[Tuple[float, Tuple[float]], TimeSeries] :return: If ``i`` is an integer, returns the tuple ``(time_stamps[i], tuple(var.values[i] for var in self.univariates))``. If ``i`` is a slice, returns the time series ``TimeSeries([var[i] for var in self.univariates])`` """ if not self.is_aligned: raise RuntimeError( "The univariates comprising this time series are not aligned " "(they have different time stamps), but alignment is required " "to index into the time series." ) if isinstance(i, int): return self._txs_to_vec([var[i] for var in self.univariates]) elif isinstance(i, slice): # ret must be aligned, so bypass the (potentially) expensive check univariates = ValIterOrderedDict([(k, v[i]) for k, v in self.items()]) ret = TimeSeries(univariates, check_aligned=False) ret._is_aligned = True return ret else: raise KeyError( f"Indexing a `TimeSeries` with key {i} of type " f"{type(i).__name__} not supported. Perhaps you " f"meant to index into `time_series.univariates`, " f"rather than `time_series`?" ) def is_empty(self) -> bool: """ :return: whether the time series is empty """ return all(len(var) == 0 for var in self.univariates) def squeeze(self) -> UnivariateTimeSeries: """ :return: `UnivariateTimeSeries` if the time series is univariate; otherwise returns itself, a `TimeSeries` """ if self.dim == 1: return self.univariates[self.names[0]] return self def __len__(self): """ :return: the number of observations in the time series """ if not self.is_aligned: warning = ( "The univariates comprising this time series are not aligned " "(they have different time stamps). The length returned is " "equal to the length of the _union_ of all time stamps present " "in any of the univariates." ) warnings.warn(warning) logger.warning(warning) return len(self.to_pd()) return len(self.univariates[self.names[0]]) def shape(self) -> Tuple[int, int]: """ :return: the shape of this time series, i.e. ``(self.dim, len(self))`` """ return self.dim, len(self) def __add__(self, other): """ Concatenates the `TimeSeries` ``other`` to the right of this one. :param TimeSeries other: :rtype: TimeSeries :return: concatenated time series """ return self.concat(other, axis=0) def concat(self, other, axis=0): """ Concatenates the `TimeSeries` ``other`` on the time axis if ``axis = 0`` or the variable axis if ``axis = 1``. :rtype: TimeSeries :return: concatenated time series """ assert axis in [0, 1] if axis == 0: assert self.dim == other.dim, ( f"Cannot concatenate a {self.dim}-dimensional time series with a {other.dim}-dimensional " f"time series on the time axis." ) assert self.names == other.names, ( f"Cannot concatenate time series on the time axis if they have two different sets of " f"variable names, {self.names} and {other.names}." ) univariates = ValIterOrderedDict( [(name, ts0.concat(ts1)) for (name, ts0), ts1 in zip(self.items(), other.univariates)] ) ret = TimeSeries(univariates, check_aligned=False) ret._is_aligned = self.is_aligned and other.is_aligned return ret else: univariates = ValIterOrderedDict([(name, var.copy()) for name, var in [*self.items(), other.items()]]) ret = TimeSeries(univariates, check_aligned=False) ret._is_aligned = self.is_aligned and other.is_aligned and self.time_stamps == other.time_stamps return ret def __eq__(self, other): if self.dim != other.dim: return False return all(u == v for u, v in zip(self.univariates, other.univariates)) def __repr__(self): return repr(self.to_pd()) def bisect(self, t: float, t_in_left: bool = False): """ Splits the time series at the point where the given timestamp ``t`` occurs. :param t: a Unix timestamp or datetime object. Everything before time ``t`` is in the left split, and everything after time ``t`` is in the right split. :param t_in_left: if ``True``, ``t`` is in the left split. Otherwise, ``t`` is in the right split. :rtype: Tuple[TimeSeries, TimeSeries] :return: the left and right splits of the time series. """ left, right = ValIterOrderedDict(), ValIterOrderedDict() for name, var in self.items(): left[name], right[name] = var.bisect(t, t_in_left) if self.is_aligned: left = TimeSeries(left, check_aligned=False) right = TimeSeries(right, check_aligned=False) left._is_aligned = True right._is_aligned = True return left, right else: return TimeSeries(left), TimeSeries(right) def window(self, t0: float, tf: float, include_tf: bool = False): """ :param t0: The timestamp/datetime at the start of the window (inclusive) :param tf: The timestamp/datetime at the end of the window (inclusive if ``include_tf`` is ``True``, non-inclusive otherwise) :param include_tf: Whether to include ``tf`` in the window. :return: The subset of the time series occurring between timestamps ``t0`` (inclusive) and ``tf`` (included if ``include_tf`` is ``True``, excluded otherwise). :rtype: `TimeSeries` """ return TimeSeries(ValIterOrderedDict([(k, var.window(t0, tf, include_tf)) for k, var in self.items()])) def to_pd(self) -> pd.DataFrame: """ :return: A pandas DataFrame (indexed by time) which represents this time series. Each variable corresponds to a column of the DataFrame. Timestamps which are present for one variable but not another, are represented with NaN. """ t = pd.DatetimeIndex([]) univariates = [(name, var.to_pd()[~var.index.duplicated()]) for name, var in self.items()] for _, var in univariates: t = t.union(var.index) t = t.sort_values() t.name = _time_col_name if len(t) >= 3: t.freq = pd.infer_freq(t) df = pd.DataFrame(np.full((len(t), len(univariates)), np.nan), index=t, columns=self.names) for name, var in univariates: df.loc[var.index, name] = var[~var.index.duplicated()] return df def to_csv(self, file_name, **kwargs): self.to_pd().to_csv(file_name, **kwargs) def from_pd(cls, df: Union[pd.Series, pd.DataFrame, np.ndarray], check_times=True, drop_nan=True, freq="1h"): """ :param df: A ``pandas.DataFrame`` with a ``DatetimeIndex``. Each column corresponds to a different variable of the time series, and the key of column (in sorted order) give the relative order of those variables in ``self.univariates``. Missing values should be represented with ``NaN``. May also be a ``pandas.Series`` for single-variable time series. :param check_times: whether to check that all times in the index are unique (up to the millisecond) and sorted. :param drop_nan: whether to drop all ``NaN`` entries before creating the time series. Specifying ``False`` is useful if you wish to impute the values on your own. :param freq: if ``df`` is not indexed by time, this is the frequency at which we will assume it is sampled. :rtype: TimeSeries :return: the `TimeSeries` object corresponding to ``df``. """ if df is None: return None elif isinstance(df, TimeSeries): return df elif isinstance(df, UnivariateTimeSeries): return cls([df]) elif isinstance(df, pd.Series): if drop_nan: df = df[~df.isna()] return cls({df.name: UnivariateTimeSeries.from_pd(df)}) elif isinstance(df, np.ndarray): arr = df.reshape(len(df), -1).T ret = cls([UnivariateTimeSeries(time_stamps=None, values=v, freq=freq) for v in arr], check_aligned=False) ret._is_aligned = True return ret elif not isinstance(df, pd.DataFrame): df = pd.DataFrame(df) # Time series is not aligned iff there are missing values aligned = df.shape[1] == 1 or not df.isna().any().any() # Check for a string-type index if df.index.dtype == "O": df = df.copy() df.index = pd.to_datetime(df.index) # Make sure there are no time duplicates (by milliseconds) if desired dt_index = isinstance(df.index, pd.DatetimeIndex) if check_times: if not df.index.is_unique: df = df[~df.index.duplicated()] if not df.index.is_monotonic_increasing: df = df.sort_index() if dt_index: times = df.index.values.astype("datetime64[ms]").astype(np.int64) df = df.reindex(pd.to_datetime(np.unique(times), unit="ms"), method="bfill") elif not aligned and not dt_index and df.index.dtype not in ("int64", "float64"): raise RuntimeError( f"We only support instantiating time series from a " f"``pd.DataFrame`` with missing values when the data frame is " f"indexed by time, int, or float. This dataframe's index is of " f"type {type(df.index).__name__}" ) if drop_nan and not aligned: ret = cls( ValIterOrderedDict( [(k, UnivariateTimeSeries.from_pd(ser[~ser.isna()], freq=freq)) for k, ser in df.items()] ), check_aligned=False, ) else: ret = cls( ValIterOrderedDict([(k, UnivariateTimeSeries.from_pd(ser, freq=freq)) for k, ser in df.items()]), check_aligned=False, ) ret._is_aligned = aligned return ret def from_ts_list(cls, ts_list, *, check_aligned=True): """ :param Iterable[TimeSeries] ts_list: iterable of time series we wish to form a multivariate time series with :param bool check_aligned: whether to check if the output time series is aligned :rtype: TimeSeries :return: A multivariate `TimeSeries` created from all the time series in the inputs. """ ts_list = list(ts_list) all_names = [set(ts.names) for ts in ts_list] if all( len(names_i.intersection(names_j)) == 0 for i, names_i in enumerate(all_names) for names_j in all_names[i + 1 :] ): univariates = ValIterOrderedDict(itertools.chain.from_iterable(ts.items() for ts in ts_list)) else: univariates = list(itertools.chain.from_iterable(ts.univariates for ts in ts_list)) return cls(univariates, check_aligned=check_aligned) def align( self, *, reference: Sequence[Union[int, float]] = None, granularity: Union[str, int, float] = None, origin: int = None, remove_non_overlapping=True, alignment_policy: AlignPolicy = None, aggregation_policy: AggregationPolicy = AggregationPolicy.Mean, missing_value_policy: MissingValuePolicy = MissingValuePolicy.Interpolate, ): """ Aligns all the univariates comprising this multivariate time series so that they all have the same time stamps. :param reference: A specific set of timestamps we want the resampled time series to contain. Required if ``alignment_policy`` is `AlignPolicy.FixedReference`. Overrides other alignment policies if specified. :param granularity: The granularity (in seconds) of the resampled time time series. Defaults to the GCD time difference between adjacent elements of ``time_series`` (otherwise). Ignored if ``reference`` is given or ``alignment_policy`` is `AlignPolicy.FixedReference`. Overrides other alignment policies if specified. :param origin: The first timestamp of the resampled time series. Only used if the alignment policy is `AlignPolicy.FixedGranularity`. :param remove_non_overlapping: If ``True``, we will only keep the portions of the univariates that overlap with each other. For example, if we have 3 univariates which span timestamps [0, 3600], [60, 3660], and [30, 3540], we will only keep timestamps in the range [60, 3540]. If ``False``, we will keep all timestamps produced by the resampling. :param alignment_policy: The policy we want to use to align the time series. - `AlignPolicy.FixedReference` aligns each single-variable time series to ``reference``, a user-specified sequence of timestamps. - `AlignPolicy.FixedGranularity` resamples each single-variable time series at the same granularity, aggregating windows and imputing missing values as desired. - `AlignPolicy.OuterJoin` returns a time series with the union of all timestamps present in any single-variable time series. - `AlignPolicy.InnerJoin` returns a time series with the intersection of all timestamps present in all single-variable time series. :param aggregation_policy: The policy used to aggregate windows of adjacent observations when downsampling. :param missing_value_policy: The policy used to impute missing values created when upsampling. :rtype: TimeSeries :return: The resampled multivariate time series. """ if self.is_empty(): if reference is not None or granularity is not None: logger.warning( "Attempting to align an empty time series to a set of reference time stamps or a " "fixed granularity. Doing nothing." ) return TimeSeries.from_pd(self.to_pd()) if reference is not None or alignment_policy is AlignPolicy.FixedReference: if reference is None: raise RuntimeError("`reference` is required when using `alignment_policy` FixedReference.") if alignment_policy not in [None, AlignPolicy.FixedReference]: logger.warning( f"TimeSeries.align() received alignment policy " f"{alignment_policy.name}, but a reference sequence of " f"timestamps was also provided. `reference` is higher " f"priority than `alignment_policy`, so we are using " f"alignment policy FixedReference." ) if granularity is not None: logger.warning( "TimeSeries.align() received a granularity at which to " "resample the time series, but a reference sequence of " "timestamps was also provided. `reference` is higher " "priority than `granularity`, so we are using alignment " "policy FixedReference, not FixedGranularity." ) # Align each univariate time series to the reference timestamps df = reindex_df(self.to_pd(), reference, missing_value_policy) return TimeSeries.from_pd(df, check_times=False) elif granularity is not None or alignment_policy is AlignPolicy.FixedGranularity: if alignment_policy not in [None, AlignPolicy.FixedGranularity]: logger.warning( f"TimeSeries.align() received alignment policy " f"{alignment_policy.name}, but a desired granularity at " f"which to resample the time series was also received. " f"`granularity` is higher priority than `alignment_policy`, " f"so we are using alignment policy FixedGranularity." ) # Get the granularity in seconds, if one is specified and the granularity is a fixed number of seconds. # Otherwise, infer the granularity. If we have a non-fixed granularity, record that fact. fixed_granularity = True if granularity is None: granularity = infer_granularity(self.time_stamps) granularity = to_offset(granularity) if isinstance(granularity, pd.DateOffset): try: granularity.nanos except ValueError: fixed_granularity = False # Remove non-overlapping portions of univariates if desired df = self.to_pd() if remove_non_overlapping: t0 = max(v.index[0] for v in self.univariates if len(v) > 0) tf = min(v.index[-1] for v in self.univariates if len(v) > 0) df = df[t0:tf] # Resample at the desired granularity, setting the origin as needed if origin is None and isinstance(granularity, pd.Timedelta): elapsed = df.index[-1] - df.index[0] origin = df.index[0] + elapsed % granularity direction = None if not fixed_granularity else "right" new_df = df.resample(granularity, origin=to_pd_datetime(origin), label=direction, closed=direction) # Apply aggregation & missing value imputation policies new_df = aggregation_policy.value(new_df) if missing_value_policy is MissingValuePolicy.Interpolate and not fixed_granularity: new_df = new_df.interpolate() else: new_df = missing_value_policy.value(new_df) # Add the date offset only if we're resampling to a non-fixed granularity if not fixed_granularity: new_df.index += get_date_offset(time_stamps=new_df.index, reference=df.index) # Do any forward-filling/back-filling to cover all the indices return TimeSeries.from_pd(new_df[df.index[0] : df.index[-1]].ffill().bfill(), check_times=False) elif alignment_policy in [None, AlignPolicy.OuterJoin]: # Outer join is the union of all timestamps appearing in any of the # univariate time series. We just need to apply the missing value # policy to self.to_pd() (and bfill()/ffill() to take care of any # additional missing values at the start/end), and then return # from_pd(). df = missing_value_policy.value(self.to_pd()) if remove_non_overlapping: t0 = max(v.index[0] for v in self.univariates if len(v) > 0) tf = min(v.index[-1] for v in self.univariates if len(v) > 0) df = df[t0:tf] else: df = df.ffill().bfill() return TimeSeries.from_pd(df, check_times=False) elif alignment_policy is AlignPolicy.InnerJoin: # Inner join is the intersection of all the timestamps appearing in # all of the univariate time series. Just get the indexes of the # univariate sub time series where all variables are present. # TODO: add a resampling step instead of just indexing? ts = [set(var.np_time_stamps) for var in self.univariates] t = ts[0] for tprime in ts[1:]: t = t.intersection(tprime) if len(t) == 0: raise RuntimeError( "No time stamps are shared between all variables! Try again with a different alignment policy." ) t = to_pd_datetime(sorted(t)) return TimeSeries.from_pd(self.to_pd().loc[t], check_times=False) else: raise RuntimeError(f"Alignment policy {alignment_policy.name} not supported") The provided code snippet includes necessary dependencies for implementing the `csv_to_time_series` function. Write a Python function `def csv_to_time_series(file_name: str, **kwargs) -> TimeSeries` to solve the following problem: Reads a CSV file and converts it to a `TimeSeries` object. Here is the function: def csv_to_time_series(file_name: str, **kwargs) -> TimeSeries: """ Reads a CSV file and converts it to a `TimeSeries` object. """ return df_to_time_series(pd.read_csv(file_name), **kwargs)
Reads a CSV file and converts it to a `TimeSeries` object.
304
from abc import ABCMeta from collections import OrderedDict from copy import deepcopy from functools import wraps import importlib import inspect import re from typing import Callable, Union The provided code snippet includes necessary dependencies for implementing the `dynamic_import` function. Write a Python function `def dynamic_import(import_path: str, alias: dict = None)` to solve the following problem: Dynamically import a member from the specified module. :param import_path: syntax 'module_name:member_name', e.g. 'merlion.transform.normalize:BoxCoxTransform' :param alias: dict which maps shortcuts for the registered classes, to their full import paths. :return: imported class Here is the function: def dynamic_import(import_path: str, alias: dict = None): """ Dynamically import a member from the specified module. :param import_path: syntax 'module_name:member_name', e.g. 'merlion.transform.normalize:BoxCoxTransform' :param alias: dict which maps shortcuts for the registered classes, to their full import paths. :return: imported class """ alias = dict() if alias is None else alias if import_path not in alias and ":" not in import_path: raise ValueError( "import_path should be one of {} or " 'include ":", e.g. "merlion.transform.normalize:MeanVarNormalize" : ' "got {}".format(set(alias), import_path) ) if ":" not in import_path: import_path = alias[import_path] module_name, objname = import_path.split(":") m = importlib.import_module(module_name) return getattr(m, objname)
Dynamically import a member from the specified module. :param import_path: syntax 'module_name:member_name', e.g. 'merlion.transform.normalize:BoxCoxTransform' :param alias: dict which maps shortcuts for the registered classes, to their full import paths. :return: imported class
305
from abc import ABCMeta from collections import OrderedDict from copy import deepcopy from functools import wraps import importlib import inspect import re from typing import Callable, Union The provided code snippet includes necessary dependencies for implementing the `call_with_accepted_kwargs` function. Write a Python function `def call_with_accepted_kwargs(fn: Callable, **kwargs)` to solve the following problem: Given a function and a list of keyword arguments, call the function with only the keyword arguments that are accepted by the function. Here is the function: def call_with_accepted_kwargs(fn: Callable, **kwargs): """ Given a function and a list of keyword arguments, call the function with only the keyword arguments that are accepted by the function. """ params = inspect.signature(fn).parameters if not any(v.kind.name == "VAR_KEYWORD" for v in params.values()): kwargs = {k: v for k, v in kwargs.items() if k in params} return fn(**kwargs)
Given a function and a list of keyword arguments, call the function with only the keyword arguments that are accepted by the function.
306
from abc import ABCMeta from collections import OrderedDict from copy import deepcopy from functools import wraps import importlib import inspect import re from typing import Callable, Union The provided code snippet includes necessary dependencies for implementing the `initializer` function. Write a Python function `def initializer(func)` to solve the following problem: Decorator for the __init__ method. Automatically assigns the parameters. Here is the function: def initializer(func): """ Decorator for the __init__ method. Automatically assigns the parameters. """ argspec = inspect.getfullargspec(func) @wraps(func) def wrapper(self, *args, **kargs): for name, arg in list(zip(argspec.args[1:], args)) + list(kargs.items()): setattr(self, name, arg) for name, default in zip(reversed(argspec.args), reversed(argspec.defaults)): if not hasattr(self, name): setattr(self, name, default) func(self, *args, **kargs) return wrapper
Decorator for the __init__ method. Automatically assigns the parameters.
307
from enum import Enum from functools import partial import logging import math import re from typing import Iterable, Sequence, Union import numpy as np import pandas as pd from pandas.tseries.frequencies import to_offset as pd_to_offset import scipy.stats The provided code snippet includes necessary dependencies for implementing the `to_offset` function. Write a Python function `def to_offset(dt)` to solve the following problem: Converts a time gap to a ``pd.Timedelta`` if possible, otherwise a ``pd.DateOffset``. Here is the function: def to_offset(dt): """ Converts a time gap to a ``pd.Timedelta`` if possible, otherwise a ``pd.DateOffset``. """ if dt is None: return None if isinstance(dt, (int, float)): dt = pd.to_timedelta(dt, unit="s") elif isinstance(dt, str) and not any(re.match(r"\d+" + suf, dt) for suf in ("M", "m", "MS", "Q", "Y", "y")): try: dt = pd.to_timedelta(dt) except ValueError: pass return dt if isinstance(dt, pd.Timedelta) else pd_to_offset(dt)
Converts a time gap to a ``pd.Timedelta`` if possible, otherwise a ``pd.DateOffset``.
308
from enum import Enum from functools import partial import logging import math import re from typing import Iterable, Sequence, Union import numpy as np import pandas as pd from pandas.tseries.frequencies import to_offset as pd_to_offset import scipy.stats The provided code snippet includes necessary dependencies for implementing the `to_timestamp` function. Write a Python function `def to_timestamp(t)` to solve the following problem: Converts a datetime to a Unix timestamp. Here is the function: def to_timestamp(t): """ Converts a datetime to a Unix timestamp. """ if isinstance(t, (int, float)) or isinstance(t, Iterable) and all(isinstance(ti, (int, float)) for ti in t): return np.asarray(t) elif isinstance(t, np.ndarray) and t.dtype in [int, np.float32, np.float64]: return t return np.asarray(t).astype("datetime64[ms]").astype(float) / 1000
Converts a datetime to a Unix timestamp.
309
from enum import Enum from functools import partial import logging import math import re from typing import Iterable, Sequence, Union import numpy as np import pandas as pd from pandas.tseries.frequencies import to_offset as pd_to_offset import scipy.stats class MissingValuePolicy(Enum): """ Missing value imputation policies. Values are partial functions for ``pd.Series`` methods. """ FFill = partial(lambda df, *args, **kwargs: getattr(df, "ffill")(*args, **kwargs)) """Fill gap with the first value before the gap.""" BFill = partial(lambda df, *args, **kwargs: getattr(df, "bfill")(*args, **kwargs)) """Fill gap with the first value after the gap.""" Nearest = partial(lambda df, *args, **kwargs: getattr(df, "interpolate")(*args, **kwargs), method="nearest") """Replace missing value with the value closest to it.""" Interpolate = partial(lambda df, *args, **kwargs: getattr(df, "interpolate")(*args, **kwargs), method="time") """Fill in missing values by linear interpolation.""" ZFill = partial(lambda df, *args, **kwargs: getattr(df, "replace")(*args, **kwargs), to_replace=np.nan, value=0) """Replace missing values with zeros.""" def to_pd_datetime(timestamp): """ Converts a timestamp (or list/iterable of timestamps) to pandas Datetime, truncated at the millisecond. """ if isinstance(timestamp, pd.DatetimeIndex): return timestamp elif isinstance(timestamp, (int, float)): return pd.to_datetime(int(timestamp * 1000), unit="ms") elif isinstance(timestamp, Iterable) and all(isinstance(t, (int, float)) for t in timestamp): timestamp = pd.to_datetime(np.asarray(timestamp).astype(float) * 1000, unit="ms") elif isinstance(timestamp, np.ndarray) and timestamp.dtype in [int, np.float32, np.float64]: timestamp = pd.to_datetime(np.asarray(timestamp).astype(float) * 1000, unit="ms") return pd.to_datetime(timestamp) The provided code snippet includes necessary dependencies for implementing the `reindex_df` function. Write a Python function `def reindex_df( df: Union[pd.Series, pd.DataFrame], reference: Sequence[Union[int, float]], missing_value_policy: MissingValuePolicy )` to solve the following problem: Reindexes a Datetime-indexed dataframe ``df`` to have the same time stamps as a reference sequence of timestamps. Imputes missing values with the given `MissingValuePolicy`. Here is the function: def reindex_df( df: Union[pd.Series, pd.DataFrame], reference: Sequence[Union[int, float]], missing_value_policy: MissingValuePolicy ): """ Reindexes a Datetime-indexed dataframe ``df`` to have the same time stamps as a reference sequence of timestamps. Imputes missing values with the given `MissingValuePolicy`. """ reference = to_pd_datetime(reference) all_times = np.unique(np.concatenate((reference.values, df.index.values))) df = df.reindex(index=all_times) df = missing_value_policy.value(df).ffill().bfill() return df.loc[reference]
Reindexes a Datetime-indexed dataframe ``df`` to have the same time stamps as a reference sequence of timestamps. Imputes missing values with the given `MissingValuePolicy`.
310
from collections import OrderedDict from typing import List import numpy as np import pandas as pd from merlion.utils.time_series import TimeSeries, to_pd_datetime class TimeSeries: """ Please read the `tutorial <tutorials/TimeSeries>` before reading this API doc. This class represents a general multivariate time series as a wrapper around a number of (optionally named) `UnivariateTimeSeries`. A `TimeSeries` object is initialized as ``time_series = TimeSeries(univariates)``, where ``univariates`` is either a list of `UnivariateTimeSeries`, or a dictionary mapping string names to their corresponding `UnivariateTimeSeries` objects. Because the individual ``univariates`` need not be sampled at the same times, an important concept for `TimeSeries` is *alignment*. We say that a `TimeSeries` is *aligned* if all of its univariates have observations sampled at the exact set set of times. One may access the `UnivariateTimeSeries` comprising this `TimeSeries` in four ways: 1. Iterate over the individual univariates using .. code-block:: python for var in time_series.univariates: # do stuff with each UnivariateTimeSeries var 2. Access an individual `UnivariateTimeSeries` by name as ``time_series.univariates[name]``. If you supplied unnamed univariates to the constructor (i.e. using a list), the name of a univariate will just be its index in that list. 3. Get the list of each univariate's name with ``time_series.names``. 4. Iterate over named univariates as .. code-block:: python for name, var in time_series.items(): # do stuff Note that this is equivalent to iterating over ``zip(time_series.names, time_series.univariates)``. This class supports the following additional features as well: 1. Interoperability with ``pandas`` - ``df = time_series.to_pd()`` yields a time-indexed ``pd.DataFrame``, where each column (with the appropriate name) corresponds to a variable. Missing values are ``NaN``. - ``time_series = TimeSeries.from_pd(df)`` takes a time-indexed ``pd.DataFrame`` and returns a corresponding `TimeSeries` object (missing values are handled appropriately). The order of ``time_series.univariates`` is the order of ``df.keys()``. 2. Automated alignment: ``aligned = time_series.align()`` resamples each of ``time_series.univariates`` so that they all have the same timestamps. By default, this is done by taking the union of all timestamps present in any individual univariate time series, and imputing missing values via interpolation. See the method documentation for details on how you may configure the alignment policy. 3. Transparent indexing and iteration for `TimeSeries` which have all univariates aligned (i.e. they all have the same timestamps) - Get the length and shape of the time series (equal to the number of observations in each individual univariate). Note that if the time series is not aligned, we will return the length/shape of an equivalent ``pandas`` dataframe and emit a warning. - Index ``time_series[i] = (times[i], (x1[i], ..., xn[i]))`` (assuming ``time_series`` has ``n`` aligned univariates with timestamps ``times``, and ``xk = time_series.univariates[k-1].values``). Slice returns a `TimeSeries` object and works as one would expect. - Assuming ``time_series`` has ``n`` variables, you may iterate with .. code-block:: python for t_i, (x1_i, ..., xn_i) in time_series: # do stuff Notably, this lets you call ``times, val_vectors = zip(*time_series)`` 4. Time-based queries for any time series - Get the two sub `TimeSeries` before and after a timestamp ``t`` via ``left, right = time_series.bisect(t)`` - Get the sub `TimeSeries` between timestamps ``t0`` (inclusive) and ``tf`` (non-inclusive) via ``window = time_series.window(t0, tf)`` 5. Concatenation: two `TimeSeries` may be concatenated (in time) as ``time_series = time_series_1 + time_series_2``. .. document special functions .. automethod:: __getitem__ .. automethod:: __iter__ """ def __init__( self, univariates: Union[Mapping[Any, UnivariateTimeSeries], Iterable[UnivariateTimeSeries]], *, freq: str = "1h", check_aligned=True, ): # Type/length checking of univariates if isinstance(univariates, Mapping): univariates = ValIterOrderedDict((str(k), v) for k, v in univariates.items()) assert all(isinstance(var, UnivariateTimeSeries) for var in univariates.values()) elif isinstance(univariates, Iterable): univariates = list(univariates) assert all(isinstance(var, UnivariateTimeSeries) for var in univariates) names = [str(var.name) for var in univariates] if len(set(names)) == len(names): names = [str(i) if name is None else name for i, name in enumerate(names)] univariates = ValIterOrderedDict(zip(names, univariates)) else: univariates = ValIterOrderedDict((str(i), v) for i, v in enumerate(univariates)) else: raise TypeError( "Expected univariates to be either a `Sequence[UnivariateTimeSeries]` or a " "`Mapping[Hashable, UnivariateTimeSeries]`." ) assert len(univariates) > 0 # Assign all the individual univariate series the appropriate names for name, var in univariates.items(): var.name = name # Set self.univariates and check if they are perfectly aligned self.univariates = univariates if check_aligned and self.dim > 1: t = self.univariates[self.names[0]].time_stamps self._is_aligned = all(self.univariates[name].time_stamps == t for name in self.names[1:]) else: self._is_aligned = len(univariates) <= 1 # Raise a warning if the univariates are too mis-aligned if check_aligned and not self.is_aligned: all_t0 = [var.index[0] for var in univariates if len(var) > 0] all_tf = [var.index[-1] for var in univariates if len(var) > 0] min_elapsed = min(tf - t0 for t0, tf in zip(all_t0, all_tf)) min_t0, max_t0 = min(all_t0), max(all_t0) min_tf, max_tf = min(all_tf), max(all_tf) if max_t0 - min_t0 > 0.1 * min_elapsed: logger.warning( f"The earliest univariate starts at {min_t0}, but the " f"latest univariate starts at {max_t0}, a difference of " f"{max_t0 - min_t0}. This is more than 10% of the length " f"of the shortest univariate ({min_elapsed}). You may " f"want to check that the univariates cover the same " f"window of time.", stack_info=True, ) if max_tf - min_tf > 0.1 * min_elapsed: logger.warning( f"The earliest univariate ends at {min_tf}, but the " f"latest univariate ends at {max_tf}, a difference of " f"{max_tf - min_tf}. This is more than 10% of the length " f"of the shortest univariate ({min_elapsed}). You may " f"want to check that the univariates cover the same " f"window of time.", stack_info=True, ) def names(self): """:return: The list of the names of the univariates.""" return list(self.univariates.keys()) def items(self): """:return: Iterator over ``(name, univariate)`` tuples.""" return self.univariates.items() def dim(self) -> int: """ :return: The dimension of the time series (the number of variables). """ return len(self.univariates) def rename(self, mapper: Union[Iterable[str], Mapping[str, str], Callable[[str], str]]): """ :param mapper: Dict-like or function transformations to apply to the univariate names. Can also be an iterable of new univariate names. :return: the time series with renamed univariates. """ if isinstance(mapper, Callable): mapper = [mapper(old) for old in self.names] elif isinstance(mapper, Mapping): mapper = [mapper.get(old, old) for old in self.names] univariates = ValIterOrderedDict((new_name, var) for new_name, var in zip(mapper, self.univariates)) return self.__class__(univariates) def is_aligned(self) -> bool: """ :return: Whether all individual variable time series are sampled at the same time stamps, i.e. they are aligned. """ return self._is_aligned def index(self): return to_pd_datetime(self.np_time_stamps) def np_time_stamps(self): """ :rtype: np.ndarray :return: the ``numpy`` representation of this time series's Unix timestamps """ return np.unique(np.concatenate([var.np_time_stamps for var in self.univariates])) def time_stamps(self): """ :rtype: List[float] :return: the list of Unix timestamps for the time series """ return self.np_time_stamps.tolist() def t0(self) -> float: """ :rtype: float :return: the first timestamp in the time series. """ return min(var.t0 for var in self.univariates) def tf(self) -> float: """ :rtype: float :return: the final timestamp in the time series. """ return max(var.tf for var in self.univariates) def _txs_to_vec(txs): """ Helper function that converts [(t_1[i], x_1[i]), ..., (t_k[i], x_k[i])], i.e. [var[i] for var in self.univariates], into the desired output form (t_1[i], (x_1[i], ..., x_k[i])). """ return txs[0][0], tuple(tx[1] for tx in txs) def __iter__(self): """ Only supported if all individual variable time series are sampled at the same time stamps. The i'th item of the iterator is the tuple ``(time_stamps[i], tuple(var.values[i] for var in self.univariates))``. """ if not self.is_aligned: raise RuntimeError( "The univariates comprising this time series are not aligned " "(they have different time stamps), but alignment is required " "to iterate over the time series." ) return map(self._txs_to_vec, zip(*self.univariates)) def __getitem__(self, i: Union[int, slice]): """ Only supported if all individual variable time series are sampled at the same time stamps. :param i: integer index or slice. :rtype: Union[Tuple[float, Tuple[float]], TimeSeries] :return: If ``i`` is an integer, returns the tuple ``(time_stamps[i], tuple(var.values[i] for var in self.univariates))``. If ``i`` is a slice, returns the time series ``TimeSeries([var[i] for var in self.univariates])`` """ if not self.is_aligned: raise RuntimeError( "The univariates comprising this time series are not aligned " "(they have different time stamps), but alignment is required " "to index into the time series." ) if isinstance(i, int): return self._txs_to_vec([var[i] for var in self.univariates]) elif isinstance(i, slice): # ret must be aligned, so bypass the (potentially) expensive check univariates = ValIterOrderedDict([(k, v[i]) for k, v in self.items()]) ret = TimeSeries(univariates, check_aligned=False) ret._is_aligned = True return ret else: raise KeyError( f"Indexing a `TimeSeries` with key {i} of type " f"{type(i).__name__} not supported. Perhaps you " f"meant to index into `time_series.univariates`, " f"rather than `time_series`?" ) def is_empty(self) -> bool: """ :return: whether the time series is empty """ return all(len(var) == 0 for var in self.univariates) def squeeze(self) -> UnivariateTimeSeries: """ :return: `UnivariateTimeSeries` if the time series is univariate; otherwise returns itself, a `TimeSeries` """ if self.dim == 1: return self.univariates[self.names[0]] return self def __len__(self): """ :return: the number of observations in the time series """ if not self.is_aligned: warning = ( "The univariates comprising this time series are not aligned " "(they have different time stamps). The length returned is " "equal to the length of the _union_ of all time stamps present " "in any of the univariates." ) warnings.warn(warning) logger.warning(warning) return len(self.to_pd()) return len(self.univariates[self.names[0]]) def shape(self) -> Tuple[int, int]: """ :return: the shape of this time series, i.e. ``(self.dim, len(self))`` """ return self.dim, len(self) def __add__(self, other): """ Concatenates the `TimeSeries` ``other`` to the right of this one. :param TimeSeries other: :rtype: TimeSeries :return: concatenated time series """ return self.concat(other, axis=0) def concat(self, other, axis=0): """ Concatenates the `TimeSeries` ``other`` on the time axis if ``axis = 0`` or the variable axis if ``axis = 1``. :rtype: TimeSeries :return: concatenated time series """ assert axis in [0, 1] if axis == 0: assert self.dim == other.dim, ( f"Cannot concatenate a {self.dim}-dimensional time series with a {other.dim}-dimensional " f"time series on the time axis." ) assert self.names == other.names, ( f"Cannot concatenate time series on the time axis if they have two different sets of " f"variable names, {self.names} and {other.names}." ) univariates = ValIterOrderedDict( [(name, ts0.concat(ts1)) for (name, ts0), ts1 in zip(self.items(), other.univariates)] ) ret = TimeSeries(univariates, check_aligned=False) ret._is_aligned = self.is_aligned and other.is_aligned return ret else: univariates = ValIterOrderedDict([(name, var.copy()) for name, var in [*self.items(), other.items()]]) ret = TimeSeries(univariates, check_aligned=False) ret._is_aligned = self.is_aligned and other.is_aligned and self.time_stamps == other.time_stamps return ret def __eq__(self, other): if self.dim != other.dim: return False return all(u == v for u, v in zip(self.univariates, other.univariates)) def __repr__(self): return repr(self.to_pd()) def bisect(self, t: float, t_in_left: bool = False): """ Splits the time series at the point where the given timestamp ``t`` occurs. :param t: a Unix timestamp or datetime object. Everything before time ``t`` is in the left split, and everything after time ``t`` is in the right split. :param t_in_left: if ``True``, ``t`` is in the left split. Otherwise, ``t`` is in the right split. :rtype: Tuple[TimeSeries, TimeSeries] :return: the left and right splits of the time series. """ left, right = ValIterOrderedDict(), ValIterOrderedDict() for name, var in self.items(): left[name], right[name] = var.bisect(t, t_in_left) if self.is_aligned: left = TimeSeries(left, check_aligned=False) right = TimeSeries(right, check_aligned=False) left._is_aligned = True right._is_aligned = True return left, right else: return TimeSeries(left), TimeSeries(right) def window(self, t0: float, tf: float, include_tf: bool = False): """ :param t0: The timestamp/datetime at the start of the window (inclusive) :param tf: The timestamp/datetime at the end of the window (inclusive if ``include_tf`` is ``True``, non-inclusive otherwise) :param include_tf: Whether to include ``tf`` in the window. :return: The subset of the time series occurring between timestamps ``t0`` (inclusive) and ``tf`` (included if ``include_tf`` is ``True``, excluded otherwise). :rtype: `TimeSeries` """ return TimeSeries(ValIterOrderedDict([(k, var.window(t0, tf, include_tf)) for k, var in self.items()])) def to_pd(self) -> pd.DataFrame: """ :return: A pandas DataFrame (indexed by time) which represents this time series. Each variable corresponds to a column of the DataFrame. Timestamps which are present for one variable but not another, are represented with NaN. """ t = pd.DatetimeIndex([]) univariates = [(name, var.to_pd()[~var.index.duplicated()]) for name, var in self.items()] for _, var in univariates: t = t.union(var.index) t = t.sort_values() t.name = _time_col_name if len(t) >= 3: t.freq = pd.infer_freq(t) df = pd.DataFrame(np.full((len(t), len(univariates)), np.nan), index=t, columns=self.names) for name, var in univariates: df.loc[var.index, name] = var[~var.index.duplicated()] return df def to_csv(self, file_name, **kwargs): self.to_pd().to_csv(file_name, **kwargs) def from_pd(cls, df: Union[pd.Series, pd.DataFrame, np.ndarray], check_times=True, drop_nan=True, freq="1h"): """ :param df: A ``pandas.DataFrame`` with a ``DatetimeIndex``. Each column corresponds to a different variable of the time series, and the key of column (in sorted order) give the relative order of those variables in ``self.univariates``. Missing values should be represented with ``NaN``. May also be a ``pandas.Series`` for single-variable time series. :param check_times: whether to check that all times in the index are unique (up to the millisecond) and sorted. :param drop_nan: whether to drop all ``NaN`` entries before creating the time series. Specifying ``False`` is useful if you wish to impute the values on your own. :param freq: if ``df`` is not indexed by time, this is the frequency at which we will assume it is sampled. :rtype: TimeSeries :return: the `TimeSeries` object corresponding to ``df``. """ if df is None: return None elif isinstance(df, TimeSeries): return df elif isinstance(df, UnivariateTimeSeries): return cls([df]) elif isinstance(df, pd.Series): if drop_nan: df = df[~df.isna()] return cls({df.name: UnivariateTimeSeries.from_pd(df)}) elif isinstance(df, np.ndarray): arr = df.reshape(len(df), -1).T ret = cls([UnivariateTimeSeries(time_stamps=None, values=v, freq=freq) for v in arr], check_aligned=False) ret._is_aligned = True return ret elif not isinstance(df, pd.DataFrame): df = pd.DataFrame(df) # Time series is not aligned iff there are missing values aligned = df.shape[1] == 1 or not df.isna().any().any() # Check for a string-type index if df.index.dtype == "O": df = df.copy() df.index = pd.to_datetime(df.index) # Make sure there are no time duplicates (by milliseconds) if desired dt_index = isinstance(df.index, pd.DatetimeIndex) if check_times: if not df.index.is_unique: df = df[~df.index.duplicated()] if not df.index.is_monotonic_increasing: df = df.sort_index() if dt_index: times = df.index.values.astype("datetime64[ms]").astype(np.int64) df = df.reindex(pd.to_datetime(np.unique(times), unit="ms"), method="bfill") elif not aligned and not dt_index and df.index.dtype not in ("int64", "float64"): raise RuntimeError( f"We only support instantiating time series from a " f"``pd.DataFrame`` with missing values when the data frame is " f"indexed by time, int, or float. This dataframe's index is of " f"type {type(df.index).__name__}" ) if drop_nan and not aligned: ret = cls( ValIterOrderedDict( [(k, UnivariateTimeSeries.from_pd(ser[~ser.isna()], freq=freq)) for k, ser in df.items()] ), check_aligned=False, ) else: ret = cls( ValIterOrderedDict([(k, UnivariateTimeSeries.from_pd(ser, freq=freq)) for k, ser in df.items()]), check_aligned=False, ) ret._is_aligned = aligned return ret def from_ts_list(cls, ts_list, *, check_aligned=True): """ :param Iterable[TimeSeries] ts_list: iterable of time series we wish to form a multivariate time series with :param bool check_aligned: whether to check if the output time series is aligned :rtype: TimeSeries :return: A multivariate `TimeSeries` created from all the time series in the inputs. """ ts_list = list(ts_list) all_names = [set(ts.names) for ts in ts_list] if all( len(names_i.intersection(names_j)) == 0 for i, names_i in enumerate(all_names) for names_j in all_names[i + 1 :] ): univariates = ValIterOrderedDict(itertools.chain.from_iterable(ts.items() for ts in ts_list)) else: univariates = list(itertools.chain.from_iterable(ts.univariates for ts in ts_list)) return cls(univariates, check_aligned=check_aligned) def align( self, *, reference: Sequence[Union[int, float]] = None, granularity: Union[str, int, float] = None, origin: int = None, remove_non_overlapping=True, alignment_policy: AlignPolicy = None, aggregation_policy: AggregationPolicy = AggregationPolicy.Mean, missing_value_policy: MissingValuePolicy = MissingValuePolicy.Interpolate, ): """ Aligns all the univariates comprising this multivariate time series so that they all have the same time stamps. :param reference: A specific set of timestamps we want the resampled time series to contain. Required if ``alignment_policy`` is `AlignPolicy.FixedReference`. Overrides other alignment policies if specified. :param granularity: The granularity (in seconds) of the resampled time time series. Defaults to the GCD time difference between adjacent elements of ``time_series`` (otherwise). Ignored if ``reference`` is given or ``alignment_policy`` is `AlignPolicy.FixedReference`. Overrides other alignment policies if specified. :param origin: The first timestamp of the resampled time series. Only used if the alignment policy is `AlignPolicy.FixedGranularity`. :param remove_non_overlapping: If ``True``, we will only keep the portions of the univariates that overlap with each other. For example, if we have 3 univariates which span timestamps [0, 3600], [60, 3660], and [30, 3540], we will only keep timestamps in the range [60, 3540]. If ``False``, we will keep all timestamps produced by the resampling. :param alignment_policy: The policy we want to use to align the time series. - `AlignPolicy.FixedReference` aligns each single-variable time series to ``reference``, a user-specified sequence of timestamps. - `AlignPolicy.FixedGranularity` resamples each single-variable time series at the same granularity, aggregating windows and imputing missing values as desired. - `AlignPolicy.OuterJoin` returns a time series with the union of all timestamps present in any single-variable time series. - `AlignPolicy.InnerJoin` returns a time series with the intersection of all timestamps present in all single-variable time series. :param aggregation_policy: The policy used to aggregate windows of adjacent observations when downsampling. :param missing_value_policy: The policy used to impute missing values created when upsampling. :rtype: TimeSeries :return: The resampled multivariate time series. """ if self.is_empty(): if reference is not None or granularity is not None: logger.warning( "Attempting to align an empty time series to a set of reference time stamps or a " "fixed granularity. Doing nothing." ) return TimeSeries.from_pd(self.to_pd()) if reference is not None or alignment_policy is AlignPolicy.FixedReference: if reference is None: raise RuntimeError("`reference` is required when using `alignment_policy` FixedReference.") if alignment_policy not in [None, AlignPolicy.FixedReference]: logger.warning( f"TimeSeries.align() received alignment policy " f"{alignment_policy.name}, but a reference sequence of " f"timestamps was also provided. `reference` is higher " f"priority than `alignment_policy`, so we are using " f"alignment policy FixedReference." ) if granularity is not None: logger.warning( "TimeSeries.align() received a granularity at which to " "resample the time series, but a reference sequence of " "timestamps was also provided. `reference` is higher " "priority than `granularity`, so we are using alignment " "policy FixedReference, not FixedGranularity." ) # Align each univariate time series to the reference timestamps df = reindex_df(self.to_pd(), reference, missing_value_policy) return TimeSeries.from_pd(df, check_times=False) elif granularity is not None or alignment_policy is AlignPolicy.FixedGranularity: if alignment_policy not in [None, AlignPolicy.FixedGranularity]: logger.warning( f"TimeSeries.align() received alignment policy " f"{alignment_policy.name}, but a desired granularity at " f"which to resample the time series was also received. " f"`granularity` is higher priority than `alignment_policy`, " f"so we are using alignment policy FixedGranularity." ) # Get the granularity in seconds, if one is specified and the granularity is a fixed number of seconds. # Otherwise, infer the granularity. If we have a non-fixed granularity, record that fact. fixed_granularity = True if granularity is None: granularity = infer_granularity(self.time_stamps) granularity = to_offset(granularity) if isinstance(granularity, pd.DateOffset): try: granularity.nanos except ValueError: fixed_granularity = False # Remove non-overlapping portions of univariates if desired df = self.to_pd() if remove_non_overlapping: t0 = max(v.index[0] for v in self.univariates if len(v) > 0) tf = min(v.index[-1] for v in self.univariates if len(v) > 0) df = df[t0:tf] # Resample at the desired granularity, setting the origin as needed if origin is None and isinstance(granularity, pd.Timedelta): elapsed = df.index[-1] - df.index[0] origin = df.index[0] + elapsed % granularity direction = None if not fixed_granularity else "right" new_df = df.resample(granularity, origin=to_pd_datetime(origin), label=direction, closed=direction) # Apply aggregation & missing value imputation policies new_df = aggregation_policy.value(new_df) if missing_value_policy is MissingValuePolicy.Interpolate and not fixed_granularity: new_df = new_df.interpolate() else: new_df = missing_value_policy.value(new_df) # Add the date offset only if we're resampling to a non-fixed granularity if not fixed_granularity: new_df.index += get_date_offset(time_stamps=new_df.index, reference=df.index) # Do any forward-filling/back-filling to cover all the indices return TimeSeries.from_pd(new_df[df.index[0] : df.index[-1]].ffill().bfill(), check_times=False) elif alignment_policy in [None, AlignPolicy.OuterJoin]: # Outer join is the union of all timestamps appearing in any of the # univariate time series. We just need to apply the missing value # policy to self.to_pd() (and bfill()/ffill() to take care of any # additional missing values at the start/end), and then return # from_pd(). df = missing_value_policy.value(self.to_pd()) if remove_non_overlapping: t0 = max(v.index[0] for v in self.univariates if len(v) > 0) tf = min(v.index[-1] for v in self.univariates if len(v) > 0) df = df[t0:tf] else: df = df.ffill().bfill() return TimeSeries.from_pd(df, check_times=False) elif alignment_policy is AlignPolicy.InnerJoin: # Inner join is the intersection of all the timestamps appearing in # all of the univariate time series. Just get the indexes of the # univariate sub time series where all variables are present. # TODO: add a resampling step instead of just indexing? ts = [set(var.np_time_stamps) for var in self.univariates] t = ts[0] for tprime in ts[1:]: t = t.intersection(tprime) if len(t) == 0: raise RuntimeError( "No time stamps are shared between all variables! Try again with a different alignment policy." ) t = to_pd_datetime(sorted(t)) return TimeSeries.from_pd(self.to_pd().loc[t], check_times=False) else: raise RuntimeError(f"Alignment policy {alignment_policy.name} not supported") The provided code snippet includes necessary dependencies for implementing the `minT_reconciliation` function. Write a Python function `def minT_reconciliation( forecasts: List[TimeSeries], errs: List[TimeSeries], sum_matrix: np.ndarray, n_leaves: int ) -> List[TimeSeries]` to solve the following problem: Computes the minimum trace reconciliation for hierarchical time series, as described by `Wickramasuriya et al. 2018 <https://robjhyndman.com/papers/mint.pdf>`__. This algorithm assumes that we have a number of time series aggregated at various levels (the aggregation tree is described by ``sum_matrix``), and we obtain independent forecasts at each level of the hierarchy. Minimum trace reconciliation finds the optimal way to adjust (reconcile) the forecasts to reduce the variance of the estimation. :param forecasts: forecast for each aggregation level of the hierarchy :param errs: standard errors of forecasts for each level of the hierarchy. While not strictly necessary, reconciliation performs better if all forecasts are accompanied by uncertainty estimates. :param sum_matrix: matrix describing how the hierarchy is aggregated :param n_leaves: the number of leaf forecasts (i.e. the number of forecasts at the most dis-aggregated level of the hierarchy). We assume that the leaf forecasts are last in the lists ``forecasts`` & ``errs``, and that ``sum_matrix`` reflects this fact. :return: reconciled forecasts for each aggregation level of the hierarchy Here is the function: def minT_reconciliation( forecasts: List[TimeSeries], errs: List[TimeSeries], sum_matrix: np.ndarray, n_leaves: int ) -> List[TimeSeries]: """ Computes the minimum trace reconciliation for hierarchical time series, as described by `Wickramasuriya et al. 2018 <https://robjhyndman.com/papers/mint.pdf>`__. This algorithm assumes that we have a number of time series aggregated at various levels (the aggregation tree is described by ``sum_matrix``), and we obtain independent forecasts at each level of the hierarchy. Minimum trace reconciliation finds the optimal way to adjust (reconcile) the forecasts to reduce the variance of the estimation. :param forecasts: forecast for each aggregation level of the hierarchy :param errs: standard errors of forecasts for each level of the hierarchy. While not strictly necessary, reconciliation performs better if all forecasts are accompanied by uncertainty estimates. :param sum_matrix: matrix describing how the hierarchy is aggregated :param n_leaves: the number of leaf forecasts (i.e. the number of forecasts at the most dis-aggregated level of the hierarchy). We assume that the leaf forecasts are last in the lists ``forecasts`` & ``errs``, and that ``sum_matrix`` reflects this fact. :return: reconciled forecasts for each aggregation level of the hierarchy """ m = len(forecasts) n = n_leaves assert len(errs) == m > n assert all(yhat.dim == 1 for yhat in forecasts) assert sum_matrix.shape == (m, n), f"Expected sum_matrix to have shape ({m}, {n}) got {sum_matrix.shape}" assert (sum_matrix[-n:] == np.eye(n)).all() # Convert forecasts to a single aligned multivariate time series names = [yhat.names[0] for yhat in forecasts] forecasts = OrderedDict((i, yhat.univariates[yhat.names[0]]) for i, yhat in enumerate(forecasts)) forecasts = TimeSeries(univariates=forecasts).align() t_ref = forecasts.time_stamps H = len(forecasts) # Matrix of stderrs (if any) at each prediction horizon. shape is [m, H]. # If no stderrs are given, we the estimation error is proportional to the number of leaf nodes being combined. coefs = sum_matrix.sum(axis=1) if all(e is None for e in errs): # FIXME: This heuristic can be improved if training errors are given. # However, the model code should probably be responsible for this, not the reconciliation code. Wh = [np.diag(coefs) for _ in range(H)] else: coefs = coefs.reshape(-1, 1) errs = np.asarray( [np.full(H, np.nan) if e is None else e.align(reference=t_ref).to_pd().values.flatten() ** 2 for e in errs] ) # [m, H] # Replace NaN's w/ the mean of non-NaN stderrs & create diagonal error matrices nan_errs = np.isnan(errs[:, 0]) if nan_errs.any(): errs[nan_errs] = np.nanmean(errs / coefs, axis=0) * coefs[nan_errs] Wh = [np.diag(errs[:, h]) for h in range(H)] # Create other supplementary matrices J = np.zeros((n, m)) J[:, -n:] = np.eye(n) U = np.zeros((m - n, m)) U[:, : m - n] = np.eye(m - n) U[:, m - n :] = -sum_matrix[:-n] # Compute projection matrices to compute coherent leaf forecasts Ph = [] for W in Wh: inv = np.linalg.inv(U @ W @ U.T) P = J - ((J @ W) @ U.T) @ (inv @ U) Ph.append(P) # Compute reconciled forecasts reconciled = [] for (t, yhat_h), P in zip(forecasts, Ph): reconciled.append(sum_matrix @ (P @ yhat_h)) reconciled = pd.DataFrame(np.asarray(reconciled), index=to_pd_datetime(t_ref)) return [u.to_ts(name=name) for u, name in zip(TimeSeries.from_pd(reconciled).univariates, names)]
Computes the minimum trace reconciliation for hierarchical time series, as described by `Wickramasuriya et al. 2018 <https://robjhyndman.com/papers/mint.pdf>`__. This algorithm assumes that we have a number of time series aggregated at various levels (the aggregation tree is described by ``sum_matrix``), and we obtain independent forecasts at each level of the hierarchy. Minimum trace reconciliation finds the optimal way to adjust (reconcile) the forecasts to reduce the variance of the estimation. :param forecasts: forecast for each aggregation level of the hierarchy :param errs: standard errors of forecasts for each level of the hierarchy. While not strictly necessary, reconciliation performs better if all forecasts are accompanied by uncertainty estimates. :param sum_matrix: matrix describing how the hierarchy is aggregated :param n_leaves: the number of leaf forecasts (i.e. the number of forecasts at the most dis-aggregated level of the hierarchy). We assume that the leaf forecasts are last in the lists ``forecasts`` & ``errs``, and that ``sum_matrix`` reflects this fact. :return: reconciled forecasts for each aggregation level of the hierarchy
311
import argparse import copy import json import logging import os import sys import time import git from typing import Tuple import matplotlib.pyplot as plt import numpy as np import pandas as pd from tqdm import tqdm from merlion.evaluate.anomaly import ( TSADEvaluatorConfig, accumulate_tsad_score, TSADScoreAccumulator as ScoreAcc, TSADEvaluator, ) from merlion.models.anomaly.base import DetectorBase from merlion.models.ensemble.anomaly import DetectorEnsemble from merlion.evaluate.anomaly import TSADMetric, ScoreType from merlion.models.factory import ModelFactory from merlion.transform.resample import TemporalResample from merlion.utils import TimeSeries from merlion.utils.resample import to_pd_datetime from ts_datasets.anomaly import * CONFIG_JSON = os.path.join(MERLION_ROOT, "conf", "benchmark_anomaly.json") class TSADMetric(Enum): def parse_args(): with open(CONFIG_JSON, "r") as f: valid_models = list(json.load(f).keys()) parser = argparse.ArgumentParser( description="Script to benchmark Merlion time series anomaly detection " "models. This script assumes that you have pip installed " "both merlion (this repo's main package) and ts_datasets " "(a sub-repo)." ) parser.add_argument( "--dataset", default="NAB_all", help="Name of dataset to run benchmark on. See get_dataset() " "in ts_datasets/ts_datasets/anomaly/__init__.py for " "valid options.", ) parser.add_argument("--data_root", default=None, help="Root directory/file of dataset.") parser.add_argument("--data_kwargs", default="{}", help="JSON of keyword arguemtns for the data loader.") parser.add_argument( "--models", type=str, nargs="+", default=["DefaultDetector"], help="Name of model (or models in ensemble) to benchmark.", choices=valid_models, ) parser.add_argument( "--retrain_freq", type=str, default="default", help="String (e.g. 1d, 2w, etc.) specifying how often " "to re-train the model before evaluating it on " "the next window of data. Note that re-training " "is unsupervised, i.e. does not use ground truth " "anomaly labels in any way. Default retrain_freq is " "1d for univariate data and None for multivariate.", ) parser.add_argument( "--train_window", type=str, default=None, help="String (e.g. 30d, 6m, etc.) specifying how much " "data (in terms of a time window) the model " "should train on at any point.", ) parser.add_argument( "--metric", type=str, default="F1", choices=list(TSADMetric.__members__.keys()), help="Metric to optimize for (where relevant)", ) parser.add_argument( "--point_adj_metric", type=str, default="PointAdjustedF1", choices=list(TSADMetric.__members__.keys()), help="Final metric to optimize for when evaluating point-adjusted performance", ) parser.add_argument( "--pointwise_metric", type=str, default="PointwiseF1", choices=list(TSADMetric.__members__.keys()), help="Final metric to optimize for when evaluating pointwise performance", ) parser.add_argument("--unsupervised", action="store_true") parser.add_argument( "--tune_on_test", action="store_true", default=False, help="Whether to tune the threshold on both train and " "test splits of the time series. Useful for " "metrics like Best F1, or NAB score with " "threshold optimization.", ) parser.add_argument( "--load_checkpoint", action="store_true", default=False, help="Specify this option if you would like continue " "training your model on a dataset from a " "checkpoint, instead of restarting from scratch.", ) parser.add_argument( "--eval_only", action="store_true", default=False, help="Specify this option if you would like to skip " "the model training phase, and simply evaluate " "on partial saved results.", ) parser.add_argument("--debug", action="store_true", default=False, help="Whether to enable INFO-level logs.") parser.add_argument( "--visualize", action="store_true", default=False, help="Whether to plot the model's predictions after " "training on each example. Mutually exclusive " "with running any sort of evaluation.", ) args = parser.parse_args() args.metric = TSADMetric[args.metric] args.pointwise_metric = TSADMetric[args.pointwise_metric] args.visualize = args.visualize and not args.eval_only args.data_kwargs = json.loads(args.data_kwargs) assert isinstance(args.data_kwargs, dict) if args.retrain_freq.lower() in ["", "none", "null"]: args.retrain_freq = None elif args.retrain_freq != "default": rf = pd.to_timedelta(args.retrain_freq).total_seconds() if rf % (3600 * 24) == 0: args.retrain_freq = f"{int(rf/3600/24)}d" elif rf % 3600 == 0: args.retrain_freq = f"{int(rf/3600)}h" elif rf % 60 == 0: args.retrain_freq = f"{int(rf//60)}min" else: args.retrain_freq = f"{int(rf)}s" return args
null
312
import argparse import copy import json import logging import os import sys import time import git from typing import Tuple import matplotlib.pyplot as plt import numpy as np import pandas as pd from tqdm import tqdm from merlion.evaluate.anomaly import ( TSADEvaluatorConfig, accumulate_tsad_score, TSADScoreAccumulator as ScoreAcc, TSADEvaluator, ) from merlion.models.anomaly.base import DetectorBase from merlion.models.ensemble.anomaly import DetectorEnsemble from merlion.evaluate.anomaly import TSADMetric, ScoreType from merlion.models.factory import ModelFactory from merlion.transform.resample import TemporalResample from merlion.utils import TimeSeries from merlion.utils.resample import to_pd_datetime from ts_datasets.anomaly import * logger = logging.getLogger(__name__) def get_dataset_name(dataset: TSADBaseDataset): name = type(dataset).__name__ if hasattr(dataset, "subset") and dataset.subset is not None: name += "_" + dataset.subset if isinstance(dataset, CustomAnomalyDataset): root = dataset.rootdir name = os.path.join(name, os.path.basename(os.path.dirname(root) if os.path.isfile(root) else root)) return name def resolve_model_name(model_name: str): with open(CONFIG_JSON, "r") as f: config_dict = json.load(f) if model_name not in config_dict: raise NotImplementedError( f"Benchmarking not implemented for model {model_name}. Valid model names are {list(config_dict.keys())}" ) while "alias" in config_dict[model_name]: assert model_name != config_dict[model_name]["alias"], "Alias name cannot be the same as the model name" model_name = config_dict[model_name]["alias"] return model_name def get_model( model_name: str, dataset: TSADBaseDataset, metric: TSADMetric, tune_on_test=False, unsupervised=False ) -> Tuple[DetectorBase, dict]: with open(CONFIG_JSON, "r") as f: config_dict = json.load(f) if model_name not in config_dict: raise NotImplementedError( f"Benchmarking not implemented for model {model_name}. Valid model names are {list(config_dict.keys())}" ) while "alias" in config_dict[model_name]: model_name = config_dict[model_name]["alias"] # Load the model with default kwargs, but override with dataset-specific # kwargs where relevant model_configs = config_dict[model_name]["config"] model_type = config_dict[model_name].get("model_type", model_name) model_kwargs = model_configs["default"] model_kwargs.update(model_configs.get(type(dataset).__name__, {})) model = ModelFactory.create(name=model_type, **model_kwargs) # The post-rule train configs are fully specified for each dataset (where # relevant), with a default option if there is no dataset-specific option. post_rule_train_configs = config_dict[model_name].get("post_rule_train_config", {}) d = post_rule_train_configs.get("default", {}) d.update(post_rule_train_configs.get(type(dataset).__name__, {})) if len(d) == 0: d = copy.copy(model._default_post_rule_train_config) d["metric"] = None if unsupervised else metric d.update({"max_early_sec": dataset.max_lead_sec, "max_delay_sec": dataset.max_lag_sec}) t = dataset_to_threshold(dataset, tune_on_test) model.threshold.alm_threshold = t d["unsup_quantile"] = None return model, d def df_to_merlion(df: pd.DataFrame, md: pd.DataFrame, get_ground_truth=False, transform=None) -> TimeSeries: """Converts a pandas dataframe time series to the Merlion format.""" if get_ground_truth: if False and "changepoint" in md.keys(): series = md["anomaly"] | md["changepoint"] else: series = md["anomaly"] else: series = df time_series = TimeSeries.from_pd(series) if transform is not None: time_series = transform(time_series) return time_series def get_code_version_info(): return dict(time=str(pd.Timestamp.now()), commit=git.Repo(search_parent_directories=True).head.object.hexsha) class ScoreType(Enum): """ The algorithm to use to compute true/false positives/negatives. See the technical report for more details on each score type. Merlion's preferred default is revised point-adjusted. """ Pointwise = 0 PointAdjusted = 1 RevisedPointAdjusted = 2 class TSADEvaluatorConfig(EvaluatorConfig): """ Configuration class for a `TSADEvaluator`. """ def __init__(self, max_early_sec: float = None, max_delay_sec: float = None, **kwargs): """ :param max_early_sec: the maximum number of seconds we allow an anomaly to be detected early. :param max_delay_sec: if an anomaly is detected more than this many seconds after its start, it is not counted as being detected. """ super().__init__(**kwargs) self.max_early_sec = max_early_sec self.max_delay_sec = max_delay_sec class TemporalResample(TransformBase): """ Defines a policy to temporally resample a time series at a specified granularity. Note that while this transform does support inversion, the recovered time series may differ from the input due to information loss when resampling. """ def __init__( self, granularity: Union[str, int, float] = None, origin: int = None, trainable_granularity: bool = None, remove_non_overlapping=True, aggregation_policy: Union[str, AggregationPolicy] = "Mean", missing_value_policy: Union[str, MissingValuePolicy] = "Interpolate", ): """ Defines a policy to temporally resample a time series. :param granularity: The granularity at which we want to resample. :param origin: The time stamp defining the offset to start at. :param trainable_granularity: Whether we will automatically infer the granularity of the time series. If ``None`` (default), it will be trainable only if no granularity is explicitly given. :param remove_non_overlapping: If ``True``, we will only keep the portions of the univariates that overlap with each other. For example, if we have 3 univariates which span timestamps [0, 3600], [60, 3660], and [30, 3540], we will only keep timestamps in the range [60, 3540]. If ``False``, we will keep all timestamps produced by the resampling. :param aggregation_policy: The policy we will use to aggregate multiple values in a window (downsampling). :param missing_value_policy: The policy we will use to impute missing values (upsampling). """ super().__init__() self.granularity = granularity self.origin = origin self.trainable_granularity = (granularity is None) if trainable_granularity is None else trainable_granularity self.remove_non_overlapping = remove_non_overlapping self.aggregation_policy = aggregation_policy self.missing_value_policy = missing_value_policy def requires_inversion_state(self): return False def proper_inversion(self): """ We treat resampling as a proper inversion to avoid emitting warnings. """ return True def granularity(self): return self._granularity def granularity(self, granularity): if not isinstance(granularity, (int, float)): try: granularity = granularity_str_to_seconds(granularity) except: granularity = getattr(granularity, "freqstr", granularity) self._granularity = granularity def aggregation_policy(self) -> AggregationPolicy: return self._aggregation_policy def aggregation_policy(self, agg: Union[str, AggregationPolicy]): if isinstance(agg, str): valid = set(AggregationPolicy.__members__.keys()) if agg not in valid: raise KeyError(f"{agg} is not a valid aggregation policy. Valid aggregation policies are: {valid}") agg = AggregationPolicy[agg] self._aggregation_policy = agg def missing_value_policy(self) -> MissingValuePolicy: return self._missing_value_policy def missing_value_policy(self, mv: Union[str, MissingValuePolicy]): if isinstance(mv, str): valid = set(MissingValuePolicy.__members__.keys()) if mv not in valid: raise KeyError(f"{mv} is not a valid missing value policy. Valid aggregation policies are: {valid}") mv = MissingValuePolicy[mv] self._missing_value_policy = mv def train(self, time_series: TimeSeries): if self.trainable_granularity: granularity = infer_granularity(time_series.np_time_stamps) logger.warning(f"Inferred granularity {granularity}") self.granularity = granularity if self.trainable_granularity or self.origin is None: t0, tf = time_series.t0, time_series.tf if isinstance(self.granularity, (int, float)): offset = (tf - t0) % self.granularity else: offset = 0 self.origin = t0 + offset def __call__(self, time_series: TimeSeries) -> TimeSeries: if self.granularity is None: logger.warning( f"Skipping resampling step because granularity is " f"None. Please either specify a granularity or train " f"this transformation on a time series." ) return time_series return time_series.align( alignment_policy=AlignPolicy.FixedGranularity, granularity=self.granularity, origin=self.origin, remove_non_overlapping=self.remove_non_overlapping, aggregation_policy=self.aggregation_policy, missing_value_policy=self.missing_value_policy, ) def to_pd_datetime(timestamp): """ Converts a timestamp (or list/iterable of timestamps) to pandas Datetime, truncated at the millisecond. """ if isinstance(timestamp, pd.DatetimeIndex): return timestamp elif isinstance(timestamp, (int, float)): return pd.to_datetime(int(timestamp * 1000), unit="ms") elif isinstance(timestamp, Iterable) and all(isinstance(t, (int, float)) for t in timestamp): timestamp = pd.to_datetime(np.asarray(timestamp).astype(float) * 1000, unit="ms") elif isinstance(timestamp, np.ndarray) and timestamp.dtype in [int, np.float32, np.float64]: timestamp = pd.to_datetime(np.asarray(timestamp).astype(float) * 1000, unit="ms") return pd.to_datetime(timestamp) The provided code snippet includes necessary dependencies for implementing the `train_model` function. Write a Python function `def train_model( model_name, metric, dataset, retrain_freq=None, train_window=None, load_checkpoint=False, visualize=False, debug=False, unsupervised=False, tune_on_test=False, )` to solve the following problem: Trains a model on the time series dataset given, and save their predictions to a dataset. Here is the function: def train_model( model_name, metric, dataset, retrain_freq=None, train_window=None, load_checkpoint=False, visualize=False, debug=False, unsupervised=False, tune_on_test=False, ): """Trains a model on the time series dataset given, and save their predictions to a dataset.""" resampler = None if isinstance(dataset, IOpsCompetition): resampler = TemporalResample("5min") model_name = resolve_model_name(model_name) dataset_name = get_dataset_name(dataset) model_dir = model_name if retrain_freq is None else f"{model_name}_{retrain_freq}" dirname = os.path.join("results", "anomaly", model_dir) csv = os.path.join(dirname, f"pred_{dataset_name}.csv.gz") config_fname = os.path.join(dirname, f"{dataset_name}_config.json") checkpoint = os.path.join(dirname, f"ckpt_{dataset_name}.txt") # Determine where to start within the dataset if there is a checkpoint i0 = 0 if os.path.isfile(checkpoint) and os.path.isfile(csv) and load_checkpoint: with open(checkpoint, "r") as f: i0 = int(f.read().rstrip("\n")) # Validate & sanitize the existing CSV checkpoint df = pd.read_csv(csv, dtype={"trainval": bool, "idx": int}) df = df[df["idx"] < i0] if set(df["idx"]) == set(range(i0)): df.to_csv(csv, index=False) else: i0 = 0 model = None for i, (df, md) in enumerate(tqdm(dataset)): if i < i0: continue # Reload model & get the train / test split for this time series model, post_rule_train_config = get_model( model_name=model_name, dataset=dataset, metric=metric, tune_on_test=tune_on_test, unsupervised=unsupervised ) delay = post_rule_train_config["max_delay_sec"] train_vals = df_to_merlion(df[md.trainval], md[md.trainval], get_ground_truth=False, transform=resampler) test_vals = df_to_merlion(df[~md.trainval], md[~md.trainval], get_ground_truth=False, transform=resampler) train_anom = df_to_merlion(df[md.trainval], md[md.trainval], get_ground_truth=True) test_anom = df_to_merlion(df[~md.trainval], md[~md.trainval], get_ground_truth=True) # Set up an evaluator & get predictions evaluator = TSADEvaluator( model=model, config=TSADEvaluatorConfig( train_window=train_window, retrain_freq=retrain_freq, max_delay_sec=delay, max_early_sec=getattr(model.threshold, "suppress_secs", delay), ), ) train_scores, test_scores = evaluator.get_predict( train_vals=train_vals, test_vals=test_vals, post_process=False, train_kwargs={"anomaly_labels": train_anom, "post_rule_train_config": post_rule_train_config}, ) # Write the model's predictions to the csv file, starting a new one # if we aren't loading an existing checkpoint. Scores from all time # series in the dataset are combined together in a single csv. Each # line in the csv corresponds to a point in a time series, and contains # the timestamp, raw anomaly score, and index of the time series. if not visualize: if i == i0 == 0: os.makedirs(os.path.dirname(csv), exist_ok=True) os.makedirs(os.path.dirname(checkpoint), exist_ok=True) df = pd.DataFrame({"timestamp": [], "y": [], "trainval": [], "idx": []}) df.to_csv(csv, index=False) df = pd.read_csv(csv) ts_df = pd.concat((train_scores.to_pd(), test_scores.to_pd())) ts_df.columns = ["y"] ts_df.loc[:, "timestamp"] = ts_df.index.view(int) // 1e9 ts_df.loc[:, "trainval"] = [j < len(train_scores) for j in range(len(ts_df))] ts_df.loc[:, "idx"] = i df = pd.concat((df, ts_df), ignore_index=True) df.to_csv(csv, index=False) # Start from time series i+1 if loading a checkpoint. with open(checkpoint, "w") as f: f.write(str(i + 1)) if visualize or debug: # Train the post-rule on the appropriate labels score = test_scores if tune_on_test else train_scores label = test_anom if tune_on_test else train_anom model.train_post_process( train_result=score, anomaly_labels=label, post_rule_train_config=post_rule_train_config ) # Log (many) evaluation metrics for the time series score_acc = evaluator.evaluate(ground_truth=test_anom, predict=model.threshold(test_scores)) mttd = score_acc.mean_time_to_detect() if mttd < pd.to_timedelta(0): mttd = f"-{-mttd}" logger.info(f"\nPerformance on time series {i+1}/{len(dataset)}") logger.info("Revised Point-Adjusted Metrics") logger.info(f"F1 Score: {score_acc.f1(score_type=ScoreType.RevisedPointAdjusted):.4f}") logger.info(f"Precision: {score_acc.precision(score_type=ScoreType.RevisedPointAdjusted):.4f}") logger.info(f"Recall: {score_acc.recall(score_type=ScoreType.RevisedPointAdjusted):.4f}\n") logger.info(f"Mean Time To Detect Anomalies: {mttd}") logger.info(f"Mean Detected Anomaly Duration: {score_acc.mean_detected_anomaly_duration()}") logger.info(f"Mean Anomaly Duration: {score_acc.mean_anomaly_duration()}\n") if debug: logger.info(f"Pointwise metrics") logger.info(f"F1 Score: {score_acc.f1(score_type=ScoreType.Pointwise):.4f}") logger.info(f"Precision: {score_acc.precision(score_type=ScoreType.Pointwise):.4f}") logger.info(f"Recall: {score_acc.recall(score_type=ScoreType.Pointwise):.4f}\n") logger.info("Point-Adjusted Metrics") logger.info(f"F1 Score: {score_acc.f1(score_type=ScoreType.PointAdjusted):.4f}") logger.info(f"Precision: {score_acc.precision(score_type=ScoreType.PointAdjusted):.4f}") logger.info(f"Recall: {score_acc.recall(score_type=ScoreType.PointAdjusted):.4f}\n") logger.info(f"NAB Scores") logger.info(f"NAB score (balanced): {score_acc.nab_score():.4f}") logger.info(f"NAB score (low FP): {score_acc.nab_score(fp_weight=0.22):.4f}") logger.info(f"NAB score (low FN): {score_acc.nab_score(fn_weight=2.0):.4f}\n") if visualize: # Make a plot alarms = model.threshold(test_scores) fig = model.get_figure(time_series=test_vals, time_series_prev=train_vals, plot_time_series_prev=True) fig.anom = alarms.univariates[alarms.names[0]] fig, ax = fig.plot(figsize=(1800, 600)) # Overlay windows indicating the true anomalies all_anom = train_anom + test_anom t, y = zip(*all_anom) y = np.asarray(y).flatten() splits = np.where(y[1:] != y[:-1])[0] + 1 splits = np.concatenate(([0], splits, [len(y) - 1])) anom_windows = [(splits[k], splits[k + 1]) for k in range(len(splits) - 1) if y[splits[k]]] for i_0, i_f in anom_windows: t_0 = to_pd_datetime(t[i_0]) t_f = to_pd_datetime(t[i_f]) ax.axvspan(t_0, t_f, color="#d07070", zorder=-1, alpha=0.5) time.sleep(2) plt.show() # Save full experimental config if model is not None and not visualize: full_config = dict( model_config=model.config.to_dict(), evaluator_config=evaluator.config.to_dict(), code_version_info=get_code_version_info(), ) os.makedirs(os.path.dirname(config_fname), exist_ok=True) with open(config_fname, "w") as f: json.dump(full_config, f, indent=2, sort_keys=True)
Trains a model on the time series dataset given, and save their predictions to a dataset.
313
import argparse import copy import json import logging import os import sys import time import git from typing import Tuple import matplotlib.pyplot as plt import numpy as np import pandas as pd from tqdm import tqdm from merlion.evaluate.anomaly import ( TSADEvaluatorConfig, accumulate_tsad_score, TSADScoreAccumulator as ScoreAcc, TSADEvaluator, ) from merlion.models.anomaly.base import DetectorBase from merlion.models.ensemble.anomaly import DetectorEnsemble from merlion.evaluate.anomaly import TSADMetric, ScoreType from merlion.models.factory import ModelFactory from merlion.transform.resample import TemporalResample from merlion.utils import TimeSeries from merlion.utils.resample import to_pd_datetime from ts_datasets.anomaly import * def get_dataset_name(dataset: TSADBaseDataset): name = type(dataset).__name__ if hasattr(dataset, "subset") and dataset.subset is not None: name += "_" + dataset.subset if isinstance(dataset, CustomAnomalyDataset): root = dataset.rootdir name = os.path.join(name, os.path.basename(os.path.dirname(root) if os.path.isfile(root) else root)) return name def to_pd_datetime(timestamp): """ Converts a timestamp (or list/iterable of timestamps) to pandas Datetime, truncated at the millisecond. """ if isinstance(timestamp, pd.DatetimeIndex): return timestamp elif isinstance(timestamp, (int, float)): return pd.to_datetime(int(timestamp * 1000), unit="ms") elif isinstance(timestamp, Iterable) and all(isinstance(t, (int, float)) for t in timestamp): timestamp = pd.to_datetime(np.asarray(timestamp).astype(float) * 1000, unit="ms") elif isinstance(timestamp, np.ndarray) and timestamp.dtype in [int, np.float32, np.float64]: timestamp = pd.to_datetime(np.asarray(timestamp).astype(float) * 1000, unit="ms") return pd.to_datetime(timestamp) The provided code snippet includes necessary dependencies for implementing the `read_model_predictions` function. Write a Python function `def read_model_predictions(dataset: TSADBaseDataset, model_dir: str)` to solve the following problem: Returns a list of lists all_preds, where all_preds[i] is the model's raw anomaly scores for time series i in the dataset. Here is the function: def read_model_predictions(dataset: TSADBaseDataset, model_dir: str): """ Returns a list of lists all_preds, where all_preds[i] is the model's raw anomaly scores for time series i in the dataset. """ csv = os.path.join("results", "anomaly", model_dir, f"pred_{get_dataset_name(dataset)}.csv.gz") preds = pd.read_csv(csv, dtype={"trainval": bool, "idx": int}) preds["timestamp"] = to_pd_datetime(preds["timestamp"]) return [preds[preds["idx"] == i].set_index("timestamp") for i in sorted(preds["idx"].unique())]
Returns a list of lists all_preds, where all_preds[i] is the model's raw anomaly scores for time series i in the dataset.
314
import argparse import copy import json import logging import os import sys import time import git from typing import Tuple import matplotlib.pyplot as plt import numpy as np import pandas as pd from tqdm import tqdm from merlion.evaluate.anomaly import ( TSADEvaluatorConfig, accumulate_tsad_score, TSADScoreAccumulator as ScoreAcc, TSADEvaluator, ) from merlion.models.anomaly.base import DetectorBase from merlion.models.ensemble.anomaly import DetectorEnsemble from merlion.evaluate.anomaly import TSADMetric, ScoreType from merlion.models.factory import ModelFactory from merlion.transform.resample import TemporalResample from merlion.utils import TimeSeries from merlion.utils.resample import to_pd_datetime from ts_datasets.anomaly import * def dataset_to_threshold(dataset: TSADBaseDataset, tune_on_test=False): if isinstance(dataset, IOpsCompetition): return 2.25 elif isinstance(dataset, NAB): return 3.5 elif isinstance(dataset, Synthetic): return 2 elif isinstance(dataset, MSL): return 3.0 elif isinstance(dataset, SMAP): return 3.5 elif isinstance(dataset, SMD): return 3 if not tune_on_test else 2.5 elif hasattr(dataset, "default_threshold"): return dataset.default_threshold return 3 def get_model( model_name: str, dataset: TSADBaseDataset, metric: TSADMetric, tune_on_test=False, unsupervised=False ) -> Tuple[DetectorBase, dict]: with open(CONFIG_JSON, "r") as f: config_dict = json.load(f) if model_name not in config_dict: raise NotImplementedError( f"Benchmarking not implemented for model {model_name}. Valid model names are {list(config_dict.keys())}" ) while "alias" in config_dict[model_name]: model_name = config_dict[model_name]["alias"] # Load the model with default kwargs, but override with dataset-specific # kwargs where relevant model_configs = config_dict[model_name]["config"] model_type = config_dict[model_name].get("model_type", model_name) model_kwargs = model_configs["default"] model_kwargs.update(model_configs.get(type(dataset).__name__, {})) model = ModelFactory.create(name=model_type, **model_kwargs) # The post-rule train configs are fully specified for each dataset (where # relevant), with a default option if there is no dataset-specific option. post_rule_train_configs = config_dict[model_name].get("post_rule_train_config", {}) d = post_rule_train_configs.get("default", {}) d.update(post_rule_train_configs.get(type(dataset).__name__, {})) if len(d) == 0: d = copy.copy(model._default_post_rule_train_config) d["metric"] = None if unsupervised else metric d.update({"max_early_sec": dataset.max_lead_sec, "max_delay_sec": dataset.max_lag_sec}) t = dataset_to_threshold(dataset, tune_on_test) model.threshold.alm_threshold = t d["unsup_quantile"] = None return model, d def df_to_merlion(df: pd.DataFrame, md: pd.DataFrame, get_ground_truth=False, transform=None) -> TimeSeries: """Converts a pandas dataframe time series to the Merlion format.""" if get_ground_truth: if False and "changepoint" in md.keys(): series = md["anomaly"] | md["changepoint"] else: series = md["anomaly"] else: series = df time_series = TimeSeries.from_pd(series) if transform is not None: time_series = transform(time_series) return time_series class ScoreType(Enum): """ The algorithm to use to compute true/false positives/negatives. See the technical report for more details on each score type. Merlion's preferred default is revised point-adjusted. """ Pointwise = 0 PointAdjusted = 1 RevisedPointAdjusted = 2 def accumulate_tsad_score( ground_truth: Union[TimeSeries, UnivariateTimeSeries], predict: Union[TimeSeries, UnivariateTimeSeries], max_early_sec=None, max_delay_sec=None, metric=None, ) -> Union[TSADScoreAccumulator, float]: """ Computes the components required to compute multiple different types of performance metrics for time series anomaly detection. :param ground_truth: A time series indicating whether each time step corresponds to an anomaly. :param predict: A time series with the anomaly score predicted for each time step. Detections correspond to nonzero scores. :param max_early_sec: The maximum amount of time (in seconds) the anomaly detection is allowed to occur before the actual incidence. If None, no early detections are allowed. Note that None is the same as 0. :param max_delay_sec: The maximum amount of time (in seconds) the anomaly detection is allowed to occur after the start of the actual incident (but before the end of the actual incident). If None, we allow any detection during the duration of the incident. Note that None differs from 0 because 0 means that we only permit detections that are early or exactly on time! :param metric: A function which takes a `TSADScoreAccumulator` as input and returns a ``float``. The `TSADScoreAccumulator` object is returned if ``metric`` is ``None``. """ ground_truth = ground_truth.to_ts() if isinstance(ground_truth, UnivariateTimeSeries) else ground_truth predict = predict.to_ts() if isinstance(predict, UnivariateTimeSeries) else predict assert ( ground_truth.dim == 1 and predict.dim == 1 ), "Can only evaluate anomaly scores when ground truth and prediction are single-variable time series." ground_truth = ground_truth.univariates[ground_truth.names[0]] ts = ground_truth.np_time_stamps ys = ground_truth.np_values.astype(bool) i_split = np.where(ys[1:] != ys[:-1])[0] + 1 predict = predict.univariates[predict.names[0]] ts_pred = predict.np_time_stamps ys_pred = predict.np_values.astype(bool) t = t_prev = ts[0] window_is_anomaly = ys[0] t0_anomaly, tf_anomaly = None, None num_tp_pointwise, num_tp_point_adj, num_tp_anom = 0, 0, 0 num_fn_pointwise, num_fn_point_adj, num_fn_anom = 0, 0, 0 num_tn, num_fp = 0, 0 tp_score, fp_score = 0.0, 0.0 tp_detection_delays, anom_durations, tp_anom_durations = [], [], [] for i in [*i_split, -1]: t_next = ts[i] + int(i == -1) # Determine the boundaries of the window # Add buffer if it's anomalous, remove buffer if it's not t0, tf = t, t_next if window_is_anomaly: t0_anomaly, tf_anomaly = t0, tf if max_early_sec is not None and max_early_sec > 0: t0 = max(t_prev, t - max_early_sec) if max_delay_sec is not None and max_delay_sec > 0 and i != -1: tf = min(t_next, t + max_delay_sec) else: if max_delay_sec is not None and max_delay_sec > 0: t0 = min(t, t_prev + max_delay_sec) if max_early_sec is not None and max_early_sec > 0: tf = max(t, t_next - max_early_sec) j0 = bisect_left(ts_pred, t0) jf = max(bisect_left(ts_pred, tf), j0 + 1) window = ys_pred[j0:jf] if window_is_anomaly: anom_durations.append(tf_anomaly - t0_anomaly) num_tp_pointwise += sum(y != 0 for y in window) num_fn_pointwise += sum(y == 0 for y in window) if not any(window): num_fn_anom += 1 num_fn_point_adj += len(window) # true positives are more beneficial if they occur earlier else: num_tp_anom += 1 num_tp_point_adj += len(window) t_detect = ts_pred[np.where(window)[0][0] + j0] tp_detection_delays.append(t_detect - t0_anomaly) tp_anom_durations.append(tf_anomaly - t0_anomaly) delay = 0 if tf - t0 == 0 else (t_detect - t0) / (tf - t0) tp_score += sum(scaled_sigmoid(delay)) else: # false positives are more severe if they occur later # FIXME: false positives can be fired in data spans that are # not present in the original data. Should we still # count these, or should we remove them from the window? if any(window): t_fp = ts_pred[np.where(window)[0] + j0] num_fp += len(t_fp) if tf != t0: delays = (t_fp - t0) / (tf - t0) else: delays = np.infty * np.ones(len(t_fp)) fp_score += sum(scaled_sigmoid(delays)) # do nothing for true negatives, except count them num_tn += sum(window == 0) # Advance to the next window t_prev = t t = t_next window_is_anomaly = not window_is_anomaly score_components = TSADScoreAccumulator( num_tp_anom=num_tp_anom, num_tp_pointwise=num_tp_pointwise, num_tp_point_adj=num_tp_point_adj, num_fp=num_fp, num_fn_anom=num_fn_anom, num_fn_pointwise=num_fn_pointwise, num_fn_point_adj=num_fn_point_adj, num_tn=num_tn, tp_score=tp_score, fp_score=fp_score, tp_detection_delays=tp_detection_delays, tp_anom_durations=tp_anom_durations, anom_durations=anom_durations, ) if metric is not None: return metric(score_components) return score_components class TSADMetric(Enum): """ Enumeration of evaluation metrics for time series anomaly detection. For each value, the name is the metric, and the value is a partial function of form ``f(ground_truth, predicted, **kwargs)`` """ MeanTimeToDetect = partial(accumulate_tsad_score, metric=TSADScoreAccumulator.mean_time_to_detect) # Revised point-adjusted metrics (default) F1 = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.f1, score_type=ScoreType.RevisedPointAdjusted) ) Precision = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.precision, score_type=ScoreType.RevisedPointAdjusted) ) Recall = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.recall, score_type=ScoreType.RevisedPointAdjusted) ) # Pointwise metrics PointwiseF1 = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.f1, score_type=ScoreType.Pointwise) ) PointwisePrecision = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.precision, score_type=ScoreType.Pointwise) ) PointwiseRecall = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.recall, score_type=ScoreType.Pointwise) ) # Point-adjusted metrics PointAdjustedF1 = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.f1, score_type=ScoreType.PointAdjusted) ) PointAdjustedPrecision = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.precision, score_type=ScoreType.PointAdjusted) ) PointAdjustedRecall = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.recall, score_type=ScoreType.PointAdjusted) ) # NAB scores NABScore = partial(accumulate_tsad_score, metric=TSADScoreAccumulator.nab_score) NABScoreLowFN = partial(accumulate_tsad_score, metric=partial(TSADScoreAccumulator.nab_score, fn_weight=2.0)) NABScoreLowFP = partial(accumulate_tsad_score, metric=partial(TSADScoreAccumulator.nab_score, fp_weight=0.22)) # Argus metrics F2 = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.f_beta, score_type=ScoreType.RevisedPointAdjusted, beta=2.0), ) F5 = partial( accumulate_tsad_score, metric=partial(TSADScoreAccumulator.f_beta, score_type=ScoreType.RevisedPointAdjusted, beta=5.0), ) class DetectorEnsemble(EnsembleBase, DetectorBase): """ Class representing an ensemble of multiple anomaly detection models. """ models: List[DetectorBase] config_class = DetectorEnsembleConfig def __init__(self, config: DetectorEnsembleConfig = None, models: List[DetectorBase] = None): super().__init__(config=config, models=models) for model in self.models: assert isinstance(model, DetectorBase), ( f"Expected all models in {type(self).__name__} to be anomaly " f"detectors, but got a {type(model).__name__}." ) model.config.enable_threshold = self.per_model_threshold def require_even_sampling(self) -> bool: return False def require_univariate(self) -> bool: return False def _default_post_rule_train_config(self): return dict(metric=TSADMetric.F1, unsup_quantile=None) def _default_train_config(self): return DetectorEnsembleTrainConfig() def per_model_threshold(self): """ :return: whether to apply the threshold rule of each individual model before aggregating their anomaly scores. """ return self.config.per_model_threshold def _train( self, train_data: TimeSeries, train_config: DetectorEnsembleTrainConfig = None, anomaly_labels: TimeSeries = None, ) -> TimeSeries: """ Trains each anomaly detector in the ensemble unsupervised, and each of their post-rules supervised (if labels are given). :param train_data: a `TimeSeries` of metric values to train the model. :param train_config: `DetectorEnsembleTrainConfig` for ensemble training. :param anomaly_labels: a `TimeSeries` indicating which timestamps are anomalous. Optional. :return: A `TimeSeries` of the ensemble's anomaly scores on the training data. """ train, valid = self.train_valid_split(train_data, train_config) if valid is not None: logger.warning("Using a train/validation split to train a DetectorEnsemble is not recommended!") train_cfgs = train_config.per_model_train_configs if train_cfgs is None: train_cfgs = [None] * len(self.models) assert len(train_cfgs) == len(self.models), ( f"You must provide the same number of per-model train configs as models, but received received" f"{len(train_cfgs)} train configs for an ensemble with {len(self.models)} models." ) pr_cfgs = train_config.per_model_post_rule_train_configs if pr_cfgs is None: pr_cfgs = [None] * len(self.models) assert len(pr_cfgs) == len(self.models), ( f"You must provide the same number of per-model post-rule train configs as models, but received " f"{len(pr_cfgs)} post-rule train configs for an ensemble with {len(self.models)} models." ) # Train each model individually, with its own train config & post-rule train config all_scores = [] eval_cfg = TSADEvaluatorConfig(retrain_freq=None, cadence=self.get_max_common_horizon(train)) # TODO: parallelize me for i, (model, cfg, pr_cfg) in enumerate(zip(self.models, train_cfgs, pr_cfgs)): try: train_kwargs = dict(train_config=cfg, anomaly_labels=anomaly_labels, post_rule_train_config=pr_cfg) train_scores, valid_scores = TSADEvaluator(model=model, config=eval_cfg).get_predict( train_vals=train, test_vals=valid, train_kwargs=train_kwargs, post_process=True ) scores = train_scores if valid is None else valid_scores except Exception: logger.warning( f"Caught an exception while training model {i + 1}/{len(self.models)} ({type(model).__name__}). " f"Model will not be used. {traceback.format_exc()}" ) self.combiner.set_model_used(i, False) scores = None all_scores.append(scores) # Train combiner on train data if there is no validation data if valid is None: return self.train_combiner(all_scores, anomaly_labels) # Otherwise, train the combiner on the validation data, and re-train the models on the full data self.train_combiner(all_scores, anomaly_labels.bisect(t=valid.time_stamps[0], t_in_left=False)[1]) all_scores = [] # TODO: parallelize me for i, (model, cfg, pr_cfg, used) in enumerate(zip(self.models, train_cfgs, pr_cfgs, self.models_used)): model.reset() if used: logger.info(f"Re-training model {i+1}/{len(self.models)} ({type(model).__name__}) on full data...") train_kwargs = dict(train_config=cfg, anomaly_labels=anomaly_labels, post_rule_train_config=pr_cfg) train_scores = model.train(train_data, **train_kwargs) train_scores = model.post_rule(train_scores) else: train_scores = None all_scores.append(train_scores) return self.combiner(all_scores, anomaly_labels) def _get_anomaly_score(self, time_series: pd.DataFrame, time_series_prev: pd.DataFrame = None) -> pd.DataFrame: time_series, time_series_prev = TimeSeries.from_pd(time_series), TimeSeries.from_pd(time_series_prev) y = [ model.get_anomaly_label(time_series, time_series_prev) for model, used in zip(self.models, self.models_used) if used ] return self.combiner(y, time_series).to_pd() class TemporalResample(TransformBase): """ Defines a policy to temporally resample a time series at a specified granularity. Note that while this transform does support inversion, the recovered time series may differ from the input due to information loss when resampling. """ def __init__( self, granularity: Union[str, int, float] = None, origin: int = None, trainable_granularity: bool = None, remove_non_overlapping=True, aggregation_policy: Union[str, AggregationPolicy] = "Mean", missing_value_policy: Union[str, MissingValuePolicy] = "Interpolate", ): """ Defines a policy to temporally resample a time series. :param granularity: The granularity at which we want to resample. :param origin: The time stamp defining the offset to start at. :param trainable_granularity: Whether we will automatically infer the granularity of the time series. If ``None`` (default), it will be trainable only if no granularity is explicitly given. :param remove_non_overlapping: If ``True``, we will only keep the portions of the univariates that overlap with each other. For example, if we have 3 univariates which span timestamps [0, 3600], [60, 3660], and [30, 3540], we will only keep timestamps in the range [60, 3540]. If ``False``, we will keep all timestamps produced by the resampling. :param aggregation_policy: The policy we will use to aggregate multiple values in a window (downsampling). :param missing_value_policy: The policy we will use to impute missing values (upsampling). """ super().__init__() self.granularity = granularity self.origin = origin self.trainable_granularity = (granularity is None) if trainable_granularity is None else trainable_granularity self.remove_non_overlapping = remove_non_overlapping self.aggregation_policy = aggregation_policy self.missing_value_policy = missing_value_policy def requires_inversion_state(self): return False def proper_inversion(self): """ We treat resampling as a proper inversion to avoid emitting warnings. """ return True def granularity(self): return self._granularity def granularity(self, granularity): if not isinstance(granularity, (int, float)): try: granularity = granularity_str_to_seconds(granularity) except: granularity = getattr(granularity, "freqstr", granularity) self._granularity = granularity def aggregation_policy(self) -> AggregationPolicy: return self._aggregation_policy def aggregation_policy(self, agg: Union[str, AggregationPolicy]): if isinstance(agg, str): valid = set(AggregationPolicy.__members__.keys()) if agg not in valid: raise KeyError(f"{agg} is not a valid aggregation policy. Valid aggregation policies are: {valid}") agg = AggregationPolicy[agg] self._aggregation_policy = agg def missing_value_policy(self) -> MissingValuePolicy: return self._missing_value_policy def missing_value_policy(self, mv: Union[str, MissingValuePolicy]): if isinstance(mv, str): valid = set(MissingValuePolicy.__members__.keys()) if mv not in valid: raise KeyError(f"{mv} is not a valid missing value policy. Valid aggregation policies are: {valid}") mv = MissingValuePolicy[mv] self._missing_value_policy = mv def train(self, time_series: TimeSeries): if self.trainable_granularity: granularity = infer_granularity(time_series.np_time_stamps) logger.warning(f"Inferred granularity {granularity}") self.granularity = granularity if self.trainable_granularity or self.origin is None: t0, tf = time_series.t0, time_series.tf if isinstance(self.granularity, (int, float)): offset = (tf - t0) % self.granularity else: offset = 0 self.origin = t0 + offset def __call__(self, time_series: TimeSeries) -> TimeSeries: if self.granularity is None: logger.warning( f"Skipping resampling step because granularity is " f"None. Please either specify a granularity or train " f"this transformation on a time series." ) return time_series return time_series.align( alignment_policy=AlignPolicy.FixedGranularity, granularity=self.granularity, origin=self.origin, remove_non_overlapping=self.remove_non_overlapping, aggregation_policy=self.aggregation_policy, missing_value_policy=self.missing_value_policy, ) def evaluate_predictions( model_names, dataset, all_model_preds, metric: TSADMetric, pointwise_metric: TSADMetric, point_adj_metric: TSADMetric, tune_on_test=False, unsupervised=False, debug=False, ): scores_rpa, scores_pw, scores_pa = [], [], [] use_ucr_eval = isinstance(dataset, UCR) and (unsupervised or not tune_on_test) resampler = None if isinstance(dataset, IOpsCompetition): resampler = TemporalResample("5min") for i, (true, md) in enumerate(tqdm(dataset)): # Get time series for the train & test splits of the ground truth idx = ~md.trainval if tune_on_test else md.trainval true_train = df_to_merlion(true[idx], md[idx], get_ground_truth=True) true_test = df_to_merlion(true[~md.trainval], md[~md.trainval], get_ground_truth=True) for acc_id, (simple_threshold, opt_metric, scores) in enumerate( [ (use_ucr_eval and not tune_on_test, metric, scores_rpa), (True, pointwise_metric, scores_pw), (True, point_adj_metric, scores_pa), ] ): if acc_id > 0 and use_ucr_eval: scores_pw = scores_rpa scores_pa = scores_rpa continue # For each model, load its raw anomaly scores for the i'th time series # as a UnivariateTimeSeries, and collect all the models' scores as a # TimeSeries. Do this for both the train and test splits. if i >= min(len(p) for p in all_model_preds): break pred = [model_preds[i] for model_preds in all_model_preds] pred_train = [p[~p["trainval"]] if tune_on_test else p[p["trainval"]] for p in pred] pred_train = [TimeSeries.from_pd(p["y"]) for p in pred_train] pred_test = [p[~p["trainval"]] for p in pred] pred_test = [TimeSeries.from_pd(p["y"]) for p in pred_test] # Train each model's post rule on the train split models = [] for name, train, og_pred in zip(model_names, pred_train, pred): m, prtc = get_model( model_name=name, dataset=dataset, metric=opt_metric, tune_on_test=tune_on_test, unsupervised=unsupervised, ) m.config.enable_threshold = len(model_names) == 1 if simple_threshold: m.threshold = m.threshold.to_simple_threshold() if tune_on_test and not unsupervised: m.calibrator.train(TimeSeries.from_pd(og_pred["y"][og_pred["trainval"]])) m.train_post_process(train_result=train, anomaly_labels=true_train, post_rule_train_config=prtc) models.append(m) # Get the lead & lag time for the dataset early, delay = dataset.max_lead_sec, dataset.max_lag_sec if early is None: leads = [getattr(m.threshold, "suppress_secs", delay) for m in models] leads = [dt for dt in leads if dt is not None] early = None if len(leads) == 0 else max(leads) # No further training if we only have 1 model if len(models) == 1: model = models[0] pred_test_raw = pred_test[0] # If we have multiple models, train an ensemble model else: threshold = dataset_to_threshold(dataset, tune_on_test) ensemble_threshold_train_config = dict( metric=opt_metric if tune_on_test else None, max_early_sec=early, max_delay_sec=delay, unsup_quantile=None, ) # Train the ensemble and its post-rule on the current time series model = DetectorEnsemble(models=models) use_m = [len(p) > 1 for p in zip(models, pred_train)] pred_train = [m.post_rule(p) for m, p, use in zip(models, pred_train, use_m) if use] pred_test = [m.post_rule(p) for m, p, use in zip(models, pred_test, use_m) if use] pred_train = model.train_combiner(pred_train, true_train) if simple_threshold: model.threshold = model.threshold.to_simple_threshold() model.threshold.alm_threshold = threshold model.train_post_process( train_result=pred_train, anomaly_labels=true_train, post_rule_train_config=ensemble_threshold_train_config, ) pred_test_raw = model.combiner(pred_test, true_test) # For UCR dataset, the evaluation just checks whether the point with the highest # anomaly score is anomalous or not. if acc_id == 0 and use_ucr_eval and not unsupervised: df = pred_test_raw.to_pd() df[np.abs(df) < df.max()] = 0 pred_test = TimeSeries.from_pd(df) else: pred_test = model.post_rule(pred_test_raw) # Compute the individual components comprising various scores. score = accumulate_tsad_score(true_test, pred_test, max_early_sec=early, max_delay_sec=delay) # Make sure all time series have exactly one detection for UCR dataset (either 1 TP, or 1 FN & 1 FP). if acc_id == 0 and use_ucr_eval: n_anom = score.num_tp_anom + score.num_fn_anom if n_anom == 0: score.num_tp_anom, score.num_fn_anom, score.num_fp = 0, 0, 0 elif score.num_tp_anom > 0: score.num_tp_anom, score.num_fn_anom, score.num_fp = 1, 0, 0 else: score.num_tp_anom, score.num_fn_anom, score.num_fp = 0, 1, 1 scores.append(score) # Aggregate statistics from full dataset score_rpa = sum(scores_rpa, ScoreAcc()) score_pw = sum(scores_pw, ScoreAcc()) score_pa = sum(scores_pa, ScoreAcc()) # Determine if it's better to have all negatives for each time series if # using the test data in a supervised way. if tune_on_test and not unsupervised: # Convert true positives to false negatives, and remove all false positives. # Keep the updated version if it improves F1 score. for s in sorted(scores_rpa, key=lambda x: x.num_fp, reverse=True): stype = ScoreType.RevisedPointAdjusted sprime = copy.deepcopy(score_rpa) sprime.num_tp_anom -= s.num_tp_anom sprime.num_fn_anom += s.num_tp_anom sprime.num_fp -= s.num_fp sprime.tp_score -= s.tp_score sprime.fp_score -= s.fp_score if score_rpa.f1(stype) < sprime.f1(stype): # Update anomaly durations for duration, delay in zip(s.tp_anom_durations, s.tp_detection_delays): sprime.tp_anom_durations.remove(duration) sprime.tp_detection_delays.remove(delay) score_rpa = sprime # Repeat for pointwise scores for s in sorted(scores_pw, key=lambda x: x.num_fp, reverse=True): stype = ScoreType.Pointwise sprime = copy.deepcopy(score_pw) sprime.num_tp_pointwise -= s.num_tp_pointwise sprime.num_fn_pointwise += s.num_tp_pointwise sprime.num_fp -= s.num_fp if score_pw.f1(stype) < sprime.f1(stype): score_pw = sprime # Repeat for point-adjusted scores for s in sorted(scores_pa, key=lambda x: x.num_fp, reverse=True): stype = ScoreType.PointAdjusted sprime = copy.deepcopy(score_pa) sprime.num_tp_point_adj -= s.num_tp_point_adj sprime.num_fn_point_adj += s.num_tp_point_adj sprime.num_fp -= s.num_fp if score_pa.f1(stype) < sprime.f1(stype): score_pa = sprime # Compute MTTD & report F1, precision, and recall mttd = score_rpa.mean_time_to_detect() if mttd < pd.to_timedelta(0): mttd = f"-{-mttd}" print() print("Revised point-adjusted metrics") print(f"F1 score: {score_rpa.f1(ScoreType.RevisedPointAdjusted):.4f}") print(f"Precision: {score_rpa.precision(ScoreType.RevisedPointAdjusted):.4f}") print(f"Recall: {score_rpa.recall(ScoreType.RevisedPointAdjusted):.4f}") print() print(f"Mean Time To Detect Anomalies: {mttd}") print(f"Mean Detected Anomaly Duration: {score_rpa.mean_detected_anomaly_duration()}") print(f"Mean Anomaly Duration: {score_rpa.mean_anomaly_duration()}") print() if debug: print("Pointwise metrics") print(f"F1 score: {score_pw.f1(ScoreType.Pointwise):.4f}") print(f"Precision: {score_pw.precision(ScoreType.Pointwise):.4f}") print(f"Recall: {score_pw.recall(ScoreType.Pointwise):.4f}") print() print("Point-adjusted metrics") print(f"F1 score: {score_pa.f1(ScoreType.PointAdjusted):.4f}") print(f"Precision: {score_pa.precision(ScoreType.PointAdjusted):.4f}") print(f"Recall: {score_pa.recall(ScoreType.PointAdjusted):.4f}") print() print("NAB Scores") print(f"NAB Score (balanced): {score_rpa.nab_score():.4f}") print(f"NAB Score (high precision): {score_rpa.nab_score(fp_weight=0.22):.4f}") print(f"NAB Score (high recall): {score_rpa.nab_score(fn_weight=2.0):.4f}") print() return score_rpa, score_pw, score_pa
null
315
import logging import os import requests from tqdm import tqdm import pandas as pd from ts_datasets.base import BaseDataset logger = logging.getLogger(__name__) def download(datapath, url, name, split=None): os.makedirs(datapath, exist_ok=True) if split is not None: namesplit = split + "/" + name else: namesplit = name url = url.format(namesplit) file_path = os.path.join(datapath, name) + ".csv" if os.path.isfile(file_path): logger.info(name + " already exists") return logger.info("Downloading " + url) r = requests.get(url, stream=True) with open(file_path, "wb") as f: for chunk in r.iter_content(chunk_size=16 * 1024**2): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush()
null
316
import os import sys import logging import requests import tarfile import numpy as np import pandas as pd from pathlib import Path from ts_datasets.anomaly.base import TSADBaseDataset def combine_train_test_datasets(train_df, test_df, test_labels): train_df.columns = [str(c) for c in train_df.columns] test_df.columns = [str(c) for c in test_df.columns] df = pd.concat([train_df, test_df]).reset_index() if "index" in df: df.drop(columns=["index"], inplace=True) df.index = pd.to_datetime(df.index * 60, unit="s") df.index.rename("timestamp", inplace=True) # There are no labels for training examples, so the training labels are set to 0 by default # The dataset is only for unsupervised time series anomaly detection metadata = pd.DataFrame( { "trainval": df.index < df.index[train_df.shape[0]], "anomaly": np.concatenate([np.zeros(train_df.shape[0], dtype=int), test_labels]), }, index=df.index, ) return df, metadata
null
317
import os import sys import logging import requests import tarfile import numpy as np import pandas as pd from pathlib import Path from ts_datasets.anomaly.base import TSADBaseDataset def download(logger, datapath, url, filename): os.makedirs(datapath, exist_ok=True) compressed_file = os.path.join(datapath, f"{filename}.tar.gz") # Download the compressed dataset if not os.path.exists(compressed_file): logger.info("Downloading " + url) with requests.get(url, stream=True) as r: with open(compressed_file, "wb") as f: for chunk in r.iter_content(chunk_size=16 * 1024**2): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() # Uncompress the downloaded tar file if not os.path.exists(os.path.join(datapath, "_SUCCESS")): logger.info(f"Uncompressing {compressed_file}") tar = tarfile.open(compressed_file, "r:gz") tar.extractall(path=datapath) tar.close() Path(os.path.join(datapath, "_SUCCESS")).touch()
null
318
import os import sys import csv import ast import logging import pickle import numpy as np import pandas as pd from ts_datasets.anomaly.base import TSADBaseDataset from ts_datasets.anomaly.smd import download, combine_train_test_datasets def preprocess(logger, data_folder, dataset): if ( os.path.exists(os.path.join(data_folder, f"{dataset}_test_label.pkl")) and os.path.exists(os.path.join(data_folder, f"{dataset}_train.pkl")) and os.path.exists(os.path.join(data_folder, f"{dataset}_test.pkl")) ): return logger.info(f"Preprocessing {dataset}") with open(os.path.join(data_folder, "labeled_anomalies.csv"), "r") as f: csv_reader = csv.reader(f, delimiter=",") res = [row for row in csv_reader][1:] res = sorted(res, key=lambda k: k[0]) labels = [] data_info = [row for row in res if row[1] == dataset and row[0] != "P-2"] for row in data_info: anomalies = ast.literal_eval(row[2]) length = int(row[-1]) label = np.zeros([length], dtype=bool) for anomaly in anomalies: label[anomaly[0] : anomaly[1] + 1] = True labels.extend(label) labels = np.asarray(labels) with open(os.path.join(data_folder, f"{dataset}_test_label.pkl"), "wb") as f: pickle.dump(labels, f) for category in ["train", "test"]: data = [] for row in data_info: data.extend(np.load(os.path.join(data_folder, category, row[0] + ".npy"))) data = np.asarray(data) with open(os.path.join(data_folder, f"{dataset}_{category}.pkl"), "wb") as f: pickle.dump(data, f)
null
319
import os import sys import csv import ast import logging import pickle import numpy as np import pandas as pd from ts_datasets.anomaly.base import TSADBaseDataset from ts_datasets.anomaly.smd import download, combine_train_test_datasets def load_data(directory, dataset): with open(os.path.join(directory, f"{dataset}_test.pkl"), "rb") as f: test_data = pickle.load(f) with open(os.path.join(directory, f"{dataset}_test_label.pkl"), "rb") as f: test_labels = pickle.load(f) with open(os.path.join(directory, f"{dataset}_train.pkl"), "rb") as f: train_data = pickle.load(f) train_df, test_df = pd.DataFrame(train_data), pd.DataFrame(test_data) return train_df, test_df, test_labels.astype(int)
null
320
from __future__ import print_function from __future__ import absolute_import from __future__ import division import numpy as np import torch def to_tensor(array, dtype=torch.float32): if 'torch.tensor' not in str(type(array)): return torch.tensor(array, dtype=dtype)
null
321
from __future__ import print_function from __future__ import absolute_import from __future__ import division import numpy as np import torch def to_np(array, dtype=np.float32): if 'scipy.sparse' in str(type(array)): array = array.todense() return np.array(array, dtype=dtype)
null
322
from __future__ import absolute_import from __future__ import print_function from __future__ import division import numpy as np import torch import torch.nn.functional as F from .utils import rot_mat_to_euler def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): ''' Calculates the rotation matrices for a batch of rotation vectors Parameters ---------- rot_vecs: torch.tensor Nx3 array of N axis-angle vectors Returns ------- R: torch.tensor Nx3x3 The rotation matrices for the given axis-angle parameters ''' batch_size = rot_vecs.shape[0] device = rot_vecs.device angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) rot_dir = rot_vecs / angle cos = torch.unsqueeze(torch.cos(angle), dim=1) sin = torch.unsqueeze(torch.sin(angle), dim=1) # Bx1 arrays rx, ry, rz = torch.split(rot_dir, 1, dim=1) K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \ .view((batch_size, 3, 3)) ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K) return rot_mat def rot_mat_to_euler(rot_mats): # Calculates rotation matrix to euler angles # Careful for extreme cases of eular angles like [0.0, pi, 0.0] sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] + rot_mats[:, 1, 0] * rot_mats[:, 1, 0]) return torch.atan2(-rot_mats[:, 2, 0], sy) The provided code snippet includes necessary dependencies for implementing the `find_dynamic_lmk_idx_and_bcoords` function. Write a Python function `def find_dynamic_lmk_idx_and_bcoords(vertices, pose, dynamic_lmk_faces_idx, dynamic_lmk_b_coords, neck_kin_chain, dtype=torch.float32)` to solve the following problem: Compute the faces, barycentric coordinates for the dynamic landmarks To do so, we first compute the rotation of the neck around the y-axis and then use a pre-computed look-up table to find the faces and the barycentric coordinates that will be used. Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de) for providing the original TensorFlow implementation and for the LUT. Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices pose: torch.tensor Bx(Jx3), dtype = torch.float32 The current pose of the body model dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long The look-up table from neck rotation to faces dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32 The look-up table from neck rotation to barycentric coordinates neck_kin_chain: list A python list that contains the indices of the joints that form the kinematic chain of the neck. dtype: torch.dtype, optional Returns ------- dyn_lmk_faces_idx: torch.tensor, dtype = torch.long A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks. dyn_lmk_b_coords: torch.tensor, dtype = torch.float32 A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks. Here is the function: def find_dynamic_lmk_idx_and_bcoords(vertices, pose, dynamic_lmk_faces_idx, dynamic_lmk_b_coords, neck_kin_chain, dtype=torch.float32): ''' Compute the faces, barycentric coordinates for the dynamic landmarks To do so, we first compute the rotation of the neck around the y-axis and then use a pre-computed look-up table to find the faces and the barycentric coordinates that will be used. Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de) for providing the original TensorFlow implementation and for the LUT. Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices pose: torch.tensor Bx(Jx3), dtype = torch.float32 The current pose of the body model dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long The look-up table from neck rotation to faces dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32 The look-up table from neck rotation to barycentric coordinates neck_kin_chain: list A python list that contains the indices of the joints that form the kinematic chain of the neck. dtype: torch.dtype, optional Returns ------- dyn_lmk_faces_idx: torch.tensor, dtype = torch.long A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks. dyn_lmk_b_coords: torch.tensor, dtype = torch.float32 A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks. ''' batch_size = vertices.shape[0] aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1, neck_kin_chain) rot_mats = batch_rodrigues( aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3) rel_rot_mat = torch.eye(3, device=vertices.device, dtype=dtype).unsqueeze_(dim=0) for idx in range(len(neck_kin_chain)): rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat) y_rot_angle = torch.round( torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi, max=39)).to(dtype=torch.long) neg_mask = y_rot_angle.lt(0).to(dtype=torch.long) mask = y_rot_angle.lt(-39).to(dtype=torch.long) neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle) y_rot_angle = (neg_mask * neg_vals + (1 - neg_mask) * y_rot_angle) dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx, 0, y_rot_angle) dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords, 0, y_rot_angle) return dyn_lmk_faces_idx, dyn_lmk_b_coords
Compute the faces, barycentric coordinates for the dynamic landmarks To do so, we first compute the rotation of the neck around the y-axis and then use a pre-computed look-up table to find the faces and the barycentric coordinates that will be used. Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de) for providing the original TensorFlow implementation and for the LUT. Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices pose: torch.tensor Bx(Jx3), dtype = torch.float32 The current pose of the body model dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long The look-up table from neck rotation to faces dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32 The look-up table from neck rotation to barycentric coordinates neck_kin_chain: list A python list that contains the indices of the joints that form the kinematic chain of the neck. dtype: torch.dtype, optional Returns ------- dyn_lmk_faces_idx: torch.tensor, dtype = torch.long A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks. dyn_lmk_b_coords: torch.tensor, dtype = torch.float32 A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks.
323
from __future__ import absolute_import from __future__ import print_function from __future__ import division import numpy as np import torch import torch.nn.functional as F from .utils import rot_mat_to_euler The provided code snippet includes necessary dependencies for implementing the `vertices2landmarks` function. Write a Python function `def vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords)` to solve the following problem: Calculates landmarks by barycentric interpolation Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices faces: torch.tensor Fx3, dtype = torch.long The faces of the mesh lmk_faces_idx: torch.tensor L, dtype = torch.long The tensor with the indices of the faces used to calculate the landmarks. lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32 The tensor of barycentric coordinates that are used to interpolate the landmarks Returns ------- landmarks: torch.tensor BxLx3, dtype = torch.float32 The coordinates of the landmarks for each mesh in the batch Here is the function: def vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords): ''' Calculates landmarks by barycentric interpolation Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices faces: torch.tensor Fx3, dtype = torch.long The faces of the mesh lmk_faces_idx: torch.tensor L, dtype = torch.long The tensor with the indices of the faces used to calculate the landmarks. lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32 The tensor of barycentric coordinates that are used to interpolate the landmarks Returns ------- landmarks: torch.tensor BxLx3, dtype = torch.float32 The coordinates of the landmarks for each mesh in the batch ''' # Extract the indices of the vertices for each face # BxLx3 batch_size, num_verts = vertices.shape[:2] device = vertices.device lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).expand( batch_size, -1, -1).long() lmk_faces = lmk_faces + torch.arange( batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts lmk_vertices = vertices.view(-1, 3)[lmk_faces].view( batch_size, -1, 3, 3) landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords]) return landmarks
Calculates landmarks by barycentric interpolation Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices faces: torch.tensor Fx3, dtype = torch.long The faces of the mesh lmk_faces_idx: torch.tensor L, dtype = torch.long The tensor with the indices of the faces used to calculate the landmarks. lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32 The tensor of barycentric coordinates that are used to interpolate the landmarks Returns ------- landmarks: torch.tensor BxLx3, dtype = torch.float32 The coordinates of the landmarks for each mesh in the batch
324
from __future__ import absolute_import from __future__ import print_function from __future__ import division import numpy as np import torch import torch.nn.functional as F from .utils import rot_mat_to_euler def vertices2joints(J_regressor, vertices): ''' Calculates the 3D joint locations from the vertices Parameters ---------- J_regressor : torch.tensor JxV The regressor array that is used to calculate the joints from the position of the vertices vertices : torch.tensor BxVx3 The tensor of mesh vertices Returns ------- torch.tensor BxJx3 The location of the joints ''' return torch.einsum('bik,ji->bjk', [vertices, J_regressor]) def blend_shapes(betas, shape_disps): ''' Calculates the per vertex displacement due to the blend shapes Parameters ---------- betas : torch.tensor Bx(num_betas) Blend shape coefficients shape_disps: torch.tensor Vx3x(num_betas) Blend shapes Returns ------- torch.tensor BxVx3 The per-vertex displacement due to shape deformation ''' # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l] # i.e. Multiply each shape displacement by its corresponding beta and # then sum them. blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps]) return blend_shape def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): ''' Calculates the rotation matrices for a batch of rotation vectors Parameters ---------- rot_vecs: torch.tensor Nx3 array of N axis-angle vectors Returns ------- R: torch.tensor Nx3x3 The rotation matrices for the given axis-angle parameters ''' batch_size = rot_vecs.shape[0] device = rot_vecs.device angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) rot_dir = rot_vecs / angle cos = torch.unsqueeze(torch.cos(angle), dim=1) sin = torch.unsqueeze(torch.sin(angle), dim=1) # Bx1 arrays rx, ry, rz = torch.split(rot_dir, 1, dim=1) K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \ .view((batch_size, 3, 3)) ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K) return rot_mat def batch_rigid_transform(rot_mats, joints, parents, dtype=torch.float32): """ Applies a batch of rigid transformations to the joints Parameters ---------- rot_mats : torch.tensor BxNx3x3 Tensor of rotation matrices joints : torch.tensor BxNx3 Locations of joints parents : torch.tensor BxN The kinematic tree of each object dtype : torch.dtype, optional: The data type of the created tensors, the default is torch.float32 Returns ------- posed_joints : torch.tensor BxNx3 The locations of the joints after applying the pose rotations rel_transforms : torch.tensor BxNx4x4 The relative (with respect to the root joint) rigid transformations for all the joints """ joints = torch.unsqueeze(joints, dim=-1) rel_joints = joints.clone() rel_joints[:, 1:] = rel_joints[:, 1:] - joints[:, parents[1:]] transforms_mat = transform_mat( rot_mats.reshape(-1, 3, 3), rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4) transform_chain = [transforms_mat[:, 0]] for i in range(1, parents.shape[0]): # Subtract the joint location at the rest pose # No need for rotation, since it's identity when at rest curr_res = torch.matmul(transform_chain[parents[i]], transforms_mat[:, i]) transform_chain.append(curr_res) transforms = torch.stack(transform_chain, dim=1) # The last column of the transformations contains the posed joints posed_joints = transforms[:, :, :3, 3] # The last column of the transformations contains the posed joints posed_joints = transforms[:, :, :3, 3] joints_homogen = F.pad(joints, [0, 0, 0, 1]) rel_transforms = transforms - F.pad( torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0]) return posed_joints, rel_transforms The provided code snippet includes necessary dependencies for implementing the `lbs` function. Write a Python function `def lbs(betas, pose, v_template, shapedirs, posedirs, J_regressor, parents, lbs_weights, pose2rot=True, dtype=torch.float32, pose_blend=True)` to solve the following problem: Performs Linear Blend Skinning with the given shape and pose parameters Parameters ---------- betas : torch.tensor BxNB The tensor of shape parameters pose : torch.tensor Bx(J + 1) * 3 The pose parameters in axis-angle format v_template torch.tensor BxVx3 The template mesh that will be deformed shapedirs : torch.tensor 1xNB The tensor of PCA shape displacements posedirs : torch.tensor Px(V * 3) The pose PCA coefficients J_regressor : torch.tensor JxV The regressor array that is used to calculate the joints from the position of the vertices parents: torch.tensor J The array that describes the kinematic tree for the model lbs_weights: torch.tensor N x V x (J + 1) The linear blend skinning weights that represent how much the rotation matrix of each part affects each vertex pose2rot: bool, optional Flag on whether to convert the input pose tensor to rotation matrices. The default value is True. If False, then the pose tensor should already contain rotation matrices and have a size of Bx(J + 1)x9 dtype: torch.dtype, optional Returns ------- verts: torch.tensor BxVx3 The vertices of the mesh after applying the shape and pose displacements. joints: torch.tensor BxJx3 The joints of the model Here is the function: def lbs(betas, pose, v_template, shapedirs, posedirs, J_regressor, parents, lbs_weights, pose2rot=True, dtype=torch.float32, pose_blend=True): ''' Performs Linear Blend Skinning with the given shape and pose parameters Parameters ---------- betas : torch.tensor BxNB The tensor of shape parameters pose : torch.tensor Bx(J + 1) * 3 The pose parameters in axis-angle format v_template torch.tensor BxVx3 The template mesh that will be deformed shapedirs : torch.tensor 1xNB The tensor of PCA shape displacements posedirs : torch.tensor Px(V * 3) The pose PCA coefficients J_regressor : torch.tensor JxV The regressor array that is used to calculate the joints from the position of the vertices parents: torch.tensor J The array that describes the kinematic tree for the model lbs_weights: torch.tensor N x V x (J + 1) The linear blend skinning weights that represent how much the rotation matrix of each part affects each vertex pose2rot: bool, optional Flag on whether to convert the input pose tensor to rotation matrices. The default value is True. If False, then the pose tensor should already contain rotation matrices and have a size of Bx(J + 1)x9 dtype: torch.dtype, optional Returns ------- verts: torch.tensor BxVx3 The vertices of the mesh after applying the shape and pose displacements. joints: torch.tensor BxJx3 The joints of the model ''' batch_size = max(betas.shape[0], pose.shape[0]) device = betas.device # Add shape contribution v_shaped = v_template + blend_shapes(betas, shapedirs) # Get the joints # NxJx3 array J = vertices2joints(J_regressor, v_shaped) # 3. Add pose blend shapes # N x J x 3 x 3 ident = torch.eye(3, dtype=dtype, device=device) if pose2rot: rot_mats = batch_rodrigues( pose.view(-1, 3), dtype=dtype).view([batch_size, -1, 3, 3]) pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1]) # (N x P) x (P, V * 3) -> N x V x 3 pose_offsets = torch.matmul(pose_feature, posedirs) \ .view(batch_size, -1, 3) else: pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident rot_mats = pose.view(batch_size, -1, 3, 3) pose_offsets = torch.matmul(pose_feature.view(batch_size, -1), posedirs).view(batch_size, -1, 3) if pose_blend: v_posed = pose_offsets + v_shaped else: v_posed = v_shaped # 4. Get the global joint location J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype) # 5. Do skinning: # W is N x V x (J + 1) W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1]) # (N x V x (J + 1)) x (N x (J + 1) x 16) num_joints = J_regressor.shape[0] T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \ .view(batch_size, -1, 4, 4) homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1], dtype=dtype, device=device) v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2) v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1)) verts = v_homo[:, :, :3, 0] return verts, J_transformed, T, W, A.view(batch_size, num_joints, 4,4)
Performs Linear Blend Skinning with the given shape and pose parameters Parameters ---------- betas : torch.tensor BxNB The tensor of shape parameters pose : torch.tensor Bx(J + 1) * 3 The pose parameters in axis-angle format v_template torch.tensor BxVx3 The template mesh that will be deformed shapedirs : torch.tensor 1xNB The tensor of PCA shape displacements posedirs : torch.tensor Px(V * 3) The pose PCA coefficients J_regressor : torch.tensor JxV The regressor array that is used to calculate the joints from the position of the vertices parents: torch.tensor J The array that describes the kinematic tree for the model lbs_weights: torch.tensor N x V x (J + 1) The linear blend skinning weights that represent how much the rotation matrix of each part affects each vertex pose2rot: bool, optional Flag on whether to convert the input pose tensor to rotation matrices. The default value is True. If False, then the pose tensor should already contain rotation matrices and have a size of Bx(J + 1)x9 dtype: torch.dtype, optional Returns ------- verts: torch.tensor BxVx3 The vertices of the mesh after applying the shape and pose displacements. joints: torch.tensor BxJx3 The joints of the model
325
import torch import torch.nn.functional as F from .smpl import SMPLServer from pytorch3d import ops The provided code snippet includes necessary dependencies for implementing the `skinning` function. Write a Python function `def skinning(x, w, tfs, inverse=False)` to solve the following problem: Linear blend skinning Args: x (tensor): canonical points. shape: [B, N, D] w (tensor): conditional input. [B, N, J] tfs (tensor): bone transformation matrices. shape: [B, J, D+1, D+1] Returns: x (tensor): skinned points. shape: [B, N, D] Here is the function: def skinning(x, w, tfs, inverse=False): """Linear blend skinning Args: x (tensor): canonical points. shape: [B, N, D] w (tensor): conditional input. [B, N, J] tfs (tensor): bone transformation matrices. shape: [B, J, D+1, D+1] Returns: x (tensor): skinned points. shape: [B, N, D] """ x_h = F.pad(x, (0, 1), value=1.0) if inverse: # p:n_point, n:n_bone, i,k: n_dim+1 w_tf = torch.einsum("bpn,bnij->bpij", w, tfs) x_h = torch.einsum("bpij,bpj->bpi", w_tf.inverse(), x_h) else: x_h = torch.einsum("bpn,bnij,bpj->bpi", w, tfs, x_h) return x_h[:, :, :3]
Linear blend skinning Args: x (tensor): canonical points. shape: [B, N, D] w (tensor): conditional input. [B, N, J] tfs (tensor): bone transformation matrices. shape: [B, J, D+1, D+1] Returns: x (tensor): skinned points. shape: [B, N, D]
326
from .networks import ImplicitNet, RenderingNet from .density import LaplaceDensity, AbsDensity from .ray_sampler import ErrorBoundSampler from .deformer import SMPLDeformer from .smpl import SMPLServer from .sampler import PointInSpace from ..utils import utils import numpy as np import torch import torch.nn as nn from torch.autograd import grad import hydra import kaolin from kaolin.ops.mesh import index_vertices_by_faces def gradient(inputs, outputs): d_points = torch.ones_like(outputs, requires_grad=False, device=outputs.device) points_grad = grad( outputs=outputs, inputs=inputs, grad_outputs=d_points, create_graph=True, retain_graph=True, only_inputs=True)[0][:, :, -3:] return points_grad
null
327
import torch class Embedder: def __init__(self, **kwargs): self.kwargs = kwargs self.create_embedding_fn() def create_embedding_fn(self): embed_fns = [] d = self.kwargs['input_dims'] out_dim = 0 if self.kwargs['include_input']: embed_fns.append(lambda x: x) out_dim += d max_freq = self.kwargs['max_freq_log2'] N_freqs = self.kwargs['num_freqs'] if self.kwargs['log_sampling']: freq_bands = 2. ** torch.linspace(0., max_freq, N_freqs) else: freq_bands = torch.linspace(2.**0., 2.**max_freq, N_freqs) for freq in freq_bands: for p_fn in self.kwargs['periodic_fns']: embed_fns.append(lambda x, p_fn=p_fn, freq=freq: p_fn(x * freq)) out_dim += d self.embed_fns = embed_fns self.out_dim = out_dim def embed(self, inputs): return torch.cat([fn(inputs) for fn in self.embed_fns], -1) def get_embedder(multires, input_dims=3, mode='fourier'): embed_kwargs = { 'include_input': True, 'input_dims': input_dims, 'max_freq_log2': multires-1, 'num_freqs': multires, 'log_sampling': True, 'periodic_fns': [torch.sin, torch.cos], } if mode == 'fourier': embedder_obj = Embedder(**embed_kwargs) def embed(x, eo=embedder_obj): return eo.embed(x) return embed, embedder_obj.out_dim
null
328
import numpy as np import cv2 import torch from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `split_input` function. Write a Python function `def split_input(model_input, total_pixels, n_pixels = 10000)` to solve the following problem: Split the input to fit Cuda memory for large resolution. Can decrease the value of n_pixels in case of cuda out of memory error. Here is the function: def split_input(model_input, total_pixels, n_pixels = 10000): ''' Split the input to fit Cuda memory for large resolution. Can decrease the value of n_pixels in case of cuda out of memory error. ''' split = [] for i, indx in enumerate(torch.split(torch.arange(total_pixels).cuda(), n_pixels, dim=0)): data = model_input.copy() data['uv'] = torch.index_select(model_input['uv'], 1, indx) split.append(data) return split
Split the input to fit Cuda memory for large resolution. Can decrease the value of n_pixels in case of cuda out of memory error.
329
import numpy as np import cv2 import torch from torch.nn import functional as F The provided code snippet includes necessary dependencies for implementing the `merge_output` function. Write a Python function `def merge_output(res, total_pixels, batch_size)` to solve the following problem: Merge the split output. Here is the function: def merge_output(res, total_pixels, batch_size): ''' Merge the split output. ''' model_outputs = {} for entry in res[0]: if res[0][entry] is None: continue if len(res[0][entry].shape) == 1: model_outputs[entry] = torch.cat([r[entry].reshape(batch_size, -1, 1) for r in res], 1).reshape(batch_size * total_pixels) else: model_outputs[entry] = torch.cat([r[entry].reshape(batch_size, -1, r[entry].shape[-1]) for r in res], 1).reshape(batch_size * total_pixels, -1) return model_outputs
Merge the split output.
330
import numpy as np import cv2 import torch from torch.nn import functional as F def get_psnr(img1, img2, normalize_rgb=False): if normalize_rgb: # [-1,1] --> [0,1] img1 = (img1 + 1.) / 2. img2 = (img2 + 1. ) / 2. mse = torch.mean((img1 - img2) ** 2) psnr = -10. * torch.log(mse) / torch.log(torch.Tensor([10.]).cuda()) return psnr
null
331
import numpy as np import cv2 import torch from torch.nn import functional as F def load_K_Rt_from_P(filename, P=None): if P is None: lines = open(filename).read().splitlines() if len(lines) == 4: lines = lines[1:] lines = [[x[0], x[1], x[2], x[3]] for x in (x.split(" ") for x in lines)] P = np.asarray(lines).astype(np.float32).squeeze() out = cv2.decomposeProjectionMatrix(P) K = out[0] R = out[1] t = out[2] K = K/K[2,2] intrinsics = np.eye(4) intrinsics[:3, :3] = K pose = np.eye(4, dtype=np.float32) pose[:3, :3] = R.transpose() pose[:3,3] = (t[:3] / t[3])[:,0] return intrinsics, pose
null
332
import numpy as np import cv2 import torch from torch.nn import functional as F def lift(x, y, z, intrinsics): # parse intrinsics intrinsics = intrinsics.cuda() fx = intrinsics[:, 0, 0] fy = intrinsics[:, 1, 1] cx = intrinsics[:, 0, 2] cy = intrinsics[:, 1, 2] sk = intrinsics[:, 0, 1] x_lift = (x - cx.unsqueeze(-1) + cy.unsqueeze(-1)*sk.unsqueeze(-1)/fy.unsqueeze(-1) - sk.unsqueeze(-1)*y/fy.unsqueeze(-1)) / fx.unsqueeze(-1) * z y_lift = (y - cy.unsqueeze(-1)) / fy.unsqueeze(-1) * z # homogeneous return torch.stack((x_lift, y_lift, z, torch.ones_like(z).cuda()), dim=-1) def quat_to_rot(q): batch_size, _ = q.shape q = F.normalize(q, dim=1) R = torch.ones((batch_size, 3,3)).cuda() qr=q[:,0] qi = q[:, 1] qj = q[:, 2] qk = q[:, 3] R[:, 0, 0]=1-2 * (qj**2 + qk**2) R[:, 0, 1] = 2 * (qj *qi -qk*qr) R[:, 0, 2] = 2 * (qi * qk + qr * qj) R[:, 1, 0] = 2 * (qj * qi + qk * qr) R[:, 1, 1] = 1-2 * (qi**2 + qk**2) R[:, 1, 2] = 2*(qj*qk - qi*qr) R[:, 2, 0] = 2 * (qk * qi-qj * qr) R[:, 2, 1] = 2 * (qj*qk + qi*qr) R[:, 2, 2] = 1-2 * (qi**2 + qj**2) return R def get_camera_params(uv, pose, intrinsics): if pose.shape[1] == 7: #In case of quaternion vector representation cam_loc = pose[:, 4:] R = quat_to_rot(pose[:,:4]) p = torch.eye(4).repeat(pose.shape[0],1,1).cuda().float() p[:, :3, :3] = R p[:, :3, 3] = cam_loc else: # In case of pose matrix representation cam_loc = pose[:, :3, 3] p = pose batch_size, num_samples, _ = uv.shape depth = torch.ones((batch_size, num_samples)).cuda() x_cam = uv[:, :, 0].view(batch_size, -1) y_cam = uv[:, :, 1].view(batch_size, -1) z_cam = depth.view(batch_size, -1) pixel_points_cam = lift(x_cam, y_cam, z_cam, intrinsics=intrinsics) # permute for batch matrix product pixel_points_cam = pixel_points_cam.permute(0, 2, 1) world_coords = torch.bmm(p, pixel_points_cam).permute(0, 2, 1)[:, :, :3] ray_dirs = world_coords - cam_loc[:, None, :] ray_dirs = F.normalize(ray_dirs, dim=2) return ray_dirs, cam_loc
null
333
import numpy as np import cv2 import torch from torch.nn import functional as F def rot_to_quat(R): batch_size, _,_ = R.shape q = torch.ones((batch_size, 4)).cuda() R00 = R[:, 0,0] R01 = R[:, 0, 1] R02 = R[:, 0, 2] R10 = R[:, 1, 0] R11 = R[:, 1, 1] R12 = R[:, 1, 2] R20 = R[:, 2, 0] R21 = R[:, 2, 1] R22 = R[:, 2, 2] q[:,0]=torch.sqrt(1.0+R00+R11+R22)/2 q[:, 1]=(R21-R12)/(4*q[:,0]) q[:, 2] = (R02 - R20) / (4 * q[:, 0]) q[:, 3] = (R10 - R01) / (4 * q[:, 0]) return q
null
334
import numpy as np import cv2 import torch from torch.nn import functional as F def get_sphere_intersections(cam_loc, ray_directions, r = 1.0): # Input: n_rays x 3 ; n_rays x 3 # Output: n_rays x 1, n_rays x 1 (close and far) ray_cam_dot = torch.bmm(ray_directions.view(-1, 1, 3), cam_loc.view(-1, 3, 1)).squeeze(-1) under_sqrt = ray_cam_dot ** 2 - (cam_loc.norm(2, 1, keepdim=True) ** 2 - r ** 2) # sanity check if (under_sqrt <= 0).sum() > 0: print('BOUNDING SPHERE PROBLEM!') exit() sphere_intersections = torch.sqrt(under_sqrt) * torch.Tensor([-1, 1]).cuda().float() - ray_cam_dot sphere_intersections = sphere_intersections.clamp_min(0.0) return sphere_intersections
null
335
import numpy as np import cv2 import torch from torch.nn import functional as F def bilinear_interpolation(xs, ys, dist_map): x1 = np.floor(xs).astype(np.int32) y1 = np.floor(ys).astype(np.int32) x2 = x1 + 1 y2 = y1 + 1 dx = np.expand_dims(np.stack([x2 - xs, xs - x1], axis=1), axis=1) dy = np.expand_dims(np.stack([y2 - ys, ys - y1], axis=1), axis=2) Q = np.stack([ dist_map[x1, y1], dist_map[x1, y2], dist_map[x2, y1], dist_map[x2, y2] ], axis=1).reshape(-1, 2, 2) return np.squeeze(dx @ Q @ dy) # ((x2 - x1) * (y2 - y1)) = 1 def get_index_outside_of_bbox(samples_uniform, bbox_min, bbox_max): samples_uniform_row = samples_uniform[:, 0] samples_uniform_col = samples_uniform[:, 1] index_outside = np.where((samples_uniform_row < bbox_min[0]) | (samples_uniform_row > bbox_max[0]) | (samples_uniform_col < bbox_min[1]) | (samples_uniform_col > bbox_max[1]))[0] return index_outside The provided code snippet includes necessary dependencies for implementing the `weighted_sampling` function. Write a Python function `def weighted_sampling(data, img_size, num_sample, bbox_ratio=0.9)` to solve the following problem: More sampling within the bounding box Here is the function: def weighted_sampling(data, img_size, num_sample, bbox_ratio=0.9): """ More sampling within the bounding box """ # calculate bounding box mask = data["object_mask"] where = np.asarray(np.where(mask)) bbox_min = where.min(axis=1) bbox_max = where.max(axis=1) num_sample_bbox = int(num_sample * bbox_ratio) samples_bbox = np.random.rand(num_sample_bbox, 2) samples_bbox = samples_bbox * (bbox_max - bbox_min) + bbox_min num_sample_uniform = num_sample - num_sample_bbox samples_uniform = np.random.rand(num_sample_uniform, 2) samples_uniform *= (img_size[0] - 1, img_size[1] - 1) # get indices for uniform samples outside of bbox index_outside = get_index_outside_of_bbox(samples_uniform, bbox_min, bbox_max) + num_sample_bbox indices = np.concatenate([samples_bbox, samples_uniform], axis=0) output = {} for key, val in data.items(): if len(val.shape) == 3: new_val = np.stack([ bilinear_interpolation(indices[:, 0], indices[:, 1], val[:, :, i]) for i in range(val.shape[2]) ], axis=-1) else: new_val = bilinear_interpolation(indices[:, 0], indices[:, 1], val) new_val = new_val.reshape(-1, *val.shape[2:]) output[key] = new_val return output, index_outside
More sampling within the bounding box
336
import numpy as np import torch from skimage import measure from lib.libmise import mise import trimesh def generate_mesh(func, verts, level_set=0, res_init=32, res_up=3, point_batch=5000): scale = 1.1 # Scale of the padded bbox regarding the tight one. verts = verts.data.cpu().numpy() gt_bbox = np.stack([verts.min(axis=0), verts.max(axis=0)], axis=0) gt_center = (gt_bbox[0] + gt_bbox[1]) * 0.5 gt_scale = (gt_bbox[1] - gt_bbox[0]).max() mesh_extractor = mise.MISE(res_init, res_up, level_set) points = mesh_extractor.query() # query occupancy grid while points.shape[0] != 0: orig_points = points points = points.astype(np.float32) points = (points / mesh_extractor.resolution - 0.5) * scale points = points * gt_scale + gt_center points = torch.tensor(points).float().cuda() values = [] for _, pnts in enumerate((torch.split(points,point_batch,dim=0))): out = func(pnts) values.append(out['sdf'].data.cpu().numpy()) values = np.concatenate(values, axis=0).astype(np.float64)[:,0] mesh_extractor.update(orig_points, values) points = mesh_extractor.query() value_grid = mesh_extractor.to_dense() # marching cube verts, faces, normals, values = measure.marching_cubes_lewiner( volume=value_grid, gradient_direction='ascent', level=level_set) verts = (verts / mesh_extractor.resolution - 0.5) * scale verts = verts * gt_scale + gt_center faces = faces[:, [0,2,1]] meshexport = trimesh.Trimesh(verts, faces, normals, vertex_colors=values) #remove disconnect part connected_comp = meshexport.split(only_watertight=False) max_area = 0 max_comp = None for comp in connected_comp: if comp.area > max_area: max_area = comp.area max_comp = comp meshexport = max_comp return meshexport
null
337
import trimesh from aitviewer.viewer import Viewer from aitviewer.renderables.meshes import Meshes, VariableTopologyMeshes import glob import argparse def vis_dynamic(args): vertices = [] faces = [] vertex_normals = [] deformed_mesh_paths = sorted(glob.glob(f'{args.path}/*_deformed.ply')) for deformed_mesh_path in deformed_mesh_paths: mesh = trimesh.load(deformed_mesh_path, process=False) # center the human mesh.vertices = mesh.vertices - mesh.vertices.mean(axis=0) vertices.append(mesh.vertices) faces.append(mesh.faces) vertex_normals.append(mesh.vertex_normals) meshes = VariableTopologyMeshes(vertices, faces, vertex_normals, preload=True ) meshes.norm_coloring = True meshes.flat_shading = True viewer = Viewer() viewer.scene.add(meshes) viewer.scene.origin.enabled = False viewer.scene.floor.enabled = True viewer.run()
null
338
import trimesh from aitviewer.viewer import Viewer from aitviewer.renderables.meshes import Meshes, VariableTopologyMeshes import glob import argparse def vis_static(args): mesh = trimesh.load(args.path, process=False) mesh = Meshes(mesh.vertices, mesh.faces, mesh.vertex_normals, name='mesh', flat_shading=True) mesh.norm_coloring = True viewer = Viewer() viewer.scene.add(mesh) viewer.scene.origin.enabled = False viewer.scene.floor.enabled = True viewer.run()
null
339
import sys import cv2 import os import numpy as np import argparse import time import glob from sklearn.neighbors import NearestNeighbors def get_bbox_center(img_path, mask_path): _img = cv2.imread(img_path) W, H = _img.shape[1], _img.shape[0] mask = cv2.imread(mask_path)[:, :, 0] where = np.asarray(np.where(mask)) bbox_min = where.min(axis=1) bbox_max = where.max(axis=1) left, top, right, bottom = bbox_min[1], bbox_min[0], bbox_max[1], bbox_max[ 0] left = max(left, 0) top = max(top, 0) right = min(right, W) bottom = min(bottom, H) bbox_center = np.array([left + (right - left) / 2, top + (bottom - top) / 2]) return bbox_center
null
340
import numpy as np import cv2 import torch import torch.nn as nn import torch.nn.functional as F from pytorch3d.renderer import ( SfMPerspectiveCameras, RasterizationSettings, MeshRenderer, MeshRasterizer, SoftPhongShader, PointLights, ) from pytorch3d.structures import Meshes from pytorch3d.renderer.mesh import Textures The provided code snippet includes necessary dependencies for implementing the `smpl_to_pose` function. Write a Python function `def smpl_to_pose(model_type='smplx', use_hands=True, use_face=True, use_face_contour=False, openpose_format='coco25')` to solve the following problem: Returns the indices of the permutation that maps OpenPose to SMPL Parameters ---------- model_type: str, optional The type of SMPL-like model that is used. The default mapping returned is for the SMPLX model use_hands: bool, optional Flag for adding to the returned permutation the mapping for the hand keypoints. Defaults to True use_face: bool, optional Flag for adding to the returned permutation the mapping for the face keypoints. Defaults to True use_face_contour: bool, optional Flag for appending the facial contour keypoints. Defaults to False openpose_format: bool, optional The output format of OpenPose. For now only COCO-25 and COCO-19 is supported. Defaults to 'coco25' Here is the function: def smpl_to_pose(model_type='smplx', use_hands=True, use_face=True, use_face_contour=False, openpose_format='coco25'): ''' Returns the indices of the permutation that maps OpenPose to SMPL Parameters ---------- model_type: str, optional The type of SMPL-like model that is used. The default mapping returned is for the SMPLX model use_hands: bool, optional Flag for adding to the returned permutation the mapping for the hand keypoints. Defaults to True use_face: bool, optional Flag for adding to the returned permutation the mapping for the face keypoints. Defaults to True use_face_contour: bool, optional Flag for appending the facial contour keypoints. Defaults to False openpose_format: bool, optional The output format of OpenPose. For now only COCO-25 and COCO-19 is supported. Defaults to 'coco25' ''' if openpose_format.lower() == 'coco25': if model_type == 'smpl': return np.array([24, 12, 17, 19, 21, 16, 18, 20, 0, 2, 5, 8, 1, 4, 7, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34], dtype=np.int32) elif model_type == 'smplh': body_mapping = np.array([52, 12, 17, 19, 21, 16, 18, 20, 0, 2, 5, 8, 1, 4, 7, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62], dtype=np.int32) mapping = [body_mapping] if use_hands: lhand_mapping = np.array([20, 34, 35, 36, 63, 22, 23, 24, 64, 25, 26, 27, 65, 31, 32, 33, 66, 28, 29, 30, 67], dtype=np.int32) rhand_mapping = np.array([21, 49, 50, 51, 68, 37, 38, 39, 69, 40, 41, 42, 70, 46, 47, 48, 71, 43, 44, 45, 72], dtype=np.int32) mapping += [lhand_mapping, rhand_mapping] return np.concatenate(mapping) # SMPLX elif model_type == 'smplx': body_mapping = np.array([55, 12, 17, 19, 21, 16, 18, 20, 0, 2, 5, 8, 1, 4, 7, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65], dtype=np.int32) mapping = [body_mapping] if use_hands: lhand_mapping = np.array([20, 37, 38, 39, 66, 25, 26, 27, 67, 28, 29, 30, 68, 34, 35, 36, 69, 31, 32, 33, 70], dtype=np.int32) rhand_mapping = np.array([21, 52, 53, 54, 71, 40, 41, 42, 72, 43, 44, 45, 73, 49, 50, 51, 74, 46, 47, 48, 75], dtype=np.int32) mapping += [lhand_mapping, rhand_mapping] if use_face: # end_idx = 127 + 17 * use_face_contour face_mapping = np.arange(76, 127 + 17 * use_face_contour, dtype=np.int32) mapping += [face_mapping] return np.concatenate(mapping) else: raise ValueError('Unknown model type: {}'.format(model_type)) elif openpose_format == 'coco19': if model_type == 'smpl': return np.array([24, 12, 17, 19, 21, 16, 18, 20, 2, 5, 8, 1, 4, 7, 25, 26, 27, 28], dtype=np.int32) elif model_type == 'smpl_neutral': return np.array([14, 12, 8, 7, 6, 9, 10, 11, 2, 1, 0, 3, 4, 5, 16, 15,18, 17,], dtype=np.int32) elif model_type == 'smplh': body_mapping = np.array([52, 12, 17, 19, 21, 16, 18, 20, 0, 2, 5, 8, 1, 4, 7, 53, 54, 55, 56], dtype=np.int32) mapping = [body_mapping] if use_hands: lhand_mapping = np.array([20, 34, 35, 36, 57, 22, 23, 24, 58, 25, 26, 27, 59, 31, 32, 33, 60, 28, 29, 30, 61], dtype=np.int32) rhand_mapping = np.array([21, 49, 50, 51, 62, 37, 38, 39, 63, 40, 41, 42, 64, 46, 47, 48, 65, 43, 44, 45, 66], dtype=np.int32) mapping += [lhand_mapping, rhand_mapping] return np.concatenate(mapping) # SMPLX elif model_type == 'smplx': body_mapping = np.array([55, 12, 17, 19, 21, 16, 18, 20, 0, 2, 5, 8, 1, 4, 7, 56, 57, 58, 59], dtype=np.int32) mapping = [body_mapping] if use_hands: lhand_mapping = np.array([20, 37, 38, 39, 60, 25, 26, 27, 61, 28, 29, 30, 62, 34, 35, 36, 63, 31, 32, 33, 64], dtype=np.int32) rhand_mapping = np.array([21, 52, 53, 54, 65, 40, 41, 42, 66, 43, 44, 45, 67, 49, 50, 51, 68, 46, 47, 48, 69], dtype=np.int32) mapping += [lhand_mapping, rhand_mapping] if use_face: face_mapping = np.arange(70, 70 + 51 + 17 * use_face_contour, dtype=np.int32) mapping += [face_mapping] return np.concatenate(mapping) else: raise ValueError('Unknown model type: {}'.format(model_type)) elif openpose_format == 'h36': if model_type == 'smpl': return np.array([2,5,8,1,4,7,12,24,16,18,20,17,19,21],dtype=np.int32) elif model_type == 'smpl_neutral': #return np.array([2,1,0,3,4,5,12,13,9,10,11,8,7,6], dtype=np.int32) return [6, 5, 4, 1, 2, 3, 16, 15, 14, 11, 12, 13, 8, 10] else: raise ValueError('Unknown joint format: {}'.format(openpose_format))
Returns the indices of the permutation that maps OpenPose to SMPL Parameters ---------- model_type: str, optional The type of SMPL-like model that is used. The default mapping returned is for the SMPLX model use_hands: bool, optional Flag for adding to the returned permutation the mapping for the hand keypoints. Defaults to True use_face: bool, optional Flag for adding to the returned permutation the mapping for the face keypoints. Defaults to True use_face_contour: bool, optional Flag for appending the facial contour keypoints. Defaults to False openpose_format: bool, optional The output format of OpenPose. For now only COCO-25 and COCO-19 is supported. Defaults to 'coco25'
341
import numpy as np import cv2 import torch import torch.nn as nn import torch.nn.functional as F from pytorch3d.renderer import ( SfMPerspectiveCameras, RasterizationSettings, MeshRenderer, MeshRasterizer, SoftPhongShader, PointLights, ) from pytorch3d.structures import Meshes from pytorch3d.renderer.mesh import Textures def render_trimesh(renderer,mesh,R,T, mode='np'): verts = torch.tensor(mesh.vertices).cuda().float()[None] faces = torch.tensor(mesh.faces).cuda()[None] colors = torch.tensor(mesh.visual.vertex_colors).float().cuda()[None,...,:3]/255 renderer.set_camera(R,T) image = renderer.render_mesh_recon(verts, faces, colors=colors, mode=mode)[0] image = (255*image).data.cpu().numpy().astype(np.uint8) return image
null
342
import numpy as np import cv2 import torch import torch.nn as nn import torch.nn.functional as F from pytorch3d.renderer import ( SfMPerspectiveCameras, RasterizationSettings, MeshRenderer, MeshRasterizer, SoftPhongShader, PointLights, ) from pytorch3d.structures import Meshes from pytorch3d.renderer.mesh import Textures INVALID_TRANS=np.ones(3)*-1 def estimate_translation_cv2(joints_3d, joints_2d, focal_length=600, img_size=np.array([512.,512.]), proj_mat=None, cam_dist=None): if proj_mat is None: camK = np.eye(3) camK[0,0], camK[1,1] = focal_length, focal_length camK[:2,2] = img_size//2 else: camK = proj_mat _, _, tvec,inliers = cv2.solvePnPRansac(joints_3d, joints_2d, camK, cam_dist,\ flags=cv2.SOLVEPNP_EPNP,reprojectionError=20,iterationsCount=100) if inliers is None: return INVALID_TRANS else: tra_pred = tvec[:,0] return tra_pred
null
343
import numpy as np import cv2 import torch import torch.nn as nn import torch.nn.functional as F from pytorch3d.renderer import ( SfMPerspectiveCameras, RasterizationSettings, MeshRenderer, MeshRasterizer, SoftPhongShader, PointLights, ) from pytorch3d.structures import Meshes from pytorch3d.renderer.mesh import Textures The provided code snippet includes necessary dependencies for implementing the `transform_mat` function. Write a Python function `def transform_mat(R, t)` to solve the following problem: Creates a batch of transformation matrices Args: - R: Bx3x3 array of a batch of rotation matrices - t: Bx3x1 array of a batch of translation vectors Returns: - T: Bx4x4 Transformation matrix Here is the function: def transform_mat(R, t): ''' Creates a batch of transformation matrices Args: - R: Bx3x3 array of a batch of rotation matrices - t: Bx3x1 array of a batch of translation vectors Returns: - T: Bx4x4 Transformation matrix ''' # No padding left or right, only add an extra row return torch.cat([F.pad(R, [0, 0, 0, 1]), F.pad(t, [0, 0, 0, 1], value=1)], dim=2)
Creates a batch of transformation matrices Args: - R: Bx3x3 array of a batch of rotation matrices - t: Bx3x1 array of a batch of translation vectors Returns: - T: Bx4x4 Transformation matrix
344
import numpy as np import cv2 import torch import torch.nn as nn import torch.nn.functional as F from pytorch3d.renderer import ( SfMPerspectiveCameras, RasterizationSettings, MeshRenderer, MeshRasterizer, SoftPhongShader, PointLights, ) from pytorch3d.structures import Meshes from pytorch3d.renderer.mesh import Textures def transform_smpl(curr_extrinsic, target_extrinsic, smpl_pose, smpl_trans, T_hip): R_root = cv2.Rodrigues(smpl_pose[:3])[0] transf_global_ori = np.linalg.inv(target_extrinsic[:3,:3]) @ curr_extrinsic[:3,:3] @ R_root target_extrinsic[:3, -1] = curr_extrinsic[:3,:3] @ (smpl_trans + T_hip) + curr_extrinsic[:3, -1] - smpl_trans - target_extrinsic[:3,:3] @ T_hip smpl_pose[:3] = cv2.Rodrigues(transf_global_ori)[0].reshape(3) smpl_trans = np.linalg.inv(target_extrinsic[:3,:3]) @ smpl_trans # we assume return target_extrinsic, smpl_pose, smpl_trans
null
345
from preprocessing_utils import GMoF import torch def get_loss_weights(): loss_weight = {'J2D_Loss': lambda cst, it: 1e-2 * cst, 'Temporal_Loss': lambda cst, it: 6e0 * cst, } return loss_weight
null
346
from preprocessing_utils import GMoF import torch joint_weights = torch.ones(num_joints) joint_weights[joints_to_ign] = 0 joint_weights = joint_weights.reshape((-1,1)).cuda() robustifier = GMoF(rho=100) def joints_2d_loss(gt_joints_2d=None, joints_2d=None, joint_confidence=None): joint_diff = robustifier(gt_joints_2d - joints_2d) joints_2dloss = torch.mean((joint_confidence*joint_weights[:, 0]).unsqueeze(-1) ** 2 * joint_diff) return joints_2dloss
null
347
from preprocessing_utils import GMoF import torch def pose_temporal_loss(last_pose, param_pose): temporal_loss = torch.mean(torch.square(last_pose - param_pose)) return temporal_loss
null
348
import cv2 import numpy as np import argparse def get_center_point(num_cams,cameras): def normalize_cameras(original_cameras_filename,output_cameras_filename,num_of_cameras, scene_bounding_sphere=3.0): cameras = np.load(original_cameras_filename) if num_of_cameras==-1: all_files=cameras.files maximal_ind=0 for field in all_files: maximal_ind=np.maximum(maximal_ind,int(field.split('_')[-1])) num_of_cameras=maximal_ind+1 camera_centers = get_center_point(num_of_cameras, cameras) center = np.array([0, 0, 0]) max_radius = np.linalg.norm((center[:, np.newaxis] - camera_centers), axis=0).max() * 1.1 normalization = np.eye(4).astype(np.float32) normalization[0, 0] = max_radius / scene_bounding_sphere normalization[1, 1] = max_radius / scene_bounding_sphere normalization[2, 2] = max_radius / scene_bounding_sphere cameras_new = {} for i in range(num_of_cameras): cameras_new['scale_mat_%d' % i] = normalization cameras_new['world_mat_%d' % i] = cameras['cam_%d' % i].copy() np.savez(output_cameras_filename, **cameras_new)
null
349
from typing import Optional, Dict, Union import os import os.path as osp import pickle import numpy as np import torch import torch.nn as nn from .lbs import ( lbs, vertices2landmarks, find_dynamic_lmk_idx_and_bcoords, vertices2joints, blend_shapes) from .vertex_ids import vertex_ids as VERTEX_IDS from .utils import ( Struct, to_np, to_tensor, Tensor, Array, SMPLOutput, SMPLHOutput, SMPLXOutput, MANOOutput, FLAMEOutput, find_joint_kin_chain) from .vertex_joint_selector import VertexJointSelector class SMPLLayer(SMPL): def __init__( self, *args ) -> None: # Just create a SMPL module without any member variables super(SMPLLayer, self).__init__( create_body_pose=False, create_betas=False, create_global_orient=False, create_transl=False, *args, ) def forward( self, betas: Optional[Tensor] = None, body_pose: Optional[Tensor] = None, global_orient: Optional[Tensor] = None, transl: Optional[Tensor] = None, return_verts=True, return_full_pose: bool = False, pose2rot: bool = True ) -> SMPLOutput: ''' Forward pass for the SMPL model Parameters ---------- global_orient: torch.tensor, optional, shape Bx3x3 Global rotation of the body. Useful if someone wishes to predicts this with an external model. It is expected to be in rotation matrix format. (default=None) betas: torch.tensor, optional, shape BxN_b Shape parameters. For example, it can used if shape parameters `betas` are predicted from some external model. (default=None) body_pose: torch.tensor, optional, shape BxJx3x3 Body pose. For example, it can used if someone predicts the pose of the body joints are predicted from some external model. It should be a tensor that contains joint rotations in rotation matrix format. (default=None) transl: torch.tensor, optional, shape Bx3 Translation vector of the body. For example, it can used if the translation `transl` is predicted from some external model. (default=None) return_verts: bool, optional Return the vertices. (default=True) return_full_pose: bool, optional Returns the full axis-angle pose vector (default=False) Returns ------- ''' model_vars = [betas, global_orient, body_pose, transl] batch_size = 1 for var in model_vars: if var is None: continue batch_size = max(batch_size, len(var)) device, dtype = self.shapedirs.device, self.shapedirs.dtype if global_orient is None: global_orient = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() if body_pose is None: body_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand( batch_size, self.NUM_BODY_JOINTS, -1, -1).contiguous() if betas is None: betas = torch.zeros([batch_size, self.num_betas], dtype=dtype, device=device) if transl is None: transl = torch.zeros([batch_size, 3], dtype=dtype, device=device) full_pose = torch.cat( [global_orient.reshape(-1, 1, 3, 3), body_pose.reshape(-1, self.NUM_BODY_JOINTS, 3, 3)], dim=1) vertices, joints = lbs(betas, full_pose, self.v_template, self.shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=False) joints = self.vertex_joint_selector(vertices, joints) # Map the joints to the current dataset if self.joint_mapper is not None: joints = self.joint_mapper(joints) if transl is not None: joints += transl.unsqueeze(dim=1) vertices += transl.unsqueeze(dim=1) output = SMPLOutput(vertices=vertices if return_verts else None, global_orient=global_orient, body_pose=body_pose, joints=joints, betas=betas, full_pose=full_pose if return_full_pose else None) return output class SMPLHLayer(SMPLH): def __init__( self, *args ) -> None: ''' SMPL+H as a layer model constructor ''' super(SMPLHLayer, self).__init__( create_global_orient=False, create_body_pose=False, create_left_hand_pose=False, create_right_hand_pose=False, create_betas=False, create_transl=False, *args) def forward( self, betas: Optional[Tensor] = None, global_orient: Optional[Tensor] = None, body_pose: Optional[Tensor] = None, left_hand_pose: Optional[Tensor] = None, right_hand_pose: Optional[Tensor] = None, transl: Optional[Tensor] = None, return_verts: bool = True, return_full_pose: bool = False, pose2rot: bool = True ) -> SMPLHOutput: ''' Forward pass for the SMPL+H model Parameters ---------- global_orient: torch.tensor, optional, shape Bx3x3 Global rotation of the body. Useful if someone wishes to predicts this with an external model. It is expected to be in rotation matrix format. (default=None) betas: torch.tensor, optional, shape BxN_b Shape parameters. For example, it can used if shape parameters `betas` are predicted from some external model. (default=None) body_pose: torch.tensor, optional, shape BxJx3x3 If given, ignore the member variable `body_pose` and use it instead. For example, it can used if someone predicts the pose of the body joints are predicted from some external model. It should be a tensor that contains joint rotations in rotation matrix format. (default=None) left_hand_pose: torch.tensor, optional, shape Bx15x3x3 If given, contains the pose of the left hand. It should be a tensor that contains joint rotations in rotation matrix format. (default=None) right_hand_pose: torch.tensor, optional, shape Bx15x3x3 If given, contains the pose of the right hand. It should be a tensor that contains joint rotations in rotation matrix format. (default=None) transl: torch.tensor, optional, shape Bx3 Translation vector of the body. For example, it can used if the translation `transl` is predicted from some external model. (default=None) return_verts: bool, optional Return the vertices. (default=True) return_full_pose: bool, optional Returns the full axis-angle pose vector (default=False) Returns ------- ''' model_vars = [betas, global_orient, body_pose, transl, left_hand_pose, right_hand_pose] batch_size = 1 for var in model_vars: if var is None: continue batch_size = max(batch_size, len(var)) device, dtype = self.shapedirs.device, self.shapedirs.dtype if global_orient is None: global_orient = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() if body_pose is None: body_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, 21, -1, -1).contiguous() if left_hand_pose is None: left_hand_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, 15, -1, -1).contiguous() if right_hand_pose is None: right_hand_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, 15, -1, -1).contiguous() if betas is None: betas = torch.zeros([batch_size, self.num_betas], dtype=dtype, device=device) if transl is None: transl = torch.zeros([batch_size, 3], dtype=dtype, device=device) # Concatenate all pose vectors full_pose = torch.cat( [global_orient.reshape(-1, 1, 3, 3), body_pose.reshape(-1, self.NUM_BODY_JOINTS, 3, 3), left_hand_pose.reshape(-1, self.NUM_HAND_JOINTS, 3, 3), right_hand_pose.reshape(-1, self.NUM_HAND_JOINTS, 3, 3)], dim=1) vertices, joints = lbs(betas, full_pose, self.v_template, self.shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=False) # Add any extra joints that might be needed joints = self.vertex_joint_selector(vertices, joints) if self.joint_mapper is not None: joints = self.joint_mapper(joints) if transl is not None: joints += transl.unsqueeze(dim=1) vertices += transl.unsqueeze(dim=1) output = SMPLHOutput(vertices=vertices if return_verts else None, joints=joints, betas=betas, global_orient=global_orient, body_pose=body_pose, left_hand_pose=left_hand_pose, right_hand_pose=right_hand_pose, full_pose=full_pose if return_full_pose else None) return output class SMPLXLayer(SMPLX): def __init__( self, *args ) -> None: # Just create a SMPLX module without any member variables super(SMPLXLayer, self).__init__( create_global_orient=False, create_body_pose=False, create_left_hand_pose=False, create_right_hand_pose=False, create_jaw_pose=False, create_leye_pose=False, create_reye_pose=False, create_betas=False, create_expression=False, create_transl=False, *args, ) def forward( self, betas: Optional[Tensor] = None, global_orient: Optional[Tensor] = None, body_pose: Optional[Tensor] = None, left_hand_pose: Optional[Tensor] = None, right_hand_pose: Optional[Tensor] = None, transl: Optional[Tensor] = None, expression: Optional[Tensor] = None, jaw_pose: Optional[Tensor] = None, leye_pose: Optional[Tensor] = None, reye_pose: Optional[Tensor] = None, return_verts: bool = True, return_full_pose: bool = False ) -> SMPLXOutput: ''' Forward pass for the SMPLX model Parameters ---------- global_orient: torch.tensor, optional, shape Bx3x3 If given, ignore the member variable and use it as the global rotation of the body. Useful if someone wishes to predicts this with an external model. It is expected to be in rotation matrix format. (default=None) betas: torch.tensor, optional, shape BxN_b If given, ignore the member variable `betas` and use it instead. For example, it can used if shape parameters `betas` are predicted from some external model. (default=None) expression: torch.tensor, optional, shape BxN_e Expression coefficients. For example, it can used if expression parameters `expression` are predicted from some external model. body_pose: torch.tensor, optional, shape BxJx3x3 If given, ignore the member variable `body_pose` and use it instead. For example, it can used if someone predicts the pose of the body joints are predicted from some external model. It should be a tensor that contains joint rotations in rotation matrix format. (default=None) left_hand_pose: torch.tensor, optional, shape Bx15x3x3 If given, contains the pose of the left hand. It should be a tensor that contains joint rotations in rotation matrix format. (default=None) right_hand_pose: torch.tensor, optional, shape Bx15x3x3 If given, contains the pose of the right hand. It should be a tensor that contains joint rotations in rotation matrix format. (default=None) jaw_pose: torch.tensor, optional, shape Bx3x3 Jaw pose. It should either joint rotations in rotation matrix format. transl: torch.tensor, optional, shape Bx3 Translation vector of the body. For example, it can used if the translation `transl` is predicted from some external model. (default=None) return_verts: bool, optional Return the vertices. (default=True) return_full_pose: bool, optional Returns the full pose vector (default=False) Returns ------- output: ModelOutput A data class that contains the posed vertices and joints ''' device, dtype = self.shapedirs.device, self.shapedirs.dtype model_vars = [betas, global_orient, body_pose, transl, expression, left_hand_pose, right_hand_pose, jaw_pose] batch_size = 1 for var in model_vars: if var is None: continue batch_size = max(batch_size, len(var)) if global_orient is None: global_orient = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() if body_pose is None: body_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand( batch_size, self.NUM_BODY_JOINTS, -1, -1).contiguous() if left_hand_pose is None: left_hand_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, 15, -1, -1).contiguous() if right_hand_pose is None: right_hand_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, 15, -1, -1).contiguous() if jaw_pose is None: jaw_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() if leye_pose is None: leye_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() if reye_pose is None: reye_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() if expression is None: expression = torch.zeros([batch_size, self.num_expression_coeffs], dtype=dtype, device=device) if betas is None: betas = torch.zeros([batch_size, self.num_betas], dtype=dtype, device=device) if transl is None: transl = torch.zeros([batch_size, 3], dtype=dtype, device=device) # Concatenate all pose vectors full_pose = torch.cat( [global_orient.reshape(-1, 1, 3, 3), body_pose.reshape(-1, self.NUM_BODY_JOINTS, 3, 3), jaw_pose.reshape(-1, 1, 3, 3), leye_pose.reshape(-1, 1, 3, 3), reye_pose.reshape(-1, 1, 3, 3), left_hand_pose.reshape(-1, self.NUM_HAND_JOINTS, 3, 3), right_hand_pose.reshape(-1, self.NUM_HAND_JOINTS, 3, 3)], dim=1) shape_components = torch.cat([betas, expression], dim=-1) shapedirs = torch.cat([self.shapedirs, self.expr_dirs], dim=-1) vertices, joints = lbs(shape_components, full_pose, self.v_template, shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=False) lmk_faces_idx = self.lmk_faces_idx.unsqueeze( dim=0).expand(batch_size, -1).contiguous() lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat( batch_size, 1, 1) if self.use_face_contour: lmk_idx_and_bcoords = find_dynamic_lmk_idx_and_bcoords( vertices, full_pose, self.dynamic_lmk_faces_idx, self.dynamic_lmk_bary_coords, self.neck_kin_chain, pose2rot=False, ) dyn_lmk_faces_idx, dyn_lmk_bary_coords = lmk_idx_and_bcoords lmk_faces_idx = torch.cat([lmk_faces_idx, dyn_lmk_faces_idx], 1) lmk_bary_coords = torch.cat( [lmk_bary_coords.expand(batch_size, -1, -1), dyn_lmk_bary_coords], 1) landmarks = vertices2landmarks(vertices, self.faces_tensor, lmk_faces_idx, lmk_bary_coords) # Add any extra joints that might be needed joints = self.vertex_joint_selector(vertices, joints) # Add the landmarks to the joints joints = torch.cat([joints, landmarks], dim=1) # Map the joints to the current dataset if self.joint_mapper is not None: joints = self.joint_mapper(joints=joints, vertices=vertices) if transl is not None: joints += transl.unsqueeze(dim=1) vertices += transl.unsqueeze(dim=1) output = SMPLXOutput(vertices=vertices if return_verts else None, joints=joints, betas=betas, expression=expression, global_orient=global_orient, body_pose=body_pose, left_hand_pose=left_hand_pose, right_hand_pose=right_hand_pose, jaw_pose=jaw_pose, transl=transl, full_pose=full_pose if return_full_pose else None) return output class MANOLayer(MANO): def __init__(self, *args) -> None: ''' MANO as a layer model constructor ''' super(MANOLayer, self).__init__( create_global_orient=False, create_hand_pose=False, create_betas=False, create_transl=False, *args) def name(self) -> str: return 'MANO' def forward( self, betas: Optional[Tensor] = None, global_orient: Optional[Tensor] = None, hand_pose: Optional[Tensor] = None, transl: Optional[Tensor] = None, return_verts: bool = True, return_full_pose: bool = False ) -> MANOOutput: ''' Forward pass for the MANO model ''' device, dtype = self.shapedirs.device, self.shapedirs.dtype if global_orient is None: batch_size = 1 global_orient = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() else: batch_size = global_orient.shape[0] if hand_pose is None: hand_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, 15, -1, -1).contiguous() if betas is None: betas = torch.zeros( [batch_size, self.num_betas], dtype=dtype, device=device) if transl is None: transl = torch.zeros([batch_size, 3], dtype=dtype, device=device) full_pose = torch.cat([global_orient, hand_pose], dim=1) vertices, joints = lbs(betas, full_pose, self.v_template, self.shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=False) if self.joint_mapper is not None: joints = self.joint_mapper(joints) if transl is not None: joints = joints + transl.unsqueeze(dim=1) vertices = vertices + transl.unsqueeze(dim=1) output = MANOOutput( vertices=vertices if return_verts else None, joints=joints if return_verts else None, betas=betas, global_orient=global_orient, hand_pose=hand_pose, full_pose=full_pose if return_full_pose else None) return output class FLAMELayer(FLAME): def __init__(self, *args) -> None: ''' FLAME as a layer model constructor ''' super(FLAMELayer, self).__init__( create_betas=False, create_expression=False, create_global_orient=False, create_neck_pose=False, create_jaw_pose=False, create_leye_pose=False, create_reye_pose=False, *args) def forward( self, betas: Optional[Tensor] = None, global_orient: Optional[Tensor] = None, neck_pose: Optional[Tensor] = None, transl: Optional[Tensor] = None, expression: Optional[Tensor] = None, jaw_pose: Optional[Tensor] = None, leye_pose: Optional[Tensor] = None, reye_pose: Optional[Tensor] = None, return_verts: bool = True, return_full_pose: bool = False, pose2rot: bool = True ) -> FLAMEOutput: ''' Forward pass for the SMPLX model Parameters ---------- global_orient: torch.tensor, optional, shape Bx3x3 Global rotation of the body. Useful if someone wishes to predicts this with an external model. It is expected to be in rotation matrix format. (default=None) betas: torch.tensor, optional, shape BxN_b Shape parameters. For example, it can used if shape parameters `betas` are predicted from some external model. (default=None) expression: torch.tensor, optional, shape BxN_e If given, ignore the member variable `expression` and use it instead. For example, it can used if expression parameters `expression` are predicted from some external model. jaw_pose: torch.tensor, optional, shape Bx3x3 Jaw pose. It should either joint rotations in rotation matrix format. transl: torch.tensor, optional, shape Bx3 Translation vector of the body. For example, it can used if the translation `transl` is predicted from some external model. (default=None) return_verts: bool, optional Return the vertices. (default=True) return_full_pose: bool, optional Returns the full axis-angle pose vector (default=False) Returns ------- output: ModelOutput A named tuple of type `ModelOutput` ''' device, dtype = self.shapedirs.device, self.shapedirs.dtype if global_orient is None: batch_size = 1 global_orient = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() else: batch_size = global_orient.shape[0] if neck_pose is None: neck_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, 1, -1, -1).contiguous() if jaw_pose is None: jaw_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() if leye_pose is None: leye_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() if reye_pose is None: reye_pose = torch.eye(3, device=device, dtype=dtype).view( 1, 1, 3, 3).expand(batch_size, -1, -1, -1).contiguous() if betas is None: betas = torch.zeros([batch_size, self.num_betas], dtype=dtype, device=device) if expression is None: expression = torch.zeros([batch_size, self.num_expression_coeffs], dtype=dtype, device=device) if transl is None: transl = torch.zeros([batch_size, 3], dtype=dtype, device=device) full_pose = torch.cat( [global_orient, neck_pose, jaw_pose, leye_pose, reye_pose], dim=1) shape_components = torch.cat([betas, expression], dim=-1) shapedirs = torch.cat([self.shapedirs, self.expr_dirs], dim=-1) vertices, joints = lbs(shape_components, full_pose, self.v_template, shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=False, ) lmk_faces_idx = self.lmk_faces_idx.unsqueeze( dim=0).expand(batch_size, -1).contiguous() lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat( self.batch_size, 1, 1) if self.use_face_contour: lmk_idx_and_bcoords = find_dynamic_lmk_idx_and_bcoords( vertices, full_pose, self.dynamic_lmk_faces_idx, self.dynamic_lmk_bary_coords, self.neck_kin_chain, pose2rot=False, ) dyn_lmk_faces_idx, dyn_lmk_bary_coords = lmk_idx_and_bcoords lmk_faces_idx = torch.cat([lmk_faces_idx, dyn_lmk_faces_idx], 1) lmk_bary_coords = torch.cat( [lmk_bary_coords.expand(batch_size, -1, -1), dyn_lmk_bary_coords], 1) landmarks = vertices2landmarks(vertices, self.faces_tensor, lmk_faces_idx, lmk_bary_coords) # Add any extra joints that might be needed joints = self.vertex_joint_selector(vertices, joints) # Add the landmarks to the joints joints = torch.cat([joints, landmarks], dim=1) # Map the joints to the current dataset if self.joint_mapper is not None: joints = self.joint_mapper(joints=joints, vertices=vertices) joints += transl.unsqueeze(dim=1) vertices += transl.unsqueeze(dim=1) output = FLAMEOutput(vertices=vertices if return_verts else None, joints=joints, betas=betas, expression=expression, global_orient=global_orient, neck_pose=neck_pose, jaw_pose=jaw_pose, full_pose=full_pose if return_full_pose else None) return output The provided code snippet includes necessary dependencies for implementing the `build_layer` function. Write a Python function `def build_layer( model_path: str, model_type: str = 'smpl' ) -> Union[SMPLLayer, SMPLHLayer, SMPLXLayer, MANOLayer, FLAMELayer]` to solve the following problem: Method for creating a model from a path and a model type Parameters ---------- model_path: str Either the path to the model you wish to load or a folder, where each subfolder contains the differents types, i.e.: model_path: | |-- smpl |-- SMPL_FEMALE |-- SMPL_NEUTRAL |-- SMPL_MALE |-- smplh |-- SMPLH_FEMALE |-- SMPLH_MALE |-- smplx |-- SMPLX_FEMALE |-- SMPLX_NEUTRAL |-- SMPLX_MALE |-- mano |-- MANO RIGHT |-- MANO LEFT |-- flame |-- FLAME_FEMALE |-- FLAME_MALE |-- FLAME_NEUTRAL model_type: str, optional When model_path is a folder, then this parameter specifies the type of model to be loaded **kwargs: dict Keyword arguments Returns ------- body_model: nn.Module The PyTorch module that implements the corresponding body model Raises ------ ValueError: In case the model type is not one of SMPL, SMPLH, SMPLX, MANO or FLAME Here is the function: def build_layer( model_path: str, model_type: str = 'smpl' ) -> Union[SMPLLayer, SMPLHLayer, SMPLXLayer, MANOLayer, FLAMELayer]: ''' Method for creating a model from a path and a model type Parameters ---------- model_path: str Either the path to the model you wish to load or a folder, where each subfolder contains the differents types, i.e.: model_path: | |-- smpl |-- SMPL_FEMALE |-- SMPL_NEUTRAL |-- SMPL_MALE |-- smplh |-- SMPLH_FEMALE |-- SMPLH_MALE |-- smplx |-- SMPLX_FEMALE |-- SMPLX_NEUTRAL |-- SMPLX_MALE |-- mano |-- MANO RIGHT |-- MANO LEFT |-- flame |-- FLAME_FEMALE |-- FLAME_MALE |-- FLAME_NEUTRAL model_type: str, optional When model_path is a folder, then this parameter specifies the type of model to be loaded **kwargs: dict Keyword arguments Returns ------- body_model: nn.Module The PyTorch module that implements the corresponding body model Raises ------ ValueError: In case the model type is not one of SMPL, SMPLH, SMPLX, MANO or FLAME ''' if osp.isdir(model_path): model_path = os.path.join(model_path, model_type) else: model_type = osp.basename(model_path).split('_')[0].lower() if model_type.lower() == 'smpl': return SMPLLayer(model_path) elif model_type.lower() == 'smplh': return SMPLHLayer(model_path) elif model_type.lower() == 'smplx': return SMPLXLayer(model_path) elif 'mano' in model_type.lower(): return MANOLayer(model_path) elif 'flame' in model_type.lower(): return FLAMELayer(model_path) else: raise ValueError(f'Unknown model type {model_type}, exiting!')
Method for creating a model from a path and a model type Parameters ---------- model_path: str Either the path to the model you wish to load or a folder, where each subfolder contains the differents types, i.e.: model_path: | |-- smpl |-- SMPL_FEMALE |-- SMPL_NEUTRAL |-- SMPL_MALE |-- smplh |-- SMPLH_FEMALE |-- SMPLH_MALE |-- smplx |-- SMPLX_FEMALE |-- SMPLX_NEUTRAL |-- SMPLX_MALE |-- mano |-- MANO RIGHT |-- MANO LEFT |-- flame |-- FLAME_FEMALE |-- FLAME_MALE |-- FLAME_NEUTRAL model_type: str, optional When model_path is a folder, then this parameter specifies the type of model to be loaded **kwargs: dict Keyword arguments Returns ------- body_model: nn.Module The PyTorch module that implements the corresponding body model Raises ------ ValueError: In case the model type is not one of SMPL, SMPLH, SMPLX, MANO or FLAME
350
from typing import Optional, Dict, Union import os import os.path as osp import pickle import numpy as np import torch import torch.nn as nn from .lbs import ( lbs, vertices2landmarks, find_dynamic_lmk_idx_and_bcoords, vertices2joints, blend_shapes) from .vertex_ids import vertex_ids as VERTEX_IDS from .utils import ( Struct, to_np, to_tensor, Tensor, Array, SMPLOutput, SMPLHOutput, SMPLXOutput, MANOOutput, FLAMEOutput, find_joint_kin_chain) from .vertex_joint_selector import VertexJointSelector class SMPL(nn.Module): NUM_JOINTS = 23 NUM_BODY_JOINTS = 23 SHAPE_SPACE_DIM = 300 def __init__( self, model_path: str, data_struct: Optional[Struct] = None, create_betas: bool = True, betas: Optional[Tensor] = None, num_betas: int = 10, create_global_orient: bool = True, global_orient: Optional[Tensor] = None, create_body_pose: bool = True, body_pose: Optional[Tensor] = None, create_transl: bool = True, transl: Optional[Tensor] = None, dtype=torch.float32, batch_size: int = 1, joint_mapper=None, gender: str = 'neutral', vertex_ids: Dict[str, int] = None, v_template: Optional[Union[Tensor, Array]] = None ) -> None: ''' SMPL model constructor Parameters ---------- model_path: str The path to the folder or to the file where the model parameters are stored data_struct: Strct A struct object. If given, then the parameters of the model are read from the object. Otherwise, the model tries to read the parameters from the given `model_path`. (default = None) create_global_orient: bool, optional Flag for creating a member variable for the global orientation of the body. (default = True) global_orient: torch.tensor, optional, Bx3 The default value for the global orientation variable. (default = None) create_body_pose: bool, optional Flag for creating a member variable for the pose of the body. (default = True) body_pose: torch.tensor, optional, Bx(Body Joints * 3) The default value for the body pose variable. (default = None) num_betas: int, optional Number of shape components to use (default = 10). create_betas: bool, optional Flag for creating a member variable for the shape space (default = True). betas: torch.tensor, optional, Bx10 The default value for the shape member variable. (default = None) create_transl: bool, optional Flag for creating a member variable for the translation of the body. (default = True) transl: torch.tensor, optional, Bx3 The default value for the transl variable. (default = None) dtype: torch.dtype, optional The data type for the created variables batch_size: int, optional The batch size used for creating the member variables joint_mapper: object, optional An object that re-maps the joints. Useful if one wants to re-order the SMPL joints to some other convention (e.g. MSCOCO) (default = None) gender: str, optional Which gender to load vertex_ids: dict, optional A dictionary containing the indices of the extra vertices that will be selected ''' self.gender = gender if data_struct is None: if osp.isdir(model_path): model_fn = 'SMPL_{}.{ext}'.format(gender.upper(), ext='pkl') smpl_path = os.path.join(model_path, model_fn) else: smpl_path = model_path assert osp.exists(smpl_path), 'Path {} does not exist!'.format( smpl_path) with open(smpl_path, 'rb') as smpl_file: data_struct = Struct(**pickle.load(smpl_file, encoding='latin1')) super(SMPL, self).__init__() self.batch_size = batch_size shapedirs = data_struct.shapedirs if (shapedirs.shape[-1] < self.SHAPE_SPACE_DIM): print(f'WARNING: You are using a {self.name()} model, with only' ' 10 shape coefficients.') num_betas = min(num_betas, 10) else: num_betas = min(num_betas, self.SHAPE_SPACE_DIM) self._num_betas = num_betas shapedirs = shapedirs[:, :, :num_betas] # The shape components self.register_buffer( 'shapedirs', to_tensor(to_np(shapedirs), dtype=dtype)) if vertex_ids is None: # SMPL and SMPL-H share the same topology, so any extra joints can # be drawn from the same place vertex_ids = VERTEX_IDS['smplh'] self.dtype = dtype self.joint_mapper = joint_mapper self.vertex_joint_selector = VertexJointSelector( vertex_ids=vertex_ids) self.faces = data_struct.f self.register_buffer('faces_tensor', to_tensor(to_np(self.faces, dtype=np.int64), dtype=torch.long)) if create_betas: if betas is None: default_betas = torch.zeros( [batch_size, self.num_betas], dtype=dtype) else: if torch.is_tensor(betas): default_betas = betas.clone().detach() else: default_betas = torch.tensor(betas, dtype=dtype) self.register_parameter( 'betas', nn.Parameter(default_betas, requires_grad=True)) # The tensor that contains the global rotation of the model # It is separated from the pose of the joints in case we wish to # optimize only over one of them if create_global_orient: if global_orient is None: default_global_orient = torch.zeros( [batch_size, 3], dtype=dtype) else: if torch.is_tensor(global_orient): default_global_orient = global_orient.clone().detach() else: default_global_orient = torch.tensor( global_orient, dtype=dtype) global_orient = nn.Parameter(default_global_orient, requires_grad=True) self.register_parameter('global_orient', global_orient) if create_body_pose: if body_pose is None: default_body_pose = torch.zeros( [batch_size, self.NUM_BODY_JOINTS * 3], dtype=dtype) else: if torch.is_tensor(body_pose): default_body_pose = body_pose.clone().detach() else: default_body_pose = torch.tensor(body_pose, dtype=dtype) self.register_parameter( 'body_pose', nn.Parameter(default_body_pose, requires_grad=True)) if create_transl: if transl is None: default_transl = torch.zeros([batch_size, 3], dtype=dtype, requires_grad=True) else: default_transl = torch.tensor(transl, dtype=dtype) self.register_parameter( 'transl', nn.Parameter(default_transl, requires_grad=True)) if v_template is None: v_template = data_struct.v_template if not torch.is_tensor(v_template): v_template = to_tensor(to_np(v_template), dtype=dtype) # The vertices of the template model self.register_buffer('v_template', v_template) j_regressor = to_tensor(to_np( data_struct.J_regressor), dtype=dtype) self.register_buffer('J_regressor', j_regressor) # Pose blend shape basis: 6890 x 3 x 207, reshaped to 6890*3 x 207 num_pose_basis = data_struct.posedirs.shape[-1] # 207 x 20670 posedirs = np.reshape(data_struct.posedirs, [-1, num_pose_basis]).T self.register_buffer('posedirs', to_tensor(to_np(posedirs), dtype=dtype)) # indices of parents for each joints parents = to_tensor(to_np(data_struct.kintree_table[0])).long() parents[0] = -1 self.register_buffer('parents', parents) self.register_buffer( 'lbs_weights', to_tensor(to_np(data_struct.weights), dtype=dtype)) def num_betas(self): return self._num_betas def num_expression_coeffs(self): return 0 def create_mean_pose(self, data_struct) -> Tensor: pass def name(self) -> str: return 'SMPL' def reset_params(self, **params_dict) -> None: for param_name, param in self.named_parameters(): if param_name in params_dict: param[:] = torch.tensor(params_dict[param_name]) else: param.fill_(0) def get_num_verts(self) -> int: return self.v_template.shape[0] def get_num_faces(self) -> int: return self.faces.shape[0] def get_T_hip(self, betas=None, displacement=None): if displacement is not None: v_shaped = self.v_template+displacement + blend_shapes(betas, self.shapedirs) else: v_shaped = self.v_template + blend_shapes(betas, self.shapedirs) J = vertices2joints(self.J_regressor, v_shaped) T_hip = J[0,0] return T_hip def extra_repr(self) -> str: msg = [ f'Gender: {self.gender.upper()}', f'Number of joints: {self.J_regressor.shape[0]}', f'Betas: {self.num_betas}', ] return '\n'.join(msg) def forward( self, betas: Optional[Tensor] = None, body_pose: Optional[Tensor] = None, global_orient: Optional[Tensor] = None, transl: Optional[Tensor] = None, return_verts=True, return_full_pose: bool = False, pose2rot: bool = True, displacement=None, absolute_displacement=True, ) -> SMPLOutput: ''' Forward pass for the SMPL model Parameters ---------- global_orient: torch.tensor, optional, shape Bx3 If given, ignore the member variable and use it as the global rotation of the body. Useful if someone wishes to predicts this with an external model. (default=None) betas: torch.tensor, optional, shape BxN_b If given, ignore the member variable `betas` and use it instead. For example, it can used if shape parameters `betas` are predicted from some external model. (default=None) body_pose: torch.tensor, optional, shape Bx(J*3) If given, ignore the member variable `body_pose` and use it instead. For example, it can used if someone predicts the pose of the body joints are predicted from some external model. It should be a tensor that contains joint rotations in axis-angle format. (default=None) transl: torch.tensor, optional, shape Bx3 If given, ignore the member variable `transl` and use it instead. For example, it can used if the translation `transl` is predicted from some external model. (default=None) return_verts: bool, optional Return the vertices. (default=True) return_full_pose: bool, optional Returns the full axis-angle pose vector (default=False) Returns ------- ''' # If no shape and pose parameters are passed along, then use the # ones from the module global_orient = (global_orient if global_orient is not None else self.global_orient) body_pose = body_pose if body_pose is not None else self.body_pose betas = betas if betas is not None else self.betas apply_trans = transl is not None or hasattr(self, 'transl') if transl is None and hasattr(self, 'transl'): transl = self.transl full_pose = torch.cat([global_orient, body_pose], dim=1) batch_size = max(betas.shape[0], global_orient.shape[0], body_pose.shape[0]) if betas.shape[0] != batch_size: num_repeats = int(batch_size / betas.shape[0]) betas = betas.expand(num_repeats, -1) if displacement is not None: if absolute_displacement: vertices, joints = lbs(betas, full_pose, displacement, self.shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=pose2rot) else: vertices, joints = lbs(betas, full_pose, self.v_template+displacement, self.shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=pose2rot) else: vertices, joints = lbs(betas, full_pose, self.v_template, self.shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=pose2rot) joints = self.vertex_joint_selector(vertices, joints) # Map the joints to the current dataset if self.joint_mapper is not None: joints = self.joint_mapper(joints) if apply_trans: joints += transl.unsqueeze(dim=1) vertices += transl.unsqueeze(dim=1) output = SMPLOutput(vertices=vertices if return_verts else None, faces=self.faces, global_orient=global_orient, body_pose=body_pose, joints=joints, betas=betas, full_pose=full_pose if return_full_pose else None) return output class SMPLH(SMPL): # The hand joints are replaced by MANO NUM_BODY_JOINTS = SMPL.NUM_JOINTS - 2 NUM_HAND_JOINTS = 15 NUM_JOINTS = NUM_BODY_JOINTS + 2 * NUM_HAND_JOINTS def __init__( self, model_path, data_struct: Optional[Struct] = None, create_left_hand_pose: bool = True, left_hand_pose: Optional[Tensor] = None, create_right_hand_pose: bool = True, right_hand_pose: Optional[Tensor] = None, use_pca: bool = True, num_pca_comps: int = 6, flat_hand_mean: bool = False, batch_size: int = 1, gender: str = 'neutral', dtype=torch.float32, vertex_ids=None, use_compressed: bool = True, ext: str = 'pkl' ) -> None: ''' SMPLH model constructor Parameters ---------- model_path: str The path to the folder or to the file where the model parameters are stored data_struct: Strct A struct object. If given, then the parameters of the model are read from the object. Otherwise, the model tries to read the parameters from the given `model_path`. (default = None) create_left_hand_pose: bool, optional Flag for creating a member variable for the pose of the left hand. (default = True) left_hand_pose: torch.tensor, optional, BxP The default value for the left hand pose member variable. (default = None) create_right_hand_pose: bool, optional Flag for creating a member variable for the pose of the right hand. (default = True) right_hand_pose: torch.tensor, optional, BxP The default value for the right hand pose member variable. (default = None) num_pca_comps: int, optional The number of PCA components to use for each hand. (default = 6) flat_hand_mean: bool, optional If False, then the pose of the hand is initialized to False. batch_size: int, optional The batch size used for creating the member variables gender: str, optional Which gender to load dtype: torch.dtype, optional The data type for the created variables vertex_ids: dict, optional A dictionary containing the indices of the extra vertices that will be selected ''' self.num_pca_comps = num_pca_comps # If no data structure is passed, then load the data from the given # model folder if data_struct is None: # Load the model if osp.isdir(model_path): model_fn = 'SMPLH_{}.{ext}'.format(gender.upper(), ext=ext) smplh_path = os.path.join(model_path, model_fn) else: smplh_path = model_path assert osp.exists(smplh_path), 'Path {} does not exist!'.format( smplh_path) if ext == 'pkl': with open(smplh_path, 'rb') as smplh_file: model_data = pickle.load(smplh_file, encoding='latin1') elif ext == 'npz': model_data = np.load(smplh_path, allow_pickle=True) else: raise ValueError('Unknown extension: {}'.format(ext)) data_struct = Struct(**model_data) if vertex_ids is None: vertex_ids = VERTEX_IDS['smplh'] super(SMPLH, self).__init__( model_path=model_path, data_struct=data_struct, batch_size=batch_size, vertex_ids=vertex_ids, gender=gender, use_compressed=use_compressed, dtype=dtype, ext=ext) self.use_pca = use_pca self.num_pca_comps = num_pca_comps self.flat_hand_mean = flat_hand_mean left_hand_components = data_struct.hands_componentsl[:num_pca_comps] right_hand_components = data_struct.hands_componentsr[:num_pca_comps] self.np_left_hand_components = left_hand_components self.np_right_hand_components = right_hand_components if self.use_pca: self.register_buffer( 'left_hand_components', torch.tensor(left_hand_components, dtype=dtype)) self.register_buffer( 'right_hand_components', torch.tensor(right_hand_components, dtype=dtype)) if self.flat_hand_mean: left_hand_mean = np.zeros_like(data_struct.hands_meanl) else: left_hand_mean = data_struct.hands_meanl if self.flat_hand_mean: right_hand_mean = np.zeros_like(data_struct.hands_meanr) else: right_hand_mean = data_struct.hands_meanr self.register_buffer('left_hand_mean', to_tensor(left_hand_mean, dtype=self.dtype)) self.register_buffer('right_hand_mean', to_tensor(right_hand_mean, dtype=self.dtype)) # Create the buffers for the pose of the left hand hand_pose_dim = num_pca_comps if use_pca else 3 * self.NUM_HAND_JOINTS if create_left_hand_pose: if left_hand_pose is None: default_lhand_pose = torch.zeros([batch_size, hand_pose_dim], dtype=dtype) else: default_lhand_pose = torch.tensor(left_hand_pose, dtype=dtype) left_hand_pose_param = nn.Parameter(default_lhand_pose, requires_grad=True) self.register_parameter('left_hand_pose', left_hand_pose_param) if create_right_hand_pose: if right_hand_pose is None: default_rhand_pose = torch.zeros([batch_size, hand_pose_dim], dtype=dtype) else: default_rhand_pose = torch.tensor(right_hand_pose, dtype=dtype) right_hand_pose_param = nn.Parameter(default_rhand_pose, requires_grad=True) self.register_parameter('right_hand_pose', right_hand_pose_param) # Create the buffer for the mean pose. pose_mean_tensor = self.create_mean_pose( data_struct, flat_hand_mean=flat_hand_mean) if not torch.is_tensor(pose_mean_tensor): pose_mean_tensor = torch.tensor(pose_mean_tensor, dtype=dtype) self.register_buffer('pose_mean', pose_mean_tensor) def create_mean_pose(self, data_struct, flat_hand_mean=False): # Create the array for the mean pose. If flat_hand is false, then use # the mean that is given by the data, rather than the flat open hand global_orient_mean = torch.zeros([3], dtype=self.dtype) body_pose_mean = torch.zeros([self.NUM_BODY_JOINTS * 3], dtype=self.dtype) pose_mean = torch.cat([global_orient_mean, body_pose_mean, self.left_hand_mean, self.right_hand_mean], dim=0) return pose_mean def name(self) -> str: return 'SMPL+H' def extra_repr(self): msg = super(SMPLH, self).extra_repr() msg = [msg] if self.use_pca: msg.append(f'Number of PCA components: {self.num_pca_comps}') msg.append(f'Flat hand mean: {self.flat_hand_mean}') return '\n'.join(msg) def forward( self, betas: Optional[Tensor] = None, global_orient: Optional[Tensor] = None, body_pose: Optional[Tensor] = None, left_hand_pose: Optional[Tensor] = None, right_hand_pose: Optional[Tensor] = None, transl: Optional[Tensor] = None, return_verts: bool = True, return_full_pose: bool = False, pose2rot: bool = True ) -> SMPLHOutput: ''' ''' # If no shape and pose parameters are passed along, then use the # ones from the module global_orient = (global_orient if global_orient is not None else self.global_orient) body_pose = body_pose if body_pose is not None else self.body_pose betas = betas if betas is not None else self.betas left_hand_pose = (left_hand_pose if left_hand_pose is not None else self.left_hand_pose) right_hand_pose = (right_hand_pose if right_hand_pose is not None else self.right_hand_pose) apply_trans = transl is not None or hasattr(self, 'transl') if transl is None: if hasattr(self, 'transl'): transl = self.transl if self.use_pca: left_hand_pose = torch.einsum( 'bi,ij->bj', [left_hand_pose, self.left_hand_components]) right_hand_pose = torch.einsum( 'bi,ij->bj', [right_hand_pose, self.right_hand_components]) full_pose = torch.cat([global_orient, body_pose, left_hand_pose, right_hand_pose], dim=1) full_pose += self.pose_mean vertices, joints = lbs(betas, full_pose, self.v_template, self.shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=pose2rot) # Add any extra joints that might be needed joints = self.vertex_joint_selector(vertices, joints) if self.joint_mapper is not None: joints = self.joint_mapper(joints) if apply_trans: joints += transl.unsqueeze(dim=1) vertices += transl.unsqueeze(dim=1) output = SMPLHOutput(vertices=vertices if return_verts else None, faces=self.faces, joints=joints, betas=betas, global_orient=global_orient, body_pose=body_pose, left_hand_pose=left_hand_pose, right_hand_pose=right_hand_pose, full_pose=full_pose if return_full_pose else None) return output class SMPLX(SMPLH): ''' SMPL-X (SMPL eXpressive) is a unified body model, with shape parameters trained jointly for the face, hands and body. SMPL-X uses standard vertex based linear blend skinning with learned corrective blend shapes, has N=10475 vertices and K=54 joints, which includes joints for the neck, jaw, eyeballs and fingers. ''' NUM_BODY_JOINTS = SMPLH.NUM_BODY_JOINTS NUM_HAND_JOINTS = 15 NUM_FACE_JOINTS = 3 NUM_JOINTS = NUM_BODY_JOINTS + 2 * NUM_HAND_JOINTS + NUM_FACE_JOINTS EXPRESSION_SPACE_DIM = 100 NECK_IDX = 12 def __init__( self, model_path: str, num_expression_coeffs: int = 10, create_expression: bool = True, expression: Optional[Tensor] = None, create_jaw_pose: bool = True, jaw_pose: Optional[Tensor] = None, create_leye_pose: bool = True, leye_pose: Optional[Tensor] = None, create_reye_pose=True, reye_pose: Optional[Tensor] = None, use_face_contour: bool = False, batch_size: int = 1, gender: str = 'neutral', dtype=torch.float32, ext: str = 'npz' ) -> None: ''' SMPLX model constructor Parameters ---------- model_path: str The path to the folder or to the file where the model parameters are stored num_expression_coeffs: int, optional Number of expression components to use (default = 10). create_expression: bool, optional Flag for creating a member variable for the expression space (default = True). expression: torch.tensor, optional, Bx10 The default value for the expression member variable. (default = None) create_jaw_pose: bool, optional Flag for creating a member variable for the jaw pose. (default = False) jaw_pose: torch.tensor, optional, Bx3 The default value for the jaw pose variable. (default = None) create_leye_pose: bool, optional Flag for creating a member variable for the left eye pose. (default = False) leye_pose: torch.tensor, optional, Bx10 The default value for the left eye pose variable. (default = None) create_reye_pose: bool, optional Flag for creating a member variable for the right eye pose. (default = False) reye_pose: torch.tensor, optional, Bx10 The default value for the right eye pose variable. (default = None) use_face_contour: bool, optional Whether to compute the keypoints that form the facial contour batch_size: int, optional The batch size used for creating the member variables gender: str, optional Which gender to load dtype: torch.dtype The data type for the created variables ''' # Load the model if osp.isdir(model_path): model_fn = 'SMPLX_{}.{ext}'.format(gender.upper(), ext=ext) smplx_path = os.path.join(model_path, model_fn) else: smplx_path = model_path assert osp.exists(smplx_path), 'Path {} does not exist!'.format( smplx_path) if ext == 'pkl': with open(smplx_path, 'rb') as smplx_file: model_data = pickle.load(smplx_file, encoding='latin1') elif ext == 'npz': model_data = np.load(smplx_path, allow_pickle=True) else: raise ValueError('Unknown extension: {}'.format(ext)) data_struct = Struct(**model_data) super(SMPLX, self).__init__( model_path=model_path, data_struct=data_struct, dtype=dtype, batch_size=batch_size, vertex_ids=VERTEX_IDS['smplx'], gender=gender, ext=ext ) lmk_faces_idx = data_struct.lmk_faces_idx self.register_buffer('lmk_faces_idx', torch.tensor(lmk_faces_idx, dtype=torch.long)) lmk_bary_coords = data_struct.lmk_bary_coords self.register_buffer('lmk_bary_coords', torch.tensor(lmk_bary_coords, dtype=dtype)) self.use_face_contour = use_face_contour if self.use_face_contour: dynamic_lmk_faces_idx = data_struct.dynamic_lmk_faces_idx dynamic_lmk_faces_idx = torch.tensor( dynamic_lmk_faces_idx, dtype=torch.long) self.register_buffer('dynamic_lmk_faces_idx', dynamic_lmk_faces_idx) dynamic_lmk_bary_coords = data_struct.dynamic_lmk_bary_coords dynamic_lmk_bary_coords = torch.tensor( dynamic_lmk_bary_coords, dtype=dtype) self.register_buffer('dynamic_lmk_bary_coords', dynamic_lmk_bary_coords) neck_kin_chain = find_joint_kin_chain(self.NECK_IDX, self.parents) self.register_buffer( 'neck_kin_chain', torch.tensor(neck_kin_chain, dtype=torch.long)) if create_jaw_pose: if jaw_pose is None: default_jaw_pose = torch.zeros([batch_size, 3], dtype=dtype) else: default_jaw_pose = torch.tensor(jaw_pose, dtype=dtype) jaw_pose_param = nn.Parameter(default_jaw_pose, requires_grad=True) self.register_parameter('jaw_pose', jaw_pose_param) if create_leye_pose: if leye_pose is None: default_leye_pose = torch.zeros([batch_size, 3], dtype=dtype) else: default_leye_pose = torch.tensor(leye_pose, dtype=dtype) leye_pose_param = nn.Parameter(default_leye_pose, requires_grad=True) self.register_parameter('leye_pose', leye_pose_param) if create_reye_pose: if reye_pose is None: default_reye_pose = torch.zeros([batch_size, 3], dtype=dtype) else: default_reye_pose = torch.tensor(reye_pose, dtype=dtype) reye_pose_param = nn.Parameter(default_reye_pose, requires_grad=True) self.register_parameter('reye_pose', reye_pose_param) shapedirs = data_struct.shapedirs if len(shapedirs.shape) < 3: shapedirs = shapedirs[:, :, None] if (shapedirs.shape[-1] < self.SHAPE_SPACE_DIM + self.EXPRESSION_SPACE_DIM): print(f'WARNING: You are using a {self.name()} model, with only' ' 10 shape and 10 expression coefficients.') expr_start_idx = 10 expr_end_idx = 20 num_expression_coeffs = min(num_expression_coeffs, 10) else: expr_start_idx = self.SHAPE_SPACE_DIM expr_end_idx = self.SHAPE_SPACE_DIM + num_expression_coeffs num_expression_coeffs = min( num_expression_coeffs, self.EXPRESSION_SPACE_DIM) self._num_expression_coeffs = num_expression_coeffs expr_dirs = shapedirs[:, :, expr_start_idx:expr_end_idx] self.register_buffer( 'expr_dirs', to_tensor(to_np(expr_dirs), dtype=dtype)) if create_expression: if expression is None: default_expression = torch.zeros( [batch_size, self.num_expression_coeffs], dtype=dtype) else: default_expression = torch.tensor(expression, dtype=dtype) expression_param = nn.Parameter(default_expression, requires_grad=True) self.register_parameter('expression', expression_param) def name(self) -> str: return 'SMPL-X' def num_expression_coeffs(self): return self._num_expression_coeffs def create_mean_pose(self, data_struct, flat_hand_mean=False): # Create the array for the mean pose. If flat_hand is false, then use # the mean that is given by the data, rather than the flat open hand global_orient_mean = torch.zeros([3], dtype=self.dtype) body_pose_mean = torch.zeros([self.NUM_BODY_JOINTS * 3], dtype=self.dtype) jaw_pose_mean = torch.zeros([3], dtype=self.dtype) leye_pose_mean = torch.zeros([3], dtype=self.dtype) reye_pose_mean = torch.zeros([3], dtype=self.dtype) pose_mean = np.concatenate([global_orient_mean, body_pose_mean, jaw_pose_mean, leye_pose_mean, reye_pose_mean, self.left_hand_mean, self.right_hand_mean], axis=0) return pose_mean def extra_repr(self): msg = super(SMPLX, self).extra_repr() msg = [ msg, f'Number of Expression Coefficients: {self.num_expression_coeffs}' ] return '\n'.join(msg) def forward( self, betas: Optional[Tensor] = None, global_orient: Optional[Tensor] = None, body_pose: Optional[Tensor] = None, left_hand_pose: Optional[Tensor] = None, right_hand_pose: Optional[Tensor] = None, transl: Optional[Tensor] = None, expression: Optional[Tensor] = None, jaw_pose: Optional[Tensor] = None, leye_pose: Optional[Tensor] = None, reye_pose: Optional[Tensor] = None, return_verts: bool = True, return_full_pose: bool = False, pose2rot: bool = True ) -> SMPLXOutput: ''' Forward pass for the SMPLX model Parameters ---------- global_orient: torch.tensor, optional, shape Bx3 If given, ignore the member variable and use it as the global rotation of the body. Useful if someone wishes to predicts this with an external model. (default=None) betas: torch.tensor, optional, shape BxN_b If given, ignore the member variable `betas` and use it instead. For example, it can used if shape parameters `betas` are predicted from some external model. (default=None) expression: torch.tensor, optional, shape BxN_e If given, ignore the member variable `expression` and use it instead. For example, it can used if expression parameters `expression` are predicted from some external model. body_pose: torch.tensor, optional, shape Bx(J*3) If given, ignore the member variable `body_pose` and use it instead. For example, it can used if someone predicts the pose of the body joints are predicted from some external model. It should be a tensor that contains joint rotations in axis-angle format. (default=None) left_hand_pose: torch.tensor, optional, shape BxP If given, ignore the member variable `left_hand_pose` and use this instead. It should either contain PCA coefficients or joint rotations in axis-angle format. right_hand_pose: torch.tensor, optional, shape BxP If given, ignore the member variable `right_hand_pose` and use this instead. It should either contain PCA coefficients or joint rotations in axis-angle format. jaw_pose: torch.tensor, optional, shape Bx3 If given, ignore the member variable `jaw_pose` and use this instead. It should either joint rotations in axis-angle format. transl: torch.tensor, optional, shape Bx3 If given, ignore the member variable `transl` and use it instead. For example, it can used if the translation `transl` is predicted from some external model. (default=None) return_verts: bool, optional Return the vertices. (default=True) return_full_pose: bool, optional Returns the full axis-angle pose vector (default=False) Returns ------- output: ModelOutput A named tuple of type `ModelOutput` ''' # If no shape and pose parameters are passed along, then use the # ones from the module global_orient = (global_orient if global_orient is not None else self.global_orient) body_pose = body_pose if body_pose is not None else self.body_pose betas = betas if betas is not None else self.betas left_hand_pose = (left_hand_pose if left_hand_pose is not None else self.left_hand_pose) right_hand_pose = (right_hand_pose if right_hand_pose is not None else self.right_hand_pose) jaw_pose = jaw_pose if jaw_pose is not None else self.jaw_pose leye_pose = leye_pose if leye_pose is not None else self.leye_pose reye_pose = reye_pose if reye_pose is not None else self.reye_pose expression = expression if expression is not None else self.expression apply_trans = transl is not None or hasattr(self, 'transl') if transl is None: if hasattr(self, 'transl'): transl = self.transl if self.use_pca: left_hand_pose = torch.einsum( 'bi,ij->bj', [left_hand_pose, self.left_hand_components]) right_hand_pose = torch.einsum( 'bi,ij->bj', [right_hand_pose, self.right_hand_components]) full_pose = torch.cat([global_orient, body_pose, jaw_pose, leye_pose, reye_pose, left_hand_pose, right_hand_pose], dim=1) # Add the mean pose of the model. Does not affect the body, only the # hands when flat_hand_mean == False full_pose += self.pose_mean batch_size = max(betas.shape[0], global_orient.shape[0], body_pose.shape[0]) # Concatenate the shape and expression coefficients scale = int(batch_size / betas.shape[0]) if scale > 1: betas = betas.expand(scale, -1) shape_components = torch.cat([betas, expression], dim=-1) shapedirs = torch.cat([self.shapedirs, self.expr_dirs], dim=-1) vertices, joints = lbs(shape_components, full_pose, self.v_template, shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=pose2rot, ) lmk_faces_idx = self.lmk_faces_idx.unsqueeze( dim=0).expand(batch_size, -1).contiguous() lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat( self.batch_size, 1, 1) if self.use_face_contour: lmk_idx_and_bcoords = find_dynamic_lmk_idx_and_bcoords( vertices, full_pose, self.dynamic_lmk_faces_idx, self.dynamic_lmk_bary_coords, self.neck_kin_chain, pose2rot=True, ) dyn_lmk_faces_idx, dyn_lmk_bary_coords = lmk_idx_and_bcoords lmk_faces_idx = torch.cat([lmk_faces_idx, dyn_lmk_faces_idx], 1) lmk_bary_coords = torch.cat( [lmk_bary_coords.expand(batch_size, -1, -1), dyn_lmk_bary_coords], 1) landmarks = vertices2landmarks(vertices, self.faces_tensor, lmk_faces_idx, lmk_bary_coords) # Add any extra joints that might be needed joints = self.vertex_joint_selector(vertices, joints) # Add the landmarks to the joints joints = torch.cat([joints, landmarks], dim=1) # Map the joints to the current dataset if self.joint_mapper is not None: joints = self.joint_mapper(joints=joints, vertices=vertices) if apply_trans: joints += transl.unsqueeze(dim=1) vertices += transl.unsqueeze(dim=1) output = SMPLXOutput(vertices=vertices if return_verts else None, faces=self.faces, joints=joints, betas=betas, expression=expression, global_orient=global_orient, body_pose=body_pose, left_hand_pose=left_hand_pose, right_hand_pose=right_hand_pose, jaw_pose=jaw_pose, full_pose=full_pose if return_full_pose else None) return output class MANO(SMPL): # The hand joints are replaced by MANO NUM_BODY_JOINTS = 1 NUM_HAND_JOINTS = 15 NUM_JOINTS = NUM_BODY_JOINTS + NUM_HAND_JOINTS def __init__( self, model_path: str, is_rhand: bool = True, data_struct: Optional[Struct] = None, create_hand_pose: bool = True, hand_pose: Optional[Tensor] = None, use_pca: bool = True, num_pca_comps: int = 6, flat_hand_mean: bool = False, batch_size: int = 1, dtype=torch.float32, vertex_ids=None, use_compressed: bool = True, ext: str = 'pkl' ) -> None: ''' MANO model constructor Parameters ---------- model_path: str The path to the folder or to the file where the model parameters are stored data_struct: Strct A struct object. If given, then the parameters of the model are read from the object. Otherwise, the model tries to read the parameters from the given `model_path`. (default = None) create_hand_pose: bool, optional Flag for creating a member variable for the pose of the right hand. (default = True) hand_pose: torch.tensor, optional, BxP The default value for the right hand pose member variable. (default = None) num_pca_comps: int, optional The number of PCA components to use for each hand. (default = 6) flat_hand_mean: bool, optional If False, then the pose of the hand is initialized to False. batch_size: int, optional The batch size used for creating the member variables dtype: torch.dtype, optional The data type for the created variables vertex_ids: dict, optional A dictionary containing the indices of the extra vertices that will be selected ''' self.num_pca_comps = num_pca_comps self.is_rhand = is_rhand # If no data structure is passed, then load the data from the given # model folder if data_struct is None: # Load the model if osp.isdir(model_path): model_fn = 'MANO_{}.{ext}'.format( 'RIGHT' if is_rhand else 'LEFT', ext=ext) mano_path = os.path.join(model_path, model_fn) else: mano_path = model_path self.is_rhand = True if 'RIGHT' in os.path.basename( model_path) else False assert osp.exists(mano_path), 'Path {} does not exist!'.format( mano_path) if ext == 'pkl': with open(mano_path, 'rb') as mano_file: model_data = pickle.load(mano_file, encoding='latin1') elif ext == 'npz': model_data = np.load(mano_path, allow_pickle=True) else: raise ValueError('Unknown extension: {}'.format(ext)) data_struct = Struct(**model_data) if vertex_ids is None: vertex_ids = VERTEX_IDS['smplh'] super(MANO, self).__init__( model_path=model_path, data_struct=data_struct, batch_size=batch_size, vertex_ids=vertex_ids, use_compressed=use_compressed, dtype=dtype, ext=ext) # add only MANO tips to the extra joints self.vertex_joint_selector.extra_joints_idxs = to_tensor( list(VERTEX_IDS['mano'].values()), dtype=torch.long) self.use_pca = use_pca self.num_pca_comps = num_pca_comps if self.num_pca_comps == 45: self.use_pca = False self.flat_hand_mean = flat_hand_mean hand_components = data_struct.hands_components[:num_pca_comps] self.np_hand_components = hand_components if self.use_pca: self.register_buffer( 'hand_components', torch.tensor(hand_components, dtype=dtype)) if self.flat_hand_mean: hand_mean = np.zeros_like(data_struct.hands_mean) else: hand_mean = data_struct.hands_mean self.register_buffer('hand_mean', to_tensor(hand_mean, dtype=self.dtype)) # Create the buffers for the pose of the left hand hand_pose_dim = num_pca_comps if use_pca else 3 * self.NUM_HAND_JOINTS if create_hand_pose: if hand_pose is None: default_hand_pose = torch.zeros([batch_size, hand_pose_dim], dtype=dtype) else: default_hand_pose = torch.tensor(hand_pose, dtype=dtype) hand_pose_param = nn.Parameter(default_hand_pose, requires_grad=True) self.register_parameter('hand_pose', hand_pose_param) # Create the buffer for the mean pose. pose_mean = self.create_mean_pose( data_struct, flat_hand_mean=flat_hand_mean) pose_mean_tensor = pose_mean.clone().to(dtype) # pose_mean_tensor = torch.tensor(pose_mean, dtype=dtype) self.register_buffer('pose_mean', pose_mean_tensor) def name(self) -> str: return 'MANO' def create_mean_pose(self, data_struct, flat_hand_mean=False): # Create the array for the mean pose. If flat_hand is false, then use # the mean that is given by the data, rather than the flat open hand global_orient_mean = torch.zeros([3], dtype=self.dtype) pose_mean = torch.cat([global_orient_mean, self.hand_mean], dim=0) return pose_mean def extra_repr(self): msg = [super(MANO, self).extra_repr()] if self.use_pca: msg.append(f'Number of PCA components: {self.num_pca_comps}') msg.append(f'Flat hand mean: {self.flat_hand_mean}') return '\n'.join(msg) def forward( self, betas: Optional[Tensor] = None, global_orient: Optional[Tensor] = None, hand_pose: Optional[Tensor] = None, transl: Optional[Tensor] = None, return_verts: bool = True, return_full_pose: bool = False ) -> MANOOutput: ''' Forward pass for the MANO model ''' # If no shape and pose parameters are passed along, then use the # ones from the module global_orient = (global_orient if global_orient is not None else self.global_orient) betas = betas if betas is not None else self.betas hand_pose = (hand_pose if hand_pose is not None else self.hand_pose) apply_trans = transl is not None or hasattr(self, 'transl') if transl is None: if hasattr(self, 'transl'): transl = self.transl if self.use_pca: hand_pose = torch.einsum( 'bi,ij->bj', [hand_pose, self.hand_components]) full_pose = torch.cat([global_orient, hand_pose], dim=1) full_pose += self.pose_mean vertices, joints = lbs(betas, full_pose, self.v_template, self.shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=True, ) # # Add pre-selected extra joints that might be needed # joints = self.vertex_joint_selector(vertices, joints) if self.joint_mapper is not None: joints = self.joint_mapper(joints) if apply_trans: joints = joints + transl.unsqueeze(dim=1) vertices = vertices + transl.unsqueeze(dim=1) output = MANOOutput(vertices=vertices if return_verts else None, joints=joints if return_verts else None, betas=betas, global_orient=global_orient, hand_pose=hand_pose, full_pose=full_pose if return_full_pose else None) return output class FLAME(SMPL): NUM_JOINTS = 5 SHAPE_SPACE_DIM = 300 EXPRESSION_SPACE_DIM = 100 NECK_IDX = 0 def __init__( self, model_path: str, data_struct=None, num_expression_coeffs=10, create_expression: bool = True, expression: Optional[Tensor] = None, create_neck_pose: bool = True, neck_pose: Optional[Tensor] = None, create_jaw_pose: bool = True, jaw_pose: Optional[Tensor] = None, create_leye_pose: bool = True, leye_pose: Optional[Tensor] = None, create_reye_pose=True, reye_pose: Optional[Tensor] = None, use_face_contour=False, batch_size: int = 1, gender: str = 'neutral', dtype: torch.dtype = torch.float32, ext='pkl' ) -> None: ''' FLAME model constructor Parameters ---------- model_path: str The path to the folder or to the file where the model parameters are stored num_expression_coeffs: int, optional Number of expression components to use (default = 10). create_expression: bool, optional Flag for creating a member variable for the expression space (default = True). expression: torch.tensor, optional, Bx10 The default value for the expression member variable. (default = None) create_neck_pose: bool, optional Flag for creating a member variable for the neck pose. (default = False) neck_pose: torch.tensor, optional, Bx3 The default value for the neck pose variable. (default = None) create_jaw_pose: bool, optional Flag for creating a member variable for the jaw pose. (default = False) jaw_pose: torch.tensor, optional, Bx3 The default value for the jaw pose variable. (default = None) create_leye_pose: bool, optional Flag for creating a member variable for the left eye pose. (default = False) leye_pose: torch.tensor, optional, Bx10 The default value for the left eye pose variable. (default = None) create_reye_pose: bool, optional Flag for creating a member variable for the right eye pose. (default = False) reye_pose: torch.tensor, optional, Bx10 The default value for the right eye pose variable. (default = None) use_face_contour: bool, optional Whether to compute the keypoints that form the facial contour batch_size: int, optional The batch size used for creating the member variables gender: str, optional Which gender to load dtype: torch.dtype The data type for the created variables ''' model_fn = f'FLAME_{gender.upper()}.{ext}' flame_path = os.path.join(model_path, model_fn) assert osp.exists(flame_path), 'Path {} does not exist!'.format( flame_path) if ext == 'npz': file_data = np.load(flame_path, allow_pickle=True) elif ext == 'pkl': with open(flame_path, 'rb') as smpl_file: file_data = pickle.load(smpl_file, encoding='latin1') else: raise ValueError('Unknown extension: {}'.format(ext)) data_struct = Struct(**file_data) super(FLAME, self).__init__( model_path=model_path, data_struct=data_struct, dtype=dtype, batch_size=batch_size, gender=gender, ext=ext) self.use_face_contour = use_face_contour self.vertex_joint_selector.extra_joints_idxs = to_tensor( [], dtype=torch.long) if create_neck_pose: if neck_pose is None: default_neck_pose = torch.zeros([batch_size, 3], dtype=dtype) else: default_neck_pose = torch.tensor(neck_pose, dtype=dtype) neck_pose_param = nn.Parameter( default_neck_pose, requires_grad=True) self.register_parameter('neck_pose', neck_pose_param) if create_jaw_pose: if jaw_pose is None: default_jaw_pose = torch.zeros([batch_size, 3], dtype=dtype) else: default_jaw_pose = torch.tensor(jaw_pose, dtype=dtype) jaw_pose_param = nn.Parameter(default_jaw_pose, requires_grad=True) self.register_parameter('jaw_pose', jaw_pose_param) if create_leye_pose: if leye_pose is None: default_leye_pose = torch.zeros([batch_size, 3], dtype=dtype) else: default_leye_pose = torch.tensor(leye_pose, dtype=dtype) leye_pose_param = nn.Parameter(default_leye_pose, requires_grad=True) self.register_parameter('leye_pose', leye_pose_param) if create_reye_pose: if reye_pose is None: default_reye_pose = torch.zeros([batch_size, 3], dtype=dtype) else: default_reye_pose = torch.tensor(reye_pose, dtype=dtype) reye_pose_param = nn.Parameter(default_reye_pose, requires_grad=True) self.register_parameter('reye_pose', reye_pose_param) shapedirs = data_struct.shapedirs if len(shapedirs.shape) < 3: shapedirs = shapedirs[:, :, None] if (shapedirs.shape[-1] < self.SHAPE_SPACE_DIM + self.EXPRESSION_SPACE_DIM): print(f'WARNING: You are using a {self.name()} model, with only' ' 10 shape and 10 expression coefficients.') expr_start_idx = 10 expr_end_idx = 20 num_expression_coeffs = min(num_expression_coeffs, 10) else: expr_start_idx = self.SHAPE_SPACE_DIM expr_end_idx = self.SHAPE_SPACE_DIM + num_expression_coeffs num_expression_coeffs = min( num_expression_coeffs, self.EXPRESSION_SPACE_DIM) self._num_expression_coeffs = num_expression_coeffs expr_dirs = shapedirs[:, :, expr_start_idx:expr_end_idx] self.register_buffer( 'expr_dirs', to_tensor(to_np(expr_dirs), dtype=dtype)) if create_expression: if expression is None: default_expression = torch.zeros( [batch_size, self.num_expression_coeffs], dtype=dtype) else: default_expression = torch.tensor(expression, dtype=dtype) expression_param = nn.Parameter(default_expression, requires_grad=True) self.register_parameter('expression', expression_param) # The pickle file that contains the barycentric coordinates for # regressing the landmarks landmark_bcoord_filename = osp.join( model_path, 'flame_static_embedding.pkl') with open(landmark_bcoord_filename, 'rb') as fp: landmarks_data = pickle.load(fp, encoding='latin1') lmk_faces_idx = landmarks_data['lmk_face_idx'].astype(np.int64) self.register_buffer('lmk_faces_idx', torch.tensor(lmk_faces_idx, dtype=torch.long)) lmk_bary_coords = landmarks_data['lmk_b_coords'] self.register_buffer('lmk_bary_coords', torch.tensor(lmk_bary_coords, dtype=dtype)) if self.use_face_contour: face_contour_path = os.path.join( model_path, 'flame_dynamic_embedding.npy') contour_embeddings = np.load(face_contour_path, allow_pickle=True, encoding='latin1')[()] dynamic_lmk_faces_idx = np.array( contour_embeddings['lmk_face_idx'], dtype=np.int64) dynamic_lmk_faces_idx = torch.tensor( dynamic_lmk_faces_idx, dtype=torch.long) self.register_buffer('dynamic_lmk_faces_idx', dynamic_lmk_faces_idx) dynamic_lmk_b_coords = torch.tensor( contour_embeddings['lmk_b_coords'], dtype=dtype) self.register_buffer( 'dynamic_lmk_bary_coords', dynamic_lmk_b_coords) neck_kin_chain = find_joint_kin_chain(self.NECK_IDX, self.parents) self.register_buffer( 'neck_kin_chain', torch.tensor(neck_kin_chain, dtype=torch.long)) def num_expression_coeffs(self): return self._num_expression_coeffs def name(self) -> str: return 'FLAME' def extra_repr(self): msg = [ super(FLAME, self).extra_repr(), f'Number of Expression Coefficients: {self.num_expression_coeffs}', f'Use face contour: {self.use_face_contour}', ] return '\n'.join(msg) def forward( self, betas: Optional[Tensor] = None, global_orient: Optional[Tensor] = None, neck_pose: Optional[Tensor] = None, transl: Optional[Tensor] = None, expression: Optional[Tensor] = None, jaw_pose: Optional[Tensor] = None, leye_pose: Optional[Tensor] = None, reye_pose: Optional[Tensor] = None, return_verts: bool = True, return_full_pose: bool = False, pose2rot: bool = True ) -> FLAMEOutput: ''' Forward pass for the SMPLX model Parameters ---------- global_orient: torch.tensor, optional, shape Bx3 If given, ignore the member variable and use it as the global rotation of the body. Useful if someone wishes to predicts this with an external model. (default=None) betas: torch.tensor, optional, shape Bx10 If given, ignore the member variable `betas` and use it instead. For example, it can used if shape parameters `betas` are predicted from some external model. (default=None) expression: torch.tensor, optional, shape Bx10 If given, ignore the member variable `expression` and use it instead. For example, it can used if expression parameters `expression` are predicted from some external model. jaw_pose: torch.tensor, optional, shape Bx3 If given, ignore the member variable `jaw_pose` and use this instead. It should either joint rotations in axis-angle format. jaw_pose: torch.tensor, optional, shape Bx3 If given, ignore the member variable `jaw_pose` and use this instead. It should either joint rotations in axis-angle format. transl: torch.tensor, optional, shape Bx3 If given, ignore the member variable `transl` and use it instead. For example, it can used if the translation `transl` is predicted from some external model. (default=None) return_verts: bool, optional Return the vertices. (default=True) return_full_pose: bool, optional Returns the full axis-angle pose vector (default=False) Returns ------- output: ModelOutput A named tuple of type `ModelOutput` ''' # If no shape and pose parameters are passed along, then use the # ones from the module global_orient = (global_orient if global_orient is not None else self.global_orient) jaw_pose = jaw_pose if jaw_pose is not None else self.jaw_pose neck_pose = neck_pose if neck_pose is not None else self.neck_pose leye_pose = leye_pose if leye_pose is not None else self.leye_pose reye_pose = reye_pose if reye_pose is not None else self.reye_pose betas = betas if betas is not None else self.betas expression = expression if expression is not None else self.expression apply_trans = transl is not None or hasattr(self, 'transl') if transl is None: if hasattr(self, 'transl'): transl = self.transl full_pose = torch.cat( [global_orient, neck_pose, jaw_pose, leye_pose, reye_pose], dim=1) batch_size = max(betas.shape[0], global_orient.shape[0], jaw_pose.shape[0]) # Concatenate the shape and expression coefficients scale = int(batch_size / betas.shape[0]) if scale > 1: betas = betas.expand(scale, -1) shape_components = torch.cat([betas, expression], dim=-1) shapedirs = torch.cat([self.shapedirs, self.expr_dirs], dim=-1) vertices, joints = lbs(shape_components, full_pose, self.v_template, shapedirs, self.posedirs, self.J_regressor, self.parents, self.lbs_weights, pose2rot=pose2rot, ) lmk_faces_idx = self.lmk_faces_idx.unsqueeze( dim=0).expand(batch_size, -1).contiguous() lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat( self.batch_size, 1, 1) if self.use_face_contour: lmk_idx_and_bcoords = find_dynamic_lmk_idx_and_bcoords( vertices, full_pose, self.dynamic_lmk_faces_idx, self.dynamic_lmk_bary_coords, self.neck_kin_chain, pose2rot=True, ) dyn_lmk_faces_idx, dyn_lmk_bary_coords = lmk_idx_and_bcoords lmk_faces_idx = torch.cat([lmk_faces_idx, dyn_lmk_faces_idx], 1) lmk_bary_coords = torch.cat( [lmk_bary_coords.expand(batch_size, -1, -1), dyn_lmk_bary_coords], 1) landmarks = vertices2landmarks(vertices, self.faces_tensor, lmk_faces_idx, lmk_bary_coords) # Add any extra joints that might be needed joints = self.vertex_joint_selector(vertices, joints) # Add the landmarks to the joints joints = torch.cat([joints, landmarks], dim=1) # Map the joints to the current dataset if self.joint_mapper is not None: joints = self.joint_mapper(joints=joints, vertices=vertices) if apply_trans: joints += transl.unsqueeze(dim=1) vertices += transl.unsqueeze(dim=1) output = FLAMEOutput(vertices=vertices if return_verts else None, joints=joints, betas=betas, expression=expression, global_orient=global_orient, neck_pose=neck_pose, jaw_pose=jaw_pose, full_pose=full_pose if return_full_pose else None) return output The provided code snippet includes necessary dependencies for implementing the `create` function. Write a Python function `def create( model_path: str, model_type: str = 'smpl' ) -> Union[SMPL, SMPLH, SMPLX, MANO, FLAME]` to solve the following problem: Method for creating a model from a path and a model type Parameters ---------- model_path: str Either the path to the model you wish to load or a folder, where each subfolder contains the differents types, i.e.: model_path: | |-- smpl |-- SMPL_FEMALE |-- SMPL_NEUTRAL |-- SMPL_MALE |-- smplh |-- SMPLH_FEMALE |-- SMPLH_MALE |-- smplx |-- SMPLX_FEMALE |-- SMPLX_NEUTRAL |-- SMPLX_MALE |-- mano |-- MANO RIGHT |-- MANO LEFT model_type: str, optional When model_path is a folder, then this parameter specifies the type of model to be loaded **kwargs: dict Keyword arguments Returns ------- body_model: nn.Module The PyTorch module that implements the corresponding body model Raises ------ ValueError: In case the model type is not one of SMPL, SMPLH, SMPLX, MANO or FLAME Here is the function: def create( model_path: str, model_type: str = 'smpl' ) -> Union[SMPL, SMPLH, SMPLX, MANO, FLAME]: ''' Method for creating a model from a path and a model type Parameters ---------- model_path: str Either the path to the model you wish to load or a folder, where each subfolder contains the differents types, i.e.: model_path: | |-- smpl |-- SMPL_FEMALE |-- SMPL_NEUTRAL |-- SMPL_MALE |-- smplh |-- SMPLH_FEMALE |-- SMPLH_MALE |-- smplx |-- SMPLX_FEMALE |-- SMPLX_NEUTRAL |-- SMPLX_MALE |-- mano |-- MANO RIGHT |-- MANO LEFT model_type: str, optional When model_path is a folder, then this parameter specifies the type of model to be loaded **kwargs: dict Keyword arguments Returns ------- body_model: nn.Module The PyTorch module that implements the corresponding body model Raises ------ ValueError: In case the model type is not one of SMPL, SMPLH, SMPLX, MANO or FLAME ''' # If it's a folder, assume if osp.isdir(model_path): model_path = os.path.join(model_path, model_type) else: model_type = osp.basename(model_path).split('_')[0].lower() if model_type.lower() == 'smpl': return SMPL(model_path) elif model_type.lower() == 'smplh': return SMPLH(model_path) elif model_type.lower() == 'smplx': return SMPLX(model_path) elif 'mano' in model_type.lower(): return MANO(model_path) elif 'flame' in model_type.lower(): return FLAME(model_path) else: raise ValueError(f'Unknown model type {model_type}, exiting!')
Method for creating a model from a path and a model type Parameters ---------- model_path: str Either the path to the model you wish to load or a folder, where each subfolder contains the differents types, i.e.: model_path: | |-- smpl |-- SMPL_FEMALE |-- SMPL_NEUTRAL |-- SMPL_MALE |-- smplh |-- SMPLH_FEMALE |-- SMPLH_MALE |-- smplx |-- SMPLX_FEMALE |-- SMPLX_NEUTRAL |-- SMPLX_MALE |-- mano |-- MANO RIGHT |-- MANO LEFT model_type: str, optional When model_path is a folder, then this parameter specifies the type of model to be loaded **kwargs: dict Keyword arguments Returns ------- body_model: nn.Module The PyTorch module that implements the corresponding body model Raises ------ ValueError: In case the model type is not one of SMPL, SMPLH, SMPLX, MANO or FLAME
351
from typing import NewType, Union, Optional from dataclasses import dataclass, asdict, fields import numpy as np import torch def find_joint_kin_chain(joint_id, kinematic_tree): kin_chain = [] curr_idx = joint_id while curr_idx != -1: kin_chain.append(curr_idx) curr_idx = kinematic_tree[curr_idx] return kin_chain
null
352
from typing import NewType, Union, Optional from dataclasses import dataclass, asdict, fields import numpy as np import torch Tensor = NewType('Tensor', torch.Tensor) Array = NewType('Array', np.ndarray) def to_tensor( array: Union[Array, Tensor], dtype=torch.float32 ) -> Tensor: if torch.is_tensor(array): return array else: return torch.tensor(array, dtype=dtype)
null
353
from typing import NewType, Union, Optional from dataclasses import dataclass, asdict, fields import numpy as np import torch def to_np(array, dtype=np.float32): if 'scipy.sparse' in str(type(array)): array = array.todense() return np.array(array, dtype=dtype)
null
354
from __future__ import absolute_import from __future__ import print_function from __future__ import division from typing import Tuple, List import numpy as np import torch import torch.nn.functional as F from .utils import rot_mat_to_euler, Tensor def batch_rodrigues( rot_vecs: Tensor, epsilon: float = 1e-8, ) -> Tensor: ''' Calculates the rotation matrices for a batch of rotation vectors Parameters ---------- rot_vecs: torch.tensor Nx3 array of N axis-angle vectors Returns ------- R: torch.tensor Nx3x3 The rotation matrices for the given axis-angle parameters ''' batch_size = rot_vecs.shape[0] device, dtype = rot_vecs.device, rot_vecs.dtype angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) rot_dir = rot_vecs / angle cos = torch.unsqueeze(torch.cos(angle), dim=1) sin = torch.unsqueeze(torch.sin(angle), dim=1) # Bx1 arrays rx, ry, rz = torch.split(rot_dir, 1, dim=1) K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \ .view((batch_size, 3, 3)) ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K) return rot_mat Tensor = NewType('Tensor', torch.Tensor) def rot_mat_to_euler(rot_mats): # Calculates rotation matrix to euler angles # Careful for extreme cases of eular angles like [0.0, pi, 0.0] sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] + rot_mats[:, 1, 0] * rot_mats[:, 1, 0]) return torch.atan2(-rot_mats[:, 2, 0], sy) The provided code snippet includes necessary dependencies for implementing the `find_dynamic_lmk_idx_and_bcoords` function. Write a Python function `def find_dynamic_lmk_idx_and_bcoords( vertices: Tensor, pose: Tensor, dynamic_lmk_faces_idx: Tensor, dynamic_lmk_b_coords: Tensor, neck_kin_chain: List[int], pose2rot: bool = True, ) -> Tuple[Tensor, Tensor]` to solve the following problem: Compute the faces, barycentric coordinates for the dynamic landmarks To do so, we first compute the rotation of the neck around the y-axis and then use a pre-computed look-up table to find the faces and the barycentric coordinates that will be used. Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de) for providing the original TensorFlow implementation and for the LUT. Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices pose: torch.tensor Bx(Jx3), dtype = torch.float32 The current pose of the body model dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long The look-up table from neck rotation to faces dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32 The look-up table from neck rotation to barycentric coordinates neck_kin_chain: list A python list that contains the indices of the joints that form the kinematic chain of the neck. dtype: torch.dtype, optional Returns ------- dyn_lmk_faces_idx: torch.tensor, dtype = torch.long A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks. dyn_lmk_b_coords: torch.tensor, dtype = torch.float32 A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks. Here is the function: def find_dynamic_lmk_idx_and_bcoords( vertices: Tensor, pose: Tensor, dynamic_lmk_faces_idx: Tensor, dynamic_lmk_b_coords: Tensor, neck_kin_chain: List[int], pose2rot: bool = True, ) -> Tuple[Tensor, Tensor]: ''' Compute the faces, barycentric coordinates for the dynamic landmarks To do so, we first compute the rotation of the neck around the y-axis and then use a pre-computed look-up table to find the faces and the barycentric coordinates that will be used. Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de) for providing the original TensorFlow implementation and for the LUT. Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices pose: torch.tensor Bx(Jx3), dtype = torch.float32 The current pose of the body model dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long The look-up table from neck rotation to faces dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32 The look-up table from neck rotation to barycentric coordinates neck_kin_chain: list A python list that contains the indices of the joints that form the kinematic chain of the neck. dtype: torch.dtype, optional Returns ------- dyn_lmk_faces_idx: torch.tensor, dtype = torch.long A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks. dyn_lmk_b_coords: torch.tensor, dtype = torch.float32 A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks. ''' dtype = vertices.dtype batch_size = vertices.shape[0] if pose2rot: aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1, neck_kin_chain) rot_mats = batch_rodrigues( aa_pose.view(-1, 3)).view(batch_size, -1, 3, 3) else: rot_mats = torch.index_select( pose.view(batch_size, -1, 3, 3), 1, neck_kin_chain) rel_rot_mat = torch.eye( 3, device=vertices.device, dtype=dtype).unsqueeze_(dim=0).repeat( batch_size, 1, 1) for idx in range(len(neck_kin_chain)): rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat) y_rot_angle = torch.round( torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi, max=39)).to(dtype=torch.long) neg_mask = y_rot_angle.lt(0).to(dtype=torch.long) mask = y_rot_angle.lt(-39).to(dtype=torch.long) neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle) y_rot_angle = (neg_mask * neg_vals + (1 - neg_mask) * y_rot_angle) dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx, 0, y_rot_angle) dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords, 0, y_rot_angle) return dyn_lmk_faces_idx, dyn_lmk_b_coords
Compute the faces, barycentric coordinates for the dynamic landmarks To do so, we first compute the rotation of the neck around the y-axis and then use a pre-computed look-up table to find the faces and the barycentric coordinates that will be used. Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de) for providing the original TensorFlow implementation and for the LUT. Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices pose: torch.tensor Bx(Jx3), dtype = torch.float32 The current pose of the body model dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long The look-up table from neck rotation to faces dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32 The look-up table from neck rotation to barycentric coordinates neck_kin_chain: list A python list that contains the indices of the joints that form the kinematic chain of the neck. dtype: torch.dtype, optional Returns ------- dyn_lmk_faces_idx: torch.tensor, dtype = torch.long A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks. dyn_lmk_b_coords: torch.tensor, dtype = torch.float32 A tensor of size BxL that contains the indices of the faces that will be used to compute the current dynamic landmarks.
355
from __future__ import absolute_import from __future__ import print_function from __future__ import division from typing import Tuple, List import numpy as np import torch import torch.nn.functional as F from .utils import rot_mat_to_euler, Tensor Tensor = NewType('Tensor', torch.Tensor) The provided code snippet includes necessary dependencies for implementing the `vertices2landmarks` function. Write a Python function `def vertices2landmarks( vertices: Tensor, faces: Tensor, lmk_faces_idx: Tensor, lmk_bary_coords: Tensor ) -> Tensor` to solve the following problem: Calculates landmarks by barycentric interpolation Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices faces: torch.tensor Fx3, dtype = torch.long The faces of the mesh lmk_faces_idx: torch.tensor L, dtype = torch.long The tensor with the indices of the faces used to calculate the landmarks. lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32 The tensor of barycentric coordinates that are used to interpolate the landmarks Returns ------- landmarks: torch.tensor BxLx3, dtype = torch.float32 The coordinates of the landmarks for each mesh in the batch Here is the function: def vertices2landmarks( vertices: Tensor, faces: Tensor, lmk_faces_idx: Tensor, lmk_bary_coords: Tensor ) -> Tensor: ''' Calculates landmarks by barycentric interpolation Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices faces: torch.tensor Fx3, dtype = torch.long The faces of the mesh lmk_faces_idx: torch.tensor L, dtype = torch.long The tensor with the indices of the faces used to calculate the landmarks. lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32 The tensor of barycentric coordinates that are used to interpolate the landmarks Returns ------- landmarks: torch.tensor BxLx3, dtype = torch.float32 The coordinates of the landmarks for each mesh in the batch ''' # Extract the indices of the vertices for each face # BxLx3 batch_size, num_verts = vertices.shape[:2] device = vertices.device lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view( batch_size, -1, 3) lmk_faces += torch.arange( batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts lmk_vertices = vertices.view(-1, 3)[lmk_faces].view( batch_size, -1, 3, 3) landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords]) return landmarks
Calculates landmarks by barycentric interpolation Parameters ---------- vertices: torch.tensor BxVx3, dtype = torch.float32 The tensor of input vertices faces: torch.tensor Fx3, dtype = torch.long The faces of the mesh lmk_faces_idx: torch.tensor L, dtype = torch.long The tensor with the indices of the faces used to calculate the landmarks. lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32 The tensor of barycentric coordinates that are used to interpolate the landmarks Returns ------- landmarks: torch.tensor BxLx3, dtype = torch.float32 The coordinates of the landmarks for each mesh in the batch
356
from __future__ import absolute_import from __future__ import print_function from __future__ import division from typing import Tuple, List import numpy as np import torch import torch.nn.functional as F from .utils import rot_mat_to_euler, Tensor def vertices2joints(J_regressor: Tensor, vertices: Tensor) -> Tensor: ''' Calculates the 3D joint locations from the vertices Parameters ---------- J_regressor : torch.tensor JxV The regressor array that is used to calculate the joints from the position of the vertices vertices : torch.tensor BxVx3 The tensor of mesh vertices Returns ------- torch.tensor BxJx3 The location of the joints ''' return torch.einsum('bik,ji->bjk', [vertices, J_regressor]) def blend_shapes(betas: Tensor, shape_disps: Tensor) -> Tensor: ''' Calculates the per vertex displacement due to the blend shapes Parameters ---------- betas : torch.tensor Bx(num_betas) Blend shape coefficients shape_disps: torch.tensor Vx3x(num_betas) Blend shapes Returns ------- torch.tensor BxVx3 The per-vertex displacement due to shape deformation ''' # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l] # i.e. Multiply each shape displacement by its corresponding beta and # then sum them. blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps]) return blend_shape def batch_rodrigues( rot_vecs: Tensor, epsilon: float = 1e-8, ) -> Tensor: ''' Calculates the rotation matrices for a batch of rotation vectors Parameters ---------- rot_vecs: torch.tensor Nx3 array of N axis-angle vectors Returns ------- R: torch.tensor Nx3x3 The rotation matrices for the given axis-angle parameters ''' batch_size = rot_vecs.shape[0] device, dtype = rot_vecs.device, rot_vecs.dtype angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) rot_dir = rot_vecs / angle cos = torch.unsqueeze(torch.cos(angle), dim=1) sin = torch.unsqueeze(torch.sin(angle), dim=1) # Bx1 arrays rx, ry, rz = torch.split(rot_dir, 1, dim=1) K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \ .view((batch_size, 3, 3)) ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K) return rot_mat def batch_rigid_transform( rot_mats: Tensor, joints: Tensor, parents: Tensor, dtype=torch.float32 ) -> Tensor: """ Applies a batch of rigid transformations to the joints Parameters ---------- rot_mats : torch.tensor BxNx3x3 Tensor of rotation matrices joints : torch.tensor BxNx3 Locations of joints parents : torch.tensor BxN The kinematic tree of each object dtype : torch.dtype, optional: The data type of the created tensors, the default is torch.float32 Returns ------- posed_joints : torch.tensor BxNx3 The locations of the joints after applying the pose rotations rel_transforms : torch.tensor BxNx4x4 The relative (with respect to the root joint) rigid transformations for all the joints """ joints = torch.unsqueeze(joints, dim=-1) rel_joints = joints.clone() rel_joints[:, 1:] -= joints[:, parents[1:]] transforms_mat = transform_mat( rot_mats.reshape(-1, 3, 3), rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4) transform_chain = [transforms_mat[:, 0]] for i in range(1, parents.shape[0]): # Subtract the joint location at the rest pose # No need for rotation, since it's identity when at rest curr_res = torch.matmul(transform_chain[parents[i]], transforms_mat[:, i]) transform_chain.append(curr_res) transforms = torch.stack(transform_chain, dim=1) # The last column of the transformations contains the posed joints posed_joints = transforms[:, :, :3, 3] joints_homogen = F.pad(joints, [0, 0, 0, 1]) rel_transforms = transforms - F.pad( torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0]) return posed_joints, rel_transforms Tensor = NewType('Tensor', torch.Tensor) The provided code snippet includes necessary dependencies for implementing the `lbs` function. Write a Python function `def lbs( betas: Tensor, pose: Tensor, v_template: Tensor, shapedirs: Tensor, posedirs: Tensor, J_regressor: Tensor, parents: Tensor, lbs_weights: Tensor, pose2rot: bool = True, ) -> Tuple[Tensor, Tensor]` to solve the following problem: Performs Linear Blend Skinning with the given shape and pose parameters Parameters ---------- betas : torch.tensor BxNB The tensor of shape parameters pose : torch.tensor Bx(J + 1) * 3 The pose parameters in axis-angle format v_template torch.tensor BxVx3 The template mesh that will be deformed shapedirs : torch.tensor 1xNB The tensor of PCA shape displacements posedirs : torch.tensor Px(V * 3) The pose PCA coefficients J_regressor : torch.tensor JxV The regressor array that is used to calculate the joints from the position of the vertices parents: torch.tensor J The array that describes the kinematic tree for the model lbs_weights: torch.tensor N x V x (J + 1) The linear blend skinning weights that represent how much the rotation matrix of each part affects each vertex pose2rot: bool, optional Flag on whether to convert the input pose tensor to rotation matrices. The default value is True. If False, then the pose tensor should already contain rotation matrices and have a size of Bx(J + 1)x9 dtype: torch.dtype, optional Returns ------- verts: torch.tensor BxVx3 The vertices of the mesh after applying the shape and pose displacements. joints: torch.tensor BxJx3 The joints of the model Here is the function: def lbs( betas: Tensor, pose: Tensor, v_template: Tensor, shapedirs: Tensor, posedirs: Tensor, J_regressor: Tensor, parents: Tensor, lbs_weights: Tensor, pose2rot: bool = True, ) -> Tuple[Tensor, Tensor]: ''' Performs Linear Blend Skinning with the given shape and pose parameters Parameters ---------- betas : torch.tensor BxNB The tensor of shape parameters pose : torch.tensor Bx(J + 1) * 3 The pose parameters in axis-angle format v_template torch.tensor BxVx3 The template mesh that will be deformed shapedirs : torch.tensor 1xNB The tensor of PCA shape displacements posedirs : torch.tensor Px(V * 3) The pose PCA coefficients J_regressor : torch.tensor JxV The regressor array that is used to calculate the joints from the position of the vertices parents: torch.tensor J The array that describes the kinematic tree for the model lbs_weights: torch.tensor N x V x (J + 1) The linear blend skinning weights that represent how much the rotation matrix of each part affects each vertex pose2rot: bool, optional Flag on whether to convert the input pose tensor to rotation matrices. The default value is True. If False, then the pose tensor should already contain rotation matrices and have a size of Bx(J + 1)x9 dtype: torch.dtype, optional Returns ------- verts: torch.tensor BxVx3 The vertices of the mesh after applying the shape and pose displacements. joints: torch.tensor BxJx3 The joints of the model ''' batch_size = max(betas.shape[0], pose.shape[0]) device, dtype = betas.device, betas.dtype # Add shape contribution v_shaped = v_template + blend_shapes(betas, shapedirs) # Get the joints # NxJx3 array J = vertices2joints(J_regressor, v_shaped) # 3. Add pose blend shapes # N x J x 3 x 3 ident = torch.eye(3, dtype=dtype, device=device) if pose2rot: rot_mats = batch_rodrigues(pose.view(-1, 3)).view( [batch_size, -1, 3, 3]) pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1]) # (N x P) x (P, V * 3) -> N x V x 3 pose_offsets = torch.matmul( pose_feature, posedirs).view(batch_size, -1, 3) else: pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident rot_mats = pose.view(batch_size, -1, 3, 3) pose_offsets = torch.matmul(pose_feature.view(batch_size, -1), posedirs).view(batch_size, -1, 3) v_posed = pose_offsets + v_shaped # 4. Get the global joint location J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype) # 5. Do skinning: # W is N x V x (J + 1) W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1]) # (N x V x (J + 1)) x (N x (J + 1) x 16) num_joints = J_regressor.shape[0] T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \ .view(batch_size, -1, 4, 4) homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1], dtype=dtype, device=device) v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2) v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1)) verts = v_homo[:, :, :3, 0] return verts, J_transformed
Performs Linear Blend Skinning with the given shape and pose parameters Parameters ---------- betas : torch.tensor BxNB The tensor of shape parameters pose : torch.tensor Bx(J + 1) * 3 The pose parameters in axis-angle format v_template torch.tensor BxVx3 The template mesh that will be deformed shapedirs : torch.tensor 1xNB The tensor of PCA shape displacements posedirs : torch.tensor Px(V * 3) The pose PCA coefficients J_regressor : torch.tensor JxV The regressor array that is used to calculate the joints from the position of the vertices parents: torch.tensor J The array that describes the kinematic tree for the model lbs_weights: torch.tensor N x V x (J + 1) The linear blend skinning weights that represent how much the rotation matrix of each part affects each vertex pose2rot: bool, optional Flag on whether to convert the input pose tensor to rotation matrices. The default value is True. If False, then the pose tensor should already contain rotation matrices and have a size of Bx(J + 1)x9 dtype: torch.dtype, optional Returns ------- verts: torch.tensor BxVx3 The vertices of the mesh after applying the shape and pose displacements. joints: torch.tensor BxJx3 The joints of the model
357
import os import io import ntpath import hashlib import fnmatch import shlex import speakeasy.winenv.defs.windows.windows as windefs import speakeasy.winenv.arch as _arch from speakeasy.errors import FileSystemEmuError def normalize_response_path(path): def _get_speakeasy_root(): return os.path.join(os.path.dirname(__file__), os.pardir) root_var = '$ROOT$' if root_var in path: root = _get_speakeasy_root() return path.replace(root_var, root) return path
null
358
import collections import speakeasy.winenv.arch as e_arch def _lowercase_set(tt): return set([bb.lower() for bb in tt])
null
359
import io import os from urllib.parse import urlparse from io import BytesIO from speakeasy.errors import NetworkEmuError def is_empty(bio): if len(bio.getbuffer()) == bio.tell(): return True return False
null
360
import io import os from urllib.parse import urlparse from io import BytesIO from speakeasy.errors import NetworkEmuError def normalize_response_path(path): def _get_speakeasy_root(): return os.path.join(os.path.dirname(__file__), os.pardir) root_var = '$ROOT$' if root_var in path: root = _get_speakeasy_root() return path.replace(root_var, root) return path
null
361
import os import ntpath import hashlib from collections import namedtuple import pefile import speakeasy.winenv.arch as _arch import speakeasy.winenv.defs.nt.ddk as ddk from speakeasy.struct import Enum def normalize_dll_name(name): ret = name # Funnel CRTs into a single handler if name.lower().startswith(('api-ms-win-crt', 'vcruntime', 'ucrtbased', 'ucrtbase', 'msvcr', 'msvcp')): ret = 'msvcrt' # Redirect windows sockets 1.0 to windows sockets 2.0 elif name.lower().startswith(('winsock', 'wsock32')): ret = 'ws2_32' elif name.lower().startswith('api-ms-win-core'): ret = 'kernel32' return ret
null
362
import os import json import time import logging import argparse import multiprocessing as mp import speakeasy from speakeasy import Speakeasy import speakeasy.winenv.arch as e_arch def get_logger(): """ Get the default logger for speakeasy """ logger = logging.getLogger('speakeasy') if not logger.handlers: sh = logging.StreamHandler() logger.addHandler(sh) logger.setLevel(logging.INFO) return logger The provided code snippet includes necessary dependencies for implementing the `emulate_binary` function. Write a Python function `def emulate_binary(q, exit_event, fpath, cfg, argv, do_raw, arch='', drop_path='', dump_path='', raw_offset=0x0, emulate_children=False)` to solve the following problem: Setup the binary for emulation Here is the function: def emulate_binary(q, exit_event, fpath, cfg, argv, do_raw, arch='', drop_path='', dump_path='', raw_offset=0x0, emulate_children=False): """ Setup the binary for emulation """ logger = get_logger() try: report = None se = Speakeasy(config=cfg, logger=logger, argv=argv, exit_event=exit_event) if do_raw: arch = arch.lower() if arch == 'x86': arch = e_arch.ARCH_X86 elif arch in ('x64', 'amd64'): arch = e_arch.ARCH_AMD64 else: raise Exception('Unsupported architecture: %s' % arch) sc_addr = se.load_shellcode(fpath, arch) se.run_shellcode(sc_addr, offset=raw_offset or 0) else: module = se.load_module(fpath) se.run_module(module, all_entrypoints=True, emulate_children=emulate_children) finally: report = se.get_json_report() q.put(report) # If a memory dump was requested, do it now if dump_path: data = se.create_memdump_archive() logger.info('* Saving memory dump archive to %s' % (dump_path)) with open(dump_path, 'wb') as f: f.write(data) if drop_path: data = se.create_file_archive() if data: logger.info('* Saving dropped files archive to %s' % (drop_path)) with open(drop_path, 'wb') as f: f.write(data) else: logger.info('* No dropped files found')
Setup the binary for emulation
363
import os import json import ntpath import hashlib import zipfile from io import BytesIO from typing import Callable from pefile import MACHINE_TYPE import jsonschema import jsonschema.exceptions import speakeasy import speakeasy.winenv.arch as _arch from speakeasy import PeFile from speakeasy import Win32Emulator from speakeasy import WinKernelEmulator from speakeasy.errors import SpeakeasyError, ConfigError, NotSupportedError import speakeasy import speakeasy.winenv.arch as _arch from speakeasy import PeFile from speakeasy import Win32Emulator from speakeasy import WinKernelEmulator from speakeasy.errors import SpeakeasyError, ConfigError, NotSupportedError The provided code snippet includes necessary dependencies for implementing the `validate_config` function. Write a Python function `def validate_config(config) -> None` to solve the following problem: Validates the given configuration objects against the built-in schemas. Raises jsonschema.exceptions.ValidationError on invalid configuration. Expose the underlying jsonschema exception due to it having lots of information about failures. On success, returns without exception. Here is the function: def validate_config(config) -> None: """ Validates the given configuration objects against the built-in schemas. Raises jsonschema.exceptions.ValidationError on invalid configuration. Expose the underlying jsonschema exception due to it having lots of information about failures. On success, returns without exception. """ schema_path = os.path.join(os.path.dirname(speakeasy.__file__), 'config_schema.json') with open(schema_path, 'r') as ff: schema = json.load(ff) validator = jsonschema.Draft7Validator(schema) validator.validate(config)
Validates the given configuration objects against the built-in schemas. Raises jsonschema.exceptions.ValidationError on invalid configuration. Expose the underlying jsonschema exception due to it having lots of information about failures. On success, returns without exception.
364
import platform import ctypes as ct import unicorn as uc import unicorn.unicorn import unicorn.x86_const as u import speakeasy.winenv.arch as arch import speakeasy.common as common from speakeasy.errors import EmuEngineError def is_platform_intel(): mach = platform.machine() if mach in ('x86_64', 'i386', 'x86'): return True return False
null
365
import os The provided code snippet includes necessary dependencies for implementing the `normalize_package_path` function. Write a Python function `def normalize_package_path(path)` to solve the following problem: Get the supplied path in relation to the package root Here is the function: def normalize_package_path(path): """ Get the supplied path in relation to the package root """ def _get_speakeasy_root(): return os.path.join(os.path.dirname(__file__)) root_var = '$ROOT$' if root_var in path: root = _get_speakeasy_root() return path.replace(root_var, root) return path
Get the supplied path in relation to the package root
366
from socket import inet_aton from urllib.parse import urlparse import speakeasy.winenv.arch as _arch import speakeasy.windows.netman as netman import speakeasy.winenv.defs.wininet as windefs from .. import api def is_ip_address(ip): try: inet_aton(ip) return True except Exception: return False
null
368
import sys import inspect import speakeasy.winenv.arch as _arch from speakeasy.errors import ApiEmuError from speakeasy.winenv.api import api from speakeasy.winenv.api.kernelmode import * from speakeasy.winenv.api.usermode import * def autoload_api_handlers(): api_handlers = [] for modname, modobj in sys.modules.items(): if not modname.startswith(('speakeasy.winenv.api.kernelmode.', 'speakeasy.winenv.api.usermode.')): continue for clsname, clsobj in inspect.getmembers(modobj, inspect.isclass): if clsobj is not api.ApiHandler and issubclass(clsobj, api.ApiHandler): api_handlers.append((clsobj.name, clsobj)) return tuple(api_handlers)
null
369
def get_define_int(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k
null
370
from speakeasy.struct import EmuStruct, Ptr import ctypes as ct def get_create_disposition(flags): disp = None dispostions = ('CREATE_ALWAYS', 'CREATE_NEW', 'OPEN_ALWAYS', 'OPEN_EXISTING', 'TRUNCATE_EXISTING') for k, v in [(k, v) for k, v in globals().items() if k in dispostions]: if isinstance(v, int): if v == flags: disp = k break return disp
null
371
from speakeasy.struct import EmuStruct, Ptr import ctypes as ct def get_define(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k
null
372
from speakeasy.struct import EmuStruct, Ptr import ctypes as ct def get_flag_defines(flags, prefix=''): def get_page_rights(define): return get_flag_defines(define, prefix='PAGE_')
null
373
from speakeasy.struct import EmuStruct, Ptr import ctypes as ct def get_flag_defines(flags, prefix=''): def get_creation_flags(flags): return get_flag_defines(flags, prefix='CREATE_')
null
374
from speakeasy.struct import EmuStruct, Ptr import ctypes as ct class SID(EmuStruct): def __init__(self, ptr_size, sub_authority_count): super().__init__(ptr_size) self.Revision = ct.c_uint8 self.SubAuthorityCount = ct.c_uint8 self.IdentifierAuthority = ct.c_uint8 * 6 self.SubAuthority = ct.c_uint32 * sub_authority_count def convert_sid_str_to_struct(ptr_size, sid_str): sid_elements = sid_str.split('-') sid_elements.remove('S') sub_authority_count = len(sid_elements) - 2 sid_struct = SID(ptr_size, sub_authority_count) sid_struct.Revision = int(sid_elements[0]) sid_struct.SubAuthorityCount = sub_authority_count sid_struct.IdentifierAuthority = int(sid_elements[1]).to_bytes(6, 'big') sub_authorities = sid_elements[2:] for i in range(len(sub_authorities)): sid_struct.SubAuthority[i] = int(sub_authorities[i]) return sid_struct
null
376
from speakeasy.struct import EmuStruct, Ptr import ctypes as ct def get_define_value(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or k != define: continue if prefix: if k.startswith(prefix): return v else: return v
null
377
from speakeasy.struct import EmuStruct, Ptr import ctypes as ct def get_flag_defines(flags, prefix=''): defs = [] for k, v in globals().items(): if not isinstance(v, int): continue if v & flags: if prefix and k.startswith(prefix): defs.append(k) return defs
null
378
from speakeasy.struct import EmuStruct, Ptr import ctypes as ct def get_define_int(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k
null
379
from speakeasy.struct import EmuStruct, Ptr import ctypes as ct def get_flag_defines(flags, prefix=''): defs = [] for k, v in globals().items(): if not isinstance(v, int): continue if v == flags: if prefix and k.startswith(prefix): defs.append(k) return defs def get_windowhook_flags(flags): return get_flag_defines(flags, prefix='WH_')
null
380
import uuid from speakeasy.struct import EmuStruct, Ptr def get_define_str(define, prefix=''): for k, v in globals().items(): if not isinstance(v, str) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k def get_clsid(define): return get_define_str(define, prefix='CLSID_')
null
381
import uuid from speakeasy.struct import EmuStruct, Ptr def get_define_str(define, prefix=''): for k, v in globals().items(): if not isinstance(v, str) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k def get_iid(define): return get_define_str(define, prefix='IID_')
null
382
import uuid from speakeasy.struct import EmuStruct, Ptr def get_define_int(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k def get_rpc_authlevel(define): return get_define_int(define, prefix='RPC_C_AUTHN_LEVEL_')
null
383
import uuid from speakeasy.struct import EmuStruct, Ptr def get_define_int(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k def get_rcp_implevel(define): return get_define_int(define, prefix='RPC_C_IMP_LEVEL_')
null
384
import uuid from speakeasy.struct import EmuStruct, Ptr def convert_guid_bytes_to_str(guid_bytes): u = uuid.UUID(bytes_le=guid_bytes) return ('{%s}' % u).upper()
null
385
def get_define(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k
null
386
from speakeasy.struct import EmuStruct, Ptr import ctypes as ct MIB_IF_TYPE_ETHERNET = 6 def get_adapter_type(type_str): if type_str == 'ethernet': return MIB_IF_TYPE_ETHERNET
null
387
from speakeasy.struct import Enum def get_access_defines(flags): defs = [] accesses = ('DELETE', 'READ_CONTROL', 'WRITE_DAC', 'WRITE_OWNER', 'SYNCHRONIZE', 'GENERIC_READ', 'GENERIC_WRITE', 'GENERIC_EXECUTE', 'GENERIC_ALL') for k, v in [(k, v) for k, v in globals().items() if k in accesses]: if isinstance(v, int): if v & flags: defs.append(k) return defs
null
388
from speakeasy.struct import Enum def get_flag_defines(flags, prefix=''): defs = [] for k, v in globals().items(): if isinstance(v, int): if v & flags: if prefix: if k.startswith(prefix): defs.append(k) else: defs.append(k) return defs def get_file_access_defines(flags): defs = get_flag_defines(flags, 'FILE_') defs = [d for d in defs if d.startswith(('FILE_READ', 'FILE_WRITE', 'FILE_DELETE', 'FILE_APPEND', 'FILE_EXECUTE'))] return defs
null
389
from speakeasy.struct import Enum def get_const_defines(const, prefix=''): defs = [] for k, v in globals().items(): if isinstance(v, int): if v == const: if prefix: if k.startswith(prefix): defs.append(k) else: defs.append(k) return defs def get_create_disposition(disp): defs = get_const_defines(disp, 'FILE_') defs = [d for d in defs if not d.startswith('FILE_SHARE')] ret = 0 if len(defs): ret = defs[0] return ret
null
390
import ctypes as ct from speakeasy.struct import EmuStruct, Ptr def get_const_defines(flags, prefix=''): def get_flag_defines(flags): return get_const_defines(flags, prefix='INTERNET_FLAG')
null
391
import ctypes as ct from speakeasy.struct import EmuStruct, Ptr def get_option_define(opt): for k, v in globals().items(): if k.startswith('INTERNET_OPTION_') and v == opt: return k
null
392
import ctypes as ct from speakeasy.struct import EmuStruct, Ptr def get_const_defines(flags, prefix=''): defs = [] for k, v in globals().items(): if isinstance(v, int): if v & flags: if prefix: if k.startswith(prefix): defs.append(k) else: defs.append(k) return defs def get_header_info_winhttp(flags): return get_const_defines(flags, prefix='WINHTTP_ADDREQ_')
null
393
import ctypes as ct from speakeasy.struct import EmuStruct, Ptr def get_header_query(opt): for k, v in globals().items(): if k.startswith('WINHTTP_QUERY_') and v == opt: return k
null
394
from speakeasy.struct import EmuStruct, Enum import ctypes as ct def get_flag_value(flag): return globals().get(flag)
null
395
from speakeasy.struct import EmuStruct, Enum import ctypes as ct def get_defines(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k def get_value_type(define): return get_defines(define, prefix='REG_')
null
396
from speakeasy.struct import EmuStruct, Enum import ctypes as ct def get_defines(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k def get_hkey_type(define): return get_defines(define, prefix='HKEY_')
null
397
def get_flag_defines(flags, prefix=''): defs = [] for k, v in globals().items(): if not isinstance(v, int): continue if v & flags: if prefix and k.startswith(prefix): defs.append(k) return defs
null
398
def get_define(define, prefix=''): def get_addr_family(define): return get_define(define, prefix='AF_')
null
399
def get_define(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k def get_sock_type(define): return get_define(define, prefix='SOCK_')
null
400
def get_define(define, prefix=''): for k, v in globals().items(): if not isinstance(v, int) or v != define: continue if prefix: if k.startswith(prefix): return k else: return k def get_proto_type(define): return get_define(define, prefix='IPPROTO_')
null
401
import os import sys import cmd import shlex import fnmatch import logging import binascii import argparse import traceback import hexdump import speakeasy import speakeasy.winenv.arch as e_arch from speakeasy.errors import SpeakeasyError The provided code snippet includes necessary dependencies for implementing the `get_logger` function. Write a Python function `def get_logger()` to solve the following problem: Get the default logger for speakeasy Here is the function: def get_logger(): """ Get the default logger for speakeasy """ logger = logging.getLogger('sedbg') if not logger.handlers: sh = logging.StreamHandler() logger.addHandler(sh) logger.setLevel(logging.INFO) return logger
Get the default logger for speakeasy