Salome HOME
Documentation review corrections
[modules/adao.git] / src / daComposant / daAlgorithms / InterpolationByReducedModelTest.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2023 EDF R&D
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18 #
19 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 #
21 # Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
22
23 import numpy, math
24 from daCore import BasicObjects, PlatformInfo
25 mpr = PlatformInfo.PlatformInfo().MachinePrecision()
26 mfp = PlatformInfo.PlatformInfo().MaximumPrecision()
27 from daCore.PlatformInfo import vfloat
28 from daAlgorithms.Atoms import ecweim, eosg
29
30 # ==============================================================================
31 class ElementaryAlgorithm(BasicObjects.Algorithm):
32     def __init__(self):
33         #
34         BasicObjects.Algorithm.__init__(self, "INTERPOLATIONBYREDUCEDMODELTEST")
35         self.defineRequiredParameter(
36             name     = "ReducedBasis",
37             default  = [],
38             typecast = numpy.array,
39             message  = "Base réduite, 1 vecteur par colonne",
40             )
41         self.defineRequiredParameter(
42             name     = "MeasurementLocations",
43             default  = [],
44             typecast = tuple,
45             message  = "Liste des indices ou noms de positions optimales de mesure selon l'ordre interne d'un vecteur de base",
46             )
47         self.defineRequiredParameter(
48             name     = "EnsembleOfSnapshots",
49             default  = [],
50             typecast = numpy.array,
51             message  = "Ensemble de vecteurs d'état physique (snapshots), 1 état par colonne (Test Set)",
52             )
53         self.defineRequiredParameter(
54             name     = "ErrorNorm",
55             default  = "L2",
56             typecast = str,
57             message  = "Norme d'erreur utilisée pour le critère d'optimalité des positions",
58             listval  = ["L2", "Linf"]
59             )
60         self.defineRequiredParameter(
61             name     = "ShowElementarySummary",
62             default  = True,
63             typecast = bool,
64             message  = "Calcule et affiche un résumé à chaque évaluation élémentaire",
65             )
66         self.defineRequiredParameter(
67             name     = "NumberOfPrintedDigits",
68             default  = 5,
69             typecast = int,
70             message  = "Nombre de chiffres affichés pour les impressions de réels",
71             minval   = 0,
72             )
73         self.defineRequiredParameter(
74             name     = "ResultTitle",
75             default  = "",
76             typecast = str,
77             message  = "Titre du tableau et de la figure",
78             )
79         self.requireInputArguments(
80             mandatory= (),
81             optional = (),
82             )
83         self.setAttributes(tags=(
84             "Reduction",
85             "Interpolation",
86             ))
87
88     def run(self, Xb=None, Y=None, U=None, HO=None, EM=None, CM=None, R=None, B=None, Q=None, Parameters=None):
89         self._pre_run(Parameters, Xb, Y, U, HO, EM, CM, R, B, Q)
90         #
91         __rb  = self._parameters["ReducedBasis"]
92         __ip  = self._parameters["MeasurementLocations"]
93         __eos = self._parameters["EnsembleOfSnapshots"]
94         __rdim, __nrb = __rb.shape
95         __fdim, __nsn = __eos.shape
96         #
97         if __fdim != __rdim:
98             raise ValueError("The dimension of each snapshot (%i) has to be equal to the dimension of each reduced basis vector."%(__fdim,__rdim))
99         if __fdim < len(__ip):
100             raise ValueError("The dimension of each snapshot (%i) has to be greater or equal to the number of optimal measurement locations (%i)."%(__fdim,len(__ip)))
101         #
102         #--------------------------
103         __s = self._parameters["ShowElementarySummary"]
104         __p = self._parameters["NumberOfPrintedDigits"]
105         __r = __nsn
106         #
107         __marge = 5*u" "
108         __flech = 3*"="+"> "
109         __ordre = int(math.log10(__nsn))+1
110         msgs  = ("\n") # 1
111         if len(self._parameters["ResultTitle"]) > 0:
112             __rt = str(self._parameters["ResultTitle"])
113             msgs += (__marge + "====" + "="*len(__rt) + "====\n")
114             msgs += (__marge + "    " + __rt + "\n")
115             msgs += (__marge + "====" + "="*len(__rt) + "====\n")
116         else:
117             msgs += (__marge + "%s\n"%self._name)
118             msgs += (__marge + "%s\n"%("="*len(self._name),))
119         #
120         msgs += ("\n")
121         msgs += (__marge + "This test allows to analyze the quality of the interpolation of states,\n")
122         msgs += (__marge + "using a reduced basis and measurements at specified points.\n")
123         msgs += ("\n")
124         msgs += (__marge + "The output shows simple statistics related to normalized errors of the\n")
125         msgs += (__marge + "interpolation with reduced basis using pseudo-measures coming from each\n")
126         msgs += (__marge + "snapshot included in the given test set.\n")
127         msgs += ("\n")
128         msgs += (__marge + "Warning:  in order to be coherent, this test has to use the same norm\n")
129         msgs += (__marge + "than the one used to build the reduced basis. The user chosen norm in\n")
130         msgs += (__marge + "this test is presently \"%s\". Check the RB building one.\n"%(self._parameters["ErrorNorm"],))
131         msgs += ("\n")
132         msgs += (__flech + "Information before launching:\n")
133         msgs += (__marge + "-----------------------------\n")
134         msgs += ("\n")
135         msgs += (__marge + "Characteristics of input data:\n")
136         msgs += (__marge + "  State dimension................: %i\n")%__fdim
137         msgs += (__marge + "  Dimension of RB................: %i\n")%__nrb
138         msgs += (__marge + "  Number of measures locations...: %i\n")%len(__ip)
139         msgs += (__marge + "  Number of snapshots to test....: %i\n")%__nsn
140         msgs += ("\n")
141         msgs += (__marge + "%s\n\n"%("-"*75,))
142         #
143         msgs += (__flech + "Interpolation error test for all given states:\n")
144         msgs += (__marge + "----------------------------------------------\n")
145         msgs += ("\n")
146         Es = []
147         for ns in range(__nsn):
148             __rm = __eos[__ip,ns]
149             __im = ecweim.EIM_online(self, __rb, __eos[__ip,ns], __ip)
150             #
151             if   self._parameters["ErrorNorm"] == "L2":
152                 __ecart = vfloat(numpy.linalg.norm( __eos[:,ns] - __im ) / numpy.linalg.norm( __eos[:,ns] ))
153             else:
154                 __ecart = vfloat(numpy.linalg.norm( __eos[:,ns] - __im, ord=numpy.inf ) / numpy.linalg.norm( __eos[:,ns], ord=numpy.inf ))
155             Es.append( __ecart )
156             if __s:
157                 msgs += (__marge + "Normalized interpolation error (%s) for state number %0"+str(__ordre)+"i..: %."+str(__p)+"e\n")%(self._parameters["ErrorNorm"],ns,__ecart)
158         msgs += ("\n")
159         msgs += (__marge + "%s\n"%("-"*75,))
160         #
161         if __r > 1:
162             msgs += ("\n")
163             msgs += (__flech + "Launching statistical summary calculation for %i states\n"%__r)
164             msgs += ("\n")
165             msgs += (__marge + "Statistical analysis of the errors Es obtained over the collection of states\n")
166             msgs += (__marge + "(Remark: numbers that are (about) under %.0e represent 0 to machine precision)\n"%mpr)
167             msgs += ("\n")
168             Yy = numpy.array( Es )
169             msgs += (__marge + "Number of evaluations...........................: %i\n")%len( Es )
170             msgs += ("\n")
171             msgs += (__marge + "Characteristics of the whole set of error outputs Es:\n")
172             msgs += (__marge + "  Minimum value of the whole set of outputs.....: %."+str(__p)+"e\n")%numpy.min(  Yy )
173             msgs += (__marge + "  Maximum value of the whole set of outputs.....: %."+str(__p)+"e\n")%numpy.max(  Yy )
174             msgs += (__marge + "  Mean of vector of the whole set of outputs....: %."+str(__p)+"e\n")%numpy.mean( Yy, dtype=mfp )
175             msgs += (__marge + "  Standard error of the whole set of outputs....: %."+str(__p)+"e\n")%numpy.std(  Yy, dtype=mfp )
176             msgs += ("\n")
177             msgs += (__marge + "%s\n"%("-"*75,))
178         #
179         msgs += ("\n")
180         msgs += (__marge + "End of the \"%s\" verification\n\n"%self._name)
181         msgs += (__marge + "%s\n"%("-"*75,))
182         print(msgs) # 3
183         #
184         self._post_run(HO)
185         return 0
186
187 # ==============================================================================
188 if __name__ == "__main__":
189     print("\n AUTODIAGNOSTIC\n")