-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.py
2027 lines (1791 loc) · 72.2 KB
/
index.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2020-2022 AstroLab Software
# Author: Julien Peloton
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import dash
from dash import (
html,
dcc,
Input,
Output,
State,
dash_table,
no_update,
clientside_callback,
ALL,
MATCH,
)
from dash.exceptions import PreventUpdate
import dash_bootstrap_components as dbc
import visdcc
import dash_mantine_components as dmc
from dash_iconify import DashIconify
from dash_autocomplete_input import AutocompleteInput
from app import server
from app import app
from app import APIURL
from apps import summary, about, statistics, query_cluster, gw
from apps.api import api
from apps.utils import markdownify_objectid, class_colors, simbad_types
from apps.utils import isoify_time
from apps.utils import convert_jd
from apps.utils import retrieve_oid_from_metaname
from apps.utils import help_popover
from apps.utils import request_api
from apps.plotting import draw_cutouts_quickview, draw_lightcurve_preview
from apps.cards import card_search_result
from apps.parse import parse_query
import pandas as pd
import numpy as np
import urllib
tns_types = pd.read_csv("assets/tns_types.csv", header=None)[0].to_numpy()
tns_types = sorted(tns_types, key=lambda s: s.lower())
fink_classes = [
"All classes",
"Anomaly",
"Unknown",
# Fink derived classes
"Early SN Ia candidate",
"SN candidate",
"Kilonova candidate",
"Microlensing candidate",
"Solar System MPC",
"Solar System candidate",
"Tracklet",
"Ambiguous",
# TNS classified data
*["(TNS) " + t for t in tns_types],
# Simbad crossmatch
*["(SIMBAD) " + t for t in simbad_types],
]
message_help = """
You may search for different kinds of data depending on what you enter. Below you will find the description of syntax rules and some examples.
The search is defined by the set of search terms (object names or coordinates) and options (e.g. search radius, number of returned entries, etc). The latters may be entered either manually or by using the `Quick fields` above the search bar. Supported formats for the options are both `name=value` and `name:value`, where `name` is case-insensitive, and `value` may use quotes to represent multi-word sentences. For some of the options, interactive drop-down menu will be shown with possible values.
The search bar has a button (on the left) to show you the list of your latest search queries so that you may re-use them, and a switch (on the right, right above the search field) to choose the format of results - either card-based (default, shows the previews of object latest cutout and light curve), or tabular (allows to see all the fields of objects).
##### Search for specific ZTF objects
To search for specific object, just use its name, or just a part of it. In the latter case, all objects with the names starting with this pattern will be returned.
Supported name patterns are as follows:
- `ZTFyyccccccc` for ZTF objects, i.e. ZTF followed with 2 digits for the year, and 7 characters after that
- `TRCK_YYYYMMDD_HHMMSS_NN` for tracklets detected at specific moment of time
Examples:
- `ZTF21abfmbix` - search for exact ZTF object
- `ZTF21abfmb` - search for partially matched ZTF object name
- `TRCK_20231213_133612_00` - search for all objects associated with specific tracklet
- `TRCK_20231213` - search for all tracklet events from the night of Dec 13, 2023
##### Search around known astronomical objects
You can run a conesearch around a known astronomical name. Examples:
- Extended objects: M31
- Catalog names: TXS 0506+056
- TNS names: AT 2019qiz, SN 2024aaj
By default, the conesearch radius is 10 arcseconds. You can change the radius by specifying `r=<number>` after the name, e.g. `Crab Nebula r=10m` (see the section Cone Search below).
##### Cone search
If you specify the position and search radius (using `r` option), all objects inside the given cone will be returned. Position may be specified by either coordinates, in either decimal or sexagesimal form, as exact ZTF object name, or as an object name resolvable through TNS or Simbad.
The coordinates may be specified as:
- Pair of degrees
- `HH MM SS.S [+-]?DD MM SS.S`
- `HH:MM:SS.S [+-]?DD:MM:SS.S`
- `HHhMMhSS.Ss [+-]?DDhMMhSS.Ss`
- optionally, you may use one more number as a radius, in either arcseconds, minutes (suffixed with `m`) or degrees (`d`). If specified, you do not need to provide the corresponding keyword (`r`) separately
If the radius is not specified, but the coordinates or resolvable object names are given, the default search radius is 10 arcseconds.
You may also restrict the alert time by specifying `after` and `before` keywords. They may be given as UTC timestamps in either ISO string format, as Julian date, or MJD. Alternatively, you may use `window` keyword to define the duration of time window in days.
Examples:
- `10 20 30` - search within 30 arcseconds around `RA=10 deg` `Dec=20 deg`
- `10 20 30 after="2023-03-29 13:36:52" window=10` - the same but also within 10 days since specified time moment
- `10 22 31 40 50 55.5` - search within 10 arcseconds around `RA=10:22:31` `Dec=+40:50:55.5`
- `Vega r=10m` - search within 600 arcseconds (10 arcminutes) from Vega
- `ZTF21abfmbix r=20` - search within 20 arcseconds around the position of ZTF21abfmbix
- `AT2021co` or `AT 2021co` - search within 10 arcseconds around the position of AT2021co
##### Date range search
The search of all objects within specified time range may be done by specifying just the `after`, `before` and/or `window` keywords. As the amount of objects is huge, it is not practical to use time window larger than 3 hours, and it is currently capped at this value. Moreover, the number of returned objects is limited to 1000.
Examples:
- `after="2023-12-29 13:36:52" before="2023-12-29 13:46:52"` - search all objects within 10 minutes long time window
- `after="2023-12-29 13:36:52" window=0.007` - the same
##### Solar System objects
To search for all ZTF objects associated with specific SSO, you may either directly specify `sso` keyword, which should be equal to contents of `i:ssnamenr` field of ZTF packets, or just enter the number or name of the SSO object that the system will try to resolve.
So you may e.g. search for:
- Asteroids by proper name
- `Vesta`
- Asteroids by number
- Asteroids (Main Belt): `8467`, `1922`, `33803`
- Asteroids (Hungarians): `18582`, `77799`
- Asteroids (Jupiter Trojans): `4501`, `1583`
- Asteroids (Mars Crossers): `302530`
- Asteroids by designation
- `2010JO69`, `2017AD19`, `2012XK111`
- Comets by number
- `10P`, `249P`, `124P`
- Comets by designation
- `C/2020V2`, `C/2020R2`
##### Latest objects
To see the latest objects just specify the amount of them you want to get using keyword `last`.
##### Class-based search
To see the list of latest objects of specific class (as listed in `v:classification` alert field), just specify the `class` keyword. By default it will return 100 latest ones, but you may also directly specify `last` keywords to alter it.
You may also specify the time interval to refine the search, using the self-explanatory keywords `before` and `after`. The limits may be specified with either time string, JD or MJD values. You may either set both limiting values, or just one of them. The results will be sorted in descending order by time, and limited to specified number of entries.
Examples:
- `last=100` or `class=allclasses` - return 100 latest objects of any class
- `class=Unknown` - return 100 latest objects with class `Unknown`
- `last=10 class="Early SN Ia candidate"` - return 10 latest arly SN Ia candidates
- `class="Early SN Ia candidate" before="2023-12-01" after="2023-11-15 04:00:00"` - objects of the same class between 4am on Nov 15, 2023 and Dec 1, 2023
##### Random objects
To get random subset of objects just specify the amount of them you want to get using keyword `random`. You may also refine it by adding the class using `class` keyword.
Examples:
- `random=10 class=Unknown` - return 10 random objects of class `Unknown`
"""
msg_info = """
The `Card view` shows the cutout from science image, some basic alert info, and its light curve. Its header also displays the badges for alert classification and the distances from several reference catalogs, as listed in the alert.
By default, the `Table view` shows the following fields:
- i:objectId: Unique identifier for this object
- i:ra: Right Ascension of candidate; J2000 (deg)
- i:dec: Declination of candidate; J2000 (deg)
- v:lastdate: last date the object has been seen by Fink
- v:classification: Classification inferred by Fink (Supernova candidate, Microlensing candidate, Solar System, SIMBAD class, ...)
- i:ndethist: Number of spatially coincident detections falling within 1.5 arcsec going back to the beginning of the survey; only detections that fell on the same field and readout-channel ID where the input candidate was observed are counted. All raw detections down to a photometric S/N of ~ 3 are included.
- v:lapse: number of days between the first and last spatially coincident detections.
You can also add more columns using the dropdown button above the result table. Full documentation of all available fields can be found at {}/api/v1/columns.
The button `Sky Map` will open a popup with embedded Aladin sky map showing the positions of the search results on the sky.
""".format(APIURL)
# Smart search field
quick_fields = [
["class", "Alert class\nSelect one of Fink supported classes from the menu"],
["last", "Number of latest alerts to show"],
[
"radius",
"Radius for cone search\nMay be used as either `r` or `radius`\nIn arcseconds by default, use `r=1m` or `r=2d` for arcminutes or degrees, correspondingly",
],
["after", "Lower timit on alert time\nISO time, MJD or JD"],
["before", "Upper timit on alert time\nISO time, MJD or JD"],
["window", "Time window length\nDays"],
["random", "Number of random objects to show"],
]
fink_search_bar = [
html.Div(
[
html.Span("Quick fields:", className="text-secondary"),
]
+ [
html.Span(
[
html.A(
__[0],
title=__[1],
id={
"type": "search_bar_quick_field",
"index": _,
"text": __[0],
},
n_clicks=0,
className="ms-2 link text-decoration-none",
),
" ",
]
)
for _, __ in enumerate(quick_fields)
]
+ [
html.Span(
dmc.Switch(
radius="xl",
size="sm",
offLabel=DashIconify(icon="radix-icons:id-card", width=15),
onLabel=DashIconify(icon="radix-icons:table", width=15),
color="orange",
checked=False,
persistence=True,
id="results_table_switch",
),
className="float-end",
title="Show results as cards or table",
),
],
className="ps-4 pe-4 mb-0 mt-1",
),
] + [
html.Div(
# className='p-0 m-0 border shadow-sm rounded-3',
className="pt-0 pb-0 ps-1 pe-1 m-0 rcorners2 shadow",
id="search_bar",
# className='rcorners2',
children=[
dbc.InputGroup(
[
# History
dmc.Menu(
[
dmc.MenuTarget(
dmc.ActionIcon(
DashIconify(icon="bi:clock-history"),
color="gray",
variant="transparent",
radius="xl",
size="lg",
# title="Search history",
)
),
dmc.MenuDropdown(
[
dmc.MenuLabel("Search history is empty"),
],
className="shadow rounded",
id="search_history_menu",
),
],
zIndex=1000000,
),
# Main input
AutocompleteInput(
id="search_bar_input",
placeholder="Search, and you will find",
component="input",
trigger=[
"class:",
"class=",
"last:",
"last=",
"radius:",
"radius=",
"r:",
"r=",
],
options={
"class:": fink_classes,
"class=": fink_classes,
"last:": ["1", "10", "100", "1000"],
"last=": ["1", "10", "100", "1000"],
"radius:": ["10", "60", "10m", "30m"],
"radius=": ["10", "60", "10m", "30m"],
"r:": ["10", "60", "10m", "30m"],
"r=": ["10", "60", "10m", "30m"],
},
maxOptions=0,
className="inputbar form-control border-0",
quoteWhitespaces=True,
autoFocus=True,
ignoreCase=True,
triggerInsideWord=False,
matchAny=True,
),
# Clear
dmc.ActionIcon(
DashIconify(icon="mdi:clear-bold"),
n_clicks=0,
id="search_bar_clear",
color="gray",
variant="subtle",
radius="xl",
size="lg",
# title="Clear the input",
),
# Submit
dbc.Spinner(
dmc.ActionIcon(
DashIconify(icon="tabler:search", width=20),
n_clicks=0,
id="search_bar_submit",
color="gray",
variant="transparent",
radius="xl",
size="lg",
loaderProps={"variant": "dots", "color": "orange"},
# title="Search",
),
size="sm",
color="warning",
),
# Help popup
help_popover(
[dcc.Markdown(message_help)],
"help_search",
trigger=dmc.ActionIcon(
DashIconify(icon="mdi:help"),
id="help_search",
color="gray",
variant="transparent",
radius="xl",
size="lg",
# className="d-none d-sm-flex"
# title="Show some help",
),
),
]
),
# Search suggestions
dbc.Collapse(
dbc.ListGroup(
id="search_bar_suggestions",
),
id="search_bar_suggestions_collapser",
is_open=False,
),
# Debounce timer
dcc.Interval(
id="search_bar_timer", interval=2000, max_intervals=1, disabled=True
),
dcc.Store(
id="search_history_store",
storage_type="local",
),
],
)
]
# Time-based debounce from https://joetatusko.com/2023/07/11/time-based-debouncing-with-plotly-dash/
clientside_callback(
"""
function start_suggestion_debounce_timer(value, n_submit, n_clicks, n_intervals) {
const triggered = dash_clientside.callback_context.triggered.map(t => t.prop_id);
if (triggered == 'search_bar_input.n_submit' || triggered == 'search_bar_submit.n_clicks')
return [dash_clientside.no_update, true];
if (n_intervals > 0)
return [0, false];
else
return [dash_clientside.no_update, false];
}
""",
[Output("search_bar_timer", "n_intervals"), Output("search_bar_timer", "disabled")],
Input("search_bar_input", "value"),
Input("search_bar_input", "n_submit"),
Input("search_bar_submit", "n_clicks"),
State("search_bar_timer", "n_intervals"),
prevent_initial_call=True,
)
# Search history
@app.callback(
Output("search_history_menu", "children"),
Input("search_history_store", "timestamp"),
Input("search_history_store", "data"),
)
def update_search_history_menu(timestamp, history):
if history:
return [
dmc.MenuLabel("Search history"),
] + [
dmc.MenuItem(
item,
id={"type": "search_bar_completion", "index": 1000 + i, "text": item},
)
for i, item in enumerate(history[::-1])
]
else:
return no_update
# Update suggestions on (debounced) input
@app.callback(
Output("search_bar_suggestions", "children"),
Output("search_bar_submit", "children"),
Output("search_bar_suggestions_collapser", "is_open"),
Input("search_bar_timer", "n_intervals"),
Input("search_bar_input", "n_submit"),
Input("search_bar_submit", "n_clicks"),
# Next input uses dynamically created source, so has to be pattern-matching
Input({"type": "search_bar_suggestion", "value": ALL}, "n_clicks"),
State("search_bar_input", "value"),
prevent_initial_call=True,
)
def update_suggestions(n_intervals, n_submit, n_clicks, s_n_clicks, value):
# Clear the suggestions on submit by various means
ctx = dash.callback_context
triggered_id = ctx.triggered[0]["prop_id"].split(".")[0]
if triggered_id in [
"search_bar_input",
"search_bar_submit",
'{"type":"search_bar_suggestion","value":0}',
]:
return no_update, no_update, False
# Did debounce trigger fire?..
if n_intervals != 1:
return no_update, no_update, no_update
if not value.strip():
return None, no_update, False
query = parse_query(value, timeout=5)
suggestions = []
params = query["params"]
if not query["action"]:
return None, no_update, False
if query["action"] == "unknown":
content = [html.Div(html.Em("Query not recognized", className="m-0"))]
else:
content = []
if query["completions"]:
completions = []
for i, item in enumerate(query["completions"]):
if isinstance(item, list) or isinstance(item, tuple):
# We expect it to be (name, ext)
name = item[0]
ext = item[1]
else:
name = item
ext = item
completions.append(
html.A(
ext,
id={"type": "search_bar_completion", "index": i, "text": name},
title=name,
n_clicks=0,
className="ms-2 link text-decoration-none",
)
)
suggestions.append(
dbc.ListGroupItem(
html.Div(
[
html.Span("Did you mean:", className="text-secondary"),
]
+ completions
),
className="border-bottom p-1 mt-1 small",
)
)
content += [
dmc.Group(
[
html.Strong(query["object"]) if query["object"] else None,
dmc.Badge(query["type"], variant="outline", color="blue")
if query["type"]
else None,
dmc.Badge(query["action"], variant="outline", color="red"),
],
wrap="wrap",
align="left",
),
html.P(query["hint"], className="m-0"),
]
if len(params):
content += [
html.Small(" ".join(["{}={}".format(_, params[_]) for _ in params]))
]
suggestion = dbc.ListGroupItem(
content,
action=True,
n_clicks=0,
# We make it pattern-matching so that it is possible to catch it in global callbacks
id={"type": "search_bar_suggestion", "value": 0},
className="border-0",
)
suggestions.append(suggestion)
return suggestions, no_update, True
# Completion clicked
clientside_callback(
"""
function on_completion(n_clicks) {
const ctx = dash_clientside.callback_context;
let triggered_id = ctx.triggered[0].prop_id;
if (!ctx.triggered[0].value)
return dash_clientside.no_update;
if (triggered_id.search('.n_clicks') > 0) {
triggered_id = JSON.parse(triggered_id.substr(0, triggered_id.indexOf('.n_clicks')));
return triggered_id.text + ' ';
}
return dash_clientside.no_update;
}
""",
Output("search_bar_input", "value", allow_duplicate=True),
Input({"type": "search_bar_completion", "index": ALL, "text": ALL}, "n_clicks"),
prevent_initial_call=True,
)
# Quick field clicked
clientside_callback(
"""
function on_quickfield(n_clicks, value) {
const ctx = dash_clientside.callback_context;
let triggered_id = ctx.triggered[0].prop_id;
if (!ctx.triggered[0].value)
return dash_clientside.no_update;
if (triggered_id.search('.n_clicks') > 0) {
triggered_id = JSON.parse(triggered_id.substr(0, triggered_id.indexOf('.n_clicks')));
if (value)
return value + ' ' + triggered_id.text + '=';
else
return triggered_id.text + '=';
}
return dash_clientside.no_update;
}
""",
Output("search_bar_input", "value", allow_duplicate=True),
Input({"type": "search_bar_quick_field", "index": ALL, "text": ALL}, "n_clicks"),
State("search_bar_input", "value"),
prevent_initial_call=True,
)
# Clear inpit field
clientside_callback(
"""
function on_clear(n_clicks) {
return '';
}
""",
Output("search_bar_input", "value", allow_duplicate=True),
Input("search_bar_clear", "n_clicks"),
prevent_initial_call=True,
)
# Disable clear button for empty input field
# clientside_callback(
# """
# function on_input(value) {
# if (value)
# return false;
# else
# return true;
# }
# """,
# Output("search_bar_clear", "disabled"),
# Input("search_bar_input", "value"),
# )
def display_table_results(table):
"""Display explorer results in the form of a table with a dropdown menu on top to insert more data columns.
The dropdown menu options are taken from the client schema (ZTF & Fink). It also
contains other derived fields from the portal (fink_additional_fields).
Parameters
----------
table: dash_table.DataTable
Dash DataTable containing the results. Can be empty.
Returns
-------
out: list of objects
The list of objects contain:
1. A dropdown menu to add new columns in the table
2. Table of results
The dropdown is shown only if the table is non-empty.
"""
pdf = request_api("/api/v1/columns", method="GET")
fink_fields = [
"d:" + i for i in pdf.loc["Fink science module outputs (d:)"]["fields"].keys()
]
ztf_fields = [
"i:" + i for i in pdf.loc["ZTF original fields (i:)"]["fields"].keys()
]
fink_additional_fields = [
"v:constellation",
"v:g-r",
"v:rate(g-r)",
"v:classification",
"v:lastdate",
"v:firstdate",
"v:lapse",
]
dropdown = dcc.Dropdown(
id="field-dropdown2",
options=[
{"label": "Fink science module outputs", "disabled": True, "value": "None"},
*[{"label": field, "value": field} for field in fink_fields],
{"label": "Fink additional values", "disabled": True, "value": "None"},
*[{"label": field, "value": field} for field in fink_additional_fields],
{
"label": "Original ZTF fields (subset)",
"disabled": True,
"value": "None",
},
*[{"label": field, "value": field} for field in ztf_fields],
],
searchable=True,
clearable=True,
placeholder="Add more fields to the table",
)
switch = dmc.Switch(
size="xs",
radius="xl",
label="Unique objects",
color="orange",
checked=False,
id="alert-object-switch",
)
switch_description = "Toggle the switch to list each object only once. Only the latest alert will be displayed."
switch_sso = dmc.Switch(
size="xs",
radius="xl",
label="Unique SSO",
color="orange",
checked=False,
id="alert-sso-switch",
)
switch_sso_description = "Toggle the switch to list each Solar System Object only once. Only the latest alert will be displayed."
switch_tracklet = dmc.Switch(
size="xs",
radius="xl",
label="Unique tracklets",
color="orange",
checked=False,
id="alert-tracklet-switch",
)
switch_tracklet_description = "Toggle the switch to list each Tracklet only once (fast moving objects). Only the latest alert will be displayed."
results = [
dbc.Row(
[
dbc.Col(dropdown, lg=5, md=6),
dbc.Col(
dmc.Tooltip(
children=switch,
w=220,
multiline=True,
withArrow=True,
transitionProps={"transition": "fade", "duration": 200},
label=switch_description,
),
md="auto",
),
dbc.Col(
dmc.Tooltip(
children=switch_sso,
w=220,
multiline=True,
withArrow=True,
transitionProps={"transition": "fade", "duration": 200},
label=switch_sso_description,
),
md="auto",
),
dbc.Col(
dmc.Tooltip(
children=switch_tracklet,
w=220,
multiline=True,
withArrow=True,
transitionProps={"transition": "fade", "duration": 200},
label=switch_tracklet_description,
),
md="auto",
),
],
align="center",
justify="start",
className="mb-2",
),
table,
]
return [
html.Div(
results,
className="results-inner bg-opaque-100 rounded mb-4 p-2 border shadow",
style={"overflow": "visible"},
)
]
@app.callback(
Output("aladin-lite-div-skymap", "run"),
[
Input("result_table", "data"),
Input("result_table", "columns"),
Input("modal_skymap", "is_open"),
],
)
def display_skymap(data, columns, is_open):
"""Display explorer result on a sky map (Aladin lite). Limited to 1000 sources total.
TODO: image is not displayed correctly the first time
the default parameters are:
* PanSTARRS colors
* FoV = 360 deg
* Fink alerts overlayed
Callbacks
----------
Input: takes the validation flag (0: no results, 1: results) and table data
Output: Display a sky image around the alert position from aladin.
"""
if not is_open:
return no_update
if len(data) > 0:
if len(data) > 1000:
# Silently limit the size of list we display
data = data[:1000]
pdf = pd.DataFrame(data)
# Coordinate of the first alert
ra0 = pdf["i:ra"].to_numpy()[0]
dec0 = pdf["i:dec"].to_numpy()[0]
# Javascript. Note the use {{}} for dictionary
# Force redraw of the Aladin lite window
img = """var container = document.getElementById('aladin-lite-div-skymap');var txt = ''; container.innerHTML = txt;"""
# Aladin lite
img += """
var a = A.aladin('#aladin-lite-div-skymap',
{{
target: '{} {}',
survey: 'https://alasky.cds.unistra.fr/Pan-STARRS/DR1/color-z-zg-g/',
showReticle: true,
allowFullZoomout: true,
showContextMenu: true,
showCooGridControl: true,
fov: 360
}}
);
""".format(ra0, dec0)
ras = pdf["i:ra"].to_numpy()
decs = pdf["i:dec"].to_numpy()
filts = pdf["i:fid"].to_numpy()
filts_dic = {1: "g", 2: "r"}
if "v:lastdate" not in pdf.columns:
# conesearch does not expose v:lastdate
pdf["v:lastdate"] = convert_jd(pdf["i:jd"])
times = pdf["v:lastdate"].to_numpy()
link = '<a target="_blank" href="{}/{}">{}</a>'
titles = [
link.format(
APIURL, i.split("]")[0].split("[")[1], i.split("]")[0].split("[")[1]
)
for i in pdf["i:objectId"].to_numpy()
]
mags = pdf["i:magpsf"].to_numpy()
if "v:classification" not in pdf.columns:
if "d:classification" in pdf.columns:
pdf["v:classification"] = pdf["d:classification"]
else:
pdf["v:classification"] = "Unknown"
classes = pdf["v:classification"].to_numpy()
n_alert_per_class = (
pdf.groupby("v:classification").count().to_dict()["i:objectId"]
)
cats = []
for ra, dec, fid, time_, title, mag, class_ in zip(
ras, decs, filts, times, titles, mags, classes
):
if class_ in simbad_types:
cat = "cat_{}".format(simbad_types.index(class_))
color = class_colors["Simbad"]
elif class_ in class_colors.keys():
cat = "cat_{}".format(class_.replace(" ", "_"))
color = class_colors[class_]
else:
# Sometimes SIMBAD mess up names :-)
cat = "cat_{}".format(class_)
color = class_colors["Simbad"]
if cat not in cats:
img += """var {} = A.catalog({{name: '{}', sourceSize: 15, shape: 'circle', color: '{}', onClick: 'showPopup', limit: 1000}});""".format(
cat, class_ + " ({})".format(n_alert_per_class[class_]), color
)
cats.append(cat)
img += """{}.addSources([A.source({}, {}, {{objectId: '{}', mag: {:.2f}, filter: '{}', time: '{}', Classification: '{}'}})]);""".format(
cat, ra, dec, title, mag, filts_dic[fid], time_, class_
)
for cat in sorted(cats):
img += """a.addCatalog({});""".format(cat)
# img cannot be executed directly because of formatting
# We split line-by-line and remove comments
img_to_show = [i for i in img.split("\n") if "// " not in i]
return " ".join(img_to_show)
else:
return ""
def modal_skymap():
button = dmc.Button(
"Sky Map",
id="open_modal_skymap",
n_clicks=0,
leftSection=DashIconify(icon="bi:stars"),
color="gray",
fullWidth=True,
variant="default",
radius="xl",
)
modal = html.Div(
[
button,
dbc.Modal(
[
# loading(
dbc.ModalBody(
html.Div(
[
visdcc.Run_js(
id="aladin-lite-div-skymap",
style={"border": "0"},
),
# dcc.Markdown('_Hit the Aladin Lite fullscreen button if the image is not displayed (we are working on it...)_'),
],
style={
"width": "100%",
"height": "100%",
},
),
className="p-1",
style={"height": "30pc"},
),
# ),
dbc.ModalFooter(
dmc.Button(
"Close",
id="close_modal_skymap",
className="ml-auto",
color="gray",
# fullWidth=True,
variant="default",
radius="xl",
),
),
],
id="modal_skymap",
is_open=False,
size="lg",
# fullscreen="lg-down",
),
]
)
return modal
clientside_callback(
"""
function toggle_modal_skymap(n1, n2, is_open) {
if (n1 || n2)
return ~is_open;
else
return is_open;
}
""",
Output("modal_skymap", "is_open"),
[Input("open_modal_skymap", "n_clicks"), Input("close_modal_skymap", "n_clicks")],
[State("modal_skymap", "is_open")],
prevent_initial_call=True,
)
def populate_result_table(data, columns):
"""Define options of the results table, and add data and columns"""
page_size = 100
markdown_options = {"link_target": "_blank"}
table = dash_table.DataTable(
data=data,
columns=columns,
id="result_table",
page_size=page_size,
# page_action='none',
style_as_list_view=True,
sort_action="native",
filter_action="native",
markdown_options=markdown_options,
# fixed_columns={'headers': True, 'data': 1},
style_data={
"backgroundColor": "rgb(248, 248, 248, 1.0)",
},
style_table={"maxWidth": "100%", "overflowX": "scroll"},
style_cell={
"padding": "5px",
"textAlign": "right",
"overflow": "hidden",
"font-family": "sans-serif",
"fontSize": 14,
},
style_data_conditional=[
{
"if": {"column_id": "i:objectId"},
"backgroundColor": "rgb(240, 240, 240, 1.0)",
}
],
style_header={
"backgroundColor": "rgb(230, 230, 230)",
"fontWeight": "bold",
"textAlign": "center",
},
# Align the text in Markdown cells
css=[dict(selector="p", rule="margin: 0; text-align: left")],
)
return table
@app.callback(
[
Output("result_table", "data"),