Salome HOME
Minor documentation improvements and fixes for internal variables
[modules/adao.git] / test / test6711 / Doc_TUI_Exemple_01_Savings.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, os, tempfile
25 import unittest
26
27 # ==============================================================================
28 class Test_Adao(unittest.TestCase):
29     def test1(self):
30         """Test"""
31         print("""Exemple de la doc :
32
33         Cas-test vérifiant les conversions
34         ++++++++++++++++++++++++++++++++++\n""")
35         #-----------------------------------------------------------------------
36         from numpy import array, matrix
37         from adao import adaoBuilder
38         case = adaoBuilder.New()
39         case.set( 'AlgorithmParameters', Algorithm='3DVAR' )
40         case.set( 'Background',          Vector=[0, 1, 2] )
41         case.set( 'BackgroundError',     ScalarSparseMatrix=1.0 )
42         case.set( 'Observation',         Vector=array([0.5, 1.5, 2.5]) )
43         case.set( 'ObservationError',    DiagonalSparseMatrix='1 1 1' )
44         case.set( 'ObservationOperator', Matrix='1 0 0;0 2 0;0 0 3' )
45         case.set( 'Observer',            Variable="Analysis", Template="ValuePrinter" )
46         #
47         case.setObserver("Analysis", String="print('  ==> Nombre d analyses   : %i'%len(var))")
48         #
49         case.execute()
50         #
51         #-----------------------------------------------------------------------
52         print("")
53         print("  #============================================================")
54         print("  #=== Export du cas")
55         print("  #============================================================")
56         with tempfile.TemporaryDirectory() as tmpdirname:
57             base_file = os.path.join(tmpdirname, "output_test6711")
58             print("  #=== Répertoire temporaire créé")
59             #
60             fname = base_file+"_TUI.py"
61             case.dump(FileName=fname, Formater="TUI")
62             print("  #=== Restitution en fichier TUI")
63             if os.path.exists(fname) and filesize(fname) > 500:
64                 print("  #    Fichier TUI correctement généré, de taille %i bytes"%filesize(fname))
65             else:
66                 raise ValueError("Fichier TUI incorrect ou inexistant")
67             #
68             fname = base_file+"_SCD.py"
69             case.dump(FileName=fname, Formater="SCD")
70             print("  #=== Restitution en fichier SCD")
71             if os.path.exists(fname) and filesize(fname) > 500:
72                 print("  #    Fichier SCD correctement généré, de taille %i bytes"%filesize(fname))
73             else:
74                 raise ValueError("Fichier SCD incorrect ou inexistant")
75             #
76             try:
77                 fname = base_file+"_YACS.xml"
78                 case.dump(FileName=fname, Formater="YACS")
79                 print("  #=== Restitution en fichier YACS")
80                 if os.path.exists(fname) and filesize(fname) > 500:
81                     print("  #    Fichier YACS correctement généré, de taille %i bytes"%filesize(fname))
82                 else:
83                     raise ValueError("Fichier YACS incorrect ou inexistant")
84             except:
85                 pass
86         print("  #=== Répertoire temporaire supprimé")
87         print("  #============================================================")
88         print("")
89         #-----------------------------------------------------------------------
90         xa = case.get("Analysis")[-1]
91         ecart = assertAlmostEqualArrays(xa, [0.25, 0.80, 0.95], places = 5)
92         #
93         print("  L'écart absolu maximal obtenu lors du test est de %.2e."%ecart)
94         print("  Les résultats obtenus sont corrects.")
95         print("")
96         #
97         return xa
98
99 # ==============================================================================
100 def filesize(name):
101     statinfo = os.stat(name)
102     return statinfo.st_size # Bytes
103
104 def assertAlmostEqualArrays(first, second, places=7, msg=None, delta=None):
105     "Compare two vectors, like unittest.assertAlmostEqual"
106     import numpy
107     if msg is not None:
108         print(msg)
109     if delta is not None:
110         if ( numpy.abs(numpy.asarray(first) - numpy.asarray(second)) > float(delta) ).any():
111             raise AssertionError("%s != %s within %s places"%(first,second,delta))
112     else:
113         if ( numpy.abs(numpy.asarray(first) - numpy.asarray(second)) > 10**(-int(places)) ).any():
114             raise AssertionError("%s != %s within %i places"%(first,second,places))
115     return max(abs(numpy.asarray(first) - numpy.asarray(second)))
116
117 # ==============================================================================
118 if __name__ == "__main__":
119     print('\nAUTODIAGNOSTIC\n')
120     sys.stderr = sys.stdout
121     unittest.main(verbosity=2)