Salome HOME
0f2b1f2388cfed04f2423f811da56f4a54e3d9e5
[modules/yacs.git] / src / yacsloader / driver.py
1 # -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2024  CEA, EDF
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20
21 # python3 /home/H87074/salome/990_CEA/SALOME-master-native-DB11-SRC/SOURCES/yacs/src/yacsloader/driver.py -v -kt micro_schema.xml
22 # python3 /home/H87074/salome/990_CEA/SALOME-master-native-DB11-SRC/SOURCES/yacs/src/yacsloader/driver.py --stop-on-error --dump-on-error="popo.xml" -v -kt -ip "PyScript0.p1=7" --dump-final="tutu.xml" micro_schema2.xml
23
24 import loader
25 import SALOMERuntime
26 import salome
27 import logging
28
29 """
30 struct arguments
31 {
32   int display = 0;
33   std::string finalDump;
34   int dump = 0;
35   std::string loadState;
36   int reset = 0;
37 };
38
39     {"display",         'd', "level", 0,                   "Display dot files: 0=never to 3=very often (default 0)"},
40     {"dump-final",      'f', "file",  OPTION_ARG_OPTIONAL, "dump final state"},
41     {"dump",            'g', "nbsec", OPTION_ARG_OPTIONAL, "dump state"},
42     {"load-state",      'l', "file",  0,                   "Load State from a previous partial execution"},
43     {"save-xml-schema", 'x', "file",  OPTION_ARG_OPTIONAL, "dump xml schema"},
44     {"reset",           'r', "level", 0,                   "Reset the schema before execution: 0=nothing, 1=reset error nodes to ready state (default 0)"},
45
46 """
47
48 my_runtime_yacs = None
49
50 def initializeSALOME():
51     import SALOMERuntime
52     global my_runtime_yacs
53     if my_runtime_yacs:
54       return
55     salome.salome_init()
56     flags = SALOMERuntime.RuntimeSALOME.UsePython + SALOMERuntime.RuntimeSALOME.UseCorba + SALOMERuntime.RuntimeSALOME.UseXml + SALOMERuntime.RuntimeSALOME.UseCpp + SALOMERuntime.RuntimeSALOME.UseSalome
57     SALOMERuntime.RuntimeSALOME.setRuntime( flags )
58     my_runtime_yacs = SALOMERuntime.getSALOMERuntime()
59     anIOR = salome.orb.object_to_string ( salome.modulcat )
60     aCatalog = my_runtime_yacs.loadCatalog( "session", anIOR )
61     my_runtime_yacs.addCatalog( aCatalog )
62
63 def SALOMEInitializationNeeded(func):
64     def decaratedFunc(*args,**kwargs):
65       initializeSALOME()
66       return func(*args,**kwargs)
67     return decaratedFunc
68
69 @SALOMEInitializationNeeded
70 def loadGraph( xmlFileName ):
71     """
72     Args:
73     -----
74     xmlFileName : XML file containing YACS schema
75
76     Returns
77     -------
78
79     SALOMERuntime.SalomeProc : YACS graph instance
80     """
81     l=loader.YACSLoader()
82     p=l.load( xmlFileName )
83     return p
84
85 def patchGraph( proc, squeezeMemory, initPorts):
86     """
87     Args:
88     -----
89
90     proc ( SALOMERuntime.SalomeProc ) : YACS Proc instance to be evaluated
91     squeezeMemory ( bool ) : squeezememory to be activated
92     initPorts (list<string>) : list of bloc.node.port=value.
93
94     """
95     def parse_init_port(input):
96       """
97       Returns
98       -------
99       node, port, value
100       """
101       node_port, value = input.split("=")
102       nodePortSpl = node_port.split(".")
103       port = nodePortSpl[-1]
104       node = ".".join( nodePortSpl[:-1] )
105       return node,port,value
106        
107     if squeezeMemory:
108       logging.info("SqueezeMemory requested -> update proc")
109       allNodes = proc.getAllRecursiveNodes()
110       for node in allNodes:
111         if isinstance(proc,SALOMERuntime.PythonNode):
112           node.setSqueezeStatus( True )
113       for initPort in initPorts:
114          node,port,value = parse_init_port(initPort)
115          init_state = proc.setInPortValue(node, port, value)
116          if init_state != value:
117             raise RuntimeError(f"Error on initialization of {initPort}")
118          
119 @SALOMEInitializationNeeded
120 def prepareExecution(proc, isStop, dumpErrorFile):
121   """
122   Returns
123   -------
124
125   pilot.ExecutorSwig : Instance of executor
126   """
127   import pilot
128   ex=pilot.ExecutorSwig()
129   if isStop:
130     logging.info(f"Stop has been activated with {dumpErrorFile}")
131     ex.setStopOnError( dumpErrorFile!="", dumpErrorFile )
132   return ex
133
134 @SALOMEInitializationNeeded
135 def executeGraph( executor, proc, finalDump ):
136     """
137     Args:
138     -----
139   
140     executor (pilot.ExecutorSwig) : Executor in charge of evaluation.
141     proc ( SALOMERuntime.SalomeProc ) : YACS Proc instance to be evaluated
142     finalDump ( string ) : filename containing final result of graph, if any.
143
144     """
145     import pilot
146     executor.RunW(proc,0)
147     if proc.getEffectiveState() != pilot.DONE:
148       raise RuntimeError( proc.getErrorReport() )
149     if finalDump:
150       SALOMERuntime.schemaSaveStateUnsafe( proc, finalDump )
151
152 @SALOMEInitializationNeeded
153 def destroyElementsGeneratedByExecutionOfGraph( proc, shutdown ):
154     """
155     Args:
156     -----
157
158     shutdown (int) : shutdown level
159
160     """
161     if shutdown < 999:
162       proc.shutdown(shutdown)
163     salome.dsm.shutdownScopes()
164     my_runtime_yacs.fini( False )
165
166 if __name__ == "__main__":
167     from salome_utils import positionVerbosityOfLoggerRegardingState,setVerboseLevel,setVerbose
168     import argparse
169     parser = argparse.ArgumentParser()
170     parser.add_argument('xmlfilename',help = "XML file containing YACS schema to be executed")
171     parser.add_argument("-v", "--verbose", dest = "verbose",help="Produce verbose output", action='store_true')
172     parser.add_argument("--stop-on-error",dest="stop",help="Stop on first error", action='store_true')
173     parser.add_argument("--dump-on-error",dest="dumpErrorFile",help="Stop on first error and dump state")
174     parser.add_argument("-kt", "--kerneltrace", dest = "kerneltrace",help="Produce verbose of SALOME/KERNEL", action='store_true')
175     parser.add_argument("--dump-final", dest ="finalDump", type=str, default="", help="dump final state")
176     parser.add_argument("--shutdown", dest = 'shutdown', type=int , default=1, help="Shutdown the schema: 0=no shutdown to 3=full shutdown")
177     parser.add_argument("-z","--donotsqueeze", dest = "donotsqueeze", help = "Desactivate squeeze memory optimization.", action='store_true')
178     parser.add_argument("-ip","--init-port", dest = 'init_port', type=str, help="Initialisation value of a port, specified as bloc.node.port=value.")
179     args = parser.parse_args()
180     #
181     if args.verbose:
182       setVerbose( args.kerneltrace )
183       setVerboseLevel(logging.INFO)
184       positionVerbosityOfLoggerRegardingState()
185     #
186     proc = loadGraph( args.xmlfilename )
187     patchGraph( proc, not args.donotsqueeze, args.init_port.split(","))
188     executor = prepareExecution( proc, args.stop, args.dumpErrorFile)
189     executeGraph( executor, proc, args.finalDump)
190     destroyElementsGeneratedByExecutionOfGraph( proc, args.shutdown )