Salome HOME
Fixup for tests details
[modules/adao.git] / test / test6904 / Definition_complete_de_cas_3DVAR.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 import sys
25 import unittest
26 import numpy
27
28 # ==============================================================================
29 #
30 # Construction artificielle d'un exemple de donnees utilisateur
31 # -------------------------------------------------------------
32 alpha = 5.
33 beta = 7
34 gamma = 9.0
35 #
36 alphamin, alphamax = 0., 10.
37 betamin,  betamax  = 3, 13
38 gammamin, gammamax = 1.5, 15.5
39 #
40 def simulation(x):
41     "Fonction de simulation H pour effectuer Y=H(X)"
42     import numpy
43     __x = numpy.matrix(numpy.ravel(numpy.matrix(x))).T
44     __H = numpy.matrix("1 0 0;0 2 0;0 0 3; 1 2 3")
45     return __H * __x
46 #
47 def multisimulation( xserie ):
48     yserie = []
49     for x in xserie:
50         yserie.append( simulation( x ) )
51     return yserie
52 #
53 # Observations obtenues par simulation
54 # ------------------------------------
55 observations = simulation((2, 3, 4))
56
57 # ==============================================================================
58 class InTest(unittest.TestCase):
59     def test1(self):
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( 'AlgorithmParameters',
81             Algorithm = '3DVAR',                  # Mots-clé réservé
82             Parameters = {                        # Dictionnaire
83                 "Bounds":Bounds,                  # Liste de paires de Real ou de None
84                 "MaximumNumberOfSteps":100,       # Int >= 0
85                 "CostDecrementTolerance":1.e-7,   # Real > 0
86                 "StoreSupplementaryCalculations":[# Liste de mots-clés réservés
87                     "CostFunctionJAtCurrentOptimum",
88                     "CostFunctionJoAtCurrentOptimum",
89                     "CurrentOptimum",
90                     "SimulatedObservationAtCurrentOptimum",
91                     "SimulatedObservationAtOptimum",
92                     ],
93                 }
94             )
95         case.set( 'Background',
96             Vector = numpy.array(Xb),             # array, list, tuple, matrix
97             Stored = True,                        # Bool
98             )
99         case.set( 'Observation',
100             Vector = numpy.array(observations),   # array, list, tuple, matrix
101             Stored = False,                       # Bool
102             )
103         case.set( 'BackgroundError',
104             Matrix = None,                        # None ou matrice carrée
105             ScalarSparseMatrix = 1.0e10,          # None ou Real > 0
106             DiagonalSparseMatrix = None,          # None ou vecteur
107             )
108         case.set( 'ObservationError',
109             Matrix = None,                        # None ou matrice carrée
110             ScalarSparseMatrix = 1.0,             # None ou Real > 0
111             DiagonalSparseMatrix = None,          # None ou vecteur
112             )
113         case.set( 'ObservationOperator',
114             OneFunction = multisimulation,        # MultiFonction [Y] = F([X])
115             Parameters  = {                       # Dictionnaire
116                 "DifferentialIncrement":0.0001,   # Real > 0
117                 "CenteredFiniteDifference":False, # Bool
118                 },
119             InputFunctionAsMulti = True,          # Bool
120             )
121         case.set( 'Observer',
122             Variable = "CurrentState",            # Mot-clé
123             Template = "ValuePrinter",            # Mot-clé
124             String   = None,                      # None ou code Python
125             Info     = None,                      # None ou string
126
127             )
128         case.execute()
129         #
130         # Exploitation independante
131         # -------------------------
132         Xbackground   = case.get("Background")
133         Xoptimum      = case.get("Analysis")[-1]
134         FX_at_optimum = case.get("SimulatedObservationAtOptimum")[-1]
135         J_values      = case.get("CostFunctionJAtCurrentOptimum")[:]
136         print("")
137         print("Number of internal iterations...: %i"%len(J_values))
138         print("Initial state...................: %s"%(numpy.ravel(Xbackground),))
139         print("Optimal state...................: %s"%(numpy.ravel(Xoptimum),))
140         print("Simulation at optimal state.....: %s"%(numpy.ravel(FX_at_optimum),))
141         print("")
142         #
143         # Fin du cas
144         # ----------
145         ecart = assertAlmostEqualArrays(Xoptimum, [ 2., 3., 4.])
146         #
147         print("  L'écart absolu maximal obtenu lors du test est de %.2e."%ecart)
148         print("  Les résultats obtenus sont corrects.")
149         print("")
150         #
151         return Xoptimum
152
153 # ==============================================================================
154 def assertAlmostEqualArrays(first, second, places=7, msg=None, delta=None):
155     "Compare two vectors, like unittest.assertAlmostEqual"
156     import numpy
157     if msg is not None:
158         print(msg)
159     if delta is not None:
160         if ( (numpy.asarray(first) - numpy.asarray(second)) > float(delta) ).any():
161             raise AssertionError("%s != %s within %s places"%(first,second,delta))
162     else:
163         if ( (numpy.asarray(first) - numpy.asarray(second)) > 10**(-int(places)) ).any():
164             raise AssertionError("%s != %s within %i places"%(first,second,places))
165     return max(abs(numpy.asarray(first) - numpy.asarray(second)))
166
167 # ==============================================================================
168 if __name__ == '__main__':
169     print("\nAUTODIAGNOSTIC\n==============")
170     unittest.main()