_dispatcher.py 26.5 KB
Newer Older
BO ZHANG's avatar
BO ZHANG committed
1
import numpy as np
BO ZHANG's avatar
BO ZHANG committed
2
3
import joblib
from astropy import table
BO ZHANG's avatar
BO ZHANG committed
4
from csst_dfs_client import plan, level0, level1
BO ZHANG's avatar
BO ZHANG committed
5
6
from tqdm import trange

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

BO ZHANG's avatar
BO ZHANG committed
9
10
# from csst_dag._csst import csst

11
12
TQDM_KWARGS = dict(unit="task", dynamic_ncols=False)

BO ZHANG's avatar
BO ZHANG committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# THESE ARE GENERAL PARAMETERS!
PLAN_PARAMS = {
    "dataset": None,
    "instrument": None,
    "obs_type": None,
    "obs_group": None,
    "obs_id": None,
    "proposal_id": None,
}

LEVEL0_PARAMS = {
    "dataset": None,
    "instrument": None,
    "obs_type": None,
    "obs_group": None,
    "obs_id": None,
    "detector": None,
30
31
    "prc_status": None,
    "qc_status": None,
BO ZHANG's avatar
BO ZHANG committed
32
33
34
35
36
37
38
39
40
}

LEVEL1_PARAMS = {
    "dataset": None,
    "instrument": None,
    "obs_type": None,
    "obs_group": None,
    "obs_id": None,
    "detector": None,
41
42
    "prc_status": None,
    "qc_status": None,
BO ZHANG's avatar
BO ZHANG committed
43
    # special keys for data products
BO ZHANG's avatar
BO ZHANG committed
44
45
    "data_model": None,
    "batch_id": "default_batch",
BO ZHANG's avatar
BO ZHANG committed
46
47
    "build": None,
    "pmapname": None,
BO ZHANG's avatar
BO ZHANG committed
48
49
}

BO ZHANG's avatar
BO ZHANG committed
50
51
52
53
54
55
56
57
# PROC_PARAMS = {
#     "priority": 1,
#     "batch_id": "default_batch",
#     "pmapname": "pmapname",
#     "final_prc_status": -2,
#     "demo": False,
#     # should be capable to extend
# }
BO ZHANG's avatar
BO ZHANG committed
58

BO ZHANG's avatar
BO ZHANG committed
59
60
61
62
63
64
65
# plan basis keys
PLAN_BASIS_KEYS = (
    "dataset",
    "instrument",
    "obs_type",
    "obs_group",
    "obs_id",
BO ZHANG's avatar
BO ZHANG committed
66
    "n_file",
BO ZHANG's avatar
BO ZHANG committed
67
68
69
70
71
72
73
74
75
76
77
78
79
    "_id",
)

# data basis keys
DATA_BASIS_KEYS = (
    "dataset",
    "instrument",
    "obs_type",
    "obs_group",
    "obs_id",
    "detector",
    "file_name",
    "_id",
BO ZHANG's avatar
BO ZHANG committed
80
    "prc_status",
BO ZHANG's avatar
BO ZHANG committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
)

# 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118

def override_common_keys(d1: dict, d2: dict) -> dict:
    """
    Construct a new dictionary by updating the values of basis_keys that exists in the first dictionary
    with the values of the second dictionary.

    Parameters
    ----------
    d1 : dict
        The first dictionary.
    d2 : dict
        The second dictionary.

    Returns
    -------
    dict:
        The updated dictionary.
    """
    return {k: d2[k] if k in d2.keys() else d1[k] for k in d1.keys()}


BO ZHANG's avatar
BO ZHANG committed
119
120
def extract_basis_table(dlist: list[dict], basis_keys: tuple) -> table.Table:
    """Extract basis key-value pairs from a list of dictionaries."""
BO ZHANG's avatar
tweak    
BO ZHANG committed
121
    return table.Table([{k: d.get(k, "") for k in basis_keys} for d in dlist])
BO ZHANG's avatar
BO ZHANG committed
122
123


BO ZHANG's avatar
BO ZHANG committed
124
def split_data_basis(data_basis: table.Table, n_split: int = 1) -> list[table.Table]:
125
    """Split data basis into n_split parts via obs_id"""
BO ZHANG's avatar
BO ZHANG committed
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
    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
153
154
155
156
157
158
class Dispatcher:
    """
    A class to dispatch tasks based on the observation type.
    """

    @staticmethod
BO ZHANG's avatar
BO ZHANG committed
159
160
161
162
163
    def find_plan_basis(**kwargs) -> table.Table:
        """
        Find plan records.
        """
        # query
BO ZHANG's avatar
BO ZHANG committed
164
165
166
        prompt = "plan"
        qr_kwargs = override_common_keys(PLAN_PARAMS, kwargs)
        qr = plan.find(**qr_kwargs)
BO ZHANG's avatar
BO ZHANG committed
167
        assert qr.success, qr
BO ZHANG's avatar
BO ZHANG committed
168
169
        print(f">>> [{prompt}] query kwargs: {qr_kwargs}")
        print(f">>> [{prompt}] {len(qr.data)} records found.")
BO ZHANG's avatar
BO ZHANG committed
170
        # plan basis / obsid basis
171
172
        try:
            for _ in qr.data:
BO ZHANG's avatar
BO ZHANG committed
173
174
                this_instrument = _["instrument"]
                if this_instrument == "HSTDM":
BO ZHANG's avatar
BO ZHANG committed
175
                    if _["params"]["detector"] == "SIS12":
BO ZHANG's avatar
BO ZHANG committed
176
                        this_n_file = len(_["params"]["exposure_start"]) * 2
BO ZHANG's avatar
BO ZHANG committed
177
                    else:
BO ZHANG's avatar
BO ZHANG committed
178
                        this_n_file = len(_["params"]["exposure_start"])
BO ZHANG's avatar
BO ZHANG committed
179
                else:
BO ZHANG's avatar
BO ZHANG committed
180
                    this_n_file = len(csst[this_instrument].effective_detector_names)
BO ZHANG's avatar
BO ZHANG committed
181
                _["n_file"] = this_n_file
182
183
184
        except KeyError:
            print(f"`n_epec_frame` is not found in {_}")
            raise KeyError(f"`n_epec_frame` is not found in {_}")
BO ZHANG's avatar
BO ZHANG committed
185
186
187
        plan_basis = extract_basis_table(
            qr.data,
            PLAN_BASIS_KEYS,
BO ZHANG's avatar
BO ZHANG committed
188
        )
BO ZHANG's avatar
BO ZHANG committed
189
        return plan_basis
BO ZHANG's avatar
BO ZHANG committed
190
191

    @staticmethod
BO ZHANG's avatar
BO ZHANG committed
192
193
194
195
196
    def find_level0_basis(**kwargs) -> table.Table:
        """
        Find level0 records.
        """
        # query
BO ZHANG's avatar
BO ZHANG committed
197
198
199
        prompt = "level0"
        qr_kwargs = override_common_keys(LEVEL0_PARAMS, kwargs)
        qr = level0.find(**qr_kwargs)
BO ZHANG's avatar
BO ZHANG committed
200
        assert qr.success, qr
BO ZHANG's avatar
BO ZHANG committed
201
202
        print(f">>> [{prompt}] query kwargs: {qr_kwargs}")
        print(f">>> [{prompt}] {len(qr.data)} records found.")
BO ZHANG's avatar
BO ZHANG committed
203
204
205
206
207
208
        # data basis
        data_basis = extract_basis_table(
            qr.data,
            DATA_BASIS_KEYS,
        )
        return data_basis
BO ZHANG's avatar
BO ZHANG committed
209

BO ZHANG's avatar
BO ZHANG committed
210
211
212
213
214
215
    @staticmethod
    def find_level1_basis(**kwargs) -> table.Table:
        """
        Find level1 records.
        """
        # query
BO ZHANG's avatar
BO ZHANG committed
216
217
218
        prompt = "level1"
        qr_kwargs = override_common_keys(LEVEL1_PARAMS, kwargs)
        qr = level1.find(**qr_kwargs)
BO ZHANG's avatar
BO ZHANG committed
219
        assert qr.success, qr
BO ZHANG's avatar
BO ZHANG committed
220
221
        print(f">>> [{prompt}] query kwargs: {qr_kwargs}")
        print(f">>> [{prompt}] {len(qr.data)} records found.")
BO ZHANG's avatar
BO ZHANG committed
222
223
224
225
226
227
        # data basis
        data_basis = extract_basis_table(
            qr.data,
            DATA_BASIS_KEYS,
        )
        return data_basis
BO ZHANG's avatar
BO ZHANG committed
228

229
    @staticmethod
BO ZHANG's avatar
tweaks    
BO ZHANG committed
230
    def find_plan_level0_basis(**kwargs) -> tuple[table.Table, table.Table]:
231
232
        data_basis = Dispatcher.find_level0_basis(**kwargs)
        plan_basis = Dispatcher.find_plan_basis(**kwargs)
233
234
        assert len(data_basis) > 0, data_basis
        assert len(plan_basis) > 0, plan_basis
235
236
237
238
239
240
241
        u_data_basis = table.unique(data_basis["dataset", "obs_id"])
        relevant_plan = table.join(
            u_data_basis,
            plan_basis,
            keys=["dataset", "obs_id"],
            join_type=PLAN_JOIN_TYPE,
        )
242
        assert len(relevant_plan) > 0, relevant_plan
243
244
245
        return relevant_plan, data_basis

    @staticmethod
BO ZHANG's avatar
tweaks    
BO ZHANG committed
246
    def find_plan_level1_basis(**kwargs) -> tuple[table.Table, table.Table]:
247
248
        data_basis = Dispatcher.find_level1_basis(**kwargs)
        plan_basis = Dispatcher.find_plan_basis(**kwargs)
249
250
        assert len(data_basis) > 0, data_basis
        assert len(plan_basis) > 0, plan_basis
251
252
253
254
255
256
257
        u_data_basis = table.unique(data_basis["dataset", "obs_id"])
        relevant_plan = table.join(
            u_data_basis,
            plan_basis,
            keys=["dataset", "obs_id"],
            join_type=PLAN_JOIN_TYPE,
        )
258
        assert len(relevant_plan) > 0, relevant_plan
259
260
        return relevant_plan, data_basis

BO ZHANG's avatar
BO ZHANG committed
261
262
263
264
265
    @staticmethod
    def dispatch_file(
        plan_basis: table.Table,
        data_basis: table.Table,
    ) -> list[dict]:
BO ZHANG's avatar
BO ZHANG committed
266
267
        # unique obsid --> useless
        # u_obsid = table.unique(data_basis["dataset", "obs_id"])
BO ZHANG's avatar
BO ZHANG committed
268

269
270
271
272
        # 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
273
274
        # initialize task list
        task_list = []
BO ZHANG's avatar
BO ZHANG committed
275

276
        # sort data_basis before dispatching
277
        data_basis.sort(keys=data_basis.colnames)
278

279
        # loop over data
280
        for i_data_basis in trange(len(data_basis), **TQDM_KWARGS):
BO ZHANG's avatar
BO ZHANG committed
281
            # i_data_basis = 1
BO ZHANG's avatar
BO ZHANG committed
282
            this_task = dict(data_basis[i_data_basis])
BO ZHANG's avatar
BO ZHANG committed
283
284
            this_data_basis = data_basis[i_data_basis : i_data_basis + 1]
            this_relevant_plan = table.join(
BO ZHANG's avatar
BO ZHANG committed
285
286
287
288
289
290
291
                this_data_basis[
                    "dataset",
                    "instrument",
                    "obs_type",
                    "obs_group",
                    "obs_id",
                ],
BO ZHANG's avatar
BO ZHANG committed
292
                plan_basis,
BO ZHANG's avatar
BO ZHANG committed
293
294
295
296
297
298
299
                keys=[
                    "dataset",
                    "instrument",
                    "obs_type",
                    "obs_group",
                    "obs_id",
                ],
BO ZHANG's avatar
BO ZHANG committed
300
                join_type="inner",
BO ZHANG's avatar
BO ZHANG committed
301
                table_names=["data", "plan"],
BO ZHANG's avatar
BO ZHANG committed
302
            )
303
304
305
            # 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
306
307
308
            # append this task
            task_list.append(
                dict(
BO ZHANG's avatar
BO ZHANG committed
309
                    task=this_task,
BO ZHANG's avatar
BO ZHANG committed
310
311
312
                    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
313
314
                    n_relevant_plan=len(this_relevant_plan),
                    n_relevant_data=1,
315
                    relevant_data_id_list=[data_basis[i_data_basis]["_id"]],
316
317
                    n_file_expected=1,
                    n_file_found=1,
BO ZHANG's avatar
BO ZHANG committed
318
319
                )
            )
BO ZHANG's avatar
BO ZHANG committed
320

BO ZHANG's avatar
BO ZHANG committed
321
        return task_list
BO ZHANG's avatar
BO ZHANG committed
322

BO ZHANG's avatar
BO ZHANG committed
323
324
325
326
327
328
329
    @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
330

BO ZHANG's avatar
BO ZHANG committed
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
        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, [])

348
349
350
351
        # 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
352
353
354
355
356
357
        # 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
358
            join_type=PLAN_JOIN_TYPE,
BO ZHANG's avatar
BO ZHANG committed
359
360
361
362
363
        )
        print(f"{len(relevant_plan)} relevant plan records")

        u_data_detector = table.unique(
            data_basis[
BO ZHANG's avatar
BO ZHANG committed
364
365
366
367
368
                "dataset",
                "instrument",
                "obs_type",
                "obs_group",
                "obs_id",
BO ZHANG's avatar
BO ZHANG committed
369
370
                "detector",
            ]
BO ZHANG's avatar
BO ZHANG committed
371
        )
BO ZHANG's avatar
BO ZHANG committed
372
373
374
375
376

        # initialize task list
        task_list = []

        # loop over plan
BO ZHANG's avatar
tweaks    
BO ZHANG committed
377
        for i_data_detector in trange(len(u_data_detector), **TQDM_KWARGS):
BO ZHANG's avatar
BO ZHANG committed
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
            # 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
406
                join_type=PLAN_JOIN_TYPE,
BO ZHANG's avatar
BO ZHANG committed
407
408
409
410
411
412
413
414
            )

            # 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
415

BO ZHANG's avatar
BO ZHANG committed
416
            n_file_expected = (
BO ZHANG's avatar
BO ZHANG committed
417
                this_data_detector_plan["n_file"][0]
BO ZHANG's avatar
BO ZHANG committed
418
419
420
                if len(this_data_detector_plan) > 0
                else 0
            )
BO ZHANG's avatar
BO ZHANG committed
421
            n_file_found = len(this_data_detector_files)
422
423
424
            # 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
425
426
427
428
429
430
431
432
            # 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
433
                        and n_file_found == n_file_expected
BO ZHANG's avatar
BO ZHANG committed
434
435
436
                    ),
                    relevant_plan=this_data_detector_plan,
                    relevant_data=this_data_detector_files,
BO ZHANG's avatar
BO ZHANG committed
437
438
                    n_relevant_plan=len(this_data_detector_plan),
                    n_relevant_data=len(this_data_detector_files),
439
440
441
                    relevant_data_id_list=(
                        []
                        if len(this_data_detector_files) == 0
442
                        else list(this_data_detector_files["_id_data"])
443
                    ),
BO ZHANG's avatar
BO ZHANG committed
444
                    n_file_expected=this_data_detector_plan["n_file"].sum(),
445
                    n_file_found=len(this_data_detector_files),
BO ZHANG's avatar
BO ZHANG committed
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
                )
            )
        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, [])

464
465
466
467
        # 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
468
469
        obsid_basis = data_basis.group_by([""])

BO ZHANG's avatar
BO ZHANG committed
470
471
472
473
474
475
        # 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
476
            join_type=PLAN_JOIN_TYPE,
BO ZHANG's avatar
BO ZHANG committed
477
478
479
480
481
        )
        print(f"{len(relevant_plan)} relevant plan records")

        u_data_obsid = table.unique(
            data_basis[
BO ZHANG's avatar
BO ZHANG committed
482
483
484
485
486
                "dataset",
                "instrument",
                "obs_type",
                "obs_group",
                "obs_id",
BO ZHANG's avatar
BO ZHANG committed
487
            ]
BO ZHANG's avatar
BO ZHANG committed
488
489
        )

BO ZHANG's avatar
BO ZHANG committed
490
491
492
493
        # initialize task list
        task_list = []

        # loop over plan
494
        for i_data_obsid in trange(len(u_data_obsid), **TQDM_KWARGS):
BO ZHANG's avatar
BO ZHANG committed
495
            # i_data_obsid = 2
BO ZHANG's avatar
BO ZHANG committed
496
497
498
499
            this_task = dict(u_data_obsid[i_data_obsid])
            this_data_obsid = u_data_obsid[i_data_obsid : i_data_obsid + 1]

            # join data and plan
BO ZHANG's avatar
BO ZHANG committed
500
            this_data_obsid_file = table.join(
BO ZHANG's avatar
BO ZHANG committed
501
502
503
504
505
506
507
508
509
510
511
                this_data_obsid,
                data_basis,
                keys=[
                    "dataset",
                    "instrument",
                    "obs_type",
                    "obs_group",
                    "obs_id",
                ],
                join_type="inner",
            )
BO ZHANG's avatar
BO ZHANG committed
512
            # print(this_data_obsid_file.colnames)
BO ZHANG's avatar
BO ZHANG committed
513
514
515
516
517
518
519
520
521
522
            this_data_obsid_plan = table.join(
                this_data_obsid,
                relevant_plan,
                keys=[
                    "dataset",
                    "instrument",
                    "obs_type",
                    "obs_group",
                    "obs_id",
                ],
BO ZHANG's avatar
BO ZHANG committed
523
                join_type=PLAN_JOIN_TYPE,
BO ZHANG's avatar
BO ZHANG committed
524
525
526
527
            )

            # whether effective detectors all there
            this_instrument = this_data_obsid["instrument"][0]
BO ZHANG's avatar
BO ZHANG committed
528
529
            this_n_file = (
                this_data_obsid_plan["n_file"] if len(this_data_obsid_plan) > 0 else 0
BO ZHANG's avatar
BO ZHANG committed
530
            )
BO ZHANG's avatar
BO ZHANG committed
531
532
533
534
535
536
537
            this_effective_detector_names = csst[
                this_instrument
            ].effective_detector_names

            if this_instrument == "HSTDM":
                # 不确定以后是1个探测器还是2个探测器
                this_n_file_found = len(this_data_obsid_file)
BO ZHANG's avatar
BO ZHANG committed
538
                this_n_file_expected = (this_n_file, this_n_file * 2)
BO ZHANG's avatar
BO ZHANG committed
539
540
541
542
543
544
545
546
547
548
549
                this_success = this_n_file_found in this_n_file_expected
            else:
                # 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_data_obsid_file["detector"]
                )
BO ZHANG's avatar
BO ZHANG committed
550

BO ZHANG's avatar
BO ZHANG committed
551
            n_file_expected = int(this_data_obsid_plan["n_file"].sum())
BO ZHANG's avatar
BO ZHANG committed
552
            n_file_found = len(this_data_obsid_file)
553
554
555
            # 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
556
557
558
559
560
561
            # append this task
            task_list.append(
                dict(
                    task=this_task,
                    success=this_success,
                    relevant_plan=this_data_obsid_plan,
BO ZHANG's avatar
BO ZHANG committed
562
563
564
                    relevant_data=this_data_obsid_file,
                    n_relevant_plan=len(this_data_obsid_plan),
                    n_relevant_data=len(this_data_obsid_file),
565
566
567
                    relevant_data_id_list=(
                        []
                        if len(this_data_obsid_file) == 0
BO ZHANG's avatar
BO ZHANG committed
568
                        else list(this_data_obsid_file["_id"])
569
                    ),
BO ZHANG's avatar
BO ZHANG committed
570
                    n_file_expected=this_data_obsid_plan["n_file"].sum(),
571
                    n_file_found=len(this_data_obsid_file),
BO ZHANG's avatar
BO ZHANG committed
572
573
574
575
                )
            )

        return task_list
BO ZHANG's avatar
BO ZHANG committed
576

BO ZHANG's avatar
BO ZHANG committed
577
    @staticmethod
578
    def dispatch_obsgroup_detector(
BO ZHANG's avatar
BO ZHANG committed
579
580
        plan_basis: table.Table,
        data_basis: table.Table,
581
        # n_jobs: int = 1,
582
    ) -> list[dict]:
583
584
585
586
        # return an empty list if input is empty
        if len(plan_basis) == 0 or len(data_basis) == 0:
            return []

587
588
589
        # unique obsgroup basis (using group_by)
        obsgroup_basis = plan_basis.group_by(
            keys=[
BO ZHANG's avatar
BO ZHANG committed
590
591
592
593
594
595
596
                "dataset",
                "instrument",
                "obs_type",
                "obs_group",
            ]
        )

597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
        # initialize task list
        task_list = []

        # loop over obsgroup
        for i_obsgroup in trange(len(obsgroup_basis.groups), **TQDM_KWARGS):
            this_obsgroup_basis = obsgroup_basis.groups[i_obsgroup]
            this_obsgroup_obsid = this_obsgroup_basis["obs_id"].data
            n_file_expected = this_obsgroup_basis["n_file"].sum()

            this_instrument = this_obsgroup_basis["instrument"][0]
            effective_detector_names = csst[this_instrument].effective_detector_names

            for this_effective_detector_name in effective_detector_names:
                this_task = dict(
                    dataset=this_obsgroup_basis["dataset"][0],
                    instrument=this_obsgroup_basis["instrument"][0],
                    obs_type=this_obsgroup_basis["obs_type"][0],
                    obs_group=this_obsgroup_basis["obs_group"][0],
                    detector=this_effective_detector_name,
                )
                this_obsgroup_detector_expected = table.Table(
                    [
                        dict(
                            dataset=this_obsgroup_basis["dataset"][0],
                            instrument=this_obsgroup_basis["instrument"][0],
                            obs_type=this_obsgroup_basis["obs_type"][0],
                            obs_group=this_obsgroup_basis["obs_group"][0],
                            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,
                        relevant_plan=this_obsgroup_basis,
                        relevant_data=this_obsgroup_detector_found,
                        n_relevant_plan=len(this_obsgroup_basis),
                        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
670
671
672
673
674
675
676
    @staticmethod
    def dispatch_obsgroup(
        plan_basis: table.Table,
        data_basis: table.Table,
        # n_jobs: int = 1,
    ) -> list[dict]:

677
678
679
680
        # 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
681
682
683
684
685
686
687
688
689
        # unique obsgroup basis
        obsgroup_basis = table.unique(
            plan_basis[
                "dataset",
                "instrument",
                "obs_type",
                "obs_group",
            ]
        )
BO ZHANG's avatar
BO ZHANG committed
690

BO ZHANG's avatar
BO ZHANG committed
691
        # initialize task list
BO ZHANG's avatar
BO ZHANG committed
692
693
        task_list = []

BO ZHANG's avatar
BO ZHANG committed
694
        # loop over obsgroup
695
        for i_obsgroup in trange(len(obsgroup_basis), **TQDM_KWARGS):
BO ZHANG's avatar
BO ZHANG committed
696
697
698
699
700

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

BO ZHANG's avatar
BO ZHANG committed
701
            this_obsgroup_plan = table.join(
BO ZHANG's avatar
BO ZHANG committed
702
703
704
                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
705
                join_type=PLAN_JOIN_TYPE,
BO ZHANG's avatar
BO ZHANG committed
706
707
            )
            this_obsgroup_file = table.join(
BO ZHANG's avatar
BO ZHANG committed
708
                this_obsgroup_plan,
BO ZHANG's avatar
BO ZHANG committed
709
710
711
712
713
714
715
                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
716
            for i_obsid in range(len(this_obsgroup_plan)):
BO ZHANG's avatar
BO ZHANG committed
717
718
                # i_obsid = 1
                # print(i_obsid)
BO ZHANG's avatar
BO ZHANG committed
719
                this_instrument = this_obsgroup_plan[i_obsid]["instrument"]
BO ZHANG's avatar
BO ZHANG committed
720
                this_n_file = this_obsgroup_plan[i_obsid]["n_file"]
BO ZHANG's avatar
BO ZHANG committed
721
722
723
                this_effective_detector_names = csst[
                    this_instrument
                ].effective_detector_names
BO ZHANG's avatar
BO ZHANG committed
724
725

                this_obsgroup_obsid_file = table.join(
BO ZHANG's avatar
BO ZHANG committed
726
                    this_obsgroup_plan[i_obsid : i_obsid + 1],  # this obsid
BO ZHANG's avatar
BO ZHANG committed
727
728
729
730
                    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
731
                )
BO ZHANG's avatar
BO ZHANG committed
732

BO ZHANG's avatar
BO ZHANG committed
733
734
735
                if this_instrument == "HSTDM":
                    # 不确定以后是1个探测器还是2个探测器
                    this_n_file_found = len(this_obsgroup_obsid_file)
BO ZHANG's avatar
BO ZHANG committed
736
737
                    this_n_file_expected = this_n_file
                    this_success &= this_n_file_found == this_n_file_expected
BO ZHANG's avatar
BO ZHANG committed
738
                else:
BO ZHANG's avatar
BO ZHANG committed
739
740
741
742
743
744
745
746
                    # 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
747
748
                    )

BO ZHANG's avatar
BO ZHANG committed
749
            n_file_expected = int(this_obsgroup_plan["n_file"].sum())
BO ZHANG's avatar
BO ZHANG committed
750
            n_file_found = len(this_obsgroup_file)
751
752
753
            # 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
754
755
756
757
758
            # append this task
            task_list.append(
                dict(
                    task=this_task,
                    success=this_success,
BO ZHANG's avatar
BO ZHANG committed
759
                    relevant_plan=this_obsgroup_plan,
BO ZHANG's avatar
BO ZHANG committed
760
                    relevant_data=this_obsgroup_file,
BO ZHANG's avatar
BO ZHANG committed
761
                    n_relevant_plan=len(this_obsgroup_plan),
762
                    n_relevant_data=len(this_obsgroup_file),
763
764
765
                    relevant_data_id_list=(
                        []
                        if len(this_obsgroup_file) == 0
766
                        else list(this_obsgroup_file["_id_data"])
767
                    ),
BO ZHANG's avatar
BO ZHANG committed
768
                    n_file_expected=this_obsgroup_plan["n_file"].sum(),
769
                    n_file_found=len(this_obsgroup_file),
BO ZHANG's avatar
BO ZHANG committed
770
771
772
                )
            )
        return task_list
BO ZHANG's avatar
BO ZHANG committed
773
774

    @staticmethod
BO ZHANG's avatar
BO ZHANG committed
775
776
777
778
779
780
781
782
    def load_test_data() -> tuple:
        import joblib

        plan_recs = joblib.load("dagtest/csst-msc-c9-25sqdeg-v3.plan.dump")
        data_recs = joblib.load("dagtest/csst-msc-c9-25sqdeg-v3.level0.dump")
        print(f"{len(plan_recs.data)} plan records")
        print(f"{len(data_recs.data)} data records")
        for _ in plan_recs.data:
BO ZHANG's avatar
BO ZHANG committed
783
            _["n_file"] = (
BO ZHANG's avatar
BO ZHANG committed
784
                _["params"]["num_epec_frame"] if _["instrument"] == "HSTDM" else 1
BO ZHANG's avatar
BO ZHANG committed
785
786
787
788
789
790
791
792
793
794
            )
        plan_basis = extract_basis_table(
            plan_recs.data,
            PLAN_BASIS_KEYS,
        )
        data_basis = extract_basis_table(
            data_recs.data,
            DATA_BASIS_KEYS,
        )
        return plan_basis, data_basis