-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyzer.py
1462 lines (1093 loc) · 56 KB
/
analyzer.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
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from assignment_functions import lobatto_quad
from mapping import StandardDomainMapping, StandardTimeMapping
from components import Metric
from solver import Problem, Solver, MESolver
from typing import Union, Callable, Literal
from sklearn.linear_model import LinearRegression
from matplotlib.patches import Rectangle
from matplotlib.transforms import Bbox
from matplotlib import rc
class PlotterHelper(object):
MARKERS = ['o', 's', 'D', '^', 'v', '<', '>', 'p', 'P', '*', 'X', 'h', 'H', '+', 'x', '|', '_']
COLORS = ["#CC6677", "#999933", "#117733", "#332288"][::-1]
MARKERSIZE = 3
REC_RATIO = 4 / 4. # w / h
A4_DIMS = (8.3, 11.7)
# cut: 10.10 cm both top and bottom; 6.90 cm both left and right
@staticmethod
def adjust_font():
plt.rcParams.update({
"text.usetex": True, # Use TeX for rendering
"font.family": "serif", # Use serif font
"font.serif": ["cmr10"], # Set the CMR font family and size
"font.size": 10, # Set the default font size
"axes.formatter.use_mathtext": True, # Enable mathtext mode
})
rc('text.latex', preamble=r'\usepackage{color}')
@staticmethod
def get_figsize(n_figs_on_page:int = 2, ratio: float=REC_RATIO, page_margin: float=1):
w = (PlotterHelper.A4_DIMS[0] - 2 * page_margin) / n_figs_on_page
h = w / ratio
return (w, h)
@staticmethod
def get_colors_markers_markersize():
return PlotterHelper.COLORS, PlotterHelper.MARKERS, PlotterHelper.MARKERSIZE
class Analyzer(object):
def __init__(self, top_solver: Union[Solver, MESolver]) -> None:
# Check typing
if not isinstance(top_solver, Solver) and not isinstance(top_solver, MESolver):
return TypeError(f"top_solver must be either of type Solver or MESolver, not {type(top_solver)}.")
self.type: Literal['SE', 'ME'] = f"{ 'SE' if isinstance(top_solver, Solver) else 'ME' }"
self.top_solver: Union[Solver, MESolver] = top_solver
if self.type == 'SE':
self.top_problem: Problem = top_solver.problem
else:
self.top_problem: Problem = top_solver.initial_problem
@staticmethod
def same_lengths(tab: list) -> bool:
"""
Function checks if all variables passed in the tab argument have the same length.
The function takes a list of variables. By assumption this list contains variables that can be either
an int, np.ndarray, or list type. Function checks if all the variables have the same length
(an int has length 1 by definition). Raises RuntimeWarning if the passed list is empty.
Returns True if all variable lengths are equal, False otherwise.
Parameters:
----------
tab : list
List containing variables to check for length equality.
Returns:
-------
bool
True if all variable lengths are equal, False otherwise.
Raises:
-------
RuntimeWarning
If the list of tabs is empty.
"""
if len(tab) < 1:
raise RuntimeWarning("The list of tabs is empty.")
# initialize list of lengths
lengths = []
for i in range(len(tab)):
lst: Union[int, np.ndarray, list] = tab[i]
if isinstance(lst, int):
lengths.append(1)
else:
lengths.append(len(lst))
lengths = np.array(lengths)
return np.all(lengths == lengths[0])
# Private method for spatial pointwise error computation
def __compute_abs_spat_ptwise_error_zw_h(self, dual: bool, \
t: float, \
N: int, K: int, \
DN_int_x: int, DN_int_y: int, DN_int_t: int, \
N_res_x: int, N_res_y: int) -> np.ndarray:
# Assure that N is alway given
if N is None:
raise ValueError("N parameter must be provided.")
# Assure that the exact solution exists in the problem (not None)
if self.top_problem.zw_exact is None:
raise ValueError("The exact solution of the problem zw_exact must be provided (not None).")
# If single element solver is used, the K parameter must be None
if self.type == 'SE' and K is not None:
raise ValueError("K parameter must be left at None when using single element solver.")
# If multiple element solver is used, the K parameter must be provided
if self.type == 'ME' and K is None:
raise ValueError("K parameter must be provided by keyword K when using multi element solver.")
# Create auxiliary solver: the same args as the top_solver but update orders
aux_kwargs = self.top_solver.kwargs
aux_kwargs["N"] = N
# Order of mass matrix integration
aux_kwargs["N_int_x"] = N + DN_int_x
aux_kwargs["N_int_y"] = N + DN_int_y
aux_kwargs["N_int_t"] = N + DN_int_t
if self.type == 'SE':
aux_solver = Solver(self.top_solver.problem_id, self.top_solver.sparse, verbose=False, **aux_kwargs)
# Solve with solver
aux_solver.solve_system(verbose=False)
else:
aux_solver = MESolver(self.top_solver.problem_id, K, self.top_solver.sparse, verbose=False, **aux_kwargs)
# Solve with solver
aux_solver.solve(verbose=False)
# Metric to be used in reconstruction
metric = Metric(N, N+DN_int_x, N+DN_int_y, N+DN_int_t, self.top_problem.c, self.top_problem.r, self.top_problem.d_map, self.top_problem.t_map)
# Retrieve mappings
d_map = self.top_problem.d_map
# Generate unit reconstruction grid
xi_rec = np.linspace(-1, 1, N_res_x)
eta_rec = np.linspace(-1, 1, N_res_y)
mesh_xieta_rec = np.meshgrid(xi_rec, eta_rec)
x_rec_grid = d_map.x(mesh_xieta_rec[0], mesh_xieta_rec[1])
y_rec_grid = d_map.y(mesh_xieta_rec[0], mesh_xieta_rec[1])
if dual:
z_h = aux_solver.reconstruct_w(mesh_xieta_rec, t, verbose=False) # solve for w DOFs
else:
z_h = aux_solver.reconstruct_z(mesh_xieta_rec, t, verbose=False) # solve for z DOFs
z_h = z_h.reshape(N_res_y, N_res_x)
# Evaluate the exact solution at integration nodes
zw_ex_evaluated = self.top_problem.zw_exact(x_rec_grid, y_rec_grid, t)
# Compute the absolute error
return np.abs(zw_ex_evaluated - z_h)
# Private method for spatial pointwise error computation
def __compute_abs_spat_ptwise_error_pi_h(self, \
t: float, \
N: int, K: int, \
DN_int_x: int, DN_int_y: int, DN_int_t: int, \
N_res_x: int, N_res_y: int) -> np.ndarray:
# Assure that N is alway given
if N is None:
raise ValueError("N parameter must be provided.")
# Assure that the exact solution exists in the problem (not None)
if self.top_problem.zw_exact is None:
raise ValueError("The exact solution of the problem zw_exact must be provided (not None).")
# If single element solver is used, the K parameter must be None
if self.type == 'SE' and K is not None:
raise ValueError("K parameter must be left at None when using single element solver.")
# If multiple element solver is used, the K parameter must be provided
if self.type == 'ME' and K is None:
raise ValueError("K parameter must be provided by keyword K when using multi element solver.")
# Create auxiliary solver: the same args as the top_solver but update orders
aux_kwargs = self.top_solver.kwargs
aux_kwargs["N"] = N
# Order of mass matrix integration
aux_kwargs["N_int_x"] = N + DN_int_x
aux_kwargs["N_int_y"] = N + DN_int_y
aux_kwargs["N_int_t"] = N + DN_int_t
if self.type == 'SE':
aux_solver = Solver(self.top_solver.problem_id, self.top_solver.sparse, verbose=False, **aux_kwargs)
# Solve with solver
aux_solver.solve_system(verbose=False)
else:
aux_solver = MESolver(self.top_solver.problem_id, K, self.top_solver.sparse, verbose=False, **aux_kwargs)
# Solve with solver
aux_solver.solve(verbose=False)
# Metric to be used in reconstruction
metric = Metric(N, N+DN_int_x, N+DN_int_y, N+DN_int_t, self.top_problem.c, self.top_problem.r, self.top_problem.d_map, self.top_problem.t_map)
# Retrieve mappings
d_map = self.top_problem.d_map
# Generate unit reconstruction grid
xi_rec = np.linspace(-1, 1, N_res_x)
eta_rec = np.linspace(-1, 1, N_res_y)
mesh_xieta_rec = np.meshgrid(xi_rec, eta_rec)
x_rec_grid = d_map.x(mesh_xieta_rec[0], mesh_xieta_rec[1])
y_rec_grid = d_map.y(mesh_xieta_rec[0], mesh_xieta_rec[1])
pi_h = aux_solver.reconstruct_pi(mesh_xieta_rec, t, verbose=False) # solve for pi DOFs
pi_h = pi_h.reshape(N_res_y, N_res_x)
# Evaluate the exact solution at integration nodes
pi_ex_evaluated = self.top_problem.pi_exact(x_rec_grid, y_rec_grid, t)
# Compute the absolute error
return np.abs(pi_ex_evaluated - pi_h)
# Private method for one-time evaluation of L2 error for zw
def __compute_L2Linf_zw_h_def(self, \
dual: bool, \
N: int, \
K: Union[int, None]=None, \
N_int_x: Union[int, None]=None, N_int_y: Union[int, None]=None, N_int_t: Union[int, None]=None, \
N_L2_int_x: Union[int, None]=None, N_L2_int_y: Union[int, None]=None, N_L2_int_t: Union[int, None]=None, \
verbose: bool=False \
) -> float:
# Assure that N is alway given
if N is None:
raise ValueError("N parameter must be provided.")
# Assure that the exact solution exists in the problem (not None)
if self.top_problem.zw_exact is None:
raise ValueError("The exact solution of the problem zw_exact must be provided (not None).")
# If single element solver is used, the K parameter must be None
if self.type == 'SE' and K is not None:
raise ValueError("K parameter must be left at None when using single element solver.")
# If multiple element solver is used, the K parameter must be provided
if self.type == 'ME' and K is None:
raise ValueError("K parameter must be provided by keyword K when using multi element solver.")
# Check if any requirements were made regarding the orders
if N_int_x is None:
N_int_x = N
if N_int_y is None:
N_int_y = N
if N_int_t is None:
N_int_t = N
if N_L2_int_x is None:
N_L2_int_x = N
if N_L2_int_y is None:
N_L2_int_y = N
if N_L2_int_t is None:
N_L2_int_t = N
# Create auxiliary solver: the same args as the top_solver but update orders
aux_kwargs = self.top_solver.kwargs
aux_kwargs["N"] = N
# Order of mass matrix integration
aux_kwargs["N_int_x"] = N_int_x
aux_kwargs["N_int_y"] = N_int_y
aux_kwargs["N_int_t"] = N_int_t
if self.type == 'SE':
aux_solver = Solver(self.top_solver.problem_id, self.top_solver.sparse, verbose=verbose, **aux_kwargs)
# Solve with solver
aux_solver.solve_system(verbose=False)
else:
aux_solver = MESolver(self.top_solver.problem_id, K, self.top_solver.sparse, verbose=verbose, **aux_kwargs)
# Solve with solver
aux_solver.solve(verbose=False)
# Metric to be used in L2 INTEGRATION
metric = Metric(N, N_L2_int_x, N_L2_int_y, N_L2_int_t, self.top_problem.c, self.top_problem.r, self.top_problem.d_map, self.top_problem.t_map)
# Retrieve mappings
d_map = metric.d_map
t_map = metric.t_map
# Generate unit integration grid
xi_int_grid, tau_int_grid, eta_int_grid = np.meshgrid(metric.GL_int_x, metric.GL_int_y, metric.GL_int_t)
mesh_xieta_int = np.meshgrid(metric.GL_int_x, metric.GL_int_y)
x_int_grid = d_map.x(xi_int_grid, eta_int_grid)
y_int_grid = d_map.y(xi_int_grid, eta_int_grid)
t_int_grid = t_map.t(tau_int_grid)
# Evaluate transformation metrics at unit integration nodes
X_XI_INT = d_map.x_xi(xi_int_grid, eta_int_grid)
X_ETA_INT = d_map.x_eta(xi_int_grid, eta_int_grid)
Y_XI_INT = d_map.y_xi(xi_int_grid, eta_int_grid)
Y_ETA_INT = d_map.y_eta(xi_int_grid, eta_int_grid)
T_TAU_INT = t_map.t_tau(tau_int_grid)
# The Jacobian evaluated at integration nodes
J_INT = T_TAU_INT * (X_XI_INT * Y_ETA_INT - Y_XI_INT * X_ETA_INT)
if dual:
z_h = aux_solver.reconstruct_w(mesh_xieta_int, t_map.t(metric.GL_int_t), verbose=False) # solve for w DOFs
else:
z_h = aux_solver.reconstruct_z(mesh_xieta_int, t_map.t(metric.GL_int_t), verbose=False) # solve for z DOFs
z_h = z_h.reshape(N_L2_int_y + 1, N_L2_int_x + 1, -1)
# Evaluate the exact solution at integration nodes
zw_ex_evaluated = self.top_problem.zw_exact(x_int_grid, y_int_grid, t_int_grid)
# Compute the difference squared with Jacobian
d_sq = np.power(zw_ex_evaluated - z_h, 2)
# Integrate
I = np.einsum('ijk,i,j,k->', d_sq * J_INT, metric.weights_int_y, metric.weights_int_x, metric.weights_int_t, optimize='greedy')
# Return the value sqrt, and Linf
return np.sqrt(I), np.max(np.abs(zw_ex_evaluated - z_h))
# Private method for one-time evaluation of L2 error for div
def __compute_L2Linf_div_h_def(self, \
N: int, \
K: Union[int, None]=None, \
N_int_x: Union[int, None]=None, N_int_y: Union[int, None]=None, N_int_t: Union[int, None]=None, \
N_L2_int_x: Union[int, None]=None, N_L2_int_y: Union[int, None]=None, N_L2_int_t: Union[int, None]=None, \
verbose: bool=False \
) -> float:
# Assure that N is alway given
if N is None:
raise ValueError("N parameter must be provided.")
# Assure that the exact solution exists in the problem (not None)
if self.top_problem.zw_exact is None:
raise ValueError("The exact solution of the problem zw_exact must be provided (not None).")
# If single element solver is used, the K parameter must be None
if self.type == 'SE' and K is not None:
raise ValueError("K parameter must be left at None when using single element solver.")
# If multiple element solver is used, the K parameter must be provided
if self.type == 'ME' and K is None:
raise ValueError("K parameter must be provided by keyword K when using multi element solver.")
# Check if any requirements were made regarding the orders
if N_int_x is None:
N_int_x = N
if N_int_y is None:
N_int_y = N
if N_int_t is None:
N_int_t = N
if N_L2_int_x is None:
N_L2_int_x = N
if N_L2_int_y is None:
N_L2_int_y = N
if N_L2_int_t is None:
N_L2_int_t = N
# Create auxiliary solver: the same args as the top_solver but update orders
aux_kwargs = self.top_solver.kwargs
aux_kwargs["N"] = N
# Order of mass matrix integration
aux_kwargs["N_int_x"] = N_int_x
aux_kwargs["N_int_y"] = N_int_y
aux_kwargs["N_int_t"] = N_int_t
if self.type == 'SE':
aux_solver = Solver(self.top_solver.problem_id, self.top_solver.sparse, verbose=verbose, **aux_kwargs)
# Solve with solver
aux_solver.solve_system(verbose=False)
else:
aux_solver = MESolver(self.top_solver.problem_id, K, self.top_solver.sparse, verbose=verbose, **aux_kwargs)
# Solve with solver
aux_solver.solve(verbose=False)
# Metric to be used in L2 INTEGRATION
metric = Metric(N, N_L2_int_x, N_L2_int_y, N_L2_int_t, self.top_problem.c, self.top_problem.r, self.top_problem.d_map, self.top_problem.t_map)
# Retrieve mappings
d_map = metric.d_map
t_map = metric.t_map
# Generate unit integration grid
xi_int_grid, tau_int_grid, eta_int_grid = np.meshgrid(metric.GL_int_x, metric.GL_int_y, metric.GL_int_t)
mesh_xieta_int = np.meshgrid(metric.GL_int_x, metric.GL_int_y)
x_int_grid = d_map.x(xi_int_grid, eta_int_grid)
y_int_grid = d_map.y(xi_int_grid, eta_int_grid)
t_int_grid = t_map.t(tau_int_grid)
# Evaluate transformation metrics at unit integration nodes
X_XI_INT = d_map.x_xi(xi_int_grid, eta_int_grid)
X_ETA_INT = d_map.x_eta(xi_int_grid, eta_int_grid)
Y_XI_INT = d_map.y_xi(xi_int_grid, eta_int_grid)
Y_ETA_INT = d_map.y_eta(xi_int_grid, eta_int_grid)
T_TAU_INT = t_map.t_tau(tau_int_grid)
# The Jacobian evaluated at integration nodes
J_INT = T_TAU_INT * (X_XI_INT * Y_ETA_INT - Y_XI_INT * X_ETA_INT)
div_h = aux_solver.reconstruct_div(mesh_xieta_int, t_map.t(metric.GL_int_t), verbose=False) # solve for z DOFs
div_h = div_h.reshape(N_L2_int_y + 1, N_L2_int_x + 1, -1)
# Compute the difference squared with Jacobian
d_sq = np.power(div_h, 2)
# Integrate
I = np.einsum('ijk,i,j,k->', d_sq * J_INT, metric.weights_int_y, metric.weights_int_x, metric.weights_int_t, optimize='greedy')
# Return the value sqrt and Linf
return np.sqrt(I), np.max(np.abs(div_h))
# Private method for one-time evaluation of condition number
def __compute_condition_number(self, \
N: int, \
K: Union[int, None]=None, \
N_int_x: Union[int, None]=None, N_int_y: Union[int, None]=None, N_int_t: Union[int, None]=None, \
N_L2_int_x: Union[int, None]=None, N_L2_int_y: Union[int, None]=None, N_L2_int_t: Union[int, None]=None, \
mode: Literal['min', 'avg', 'max']='max', \
verbose: bool=False \
) -> float:
# Assure that N is alway given
if N is None:
raise ValueError("N parameter must be provided.")
# Assure that the exact solution exists in the problem (not None)
if self.top_problem.zw_exact is None:
raise ValueError("The exact solution of the problem zw_exact must be provided (not None).")
# If single element solver is used, the K parameter must be None
if self.type == 'SE' and K is not None:
raise ValueError("K parameter must be left at None when using single element solver.")
# If multiple element solver is used, the K parameter must be provided
if self.type == 'ME' and K is None:
raise ValueError("K parameter must be provided by keyword K when using multi element solver.")
# Check if any requirements were made regarding the orders
if N_int_x is None:
N_int_x = N
if N_int_y is None:
N_int_y = N
if N_int_t is None:
N_int_t = N
if N_L2_int_x is None:
N_L2_int_x = N
if N_L2_int_y is None:
N_L2_int_y = N
if N_L2_int_t is None:
N_L2_int_t = N
# Create auxiliary solver: the same args as the top_solver but update orders
aux_kwargs = self.top_solver.kwargs
aux_kwargs["N"] = N
# Order of mass matrix integration
aux_kwargs["N_int_x"] = N_int_x
aux_kwargs["N_int_y"] = N_int_y
aux_kwargs["N_int_t"] = N_int_t
if self.type == 'SE':
aux_solver = Solver(self.top_solver.problem_id, self.top_solver.sparse, verbose=verbose, **aux_kwargs)
# Solve with solver
aux_solver.solve_system(verbose=False)
else:
aux_solver = MESolver(self.top_solver.problem_id, K, self.top_solver.sparse, verbose=verbose, **aux_kwargs)
# Solve with solver
aux_solver.solve(verbose=False)
if mode == 'min':
return np.min(aux_solver.get_condition_number())
elif mode == 'avg':
return np.mean(aux_solver.get_condition_number())
elif mode == 'max':
return np.max(aux_solver.get_condition_number())
# Public method for L2 error for zw
def compute_L2Linf_zw_h(self, \
dual: bool, \
N: Union[int, tuple, list, np.ndarray], \
K: Union[int, tuple, list, np.ndarray, None], \
DN_int_x: int, DN_int_y: int, DN_int_t: int, \
DN_L2_int_x: int, DN_L2_int_y: int, DN_L2_int_t: int, \
regression: bool=True
) -> tuple:
# If multiple element solver is used, the K parameter must be provided'
if self.type == 'ME' and K is None:
raise ValueError("K parameter must be provided when using multi element solver.")
# If single element solver is used, the K parameter must be None
if self.type == 'SE' and K is not None:
raise ValueError("K parameter must be left at None when using single element solver.")
# Convert the N list to np.ndarray
if isinstance(N, int):
N = np.array([N])
elif isinstance(N, list):
N = np.array(N)
elif isinstance(N, tuple):
N = np.array(N)
elif isinstance(N, range):
N = np.array(list(N))
# Convert the K list to np.ndarray
if isinstance(K, int):
K = np.array([K])
elif isinstance(K, list):
K = np.array(K)
elif isinstance(K, tuple):
K = np.array(K)
elif isinstance(K, range):
K = np.array(list(K))
# Prelocate memory
eL2 = np.zeros(shape = (len(K), len(N)) if K is not None else (1, len(N)), dtype=float)
eLinf = np.zeros(shape = (len(K), len(N)) if K is not None else (1, len(N)), dtype=float)
# Compute the array of L2s corresponding to each N-option
print("Computing L2 errors (by definition) for...")
for i in range(eL2.shape[0]):
for j in range(eL2.shape[1]):
n = N[j]
k = K[i] if K is not None else None
print(f"N = {n}, K = {k}")
l2, linf = self.__compute_L2Linf_zw_h_def(dual, n, k, \
n + DN_int_x, n + DN_int_y, \
n + DN_int_t, n + DN_L2_int_x, n + DN_L2_int_y, n + DN_L2_int_t, \
verbose=False)
eL2[i, j] = l2
eLinf[i, j] = linf
print(f"N = {n}, K = {k}: eL2 = {l2}\n")
# If the number of points in K or N directions are at least 2, perform regression on each dimension
if regression:
if len(N) > 1:
reg_arr_L2 = np.empty(len(K), dtype=object)
reg_arr_Linf = np.empty(len(K), dtype=object)
for i in range(len(K)):
reg_arr_L2[i] = LinearRegression().fit(N.reshape(-1, 1), np.log10(eL2[i, :]))
reg_arr_Linf[i] = LinearRegression().fit(N.reshape(-1, 1), np.log10(eLinf[i, :]))
return eL2, eLinf, reg_arr_L2, reg_arr_Linf
return eL2, eLinf, None, None
# Public method for L2 error for div
def compute_L2Linf_div_h(self, \
N: Union[int, tuple, list, np.ndarray], \
K: Union[int, tuple, list, np.ndarray, None], \
DN_int_x: int, DN_int_y: int, DN_int_t: int, \
DN_L2_int_x: int, DN_L2_int_y: int, DN_L2_int_t: int, \
regression: bool=True
) -> tuple:
# If multiple element solver is used, the K parameter must be provided'
if self.type == 'ME' and K is None:
raise ValueError("K parameter must be provided when using multi element solver.")
# If single element solver is used, the K parameter must be None
if self.type == 'SE' and K is not None:
raise ValueError("K parameter must be left at None when using single element solver.")
# Convert the N list to np.ndarray
if isinstance(N, int):
N = np.array([N])
elif isinstance(N, list):
N = np.array(N)
elif isinstance(N, tuple):
N = np.array(N)
elif isinstance(N, range):
N = np.array(list(N))
# Convert the K list to np.ndarray
if isinstance(K, int):
K = np.array([K])
elif isinstance(K, list):
K = np.array(K)
elif isinstance(K, tuple):
K = np.array(K)
elif isinstance(K, range):
K = np.array(list(K))
# Prelocate memory
eL2 = np.zeros(shape = (len(K), len(N)) if K is not None else (1, len(N)), dtype=float)
eLinf = np.zeros(shape = (len(K), len(N)) if K is not None else (1, len(N)), dtype=float)
# Compute the array of L2s corresponding to each N-option
print("Computing L2, Linf errors (by definition) for...")
for i in range(eL2.shape[0]):
for j in range(eL2.shape[1]):
n = N[j]
k = K[i] if K is not None else None
print(f"N = {n}, K = {k}")
l2, linf = self.__compute_L2Linf_div_h_def(n, k, \
n + DN_int_x, n + DN_int_y, \
n + DN_int_t, n + DN_L2_int_x, n + DN_L2_int_y, n + DN_L2_int_t, \
verbose=False)
eL2[i, j] = l2
eLinf[i, j] = linf
print(f"N = {n}, K = {k}: eL2 = {l2}, eLinf = {linf}\n")
return eL2, eLinf
# Public method for condition number
def compute_condition_number(self, \
N: Union[int, tuple, list, np.ndarray], \
K: Union[int, tuple, list, np.ndarray, None], \
DN_int_x: int, DN_int_y: int, DN_int_t: int, \
DN_L2_int_x: int, DN_L2_int_y: int, DN_L2_int_t: int, \
mode: Literal['min', 'avg', 'max']='max' \
) -> np.ndarray:
# If multiple element solver is used, the K parameter must be provided'
if self.type == 'ME' and K is None:
raise ValueError("K parameter must be provided when using multi element solver.")
# If single element solver is used, the K parameter must be None
if self.type == 'SE' and K is not None:
raise ValueError("K parameter must be left at None when using single element solver.")
# Convert the N list to np.ndarray
if isinstance(N, int):
N = np.array([N])
elif isinstance(N, list):
N = np.array(N)
elif isinstance(N, tuple):
N = np.array(N)
elif isinstance(N, range):
N = np.array(list(N))
# Convert the K list to np.ndarray
if isinstance(K, int):
K = np.array([K])
elif isinstance(K, list):
K = np.array(K)
elif isinstance(K, tuple):
K = np.array(K)
elif isinstance(K, range):
K = np.array(list(K))
# Prelocate memory
CN = np.zeros(shape = (len(K), len(N)) if K is not None else (1, len(N)), dtype=float)
# Compute the array of L2s corresponding to each N-option
print("Computing condition numbers for...")
for i in range(CN.shape[0]):
for j in range(CN.shape[1]):
n = N[j]
k = K[i] if K is not None else None
print(f"N = {n}, K = {k}")
cn = self.__compute_condition_number(n, k, \
n + DN_int_x, n + DN_int_y, \
n + DN_int_t, n + DN_L2_int_x, n + DN_L2_int_y, n + DN_L2_int_t, \
mode=mode, \
verbose=False)
CN[i, j] = cn
print(f"N = {n}, K = {k}: condition number = {cn}\n")
return CN
# Deprecated method
def __depr_compute_L2_zw_h_M0(self, \
dual: bool, \
N: int, \
N_int: Union[None, int], \
zw_exact: Callable, \
verbose: bool=False \
) -> float:
# Create auxiliary solver: the same args as the top_solver but update orders
aux_kwargs = self.top_solver.kwargs
aux_kwargs["N"] = N
aux_kwargs["N_int_x"] = N
aux_kwargs["N_int_y"] = N
aux_kwargs["N_int_t"] = N
aux_solver = Solver(self.top_solver.problem_id, self.top_solver.sparse, verbose=verbose, **aux_kwargs)
metric = Metric(N_int, N_int, N_int, N_int, aux_solver.problem.c, aux_solver.problem.r, aux_solver.problem.d_map, aux_solver.problem.t_map)
# Retrieve mappings
d_map = metric.d_map
t_map = metric.t_map
# Generate unit integration grid
xi_int_grid, tau_int_grid, eta_int_grid = np.meshgrid(metric.GL_int_x, metric.GL_int_y, metric.GL_int_t)
mesh_xieta_int = np.meshgrid(metric.GL_int_x, metric.GL_int_y)
x_int_grid = d_map.x(xi_int_grid, eta_int_grid)
y_int_grid = d_map.y(xi_int_grid, eta_int_grid)
t_int_grid = t_map.t(tau_int_grid)
# Solve with solver
aux_solver.solve_system(verbose)
if dual:
z_h = aux_solver.reconstruct_w(mesh_xieta_int, t_map.t(metric.GL_int_t), verbose=False) # solve for w DOFs
else:
z_h = aux_solver.reconstruct_z(mesh_xieta_int, t_map.t(metric.GL_int_t), verbose=False) # solve for z DOFs
# Evaluate the exact solution at integration nodes
zw_ex_evaluated = zw_exact(x_int_grid, y_int_grid, t_int_grid)
# get M0
M0 = metric.M_0(False)
# Error vector
e = (zw_ex_evaluated - z_h).reshape(-1)
# Integrate the error squared
I = e.T @ M0 @ e
# Return the value sqrt
return np.sqrt(I)
def compute_energy(self, t: Union[float, np.ndarray, list], \
N_int_x: Union[None, int]=None, N_int_y: Union[None, int]=None, \
verbose: bool=False):
# Inform
print("Computing total energy...\n")
# Get the top problem
top_problem = self.top_problem
top_solver = self.top_solver
# Check if the system is solved. If not -- solve it
if self.type == 'SE':
if top_solver.get_solution() is None:
top_solver.solve_system(verbose=False)
else:
if top_solver.solver_chain is None:
top_solver.solve(verbose=False)
# Assign appropriate integration orders
if N_int_x is None:
N_int_x = top_problem.N_int_x
if N_int_y is None:
N_int_y = top_problem.N_int_y
# Process the time slices
if not (isinstance(t, float) or isinstance(t, np.ndarray) or isinstance(t, list)):
raise ValueError("The 't' arguments (time slices) must be either of type float, np.ndarray or list.")
if isinstance(t, float):
t = np.array([t])
elif isinstance(t, list):
t = np.array(t)
# Get the integration weights and integration points
GL_int_x, weights_int_x = lobatto_quad(N_int_x)
GL_int_y, weights_int_y = lobatto_quad(N_int_y)
# Make the reconstruction integration mesh grid
mesh_grid_xieta_rec_int = np.meshgrid(GL_int_x, GL_int_y)
# Reconstruct physical quantities
sigma_kx = top_solver.reconstruct_sigma_kx(mesh_grid_xieta_rec_int, t, verbose=verbose)
sigma_ky = top_solver.reconstruct_sigma_ky(mesh_grid_xieta_rec_int, t, verbose=verbose)
pi = top_solver.reconstruct_pi(mesh_grid_xieta_rec_int, t, verbose=verbose)
# Compute the total energy at all time slices
e_pot = 0.5 * (sigma_kx ** 2 + sigma_ky ** 2)
e_kin = 0.5 * pi ** 2
e_tot = e_pot + e_kin
# Integrate the energy for each time slice
e_pot = np.einsum('ijk,k,j->i', e_pot, weights_int_x, weights_int_y)
e_kin = np.einsum('ijk,k,j->i', e_kin, weights_int_x, weights_int_y)
e_tot = np.einsum('ijk,k,j->i', e_tot, weights_int_x, weights_int_y)
# All done
return e_pot, e_kin, e_tot
def plot_abs_spat_ptwise_error_zw_h(self, \
dual: bool, \
t: float, \
N: int, K: int, \
DN_int_x: int, DN_int_y: int, DN_int_t: int, \
N_res_x: int, N_res_y: int, \
adjust_font: bool=False, \
show: bool=True, save_name: Union[str, None]=None):
# Adjust the font
if adjust_font:
PlotterHelper.adjust_font()
# Get colors, markers and markersize
my_colors, _, _ = PlotterHelper.get_colors_markers_markersize()
# Get the error
abs_ptwse_err = self.__compute_abs_spat_ptwise_error_zw_h(dual, t, N, K, DN_int_x, DN_int_y, DN_int_t, N_res_x, N_res_y)
# Convert to log10
abs_ptwse_err = np.log10(abs_ptwse_err)
# Create the figure and axis
fig, ax = plt.subplots(figsize=PlotterHelper.get_figsize())
# Plot the mesh
N = self.top_problem.N
self.top_problem.d_map.plot(N, N, color='white', linewidth=0.5, linestyle='--', alpha=0.3, ax=ax)
# Create the color map
cvals = [-7.921232099848884, -1.511745683812782]
colors = [my_colors[0], my_colors[3]]
norm=plt.Normalize(min(cvals), max(cvals))
tuples = list(zip(map(norm,cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
# min max for zw, t 1, 2
# min = -8.914516222598609
# max = -1.1799912639273973
# print(f"min = {np.min(abs_ptwse_err)}, max = {np.max(abs_ptwse_err)}")
# Plot the 2D array using imshow
cax = ax.imshow(abs_ptwse_err, cmap=cmap, norm=norm, interpolation='bilinear', extent=[-1, 1, -1, 1])
# Create a divider for the existing axis
# divider = make_axes_locatable(ax)
# # Append a new axis to the right of the current axis, for the colorbar
# cax_cb = divider.append_axes("right", size="5%", pad=0.05)
# ticks = np.linspace(np.min(abs_ptwse_err), np.max(abs_ptwse_err), 4)
# ticks = np.ceil(ticks)
# ticks.astype(int)
cbar = fig.colorbar(cax, fraction=0.05) # Add a colorbar to show the color scale
cbar.set_label(r'$\log_{10} \left( \left| w^{ex} - w^{h} \right| \right)$')
# cbar.set_ticks(ticks)
# Adding titles and labels
ax.set_xlabel(r'$\xi$')
ax.set_ylabel(r'$\eta$')
ax.set_xticks([-1, 0, 1])
ax.set_yticks([-1, 0, 1])
# Tight layout
plt.tight_layout()
# Showing and saving
if save_name is not None:
plt.savefig('res//log_e_w//' + save_name)
if show:
plt.show()
def plot_abs_spat_ptwise_error_pi_h(self, \
t: float, \
N: int, K: int, \
DN_int_x: int, DN_int_y: int, DN_int_t: int, \
N_res_x: int, N_res_y: int, \
adjust_font: bool=False, \
show: bool=True, save_name: Union[str, None]=None):
# Adjust the font
if adjust_font:
PlotterHelper.adjust_font()
# Get colors, markers and markersize
my_colors, _, _ = PlotterHelper.get_colors_markers_markersize()
# Get the error
abs_ptwse_err = self.__compute_abs_spat_ptwise_error_pi_h(t, N, K, DN_int_x, DN_int_y, DN_int_t, N_res_x, N_res_y)
# Convert to log10
abs_ptwse_err = np.log10(abs_ptwse_err)
# Create the figure and axis
fig, ax = plt.subplots(figsize=PlotterHelper.get_figsize())
# Plot the mesh
N = self.top_problem.N
self.top_problem.d_map.plot(N, N, color='white', linewidth=0.5, linestyle='--', alpha=0.3, ax=ax)
# Create the color map
cvals = [-6.653250879972099, -0.40260578508545425]
colors = [my_colors[0], my_colors[3]]
# min max for pi
# min = -7.1277045320496395
# max = 0.44079439027450185
# print(f"min = {np.min(abs_ptwse_err)}, max = {np.max(abs_ptwse_err)}")
norm=plt.Normalize(min(cvals), max(cvals))
tuples = list(zip(map(norm,cvals), colors))
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", tuples)
# Plot the 2D array using imshow
cax = ax.imshow(abs_ptwse_err, cmap=cmap, norm=norm, interpolation='bilinear', extent=[-1, 1, -1, 1])
# Create a divider for the existing axis
# divider = make_axes_locatable(ax)
# # Append a new axis to the right of the current axis, for the colorbar
# cax_cb = divider.append_axes("right", size="5%", pad=0.05)
# ticks = np.linspace(np.min(abs_ptwse_err), np.max(abs_ptwse_err), 4)
# ticks = np.ceil(ticks)
# ticks.astype(int)
cbar = fig.colorbar(cax, fraction=0.05) # Add a colorbar to show the color scale
cbar.set_label(r'$\log_{10} \left( \left| {\pi}^{ex} - {\pi}^{h} \right| \right)$')
# cbar.set_ticks(ticks)
# Adding titles and labels
ax.set_xlabel(r'$\xi$')
ax.set_ylabel(r'$\eta$')
ax.set_xticks([-1, 0, 1])
ax.set_yticks([-1, 0, 1])
# Tight layout
plt.tight_layout()
# Showing and saving
if save_name is not None:
plt.savefig('res//log_e_pi//' + save_name)
if show:
plt.show()
def plot_L2Linf_zw_h(self, dual: bool, \