-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptimizer.py
More file actions
659 lines (583 loc) · 36.7 KB
/
Copy pathOptimizer.py
File metadata and controls
659 lines (583 loc) · 36.7 KB
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
"""
#TODO:
add a target pathogen and log reduction as control variables (optimize for log-inactivation)
optimze for UV-Dose
"""
import PQR_optimizer
import opt_config
from nicegui import ui
import asyncio
import numpy as np
class PQUVT:
def __init__(self):
# Initial Values can be changed later
self.minP = 40
self.maxP = 100
if opt_config.flowUnits == 'm3h':
self.minQ = 10
self.maxQ = 2000
self.flowUnits = '[m³/h]'
else:
self.minQ = 10*opt_config.m3h_2_gpm
self.maxQ = 2000*opt_config.m3h_2_gpm
self.flowUnits = '[gpm]'
self.pressureUnits = opt_config.dp_units
self.minUVT = 25
self.maxUVT = 99
self.targetRED = 40
self.redMargin = 3 # RED +/- margin of RED
self.D1Log = 18 # mJ/cm^2
pquvt = PQUVT()
# This is a temporary procedure and will be replaced
async def optimize():
table.options.rowData = []
opbutton.visible = False # Hide the "Optimize by PQR" button
opDPbutton.visible = False # Hide the "Optimize by dP" button
ui.colors(primary='#555') # Make all gray
ui.notify('Optimiation in progress...\nPlease wait for the calculation results to be finished', close_button='OK')
# Set flow unit multiplier for flow units according to the selection
unit_multiplier = {'m3h': 1, 'gpm': opt_config.m3h_2_gpm}[opt_config.flowUnits]
table.options.columnDefs[9].__setattr__('cellClass', ['', '']) # reset to default
for system in opt_config.valid_systems:
try:
# Iterations (by means of complexity)
iters = 5
max_iters = 8
REDOpt = 0 #Initial value
#redMargin = 5
while not ((pquvt.targetRED - pquvt.redMargin) <= REDOpt <= (pquvt.targetRED + pquvt.redMargin)) and (iters < max_iters):
# The flow untis are divided by multiplier, since the calculated flow units shall be in m3h and not in gpm
xOpt, REDOpt, PQROpt = PQR_optimizer.optimize(System=system,minP=pquvt.minP,maxP=pquvt.maxP,
minFlow=pquvt.minQ/unit_multiplier,maxFlow=pquvt.maxQ/unit_multiplier,
minUVT=pquvt.minUVT,maxUVT=pquvt.maxUVT,
iters = iters,targetRED=pquvt.targetRED,
redMargin=pquvt.redMargin,D1Log=pquvt.D1Log)
# Calculate the pressure drop at the selected flow rate xOpt[1]
dP = PQR_optimizer.HeadLoss(module=opt_config.systems[system],Flow=xOpt[1]/unit_multiplier,NLamps=opt_config.NLamps[system])
PQROpt /= unit_multiplier # In this case we want to return the flow in the P/Q in actual units.
iters += 1
if iters == max_iters:
raise Exception("not converging good enough")
"""
# Old and working:
table.options.rowData.append({
'system': system, 'pqr': round(PQROpt, 1), 'targetRED': round(REDOpt, 1),
'pMin': max(int(opt_config.Pmin_max(system)[0]),pquvt.minP), 'pMax': min(int(opt_config.Pmin_max(system)[1]),pquvt.maxP),
'qMin': max(int(opt_config.Qmin_max(system)[0])*unit_multiplier,pquvt.minQ), 'qMax': min(int(opt_config.Qmin_max(system)[1])*unit_multiplier,pquvt.maxQ),
'uvtMin': max(int(opt_config.UVTmin_max(system)[0]),pquvt.minUVT), 'uvtMax': min(int(opt_config.UVTmin_max(system)[1]),pquvt.maxUVT),
'dP': dP
})
"""
# Taking results from xOpt
table.options.rowData.append({
'system': system, 'pqr': round(PQROpt, 1), 'targetRED': round(REDOpt, 1),
'pMin': round(xOpt[0],1), # aka - optimum Power
'pMax': min(int(opt_config.Pmin_max(system)[1]), pquvt.maxP),
'qMin': round(xOpt[1],1), # aka optimum Flow Rate
'qMax': min(int(opt_config.Qmin_max(system)[1]) * unit_multiplier, pquvt.maxQ),
'uvtMin': max(int(opt_config.UVTmin_max(system)[0]),pquvt.minUVT),
'uvtMax': round(xOpt[2],1), # aka optimum UVT,
'dP': dP
})
await table.view.update()
await asyncio.sleep(1)
except: # no solution for the selected range
await asyncio.sleep(0)
table.options.rowData = sorted(table.options.rowData, key=lambda d: d['pqr'])
table.options.columnDefs[1].__setattr__('cellClass', ['text-lg', 'text-red-500']) # PQR
ui.colors() # Reset colors
ui.notify('Finished the optimization by PQR',close_button='OK',position='center')
opbutton.visible = True # Restore button visibility
opDPbutton.visible = True # Restore button visibility
if len(table.options.rowData)>0:
loadChartPQR()
RED_UVT_chartMin.visible = True
RED_UVT_chartMax.visible = True
else:
RED_UVT_chartMin.visible = False
RED_UVT_chartMax.visible = False
async def optimize_by_dP():
table.options.rowData = []
opbutton.visible = False # Hide the "Optimize by PQR" button
opDPbutton.visible = False # Hide the "Optimize by dP" button
ui.colors(primary='#555') # Make all gray
ui.notify('Optimiation in progress...\nPlease wait for the calculation results to be finished', close_button='OK')
# Set flow unit multiplier for flow units according to the selection
unit_multiplier = {'m3h': 1, 'gpm': opt_config.m3h_2_gpm}[opt_config.flowUnits]
#for system in opt_config.systems.keys():
table.options.columnDefs[1].__setattr__('cellClass', ['', '']) # reset to default
for system in opt_config.valid_systems:
try:
# Iterations (by means of complexity)
iters = 5
max_iters = 8
REDOpt = 0 #Initial value
#redMargin = 5
while not ((pquvt.targetRED - pquvt.redMargin) <= REDOpt <= (pquvt.targetRED + pquvt.redMargin)) and (iters < max_iters):
# The flow untis are divided by multiplier, since the calculated flow units shall be in m3h and not in gpm
xOpt, REDOpt, dPOpt = PQR_optimizer.optimize_by_dP(System=system,minP=pquvt.minP,maxP=pquvt.maxP,
minFlow=pquvt.minQ/unit_multiplier,maxFlow=pquvt.maxQ/unit_multiplier,
minUVT=pquvt.minUVT,maxUVT=pquvt.maxUVT,
iters = iters,targetRED=pquvt.targetRED,
redMargin=pquvt.redMargin,D1Log=pquvt.D1Log,target_dP=dP_trget_input.value)
# Calculate the pressure drop at the selected flow rate xOpt[1]
dP = PQR_optimizer.HeadLoss(module=opt_config.systems[system],Flow=xOpt[1]/unit_multiplier,NLamps=opt_config.NLamps[system])
PQROpt = xOpt[0]/xOpt[1] * opt_config.LampPower(system) * opt_config.NLamps[system]
#PQROpt = xOpt[0] / xOpt[1]
PQROpt /= unit_multiplier # In this case we want to return the flow in the P/Q in actual units.
iters += 1
if iters == max_iters:
raise Exception("not converging good enough")
table.options.rowData.append({
'system': system, 'pqr': round(PQROpt, 1), 'targetRED': round(REDOpt, 1),
'pMin': max(int(opt_config.Pmin_max(system)[0]),pquvt.minP), 'pMax': min(int(opt_config.Pmin_max(system)[1]),pquvt.maxP),
'qMin': max(int(opt_config.Qmin_max(system)[0])*unit_multiplier,pquvt.minQ), 'qMax': min(int(opt_config.Qmin_max(system)[1])*unit_multiplier,pquvt.maxQ),
'uvtMin': max(int(opt_config.UVTmin_max(system)[0]),pquvt.minUVT), 'uvtMax': min(int(opt_config.UVTmin_max(system)[1]),pquvt.maxUVT),
'dP': dPOpt
})
await table.view.update()
await asyncio.sleep(1)
except: # no solution for the selected range
await asyncio.sleep(0)
table.options.rowData = sorted(table.options.rowData, key=lambda d: d['dP'])
table.options.columnDefs[9].__setattr__('cellClass', ['text-lg', 'text-red-500']) # dP
ui.colors() # Reset colors
ui.notify('Finished the optimization by Pressure Loss',close_button='OK',position='center')
opbutton.visible = True # Restore button visibility
opDPbutton.visible = True # Restore button visibility
if len(table.options.rowData)>0:
loadChartPQR()
RED_UVT_chartMin.visible = True
RED_UVT_chartMax.visible = True
else:
RED_UVT_chartMin.visible = False
RED_UVT_chartMax.visible = False
def export_to_CSV(): # Export the data to csv
tableData = table.options.to_dict()['rowData']
columnDefs = [line['headerName'] for line in table.options.to_dict()['columnDefs']]
with open('best_reactors.csv', 'w') as f:
[f.write("%s," % (_).replace("²", "^2").replace("³", "^3").replace("Δ","dP")) for _ in columnDefs]
f.write("\n")
for tableLine in tableData:
for line in tableLine.values():
f.write("%s," % (line))
f.write("\n")
f.close()
def reset(): # Reset everything
pquvt = PQUVT()
selectAll()
table.options.rowData = []
minPower.__setattr__('value', pquvt.minP)
maxPower.__setattr__('value', pquvt.maxP)
minFlow.__setattr__('value', pquvt.minQ)
maxFlow.__setattr__('value', pquvt.maxQ)
minUVT.__setattr__('value', pquvt.minUVT)
maxUVT.__setattr__('value', pquvt.maxUVT)
targetRED_input.__setattr__('value',pquvt.targetRED)
redMargin_input.__setattr__('value',pquvt.redMargin)
D1Log_input.__setattr__('value',pquvt.D1Log)
RED_UVT_chartMin.visible = False
RED_UVT_chartMax.visible = False
loadChartPQR()
def clearAll():
for _ in opt_config.reactor_families:
switch[_].value = False
for _ in list(opt_config.systems.keys()):
subswitch[_].props('color=gray text-color=green')
def selectAll():
for _ in opt_config.reactor_families:
switch[_].value = True
for _ in list(opt_config.systems.keys()):
subswitch[_].props('color=primary text-color=white')
def validatedOnly():
for _ in opt_config.reactor_families:
switch[_].value = False
for _ in opt_config.validatedFamilies:
switch[_].value = True
# This is a specific requirement to "unvalidate" RZ-163-11 system
opt_config.valid_systems.remove('RZ-163_Reg-11')
subswitch['RZ-163_Reg-11'].props('color=gray text-color=green')
def add_remove_system(e):
# Filter-out the systems per family
if switch[e.sender.type].value == False:
opt_config.valid_systems = [system for system in opt_config.valid_systems
if system not in list(filter(lambda t: e.sender.type in t, opt_config.valid_systems))]
else:
opt_config.valid_systems.extend(list(filter(lambda t: e.sender.type in t, opt_config.systems.keys())))
for _ in list(opt_config.systems.keys()):
if _ in opt_config.valid_systems:
subswitch[_].props('color=primary text-color=white')
else:
subswitch[_].props('color=gray text-color=green')
def add_remove_subsystem(z):
# Add or Remove the subsystem
selected_subsystem = z.sender.model[0]+'-'+z.sender.model[1]
if selected_subsystem in opt_config.valid_systems: # Disable sybsystem
opt_config.valid_systems.remove(selected_subsystem)
z.sender.props('color=gray text-color=green')
if not list(filter(lambda t: z.sender.model[0] in t, opt_config.valid_systems)): # If list is empty
switch[z.sender.model[0]].value = False # Switch-off the entire family
else: # Enable sybsystem
if switch[z.sender.model[0]].value == False: # If the family is off
switch[z.sender.model[0]].value = True
for _ in list(filter(lambda t: z.sender.model[0] in t, opt_config.systems.keys())):
opt_config.valid_systems.remove(_)
subswitch[_].props('color=gray text-color=green')
opt_config.valid_systems.append(selected_subsystem)
subswitch[selected_subsystem].props('color=primary text-color=white')
else:
opt_config.valid_systems.append(selected_subsystem)
z.sender.props('color=primary text-color=white')
def power(minmax):
# Resolve the minimum-maximum for Power
if minmax == 'min':
if minPower.value > maxPower.value:
maxPower.__setattr__('value', minPower.value)
if minmax == 'max':
if maxPower.value < minPower.value:
minPower.__setattr__('value', maxPower.value)
def flow(minmax):
# Resolve the minimum-maximum for Flow
if minmax == 'min':
if minFlow.value > maxFlow.value:
maxFlow.__setattr__('value', minFlow.value)
if minmax == 'max':
if maxFlow.value < minFlow.value:
minFlow.__setattr__('value', maxFlow.value)
def uvt(minmax):
# Resolve the minimum-maximum for UVT254
if minmax == 'min':
if minUVT.value > maxUVT.value:
maxUVT.__setattr__('value', minUVT.value)
if minmax == 'max':
if maxUVT.value < minUVT.value:
minUVT.__setattr__('value', maxUVT.value)
def loadChartRED(minmax):
# The function plots RED = f(UVT) at minimum or maximum flow rate
# Set flow unit multiplier for flow units according to the selection:
unit_multiplier = {'m3h': 1, 'gpm': opt_config.m3h_2_gpm}[opt_config.flowUnits]
tableData = table.options.to_dict()['rowData']
chart.options['chart']['type'] = 'scatter'
chart.options['legend'] = {'borderWidth': 1, 'backgroundColor': 'white', 'x': 70, 'y': 60, 'shadow': True,
'layout': 'vertical', 'align': 'left', 'verticalAlign': 'top', 'floating': True}
chart.options['xAxis'] = {'title': {'text': 'UVT [%-1cm]'}}
chart.options['yAxis'] = {'title': {'text': 'RED [mJ/cm²]'}}
chart.options['title'] = {'text': 'RED vs. UVT'}
if minmax == 'min':
chart.options['subtitle'] = {'text': 'Top 5 UV-Systems at minimum common Optimum Flow'}
elif minmax =='max':
chart.options['subtitle'] = {'text': 'Top 5 UV-Systems at minimum common Upper Limit Flow'}
chart.options['series'] = [] # Initialize Empty
# Add all the systems into the list
systems = [tableLine['system'] for tableLine in tableData][:5]
UVTs = np.round(np.linspace(70, 98), 1)
# Units have to be in m3h, not in gpm
#minFlow = max([[x for x in tableData[:5] if x['system'] == system][0]['qMin']/unit_multiplier for system in systems])
minFlow = min([[x for x in tableData[:5] if x['system'] == system][0]['qMin'] / unit_multiplier for system in systems])
maxFlow = min([[x for x in tableData[:5] if x['system'] == system][0]['qMax']/unit_multiplier for system in systems])
for system in systems:
if minmax == 'min': #Optimum
qFlow = minFlow
elif minmax =='max':
qFlow = maxFlow
REDs = [PQR_optimizer.RED(module=opt_config.systems[system], P=100, Flow=qFlow,
UVT=uvt, UVT215=uvt, Status=100, D1Log=18, NLamps=opt_config.NLamps[system])
for uvt in UVTs]
if opt_config.flowUnits == 'm3h':
chart.options['series'].append(
{'name': system + ' at ' + str(int(qFlow*unit_multiplier)) + '[m³/h]', 'data': [list(_) for _ in zip(UVTs, REDs)]})
elif opt_config.flowUnits == 'gpm':
chart.options['series'].append(
{'name': system + ' at ' + str(int(qFlow*unit_multiplier)) + '[gpm]', 'data': [list(_) for _ in zip(UVTs, REDs)]})
def loadChartPQR():
chart.options['series'] = [] # Initialize Empty
tableData = table.options.to_dict()['rowData']
PQRs = [tableLine['pqr'] for tableLine in tableData]
chart.options['series'].append({'name': 'Optimized PQR', 'data': PQRs})
chart.options['chart'] = {'type': 'column', 'height': 270, 'zoomType': 'y'}
chart.options['title'] = {'text': 'Optimized PQR'}
chart.options['legend'] = {'borderWidth': 1, 'backgroundColor': 'white', 'x': 0, 'y': 0, 'shadow': True,
'layout': 'vertical', 'align': 'right', 'verticalAlign': 'top', 'floating': True}
chart.options['subtitle'] = {'text': 'Calculated Values inside the selected range'}
chart.options['xAxis'] = {'title': {'text': 'UV-Systems'},
'categories': [tableLine['system'] for tableLine in tableData]}
if opt_config.flowUnits == 'm3h':
chart.options['yAxis'] = {'title': {'text': 'P/Q [W/(m³/h)]'}}
elif opt_config.flowUnits == 'gpm':
chart.options['yAxis'] = {'title': {'text': 'P/Q [W/(gpm)]'}}
# print(PQR_optimizer.specificPQR(system=system,P=100,Status=100,UVT254=maxUVT,targetRED=40))
def checkPower(P):
# helper function for numeric input of Power (min/max)
if P.value < PQUVT().minP:
minP_number.value = PQUVT().minP
if P.value > PQUVT().maxP:
maxP_number.value = PQUVT().maxP
def checkFlow(Q):
# helper function for numeric input of Flow (min/max)
if Q.value < PQUVT().minQ:
minQ_number.value = PQUVT().minQ
if Q.value > PQUVT().maxQ:
maxQ_number.value = PQUVT().maxQ
def checkUVT(UVT):
# helper function for numeric input of UVT (min/max)
if UVT.value < PQUVT().minUVT:
minUVT_number.value = PQUVT().minUVT
if UVT.value > PQUVT().maxUVT:
maxUVT_number.value = PQUVT().maxUVT
def changeFlowUnits():
# Change the flow units whenever the button is pressed
if pquvt.flowUnits == '[m³/h]':
pquvt.minQ = round(pquvt.minQ * opt_config.m3h_2_gpm,0)
pquvt.maxQ = round(pquvt.maxQ * opt_config.m3h_2_gpm,0)
pquvt.flowUnits = '[gpm]'
opt_config.flowUnits = 'gpm'
# Set the column definitions to "gpm":
table.options.columnDefs[1]['headerName'] = 'PQR [W/gpm]'
table.options.columnDefs[5]['headerName'] = 'Qmin [gpm]'
table.options.columnDefs[6]['headerName'] = 'Qmax [gpm]'
"""
table.options['columnDefs'] = [
{'headerName': 'System Type', 'field': 'system'},
{'headerName': 'PQR [W/gpm]', 'field': 'pqr'},
{'headerName': 'Effective RED [mJ/cm²]', 'field': 'targetRED'},
{'headerName': 'Pmin [%]', 'field': 'pMin'},
{'headerName': 'Pmax [%]', 'field': 'pMax'},
{'headerName': 'Qmin [gpm]', 'field': 'qMin'},
{'headerName': 'Qmax [gpm]', 'field': 'qMax'},
{'headerName': 'UVT254min [%-1cm]', 'field': 'uvtMin'},
{'headerName': 'UVT254max [%-1cm]', 'field': 'uvtMax'},
{'headerName': 'ΔP [mH₂O]', 'field': 'dP'}
]
"""
# Convert table flow and PQR to gpm
for row in range(len(table.options.rowData)):
table.options.rowData[row]['pqr'] = round(table.options.rowData[row]['pqr'] / opt_config.m3h_2_gpm, 1)
table.options.rowData[row]['qMin'] = round(table.options.rowData[row]['qMin'] * opt_config.m3h_2_gpm, 0)
table.options.rowData[row]['qMax'] = round(table.options.rowData[row]['qMax'] * opt_config.m3h_2_gpm, 0)
elif pquvt.flowUnits == '[gpm]':
pquvt.minQ = round(pquvt.minQ / opt_config.m3h_2_gpm,0)
pquvt.maxQ = round(pquvt.maxQ / opt_config.m3h_2_gpm,0)
pquvt.flowUnits = '[m³/h]'
opt_config.flowUnits = 'm3h'
# Set the column definitions to "m³/h":
table.options.columnDefs[1]['headerName'] = 'PQR [W/(m³/h)]'
table.options.columnDefs[5]['headerName'] = 'Qmin [m³/h]'
table.options.columnDefs[6]['headerName'] = 'Qmax [m³/h]'
"""
table.options['columnDefs'] = [
{'headerName': 'System Type', 'field': 'system'},
{'headerName': 'PQR [W/(m³/h)]', 'field': 'pqr'},
{'headerName': 'Effective RED [mJ/cm²]', 'field': 'targetRED'},
{'headerName': 'Pmin [%]', 'field': 'pMin'},
{'headerName': 'Pmax [%]', 'field': 'pMax'},
{'headerName': 'Qmin [m³/h]', 'field': 'qMin'},
{'headerName': 'Qmax [m³/h]', 'field': 'qMax'},
{'headerName': 'UVT254min [%-1cm]', 'field': 'uvtMin'},
{'headerName': 'UVT254max [%-1cm]', 'field': 'uvtMax'},
{'headerName': 'ΔP [mH₂O]', 'field': 'dP'}
]
"""
# Convert table flow and PQR to m3h
for row in range(len(table.options.rowData)):
table.options.rowData[row]['pqr'] = round(table.options.rowData[row]['pqr'] * opt_config.m3h_2_gpm,1)
table.options.rowData[row]['qMin'] = round(table.options.rowData[row]['qMin'] / opt_config.m3h_2_gpm,0)
table.options.rowData[row]['qMax'] = round(table.options.rowData[row]['qMax'] / opt_config.m3h_2_gpm,0)
if len(table.options.rowData)>0: loadChartPQR()
maxFlow.view.__setattr__('max', round(PQUVT().maxQ, 0))
maxFlow.view.__setattr__('min', round(PQUVT().minQ, 0))
minFlow.view.__setattr__('max', round(PQUVT().maxQ, 0))
minFlow.view.__setattr__('min', round(PQUVT().minQ, 0))
def changeDPUnits():
# Change the Pressure Drop units whenever the button is pressed
changeSequence = {'m_H₂O':'PSI','PSI':'in_H₂O','in_H₂O':'m_H₂O'}
from_Unit = pquvt.pressureUnits
dP_trget_input.value *= opt_config.P_coeff[from_Unit]
pquvt.pressureUnits = changeSequence[opt_config.dp_units]
opt_config.dp_units = pquvt.pressureUnits
Punit = 'ΔP ['+ pquvt.pressureUnits.replace('_','') +']'
table.options.columnDefs[9]['headerName']=Punit
# Convert table dP data units
for row in range(len(table.options.rowData)):
table.options.rowData[row]['dP'] = round(table.options.rowData[row]['dP'] * opt_config.P_coeff[from_Unit], 2)
#%% --- Main Frame ---
ui.colors()
# Help Dialog:
with ui.dialog() as help_dialog, ui.card():
ui.markdown('### PQR Optimization Tool for UV-Systems\n'
'Please apply to [Atlantium Technologies](https://atlantium.com/) website for more information.')
ui.html('<p>This tool is intended to provide a global parametric optimization in terms of <strong>PQR</strong>:<br>'
'<strong>P</strong>ower-to-Flow (<strong>Q</strong>) <strong>R</strong>atio, '
'which is similar to the <strong>Cost-Per-Treated-Volume</strong> for the Atlantium UV-Reactors Family</p>')
ui.html('<p><u>Steps to work with the tool:</u></p>'
'<p><strong>1:</strong> Choose the parametric range in terms of minimum/maximum for Power in [%], Flow Rate in [m³/h] or [gpm] and UVT254 in [%-1cm].<br>'
'Push the [m³/h] <u>or</u> [gpm] button to change the units<br>'
'<strong>2:</strong> Choose the target UV-Dose, D1-Log inactivation dose and algorithmic accuracy tolerance.<br>'
'<strong>3:</strong> Select the relevant UV-reactors by family and/or by specific branch. One may filter out the validated systems only.<br>'
'<strong>4:</strong> Push the "Optimize by PQR" button to start global search process.<br>'
'<strong>5:</strong> The algorithm performs a "simplicial homology global optimization" search for an optimal solution inside the selected range, so that '
'the cost-per-treated volume for the selected reactor, in terms of PQR value, will provide the specified UV-Dose within the set tolerance. '
'Note that every UV-reactor type has a specific operating parametric range, so that the algorithm will search inside these limits only.<br>'
'Some of the reactors will not have a solution for the selected target dose and/or accuracy tolerance<br>'
'<strong>6:</strong> As soon as the algorithm finishes the optimization, it will populate the ranged table with the most '
'relevant UV-reactor types at the top of the table. You may find the relevant bar chart of this range at the top-right of the calculator window.<br>'
'<strong>7:</strong> One may take a look at the additional charts/graphs for the 5 best performing UV-systems and export the table in CSV format.<br>'
'Note, that the estimated Pressure Drop is calculated for the optimum flow rate inside the selected range</p>')
ui.button('Close and back to the PQR tool', on_click=help_dialog.close)
# Main Window:
with ui.row().classes('no-wrap'):
with ui.column().classes('no-wrap'):
with ui.row().classes('flex items-stretch no-wrap'):
with ui.card().classes('max-w-full mr-2 no-wrap'):
ui.label('Control Variables:').classes('text-h7 underline')
with ui.row().classes('max-w-full space-x-2 no-wrap'): #Power
# P_check = ui.checkbox('Power:',value=True).classes('max-w-full w-20')
with ui.column().classes('max-w-full -space-y-5 w-52 no-wrap'):
minPower = ui.slider(min=pquvt.minP, max=pquvt.maxP, value=pquvt.minP,on_change=lambda: power('min')).bind_value(pquvt,'minP').props('label')
with ui.row() as row:
ui.label('Minimum Power:')
ui.label().bind_text_from(minPower, 'value').classes('font-black')
ui.label('[%]')
with ui.column().classes('max-w-full -space-y-5 w-52 no-wrap'):
maxPower = ui.slider(min=pquvt.minP, max=pquvt.maxP, value=pquvt.maxP,on_change=lambda: power('max')).bind_value(pquvt,'maxP').props('label')
with ui.row() as row:
ui.label('Maximum Power:')
ui.label().bind_text_from(maxPower, 'value').classes('font-black')
ui.label('[%]')
minP_number = ui.number(label='Pmin', format='%.0f', on_change=lambda x: checkPower(x)).classes(
'font-black w-14 h-1').bind_value(pquvt,'minP')
maxP_number = ui.number(label='Pmax', format='%.0f', on_change=lambda x: checkPower(x)).classes(
'font-black w-14 h-1').bind_value(pquvt,'maxP')
with ui.row().classes('max-w-full space-x-2 no-wrap'): # Flow
# Q_check = ui.checkbox('Flow:',value=True).classes('max-w-full w-20')
with ui.column().classes('max-w-full -space-y-5 w-52 no-wrap'):
minFlow = ui.slider(min=pquvt.minQ, max=pquvt.maxQ, step=10, value=pquvt.minQ, on_change=lambda: flow('min')).bind_value(pquvt,'minQ').props('label')
with ui.row().classes('-space-x-3 w-full justify-evenly'):
ui.label('Minimum Flow:')
ui.label().bind_text_from(minFlow, 'value').classes('font-black')
#ui.label('[m³/h]')
minFlowUnits = ui.button('[m³/h]', on_click = changeFlowUnits).props('outline size=xs').bind_text_from(pquvt,'flowUnits')
with ui.column().classes('max-w-full -space-y-5 w-52 no-wrap'):
maxFlow = ui.slider(min=pquvt.minQ, max=pquvt.maxQ, step=10, value=pquvt.maxQ, on_change=lambda: flow('max')).bind_value(pquvt,'maxQ').props('label')
with ui.row().classes('-space-x-3 w-full justify-evenly'):
ui.label('Maximum Flow:')
ui.label().bind_text_from(maxFlow, 'value').classes('font-black')
#ui.label('[m³/h]')
maxFlowUnits = ui.button('[m³/h]', on_click=changeFlowUnits).props('outline size=xs').bind_text_from(pquvt,'flowUnits')
minQ_number = ui.number(label='minFlow', format='%.0f', on_change=lambda x: checkFlow(x)).classes(
'font-black w-14 h-1').bind_value(pquvt,'minQ')
maxQ_number = ui.number(label='maxFlow', format='%.0f', on_change=lambda x: checkFlow(x)).classes(
'font-black w-14 h-1').bind_value(pquvt,'maxQ')
with ui.row().classes('max-w-full space-x-2 no-wrap'): # UVT
# UVT_check = ui.checkbox('UVT:',value=True).classes('max-w-full w-20')
with ui.column().classes('max-w-full -space-y-5 w-52'):
minUVT = ui.slider(min=pquvt.minUVT, max=pquvt.maxUVT, value=pquvt.minUVT,on_change=lambda: uvt('min')).bind_value(pquvt,'minUVT').props('label')
with ui.row() as row:
ui.label('Minimum UVT:')
ui.label().bind_text_from(minUVT, 'value').classes('font-black')
ui.label('[%-1cm]')
with ui.column().classes('max-w-full -space-y-5 w-52 no-wrap'):
maxUVT = ui.slider(min=pquvt.minUVT, max=pquvt.maxUVT, value=pquvt.maxUVT,on_change=lambda: uvt('max')).bind_value(pquvt,'maxUVT').props('label')
with ui.row() as row:
ui.label('Maximum UVT:')
ui.label().bind_text_from(maxUVT, 'value').classes('font-black')
ui.label('[%-1cm]')
minUVT_number = ui.number(label='minUVT', format='%.0f', on_change=lambda x: checkUVT(x)).classes(
'font-black w-14 h-1').bind_value(pquvt,'minUVT')
maxUVT_number = ui.number(label='maxUVT', format='%.0f', on_change=lambda x: checkUVT(x)).classes(
'font-black w-14 h-1').bind_value(pquvt,'maxUVT')
with ui.row().classes('w-full justify-evenly no-wrap'):
with ui.row().classes('w-full justify-evenly no-wrap'):
targetRED_input = ui.number(label = 'Target RED [mJ/cm²]',value=pquvt.targetRED,
format='%.1f',placeholder='Target Dose?').bind_value_to(pquvt,'targetRED').classes('space-x-5 w-32')
redMargin_input = ui.number(label = 'RED margin [±mJ/cm²]',value=pquvt.redMargin,
format='%.1f',placeholder='Dose Margin?').bind_value_to(pquvt,'redMargin').classes('space-x-5 w-32')
D1Log_input = ui.number(label='1-Log Dose [±mJ/cm²]', value=pquvt.D1Log,
format='%.1f', placeholder='D-1Log?').bind_value_to(pquvt,'D1Log').classes('space-x-5 w-32')
with ui.column().classes('-space-y-5 -mt-4'): # Pressure Drop control
dP_Units = ui.button('[' + opt_config.dp_units + ']', on_click=changeDPUnits).props(
'outline size=xs').bind_text_from(pquvt,'pressureUnits')
dP_trget_input = ui.number(label = 'max ΔP',value=0.5,
format='%.2f',placeholder='Max ΔP Limit').classes('space-x-5 w-16')
with ui.card().classes('no-wrap'):
chart = ui.chart({
'title': {'text': 'Run PQR Optimization to make the chart available'},
'chart': {'height': 270, 'zoomType': 'y'},
'exporting':{'enabled':False},
'credits': {'enabled': False}
}).classes('h-64')
with ui.row():
PQR_chart = ui.button('PQR chart', on_click = loadChartPQR).props('size=sm')
RED_UVT_chartMin = ui.button('RED vs UVT at Q_opt common minimum', on_click = lambda: loadChartRED('min')).props('size=sm')
RED_UVT_chartMax = ui.button('RED vs UVT at Q_max common upper limit', on_click = lambda: loadChartRED('max')).props('size=sm')
RED_UVT_chartMin.visible = False
RED_UVT_chartMax.visible = False
with ui.card().classes('bg-yellow-300 w-full h-64 no-wrap'):
table = ui.table({
'columnDefs': [
{'headerName': 'System Type', 'field': 'system'},
{'headerName': 'PQR [W/(m³/h)]', 'field': 'pqr'},
{'headerName': 'Effective RED [mJ/cm²]', 'field': 'targetRED'},
{'headerName': 'Popt [%]', 'field': 'pMin'}, #Optimum
{'headerName': 'Pmax [%]', 'field': 'pMax'},
{'headerName': 'Qopt [m³/h]', 'field': 'qMin'}, #Optimum
{'headerName': 'Qmax [m³/h]', 'field': 'qMax'},
{'headerName': 'UVT254min [%-1cm]', 'field': 'uvtMin'},
{'headerName': 'UVT254opt [%-1cm]', 'field': 'uvtMax'}, #Optimum
{'headerName': 'ΔP [mH2O]', 'field': 'dP'}
],
'rowData': [],
})
# Set of auxillary attributes for the resaulting table:
#table.options.columnDefs[1].__setattr__('editable',True)
#table.options.columnDefs[1].__setattr__('cellClass', ['text-lg','text-red-500']) # PQR
for column in range(len(table.options.columnDefs)):
table.options.columnDefs[column].__setattr__('resizable', False)
table.options.columnDefs[column].__setattr__('sortable', True)
table.options.__setattr__('suppressHorizontalScroll', True)
table.options.__setattr__('suppressMovableColumns', True)
table.options.columnDefs[3].__setattr__('maxWidth', 80) # Pmin
table.options.columnDefs[4].__setattr__('maxWidth', 80) # Pmax
table.options.columnDefs[5].__setattr__('maxWidth', 100) # Qmin
table.options.columnDefs[6].__setattr__('maxWidth', 100) # Qmax
table.options.columnDefs[0].__setattr__('filter','agTextColumnFilter') # System
table.options.columnDefs[1].__setattr__('filter', 'agNumberColumnFilter') # PQR
table.options.columnDefs[9].__setattr__('filter', 'agNumberColumnFilter') # dP
with ui.card().classes('bg-yellow-300 w-full no-wrap'):
with ui.row().classes('w-full justify-between'):
with ui.row().classes('relative left-0'):
opbutton = ui.button('Optimize by PQR', on_click=optimize)
opDPbutton = ui.button('Optimize by ΔP', on_click=optimize_by_dP)
with ui.row().classes('relative right-0'):
reset = ui.button('Reset All', on_click=reset)
export = ui.button('Export to csv', on_click=export_to_CSV)
help = ui.button(on_click=help_dialog.open).props('icon=help')
# Switches
switch = {}
subswitch = {}
with ui.card().classes('max-w-full w-64 -space-y-1 no-wrap'):
ui.image('https://atlantium.com/wp-content/uploads/2020/03/Atlantium_Logo_Final_white3.png').style('width:200px').classes('no-wrap')
ui.label('Specific Reactor Types:').classes('text-h8 underline no-wrap')
validatedOnly = ui.button('Choose Validated Models Only', on_click=validatedOnly).props(
'rounded align=around icon=directions size=sm').classes('no-wrap')
with ui.column().classes('-space-y-6 no-wrap'):
for reactor_type in opt_config.reactor_families:
with ui.row().classes('w-full justify-between no-wrap'):
# Main switch
switch[reactor_type]=ui.switch(reactor_type, value=True, on_change=lambda e: add_remove_system(e)).classes('no-wrap')
setattr(switch[reactor_type], 'type', reactor_type)
# Subsystem switches
with ui.row().classes('pt-3 -space-x-3 no-wrap'):
for sub_type in opt_config.reactor_subtypes(reactor_type):
subswitch[reactor_type+'-'+sub_type] = ui.button(
sub_type, on_click=lambda z: add_remove_subsystem(z)
).props('push rounded dense size=xs').classes('no-wrap')
setattr(subswitch[reactor_type+'-'+sub_type], 'model', (reactor_type,sub_type))
ui.html('<br><br>').classes('no-wrap')
with ui.row().classes('w-full justify-between no-wrap'):
clearAll = ui.button('Clear', on_click=clearAll).props('size=sm icon=camera align=around').classes('no-wrap')
enableAll = ui.button('Select All', on_click=selectAll).props('size=sm icon=my_location align=around').classes('no-wrap')
ui.image('https://atlantium.com/wp-content/uploads/2022/06/HOD-UV-A_Technology_Overview-540x272.jpg').style('height:78px').classes('no-wrap')
ui.html('<p>Atlantium Technologies, Mike Kertser, 2022, <strong>v1.11</strong></p>').classes('no-wrap')
if __name__ == "__main__":
#ui.run(title='Optimizer', favicon='favicon.ico', host='127.0.0.1', reload=False, show=True)
ui.run(title='Optimizer', reload=True, show=True)