Salome HOME
Python is no longer initialized by YACSEvalSession.
[modules/yacs.git] / src / evalyfx / YACSEvalYFXPattern.cxx
1 // Copyright (C) 2012-2016  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // Author : Anthony Geay (EDF R&D)
20
21 #include "YACSEvalYFXPattern.hxx"
22 #include "YACSEvalResource.hxx"
23 #include "YACSEvalSeqAny.hxx"
24 #include "YACSEvalSession.hxx"
25 #include "YACSEvalObserver.hxx"
26 #include "YACSEvalSessionInternal.hxx"
27 #include "YACSEvalAutoPtr.hxx"
28 #include "YACSEvalExecParams.hxx"
29
30 #include "ElementaryNode.hxx"
31 #include "RuntimeSALOME.hxx"
32 #include "Dispatcher.hxx"
33 #include "Executor.hxx"
34 #include "InputPort.hxx"
35 #include "LinkInfo.hxx"
36 #include "TypeCode.hxx"
37 #include "Proc.hxx"
38 #include "Dispatcher.hxx"
39
40 #include "PythonPorts.hxx"
41 #include "ForEachLoop.hxx"
42 #include "PythonNode.hxx"
43 #include "InlineNode.hxx"
44 #include "ServiceNode.hxx"
45 #include "PyStdout.hxx"
46 #include "AutoGIL.hxx"
47
48 #include "ResourcesManager.hxx"
49
50 #include <map>
51 #include <limits>
52 #include <numeric>
53 #include <sstream>
54 #include <iterator>
55
56 ////
57 #include <stdlib.h>
58
59 const char YACSEvalYFXPattern::ST_OK[]="ALL_OK";
60
61 const char YACSEvalYFXPattern::ST_FAILED[]="SOME_SAMPLES_FAILED_AND_ALL_OF_THEM_FAILED_DETERMINISTICALLY";
62
63 const char YACSEvalYFXPattern::ST_ERROR[]="SOME_SAMPLES_FAILED_BUT_IMPOSSIBLE_TO_CONCLUDE_ON_THEM";
64
65 const std::size_t YACSEvalYFXPattern::MAX_LGTH_OF_INP_DUMP=10000;
66
67 const char YACSEvalYFXGraphGen::DFT_PROC_NAME[]="YFX";
68
69 const char YACSEvalYFXGraphGen::FIRST_FE_SUBNODE_NAME[]="Bloc";
70
71 const char YACSEvalYFXGraphGen::GATHER_NODE_NAME[]="__gather__";
72
73 class MyAutoThreadSaver
74 {
75 public:
76   MyAutoThreadSaver(bool isToSave):_isToSave(isToSave),_save(0)
77   {
78     if(_isToSave)
79       {
80         PyThreadState *save(PyThreadState_Swap(NULL));// safe call of PyEval_SaveThread()
81         if(save)
82           {
83             _save=save;
84             PyEval_ReleaseLock();
85           }
86       }
87   }
88   ~MyAutoThreadSaver() { if(_isToSave) if(_save) { PyEval_AcquireLock(); PyThreadState_Swap(_save); /*safe call of PyEval_RestoreThread*/ } }
89 private:
90   bool _isToSave;
91   PyThreadState *_save;
92 };
93
94 std::vector< YACSEvalInputPort *> YACSEvalYFXPattern::getFreeInputPorts() const
95 {
96   std::size_t sz(_inputs.size());
97   std::vector< YACSEvalInputPort *> ret;
98   std::vector< YACSEvalInputPort >::const_iterator it(_inputs.begin());
99   for(std::size_t i=0;i<sz;i++,it++)
100     ret.push_back(const_cast<YACSEvalInputPort *>(&(*it)));
101   return ret;
102 }
103
104 std::vector< YACSEvalOutputPort *> YACSEvalYFXPattern::getFreeOutputPorts() const
105 {
106   std::size_t sz(_outputs.size());
107   std::vector< YACSEvalOutputPort *> ret;
108   std::vector< YACSEvalOutputPort >::const_iterator it(_outputs.begin());
109   for(std::size_t i=0;i<sz;i++,it++)
110     ret.push_back(const_cast<YACSEvalOutputPort *>(&(*it)));
111   return ret;
112 }
113
114 YACSEvalYFXPattern *YACSEvalYFXPattern::FindPatternFrom(YACSEvalYFX *boss, YACS::ENGINE::Proc *scheme, bool ownScheme)
115 {
116   if(!scheme)
117     throw YACS::Exception("YACSEvalYFXPattern::FindPatternFrom : input scheme must be not null !");
118   {
119       YACS::ENGINE::ComposedNode *zeRunNode(0);
120       bool isMatchingRunOnlyPattern(YACSEvalYFXRunOnlyPattern::IsMatching(scheme,zeRunNode));
121       if(isMatchingRunOnlyPattern)
122         return new YACSEvalYFXRunOnlyPattern(boss,scheme,ownScheme,zeRunNode);
123   }
124   throw YACS::Exception("YACSEvalYFXPattern::FindPatternFrom : no pattern found for the input scheme !");
125 }
126
127 bool YACSEvalYFXPattern::isAlreadyComputedResources() const
128 {
129   return _res!=0;
130 }
131
132 void YACSEvalYFXPattern::checkNonAlreadyComputedResources() const
133 {
134   if(isAlreadyComputedResources())
135     throw YACS::Exception("checkNonAlreadyComputedResources : instance of computed resources already computed !");
136 }
137
138 void YACSEvalYFXPattern::checkAlreadyComputedResources() const
139 {
140   if(!isAlreadyComputedResources())
141     throw YACS::Exception("checkAlreadyComputedResources : instance of computed resources not already computed !");
142 }
143
144 void YACSEvalYFXPattern::checkLocked() const
145 {
146   if(!isLocked())
147     throw YACS::Exception("YACSEvalYFXPattern::checkLocked : Pattern is not locked !");
148 }
149
150 void YACSEvalYFXPattern::checkNonLocked() const
151 {
152   if(isLocked())
153     throw YACS::Exception("YACSEvalYFXPattern::checkNonLocked : Pattern is locked !");
154 }
155
156 void YACSEvalYFXPattern::CheckNodeIsOK(YACS::ENGINE::ComposedNode *node)
157 {
158   /*YACS::ENGINE::LinkInfo info(YACS::ENGINE::LinkInfo::WARN_ONLY_DONT_STOP);
159   try
160   {
161       node->checkConsistency(info);
162   }
163   catch(YACS::Exception& e)
164   {
165   }
166   if(info.getNumberOfErrLinks(YACS::ENGINE::E_ALL)!=0)
167     throw YACS::Exception("YACSEvalYFXPattern::CheckNodeIsOK : found node is not OK !");
168   std::list<YACS::ENGINE::ElementaryNode *> allNodes(node->getRecursiveConstituents());
169   for(std::list<YACS::ENGINE::ElementaryNode *>::const_iterator it=allNodes.begin();it!=allNodes.end();it++)
170     {
171       YACS::ENGINE::ServiceNode *node0(dynamic_cast<YACS::ENGINE::ServiceNode *>(*it));
172       YACS::ENGINE::InlineNode *node1(dynamic_cast<YACS::ENGINE::InlineNode *>(*it));
173       if(node0)
174         {
175           YACS::ENGINE::Container *cont(node0->getContainer());
176           YACS::ENGINE::ComponentInstance *comp(node0->getComponent());
177           if(!cont || !comp)
178             {
179               std::ostringstream oss; oss << "YACSEvalYFXPattern::CheckNodeIsOK : ServiceNode called \"" << node0->getName() << "\" is not correctly defined !";
180               throw YACS::Exception(oss.str());
181             }
182         }
183       if(node1)
184         {
185           YACS::ENGINE::Container *cont(node1->getContainer());
186           if(!cont && node1->getExecutionMode()==YACS::ENGINE::InlineNode::REMOTE_STR)
187             {
188               std::ostringstream oss; oss << "YACSEvalYFXPattern::CheckNodeIsOK : InlineNode called \"" << node1->getName() << "\" is not correctly defined !";
189               throw YACS::Exception(oss.str());
190             }
191         }
192     }*/
193 }
194
195 void YACSEvalYFXPattern::registerObserver(YACSEvalObserver *observer)
196 {
197   if(_observer==observer)
198     return ;
199   if(_observer)
200     _observer->decrRef();
201   _observer=observer;
202   if(_observer)
203     _observer->incrRef();
204 }
205
206 YACSEvalYFXPattern::YACSEvalYFXPattern(YACSEvalYFX *boss, YACS::ENGINE::Proc *scheme, bool ownScheme):_boss(boss),_scheme(scheme),_ownScheme(ownScheme),_parallelizeStatus(true),_rm(new ResourcesManager_cpp),_res(0),_observer(0)
207 {
208 }
209
210 YACS::ENGINE::TypeCode *YACSEvalYFXPattern::CreateSeqTypeCodeFrom(YACS::ENGINE::Proc *scheme, const std::string& zeType)
211 {
212   std::ostringstream oss; oss << "list[" << zeType << "]";
213   YACS::ENGINE::TypeCode *tc(scheme->getTypeCode(zeType));
214   return scheme->createSequenceTc(oss.str(),oss.str(),tc);
215 }
216
217 void YACSEvalYFXPattern::setResources(YACSEvalListOfResources *res)
218 {
219   checkNonAlreadyComputedResources();
220   if(res!=_res)
221     delete _res;
222   _res=res;
223 }
224
225 void YACSEvalYFXPattern::resetResources()
226 {
227   delete _res;
228   _res=0;
229 }
230
231 YACSEvalSeqAny *YACSEvalYFXPattern::BuildValueInPort(YACS::ENGINE::InputPyPort *port)
232 {
233   if(!port)
234     throw YACS::Exception("YACSEvalYFXPattern::GetValueInPort : null input port !");
235   PyObject *obj(port->getPyObj());
236   YACS::ENGINE::TypeCode *tc(port->edGetType());
237   YACS::ENGINE::TypeCodeSeq *tcc(dynamic_cast<YACS::ENGINE::TypeCodeSeq *>(tc));
238   if(!tcc)
239     {
240       std::ostringstream oss; oss << "YACSEvalYFXPattern::GetValueInPort : internal error for tc of input \"" << port->getName() << "\"";
241       throw YACS::Exception(oss.str());
242     }
243   const YACS::ENGINE::TypeCode *tcct(tcc->contentType());
244   if(!PyList_Check(obj))
245     throw YACS::Exception("YACSEvalYFXPattern::GetValueInPort : internal error 2 !");
246   std::size_t sz(PyList_Size(obj));
247   if(tcct->kind()==YACS::ENGINE::Double)
248     {
249       std::vector<double> eltCpp(sz);
250       for(std::size_t i=0;i<sz;i++)
251         {
252           PyObject *elt(PyList_GetItem(obj,i));
253           eltCpp[i]=PyFloat_AsDouble(elt);
254         }
255       YACS::AutoCppPtr<YACSEvalSeqAnyDouble> elt(new YACSEvalSeqAnyDouble(eltCpp));
256       return elt.dettach();
257     }
258   else if(tcct->kind()==YACS::ENGINE::Int)
259     {
260       std::vector<int> eltCpp(sz);
261       for(std::size_t i=0;i<sz;i++)
262         {
263           PyObject *elt(PyList_GetItem(obj,i));
264           eltCpp[i]=PyInt_AsLong(elt);
265         }
266       YACS::AutoCppPtr<YACSEvalSeqAnyInt> elt(new YACSEvalSeqAnyInt(eltCpp));
267       return elt.dettach();
268     }
269   else
270     throw YACS::Exception("YACSEvalYFXPattern::GetValueInPort : not implemented yet for other than Double and Int !");
271 }
272
273 YACSEvalSeqAny *YACSEvalYFXPattern::BuildValueFromEngineFrmt(YACS::ENGINE::SequenceAny *data)
274 {
275   unsigned int sz(data->size());
276   std::vector<double> eltCpp(sz);
277   for(unsigned int ii=0;ii<sz;ii++)
278     {
279       YACS::ENGINE::AnyPtr elt((*data)[ii]);
280       YACS::ENGINE::Any *eltPtr((YACS::ENGINE::Any *)elt);
281       YACS::ENGINE::AtomAny *eltPtr2(dynamic_cast<YACS::ENGINE::AtomAny *>(eltPtr));
282       if(!eltPtr2)
283         {
284           std::ostringstream oss; oss << "YACSEvalYFXPattern::BuildValueFromEngineFrmt : error at pos #" << ii << " ! It is not an AtomAny !";
285           throw YACS::Exception(oss.str());
286         }
287       eltCpp[ii]=eltPtr2->getDoubleValue();
288     }
289   return new YACSEvalSeqAnyDouble(eltCpp);
290 }
291
292 void YACSEvalYFXPattern::cleanScheme()
293 {
294   if(_ownScheme)
295     delete _scheme;
296   _scheme=0;
297 }
298
299 YACSEvalYFXPattern::~YACSEvalYFXPattern()
300 {
301   if(_observer)
302     _observer->decrRef();
303   delete _rm;
304   delete _res;
305 }
306
307 /////////////////////
308
309 class YACSEvalYFXRunOnlyPatternInternalObserver : public YACS::ENGINE::Observer
310 {
311 public:
312   YACSEvalYFXRunOnlyPatternInternalObserver(YACSEvalYFXRunOnlyPattern *boss):_boss(boss) { if(!_boss) throw YACS::Exception("YACSEvalYFXRunOnlyPatternInternalObserver constructor : null boss not supported :)"); }
313   void notifyObserver2(YACS::ENGINE::Node *object, const std::string& event, void *something);
314 private:
315   YACSEvalYFXRunOnlyPattern *_boss;
316 };
317
318 void YACSEvalYFXRunOnlyPatternInternalObserver::notifyObserver2(YACS::ENGINE::Node *object, const std::string& event, void *something)
319 {
320   YACS::ENGINE::ForEachLoop *object2(_boss->getUndergroundForEach());
321   YACSEvalObserver *obs(_boss->getObserver());
322   if(!obs)
323     return ;
324   if(event=="progress_ok" && object2==object)
325     {
326       int *casted(reinterpret_cast<int *>(something));
327       obs->notifySampleOK(_boss->getBoss(),*casted);
328       return ;
329     }
330   if(event=="progress_ko" && object2==object)
331     {
332       int *casted(reinterpret_cast<int *>(something));
333       obs->notifySampleKO(_boss->getBoss(),*casted);
334       return ;
335     }
336 }
337
338 /////////////////////
339
340 YACSEvalYFXRunOnlyPattern::YACSEvalYFXRunOnlyPattern(YACSEvalYFX *boss, YACS::ENGINE::Proc *scheme, bool ownScheme, YACS::ENGINE::ComposedNode *runNode):YACSEvalYFXPattern(boss,scheme,ownScheme),_lockedStatus(false),_runNode(runNode),_gen(0),_obs(new YACSEvalYFXRunOnlyPatternInternalObserver(this))
341 {
342   if(!_runNode)
343     throw YACS::Exception("YACSEvalYFXRunOnlyPattern : internal run node must be not null !");
344   buildInputPorts();
345   buildOutputPorts();
346 }
347
348 YACSEvalYFXRunOnlyPattern::~YACSEvalYFXRunOnlyPattern()
349 {
350   delete _obs;
351   delete _gen;
352 }
353
354 void YACSEvalYFXRunOnlyPattern::setOutPortsOfInterestForEvaluation(const std::vector<YACSEvalOutputPort *>& outputsOfInterest)
355 {
356   checkNonLocked();
357   _outputsOfInterest=outputsOfInterest;
358   _lockedStatus=true;
359 }
360
361 void YACSEvalYFXRunOnlyPattern::resetOutputsOfInterest()
362 {
363   checkLocked();
364   _outputsOfInterest.clear();
365   _lockedStatus=false;
366 }
367
368 void YACSEvalYFXRunOnlyPattern::generateGraph()
369 {
370   delete _gen;
371   if(getResourcesInternal()->isInteractive())
372     _gen=new YACSEvalYFXGraphGenInteractive(this);
373   else
374     _gen=new YACSEvalYFXGraphGenCluster(this);
375   _gen->generateGraph();
376 }
377
378 void YACSEvalYFXRunOnlyPattern::resetGeneratedGraph()
379 {
380   if(_gen)
381     _gen->resetGeneratedGraph();
382 }
383
384 int YACSEvalYFXRunOnlyPattern::assignNbOfBranches()
385 {
386   checkAlreadyComputedResources();
387   if(!_gen)
388     throw YACS::Exception("YACSEvalYFXRunOnlyPattern::assignNbOfBranches : generator is NULL ! Please invoke generateGraph before !");
389   return _gen->assignNbOfBranches();
390 }
391
392 void YACSEvalYFXRunOnlyPattern::assignRandomVarsInputs()
393 {
394   std::size_t sz(std::numeric_limits<std::size_t>::max());
395   for(std::vector< YACSEvalInputPort >::const_iterator it=_inputs.begin();it!=_inputs.end();it++)
396     if((*it).isRandomVar())
397       {
398         std::size_t locSize((*it).initializeUndergroundWithSeq());
399         if(sz==std::numeric_limits<std::size_t>::max())
400           sz=locSize;
401         else
402           if(sz!=locSize)
403             throw YACS::Exception("YACSEvalYFXRunOnlyPattern::assignRandomVarsInputs : length of sequences in random vars must be the same !");
404       }
405 }
406
407 bool YACSEvalYFXRunOnlyPattern::isLocked() const
408 {
409   return _lockedStatus;
410 }
411
412 YACSEvalListOfResources *YACSEvalYFXRunOnlyPattern::giveResources()
413 {
414   checkLocked();
415   if(!isAlreadyComputedResources())
416     {
417       YACS::ENGINE::DeploymentTree dt(_runNode->getDeploymentTree());
418       _runNode->removeRecursivelyRedundantCL();
419       YACSEvalListOfResources *res(new YACSEvalListOfResources(_runNode->getMaxLevelOfParallelism(),getCatalogInAppli(),dt));
420       setResources(res);
421     }
422   return getResourcesInternal();
423 }
424
425 YACS::ENGINE::Proc *YACSEvalYFXRunOnlyPattern::getUndergroundGeneratedGraph() const
426 {
427   return getGenerator()->getUndergroundGeneratedGraph();
428 }
429
430 std::string YACSEvalYFXRunOnlyPattern::getErrorDetailsInCaseOfFailure() const
431 {
432   std::string st(getStatusOfRunStr());//test if a run has occurred.
433   if(st==ST_OK)
434     throw YACS::Exception("YACSEvalYFXRunOnlyPattern::getErrorDetailsInCaseOfFailure : The execution of scheme has been carried out to the end without any problem !");
435   // All the problem can only comes from foreach -> scan it
436   YACS::ENGINE::ForEachLoop *fe(getUndergroundForEach());
437   YACS::ENGINE::NodeStateNameMap nsm;
438   unsigned nbB(fe->getNumberOfBranchesCreatedDyn());
439   std::ostringstream oss;
440   for(unsigned j=0;j<nbB;j++)
441     {
442       YACS::ENGINE::Node *nn(fe->getChildByNameExec(YACSEvalYFXGraphGen::FIRST_FE_SUBNODE_NAME,j));
443       YACS::ENGINE::Bloc *nnc(dynamic_cast<YACS::ENGINE::Bloc *>(nn));
444       if(!nnc)
445         throw YACS::Exception("YACSEvalYFXRunOnlyPattern::getErrorDetailsInCaseOfFailure : internal error 1 ! The direct son of main foreach is expected to be a Bloc !");
446       if(nnc->getState()==YACS::DONE)
447         continue;
448       std::list< YACS::ENGINE::ElementaryNode *> fec(nnc->getRecursiveConstituents());
449       for(std::list< YACS::ENGINE::ElementaryNode *>::reverse_iterator it1=fec.rbegin();it1!=fec.rend();it1++)
450         {
451           YACS::StatesForNode st0((*it1)->getState());
452           if(st0!=YACS::DONE)
453             {
454               oss << "NODE = " << nnc->getChildName(*it1) << std::endl;
455               oss << "STATUS = " << nsm[st0] << std::endl;
456               oss << "BRANCH ID = " << j << std::endl;
457               std::list<YACS::ENGINE::InputPort *> inps((*it1)->getSetOfInputPort());
458               for(std::list<YACS::ENGINE::InputPort *>::const_iterator it2=inps.begin();it2!=inps.end();it2++)
459                 {
460                   std::string d((*it2)->getHumanRepr());
461                   if(d.size()>10000)
462                     d=d.substr(0,MAX_LGTH_OF_INP_DUMP);
463                   oss << "INPUT \"" << (*it2)->getName() << "\" = " << d << std::endl;
464                 }
465               oss << "DETAILS = " << std::endl;
466               oss << (*it1)->getErrorDetails();
467             }
468         }
469     }
470   return oss.str();
471 }
472
473 std::string YACSEvalYFXRunOnlyPattern::getStatusOfRunStr() const
474 {
475   YACS::StatesForNode st(getUndergroundGeneratedGraph()->getState());
476   switch(st)
477     {
478     case YACS::READY:
479     case YACS::TOLOAD:
480     case YACS::LOADED:
481     case YACS::TOACTIVATE:
482     case YACS::ACTIVATED:
483     case YACS::SUSPENDED:
484     case YACS::PAUSE:
485     case YACS::DISABLED:
486     case YACS::DESACTIVATED:
487       {
488         std::ostringstream oss; oss << "YACSEvalYFXRunOnlyPattern::getStatusOfRunStr : Unexpected state \"" << YACS::ENGINE::Node::getStateName(st) << "\" ! Did you invoke run ?";
489         throw YACS::Exception(oss.str());
490       }
491     case YACS::LOADFAILED:
492     case YACS::EXECFAILED:
493     case YACS::ERROR:
494     case YACS::INTERNALERR:
495       return std::string(ST_ERROR);
496     case YACS::FAILED:
497       return std::string(ST_FAILED);
498     case YACS::DONE:
499       return std::string(ST_OK);
500     default:
501       {
502         std::ostringstream oss; oss << "YACSEvalYFXRunOnlyPattern::getStatusOfRunStr : unrecognized and managed state \"" << YACS::ENGINE::Node::getStateName(st) << "\" !";
503         throw YACS::Exception(oss.str());
504       }
505     }
506 }
507
508 std::vector<YACSEvalSeqAny *> YACSEvalYFXRunOnlyPattern::getResults() const
509 {
510   return _gen->getResults();
511 }
512
513 /*!
514  * This method works if run succeeded (true return) and also if graph has failed. Graph failed means soft error of evaluation due to error in evaluation (example 1/0 or a normal throw from one node)
515  * If a more serious error occured (SIGSEGV of a server or internal error in YACS engine, cluster error, loose of connection...) this method will throw an exception to warn the caller that the results may be 
516  */
517 std::vector<YACSEvalSeqAny *> YACSEvalYFXRunOnlyPattern::getResultsInCaseOfFailure(std::vector<unsigned int>& passedIds) const
518 {
519   YACS::StatesForNode st(getUndergroundGeneratedGraph()->getState());
520   if(st==YACS::DONE)
521     {
522       passedIds.clear();
523       std::vector<YACSEvalSeqAny *> ret(getResults());
524       if(!ret.empty())
525         {
526           if(!ret[0])
527             throw YACS::Exception("YACSEvalYFXRunOnlyPattern::getResultsInCaseOfFailure : internal error ! The returned vector has a null pointer at pos #0 !");
528           std::size_t sz(ret[0]->size());
529           passedIds.resize(sz);
530           for(std::size_t i=0;i<sz;i++)
531             passedIds[i]=i;
532         }
533       return ret;
534     }
535   getStatusOfRunStr();// To check that the status is recognized.
536   std::list<YACS::ENGINE::Node *> lns(getUndergroundGeneratedGraph()->edGetDirectDescendants());
537   YACS::ENGINE::ForEachLoop *fe(getUndergroundForEach());
538   //
539   YACS::ENGINE::Executor exe;
540   std::vector<YACS::ENGINE::SequenceAny *> outputs;
541   std::vector<std::string> nameOfOutputs;
542   passedIds=fe->getPassedResults(&exe,outputs,nameOfOutputs);//<- the key invokation is here.
543   std::size_t sz(passedIds.size()),ii(0);
544   std::vector<YACSEvalSeqAny *> ret(_outputsOfInterest.size());
545   for(std::vector<YACSEvalOutputPort *>::const_iterator it1=_outputsOfInterest.begin();it1!=_outputsOfInterest.end();it1++,ii++)
546     {
547       YACS::ENGINE::OutputPort *p((*it1)->getUndergroundPtr());
548       std::string st(_runNode->getOutPortName(p));
549       std::ostringstream oss; oss << YACSEvalYFXGraphGen::FIRST_FE_SUBNODE_NAME << '.' << _runNode->getName() << '.' << st;
550       st=oss.str();
551       YACS::ENGINE::ForEachLoop::InterceptorizeNameOfPort(st);
552       std::vector<std::string>::iterator it2(std::find(nameOfOutputs.begin(),nameOfOutputs.end(),st));
553       if(it2==nameOfOutputs.end())
554         {
555           std::ostringstream oss; oss << "YACSEvalYFXRunOnlyPattern::getResultsInCaseOfFailure : internal error 3 ! Unable to locate interceptor with name " << st << " ! Possibilities are : ";
556           std::copy(nameOfOutputs.begin(),nameOfOutputs.end(),std::ostream_iterator<std::string>(oss," "));
557           oss << " !";
558           throw YACS::Exception(oss.str());
559         }
560       std::size_t pos(std::distance(nameOfOutputs.begin(),it2));
561       ret[ii]=BuildValueFromEngineFrmt(outputs[pos]);
562     }
563   return ret;
564 }
565
566 void YACSEvalYFXRunOnlyPattern::emitStart() const
567 {
568   YACSEvalObserver *obs(getObserver());
569   if(!obs)
570     return ;
571   obs->startComputation(getBoss());
572 }
573
574 bool YACSEvalYFXRunOnlyPattern::go(const YACSEvalExecParams& params, YACSEvalSession *session) const
575 {
576   emitStart();
577   YACS::ENGINE::Dispatcher *disp(YACS::ENGINE::Dispatcher::getDispatcher());
578   disp->addObserver(_obs,getUndergroundForEach(),"progress_ok");
579   disp->addObserver(_obs,getUndergroundForEach(),"progress_ko");
580   bool ret(getGenerator()->go(params,session));
581   disp->removeObserver(_obs,getUndergroundForEach(),"progress_ok");
582   disp->removeObserver(_obs,getUndergroundForEach(),"progress_ko");
583   return ret;
584 }
585
586 YACS::ENGINE::ForEachLoop *YACSEvalYFXRunOnlyPattern::getUndergroundForEach() const
587 {
588   return getGenerator()->getUndergroundForEach();
589 }
590
591 bool YACSEvalYFXRunOnlyPattern::IsMatching(YACS::ENGINE::Proc *scheme, YACS::ENGINE::ComposedNode *& runNode)
592 {
593   std::list<YACS::ENGINE::Node *> nodes(scheme->getChildren());
594   if(nodes.empty())
595     return false;
596   bool areAllElementary(true);
597   for(std::list<YACS::ENGINE::Node *>::const_iterator it=nodes.begin();it!=nodes.end() && areAllElementary;it++)
598     if(!dynamic_cast<YACS::ENGINE::ElementaryNode *>(*it))
599       areAllElementary=false;
600   if(areAllElementary)
601     {
602       if(scheme)
603         CheckNodeIsOK(scheme);
604       runNode=scheme;
605       return true;
606     }
607   if(nodes.size()!=1)
608     return false;
609   YACS::ENGINE::ComposedNode *candidate(dynamic_cast<YACS::ENGINE::ComposedNode *>(nodes.front()));
610   runNode=candidate;
611   if(candidate)
612     CheckNodeIsOK(candidate);
613   return candidate!=0;
614 }
615
616 void YACSEvalYFXRunOnlyPattern::buildInputPorts()
617 {
618   _inputs.clear();
619   std::list< YACS::ENGINE::InputPort *> allInputPorts(_runNode->getSetOfInputPort());
620   std::vector<std::string> allNames;
621   for(std::list< YACS::ENGINE::InputPort *>::const_iterator it=allInputPorts.begin();it!=allInputPorts.end();it++)
622     {
623       YACS::ENGINE::InputPort *elt(*it);
624       if(!elt)
625         throw YACS::Exception("YACSEvalYFXRunOnlyPattern::buildInputPorts : presence of null input !");
626       std::set<YACS::ENGINE::OutPort *> bls(elt->edSetOutPort());
627       if(bls.empty())
628         {
629           if(YACSEvalPort::IsInputPortPublishable(elt))
630             {
631               std::string inpName(elt->getName());
632               if(inpName.empty())
633                 throw YACS::Exception("YACSEvalYFXRunOnlyPattern::buildInputPorts : an input has empty name ! Should not !");
634               _inputs.push_back(YACSEvalInputPort(elt));
635               if(std::find(allNames.begin(),allNames.end(),inpName)!=allNames.end())
636                 {
637                   std::ostringstream oss; oss << "YACSEvalYFXRunOnlyPattern::buildInputPorts : input name \"" << inpName << "\" appears more than once !";
638                   throw YACS::Exception(oss.str());
639                 }
640               allNames.push_back(inpName);
641             }
642         }
643     }
644 }
645
646 void YACSEvalYFXRunOnlyPattern::buildOutputPorts()
647 {
648   _outputs.clear();
649   std::list< YACS::ENGINE::OutputPort *> allOutputPorts(_runNode->getSetOfOutputPort());
650   std::vector<std::string> allNames;
651   for(std::list< YACS::ENGINE::OutputPort *>::const_iterator it=allOutputPorts.begin();it!=allOutputPorts.end();it++)
652     {
653       YACS::ENGINE::OutputPort *elt(*it);
654       if(YACSEvalPort::IsOutputPortPublishable(elt))
655         {
656           if(!elt)
657             throw YACS::Exception("YACSEvalYFXRunOnlyPattern::buildOutputPorts : presence of null output !");
658           std::string outpName(elt->getName());
659           if(outpName.empty())
660             throw YACS::Exception("YACSEvalYFXRunOnlyPattern::buildOutputPorts : an output has empty name ! Should not !");
661           if(std::find(allNames.begin(),allNames.end(),outpName)!=allNames.end())
662             {
663               std::ostringstream oss; oss << "YACSEvalYFXRunOnlyPattern::buildOutputPorts : output name \"" << outpName << "\" appears more than once !";
664               throw YACS::Exception(oss.str());
665             }
666           _outputs.push_back(YACSEvalOutputPort(*it));
667         }
668     }
669 }
670
671 YACSEvalYFXGraphGen *YACSEvalYFXRunOnlyPattern::getGenerator() const
672 {
673   if(!_gen)
674     throw YACS::Exception("getGenerator : generator is NULL !");
675   return _gen;
676 }
677
678 /////////////////////
679
680 YACSEvalYFXGraphGen::YACSEvalYFXGraphGen(YACSEvalYFXRunOnlyPattern *boss):_boss(boss),_generatedGraph(0),_FEInGeneratedGraph(0)
681 {
682   if(!_boss)
683     throw YACS::Exception("YACSEvalYFXGraphGen constructor : boss is NULL !");
684 }
685
686 YACSEvalYFXGraphGen::~YACSEvalYFXGraphGen()
687 {
688   //delete _generatedGraph;// -> TODO : AGY why ?
689 }
690
691 void YACSEvalYFXGraphGen::resetGeneratedGraph()
692 {
693   delete _generatedGraph;
694   _generatedGraph=0; _FEInGeneratedGraph=0;
695 }
696
697 bool YACSEvalYFXGraphGen::isLocked() const
698 {
699   return _generatedGraph!=0;
700 }
701
702 int YACSEvalYFXGraphGen::assignNbOfBranches()
703 {
704   if(!_generatedGraph)
705     throw YACS::Exception("YACSEvalYFXGraphGen::assignNbOfBranches : the generated graph has not been created !");
706   std::list<YACS::ENGINE::Node *> nodes(_generatedGraph->getChildren());
707   YACS::ENGINE::ForEachLoop *zeMainNode(0);
708   for(std::list<YACS::ENGINE::Node *>::const_iterator it=nodes.begin();it!=nodes.end();it++)
709     {
710       YACS::ENGINE::ForEachLoop *isZeMainNode(dynamic_cast<YACS::ENGINE::ForEachLoop *>(*it));
711       if(isZeMainNode)
712         {
713           if(!zeMainNode)
714             zeMainNode=isZeMainNode;
715           else
716             throw YACS::Exception("YACSEvalYFXGraphGen::assignNbOfBranches : internal error 1 !");
717         }
718     }
719   if(!zeMainNode)
720     throw YACS::Exception("YACSEvalYFXGraphGen::assignNbOfBranches : internal error 2 !");
721   unsigned int nbProcsDeclared(getBoss()->getResourcesInternal()->getNumberOfProcsDeclared());
722   nbProcsDeclared=std::max(nbProcsDeclared,4u);
723   int nbOfBranch=1;
724   if(getBoss()->getParallelizeStatus())
725     {
726       nbOfBranch=(nbProcsDeclared/getBoss()->getResourcesInternal()->getMaxLevelOfParallelism());
727       nbOfBranch=std::max(nbOfBranch,1);
728     }
729   YACS::ENGINE::InputPort *zeInputToSet(zeMainNode->edGetNbOfBranchesPort());
730   YACS::ENGINE::AnyInputPort *zeInputToSetC(dynamic_cast<YACS::ENGINE::AnyInputPort *>(zeInputToSet));
731   if(!zeInputToSetC)
732     throw YACS::Exception("YACSEvalYFXGraphGen::assignNbOfBranches : internal error 3 !");
733   YACS::ENGINE::Any *a(YACS::ENGINE::AtomAny::New(nbOfBranch));
734   zeInputToSetC->put(a);
735   zeInputToSetC->exSaveInit();
736   a->decrRef();
737   return nbOfBranch;
738 }
739
740 void YACSEvalYFXGraphGenInteractive::generateGraph()
741 {
742   if(_generatedGraph)
743     { delete _generatedGraph; _generatedGraph=0; _FEInGeneratedGraph=0; }
744   static const char LISTPYOBJ_STR[]="list[pyobj]";
745   if(getBoss()->getOutputsOfInterest().empty())
746     return ;
747   YACS::ENGINE::RuntimeSALOME::setRuntime();
748   YACS::ENGINE::RuntimeSALOME *r(YACS::ENGINE::getSALOMERuntime());
749   _generatedGraph=r->createProc(DFT_PROC_NAME);
750   YACS::ENGINE::TypeCode *pyobjTC(_generatedGraph->createInterfaceTc("python:obj:1.0","pyobj",std::list<YACS::ENGINE::TypeCodeObjref *>()));
751   std::ostringstream oss; oss << "Loop_" << getBoss()->getRunNode()->getName();
752   _generatedGraph->createType(YACSEvalAnyDouble::TYPE_REPR,"double");
753   _generatedGraph->createType(YACSEvalAnyInt::TYPE_REPR,"int");
754   //
755   YACS::ENGINE::InlineNode *n0(r->createScriptNode(YACS::ENGINE::PythonNode::KIND,"__initializer__"));
756   _generatedGraph->edAddChild(n0);
757   YACS::ENGINE::TypeCode *listPyobjTC(_generatedGraph->createSequenceTc(LISTPYOBJ_STR,LISTPYOBJ_STR,pyobjTC));
758   YACS::ENGINE::OutputPort *sender(n0->edAddOutputPort("sender",listPyobjTC));
759   std::ostringstream var0;
760   const std::vector< YACSEvalInputPort >& inputs(getBoss()->getInputs());
761   for(std::vector< YACSEvalInputPort >::const_iterator it=inputs.begin();it!=inputs.end();it++)
762     {
763       if((*it).isRandomVar())
764         {
765           var0 << (*it).getName() << ",";
766           YACS::ENGINE::TypeCode *tc(YACSEvalYFXPattern::CreateSeqTypeCodeFrom(_generatedGraph,(*it).getTypeOfData()));
767           YACS::ENGINE::InputPort *inp(n0->edAddInputPort((*it).getName(),tc));
768           YACS::ENGINE::InputPyPort *inpc(dynamic_cast<YACS::ENGINE::InputPyPort *>(inp));
769           if(!inpc)
770             throw YACS::Exception("YACSEvalYFXRunOnlyPattern::generateGraph : internal error 1 !");
771           (*it).setUndergroundPortToBeSet(inpc);
772         }
773     }
774   std::ostringstream n0Script; n0Script << "sender=zip(" << var0.str() << ")\n";
775   n0->setScript(n0Script.str());
776   //
777   YACS::ENGINE::ForEachLoop *n1(r->createForEachLoop(oss.str(),pyobjTC));
778   _FEInGeneratedGraph=n1;
779   _generatedGraph->edAddChild(n1);
780   _generatedGraph->edAddCFLink(n0,n1);
781   _generatedGraph->edAddDFLink(sender,n1->edGetSeqOfSamplesPort());
782   YACS::ENGINE::InlineNode *n2(r->createScriptNode(YACS::ENGINE::PythonNode::KIND,GATHER_NODE_NAME));
783   _generatedGraph->edAddChild(n2);
784   _generatedGraph->edAddCFLink(n1,n2);
785   //
786   YACS::ENGINE::Bloc *n10(r->createBloc(FIRST_FE_SUBNODE_NAME));
787   n1->edAddChild(n10);
788   YACS::ENGINE::InlineNode *n100(r->createScriptNode(YACS::ENGINE::PythonNode::KIND,"__dispatch__"));
789   YACS::ENGINE::ComposedNode *runNode(getBoss()->getRunNode());
790   YACS::ENGINE::Node *n101(runNode->cloneWithoutCompAndContDeepCpy(0,true));
791   n10->edAddChild(n100);
792   n10->edAddChild(n101);
793   YACS::ENGINE::InputPort *dispatchIn(n100->edAddInputPort("i0",pyobjTC));
794   n10->edAddCFLink(n100,n101);
795   n1->edAddDFLink(n1->edGetSamplePort(),dispatchIn);
796   std::ostringstream var1;
797   for(std::vector< YACSEvalInputPort >::const_iterator it=inputs.begin();it!=inputs.end();it++)
798     {
799       if((*it).isRandomVar())
800         {
801           var1 << (*it).getName() << ",";
802           YACS::ENGINE::OutputPort *myOut(n100->edAddOutputPort((*it).getName(),_generatedGraph->getTypeCode((*it).getTypeOfData())));
803           std::string tmpPortName(runNode->getInPortName((*it).getUndergroundPtr()));
804           YACS::ENGINE::InputPort *myIn(n101->getInputPort(tmpPortName));
805           n10->edAddDFLink(myOut,myIn);
806         }
807     }
808   std::ostringstream n100Script;  n100Script << var1.str() << "=i0\n";
809   n100->setScript(n100Script.str());
810   const std::vector<YACSEvalOutputPort *>& outputsOfInt(getBoss()->getOutputsOfInterest());
811   for(std::vector< YACSEvalOutputPort * >::const_iterator it=outputsOfInt.begin();it!=outputsOfInt.end();it++)
812     {
813       YACS::ENGINE::TypeCode *tc(YACSEvalYFXPattern::CreateSeqTypeCodeFrom(_generatedGraph,(*it)->getTypeOfData()));
814       YACS::ENGINE::InputPort *myIn(n2->edAddInputPort((*it)->getName(),tc));
815       std::string tmpPortName(runNode->getOutPortName((*it)->getUndergroundPtr()));
816       YACS::ENGINE::OutputPort *myOut(n101->getOutputPort(tmpPortName));
817       _generatedGraph->edAddDFLink(myOut,myIn);
818     }
819   _generatedGraph->updateContainersAndComponents();
820 }
821
822 bool YACSEvalYFXGraphGenInteractive::go(const YACSEvalExecParams& params, YACSEvalSession *session) const
823 {
824   YACS::ENGINE::Executor exe;
825   exe.setKeepGoingProperty(!params.getStopASAPAfterErrorStatus());
826   {
827     MyAutoThreadSaver locker(!session->isAlreadyPyThreadSaved());
828     exe.RunW(getUndergroundGeneratedGraph());
829   }
830   return getUndergroundGeneratedGraph()->getState()==YACS::DONE;
831 }
832
833 std::vector<YACSEvalSeqAny *> YACSEvalYFXGraphGenInteractive::getResults() const
834 {
835   if(getUndergroundGeneratedGraph()->getState()!=YACS::DONE)
836     throw YACS::Exception("YACSEvalYFXRunOnlyPattern::getResults : the execution did not finished correctly ! getResults should not be called !");
837   const std::vector<YACSEvalOutputPort *>& outputsOfInt(getBoss()->getOutputsOfInterest()); 
838   std::vector<YACSEvalSeqAny *> ret(outputsOfInt.size());
839   YACS::ENGINE::Node *node(getUndergroundGeneratedGraph()->getChildByName(YACSEvalYFXGraphGen::GATHER_NODE_NAME));
840   YACS::ENGINE::PythonNode *nodeC(dynamic_cast<YACS::ENGINE::PythonNode *>(node));
841   if(!nodeC)
842     throw YACS::Exception("YACSEvalYFXRunOnlyPattern::getResults : internal error !");
843   std::size_t ii(0);
844   for(std::vector< YACSEvalOutputPort * >::const_iterator it=outputsOfInt.begin();it!=outputsOfInt.end();it++,ii++)
845     {
846       YACS::ENGINE::InPort *input(nodeC->getInPort((*it)->getName()));
847       YACS::ENGINE::InputPyPort *inputC(dynamic_cast<YACS::ENGINE::InputPyPort *>(input));
848       if(!inputC)
849         {
850           std::ostringstream oss; oss << "YACSEvalYFXRunOnlyPattern::getResults : internal error for input \"" << (*it)->getName() << "\"";
851           throw YACS::Exception(oss.str());
852         }
853       ret[ii]=YACSEvalYFXPattern::BuildValueInPort(inputC);
854     }
855   return ret;
856 }
857
858 ////////////////////
859
860 void YACSEvalYFXGraphGenCluster::generateGraph()
861 {
862   YACS::ENGINE::AutoGIL agil;
863   if(_generatedGraph)
864     { delete _generatedGraph; _generatedGraph=0; _FEInGeneratedGraph=0; }
865   //
866   const char EFXGenFileName[]="EFXGenFileName";
867   const char EFXGenContent[]="import getpass,datetime,os\nn=datetime.datetime.now()\nreturn os.path.join(os.path.sep,\"tmp\",\"EvalYFX_%s_%s_%s.xml\"%(getpass.getuser(),n.strftime(\"%d%m%y\"),n.strftime(\"%H%M%S\")))";
868   const char EFXGenContent2[]="import getpass,datetime\nn=datetime.datetime.now()\nreturn \"EvalYFX_%s_%s_%s\"%(getpass.getuser(),n.strftime(\"%d%m%y\"),n.strftime(\"%H%M%S\"))";
869   //
870   YACS::ENGINE::AutoPyRef func(YACS::ENGINE::evalPy(EFXGenFileName,EFXGenContent));
871   YACS::ENGINE::AutoPyRef val(YACS::ENGINE::evalFuncPyWithNoParams(func));
872   _locSchemaFile=PyString_AsString(val);
873   func=YACS::ENGINE::evalPy(EFXGenFileName,EFXGenContent2);
874   val=YACS::ENGINE::evalFuncPyWithNoParams(func);
875   _jobName=PyString_AsString(val);
876   //
877   static const char LISTPYOBJ_STR[]="list[pyobj]";
878   if(getBoss()->getOutputsOfInterest().empty())
879     return ;
880   YACS::ENGINE::RuntimeSALOME::setRuntime();
881   YACS::ENGINE::RuntimeSALOME *r(YACS::ENGINE::getSALOMERuntime());
882   _generatedGraph=r->createProc(DFT_PROC_NAME);
883   YACS::ENGINE::TypeCode *pyobjTC(_generatedGraph->createInterfaceTc("python:obj:1.0","pyobj",std::list<YACS::ENGINE::TypeCodeObjref *>()));
884   std::ostringstream oss; oss << "Loop_" << getBoss()->getRunNode()->getName();
885   _generatedGraph->createType(YACSEvalAnyDouble::TYPE_REPR,"double");
886   _generatedGraph->createType(YACSEvalAnyInt::TYPE_REPR,"int");
887   //
888   YACS::ENGINE::InlineNode *n0(r->createScriptNode(YACS::ENGINE::PythonNode::KIND,"__initializer__"));
889   _generatedGraph->edAddChild(n0);
890   YACS::ENGINE::TypeCode *listPyobjTC(_generatedGraph->createSequenceTc(LISTPYOBJ_STR,LISTPYOBJ_STR,pyobjTC));
891   YACS::ENGINE::OutputPort *sender(n0->edAddOutputPort("sender",listPyobjTC));
892   std::ostringstream var0;
893   const std::vector< YACSEvalInputPort >& inputs(getBoss()->getInputs());
894   for(std::vector< YACSEvalInputPort >::const_iterator it=inputs.begin();it!=inputs.end();it++)
895     {
896       if((*it).isRandomVar())
897         {
898           var0 << (*it).getName() << ",";
899           YACS::ENGINE::TypeCode *tc(YACSEvalYFXPattern::CreateSeqTypeCodeFrom(_generatedGraph,(*it).getTypeOfData()));
900           YACS::ENGINE::InputPort *inp(n0->edAddInputPort((*it).getName(),tc));
901           YACS::ENGINE::InputPyPort *inpc(dynamic_cast<YACS::ENGINE::InputPyPort *>(inp));
902           if(!inpc)
903             throw YACS::Exception("YACSEvalYFXRunOnlyPattern::generateGraph : internal error 1 !");
904           (*it).setUndergroundPortToBeSet(inpc);
905         }
906     }
907   std::ostringstream n0Script; n0Script << "sender=zip(" << var0.str() << ")\n";
908   n0->setScript(n0Script.str());
909   //
910   YACS::ENGINE::ForEachLoop *n1(r->createForEachLoop(oss.str(),pyobjTC));
911   _FEInGeneratedGraph=n1;
912   _generatedGraph->edAddChild(n1);
913   _generatedGraph->edAddCFLink(n0,n1);
914   _generatedGraph->edAddDFLink(sender,n1->edGetSeqOfSamplesPort());
915   YACS::ENGINE::InlineNode *n2(r->createScriptNode(YACS::ENGINE::PythonNode::KIND,GATHER_NODE_NAME));
916   _generatedGraph->edAddChild(n2);
917   _generatedGraph->edAddCFLink(n1,n2);
918   //
919   YACS::ENGINE::Bloc *n10(r->createBloc(FIRST_FE_SUBNODE_NAME));
920   n1->edAddChild(n10);
921   YACS::ENGINE::InlineNode *n100(r->createScriptNode(YACS::ENGINE::PythonNode::KIND,"__dispatch__"));
922   YACS::ENGINE::ComposedNode *runNode(getBoss()->getRunNode());
923   YACS::ENGINE::Node *n101(runNode->cloneWithoutCompAndContDeepCpy(0,true));
924   n10->edAddChild(n100);
925   n10->edAddChild(n101);
926   YACS::ENGINE::InputPort *dispatchIn(n100->edAddInputPort("i0",pyobjTC));
927   n10->edAddCFLink(n100,n101);
928   n1->edAddDFLink(n1->edGetSamplePort(),dispatchIn);
929   std::ostringstream var1;
930   for(std::vector< YACSEvalInputPort >::const_iterator it=inputs.begin();it!=inputs.end();it++)
931     {
932       if((*it).isRandomVar())
933         {
934           var1 << (*it).getName() << ",";
935           YACS::ENGINE::OutputPort *myOut(n100->edAddOutputPort((*it).getName(),_generatedGraph->getTypeCode((*it).getTypeOfData())));
936           std::string tmpPortName(runNode->getInPortName((*it).getUndergroundPtr()));
937           YACS::ENGINE::InputPort *myIn(n101->getInputPort(tmpPortName));
938           n10->edAddDFLink(myOut,myIn);
939         }
940     }
941   std::ostringstream n100Script;  n100Script << var1.str() << "=i0\n";
942   n100->setScript(n100Script.str());
943   const std::vector<YACSEvalOutputPort *>& outputsOfInt(getBoss()->getOutputsOfInterest());
944   std::ostringstream n2Script; n2Script << "zeRes=[";
945   for(std::vector< YACSEvalOutputPort * >::const_iterator it=outputsOfInt.begin();it!=outputsOfInt.end();it++)
946     {
947       YACS::ENGINE::TypeCode *tc(YACSEvalYFXPattern::CreateSeqTypeCodeFrom(_generatedGraph,(*it)->getTypeOfData()));
948       YACS::ENGINE::InputPort *myIn(n2->edAddInputPort((*it)->getName(),tc));
949       n2Script << (*it)->getName() << ", ";
950       std::string tmpPortName(runNode->getOutPortName((*it)->getUndergroundPtr()));
951       YACS::ENGINE::OutputPort *myOut(n101->getOutputPort(tmpPortName));
952       _generatedGraph->edAddDFLink(myOut,myIn);
953     }
954   n2Script << "]\nf=file(\"" << _jobName << "\",\"w\") ; f.write(str(zeRes)) ; del f";
955   n2->setScript(n2Script.str());
956   _generatedGraph->updateContainersAndComponents();
957 }
958
959 bool YACSEvalYFXGraphGenCluster::go(const YACSEvalExecParams& params, YACSEvalSession *session) const
960 {
961   YACS::ENGINE::AutoGIL agil;
962   getUndergroundGeneratedGraph()->saveSchema(_locSchemaFile);
963   YACSEvalListOfResources *rss(getBoss()->getResourcesInternal());
964   const YACSEvalParamsForCluster& cli(rss->getAddParamsForCluster());
965   std::vector<std::string> machines(rss->getAllChosenMachines());
966   if(machines.size()!=1)
967     throw YACS::Exception("YACSEvalYFXGraphGenCluster::go : internal error ! In batch mode and not exactly one machine !");
968   Engines::SalomeLauncher_var sl(session->getInternal()->goFetchingSalomeLauncherInNS());
969   Engines::ResourceParameters rr;
970   rr.name=CORBA::string_dup(machines[0].c_str());
971   rr.hostname=CORBA::string_dup("");
972   rr.can_launch_batch_jobs=true;
973   rr.can_run_containers=true;
974   rr.OS=CORBA::string_dup("Linux");
975   rr.componentList.length(0);
976   rr.nb_proc=rss->getNumberOfProcsDeclared();// <- important
977   rr.mem_mb=1024;
978   rr.cpu_clock=1000;
979   rr.nb_node=1;// useless only nb_proc used.
980   rr.nb_proc_per_node=1;// useless only nb_proc used.
981   rr.policy=CORBA::string_dup("cycl");
982   rr.resList.length(0);
983   Engines::JobParameters jp;
984   jp.job_name=CORBA::string_dup(_jobName.c_str());
985   jp.job_type=CORBA::string_dup("yacs_file");
986   jp.job_file=CORBA::string_dup(_locSchemaFile.c_str());
987   jp.env_file=CORBA::string_dup("");
988   jp.in_files.length(0);
989   jp.out_files.length(1);
990   jp.out_files[0]=CORBA::string_dup(_jobName.c_str());
991   jp.work_directory=CORBA::string_dup(cli.getRemoteWorkingDir().c_str());
992   jp.local_directory=CORBA::string_dup(cli.getLocalWorkingDir().c_str());
993   jp.result_directory=CORBA::string_dup(cli.getLocalWorkingDir().c_str());
994   jp.maximum_duration=CORBA::string_dup(cli.getMaxDuration().c_str());
995   jp.resource_required=rr;
996   jp.queue=CORBA::string_dup("");
997   jp.exclusive=false;
998   jp.mem_per_cpu=rr.mem_mb;
999   jp.wckey=CORBA::string_dup(cli.getWCKey().c_str());
1000   jp.extra_params=CORBA::string_dup("");
1001   jp.specific_parameters.length(0);
1002   jp.launcher_file=CORBA::string_dup("");
1003   jp.launcher_args=CORBA::string_dup("");
1004   _jobid=sl->createJob(jp);
1005   sl->launchJob(_jobid);
1006   bool ret(false);
1007   while(true)
1008     {
1009       PyRun_SimpleString("import time ; time.sleep(10)");
1010       char *state(sl->getJobState(_jobid));//"CREATED", "IN_PROCESS", "QUEUED", "RUNNING", "PAUSED", "FINISHED" or "FAILED"
1011       std::string sstate(state);
1012       CORBA::string_free(state);
1013       if(sstate=="FINISHED" || sstate=="FAILED")
1014         {
1015           ret=sstate=="FINISHED";
1016           break;
1017         }
1018     }
1019   sl->getJobResults(_jobid,cli.getLocalWorkingDir().c_str());
1020   //
1021   try
1022     {
1023       std::ostringstream oss; oss << "import os" << std::endl << "p=os.path.join(\"" << cli.getLocalWorkingDir() << "\",\"" << _jobName  << "\")" << std::endl;
1024       oss << "if not os.path.exists(p):\n  return None\n";
1025       oss << "f=file(p,\"r\")" << std::endl;
1026       oss << "return eval(f.read())";
1027       std::string zeInput(oss.str());
1028       YACS::ENGINE::AutoPyRef func(YACS::ENGINE::evalPy("fetch",zeInput));
1029       YACS::ENGINE::AutoPyRef val(YACS::ENGINE::evalFuncPyWithNoParams(func));
1030       if(!PyList_Check(val))
1031         throw YACS::Exception("Fetched file does not contain a list !");
1032       Py_ssize_t sz(PyList_Size(val));
1033       _res.resize(sz);
1034       for(Py_ssize_t i=0;i<sz;i++)
1035         {
1036           std::vector<double>& res0(_res[i]);
1037           PyObject *elt0(PyList_GetItem(val,i));
1038           if(!PyList_Check(elt0))
1039             throw YACS::Exception("Fetched file does contain a list of list !");
1040           Py_ssize_t sz0(PyList_Size(elt0)); res0.resize(sz0);
1041           for(Py_ssize_t j=0;j<sz0;j++)
1042             {
1043               PyObject *elt1(PyList_GetItem(elt0,j));
1044               res0[j]=PyFloat_AsDouble(elt1);
1045             }
1046         }
1047       // cleanup
1048       std::ostringstream oss1; oss1 << "import os" << std::endl << "p=os.path.join(\"" << cli.getLocalWorkingDir() << "\",\"" << _jobName  << "\") ; os.remove(p)" << std::endl;
1049       std::string s1(oss1.str());
1050       PyRun_SimpleString(s1.c_str());
1051       if(!params.getFetchRemoteDirForClusterStatus())
1052         {
1053           std::ostringstream oss2; oss2 << "import os,shutil" << std::endl << "p=os.path.join(\"" << cli.getLocalWorkingDir() << "\",\"logs\") ; shutil.rmtree(p)" << std::endl;
1054           std::string s2(oss2.str());
1055           PyRun_SimpleString(s2.c_str());
1056         }
1057     }
1058   catch(YACS::Exception& e)
1059     {
1060       _errors=e.what();
1061       return false;
1062     }
1063   //
1064   return ret;
1065 }
1066
1067 std::vector<YACSEvalSeqAny *> YACSEvalYFXGraphGenCluster::getResults() const
1068 {
1069   std::size_t sz(_res.size());
1070   std::vector<YACSEvalSeqAny *> ret(sz);
1071   for(std::size_t i=0;i<sz;i++)
1072     {
1073       YACS::AutoCppPtr<YACSEvalSeqAnyDouble> elt(new YACSEvalSeqAnyDouble(_res[i]));
1074       ret[i]=elt.dettach();
1075     }
1076   return ret;
1077 }