-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctionsFigure2DGenerator.py
More file actions
executable file
·1379 lines (1199 loc) · 54.8 KB
/
functionsFigure2DGenerator.py
File metadata and controls
executable file
·1379 lines (1199 loc) · 54.8 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
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright 2023-2024 TotalEnergies.
# SPDX-FileContributor: Alexandre Benedicto
import math
from typing import Any
import matplotlib.pyplot as plt # type: ignore[import-untyped]
import numpy as np
import numpy.typing as npt
import pandas as pd # type: ignore[import-untyped]
from matplotlib import axes, figure, lines # type: ignore[import-untyped]
from matplotlib.font_manager import ( # type: ignore[import-untyped]
FontProperties, # type: ignore[import-untyped]
)
import geos.pv.geosLogReaderUtils.geosLogReaderFunctions as fcts
"""
Plotting tools for 2D figure and axes generation.
"""
def oneSubplot(
df: pd.DataFrame,
userChoices: dict[ str, Any ] ) -> tuple[ figure.Figure, list[ axes.Axes ], list[ lines.Line2D ], list[ str ] ]:
"""Created a single subplot.
From a dataframe, knowing which curves to plot along which variable,
generates a fig and its list of axes with the data plotted.
Args:
df (pd.DataFrame): Dataframe containing at least two columns,
one named "variableName" and the other "curveName".
userChoices (dict[str, Any]): Choices made by widget selection
in PythonViewConfigurator filter.
Returns:
tuple(figure.Figure, list[axes.Axes],
list[lines.Line2D] , list[str]): The fig and its list of axes.
"""
curveNames: list[ str ] = userChoices[ "curveNames" ]
variableName: str = userChoices[ "variableName" ]
curvesAspect: dict[ str, tuple[ tuple[ float, float, float ], str, float, str,
float ] ] = userChoices[ "curvesAspect" ]
associatedProperties: dict[ str, list[ str ] ] = associatePropertyToAxeType( curveNames )
fig, ax = plt.subplots( constrained_layout=True )
all_ax: list[ axes.Axes ] = setupAllAxes( ax, variableName, associatedProperties, True )
lineList: list[ lines.Line2D ] = []
labels: list[ str ] = []
cpt_cmap: int = 0
x: npt.NDArray[ np.float64 ] = df[ variableName ].to_numpy()
for cpt_ax, ( ax_name, propertyNames ) in enumerate( associatedProperties.items() ):
ax_to_use: axes.Axes = setupAxeToUse( all_ax, cpt_ax, ax_name, False )
for propName in propertyNames:
y: npt.NDArray[ np.float64 ] = df[ propName ].to_numpy()
plotAxe( ax_to_use, x, y, propName, cpt_cmap, curvesAspect )
cpt_cmap += 1
new_lines, new_labels = ax_to_use.get_legend_handles_labels()
lineList += new_lines # type: ignore[arg-type]
labels += new_labels
labels, lineList = smartLabelsSorted( labels, lineList, userChoices )
if userChoices[ "displayLegend" ]:
ax.legend(
lineList,
labels,
loc=userChoices[ "legendPosition" ],
fontsize=userChoices[ "legendSize" ],
)
ax.grid()
return ( fig, all_ax, lineList, labels )
def oneSubplotInverted(
df: pd.DataFrame,
userChoices: dict[ str, Any ] ) -> tuple[ figure.Figure, list[ axes.Axes ], list[ lines.Line2D ], list[ str ] ]:
"""Created a single subplot with inverted X Y axes.
From a dataframe, knowing which curves to plot along which variable,
generates a fig and its list of axes with the data plotted.
Args:
df (pd.DataFrame): Dataframe containing at least two columns,
one named "variableName" and the other "curveName".
userChoices (dict[str, Any]): Choices made by widget selection
in PythonViewConfigurator filter.
Returns:
tuple(figure.Figure, list[axes.Axes],
list[lines.Line2D] , list[str]): The fig and its list of axes.
"""
curveNames: list[ str ] = userChoices[ "curveNames" ]
variableName: str = userChoices[ "variableName" ]
curvesAspect: dict[ str, tuple[ tuple[ float, float, float ], str, float, str,
float ] ] = userChoices[ "curvesAspect" ]
associatedProperties: dict[ str, list[ str ] ] = associatePropertyToAxeType( curveNames )
fig, ax = plt.subplots( constrained_layout=True )
all_ax: list[ axes.Axes ] = setupAllAxes( ax, variableName, associatedProperties, False )
linesList: list[ lines.Line2D ] = []
labels: list[ str ] = []
cpt_cmap: int = 0
y: npt.NDArray[ np.float64 ] = df[ variableName ].to_numpy()
for cpt_ax, ( ax_name, propertyNames ) in enumerate( associatedProperties.items() ):
ax_to_use: axes.Axes = setupAxeToUse( all_ax, cpt_ax, ax_name, True )
for propName in propertyNames:
x: npt.NDArray[ np.float64 ] = df[ propName ].to_numpy()
plotAxe( ax_to_use, x, y, propName, cpt_cmap, curvesAspect )
cpt_cmap += 1
new_lines, new_labels = ax_to_use.get_legend_handles_labels()
linesList += new_lines # type: ignore[arg-type]
labels += new_labels
labels, linesList = smartLabelsSorted( labels, linesList, userChoices )
if userChoices[ "displayLegend" ]:
ax.legend(
linesList,
labels,
loc=userChoices[ "legendPosition" ],
fontsize=userChoices[ "legendSize" ],
)
ax.grid()
return ( fig, all_ax, linesList, labels )
def multipleSubplots(
df: pd.DataFrame,
userChoices: dict[ str, Any ] ) -> tuple[ figure.Figure, list[ axes.Axes ], list[ lines.Line2D ], list[ str ] ]:
"""Created multiple subplots.
From a dataframe, knowing which curves to plot along which variable,
generates a fig and its list of axes with the data plotted.
Args:
df (pd.DataFrame): Dataframe containing at least two columns,
one named "variableName" and the other "curveName".
userChoices (dict[str, Any]): Choices made by widget selection
in PythonViewConfigurator filter.
Returns:
tuple(figure.Figure, list[axes.Axes],
list[lines.Line2D] , list[str]): The fig and its list of axes.
"""
curveNames: list[ str ] = userChoices[ "curveNames" ]
variableName: str = userChoices[ "variableName" ]
curvesAspect: dict[ str, tuple[ tuple[ float, float, float ], str, float, str,
float ] ] = userChoices[ "curvesAspect" ]
ratio: float = userChoices[ "ratio" ]
assosIdentifiers: dict[ str, dict[ str, list[ str ] ] ] = associationIdentifiers( curveNames )
nbr_suplots: int = len( assosIdentifiers.keys() )
# if only one subplots needs to be created
if nbr_suplots == 1:
return oneSubplot( df, userChoices )
layout: tuple[ int, int, int ] = smartLayout( nbr_suplots, ratio )
fig, axs0 = plt.subplots( layout[ 0 ], layout[ 1 ], constrained_layout=True )
axs: list[ axes.Axes ] = axs0.flatten().tolist() # type: ignore[union-attr]
for i in range( layout[ 2 ] ):
fig.delaxes( axs[ -( i + 1 ) ] )
all_lines: list[ lines.Line2D ] = []
all_labels: list[ str ] = []
# first loop for subplots
propertiesExtremas: dict[ str, tuple[ float, float ] ] = ( findExtremasPropertiesForAssociatedIdentifiers(
df, assosIdentifiers, True ) )
for j, identifier in enumerate( assosIdentifiers.keys() ):
first_ax: axes.Axes = axs[ j ]
associatedProperties: dict[ str, list[ str ] ] = assosIdentifiers[ identifier ]
all_ax: list[ axes.Axes ] = setupAllAxes( first_ax, variableName, associatedProperties, True )
axs += all_ax[ 1: ]
linesList: list[ lines.Line2D ] = []
labels: list[ str ] = []
cpt_cmap: int = 0
x: npt.NDArray[ np.float64 ] = df[ variableName ].to_numpy()
# second loop for axes per subplot
for cpt_ax, ( ax_name, propertyNames ) in enumerate( associatedProperties.items() ):
ax_to_use: axes.Axes = setupAxeToUse( all_ax, cpt_ax, ax_name, False )
for propName in propertyNames:
y: npt.NDArray[ np.float64 ] = df[ propName ].to_numpy()
plotAxe( ax_to_use, x, y, propName, cpt_cmap, curvesAspect )
ax_to_use.set_ylim( *propertiesExtremas[ ax_name ] )
cpt_cmap += 1
new_lines, new_labels = ax_to_use.get_legend_handles_labels()
linesList += new_lines # type: ignore[arg-type]
all_lines += new_lines # type: ignore[arg-type]
labels += new_labels
all_labels += new_labels
labels, linesList = smartLabelsSorted( labels, linesList, userChoices )
if userChoices[ "displayLegend" ]:
first_ax.legend(
linesList,
labels,
loc=userChoices[ "legendPosition" ],
fontsize=userChoices[ "legendSize" ],
)
if userChoices[ "displayTitle" ]:
first_ax.set_title( identifier, fontsize=10 )
first_ax.grid()
return ( fig, axs, all_lines, all_labels )
def multipleSubplotsInverted(
df: pd.DataFrame,
userChoices: dict[ str, Any ] ) -> tuple[ figure.Figure, list[ axes.Axes ], list[ lines.Line2D ], list[ str ] ]:
"""Created multiple subplots with inverted X Y axes.
From a dataframe, knowing which curves to plot along which variable,
generates a fig and its list of axes with the data plotted.
Args:
df (pd.DataFrame): Dataframe containing at least two columns,
one named "variableName" and the other "curveName".
userChoices (dict[str, Any]): Choices made by widget selection
in PythonViewConfigurator filter.
Returns:
tuple(figure.Figure, list[axes.Axes],
list[lines.Line2D] , list[str]): The fig and its list of axes.
"""
curveNames: list[ str ] = userChoices[ "curveNames" ]
variableName: str = userChoices[ "variableName" ]
curvesAspect: dict[ str, tuple[ tuple[ float, float, float ], str, float, str,
float ] ] = userChoices[ "curvesAspect" ]
ratio: float = userChoices[ "ratio" ]
assosIdentifiers: dict[ str, dict[ str, list[ str ] ] ] = associationIdentifiers( curveNames )
nbr_suplots: int = len( assosIdentifiers.keys() )
# If only one subplots needs to be created.
if nbr_suplots == 1:
return oneSubplotInverted( df, userChoices )
layout: tuple[ int, int, int ] = smartLayout( nbr_suplots, ratio )
fig, axs0 = plt.subplots( layout[ 0 ], layout[ 1 ], constrained_layout=True )
axs: list[ axes.Axes ] = axs0.flatten().tolist() # type: ignore[union-attr]
for i in range( layout[ 2 ] ):
fig.delaxes( axs[ -( i + 1 ) ] )
all_lines: list[ lines.Line2D ] = []
all_labels: list[ str ] = []
# First loop for subplots.
propertiesExtremas: dict[ str, tuple[ float, float ] ] = ( findExtremasPropertiesForAssociatedIdentifiers(
df, assosIdentifiers, True ) )
for j, identifier in enumerate( assosIdentifiers.keys() ):
first_ax: axes.Axes = axs[ j ]
associatedProperties: dict[ str, list[ str ] ] = assosIdentifiers[ identifier ]
all_ax: list[ axes.Axes ] = setupAllAxes( first_ax, variableName, associatedProperties, False )
axs += all_ax[ 1: ]
linesList: list[ lines.Line2D ] = []
labels: list[ str ] = []
cpt_cmap: int = 0
y: npt.NDArray[ np.float64 ] = df[ variableName ].to_numpy()
# Second loop for axes per subplot.
for cpt_ax, ( ax_name, propertyNames ) in enumerate( associatedProperties.items() ):
ax_to_use: axes.Axes = setupAxeToUse( all_ax, cpt_ax, ax_name, True )
for propName in propertyNames:
x: npt.NDArray[ np.float64 ] = df[ propName ].to_numpy()
plotAxe( ax_to_use, x, y, propName, cpt_cmap, curvesAspect )
ax_to_use.set_xlim( propertiesExtremas[ ax_name ] )
cpt_cmap += 1
new_lines, new_labels = ax_to_use.get_legend_handles_labels()
linesList += new_lines # type: ignore[arg-type]
all_lines += new_lines # type: ignore[arg-type]
labels += new_labels
all_labels += new_labels
labels, linesList = smartLabelsSorted( labels, linesList, userChoices )
if userChoices[ "displayLegend" ]:
first_ax.legend(
linesList,
labels,
loc=userChoices[ "legendPosition" ],
fontsize=userChoices[ "legendSize" ],
)
if userChoices[ "displayTitle" ]:
first_ax.set_title( identifier, fontsize=10 )
first_ax.grid()
return ( fig, axs, all_lines, all_labels )
def setupAllAxes(
first_ax: axes.Axes,
variableName: str,
associatedProperties: dict[ str, list[ str ] ],
axisX: bool,
) -> list[ axes.Axes ]:
"""Modify axis name and ticks with X or Y axis of all subplots.
Args:
first_ax (axes.Axes): Subplot id.
variableName (str): Name of the axis.
associatedProperties (dict[str, list[str]]): Name of the properties.
axisX (bool): X (True) or Y (False) axis to modify.
Returns:
list[axes.Axes]: Modified subplots.
"""
all_ax: list[ axes.Axes ] = [ first_ax ]
if axisX:
first_ax.set_xlabel( variableName )
first_ax.ticklabel_format( style="sci", axis="x", scilimits=( 0, 0 ), useMathText=True )
for i in range( 1, len( associatedProperties.keys() ) ):
second_ax = first_ax.twinx()
if not isinstance( second_ax, axes.Axes ):
raise TypeError( "The second ax has not the right type.")
all_ax.append( second_ax )
all_ax[ i ].spines[ "right" ].set_position( ( "axes", 1 + 0.07 * ( i - 1 ) ) )
all_ax[ i ].tick_params( axis="y", which="both", left=False, right=True )
all_ax[ i ].yaxis.set_ticks_position( "right" )
all_ax[ i ].yaxis.offsetText.set_position( ( 1.04 + 0.07 * ( i - 1 ), 0 ) )
first_ax.yaxis.offsetText.set_position( ( -0.04, 0 ) )
else:
first_ax.set_ylabel( variableName )
first_ax.ticklabel_format( style="sci", axis="y", scilimits=( 0, 0 ), useMathText=True )
for i in range( 1, len( associatedProperties.keys() ) ):
second_ax = first_ax.twiny()
if not isinstance( second_ax, axes.Axes ):
raise TypeError( "The second ax has not the right type.")
all_ax.append( second_ax )
all_ax[ i ].spines[ "bottom" ].set_position( ( "axes", -0.08 * i ) )
all_ax[ i ].xaxis.set_label_position( "bottom" )
all_ax[ i ].tick_params( axis="x", which="both", bottom=True, top=False )
all_ax[ i ].xaxis.set_ticks_position( "bottom" )
return all_ax
def setupAxeToUse( all_ax: list[ axes.Axes ], axeId: int, ax_name: str, axisX: bool ) -> axes.Axes:
"""Modify axis name and ticks with X or Y axis of subplot axeId in all_ax.
Args:
all_ax (list[axes.Axes]): List of all subplots.
axeId (int): Id of the subplot.
ax_name (str): Name of the X or Y axis.
axisX (bool): X (True) or Y (False) axis to modify.
Returns:
axes.Axes: Modified subplot.
"""
ax_to_use: axes.Axes = all_ax[ axeId ]
if axisX:
ax_to_use.set_xlabel( ax_name )
ax_to_use.ticklabel_format( style="sci", axis="x", scilimits=( 0, 0 ), useMathText=True )
else:
ax_to_use.set_ylabel( ax_name )
ax_to_use.ticklabel_format( style="sci", axis="y", scilimits=( 0, 0 ), useMathText=True )
return ax_to_use
def plotAxe(
ax_to_use: axes.Axes,
x: npt.NDArray[ np.float64 ],
y: npt.NDArray[ np.float64 ],
propertyName: str,
cpt_cmap: int,
curvesAspect: dict[ str, tuple[ tuple[ float, float, float ], str, float, str, float ] ],
) -> None:
"""Plot x, y data using input ax_to_use according to curvesAspect.
Args:
ax_to_use (axes.Axes): Subplot to use.
x (npt.NDArray[np.float64]): Abscissa data.
y (npt.NDArray[np.float64]): Ordinate data.
propertyName (str): Name of the property.
cpt_cmap (int): Colormap to use.
curvesAspect (dict[str, tuple[tuple[float, float, float],str, float, str, float]]):
User choices on curve aspect.
"""
cmap = plt.rcParams[ "axes.prop_cycle" ].by_key()[ "color" ][ cpt_cmap % 10 ]
mask = np.logical_and( np.isnan( x ), np.isnan( y ) )
not_mask = ~mask
# Plot only when x and y values are not nan values.
if propertyName in curvesAspect:
asp: tuple[ tuple[ float, float, float ], str, float, str, float ] = curvesAspect[ propertyName ]
ax_to_use.plot(
x[ not_mask ],
y[ not_mask ],
label=propertyName,
color=asp[ 0 ],
linestyle=asp[ 1 ],
linewidth=asp[ 2 ],
marker=asp[ 3 ],
markersize=asp[ 4 ],
)
else:
ax_to_use.plot( x[ not_mask ], y[ not_mask ], label=propertyName, color=cmap )
def getExtremaAllAxes( axes: list[ axes.Axes ], ) -> tuple[ tuple[ float, float ], tuple[ float, float ] ]:
"""Gets the limits of both X and Y axis as a 2x2 element tuple.
Args:
axes (list[axes.Axes]): List of subplots to get limits.
Returns:
tuple[tuple[float, float], tuple[float, float]]: ((xMin, xMax), (yMin, yMax))
"""
if len( axes ) <= 0:
raise ValueError( "The list of axes can not be empty.")
xMin, xMax, yMin, yMax = getAxeLimits( axes[ 0 ] )
if len( axes ) > 1:
for i in range( 1, len( axes ) ):
x1, x2, y1, y2 = getAxeLimits( axes[ i ] )
if x1 < xMin:
xMin = x1
if x2 > xMax:
xMax = x2
if y1 < yMin:
yMin = y1
if y2 > yMax:
yMax = y2
return ( ( xMin, xMax ), ( yMin, yMax ) )
def getAxeLimits( ax: axes.Axes ) -> tuple[ float, float, float, float ]:
"""Gets the limits of both X and Y axis as a 4 element tuple.
Args:
ax (axes.Axes): Subplot to get limits.
Returns:
tuple[float, float, float, float]: (xMin, xMax, yMin, yMax)
"""
xMin, xMax = ax.get_xlim()
yMin, yMax = ax.get_ylim()
return ( xMin, xMax, yMin, yMax )
def findExtremasPropertiesForAssociatedIdentifiers(
df: pd.DataFrame,
associatedIdentifiers: dict[ str, dict[ str, list[ str ] ] ],
offsetPlotting: bool = False,
offsetPercentage: int = 5,
) -> dict[ str, tuple[ float, float ] ]:
"""Find min and max of all properties linked to a same identifier.
Using an associatedIdentifiers dict containing associatedProperties dict,
we can find the extremas for each property of each identifier. Once we have them all,
we compare for each identifier what are the most extreme values and only the biggest and
lowest are kept in the end.
Args:
df (pd.DataFrame): Pandas dataframe.
associatedIdentifiers (dict[str, dict[str, list[str]]]): Property identifiers.
offsetPlotting (bool, optional): When using the values being returned,
we might want to add an offset to these values. If set to True,
the offsetPercentage is taken into account. Defaults to False.
offsetPercentage (int, optional): Value by which we will offset
the min and max values of each tuple of floats. Defaults to 5.
Returns:
dict[str, tuple[float, float]]: {
"BHP (Pa)": (minAllWells, maxAllWells),
"TotalMassRate (kg)": (minAllWells, maxAllWells),
"TotalSurfaceVolumetricRate (m3/s)": (minAllWells, maxAllWells),
"SurfaceVolumetricRateCO2 (m3/s)": (minAllWells, maxAllWells),
"SurfaceVolumetricRateWater (m3/s)": (minAllWells, maxAllWells)
}
"""
extremasProperties: dict[ str, tuple[ float, float ] ] = {}
# First we need to find the extrema for each property type per region.
propertyTypesExtremas: dict[ str, list[ tuple[ float, float ] ] ] = {}
for associatedProperties in associatedIdentifiers.values():
extremasPerProperty: dict[ str,
tuple[ float,
float ] ] = ( findExtremasAssociatedProperties( df, associatedProperties ) )
for propertyType, extremaFound in extremasPerProperty.items():
if propertyType not in propertyTypesExtremas:
propertyTypesExtremas[ propertyType ] = [ extremaFound ]
else:
propertyTypesExtremas[ propertyType ].append( extremaFound )
# Then, once all extrema have been found for all regions, we need to figure out
# which extrema per property type is the most extreme one.
for propertyType in propertyTypesExtremas:
values: list[ tuple[ float, float ] ] = propertyTypesExtremas[ propertyType ]
minValues: list[ float ] = [ values[ i ][ 0 ] for i in range( len( values ) ) ]
maxValues: list[ float ] = [ values[ i ][ 1 ] for i in range( len( values ) ) ]
lowest, highest = ( min( minValues ), max( maxValues ) )
if offsetPlotting:
offset: float = ( highest - lowest ) / 100 * offsetPercentage
lowest, highest = ( lowest - offset, highest + offset )
extremasProperties[ propertyType ] = ( lowest, highest )
return extremasProperties
def findExtremasAssociatedProperties(
df: pd.DataFrame, associatedProperties: dict[ str, list[ str ] ] ) -> dict[ str, tuple[ float, float ] ]:
"""Find the min and max of properties.
Using an associatedProperties dict containing property types
as keys and a list of property names as values,
and a pandas dataframe whose column names are composed of those same
property names, you can find the min and max values of each property
type and return it as a tuple.
Args:
df (pd.DataFrame): Pandas dataframe.
associatedProperties (dict[str, list[str]]): {
"Pressure (Pa)": ["Reservoir__Pressure__Pa__Source1"],
"Mass (kg)": ["CO2__Mass__kg__Source1",
"Water__Mass__kg__Source1"]
}
Returns:
dict[str, tuple[float, float]]: {
"Pressure (Pa)": (minPressure, maxPressure),
"Mass (kg)": (minMass, maxMass)
}
"""
extremasProperties: dict[ str, tuple[ float, float ] ] = {}
for propertyType, propertyNames in associatedProperties.items():
minValues = np.empty( len( propertyNames ) )
maxValues = np.empty( len( propertyNames ) )
for i, propertyName in enumerate( propertyNames ):
values: npt.NDArray[ np.float64 ] = df[ propertyName ].to_numpy()
minValues[ i ] = np.nanmin( values )
maxValues[ i ] = np.nanmax( values )
extrema: tuple[ float, float ] = (
float( np.min( minValues ) ),
float( np.max( maxValues ) ),
)
extremasProperties[ propertyType ] = extrema
return extremasProperties
"""
Utils for treatment of the data.
"""
def associatePropertyToAxeType( propertyNames: list[ str ] ) -> dict[ str, list[ str ] ]:
"""Identify property types.
From a list of property names, identify if each of this property
corresponds to a certain property type like "Pressure", "Mass",
"Temperature" etc ... and returns a dict where the keys are the property
type and the value the list of property names associated to it.
Args:
propertyNames (list[str]): ["Reservoir__Pressure__Pa__Source1",
"CO2__Mass__kg__Source1", "Water__Mass__kg__Source1"]
Returns:
dict[str, list[str]]: { "Pressure (Pa)": ["Reservoir__Pressure__Pa__Source1"],
"Mass (kg)": ["CO2__Mass__kg__Source1",
"Water__Mass__kg__Source1"] }
"""
propertyIds: list[ str ] = fcts.identifyProperties( propertyNames )
associationTable: dict[ str, str ] = {
"0": "Pressure",
"1": "Pressure",
"2": "Temperature",
"3": "PoreVolume",
"4": "PoreVolume",
"5": "Mass",
"6": "Mass",
"7": "Mass",
"8": "Mass",
"9": "Mass",
"10": "Mass",
"11": "BHP",
"12": "MassRate",
"13": "VolumetricRate",
"14": "VolumetricRate",
"15": "BHP",
"16": "MassRate",
"17": "VolumetricRate",
"18": "VolumetricRate",
"19": "VolumetricRate",
"20": "Volume",
"21": "VolumetricRate",
"22": "Volume",
"23": "Iterations",
"24": "Iterations",
"25": "Stress",
"26": "Displacement",
"27": "Permeability",
"28": "Porosity",
"29": "Ratio",
"30": "Fraction",
"31": "BulkModulus",
"32": "ShearModulus",
"33": "OedometricModulus",
"34": "Points",
"35": "Density",
"36": "Mass",
"37": "Mass",
"38": "Time",
"39": "Time",
}
associatedPropertyToAxeType: dict[ str, list[ str ] ] = {}
noUnitProperties: list[ str ] = [
"Iterations",
"Porosity",
"Ratio",
"Fraction",
"OedometricModulus",
]
for i, propId in enumerate( propertyIds ):
idProp: str = propId.split( ":" )[ 0 ]
propNoId: str = propId.split( ":" )[ 1 ]
associatedType: str = associationTable[ idProp ]
if associatedType in noUnitProperties:
axeName: str = associatedType
else:
propIdElts: list[ str ] = propNoId.split( "__" )
# No unit was found.
if len( propIdElts ) <= 2:
axeName = associatedType
# There is a unit.
else:
unit: str = propIdElts[ -2 ]
axeName = associatedType + " (" + unit + ")"
if axeName not in associatedPropertyToAxeType:
associatedPropertyToAxeType[ axeName ] = []
associatedPropertyToAxeType[ axeName ].append( propertyNames[ i ] )
return associatedPropertyToAxeType
def propertiesPerIdentifier( propertyNames: list[ str ] ) -> dict[ str, list[ str ] ]:
"""Extract identifiers with associated properties.
From a list of property names, extracts the identifier (name of the
region for flow property or name of a well for well property) and creates
a dictionary with identifiers as keys and the properties containing them
for value in a list.
Args:
propertyNames (list[str]): Property names.
Example
.. code-block:: python
[
"WellControls1__BHP__Pa__Source1",
"WellControls1__TotalMassRate__kg/s__Source1",
"WellControls2__BHP__Pa__Source1",
"WellControls2__TotalMassRate__kg/s__Source1"
]
Returns:
dict[str, list[str]]: Property identifiers.
Example
.. code-block:: python
{
"WellControls1": [
"WellControls1__BHP__Pa__Source1",
"WellControls1__TotalMassRate__kg/s__Source1"
],
"WellControls2": [
"WellControls2__BHP__Pa__Source1",
"WellControls2__TotalMassRate__kg/s__Source1"
]
}
"""
propsPerIdentifier: dict[ str, list[ str ] ] = {}
for propertyName in propertyNames:
elements: list[ str ] = propertyName.split( "__" )
identifier: str = elements[ 0 ]
if identifier not in propsPerIdentifier:
propsPerIdentifier[ identifier ] = []
propsPerIdentifier[ identifier ].append( propertyName )
return propsPerIdentifier
def associationIdentifiers( propertyNames: list[ str ] ) -> dict[ str, dict[ str, list[ str ] ] ]:
"""Extract identifiers with associated curves.
From a list of property names, extracts the identifier (name of the
region for flow property or name of a well for well property) and creates
a dictionary with identifiers as keys and the properties containing them
for value in a list.
Args:
propertyNames (list[str]): Property names.
Example
.. code-block:: python
[
"WellControls1__BHP__Pa__Source1",
"WellControls1__TotalMassRate__kg/s__Source1",
"WellControls1__TotalSurfaceVolumetricRate__m3/s__Source1",
"WellControls1__SurfaceVolumetricRateCO2__m3/s__Source1",
"WellControls1__SurfaceVolumetricRateWater__m3/s__Source1",
"WellControls2__BHP__Pa__Source1",
"WellControls2__TotalMassRate__kg/s__Source1",
"WellControls2__TotalSurfaceVolumetricRate__m3/s__Source1",
"WellControls2__SurfaceVolumetricRateCO2__m3/s__Source1",
"WellControls2__SurfaceVolumetricRateWater__m3/s__Source1",
"WellControls3__BHP__Pa__Source1",
"WellControls3__TotalMassRate__tons/day__Source1",
"WellControls3__TotalSurfaceVolumetricRate__bbl/day__Source1",
"WellControls3__SurfaceVolumetricRateCO2__bbl/day__Source1",
"WellControls3__SurfaceVolumetricRateWater__bbl/day__Source1",
"Mean__BHP__Pa__Source1",
"Mean__TotalMassRate__tons/day__Source1",
"Mean__TotalSurfaceVolumetricRate__bbl/day__Source1",
"Mean__SurfaceVolumetricRateCO2__bbl/day__Source1",
"Mean__SurfaceVolumetricRateWater__bbl/day__Source1"
]
Returns:
dict[str, dict[str, list[str]]]: Property identifiers.
Example
.. code-block:: python
{
"WellControls1": {
'BHP (Pa)': [
'WellControls1__BHP__Pa__Source1'
],
'MassRate (kg/s)': [
'WellControls1__TotalMassRate__kg/s__Source1'
],
'VolumetricRate (m3/s)': [
'WellControls1__TotalSurfaceVolumetricRate__m3/s__Source1',
'WellControls1__SurfaceVolumetricRateCO2__m3/s__Source1',
'WellControls1__SurfaceVolumetricRateWater__m3/s__Source1'
]
},
"WellControls2": {
'BHP (Pa)': [
'WellControls2__BHP__Pa__Source1'
],
'MassRate (kg/s)': [
'WellControls2__TotalMassRate__kg/s__Source1'
],
'VolumetricRate (m3/s)': [
'WellControls2__TotalSurfaceVolumetricRate__m3/s__Source1',
'WellControls2__SurfaceVolumetricRateCO2__m3/s__Source1',
'WellControls2__SurfaceVolumetricRateWater__m3/s__Source1'
]
},
"WellControls3": {
'BHP (Pa)': [
'WellControls3__BHP__Pa__Source1'
],
'MassRate (tons/day)': [
'WellControls3__TotalMassRate__tons/day__Source1'
],
'VolumetricRate (bbl/day)': [
'WellControls3__TotalSurfaceVolumetricRate__bbl/day__Source1',
'WellControls3__SurfaceVolumetricRateCO2__bbl/day__Source1',
'WellControls3__SurfaceVolumetricRateWater__bbl/day__Source1'
]
},
"Mean": {
'BHP (Pa)': [
'Mean__BHP__Pa__Source1'
],
'MassRate (tons/day)': [
'Mean__TotalMassRate__tons/day__Source1'
],
'VolumetricRate (bbl/day)': [
'Mean__TotalSurfaceVolumetricRate__bbl/day__Source1',
'Mean__SurfaceVolumetricRateCO2__bbl/day__Source1',
'Mean__SurfaceVolumetricRateWater__bbl/day__Source1'
]
}
}
"""
propsPerIdentifier: dict[ str, list[ str ] ] = propertiesPerIdentifier( propertyNames )
assosIdentifier: dict[ str, dict[ str, list[ str ] ] ] = {}
for ident, propNames in propsPerIdentifier.items():
assosPropsToAxeType: dict[ str, list[ str ] ] = associatePropertyToAxeType( propNames )
assosIdentifier[ ident ] = assosPropsToAxeType
return assosIdentifier
def buildFontTitle( userChoices: dict[ str, Any ] ) -> FontProperties:
"""Builds a Fontproperties object according to user choices on title.
Args:
userChoices (dict[str, Any]): Customization parameters.
Returns:
FontProperties: FontProperties object for the title.
"""
fontTitle: FontProperties = FontProperties()
if "titleStyle" in userChoices:
fontTitle.set_style( userChoices[ "titleStyle" ] )
if "titleWeight" in userChoices:
fontTitle.set_weight( userChoices[ "titleWeight" ] )
if "titleSize" in userChoices:
fontTitle.set_size( userChoices[ "titleSize" ] )
return fontTitle
def buildFontVariable( userChoices: dict[ str, Any ] ) -> FontProperties:
"""Builds a Fontproperties object according to user choices on variables.
Args:
userChoices (dict[str, Any]): Customization parameters.
Returns:
FontProperties: FontProperties object for the variable axes.
"""
fontVariable: FontProperties = FontProperties()
if "variableStyle" in userChoices:
fontVariable.set_style( userChoices[ "variableStyle" ] )
if "variableWeight" in userChoices:
fontVariable.set_weight( userChoices[ "variableWeight" ] )
if "variableSize" in userChoices:
fontVariable.set_size( userChoices[ "variableSize" ] )
return fontVariable
def buildFontCurves( userChoices: dict[ str, Any ] ) -> FontProperties:
"""Builds a Fontproperties object according to user choices on curves.
Args:
userChoices (dict[str, str]): Customization parameters.
Returns:
FontProperties: FontProperties object for the curves axes.
"""
fontCurves: FontProperties = FontProperties()
if "curvesStyle" in userChoices:
fontCurves.set_style( userChoices[ "curvesStyle" ] )
if "curvesWeight" in userChoices:
fontCurves.set_weight( userChoices[ "curvesWeight" ] )
if "curvesSize" in userChoices:
fontCurves.set_size( userChoices[ "curvesSize" ] )
return fontCurves
def customizeLines( userChoices: dict[ str, Any ], labels: list[ str ],
linesList: list[ lines.Line2D ] ) -> list[ lines.Line2D ]:
"""Customize lines according to user choices.
By applying the user choices, we modify or not the list of lines
and return it with the same number of lines in the same order.
Args:
userChoices (dict[str, Any]): Customization parameters.
labels (list[str]): Labels of lines.
linesList (list[lines.Line2D]): List of lines object.
Returns:
list[lines.Line2D]: List of lines object modified.
"""
if "linesModified" in userChoices:
linesModified: dict[ str, dict[ str, Any ] ] = userChoices[ "linesModified" ]
linesChanged: list[ lines.Line2D ] = []
for i, label in enumerate( labels ):
if label in linesModified:
lineChanged: lines.Line2D = applyCustomizationOnLine( linesList[ i ], linesModified[ label ] )
linesChanged.append( lineChanged )
else:
linesChanged.append( linesList[ i ] )
return linesChanged
else:
return linesList
def applyCustomizationOnLine( line: lines.Line2D, parameters: dict[ str, Any ] ) -> lines.Line2D:
"""Apply modification methods on a line from parameters.
Args:
line (lines.Line2D): Matplotlib Line2D.
parameters (dict[str, Any]): Dictionary of {
"linestyle": one of ["-","--","-.",":"]
"linewidth": positive int
"color": color code
"marker": one of ["",".","o","^","s","*","D","+","x"]
"markersize":positive int
}
Returns:
lines.Line2D: Line2D object modified.
"""
if "linestyle" in parameters:
line.set_linestyle( parameters[ "linestyle" ] )
if "linewidth" in parameters:
line.set_linewidth( parameters[ "linewidth" ] )
if "color" in parameters:
line.set_color( parameters[ "color" ] )
if "marker" in parameters:
line.set_marker( parameters[ "marker" ] )
if "markersize" in parameters:
line.set_markersize( parameters[ "markersize" ] )
return line
"""
Layout tools for layering subplots in a figure.
"""
def isprime( x: int ) -> bool:
"""Checks if a number is primer or not.
Args:
x (int): Positive number to test.
Returns:
bool: True if prime, False if not.
"""
if x < 0:
print( "Invalid number entry, needs to be positive int." )
return False
return all( x % n != 0 for n in range( 2, int( x**0.5 ) + 1 ) )
def findClosestPairIntegers( x: int ) -> tuple[ int, int ]:
"""Get the pair of integers that multiply the closest to input value.
Finds the closest pair of integers that when multiplied together,
gives a number the closest to the input number (always above or equal).
Args:
x (int): Positive number.
Returns:
tuple[int, int]: (highest int, lowest int)
"""
if x < 4:
return ( x, 1 )
while isprime( x ):
x += 1
N: int = round( math.sqrt( x ) )
while x > N:
if x % N == 0:
M = x // N
highest = max( M, N )
lowest = min( M, N )
return ( highest, lowest )
else:
N += 1
return ( x, 1 )
def smartLayout( x: int, ratio: float ) -> tuple[ int, int, int ]:
"""Return the best layout according to the number of subplots.
For multiple subplots, we need to have a layout that can adapt to
the number of subplots automatically. This function figures out the
best layout possible knowing the number of suplots and the figure ratio.
Args:
x (int): Positive number.
ratio (float): Width to height ratio of a figure.
Returns:
tuple[int]: (nbr_rows, nbr_columns, number of axes to remove)
"""
pair: tuple[ int, int ] = findClosestPairIntegers( x )
nbrAxesToRemove: int = pair[ 0 ] * pair[ 1 ] - x
if ratio < 1:
return ( pair[ 0 ], pair[ 1 ], nbrAxesToRemove )
else:
return ( pair[ 1 ], pair[ 0 ], nbrAxesToRemove )
"""
Legend tools
"""
commonAssociations: dict[ str, str ] = {
"pressuremin": "Pmin",
"pressureMax": "Pmax",
"pressureaverage": "Pavg",
"deltapressuremin": "DPmin",
"deltapressuremax": "DPmax",
"temperaturemin": "Tmin",
"temperaturemax": "Tmax",
"temperatureaverage": "Tavg",
"effectivestressxx": "ESxx",
"effectivestresszz": "ESzz",
"effectivestressratio": "ESratio",
"totaldisplacementx": "TDx",
"totaldisplacementy": "TDy",
"totaldisplacementz": "TDz",
"totalstressXX": "TSxx",
"totalstressZZ": "TSzz",
"stressxx": "Sxx",
"stressyy": "Syy",
"stresszz": "Szz",
"stressxy": "Sxy",
"stressxz": "Sxz",
"stressyz": "Syz",
"poissonratio": "PR",
"porosity": "PORO",
"specificgravity": "SG",
"theoreticalverticalstress": "TVS",
"density": "DNST",
"pressure": "P",
"permeabilityx": "PERMX",
"permeabilityy": "PERMY",
"permeabilityz": "PERMZ",
"oedometric": "OEDO",
"young": "YOUNG",
"shear": "SHEAR",
"bulk": "BULK",
"totaldynamicporevolume": "TDPORV",
"time": "TIME",
"dt": "DT",
"meanbhp": "MBHP",
"meantotalmassrate": "MTMR",
"meantotalvolumetricrate": "MTSVR",
"bhp": "BHP",
"totalmassrate": "TMR",
"cumulatedlineariter": "CLI",
"cumulatednewtoniter": "CNI",