processing.py 4.72 KB
Newer Older
matthmey's avatar
matthmey committed
1
2
3
4
from ..global_config import get_setting
from ..core.graph import StuettNode

import dask
matthmey's avatar
matthmey committed
5
6
import numpy as np
import xarray as xr
7
8
import scipy.signal
import pandas as pd
matthmey's avatar
matthmey committed
9
import lttb
matthmey's avatar
matthmey committed
10
11
12


class MinMaxDownsampling(StuettNode):
matthmey's avatar
matthmey committed
13
14
15
    def __init__(self, rate=1):
        # since we always choose two values (min and max) per bucket the
        # the internal downsampling rate must be of factor two larger than
matthmey's avatar
matthmey committed
16
        # the effective (and desired) downsampling rate
matthmey's avatar
matthmey committed
17
18
        self.rate = rate * 2

19
20
    def forward(self, data=None, request=None):
        rolling = data.rolling(time=self.rate, stride=self.rate)
matthmey's avatar
matthmey committed
21

matthmey's avatar
matthmey committed
22
23
        # x_min = rolling.construct("buckets", stride=self.rate).min("time").dropna('time')
        # x_max = rolling.construct("buckets", stride=self.rate).max("time").dropna('time')
matthmey's avatar
matthmey committed
24

matthmey's avatar
matthmey committed
25
26
        x_min = rolling.min().dropna("time")
        x_max = rolling.max().dropna("time")
matthmey's avatar
matthmey committed
27

matthmey's avatar
matthmey committed
28
29
30
        x_ds = xr.concat(
            [x_min, x_max], "time"
        )  # TODO: better interleave instead of concat
matthmey's avatar
matthmey committed
31

matthmey's avatar
matthmey committed
32
33
34
        x_ds = x_ds.sortby("time")  # TODO: try to avoid this by using interleaving

        return x_ds
matthmey's avatar
matthmey committed
35

matthmey's avatar
matthmey committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class LTTBDownsampling(StuettNode):
    def __init__(self, rate=1):
        # Based on and many thanks to https://github.com/javiljoen/lttb.py
        self.rate = rate

    def forward(self, data=None, request=None):
        rolling = data.rolling(time=self.rate, stride=self.rate)        #TODO: make this not dependend on time dimension
        print(rolling)
        n_out = data.sizes['time']//self.rate
        # print(data.sizes['time']//self.rate)

        data_bins = rolling.construct("buckets")
        return

        mean = rolling.mean()
        print(mean)
        out = []
        for i, (index, roll) in enumerate(rolling):
            print(i)
            if i == 0:
                prev = data[0]
            
            print(prev)
            print(mean.sel(time=index))
            print(roll)

            prev = roll


        # x_min = rolling.min().dropna("time")
        small_data = lttb.downsample(data, n_out=20)

        return x_ds

matthmey's avatar
matthmey committed
70
71
72
73

class Downsampling(StuettNode):
    def __init__(self):
        raise NotImplementedError()
matthmey's avatar
matthmey committed
74
        # TODO: high level downsampling node which uses one of the other downsampling
matthmey's avatar
matthmey committed
75
        #       classes depending on the user request
matthmey's avatar
matthmey committed
76
        pass
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112


class Spectrogram(StuettNode):
    def __init__(
        self,
        nfft=2048,
        stride=1024,
        dim=None,
        sampling_rate=None,
        window=("tukey", 0.25),
        detrend="constant",
        return_onesided=True,
        scaling="density",
        mode="psd",
    ):
        super().__init__(
            nfft=nfft,
            stride=stride,
            dim=dim,
            sampling_rate=sampling_rate,
            window=window,
            detrend=detrend,
            return_onesided=return_onesided,
            scaling=scaling,
            mode=mode,
        )

    def forward(self, data=None, request=None):
        config = self.config.copy()  # TODO: do we need a deep copy?
        if request is not None:
            config.update(request)

        if config["dim"] is None:
            config["dim"] = data.dims[-1]

        axis = data.get_axis_num(config["dim"])
matthmey's avatar
matthmey committed
113
           
114
        if config["sampling_rate"] is None:
matthmey's avatar
matthmey committed
115
116
117
118
119
            if 'sampling_rate' not in data.attrs:
                raise RuntimeError("Please provide a sampling_rate attribute "
                                   "to your config or your input data")
            else:
                config["sampling_rate"] = data.attrs["sampling_rate"]
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145

        samples = data.values
        noverlap = config["nfft"] - config["stride"]

        freqs, spectrum_time, spectrum = scipy.signal.spectrogram(
            samples,
            nfft=config["nfft"],
            nperseg=config["nfft"],
            noverlap=noverlap,
            fs=config["sampling_rate"],
            axis=axis,
            detrend=config["detrend"],
            scaling=config["scaling"],
            return_onesided=config["return_onesided"],
            mode=config["mode"],
            window=config["window"],
        )

        # TODO: check if this is what we want. it's: the earliest timestamp of input + the delta computed by scipy
        ds_coords = pd.to_datetime(
            pd.to_datetime(data[config["dim"]][0].values)
            + pd.to_timedelta(spectrum_time, "s")
        ).tz_localize(
            None
        )  # TODO: change when xarray #3291 is fixed

matthmey's avatar
matthmey committed
146
147


148
        # Create a new DataArray for the spectogram
matthmey's avatar
matthmey committed
149
150

        dims = data.dims[:axis] + ("frequency",) + data.dims[axis+1:] + (config["dim"],)
151
        coords = dict(data.coords)
matthmey's avatar
matthmey committed
152
        coords.update({"frequency": ("frequency", freqs), config["dim"]: ds_coords})       
153
154
155
        dataarray = xr.DataArray(spectrum, dims=dims, coords=coords)

        return dataarray