aboutsummaryrefslogtreecommitdiffhomepage
path: root/pyecsca/sca/stacked_traces/stacked_traces.py
blob: 3c367e997c722313f0a40b87d931a0f1a9849978 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import numpy as np
from public import public
from typing import Any, Mapping, Sequence, Optional

from pyecsca.sca.trace_set.base import TraceSet


@public
class StackedTraces:
    """Samples of multiple traces and metadata"""

    meta: Mapping[str, Any]
    samples: np.ndarray

    # TODO: Split metadata into common and per-trace
    def __init__(
        self, samples: np.ndarray, meta: Optional[Mapping[str, Any]] = None
    ) -> None:
        if meta is None:
            meta = {}
        self.meta = meta
        self.samples = samples

    @classmethod
    def fromarray(
        cls, traces: Sequence[np.ndarray], meta: Optional[Mapping[str, Any]] = None
    ) -> "StackedTraces":
        if meta is None:
            meta = {}
        ts = list(traces)
        min_samples = min(map(len, ts))
        for i, t in enumerate(ts):
            ts[i] = t[:min_samples]
        stacked = np.stack(ts)
        return cls(stacked, meta)

    @classmethod
    def fromtraceset(cls, traceset: TraceSet) -> "StackedTraces":
        traces = [t.samples for t in traceset]
        return cls.fromarray(traces)

    def __len__(self):
        return self.samples.shape[0]

    def __getitem__(self, index):
        return self.samples[index]

    def __iter__(self):
        yield from self.samples