Salome HOME
Adding multi-functions input capabilities (7)
[modules/adao.git] / test / test6903 / Verification_des_mono_et_multi_fonctions_D.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 def ElementaryFunction01( InputArgument ):
29     """
30     Exemple de fonction non-lineaire et non-carree
31
32     L'argument en entree est un vecteur au sens mathematique, c'est-a-dire
33     une suite ordonnee de valeurs reelles. Au sens informatique, c'est tout
34     objet qui peut se transformer en une serie continue unidimensionnelle de
35     valeurs reelles. L'argument en sortie est un vecteur Numpy 1D.
36     """
37     #
38     if isinstance( InputArgument, (numpy.ndarray, numpy.matrix, list, tuple) ) or type(InputArgument).__name__ in ('generator','range'):
39         _subX = numpy.ravel(InputArgument)
40     else:
41         raise ValueError("ElementaryFunction01 unkown input type: %s"%(type(InputArgument).__name__,))
42     #
43     _OutputArgument = []
44     _OutputArgument.extend( (-1 + _subX).tolist() )
45     _OutputArgument.extend( numpy.cos(_subX/2).tolist() )
46     _OutputArgument.extend( numpy.exp((3.14 * _subX)).tolist() )
47     #
48     return numpy.ravel( _OutputArgument )
49
50 def MultiFonction01( xSerie ):
51     """
52     Exemple de multi-fonction
53
54     Pour une liste ordonnee de vecteurs en entree, renvoie en sortie la liste
55     correspondante de valeurs de la fonction en argument
56     """
57     if not (isinstance( xSerie, (list, tuple) ) or type(xSerie).__name__ in ('generator','range')):
58         raise ValueError("MultiFonction01 unkown input type: %s"%(type(xSerie),))
59     #
60     _ySerie = []
61     for _subX in xSerie:
62         _ySerie.append( ElementaryFunction01( _subX ) )
63     #
64     return _ySerie
65
66 # ==============================================================================
67 def test1():
68     """
69     Verification du fonctionnement identique pour les algorithmes non-temporels
70     en utilisant une fonction non-lineaire et non-carree
71     """
72     print(test1.__doc__)
73     Xa = {}
74     #
75     for algo in ("3DVAR", "Blue", "ExtendedBlue", "NonLinearLeastSquares", "DerivativeFreeOptimization"):
76         print("")
77         msg = "Algorithme en test en MonoFonction : %s"%algo
78         print(msg+"\n"+"-"*len(msg))
79         #
80         adaopy = adaoBuilder.New()
81         adaopy.setAlgorithmParameters(Algorithm=algo, Parameters={"EpsilonMinimumExponent":-10, "Bounds":[[-1,10.],[-1,10.],[-1,10.]]})
82         adaopy.setBackground         (Vector = [0,1,2])
83         adaopy.setBackgroundError    (ScalarSparseMatrix = 1.)
84         adaopy.setObservation        (Vector = [0.5,1.5,2.5,0.5,1.5,2.5,0.5,1.5,2.5])
85         adaopy.setObservationError   (DiagonalSparseMatrix = "1 1 1 1 1 1 1 1 1")
86         adaopy.setObservationOperator(OneFunction = ElementaryFunction01)
87         adaopy.setObserver("Analysis",Template="ValuePrinter")
88         adaopy.execute()
89         Xa["Mono/"+algo] = adaopy.get("Analysis")[-1]
90         del adaopy
91     #
92     for algo in ("3DVAR", "Blue", "ExtendedBlue", "NonLinearLeastSquares", "DerivativeFreeOptimization"):
93         print("")
94         msg = "Algorithme en test en MultiFonction : %s"%algo
95         print(msg+"\n"+"-"*len(msg))
96         #
97         adaopy = adaoBuilder.New()
98         adaopy.setAlgorithmParameters(Algorithm=algo, Parameters={"EpsilonMinimumExponent":-10, "Bounds":[[-1,10.],[-1,10.],[-1,10.]]})
99         adaopy.setBackground         (Vector = [0,1,2])
100         adaopy.setBackgroundError    (ScalarSparseMatrix = 1.)
101         adaopy.setObservation        (Vector = [0.5,1.5,2.5,0.5,1.5,2.5,0.5,1.5,2.5])
102         adaopy.setObservationError   (DiagonalSparseMatrix = "1 1 1 1 1 1 1 1 1")
103         adaopy.setObservationOperator(OneFunction = MultiFonction01, InputAsMF = True)
104         adaopy.setObserver("Analysis",Template="ValuePrinter")
105         adaopy.execute()
106         Xa["Multi/"+algo] = adaopy.get("Analysis")[-1]
107         del adaopy
108     #
109     print("")
110     msg = "Tests des ecarts attendus :"
111     print(msg+"\n"+"="*len(msg))
112     for algo in ("3DVAR", "Blue", "ExtendedBlue", "NonLinearLeastSquares", "DerivativeFreeOptimization"):
113         verify_similarity_of_algo_results(("Multi/"+algo, "Mono/"+algo), Xa, 1.e-20)
114     print("  Les resultats obtenus sont corrects.")
115     print("")
116     #
117     return 0
118
119 # ==============================================================================
120 def almost_equal_vectors(v1, v2, precision = 1.e-15, msg = ""):
121     """Comparaison de deux vecteurs"""
122     print("    Difference maximale %s: %.2e"%(msg, max(abs(v2 - v1))))
123     return max(abs(v2 - v1)) < precision
124
125 def verify_similarity_of_algo_results(serie = [], Xa = {}, precision = 1.e-15):
126     print("  Comparaisons :")
127     for algo1 in serie:
128         for algo2 in serie:
129             if algo1 is algo2: break
130             assert almost_equal_vectors( Xa[algo1], Xa[algo2], precision, "entre %s et %s "%(algo1, algo2) )
131     print("  Algorithmes dont les resultats sont similaires a %.0e : %s\n"%(precision, serie,))
132     sys.stdout.flush()
133
134 #===============================================================================
135 if __name__ == "__main__":
136     print('\nAUTODIAGNOSTIC\n')
137     test1()