Salome HOME
Minor documentation and code review corrections (39)
[modules/adao.git] / test / test6903 / Verification_des_mono_et_multi_fonctions_C.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 "Verification du fonctionnement correct d'entrees en mono ou multi-fonctions"
23
24 import sys
25 import unittest
26 import numpy
27 from adao import adaoBuilder
28
29 # ==============================================================================
30
31 M = numpy.matrix("1 0 0;0 2 0;0 0 3")
32 def MonoFonction( x ):
33     return M * numpy.asmatrix(numpy.ravel( x )).T
34
35 def MultiFonction( xserie ):
36     _mulHX = []
37     for _subX in xserie:
38         _mulHX.append( M * numpy.asmatrix(numpy.ravel( _subX )).T )
39     return _mulHX
40
41 # ==============================================================================
42 class Test_Adao(unittest.TestCase):
43     def test1(self):
44         """
45         Verification du fonctionnement identique pour les algorithmes autres
46         en utilisant une fonction lineaire et carree
47         """
48         print("\n        "+self.test1.__doc__.strip()+"\n")
49         Xa = {}
50         #
51         for algo in ("ParticleSwarmOptimization", "QuantileRegression", ):
52             print("")
53             msg = "Algorithme en test en MonoFonction : %s"%algo
54             print(msg+"\n"+"-"*len(msg))
55             #
56             adaopy = adaoBuilder.New()
57             adaopy.setAlgorithmParameters(Algorithm=algo, Parameters={"BoxBounds":3*[[-1,3]], "SetSeed":1000})
58             adaopy.setBackground         (Vector = [0,1,2])
59             adaopy.setBackgroundError    (ScalarSparseMatrix = 1.)
60             adaopy.setObservation        (Vector = [0.5,1.5,2.5])
61             adaopy.setObservationError   (DiagonalSparseMatrix = "1 2 3")
62             adaopy.setObservationOperator(OneFunction = MonoFonction)
63             adaopy.setObserver("Analysis",Template="ValuePrinter")
64             adaopy.execute()
65             Xa["Mono/"+algo] = adaopy.get("Analysis")[-1]
66             del adaopy
67         #
68         for algo in ("ParticleSwarmOptimization", "QuantileRegression", ):
69             print("")
70             msg = "Algorithme en test en MultiFonction : %s"%algo
71             print(msg+"\n"+"-"*len(msg))
72             #
73             adaopy = adaoBuilder.New()
74             adaopy.setAlgorithmParameters(Algorithm=algo, Parameters={"BoxBounds":3*[[-1,3]], "SetSeed":1000})
75             adaopy.setBackground         (Vector = [0,1,2])
76             adaopy.setBackgroundError    (ScalarSparseMatrix = 1.)
77             adaopy.setObservation        (Vector = [0.5,1.5,2.5])
78             adaopy.setObservationError   (DiagonalSparseMatrix = "1 2 3")
79             adaopy.setObservationOperator(OneFunction = MultiFonction, InputFunctionAsMulti = True)
80             adaopy.setObserver("Analysis",Template="ValuePrinter")
81             adaopy.execute()
82             Xa["Multi/"+algo] = adaopy.get("Analysis")[-1]
83             del adaopy
84         #
85         print("")
86         msg = "Tests des ecarts attendus :"
87         print(msg+"\n"+"="*len(msg))
88         for algo in ("ParticleSwarmOptimization", "QuantileRegression"):
89             verify_similarity_of_algo_results(("Multi/"+algo, "Mono/"+algo), Xa, 1.e-20)
90         print("  Les resultats obtenus sont corrects.")
91         print("")
92
93 # ==============================================================================
94 def almost_equal_vectors(v1, v2, precision = 1.e-15, msg = ""):
95     """Comparaison de deux vecteurs"""
96     print("    Difference maximale %s: %.2e"%(msg, max(abs(v2 - v1))))
97     return max(abs(v2 - v1)) < precision
98
99 def verify_similarity_of_algo_results(serie = [], Xa = {}, precision = 1.e-15):
100     print("  Comparaisons :")
101     for algo1 in serie:
102         for algo2 in serie:
103             if algo1 is algo2: break
104             assert almost_equal_vectors( Xa[algo1], Xa[algo2], precision, "entre %s et %s "%(algo1, algo2) )
105     print("  Algorithmes dont les resultats sont similaires a %.0e : %s\n"%(precision, serie,))
106     sys.stdout.flush()
107
108 #===============================================================================
109 if __name__ == "__main__":
110     print("\nAUTODIAGNOSTIC\n==============")
111     sys.stderr = sys.stdout
112     unittest.main(verbosity=2)