Salome HOME
Remove useless dependency to py2cpp.
[tools/adao_interface.git] / Cases / 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 "Full definition of a use case for the standard user"
23
24 import sys
25 import unittest
26 import numpy
27
28 # ==============================================================================
29 #
30 # Artificial user data example
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     "Observation operator H for Y=H(X)"
42     import numpy
43     __x = numpy.ravel(x)
44     __H = numpy.array([[1, 0, 0], [0, 2, 0], [0, 0, 3], [1, 2, 3]])
45     return numpy.dot(__H,__x)
46 #
47 def multisimulation( xserie ):
48     yserie = []
49     for x in xserie:
50         yserie.append( simulation( x ) )
51     return yserie
52 #
53 # Twin experiment observations
54 # ----------------------------
55 observations = simulation((2, 3, 4))
56
57 # ==============================================================================
58 class InTest(unittest.TestCase):
59     def test1(self):
60         print("""
61         Full definition of a use case for the standard user
62         +++++++++++++++++++++++++++++++++++++++++++++++++++
63         """)
64         #
65         import numpy
66         from adao import adaoBuilder
67         #
68         # Mise en forme des entrees
69         # -------------------------
70         Xb = (alpha, beta, gamma)
71         Bounds = (
72             (alphamin, alphamax),
73             (betamin,  betamax ),
74             (gammamin, gammamax))
75         #
76         # TUI ADAO
77         # --------
78         case = adaoBuilder.New()
79         case.set( 'AlgorithmParameters',
80             Algorithm = '3DVAR',                  # Mots-clé réservé
81             Parameters = {                        # Dictionnaire
82                 "Bounds":Bounds,                  # Liste de paires de Real ou de None
83                 "MaximumNumberOfSteps":100,       # Int >= 0
84                 "CostDecrementTolerance":1.e-7,   # Real > 0
85                 "StoreSupplementaryCalculations":[# Liste de mots-clés réservés
86                     "CostFunctionJAtCurrentOptimum",
87                     "CostFunctionJoAtCurrentOptimum",
88                     "CurrentOptimum",
89                     "SimulatedObservationAtCurrentOptimum",
90                     "SimulatedObservationAtOptimum",
91                     ],
92                 }
93             )
94         case.set( 'Background',
95             Vector = Xb,                          # array, list, tuple, matrix
96             Stored = True,                        # Bool
97             )
98         case.set( 'Observation',
99             Vector = observations,                # array, list, tuple, matrix
100             Stored = False,                       # Bool
101             )
102         case.set( 'BackgroundError',
103             Matrix = None,                        # None ou matrice carrée
104             ScalarSparseMatrix = 1.0e10,          # None ou Real > 0
105             DiagonalSparseMatrix = None,          # None ou vecteur
106             )
107         case.set( 'ObservationError',
108             Matrix = None,                        # None ou matrice carrée
109             ScalarSparseMatrix = 1.0,             # None ou Real > 0
110             DiagonalSparseMatrix = None,          # None ou vecteur
111             )
112         case.set( 'ObservationOperator',
113             OneFunction = multisimulation,        # MultiFonction [Y] = F([X])
114             Parameters  = {                       # Dictionnaire
115                 "DifferentialIncrement":0.0001,   # Real > 0
116                 "CenteredFiniteDifference":False, # Bool
117                 },
118             InputFunctionAsMulti = True,          # Bool
119             )
120         case.set( 'Observer',
121             Variable = "CurrentState",            # Mot-clé
122             Template = "ValuePrinter",            # Mot-clé
123             String   = None,                      # None ou code Python
124             Info     = None,                      # None ou string
125
126             )
127         case.execute()
128         #
129         # Exploitation independante
130         # -------------------------
131         Xbackground   = case.get("Background")
132         Xoptimum      = case.get("Analysis")[-1]
133         FX_at_optimum = case.get("SimulatedObservationAtOptimum")[-1]
134         J_values      = case.get("CostFunctionJAtCurrentOptimum")[:]
135         print("")
136         print("Number of internal iterations...: %i"%len(J_values))
137         print("Initial state...................: %s"%(numpy.ravel(Xbackground),))
138         print("Optimal state...................: %s"%(numpy.ravel(Xoptimum),))
139         print("Simulation at optimal state.....: %s"%(numpy.ravel(FX_at_optimum),))
140         print("")
141         #
142         # Fin du cas
143         # ----------
144         ecart = assertAlmostEqualArrays(Xoptimum, [ 2., 3., 4.])
145         #
146         print("  The maximal absolute error in the test is of %.2e."%ecart)
147         print("  The results are correct.")
148         print("")
149         #
150         return Xoptimum
151
152 # ==============================================================================
153 def assertAlmostEqualArrays(first, second, places=7, msg=None, delta=None):
154     "Compare two vectors, like unittest.assertAlmostEqual"
155     import numpy
156     if msg is not None:
157         print(msg)
158     if delta is not None:
159         if ( (numpy.asarray(first) - numpy.asarray(second)) > float(delta) ).any():
160             raise AssertionError("%s != %s within %s places"%(first,second,delta))
161     else:
162         if ( (numpy.asarray(first) - numpy.asarray(second)) > 10**(-int(places)) ).any():
163             raise AssertionError("%s != %s within %i places"%(first,second,places))
164     return max(abs(numpy.asarray(first) - numpy.asarray(second)))
165
166 # ==============================================================================
167 if __name__ == '__main__':
168     print("\nAUTODIAGNOSTIC\n==============")
169     unittest.main()