-
Notifications
You must be signed in to change notification settings - Fork 3
/
conftest.py
409 lines (317 loc) · 11.6 KB
/
conftest.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
113
114
115
116
117
118
119
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
import os
import pytest
from pytest import fixture
from zipfile import ZipFile
import pandas as pd
from spacekit.analyzer.explore import HstCalPlots, HstSvmPlots
from spacekit.analyzer.scan import HstSvmScanner, HstCalScanner, import_dataset
from spacekit.extractor.load import load_datasets, extract_file
from spacekit.skopes.jwst.cal.config import KEYPAIR_DATA
from spacekit.preprocessor.scrub import JwstCalScrubber
TESTED_VERSIONS = {}
try:
from spacekit import __version__ as version
except ImportError:
version = "unknown"
TESTED_VERSIONS["spacekit"] = version
# Uncomment and customize the following lines to add/remove entries
# from the list of packages for which version numbers are displayed
# when running the tests.
# PYTEST_HEADER_MODULES = {}
# PYTEST_HEADER_MODULES['astropy'] = 'astropy'
# PYTEST_HEADER_MODULES.pop('Matplotlib')
# PYTEST_HEADER_MODULES.pop('Pandas')
# PYTEST_HEADER_MODULES.pop('h5py')
pytest_plugins = [
'tests.data_plugin'
]
class Config:
def __init__(self, env):
SUPPORTED_ENVS = ["svm", "hstcal", "jwstcal"]
self.env = env
if env.lower() not in SUPPORTED_ENVS:
raise Exception(
f"{env} is not a supported environment (supported envs: {SUPPORTED_ENVS})"
)
self.data_path = {
"svm": os.path.join(f"tests/data/{env}/data.zip"),
"hstcal": os.path.join(f"tests/data/{env}/data.zip"),
"jwstcal": os.path.join(f"tests/data/{env}/data.zip"),
}[env]
self.kwargs = {
"svm": dict(index_col="index"),
"hstcal": dict(index_col="ipst"),
"jwstcal": dict(index_col="Dataset")
}[env]
self.decoder = {
"svm": {"det": {0: "hrc", 1: "ir", 2: "sbc", 3: "uvis", 4: "wfc"}},
"hstcal": {"instr": {0: "acs", 1: "cos", 2: "stis", 3: "wfc3"}},
"jwstcal": KEYPAIR_DATA,
}[env]
self.labeled = {
"svm": "tests/data/svm/train/training.csv",
"hstcal": "tests/data/hstcal/train/training.csv",
"jwstcal": "tests/data/jwstcal/train/training.csv",
}[env]
self.unlabeled = {
"svm": "tests/data/svm/predict/unlabeled.csv",
"hstcal": "tests/data/hstcal/predict/unlabeled.csv",
"jwstcal" : "tests/data/jwstcal/predict/unlabeled.csv"
}[env]
self.norm_cols = {
"svm": [
"numexp",
"rms_ra",
"rms_dec",
"nmatches",
"point",
"segment",
"gaia",
],
"hstcal": ["n_files", "total_mb"],
"jwstcal": [
'offset',
'max_offset',
'mean_offset',
'sigma_offset',
'err_offset',
'sigma1_mean'
],
}[env]
self.rename_cols = {
"svm": "_scl",
"hstcal": ["x_files", "x_size"],
"jwstcal": None
}[env]
self.enc_cols = {
"svm": ["det", "wcs", "cat"],
"hstcal": [
"drizcorr",
"pctecorr",
"crsplit",
"subarray",
"detector",
"dtype",
"instr",
],
"jwstcal": [
"instr",
"detector",
"visitype",
"filter",
"pupil",
"channel",
"subarray"
],
}[env]
self.tx_file = {
"svm": "tests/data/svm/tx_data.json",
"hstcal": "tests/data/hstcal/tx_data.json",
"jwstcal": "tests/data/jwstcal/tx_data-{}.json"
}[env]
self.visits = {
"svm": [],
"hstcal": {
"asn": ["j8zs05020", "ic0k06010", "la8mffg5q", "oc3p011i0"],
"svm": [],
},
"jwstcal": ["jw02732"],
}[env]
def pytest_addoption(parser):
parser.addoption("--env", action="store", default=None, help="Environment to run tests against")
@fixture(scope="session")
def env(request):
return request.config.getoption("--env")
@fixture(scope="session", params=["hstcal", "svm"])
def skope(request):
env_param = request.config.getoption("--env")
if env_param is not None and request.param != env_param:
pytest.skip(reason="skipping param based on --env")
else:
return Config(request.param)
def check_skope(skope, param):
if skope.env != param:
pytest.skip(reason="skipping based on skope param")
@fixture(scope="session")
def test_data(request):
return request.config.getoption("data_path")
@fixture(scope="session")
def res_data_path(test_data, skope):
skope_data = os.path.join(test_data, skope.env, "data")
if not os.path.exists(skope_data):
with ZipFile(skope.data_path, "r") as z:
z.extractall(os.path.dirname(skope_data))
return skope_data
@fixture(scope="session")
def df_ncols(skope):
fname = skope.labeled
X_cols = skope.norm_cols + skope.enc_cols
df = load_datasets([fname], index_col=skope.kwargs["index_col"], column_order=X_cols)
ncols = [i for i, c in enumerate(df.columns) if c in skope.norm_cols]
return (df, ncols)
@fixture(scope="session")
def scanner(skope, res_data_path):
if skope.env == "svm":
scanner = HstSvmScanner(perimeter=f"{res_data_path}/20??-*-*-*", primary=-1)
elif skope.env == "hstcal":
scanner = HstCalScanner(perimeter=f"{res_data_path}/20??-*-*-*", primary=-1)
else:
pytest.skip(reason="JWST does not yet have a scanner.")
scanner.exp = skope.env
return scanner
@fixture(scope="session")
def explorer(skope, res_data_path):
fname = res_data_path
df = import_dataset(filename=fname, kwargs=skope.kwargs, decoder=skope.decoder)
if skope.env == "svm":
hst = HstSvmPlots(df)
elif skope.env == "hstcal":
hst = HstCalPlots(df)
elif skope.env == "jwstcal":
pytest.skip(reason="TODO")
hst.env = skope.env
return hst
@fixture(scope="session")
def labeled_dataset(skope):
return skope.labeled
@fixture(scope="session") # session
def unlabeled_dataset(skope):
return skope.unlabeled
# SVM PREP
@fixture(scope="session") # "ibl738.tgz"
def single_visit_path(tmp_path_factory):
visit_path = os.path.relpath("tests/data/svm/prep/singlevisits.tgz")
basepath = tmp_path_factory.getbasetemp()
extract_file(visit_path, dest=basepath)
dname = os.path.basename(visit_path.split(".")[0])
visit_path = os.path.join(basepath, dname)
return visit_path
@fixture(scope="function")
def img_outpath(tmp_path):
return os.path.join(tmp_path, "img")
# # SVM PREDICT
@fixture(scope="session", params=["img.tgz", "img_pred.npz"])
def svm_pred_img(request, tmp_path_factory):
img_path = os.path.join("tests/data/svm/predict", request.param)
if img_path.split(".")[-1] == "tgz":
basepath = tmp_path_factory.getbasetemp()
extract_file(img_path, dest=basepath)
fname = os.path.basename(img_path.split(".")[0])
img_path = os.path.join(basepath, fname)
return img_path
# # SVM TRAIN
@fixture(scope="session", params=["img.tgz", "img_data.npz"])
def svm_train_img(request, tmp_path_factory):
img_path = os.path.join("tests/data/svm/train", request.param)
fname = os.path.basename(img_path.split(".")[0])
if img_path.split(".")[-1] == "tgz":
basepath = tmp_path_factory.getbasetemp()
extract_file(img_path, dest=basepath)
img_path = os.path.join(basepath, fname)
return img_path
@fixture(scope="function")
def svm_train_npz():
return "tests/data/svm/train/img_data.npz"
# GENERATOR: DRAW
@fixture(params=["single_reg.csv"])
def draw_mosaic_fname(request):
return os.path.join("tests/data/svm/prep", request.param)
@fixture(params=["*", "ibl*", ""])
def draw_mosaic_pattern(request):
return request.param
# PREPROCESSOR: SCRUB
@fixture(scope="module")
def raw_csv_file():
return "tests/data/svm/prep/single_scrub.csv"
@fixture(scope="module")
def raw_svm_data(raw_csv_file):
data = pd.read_csv(raw_csv_file, index_col="index")
return data
@fixture(scope="function")
def h5_data():
return "tests/data/svm/prep/single_reg"
@fixture(scope="function")
def scrubbed_svm_file():
return "tests/data/svm/prep/scrubbed_cols.csv"
@fixture(scope="function")
def scrubbed_svm_data(scrubbed_svm_file):
data = pd.read_csv(scrubbed_svm_file, index_col="index")
return data
@fixture(scope="function")
def scraped_fits_file():
return "tests/data/svm/prep/scraped_fits.csv"
@fixture(scope="function")
def scraped_fits_data(scraped_fits_file):
data = pd.read_csv(scraped_fits_file, index_col="index")
return data
@fixture(scope="function")
def scraped_mast_file():
return "tests/data/svm/prep/scraped_mast.csv"
@fixture(scope="function")
def hst_cal_predict_visits():
return {
"asn": ["j8zs05020", "ic0k06010", "la8mffg5q", "oc3p011i0"]
}
@fixture(scope="function")
def jwstcal_input_path():
return "tests/data/jwstcal/predict/inputs"
@fixture(scope="module")
def jwstcal_scrub_filepath():
return "tests/data/jwstcal/scrub/{}-inputs.csv"
@fixture(scope="module")
def jwst_cal_img_data(jwstcal_scrub_filepath):
data = pd.read_csv(jwstcal_scrub_filepath.format('img'), index_col="Dataset")
data['PROGRAM'] = data['PROGRAM'].apply(lambda x: '{:0>5}'.format(x))
data['OBSERVTN'] = data['OBSERVTN'].apply(lambda x: '{:0>3}'.format(x))
return data
@fixture(scope="function")
def jwst_cal_wfsc_data(jwstcal_scrub_filepath):
data = pd.read_csv(jwstcal_scrub_filepath.format('wfsc'), index_col="Dataset")
data['PROGRAM'] = data['PROGRAM'].apply(lambda x: '{:0>5}'.format(x))
data['OBSERVTN'] = data['OBSERVTN'].apply(lambda x: '{:0>3}'.format(x))
return data
@fixture(scope="module")
def jwst_cal_spec_data(jwstcal_scrub_filepath):
data = pd.read_csv(jwstcal_scrub_filepath.format('spec'), index_col="Dataset")
data['PROGRAM'] = data['PROGRAM'].apply(lambda x: '{:0>5}'.format(x))
data['OBSERVTN'] = data['OBSERVTN'].apply(lambda x: '{:0>3}'.format(x))
return data
@fixture(scope="module")
def jwst_cal_tac_data(jwstcal_scrub_filepath):
data = pd.read_csv(jwstcal_scrub_filepath.format('tac'), index_col="Dataset")
data['PROGRAM'] = data['PROGRAM'].apply(lambda x: '{:0>5}'.format(x))
data['OBSERVTN'] = data['OBSERVTN'].apply(lambda x: '{:0>3}'.format(x))
return data
@fixture(scope="module")
def jwst_cal_img_df(jwst_cal_img_data):
scrubber = JwstCalScrubber(
"tmp",
data=jwst_cal_img_data,
mode='df',
encoding_pairs=KEYPAIR_DATA
)
df = pd.DataFrame.from_dict(scrubber.imgpix, orient='index')
df['name'] = ['_'.join([n.split('_')[0]] + n.split('_')[2:]) for n in list(df.index)]
return df
@fixture(scope="module")
def jwst_cal_spec_df(jwst_cal_spec_data):
scrubber = JwstCalScrubber(
"tmp",
data=jwst_cal_spec_data,
mode='df',
encoding_pairs=KEYPAIR_DATA
)
df = pd.DataFrame.from_dict(scrubber.specpix, orient='index')
df['name'] = ['_'.join([n.split('_')[0]] + n.split('_')[2:]) for n in list(df.index)]
return df
@fixture(scope="module")
def jwst_cal_tac_df(jwst_cal_tac_data):
scrubber = JwstCalScrubber(
"tmp",
data=jwst_cal_tac_data,
mode='df',
encoding_pairs=KEYPAIR_DATA
)
df = pd.DataFrame.from_dict(scrubber.tacpix, orient='index')
df['name'] = ['_'.join([n.split('_')[0]] + n.split('_')[2:]) for n in list(df.index)]
return df