-
Notifications
You must be signed in to change notification settings - Fork 2
/
jquery.jsparc.js
1496 lines (1285 loc) · 63.6 KB
/
jquery.jsparc.js
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
/* jSparc - Javascript library for HiSPARC
This library contains functions to work with HiSPARC data.
Warnings
--------
In HiSPARC we use GPS timestamps record event times, these timestamps
have nanosecond accuracy. The timestamp (normally only seconds) that
includes this nanosecond part is called the `extended timestamp`.
However, this number is so long it only fits in a 64-bit integer, but
javascript numbers only has 53 bits of accuracy. So using an extended
timestamp like "1380412812090648357" would result in
1380412812090648300. To work with extended timestamps, the values should
be stored as strings.
*/
"use strict";
(function($) {
function jSparc() {
// Development
/* Most functions are made public to make development easier,
some might not be when the library is released.
*/
// Constants
/* jshint validthis: true */
var jsparc = this,
API_URL = 'https://data.hisparc.nl/api',
DATA_URL = 'https://data.hisparc.nl/data',
JSPARC_URL = 'https://data.hisparc.nl/analysis-session',
events_format = {'date': {'column': 0, 'name': 'Date', 'units': 'GPS date'},
'time': {'column': 1, 'name': 'Time', 'units': 'GPS time'},
'timestamp': {'column': 2, 'name': 'Timestamp', 'units': 's'},
'nanoseconds': {'column': 3, 'name': 'Nanoseconds', 'units': 'ns'},
'pulseheights': {'column': [4, 5, 6, 7], 'name': 'Pulseheight', 'units': 'ADC'},
'integral': {'column': [8, 9, 10, 11], 'name': 'Pulseintegral', 'units': 'ADC.sample'},
'number_of_mips': {'column': [12, 13, 14, 15], 'name': 'Number of MIPs', 'units': 'N'},
'arrival_times': {'column': [16, 17, 18, 19], 'name': 'Arrival time', 'units': 'ns'},
't_trigger': {'column': 20, 'name': 'Trigger time', 'units': 'ns'},
'zenith': {'column': 21, 'name': 'Zenith', 'units': '°'},
'azimuth': {'column': 22, 'name': 'Azimuth', 'units': '°'}},
weather_format = {'date': {'column': 0, 'name': 'Date', 'units': 'GPS date'},
'time': {'column': 1, 'name': 'Time', 'units': 'GPS time'},
'timestamp': {'column': 2, 'name': 'Timestamp', 'units': 's'},
'temperature': {'column': [3, 4], 'name': 'Temperature', 'units': '°C'},
'humidity': {'column': [5, 6], 'name': 'Humidity', 'units': '%'},
'atmospheric_pressure': {'column': 7, 'name': 'Atmospheric pressure', 'units': 'hPa'},
'wind_direction': {'column': 8, 'name': 'Wind direction', 'units': '°'},
'wind_speed': {'column': 9, 'name': 'Wind speed', 'units': 'm/s'},
'solar_radiation': {'column': 10, 'name': 'Solar radiation', 'units': 'W/m/m'},
'uv_index': {'column': 11, 'name': 'UV index', 'units': '0-16'},
'evapotranspiration': {'column': 12, 'name': 'Evapotranspiration', 'units': 'mm'},
'rain_rate': {'column': 13, 'name': 'Rain rate', 'units': 'mm/h'},
'heat_index': {'column': 14, 'name': 'Heat index', 'units': '°C'},
'dew_point': {'column': 15, 'name': 'Dew point', 'units': '°C'},
'wind_chill': {'column': 16, 'name': 'Wind chill', 'units': '°C'}},
singles_format = {'date': {'column': 0, 'name': 'Date', 'units': 'GPS date'},
'time': {'column': 1, 'name': 'Time', 'units': 'GPS time'},
'timestamp': {'column': 2, 'name': 'Timestamp', 'units': 's'},
'mas_ch1_high': {'column': 3, 'name': 'ch1 high', 'units': 'Hz'},
'mas_ch1_low': {'column': 4, 'name': 'ch1 low', 'units': 'Hz'},
'mas_ch2_high': {'column': 5, 'name': 'ch2 high', 'units': 'Hz'},
'mas_ch2_low': {'column': 6, 'name': 'ch2 low', 'units': 'Hz'},
'slv_ch1_high': {'column': 7, 'name': 'ch3 high', 'units': 'Hz'},
'slv_ch1_low': {'column': 8, 'name': 'ch3 low', 'units': 'Hz'},
'slv_ch2_high': {'column': 9, 'name': 'ch4 high', 'units': 'Hz'},
'slv_ch2_low': {'column': 10, 'name': 'ch4 low', 'units': 'Hz'}},
lightning_format = {'date': {'column': 0, 'name': 'Date', 'units': 'GPS date'},
'time': {'column': 1, 'name': 'Time', 'units': 'GPS time'},
'timestamp': {'column': 2, 'name': 'Timestamp', 'units': 's'},
'nanoseconds': {'column': 3, 'name': 'Nanoseconds', 'units': 'ns'},
'latitude': {'column': 4, 'name': 'Latitude', 'units': '°'},
'longitude': {'column': 5, 'name': 'Longitude', 'units': '°'},
'current': {'column': 6, 'name': 'Current', 'units': 'A'}},
eventtime_format = {'hour_of_day': {'column': 0, 'name': 'Hour of day', 'units': 'hour'},
'n_events': {'column': 1, 'name': 'Number of events', 'units': 'count'}},
pulseheight_format = {'pulseheight_bins': {'column': 0, 'name': 'Pulseheight', 'units': 'ADC'},
'n_pulseheight': {'column': [1, 2, 3, 4], 'name': 'Occurrence', 'units': 'count'}},
pulseintegral_format = {'integral_bins': {'column': 0, 'name': 'Pulseintegral', 'units': 'ADC.sample'},
'n_integral': {'column': [1, 2, 3, 4], 'name': 'Occurrence', 'units': 'count'}},
singlesratelow_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'singles_rate': {'column': [1, 2, 3, 4], 'name': 'Singles rate', 'units': 'Hz'}},
singlesratehigh_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'singles_rate': {'column': [1, 2, 3, 4], 'name': 'Singles rate', 'units': 'Hz'}},
singleslow_format = {'singles_rate': {'column': 0, 'name': 'Singles rate', 'units': 'Hz'},
'n_singles': {'column': [1, 2, 3, 4], 'name': 'Occurrence', 'units': 'count'}},
singleshigh_format = {'singles_rate': {'column': 0, 'name': 'Singles rate', 'units': 'Hz'},
'n_singles': {'column': [1, 2, 3, 4], 'name': 'Occurrence', 'units': 'count'}},
zenith_format = {'zenith_angle': {'column': 0, 'name': 'Zenith', 'units': '°'},
'n_events': {'column': 1, 'name': 'Number of events', 'units': 'count'}},
azimuth_format = {'azimuth_angle': {'column': 0, 'name': 'Azimuth', 'units': '°'},
'n_events': {'column': 1, 'name': 'Number of events', 'units': 'count'}},
temperature_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'temperature_outside': {'column': 1, 'name': 'Temperature', 'units': '°C'}},
barometer_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'atmospheric_pressure': {'column': 1, 'name': 'Atmospheric pressure', 'units': 'hPa'}},
voltage_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'pmt_voltage': {'column': [1, 2, 3, 4], 'name': 'PMT voltage', 'units': 'V'}},
current_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'pmt_current': {'column': [1, 2, 3, 4], 'name': 'PMT current', 'units': 'mA'}},
trigger_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'low': {'column': [1, 2, 3, 4], 'name': 'Low threshold', 'units': 'ADC'},
'high': {'column': [5, 6, 7, 8], 'name': 'High threshold', 'units': 'ADC'},
'n_low': {'column': 9, 'name': 'Number of low', 'units': 'count'},
'n_high': {'column': 10, 'name': 'Number of high', 'units': 'count'},
'and_or': {'column': 10, 'name': 'And-or', 'units': 'boolean'},
'external': {'column': 10, 'name': 'External', 'units': 'ternary'}},
detector_timing_offsets_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'detector_timing_offset': {'column': [1, 2, 3, 4], 'name': 'Detector offset', 'units': 'ns'}},
station_timing_offsets_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'offset': {'column': 1, 'name': 'Station offset', 'units': 'ns'},
'error': {'column': 2, 'name': 'Error', 'units': 'ns'}},
coincidencenumber_format = {'n_stations': {'column': 0, 'name': 'Number of stations', 'units': 'count'},
'n_coincidences': {'column': 1, 'name': 'Number of coincidences', 'units': 'count'}},
coincidencetime_format = {'hour_of_day': {'column': 0, 'name': 'Hour of day', 'units': 'hour'},
'n_coincidences': {'column': 1, 'name': 'Number of coincidences', 'units': 'count'}},
station_layout_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'radius': {'column': [1, 5, 9, 13], 'name': 'Radius', 'units': 'm'},
'alpha': {'column': [2, 6, 10, 14], 'name': 'Alpha', 'units': '°'},
'height': {'column': [3, 7, 11, 15], 'name': 'Height', 'units': 'm'},
'beta': {'column': [4, 8, 12, 16], 'name': 'Beta', 'units': '°'}},
gps_format = {'timestamp': {'column': 0, 'name': 'Timestamp', 'units': 's'},
'latitude': {'column': 1, 'name': 'Latitude', 'units': '°'},
'longitude': {'column': 2, 'name': 'Longitude', 'units': '°'},
'altitude': {'column': 3, 'name': 'Altitude', 'units': 'm'}};
jsparc.API_URL = API_URL;
jsparc.DATA_URL = DATA_URL;
jsparc.JSPARC_URL = JSPARC_URL;
jsparc.events_format = events_format;
jsparc.weather_format = weather_format;
jsparc.singles_format = singles_format;
jsparc.lightning_format = lightning_format;
jsparc.eventtime_format = eventtime_format;
jsparc.pulseheight_format = pulseheight_format;
jsparc.pulseintegral_format = pulseintegral_format;
jsparc.singlesratelow_format = singlesratelow_format;
jsparc.singlesratehigh_format = singlesratehigh_format;
jsparc.singleslow_format = singleslow_format;
jsparc.singleshigh_format = singleshigh_format;
jsparc.zenith_format = zenith_format;
jsparc.azimuth_format = azimuth_format;
jsparc.temperature_format = temperature_format;
jsparc.barometer_format = barometer_format;
jsparc.voltage_format = voltage_format;
jsparc.current_format = current_format;
jsparc.trigger_format = trigger_format;
jsparc.detector_timing_offsets_format = detector_timing_offsets_format;
jsparc.station_timing_offsets_format = station_timing_offsets_format;
jsparc.coincidencenumber_format = coincidencenumber_format;
jsparc.coincidencetime_format = coincidencetime_format;
jsparc.station_layout_format = station_layout_format;
jsparc.gps_format = gps_format;
// Create format for unknown type
jsparc.unknown_format = unknown_format;
function unknown_format(url) {
/* Create a generic column format for unknown dataset types
*/
var generic_format = {},
n_columns = datasets[url].data[0].length;
for (var i = 0; i < n_columns; i++) {
generic_format['column_' + i] = {'column': i, 'name': 'Column ' + i, 'units': '?'};}
return generic_format;
}
// Data container
jsparc.datasets = function() {return datasets;};
var datasets = {};
// Datasets
jsparc.download_dataset = download_dataset;
function download_dataset(station_number, startdate, enddate, type) {
/* Store the result of downloading data to the datasets
The url will be used as key to reference the data
*/
// var url = data_example(station_number, startdate, enddate, type);
var url = data_download(station_number, startdate, enddate, type);
if (datasets[url]) {
alert('That dataset is already available');
return;}
return get_tsv(url)
.done(function(data) {
if (!data.length) {
alert('No data found for the requested variables');}
else {
datasets[url] = ({data: data,
station_number: station_number,
startdate: startdate,
enddate: enddate,
type: type,
url: url});
update_dataset_table();}
});
}
jsparc.load_dataset = load_dataset;
function load_dataset(file, done) {
/* Load datafiles from the local machine
The filename will be used as key to reference the data
*/
var reader = new FileReader();
if (datasets[file.name]) {
alert('That dataset is already available');
return;}
reader.onload = function(event) {
var data = parse_tsv(event.target.result),
info = parse_filename(file.name);
if (!data.length) {
alert('No data in the chosen file');}
else {
datasets[file.name] = ({data: data,
station_number: info.station_number,
startdate: info.startdate,
enddate: info.enddate,
type: info.type,
url: file.name});
update_dataset_table();}
};
reader.readAsText(file);
// Return the reader object so we can listen for the onloadend event
// and easily recheck all previous checked radio buttons
return reader;
}
jsparc.remove_dataset = remove_dataset;
function remove_dataset(url) {
/* Remove a specific dataset
*/
delete datasets[url];
}
jsparc.remove_dataset_from_list = remove_dataset_from_list;
function remove_dataset_from_list(span) {
/* Remove the clicked dataset
*/
remove_dataset($(span).parent().attr('name'));
}
jsparc.sort_events = sort_events;
function sort_events(data) {
/* Sort event data by extended timestamps
Data from the ESD is already sorted.
However, this can be useful after merging datasets
*/
return data.sort(sort_extendedtimestamps);
}
jsparc.sort_weather = sort_weather;
function sort_weather(data) {
/* Sort weather data by timestamps
Data from the ESD is already sorted.
However, this can be useful after merging datasets
*/
return data.sort(sort_timestamps);
}
jsparc.sort_extendedtimestamps = sort_extendedtimestamps;
function sort_extendedtimestamps(a, b) {
/* Sort events by extended timestamps
First sort by timestamp, if they are the same, use the nanoseconds
*/
var t = events_format.timestamp.column,
n = events_format.nanoseconds.column;
return (a[t] == b[t]) ? a[n] - b[n] : a[t] - b[t];
}
jsparc.sort_timestamps = sort_timestamps;
function sort_timestamps(a, b) {
/* Sort weather data by timestamp
*/
var t = weather_format.timestamp.column;
return a[t] - b[t];
}
jsparc.combine_datasets = combine_datasets;
function combine_datasets(urls) {
/* Concat several array into one
*/
var datatype = datasets[urls[0]].type;
for (var i = 0; i < urls.length; i++) {
if (urls[i].indexOf(datatype) == -1) {
return false;}} // Not all of same type!
var combined_dataset = [];
combined_dataset = combined_dataset.concat.apply(
[], urls.map(function(url) {return datasets[url].data;}));
return combined_dataset;
}
jsparc.make_ext_timestamp_str = make_ext_timestamp_str;
function make_ext_timestamp_str(timestamp, nanoseconds) {
/* Combine timestamp and nanoseconds to one value
See Warnings
*/
if (timestamp instanceof Array) {
var ext_timestamps = [];
for (var i = 0; i < timestamp.length; i++) {
var ns = nanoseconds instanceof Array ? nanoseconds[i] : null;
ext_timestamps.push(make_ext_timestamp(timestamp[i], ns));}
return ext_timestamps;}
nanoseconds = nanoseconds || null;
// return timestamp * 1e9 + nanoseconds;
return timestamp.toString() + pad_zero(nanoseconds, 9);
}
jsparc.make_ext_timestamp = make_ext_timestamp;
function make_ext_timestamp(timestamp, nanoseconds) {
/* Combine timestamp and nanoseconds to one value
See Warnings
*/
if (timestamp instanceof Array) {
var ext_timestamps = [];
for (var i = 0; i < timestamp.length; i++) {
var ns = nanoseconds instanceof Array ? nanoseconds[i] : null;
ext_timestamps.push(make_ext_timestamp(timestamp[i], ns));}
return ext_timestamps;}
nanoseconds = nanoseconds || null;
return timestamp * 1e9 + nanoseconds;
// return timestamp.toString() + pad_zero(nanoseconds, 9);
}
jsparc.make_javascript_timestamp = make_javascript_timestamp;
function make_javascript_timestamp(timestamp, nanoseconds) {
/* Combine timestamp and nanoseconds to one value
flot recognizes javascript timestamps for time series data
*/
if (timestamp instanceof Array) {
nanoseconds = nanoseconds || [];
var js_timestamps = [];
for (var i = 0; i < timestamp.length; i++) {
var ns = nanoseconds instanceof Array ? nanoseconds[i] : null;
js_timestamps.push(make_javascript_timestamp(timestamp[i], ns));}
return js_timestamps;}
nanoseconds = nanoseconds || null;
return timestamp * 1e3 + Math.round(nanoseconds / 1e6);
}
jsparc.get_ext_timestamp = get_ext_timestamp;
function get_ext_timestamp(url) {
/* Get ext_timestamps
See Warnings
*/
var type = datasets[url].type,
ext_timestamps;
if (type == 'events') {
ext_timestamps = make_ext_timestamp(get_column('timestamp', url),
get_column('nanoseconds', url));}
else {
ext_timestamps = make_ext_timestamp(get_column('timestamp', url));}
return ext_timestamps;
}
jsparc.get_column = get_column;
function get_column(column_name, url) {
/* Get a column from a dataset
If a column occurs more than once (e.g. pulseheights, integrals)
it will return an array containing each column:
[[x1, x2, x3, x4], [y1, y2, y3, y4]]
*/
var data = datasets[url].data,
type = datasets[url].type,
column = [];
var format, col, i, j;
if (column_name == 'event_rate') {
return generate_event_rate(url);}
if (jsparc.hasOwnProperty(type + '_format')) {
format = jsparc[type + '_format'];}
else {
format = unknown_format(url);}
try {
col = format[column_name].column;}
catch (e) {
var error = 'No column named: ' + column_name + ', in dataset: ' + url;
alert(error);
throw error;}
if (col.length) {
for (i = 0; i < col.length; i++) {
var values = [];
for (j = 0; j < data.length; j++) {
values[j] = data[j][col[i]];}
column[i] = values;}}
else {
for (i = 0; i < data.length; i++) {
column[i] = data[i][col];}}
return column;
}
jsparc.generate_event_rate = generate_event_rate;
function generate_event_rate(url) {
/* Generate event rate from timestamps
*/
var window = 300,
data = get_column('timestamp', url),
bins = range(data[0], data[data.length-1], window),
hist = histogram(data, bins),
rate = linear_interpolation(data, bins, hist[0]);
for (var i = 0; i < rate.length; i++) {
rate[i] /= window;}
return rate;
}
// User Interface
jsparc.make_station_select = make_station_select;
function make_station_select(target, type) {
/* Create a select menu to choose a single station
*/
var url;
if (type == 'events') {
url = api_stations_with_data();}
else if (type == 'weather') {
url = api_stations_with_weather();}
else if (type == 'singles') {
url = api_stations_with_singles();}
else {
url = api_stations();}
return get_json(url)
.done(function(station_json) {
var select = $('<select>'),
selected = Math.round(Math.random() * (station_json.length - 1)),
number,
name;
for (var i = 0; i < station_json.length; i++) {
number = station_json[i].number;
name = station_json[i].name;
if (i == selected) {
select.append($('<option>').text(number + ' - ' + name)
.attr('value', number)
.prop('selected', true));}
else {
select.append($('<option>').text(number + ' - ' + name)
.attr('value', number));}}
target.html(select);
});
}
jsparc.set_dataset_list_controls = set_dataset_list_controls;
function set_dataset_list_controls(target) {
target = target || $('#dataset_list');
target.on('click', 'td.delete', function() {
// Use array to store the set names ('set1' or 'set2') of div's
// that should be deleted
var set_array = [];
// Get selected radio button i.e. set1 or set2 in row we want
// to remove to know which div to empty out
$(this).parent().find('input:checked').each(function() {
set_array.push($(this).attr('name'));});
// find and empty divs
if (set_array.length) {
$.each(set_array, function(index, value){
$('#' + value + '_variables').empty();});}
// remove the dataset
remove_dataset_from_list(this);
$(this).parent().remove();});
}
jsparc.update_dataset_table = update_dataset_table;
function update_dataset_table(target) {
/* Create a readable overview table of the available datasets
*/
target = target || $('#dataset_list');
var list = $('<table>'),
firstrow = $('<tr>');
firstrow.append($('<th>').text('Select').attr('colspan', 2));
firstrow.append($('<th>').text('Station'));
firstrow.append($('<th>').text('Type'));
firstrow.append($('<th>').text('Start date'));
firstrow.append($('<th>').text('End date'));
firstrow.append($('<th>').text('Entries'));
firstrow.append($('<th>').text('Preview'));
firstrow.append($('<th>').text('Download'));
firstrow.append($('<th>').text('Remove'));
list.append(firstrow);
for (var i in datasets) {
if (!datasets.hasOwnProperty(i)) {continue;}
var row = $('<tr>').attr('name', datasets[i].url);
row.append($('<td>').append($('<input>').attr('type', 'radio')
.attr('title', 'Choose which dataset you want to use.' +
'Using both radio buttons you could select different datasets to interpolate data.')
.attr('name', 'set1').attr('alt', 'set2').val(i)));
row.append($('<td>').append($('<input>').attr('type', 'radio')
.attr('title', 'Select a second dataset, for example from a different row, to interpolate data.')
.attr('name', 'set2').attr('alt', 'set1').val(i)));
row.append($('<td>').text(datasets[i].station_number).addClass('station'));
row.append($('<td>').text(datasets[i].type).addClass('type'));
row.append($('<td>').text(datasets[i].startdate).addClass('start'));
row.append($('<td>').text(datasets[i].enddate).addClass('end'));
row.append($('<td>').text(datasets[i].data.length).addClass('entries'));
row.append($('<td>').text('show').addClass('preview').attr('name', datasets[i].url));
if (datasets[i].url.slice(0, 4) == 'http') {
row.append($('<td>').text('tsv').addClass('download')
.attr('name', datasets[i].url + '&download=true'));}
else {
row.append($('<td>').text('-'));}
row.append($('<td>').text('x').addClass('delete'));
list.append(row);}
target.html(list);
set_dataset_list_controls(target);
}
jsparc.update_dataset_select = update_dataset_select;
function update_dataset_select(target) {
/* Create a readable select menu of the available datasets
*/
var select = $('<select>');
var station_number, startdate, enddate, type, url, str;
for (var i in datasets) {
if (!datasets.hasOwnProperty(i)) {continue;}
station_number = datasets[i].station_number;
startdate = datasets[i].startdate;
enddate = datasets[i].enddate;
type = datasets[i].type;
url = datasets[i].url;
str = 'Station ' + station_number + ' - ' + type + ': ' + startdate + ' - ' + enddate;
select.append($('<option>').attr('value', url).text(str));}
target.html(select);
}
jsparc.make_variable_plot_table = make_variable_plot_table;
function make_variable_plot_table(url, target) {
/* Make an overview of available variables in the dataset for plot
*/
target = target || $('#set_variables');
var type = datasets[url].type,
format,
header = $('<span>').addClass('key').text(datasets[url].station_number + ' (' + datasets[url].type + ')'),
list = $('<table>').attr('name', url),
firstrow = $('<tr>'),
eventraterow = $('<tr>');
if (jsparc.hasOwnProperty(type + '_format')) {
format = jsparc[type + '_format'];}
else {
format = unknown_format(url);}
firstrow.append($('<th>').text('x-Axis'));
firstrow.append($('<th>').text('y-Axis'));
firstrow.append($('<th>').text('Variable'));
firstrow.append($('<th>').text('Units'));
list.append(firstrow);
/* Add Event Rate as variable
*/
if (format.hasOwnProperty('timestamp')) {
eventraterow.append($('<td>').append($('<input>').attr('type', 'radio')
.attr('name', 'x-axis').attr('alt', 'y-axis')
.data('label', 'Event rate [Hz]').val('event_rate')));
eventraterow.append($('<td>').append($('<input>').attr('type', 'radio')
.attr('name', 'y-axis').attr('alt', 'x-axis')
.data('label', 'Event rate [Hz]').val('event_rate')));
eventraterow.append($('<td>').text('Event rate'));
eventraterow.append($('<td>').text('Hz').addClass('units'));
list.append(eventraterow);}
for (var i in format) {
if (!format.hasOwnProperty(i)) {continue;}
if (i == 'date' || i == 'time') {continue;}
var row = $('<tr>').attr('name', i);
row.append($('<td>').append($('<input>').attr('type', 'radio')
.attr('name', 'x-axis').attr('alt', 'y-axis')
.data('label', format[i].name + ' [' + format[i].units + ']').val(i)));
row.append($('<td>').append($('<input>').attr('type', 'radio')
.attr('name', 'y-axis').attr('alt', 'x-axis')
.data('label', format[i].name + ' [' + format[i].units + ']').val(i)));
row.append($('<td>').text(format[i].name).addClass('variable'));
row.append($('<td>').text(format[i].units).addClass('units'));
list.append(row);}
target.html(header);
target.append(list);
}
jsparc.create_dataset_table = create_dataset_table;
function create_dataset_table(url, target, limit) {
/* Create a table representation of a dataset
*/
target = (target) ? target : $('#dataTable');
limit = (limit) ? limit : dataset.data.length;
var dataset = datasets[url],
type = dataset.type,
table = $('<table>').addClass(dataset.type);
if (limit > dataset.data.length) {
limit = dataset.data.length;}
// Header row
var firstrow = $('<tr>'),
format;
if (jsparc.hasOwnProperty(type + '_format')) {
format = jsparc[type + '_format'];}
else {
format = unknown_format(url);}
firstrow.append($('<th>').text('#'));
for (var key in format) {
if (!format.hasOwnProperty(key)) {continue;}
var ncol = (format[key].column.length) ? format[key].column.length : 1;
firstrow.append($('<th>').text(format[key].name).attr('colspan', ncol));}
if (type == 'events') {
firstrow.append($('<th>').text('Trace'));}
table.append(firstrow);
// Data rows
for (var i = 0; i < dataset.data.length; i++) {
var row = $('<tr>');
row.append($('<td>').text(i + 1));
for (var j = 0; j < dataset.data[i].length; j++) {
row.append($('<td>').text(dataset.data[i][j]));}
if (type == 'events') {
var t = make_ext_timestamp_str(dataset.data[i][2], dataset.data[i][3]);
var trace_url = api_event_trace(dataset.station_number, t);
row.append($('<td>').text('show').addClass('trace').attr('data-url', trace_url));}
table.append(row);
if (limit != dataset.data.length && i == Math.floor(limit / 2) - 1) {
var truncrow = $('<tr>');
truncrow.append($('<td>')
.text('... truncated table, click here to show more rows ...')
.attr('colspan', dataset.data[0].length + 1)
.css({'text-align': 'left',
'cursor': 'pointer'})
.click(function() {create_dataset_table(url, target, limit * 2);}));
table.append(truncrow);
i = dataset.data.length - 1 - Math.ceil(limit / 2);}}
target.html(table);
}
// AJAX
jsparc.get_multiple_json = get_multiple_json;
function get_multiple_json(urls) {
/* Asynchronously download multiple urls of type json
*/
return $.when.apply(null, urls.map(function (url) {return get_json(url);}));
}
jsparc.get_multiple_tsv = get_multiple_tsv;
function get_multiple_tsv(urls) {
/* Asynchronously download multiple urls of type tsv
*/
return $.when.apply(null, urls.map(function (url) {return get_tsv(url);}));
}
jsparc.get_json = get_json;
function get_json(url) {
/* Asynchronously download data of type json
*/
return $.ajax({url: url,
dataType: 'json',
type: 'GET'});
}
jsparc.get_tsv = get_tsv;
function get_tsv(url) {
/* Asynchronously download data of type tsv
The tsv data will be converted to an array
Comment headers will be removed
*/
return $.ajax({url: url,
converters: {'text json': parse_tsv},
dataType: 'json',
type: 'GET'});
}
// API
/* Functions to construct URLs to access the publicdb API
*/
jsparc.api_man = api_man;
function api_man() {
return API_URL;}
jsparc.api_stations = api_stations;
function api_stations() {
return build_url([API_URL, 'stations', '']);}
jsparc.api_stations_in_subcluster = api_stations_in_subcluster;
function api_stations_in_subcluster(subcluster_number) {
return build_url([API_URL, 'subclusters', subcluster_number, '']);}
jsparc.api_subclusters = api_subclusters;
function api_subclusters() {
return build_url([API_URL, 'subclusters', '']);}
jsparc.api_subclusters_in_cluster = api_subclusters_in_cluster;
function api_subclusters_in_cluster(cluster_number) {
return build_url([API_URL, 'clusters', cluster_number, '']);}
jsparc.api_clusters = api_clusters;
function api_clusters() {
return build_url([API_URL, 'clusters', '']);}
jsparc.api_clusters_in_country = api_clusters_in_country;
function api_clusters_in_country(country_number) {
return build_url([API_URL, 'countries', country_number, '']);}
jsparc.api_countries = api_countries;
function api_countries() {
return build_url([API_URL, 'countries', '']);}
jsparc.api_stations_with_data = api_stations_with_data;
function api_stations_with_data(year, month, day) {
return build_url([API_URL, 'stations/data', year, month, day, '']);}
jsparc.api_stations_with_weather = api_stations_with_weather;
function api_stations_with_weather(year, month, day) {
return build_url([API_URL, 'stations/weather', year, month, day, '']);}
jsparc.api_stations_with_singles = api_stations_with_singles;
function api_stations_with_singles(year, month, day) {
return build_url([API_URL, 'stations/singles', year, month, day, '']);}
jsparc.api_station_info = api_station_info;
function api_station_info(station_number, year, month, day) {
return build_url([API_URL, 'station', station_number, year, month, day, '']);}
jsparc.api_has_data = api_has_data;
function api_has_data(station_number, year, month, day) {
return build_url([API_URL, 'station', station_number, 'data', year, month, day, '']);}
jsparc.api_has_weather = api_has_weather;
function api_has_weather(station_number, year, month, day) {
return build_url([API_URL, 'station', station_number, 'weather', year, month, day, '']);}
jsparc.api_configuration = api_configuration;
function api_configuration(station_number, year, month, day) {
return build_url([API_URL, 'station', station_number, 'config', year, month, day, '']);}
jsparc.api_number_of_events = api_number_of_events;
function api_number_of_events(station_number, year, month, day, hour) {
return build_url([API_URL, 'station', station_number, 'num_events', year, month, day, hour, '']);}
jsparc.api_event_trace = api_event_trace;
function api_event_trace(station_number, ext_timestamp) {
return build_url([API_URL, 'station', station_number, 'trace', ext_timestamp, '']);}
// Process urls
jsparc.build_url = build_url;
function build_url(components) {
return components.join('/').replace(/\/+$/,'/');}
// Data Download
jsparc.data_example = data_example;
function data_example(station_number, startdate, enddate, type) {
/* Construct URLs to access local example data
*/
if (type == 'events') {
return './examples/events-s501-20130910.tsv';}
//return './examples/events-s8006-20130910.tsv';}
else {
return './examples/weather-s501-20130910.tsv';}}
//return './examples/weather-s8006-20130910.tsv';}}
jsparc.data_download = data_download;
function data_download(station_number, startdate, enddate, type) {
/* Construct URLs to access the publicdb data download
*/
return [DATA_URL, station_number, type].join('/') + '?start=' + startdate + '&end=' + enddate;}
// jSparc
jsparc.jsparc_get_coincidence = jsparc_get_coincidence;
function jsparc_get_coincidence(get_coincidence) {
/* Create url with query to get a coincidence from a jSparc analysis session
get_coincidence should be an object with the following keys:
session_title, session_pin, student_name
*/
return [JSPARC_URL, 'get_coincidence', ''].join('/') + '?' + $.param(get_coincidence);}
jsparc.jsparc_result = jsparc_result;
function jsparc_result(result) {
/* Create url with query to send the jSparc analysis session results to the server
result should be an object with the following keys:
session_title, session_pin, student_name, pk, logEnergy, error, lon, lat
*/
return [JSPARC_URL, 'result', ''].join('/') + '?' + $.param(result);}
// Flot
// Requires jquery.flot.js
jsparc.make_plot = make_plot;
function make_plot(target, data) {
/* Create a plot of data
data can be a single dataset: [[x1, y1], [x2, y2], ... ]
or consist of multiple datasets i.e. serie 1 and 2: [[[x11, y11], ... ], [[x21, y21], ...], ...]
Warning: This function filters all data points for which
either the x or y value is -999 or -1.
*/
target = (target) ? target : $('#plot');
var datas = [{data: [1, 1], lines: {show: false}, xaxis: 2, yaxis: 2}];
if (data[0][0] instanceof Array) {
for (var i = data.length - 1; i >= 0; i--) {
datas.unshift({data: data[i], yaxis: 1});}}
else {
datas.unshift({data: data, yaxis: 1});}
return $.plot(target, datas, flot_active);
}
jsparc.download_plot = download_plot;
function download_plot(target) {
/* Open a new window with a png version (base64 encoded) of the plot
*/
target = (target) ? target : $('#plot');
var dataurl = target.find('.flot-base')[0].toDataURL();
window.open(dataurl, '_blank', 'height=450, width=820, toolbar=yes');
}
jsparc.zip_data = zip_data;
function zip_data(x, y) {
/* Create a zipped array of 2 arrays
Give two equal length arrays (x, y)
They will be zipped to: [[x1, y1], [x2, y2], [x3, y3], ...]
If x OR y contains multiple arrays each will be zipped with the other:
[[[x1, y11], [x2, y12], ...], [[x1, y21], [x2, y22], ...], ...]
[[[x11, y1], [x12, y2], ...], [[x21, y1], [x22, y2], ...], ...]
If both x AND y contain multiple arrays each will be zipped with their counterpart:
[[[x11, y11], [x12, y12], ...], [[x21, y21], [x22, y22], ...], ...]
*/
var data = [],
i;
if (x[0] instanceof Array && y[0] instanceof Array) {
if (x.length == y.length) {
for (i = 0; i < x.length; i++) {
data[i] = zip_data(x[i], y[i]);}}
else {
for (i = 0; i < x.length; i++) {
for (var j = 0; j < y.length; j++) {
data[i + j * (y.length - 1)] = zip_data(x[i], y[j]);}}}}
else if (x[0] instanceof Array) {
for (i = 0; i < x.length; i++) {
data[i] = zip_data(x[i], y);}}
else if (y[0] instanceof Array) {
for (i = 0; i < y.length; i++) {
data[i] = zip_data(x, y[i]);}}
else {
for (i = 0; i < x.length; i++) {
data.push([x[i], y[i]]);}}
return data;
}
jsparc.linear_interpolation = linear_interpolation;
function linear_interpolation(x1, x2, y2) {
/* Make a linear interpolation to get y2 to be the same length as x1
*/
var y1 = [];
var k, dydx;
if (y2[0] instanceof Array) {
for (k = 0; k < y2.length; k++) {
y1[k] = [];}}
for (var i = 0; i < x1.length; i++) {
var j = bisect_search(x1[i], x2);
if (y2[0] instanceof Array) {
for (k = 0; k < y2.length; k++) {
dydx = (y2[k][j + 1] - y2[k][j]) / (x2[j + 1] - x2[j]);
y1[k][i] = y2[k][j] + dydx * (x1[i] - x2[j]);}}
else {
dydx = (y2[j + 1] - y2[j]) / (x2[j + 1] - x2[j]);
y1.push(y2[j] + dydx * (x1[i] - x2[j]));}}
return y1;
}
jsparc.bisect_search = bisect_search;
function bisect_search(point, array) {
/* Use bisection to find an index i where array[i] <= point < array[i + 1].
*/
if (point >= array[array.length - 2]) {
return array.length - 2;}
if (point < array[1]) {
return 0;}
var imin = 0;
var imax = array.length;
while (imin < imax) {
var imid = imin + ((imax - imin) >> 1);
if (point >= array[imid]) {
imin = imid + 1;}
else {
imax = imid;}}
return imin - 1;
}
jsparc.set_flot_options = set_flot_options;
function set_flot_options(options) {
/* Combine plot options
Apply these options to the float_base options
line style (histogram, line, scatter)
axis (x, y: linear, log)
variables (x, y: labels)
*/
var extend_default = [true, {}, flot_base];
for (var i = 0; i < options.length ; i++) {
extend_default.push(options[i]);}
flot_active = $.extend.apply([], extend_default);
}
jsparc.add_flot_options = add_flot_options;
function add_flot_options(options) {
/* Append plot options to the currently active options
*/
flot_active = $.extend(true, {}, flot_active, options);
}
// Flot options
// Requires jquery.flot.axislabels.js, jquery.flot.time.js
jsparc.flot_active = function() {return flot_active;};
var flot_active = {};
jsparc.flot_base = function() {return flot_base;};
var flot_base = {
colors: ['#222', '#D22', '#1C1', '#1CC', '#C1C', '#15C', '#AA1', '#C51'],
legend: {show: false},
xaxis: {
show: true,
font: {
size: 14,
lineHeight: 14,
family: 'sans-serif',
color: '#000'},
color: '#000',
tickColor: '#000',
labelHeight: 23,
tickLength: 4,
axisLabelUseCanvas: true},
yaxis: {
show: true,
font: {
size: 14,
lineHeight: 14,
family: 'sans-serif',
color: '#000'},
color: '#000',
tickColor: '#000',
tickLength: 4,
axisLabelUseCanvas: true},
y2axis: {
show: true,
position: 'right',
tickFormatter: _hide_tick_labels,