Salome HOME
Correction and support extension of YACS/TUI export (4)
[modules/adao.git] / test / test6904 / Definition_complete_de_cas_Blue.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2008-2020 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 Test_Adao(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 = 'Blue',                   # Mots-clé réservé
81             Parameters = {                        # Dictionnaire
82                 "StoreSupplementaryCalculations":[# Liste de mots-clés réservés
83                     "CostFunctionJAtCurrentOptimum",
84                     "CostFunctionJoAtCurrentOptimum",
85                     "CurrentOptimum",
86                     "SimulatedObservationAtCurrentOptimum",
87                     "SimulatedObservationAtOptimum",
88                     ],
89                 }
90             )
91         case.set( 'Background',
92             Vector = Xb,                          # array, list, tuple, matrix
93             Stored = True,                        # Bool
94             )
95         case.set( 'Observation',
96             Vector = observations,                # array, list, tuple, matrix
97             Stored = False,                       # Bool
98             )
99         case.set( 'BackgroundError',
100             Matrix = None,                        # None ou matrice carrée
101             ScalarSparseMatrix = 1.0e10,          # None ou Real > 0
102             DiagonalSparseMatrix = None,          # None ou vecteur
103             )
104         case.set( 'ObservationError',
105             Matrix = None,                        # None ou matrice carrée
106             ScalarSparseMatrix = 1.0,             # None ou Real > 0
107             DiagonalSparseMatrix = None,          # None ou vecteur
108             )
109         case.set( 'ObservationOperator',
110             OneFunction = multisimulation,        # MultiFonction [Y] = F([X])
111             Parameters  = {                       # Dictionnaire
112                 "DifferentialIncrement":0.0001,   # Real > 0
113                 "CenteredFiniteDifference":False, # Bool
114                 },
115             InputFunctionAsMulti = True,          # Bool
116             )
117         case.set( 'Observer',
118             Variable = "CurrentState",            # Mot-clé
119             Template = "ValuePrinter",            # Mot-clé
120             String   = None,                      # None ou code Python
121             Info     = None,                      # None ou string
122
123             )
124         case.execute()
125         #
126         # Exploitation independante
127         # -------------------------
128         Xbackground   = case.get("Background")
129         Xoptimum      = case.get("Analysis")[-1]
130         FX_at_optimum = case.get("SimulatedObservationAtOptimum")[-1]
131         J_values      = case.get("CostFunctionJAtCurrentOptimum")[:]
132         print("")
133         print("Number of internal iterations...: %i"%len(J_values))
134         print("Initial state...................: %s"%(numpy.ravel(Xbackground),))
135         print("Optimal state...................: %s"%(numpy.ravel(Xoptimum),))
136         print("Simulation at optimal state.....: %s"%(numpy.ravel(FX_at_optimum),))
137         print("")
138         #
139         # Fin du cas
140         # ----------
141         ecart = assertAlmostEqualArrays(Xoptimum, [ 2., 3., 4.])
142         #
143         print("The maximal absolute error in the test is of %.2e."%ecart)
144         print("The results are correct.")
145         print("")
146         #
147         return Xoptimum
148
149 # ==============================================================================
150 def assertAlmostEqualArrays(first, second, places=7, msg=None, delta=None):
151     "Compare two vectors, like unittest.assertAlmostEqual"
152     import numpy
153     if msg is not None:
154         print(msg)
155     if delta is not None:
156         if ( numpy.abs(numpy.asarray(first) - numpy.asarray(second)) > float(delta) ).any():
157             raise AssertionError("%s != %s within %s places"%(first,second,delta))
158     else:
159         if ( numpy.abs(numpy.asarray(first) - numpy.asarray(second)) > 10**(-int(places)) ).any():
160             raise AssertionError("%s != %s within %i places"%(first,second,places))
161     return max(abs(numpy.asarray(first) - numpy.asarray(second)))
162
163 # ==============================================================================
164 if __name__ == '__main__':
165     print("\nAUTODIAGNOSTIC\n==============")
166     sys.stderr = sys.stdout
167     unittest.main(verbosity=2)