Repository navigation
Expand file tree
/
Copy pathFunctionTools.py
More file actions
1484 lines (1061 loc) · 51.3 KB
/
Copy pathFunctionTools.py
File metadata and controls
1484 lines (1061 loc) · 51.3 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
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
from paraview.simple import *
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import matplotlib as mpl
import glob
import os
import csv
import sys
# ============================================================
# PLOT SCENE
# ============================================================
def plot_scene(folder, dim, data_name, property_name, skip_scenes, plane_y=None, plane_z=None):
# ========================================================
# CHECK INPUTS
# ========================================================
if dim not in [2, 3]:
raise ValueError("ERROR: dim must be either 2 or 3.")
if not os.path.isdir(folder):
raise ValueError(f"ERROR: Folder does not exist: {folder}")
if not data_name:
raise ValueError("ERROR: Data folder name cannot be empty.")
if not property_name:
raise ValueError("ERROR: Property name cannot be empty.")
if skip_scenes < 0:
raise ValueError("ERROR: skip_scenes must be greater than or equal to zero.")
if dim == 3 and plane_y is None:
raise ValueError("ERROR: plane_y must be provided for dim = 3.")
if dim == 3 and plane_z is None:
raise ValueError("ERROR: plane_z must be provided for dim = 3.")
# ========================================================
# OUTPUT FOLDER
# ========================================================
data_folder = os.path.join(folder, data_name)
property_folder = os.path.join(data_folder, property_name)
os.makedirs(property_folder, exist_ok=True)
# ========================================================
# INFORMATION
# ========================================================
print("")
print("============================================")
print("PLOT SCENE")
print("============================================")
print("Input folder :", folder)
print("Output folder :", property_folder)
print("Dimension :", dim)
print("Property :", property_name)
print("Skipped scenes :", skip_scenes)
if dim == 3:
print("Y-plane position :", plane_y)
print("Z-plane position :", plane_z)
# ========================================================
# FIND FILES
# ========================================================
pvtu_pattern = os.path.join(folder, "*.pvtu")
vtu_pattern = os.path.join(folder, "*.vtu")
pvtu_files = sorted(glob.glob(pvtu_pattern))
vtu_files = sorted(glob.glob(vtu_pattern))
# ========================================================
# SELECT FILE TYPE AND READER
# ========================================================
if len(pvtu_files) > 0:
files = pvtu_files
print("Detected partitioned VTU data.")
print("Using .pvtu files.")
print("Files found :", len(files))
solution = XMLPartitionedUnstructuredGridReader(registrationName="Solution", FileName=files)
elif len(vtu_files) > 0:
files = vtu_files
print("Detected standard VTU data.")
print("Using .vtu files.")
print("Files found :", len(files))
solution = XMLUnstructuredGridReader(registrationName="Solution", FileName=files)
else:
raise RuntimeError("ERROR: No .pvtu or .vtu files found!")
solution.UpdatePipeline()
# ========================================================
# GET TIMESTEPS
# ========================================================
animation_scene = GetAnimationScene()
animation_scene.UpdateAnimationUsingDataTimeSteps()
timesteps = solution.TimestepValues
if timesteps is None or len(timesteps) == 0:
if len(files) == 1:
timesteps = [0.0]
print("Single solution file detected. Using one static scene.")
else:
raise RuntimeError("ERROR: No timesteps found in the solution data!")
# ========================================================
# SELECT SCENES
# ========================================================
step = skip_scenes + 1
selected_indices = list(range(0, len(timesteps), step))
if selected_indices[-1] != len(timesteps) - 1:
selected_indices.append(len(timesteps) - 1)
selected_timesteps = [timesteps[i] for i in selected_indices]
print("Available scenes :", len(timesteps))
print("Selected scenes :", len(selected_timesteps))
#print("Selected indices :", selected_indices)
# ========================================================
# CHECK PROPERTY
# ========================================================
solution.UpdatePipeline(time=selected_timesteps[0])
point_data = solution.GetPointDataInformation()
cell_data = solution.GetCellDataInformation()
point_properties = []
cell_properties = []
for i in range(point_data.GetNumberOfArrays()):
point_properties.append(point_data.GetArray(i).GetName())
for i in range(cell_data.GetNumberOfArrays()):
cell_properties.append(cell_data.GetArray(i).GetName())
if property_name in point_properties:
property_association = "POINTS"
elif property_name in cell_properties:
property_association = "CELLS"
else:
print("Available point properties :", point_properties)
print("Available cell properties :", cell_properties)
raise RuntimeError(f"ERROR: Property '{property_name}' was not found in the solution data!")
print("Property location :", property_association)
# ========================================================
# PROPERTY INFORMATION
# ========================================================
if property_association == "POINTS":
property_info = point_data.GetArray(property_name)
else:
property_info = cell_data.GetArray(property_name)
property_num_components = property_info.GetNumberOfComponents()
print("Property components :", property_num_components)
# ========================================================
# CREATE RENDER VIEW
# ========================================================
animation_scene.AnimationTime = selected_timesteps[0]
solution.UpdatePipeline(time=selected_timesteps[0])
render_view = CreateView("RenderView")
ViewSize = [1700, 500]
ImRes = [3 * value for value in ViewSize]
render_view.ViewSize = ViewSize
render_view.Background = [1.0, 1.0, 1.0]
render_view.OrientationAxesVisibility = 0
if dim == 2:
solution_display = Show(solution, render_view)
solution_display.Representation = "Surface"
elif dim == 3:
slice_y = Slice(Input=solution)
slice_y.SliceType = "Plane"
slice_y.SliceType.Normal = [0.0, -1.0, 0.0]
slice_y.SliceType.Origin = [0.0, plane_y, 0.0]
slice_z = Slice(Input=solution)
slice_z.SliceType = "Plane"
slice_z.SliceType.Normal = [0.0, 0.0, 1.0]
slice_z.SliceType.Origin = [0.0, 0.0, plane_z]
slice_y.UpdatePipeline(time=selected_timesteps[0])
slice_z.UpdatePipeline(time=selected_timesteps[0])
# ========================================================
# STREAM TRACER
# ========================================================
if dim == 2 and property_name == "velocity":
bounds = solution.GetDataInformation().GetBounds()
x_min = bounds[0]
x_max = bounds[1]
y_min = bounds[2]
y_max = bounds[3]
seed_x = x_min + 0.36 * (x_max - x_min)
stream_tracer = StreamTracer(Input=solution, SeedType="Line")
stream_tracer.Vectors = ["POINTS", "velocity"]
stream_tracer.IntegrationDirection = "BOTH" #FORWARD BACKWARD BOTH
stream_tracer.MaximumStreamlineLength = 0.4 * (x_max - x_min)
stream_tracer.SeedType.Point1 = [seed_x, y_min, 0.0]
stream_tracer.SeedType.Point2 = [seed_x, y_max, 0.0]
stream_tracer.SeedType.Resolution = 50
streamline_display = Show(stream_tracer, render_view)
streamline_display.Representation = "Surface"
streamline_display.LineWidth = 2.0
streamline_display.AmbientColor = [0.0, 0.0, 0.0]
streamline_display.DiffuseColor = [1.0, 1.0, 1.0]
render_view.Update()
if dim == 2:
if property_num_components == 1:
ColorBy(solution_display, (property_association, property_name))
else:
ColorBy(solution_display, (property_association, property_name, "Magnitude"))
solution_display.RescaleTransferFunctionToDataRange(True, False)
solution_display.SetScalarBarVisibility(render_view, True)
elif dim == 3:
slice_y_display = Show(slice_y, render_view)
slice_y_display.Representation = "Surface"
slice_z_display = Show(slice_z, render_view)
slice_z_display.Representation = "Surface"
if property_num_components == 1:
ColorBy(slice_y_display, (property_association, property_name))
ColorBy(slice_z_display, (property_association, property_name))
else:
ColorBy(slice_y_display, (property_association, property_name, "Magnitude"))
ColorBy(slice_z_display, (property_association, property_name, "Magnitude"))
slice_y_display.SetScalarBarVisibility(render_view, True)
# ========================================================
# CONTOUR
# ========================================================
if property_name == "c":
contour_values = [0.0001, 0.001, 0.01, 0.5]
else:
contour_values = [0.5]
if dim == 2:
contour = Contour(Input=solution)
contour.ContourBy = ["POINTS", "c"]
contour.Isosurfaces = contour_values
contour_display = Show(contour, render_view)
contour_display.Representation = "Surface"
ColorBy(contour_display, None)
contour_display.AmbientColor = [0.0, 0.0, 0.0]
if property_name == "c":
contour_display.DiffuseColor = [1.0, 1.0, 1.0]
contour_display.LineWidth = 2.0
else:
contour_display.DiffuseColor = [1.0, 0.0, 0.0]
contour_display.LineWidth = 4.0
elif dim == 3:
contour_y = Contour(Input=slice_y)
contour_y.ContourBy = ["POINTS", "c"]
contour_y.Isosurfaces = contour_values
contour_z = Contour(Input=slice_z)
contour_z.ContourBy = ["POINTS", "c"]
contour_z.Isosurfaces = contour_values
contour_y_display = Show(contour_y, render_view)
contour_y_display.Representation = "Surface"
contour_z_display = Show(contour_z, render_view)
contour_z_display.Representation = "Surface"
ColorBy(contour_y_display, None)
ColorBy(contour_z_display, None)
contour_y_display.AmbientColor = [0.0, 0.0, 0.0]
contour_z_display.AmbientColor = [0.0, 0.0, 0.0]
if property_name == "c":
contour_y_display.DiffuseColor = [1.0, 1.0, 1.0]
contour_z_display.DiffuseColor = [1.0, 1.0, 1.0]
contour_y_display.LineWidth = 2.0
contour_z_display.LineWidth = 2.0
else:
contour_y_display.DiffuseColor = [1.0, 0.0, 0.0]
contour_z_display.DiffuseColor = [1.0, 0.0, 0.0]
contour_y_display.LineWidth = 4.0
contour_z_display.LineWidth = 4.0
slice_y_display.Visibility = 0
contour_y_display.Visibility = 0
slice_z_display.Visibility = 0
contour_z_display.Visibility = 0
# ========================================================
# COLORBAR
# ========================================================
color_map = GetColorTransferFunction(property_name)
if property_num_components == 1:
color_min, color_max = property_info.GetRange(0)
else:
color_min, color_max = property_info.GetRange(-1)
if property_name == "c":
color_min = 1.0e-6
color_max = 1.0
color_map.RescaleTransferFunction(color_min, color_max)
color_bar = GetScalarBar(color_map, render_view)
color_bar.Orientation = "Horizontal"
color_bar.WindowLocation = "Any Location"
color_bar.Position = [0.35, 0.75]
color_bar.ScalarBarLength = 0.3
render_view.Update()
print("Render view created.")
# ========================================================
# CAMERA
# ========================================================
render_view.InteractionMode = "2D"
render_view.CameraParallelProjection = 1
if dim == 2:
camera_x = 20.0
camera_y = 1.9
camera_z = 264.65000000000003
camera_scale = 3.5
render_view.CameraFocalPoint = [camera_x, camera_y, 0.0]
render_view.CameraPosition = [camera_x, camera_y, camera_z]
render_view.CameraViewUp = [0.0, 1.0, 0.0]
render_view.CameraParallelScale = camera_scale
render_view.Update()
elif dim == 3:
bounds = solution.GetDataInformation().GetBounds()
x_min = bounds[0]
x_max = bounds[1]
y_min = bounds[2]
y_max = bounds[3]
z_min = bounds[4]
z_max = bounds[5]
x_center = 0.5 * (x_min + x_max)
y_center = 0.5 * (y_min + y_max)
z_center = 0.5 * (z_min + z_max)
x_length = x_max - x_min
y_length = y_max - y_min
z_length = z_max - z_min
aspect_ratio = ViewSize[0] / ViewSize[1]
camera_scale_y = 0.5 * max(z_length, x_length / aspect_ratio)
camera_scale_z = 0.5 * max(y_length, x_length / aspect_ratio)
camera_distance = 2.0 * max(x_length, y_length, z_length)
# ========================================================
# SAVE ALL SELECTED SCENES
# ========================================================
if dim == 3:
plane_y_folder = os.path.join(property_folder, "plane_y")
plane_z_folder = os.path.join(property_folder, "plane_z")
os.makedirs(plane_y_folder, exist_ok=True)
os.makedirs(plane_z_folder, exist_ok=True)
for saved_scene_number, scene_index in enumerate(selected_indices):
scene_time = timesteps[scene_index]
scene_file = files[scene_index]
animation_scene.AnimationTime = scene_time
solution.UpdatePipeline(time=scene_time)
scene_base = os.path.splitext(os.path.basename(scene_file))[0]
scene_suffix = scene_base.split("_")[-1]
if scene_suffix.startswith("t") and scene_suffix[1:].isdigit():
scene_suffix = scene_suffix[1:]
elif not scene_suffix.isdigit():
raise RuntimeError(f"ERROR: Could not extract a numeric index from file: {scene_file}")
if dim == 2:
render_view.Update()
output_file = os.path.join(property_folder, f"{property_name}_{scene_suffix}.png")
SaveScreenshot(output_file, render_view, ImageResolution=ImRes, TransparentBackground=1)
print("Saved scene", saved_scene_number + 1, "of", len(selected_indices), ":", output_file)
elif dim == 3:
slice_y.UpdatePipeline(time=scene_time)
slice_z.UpdatePipeline(time=scene_time)
contour_y.UpdatePipeline(time=scene_time)
contour_z.UpdatePipeline(time=scene_time)
# ====================================================
# Y-PLANE: normal = [0, -1, 0]
# ====================================================
slice_y_display.Visibility = 1
contour_y_display.Visibility = 1
slice_z_display.Visibility = 0
contour_z_display.Visibility = 0
render_view.CameraFocalPoint = [x_center, plane_y, z_center]
render_view.CameraPosition = [x_center, plane_y - camera_distance, z_center]
render_view.CameraViewUp = [0.0, 0.0, 1.0]
render_view.CameraParallelScale = camera_scale_y
render_view.Update()
output_file_y = os.path.join(plane_y_folder, f"{property_name}_{scene_suffix}.png")
SaveScreenshot(output_file_y, render_view, ImageResolution=ImRes, TransparentBackground=1)
# ====================================================
# Z-PLANE: normal = [0, 0, 1]
# ====================================================
slice_y_display.Visibility = 0
contour_y_display.Visibility = 0
slice_z_display.Visibility = 1
contour_z_display.Visibility = 1
render_view.CameraFocalPoint = [x_center, y_center, plane_z]
render_view.CameraPosition = [x_center, y_center, plane_z + camera_distance]
render_view.CameraViewUp = [0.0, 1.0, 0.0]
render_view.CameraParallelScale = camera_scale_z
render_view.Update()
output_file_z = os.path.join(plane_z_folder, f"{property_name}_{scene_suffix}.png")
SaveScreenshot(output_file_z, render_view, ImageResolution=ImRes, TransparentBackground=1)
print("Saved scene", saved_scene_number + 1, "of", len(selected_indices), ":")
print(" Y-plane:", output_file_y)
print(" Z-plane:", output_file_z)
# ============================================================
# CALCULATE CONTOUR
# ============================================================
def calculate_contour(folder, dim, data_name, time_factor):
# ========================================================
# CHECK INPUTS
# ========================================================
if dim not in [2, 3]:
raise ValueError("ERROR: dim must be either 2 or 3. Code stopped.")
if not os.path.isdir(folder):
raise ValueError(f"ERROR: Folder does not exist: {folder}")
if not data_name:
raise ValueError("ERROR: Data folder name cannot be empty.")
if time_factor <= 0:
raise ValueError("ERROR: time_factor must be greater than zero.")
# ========================================================
# OUTPUT FOLDER
# ========================================================
output_folder = os.path.join(folder, data_name)
os.makedirs(output_folder, exist_ok=True)
print("Input folder :", folder)
print("Output folder:", output_folder)
print("Dimension :", dim)
print("Time factor :", time_factor)
# ========================================================
# FIND FILES
# ========================================================
pvtu_pattern = os.path.join(folder, "*.pvtu")
vtu_pattern = os.path.join(folder, "*.vtu")
pvtu_files = sorted(glob.glob(pvtu_pattern))
vtu_files = sorted(glob.glob(vtu_pattern))
# ========================================================
# SELECT FILE TYPE AND READER
# ========================================================
if len(pvtu_files) > 0:
files = pvtu_files
print("Detected partitioned VTU data.")
print("Using .pvtu files.")
print("Found", len(files), "files")
solution = XMLPartitionedUnstructuredGridReader(registrationName="Solution", FileName=files)
elif len(vtu_files) > 0:
files = vtu_files
print("Detected standard VTU data.")
print("Using .vtu files.")
print("Found", len(files), "files")
solution = XMLUnstructuredGridReader(
registrationName="Solution", FileName=files
)
else:
raise RuntimeError("ERROR: No .pvtu or .vtu files found!")
# ========================================================
# OUTPUT FILE
# ========================================================
OUTPUT_FILE = os.path.join(
output_folder,
f"Contour{dim}D.csv"
)
# ========================================================
# READ FILES
# ========================================================
solution.UpdatePipeline()
# ========================================================
# TIME STEPS
# ========================================================
animationScene = GetAnimationScene()
animationScene.UpdateAnimationUsingDataTimeSteps()
timesteps = animationScene.TimeKeeper.TimestepValues
print("Number of timesteps:", len(timesteps))
# ========================================================
# CREATE CONTOUR
# ========================================================
contour1 = Contour(Input=solution)
contour1.ContourBy = ["POINTS", "c"]
contour1.Isosurfaces = [0.5]
contour1.UpdatePipeline()
# ========================================================
# OPEN CSV
# ========================================================
if os.path.exists(OUTPUT_FILE):
print("WARNING: Output file already exists and will be overwritten:")
print(OUTPUT_FILE)
with open(OUTPUT_FILE, "w", newline="") as csvfile:
writer = csv.writer(csvfile)
if dim == 2:
writer.writerow([
"TimeStep", "Time", "X", "Y", "Z","c", "p", "u", "v","velocity_x", "velocity_y", "velocity_z"])
elif dim == 3:
writer.writerow(["TimeStep", "Time", "X", "Y", "Z","c", "p", "u", "v", "w","velocity_x", "velocity_y", "velocity_z"])
# ====================================================
# LOOP OVER TIME
# ====================================================
data_found = False
for i, time in enumerate(timesteps):
#print("Processing timestep", i, "/", len(timesteps) - 1)
scaled_time = time * time_factor
solution.UpdatePipeline(time)
contour1.UpdatePipeline(time)
data_contour = servermanager.Fetch(contour1)
if data_contour is None:
print("WARNING: No data")
continue
number_of_points = data_contour.GetNumberOfPoints()
#print("Contour points:", number_of_points)
if number_of_points == 0:
print("WARNING: Empty contour at timestep", i)
continue
data_found = True
# =================================================
# DATA ARRAYS
# =================================================
point_data = data_contour.GetPointData()
c_array = point_data.GetArray("c")
p_array = point_data.GetArray("p")
u_array = point_data.GetArray("u")
v_array = point_data.GetArray("v")
if dim == 3:
w_array = point_data.GetArray("w")
velocity_array = point_data.GetArray("velocity")
# =================================================
# WRITE POINTS
# =================================================
for point_id in range(number_of_points):
x, y, z = data_contour.GetPoint(point_id)
# ---------------------------------------------
# Scalars
# ---------------------------------------------
c = c_array.GetTuple1(point_id) if c_array is not None else ""
p = p_array.GetTuple1(point_id) if p_array is not None else ""
u = u_array.GetTuple1(point_id) if u_array is not None else ""
v = v_array.GetTuple1(point_id) if v_array is not None else ""
if dim == 3:
w = w_array.GetTuple1(point_id) if w_array is not None else ""
# ---------------------------------------------
# Velocity vector
# ---------------------------------------------
if velocity_array is not None:
velocity = velocity_array.GetTuple(point_id)
velocity_x = velocity[0]
velocity_y = velocity[1]
if len(velocity) > 2:
velocity_z = velocity[2]
else:
velocity_z = 0.0
else:
velocity_x = ""
velocity_y = ""
velocity_z = ""
# ---------------------------------------------
# Write row
# ---------------------------------------------
if dim == 2:
writer.writerow([i, scaled_time, x, y, z, c, p, u, v,velocity_x, velocity_y, velocity_z])
elif dim == 3:
writer.writerow([i, scaled_time, x, y, z, c, p, u, v, w,velocity_x, velocity_y, velocity_z])
# ========================================================
# CHECK DATA
# ========================================================
if not data_found:
print("")
print("WARNING: No contour data was found.")
# ========================================================
# CLEANUP
# ========================================================
Delete(contour1)
Delete(solution)
# ========================================================
# FINISHED
# ========================================================
print("")
print("============================================")
if data_found:
print("DONE")
else:
print("DONE - NO CONTOUR DATA")
print("============================================")
print("Files found :", len(files))
print("Output file :", OUTPUT_FILE)
print("============================================")
if data_found:
return OUTPUT_FILE
else:
return None
# ============================================================
# PLOT CONTOUR
# ============================================================
def plot_contour(folder, dim, data_name, num_contours, time_factor):
# ========================================================
# CHECK INPUTS
# ========================================================
if dim != 2: raise ValueError("ERROR: plot_contour is currently implemented only for dim = 2.")
if not os.path.isdir(folder): raise ValueError(f"ERROR: Folder does not exist: {folder}")
if not data_name: raise ValueError("ERROR: Data folder name cannot be empty.")
if num_contours <= 0: raise ValueError("ERROR: num_contours must be greater than zero.")
# ========================================================
# INPUT / OUTPUT FILES
# ========================================================
data_folder = os.path.join(folder, data_name)
input_file = os.path.join(data_folder, f"Contour{dim}D.csv")
output_file = os.path.join(data_folder, f"ContourEvolution{dim}D.png")
if not os.path.isfile(input_file):
print(f"Contour file does not exist: {input_file}")
print("Creating contour file...")
calculate_contour(folder, dim, data_name, time_factor)
if not os.path.isfile(input_file):
raise RuntimeError(f"ERROR: Failed to create contour file: {input_file}")
print("")
print("============================================")
print("PLOT CONTOUR")
print("============================================")
print("Input file :", input_file)
print("Output file :", output_file)
print("Requested plots :", num_contours)
# ========================================================
# READ CONTOUR DATA
# ========================================================
contours = {}
with open(input_file, "r", newline="") as csvfile:
reader = csv.DictReader(csvfile)
required_columns = ["TimeStep", "Time", "X", "Y"]
if reader.fieldnames is None: raise RuntimeError(f"ERROR: Empty CSV file: {input_file}")
for column in required_columns:
if column not in reader.fieldnames: raise RuntimeError(f"ERROR: Column '{column}' was not found in: {input_file}")
for row in reader:
timestep = int(row["TimeStep"])
time = float(row["Time"])
x = float(row["X"])
y = float(row["Y"])
if timestep not in contours: contours[timestep] = {"time": time, "x": [], "y": []}
contours[timestep]["x"].append(x)
contours[timestep]["y"].append(y)
# ========================================================
# CHECK DATA
# ========================================================
if len(contours) == 0: raise RuntimeError("ERROR: No contour data was found.")
timesteps = sorted(contours.keys())
print("Available plots :", len(timesteps))
# ========================================================
# SELECT TIMESTEPS
# ========================================================
num_selected = min(num_contours, len(timesteps))
if num_selected == 1:
selected_timesteps = [timesteps[0]]
else:
selected_timesteps = []
for i in range(num_selected):
index = round(i * (len(timesteps) - 1) / (num_selected - 1))
selected_timesteps.append(timesteps[index])
print("Selected plots :", len(selected_timesteps))
# ========================================================
# SELECTED TIMES
# ========================================================
selected_times = [contours[timestep]["time"] for timestep in selected_timesteps]
time_min = min(selected_times)#/3.6
time_max = max(selected_times)#/3.6
# ========================================================
# COLORMAP
# ========================================================
if time_min == time_max: norm = mpl.colors.Normalize(vmin=time_min - 0.5, vmax=time_max + 0.5)
else: norm = mpl.colors.Normalize(vmin=time_min, vmax=time_max)
cmap = plt.get_cmap("viridis")
#cmap = LinearSegmentedColormap.from_list("black_yellow", ["yellow", "black"])
# ========================================================
# CREATE FIGURE
# ========================================================
fig, ax = plt.subplots(figsize=(10, 5))
# ========================================================
# PLOT CONTOURS
# ========================================================
for timestep in selected_timesteps:
time = contours[timestep]["time"]
points = sorted(zip(contours[timestep]["x"], contours[timestep]["y"]), key=lambda point: point[0])
x_sorted = [point[0] for point in points]
y_sorted = [point[1] for point in points]
#ax.plot(x_sorted, y_sorted, color=cmap(norm(time)), linewidth=1.2)
ax.plot(x_sorted, y_sorted, color="k", linewidth=0.5)
#ax.plot(x_sorted, y_sorted, color="k", linewidth=1.2,label="Steady State")
ax.fill_between(x_sorted, 0.0, y_sorted, color="yellow", alpha=0.1)
if True == False:
# ========================================================
# COLORBAR
# ========================================================
scalar_map = mpl.cm.ScalarMappable(norm=norm, cmap=cmap)
scalar_map.set_array([])
colorbar = fig.colorbar(scalar_map, ax=ax)
colorbar.set_label("Time [h]", fontsize = 14)
colorbar.ax.tick_params(labelsize=14)
# ========================================================
# AXES
# ========================================================
ax.set_xlabel("X",fontsize=14)
ax.set_ylabel("Y",fontsize=14)
ax.set_aspect("equal")
#ax.set_xlim(11.0, 27)
ax.set_xlim(left=-0.001)
ax.set_ylim(bottom=-0.02)
ax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(0.2))
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.2))
ax.tick_params(axis="both", labelsize=18)
ax.plot([0.0, 0.0], [0.0, 0.66], color="black", linewidth=2.0, linestyle = "--",zorder=10, solid_capstyle="butt")#LEFT
ax.plot([0.0, 0.3], [0.66, 0.66], color="black", linewidth=2.0, linestyle = "--",zorder=10, solid_capstyle="butt")#TOP
ax.plot([0.3, 1.0], [0.66, 0.66], color="red", linewidth=2.0, zorder=10, solid_capstyle="butt", label=r"$\Gamma_{in}$")#TOP SOURCE
ax.plot([1.01, 1.008], [-0.018, 0.68], color="black", linewidth=7.0, zorder=10, solid_capstyle="butt")#Right
ax.plot([0.0, 1.0078], [-0.01, -0.01], color="black", linewidth=7.0, zorder=10, solid_capstyle="butt")#BOTTOM
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
else:
ax.set_xlabel("X",fontsize=7)
ax.set_ylabel("Y",fontsize=7)
ax.set_aspect("equal")
ax.set_xlim(10.0, 30.0)
ax.set_ylim(bottom=-0.02)
#ax.xaxis.set_major_locator(mpl.ticker.MultipleLocator(0.2))
#ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.2))
#ax.tick_params(axis="both", labelsize=18)
ax.spines["top"].set_visible(False)
#ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
#ax.spines["left"].set_visible(False)
#ax.legend()
# ========================================================
# SAVE FIGURE
# ========================================================
fig.tight_layout()
fig.savefig(output_file, dpi=300, bbox_inches="tight")
plt.close(fig)
# ========================================================
# FINISHED
# ========================================================
print("")
print("============================================")
print("DONE")
print("============================================")
print("Contours plotted:", len(selected_timesteps))
print("Initial time :", time_min)
print("Final time :", time_max)
print("Output file :", output_file)
print("============================================")
return output_file
# ============================================================
# SCALABILITY
# ============================================================
def StrongScalability(folder, step, level):
# ========================================================
# CHECK INPUTS
# ========================================================
if not os.path.isdir(folder):
raise ValueError(f"ERROR: Folder does not exist: {folder}")
# ========================================================
# FIND PARALLEL CASES
# ========================================================