-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.xql
1437 lines (1297 loc) · 81.7 KB
/
app.xql
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
xquery version "3.1";
(:~ This is the default application library module of the searchftt app.
:
: @author JMMC Tech Group
: @see https://www.jmmc.fr
:)
(: Module for app-specific template functions :)
module namespace app="http://exist.jmmc.fr/searchftt/apps/searchftt/templates";
import module namespace templates="http://exist-db.org/xquery/html-templating";
import module namespace lib="http://exist-db.org/xquery/html-templating/lib";
import module namespace config="http://exist.jmmc.fr/searchftt/apps/searchftt/config" at "config.xqm";
import module namespace jmmc-tap="http://exist.jmmc.fr/jmmc-resources/tap" at "/db/apps/jmmc-resources/content/jmmc-tap.xql";
import module namespace jmmc-simbad="http://exist.jmmc.fr/jmmc-resources/simbad" at "/db/apps/jmmc-resources/content/jmmc-simbad.xql";
import module namespace jmmc-ws="http://exist.jmmc.fr/jmmc-resources/ws" at "/db/apps/jmmc-resources/content/jmmc-ws.xql";
import module namespace astro="http://exist.jmmc.fr/searchftt/astro" at "astro.xql";
(:import module namespace jmmc-astro="http://exist.jmmc.fr/jmmc-resources/astro" at "/db/apps/jmmc-resources/content/jmmc-astro.xql";:) (: WARNING this module require to enable eXistDB's Java Binding :)
(: DEV HINTS:
- prefer lower_case colnames since some backend rewrite to lower case input colnames
- we could refactor with a map that would store column names so we replace and avoid use of error prone strings searching for come columns
- we could extend the default map (and rename it to config ? ) so we can store more than max values and associate for each of them more metadata : desc, displayorder...)
FUTURE IDEAS/TODOS :
- present ft/ao tuples in the science table with a wait to keep only the best one so we can transmit them to Aspro2
- add a constraint on tmass_dist so we avoid wrong GAIA Xmatches
- show table overflow reaching max_result_table_rows !
- add units in table
- use cookies to store user defined values
- move magnitude field names to standart notation https://vizier.cds.unistra.fr/vizier/catstd/catstd.htx
- do chunk of long votables before quering TAP
- support coord+pm when simbad does resolv it!
- add objtypes while resolving simbad
:)
(: suffix used in maps to provide a text or html documentation :)
declare variable $app:doc-suffix := "_doc";
(: Main config to unify catalog accross their colnames or simbad :)
declare variable $app:json-conf :='{
"default":{
"max_magV" : 15,
"max_magK_UT" : 11,
"max_magK_AT" : 10,
"max_magR" : 12.5,
"max_AO_mag": 12.5,
"max_AO_mag_doc": "use Gmag if present in catalogs else Rmag or Vmag",
"max_FT_mag": 12,
"max_dist_as" : 30,
"max_declination" : 40,
"max_rec" : 25,
"max_result_table_rows" : 1000,
"max_rank" : 4,
"max_rank_doc" : "max number of best AOFT tuples sorted by score. This is the rank",
"min_score" : 0.0,
"min_score_doc" : "1= best performance, 0= worst performance",
"preferred_bulk_catalog" : "Gaia DR3",
"max_rows_from_vizier" : 500
},
"aspro-cols" : {"pmra":"PMRA", "pmdec":"PMDEC", "mag_v": "FLUX_V", "mag_r": "FLUX_R", "mag_g": "FLUX_G", "mag_ks": "FLUX_K"},
"extended-cols" : [ "pmra", "pmdec", "pmde", "epoch", "cat_dist_as", "today_dist_as", "id", "str_source_id", "name" ],
"samestar-dist_deg" : 2.78E-4,
"samestar-dist_as" : 1,
"catalogs":{
"simcat": {
"cat_name":"Simbad",
"main_cat":true,
"bulk" : true,
"description": "<a href='http://simbad.u-strasbg.fr/'>CDS / Simbad</a>",
"tap_endpoint": "http://simbad.u-strasbg.fr/simbad/sim-tap/sync",
"tap_format" : "",
"tap_viewer" : "",
"simbad_prefix_id" : "",
"source_id": "basic.main_id",
"epoch" : 2000,
"ra" : "basic.ra",
"dec" : "basic.dec",
"pmra" : "basic.pmra",
"pmdec" : "basic.pmdec",
"mag_k" : "allfluxes.K",
"mag_g" : "allfluxes.G",
"mag_bp" : "",
"mag_rp" : "",
"mag_v" : "allfluxes.V",
"mag_r" : "allfluxes.R",
"detail" : { "otype_txt":"otype_txt" },
"from" : "basic JOIN allfluxes ON oid=oidref"
},
"gdr2ap": {
"cat_name":"GDR2AP",
"main_cat":false,
"description": "The <a href='https://ui.adsabs.harvard.edu/abs/2022arXiv220103252F/abstract'>Astrophysical Parameters from Gaia DR2, 2MASS &amp; AllWISE</a> catalog through the GAVO DC.",
"tap_endpoint": "https://dc.zah.uni-heidelberg.de/tap/sync",
"tap_format" : "",
"tap_viewer" : "http://dc.g-vo.org/__system__/adql/query/form?__nevow_form__=genForm&_FORMAT=HTML&submit=Go&query=",
"simbad_prefix_id" : "Gaia DR2 ",
"source_id":"gaia.dr2light.source_id",
"epoch" : 2015.5,
"ra" :"gaia.dr2light.ra",
"dec" :"gaia.dr2light.dec",
"pmra" : "pmra",
"pmdec" : "pmdec",
"old_pos_others" : "(-15.5*pmra/1000.0) as delta_ra2000_as, (-15.5*pmdec/1000.0) as delta_de2000_as, (ra-15.5*pmra/3600000.0) as RA2000, (dec-15.5*pmdec/3600000.0) as de2000",
"mag_k" : "mag_ks",
"mag_g" : "mag_g",
"mag_bp" : "mag_bp",
"mag_rp" : "mag_rp",
"detail" : { },
"from" : "gaia.dr2light JOIN gdr2ap.main ON gaia.dr2light.source_id=gdr2ap.main.source_id"
},"esagaia3": {
"cat_name" : "Gaia DR3",
"main_cat" : true,
"bulk" : true,
"description" : "Gaia DR3 catalogues and cross-matched catalogues though <a href='https://www.cosmos.esa.int/web/gaia-users/archive'>ESA archive center</a>.",
"tap_endpoint" : "https://gea.esac.esa.int/tap-server/tap/sync",
"tap_endpoint_coulb_be_a_backup" : "https://gaia.aip.de/tap/sync",
"tap_format" : "votable_plain",
"tap_viewer" : "",
"tap_max_xmatch_votable_size" : 500,
"simbad_prefix_id" : "Gaia DR3 ",
"source_id" :"gaia.source_id",
"epoch" : 2016.0,
"ra" : "gaia.ra",
"dec" : "gaia.dec",
"pmra" : "gaia.pmra",
"pmdec" : "gaia.pmdec",
"mag_k" : "tmass.ks_m",
"mag_g" : "gaia.phot_g_mean_mag",
"mag_bp" : "gaia.phot_bp_mean_mag",
"mag_rp" : "gaia.phot_rp_mean_mag",
"detail" : { "gaia.phot_rp_mean_mag": "Grp_mag", "tmass.h_m":"H_mag", "tmass_nb.angular_distance":"tmass_dist", "tmass.designation":"J_2MASS" },
"from_very_slow" :
"gaiadr3.gaia_source_lite as gaia JOIN gaiaedr3.tmass_psc_xsc_best_neighbour AS tmass_nb USING (source_id) JOIN gaiaedr3.tmass_psc_xsc_join AS xjoin ON tmass_nb.original_ext_source_id = xjoin.original_psc_source_id JOIN gaiadr1.tmass_original_valid AS tmass ON xjoin.original_psc_source_id = tmass.designation"
,
"from" :
[
"gaiadr3.gaia_source_lite as gaia",
"gaiaedr3.tmass_psc_xsc_best_neighbour AS tmass_nb USING (source_id) JOIN gaiaedr3.tmass_psc_xsc_join AS xjoin ON tmass_nb.original_ext_source_id = xjoin.original_psc_source_id JOIN gaiadr1.tmass_original_valid AS tmass ON xjoin.original_psc_source_id = tmass.designation"
]
},"esagaia2": {
"cat_name" : "Gaia DR2",
"main_cat":false,
"description" : "Gaia DR2 catalogues <a href='https://arxiv.org/pdf/1808.09151.pdf'>with its external catalogues cross-match</a> though <a href='https://gea.esac.esa.int/archive/'>ESA archive center</a>.",
"tap_endpoint" : "https://gea.esac.esa.int/tap-server/tap/sync",
"tap_format" : "votable_plain",
"tap_viewer" : "",
"simbad_prefix_id" : "Gaia DR2 ",
"source_id" :"gaia.source_id",
"epoch" : 2015.5,
"ra" : "gaia.ra",
"dec" : "gaia.dec",
"pmra" : "gaia.pmra",
"pmdec" : "gaia.pmdec",
"mag_k" : "tmass.ks_m",
"mag_g" : "gaia.phot_g_mean_mag",
"mag_bp" : "gaia.phot_bp_mean_mag",
"mag_rp" : "gaia.phot_rp_mean_mag",
"detail" : { "tmass.h_m":"H_mag", "tmass_nb.angular_distance":"tmass_dist", "tmass.designation":"J_2MASS" },
"from" : "gaiadr2.gaia_source as gaia JOIN gaiadr2.tmass_best_neighbour as tmass_nb USING (source_id) JOIN gaiadr1.tmass_original_valid as tmass ON tmass.tmass_oid = tmass_nb.tmass_oid"
},"gsc": {
"cat_name" : "GSC2",
"main_cat":true,
"description" : "<a href='https://cdsarc.cds.unistra.fr/viz-bin/cat/I/353'>The Guide Star Catalogue, Version 2.4.2 (2020)</a>",
"tap_endpoint" : "http://tapvizier.cds.unistra.fr/TAPVizieR/tap/sync",
"tap_format" : "",
"tap_viewer" : "",
"simbad_prefix_id" : "GSC2 ",
"source_id" :"GSC2",
"epoch" : "Epoch",
"ra" : "RA_ICRS",
"dec" : "DE_ICRS",
"pmra" : "pmRA",
"pmdec" : "pmDE",
"mag_k" : "Ksmag",
"mag_r" : "rmag",
"mag_g" : "",
"mag_bp" : "",
"mag_rp" : "",
"mag_v" : "Vmag",
"mag_r" : "rmag",
"detail" : { },
"from" : "I/353/gsc242"
}
}
}';
declare variable $app:conf := parse-json($app:json-conf);
(:~
: Build a map with default value comming from given config or overidden by user params.
: Caller will use it as $max?keyname to retrieve $conf?max_keyname or max_keyname parameter
: User params are converted to the default value types if possible or not applied else.
: map will be populated by keyname_info entries so we can display overriden param.
: @return a map with default or overriden values to use in the application.
:)
declare function app:config() as map(*){
let $sections := ("min", "max", "preferred")
return
map:merge(
for $section in $sections
let $section-prefix := $section||"_"
return
map:entry($section, map:merge(
for $key in map:keys($app:conf?default) where starts-with($key, $section-prefix)
let $map-key:=replace($key, $section-prefix, "")
let $map-info-key:=$map-key||"_info"
let $conf := $app:conf?default($key)
let $param := (request:get-parameter($key, ()))[1] (: accept one param from uri or post payload :)
let $map-info:= if( exists($param) and ( string($param) != string($conf) )) then <mark title="overridden by user : default conf is {$conf}">{$param}</mark> else $conf
let $map-value:= if( exists($param) ) then
try{
typeswitch($conf)
case xs:double return xs:double($param)
case xs:integer return xs:integer($param)
default return $param
} catch * {$conf}
else $conf
(: let $log := util:log("info", "conf ["|| $section ||"."|| $map-key || "]=" || $map-value) :)
return ( map:entry($map-key, $map-value), map:entry($map-info-key, $map-info))
))
)
};
declare %templates:wrap function app:dyn-nav-li($node as node(), $model as map(*), $identifiers as xs:string*) {
let $toggle-classes := map{ (:"extcats" : "extended catalogs", :) "extquery" : "queries", "exttable" : "hide tables", (: "extorphan" : "hide orphans",:) "extdebug" : "debug" }
return
<li class="nav-link">{
map:for-each( $toggle-classes, function ($k, $label) {
<div class="form-check form-check-inline form-switch nav-orange">
<input class="form-check-input" type="checkbox" onClick='$(".{$k}").toggleClass("d-none");'/><label class="form-check-label">{$label}</label>
</div>
})
}</li>[exists($identifiers)]
};
declare function app:datatable-script($score_index, $rank_index, $sci_ft_dist_index, $sci_ao_dist_index){
(: TODO try to avoid hardcoded indexes for datacolumns :)
<script type="text/javascript">
let grays = culori.interpolate(['FF6666', '#FFFF66', '#B2FFB2']);
let formatTable = true;
$(document).ready(function() {{
// bulk filter
const min_score = document.querySelector('#min_score');
const max_rank = document.querySelector('#max_rank');
// Custom range filtering function
DataTable.ext.search.push(function (settings, data, dataIndex) {{
// Don t filter on anything other than "bulkTable"
if ( settings.nTable.id !== 'bulkTable' ) {{
return true;
}}
let min_s = parseFloat(min_score.value, 10) || 0;
let s = parseFloat(data[{$score_index - 1}],10) || 0;
let max_r = parseInt(max_rank.value) || 100;
let r = parseInt(data[{$rank_index - 1}]) || 100;
if ( ( r <= max_r ) && ( s >= min_s ) ) {{
return true;
}}
return false;
}});
var tables = $('.datatable').DataTable( {{
/* */
"aoColumnDefs": [
{{
"targets": '_all',
"mRender": function ( data, type, row ) {{
if(type == "display" && formatTable ){{
fdata=parseFloat(Number(data))
if(isNaN(fdata) || data % 1 == 0){{
return data;
}}
return fdata.toFixed(3);
}}
return data;
}}
}},
{{
"targets": {$score_index - 1},
"createdCell": function (td, cellData, rowData, row, col) {{
if ( $(this)[0].id == 'bulkTable' ) {{
$(td).css('background-color', culori.formatHex(culori.convertOklabToRgb(culori.convertRgbToOklab( grays(cellData)))));
}}
}}
}},
{{
"targets": [ {$sci_ft_dist_index - 1 },{$sci_ao_dist_index - 1 } ],
"createdCell": function (td, cellData, rowData, row, col) {{
if ( $(this)[0].id == 'bulkTable' ) {{
$l = 1 - ( cellData / {app:config()?max?dist_as} );
$(td).css('background-color', culori.formatHex(culori.convertOklabToRgb(culori.convertRgbToOklab(grays($l)))));
}}
}}
}}
],
"paging": false,"scrollX": true,"scrollY": 600, "scrollResize": true,"scrollCollapse": true,
"searching":true,"info": true,"order": [],
"dom": 'Bfrti',
"buttons": [ 'colvis','csv','copy' ]
}});
// Changes to the inputs will trigger a redraw to update the table
min_score.addEventListener('input', function () {{ tables.draw(); }});
max_rank.addEventListener('input', function () {{ tables.draw(); }});
// Hide extcols by default
tables.columns( '.extcols' ).visible( false );
// Set search input and buttons on the same line
// bugged tables.buttons().container().appendTo( '.dataTables_filter' );
}});
</script>
};
declare %templates:wrap function app:form($node as node(), $model as map(*), $identifiers as xs:string*, $format as xs:string*) {
let $max := app:config()("max")
let $params := for $p in request:get-parameter-names()[.!="identifiers"] return <input type="hidden" name="{$p}" value="{request:get-parameter($p,' ')}"/>
return
(
<div>
<h1>GRAVITY-wide: finding off-axis fringe tracking targets.</h1>
<p>This newborn tool is in its first versions and is subject to various changes in its early development phase.</p>
<h2>Underlying method:</h2>
<p>
You can query one or several Science Targets. For each of them, suitable ringe Tracker Targets will be given using following research methods: <br/>
<ul>
<li>Main catalogs<ul>{ for $cat in $app:conf?catalogs?* where $cat?main_cat return <li><b>{$cat?cat_name}</b> {parse-xml("<span>"||$cat?description||"</span>")}</li>}</ul></li>
{if ( false() = $app:conf?catalogs?*?main_cat ) then <li>Additionnal catalogs (use toggle button in the menu to get result tables)<ul>{ for $cat in $app:conf?catalogs?* where not($cat?main_cat) return <li><b>{$cat?cat_name}</b> {parse-xml("<span>"||$cat?description||"</span>")}</li>}</ul></li> else ()}
</ul>
Each query is performed within {$max?dist_as_info}'' of the Science Target below the max declination of {$max?declination_info}°.
A magnitude filter is applied on every Fringe Tracker Targets according to the best limits offered in P110
for <b>UT (MACAO) OR AT (NAOMI)</b> respectively <b>( K < {$max?magK_UT_info} AND V < {$max?magV_info} ) OR ( K < {$max?magK_AT_info} AND R<{$max?magR_info} )</b>.
When missing, the V and R magnitudes are computed from the Gaia G, Grb and Grp magnitudes.
The user must <b>refine its target selection</b> to take into account <a href="https://www.eso.org/sci/facilities/paranal/instruments/gravity/inst.html">VLTI Adaptive Optics specifications</a> before we offer a configuration selector in a future release.
</p>
<p>
<ul>
<li>Enter semicolon separated names ( SearchFTT will try to resolve it using <a href="http://simbad.u-strasbg.fr">Simbad</a> ) or coordinates (RA +/-DEC in degrees J2000), in the TextBox below.</li>
<li>Move your pointer to the column titles of the result tables to get the column descriptions.</li>
<li>To send a target to <a href="https://www.jmmc.fr/getstar">Aspro2</a> (already open), click on the icon in the <a href="https://www.jmmc.fr/getstar">GetStar</a> column, then press "Send Votable".</li>
<li>Please <a href="http://www.jmmc.fr/feedback">fill a report</a> for any question or remark.</li>
</ul>
</p>
<form>
<div class="p-3 input-group mb-3 ">
<input type="text" class="form-control" placeholder="Science identifiers (semicolon separator) e.g : 0 0; 4.321 6.543; HD123; HD234" aria-label="Science identifiers (semicolon separator)" aria-describedby="b2"
id="identifiers" name="identifiers" value="{$identifiers}" required=""/>
<button class="btn btn-outline-secondary" type="submit" id="b2"><i class="bi bi-search"/></button>
</div>
{$params}
</form>
</div>
,
if (exists($identifiers)) then ( app:searchftt-list($identifiers, $max), app:datatable-script(0,0,0,0) ) else ()
)
};
(:~
Build a fake target record mimicing jmmc-simbad format.
If votable-tr and colidx are provided, try to search for aspro2 fluxes FLUX_V,R,G,K
let $colidx := map:merge( for $e at $pos in $votable//*:FIELD/@name return map:entry(replace(lower-case($e),"computed_",""), $pos) )
@param $votable-tr optional votable tr
@param $colidx optional map of td indexes to search into given votable-tr/*:TD
:)
declare %private function app:fake-target($name as xs:string?, $coords as xs:string?,$votable-tr as node()?, $colidx as map(*)?) {
let $name := if($name) then $name else normalize-space($coords)
let $coord := $coords => replace( "\+", " +") => replace ("\-", " -") => replace ("	", " ")
let $t := for $e in tokenize($coord, " ")[string-length(.)>0] return $e
let $t := try{
if(matches($coords, ":")) then (astro:from-hms($t[1]), astro:from-dms($t[2])) else $t
}catch*{(0,0)}
let $t := try{
if(count($t)>2) then
(astro:from-hms(string-join($t[position()<4], ":" )), astro:from-dms(string-join($t[position()>3], ":" )))
else
$t
}catch*{(0,0)}
let $additional-info := if(exists($votable-tr)) then
let $tds := $votable-tr/*:TD
let $aspro-elements := map:for-each($app:conf?aspro-cols,
function ($tr-col, $aspro-col){
let $td-value := $tds[$colidx($tr-col)]/text()
return if(exists($td-value)) then element {$aspro-col} {data($td-value)} else ()
}
)(:
let $log := util:log("info", "addtional info")
let $log := util:log("info", $votable-tr)
let $log := util:log("info", $colidx)
let $log := util:log("info", $aspro-elements) :)
return $aspro-elements
else
()
let $fake-target :=
<target fake-target="y">
<user_identifier>{$name}</user_identifier>
<name>{$name}</name>
<ra>{$t[1]}</ra>
<dec>{$t[2]}</dec>
<pmra>-0.0</pmra>
<pmdec>-0.0</pmdec>
{$additional-info}
</target>
(: let $log := util:log("info", "fake-target:")
let $log := util:log("info", $fake-target) :)
return $fake-target
};
(:~
: Resolve name using simbad or forge the same response if coordinates are detected.
:
: @param $name-or-coords name or coordinates
: @return an xml node with name and coordinates
:)
declare function app:resolve-by-name($name-or-coords) {
if (matches($name-or-coords, "[a-z]", "i"))
then
jmmc-simbad:resolve-by-name($name-or-coords)
else
app:fake-target((), $name-or-coords, (), ())
};
(:~
: Resolve names using simbad or forge the same response if coordinates are detected.
:
: @param $name-or-coords name or coordinates
: @return a map of identifier with associated target element (see jmmc-simbad:resolve-by-name or app:fake-target format)
:)
declare function app:resolve-by-names($name-or-coords) {
let $names := $name-or-coords[matches(., "[a-z]", "i")]
let $coords := $name-or-coords[not(matches(., "[a-z]", "i"))] (: should we check for :)
let $map := map:merge((
for $c in $coords return map:entry($c, app:fake-target((),$c, (), ()))
,
if(exists(request:get-parameter("dry", ()))) then
()
else
jmmc-simbad:resolve-by-names($names)
))
let $log := util:log("info", $map)
return $map
};
declare function app:searchftt-list($identifiers as xs:string, $max as map(*) ) {
let $fov_deg := 3 * $max?dist_as div 3600
let $ids := distinct-values($identifiers ! tokenize(., ";") ! normalize-space(.))[string-length()>0]
let $targets-maps := app:resolve-by-names($ids)
let $count := count($ids)
let $lis :=
for $id at $pos in $ids
let $s := map:get($targets-maps, $id)
let $log := util:log("info", <txt>loop {$pos} / {$count} : {$id} {$s} </txt>)
let $simbad-link := if($s/@fake-target) then <a target="_blank" href="http://simbad.u-strasbg.fr/simbad/sim-coo?Coord={encode-for-uri($id)}&CooEpoch=2000&CooEqui=2000&Radius={$app:conf?samestar-dist_as}&Radius.unit=arcsec">{$id}</a> else <a target="_blank" href="http://simbad.u-strasbg.fr/simbad/sim-id?Ident={encode-for-uri($id)}">{$id}</a>
let $ra := $s/ra let $dec := $s/dec
let $info := if(exists($s/ra))then
<ul class="list-group">
{
for $cat in $app:conf?catalogs?* (: where $cat?enable = true() :) order by $cat?main_cat descending return
<li class="list-group-item d-flex justify-content-between align-items-start {if($cat?main_cat) then () else "extcats d-none"}">
<div class="ms-2 me-auto">{app:search($id, $max, $s, $cat)}</div>
</li>
}
</ul>
else
<div>Can't get position from Simbad, please check your identifier.</div>
let $state := if(exists($info//table)) then "success" else if(exists($s/ra)) then "warning" else "danger"
let $orphan := if (exists($info//table)) then () else "extorphan"
return
<div class="{$orphan}"><ul class="p-1 list-group">
<li class="list-group-item list-group-item-{$state}">
<div class="">
<div class="row">
<div class="col"><b>{$simbad-link}</b>
<br/>ICRS coord. [deg] (ep=J2000) : {$ra} {$dec}
<br/>Proper motions [mas/yr] : {$s/pmra} {$s/pmdec}
<br/>
{
for $e in $info//*[@data-found-targets]
let $count := data($e/@data-found-targets)
let $class := if ($count > 0) then "success" else "warning"
return (
<span class="btn btn-{$class} "><span class="badge rounded-pill bg-dark">{$count}</span> {data($e/@data-src-targets)}</span>, " "
)
}
</div>
{ if (count($ids) < 20 and exists($s/ra)) then
<div class="col d-flex flex-row-reverse">
<div id="aladin-lite-div{$pos}" style="width:200px;height:200px;"></div>
<script type="text/javascript">
var aladin = A.aladin('#aladin-lite-div{$pos}', {{survey: "P/2MASS/H", fov:{$fov_deg}, target:"{$id}" }});
</script>
</div>
else ()
}
</div>
<div class="row exttable">
{ $info }
</div>
</div>
</li>
</ul></div>
let $merged-table :=
<table class="table table-bordered table-light table-hover datatable">
<thead><th>Science</th>{($lis//thead)[1]//th}</thead>
{
for $table in $lis//table
for $tr in $table//tr[td]
return <tr><td>{data($table/@data-science)}</td>{$tr/td}</tr>
}
</table>
return
<div>
<script type="text/javascript" src="https://aladin.u-strasbg.fr/AladinLite/api/v2/latest/aladin.min.js" charset="utf-8"></script>
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home-tab-pane" type="button" role="tab" aria-controls="home-tab-pane" aria-selected="true">Result list</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile-tab-pane" type="button" role="tab" aria-controls="profile-tab-pane" aria-selected="false">Merged table</button>
</li>
</ul>
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="home-tab-pane" role="tabpanel" aria-labelledby="home-tab" tabindex="0">{$lis}</div>
<div class="tab-pane fade" id="profile-tab-pane" role="tabpanel" aria-labelledby="profile-tab" tabindex="0">{$merged-table}</div>
</div>
</div>
};
declare function app:search($id, $max, $s, $cat) {
let $log := util:log("info", "searching single ftt in "||$cat?cat_name||" ...")
let $query := app:build-query($id, (), $max, $cat)
let $votable := try{if(exists(request:get-parameter("dry", ()))) then <error>dry run : remote query SKIPPED ! </error> else jmmc-tap:tap-adql-query($cat?tap_endpoint,$query, $max?rec, $cat?tap_format) }catch * {util:log("error", serialize($err:value)), $err:value}
let $votable-url := jmmc-tap:tap-adql-query-uri($cat?tap_endpoint,$query, $max?rec, $cat?tap_format)
let $query-code := <div class="extquery d-none"><pre><br/>{data($query)}</pre><a target="_blank" href="{$votable-url}">get original votable</a></div>
let $src := if ($cat?tap_viewer) then <a class="extquery d-none" href="{$cat?tap_viewer||encode-for-uri($query)}">View original votable</a> else ()
let $log := util:log("info", "done")
return
if(exists($votable//*:TABLEDATA/*)) then
let $detail_cols := for $e in (array:flatten($app:conf?extended-cols), $cat?detail?*) return lower-case($e) (: values correspond to column names given by AS ...:)
let $field_names := for $e in $votable//*:FIELD/@name return lower-case($e)
let $source_id_idx := index-of($field_names, "source_id")
let $tr-count := count($votable//*:TABLEDATA/*)
return
<div class="table-responsive">
<table class="table table-bordered table-light table-hover datatable" data-found-targets="{$tr-count}" data-src-targets="{$cat?cat_name}" data-science="{$s/name}">
<thead><tr>
{for $f at $cpos in $votable//*:FIELD return
if ($cpos != $source_id_idx) then
let $title := if("cat_dist_as"=$f/@name) then "Distance computed moving science star to the catalog epoch using its proper motion"
else if("j2000_dist_as"=$f/@name) then "Distance computed moving candidates to J2000"
else if("today_dist_as"=$f/@name) then "Distance computed moving science star and candidates to current year epoch"
else $f/*:DESCRIPTION
let $name := if(starts-with($f/@name, "computed_")) then replace($f/@name, "computed_", "") else data($f/@name)
let $name := replace($name, "j_2mass", "2MASS J")
let $name :=if (ends-with($name, "_as")) then replace($name, "_as", "") else data($name)
let $unit :=if (ends-with($f/@name, "_as")) then "[arcsec]" else if(starts-with($f/@name, "computed_")) then "(computed)" else if (data($f/@unit)) then "["|| $f/@unit ||"]" else ()
return
<th title="{$title}">{if($field_names[$cpos]=$detail_cols) then attribute {"class"} {"extcols"} else ()}{$name}   {$unit}</th>
else
<th><span class="badge rounded-pill bg-dark">{$tr-count}</span> Simbad link for <u>{$cat?cat_name}</u></th>
}
<th>GetStar</th>
</tr></thead>
{
let $trs := $votable//*:TABLEDATA/*
(: compute simbad id adding a prefix to build a valid identifier :)
let $targets-ids := $trs/*[$source_id_idx]!concat($cat?simbad_prefix_id, .)
let $targets-maps := app:resolve-by-names($targets-ids)
for $tr in $trs return
<tr>{
let $simbad_id := $cat?simbad_prefix_id||$tr/*[$source_id_idx]
let $simbad := map:get($targets-maps, $simbad_id)
let $target_link := if (exists($simbad/ra/text())) then <a href="http://simbad.u-strasbg.fr/simbad/sim-id?Ident={encode-for-uri($simbad_id)}">{replace($simbad/name," "," ")}</a> else
let $ra := $tr/*[index-of($field_names, "ra")]
let $dec := $tr/*[index-of($field_names, "dec")]
return <a href="http://simbad.u-strasbg.fr/simbad/sim-coo?Coord={$ra}+{$dec}&CooEpoch=2000&CooEqui=2000&Radius={$app:conf?samestar-dist_as}&Radius.unit=arcsec" title="Using coords because Simbad does't know : {$simbad_id}">{replace($simbad_id," "," ")}</a>
let $getstar-url := "https://apps.jmmc.fr/~sclws/getstar/sclwsGetStarProxy.php?star="||encode-for-uri($simbad/name)
let $getstar-link := if ($simbad/ra) then <a href="{$getstar-url}" target="_blank"><i class="bi bi-box-arrow-up-right"></i></a> else "-"
return
(
<td>{$target_link}</td>,
for $td at $cpos in $tr/* where $cpos != 1 return
element {"td"} {attribute {"class"} {if( $field_names[$cpos]=$detail_cols ) then "extcols" else ()},try { let $d := xs:double($td) return format-number($d, "0.###") } catch * { if(string-length($td)>1) then data($td) else "-" }},
<td>{$getstar-link}<!--{$getstar-votable//*:TABLEDATA/*:TR/*:TD[121]/text()}--></td>
)
}</tr>
}
</table>
<span class="extdebug d-none">{serialize($votable//*:COOSYS[1])}</span> {$query-code}
{$src}
</div>
else
<div>
{
if ( $votable//*:INFO[@name="QUERY_STATUS" and @value="ERROR"] ) then let $anchor := "error-"||util:uuid() return
(<a id="{$anchor}" href="#{$anchor}" class="text-danger" onclick='$(".extdebug").toggleClass("d-none");'>Sorry, an error occured executing the query. {$votable//*:INFO[@name='QUERY_STATUS' and @value='ERROR']}</a>
,<code class="extdebug d-none"><br/>{serialize($votable)}</code>)
else
<span>Sorry, no fringe traking star found for <b>{$s/name/text()} in {$cat?cat_name}</b>.</span>
}
{$query-code}
{$src}
</div>
};
declare function app:get-identifiers-from-file($indentifiersFile as xs:string*){
if (exists($indentifiersFile)) then
for $i in distinct-values($indentifiersFile)
(: let $log := util:log("info", "identifiersFile[" || $i || "]:"|| request:get-uploaded-file-data("indentifiersFile") ) :)
return "a"
else ()
};
declare %templates:wrap function app:bulk-form($node as node(), $model as map(*), $identifiers as xs:string*, $catalogs as xs:string*, $viziertable as xs:string?) {
for $type in ("success", "danger")
where exists(session:get-attribute($type))
return
<div class="alert alert-{$type} alert-dismissible fade show" role="alert">
{session:get-attribute($type)}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
,
app:bulk-form-html($identifiers, $catalogs, $viziertable)
,try{ session:clear() }catch *{ () }
};
declare function app:bulk-form-html($identifiers as xs:string*, $catalogs as xs:string*, $viziertable as xs:string?) {
let $start-time := util:system-time()
let $config := app:config()
let $max := $config("max")
(: was here before max-mags to convey mags parameters
let $params := for $p in request:get-parameter-names() where not ( $p=("identifiers", "catalogs") ) return <input type="hidden" name="{$p}" value="{request:get-parameter($p,' ')}"/> :)
let $max-inputs := for $k in ("FT_mag","AO_mag", "declination") let $v := map:get($max,$k) return
<div class="p-2"><div class="input-group">
<span class="input-group-text">
{
let $doc := map:get($max, $k||$app:doc-suffix)
let $label := replace($k, "_", " ")
return
if(exists($doc))then <a title="{$doc}">{$label}<i class="bi bi-question-circle"></i></a> else $label
}
</span>
<input name="max_{$k}" value="{$v}" class="form-control"/>
</div></div>
let $default-catalogs := for $cat in $app:conf?catalogs?* where exists($cat?bulk) order by $cat?main_cat descending return $cat?cat_name
let $catalogs := if(exists($catalogs)) then $catalogs else $config?preferred?bulk_catalog
let $cats-params := for $catalog in $default-catalogs order by $catalog
return
<div class="p-2"><div class="input-group">
<div class="input-group-text">
{ element input { attribute class {"form-check-input"}, attribute type {"checkbox"}, attribute name {"catalogs"}, attribute value {$catalog}, if ($catalog=$catalogs) then attribute checked {"true"} else ()} }
</div> <span class="form-control">{$catalog}</span>
</div></div>
return
(
<div>
<h2>Search Fringe Tracking Targets and Adaptative Optics stars</h2>
<p><b>SearchFTT</b> searches for nearby stars of your Science Target(s) suitable for off-axis Fringe Tracking (FT) and off-axis Adaptive Optics (AO). <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapseIntro" role="button" aria-expanded="false" aria-controls="collapseIntro">...</a>
</p>
<div class="collapse" id="collapseIntro">
<p>The query can be made in different ways:</p>
<ul>
<li>enter your Science Target by name (resolved using Simbad for proper motion) or by coordinates (RA ±DEC J2000). For several Science Targets, the names or the coordinates are separated by semicolons.</li>
<li>upload a CSV file with an identifier (name or coordinates) per line.</li>
<li>fill a VizieR table code with the option of try selecting names instead of coordinates.</li>
</ul>
<p>Each query is performed using SIMBAD or/and Gaia DR3 catalogues, which are cross-matched though CDS and ESA data centers. The search angular radius around each Science Target is compatible with a given maximal declination. A magnitude filter is applied to satisfy flux constraints for the near-infrared FT and for the visible AO. The query results following these constraints are presented in a main output table.</p><p>A “Score” is proposed for each pair (FT, AO) of candidates. The score is proportional to the Strehl ratio given by the AO correction, the proportionality coefficient depending on the expected fringe tracking performances given the FT candidate [<a href="#ref1">ref1</a>].
<br/><i class="bi-exclamation-circle"></i> the K-band magnitude listed for the FT targets is the total magnitude, which is equal to the correlated magnitude (the one that matter for fringe tracking performance) for non-resolved objects. In the case of partially or significantly resolved targets, the correlated K-band magnitude could be significantly higher than the total magnitude. Therefore, for the considered VLTI array, the user should check the expected K-band correlated magnitudes of the FT target to insure that it can really be used for fringe tracking.
<br/> In the Natural Guide Star mode (NGS), the Strehl ratio is estimated from an analytical model of GPAO [<a href="#ref2">ref2</a>]. So, in this AO mode, a score ranking is possible.<br/>
Solutions can however be found in the AO Laser Guide Star mode (LGS) by reducing the AO magnitude to be entered but without a valid score provided, which prevents any score ranking.</p>
<p>If the Science Target follows the constraints on magnitude and can be itself the (FT, AO) candidates, this on-axis solution is also estimated and ranked.</p>
<p>You can save the query results by making an asprox-file, to see on Aspro2 the Science Targets with their FT and AO stars. Aspro2 will help the user to verify the feasibility of the observations in term of visibility level or correlated magnitude when using on-axis fringe tracking.</p>
<p>You can also save the list of identifiers which have some candidates in a CSV file.</p>
<ul>
<li id="ref1">[ref1]: T.Shimizu, in prep.</li>
<li id="ref2">[ref2]: Berdeu et al., <a href="https://www.jmmc.fr/doc/approved/JMMC-POS-2910-0001.pdf" target="_blank" rel="noopener">Simplified model(s) of the GRAVITY+ adaptive optics system(s) for performance prediction.</a></li>
</ul>
<p>Acknowledgement<br/>
If this software was helpful in your research, please use this acknowledgement and give the access link.<br/><code>
This research has made use of the Jean-Marie Mariotti Center \texttt{{SearchFTT}} service.<br/>
\footnote{{Available at <a href="https://searchftt.jmmc.fr" target="_blank" rel="noopener">https://searchftt.jmmc.fr</a>}}
</code>
</p>
<p>
Please watch <a href="https://www.jmmc.fr/pub/tutos/SearchFTT.mov">our 3' video for an overview of SearchFTT</a>.
</p>
</div>
<form method="post" action="bulk.html"> <!-- force action to avoid param duplication on post -->
<div class="d-flex p-2">
<div class="input-group">
<input title="You may drag and drop a multiline list in this field" type="text" class="form-control" placeholder="Enter your science identifiers or coordinates. Use semicolon as separator, e.g : 0 0 ; 4.321 -6.543 ; -00:11:22 +33:44:55.66 ; HD123 ; HD234 " aria-label="Science identifiers (semicolon separator)" id="identifiers" name="identifiers" value="{$identifiers}"/>
</div>
</div>
<div class="d-flex p-2"><div class="p-2 justify-content-end"><label class="form-check-label ">Catalogs to query:</label></div>
{$cats-params}
</div>
<div class="d-flex p-2"><div class="p-2 justify-content-end">Constraints:</div>
{$max-inputs}
</div>
<div class="d-flex p-2">
<div class="col-sm-8"><input type="submit" class="btn btn-primary" value="Submit my identifiers"/></div>
<div class="col-sm-2"><a href="bulk.html" class="btn btn-outline-secondary" role="button"> Reset <i class="bi bi-arrow-clockwise"></i></a></div>
</div>
{
if (exists($identifiers[string-length()>0])) then
(
app:searchftt-bulk-list-html($identifiers, $max, $catalogs),
<code class="extdebug d-none"><br/>Request processing duration : {seconds-from-duration(util:system-time()-$start-time)}s</code>
)
else ()
}
</form>
<script>
document.querySelector('#identifiers').addEventListener('beforeinput', function (event) {{
if(event.inputType=="insertFromDrop"){{
if (event.data) {{
event.preventDefault();
event.srcElement.value=event.data.replace(/[\r\n]+/g, " ; ");
}}
}}
if(event.inputType=="insertFromPaste"){{
if (event.data) {{
event.preventDefault();
paste = event.data.replace(/[\r\n]+/g, " ; ");
old = event.srcElement.value;
event.srcElement.value=old.substring(0,event.srcElement.selectionStart ) + paste + old.substring(event.srcElement.selectionEnd,event.srcElement.value.size )
}}
}}
}});
</script>
{
if (exists($identifiers[string-length()>0]) ) then () else
<div>
<form method="post" enctype="multipart/form-data" action="modules/inputfile.xql">
<div class="d-flex p-2">or <br/></div>
<div class="d-flex p-2">
<div class="col-sm-3"><button type="submit" class="btn btn-primary" title="You may submit an input file with one id or coordinate (RA +/-DEC in degrees J2000) per line ">Submit my SearchFTT.csv file<i class="bi bi-question-circle"></i></button></div>
<div class="col-sm-2"><input type="file" class="form-control" name="inputfile"/></div>
<div class="col-sm-2">  <a href="test/inputs/test1.csv">(see sample file)</a></div>
</div></form>
<form method="post" action="modules/viziertable.xql"><div class="d-flex p-2">
<div class="col-sm-3"><button type="submit" class="btn btn-primary" title="You may request to gather coordinates using a VizieR table name">Use VizieR table <i class="bi bi-question-circle"></i></button></div>
<div class="col-sm-2"><input type="text" class="form-control" name="viziertable" value="{$viziertable}"/></div>
<div class="col-sm-3"> <input class="form-check-input" type="checkbox" name="try-name-first"/><label class="form-check-label">Prefer name over coordinates</label></div>
<div class="col-sm-3">  <a href="modules/viziertable.xql?try-name-first=y&viziertable=J/MNRAS/414/108/stars">(test J/MNRAS/414/108/stars)</a></div>
</div></form>
</div>
}
</div>
)
};
declare function app:simbad-link($id as xs:string, $target, $ra as xs:string?, $dec as xs:string?){
if (exists($target/ra/text()) and empty($target/@fake-target) ) then
<a title="{$target/user_identifier} ( RA/DEC {$target/ra} {$target/dec} )" href="http://simbad.u-strasbg.fr/simbad/sim-id?Ident={encode-for-uri($id)}" target="_blank">{replace($target/name," "," ")} <i class="bi bi-arrow-up-right-square"></i></a>
else if (exists($ra) and exists($dec) ) then
<span>{replace($id," "," ")}<a href="http://simbad.u-strasbg.fr/simbad/sim-coo?Coord={$ra}+{$dec}&CooEpoch=2000&CooEqui=2000&Radius={$app:conf?samestar-dist_as}&Radius.unit=arcsec" title="Using coords ( {$ra} {$dec} ) because Simbad does't know : {$id}" target="_blank"> <i class="bi bi-arrow-up-right-square"></i></a></span>
else if (exists($target/ra/text()) and exists($target/dec/text()) ) then
<span>{replace($id," "," ")}<a href="http://simbad.u-strasbg.fr/simbad/sim-coo?Coord={$target/ra}+{$target/dec}&CooEpoch=2000&CooEqui=2000&Radius={$app:conf?samestar-dist_as}&Radius.unit=arcsec" title="Using coords ( {$target/ra} {$target/dec} ) because Simbad does't know : {$id}" target="_blank"> <i class="bi bi-arrow-up-right-square"></i></a></span>
else
$target/user_identifier/text()
};
declare function app:searchftt-bulk-list-html($identifiers as xs:string*, $max as map(*), $catalogs-to-query as xs:string* ) {
let $config := app:config()
let $bulk-search-map := app:searchftt-bulk-list($identifiers, $catalogs-to-query)
let $identifiers-map := $bulk-search-map?identifiers-map
let $start-time := util:system-time()
(: Rebuild the table (and votable) with a summary of what we have in the catalogs :)
let $cnt := try{ count( $bulk-search-map?ranking?scores?* ) }catch * { "XX" }
let $log := util:log("info", "merge main table to show ranked results ("|| $cnt || " for " || count($identifiers-map?*) ||" sciences))... ")
let $detail_cols := for $e in (array:flatten($app:conf?extended-cols)) return lower-case($e)
let $sci-cols := $identifiers-map?*[1]/* ! name(.)
let $ranking-input-params := (($bulk-search-map?catalogs?*)[1])?ranking?input-params
let $cols := ($sci-cols,"FT identifier", "AO identifier", "Score", "Rank", $ranking-input-params , "Catalog")
let $th := <tr> {$cols ! <th>{if(.=$detail_cols) then attribute {"class"} {"extcols"} else ()} {.}</th>}</tr>
(: prepare some data for speedup in the following loops :)
let $cat-sciences-scores := map:merge((
for $cat-name in map:keys($bulk-search-map?catalogs) return map:entry($cat-name, $bulk-search-map?catalogs($cat-name)?ranking?scores?* )
))
(: let $log := util:log("info", ``[identifiers returned : `{string-join(map:keys($identifiers-map), ", ")}`]``) :)
let $trs := map:merge((
for $identifier at $identifier-pos in map:keys($identifiers-map) order by $identifier
let $science := map:get($identifiers-map, $identifier)
(: let $log := util:log("info", ``[identifier : `{$identifier}`]``) :)
let $identifier-name := data($science/name)
return
map:entry($identifier,
for $cat-name in map:keys($bulk-search-map?catalogs)
let $cat := $bulk-search-map?catalogs($cat-name)
let $targets-map := $cat?targets-map
let $ranking := $cat?ranking
let $ftaos := $cat?ranking?ftaos
let $scores := $cat?ranking?scores
let $science-idx := $cat?ranking?sciences-idx?($identifier-name)
(: let $science-scores := for $idx in $science-idx return $cat?ranking?scores?*[$idx] This line is very cost effective !! prefer following one :)
let $science-scores := for $idx in $science-idx return $cat-sciences-scores($cat-name)[$idx]
(: reorder with NaN at the end of the sequence :)
(: does it work ??? using descending empty least_or_greatest return $idx ???:)
let $ordered-science-idx := for $idx at $pos in $science-idx let $score:=$science-scores[$pos] let $score := if($score=$score) then $score else -1 order by $score descending return $idx
let $ordered-science-scores := for $idx at $pos in $ordered-science-idx return $science-scores[$pos]
let $inputs := $cat?ranking?inputs
let $rows :=
for $idx at $pos in $ordered-science-idx
where $ordered-science-scores[$pos] >= $config?min?score and $pos <= $max?rank
let $ftao := $ftaos?*[$idx]?*
return
(: <tr class="opacity-{$opacity}"> :)
<tr>
{for $col in $sci-cols return <td>{ if($col=("name","user_identifier")) then app:simbad-link($science/*[name(.)=$col], $science,(),()) else data($science/*[name(.)=$col]) }</td>}
{for $id in $ftao let $t := $targets-map($id) return <td>{app:simbad-link($id, $t,$t/ra,$t/dec)}</td>}
<td>{$scores?*[$idx]}</td>
<td>{$pos}</td>
{ let $tds := array:flatten($inputs?*[$idx]) return for $c at $pos in $ranking-input-params return <td>{$tds[$pos+1]}</td>}
<td>{$cat-name}</td>
</tr>
(:let $log := util:log("info", "done "|| $identifier || "("||seconds-from-duration(util:system-time()-$start-time)||"s) : " || count($rows) ||"solutions" ) :)
return $rows
)))
let $table := <table class="table table-bordered table-light table-hover datatable" id="bulkTable">
<thead>{$th}</thead>
{$trs?*}
</table>
let $votable := jmmc-tap:table2votable($table, "targets")
let $error-report := for $cat in map:keys($bulk-search-map?catalogs)
let $cat := $bulk-search-map?catalogs($cat)
let $info := $cat?ranking
let $error := ($cat?error,$info?error)
where exists($error)
return
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{$error}
{ if (exists($info?query)) then <span><br/> query was for {$info?cat}: <br/>{$info?query}</span> else () }
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
let $log := util:log("info", "done ("||seconds-from-duration(util:system-time()-$start-time)||"s)")
let $nb-results := count(map:for-each($trs, function($k,$v){if(exists($v)) then $k else ()}))
let $targets :=<div><h3>{ $nb-results } targets with both FT and AO solutions
<a class="btn btn-outline-secondary btn-sm" href="data:application/x-votable+xml;base64,{util:base64-encode(serialize($votable))}" type="application/x-votable+xml" download="input_{app:getFileSuffix($identifiers)}.vot">votable</a> 
{(:)
for $cat-name in map:keys($bulk-search-map?catalogs)
let $v := $bulk-search-map?catalogs($cat-name)?ranking?res
return
<a class="btn btn-outline-secondary btn-sm" href="data:application/x-votable+xml;base64,{util:base64-encode(serialize($v))}" type="application/x-votable+xml" download="internal{$cat-name}.vot">internal query({$cat-name}) </a>
:)}
</h3>
{
(:)
for $cat-name in map:keys($bulk-search-map?catalogs)
return <div class="extquery d-none"><pre><br/>{data($bulk-search-map?catalogs($cat-name)?ranking?query)}<br/></pre></div>
:)
}
{$error-report}
{if ($nb-results = 0) then () else (
$table
,<div class="p-2 d-flex">
<div class="p-2 justify-content-end">Limit to :</div>
<div class="p-2"><div class="input-group"><span class="input-group-text" title="{$config?min?score_doc}">Min score of solutions <i class="bi bi-question-circle"></i></span><input type="text" id="min_score" name="min_score" value="{$config?min?score}"/></div></div>
<div class="p-2"><div class="input-group"><span class="input-group-text" title="{$max?rank_doc}">Max number solutions per science <i class="bi bi-question-circle"></i></span><input type="text" id="max_rank" name="max_rank" value="{$max?rank}"/></div></div>
</div>
,<div class="p-2 d-flex">
<div class="p-2"><button class="btn btn-primary" type="submit" formaction="modules/aspro.xql">Save my SearchFTT.asprox file</button></div>
<div class="p-2"><button class="btn btn-primary" type="submit" formaction="modules/outputfile.xql">Save my SearchFTT.csv file</button></div>
<!-- <div class="p-2"><button class="btn btn-primary" type="submit" formaction="modules/test.xql">Test this list</button></div> -->
</div>
,<p><i class="bi bi-info-circle-fill"></i> <kbd>Shift</kbd> click in the column order buttons to combine a multi column sorting.</p>
)}
<div class="extquery d-none">{for $q in $bulk-search-map?catalogs?*?ranking?query return <pre><br/>{data($q)}<br/></pre>}</div>
</div>
let $debug-info := if (empty($bulk-search-map?catalogs?*?html) ) then () else
(<br/>,<hr/>,
<em>Next debug content will be improved if not removed...</em>,<br/>
,<h2>Raw results from catalogs.</h2>
,<p>By now, the ut_flag and at_flag columns are not computed in the votable but the table below ( 1=FT, 2=AO, 3=FT or AO). <br/> Magnitudes columns colors are for
<small class="d-inline-flex mb-3 px-2 py-1 fw-semibold bg-success bg-opacity-10 border border-success border-opacity-10 rounded-2">UT and AT compliancy</small>,
<small class="d-inline-flex mb-3 px-2 py-1 fw-semibold bg-warning bg-opacity-10 border border-warning border-opacity-10 rounded-2">UT compliancy</small> or
<small class="d-inline-flex mb-3 px-2 py-1 fw-semibold bg-danger bg-opacity-10 border border-danger border-opacity-10 rounded-2">not compatible / unknown</small>
</p>
, $bulk-search-map?catalogs?*?html)
return
($targets
,$debug-info
,app:datatable-script(index-of($cols, "Score"),index-of($cols, "Rank"),index-of($cols, "sci_ft_dist"),index-of($cols, "sci_ao_dist"))
)
};
(: query given catalogs and perform for rank each ft ao compatible combination
output structure is a map :
- $res?identifiers-map : map {$identifier : id-info}
- $res?catalogs : map{ $catalogName :
map {
"error" : htmlerror
"votable":$votable
or
"votable":$votable
"html" : $html
"targets-map" : map {$identifier : id-info}
"ranking : map {
"error": $error
"query" : $query
"sciences-idx" : map { $science-id : array{ $pos-idx } }
"input-params" : array { $colnames }
"inputs" : array { $colvalues_of_colnames }
"ftaos" : array { [ft1, ao1], ... [ftn, aon] }
"scores" : array { $scores }
}
}
:)
declare function app:searchftt-bulk-list($identifiers as xs:string*, $catalogs-to-query as xs:string* ) {
let $log := util:log("info", "catalogs to query : " || string-join($catalogs-to-query))
(: Check that we have requested catalog in our conf :)
let $catalogs-to-query := for $cat-name in $catalogs-to-query
where exists($app:conf?catalogs?*[?cat_name=$cat-name])
return $cat-name
let $config := app:config()
let $catalogs-to-query := if(exists($catalogs-to-query)) then $catalogs-to-query else $config?preferred?bulk_catalog
(: Cleanup requested ids and get Simbad or basic informations for each of them :)
let $ids := distinct-values($identifiers ! tokenize(., ";") ! normalize-space(.))[string-length()>0]
let $identifiers-map := app:resolve-by-names($ids)
let $catalogs := map:merge((
for $cat-name in $catalogs-to-query
let $cat := $app:conf?catalogs?*[?cat_name=$cat-name]
let $res := try{app:bulk-search($identifiers-map, $cat)}catch *{map{"error":<div>{$err:description} : <br/> <pre>{$err:value}</pre> </div>}}
return map:entry($cat-name,$res)
))
let $bulk-search-map := map:merge((
map:entry("identifiers-map",$identifiers-map),
map:entry("catalogs", $catalogs)))
return
$bulk-search-map
};
declare function app:get-input-votables($ths,$trs, $split-size){
let $size := count($trs)
return
for $i in 0 to xs:integer($size div $split-size)
let $sub-trs := subsequence( $trs, 1+($i*$split-size) , ($i+1)*$split-size)
let $table := <table class="table table-bordered table-light table-hover datatable">
<thead>{$ths}</thead>
{$sub-trs}
</table>
return