To receive notifications about scheduled maintenance, please subscribe to the mailing-list gitlab-operations@sympa.ethz.ch. You can subscribe to the mailing-list at https://sympa.ethz.ch

test_management.py 9.2 KB
Newer Older
matthmey's avatar
black    
matthmey committed
1
"""MIT License
matthmey's avatar
matthmey committed
2

matthmey's avatar
matthmey committed
3
4
Copyright (c) 2019, Swiss Federal Institute of Technology (ETH Zurich), Matthias Meyer

matthmey's avatar
matthmey committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
matthmey's avatar
black    
matthmey committed
22
SOFTWARE."""
matthmey's avatar
matthmey committed
23

24
25
26
import stuett
from tests.stuett.sample_data import *

matthmey's avatar
matthmey committed
27
28
29
30
31
import datetime as dt
import pandas as pd
import base64
import os

32
import pytest
matthmey's avatar
matthmey committed
33
34
35
import zarr
from pathlib import Path

matthmey's avatar
matthmey committed
36
37
test_data_dir = Path(__file__).absolute().parent.joinpath("..", "data")
stuett.global_config.set_setting("user_dir", test_data_dir.joinpath("user_dir/"))
matthmey's avatar
matthmey committed
38

39
40
41
42
43
44
45
46
47
48
49
50
51

class TestSeismicSource(object):
    @pytest.mark.slow
    def test_seismic_source(self):
        # first test without config
        seismic_source = stuett.data.SeismicSource()

        # with config
        seismic_source = stuett.data.SeismicSource(config)

    @pytest.mark.slow
    def test_call(self):
        # first test without config
52
        seismic_source = stuett.data.SeismicSource(use_arclink=True)
53
54
55

        x = seismic_source(config)
        x = x.compute()
matthmey's avatar
matthmey committed
56
57
58
59

        print(x)
        return

matthmey's avatar
matthmey committed
60
        assert x.mean() == -55.73599312780376
61
62

        # with config
matthmey's avatar
matthmey committed
63
        seismic_source = stuett.data.SeismicSource(config, use_arclink=True)
64

matthmey's avatar
matthmey committed
65
        request = {"start_time": start_time + offset, "end_time": end_time + offset}
66
67
        x = seismic_source(request)
        x = x.compute()
matthmey's avatar
matthmey committed
68
        assert x.mean() == -61.23491399790934
69

matthmey's avatar
matthmey committed
70
        # TODO: make test to compare start_times
71

matthmey's avatar
matthmey committed
72

matthmey's avatar
matthmey committed
73
@pytest.mark.slow
74
75
def test_gsn():
    # test_data = pd.read_csv(test_data_dir + 'matterhorn_27_temperature_rock.csv',index_col='time')
matthmey's avatar
matthmey committed
76
77
78
79
80
    gsn_node = stuett.data.GSNDataSource(
        deployment="matterhorn", position=30, vsensor="temperature_rock"
    )
    x = gsn_node({"start_time": "2017-07-01", "end_time": "2017-07-02"})

matthmey's avatar
matthmey committed
81
    assert x.sum() == 1600959.34
matthmey's avatar
matthmey committed
82
    # TODO: proper testing
83
84


matthmey's avatar
matthmey committed
85
# test_gsn()
86
87


88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
def test_delayed():
    filename = Path(test_data_dir).joinpath(
        "timeseries", "MH30_temperature_rock_2017.csv"
    )
    node = stuett.data.CsvSource(filename)

    x = node(delayed=True)
    from dask.delayed import Delayed

    assert isinstance(x, Delayed)

    x = x.compute()

    non_delayed = node(delayed=False)

    assert x.mean() == 0.16201109532441677
    assert non_delayed.mean() == 0.16201109532441677


matthmey's avatar
matthmey committed
107
108
109
def test_freeze():
    # with config
    # seismic_source = stuett.data.SeismicSource(config,use_arclink=True)
110
111
112
    filename = Path(test_data_dir).joinpath(
        "timeseries", "MH30_temperature_rock_2017.csv"
    )
matthmey's avatar
matthmey committed
113
114
    node = stuett.data.CsvSource(filename)

115
116
    user_dir = stuett.global_config.get_setting("user_dir")
    store_name = user_dir.joinpath("frozen", "test.zarr")
matthmey's avatar
matthmey committed
117
    import shutil
118
119

    shutil.rmtree(store_name, ignore_errors=True)
matthmey's avatar
matthmey committed
120
121
122
123
124

    store = zarr.DirectoryStore(store_name)
    # account_name = stuett.global_config.get_setting('azure')['account_name'] if stuett.global_config.setting_exists('azure') else "storageaccountperma8980"
    # account_key  = stuett.global_config.get_setting('azure')['account_key']  if stuett.global_config.setting_exists('azure')  else None
    # store = zarr.ABSStore(container='hackathon-on-permafrost', prefix='dataset/test.zarr', account_name=account_name, account_key=account_key, blob_service_kwargs={})
matthmey's avatar
matthmey committed
125

matthmey's avatar
matthmey committed
126
    freezer = stuett.data.Freezer(store,'testgroup','time',pd.to_timedelta('5 hours'))
matthmey's avatar
matthmey committed
127

matthmey's avatar
matthmey committed
128
129
130
131
132
    request = {"start_time": "2017-07-01", "end_time": "2017-07-04"}
    x = node(delayed=True)
    x = freezer(x,delayed=True)
    x = stuett.core.configuration(x, request)
    print('x1',x.compute())
matthmey's avatar
matthmey committed
133

matthmey's avatar
matthmey committed
134
135
136
137
138
139
140
141

    # trying to load the same request but from disk
    x = freezer(delayed=True)
    x = stuett.core.configuration(x, request)
    print("from disk", x.compute())
    exit()

    # Note there is a gap
142
    request = {"start_time": "2017-09-01", "end_time": "2017-10-01"}
matthmey's avatar
matthmey committed
143
144
145
146
147
    x = node(delayed=True)
    x = freezer(x,delayed=True)
    x = stuett.core.configuration(x, request)
    print('x2',x.compute())
    exit()
matthmey's avatar
matthmey committed
148

matthmey's avatar
matthmey committed
149
    # x = freezer()
matthmey's avatar
matthmey committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    # Load everything that was saved (but not the gap)
    request = {"start_time": "2017-07-01 16:00:00", "end_time": "2017-10-01"}
    x = freezer(request=request)
    print("x1 and x2", x)


    # Now add somethinge before the time frame and with a gap
    request = {"start_time": "2017-05-01", "end_time": "2017-05-31"}
    x = node(request=request)
    x = freezer(x)
    print('before',x)

    # Load everything that was saved (but not the gap)
    request = {"start_time": "2017-05-01", "end_time": "2017-10-01"}
    x = freezer(request=request)
    print("x1 and x2", x)
    print(x['frozen'].values.shape)
matthmey's avatar
matthmey committed
167

168
169
170
    shutil.rmtree(store_name, ignore_errors=True)


matthmey's avatar
matthmey committed
171
test_freeze()
matthmey's avatar
matthmey committed
172
173
174
175


def test_image_filenames():
    # first test without config
matthmey's avatar
matthmey committed
176
    node = stuett.data.MHDSLRFilenames(base_directory=test_data_dir.joinpath("MHDSLR"))
matthmey's avatar
matthmey committed
177
178
179
180
181
182
183
184
185
186
187
188

    start_time = dt.datetime(2017, 8, 6, 9, 56, 12, tzinfo=dt.timezone.utc)
    end_time = dt.datetime(2017, 8, 6, 10, 14, 10, tzinfo=dt.timezone.utc)

    offset = dt.timedelta(days=1)
    config_0 = {
        "channel": channels[0],
        "station": stations[0],
        "start_time": start_time,
        "end_time": end_time,
    }

189
    data = node(request=config_0)
matthmey's avatar
matthmey committed
190

191
    config_1 = config.copy()
matthmey's avatar
matthmey committed
192
    # this should return and empty list
193
194
195
196
197
198
199
200
201
202
203
    data = node(config_1)

    # Test if we do not provide a end_time
    del config_0["end_time"]
    data = node(config_0)

    del config_1["end_time"]
    data = node(config_1)

    config_1["start_time"] = dt.datetime(2018, 8, 6, 20, 0, 0, tzinfo=dt.timezone.utc)
    data = node(config_1)
matthmey's avatar
matthmey committed
204
205


matthmey's avatar
matthmey committed
206
207
208
# test_image_filenames()


matthmey's avatar
matthmey committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def test_mhdslrimage():
    base_dir = Path(test_data_dir).joinpath("MHDSLR")
    node = stuett.data.MHDSLRImages(base_directory=base_dir)

    start_time = dt.datetime(2017, 8, 6, 9, 50, 12, tzinfo=dt.timezone.utc)
    end_time = dt.datetime(2017, 8, 6, 10, 12, 10, tzinfo=dt.timezone.utc)

    offset = dt.timedelta(days=1)
    config = {
        "start_time": start_time,
        "end_time": end_time,
    }

    data = node(config)

    config["output_format"] = "base64"
    data = node(config)

    from PIL import Image

matthmey's avatar
matthmey committed
229
230
231
    with open(base_dir.joinpath("2017-08-06", "20170806_095212.JPG"), "rb") as image_file:
        img_base64 = base64.b64encode(image_file.read())
        assert data[0].values == img_base64
232

matthmey's avatar
matthmey committed
233
234
235
236
237
238
239
240
241
242
243
244
    # Check a period where there is no image
    start_time = dt.datetime(2017, 8, 6, 9, 55, 12, tzinfo=dt.timezone.utc)
    end_time = dt.datetime(2017, 8, 6, 10, 10, 10, tzinfo=dt.timezone.utc)
    config = {
        "start_time": start_time,
        "end_time": end_time,
    }
    data = node(config)

    # print(data)
    assert data.shape == (0, 0, 0, 0)

245

matthmey's avatar
matthmey committed
246
247
248
249
250
251
252
253
254
255
# test_mhdslrimage()


def test_csv():
    filename = Path(test_data_dir).joinpath(
        "timeseries", "MH30_temperature_rock_2017.csv"
    )
    node = stuett.data.CsvSource(filename)
    x = node()

256
257
    assert len(x) == 8760
    assert x.mean() == 0.16201109532441677
matthmey's avatar
matthmey committed
258

259
    # Test with store
matthmey's avatar
black    
matthmey committed
260
    directory = Path(test_data_dir).joinpath("timeseries")
261
262
    store = stuett.DirectoryStore(directory)
    filename = "MH30_temperature_rock_2017.csv"
matthmey's avatar
black    
matthmey committed
263
    node = stuett.data.CsvSource(filename=filename, store=store)
264
    x = node()
matthmey's avatar
matthmey committed
265

266
267
268
269
    assert len(x) == 8760
    assert x.mean() == 0.16201109532441677

    # TODO: test with start and end time
matthmey's avatar
black    
matthmey committed
270
271


matthmey's avatar
matthmey committed
272
# test_csv()
matthmey's avatar
matthmey committed
273

matthmey's avatar
black    
matthmey committed
274

matthmey's avatar
matthmey committed
275
276
277
278
def test_annotations():
    filename = Path(test_data_dir).joinpath("annotations", "boundingbox_timeseries.csv")
    node = stuett.data.BoundingBoxAnnotation(filename)

279
280
    targets = node()

matthmey's avatar
black    
matthmey committed
281
    assert targets[0] == "no_visibility"
282

matthmey's avatar
matthmey committed
283
284
285
286
287
    filename = Path(test_data_dir).joinpath("annotations", "boundingbox_images.csv")
    node = stuett.data.BoundingBoxAnnotation(filename)

    targets = node()

288
289
    targets = targets.swap_dims({"index": "start_time"})
    targets = targets.sortby("start_time")
matthmey's avatar
matthmey committed
290

matthmey's avatar
black    
matthmey committed
291
292
293
    assert targets.sel(start_time="2017-08-04T08:12:11") == "mountaineer"
    assert targets["start_y"][1] == 16

294

matthmey's avatar
matthmey committed
295
296
297
# test_annotations()


298
299
300
def test_datasets():
    filename = Path(test_data_dir).joinpath("annotations", "boundingbox_timeseries.csv")
    label = stuett.data.BoundingBoxAnnotation(filename)
matthmey's avatar
matthmey committed
301

302
303
304
305
    filename = Path(test_data_dir).joinpath(
        "timeseries", "MH30_temperature_rock_2017.csv"
    )
    data = stuett.data.CsvSource(filename)
matthmey's avatar
black    
matthmey committed
306

307
308
309
310
311
312
    dataset = stuett.data.SegmentedDataset(
        data,
        label,
        dataset_slice={"time": slice("2017-08-01", "2017-08-03")},
        batch_dims={"time": pd.to_timedelta(24, "m")},
    )
matthmey's avatar
matthmey committed
313

matthmey's avatar
matthmey committed
314
    # x = dataset[0]
matthmey's avatar
matthmey committed
315
316


matthmey's avatar
matthmey committed
317
# test_datasets()