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