_dispatcher.py 18.6 KB
Newer Older
BO ZHANG's avatar
BO ZHANG committed
1
import numpy as np
BO ZHANG's avatar
BO ZHANG committed
2
3
4
5
import joblib
from astropy import table
from tqdm import trange

BO ZHANG's avatar
BO ZHANG committed
6
7
from .._csst import csst

BO ZHANG's avatar
BO ZHANG committed
8

9
10
TQDM_KWARGS = dict(unit="task", dynamic_ncols=False)

BO ZHANG's avatar
BO ZHANG committed
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# join_type for data x plan
PLAN_JOIN_TYPE = "inner"
"""
References:
    - https://docs.astropy.org/en/stable/api/astropy.table.join.html
    - https://docs.astropy.org/en/stable/table/operations.html#join

Typical types:
    - inner join: Only matching rows from both tables
    - left join: All rows from left table, matching rows from right table
    - right join: All rows from right table, matching rows from left table
    - outer join: All rows from both tables
    - cartesian join: Every combination of rows from both tables
"""

BO ZHANG's avatar
BO ZHANG committed
26

BO ZHANG's avatar
BO ZHANG committed
27
def split_data_basis(data_basis: table.Table, n_split: int = 1) -> list[table.Table]:
28
    """Split data basis into n_split parts via obs_id"""
BO ZHANG's avatar
BO ZHANG committed
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
    assert (
        np.unique(data_basis["dataset"]).size == 1
    ), "Only one dataset is allowed for splitting."
    # sort
    data_basis.sort(keys=["dataset", "obs_id"])
    # get unique obsid
    u_obsid, i_obsid, c_obsid = np.unique(
        data_basis["obs_id"].data, return_index=True, return_counts=True
    )
    # set chunk size
    chunk_size = int(np.fix(len(u_obsid) / n_split))
    # initialize chunks
    chunks = []
    for i_split in range(n_split):
        if i_split < n_split - 1:
            chunks.append(
                data_basis[
                    i_obsid[i_split * chunk_size] : i_obsid[(i_split + 1) * chunk_size]
                ]
            )
        else:
            chunks.append(data_basis[i_obsid[i_split * chunk_size] :])
    # np.unique(table.vstack(chunks)["_id"])
    # np.unique(table.vstack(chunks)["obs_id"])
    return chunks


BO ZHANG's avatar
BO ZHANG committed
56
57
58
59
60
class Dispatcher:
    """
    A class to dispatch tasks based on the observation type.
    """

BO ZHANG's avatar
BO ZHANG committed
61
62
63
64
65
    @staticmethod
    def dispatch_file(
        plan_basis: table.Table,
        data_basis: table.Table,
    ) -> list[dict]:
BO ZHANG's avatar
BO ZHANG committed
66
67
        # unique obsid --> useless
        # u_obsid = table.unique(data_basis["dataset", "obs_id"])
BO ZHANG's avatar
BO ZHANG committed
68

69
70
71
72
        # return an empty list if input is empty
        if len(plan_basis) == 0 or len(data_basis) == 0:
            return []

BO ZHANG's avatar
BO ZHANG committed
73
74
        # initialize task list
        task_list = []
BO ZHANG's avatar
BO ZHANG committed
75

76
        # sort data_basis before dispatching
BO ZHANG's avatar
BO ZHANG committed
77
        data_basis.sort(keys=["dataset", "obs_id", "detector"])
78

79
        # loop over data
80
        for i_data_basis in trange(len(data_basis), **TQDM_KWARGS):
BO ZHANG's avatar
BO ZHANG committed
81
            # i_data_basis = 1
BO ZHANG's avatar
BO ZHANG committed
82
            this_task = dict(data_basis[i_data_basis])
BO ZHANG's avatar
BO ZHANG committed
83
84
            this_data_basis = data_basis[i_data_basis : i_data_basis + 1]
            this_relevant_plan = table.join(
BO ZHANG's avatar
BO ZHANG committed
85
86
87
88
89
90
91
                this_data_basis[
                    "dataset",
                    "instrument",
                    "obs_type",
                    "obs_group",
                    "obs_id",
                ],
BO ZHANG's avatar
BO ZHANG committed
92
                plan_basis,
BO ZHANG's avatar
BO ZHANG committed
93
94
95
96
97
98
99
                keys=[
                    "dataset",
                    "instrument",
                    "obs_type",
                    "obs_group",
                    "obs_id",
                ],
BO ZHANG's avatar
BO ZHANG committed
100
                join_type="inner",
BO ZHANG's avatar
BO ZHANG committed
101
                table_names=["data", "plan"],
BO ZHANG's avatar
BO ZHANG committed
102
            )
103
104
105
            # set n_file_expected and n_file_found
            this_task["n_file_expected"] = 1
            this_task["n_file_found"] = 1
BO ZHANG's avatar
BO ZHANG committed
106
107
108
            # append this task
            task_list.append(
                dict(
BO ZHANG's avatar
BO ZHANG committed
109
                    task=this_task,
BO ZHANG's avatar
BO ZHANG committed
110
111
112
                    success=True,
                    relevant_plan=this_relevant_plan,
                    relevant_data=data_basis[i_data_basis : i_data_basis + 1],
BO ZHANG's avatar
BO ZHANG committed
113
114
                    n_relevant_plan=len(this_relevant_plan),
                    n_relevant_data=1,
115
                    relevant_data_id_list=[data_basis[i_data_basis]["_id"]],
116
117
                    n_file_expected=1,
                    n_file_found=1,
BO ZHANG's avatar
BO ZHANG committed
118
119
                )
            )
BO ZHANG's avatar
BO ZHANG committed
120

BO ZHANG's avatar
BO ZHANG committed
121
        return task_list
BO ZHANG's avatar
BO ZHANG committed
122

BO ZHANG's avatar
BO ZHANG committed
123
124
125
126
127
128
129
    @staticmethod
    def dispatch_detector(
        plan_basis: table.Table,
        data_basis: table.Table,
        n_jobs: int = 1,
    ) -> list[dict]:
        """
BO ZHANG's avatar
BO ZHANG committed
130

BO ZHANG's avatar
BO ZHANG committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
        Parameters
        ----------
        plan_basis
        data_basis
        n_jobs

        Returns
        -------

        """
        if n_jobs != 1:
            task_list = joblib.Parallel(n_jobs=n_jobs)(
                joblib.delayed(Dispatcher.dispatch_detector)(plan_basis, _)
                for _ in split_data_basis(data_basis, n_split=n_jobs)
            )
            return sum(task_list, [])

148
149
150
151
        # return an empty list if input is empty
        if len(plan_basis) == 0 or len(data_basis) == 0:
            return []

BO ZHANG's avatar
BO ZHANG committed
152
153
154
155
156
157
        # unique obsid
        u_obsid = table.unique(data_basis["dataset", "obs_id"])
        relevant_plan = table.join(
            u_obsid,
            plan_basis,
            keys=["dataset", "obs_id"],
BO ZHANG's avatar
BO ZHANG committed
158
            join_type=PLAN_JOIN_TYPE,
BO ZHANG's avatar
BO ZHANG committed
159
160
161
162
163
        )
        print(f"{len(relevant_plan)} relevant plan records")

        u_data_detector = table.unique(
            data_basis[
BO ZHANG's avatar
BO ZHANG committed
164
165
166
167
168
                "dataset",
                "instrument",
                "obs_type",
                "obs_group",
                "obs_id",
BO ZHANG's avatar
BO ZHANG committed
169
170
                "detector",
            ]
BO ZHANG's avatar
BO ZHANG committed
171
        )
BO ZHANG's avatar
BO ZHANG committed
172
173
174
175
176

        # initialize task list
        task_list = []

        # loop over plan
BO ZHANG's avatar
tweaks    
BO ZHANG committed
177
        for i_data_detector in trange(len(u_data_detector), **TQDM_KWARGS):
BO ZHANG's avatar
BO ZHANG committed
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
            # i_data_detector = 1
            this_task = dict(u_data_detector[i_data_detector])
            this_data_detector = u_data_detector[i_data_detector : i_data_detector + 1]

            # join data and plan
            this_data_detector_files = table.join(
                this_data_detector,
                data_basis,
                keys=[
                    "dataset",
                    "instrument",
                    "obs_type",
                    "obs_group",
                    "obs_id",
                    "detector",
                ],
                join_type="inner",
            )
            this_data_detector_plan = table.join(
                this_data_detector,
                relevant_plan,
                keys=[
                    "dataset",
                    "instrument",
                    "obs_type",
                    "obs_group",
                    "obs_id",
                ],
BO ZHANG's avatar
BO ZHANG committed
206
                join_type=PLAN_JOIN_TYPE,
BO ZHANG's avatar
BO ZHANG committed
207
208
209
210
211
212
213
214
            )

            # whether detector effective
            this_detector = this_data_detector["detector"][0]
            this_instrument = this_data_detector["instrument"][0]
            this_detector_effective = (
                this_detector in csst[this_instrument].effective_detector_names
            )
BO ZHANG's avatar
BO ZHANG committed
215

BO ZHANG's avatar
BO ZHANG committed
216
            n_file_expected = (
BO ZHANG's avatar
BO ZHANG committed
217
                this_data_detector_plan["n_file"][0]
BO ZHANG's avatar
BO ZHANG committed
218
219
220
                if len(this_data_detector_plan) > 0
                else 0
            )
BO ZHANG's avatar
BO ZHANG committed
221
            n_file_found = len(this_data_detector_files)
222
223
224
            # set n_file_expected and n_file_found
            this_task["n_file_expected"] = n_file_expected
            this_task["n_file_found"] = n_file_found
BO ZHANG's avatar
BO ZHANG committed
225
226
227
228
229
230
231
232
            # append this task
            task_list.append(
                dict(
                    task=this_task,
                    success=(
                        len(this_data_detector_plan) == 1
                        and len(this_data_detector_files) == 1
                        and this_detector_effective
BO ZHANG's avatar
BO ZHANG committed
233
                        and n_file_found == n_file_expected
BO ZHANG's avatar
BO ZHANG committed
234
235
236
                    ),
                    relevant_plan=this_data_detector_plan,
                    relevant_data=this_data_detector_files,
BO ZHANG's avatar
BO ZHANG committed
237
238
                    n_relevant_plan=len(this_data_detector_plan),
                    n_relevant_data=len(this_data_detector_files),
239
240
241
                    relevant_data_id_list=(
                        []
                        if len(this_data_detector_files) == 0
242
                        else list(this_data_detector_files["_id"])
243
                    ),
BO ZHANG's avatar
BO ZHANG committed
244
                    n_file_expected=this_data_detector_plan["n_file"].sum(),
245
                    n_file_found=len(this_data_detector_files),
BO ZHANG's avatar
BO ZHANG committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
                )
            )
        return task_list

    @staticmethod
    def dispatch_obsid(
        plan_basis: table.Table,
        data_basis: table.Table,
        n_jobs: int = 1,
    ) -> list[dict]:

        if n_jobs != 1:
            task_list = joblib.Parallel(n_jobs=n_jobs)(
                joblib.delayed(Dispatcher.dispatch_obsid)(plan_basis, _)
                for _ in split_data_basis(data_basis, n_split=n_jobs)
            )
            return sum(task_list, [])

264
265
266
267
        # return an empty list if input is empty
        if len(plan_basis) == 0 or len(data_basis) == 0:
            return []

268
269
        group_keys = ["dataset", "instrument", "obs_type", "obs_group", "obs_id"]
        obsid_basis = data_basis.group_by(group_keys)
BO ZHANG's avatar
BO ZHANG committed
270

BO ZHANG's avatar
BO ZHANG committed
271
272
        # initialize task list
        task_list = []
273
274
        # loop over obsid
        for this_obsid_basis in obsid_basis.groups:
275
            # find relevant plan
276
277
278
279
            this_relevant_plan_basis = table.join(
                this_obsid_basis[group_keys][:1],
                plan_basis,
                keys=group_keys,
BO ZHANG's avatar
BO ZHANG committed
280
                join_type=PLAN_JOIN_TYPE,
BO ZHANG's avatar
BO ZHANG committed
281
            )
282
            assert len(this_relevant_plan_basis) == 1
283
284
            # generate task
            this_task = dict(this_relevant_plan_basis[group_keys][0])
285
286
287
288
289
290
291
292
            n_file_expected = this_relevant_plan_basis[0]["n_file"]
            n_file_found = len(this_obsid_basis)
            this_instrument = this_relevant_plan_basis[0]["instrument"]
            detectors_found = set(this_obsid_basis["detector"])
            detectors_expected = set(csst[this_instrument].effective_detector_names)
            this_success = (
                n_file_expected == n_file_found
                and detectors_found == detectors_expected
BO ZHANG's avatar
BO ZHANG committed
293
            )
294
295
            this_task["n_file_expected"] = n_file_expected
            this_task["n_file_found"] = n_file_found
BO ZHANG's avatar
BO ZHANG committed
296
297
298
            # append this task
            task_list.append(
                dict(
299
                    task=this_task,
BO ZHANG's avatar
BO ZHANG committed
300
                    success=this_success,
301
302
303
304
                    relevant_plan=this_relevant_plan_basis,
                    relevant_data=this_obsid_basis,
                    n_relevant_plan=len(this_relevant_plan_basis),
                    n_relevant_data=len(this_obsid_basis),
305
306
                    relevant_data_id_list=(
                        []
307
308
                        if len(this_obsid_basis) == 0
                        else list(this_obsid_basis["_id"])
309
                    ),
310
311
                    n_file_expected=n_file_expected,
                    n_file_found=n_file_found,
BO ZHANG's avatar
BO ZHANG committed
312
313
314
                )
            )
        return task_list
BO ZHANG's avatar
BO ZHANG committed
315

BO ZHANG's avatar
BO ZHANG committed
316
    @staticmethod
317
    def dispatch_obsgroup_detector(
BO ZHANG's avatar
BO ZHANG committed
318
319
        plan_basis: table.Table,
        data_basis: table.Table,
320
        # n_jobs: int = 1,
321
    ) -> list[dict]:
322
323
324
325
        # return an empty list if input is empty
        if len(plan_basis) == 0 or len(data_basis) == 0:
            return []

326
        # unique obsgroup basis (using group_by)
327
        obsgroup_plan_basis = plan_basis.group_by(
328
            keys=[
BO ZHANG's avatar
BO ZHANG committed
329
330
331
332
333
334
335
                "dataset",
                "instrument",
                "obs_type",
                "obs_group",
            ]
        )

336
337
338
339
        # initialize task list
        task_list = []

        # loop over obsgroup
340
341
342
343
        for i_obsgroup_plan in trange(len(obsgroup_plan_basis.groups), **TQDM_KWARGS):
            this_obsgroup_plan_basis = obsgroup_plan_basis.groups[i_obsgroup_plan]
            this_obsgroup_obsid = this_obsgroup_plan_basis["obs_id"].data
            n_file_expected = len(this_obsgroup_obsid)
344

345
            this_instrument = this_obsgroup_plan_basis["instrument"][0]
346
347
348
349
            effective_detector_names = csst[this_instrument].effective_detector_names

            for this_effective_detector_name in effective_detector_names:
                this_task = dict(
350
351
352
353
                    dataset=this_obsgroup_plan_basis["dataset"][0],
                    instrument=this_obsgroup_plan_basis["instrument"][0],
                    obs_type=this_obsgroup_plan_basis["obs_type"][0],
                    obs_group=this_obsgroup_plan_basis["obs_group"][0],
354
355
356
357
358
                    detector=this_effective_detector_name,
                )
                this_obsgroup_detector_expected = table.Table(
                    [
                        dict(
359
360
361
362
                            dataset=this_obsgroup_plan_basis["dataset"][0],
                            instrument=this_obsgroup_plan_basis["instrument"][0],
                            obs_type=this_obsgroup_plan_basis["obs_type"][0],
                            obs_group=this_obsgroup_plan_basis["obs_group"][0],
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
                            obs_id=this_obsid,
                            detector=this_effective_detector_name,
                        )
                        for this_obsid in this_obsgroup_obsid
                    ]
                )
                this_obsgroup_detector_found = table.join(
                    this_obsgroup_detector_expected,
                    data_basis,
                    keys=[
                        "dataset",
                        "instrument",
                        "obs_type",
                        "obs_group",
                        "obs_id",
                        "detector",
                    ],
                    join_type="inner",
                )
                n_file_found = len(this_obsgroup_detector_found)
                this_success = n_file_found == n_file_expected and set(
                    this_obsgroup_detector_found["obs_id"]
                ) == set(this_obsgroup_obsid)
                # set n_file_expected and n_file_found
                this_task["n_file_expected"] = n_file_expected
                this_task["n_file_found"] = n_file_found
                # append this task
                task_list.append(
                    dict(
                        task=this_task,
                        success=this_success,
394
                        relevant_plan=this_obsgroup_plan_basis,
395
                        relevant_data=this_obsgroup_detector_found,
396
                        n_relevant_plan=len(this_obsgroup_plan_basis),
397
398
399
400
401
402
403
404
405
406
407
408
                        n_relevant_data=len(this_obsgroup_detector_found),
                        relevant_data_id_list=(
                            list(this_obsgroup_detector_found["_id"])
                            if n_file_found > 0
                            else []
                        ),
                        n_file_expected=n_file_expected,
                        n_file_found=n_file_found,
                    )
                )
        return task_list

BO ZHANG's avatar
BO ZHANG committed
409
410
411
412
413
414
415
    @staticmethod
    def dispatch_obsgroup(
        plan_basis: table.Table,
        data_basis: table.Table,
        # n_jobs: int = 1,
    ) -> list[dict]:

416
417
418
419
        # return an empty list if input is empty
        if len(plan_basis) == 0 or len(data_basis) == 0:
            return []

BO ZHANG's avatar
BO ZHANG committed
420
421
422
423
424
425
426
427
428
        # unique obsgroup basis
        obsgroup_basis = table.unique(
            plan_basis[
                "dataset",
                "instrument",
                "obs_type",
                "obs_group",
            ]
        )
BO ZHANG's avatar
BO ZHANG committed
429

BO ZHANG's avatar
BO ZHANG committed
430
        # initialize task list
BO ZHANG's avatar
BO ZHANG committed
431
432
        task_list = []

BO ZHANG's avatar
BO ZHANG committed
433
        # loop over obsgroup
434
        for i_obsgroup in trange(len(obsgroup_basis), **TQDM_KWARGS):
BO ZHANG's avatar
BO ZHANG committed
435
436
437
438
439

            # i_obsgroup = 1
            this_task = dict(obsgroup_basis[i_obsgroup])
            this_success = True

BO ZHANG's avatar
BO ZHANG committed
440
            this_obsgroup_plan = table.join(
BO ZHANG's avatar
BO ZHANG committed
441
442
443
                obsgroup_basis[i_obsgroup : i_obsgroup + 1],  # this obsgroup
                plan_basis,
                keys=["dataset", "instrument", "obs_type", "obs_group"],
BO ZHANG's avatar
BO ZHANG committed
444
                join_type=PLAN_JOIN_TYPE,
BO ZHANG's avatar
BO ZHANG committed
445
446
            )
            this_obsgroup_file = table.join(
BO ZHANG's avatar
BO ZHANG committed
447
                this_obsgroup_plan,
BO ZHANG's avatar
BO ZHANG committed
448
449
450
451
452
453
454
                data_basis,
                keys=["dataset", "instrument", "obs_type", "obs_group", "obs_id"],
                join_type="inner",
                table_names=["plan", "data"],
            )

            # loop over obsid
BO ZHANG's avatar
BO ZHANG committed
455
            for i_obsid in range(len(this_obsgroup_plan)):
BO ZHANG's avatar
BO ZHANG committed
456
457
                # i_obsid = 1
                # print(i_obsid)
BO ZHANG's avatar
BO ZHANG committed
458
                this_instrument = this_obsgroup_plan[i_obsid]["instrument"]
BO ZHANG's avatar
BO ZHANG committed
459
                this_n_file = this_obsgroup_plan[i_obsid]["n_file"]
BO ZHANG's avatar
BO ZHANG committed
460
461
462
                this_effective_detector_names = csst[
                    this_instrument
                ].effective_detector_names
BO ZHANG's avatar
BO ZHANG committed
463
464

                this_obsgroup_obsid_file = table.join(
BO ZHANG's avatar
BO ZHANG committed
465
                    this_obsgroup_plan[i_obsid : i_obsid + 1],  # this obsid
BO ZHANG's avatar
BO ZHANG committed
466
467
468
469
                    data_basis,
                    keys=["dataset", "instrument", "obs_type", "obs_group", "obs_id"],
                    join_type="inner",
                    table_names=["plan", "data"],
BO ZHANG's avatar
BO ZHANG committed
470
                )
BO ZHANG's avatar
BO ZHANG committed
471

BO ZHANG's avatar
BO ZHANG committed
472
473
474
                if this_instrument == "HSTDM":
                    # 不确定以后是1个探测器还是2个探测器
                    this_n_file_found = len(this_obsgroup_obsid_file)
BO ZHANG's avatar
BO ZHANG committed
475
476
                    this_n_file_expected = this_n_file
                    this_success &= this_n_file_found == this_n_file_expected
BO ZHANG's avatar
BO ZHANG committed
477
                else:
BO ZHANG's avatar
BO ZHANG committed
478
479
480
481
482
483
484
485
                    # for other instruments, e.g., MSC
                    # n_file_found = len(this_obsgroup_obsid_file)
                    # n_file_expected = len(effective_detector_names)
                    # this_success &= n_file_found == n_file_expected

                    # or more strictly, expected files are a subset of files found
                    this_success &= set(this_effective_detector_names) <= set(
                        this_obsgroup_obsid_file["detector"]
BO ZHANG's avatar
BO ZHANG committed
486
487
                    )

BO ZHANG's avatar
BO ZHANG committed
488
            n_file_expected = int(this_obsgroup_plan["n_file"].sum())
BO ZHANG's avatar
BO ZHANG committed
489
            n_file_found = len(this_obsgroup_file)
490
491
492
            # set n_file_expected and n_file_found
            this_task["n_file_expected"] = n_file_expected
            this_task["n_file_found"] = n_file_found
BO ZHANG's avatar
BO ZHANG committed
493
494
495
496
497
            # append this task
            task_list.append(
                dict(
                    task=this_task,
                    success=this_success,
BO ZHANG's avatar
BO ZHANG committed
498
                    relevant_plan=this_obsgroup_plan,
BO ZHANG's avatar
BO ZHANG committed
499
                    relevant_data=this_obsgroup_file,
BO ZHANG's avatar
BO ZHANG committed
500
                    n_relevant_plan=len(this_obsgroup_plan),
501
                    n_relevant_data=len(this_obsgroup_file),
502
503
504
                    relevant_data_id_list=(
                        []
                        if len(this_obsgroup_file) == 0
505
                        else list(this_obsgroup_file["_id_data"])
506
                    ),
BO ZHANG's avatar
BO ZHANG committed
507
                    n_file_expected=this_obsgroup_plan["n_file"].sum(),
508
                    n_file_found=len(this_obsgroup_file),
BO ZHANG's avatar
BO ZHANG committed
509
510
511
                )
            )
        return task_list
BO ZHANG's avatar
BO ZHANG committed
512
513

    @staticmethod
BO ZHANG's avatar
BO ZHANG committed
514
515
516
    def load_test_data() -> tuple:
        import joblib

517
518
        plan_basis = joblib.load("dagtest/csst-msc-c9-25sqdeg-v3.plan_basis.dump")
        data_basis = joblib.load("dagtest/csst-msc-c9-25sqdeg-v3.level0_basis.dump")
BO ZHANG's avatar
BO ZHANG committed
519
        return plan_basis, data_basis