-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
595 lines (520 loc) · 23 KB
/
app.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
var L = require('leaflet');
var LD = require('leaflet-draw')
var Lfullscreen = require('leaflet-fullscreen')
var utils = require('./utils.js');
var random = require('geojson-random');
var easybutton = require('leaflet-easybutton');
const Cookies = require('js-cookie'); //assign module to variable called "Cookies"
var mlutils = require("./ml-utils");
var data = require("./data.js");
var db = require("./src/dbAccess.js");
var tfvis = require('@tensorflow/tfjs-vis')
L.Icon.Default.imagePath = 'node_modules/leaflet/dist/images/';
/* Base Setup of the Map*/
// center of the map
var center = [40.5853, -105.0844];
console.time("Home");
// Create the map
var map = L.map('map',
{
renderer: L.canvas(),
zoomSnap: 0
});
map.setView(center, 5);
var tiles = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
// Set up the OSM layer
var mainlayer = L.tileLayer(tiles, {
attribution: 'Data © <a href="http://osm.org/copyright">OpenStreetMap</a>',
maxZoom: 18,
});
mainlayer.addTo(map);
//Add the map scale
L.control.scale().addTo(map);
/* END Base Setup of the Map*/
//////////////// ////////////// On click interactivity
// var popup = L.popup();
// function onMapClick(e) {
// map.flyTo(e.latlng);
// popup
// .setLatLng(e.latlng)
// .setContent("<strong>" + e.latlng.lat.toFixed(2).toString() + "," + e.latlng.lng.toFixed(2).toString() + "</strong>")
// .openOn(map);
// //breadcrumb update
// }
//
// map.on("click", onMapClick);
/////////////////////////////END on click interactivity
//////////////////////////DRAW CONTROL ON THE MAP
// Initialize the FeatureGroup to store editable layers
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
exports.editableLayers = editableLayers;
var options = {
position: "topleft",
draw: {
polygon: {
// allowIntersection: false, // Restricts shapes to simple polygons
// drawError: {
// color: "#e1e100", // Color the shape will turn when intersects
// message: "<strong>Oh snap!<strong> you can't draw that!", // Message that will show when intersect
// },
shapeOptions: {
color: "#f8c39b",
weight: 0.01
},
},
polyline: {
shapeOptions: {
color: "#f357a1",
weight: 1,
},
},
// disable toolbar item by setting it to false
// polyline: true,
// circle: true, // Turns off this drawing tool
// polygon: true,
// marker: true,
// rectangle: true,
},
edit: {
featureGroup: editableLayers, //REQUIRED!!
remove: true,
},
};
// Initialize the draw control and pass it the FeatureGroup of editable layers
var drawControl = new L.Control.Draw(options);
map.addControl(drawControl);
map.on("draw:created", function (e) {
var type = e.layerType,
layer = e.layer;
if (type === "polyline") {
layer.bindPopup("A polyline!");
} else if (type === "polygon") {
layer.bindPopup("A polygon!");
} else if (type === "marker") {
layer.bindPopup("marker!");
} else if (type === "circle") {
layer.bindPopup("A circle!");
} else if (type === "rectangle") {
layer.bindPopup("A rectangle!");
}
editableLayers.addLayer(layer);
});
// drawControl.setDrawingOptions({
// polygon: {
// shapeOptions: {
// color: '#eccdb6',
// weight:0.001
// }
// }
// });
//////////////////////////END DRAW CONTROL ON THE MAP
//////////////////////////start fullscreen CONTROL ON THE MAP
map.addControl(new L.Control.Fullscreen());
map.on('fullscreenchange', function () {
if (map.isFullscreen()) {
console.log('entered fullscreen');
fscrinfo.addTo(map);
} else {
console.log('exited fullscreen');
fscrinfo.remove();
}
});
//////////////////////////end fullscreen CONTROL ON THE MAP
/*Performance check by adding large number of circle markers*/
////////////// control that shows state info on hover
var info = L.control();
info.onAdd = function (map) {
this._div = L.DomUtil.create("div", "info legend",);
this.update();
return this._div;
};
info.update = function (props) {
this._div.innerHTML = "<h4>Test: </h4>" + (props ? "<b id='num_shapes'>" + props.name.toString() +", " + props.timestamp.toString() + " ms</b><br />" : "Starting Experiment");
};
info.addTo(map);
exports.info = info;
////////////END control that shows state info on hover
function onEachFeature(feature, layer) {
// console.log(feature.properties.NAME);
if (feature.properties && feature.properties.NAME) {
layer.bindPopup(feature.properties.NAME);
}else{
layer.bindPopup("Sample Properties:" + "\n" + "1)This is a polygon");
}
preplotpoints.push(feature.properties.NAME);
}
var preplotpoints = [];
exports.onEachFeature = onEachFeature;
exports.preplotpoints = preplotpoints;
window.getLoadPoints = data.getLoadPoints;
window.getLoadShapes = data.getLoadShapes;
window.getLoadData = data.getLoadData;
window.sleep = data.sleep;
async function getCompoundData(numPoints, numShapes, numTracts){
var shapes = [];
const starttime = Date.now();
performance.mark("all performanceAnalyzerData: loading");
for(i = 1 ; i <= numShapes; i++){
let filename='pentagons_run_' + i.toString() + '.json' //petagons_run_'+ i.toString()+'.json';
shapes[i] = $.ajax({
url: "https://raw.githubusercontent.com/mehrotrasan16/us-census-tracts-shapefiles-and-geojson/master/shape-data/"+filename,
dataType: "json",
success: function (data){
// console.log(filename + " Retrieved");
// console.log(shapes)
performance.mark('Start: Adding Shape Layer ' +i +' to map');
editableLayers.addLayer(L.geoJSON(data,{
onEachFeature: onEachFeature,
style: {
color: '#eccdb6',
weight:1,
stroke: true,
fill:false
}
}));
performance.mark('Done: Adding Shape Layer ' +i +' to map');
performance.measure('Shape Layer ' + i + ' Scripting:', 'Start: Adding Shape Layer ' +i +' to map', 'Done: Adding Shape Layer ' +i+' to map');
var updateProps = {
name: preplotpoints.length,
timestamp: Date.now() - starttime,
};
info.update(updateProps);
},
error: function (xhr){
// console.log(xhr.statusText);
//alert(xhr.statusText);
},
complete: function(data) {
mypagefn();
var points = [];
const starttime = Date.now();
// performance.mark("all points: loading");
for(i = 1 ; i <= numPoints; i++){
let filename='points_run_'+ i.toString()+'.json';
points[i] = $.ajax({
url: "https://raw.githubusercontent.com/mehrotrasan16/us-census-tracts-shapefiles-and-geojson/master/point-data/"+filename,
dataType: "json",
success: function (data){
// console.log(filename + " Retrieved");
performance.mark("Start: Adding Point Layer " +i +" to map");
editableLayers.addLayer(L.geoJSON(data,{
onEachFeature: onEachFeature,
pointToLayer: function (geoJsonPoint,latlng){
return L.circle(latlng);
}
}
)
);
performance.mark('Done: Adding Point Layer ' +i +' to map'); //Loading and Adding done for one performanceAnalyzerData file.
performance.measure('Point Layer ' + i + ' Scripting:', 'Start: Adding Point Layer ' +i+' to map', 'Done: Adding Point Layer ' +i +' to map');
var updateProps = {
name: preplotpoints.length,
timestamp: Date.now() - starttime,
};
info.update(updateProps);
},
error: function (xhr){
// console.log(xhr.statusText);
//alert(xhr.statusText);
},
complete: function(data) {
mypagefn();
performance.mark("all points: loaded")
var stateshapes = [];
// let num_states = 30
const starttime = Date.now();
//https://medium.com/@maptastik/loading-external-geojson-a-nother-way-to-do-it-with-jquery-c72ae3b41c01 dynamically load geojson
for(i = 1 ; i <= numTracts; i++){
let statenumber=(i < 10)? '0'+i.toString():i.toString()
let filename='cb_2018_'+statenumber+'_tract_500k.json';
stateshapes[i] = $.ajax({
url: "https://raw.githubusercontent.com/mehrotrasan16/us-census-tracts-shapefiles-and-geojson/master/USA-cb_tract_500k-geojson/"+filename,
dataType: "json",
success: function (data){
// console.log(filename + " Retrieved");
// console.log(stateshapes[i]);
// console.log(performanceAnalyzerData);
performance.mark("Start: Adding Tract Layer " +i +" to map");
editableLayers.addLayer(L.geoJSON(data,{
onEachFeature: onEachFeature,
style: {
// color: '#eccdb6',
weight:1,
stroke: true,
fill:false
}
})
);
performance.mark("Done: Adding Tract Layer " +i +" to map");
performance.measure('Tract Layer ' + i + ' Scripting:', 'Start: Adding Tract Layer ' +i+' to map', 'Done: Adding Tract Layer ' +i +' to map');
var updateProps = {
name: preplotpoints.length,
timestamp: Date.now() - starttime,
};
info.update(updateProps);
},
error: function (xhr){
// console.log(xhr.statusText);
//alert(xhr.statusText);
},
complete: function (data) {
performance.mark("tracts Loaded")
localmydata = mypagefn(); //returns a promise.
// console.log(localmydata);
localmydata.then(function(res) {
window.mycorr = utils.calculateCorrelation(res.x);
var json_str = JSON.stringify(window.mycorr);
Cookies.set('mycorr', json_str);
// console.log(window.mycorr);
});
// setTimeout(() => {
// console.log(utils.calculateCorrelation.bind(localmydata.x)());
// }, 3000);
}
})
}
window.stateshapes = stateshapes;
}
})
}
window.pointshapes = points;
}
})
}
window.pentshapes = shapes;
}
//----------------------------------------
//Network Connection Information API
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
var type = connection.effectiveType;
function updateConnectionStatus() {
console.log("Connection type changed from " + type + " to " + connection.effectiveType);
type = connection.effectiveType;
}
connection.addEventListener('change', updateConnectionStatus);
//----------------------------------------
var mybtn = L.easyButton({
id: "random_data_puller",
position: 'topleft',
leafletClasses: true,
states: [{
stateName: 'center',
onClick: function(btn, map){
// console.profile("MeME")
console.time("getLoadData")
// clicked(this);
// $.when(getLoadData(5)).then().then(mypagefn());
getCompoundData(1,1,7);
console.timeEnd("getLoadData");
// console.profileEnd();
// console.log("mydataframe");
// console.log(mydata)
},
title: 'Performance',
icon: '<img src="images/performance.svg">',
}]
}).addTo(map);
// async function clicked(elem) {
// preplotpoints = [];
// getLoadData(5);
// // getLoadShapes(1);
// getLoadPoints(3);
// // $.when(getLoadData(5)).then(getLoadPoints(3));
// performance.measure('button clicked');
// console.log("Page Load timings Info");
// console.log(utils.network_perf_info());
// console.log(utils.get_web_vitals());
// console.log("Network Connection Information! : ");
// console.log(navigator.connection);
// }
//Data Structure to hold all my features plus their outputs
var mydata = {
x: [],
y: []
}
var jsonData = []
async function mypagefn() {
var x = await document.getElementsByClassName("legend");
var shapecount = await x[0].innerHTML.split(",")[0].split('>')[3];
//console.log(shapecount);
//Total Loading time of all resources, including XMLHTTPRequests
var resourceLoadingSum = 0;
var xmlHttpRequestLoadingSum = 0;
performance.getEntriesByType('resource').forEach(entry => {
resourceLoadingSum += entry.duration;
if(entry.initiatorType === "xmlhttprequest"){ //cool one liner to do this : p.filter(function(entry) { return entry.initiatorType === "xmlhttprequest" })
xmlHttpRequestLoadingSum += entry.duration;
}
});
// myWebvitals = await utils.get_web_vitals();
// mypageLoadInfo = await utils.network_perf_info();
mypageMemoryData = await utils.memory_performance_info();
var EffectiveConnectionTypeDict = {
"2g":2,
"3g":3,
"4g":4,
"slow-2g":1
};
var totalDataDownloaded = 0;
if(window.stateshapes){
window.stateshapes.forEach(function(ajaxobject) {
totalDataDownloaded += (ajaxobject.getResponseHeader('Content-Length')? parseInt(ajaxobject.getResponseHeader('Content-Length')): 0 );
});
}
if(window.pointshapes){
pointshapes.forEach(function(ajaxobject) {
totalDataDownloaded += (ajaxobject.getResponseHeader('Content-Length')? parseInt(ajaxobject.getResponseHeader('Content-Length')): 0 );
});
}
if(window.pentshapes){
window.pentshapes.forEach(function(ajaxobject) {
totalDataDownloaded += (ajaxobject.getResponseHeader('Content-Length')? parseInt(ajaxobject.getResponseHeader('Content-Length')): 0 );
});
}
mydata.x.push([resourceLoadingSum,xmlHttpRequestLoadingSum,totalDataDownloaded, mypageMemoryData.usedJSHeapSize/mypageMemoryData.totalJSHeapSize]); //mypageLoadInfo, myWebvitals
mydata.y.push(parseInt(shapecount));
var jsonrec = {
"timestamp": Date.now(),
"nodes": parseInt(shapecount),
"resourceLoadingTime":resourceLoadingSum,
"xmlHttpRequestLoadingTime": xmlHttpRequestLoadingSum,
"totalDataDownloaded":totalDataDownloaded,
"connectionType": EffectiveConnectionTypeDict[connection.effectiveType],
"connectionMaxSpeed":connection.downlink,
"JSmemoryUsed": mypageMemoryData.usedJSHeapSize,
"JStotalMemory": mypageMemoryData.totalJSHeapSize,
"deviceRAM": navigator.deviceMemory
}
jsonData.push(jsonrec);
// console.log("mydataframe");
//console.log(mydata);
window.mydata = mydata;
window.jsonData = jsonData;
var json_str = JSON.stringify(mydata);
Cookies.set('mydata',json_str);
json_str = JSON.stringify(jsonData);
Cookies.set('jsonData',json_str);
return mydata;
}
exports.mypagefn = mypagefn;
//-------------------------------------------------
var corrBtn = L.easyButton({
id: "corrButton",
position: 'topleft',
leafletClasses: true,
states: [{
stateName: 'center',
onClick: function(btn, map){
// create popup contents
// var matrix = JSON.parse(Cookies.get('mycorr'));
// var json_str = JSON.stringify(matrix);
// Cookies.set('mycorr', json_str);
utils.drawCorrelogram('mycorr');
},
title: 'Correlation Graph',
icon: '<i>☈</i>',
}]
}).addTo(map);
// document.getElementById("random_data_puller").click();
// document.getElementById("corrButton").click();
//-------------------------------------------------------
var trainBtn = L.easyButton({
id: "trainButton",
position: 'topleft',
leafletClasses: true,
states: [{
stateName: 'center',
onClick: function(btn, map){
mlutils.run();
},
title: 'Train Model',
icon: '<i>⚙</i>',
}]
}).addTo(map);
var viewBtn = L.easyButton({
id: "viewButton",
position: 'topleft',
leafletClasses: true,
states: [{
stateName: 'center',
onClick: function(btn, map){
tfvis.visor().toggle();
},
title: 'View Window',
icon: '<i>ModelView</i>',
}]
}).addTo(map);
//-------------------------------------------------
var storeBtn = L.easyButton({
id: "storeButton",
position: 'topleft',
leafletClasses: true,
states: [{
stateName: 'center',
onClick: function(btn, map){
var json_arr = window.jsonData;
// console.log("Storing");
// console.log(json_arr.length);
// console.log(json_arr[0]);
callIdb(json_arr);
},
title: 'Store Measurements',
icon: '<i>DB ⬇</i>',
}]
}).addTo(map);
/***
* https://stackoverflow.com/questions/54718446/objectstore-add-not-adding-data-with-different-key-in-indexeddb
* @param json_arr
*/
function callIdb(json_arr) {
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction || {READ_WRITE: "readwrite"}; // This line should only be needed if it is needed to support the object's constants for older browsers
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
if (!window.indexedDB) {
console.log("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.");
} else {
console.log("You're good to go with IndexedDB");
}
var request = window.indexedDB.open("PerfDB", 1);
request.onerror = function(event) {
console.log("Hi, DB Open Failure. Please Try again", event);
};
request.onupgradeneeded = function(event) {
console.log('(WINR.UGN)Within request.upgradeneeded');
var db = event.target.result;
console.log("(WINR.UGN) db:", db);
var oS = db.createObjectStore("dom_measurements", { keyPath: "timestamp" });
// oS.createIndex("name", "name", { unique: false });
// oS.createIndex("email", "email", { unique: true });
// oS.createIndex("age", "age", { unique: false });
};
request.onsuccess = function(event) {
console.log('(WOR.NS) Within request.onsuccess');
var db = event.target.result;
console.log("(WOR.NS) db= ", db);
var rTrans = db.transaction("dom_measurements", "readwrite").objectStore("dom_measurements");
json_arr.forEach(function(json_rec) {
rTrans.add(json_rec);
// console.log("You followed directions! Well done. var restaurant: ", json_rec, "stored with this transaction: ", rTrans);
});
rTrans.oncomplete = function () {
console.log("CONGRATULATIONS.");
}
rTrans.onerror = function () {
console.log("error in insertion to Idb.");
}
};
request.onupgradeneeded.onerror = function(event) {
console.log("err", event);
}
}
//-------------------------------------------------
// But with the Performance APIs, we can get real user measurement (RUM) in production.
//The downlink attribute represents the effective bandwidth estimate in megabits per second, rounded to nearest multiple of 25 kilobits per second, and is based on recently observed application layer throughput across recently active connections, excluding connections made to private address space [RFC1918].
//connection.rtt: The rtt attribute represents the effective round-trip time estimate in milliseconds, rounded to nearest multiple of 25 milliseconds, and is based on recently observed application-layer RTT measurements across recently active connections, excluding connections made to private address space [RFC1918].
// EffectiveDataTypesEnum - https://wicg.github.io/netinfo/#webidl-403640128
//The PerformancePaintTiming interface of the Paint Timing API provides timing information about "paint" (also called "render") operations during web page construction. "Paint" refers to conversion of the render tree to on-screen pixels.
//stateshapes[1].getResponseHeader('Content-Length')
// https://blog.logrocket.com/rethinking-frontend-apm/
// In modern single-page apps, performance is affected by a host of factors, including network requests, JavaScript execution, local resource access, CPU load, and memory usage. Slowness can be introduced from the backend, CDN layer, internet connectivity, JavaScript performance, or client device (iOS, Android, browser, etc.).