Salome HOME
Updating test with unittest and extended user case definition
[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 from utExtend import assertAlmostEqualArrays
28
29 # ==============================================================================
30 #
31 # Construction artificielle d'un exemple de donnees utilisateur
32 # -------------------------------------------------------------
33 alpha = 5.
34 beta = 7
35 gamma = 9.0
36 #
37 alphamin, alphamax = 0., 10.
38 betamin,  betamax  = 3, 13
39 gammamin, gammamax = 1.5, 15.5
40 #
41 def simulation(x):
42     "Fonction de simulation H pour effectuer Y=H(X)"
43     import numpy
44     __x = numpy.matrix(numpy.ravel(numpy.matrix(x))).T
45     __H = numpy.matrix("1 0 0;0 2 0;0 0 3; 1 2 3")
46     return __H * __x
47 #
48 def multisimulation( xserie ):
49     yserie = []
50     for x in xserie:
51         yserie.append( simulation( x ) )
52     return yserie
53 #
54 # Observations obtenues par simulation
55 # ------------------------------------
56 observations = simulation((2, 3, 4))
57
58 # ==============================================================================
59 class InTest(unittest.TestCase):
60     def test1(self):
61         print("""Exemple de la doc :
62
63         Exploitation independante des resultats d'un cas de calcul
64         ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
65         """)
66         #
67         import numpy
68         from adao import adaoBuilder
69         #
70         # Mise en forme des entrees
71         # -------------------------
72         Xb = (alpha, beta, gamma)
73         Bounds = (
74             (alphamin, alphamax),
75             (betamin,  betamax ),
76             (gammamin, gammamax))
77         #
78         # TUI ADAO
79         # --------
80         case = adaoBuilder.New()
81         case.set( 'AlgorithmParameters',
82             Algorithm = '3DVAR',                  # Mots-clé réservé
83             Parameters = {                        # Dictionnaire
84                 "Bounds":Bounds,                  # Liste de paires de Real ou de None
85                 "MaximumNumberOfSteps":100,       # Int >= 0
86                 "CostDecrementTolerance":1.e-7,   # Real > 0
87                 "StoreSupplementaryCalculations":[# Liste de mots-clés réservés
88                     "CostFunctionJAtCurrentOptimum",
89                     "CostFunctionJoAtCurrentOptimum",
90                     "CurrentOptimum",
91                     "SimulatedObservationAtCurrentOptimum",
92                     "SimulatedObservationAtOptimum",
93                     ],
94                 }
95             )
96         case.set( 'Background',
97             Vector = numpy.array(Xb),             # array, list, tuple, matrix
98             Stored = True,                        # Bool
99             )
100         case.set( 'Observation',
101             Vector = numpy.array(observations),   # array, list, tuple, matrix
102             Stored = False,                       # Bool
103             )
104         case.set( 'BackgroundError',
105             Matrix = None,                        # None ou matrice carrée
106             ScalarSparseMatrix = 1.0e10,          # None ou Real > 0
107             DiagonalSparseMatrix = None,          # None ou vecteur
108             )
109         case.set( 'ObservationError',
110             Matrix = None,                        # None ou matrice carrée
111             ScalarSparseMatrix = 1.0,             # None ou Real > 0
112             DiagonalSparseMatrix = None,          # None ou vecteur
113             )
114         case.set( 'ObservationOperator',
115             OneFunction = multisimulation,        # MultiFonction [Y] = F([X])
116             Parameters  = {                       # Dictionnaire
117                 "DifferentialIncrement":0.0001,   # Real > 0
118                 "CenteredFiniteDifference":False, # Bool
119                 },
120             InputFunctionAsMulti = True,          # Bool
121             )
122         case.set( 'Observer',
123             Variable = "CurrentState",            # Mot-clé
124             Template = "ValuePrinter",            # Mot-clé
125             String   = None,                      # None ou code Python
126             Info     = None,                      # None ou string
127
128             )
129         case.execute()
130         #
131         # Exploitation independante
132         # -------------------------
133         Xbackground   = case.get("Background")
134         Xoptimum      = case.get("Analysis")[-1]
135         FX_at_optimum = case.get("SimulatedObservationAtOptimum")[-1]
136         J_values      = case.get("CostFunctionJAtCurrentOptimum")[:]
137         print("")
138         print("Number of internal iterations...: %i"%len(J_values))
139         print("Initial state...................: %s"%(numpy.ravel(Xbackground),))
140         print("Optimal state...................: %s"%(numpy.ravel(Xoptimum),))
141         print("Simulation at optimal state.....: %s"%(numpy.ravel(FX_at_optimum),))
142         print("")
143         #
144         ecart = assertAlmostEqualArrays(Xoptimum, [ 2., 3., 4.])
145         #
146         print("  L'écart absolu maximal obtenu lors du test est de %.2e."%ecart)
147         print("  Les résultats obtenus sont corrects.")
148         print("")
149         #
150         return Xoptimum
151
152 # ==============================================================================
153 if __name__ == '__main__':
154     print("\nAUTODIAGNOSTIC\n==============")
155     unittest.main()