Salome HOME
Improve ADAO test install
[modules/adao.git] / test / test6703 / Doc_TUI_Exemple_03.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 # Observations obtenues par simulation
44 # ------------------------------------
45 observations = simulation((2, 3, 4))
46
47 # ==============================================================================
48 def test1():
49     "Test"
50     import numpy
51     from adao import adaoBuilder
52     #
53     # Mise en forme des entrees
54     # -------------------------
55     Xb = (alpha, beta, gamma)
56     Bounds = (
57         (alphamin, alphamax),
58         (betamin,  betamax ),
59         (gammamin, gammamax))
60     #
61     # TUI ADAO
62     # --------
63     case = adaoBuilder.New()
64     case.set(
65         'AlgorithmParameters',
66         Algorithm = '3DVAR',
67         Parameters = {
68             "Bounds":Bounds,
69             "MaximumNumberOfSteps":100,
70             "StoreSupplementaryCalculations":[
71                 "CostFunctionJ",
72                 "CurrentState",
73                 "SimulatedObservationAtOptimum",
74                 ],
75             }
76         )
77     case.set( 'Background', Vector = numpy.array(Xb), Stored = True )
78     case.set( 'Observation', Vector = numpy.array(observations) )
79     case.set( 'BackgroundError', ScalarSparseMatrix = 1.0e10 )
80     case.set( 'ObservationError', ScalarSparseMatrix = 1.0 )
81     case.set(
82         'ObservationOperator',
83         OneFunction = simulation,
84         Parameters  = {"DifferentialIncrement":0.0001},
85         )
86     case.set( 'Observer', Variable="CurrentState", Template="ValuePrinter" )
87     case.execute()
88     #
89     # Exploitation independante
90     # -------------------------
91     Xbackground   = case.get("Background")
92     Xoptimum      = case.get("Analysis")[-1]
93     FX_at_optimum = case.get("SimulatedObservationAtOptimum")[-1]
94     J_values      = case.get("CostFunctionJ")[:]
95     print("")
96     print("Number of internal iterations...: %i"%len(J_values))
97     print("Initial state...................: %s"%(numpy.ravel(Xbackground),))
98     print("Optimal state...................: %s"%(numpy.ravel(Xoptimum),))
99     print("Simulation at optimal state.....: %s"%(numpy.ravel(FX_at_optimum),))
100     print("")
101     #
102     return case.get("Analysis")[-1]
103
104 # ==============================================================================
105 def assertAlmostEqualArrays(first, second, places=7, msg=None, delta=None):
106     "Compare two vectors, like unittest.assertAlmostEqual"
107     import numpy
108     if msg is not None:
109         print(msg)
110     if delta is not None:
111         if ( (numpy.asarray(first) - numpy.asarray(second)) > float(delta) ).any():
112             raise AssertionError("%s != %s within %s places"%(first,second,delta))
113     else:
114         if ( (numpy.asarray(first) - numpy.asarray(second)) > 10**(-int(places)) ).any():
115             raise AssertionError("%s != %s within %i places"%(first,second,places))
116     return max(abs(numpy.asarray(first) - numpy.asarray(second)))
117
118 # ==============================================================================
119 if __name__ == "__main__":
120     print('\nAUTODIAGNOSTIC\n')
121     print("""Exemple de la doc :
122
123     Exploitation independante des resultats d'un cas de calcul
124     ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
125     """)
126     xa = test1()
127     ecart = assertAlmostEqualArrays(xa, [ 2., 3., 4.])
128     #
129     print("  L'écart absolu maximal obtenu lors du test est de %.2e."%ecart)
130     print("  Les résultats obtenus sont corrects.")
131     print("")