-
Notifications
You must be signed in to change notification settings - Fork 6
/
su2gui.py
1608 lines (1328 loc) · 54.8 KB
/
su2gui.py
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
r"""
The SU2 Graphical User Interface.
"""
import os
import argparse
from base64 import b64encode
from trame.app import get_server
from trame.app.file_upload import ClientFile
from trame.widgets import markdown
from trame.ui.vuetify import SinglePageWithDrawerLayout
#from trame.ui.vuetify import SinglePageLayout
from trame.widgets import vuetify, vtk as vtk_widgets
from trame.widgets import trame
#import itertools
from datetime import date
# Import json setup for writing the config file in json and cfg file format.
from su2_json import *
# Export su2 mesh file.
from su2_io import save_su2mesh, save_json_cfg_file
#
from vtk_helper import *
#
from cases import update_manage_case_dialog_card, manage_case_dialog_card, case_name_dialog_card, case_args
#
# Definition of ui_card and the server.
from uicard import ui_card, server
# Logging funtions
from logger import log, clear_logs , Error_dialog_card, Warn_dialog_card, logs_tab
from config import *
import vtk
# vtm reader
#from paraview.vtk.vtkIOXML import vtkXMLMultiBlockDataReader
#from vtkmodules.web.utils import mesh as vtk_mesh
from vtkmodules.vtkCommonDataModel import vtkDataObject
#from vtkmodules.vtkFiltersCore import vtkContourFilter #noqa
from vtkmodules.vtkRenderingAnnotation import vtkAxesActor
from vtkmodules.vtkCommonTransforms import vtkTransform
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkRenderingAnnotation import vtkCubeAxesActor, vtkScalarBarActor
from vtkmodules.vtkInteractionWidgets import vtkOrientationMarkerWidget, vtkScalarBarWidget
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkRenderer,
vtkRenderWindow,
vtkRenderWindowInteractor,
)
from vtkmodules.vtkCommonDataModel import (
VTK_HEXAHEDRON,
VTK_LINE,
VTK_POLYGON,
VTK_QUAD,
VTK_TETRA,
VTK_TRIANGLE,
VTK_PYRAMID,
VTK_WEDGE,
VTK_TRIANGLE_STRIP,
VTK_VERTEX,
vtkUnstructuredGrid)
# Required for interactor initialization
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch # noqa
# Required for rendering initialization, not necessary for
# local rendering, but doesn't hurt to include it
import vtkmodules.vtkRenderingOpenGL2 # noqa
#############################################################################
# Gittree menu #
# We have defined each of the tabs in its own module and we import it here. #
# We then call the card in the SinglePageWithDrawerLayout() function. #
#############################################################################
# gittree menu : import mesh tab #
from mesh import *
# gittree menu : import physics tab #
from physics import *
# gittree menu : import materials tab #
from materials import *
# gittree menu : import numerics tab #
from numerics import *
# gittree menu : import boundaries tab #
from boundaries import *
# gittree menu : import solver tab #
from solver import *
# gittree menu : import initialization tab #
from initialization import *
# gittree menu : import file I/O tab #
from fileio import *
#############################################################################
# -----------------------------------------------------------------------------
# Trame setup
# -----------------------------------------------------------------------------
state, ctrl = server.state, server.controller
from pipeline import PipelineManager
from pathlib import Path
BASE = Path(__file__).parent
from trame.assets.local import LocalFileManager
clear_logs()
log("info" , f"""
****************************************
Base path = {BASE}
****************************************
"""
)
state.filename_cfg_export = "config_new.cfg"
state.filename_json_export = "config_new.json"
# for server side, we need to use a file manager
local_file_manager = LocalFileManager(__file__)
local_file_manager.url("collapsed", BASE / "icons/chevron-up.svg")
local_file_manager.url("collapsible", BASE / "icons/chevron-down.svg")
local_file_manager.url("su2logo", BASE / "img/logoSU2small.png")
local_file_manager.url("favicon", BASE / "img/favicon.ico")
log("info", f"""
****************************************
local_file_manager = {local_file_manager}
local_file_manager = {type(local_file_manager)}
local_file_manager = {type(local_file_manager.assets)}
local_file_manager = {dir(local_file_manager.assets.items())}
local_file_manager = {local_file_manager.assets.keys()}
****************************************
"""
)
# matplotlib history
state.show_dialog = False
# TODO FIXME update from user input / cfg file
state.history_filename = 'history.csv'
state.fileio_restart_filename = 'restart'
state.monitorLinesVisibility = []
state.monitorLinesNames = []
state.monitorLinesRange = []
# -----------------------------------------------------------------------------
# keep updating the graph (real-time update with asynchronous io)
state.keep_updating = True
state.countdown = True
# -----------------------------------------------------------------------------
# SU2 setup
# -----------------------------------------------------------------------------
# global iteration number while running a case
#state.global_iter = -1
state.initialize=-1
# number of dimensions of the mesh (2 or 3)
state.nDim = 2
# which boundary is selected?
state.selectedBoundaryName="none"
state.selectedBoundaryIndex = 0
# Boundary Condition Dictionary List
# This is the internal list of dictionaries for the boundary conditions
# This will be converted and written as MARKER info to .json and .cfg files.
state.BCDictList = [{"bcName": "main_wall",
"bcType":"Wall",
"bc_subtype":"Temperature",
"json":"MARKER_ISOTHERMAL",
"bc_velocity_magnitude":0.0,
"bc_temperature":300.0,
"bc_pressure":0,
"bc_density":0.0,
"bc_massflow":1.0,
"bc_velocity_normal":[1,0,0],
"bc_heatflux":0.0,
"bc_heattransfer":[1000.0,300.0],
}]
# disable the export file button
state.export_disabled=True
# (solver.py) disable the solve button
state.su2_solve_disabled=False
# solver settings
# current solver icon
state.solver_icon = "mdi-play-circle"
# current running state
state.solver_running = False
# the imported mesh block and boundary blocks
# must be state or else it cannot be an argument to click
state.su2_meshfile="mesh_out.su2"
# list of all the mesh actors (boundaries)
state.selectedBoundary = 0
mesh_actor_list = [{"id":0,"name":"internal","mesh":mesh_actor}]
# vtk named colors
colors = vtkNamedColors()
mesh_actor.SetMapper(mesh_mapper)
mesh_actor.SetObjectName("initial_square")
# Mesh: Setup default representation to surface
mesh_actor.GetProperty().SetRepresentationToSurface()
mesh_actor.GetProperty().SetPointSize(1)
# show the edges
mesh_actor.GetProperty().EdgeVisibilityOn()
# color is based on field values
renderer.AddActor(mesh_actor)
###################################
# ##### gradient background ##### #
###################################
# bottom: white
renderer.SetBackground(1., 1., 1.)
# top: light blue
renderer.SetBackground2(0.6, 0.8, 1.0)
# activate gradient background
renderer.GradientBackgroundOn()
###################################
# Extract Array/Field information
datasetArrays = []
name = "Solid"
ArrayObject = vtk.vtkFloatArray()
ArrayObject.SetName(name)
# all components are scalars, no vectors for velocity
ArrayObject.SetNumberOfComponents(1)
# how many elements do we have?
nElems = 1
ArrayObject.SetNumberOfValues(nElems)
nPoints = 4
ArrayObject.SetNumberOfTuples(4)
# Nijso: TODO FIXME very slow!
# this is the color of the initial square
#for i in range(nElems):
for i in range(nPoints):
#ArrayObject.SetValue(i,1.0)
ArrayObject.SetValue(i,1.0)
grid.GetPointData().AddArray(ArrayObject)
# as soon as we add the array, it is being used for coloring.
datasetArrays.append(
{
"text": name,
"value": 0,
"range": [1.0,1.0],
"type": vtkDataObject.FIELD_ASSOCIATION_POINTS,
}
)
default_array = datasetArrays[0]
default_min, default_max = default_array.get("range")
state.dataset_arrays= datasetArrays
log("info", f"dataset_arrays = {state.dataset_arrays}")
mesh_mapper.SetInputData(grid)
mesh_mapper.SelectColorArray(default_array.get("text"))
mesh_mapper.GetLookupTable().SetRange(default_min, default_max)
mesh_mapper.SetScalarModeToUsePointFieldData()
mesh_mapper.SetScalarVisibility(True)
mesh_mapper.SetUseLookupTableScalarRange(True)
# cube axes (bounded with length scales)
cube_axes = MakeCubeAxesActor()
renderer.AddActor(cube_axes)
# scalar bar
scalar_bar = MakeScalarBarActor()
scalar_bar_widget =MakeScalarBarWidget(scalar_bar)
# coordinate axes
axes1 = MakeAxesActor()
coord_axes = MakeOrientationMarkerWidget(axes1)
renderer.ResetCamera()
# -----------------------------------------------------------------------------
# Constants
# -----------------------------------------------------------------------------
pipeline = PipelineManager(state, "git_tree")
# main menu, note that only these are collapsible
# These are head nodes. boundary for instance are all subnodes sharing one head node
# note that subui points to a submenu. We can set it to an existing submenu, or point to "none"
# 1
id_root = pipeline.add_node( name="Mesh",
subui="none", visible=1, color="#9C27B0", actions=["collapsible"])
# 2
id_physics = pipeline.add_node(parent=id_root, name="Physics",
subui="none", visible=1, color="#42A5F5", actions=["collapsible"])
# 3
id_materials = pipeline.add_node(parent=id_physics, name="Materials",
subui="none", visible=1, color="#42A5F5", actions=["collapsible"])
# 4
id_numerics = pipeline.add_node(parent=id_materials, name="Numerics",
subui="none", visible=1, color="#42A5F5", actions=["collapsible"])
# 5
id_boundaries = pipeline.add_node(parent=id_numerics, name="Boundaries",
subui="none", visible=1, color="#42A5F5", actions=["collapsible"])
# 6
id_initial = pipeline.add_node(parent=id_boundaries, name="Initialization",
subui="none", visible=1, color="#42A5F5", actions=["collapsible"])
# 7
# id_monitor = pipeline.add_node(parent=id_initial, name="Monitor",
# subui="none", visible=1, color="#42A5F5", actions=["collapsible"])
# 8
id_fileio = pipeline.add_node(parent=id_initial, name="File I/O",
subui="none", visible=1, color="#42A5F5", actions=["collapsible"])
# 9
id_solver = pipeline.add_node(parent=id_fileio, name="Solver",
subui="none", visible=1, color="#00ACC1", actions=["collapsible"])
# first node is active initially
state.selection=["1"]
# important for the interactive ui
state.setdefault("active_ui", "Mesh")
# for submesh
state.setdefault("active_subui", "submesh_none")
state.setdefault("active_parent_ui", "submesh_none")
state.setdefault("active_head_ui", "submesh_none")
pipeline.update()
# which node in the gittree is active
state.active_id=1
# which sub ui menu is active
state.active_sub_ui = "none"
# this counter is used for the gittree items that are added and removed to/from the gittree
state.counter = 0
# -----------------------------------------------------------------------------
# Callbacks
# -----------------------------------------------------------------------------
def actives_change(ids):
log("info", f"actives_change::ids = = {ids}")
_id = ids[0]
state.active_id = _id
#state.boundaryText=_id
log("info", f"actives_change::active id = = {state.active_id}")
# get boundary name belonging to ID
_name = pipeline.get_node(_id)
# get the headnode of this node
_headnode = _name['headnode']
log("info", f"headnode= = {_headnode}")
log("info", f"active name = = {_name['name']}")
# if the headnode = active_name, then we have selected the head node
# if active_name != headnode, then we are a child of the headnode.
if _headnode == _name['name']:
log("info", f" headnode = = {_headnode}")
# we are at a headnode, so we do not have a parent id
state.active_parent_ui = "none"
state.active_head_ui = _headnode
else:
log("info", " we are at child node")
state.active_parent_ui = _headnode
# so headnode is none
state.active_head_ui = "none"
# check if we need to show a submenu
_subui = _name['subui']
# whatever the value, we update the pipeline with it
state.active_sub_ui = _subui
log("info", f"subnode= = {_subui}")
log("info", f"children: = {pipeline._children_map}")
_name = _name['name']
log("info", f"active name = = {_name}")
selectedBoundary = next((item for item in mesh_actor_list if item["name"] == _name), None)
log("info", f"mesh_actor_list = = {mesh_actor_list}")
if not selectedBoundary==None:
state.selectedBoundaryName = selectedBoundary["name"]
else:
# for 2D, show internal as default when we have not selected anything
if state.nDim == 2:
state.selectedBoundaryName = "internal"
else:
state.selectedBoundaryName = "None"
log("info", f"selected boundary name = = {state.selectedBoundaryName}")
state.dirty('selectedBoundaryName')
# nijso: hardcode internal as selected mesh
#state.selectedBoundaryName = "internal"
# get list of all actors, loop and color the selected actor
actorlist = vtk.vtkActorCollection()
actorlist = renderer.GetActors()
actorlist.InitTraversal()
# only if we have selected a boundary
if _headnode!="Boundaries":
log("info", "************* headnode is not a boundary")
for a in range(0, actorlist.GetNumberOfItems()):
actor = actorlist.GetNextActor()
log("info", f"actor name= = {actor.GetObjectName}")
# ignore everything that is not a boundary, so CoordAxes and CubeAxes
if ("Axes" in actor.GetObjectName()):
continue
# for 3D, no visualization of internal points
if (state.nDim==3 and actor.GetObjectName()=="internal"):
actor.VisibilityOff()
else:
# visualize everything
# the color of the geometry when we are outside of the boundary gittree
actor.VisibilityOn()
actor.GetProperty().SetLineWidth(2)
actor.GetProperty().RenderLinesAsTubesOn()
actor.GetProperty().SetColor(colors.GetColor3d('floralwhite'))
else:
internal=False
if state.selectedBoundaryName=="internal":
log("info", "internal selected")
internal=True
# ##### show/highlight the actor based on selection ##### #
# we loop over all actors and switch it on or off
for a in range(0, actorlist.GetNumberOfItems()):
actor = actorlist.GetNextActor()
log("info", f"actor name= = {actor.GetObjectName}")
if ("Axes" in actor.GetObjectName()):
continue
actor.GetProperty().SetRoughness(0.5)
actor.GetProperty().SetDiffuse(0.5)
actor.GetProperty().SetAmbient(0.5)
actor.GetProperty().SetSpecular(0.1)
actor.GetProperty().SetSpecularPower(10)
#log("info", f"getnextactor: name = = {actor.GetObjectName(}"))
#log("info", f"ambient= = {actor.GetProperty(}").GetAmbient())
#log("info", f"diffuse= = {actor.GetProperty(}").GetDiffuse())
#log("info", f"specular= = {actor.GetProperty(}").GetSpecular())
#log("info", f"roughness= = {actor.GetProperty(}").GetRoughness())
if (state.nDim==3 and actor.GetObjectName()=="internal"):
actor.VisibilityOff()
elif actor.GetObjectName() == state.selectedBoundaryName:
# current actor is selected, we highlight it
actor.VisibilityOn()
actor.GetProperty().SetLineWidth(4)
actor.GetProperty().RenderLinesAsTubesOn()
actor.GetProperty().SetColor(colors.GetColor3d('yellow'))
else:
actor.VisibilityOn()
if (state.nDim==3 and internal==True):
actor.GetProperty().SetLineWidth(2)
actor.GetProperty().RenderLinesAsTubesOn()
actor.GetProperty().SetColor(colors.GetColor3d('yellow'))
else:
actor.GetProperty().SetLineWidth(2)
actor.GetProperty().RenderLinesAsTubesOn()
actor.GetProperty().SetColor(colors.GetColor3d('floralwhite'))
ctrl.view_update()
log("info", f"state= = {_id}")
# active ui is the head node of the gittree
state.active_ui = _headnode
# check if we need to show a subui
# improvements required
def resetCamera():
renderer.ResetCamera()
ctrl.view_update()
###############################################################
# PIPELINE CARD : BOUNDARY
###############################################################
state.meshText="meshtext"
#state.boundaryText="boundtext"
#state.selectedBoundaryName = "internal"
# export su2 file (save on the server)
def save_file_su2(su2_filename):
log("info", "********** save .su2 **********\n")
# add the filename to the json database
state.jsonData['MESH_FILENAME'] = su2_filename
global root
save_su2mesh(root,su2_filename)
# Color By Callbacks
def color_by_array(actor, array):
log("info", "change color by array")
_min, _max = array.get("range")
mesh_mapper = actor.GetMapper()
mesh_mapper.SelectColorArray(array.get("text"))
mesh_mapper.GetLookupTable().SetRange(_min, _max)
if array.get("type") == vtkDataObject.FIELD_ASSOCIATION_POINTS:
mesh_mapper.SetScalarModeToUsePointFieldData()
else:
mesh_mapper.SetScalarModeToUseCellFieldData()
mesh_mapper.SetScalarVisibility(True)
mesh_mapper.SetUseLookupTableScalarRange(True)
lut = get_diverging_lut()
lut.SetTableRange(_min,_max)
mesh_mapper.SetLookupTable(lut)
mesh_mapper.GetLookupTable().SetRange(_min, _max)
actor.SetMapper(mesh_mapper)
global scalar_bar
global scalar_bar_widget
scalar_bar = MakeScalarBarActor()
scalar_bar_widget =MakeScalarBarWidget(scalar_bar)
log("info", f"scalarbarwidget= = {scalar_bar_widget}")
@state.change("mesh_color_array_idx")
def update_mesh_color_by_name(mesh_color_array_idx, **kwargs):
log("info", "change mesh color by array")
if mesh_color_array_idx < len(state.dataset_arrays):
array = state.dataset_arrays[mesh_color_array_idx]
else:
array = {'text': 'Solid', 'value': 0, 'range': [1.0, 1.0], 'type': 0}
if state.nDim == 2:
# color the internal
#color_by_array(mesh_actor, array)
if(len(mesh_actor_list)> 0 ):
actor = get_entry_from_name('internal','name',mesh_actor_list)
else:
actor = get_entry_from_name('internal','name',[{"id":0,"name":"internal","mesh":mesh_actor}])
color_by_array(actor['mesh'], array)
else:
# color all boundaries (all mesh actors that are not internal)
for actor in mesh_actor_list:
log("info", f"3D actor= = {actor}")
log("info", f"3D actor= = {actor['mesh']}")
if actor['name'] != 'internal':
log("info", "passing actor")
color_by_array(actor['mesh'], array)
ctrl.view_update()
# every time we change the main gittree ("ui"), we end up here
# we need to update the ui because it might have changed due to changes
# in other git nodes
#
@state.change("active_ui")
def update_active_ui(active_ui, **kwargs):
# log("info", f"update_active_ui:: = {active_ui}")
if not(state.active_id == 0):
# get boundary name belonging to ID
_name = pipeline.get_node(state.active_id)['name']
# log("info", f"update_active_ui::name= = {_name}")
if (_name=="Physics"):
# log("info", "update node physics")
#pipeline.update_node_value("Physics","subui",active_ui)
pass
elif (_name=="Initialization"):
# log("info", "update node Initialization")
# force update of initial_option_idx so we get the submenu
state.dirty('initial_option_idx')
#pipeline.update_node_value("Initialization","subui",active_ui)
# update because it might be changed elsewhere
#initialization_card()
ctrl.view_update()
@state.change("active_parent_ui")
def update_active_ui(active_ui, **kwargs):
log("info", f"update_active_ui:: = {active_ui}")
if not(state.active_id == 0):
# get boundary name belonging to ID
#_name = pipeline.get_node(state.active_id)['name']
#log("info", f"update_active_ui::name= = {_name}")
#if (_name=="Physics"):
# log("info", "update node physics")
#elif (_name=="Initialization"):
# log("info", "update node Initialization")
# # update because it might be changed elsewhere
# initialization_card()
ctrl.view_update()
@state.change("active_head_ui")
def update_active_ui(active_ui, **kwargs):
log("info", f"update_active_ui:: = {active_ui}")
if not(state.active_id == 0):
# get boundary name belonging to ID
_name = pipeline.get_node(state.active_id)['name']
#log("info", f"update_active_ui::name= = {_name}")
if (_name=="Physics"):
log("info", "*********** update ui: physics ************************")
# call to update physics submenu visibility
# this is important when setting all options from the config file
state.dirty('physics_turb_idx')
#elif (_name=="Initialization"):
# log("info", "update node Initialization")
# # update because it might be changed elsewhere
# initialization_card()
ctrl.view_update()
#
# every time we change the main gittree ("ui"), we end up here
# we have to set the correct "subui" again from the last visit.
@state.change("active_sub_ui")
def update_active_sub_ui(active_sub_ui, **kwargs):
log("info", f"update_active_sub_ui:: = {active_sub_ui}")
if not(state.active_id == 0):
_name = pipeline.get_node(state.active_id)['name']
log("info", f"update_active_sub_ui::parent name= = {_name}")
log("info", f"choice = = {state.initial_option_idx}")
if not(state.active_id == 0):
# get boundary name belonging to ID
_name = pipeline.get_node(state.active_id)['name']
log("info", f"update_active_sub_ui::name= = {_name}")
if (_name=="Physics"):
log("info", "update node physics")
pipeline.update_node_value("Physics","subui",active_sub_ui)
elif (_name=="Initialization"):
log("info", "update node Initialization")
pipeline.update_node_value("Initialization","subui",active_sub_ui)
# necessary?
#initialization_subcard()
ctrl.view_update()
# some default options
state.submodeltext = "none"
# initial value for the materials-fluidmodel list
state.LMaterialsFluid = LMaterialsFluidComp
state.LMaterialsViscosity = LMaterialsViscosityComp
state.LMaterialsConductivity = LMaterialsConductivityComp
state.LMaterialsHeatCapacity = LMaterialsHeatCapacityConst
###############################################################
# FILES
###############################################################
# load SU2 .su2 mesh file #
# currently loads a 2D or 3D .su2 file
@state.change("su2_file_upload")
def load_file_su2(su2_file_upload, **kwargs):
global pipeline
# remove the added boundary conditions in the pipeline
pipeline.remove_right_subnode("Boundaries")
del mesh_actor_list[:]
if su2_file_upload is None:
return
# check if the case name is set
if not checkCaseName():
state.su2_file_upload = None
return
# log("info", f"name = = {su2_file_upload.get("name"}"))
# log("info", f"last modified = = {su2_file_upload.get("lastModified"}"))
# log("info", f"size = = {su2_file_upload.get("size"}"))
# log("info", f"type = = {su2_file_upload.get("type"}"))
# remove all actors
renderer.RemoveAllViewProps()
grid.Reset()
# ### setup of the internal data structure ###
branch_interior = vtkMultiBlockDataSet()
branch_boundary = vtkMultiBlockDataSet()
global root
root.SetBlock(0, branch_interior)
root.GetMetaData(0).Set(vtk.vtkCompositeDataSet.NAME(), 'Interior')
root.SetBlock(1, branch_boundary)
root.GetMetaData(1).Set(vtk.vtkCompositeDataSet.NAME(), 'Boundary')
pts = vtk.vtkPoints()
# ### ### #
# mesh file format specific
file = ClientFile(su2_file_upload)
try:
filecontent = file.content.decode('utf-8')
except:
filecontent = file.content
f = filecontent.splitlines()
index = [idx for idx, s in enumerate(f) if 'NDIME' in s][0]
NDIME = int(f[index].split('=')[1])
# number of dimensions of the su2 mesh (2D or 3D)
state.nDim = NDIME
# for the mesh info display
#state.meshText += "Mesh Dimensions: " + str(NDIME) + "D \n"
index = [idx for idx, s in enumerate(f) if 'NPOIN' in s][0]
numPoints = int((f[index].split('=')[1]).split()[0])
#state.meshText += "Number of points: " + str(numPoints) + "\n"
# get all the points
for point in range(numPoints):
x = float()
y = float()
z = float()
line = f[index+point+1].split()
x = float(line[0])
y = float(line[1])
if (NDIME==2):
# 2D is always x-y plane (z=0)
z = float(0.0)
else:
z = float(line[2])
pts.InsertNextPoint(x,y,z)
grid.SetPoints(pts)
# get the number of elements/cells
index = [idx for idx, s in enumerate(f) if 'NELEM' in s][0]
numCells = int(f[index].split('=')[1])
state.mesh= ["Number of cells: " + str(numCells) + "\n"]
for cell in range(numCells):
data = f[index+cell+1].split()
CellType = int(data[0])
# quadrilaterals
if(CellType==9):
quaddata = [int(data[1]),int(data[2]),int(data[3]),int(data[4])]
grid.InsertNextCell(VTK_QUAD,4,quaddata)
# triangles
elif(CellType==5):
tridata = [int(data[1]),int(data[2]),int(data[3])]
grid.InsertNextCell(VTK_TRIANGLE,3,tridata)
# hexahedral
elif(CellType==12):
hexdata = [int(data[1]),int(data[2]),int(data[3]),int(data[4]),int(data[5]),int(data[6]),int(data[7]),int(data[8])]
grid.InsertNextCell(VTK_HEXAHEDRON,8,hexdata)
# tetrahedral (4 faces)
elif(CellType==10):
tetdata = [int(data[1]),int(data[2]),int(data[3]),int(data[4])]
grid.InsertNextCell(VTK_TETRA,4,tetdata)
# wedge
elif(CellType==13):
wedgedata = [int(data[1]),int(data[2]),int(data[3]),int(data[4]),int(data[5]),int(data[6])]
grid.InsertNextCell(VTK_WEDGE,6,wedgedata)
# pyramid
elif(CellType==14):
pyramiddata = [int(data[1]),int(data[2]),int(data[3]),int(data[4]),int(data[5])]
grid.InsertNextCell(VTK_PYRAMID,5,pyramiddata)
else:
log("Error", f"cell type not suppported")
branch_interior.SetBlock(0, grid)
branch_interior.GetMetaData(0).Set(vtk.vtkCompositeDataSet.NAME(), 'Fluid-Zone-1')
del branch_interior
# ### read the markers ### #
boundaryNames = []
markerNames=[]
index = [idx for idx, s in enumerate(f) if 'NMARK' in s][0]
numMarkers = int(f[index].split('=')[1])
global markergrid
markergrid = [vtkUnstructuredGrid() for i in range(numMarkers)]
# now loop over the markers
counter=0
for iMarker in range(numMarkers):
# grid for the marker
#markergrid = vtkUnstructuredGrid()
# copy all the points into the markergrid (inefficient)
markergrid[iMarker].SetPoints(pts)
# next line: marker tag, marker_elem
counter += 1
# this is the name (string) of the boundary
markertag = f[index+counter].split("=")[1].strip()
# add name to the boundaryNames list of dicts
boundaryNames.append(
{
"text": markertag,
"value": iMarker,
}
)
markerNames.append(markertag)
# next line: marker tag, marker_elem
counter+=1
line = f[index+counter].split("=")
numCells = int(line[1])
#log("info", f"number of cells = = {numCells}")
# loop over all cells
for cell in range(numCells):
counter+=1
data = f[index+counter].split()
#log("info", f"data = = {data}")
CellType = int(data[0])
# line
if(CellType==3):
linedata = [int(data[1]),int(data[2])]
markergrid[iMarker].InsertNextCell(VTK_LINE,2,linedata)
# triangles
elif(CellType==5):
tridata = [int(data[1]),int(data[2]),int(data[3])]
markergrid[iMarker].InsertNextCell(VTK_TRIANGLE,3,tridata)
# quadrilaterals
elif(CellType==9):
quaddata = [int(data[1]),int(data[2]),int(data[3]),int(data[4])]
markergrid[iMarker].InsertNextCell(VTK_QUAD,4,quaddata)
else:
log("Error", f"marker cell type not suppported")
# put boundary in multiblock structure
branch_boundary.SetBlock(iMarker, markergrid[iMarker])
branch_boundary.GetMetaData(iMarker).Set(vtk.vtkCompositeDataSet.NAME(), markertag)
# end loop over lines
#del markergrid
#del pts
# boundary meshes as unstructured grids
ds_b = []
for i in range(branch_boundary.GetNumberOfBlocks()):
ds_b.append(vtk.vtkUnstructuredGrid.SafeDownCast(branch_boundary.GetBlock(i)))
del branch_boundary
# we also clear the arrays, if any
for array in state.dataset_arrays:
arrayName = array.get("text")
log("info", f"removing array = {arrayName}")
grid.GetPointData().RemoveArray(arrayName)
# nijso TODO BUG does not contain data yet
#for iMarker in range(numMarkers):
# markergrid[iMarker].GetPointData().RemoveArray(arrayName)
# and we only use the default array
state.dataset_arrays = []
# show the internal mesh in 2D
if (NDIME==2):
mesh_actor.VisibilityOn()
mesh_actor.GetProperty().EdgeVisibilityOn()
else:
mesh_actor.VisibilityOff()
# initial color of the geometry
mesh_actor.GetProperty().SetColor(colors.GetColor3d('floralwhite'))
# Mesh - add mesh to the renderer
mesh_mapper.SetInputData(grid)
mesh_actor.SetMapper(mesh_mapper)
mesh_actor.SetObjectName("internal")
renderer.AddActor(mesh_actor)
# boundary actors
boundary_id = 101
i = 0
log("info", f"length of ds_b= = {len(ds_b)}")
for bcName in boundaryNames:
log("info", f"bc name= = {bcName}")
mesh_mapper_b1 = vtkDataSetMapper()
mesh_mapper_b1.ScalarVisibilityOff()
mesh_actor_b1 = vtkActor()
# in 2D, we show the interior (2D surface) and in 3D, we show all boundaries
if (NDIME==2):
mesh_actor_b1.VisibilityOff()
else:
mesh_actor_b1.VisibilityOn()
mesh_actor_b1.GetProperty().EdgeVisibilityOn()
mesh_actor_b1.GetProperty().SetColor(colors.GetColor3d('Peacock'))
mesh_mapper_b1.SetInputData(ds_b[i])
i += 1
mesh_actor_b1.SetMapper(mesh_mapper_b1)
mesh_actor_b1.SetObjectName(bcName.get("text"))
renderer.AddActor(mesh_actor_b1)
mesh_actor_list.append({"id":boundary_id,"name":bcName.get("text"), "mesh":mesh_actor_b1})
boundary_id += 1
# add internal mesh as well.
mesh_actor_list.append({"id":boundary_id,"name":"internal", "mesh":mesh_actor})
# internal block is also a 'boundary'
boundaryNames.append(
{
"text": "internal",
"value": numMarkers,
}
)
# now construct the actual boundary list for the GUI
for bcName in boundaryNames:
log("info", f"boundary name= = {bcName.get('text')}")
# add the boundaries to the right tree and not the left tree
id_aa = pipeline.append_node(parent_name="Boundaries", name=bcName.get("text"), left=False, subui="none", visible=1, color="#2962FF")
state.BCDictList = []
# fill the boundary conditions with initial boundary condition type
for bcName in boundaryNames:
log("info", f"*************** BCNAME ********** = {bcName}")
# do not add internal boundaries to bcdictlist
if bcName.get("text") != "internal":
state.BCDictList.append({"bcName":bcName.get("text"),
"bcType":"Wall",
"bc_subtype":"Temperature",
"json":"MARKER_ISOTHERMAL",
"bc_velocity_magnitude":1.0,
"bc_temperature":300.0,
"bc_pressure":0.0,
"bc_density":1.2,
"bc_massflow":0.0,
"bc_velocity_normal":[1.0, 0.0, 0.0],
"bc_heatflux":0.0,
"bc_heattransfer":[0.0, 300.0],
},
)
else:
state.BCDictList.append({"bcName":bcName.get("text"),
"bcType":"Internal",
"bc_subtype":"None",
"json":"NONE",
"bc_velocity_magnitude":0.0,
"bc_temperature":0.0,
"bc_pressure":0.0,
"bc_density":0.0,
"bc_massflow":0.0,
"bc_velocity_normal":[0.0, 0.0, 0.0],