dags.py 10.5 KB
Newer Older
BO ZHANG's avatar
BO ZHANG committed
1
2
3
4
5
import json

import numpy as np
from csst_dfs_client import plan, level0

BO ZHANG's avatar
BO ZHANG committed
6
from .._csst import csst, CsstPlanObsid, CsstPlanObsgroup
BO ZHANG's avatar
BO ZHANG committed
7
from ._base_dag import BaseDAG
BO ZHANG's avatar
BO ZHANG committed
8
from .._csst import csst
BO ZHANG's avatar
BO ZHANG committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26


# DAG_DETECTOR_NAMES = {
#     "csst-msc-l1-mbi": {"detector": csst["msc"]["mbi"].effective_detector_names},
#     "csst-msc-l1-ast": {"detector": csst["msc"]["mbi"].effective_detector_names},
#     "csst-msc-l1-sls": {"detector": csst["msc"]["sls"].effective_detector_names},
#     "csst-msc-l1-qc0": {"detector": csst["msc"].effective_detector_names},
#     "csst-msc-l1-ooc": {"detector": csst["msc"].effective_detector_names},
#     "csst-mci-l1": {"detector": csst["mci"].effective_detector_names},
#     "csst-ifs-l1-rss": {"detector": csst["ifs"].effective_detector_names},
#     "csst-cpic-l1": {"detector": csst["cpic"].effective_detector_names},
#     "csst-cpic-l1-qc0": {"detector": csst["cpic"].effective_detector_names},
#     "csst-hstdm-l1": {"detector": csst["cpic"].effective_detector_names},
# }


def get_detector_names_via_dag(dag: str) -> list[str]:
    if "msc" in dag:
BO ZHANG's avatar
BO ZHANG committed
27
28
        if "mbi" in dag or "ast" in dag:
            return csst["MSC"]["MBI"].effective_detector_names
BO ZHANG's avatar
BO ZHANG committed
29
        elif "sls" in dag:
BO ZHANG's avatar
BO ZHANG committed
30
            return csst["MSC"]["SLS"].effective_detector_names
BO ZHANG's avatar
BO ZHANG committed
31
        else:
BO ZHANG's avatar
BO ZHANG committed
32
            return csst["MSC"].effective_detector_names
BO ZHANG's avatar
BO ZHANG committed
33
    elif "mci" in dag:
BO ZHANG's avatar
BO ZHANG committed
34
        return csst["MCI"].effective_detector_names
BO ZHANG's avatar
BO ZHANG committed
35
    elif "ifs" in dag:
BO ZHANG's avatar
BO ZHANG committed
36
        return csst["IFS"].effective_detector_names
BO ZHANG's avatar
BO ZHANG committed
37
    elif "cpic" in dag:
BO ZHANG's avatar
BO ZHANG committed
38
        return csst["CPIC"].effective_detector_names
BO ZHANG's avatar
BO ZHANG committed
39
    elif "hstdm" in dag:
BO ZHANG's avatar
BO ZHANG committed
40
        return csst["HSTDM"].effective_detector_names
BO ZHANG's avatar
BO ZHANG committed
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


class GeneralDAGViaObsid(BaseDAG):

    def __init__(self, dag_group: str, dag: str, use_detector: bool = False):
        super().__init__(dag_group=dag_group, dag=dag, use_detector=use_detector)
        # set effective detector names
        self.effective_detector_names = get_detector_names_via_dag(dag)

    def schedule(
        self,
        batch_id: str | None = "-",
        priority: int = 1,
        dataset: str = "csst-msc-c9-25sqdeg-v3",
        obs_type: str = "WIDE",
        obs_group: str = "W1",
        pmapname: str = "csst_000001.map",
        initial_prc_status: int = -1024,  # level0 prc_status level1
        final_prc_status: int = -2,
        demo=True,
    ):
        # no need to query plan
        # plan.write_file(local_path="plan.json")
        # plan.find(
        #     instrument="MSC",
        #     dataset=dataset,
        #     obs_type=obs_type,
        #     project_id=project_id,
        # )

        # generate a dag_group_run
        dag_group_run = self.gen_dag_group_run(
            dag_group=self.dag_group,
            batch_id=batch_id,
            priority=priority,
        )
        dag_run_list = []

        # find level0 data records
        recs = level0.find(
            instrument=self.instrument,
            dataset=dataset,
            obs_type=obs_type,
            obs_group=obs_group,
            prc_status=initial_prc_status,
        )
        assert recs.success, recs
        print(f"{len(recs.data)} records -> ", end="")

        if self.use_detector:
            # generate DAG messages via obs_id-detector
BO ZHANG's avatar
BO ZHANG committed
92
            for i_rec, this_rec in enumerate(recs.data):
BO ZHANG's avatar
tweaks    
BO ZHANG committed
93
                # print(i_rec, this_rec, self.effective_detector_names)
BO ZHANG's avatar
BO ZHANG committed
94
95
                # filter level0 data records: detector in expected list
                if this_rec["detector"] in self.effective_detector_names:
BO ZHANG's avatar
BO ZHANG committed
96

BO ZHANG's avatar
BO ZHANG committed
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
                    # generate a DAG message if is_selected
                    this_dag_run = self.gen_dag_run(
                        dag_group_run=dag_group_run,
                        dag_run=self.generate_sha1(),
                        batch_id=batch_id,
                        pmapname=pmapname,
                        dataset=dataset,
                        obs_type=obs_type,
                        obs_group=obs_group,
                        obs_id=this_rec["obs_id"],
                        detector=this_rec["detector"],
                    )
                    dag_run_list.append(this_dag_run)
                    # update level0 prc_status
                    if not demo:
                        this_update = level0.update_prc_status(
                            level0_id=this_rec["level0_id"],
                            dag_run=this_dag_run["dag_run"],
                            prc_status=final_prc_status,
                            dataset=dataset,
                        )
                        assert this_update.success, this_update.message

BO ZHANG's avatar
BO ZHANG committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
        # generate DAG messages via obs_id
        else:
            u_obsid, c_obsid = np.unique(
                [this_rec["obs_id"] for this_rec in recs.data],
                return_counts=True,
            )
            # select those obs_ids with `counts == effective detector number`
            u_obsid_selected = u_obsid[c_obsid == len(self.effective_detector_names)]
            for this_obsid in u_obsid[u_obsid_selected]:
                # generate a DAG message if is_selected
                this_dag_run = self.gen_dag_run(
                    dag_group_run=dag_group_run,
                    dag_run=self.generate_sha1(),
                    batch_id=batch_id,
                    pmapname=pmapname,
                    dataset=dataset,
                    obs_type=obs_type,
                    obs_group=obs_group,
                    obs_id=this_obsid,
BO ZHANG's avatar
BO ZHANG committed
139
                )
BO ZHANG's avatar
BO ZHANG committed
140
                dag_run_list.append(this_dag_run)
BO ZHANG's avatar
BO ZHANG committed
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

        if not demo:
            # push and update
            res_push = self.push_dag_group_run(dag_group_run, dag_run_list)
            print(
                f"{len(dag_run_list)} DAG runs -> "
                f"{json.dumps(dag_group_run, indent=None, separators=(',', ':'))} -> "
                f"{res_push}"
            )
            assert res_push.success, res_push.message
        else:
            # no push
            print(
                f"{len(dag_run_list)} DAG runs -> "
                f"{json.dumps(dag_group_run, indent=None, separators=(',', ':'))}"
            )
        # TODO: `dag_group_run` and `dag_run_list` should be dumped to a text file in the future
        return dict(
            dag_group_run=dag_group_run,
            dag_run_list=dag_run_list,
        )


class GeneralDAGViaObsgroup(BaseDAG):

    def __init__(self, dag_group: str, dag: str, use_detector: bool = False):
        super().__init__(dag_group=dag_group, dag=dag, use_detector=use_detector)
        # set effective detector names
BO ZHANG's avatar
BO ZHANG committed
169
        # self.effective_detector_names = get_detector_names_via_dag(dag)
BO ZHANG's avatar
BO ZHANG committed
170
171
172
173
174
175
176
177

    def schedule(
        self,
        batch_id: str | None = "-",
        priority: int = 1,
        dataset: str = "csst-msc-c9-25sqdeg-v3",
        obs_type: str = "WIDE",
        obs_group: str = "W1",
BO ZHANG's avatar
BO ZHANG committed
178
        pmapname: str = "csst_000001.pmap",
BO ZHANG's avatar
BO ZHANG committed
179
180
181
182
183
184
185
186
187
188
189
190
        initial_prc_status: int = -1024,  # level0 prc_status level1
        final_prc_status: int = -2,
        demo=True,
    ):
        # generate a dag_group_run
        dag_group_run = self.gen_dag_group_run(
            dag_group=self.dag_group,
            batch_id=batch_id,
            priority=priority,
        )
        dag_run_list = []

BO ZHANG's avatar
BO ZHANG committed
191
192
193
194
195
196
197
        instrument = "MSC"
        obs_type = "BIAS"
        obs_group = "bias-temperature-var"
        dataset = "csst-msc-c9-ooc-v1"
        initial_prc_status = -1024
        final_prc_status = -2

BO ZHANG's avatar
BO ZHANG committed
198
        # find plan with compact mode
BO ZHANG's avatar
BO ZHANG committed
199
200
        qr_count = plan.count_plan_level0(
            instrument=instrument,
BO ZHANG's avatar
BO ZHANG committed
201
202
203
204
205
            obs_type=obs_type,
            obs_group=obs_group,
            dataset=dataset,
            prc_status=initial_prc_status,
        )
BO ZHANG's avatar
BO ZHANG committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
        assert qr_count.success, qr_count
        n_plan = qr_count.data["plan_count"]
        n_level0 = qr_count.data["level0_count"]
        assert n_plan > 0, f"No plan found for {obs_type} {obs_group} {dataset}"
        assert (
            n_level0 > 0
        ), f"No level0 record found for {obs_type} {obs_group} {dataset}"

        # find plan and level0 data
        qr_plan = plan.find(
            instrument=instrument,
            obs_type=obs_type,
            obs_group=obs_group,
            dataset=dataset,
BO ZHANG's avatar
BO ZHANG committed
220
        )
BO ZHANG's avatar
BO ZHANG committed
221
222
223
224
225
226
227
228
229
        qr_level0 = level0.find(
            instrument=instrument,
            obs_type=obs_type,
            obs_group=obs_group,
            dataset=dataset,
            prc_status=initial_prc_status,
        )

        obs_group = CsstPlanObsgroup.from_plan(qr_plan.data)
BO ZHANG's avatar
BO ZHANG committed
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

        # find level0 records
        if n_plan == 0:
            print(f"No plan found for {obs_type} {obs_group} {dataset}")
        if n_level0 < n_plan * self.n_effective_detector:
            print(
                f"Plan {obs_type} {obs_group} {dataset} has {n_plan} plans, "
                f"but {n_level0} level0 records found"
            )
        if n_plan == n_level0 * self.n_effective_detector:
            print(
                f"Plan {obs_type} {obs_group} {dataset} has {n_plan} plans, "
                f"and {n_level0} level0 records found"
            )

            # generate DAG run list
            if not self.use_detector:
                # generate a DAG run via obs_group
                this_dag_run = self.gen_dag_run(
                    dag_group_run=dag_group_run,
                    batch_id=batch_id,
                    dag_run=self.generate_sha1(),
                    dataset=dataset,
                    obs_type=obs_type,
                    obs_group=obs_group,
                    pmapname=pmapname,
                )
                dag_run_list.append(this_dag_run)
            else:
                # generate DAG runs via obs_group-detectors
                for this_detector in self.effective_detector_names:

                    this_dag_run = self.gen_dag_run(
                        dag_group_run=dag_group_run,
                        batch_id=batch_id,
                        dag_run=self.generate_sha1(),
                        dataset=dataset,
                        obs_type=obs_type,
                        obs_group=obs_group,
                        detector=this_detector,
                        pmapname=pmapname,
                    )
                    dag_run_list.append(this_dag_run)
            if not demo:
                # push and update
                res_push = self.push_dag_group_run(dag_group_run, dag_run_list)
                print(
                    f"{len(dag_run_list)} DAG runs -> "
                    f"{json.dumps(dag_group_run, indent=None, separators=(',', ':'))} -> "
                    f"{res_push}"
                )

        return dict(
            dag_group_run=dag_group_run,
            dag_run_list=dag_run_list,
        )