Salome HOME
pour PSEN et Telemac
[tools/eficas.git] / generator / OpenturnsSTD.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2007-2013   EDF R&D
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.
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 """
22 Ce module contient le generateur Etude pour Openturns
23 """
24
25 from Extensions.i18n import tr
26
27 __revision__ = "V1.0"
28
29 defaultSTD = """#! /usr/bin/env python
30
31 class StudyFileGenerationError:
32   def __init__ (self, st):
33     self.st = st
34   def __str__(self):
35     return "'%s'" % self.st
36
37 raise StudyFileGenerationError, "The study file was not generated. Check analysis type."
38 """
39
40 headerSTD = """#! /usr/bin/env python
41
42 # Chargement du module systeme
43 import sys
44 sys.path[:0]=['%s']
45
46 # Chargement du module math
47 import math
48
49 # Chargement du module Open TURNS
50 from openturns import *
51
52 # Fonction verifiant si un echantillon contient des valeurs non valides (NaN)
53 def contain_nan_values(sample):
54   for point in sample:
55     for val in point:
56       if math.isnan(val):
57         return True
58   return False
59
60 results = {}
61
62 """
63
64 viewerSTD = """
65 from openturns.viewer import View
66
67 # Fonction de test du serveur X
68 import subprocess
69 xserver_available = None
70 def is_xserver_available():
71   global xserver_available
72   if xserver_available is None:
73     xserver_available = True
74     try:
75       subprocess.check_call('python -c "from matplotlib import pyplot;pyplot.figure()" >/dev/null 2>&1', shell = True)
76     except:
77       xserver_available = False
78   return xserver_available
79
80 """
81
82 footerSTD = """
83
84 # Flush des messages en attente
85 Log.Flush()
86
87 # Terminaison du fichier
88 #sys.exit( 0 )
89 """
90
91 #=============================================
92 #  La classe de creation du fichier STD
93 #=============================================
94
95 class STDGenerateur :
96
97   '''
98   Generation du fichier python
99   '''
100   def __init__ (self, appli, DictMCVal, ListeVariablesIn, ListeVariablesOut, DictLois ) :
101     self.DictMCVal = DictMCVal
102     self.ListeVariablesIn = ListeVariablesIn
103     self.ListeVariablesOut = ListeVariablesOut
104     self.DictLois = DictLois
105     #print "DictMCVal=", DictMCVal
106     print "ListeVariablesIn= %s", ListeVariablesIn
107
108 # A REPRENDRE DEPUIS ICI !!
109     print "ListeVariablesOut= %s", ListeVariablesOut
110     #print "DictLois=", DictLois
111     self.texteSTD = defaultSTD
112     self.OpenTURNS_path = appli.CONFIGURATION.OpenTURNS_path
113
114     # Ce dictionnaire fait la correspondance entre le mot lu dans le dictionnaire des mots-clefs et la methode a appeler
115     self.traitement = {
116       "Min/Max" :
117       ( "MinMax",
118         { "Experiment Plane" : "ExperimentPlane",
119           "Random Sampling" : "MinMaxRandomSampling",
120           },
121         ),
122       "Central Uncertainty" :
123       ( "CentralUncertainty",
124         { "Taylor Variance Decomposition" : "TaylorVarianceDecomposition",
125           "Random Sampling" : "CentralUncertaintyRandomSampling",
126          },
127         ),
128       "Threshold Exceedence" :
129       ( "ThresholdExceedence",
130         { "Simulation" : "Simulation",
131           "FORM_SORM" : "Analytical",
132           "MonteCarlo" : "MonteCarlo",
133           "LHS" : "LHS",
134           "ImportanceSampling" : "ImportanceSampling",
135           "FirstOrder" : "FORM",
136           "SecondOrder" : "SORM",
137           "Cobyla" : "Cobyla",
138           "AbdoRackwitz" : "AbdoRackwitz",
139           },
140         ),
141       }
142
143     # Ce dictionnaire liste le nom des variables utilisees dans le script
144     # La clef est le nom attendu par les methodes, la valeur est le nom produit dans le fichier de sortie
145     # Le fait de passer par un dictionnaire permet de controler que les variables existent et sont correctement nommees
146     # meme si clef == valeur
147     self.variable = {
148       "n" : "n",
149       "p" : "p",
150       "wrapper" : "wrapper",
151       "wrapperdata" : "wrapperdata",
152       "frameworkdata" : "frameworkdata",
153       "framework" : "framework",
154       "studyid" : "studyid",
155       "studycase" : "studycase",
156       "componentname" : "componentname",
157       "model" : "model",
158       "scaledVector" : "scaledVector",
159       "translationVector" : "translationVector",
160       "levels" : "levels",
161       "myCenteredReductedGrid" : "myCenteredReductedGrid",
162       "myExperimentPlane" : "myExperimentPlane",
163       "inputSample" : "inputSample",
164       "outputSample" : "outputSample",
165       "minValue" : 'results["minValue"]',
166       "maxValue" : 'results["maxValue"]',
167       "flags" : "flags",
168       "inSize" : "inSize",
169       "distribution" : "distribution",
170       "marginal" : "marginal",
171       "collection" : "collection",
172       "copula" : "copula",
173       "correlation" : "correlation",
174       "R" : "R",
175       "vars" : "vars",
176       "description" : "description",
177       "inputRandomVector" : "inputRandomVector",
178       "outputRandomVector" : "outputRandomVector",
179       "myQuadraticCumul" : "myQuadraticCumul",
180       "meanFirstOrder" : 'results["meanFirstOrder"]',
181       "meanSecondOrder" : 'results["meanSecondOrder"]',
182       "standardDeviationFirstOrder" : 'results["standardDeviationFirstOrder"]',
183       "importanceFactors" : 'results["importanceFactors"]',
184       "importanceFactorsGraph" : "importanceFactorsGraph",
185       "importanceFactorsDrawing" : "importanceFactorsDrawing",
186       "empiricalMean" : 'results["empiricalMean"]',
187       "empiricalStandardDeviation" : 'results["empiricalStandardDeviation"]',
188       "empiricalQuantile" : 'results["empiricalQuantile"]',
189       "alpha" : "alpha",
190       "beta" : "beta",
191       "PCCcoefficient" : 'results["PCCcoefficient"]',
192       "PRCCcoefficient" : 'results["PRCCcoefficient"]',
193       "SRCcoefficient" : 'results["SRCcoefficient"]',
194       "SRRCcoefficient" : 'results["SRRCcoefficient"]',
195       "kernel" : "kernel",
196       "kernelSmoothedDist" : "kernelSmoothedDist",
197       "kernelSmoothedPDFDrawing" : "kernelSmoothedPDFDrawing",
198       "kernelSmoothedGraph" : "kernelSmoothedGraph",
199       "meanVector" : "meanVector",
200       "importanceDensity" : "importanceDensity",
201       "myEvent" : "myEvent",
202       "myAlgo" : "myAlgo",
203       "myResult" : "myResult",
204       "probability" : 'results["probability"]',
205       "standardDeviation" : 'results["standardDeviation"]',
206       "level" : "level",
207       "length" : "length",
208       "coefficientOfVariation" : 'results["coefficientOfVariation"]',
209       "convergenceGraph" : "convergenceGraph",
210       "convergenceDrawing" : "convergenceDrawing",
211       "simulationNumbers" : 'results["simulationNumbers"]',
212       "myOptimizer" : "myOptimizer",
213       "specificParameters" : "specificParameters",
214       "startingPoint" : "startingPoint",
215       "hasoferReliabilityIndex" : 'results["hasoferReliabilityIndex"]',
216       "standardSpaceDesignPoint" : 'results["standardSpaceDesignPoint"]',
217       "physicalSpaceDesignPoint" : 'results["physicalSpaceDesignPoint"]',
218       "eventProbabilitySensitivity" : 'results["eventProbabilitySensitivity"]',
219       "hasoferReliabilityIndexSensitivity" : 'results["hasoferReliabilityIndexSensitivity"]',
220       "eventProbabilitySensitivityGraph" : "eventProbabilitySensitivityGraph",
221       "eventProbabilitySensitivityDrawing" : "eventProbabilitySensitivityDrawing",
222       "hasoferReliabilityIndexSensitivityGraph" : "hasoferReliabilityIndexSensitivityGraph",
223       "hasoferReliabilityIndexSensitivityDrawing" : "hasoferReliabilityIndexSensitivityDrawing",
224       "modelEvaluationCalls" : 'results["modelEvaluationCalls"]',
225       "modelGradientCalls" : 'results["modelGradientCalls"]',
226       "modelHessianCalls" : 'results["modelHessianCalls"]',
227       "tvedtApproximation" : 'results["tvedtApproximation"]',
228       "hohenBichlerApproximation" : 'results["hohenBichlerApproximation"]',
229       "breitungApproximation" : 'results["breitungApproximation"]',
230       }
231
232     # Ce dictionnaire fait la correspondance entre le mot-clef du catalogue et le flag de la bibliotheque
233     self.logFlags = {
234       "DebugMessages"   : "Log.DBG",
235       "WrapperMessages" : "Log.WRAPPER",
236       "UserMessages"    : "Log.USER",
237       "InfoMessages"    : "Log.INFO",
238       "WarningMessages" : "Log.WARN",
239       "ErrorMessages"   : "Log.ERROR",
240       }
241     
242   def CreeSTD (self) :
243     '''
244     Pilotage de la creation du fichier python
245     '''
246     TypeAnalyse = None
247     if ( self.DictMCVal.has_key( 'Type' ) ):
248       TypeAnalyse =  self.DictMCVal[ 'Type' ]
249
250     Traitement = None
251     subDict = {}
252     if ( self.traitement.has_key( TypeAnalyse ) ):
253       (Traitement, subDict) =  self.traitement[ TypeAnalyse ]
254
255     if ( Traitement is not None ):
256       self.texteSTD = apply( STDGenerateur.__dict__[ Traitement ], (self, subDict) )
257     
258     return self.texteSTD
259
260   def Header (self) :
261     '''
262     Imprime l entete commun a tous les fichiers
263     '''
264     txt  = headerSTD % self.OpenTURNS_path
265     txt += viewerSTD
266     txt += "# Definit le niveau d'affichage de la log\n"
267     txt += "%s = Log.NONE\n" % self.variable["flags"]
268     for flag in self.logFlags.keys():
269       if ( self.DictMCVal.has_key( flag ) ):
270         val =  self.DictMCVal[ flag ]
271         op = "-"
272         if val == 'yes' :
273           op = "+"
274         txt += "%s = %s %s %s\n" % (self.variable["flags"], self.variable["flags"], op, self.logFlags[ flag ])
275     txt += "Log.Show( %s )\n" % self.variable["flags"]
276     txt += "\n"
277     return txt
278
279   def Footer (self) :
280     '''
281     Imprime le pied de page commun a tous les fichiers
282     '''
283     return footerSTD
284
285   def MinMax (self, subDict):
286     '''
287     Produit le fichier study correspondant a une analyse Min/Max
288     '''
289     txt  = self.Header()
290     txt += self.Model()
291     
292     Methode = None
293     if ( self.DictMCVal.has_key( 'Method' ) ):
294       Methode =  self.DictMCVal[ 'Method' ]
295
296     Traitement = None
297     if ( subDict.has_key( Methode ) ):
298       Traitement =  subDict[ Methode ]
299
300     if ( Traitement is not None ):
301       txt += apply( STDGenerateur.__dict__[ Traitement ], (self,) )
302
303     txt += self.MinMaxResult()
304     
305     txt += self.Footer()
306     return txt
307
308   def Model (self):
309     '''
310     Importe le modele physique
311     '''
312     if ( self.DictMCVal.has_key( 'FileName' ) ):
313       name =  self.DictMCVal[ 'FileName' ]
314       
315     txt  = "# Charge le modele physique\n"
316     txt += "%s = WrapperFile( '%s' )\n" % (self.variable["wrapper"], name)
317     txt += "%s = %s.getWrapperData()\n" % (self.variable["wrapperdata"], self.variable["wrapper"])
318
319     txt += "# Ces lignes sont utiles pour le fonctionnement du script sous Salome\n"
320     txt += "if globals().has_key('%s'):\n" % self.variable["framework"]
321     txt += "  %s = %s.getFrameworkData()\n" % (self.variable["frameworkdata"], self.variable["wrapperdata"])
322     txt += "  %s.studyid_ = %s['%s']\n"  % (self.variable["frameworkdata"], self.variable["framework"], self.variable["studyid"])
323     txt += "  %s.studycase_ = %s['%s']\n"  % (self.variable["frameworkdata"], self.variable["framework"], self.variable["studycase"])
324     txt += "  %s.componentname_ = %s['%s']\n"  % (self.variable["frameworkdata"], self.variable["framework"], self.variable["componentname"])
325     txt += "  %s.setFrameworkData( %s )\n" % (self.variable["wrapperdata"], self.variable["frameworkdata"])
326     txt += "  %s.setWrapperData( %s )\n" % (self.variable["wrapper"], self.variable["wrapperdata"])
327     txt += "# Fin des lignes pour Salome\n"
328     
329     txt += "%s = NumericalMathFunction( %s )\n" % (self.variable["model"], self.variable["wrapper"],)
330     txt += "%s = %s.getInputDimension()\n" % (self.variable["n"], self.variable["model"])
331     txt += "\n"
332     return txt
333
334   def ExperimentPlane (self):
335     '''
336     Etude par plan d experience
337     '''
338     txt  = "# Etude par plan d'experience\n"
339     txt += self.Levels()
340     txt += self.CenteredReductedGrid()
341     txt += self.ScaledVector()
342     txt += self.TranslationVector()
343     txt += "%s = %s\n" % (self.variable["inputSample"], self.variable["myExperimentPlane"])
344     txt += "\n"
345     txt += "# Etude 'Min/Max'\n"
346     txt += "# Calcul\n"
347     txt += "%s = %s( %s )\n" % (self.variable["outputSample"], self.variable["model"], self.variable["inputSample"])
348     txt += "if contain_nan_values( %s ):\n" % (self.variable["outputSample"])
349     txt += "  raise Exception('Some computations failed')\n"
350     txt += "\n"
351     return txt
352
353   def MinMaxRandomSampling (self):
354     '''
355     Etude par echantillonage aleatoire
356     '''
357     size = 0
358     if ( self.DictMCVal.has_key( 'SimulationsNumber' ) ):
359       size =  self.DictMCVal[ 'SimulationsNumber' ]
360
361     txt  = "# Etude par echantillonage aleatoire\n"
362     txt += self.InputDistribution()
363     txt += self.InputRandomVector()
364     txt += "\n"
365     txt += "# Etude 'Min/Max'\n"
366     txt += "# Calcul\n"
367     txt += "%s = %d\n" % (self.variable["inSize"], size)
368     txt += "%s = RandomVector( %s, %s )\n" % (self.variable["outputRandomVector"], self.variable["model"], self.variable["inputRandomVector"])
369     txt += "%s = %s.getSample( %s )\n" % (self.variable["outputSample"], self.variable["outputRandomVector"], self.variable["inSize"])
370     txt += "if contain_nan_values( %s ):\n" % (self.variable["outputSample"])
371     txt += "  raise Exception('Some computations failed')\n"
372     return txt
373
374   def InputDistribution (self):
375     '''
376     Cree la loi jointe des variables d entree
377     '''
378     txt  = "# Definit la loi jointe des variables d'entree\n"
379     txt += "%s = DistributionCollection( %s )\n" % (self.variable["collection"], self.variable["n"])
380     txt += "%s = Description( %s )\n" % (self.variable["description"], self.variable["n"])
381     txt += "\n"
382
383     dictVariables = {}
384     for variable in self.ListeVariablesIn:
385       nomVar = variable['ModelVariable'].get_name()
386       dictVariables[ nomVar ] = variable['Distribution']
387
388     i = 0
389     sortedVarNames = dictVariables.keys()
390     sortedVarNames.sort()
391     for variable in sortedVarNames:
392       conceptloi = dictVariables[ variable ]
393       loi = self.DictLois[ conceptloi ]
394       if loi.has_key( 'Kind' ):
395         marginale = "%s_%d" % (self.variable["marginal"], i)
396         txt += "# Definit la loi marginale de la composante %d\n" % i
397         txt += "%s = %s\n" % (marginale, apply( STDGenerateur.__dict__[ loi[ 'Kind' ] ], (self, loi) ))
398         txt += "%s.setName( '%s' )\n" % (marginale, conceptloi.get_name())
399         txt += "%s[ %d ] = '%s'\n" % (self.variable["description"], i, variable)
400         txt += "%s[ %d ] = Distribution( %s )\n" % (self.variable["collection"], i, marginale)
401         txt += "\n"
402         i += 1
403
404     txt += self.Copula()
405
406     txt += "# Definit la loi jointe\n"
407     txt += "%s = ComposedDistribution( %s, Copula( %s ) )\n" % (self.variable["distribution"], self.variable["collection"], self.variable["copula"])
408     txt += "%s.setDescription( %s )\n" % (self.variable["distribution"], self.variable["description"])
409     txt += "\n"
410     return txt
411
412   def Copula (self):
413     '''
414     Cree la copule de la loi jointe
415     '''
416     txt  = "# Definit la copule de la loi jointe\n"
417
418     if ( not self.DictMCVal.has_key( 'Copula' ) ):
419       self.DictMCVal[ 'Copula' ] = 'Independent'
420
421     if ( self.DictMCVal[ 'Copula' ] in ( 'Independent', ) ):
422       txt += "%s = IndependentCopula( %s )\n" % (self.variable["copula"], self.variable["n"])
423     elif ( self.DictMCVal[ 'Copula' ] in ( 'Normal', ) ):
424       varList   = self.DictMCVal[ 'CorrelationMatrix' ][0]
425       dimension = len(varList)
426       txt += "%s = {}\n" % self.variable["correlation"]
427       for i in range( dimension ):
428         txt += "%s['%s'] = {}\n" % (self.variable["correlation"], varList[i])
429         for j in range ( dimension ):
430           txt += "%s['%s']['%s'] = %g\n" % (self.variable["correlation"], varList[i], varList[j], self.DictMCVal[ 'CorrelationMatrix' ][i+1][j])
431       txt += "%s = getCorrelationMatrixFromMap( %s.getVariableList(), %s )\n" % (self.variable["R"], self.variable["wrapperdata"], self.variable["correlation"])
432       txt += "%s = NormalCopula( %s )\n" % (self.variable["copula"], self.variable["R"])
433
434     txt += "\n"
435     return txt
436
437   def InputRandomVector (self):
438     '''
439     Cree le vector aleatoire d entree
440     '''
441     txt  = "# Definit le vecteur aleatoire d'entree\n"
442     txt += "%s = RandomVector( %s )\n" % (self.variable["inputRandomVector"], self.variable["distribution"])
443     txt += "\n"
444     return txt
445
446   def OutputRandomVector (self):
447     '''
448     Cree le vector aleatoire de sortie
449     '''
450     nomVar = "output"
451     for variable in self.ListeVariablesOut:
452       nomVar = variable['ModelVariable'].get_name()
453
454     txt  = "# Definit le vecteur aleatoire de sortie\n"
455     txt += "%s = RandomVector( %s, %s )\n" % (self.variable["outputRandomVector"], self.variable["model"], self.variable["inputRandomVector"])
456     txt += "%s.setName( '%s' )\n" % (self.variable["outputRandomVector"], nomVar)
457     txt += "\n"
458     return txt
459
460   def ScaledVector (self):
461     '''
462     Definit les coefficients multiplicateurs par composante du vecteur
463     '''
464     dimension = 0
465     if ( self.DictMCVal.has_key( 'UnitsPerDimension' ) ):
466       unitsPerDimension =  self.DictMCVal[ 'UnitsPerDimension' ]
467       dimension = len( unitsPerDimension )
468     
469     txt  = "# Definit les facteurs d'echelle dans chaque direction\n"
470     txt += "%s = NumericalPoint( %s )\n" % (self.variable["scaledVector"], self.variable["n"])
471     for i in range(dimension):
472       txt += "%s[%d] = %g\n" % (self.variable["scaledVector"], i, unitsPerDimension[i])
473     txt += "%s.scale( %s )\n" % (self.variable["myExperimentPlane"], self.variable["scaledVector"])
474     txt += "\n"
475     return txt
476
477   def TranslationVector (self):
478     '''
479     Definit le vecteur de translation
480     '''
481     dimension = 0
482     if ( self.DictMCVal.has_key( 'Center' ) ):
483       center =  self.DictMCVal[ 'Center' ]
484       dimension = len( center )
485     
486     txt  = "# Definit le vecteur de translation\n"
487     txt += "%s = NumericalPoint( %s )\n" % (self.variable["translationVector"], self.variable["n"])
488     for i in range(dimension):
489       txt += "%s[%d] = %g\n" % (self.variable["translationVector"], i, center[i])
490     txt += "%s.translate( %s )\n" % (self.variable["myExperimentPlane"], self.variable["translationVector"])
491     txt += "\n"
492     return txt
493
494   def Levels (self):
495     '''
496     Definit les niveaux du plan d experience
497     '''
498     dimension = 0
499     if ( self.DictMCVal.has_key( 'Levels' ) ):
500       levels =  self.DictMCVal[ 'Levels' ]
501       dimension = len( levels )
502     
503     txt  = "# Definit les niveaux de la structure de grille\n"
504     txt += "%s = NumericalPoint( %d )\n" % (self.variable["levels"], dimension)
505     for i in range(dimension):
506       txt += "%s[%d] = %g\n" % (self.variable["levels"], i, levels[i])
507     txt += "\n"
508     return txt
509
510   def CenteredReductedGrid (self):
511     '''
512     Definit la grille reduite du plan d experience
513     '''
514     plane = None
515     if ( self.DictMCVal.has_key( 'ExperimentPlane' ) ):
516       plane =  self.DictMCVal[ 'ExperimentPlane' ]
517
518     txt  = "# Cree le plan d'experience centre reduit\n"
519     txt += "%s = %s(%s, %s)\n" % (self.variable["myCenteredReductedGrid"], plane, self.variable["n"], self.variable["levels"])
520     txt += "%s = %s.generate()\n" % (self.variable["myExperimentPlane"], self.variable["myCenteredReductedGrid"])
521     txt += "\n"
522     return txt
523
524   def MinMaxResult (self):
525     '''
526     Produit les resultats de l etude
527     '''
528     txt  = "# Resultats\n"
529     txt += "%s = %s.getMin()\n" % (self.variable["minValue"], self.variable["outputSample"])
530     txt += "print '%s = ', %s\n" % ("minValue", self.variable["minValue"])
531     txt += "\n"
532     txt += "%s = %s.getMax()\n" % (self.variable["maxValue"], self.variable["outputSample"])
533     txt += "print '%s = ', %s\n" % ("maxValue", self.variable["maxValue"])
534     txt += "\n"
535     return txt
536
537   def CentralUncertainty (self, subDict):
538     '''
539     Produit le fichier study correspondant a une analyse d incertitude en valeur centrale
540     '''
541     txt  = self.Header()
542     txt += self.Model()
543     txt += self.InputDistribution()
544     txt += self.InputRandomVector()
545     txt += self.OutputRandomVector()
546    
547     Methode = None
548     if ( self.DictMCVal.has_key( 'Method' ) ):
549       Methode =  self.DictMCVal[ 'Method' ]
550
551     Traitement = None
552     if ( subDict.has_key( Methode ) ):
553       Traitement =  subDict[ Methode ]
554
555     if ( Traitement is not None ):
556       txt += "# Etude 'Central Uncertainty'\n"
557       txt += apply( STDGenerateur.__dict__[ Traitement ], (self,) )
558
559     txt += self.Footer()
560     return txt
561
562
563   def TaylorVarianceDecomposition (self):
564     '''
565     Etude par decomposition de Taylor
566     '''
567     txt  = "# Cumul quadratique (decomposition de Taylor)\n"
568     txt += "%s = QuadraticCumul( %s )\n" % (self.variable["myQuadraticCumul"], self.variable["outputRandomVector"])
569     txt += "\n"
570     txt += "# Resultats\n"
571     
572     if ( self.DictMCVal.has_key( 'MeanFirstOrder' ) ):
573       if ( self.DictMCVal[ 'MeanFirstOrder' ] == "yes" ):
574         txt += "%s = %s.getMeanFirstOrder()\n" % (self.variable["meanFirstOrder"], self.variable["myQuadraticCumul"])
575         txt += "print '%s = ', %s\n" % ("mean First Order", self.variable["meanFirstOrder"])
576         txt += "\n"
577        
578     if ( self.DictMCVal.has_key( 'MeanSecondOrder' ) ):
579       if ( self.DictMCVal[ 'MeanSecondOrder' ] == "yes" ):
580         txt += "%s = %s.getMeanSecondOrder()\n" % (self.variable["meanSecondOrder"], self.variable["myQuadraticCumul"])
581         txt += "print '%s = ', %s\n" % ("mean Second Order", self.variable["meanSecondOrder"])
582         txt += "\n"
583
584     if ( self.DictMCVal.has_key( 'StandardDeviationFirstOrder' ) ):
585       if ( self.DictMCVal[ 'StandardDeviationFirstOrder' ] == "yes" ):
586         txt += "%s = %s.getCovariance()\n" % (self.variable["standardDeviationFirstOrder"], self.variable["myQuadraticCumul"])
587         txt += "dim = %s.getDimension()\n" % self.variable["standardDeviationFirstOrder"]
588         txt += "for i in range( dim ):\n"
589         txt += "  %s[ i, i ] = math.sqrt( %s[ i, i ] )\n" % (self.variable["standardDeviationFirstOrder"], self.variable["standardDeviationFirstOrder"])
590         txt += "  print '%s = ', %s[ i, i ]\n" % ("standard Deviation First Order", self.variable["standardDeviationFirstOrder"])
591         txt += "\n"
592
593     if ( self.DictMCVal.has_key( 'ImportanceFactor' ) ):
594       if ( self.DictMCVal[ 'ImportanceFactor' ] == "yes" ):
595         txt += "%s = %s.getImportanceFactors()\n" % (self.variable["importanceFactors"], self.variable["myQuadraticCumul"])
596         txt += "for i in range(%s.getDimension()):\n" % self.variable["importanceFactors"]
597         txt += "  print %s.getDescription()[i], ':', %s[i]*100., '%%'\n" % (self.variable["distribution"], self.variable["importanceFactors"])
598         txt += "\n"
599         txt += "%s = %s.drawImportanceFactors()\n" % (self.variable["importanceFactorsGraph"], self.variable["myQuadraticCumul"])
600         txt += "%s = '%s'\n" % (self.variable["importanceFactorsDrawing"], self.DictMCVal[ 'ImportanceFactorDrawingFilename' ])
601         txt += "%s.draw( %s )\n" % (self.variable["importanceFactorsGraph"], self.variable["importanceFactorsDrawing"])
602         txt += "#if is_xserver_available():\n"
603         txt += "#  view = View(%s)\n" % self.variable["importanceFactorsGraph"]
604         txt += "#  view.show(block=True)\n"
605         txt += "#else:\n"
606         txt += "#  print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["importanceFactorsGraph"]
607         txt += "print 'bitmap =', %s.getBitmap()\n"  % self.variable["importanceFactorsGraph"]
608         txt += "print 'postscript =', %s.getPostscript()\n"  % self.variable["importanceFactorsGraph"]
609         txt += "\n"
610         
611     txt += "\n"
612     return txt
613
614   def CentralUncertaintyRandomSampling (self):
615     '''
616     Etude par echantillonage aleatoire
617     '''
618     size = 0
619     if ( self.DictMCVal.has_key( 'SimulationsNumber' ) ):
620       size =  self.DictMCVal[ 'SimulationsNumber' ]
621
622     txt  = "# Echantillonnage aleatoire de la variable de sortie\n"
623     txt += "%s = %d\n" % (self.variable["inSize"], size)
624     txt += "%s = %s.getSample( %s )\n" % (self.variable["inputSample"], self.variable["inputRandomVector"], self.variable["inSize"])
625     txt += "%s = %s( %s )\n" % (self.variable["outputSample"], self.variable["model"], self.variable["inputSample"])
626     txt += "if contain_nan_values( %s ):\n" % (self.variable["outputSample"])
627     txt += "  raise Exception('Some computations failed')\n"
628     txt += "\n"
629
630     if ( self.DictMCVal.has_key( 'EmpiricalMean' ) ):
631       if ( self.DictMCVal[ 'EmpiricalMean' ] == "yes" ):
632         txt += "%s = %s.computeMean()\n" % (self.variable["empiricalMean"], self.variable["outputSample"])
633         txt += "print '%s =', %s[0]\n" % ("empirical Mean", self.variable["empiricalMean"])
634         txt += "\n"
635
636     if ( self.DictMCVal.has_key( 'EmpiricalStandardDeviation' ) ):
637       if ( self.DictMCVal[ 'EmpiricalStandardDeviation' ] == "yes" ):
638         txt += "%s = %s.computeCovariance()\n" % (self.variable["empiricalStandardDeviation"], self.variable["outputSample"])
639         txt += "dim = %s.getDimension()\n" % self.variable["empiricalStandardDeviation"]
640         txt += "for i in range( dim ):\n"
641         txt += "  %s[ i, i ] = math.sqrt( %s[ i, i ] )\n" % (self.variable["empiricalStandardDeviation"], self.variable["empiricalStandardDeviation"])
642         txt += "  print '%s = ', %s[ i, i ]\n" % ("empirical Standard Deviation", self.variable["empiricalStandardDeviation"])
643         txt += "\n"
644
645     if ( self.DictMCVal.has_key( 'EmpiricalQuantile_Order' ) ):
646       ordre = self.DictMCVal[ 'EmpiricalQuantile_Order' ]
647       txt += "%s = %s.computeQuantile( %s )\n" % (self.variable["empiricalQuantile"], self.variable["outputSample"], ordre)
648       txt += "print '%s ( %s ) =', %s\n" % ("empirical Quantile", ordre, self.variable["empiricalQuantile"])
649       txt += "\n"
650    
651     if ( self.DictMCVal.has_key( 'CorrelationAnalysis' ) ):
652       if ( self.DictMCVal[ 'CorrelationAnalysis' ] == "yes" ):
653         txt += "if ( %s.getDimension() == 1 ):\n" % self.variable["outputSample"]
654         txt += "  %s = CorrelationAnalysis.PCC( %s, %s )\n" % (self.variable["PCCcoefficient"], self.variable["inputSample"], self.variable["outputSample"])
655         txt += "  print 'PCC Coefficients:'\n"
656         txt += "  for i in range( %s ):\n" % self.variable["n"]
657         txt += "    print %s.getDescription()[i], ':', %s[i]\n" % (self.variable["distribution"], self.variable["PCCcoefficient"])
658         txt += "\n"
659         txt += "  %s = CorrelationAnalysis.PRCC( %s, %s )\n" % (self.variable["PRCCcoefficient"], self.variable["inputSample"], self.variable["outputSample"])
660         txt += "  print 'PRCC Coefficients:'\n"
661         txt += "  for i in range( %s ):\n" % self.variable["n"]
662         txt += "    print %s.getDescription()[i], ':', %s[i]\n" % (self.variable["distribution"], self.variable["PRCCcoefficient"])
663         txt += "\n"
664         txt += "  %s = CorrelationAnalysis.SRC( %s, %s )\n" % (self.variable["SRCcoefficient"], self.variable["inputSample"], self.variable["outputSample"])
665         txt += "  print 'SRC Coefficients:'\n"
666         txt += "  for i in range( %s ):\n" % self.variable["n"]
667         txt += "    print %s.getDescription()[i], ':', %s[i]\n" % (self.variable["distribution"], self.variable["SRCcoefficient"])
668         txt += "\n"
669         txt += "  %s = CorrelationAnalysis.SRRC( %s, %s )\n" % (self.variable["SRRCcoefficient"], self.variable["inputSample"], self.variable["outputSample"])
670         txt += "  print 'SRRC Coefficients:'\n"
671         txt += "  for i in range( %s ):\n" % self.variable["n"]
672         txt += "    print %s.getDescription()[i], ':', %s[i]\n" % (self.variable["distribution"], self.variable["SRRCcoefficient"])
673         txt += "\n"
674    
675     if ( self.DictMCVal.has_key( 'KernelSmoothing' ) ):
676       if ( self.DictMCVal[ 'KernelSmoothing' ] == "yes" ):
677         txt += "# Kernel Smoohing\n"
678         txt += "%s = KernelSmoothing()\n" % self.variable["kernel"]
679         txt += "if ( %s.getDimension() == 1 ):\n" % self.variable["outputSample"]
680         txt += "  %s.setName( 'Output' )\n" % self.variable["outputSample"]
681         txt += "  %s = %s.build( %s, 'TRUE')\n" % (self.variable["kernelSmoothedDist"], self.variable["kernel"], self.variable["outputSample"])
682         txt += "  %s = %s.drawPDF()\n" % (self.variable["kernelSmoothedGraph"], self.variable["kernelSmoothedDist"])
683         txt += "  %s = '%s'\n" % (self.variable["kernelSmoothedPDFDrawing"], self.DictMCVal[ 'KernelSmoothingDrawingFilename' ])
684         txt += "  %s.draw( %s )\n" % (self.variable["kernelSmoothedGraph"], self.variable["kernelSmoothedPDFDrawing"])
685         txt += "  #if is_xserver_available():\n"
686         txt += "  #  view = View(%s)\n" % self.variable["kernelSmoothedGraph"]
687         txt += "  #  view.show(block=True)\n"
688         txt += "  #else:\n"
689         txt += "  #  print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["kernelSmoothedGraph"]
690         txt += "  print 'bitmap =', %s.getBitmap()\n"  % self.variable["kernelSmoothedGraph"]
691         txt += "  print 'postscript =', %s.getPostscript()\n"  % self.variable["kernelSmoothedGraph"]
692         txt += "\n"
693    
694     return txt
695
696   def ThresholdExceedence (self, subDict):
697     '''
698     Produit le fichier study correspondant a une analyse de depassement de seuil
699     '''
700     txt  = self.Header()
701     txt += "# Etude 'Threshold Exceedence'\n"
702
703     txt += self.RandomGenerator()
704     txt += self.Model()
705     txt += self.InputDistribution()
706     txt += self.InputRandomVector()
707     txt += self.OutputRandomVector()
708     txt += self.Event()
709    
710     Methode = None
711     if ( self.DictMCVal.has_key( 'Method' ) ):
712       Methode =  self.DictMCVal[ 'Method' ]
713
714     Traitement = None
715     if ( subDict.has_key( Methode ) ):
716       Traitement =  subDict[ Methode ]
717
718     if ( Traitement is not None ):
719       txt += apply( STDGenerateur.__dict__[ Traitement ], (self, subDict) )
720
721     txt += self.Footer()
722     return txt
723
724   def Simulation (self, subDict):
725     '''
726     Methodes de simulation
727     '''
728     Algorithme = None
729     if ( self.DictMCVal.has_key( 'Algorithm' ) ):
730       Algorithme =  self.DictMCVal[ 'Algorithm' ]
731
732     Traitement = None
733     if ( subDict.has_key( Algorithme ) ):
734       Traitement =  subDict[ Algorithme ]
735
736     if ( Traitement is not None ):
737       txt = apply( STDGenerateur.__dict__[ Traitement ], (self,) )
738
739     maxOuterSampling = None
740     if ( self.DictMCVal.has_key( 'MaximumOuterSampling' ) ):
741       maxOuterSampling = self.DictMCVal[ 'MaximumOuterSampling' ]
742       txt += "%s.setMaximumOuterSampling( %s )\n" % (self.variable["myAlgo"], maxOuterSampling)
743
744     blockSize = None
745     if ( self.DictMCVal.has_key( 'BlockSize' ) ):
746       blockSize = self.DictMCVal[ 'BlockSize' ]
747       txt += "%s.setBlockSize( %s )\n" % (self.variable["myAlgo"], blockSize)
748
749     maxCoefficientOfVariation = None
750     if ( self.DictMCVal.has_key( 'MaximumCoefficientOfVariation' ) ):
751       maxCoefficientOfVariation = self.DictMCVal[ 'MaximumCoefficientOfVariation' ]
752       txt += "%s.setMaximumCoefficientOfVariation( %s )\n" % (self.variable["myAlgo"], maxCoefficientOfVariation)
753
754     txt += "%s.run()\n"  % self.variable["myAlgo"]
755     txt += "\n"
756     txt += "# Resultats de la simulation\n"
757     txt += "%s = %s.getResult()\n"  % (self.variable["myResult"], self.variable["myAlgo"])
758     txt += "\n"
759
760     if ( self.DictMCVal.has_key( 'Probability' ) ):
761       if ( self.DictMCVal[ 'Probability' ] == "yes" ):
762         txt += "%s = %s.getProbabilityEstimate()\n" % (self.variable["probability"], self.variable["myResult"])
763         txt += "print '%s =', %s\n" % ("probability", self.variable["probability"])
764         txt += "\n"
765
766     if ( self.DictMCVal.has_key( 'StandardDeviation' ) ):
767       if ( self.DictMCVal[ 'StandardDeviation' ] == "yes" ):
768         txt += "%s = math.sqrt( %s.getProbabilityEstimate() )\n" % (self.variable["standardDeviation"], self.variable["myResult"])
769         txt += "print '%s =', %s\n" % ("standard Deviation", self.variable["standardDeviation"])
770         txt += "\n"
771
772     if ( self.DictMCVal.has_key( 'ConfidenceInterval' ) and self.DictMCVal.has_key( 'Probability' ) ):
773       if ( ( self.DictMCVal[ 'ConfidenceInterval' ] == "yes" ) and ( self.DictMCVal[ 'Probability' ] == "yes" ) ):
774         level = self.DictMCVal[ 'Level' ]
775         txt += "%s = %s.getConfidenceLength( %s )\n" % (self.variable["length"], self.variable["myResult"], level)
776         txt += "print 'confidence interval at %s = [', %s-0.5*%s, ',', %s+0.5*%s, ']'\n" % (level, self.variable["probability"], self.variable["length"], self.variable["probability"], self.variable["length"])
777         txt += "\n"
778
779     if ( self.DictMCVal.has_key( 'VariationCoefficient' ) ):
780       if ( self.DictMCVal[ 'VariationCoefficient' ] == "yes" ):
781         txt += "%s = %s.getCoefficientOfVariation()\n" % (self.variable["coefficientOfVariation"], self.variable["myResult"])
782         txt += "print '%s =', %s\n" % ("coefficient of Variation", self.variable["coefficientOfVariation"])
783         txt += "\n"
784
785     if ( self.DictMCVal.has_key( 'SimulationsNumber' ) ):
786       if ( self.DictMCVal[ 'SimulationsNumber' ] == "yes" ):
787         txt += "%s = %s.getOuterSampling()\n" % (self.variable["simulationNumbers"], self.variable["myResult"])
788         txt += "print '%s =', %s\n" % ("simulation Numbers", self.variable["simulationNumbers"])
789         txt += "\n"
790
791     if ( self.DictMCVal.has_key( 'ConvergenceGraph' ) and self.DictMCVal.has_key( 'ConfidenceInterval' ) ):
792       if ( ( self.DictMCVal[ 'ConvergenceGraph' ] == "yes" ) and ( self.DictMCVal[ 'ConfidenceInterval' ] == "yes" ) ):
793         txt += "%s = %s\n" % (self.variable["alpha"], self.DictMCVal[ 'Level' ])
794         txt += "%s = %s.drawProbabilityConvergence( %s )\n" % (self.variable["convergenceGraph"], self.variable["myAlgo"], self.variable["alpha"])
795         txt += "%s = '%s'\n" % (self.variable["convergenceDrawing"], self.DictMCVal[ 'ConvergenceDrawingFilename' ])
796         txt += "%s.draw( %s )\n" % (self.variable["convergenceGraph"], self.variable["convergenceDrawing"])
797         txt += "#if is_xserver_available():\n"
798         txt += "#  view = View(%s)\n" % self.variable["convergenceGraph"]
799         txt += "#  view.show(block=True)\n"
800         txt += "#else:\n"
801         txt += "#  print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["convergenceGraph"]
802         txt += "\n"
803
804     return txt
805
806   def Analytical (self, subDict):
807     '''
808     Methodes analytiques
809     '''
810     txt = ""
811     
812     OptimizationAlgo = None
813     if ( self.DictMCVal.has_key( 'OptimizationAlgorithm' ) ):
814       OptimizationAlgo =  self.DictMCVal[ 'OptimizationAlgorithm' ]
815
816     Traitement = None
817     if ( subDict.has_key( OptimizationAlgo ) ):
818       Traitement =  subDict[ OptimizationAlgo ]
819
820     if ( Traitement is not None ):
821       txt += apply( STDGenerateur.__dict__[ Traitement ], (self,) )
822
823     txt += self.OptimizerSettings()
824     txt += self.PhysicalStartingPoint()
825
826     Approximation = None
827     if ( self.DictMCVal.has_key( 'Approximation' ) ):
828       Approximation =  self.DictMCVal[ 'Approximation' ]
829
830     Traitement = None
831     if ( subDict.has_key( Approximation ) ):
832       Traitement =  subDict[ Approximation ]
833
834     if ( Traitement is not None ):
835       txt += apply( STDGenerateur.__dict__[ Traitement ], (self,) )
836
837     txt += self.RunAlgorithm()
838     txt += self.AnalyticalResult()
839
840     return txt
841
842   def OptimizerSettings (self):
843     '''
844     Parametrage de l optimiseur
845     '''
846     txt = ""
847     
848     simulationNumbers = None
849     if ( self.DictMCVal.has_key( 'MaximumIterationsNumber' ) ):
850       simulationNumbers = self.DictMCVal[ 'MaximumIterationsNumber' ]
851       txt += "%s.setMaximumIterationsNumber( %s )\n" % (self.variable["myOptimizer"], simulationNumbers)
852
853     absoluteError = None
854     if ( self.DictMCVal.has_key( 'MaximumAbsoluteError' ) ):
855       absoluteError = self.DictMCVal[ 'MaximumAbsoluteError' ]
856       txt += "%s.setMaximumAbsoluteError( %s )\n" % (self.variable["myOptimizer"], absoluteError)
857
858     relativeError = None
859     if ( self.DictMCVal.has_key( 'MaximumRelativeError' ) ):
860       relativeError = self.DictMCVal[ 'MaximumRelativeError' ]
861       txt += "%s.setMaximumRelativeError( %s )\n" % (self.variable["myOptimizer"], relativeError)
862
863     residualError = None
864     if ( self.DictMCVal.has_key( 'MaximumResidualError' ) ):
865       residualError = self.DictMCVal[ 'MaximumResidualError' ]
866       txt += "%s.setMaximumResidualError( %s )\n" % (self.variable["myOptimizer"], residualError)
867
868     constraintError = None
869     if ( self.DictMCVal.has_key( 'MaximumConstraintError' ) ):
870       constraintError = self.DictMCVal[ 'MaximumConstraintError' ]
871       txt += "%s.setMaximumConstraintError( %s )\n" % (self.variable["myOptimizer"], constraintError)
872
873     txt += "\n"
874
875     return txt
876
877   def PhysicalStartingPoint (self):
878     '''
879     Point physique de depart
880     '''
881     txt  = "# Point physique de depart\n"
882
883     if ( self.DictMCVal.has_key( 'PhysicalStartingPoint' ) ):
884       point = self.DictMCVal[ 'PhysicalStartingPoint' ]
885       dimension = len( point )
886       txt += "%s = NumericalPoint( %d )\n" % (self.variable["startingPoint"], dimension)
887       for i in range( dimension ):
888         txt += "%s[ %d ] = %g\n" % (self.variable["startingPoint"], i, point[i])
889     else:
890       txt += "%s = %s.getMean()\n" % (self.variable["startingPoint"], self.variable["inputRandomVector"])
891       
892     txt += "\n"
893
894     return txt
895
896   def AnalyticalResult (self):
897     '''
898     Resultat des methodes analytiques
899     '''
900     txt  = "# Resultat des methodes analytiques\n"
901     txt += "%s = %s.getResult()\n" % (self.variable["myResult"], self.variable["myAlgo"])
902     
903     if ( self.DictMCVal.has_key( 'Probability' ) ):
904       if ( self.DictMCVal[ 'Probability' ] == "yes" ):
905         txt += "%s = %s.getEventProbability()\n" % (self.variable["probability"], self.variable["myResult"])
906         txt += "print '%s =', %s\n" % (self.variable["probability"], self.variable["probability"])
907         txt += "\n"
908
909     if ( self.DictMCVal.has_key( 'HasoferReliabilityIndex' ) ):
910       if ( self.DictMCVal[ 'HasoferReliabilityIndex' ] == "yes" ):
911         txt += "%s = %s.getHasoferReliabilityIndex()\n" % (self.variable["hasoferReliabilityIndex"], self.variable["myResult"])
912         txt += "print '%s =', %s\n" % ("hasofer Reliability Index", self.variable["hasoferReliabilityIndex"])
913         txt += "\n"
914
915     if ( self.DictMCVal.has_key( 'DesignPoint' ) ):
916       if ( self.DictMCVal[ 'DesignPoint' ] == "yes" ):
917         txt += "%s = %s.getStandardSpaceDesignPoint()\n" % (self.variable["standardSpaceDesignPoint"], self.variable["myResult"])
918         txt += "print '%s =', %s\n" % ("standard Space Design Point", self.variable["standardSpaceDesignPoint"])
919         txt += "%s = %s.getPhysicalSpaceDesignPoint()\n" % (self.variable["physicalSpaceDesignPoint"], self.variable["myResult"])
920         txt += "print '%s =', %s\n" % ("physical Space Design Point", self.variable["physicalSpaceDesignPoint"])
921         txt += "\n"
922
923     if ( self.DictMCVal.has_key( 'ImportanceFactor' ) ):
924       if ( self.DictMCVal[ 'ImportanceFactor' ] == "yes" ):
925         txt += "print 'Importance Factors:'\n"
926         txt += "%s = %s.getImportanceFactors()\n" % (self.variable["importanceFactors"], self.variable["myResult"])
927         txt += "for i in range(%s.getDimension()):\n" % self.variable["importanceFactors"]
928         txt += "  print %s.getDescription()[i], ':', %s[i]*100., '%%'\n" % (self.variable["distribution"], self.variable["importanceFactors"])
929         txt += "\n"
930         txt += "%s = %s.drawImportanceFactors()\n" % (self.variable["importanceFactorsGraph"], self.variable["myResult"])
931         txt += "%s = '%s'\n" % (self.variable["importanceFactorsDrawing"], self.DictMCVal[ 'ImportanceFactorDrawingFilename' ])
932         txt += "%s.draw( %s )\n" % (self.variable["importanceFactorsGraph"], self.variable["importanceFactorsDrawing"])
933         txt += "#if is_xserver_available():\n"
934         txt += "#  view = View(%s)\n" % self.variable["importanceFactorsGraph"]
935         txt += "#  view.show(block=True)\n"
936         txt += "#else:\n"
937         txt += "#  print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["importanceFactorsGraph"]
938         txt += "print 'bitmap =', %s.getBitmap()\n"  % self.variable["importanceFactorsGraph"]
939         txt += "print 'postscript =', %s.getPostscript()\n"  % self.variable["importanceFactorsGraph"]
940         txt += "\n"
941
942     if ( self.DictMCVal.has_key( 'FORMEventProbabilitySensitivity' ) ):
943       if ( self.DictMCVal[ 'FORMEventProbabilitySensitivity' ] == "yes" ):
944         txt += "%s = %s.getEventProbabilitySensitivity()\n" % (self.variable["eventProbabilitySensitivity"], self.variable["myResult"])
945         txt += "print 'FORM Event Probability Sensitivity:'\n"
946         txt += "for i in range( %s ):\n" % self.variable["n"]
947         txt += "  print %s.getDescription()[i], ':'\n" % self.variable["distribution"]
948         txt += "  for j in range( %s[i].getDimension() ):\n" % self.variable["eventProbabilitySensitivity"]
949         txt += "    print '  ', %s[i].getDescription()[j], ':', %s[i][j]\n" % (self.variable["eventProbabilitySensitivity"], self.variable["eventProbabilitySensitivity"])
950         txt += "\n"
951         txt += "%s = %s.drawEventProbabilitySensitivity()[0]\n" % (self.variable["eventProbabilitySensitivityGraph"], self.variable["myResult"])
952         txt += "%s = '%s'\n" % (self.variable["eventProbabilitySensitivityDrawing"], self.DictMCVal[ 'FORMEventProbabilitySensitivityDrawingFilename' ])
953         txt += "%s.draw( %s )\n" % (self.variable["eventProbabilitySensitivityGraph"], self.variable["eventProbabilitySensitivityDrawing"])
954         txt += "#if is_xserver_available():\n"
955         txt += "#  view = View(%s)\n" % self.variable["eventProbabilitySensitivityGraph"]
956         txt += "#  view.show(block=True)\n"
957         txt += "#else:\n"
958         txt += "#  print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["eventProbabilitySensitivityGraph"]
959         txt += "print 'bitmap =', %s.getBitmap()\n"  % self.variable["eventProbabilitySensitivityGraph"]
960         txt += "print 'postscript =', %s.getPostscript()\n"  % self.variable["eventProbabilitySensitivityGraph"]
961         txt += "\n"
962
963     if ( self.DictMCVal.has_key( 'HasoferReliabilityIndexSensitivity' ) ):
964       if ( self.DictMCVal[ 'HasoferReliabilityIndexSensitivity' ] == "yes" ):
965         txt += "%s = %s.getHasoferReliabilityIndexSensitivity()\n" % (self.variable["hasoferReliabilityIndexSensitivity"], self.variable["myResult"])
966         txt += "print 'Hasofer Reliability Index Sensitivity:'\n"
967         txt += "for i in range( %s ):\n" % self.variable["n"]
968         txt += "  print %s.getDescription()[i], ':'\n" % self.variable["distribution"]
969         txt += "  for j in range( %s[i].getDimension() ):\n" % self.variable["hasoferReliabilityIndexSensitivity"]
970         txt += "    print '  ', %s[i].getDescription()[j], ':', %s[i][j]\n" % (self.variable["hasoferReliabilityIndexSensitivity"], self.variable["hasoferReliabilityIndexSensitivity"])
971         txt += "\n"
972         txt += "%s = %s.drawHasoferReliabilityIndexSensitivity()[0]\n" % (self.variable["hasoferReliabilityIndexSensitivityGraph"], self.variable["myResult"])
973         txt += "%s = '%s'\n" % (self.variable["hasoferReliabilityIndexSensitivityDrawing"], self.DictMCVal[ 'HasoferReliabilityIndexSensitivityDrawingFilename' ])
974         txt += "%s.draw( %s )\n" % (self.variable["hasoferReliabilityIndexSensitivityGraph"], self.variable["hasoferReliabilityIndexSensitivityDrawing"])
975         txt += "#if is_xserver_available():\n"
976         txt += "#  view = View(%s)\n" % self.variable["hasoferReliabilityIndexSensitivityGraph"]
977         txt += "#  view.show(block=True)\n"
978         txt += "#else:\n"
979         txt += "#  print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["hasoferReliabilityIndexSensitivityGraph"]
980         txt += "print 'bitmap =', %s.getBitmap()\n"  % self.variable["hasoferReliabilityIndexSensitivityGraph"]
981         txt += "print 'postscript =', %s.getPostscript()\n"  % self.variable["hasoferReliabilityIndexSensitivityGraph"]
982         txt += "\n"
983
984     if ( self.DictMCVal.has_key( 'TvedtApproximation' ) ):
985       if ( self.DictMCVal[ 'TvedtApproximation' ] == "yes" ):
986         txt += "%s = %s.getEventProbabilityTvedt()\n" % (self.variable["tvedtApproximation"], self.variable["myResult"])
987         txt += "print '%s =', %s\n" % ("Tvedt Approximation", self.variable["tvedtApproximation"])
988         txt += "\n"
989
990     if ( self.DictMCVal.has_key( 'HohenBichlerApproximation' ) ):
991       if ( self.DictMCVal[ 'HohenBichlerApproximation' ] == "yes" ):
992         txt += "%s = %s.getEventProbabilityHohenBichler()\n" % (self.variable["hohenBichlerApproximation"], self.variable["myResult"])
993         txt += "print '%s =', %s\n" % ("HohenBichler Approximation", self.variable["tvedtApproximation"])
994         txt += "\n"
995
996     if ( self.DictMCVal.has_key( 'BreitungApproximation' ) ):
997       if ( self.DictMCVal[ 'BreitungApproximation' ] == "yes" ):
998         txt += "%s = %s.getEventProbabilityBreitung()\n" % (self.variable["breitungApproximation"], self.variable["myResult"])
999         txt += "print '%s =', %s\n" % ("Breitung Approximation", self.variable["breitungApproximation"])
1000         txt += "\n"
1001
1002
1003     return txt
1004
1005   def RandomGenerator (self):
1006     '''
1007     Generateur Aleatoire
1008     '''
1009     txt = ""
1010     
1011     seed = None
1012     if ( self.DictMCVal.has_key( 'RandomGeneratorSeed' ) ):
1013       seed = self.DictMCVal[ 'RandomGeneratorSeed' ]
1014       txt += "# Initialise le generateur aleatoire\n"
1015       txt += "RandomGenerator.SetSeed( %s )\n" % seed
1016       txt += "\n"
1017     
1018     return txt
1019
1020   def Event (self):
1021     '''
1022     Definition de l evenement de defaillance
1023     '''
1024     operator = None
1025     if ( self.DictMCVal.has_key( 'ComparisonOperator' ) ):
1026       operator = self.DictMCVal[ 'ComparisonOperator' ]
1027
1028     threshold = None
1029     if ( self.DictMCVal.has_key( 'Threshold' ) ):
1030       threshold = self.DictMCVal[ 'Threshold' ]
1031     
1032     txt  = "# Evenement de defaillance\n"
1033     txt += "%s = Event( %s, ComparisonOperator( %s() ), %s )\n" % (self.variable["myEvent"], self.variable["outputRandomVector"], operator, threshold)
1034     txt += "%s.setName( '%s' )\n" % (self.variable["myEvent"], "myEvent")
1035     txt += "\n"
1036     return txt
1037     
1038   def MonteCarlo (self):
1039     '''
1040     Methode de MonteCarlo
1041     '''
1042     txt  = "# Simulation par MonteCarlo\n"
1043     txt += "%s = MonteCarlo( %s )\n"  % (self.variable["myAlgo"], self.variable["myEvent"])
1044     txt += "\n"
1045    
1046     return txt
1047
1048   def LHS (self):
1049     '''
1050     Methode LHS
1051     '''
1052     txt  = "# Simulation par LHS\n"
1053     txt += "%s = LHS( %s )\n"  % (self.variable["myAlgo"], self.variable["myEvent"])
1054     txt += "\n"
1055    
1056     return txt
1057
1058   def ImportanceSampling (self):
1059     '''
1060     Methode de tirage d importance
1061     '''
1062     dimension = 0
1063     if ( self.DictMCVal.has_key( 'MeanVector' ) ):
1064       meanVector =  self.DictMCVal[ 'MeanVector' ]
1065       dimension = len( meanVector )
1066         
1067     txt  = "# Simulation par Tirage d'importance\n"
1068     txt += "# Densite d'importance\n"
1069     txt += "%s = NumericalPoint( %s )\n" % (self.variable["meanVector"], self.variable["n"])
1070     for i in range(dimension):
1071       txt += "%s[%d] = %g\n" % (self.variable["meanVector"], i, meanVector[i])
1072       
1073     txt += "%s = Normal( %s, CovarianceMatrix( IdentityMatrix( %s ) ) )\n" % (self.variable["importanceDensity"], self.variable["meanVector"], self.variable["n"])
1074     txt += "%s = ImportanceSampling( %s, Distribution( %s ) )\n"  % (self.variable["myAlgo"], self.variable["myEvent"], self.variable["importanceDensity"])
1075     txt += "\n"
1076
1077     return txt
1078
1079   def FORM (self):
1080     '''
1081     Methode FORM
1082     '''
1083     txt  = "# Algorithme FORM\n"
1084     txt += "%s = FORM ( NearestPointAlgorithm( %s ), %s, %s )\n"  % (self.variable["myAlgo"], self.variable["myOptimizer"], self.variable["myEvent"], self.variable["startingPoint"])
1085     txt += "\n"
1086
1087     return txt
1088
1089   def SORM (self):
1090     '''
1091     Methode SORM
1092     '''
1093     txt  = "# Algorithme SORM\n"
1094     txt += "%s = SORM ( NearestPointAlgorithm( %s ), %s, %s )\n"  % (self.variable["myAlgo"], self.variable["myOptimizer"], self.variable["myEvent"], self.variable["startingPoint"])
1095     txt += "\n"
1096
1097     return txt
1098
1099   def RunAlgorithm (self):
1100     '''
1101     Do the computation
1102     '''
1103     txt = ""
1104     if ( self.DictMCVal.has_key( 'FunctionCallsNumber' ) ):
1105       if ( self.DictMCVal[ 'FunctionCallsNumber' ] == "yes" ):
1106         txt += "%s = %s.getEvaluationCallsNumber()\n" % (self.variable["modelEvaluationCalls"], self.variable["model"])
1107         txt += "%s = %s.getGradientCallsNumber()\n" % (self.variable["modelGradientCalls"], self.variable["model"])
1108         txt += "%s = %s.getHessianCallsNumber()\n" % (self.variable["modelHessianCalls"], self.variable["model"])
1109         txt += "\n"
1110
1111     txt += "# Perform the computation\n"
1112     txt += "%s.run()\n" % self.variable["myAlgo"]
1113     txt += "\n"
1114     
1115
1116     if ( self.DictMCVal.has_key( 'FunctionCallsNumber' ) ):
1117       if ( self.DictMCVal[ 'FunctionCallsNumber' ] == "yes" ):
1118         txt += "%s = %s.getEvaluationCallsNumber() - %s\n" % (self.variable["modelEvaluationCalls"], self.variable["model"], self.variable["modelEvaluationCalls"])
1119         txt += "%s = %s.getGradientCallsNumber() - %s\n" % (self.variable["modelGradientCalls"], self.variable["model"], self.variable["modelGradientCalls"])
1120         txt += "%s = %s.getHessianCallsNumber() - %s\n" % (self.variable["modelHessianCalls"], self.variable["model"], self.variable["modelHessianCalls"])
1121         txt += "\n"
1122         txt += "print '%s =', %s\n" % ("model Evaluation Calls", self.variable["modelEvaluationCalls"])
1123         txt += "print '%s =', %s\n" % ("model Gradient Calls", self.variable["modelGradientCalls"])
1124         txt += "print '%s =', %s\n" % ("model Hessian Calls", self.variable["modelHessianCalls"])
1125         txt += "\n"
1126
1127     return txt
1128
1129   def Cobyla (self):
1130     '''
1131     Methode Cobyla
1132     '''
1133     txt  = "# Optimisation par Cobyla\n"
1134     txt += "%s = Cobyla()\n" % self.variable["myOptimizer"]
1135     txt += "#%s = CobylaSpecificParameters()\n" % self.variable["specificParameters"]
1136     txt += "#%s.setSpecificParameters( %s )\n" % (self.variable["myOptimizer"], self.variable["specificParameters"])
1137     txt += "\n"
1138         
1139     return txt
1140
1141   def AbdoRackwitz (self):
1142     '''
1143     Methode AbdoRackwitz
1144     '''
1145     txt  = "# Optimisation par AbdoRackwitz\n"
1146     txt += "%s = AbdoRackwitz()\n" % self.variable["myOptimizer"]
1147     txt += "#%s = AbdoRackwitzSpecificParameters()\n" % self.variable["specificParameters"]
1148     txt += "#%s.setSpecificParameters( %s )\n" % (self.variable["myOptimizer"], self.variable["specificParameters"])
1149     txt += "\n"
1150     return txt
1151
1152   def Beta (self, loi):
1153     '''
1154     Definition de la loi Beta
1155     '''
1156     settings = {
1157       "RT" : "Beta.RT",
1158       "MuSigma" : "Beta.MUSIGMA",
1159       }
1160     if loi[ 'Settings' ] == 'RT' :
1161       arg1 = loi[ 'R' ]
1162       arg2 = loi[ 'T' ]
1163     else :
1164       arg1 = loi[ 'Mu'    ]
1165       arg2 = loi[ 'Sigma' ]
1166       
1167     arg3 = loi[ 'A' ]
1168     arg4 = loi[ 'B' ]
1169     txt = "Beta( %g, %g, %g, %g, %s )" % (arg1, arg2, arg3, arg4, settings[ loi[ 'Settings' ] ])
1170     return txt
1171   
1172   def Exponential (self, loi):
1173     '''
1174     Definition de la loi Exponential
1175     '''
1176     arg1 = loi[ 'Lambda' ]
1177     arg2 = loi[ 'Gamma'  ]
1178     txt = "Exponential( %g, %g )" % (arg1, arg2)
1179     return txt
1180   
1181   def Gamma (self, loi):
1182     '''
1183     Definition de la loi Gamma
1184     '''
1185     settings = {
1186       "KLambda" : "Gamma.KLAMBDA",
1187       "MuSigma" : "Gamma.MUSIGMA",
1188     }
1189     if loi[ 'Settings' ] == 'KLambda' :
1190       arg1 = loi[ 'K'      ]
1191       arg2 = loi[ 'Lambda' ]
1192     else :
1193       arg1 = loi[ 'Mu'    ]
1194       arg2 = loi[ 'Sigma' ]
1195       
1196     arg3 = loi[ 'Gamma' ]
1197     txt = "Gamma( %g, %g, %g, %s )" % (arg1, arg2, arg3, settings[ loi[ 'Settings' ] ])
1198     return txt
1199
1200   def Geometric (self, loi):
1201     '''
1202     Definition de la loi Geometric
1203     '''
1204     txt = "Geometric( %g )" % loi[ 'P' ]
1205     return txt
1206
1207   def Gumbel (self, loi):
1208     '''
1209     Definition de la loi Gumbel
1210     '''
1211     settings = {
1212       "AlphaBeta" : "Gumbel.ALPHABETA",
1213       "MuSigma" : "Gumbel.MUSIGMA",
1214     }
1215     if loi[ 'Settings' ] == 'AlphaBeta' :
1216       arg1 = loi[ 'Alpha' ]
1217       arg2 = loi[ 'Beta'  ]
1218     else :
1219       arg1 = loi[ 'Mu'    ]
1220       arg2 = loi[ 'Sigma' ]
1221       
1222     txt = "Gumbel( %g, %g, %s )" % (arg1, arg2, settings[ loi[ 'Settings' ] ])
1223     return txt
1224
1225   def Histogram (self, loi):
1226     '''
1227     Definition de la loi Histogram
1228     '''
1229     arg1 = loi[ 'First' ]
1230     arg2 = loi[ 'Values'  ]
1231     txt = "Histogram( %g, %s )" % (arg1, arg2)
1232     return txt
1233
1234   def Laplace (self, loi):
1235     '''
1236     Definition de la loi Laplace
1237     '''
1238     arg1 = loi[ 'Lambda' ]
1239     arg2 = loi[ 'Mu'     ]
1240     txt = "Laplace( %g, %g )" % (arg1, arg2)
1241     return txt
1242
1243   def Logistic (self, loi):
1244     '''
1245     Definition de la loi Logistic
1246     '''
1247     arg1 = loi[ 'Alpha' ]
1248     arg2 = loi[ 'Beta'  ]
1249     txt = "Logistic( %g, %g )" % (arg1, arg2)
1250     return txt
1251
1252   def LogNormal (self, loi):
1253     '''
1254     Definition de la loi LogNormal
1255     '''
1256     settings = {
1257       "MuSigmaLog" : "LogNormal.MUSIGMA_LOG",
1258       "MuSigma" : "LogNormal.MUSIGMA",
1259       "MuSigmaOverMu" : "LogNormal.MU_SIGMAOVERMU",
1260     }
1261     if loi[ 'Settings' ] == 'MuSigmaLog' :
1262       arg1 = loi[ 'MuLog' ]
1263       arg2 = loi[ 'SigmaLog' ]
1264     elif loi[ 'Settings' ] == 'MuSigmaOverMu' :
1265       arg1 = loi[ 'Mu' ]
1266       arg2 = loi[ 'SigmaOverMu' ]
1267     else :
1268       arg1 = loi[ 'Mu'    ]
1269       arg2 = loi[ 'Sigma' ]
1270       
1271     arg3 = loi[ 'Gamma' ]
1272     txt = "LogNormal( %g, %g, %g, %s )" % (arg1, arg2, arg3, settings[ loi[ 'Settings' ] ])
1273     return txt
1274
1275   def MultiNomial (self, loi):
1276     '''
1277     Definition de la loi MultiNomial
1278     '''
1279     arg1 = loi[ 'Values' ]
1280     arg2 = loi[ 'N' ]
1281     txt = "MultiNomial( NumericalPoint( %s ) , %d)" % (arg1, arg2)
1282     return txt
1283
1284   def NonCentralStudent (self, loi):
1285     '''
1286     Definition de la loi NonCentralStudent
1287     '''
1288     arg1 = loi[ 'Nu'    ]
1289     arg2 = loi[ 'Delta' ]
1290     arg3 = loi[ 'Gamma' ]
1291     txt = "NonCentralStudent( %g, %g )" % (arg1, arg2, arg3)
1292     return txt
1293
1294   def Normal (self, loi):
1295     '''
1296     Definition de la loi Normal
1297     '''
1298     arg1 = loi[ 'Mu'    ]
1299     arg2 = loi[ 'Sigma' ]
1300     txt = "Normal( %g, %g )" % (arg1, arg2)
1301     return txt
1302
1303   def TruncatedNormal (self, loi):
1304     '''
1305     Definition de la loi TruncatedNormal
1306     '''
1307     arg1 = loi[ 'MuN' ]
1308     arg2 = loi[ 'SigmaN' ]
1309     arg3 = loi[ 'A' ]
1310     arg4 = loi[ 'B' ]
1311     txt = "TruncatedNormal( %g, %g, %g, %g )" % (arg1, arg2, arg3, arg4)
1312     return txt
1313
1314   def Poisson (self, loi):
1315     '''
1316     Definition de la loi Poisson
1317     '''
1318     txt = "Poisson( %g )" % loi[ 'Lambda' ]
1319     return txt
1320
1321   def Rayleigh (self, loi):
1322     '''
1323     Definition de la loi Rayleigh
1324     '''
1325     arg1 = loi[ 'Sigma' ]
1326     arg2 = loi[ 'Gamma' ]
1327     txt = "Rayleigh( %g, %g )" % (arg1, arg2)
1328     return txt
1329
1330   def Student (self, loi):
1331     '''
1332     Definition de la loi Student
1333     '''
1334     arg1 = loi[ 'Mu' ]
1335     arg2 = loi[ 'Nu' ]
1336     arg3 = loi[ 'Sigma' ]
1337     txt = "Student( %g, %g, %g )" % (arg1, arg2, arg3)
1338     return txt
1339
1340   def Triangular (self, loi):
1341     '''
1342     Definition de la loi Triangular
1343     '''
1344     arg1 = loi[ 'A' ]
1345     arg2 = loi[ 'M' ]
1346     arg3 = loi[ 'B' ]
1347     txt = "Triangular( %g, %g, %g )" % (arg1, arg2, arg3)
1348     return txt
1349
1350   def Uniform (self, loi):
1351     '''
1352     Definition de la loi Uniform
1353     '''
1354     arg1 = loi[ 'A' ]
1355     arg2 = loi[ 'B' ]
1356     txt = "Uniform( %g, %g )" % (arg1, arg2)
1357     return txt
1358
1359   def UserDefined (self, loi):
1360     '''
1361     Definition de la loi UserDefined
1362     '''
1363     txt = "** UserDefined not defined yet **"
1364     return txt
1365
1366   def Weibull (self, loi):
1367     '''
1368     Definition de la loi Weibull
1369     '''
1370     settings = {
1371       "AlphaBeta" : "Weibull.ALPHABETA",
1372       "MuSigma" : "Weibull.MUSIGMA",
1373     }
1374     if loi[ 'Settings' ] == 'AlphaBeta' :
1375       arg1 = loi[ 'Alpha' ]
1376       arg2 = loi[ 'Beta'  ]
1377     else :
1378       arg1 = loi[ 'Mu'    ]
1379       arg2 = loi[ 'Sigma' ]
1380       
1381     arg3 = loi[ 'Gamma' ]
1382     txt = "Weibull( %g, %g, %g, %s )" % (arg1, arg2, arg3, settings[ loi[ 'Settings' ] ])
1383     return txt
1384
1385
1386
1387   def GraphiquePDF (self, loi, chemin, fichier):
1388     '''
1389     Produit une image PNG representant la PDF de la loi
1390     '''
1391     txt  = headerSTD % self.OpenTURNS_path
1392     txt += "dist = %s\n" % apply( STDGenerateur.__dict__[ loi[ 'Kind' ] ], (self, loi) )
1393     txt += "graph = dist.drawPDF()\n"
1394     txt += "graph.draw( '%s/%s' , 640, 480, GraphImplementation.PNG)\n" % (chemin, fichier)
1395     txt += footerSTD
1396     return txt
1397