Salome HOME
Tests update for vector error identification
[modules/adao.git] / test / test6704 / Doc_TUI_Exemple_03_en_multifonction.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2019 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 d'un exemple de la documentation"
23
24 # ==============================================================================
25 #
26 # Construction artificielle d'un exemple de donnees utilisateur
27 # -------------------------------------------------------------
28 alpha = 5.
29 beta = 7
30 gamma = 9.0
31 #
32 alphamin, alphamax = 0., 10.
33 betamin,  betamax  = 3, 13
34 gammamin, gammamax = 1.5, 15.5
35 #
36 def simulation(x):
37     "Fonction de simulation H pour effectuer Y=H(X)"
38     import numpy
39     __x = numpy.matrix(numpy.ravel(numpy.matrix(x))).T
40     __H = numpy.matrix("1 0 0;0 2 0;0 0 3; 1 2 3")
41     return __H * __x
42 #
43 def multisimulation( xserie ):
44     yserie = []
45     for x in xserie:
46         yserie.append( simulation( x ) )
47     return yserie
48 #
49 # Observations obtenues par simulation
50 # ------------------------------------
51 observations = simulation((2, 3, 4))
52
53 # ==============================================================================
54 def test1():
55     "Test"
56     import numpy
57     from adao import adaoBuilder
58     #
59     # Mise en forme des entrees
60     # -------------------------
61     Xb = (alpha, beta, gamma)
62     Bounds = (
63         (alphamin, alphamax),
64         (betamin,  betamax ),
65         (gammamin, gammamax))
66     #
67     # TUI ADAO
68     # --------
69     case = adaoBuilder.New()
70     case.set(
71         'AlgorithmParameters',
72         Algorithm = '3DVAR',
73         Parameters = {
74             "Bounds":Bounds,
75             "MaximumNumberOfSteps":100,
76             "StoreSupplementaryCalculations":[
77                 "CostFunctionJ",
78                 "CurrentState",
79                 "SimulatedObservationAtOptimum",
80                 ],
81             }
82         )
83     case.set( 'Background', Vector = numpy.array(Xb), Stored = True )
84     case.set( 'Observation', Vector = numpy.array(observations) )
85     case.set( 'BackgroundError', ScalarSparseMatrix = 1.0e10 )
86     case.set( 'ObservationError', ScalarSparseMatrix = 1.0 )
87     case.set(
88         'ObservationOperator',
89         OneFunction = multisimulation,
90         Parameters  = {"DifferentialIncrement":0.0001},
91         InputFunctionAsMulti = True,
92         )
93     case.set( 'Observer', Variable="CurrentState", Template="ValuePrinter" )
94     case.execute()
95     #
96     # Exploitation independante
97     # -------------------------
98     Xbackground   = case.get("Background")
99     Xoptimum      = case.get("Analysis")[-1]
100     FX_at_optimum = case.get("SimulatedObservationAtOptimum")[-1]
101     J_values      = case.get("CostFunctionJ")[:]
102     print("")
103     print("Number of internal iterations...: %i"%len(J_values))
104     print("Initial state...................: %s"%(numpy.ravel(Xbackground),))
105     print("Optimal state...................: %s"%(numpy.ravel(Xoptimum),))
106     print("Simulation at optimal state.....: %s"%(numpy.ravel(FX_at_optimum),))
107     print("")
108     #
109     return case.get("Analysis")[-1]
110
111 # ==============================================================================
112 def assertAlmostEqualArrays(first, second, places=7, msg=None, delta=None):
113     "Compare two vectors, like unittest.assertAlmostEqual"
114     import numpy
115     if msg is not None:
116         print(msg)
117     if delta is not None:
118         if ( numpy.abs(numpy.asarray(first) - numpy.asarray(second)) > float(delta) ).any():
119             raise AssertionError("%s != %s within %s places"%(first,second,delta))
120     else:
121         if ( numpy.abs(numpy.asarray(first) - numpy.asarray(second)) > 10**(-int(places)) ).any():
122             raise AssertionError("%s != %s within %i places"%(first,second,places))
123     return max(abs(numpy.asarray(first) - numpy.asarray(second)))
124
125 # ==============================================================================
126 if __name__ == "__main__":
127     print('\nAUTODIAGNOSTIC\n')
128     print("""Exemple de la doc :
129
130     Exploitation independante des resultats d'un cas de calcul
131     ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
132     """)
133     xa = test1()
134     ecart = assertAlmostEqualArrays(xa, [ 2., 3., 4.])
135     #
136     print("  L'écart absolu maximal obtenu lors du test est de %.2e."%ecart)
137     print("  Les résultats obtenus sont corrects.")
138     print("")