-
Notifications
You must be signed in to change notification settings - Fork 3
/
script.js
571 lines (490 loc) · 18.8 KB
/
script.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
// Chartspecs and DataElement should be eliminated, so do not do anything with it.
//const { data } = require("jquery");
// dataElements are classes for data row/objects.
class DataElement{
constructor(cat, y){
// cat: a category, numeric value.
//this.cat = new Date(2000, 0, 1, cat.split(':')[0], cat.split(':')[1]);
this.cat = cat;
// y: independent numeric value.
this.y = y;
}
}
// ChartSpecs holds the general display parameters and data for a chart.
class ChartSpecs {
// Constructor for parts of the chart that depend upon the data.
constructor(data){
// The x/y relational data for the chart.
this.data = data;
// Establish the basic parameters of the display
// The starting position of the chart.
this.chartBodyX = 50;
this.chartBodyY = 0;
// The relative size of the axes.
this.xScaleWidth = 300;
this.yScaleHeight = 200;
// The number of tick marks on the x axis.
this.numTicks = 5;
// The amount of space to allocate for text,e etc. on the x and y axes.
this.textBuffer = 60;
this.topMargin = 10;
// Take calcs out of loop functions.
this.theMax = 0;
this.theExtents;
}
// The maximum value of the independent variable.
get maxVal() {
return d3.max(this.data, d => d.y);
}
// To create a scaling Y function for the chart, use this getter.
get scaleY() {
return d3.scaleLinear()
.range([this.yScaleHeight, 0])
.domain([0, this.theMax]);
}
// To create a scaling X function for the chart, use this getter.
get scaleX() {
return d3.scaleTime()
.range([0, this.xScaleWidth])
//.domain(d3.extent(this.data, d=>d.cat))
.domain(this.theExtents)
}
setMax(){
this.theMax = d3.max(this.data, d=>d.y);
}
setExtents(){
this.theExtents = d3.extent(this.data, d=>d.cat)
}
}
// When the document is loaded:
// Create some data
// Draw a line chart with the data.
document.addEventListener("DOMContentLoaded", function() {
// Personalization variables.
let fileName = null;
let authorName = null;
let description = null;
/////////////////////////////////////////////
// Cover modal: for project intros, demos, etc.
/////////////////////////////////////////////
if(document.getElementById("modalCover")){
if(document.getElementById("defaultModel1")){
document.getElementById("defaultModel1").addEventListener('click',
function () {
jQuery.get('./data/Example1.inp', function(contents){
processInput(contents);
})
$('#modalCover').modal('toggle');
},
false)
}
if(document.getElementById("defaultModel2")){
document.getElementById("defaultModel2").addEventListener('click',
function () {
jQuery.get('./data/Example2.inp', function(contents){
processInput(contents);
})
$('#modalCover').modal('toggle');
},
false)
}
$('#modalCover').modal('toggle');
}
/////////////////////////////////////////////
// Visualization elements - temporary
/////////////////////////////////////////////
// dataObj is an array of dataElement objects.
dataObj = [];
let viz_svg01 = d3.select("#viz_svg01");
let inpText = null;
/////////////////////////////////////////////
// Modal controls.
/////////////////////////////////////////////
// Get the modal
let modal = document.getElementById("myModal");
$('.modal-backdrop').remove();
/////////////////////////////////////////////
// Project Tree controls.
/////////////////////////////////////////////
// Setting up to process input file.
Module.onRuntimeInitialized = _ => {
// Process the metadata file
// Load info.json if there is a cover modal
if(document.getElementById("modalCover")){
fetchRetry('./data/info.json', 500, 20, {headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}});
}
}
// Listen for requests to open the default file.
const demoElement = document.getElementById("nav-file-demo");
if(demoElement){
demoElement.addEventListener('click', loadDemo, false);
function loadDemo() {
jQuery.get('./data/Mod.inp', function(contents){
processInput(contents);
})
}
}
// Listen for requests to create a new file.
const newFileElement = document.getElementById("nav-file-new");
if(newFileElement){
newFileElement.addEventListener('click', createNewFile, false);
function createNewFile() {
document.getElementById('inpFile').value =
`[TITLE]
;;Project Title/Notes
[OPTIONS]
;;Option Value
FLOW_UNITS CFS
INFILTRATION HORTON
FLOW_ROUTING KINWAVE
LINK_OFFSETS DEPTH
MIN_SLOPE 0
ALLOW_PONDING NO
SKIP_STEADY_STATE NO
START_DATE 03/26/2021
START_TIME 00:00:00
REPORT_START_DATE 03/26/2021
REPORT_START_TIME 00:00:00
END_DATE 03/26/2021
END_TIME 06:00:00
SWEEP_START 1/1
SWEEP_END 12/31
DRY_DAYS 0
REPORT_STEP 00:15:00
WET_STEP 00:05:00
DRY_STEP 01:00:00
ROUTING_STEP 0:00:30
INERTIAL_DAMPING PARTIAL
NORMAL_FLOW_LIMITED BOTH
FORCE_MAIN_EQUATION H-W
VARIABLE_STEP 0.75
LENGTHENING_STEP 0
MIN_SURFAREA 0
MAX_TRIALS 0
HEAD_TOLERANCE 0
SYS_FLOW_TOL 5
LAT_FLOW_TOL 5
[EVAPORATION]
;;Evap Data Parameters
;;-------------- ----------------
CONSTANT 0.0
DRY_ONLY NO
[REPORT]
;;Reporting Options
INPUT NO
CONTROLS NO
SUBCATCHMENTS ALL
NODES ALL
LINKS ALL
[TAGS]
[MAP]
DIMENSIONS 0.000 0.000 10000.000 10000.000
Units None
[COORDINATES]
;;Node X-Coord Y-Coord
;;-------------- ------------------ ------------------
[VERTICES]
;;Link X-Coord Y-Coord
;;-------------- ------------------ ------------------
`
processInput(document.getElementById('inpFile').value);
}
}
// Listen for requests to run the simulation.
const runElement = document.getElementById("nav-project-runsimulation");
if(runElement){
runElement.addEventListener('click', runSimulation, false);
function runSimulation() {
//processInput(document.getElementById('inpFile').value);
// Pop up the processing modal.
$('#modalSpinner').modal('show')
runModelClick();
}
}
// Listen for requests to display a project summary.
const summaryElement = document.getElementById("nav-project-summary");
if(summaryElement){
summaryElement.addEventListener('click', displayProjectSummary, false);
function displayProjectSummary(){
modalProjectSummary();
}
}
// Listen for requests to display a report status
const reportstatusElement = document.getElementById("nav-report-status");
if(reportstatusElement){
reportstatusElement.addEventListener('click', displayReportStatus, false);
function displayReportStatus() {
modalReportStatus();
}
}
// Listen for requests to open an .inp file.
const inputElement = document.getElementById("nav-file-input");
if(inputElement){
inputElement.addEventListener('change', handleFiles, false);
function handleFiles() {
const fileList = this.files;
let fr = new FileReader();
fr.onload=function(){
if(fr.result){inpText =
processInput(fr.result)
}
}
fr.readAsText(fileList[0]);
}
}
// Listen for requests to change the language:
const languageElement = document.getElementById("navbarLanguageLink");
if(languageElement){
languageElement.addEventListener('click', displayLanguageModal, false);
function displayLanguageModal() {
$('#modalLanguage').modal('toggle');
}
}
// Listen for requests to save an .inp file.
const saveElement = document.getElementById("save");
if(saveElement){
saveElement.addEventListener('click', saveFile, false);
function saveFile() {
swmmjs.svg.save();
}
}
})
// Read the input file (text).
// Parse the data into memory.
// Run the model.
function processInput(inpText){
try
{
$('#modalSpinner').modal('show');
document.getElementById('inpFile').value = inpText;
swmmjs.loadModel(swmmjs.Module)
//swmmjs.run(swmmjs.Module);
$('#modalSpinner').modal('hide');
} catch (e) {
console.log('/input.inp creation failed');
$('#modalSpinner').modal('hide');
}
}
// representData draws the chart
// location is an svg where the chart will be drawn.
// theseSpecs is an object of class ChartSpecs
function representData(location, theseSpecs){
// Create the viewbox. This viewbox helps define the visible portions
// of the chart, but it also helps when making the chart responsive.
location.attr('viewBox', ` 0 0 ${theseSpecs.xScaleWidth + theseSpecs.chartBodyX + theseSpecs.textBuffer} ${theseSpecs.yScaleHeight + theseSpecs.textBuffer + theseSpecs.topMargin}`);
// Add groups to the svg for the body of the chart, the x axis, and the y axis.
body = location.append('g')
.attr('id', 'chartBody')
.attr('transform', `translate(${theseSpecs.chartBodyX}, ${theseSpecs.topMargin})`);
location.append('g')
.attr('id', 'yAxis')
.call(d3.axisLeft(theseSpecs.scaleY))
.attr('transform', `translate(${theseSpecs.chartBodyX}, ${theseSpecs.topMargin})`);
location.append('g')
.attr('id', 'xAxis')
.attr('transform', `translate(${theseSpecs.chartBodyX}, ${theseSpecs.yScaleHeight + theseSpecs.topMargin})`);
// Create the location for the line
body.append('path')
drawLine(theseSpecs, d3.curveLinear);
}
function drawLine(theseSpecs, curveType){
theseSpecs.setMax();
theseSpecs.setExtents();
// Create the line
let line = d3.line()
.x(function(d) { return theseSpecs.scaleX(d.cat); })
.y(function(d) { return theseSpecs.scaleY(d.y); })
.curve(curveType)
// Create a join on 'path' and the data
let join = d3.selectAll('#chartBody')
.append('path')
.attr('d', line(theseSpecs.data))
.attr('stroke', 'rgba(255, 125, 125, 1)')
.attr('stroke-width', '2px')
.style('fill', 'none')
// Update the y axis.
d3.selectAll('#yAxis')
.call(d3.axisLeft(theseSpecs.scaleY))
// Update the x axis.
d3.selectAll('#xAxis')
.call(
d3.axisBottom(theseSpecs.scaleX)
.ticks(5)
.tickFormat(d3.timeFormat('%Y-%m-%d %H:%M'))
)
.selectAll('text')
//split the date and time onto two lines for the xAxis
.call(function(t){
t.each(function(d){
let self = d3.select(this);
var s = self.text().split(' ');
self.text('');
self.append('tspan')
.attr('x', 0)
.attr('dy', 0)
.text(s[0]);
self.append('tspan')
.attr('x', '-2em')
.attr('dy', '1em')
.text(s[1]);
})
})
.style('text-anchor', 'end')
.attr('dx', '-0.8em')
.attr('dy', '0.15em')
.attr('transform', 'rotate(-65)');
}
const swmm_run = Module.cwrap('swmm_run', 'number', ['string', 'string', 'string']);
const swmm_transcribe = Module.cwrap('swmm_transcribe', 'number', ['string', 'string', 'string']);
/////////////////////////////////////////////////////////////////////////
// Network file functions
/////////////////////////////////////////////////////////////////////////
function wait(delay){
return new Promise((resolve) => setTimeout(resolve, delay));
}
function fetchRetry(url, delay, tries, fetchOptions = {}){
$.ajax({
url: url,
dataType: 'json',
success: function(json){
//alert('Loaded file: info.json')
$('#coverTitle').text(json[0].Title);
// For each entry in info[0].Files:
// -- add the Title to the dropdown select
// -- clicking on the select will:
// -- close the modal.
// -- load the selected file.
$('#coverDropdown').empty();
json[0].Files.forEach(function(value, i) {
$('#coverDropdown').append('<a class="dropdown-item" id="coverModel'+i+'">'+ value.Title +'</a>')
document.getElementById("coverModel"+i).addEventListener('click',
function () {
jQuery.get(value.FileLoc, function(contents){
processInput(contents);
})
$('#modalCover').modal('toggle');
},
false)
})
},
error: function(xhr, textStatus, errorThrown){
if(textStatus == 'timeout'){
this.tryCount++;
if(this.tryCount <= this.retryLimit){
//try again
$.ajax(this);
return;
}
return;
}
if(xhr.status == 500){
this.tryCount++;
if(this.tryCount <= this.retryLimit){
//try again
$.ajax(this);
return;
}
return;
}else {
alert('Cannot find data file: info.json')
}
},
tryCount: 0,
retryLimit: 5
})
}
/*function inpToJSON(){
let inpText = document.getElementById('inpFile').value;
try
{
FS.createPath('/', '/', true, true);
FS.ignorePermissions = true;
var f = FS.findObject('input.inp');
if (f) {
FS.unlink('input.inp');
}
FS.createDataFile('/', 'input.inp', inpText, true, true);
let JSONpointer = swmm_transcribe("/input.inp", "data/Example1x.rpt", "data/out.out");
return JSONpointer;
} catch (e) {
console.log('/input.inp creation failed');
// Remove the processing modal.
$('#modalSpinner').modal('hide')
} finally{
// Remove the processing modal.
$('#modalSpinner').modal('hide')
}
console.log('runran')
}*/
function runModelClick(){
// dataObj is an array of dataElement objects.
dataObj = [];
let inpText = null;
// Create a set of dataElements.
//Get the input file for parsing:
// Since we are running a model, it would be a good idea to
// write the current model objects into a string field,
// then send that string field to the executable.
// --1: Translate the model to a string vSia svg.save() in swmm.js
// --2: Modify svg.save to instead call a string creation function.
// This function can then be called by this click event as well, so no files
// need to be saved (though it would be a good idea to save a file before you run it, right?)
// --3: New function is called svg.dataToInpString().
// --4: To send the inpString to the swmm_run file, inpText can be used.
fetch('data/info.json')
.then(response => response.text())
.then((data) => {
inpText = swmmjs.svg.dataToInpString();
try
{
FS.createPath('/', '/', true, true);
FS.ignorePermissions = true;
var f = FS.findObject('input.inp');
if (f) {
FS.unlink('input.inp');
}
FS.createDataFile('/', 'input.inp', inpText, true, true);
async function processModel(){
swmm_run("/input.inp", "data/Example1x.rpt", "data/out.out");
return 1;
}
processModel().then(function (){
let rpt = intArrayToString(FS.findObject('data/Example1x.rpt').contents);
document.getElementById('rptFile').innerHTML = rpt;
modalReportStatus();
})
} catch (e) {
console.log('/input.inp creation failed');
// Remove the processing modal.
$('#modalSpinner').modal('hide')
} finally{
// Remove the processing modal.
$('#modalSpinner').modal('hide')
}
console.log('runran')
})
}
/*************************************
* Ripple effect for buttons
*/
var buttons = document.body.getElementsByClassName("ripplebutton");
Array.prototype.forEach.call(buttons, function (btn) {
btn.addEventListener('click', createRipple);
});
function createRipple(e) {
var children = this.getElementsByClassName('wave-ripple');
while(children.length > 0){
children[0].parentNode.removeChild(children[0]);
};
for(let i = 0; i < 4; i++){
var circle = document.createElement('div');
circle.style["position"] = 'absolute';
this.appendChild(circle);
var d = Math.max(this.clientWidth, this.clientHeight);
var eRect = this.getBoundingClientRect()
circle.style.width = circle.style.height = d*(10+2*i)/10 + 'px';
circle.style.left = e.clientX - eRect.left - d / 2 + 'px';
circle.style.top = e.clientY - eRect.top - d / 2 + 'px';
circle.classList.add('wave-ripple');
}
}