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