]> SALOME platform Git repositories - modules/yacs.git/blob - src/yacsloader/driver.py
Salome HOME
[EDF29576] : 2 options remaining
[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 -d 3 --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   int dump = 0;
34 };
35
36     {"display",         'd', "level", 0,                   "Display dot files: 0=never to 3=very often (default 0)"},
37     {"dump",            'g', "nbsec", OPTION_ARG_OPTIONAL, "dump state"},
38     {"save-xml-schema", 'x', "file",  OPTION_ARG_OPTIONAL, "dump xml schema"},
39 """
40
41 my_runtime_yacs = None
42
43 def initializeSALOME():
44     import SALOMERuntime
45     global my_runtime_yacs
46     if my_runtime_yacs:
47       return
48     salome.salome_init()
49     flags = SALOMERuntime.RuntimeSALOME.UsePython + SALOMERuntime.RuntimeSALOME.UseCorba + SALOMERuntime.RuntimeSALOME.UseXml + SALOMERuntime.RuntimeSALOME.UseCpp + SALOMERuntime.RuntimeSALOME.UseSalome
50     SALOMERuntime.RuntimeSALOME.setRuntime( flags )
51     my_runtime_yacs = SALOMERuntime.getSALOMERuntime()
52     anIOR = salome.orb.object_to_string ( salome.modulcat )
53     aCatalog = my_runtime_yacs.loadCatalog( "session", anIOR )
54     my_runtime_yacs.addCatalog( aCatalog )
55
56 def SALOMEInitializationNeeded(func):
57     def decaratedFunc(*args,**kwargs):
58       initializeSALOME()
59       return func(*args,**kwargs)
60     return decaratedFunc
61
62 @SALOMEInitializationNeeded
63 def loadGraph( xmlFileName ):
64     """
65     Args:
66     -----
67     xmlFileName : XML file containing YACS schema
68
69     Returns
70     -------
71
72     SALOMERuntime.SalomeProc : YACS graph instance
73     """
74     l=loader.YACSLoader()
75     p=l.load( xmlFileName )
76     return p
77
78 def patchGraph( proc, squeezeMemory, initPorts, loadStateXmlFile, reset, display):
79     """
80     Args:
81     -----
82
83     proc ( SALOMERuntime.SalomeProc ) : YACS Proc instance to be evaluated
84     squeezeMemory ( bool ) : squeezememory to be activated
85     initPorts (list<string>) : list of bloc.node.port=value.
86     loadStateXmlFile (string) : file if any of state to be loaded inside proc
87     reset (int) : 
88     display (int) :
89     """
90     def parse_init_port(input):
91       """
92       Returns
93       -------
94       node, port, value
95       """
96       node_port, value = input.split("=")
97       nodePortSpl = node_port.split(".")
98       port = nodePortSpl[-1]
99       node = ".".join( nodePortSpl[:-1] )
100       return node,port,value
101        
102     if squeezeMemory:
103       logging.info("SqueezeMemory requested -> update proc")
104       allNodes = proc.getAllRecursiveNodes()
105       for node in allNodes:
106         if isinstance(proc,SALOMERuntime.PythonNode):
107           node.setSqueezeStatus( True )
108     #
109     for initPort in initPorts:
110         node,port,value = parse_init_port(initPort)
111         init_state = proc.setInPortValue(node, port, value)
112         if init_state != value:
113           raise RuntimeError(f"Error on initialization of {initPort}")
114     #
115     if loadStateXmlFile:
116       loader.loadState( proc, loadStateXmlFile )
117       if reset > 0:
118         proc.resetState(reset)
119         proc.exUpdateState()
120     #
121     if display > 0:
122        proc.writeDotInFile("toto")
123          
124 @SALOMEInitializationNeeded
125 def prepareExecution(proc, isStop, dumpErrorFile):
126   """
127   Returns
128   -------
129
130   pilot.ExecutorSwig : Instance of executor
131   """
132   import pilot
133   ex=pilot.ExecutorSwig()
134   if isStop:
135     logging.info(f"Stop has been activated with {dumpErrorFile}")
136     ex.setStopOnError( dumpErrorFile!="", dumpErrorFile )
137   return ex
138
139 @SALOMEInitializationNeeded
140 def executeGraph( executor, proc, finalDump, display ):
141     """
142     Args:
143     -----
144   
145     executor (pilot.ExecutorSwig) : Executor in charge of evaluation.
146     proc ( SALOMERuntime.SalomeProc ) : YACS Proc instance to be evaluated
147     finalDump ( string ) : filename containing final result of graph, if any.
148     display (int) :
149     """
150     import pilot
151     executor.RunW(proc,display)
152     if proc.getEffectiveState() != pilot.DONE:
153       raise RuntimeError( proc.getErrorReport() )
154     #
155     if display > 0:
156        proc.writeDotInFile("titi")
157     #
158     if finalDump:
159       logging.info(f"Final dump requested : {finalDump}")
160       SALOMERuntime.schemaSaveStateUnsafe( proc, finalDump )
161
162 @SALOMEInitializationNeeded
163 def destroyElementsGeneratedByExecutionOfGraph( proc, shutdown ):
164     """
165     Args:
166     -----
167
168     shutdown (int) : shutdown level
169
170     """
171     if shutdown < 999:
172       proc.shutdown(shutdown)
173     salome.dsm.shutdownScopes()
174     my_runtime_yacs.fini( False )
175
176 if __name__ == "__main__":
177     from salome_utils import positionVerbosityOfLoggerRegardingState,setVerboseLevel,setVerbose
178     import argparse
179     parser = argparse.ArgumentParser()
180     parser.add_argument('xmlfilename',help = "XML file containing YACS schema to be executed")
181     parser.add_argument("-d", "--display", dest = "display", type=int, default=[0], nargs=1, help="Display dot files: 0=never to 3=very often")
182     parser.add_argument("-v", "--verbose", dest = "verbose",help="Produce verbose output", action='store_true')
183     parser.add_argument("--stop-on-error",dest="stop",help="Stop on first error", action='store_true')
184     parser.add_argument("-e","--dump-on-error",dest="dumpErrorFile", type=str, const='dumpErrorState.xml', default="", nargs='?', help="Stop on first error and dump state")
185     parser.add_argument("-kt", "--kerneltrace", dest = "kerneltrace",help="Produce verbose of SALOME/KERNEL", action='store_true')
186     parser.add_argument("-f","--dump-final", dest ="finalDump", type=str, const='finalDumpState.xml', default="", nargs='?', help="dump final state")
187     parser.add_argument("--load-state", dest="loadState", type=str, default="", help="Load State from a previous partial execution")
188     parser.add_argument("--shutdown", dest = 'shutdown', type=int , default=1, help="Shutdown the schema: 0=no shutdown to 3=full shutdown")
189     parser.add_argument("--reset", dest = "reset", type=int , default = 0, help="Reset the schema before execution: 0=nothing, 1=reset error nodes to ready state")
190     parser.add_argument("-z","--donotsqueeze", dest = "donotsqueeze", help = "Desactivate squeeze memory optimization.", action='store_true')
191     parser.add_argument("-ip","--init-port", dest = 'init_port', type=str, help="Initialisation value of a port, specified as bloc.node.port=value.")
192     args = parser.parse_args()
193     args.display = args.display[0]
194     #
195     if args.verbose:
196       setVerbose( args.kerneltrace )
197       setVerboseLevel(logging.INFO)
198       positionVerbosityOfLoggerRegardingState()
199     #
200     proc = loadGraph( args.xmlfilename )
201     patchGraph( proc, not args.donotsqueeze, args.init_port.split(","), args.loadState, args.reset, args.display)
202     executor = prepareExecution( proc, args.stop, args.dumpErrorFile)
203     executeGraph( executor, proc, args.finalDump, args.display)
204     destroyElementsGeneratedByExecutionOfGraph( proc, args.shutdown )