-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
import logging
import traceback
import sys
-import string
-import StringIO
+import io
+import os
import module_version
logging.basicConfig(level=logging.WARNING)
+if sys.version_info.major > 2:
+ def unicode(text, encoding='utf-8'): return text
+
#----------- Templates Part ---------------#
-begin_catalog_file = """#-*-coding:iso-8859-1-*-
+begin_catalog_file = """# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
# --------------------------------------------------------
-# Generated by AdaoCatalogGenerator on ${date}
+# Generated by AdaoCatalogGenerator on {date}
# --------------------------------------------------------
import os, re
def NoCheckInNS(filename):
return 1
-NoCheckInNS.info = ""
+NoCheckInNS.info = u""
def DirectOperatorInNS(filename):
if os.path.exists(filename):
fc = open(filename, 'r').readlines()
AdjointOperatorInNS.info = u"The Python file has to contain explicitly an \\"AdjointOperator\\" function definition with only one pair of vectors as argument."
"""%(module_version.name,module_version.version)
-# Important : validators=[...] pour que les conditions soient traitées simultanément, en "ET", et pas en "OU" (choisi dans le cas du tuple à la place de la liste)
+# Important : validators=[...] pour que les conditions soient traitees simultanement, en "ET", et pas en "OU" (choisi dans le cas du tuple a la place de la liste)
# validators=[OnlyStr(), FileExtVal('py'), FunctionVal(fv)]
data_method = """
-def F_${data_name}(statut, fv=NoCheckInNS) : return FACT(
+def F_{data_name}(statut, fv=NoCheckInNS) : return FACT(
statut = statut,
- FROM = SIMP(statut = "o", typ = "TXM", into=(${data_into}), defaut=${data_default}),
+ FROM = SIMP(statut = "o", typ = "TXM", into=({data_into}), defaut={data_default}),
SCRIPT_DATA = BLOC ( condition = " FROM in ( 'Script', ) ",
- SCRIPT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py'), FunctionVal(fv)], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant si nécessaire la définition d'une variable interne de même nom que le concept parent", ang="Waiting for a script file name, with or without the full path to find it, containing if necessary the definition of an internal variable of the same name as the parent concept"),
+ SCRIPT_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py'), FunctionVal(fv)], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant si nécessaire la définition d'une variable interne de même nom que le concept parent", ang="Waiting for a script file name, with or without the full path to find it, containing if necessary the definition of an internal variable of the same name as the parent concept"),
),
STRING_DATA = BLOC ( condition = " FROM in ( 'String', ) ",
- STRING = SIMP(statut = "o", typ = "TXM",${ms_default} fr="En attente d'une chaine de caractères entre guillements. Pour construire un vecteur ou une matrice, ce doit être une suite de nombres, utilisant un espace ou une virgule pour séparer deux éléments et un point-virgule pour séparer deux lignes", ang="Waiting for a string in quotes. To build a vector or a matrix, it has to be a float serie, using a space or comma to separate two elements in a line, a semi-colon to separate rows"),
+ STRING = SIMP(statut = "o", typ = "TXM",{ms_default} fr="En attente d'une chaine de caractères entre guillements. Pour construire un vecteur ou une matrice, ce doit être une suite de nombres, utilisant un espace ou une virgule pour séparer deux éléments et un point-virgule pour séparer deux lignes", ang="Waiting for a string in quotes. To build a vector or a matrix, it has to be a float serie, using a space or comma to separate two elements in a line, a semi-colon to separate rows"),
),
SCRIPTWITHFUNCTIONS_DATA = BLOC ( condition = " FROM in ( 'ScriptWithFunctions', ) ",
- SCRIPTWITHFUNCTIONS_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py'), FunctionVal(DirectOperatorInNS), FunctionVal(TangentOperatorInNS), FunctionVal(AdjointOperatorInNS)], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant en variables internes trois fonctions de calcul nommées DirectOperator, TangentOperator et AdjointOperator", ang="Waiting for a script file name, with or without the full path to find it, containing as internal variables three computation functions named DirectOperator, TangentOperator and AdjointOperator"),
+ SCRIPTWITHFUNCTIONS_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py'), FunctionVal(DirectOperatorInNS), FunctionVal(TangentOperatorInNS), FunctionVal(AdjointOperatorInNS)], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant en variables internes trois fonctions de calcul nommées DirectOperator, TangentOperator et AdjointOperator", ang="Waiting for a script file name, with or without the full path to find it, containing as internal variables three computation functions named DirectOperator, TangentOperator and AdjointOperator"),
),
SCRIPTWITHONEFUNCTION_DATA = BLOC ( condition = " FROM in ( 'ScriptWithOneFunction', ) ",
- SCRIPTWITHONEFUNCTION_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py'), FunctionVal(DirectOperatorInNS)], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant en variable interne une seule fonction de calcul nommée DirectOperator", ang="Waiting for a script file name, with or without the full path to find it, containing as internal variable only one function named DirectOperator"),
- DifferentialIncrement = SIMP(statut="o", typ = "R", val_min=0, val_max=1, defaut=0.01, fr="Incrément de la perturbation dX pour calculer la dérivée, construite en multipliant X par l'incrément en évitant les valeurs nulles", ang="Increment of dX perturbation to calculate the derivative, build multiplying X by the increment avoiding null values"),
- CenteredFiniteDifference = SIMP(statut="o", typ = "I", into=(0, 1), defaut=0, fr="Formulation centrée (1) ou décentrée (0) pour la méthode des différences finies", ang="Centered (1) or uncentered (0) formulation for the finite differences method"),
- EnableMultiProcessing = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0, fr="Calculs élémentaires effectués en séquentiel (0) ou en parallèle (1) dans la méthode des différences finies", ang="Elementary calculations done sequentially (0) or in parallel (1) in the finite differences method"),
- NumberOfProcesses = SIMP(statut="f", typ = "I", val_min=0, defaut=0, fr="Nombre de processus parallèles, 0 pour un contrôle automatique", ang="Number of parallel processes, 0 for automatic control"),
+ SCRIPTWITHONEFUNCTION_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py'), FunctionVal(DirectOperatorInNS)], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant en variable interne une seule fonction de calcul nommée DirectOperator", ang="Waiting for a script file name, with or without the full path to find it, containing as internal variable only one function named DirectOperator"),
+ DifferentialIncrement = SIMP(statut="o", typ = "R", val_min=0, val_max=1, defaut=0.01, fr="Incrément de la perturbation dX pour calculer la dérivée, construite en multipliant X par l'incrément en évitant les valeurs nulles", ang="Increment of dX perturbation to calculate the derivative, build multiplying X by the increment avoiding null values"),
+ CenteredFiniteDifference = SIMP(statut="o", typ = "I", into=(0, 1), defaut=0, fr="Formulation centrée (1) ou décentrée (0) pour la méthode des différences finies", ang="Centered (1) or uncentered (0) formulation for the finite differences method"),
+ EnableMultiProcessing = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0, fr="Calculs élémentaires effectués en séquentiel (0) ou en parallèle (1) dans la méthode des différences finies", ang="Elementary calculations done sequentially (0) or in parallel (1) in the finite differences method"),
+ NumberOfProcesses = SIMP(statut="f", typ = "I", val_min=0, defaut=0, fr="Nombre de processus parallèles, 0 pour un contrôle automatique", ang="Number of parallel processes, 0 for automatic control"),
),
SCRIPTWITHSWITCH_DATA = BLOC ( condition = " FROM in ( 'ScriptWithSwitch', ) ",
SCRIPTWITHSWITCH_FILE = SIMP(statut = "o", typ = "FichierNoAbs", validators=[OnlyStr(), FileExtVal('py')], fr="En attente d'un nom de fichier script, avec ou sans le chemin complet pour le trouver, contenant un switch pour les calculs direct, tangent et adjoint", ang="Waiting for a script file name, with or without the full path to find it, containing a switch for direct, tangent and adjoint computations"),
"""
assim_data_method = """
-def ${assim_name}InNS(filename):
+def {assim_name}InNS(filename):
if os.path.exists(filename):
fc = open(filename, 'r').readlines()
- cr = re.compile("^${assim_name}[\s]*=")
+ cr = re.compile("^{assim_name}[\s]*=")
for ln in fc:
if cr.match(ln): return 1
return 0
-${assim_name}InNS.info = u"The Python file has to contain explicitly a \\"${assim_name}\\" variable."
-def F_${assim_name}(statut, fv=NoCheckInNS) : return FACT(
+{assim_name}InNS.info = u"The Python file has to contain explicitly a \\"{assim_name}\\" variable."
+def F_{assim_name}(statut, fv=NoCheckInNS) : return FACT(
statut=statut,
-${storage}
- INPUT_TYPE = SIMP(statut="o", typ = "TXM", into=(${choices}), defaut=${default_choice}),${decl_choices}
+{storage}
+ INPUT_TYPE = SIMP(statut="o", typ = "TXM", into=({choices}), defaut={default_choice}),{decl_choices}
)
"""
assim_data_choice = """
- ${choice_name} = BLOC ( condition = " INPUT_TYPE in ( '${choice_name}', ) ",
- data = F_${choice_name}("o", fv),
+ {choice_name} = BLOC ( condition = " INPUT_TYPE in ( '{choice_name}', ) ",
+ data = F_{choice_name}("o", fv),
),"""
observers_choice = """
- ${var_name} = BLOC (condition=" '${var_name}' in set(SELECTION) ",
- ${var_name}_data = FACT(statut = "o",
+ {var_name} = BLOC (condition=" '{var_name}' in set(SELECTION) ",
+ {var_name}_data = FACT(statut = "o",
Scheduler = SIMP(statut = "f", typ = "TXM"),
- Info = SIMP(statut = "o", typ = "TXM", defaut = "${var_name}"),
+ Info = SIMP(statut = "o", typ = "TXM", defaut = "{var_name}"),
NodeType = SIMP(statut = "o", typ = "TXM", min=1, max=1, defaut = "Template", into=("String", "Script", "Template")),
PythonScript = BLOC (condition = " NodeType == 'String' ",
Value = SIMP(statut = "o", typ = "TXM")
def F_Observers(statut) : return FACT(
statut=statut,
- SELECTION = SIMP(statut="o", defaut=[], typ="TXM", min=0, max="**", homo="SansOrdreNiDoublon", validators=NoRepeat(), into=(${choices})),${decl_choices}
+ SELECTION = SIMP(statut="o", defaut=[], typ="TXM", min=0, max="**", homo="SansOrdreNiDoublon", validators=NoRepeat(), into=({choices})),{decl_choices}
)
"""%(observers_list,observers_cont)
Dict = BLOC ( condition = " Parameters == 'Dict' ",
statut="f",
data = F_Dict("o", fv),
- ),${all_algo_defaults}
+ ),{all_algo_defaults}
)
"""
one_algo_choices = """
- Parameters${algo_name} = BLOC (condition = " (Parameters == 'Defaults') and (Algorithm == '${algo_name}') ",
+ Parameters{algo_name} = BLOC (condition = " (Parameters == 'Defaults') and (Algorithm == '{algo_name}') ",
statut="f",
-${algo_parameters} ),"""
+{algo_parameters} ),"""
assim_study = """
def F_variables(statut) : return FACT(
StudyName = SIMP(statut="o", typ = "TXM", defaut="ADAO Calculation Case"),
StudyRepertory = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
Debug = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
- AlgorithmParameters = F_AlgorithmParameters("o",(${algos_names}), AlgorithmParametersInNS),
+ AlgorithmParameters = F_AlgorithmParameters("o",({algos_names}), AlgorithmParametersInNS),
Background = F_Background("o", BackgroundInNS),
BackgroundError = F_BackgroundError("o", BackgroundErrorInNS),
Observation = F_Observation("o", ObservationInNS),
StudyName = SIMP(statut="o", typ = "TXM", defaut="ADAO Checking Case"),
StudyRepertory = SIMP(statut="f", typ = "Repertoire", validators=FunctionVal(ChDir), min=1, max=1),
Debug = SIMP(statut="f", typ = "I", into=(0, 1), defaut=0),
- AlgorithmParameters = F_AlgorithmParameters("o", (${check_names}), AlgorithmParametersInNS),
+ AlgorithmParameters = F_AlgorithmParameters("o", ({check_names}), AlgorithmParametersInNS),
CheckingPoint = F_CheckingPoint("o", CheckingPointInNS),
BackgroundError = F_BackgroundError("f", BackgroundErrorInNS),
Observation = F_Observation("f", ObservationInNS),
)
"""
-begin_catalog_file = string.Template(begin_catalog_file)
-data_method = string.Template(data_method)
-assim_data_method = string.Template(assim_data_method)
-assim_data_choice = string.Template(assim_data_choice)
-assim_study = string.Template(assim_study)
-observers_method = string.Template(observers_method)
-observers_choice = string.Template(observers_choice)
-algo_choices = string.Template(algo_choices)
-one_algo_choices = string.Template(one_algo_choices)
-
#----------- End of Templates Part ---------------#
#----------- Begin generation script -----------#
-print "-- Starting AdaoCalatogGenerator.py --"
+print("-- Starting AdaoCalatogGenerator.py --")
try:
import daEficas
traceback.print_exc()
sys.exit(1)
-def check_args(args):
- logging.debug("Arguments are :" + str(args))
- if len(args) != 2:
- logging.fatal("Bad number of arguments: you have to provide two arguments (%d given)" % (len(args)))
- sys.exit(1)
-
# Parse arguments
-from optparse import OptionParser
-usage = "usage: %prog [options] catalog_path catalog_name"
-version="%prog 0.1"
-my_parser = OptionParser(usage=usage, version=version)
-(options, args) = my_parser.parse_args()
-check_args(args)
-
-catalog_path = args[0]
-catalog_name = args[1]
+from argparse import ArgumentParser
+usage = "usage: %(prog)s [options] catalog_path catalog_name"
+version="%(prog)s 0.1"
+my_parser = ArgumentParser(usage=usage)
+my_parser.add_argument('-v', '--version', action='version', version=version)
+my_parser.add_argument('catalog_path')
+my_parser.add_argument('catalog_name')
+args = my_parser.parse_args()
# Generates into a string
-mem_file = StringIO.StringIO()
+mem_file = io.StringIO()
# Start file
from time import strftime
-mem_file.write(begin_catalog_file.substitute(date=strftime("%Y-%m-%d %H:%M:%S")))
+mem_file.write(unicode(begin_catalog_file, 'utf-8').format(**{'date':strftime("%Y-%m-%d %H:%M:%S")}))
# Step initial: on obtient la liste des algos
algos_names = ""
# Step 1: A partir des infos, on cree les fonctions qui vont permettre
# d'entrer les donnees utilisateur
-for data_input_name in infos.DataTypeDict.keys():
+for data_input_name in infos.DataTypeDict:
logging.debug('A data input Type is found: ' + data_input_name)
data_name = data_input_name
data_into = ""
# On choisit le default
data_default = "\"" + infos.DataTypeDefaultDict[data_input_name] + "\""
- if infos.DataSValueDefaultDict.has_key(data_input_name):
+ if data_input_name in infos.DataSValueDefaultDict:
ms_default = " defaut=\"" + infos.DataSValueDefaultDict[data_input_name] + "\","
- mem_file.write(data_method.substitute(data_name = data_name,
- data_into = data_into,
- data_default = data_default,
- ms_default = ms_default,
- algos_names = algos_names+check_names))
+ mem_file.write(unicode(data_method, 'utf-8').format(**{
+ 'data_name' : data_name,
+ 'data_into' : data_into,
+ 'data_default' : data_default,
+ 'ms_default' : ms_default,
+ 'algos_names' : algos_names+check_names,
+ }))
# Step 2: On cree les fonctions qui permettent de rentrer les donnees des algorithmes
-for assim_data_input_name in infos.AssimDataDict.keys():
+for assim_data_input_name in infos.AssimDataDict:
logging.debug("An input function data input is found: " + assim_data_input_name)
- # assim_name = assim_data_input_name
+ #Â assim_name = assim_data_input_name
storage = ""
choices = ""
default_choice = ""
storage = " Stored = SIMP(statut=\"f\", typ = \"I\", into=(0, 1), defaut=0, fr=\"Choix de stockage interne ou non du concept parent\", ang=\"Choice of the storage or not of the parent concept\"),"
for choice in infos.AssimDataDict[assim_data_input_name]:
choices += "\"" + choice + "\", "
- decl_choices += assim_data_choice.substitute(choice_name = choice)
+ decl_choices += assim_data_choice.format(**{'choice_name' : choice})
if choice in infos.StoredAssimData:
storage = " Stored = SIMP(statut=\"f\", typ = \"I\", into=(0, 1), defaut=0, fr=\"Choix de stockage interne ou non du concept parent\", ang=\"Choice of the storage or not of the parent concept\"),"
default_choice = "\"" + infos.AssimDataDefaultDict[assim_data_input_name] + "\""
- mem_file.write(assim_data_method.substitute(assim_name = assim_data_input_name,
- storage = storage,
- choices = choices,
- decl_choices = decl_choices,
- default_choice = default_choice))
+ mem_file.write(unicode(assim_data_method, 'utf-8').format(**{
+ 'assim_name' : assim_data_input_name,
+ 'storage' : storage,
+ 'choices' : choices,
+ 'decl_choices' : decl_choices,
+ 'default_choice' : default_choice,
+ }))
# Step 3: On ajoute les fonctions representant les options possibles
-for opt_name in infos.OptDict.keys():
+for opt_name in infos.OptDict:
logging.debug("An optional node is found: " + opt_name)
data_name = opt_name
data_into = ""
# On choisit le default
data_default = "\"" + infos.OptDefaultDict[opt_name] + "\""
- if infos.DataSValueDefaultDict.has_key(opt_name):
+ if opt_name in infos.DataSValueDefaultDict:
ms_default = " defaut=\"" + infos.DataSValueDefaultDict[opt_name] + "\","
- mem_file.write(data_method.substitute(data_name = data_name,
- data_into = data_into,
- data_default = data_default,
- ms_default = ms_default,
- algos_names = algos_names+check_names))
+ mem_file.write(unicode(data_method, 'utf-8').format(**{
+ 'data_name' : data_name,
+ 'data_into' : data_into,
+ 'data_default' : data_default,
+ 'ms_default' : ms_default,
+ 'algos_names' : algos_names+check_names,
+ }))
# Step 4: On ajoute la methode optionnelle init
# TODO uniformiser avec le step 3
-mem_file.write(init_method)
+mem_file.write(unicode(init_method, 'utf-8'))
# Step 5: Add observers
decl_choices = ""
for obs_var in infos.ObserversList:
- decl_choices += observers_choice.substitute(var_name=obs_var)
-mem_file.write(observers_method.substitute(choices = infos.ObserversList,
- decl_choices = decl_choices))
+ decl_choices += observers_choice.format(**{'var_name':obs_var})
+mem_file.write(unicode(observers_method, 'utf-8').format(**{
+ 'choices' : infos.ObserversList,
+ 'decl_choices' : decl_choices,
+ }))
# Step 5: Add algorithmic choices
all_algo_defaults = ""
for algo in all_names:
assim_study_object = daCore.AssimilationStudy.AssimilationStudy()
- assim_study_object.setAlgorithm(choice=algo)
- par_dict = assim_study_object.getAlgorithmParameters(False)
- par_keys = par_dict.keys()
- par_keys.sort()
+ assim_study_object.setAlgorithmParameters(Algorithm=algo)
+ par_dict = assim_study_object.get("AlgorithmRequiredParameters",False)
+ par_keys = sorted(par_dict.keys())
algo_parameters = ""
for pn in par_keys:
if pn in ("StoreInternalVariables", "PlotAndSave", "ResultFile", "ResultTitle", "ResultLabel"): continue # Cles a supprimer
- pt = par_dict[pn]["typecast"]
+ pt = par_dict[pn]["typecast"] # Pointeur de type
pd = par_dict[pn]["default"]
pm = par_dict[pn]["message"]
- if par_dict[pn].has_key("minval") and par_dict[pn]["minval"] is not None:
+ if "minval" in par_dict[pn] and par_dict[pn]["minval"] is not None:
vi = ", val_min=%s"%par_dict[pn]["minval"]
else:
vi = ""
- if par_dict[pn].has_key("minval") and par_dict[pn]["maxval"] is not None:
+ if "minval" in par_dict[pn] and par_dict[pn]["maxval"] is not None:
vs = ", val_max=%s"%par_dict[pn]["maxval"]
else:
vs = ""
algo_parameters += """ %s = SIMP(statut="f", typ="R"%s%s, min=1, max=1, defaut=%s, fr="%s"),\n"""%(pn,vi,vs,float(pd),pm)
elif pt is bool:
algo_parameters += """ %s = SIMP(statut="f", typ="I", min=1, max=1, defaut=%s, fr="%s"),\n"""%(pn,int(pd),pm)
- elif pt is str and par_dict[pn].has_key("listval"):
- algo_parameters += """ %s = SIMP(statut="f", typ="TXM", min=1, max=1, defaut="%s", into=%s, fr="%s"),\n"""%(pn,str(pd),par_dict[pn]["listval"],pm)
- elif pt is tuple and par_dict[pn].has_key("listval"):
+ elif pt is str and "listval" in par_dict[pn]:
+ algo_parameters += """ %s = SIMP(statut="f", typ="TXM", min=1, max=1, defaut="%s", into=%s, fr="%s"),\n"""%(pn,pd,par_dict[pn]["listval"],pm)
+ elif pt is tuple and "listval" in par_dict[pn]:
algo_parameters += """ %s = SIMP(statut="f", typ="TXM", max="**", into=%s, fr="%s"),\n"""%(pn,par_dict[pn]["listval"],pm)
else:
algo_parameters += """ %s = SIMP(statut="f", typ="TXM", fr="%s"),\n"""%(pn,pm)
del assim_study_object
if algo_parameters != "":
- all_algo_defaults += one_algo_choices.substitute(
- algo_name=algo,
- algo_parameters=algo_parameters,
- )
-
-mem_file.write(algo_choices.substitute(all_algo_defaults=all_algo_defaults))
+ all_algo_defaults += one_algo_choices.format(**{
+ 'algo_name':algo,
+ 'algo_parameters':algo_parameters,
+ })
+mem_file.write(unicode(algo_choices, 'utf-8').format(**{'all_algo_defaults':unicode(all_algo_defaults, 'utf-8')}))
# Final step: Add algorithm and assim_study
-mem_file.write(assim_study.substitute(algos_names=algos_names,
- check_names=check_names,
- decl_algos=decl_algos))
+mem_file.write(unicode(assim_study, 'utf-8').format(**{
+ 'algos_names':algos_names,
+ 'check_names':check_names,
+ 'decl_algos':decl_algos,
+ }))
+
# Write file
-final_file = open(catalog_path + "/" + catalog_name, "wr")
-final_file.write(mem_file.getvalue())
+if sys.version_info.major > 2:
+ with open(os.path.join(args.catalog_path, args.catalog_name), "w", encoding='utf8') as final_file:
+ final_file.write(mem_file.getvalue())
+else:
+ with open(os.path.join(args.catalog_path, args.catalog_name), "wr") as final_file:
+ final_file.write(mem_file.getvalue().encode('utf-8'))
mem_file.close()
-final_file.close()
-
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-# Author: André Ribes, andre.ribes@edf.fr, EDF R&D
+# Author: André Ribes, andre.ribes@edf.fr, EDF R&D
import sys
import os
sys.exit(1)
# Parse arguments
-from optparse import OptionParser
-usage = "usage: %prog [options] config_file yacs_schema_filename"
-version="%prog 0.1"
-my_parser = OptionParser(usage=usage, version=version)
-(options, args) = my_parser.parse_args()
-check_args(args)
+from argparse import ArgumentParser
+usage = "usage: %(prog)s [options] config_file yacs_schema_filename"
+version="%(prog)s 0.1"
+my_parser = ArgumentParser(usage=usage, version=version)
+my_parser.add_argument('config_file')
+my_parser.add_argument('yacs_schema_filename')
+args = my_parser.parse_args()
-config_file = args[0]
-yacs_schema_filename = args[1]
-create_schema(config_file, yacs_schema_filename)
+create_schema(args.config_file, args.yacs_schema_filename)
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
-<?xml version='1.0' encoding='iso-8859-1' ?>
+<?xml version='1.0' encoding='utf-8' ?>
<!--
Copyright (C) 2008-2017 EDF R&D
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-
+
Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-->
<proc>
<![CDATA[
import numpy, logging
-logging.debug("CREATE Entering in CreateAssimilationStudy")
+logging.debug("CREATE YI Entering in CreateAssimilationStudy")
print "Entering in the assimilation study"
print "Name is set to........:", Name
print "Algorithm is set to...:", Algorithm
from daYacsIntegration.daStudy import *
assim_study = daStudy(Name, Algorithm, Debug)
- logging.debug("CREATE Data entered are:")
+ logging.debug("CREATE YI Data entered are:")
# Algorithm parameters
if "AlgorithmParameters" in locals():
- logging.debug("CREATE AlgorithmParameters is %s"%AlgorithmParameters)
- assim_study.setAlgorithmParameters(AlgorithmParameters)
+ logging.debug("CREATE YI AlgorithmParameters is %s"%AlgorithmParameters)
+ assim_study.setYIAlgorithmParameters(AlgorithmParameters)
# Background
if "Background" in locals():
- logging.debug("CREATE Background is set")
- logging.debug("CREATE BackgroundType is %s"%BackgroundType)
- logging.debug("CREATE BackgroundStored is %s"%BackgroundStored)
- assim_study.setBackgroundType(BackgroundType)
- assim_study.setBackgroundStored(BackgroundStored)
- assim_study.setBackground(Background)
+ logging.debug("CREATE YI Background is set")
+ logging.debug("CREATE YI BackgroundType is %s"%BackgroundType)
+ logging.debug("CREATE YI BackgroundStored is %s"%BackgroundStored)
+ assim_study.setYIBackgroundType(BackgroundType)
+ assim_study.setYIBackgroundStored(BackgroundStored)
+ assim_study.setYIBackground(Background)
# CheckingPoint
if "CheckingPoint" in locals():
- logging.debug("CREATE CheckingPoint is set")
- logging.debug("CREATE CheckingPointType is %s"%CheckingPointType)
- logging.debug("CREATE CheckingPointStored is %s"%CheckingPointStored)
- assim_study.setCheckingPointType(CheckingPointType)
- assim_study.setCheckingPointStored(CheckingPointStored)
- assim_study.setCheckingPoint(CheckingPoint)
+ logging.debug("CREATE YI CheckingPoint is set")
+ logging.debug("CREATE YI CheckingPointType is %s"%CheckingPointType)
+ logging.debug("CREATE YI CheckingPointStored is %s"%CheckingPointStored)
+ assim_study.setYICheckingPointType(CheckingPointType)
+ assim_study.setYICheckingPointStored(CheckingPointStored)
+ assim_study.setYICheckingPoint(CheckingPoint)
# ControlInput
if "ControlInput" in locals():
- logging.debug("CREATE ControlInput is set")
- logging.debug("CREATE ControlInputType is %s"%ControlInputType)
- logging.debug("CREATE ControlInputStored is %s"%ControlInputStored)
- assim_study.setControlInputType(ControlInputType)
- assim_study.setControlInputStored(ControlInputStored)
- assim_study.setControlInput(ControlInput)
+ logging.debug("CREATE YI ControlInput is set")
+ logging.debug("CREATE YI ControlInputType is %s"%ControlInputType)
+ logging.debug("CREATE YI ControlInputStored is %s"%ControlInputStored)
+ assim_study.setYIControlInputType(ControlInputType)
+ assim_study.setYIControlInputStored(ControlInputStored)
+ assim_study.setYIControlInput(ControlInput)
# Observation
if "Observation" in locals():
- logging.debug("CREATE Observation is set")
- logging.debug("CREATE ObservationType is %s"%ObservationType)
- logging.debug("CREATE ObservationStored is %s"%ObservationStored)
- assim_study.setObservationType(ObservationType)
- assim_study.setObservationStored(ObservationStored)
- assim_study.setObservation(Observation)
+ logging.debug("CREATE YI Observation is set")
+ logging.debug("CREATE YI ObservationType is %s"%ObservationType)
+ logging.debug("CREATE YI ObservationStored is %s"%ObservationStored)
+ assim_study.setYIObservationType(ObservationType)
+ assim_study.setYIObservationStored(ObservationStored)
+ assim_study.setYIObservation(Observation)
# BackgroundError
if "BackgroundError" in locals():
- logging.debug("CREATE BackgroundError is set")
- logging.debug("CREATE BackgroundErrorType is %s"%BackgroundErrorType)
- logging.debug("CREATE BackgroundErrorStored is %s"%BackgroundErrorStored)
- assim_study.setBackgroundErrorType(BackgroundErrorType)
- assim_study.setBackgroundErrorStored(BackgroundErrorStored)
- assim_study.setBackgroundError(BackgroundError)
+ logging.debug("CREATE YI BackgroundError is set")
+ logging.debug("CREATE YI BackgroundErrorType is %s"%BackgroundErrorType)
+ logging.debug("CREATE YI BackgroundErrorStored is %s"%BackgroundErrorStored)
+ assim_study.setYIBackgroundErrorType(BackgroundErrorType)
+ assim_study.setYIBackgroundErrorStored(BackgroundErrorStored)
+ assim_study.setYIBackgroundError(BackgroundError)
# ObservationError
if "ObservationError" in locals():
- logging.debug("CREATE ObservationError is set")
- logging.debug("CREATE ObservationErrorType is %s"%ObservationErrorType)
- logging.debug("CREATE ObservationErrorStored is %s"%ObservationErrorStored)
- assim_study.setObservationErrorType(ObservationErrorType)
- assim_study.setObservationErrorStored(ObservationErrorStored)
- assim_study.setObservationError(ObservationError)
+ logging.debug("CREATE YI ObservationError is set")
+ logging.debug("CREATE YI ObservationErrorType is %s"%ObservationErrorType)
+ logging.debug("CREATE YI ObservationErrorStored is %s"%ObservationErrorStored)
+ assim_study.setYIObservationErrorType(ObservationErrorType)
+ assim_study.setYIObservationErrorStored(ObservationErrorStored)
+ assim_study.setYIObservationError(ObservationError)
# EvolutionError
if "EvolutionError" in locals():
- logging.debug("CREATE EvolutionError is set")
- logging.debug("CREATE EvolutionErrorType is %s"%EvolutionErrorType)
- logging.debug("CREATE EvolutionErrorStored is %s"%EvolutionErrorStored)
- assim_study.setEvolutionErrorType(EvolutionErrorType)
- assim_study.setEvolutionErrorStored(EvolutionErrorStored)
- assim_study.setEvolutionError(EvolutionError)
+ logging.debug("CREATE YI EvolutionError is set")
+ logging.debug("CREATE YI EvolutionErrorType is %s"%EvolutionErrorType)
+ logging.debug("CREATE YI EvolutionErrorStored is %s"%EvolutionErrorStored)
+ assim_study.setYIEvolutionErrorType(EvolutionErrorType)
+ assim_study.setYIEvolutionErrorStored(EvolutionErrorStored)
+ assim_study.setYIEvolutionError(EvolutionError)
# ObservationOperator
ObservationOperatorOk = 0
if "ObservationOperator" in locals():
- logging.debug("CREATE ObservationOperator is set")
- logging.debug("CREATE ObservationOperatorType is %s"%ObservationOperatorType)
- assim_study.setObservationOperatorType("Matrix", ObservationOperatorType)
- assim_study.setObservationOperator("Matrix", ObservationOperator)
+ logging.debug("CREATE YI ObservationOperator is set")
+ logging.debug("CREATE YI ObservationOperatorType is %s"%ObservationOperatorType)
+ assim_study.setYIObservationOperatorType("Matrix", ObservationOperatorType)
+ assim_study.setYIObservationOperator("Matrix", ObservationOperator)
ObservationOperatorOk = 1
if ObservationOperatorOk == 0:
if "ObservationOperatorDirect" in locals():
- logging.debug("CREATE ObservationOperatorDirect is %s"%ObservationOperatorDirect)
- assim_study.setObservationOperatorType("Direct", "Function")
- assim_study.setObservationOperator("Direct", ObservationOperatorDirect)
+ logging.debug("CREATE YI ObservationOperatorDirect is %s"%ObservationOperatorDirect)
+ assim_study.setYIObservationOperatorType("Direct", "Function")
+ assim_study.setYIObservationOperator("Direct", ObservationOperatorDirect)
if "ObservationOperatorTangent" in locals():
- logging.debug("CREATE ObservationOperatorTangent is %s"%ObservationOperatorTangent)
- assim_study.setObservationOperatorType("Tangent", "Function")
- assim_study.setObservationOperator("Tangent", ObservationOperatorTangent)
+ logging.debug("CREATE YI ObservationOperatorTangent is %s"%ObservationOperatorTangent)
+ assim_study.setYIObservationOperatorType("Tangent", "Function")
+ assim_study.setYIObservationOperator("Tangent", ObservationOperatorTangent)
if "ObservationOperatorAdjoint" in locals():
- logging.debug("CREATE ObservationOperatorAdjoint is %s"%ObservationOperatorAdjoint)
- assim_study.setObservationOperatorType("Adjoint", "Function")
- assim_study.setObservationOperator("Adjoint", ObservationOperatorAdjoint)
+ logging.debug("CREATE YI ObservationOperatorAdjoint is %s"%ObservationOperatorAdjoint)
+ assim_study.setYIObservationOperatorType("Adjoint", "Function")
+ assim_study.setYIObservationOperator("Adjoint", ObservationOperatorAdjoint)
# EvolutionModel
EvolutionModelOk = 0
if "EvolutionModel" in locals():
- logging.debug("CREATE EvolutionModel is set")
- logging.debug("CREATE EvolutionModelType is %s"%EvolutionModelType)
- assim_study.setEvolutionModelType("Matrix", EvolutionModelType)
- assim_study.setEvolutionModel("Matrix", EvolutionModel)
+ logging.debug("CREATE YI EvolutionModel is set")
+ logging.debug("CREATE YI EvolutionModelType is %s"%EvolutionModelType)
+ assim_study.setYIEvolutionModelType("Matrix", EvolutionModelType)
+ assim_study.setYIEvolutionModel("Matrix", EvolutionModel)
EvolutionModelOk = 1
if EvolutionModelOk == 0:
if "EvolutionModelDirect" in locals():
- logging.debug("CREATE EvolutionModelDirect is %s"%EvolutionModelDirect)
- assim_study.setEvolutionModelType("Direct", "Function")
- assim_study.setEvolutionModel("Direct", EvolutionModelDirect)
+ logging.debug("CREATE YI EvolutionModelDirect is %s"%EvolutionModelDirect)
+ assim_study.setYIEvolutionModelType("Direct", "Function")
+ assim_study.setYIEvolutionModel("Direct", EvolutionModelDirect)
if "EvolutionModelTangent" in locals():
- logging.debug("CREATE EvolutionModelTangent is %s"%EvolutionModelTangent)
- assim_study.setEvolutionModelType("Tangent", "Function")
- assim_study.setEvolutionModel("Tangent", EvolutionModelTangent)
+ logging.debug("CREATE YI EvolutionModelTangent is %s"%EvolutionModelTangent)
+ assim_study.setYIEvolutionModelType("Tangent", "Function")
+ assim_study.setYIEvolutionModel("Tangent", EvolutionModelTangent)
if "EvolutionModelAdjoint" in locals():
- logging.debug("CREATE EvolutionModelAdjoint is %s"%EvolutionModelAdjoint)
- assim_study.setEvolutionModelType("Adjoint", "Function")
- assim_study.setEvolutionModel("Adjoint", EvolutionModelAdjoint)
+ logging.debug("CREATE YI EvolutionModelAdjoint is %s"%EvolutionModelAdjoint)
+ assim_study.setYIEvolutionModelType("Adjoint", "Function")
+ assim_study.setYIEvolutionModel("Adjoint", EvolutionModelAdjoint)
# Variables
for name, size in zip(InputVariablesNames, InputVariablesSizes):
- assim_study.setInputVariable(name, size)
+ assim_study.setYIInputVariable(name, size)
for name, size in zip(OutputVariablesNames, OutputVariablesSizes):
- assim_study.setOutputVariable(name, size)
+ assim_study.setYIOutputVariable(name, size)
if has_observers:
- logging.debug("CREATE Observers keys are %s"%observers.keys())
+ logging.debug("CREATE YI Observers keys are %s"%observers.keys())
# Adding observers to the study
for observer_name in observers.keys():
scheduler = ""
scheduler = observers[observer_name]["scheduler"]
if "info" in observers[observer_name].keys():
info = observers[observer_name]["info"]
- assim_study.addObserver(observer_name, scheduler, info, number)
+ assim_study.addYIObserver(observer_name, scheduler, info, number)
except Exception as e:
if isinstance(e, SyntaxError): msg = "at %s: %s"%(e.offset, e.text)
<inline name="CreateNumpyMatrixFromString">
<script><code><![CDATA[
import numpy, logging
-logging.debug("CREATE Entering in CreateNumpyMatrixFromString")
-matrix = numpy.matrix(matrix_in_string)
+logging.debug("CREATE YI Entering in CreateNumpyMatrixFromString")
+if (matrix_in_string.find("array")>-1) or (matrix_in_string.find("matrix")>-1):
+ matrix_in_string=matrix_in_string.replace("array","numpy.array")
+ matrix_in_string=matrix_in_string.replace("matrix","numpy.matrix")
+ exec("matrix="+matrix_in_string)
+ matrix = numpy.matrix(matrix)
+else:
+ matrix = numpy.matrix(matrix_in_string)
type = "Matrix"
-logging.debug("CREATE Matrix is %s"%matrix)
+logging.debug("CREATE YI Matrix is %s"%matrix)
]]></code></script>
<inport name="matrix_in_string" type="string"/>
<outport name="matrix" type="pyobj"/>
<inline name="CreateNumpyScalarSparseMatrixFromString">
<script><code><![CDATA[
import numpy, logging
-logging.debug("CREATE Entering in CreateNumpyScalarSparseMatrixFromString")
-matrix = numpy.matrix(matrix_in_string)
+logging.debug("CREATE YI Entering in CreateNumpyScalarSparseMatrixFromString")
+if (matrix_in_string.find("array")>-1) or (matrix_in_string.find("matrix")>-1):
+ matrix_in_string=matrix_in_string.replace("array","numpy.array")
+ matrix_in_string=matrix_in_string.replace("matrix","numpy.matrix")
+ exec("matrix="+matrix_in_string)
+ matrix = numpy.matrix(matrix)
+else:
+ matrix = numpy.matrix(matrix_in_string)
type = "ScalarSparseMatrix"
-logging.debug("CREATE ScalarSparseMatrix is %s"%matrix)
+logging.debug("CREATE YI ScalarSparseMatrix is %s"%matrix)
]]></code></script>
<inport name="matrix_in_string" type="string"/>
<outport name="matrix" type="pyobj"/>
<inline name="CreateNumpyDiagonalSparseMatrixFromString">
<script><code><![CDATA[
import numpy, logging
-logging.debug("CREATE Entering in CreateNumpyDiagonalSparseMatrixFromString")
-matrix = numpy.matrix(matrix_in_string)
+logging.debug("CREATE YI Entering in CreateNumpyDiagonalSparseMatrixFromString")
+if (matrix_in_string.find("array")>-1) or (matrix_in_string.find("matrix")>-1):
+ matrix_in_string=matrix_in_string.replace("array","numpy.array")
+ matrix_in_string=matrix_in_string.replace("matrix","numpy.matrix")
+ exec("matrix="+matrix_in_string)
+ matrix = numpy.matrix(matrix)
+else:
+ matrix = numpy.matrix(matrix_in_string)
type = "DiagonalSparseMatrix"
-logging.debug("CREATE DiagonalSparseMatrix is %s"%matrix)
+logging.debug("CREATE YI DiagonalSparseMatrix is %s"%matrix)
]]></code></script>
<inport name="matrix_in_string" type="string"/>
<outport name="matrix" type="pyobj"/>
<inline name="CreateNumpyMatrixFromScript">
<script><code><![CDATA[
import logging, sys, os
-logging.debug("CREATE Entering in CreateNumpyMatrixFromScript")
+logging.debug("CREATE YI Entering in CreateNumpyMatrixFromScript")
type = "Matrix"
# Get file path and filename
<inline name="CreateNumpyScalarSparseMatrixFromScript">
<script><code><![CDATA[
import logging, sys, os
-logging.debug("CREATE Entering in CreateNumpyScalarSparseMatrixFromScript")
+logging.debug("CREATE YI Entering in CreateNumpyScalarSparseMatrixFromScript")
type = "ScalarSparseMatrix"
# Get file path and filename
<inline name="CreateNumpyDiagonalSparseMatrixFromScript">
<script><code><![CDATA[
import logging, sys, os
-logging.debug("CREATE Entering in CreateNumpyDiagonalSparseMatrixFromScript")
+logging.debug("CREATE YI Entering in CreateNumpyDiagonalSparseMatrixFromScript")
type = "DiagonalSparseMatrix"
# Get file path and filename
<inline name="CreateNumpyVectorFromString">
<script><code><![CDATA[
import numpy, logging
-logging.debug("CREATE Entering in CreateNumpyVectorFromString")
-vector = numpy.matrix(vector_in_string)
+logging.debug("CREATE YI Entering in CreateNumpyVectorFromString")
+if (vector_in_string.find("array")>-1) or (vector_in_string.find("matrix")>-1):
+ vector_in_string=vector_in_string.replace("array","numpy.array")
+ vector_in_string=vector_in_string.replace("matrix","numpy.matrix")
+ exec("vector="+vector_in_string)
+ vector = numpy.matrix(vector)
+else:
+ vector = numpy.matrix(vector_in_string)
type = "Vector"
logging.debug("Vector is %s"%vector)
]]></code></script>
<inline name="CreateNumpyVectorFromScript">
<script><code><![CDATA[
import logging, sys, os
-logging.debug("CREATE Entering in CreateNumpyVectorFromScript")
+logging.debug("CREATE YI Entering in CreateNumpyVectorFromScript")
type = "Vector"
# Get file path and filename
<inline name="CreateNumpyVectorSerieFromString">
<script><code><![CDATA[
import numpy, logging
-logging.debug("CREATE Entering in CreateNumpyVectorSerieFromString")
+logging.debug("CREATE YI Entering in CreateNumpyVectorSerieFromString")
vector_in_list = eval(str(vector_in_string),{},{})
vector = numpy.matrix(vector_in_list)
type = "VectorSerie"
<inline name="CreateNumpyVectorSerieFromScript">
<script><code><![CDATA[
import logging, sys, os
-logging.debug("CREATE Entering in CreateNumpyVectorSerieFromScript")
+logging.debug("CREATE YI Entering in CreateNumpyVectorSerieFromScript")
type = "VectorSerie"
# Get file path and filename
<inline name="SimpleUserAnalysis">
<script><code><![CDATA[
-#-*-coding:iso-8859-1-*-
+#-*- coding: utf-8 -*-
import logging
logging.debug("TERMINATE Entering in SimpleUserAnalysis")
ADD = Study.getResults()
<inline name="CreateDictFromString">
<script><code><![CDATA[
import logging, sys, os
-logging.debug("CREATE Entering in CreateDictFromString")
+logging.debug("CREATE YI Entering in CreateDictFromString")
dico = eval(dict_in_string)
]]></code></script>
<inport name="dict_in_string" type="string"/>
<inline name="CreateDictFromScript">
<script><code><![CDATA[
import logging, sys, os
-logging.debug("CREATE Entering in CreateDictFromScript")
+logging.debug("CREATE YI Entering in CreateDictFromScript")
# Get file path and filename
try:
<inline name="UserDataInitFromScript">
<script><code><![CDATA[
import logging, sys, os
-logging.debug("CREATE Entering in UserDataInitFromScript")
+logging.debug("CREATE YI Entering in UserDataInitFromScript")
# Get file path and filename
try:
<inline name="ReadForSwitchNode">
<script><code><![CDATA[
import logging
-logging.debug("CREATE Entering in ReadForSwitchNode")
+logging.debug("CREATE YI Entering in ReadForSwitchNode")
logging.debug(" with input data : "+str(data["specificParameters"]))
switch_value = -1
for param in data["specificParameters"]:
#
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-# Author: André Ribes, andre.ribes@edf.fr, EDF R&D
+# Author: André Ribes, andre.ribes@edf.fr, EDF R&D
"""
- Ce module sert pour charger les paramètres de configuration d'EFICAS
+ Ce module sert pour charger les paramètres de configuration d'EFICAS
"""
# Modules Python
# print "passage dans la surcharge de configuration pour Adao"
self.labels_eficas = ['lang','rep_cata','catalogues','closeAutreCommande','closeFrameRechercheCommande','closeEntete','taille']
configuration.CONFIG_BASE.__init__(self,appli,repIni)
- self.rep_user = os.environ["HOME"]
- self.appli = appli
- self.code = appli.code
- # self.lang = "fr"
- self.rep_ini = repIni
- self.rep_mat=" " # Compatbilite Aster
- self.savedir = self.rep_user
+ self.rep_user = os.environ["HOME"]
+ self.appli = appli
+ self.code = appli.code
+ # self.lang = "fr"
+ self.rep_ini = repIni
+ self.rep_mat = " " # Compatbilite Aster
+ self.savedir = self.rep_user
self.generator_module = "generator_adao"
- self.convert_module = "convert_adao"
+ self.convert_module = "convert_adao"
# Format des catalogues...
# (code, version, catalogue, formatIn, formatOut)
def gener(self,obj,format='brut',config=None,appli=None):
self.logger.debug("method gener called")
self.text_comm = PythonGenerator.gener(self, obj, format, config)
- for key, value in self.dictMCVal.iteritems():
+ for key, value in self.dictMCVal.items():
self.logger.debug("dictMCVAl %s %s" % (key,value))
try :
self.logger.debug("EFICAS case is not valid, python command file for YACS schema generation cannot be created")
self.logger.debug(self.text_da)
self.dictMCVal = {}
- # traceback.print_exc()
+ #Â traceback.print_exc()
return self.text_comm
def writeDefault(self, fn):
return s
def generate_da(self):
-
+
if "__CHECKING_STUDY__StudyName" in self.dictMCVal.keys():
self.type_of_study = "CHECKING_STUDY"
else:
self.type_of_study = "ASSIMILATION_STUDY"
-
- self.text_da += "#-*-coding:iso-8859-1-*- \n"
- self.text_da += "study_config = {} \n"
+
+ self.text_da += "#-*- coding: utf-8 -*-\n"
+ self.text_da += "study_config = {}\n"
# Extraction de Study_type
self.text_da += "study_config['StudyType'] = '" + self.type_of_study + "'\n"
def add_data(self, data_name):
- # Extraction des données
+ # Extraction des donnees
search_text = "__"+self.type_of_study+"__" + data_name + "__"
data_type = self.dictMCVal[search_text + "INPUT_TYPE"]
search_type = search_text + data_type + "__data__"
self.text_da += "Init_config['From'] = 'Script'\n"
self.text_da += "Init_config['Data'] = '" + init_file_data + "'\n"
self.text_da += "Init_config['Target'] = ["
- if type(init_target_list) is type("str"):
+ if isinstance(init_target_list, "str"):
self.text_da += "'" + init_target_list + "',"
else:
for target in init_target_list:
def add_AlgorithmParameters(self):
- if not self.dictMCVal.has_key("__"+self.type_of_study+"__AlgorithmParameters__Parameters"): return
+ if "__"+self.type_of_study+"__AlgorithmParameters__Parameters" not in self.dictMCVal: return
data_name = "AlgorithmParameters"
data_type = "Dict"
# Traductions et codages
#
# Codage des strings qui accepte les accents (en remplacement de 'ascii')
-# encoding='iso-8859-1'
-# ===== Specifique : pour la 8_3_0 et suivantes 8_x ! Enlever pour les 9_x !
-import sys
-reload(sys)
-sys.setdefaultencoding('latin1')
-# ===== Fin specifique =====================================================
+# encoding='utf-8'
+#
+# ===== Specifique : pour la 8_3_0 et suivantes 8_x ! Enlever pour les 9_x ! JPA
+if sys.version.split()[0] < '3':
+ # ===== Specifique : redefinition de l'encoding avant le Python 3 ! JPA
+ reload(sys)
+ sys.setdefaultencoding('latin1')
+ # ===== Specifique : pour les suivantes 8_x ! Enlever pour les 9_x ! JPA
+ # 19/05/2017 : Redefinition du hook de "sys" present dans <GUI/src/SUITApp/SUITApp_init_python.cxx>
+ def _custom_except_hook(exc_type, exc_value, exc_traceback):
+ import sys
+ sys.__excepthook__(exc_type, exc_value, exc_traceback)
+ pass
+ sys.excepthook = _custom_except_hook
+ del _custom_except_hook, sys
+# ===== Fin specifique ===================================================== JPA
#
# Indique la langue du catalogue utilisee pour les chaines d'aide : fr ou ang
-# lang='fr'
+# lang = 'fr'
# Traduction des labels de boutons ou autres
translatorFichier = os.environ["ADAO_ROOT_DIR"] + "/share/salome/resources/adao/adao" # Ce nom sera complete par EFICAS avec _<LANG>.qm
#
closeFrameRechercheCommande = True
closeEntete = True
closeArbre = True
-taille=800
+taille = 800
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-import optparse
+import argparse
import sys
import re
version_out = "V8_3_0"
-usage="""Usage: python %prog [options]
+usage="""Usage: python %(prog)s [options]
Typical use is:
- python %prog --infile=xxxx.comm --outfile=yyyy.comm"""
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
atraiter = (
"ASSIMILATION_STUDY",
#
log.ferme(hdlr)
if outfile is not None:
- f=open(outfile,'w')
- f.write( fsrc )
- f.close()
+ with open(outfile,'w',encoding='utf8') as f:
+ f.write( fsrc )
else:
return fsrc
return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
def main():
- parser = optparse.OptionParser(usage=usage)
+ parser = argparse.ArgumentParser(usage=usage)
- parser.add_option('-i','--infile', dest="infile",
+ parser.add_argument('-i','--infile', dest="infile",
help="Le fichier COMM en entree, a traduire")
- parser.add_option('-o','--outfile', dest="outfile", default='out.comm',
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
help="Le fichier COMM en sortie, traduit")
- options, args = parser.parse_args()
- if len(options.infile) == 0:
- print
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
parser.print_help()
- print
+ print("")
sys.exit(1)
- traduc(options.infile,options.outfile)
+ traduc(args.infile,args.outfile)
if __name__ == '__main__':
main()
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-import optparse
+import argparse
import sys
import re
version_out = "V8_3_0"
-usage="""Usage: python %prog [options]
+usage="""Usage: python %(prog)s [options]
Typical use is:
- python %prog --infile=xxxx.comm --outfile=yyyy.comm"""
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
atraiter = (
"ASSIMILATION_STUDY",
#
log.ferme(hdlr)
if outfile is not None:
- f=open(outfile,'w')
- f.write( fsrc )
- f.close()
+ with open(outfile,'w',encoding='utf8') as f:
+ f.write( fsrc )
else:
return fsrc
return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
def main():
- parser = optparse.OptionParser(usage=usage)
+ parser = argparse.ArgumentParser(usage=usage)
- parser.add_option('-i','--infile', dest="infile",
+ parser.add_argument('-i','--infile', dest="infile",
help="Le fichier COMM en entree, a traduire")
- parser.add_option('-o','--outfile', dest="outfile", default='out.comm',
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
help="Le fichier COMM en sortie, traduit")
- options, args = parser.parse_args()
- if len(options.infile) == 0:
- print
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
parser.print_help()
- print
+ print("")
sys.exit(1)
- traduc(options.infile,options.outfile)
+ traduc(args.infile,args.outfile)
if __name__ == '__main__':
main()
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-import optparse
+import argparse
import sys
import re
version_out = "V8_3_0"
-usage="""Usage: python %prog [options]
+usage="""Usage: python %(prog)s [options]
Typical use is:
- python %prog --infile=xxxx.comm --outfile=yyyy.comm"""
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
atraiter = (
"ASSIMILATION_STUDY",
#
log.ferme(hdlr)
if outfile is not None:
- f=open(outfile,'w')
- f.write( fsrc )
- f.close()
+ with open(outfile,'w',encoding='utf8') as f:
+ f.write( fsrc )
else:
return fsrc
return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
def main():
- parser = optparse.OptionParser(usage=usage)
+ parser = argparse.ArgumentParser(usage=usage)
- parser.add_option('-i','--infile', dest="infile",
+ parser.add_argument('-i','--infile', dest="infile",
help="Le fichier COMM en entree, a traduire")
- parser.add_option('-o','--outfile', dest="outfile", default='out.comm',
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
help="Le fichier COMM en sortie, traduit")
- options, args = parser.parse_args()
- if len(options.infile) == 0:
- print
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
parser.print_help()
- print
+ print("")
sys.exit(1)
- traduc(options.infile,options.outfile)
+ traduc(args.infile,args.outfile)
if __name__ == '__main__':
main()
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-import optparse
+import argparse
import sys
import re
version_out = "V8_3_0"
-usage="""Usage: python %prog [options]
+usage="""Usage: python %(prog)s [options]
Typical use is:
- python %prog --infile=xxxx.comm --outfile=yyyy.comm"""
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
atraiter = (
)
#
log.ferme(hdlr)
if outfile is not None:
- f=open(outfile,'w')
- f.write( fsrc )
- f.close()
+ with open(outfile,'w',encoding='utf8') as f:
+ f.write( fsrc )
else:
return fsrc
return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
def main():
- parser = optparse.OptionParser(usage=usage)
+ parser = argparse.ArgumentParser(usage=usage)
- parser.add_option('-i','--infile', dest="infile",
+ parser.add_argument('-i','--infile', dest="infile",
help="Le fichier COMM en entree, a traduire")
- parser.add_option('-o','--outfile', dest="outfile", default='out.comm',
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
help="Le fichier COMM en sortie, traduit")
- options, args = parser.parse_args()
- if len(options.infile) == 0:
- print
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
parser.print_help()
- print
+ print("")
sys.exit(1)
- traduc(options.infile,options.outfile)
+ traduc(args.infile,args.outfile)
if __name__ == '__main__':
main()
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-import optparse
+import argparse
import sys
import re
version_out = "V8_3_0"
-usage="""Usage: python %prog [options]
+usage="""Usage: python %(prog)s [options]
Typical use is:
- python %prog --infile=xxxx.comm --outfile=yyyy.comm"""
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
atraiter = (
)
#
log.ferme(hdlr)
if outfile is not None:
- f=open(outfile,'w')
- f.write( fsrc )
- f.close()
+ with open(outfile,'w',encoding='utf8') as f:
+ f.write( fsrc )
else:
return fsrc
return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
def main():
- parser = optparse.OptionParser(usage=usage)
+ parser = argparse.ArgumentParser(usage=usage)
- parser.add_option('-i','--infile', dest="infile",
+ parser.add_argument('-i','--infile', dest="infile",
help="Le fichier COMM en entree, a traduire")
- parser.add_option('-o','--outfile', dest="outfile", default='out.comm',
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
help="Le fichier COMM en sortie, traduit")
- options, args = parser.parse_args()
- if len(options.infile) == 0:
- print
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
parser.print_help()
- print
+ print("")
sys.exit(1)
- traduc(options.infile,options.outfile)
+ traduc(args.infile,args.outfile)
if __name__ == '__main__':
main()
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-import optparse
+import argparse
import sys
import re
version_out = "V8_3_0"
-usage="""Usage: python %prog [options]
+usage="""Usage: python %(prog)s [options]
Typical use is:
- python %prog --infile=xxxx.comm --outfile=yyyy.comm"""
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
atraiter = (
)
#
log.ferme(hdlr)
if outfile is not None:
- f=open(outfile,'w')
- f.write( fsrc )
- f.close()
+ with open(outfile,'w',encoding='utf8') as f:
+ f.write( fsrc )
else:
return fsrc
return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
def main():
- parser = optparse.OptionParser(usage=usage)
+ parser = argparse.ArgumentParser(usage=usage)
- parser.add_option('-i','--infile', dest="infile",
+ parser.add_argument('-i','--infile', dest="infile",
help="Le fichier COMM en entree, a traduire")
- parser.add_option('-o','--outfile', dest="outfile", default='out.comm',
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
help="Le fichier COMM en sortie, traduit")
- options, args = parser.parse_args()
- if len(options.infile) == 0:
- print
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
parser.print_help()
- print
+ print("")
sys.exit(1)
- traduc(options.infile,options.outfile)
+ traduc(args.infile,args.outfile)
if __name__ == '__main__':
main()
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-import optparse
+import argparse
import sys
import re
version_out = "V8_3_0"
-usage="""Usage: python %prog [options]
+usage="""Usage: python %(prog)s [options]
Typical use is:
- python %prog --infile=xxxx.comm --outfile=yyyy.comm"""
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
atraiter = (
)
#
log.ferme(hdlr)
if outfile is not None:
- f=open(outfile,'w')
- f.write( fsrc )
- f.close()
+ with open(outfile,'w',encoding='utf8') as f:
+ f.write( fsrc )
else:
return fsrc
return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
def main():
- parser = optparse.OptionParser(usage=usage)
+ parser = argparse.ArgumentParser(usage=usage)
- parser.add_option('-i','--infile', dest="infile",
+ parser.add_argument('-i','--infile', dest="infile",
help="Le fichier COMM en entree, a traduire")
- parser.add_option('-o','--outfile', dest="outfile", default='out.comm',
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
help="Le fichier COMM en sortie, traduit")
- options, args = parser.parse_args()
- if len(options.infile) == 0:
- print
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
parser.print_help()
- print
+ print("")
sys.exit(1)
- traduc(options.infile,options.outfile)
+ traduc(args.infile,args.outfile)
if __name__ == '__main__':
main()
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-import optparse
+import argparse
import sys
import re
version_out = "V8_3_0"
-usage="""Usage: python %prog [options]
+usage="""Usage: python %(prog)s [args]
Typical use is:
- python %prog --infile=xxxx.comm --outfile=yyyy.comm"""
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
atraiter = (
)
#
log.ferme(hdlr)
if outfile is not None:
- f=open(outfile,'w')
- f.write( fsrc )
- f.close()
+ with open(outfile,'w',encoding='utf8') as f:
+ f.write( fsrc )
else:
return fsrc
return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
def main():
- parser = optparse.OptionParser(usage=usage)
+ parser = argparse.ArgumentParser(usage=usage)
- parser.add_option('-i','--infile', dest="infile",
+ parser.add_argument('-i','--infile', dest="infile",
help="Le fichier COMM en entree, a traduire")
- parser.add_option('-o','--outfile', dest="outfile", default='out.comm',
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
help="Le fichier COMM en sortie, traduit")
- options, args = parser.parse_args()
- if len(options.infile) == 0:
- print
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
parser.print_help()
- print
+ print("")
sys.exit(1)
- traduc(options.infile,options.outfile)
+ traduc(args.infile,args.outfile)
if __name__ == '__main__':
main()
-#-*-coding:iso-8859-1-*-
+#-*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#
# Author: Jean-Philippe Argaud, jean-philippe.argaud@edf.fr, EDF R&D
-import optparse
+import argparse
import sys
import re
version_out = "V8_3_0"
-usage="""Usage: python %prog [options]
+usage="""Usage: python %(prog)s [args]
Typical use is:
- python %prog --infile=xxxx.comm --outfile=yyyy.comm"""
+ python %(prog)s --infile=xxxx.comm --outfile=yyyy.comm"""
atraiter = (
"ASSIMILATION_STUDY",
#
log.ferme(hdlr)
if outfile is not None:
- f=open(outfile,'w')
- f.write( fsrc )
- f.close()
+ with open(outfile,'w',encoding='utf8') as f:
+ f.write( fsrc )
else:
return fsrc
return traduc(infile=None,outfile=None,texte=self.__texte,flog=None)
def main():
- parser = optparse.OptionParser(usage=usage)
+ parser = argparse.ArgumentParser(usage=usage)
- parser.add_option('-i','--infile', dest="infile",
+ parser.add_argument('-i','--infile', dest="infile",
help="Le fichier COMM en entree, a traduire")
- parser.add_option('-o','--outfile', dest="outfile", default='out.comm',
+ parser.add_argument('-o','--outfile', dest="outfile", default='out.comm',
help="Le fichier COMM en sortie, traduit")
- options, args = parser.parse_args()
- if len(options.infile) == 0:
- print
+ args = parser.parse_args()
+ if len(args.infile) == 0:
+ print("")
parser.print_help()
- print
+ print("")
sys.exit(1)
- traduc(options.infile,options.outfile)
+ traduc(args.infile,args.outfile)
if __name__ == '__main__':
main()
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
__author__ = "Jean-Philippe ARGAUD"
__all__ = ["New"]
-import os
-from daCore.AssimilationStudy import AssimilationStudy as _AssimilationStudy
-from daCore.Templates import ObserverTemplates as _ObserverTemplates
-from daCore.BasicObjects import ImportFromScript as _ImportFromScript
-from daCore.BasicObjects import ObserverF as _ObserverF
+from daCore.Aidsm import Aidsm
# ==============================================================================
-class New(object):
+class New(Aidsm):
"""
- Creation TUI d'un cas ADAO
+ Generic ADAO TUI builder
"""
def __init__(self, name = ""):
- self.__adaoStudy = _AssimilationStudy(name)
- self.__case = _CaseLogger(name)
-
- # -----------------------------------------------------------
-
- def set(
- self,
- Concept = None,
- Algorithm = None,
- DiagonalSparseMatrix = None,
- Info = None,
- Matrix = None,
- OneFunction = None,
- Parameters = None,
- ScalarSparseMatrix = None,
- Script = None,
- Stored = False,
- String = None,
- Template = None,
- ThreeFunctions = None,
- AppliedInXb = None,
- Variable = None,
- Vector = None,
- VectorSerie = None):
- "Interface unique de definition de variables d'entrees par argument"
- self.__case.register("set",dir(),locals(),None,True)
- try:
- if Concept == "Background":
- self.setBackground(Vector,VectorSerie,Script,Stored)
- elif Concept == "BackgroundError":
- self.setBackgroundError(Matrix,ScalarSparseMatrix,
- DiagonalSparseMatrix,Script,Stored)
- elif Concept == "CheckingPoint":
- self.setCheckingPoint(Vector,VectorSerie,Script,Stored)
- elif Concept == "ControlModel":
- self.setControlModel(Matrix,OneFunction,ThreeFunctions,
- Parameters,Script,Stored)
- elif Concept == "ControlInput":
- self.setControlInput(Vector,VectorSerie,Script,Stored)
- elif Concept == "EvolutionError":
- self.setEvolutionError(Matrix,ScalarSparseMatrix,
- DiagonalSparseMatrix,Script,Stored)
- elif Concept == "EvolutionModel":
- self.setEvolutionModel(Matrix,OneFunction,ThreeFunctions,
- Parameters,Script,Stored)
- elif Concept == "Observation":
- self.setObservation(Vector,VectorSerie,Script,Stored)
- elif Concept == "ObservationError":
- self.setObservationError(Matrix,ScalarSparseMatrix,
- DiagonalSparseMatrix,Script,Stored)
- elif Concept == "ObservationOperator":
- self.setObservationOperator(Matrix,OneFunction,ThreeFunctions,
- AppliedInXb, Parameters,Script,Stored)
- elif Concept == "AlgorithmParameters":
- self.setAlgorithmParameters(Algorithm,Parameters,Script)
- elif Concept == "Debug":
- self.setDebug()
- elif Concept == "NoDebug":
- self.setNoDebug()
- elif Concept == "Observer":
- self.setObserver(Variable,Template,String,Script,Info)
- else:
- raise ValueError("the variable named '%s' is not allowed."%str(Concept))
- except Exception as e:
- if isinstance(e, SyntaxError): msg = "at %s: %s"%(e.offset, e.text)
- else: msg = ""
- raise ValueError("during settings, the following error occurs:\n\n%s %s\n\nSee also the potential messages, which can show the origin of the above error, in the launching terminal."%(str(e),msg))
-
- # -----------------------------------------------------------
-
- def setBackground(
- self,
- Vector = None,
- VectorSerie = None,
- Script = None,
- Stored = False):
- "Definition d'une entree de calcul"
- self.__case.register("setBackground", dir(), locals())
- if Script is not None:
- __Vector, __PersistentVector = None, None
- if VectorSerie:
- __PersistentVector = _ImportFromScript(Script).getvalue( "Background" )
- else:
- __Vector = _ImportFromScript(Script).getvalue( "Background" )
- else:
- __Vector, __PersistentVector = Vector, VectorSerie
- #
- self.__adaoStudy.setBackground(
- asVector = __Vector,
- asPersistentVector = __PersistentVector,
- toBeStored = Stored,
- )
-
- def setBackgroundError(
- self,
- Matrix = None,
- ScalarSparseMatrix = None,
- DiagonalSparseMatrix = None,
- Script = None,
- Stored = False):
- "Definition d'une entree de calcul"
- self.__case.register("setBackgroundError", dir(), locals())
- if Script is not None:
- __Covariance, __Scalar, __Vector = None, None, None
- if ScalarSparseMatrix:
- __Scalar = _ImportFromScript(Script).getvalue( "BackgroundError" )
- elif DiagonalSparseMatrix:
- __Vector = _ImportFromScript(Script).getvalue( "BackgroundError" )
- else:
- __Covariance = _ImportFromScript(Script).getvalue( "BackgroundError" )
- else:
- __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
- #
- self.__adaoStudy.setBackgroundError(
- asCovariance = __Covariance,
- asEyeByScalar = __Scalar,
- asEyeByVector = __Vector,
- toBeStored = Stored,
- )
-
- def setCheckingPoint(
- self,
- Vector = None,
- VectorSerie = None,
- Script = None,
- Stored = False):
- "Definition d'une entree de verification"
- self.__case.register("setCheckingPoint", dir(), locals())
- if Script is not None:
- __Vector, __PersistentVector = None, None
- if VectorSerie:
- __PersistentVector = _ImportFromScript(Script).getvalue( "CheckingPoint" )
- else:
- __Vector = _ImportFromScript(Script).getvalue( "CheckingPoint" )
- else:
- __Vector, __PersistentVector = Vector, VectorSerie
- #
- self.__adaoStudy.setBackground(
- asVector = __Vector,
- asPersistentVector = __PersistentVector,
- toBeStored = Stored,
- )
-
- def setControlModel(
- self,
- Matrix = None,
- OneFunction = None,
- ThreeFunctions = None,
- Parameters = None,
- Script = None,
- Stored = False):
- "Definition d'une entree de calcul"
- self.__case.register("setControlModel", dir(), locals())
- __Parameters = {}
- if (Parameters is not None) and isinstance(Parameters, dict):
- if "DifferentialIncrement" in Parameters:
- __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
- if "CenteredFiniteDifference" in Parameters:
- __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
- if Script is not None:
- __Matrix, __Function = None, None
- if Matrix:
- __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
- elif OneFunction:
- __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
- __Function.update({"useApproximatedDerivatives":True})
- __Function.update(__Parameters)
- elif ThreeFunctions:
- __Function = {
- "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
- "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
- "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
- }
- __Function.update(__Parameters)
- else:
- __Matrix = Matrix
- if OneFunction is not None:
- __Function = { "Direct":OneFunction }
- __Function.update({"useApproximatedDerivatives":True})
- __Function.update(__Parameters)
- elif ThreeFunctions is not None:
- if (not isinstance(ThreeFunctions, dict)) or \
- "Direct" not in ThreeFunctions or \
- "Tangent" not in ThreeFunctions or \
- "Adjoint" not in ThreeFunctions:
- raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
- __Function = ThreeFunctions
- __Function.update(__Parameters)
- else:
- __Function = None
- #
- self.__adaoStudy.setControlModel(
- asFunction = __Function,
- asMatrix = __Matrix,
- toBeStored = Stored,
- )
-
- def setControlInput(
- self,
- Vector = None,
- VectorSerie = None,
- Script = None,
- Stored = False):
- "Definition d'une entree de calcul"
- self.__case.register("setControlInput", dir(), locals())
- if Script is not None:
- __Vector, __PersistentVector = None, None
- if VectorSerie:
- __PersistentVector = _ImportFromScript(Script).getvalue( "ControlInput" )
- else:
- __Vector = _ImportFromScript(Script).getvalue( "ControlInput" )
- else:
- __Vector, __PersistentVector = Vector, VectorSerie
- #
- self.__adaoStudy.setControlInput(
- asVector = __Vector,
- asPersistentVector = __PersistentVector,
- toBeStored = Stored,
- )
-
- def setEvolutionError(
- self,
- Matrix = None,
- ScalarSparseMatrix = None,
- DiagonalSparseMatrix = None,
- Script = None,
- Stored = False):
- "Definition d'une entree de calcul"
- self.__case.register("setEvolutionError", dir(), locals())
- if Script is not None:
- __Covariance, __Scalar, __Vector = None, None, None
- if ScalarSparseMatrix:
- __Scalar = _ImportFromScript(Script).getvalue( "EvolutionError" )
- elif DiagonalSparseMatrix:
- __Vector = _ImportFromScript(Script).getvalue( "EvolutionError" )
- else:
- __Covariance = _ImportFromScript(Script).getvalue( "EvolutionError" )
- else:
- __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
- #
- self.__adaoStudy.setEvolutionError(
- asCovariance = __Covariance,
- asEyeByScalar = __Scalar,
- asEyeByVector = __Vector,
- toBeStored = Stored,
- )
-
- def setEvolutionModel(
- self,
- Matrix = None,
- OneFunction = None,
- ThreeFunctions = None,
- Parameters = None,
- Script = None,
- Stored = False):
- "Definition d'une entree de calcul"
- self.__case.register("setEvolutionModel", dir(), locals())
- __Parameters = {}
- if (Parameters is not None) and isinstance(Parameters, dict):
- if "DifferentialIncrement" in Parameters:
- __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
- if "CenteredFiniteDifference" in Parameters:
- __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
- if "EnableMultiProcessing" in Parameters:
- __Parameters["withmpEnabled"] = Parameters["EnableMultiProcessing"]
- if "NumberOfProcesses" in Parameters:
- __Parameters["withmpWorkers"] = Parameters["NumberOfProcesses"]
- if Script is not None:
- __Matrix, __Function = None, None
- if Matrix:
- __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
- elif OneFunction:
- __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
- __Function.update({"useApproximatedDerivatives":True})
- __Function.update(__Parameters)
- elif ThreeFunctions:
- __Function = {
- "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
- "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
- "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
- }
- __Function.update(__Parameters)
- else:
- __Matrix = Matrix
- if OneFunction is not None:
- __Function = { "Direct":OneFunction }
- __Function.update({"useApproximatedDerivatives":True})
- __Function.update(__Parameters)
- elif ThreeFunctions is not None:
- if (not isinstance(ThreeFunctions, dict)) or \
- "Direct" not in ThreeFunctions or \
- "Tangent" not in ThreeFunctions or \
- "Adjoint" not in ThreeFunctions:
- raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
- __Function = ThreeFunctions
- __Function.update(__Parameters)
- else:
- __Function = None
- #
- self.__adaoStudy.setEvolutionModel(
- asFunction = __Function,
- asMatrix = __Matrix,
- toBeStored = Stored,
- )
-
- def setObservation(
- self,
- Vector = None,
- VectorSerie = None,
- Script = None,
- Stored = False):
- "Definition d'une entree de calcul"
- self.__case.register("setObservation", dir(), locals())
- if Script is not None:
- __Vector, __PersistentVector = None, None
- if VectorSerie:
- __PersistentVector = _ImportFromScript(Script).getvalue( "Observation" )
- else:
- __Vector = _ImportFromScript(Script).getvalue( "Observation" )
- else:
- __Vector, __PersistentVector = Vector, VectorSerie
- #
- self.__adaoStudy.setObservation(
- asVector = __Vector,
- asPersistentVector = __PersistentVector,
- toBeStored = Stored,
- )
-
- def setObservationError(
- self,
- Matrix = None,
- ScalarSparseMatrix = None,
- DiagonalSparseMatrix = None,
- Script = None,
- Stored = False):
- "Definition d'une entree de calcul"
- self.__case.register("setObservationError", dir(), locals())
- if Script is not None:
- __Covariance, __Scalar, __Vector = None, None, None
- if ScalarSparseMatrix:
- __Scalar = _ImportFromScript(Script).getvalue( "ObservationError" )
- elif DiagonalSparseMatrix:
- __Vector = _ImportFromScript(Script).getvalue( "ObservationError" )
- else:
- __Covariance = _ImportFromScript(Script).getvalue( "ObservationError" )
- else:
- __Covariance, __Scalar, __Vector = Matrix, ScalarSparseMatrix, DiagonalSparseMatrix
- #
- self.__adaoStudy.setObservationError(
- asCovariance = __Covariance,
- asEyeByScalar = __Scalar,
- asEyeByVector = __Vector,
- toBeStored = Stored,
- )
-
- def setObservationOperator(
- self,
- Matrix = None,
- OneFunction = None,
- ThreeFunctions = None,
- AppliedInXb = None,
- Parameters = None,
- Script = None,
- Stored = False):
- "Definition d'une entree de calcul"
- self.__case.register("setObservationOperator", dir(), locals())
- __Parameters = {}
- if (Parameters is not None) and isinstance(Parameters, dict):
- if "DifferentialIncrement" in Parameters:
- __Parameters["withIncrement"] = Parameters["DifferentialIncrement"]
- if "CenteredFiniteDifference" in Parameters:
- __Parameters["withCenteredDF"] = Parameters["CenteredFiniteDifference"]
- if "EnableMultiProcessing" in Parameters:
- __Parameters["EnableMultiProcessing"] = Parameters["EnableMultiProcessing"]
- __Parameters["withmpEnabled"] = Parameters["EnableMultiProcessing"]
- if "NumberOfProcesses" in Parameters:
- __Parameters["NumberOfProcesses"] = Parameters["NumberOfProcesses"]
- __Parameters["withmpWorkers"] = Parameters["NumberOfProcesses"]
- if Script is not None:
- __Matrix, __Function = None, None
- if Matrix:
- __Matrix = _ImportFromScript(Script).getvalue( "ObservationOperator" )
- elif OneFunction:
- __Function = { "Direct":_ImportFromScript(Script).getvalue( "DirectOperator" ) }
- __Function.update({"useApproximatedDerivatives":True})
- __Function.update(__Parameters)
- elif ThreeFunctions:
- __Function = {
- "Direct" :_ImportFromScript(Script).getvalue( "DirectOperator" ),
- "Tangent":_ImportFromScript(Script).getvalue( "TangentOperator" ),
- "Adjoint":_ImportFromScript(Script).getvalue( "AdjointOperator" ),
- }
- __Function.update(__Parameters)
- else:
- __Matrix = Matrix
- if OneFunction is not None:
- __Function = { "Direct":OneFunction }
- __Function.update({"useApproximatedDerivatives":True})
- __Function.update(__Parameters)
- elif ThreeFunctions is not None:
- if (not isinstance(ThreeFunctions, dict)) or \
- "Direct" not in ThreeFunctions or \
- "Tangent" not in ThreeFunctions or \
- "Adjoint" not in ThreeFunctions:
- raise ValueError("ThreeFunctions has to be a dictionnary and to have the 3 keys Direct, Tangent, Adjoint")
- __Function = ThreeFunctions
- __Function.update(__Parameters)
- else:
- __Function = None
- if AppliedInXb is not None:
- __appliedToX = {"HXb":AppliedInXb}
- else:
- __appliedToX = None
- #
- self.__adaoStudy.setObservationOperator(
- asFunction = __Function,
- asMatrix = __Matrix,
- appliedToX = __appliedToX,
- toBeStored = Stored,
- )
-
- # -----------------------------------------------------------
-
- def setAlgorithmParameters(
- self,
- Algorithm = None,
- Parameters = None,
- Script = None):
- "Definition d'un parametrage du calcul"
- self.__case.register("setAlgorithmParameters", dir(), locals())
- if Script is not None:
- __Algorithm = _ImportFromScript(Script).getvalue( "Algorithm" )
- __Parameters = _ImportFromScript(Script).getvalue( "AlgorithmParameters", "Parameters" )
- else:
- __Algorithm = Algorithm
- __Parameters = Parameters
- self.__adaoStudy.setAlgorithm( choice = __Algorithm )
- self.__adaoStudy.setAlgorithmParameters( asDico = __Parameters )
-
- def setDebug(self):
- "Definition d'un parametrage du calcul"
- self.__case.register("setDebug",dir(),locals())
- return self.__adaoStudy.setDebug()
-
- def setNoDebug(self):
- "Definition d'un parametrage du calcul"
- self.__case.register("setNoDebug",dir(),locals())
- return self.__adaoStudy.unsetDebug()
-
- def setObserver(
- self,
- Variable = None,
- Template = None,
- String = None,
- Script = None,
- Info = None):
- "Definition d'un parametrage du calcul"
- self.__case.register("setObserver", dir(), locals())
- if Variable is None:
- raise ValueError("setting an observer has to be done over a variable name, not over None.")
- else:
- __Variable = str(Variable)
- if Info is None:
- __Info = str(Variable)
- else:
- __Info = str(Info)
- #
- if String is not None:
- __FunctionText = String
- elif (Template is not None) and (Template in _ObserverTemplates):
- __FunctionText = _ObserverTemplates[Template]
- elif Script is not None:
- __FunctionText = _ImportFromScript(Script).getstring()
- else:
- __FunctionText = ""
- __Function = _ObserverF(__FunctionText)
- #
- self.__adaoStudy.setDataObserver(
- VariableName = __Variable,
- HookFunction = __Function.getfunc(),
- HookParameters = __Info,
- )
-
- # -----------------------------------------------------------
-
- def executePythonScheme(self):
- "Lancement du calcul"
- self.__case.register("executePythonScheme", dir(), locals())
- try:
- self.__adaoStudy.analyze()
- except Exception as e:
- if isinstance(e, SyntaxError): msg = "at %s: %s"%(e.offset, e.text)
- else: msg = ""
- raise ValueError("during execution, the following error occurs:\n\n%s %s\n\nSee also the potential messages, which can show the origin of the above error, in the launching terminal."%(str(e),msg))
-
- execute = executePythonScheme
-
- def executeYACSScheme(self, File=None):
- "Lancement du calcul"
- self.__case.register("executeYACSScheme", dir(), locals())
- raise NotImplementedError()
-
- # -----------------------------------------------------------
-
- def get(self, Concept=None):
- "Recuperation d'une sortie du calcul"
- self.__case.register("get",dir(),locals(),Concept)
- return self.__adaoStudy.get(Concept)
-
- def dumpNormalizedCommands(self, filename=None):
- "Recuperation de la liste des commandes du cas TUI"
- return self.__case.dump(filename, "TUI")
-
- def __dir__(self):
- return ['set', 'get', 'execute', '__doc__', '__init__', '__module__']
-
-# ==============================================================================
-class _CaseLogger(object):
- """
- Conservation des commandes de creation d'un cas
- """
- def __init__(self, __name="", __objname="case"):
- self.__name = str(__name)
- self.__objname = str(__objname)
- self.__logSerie = []
- self.__switchoff = False
- def register(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
- "Enregistrement d'une commande individuelle"
- if __command is not None and __keys is not None and __local is not None and not self.__switchoff:
- if "self" in __keys: __keys.remove("self")
- self.__logSerie.append( (str(__command), __keys, __local, __pre, __switchoff) )
- if __switchoff:
- self.__switchoff = True
- if not __switchoff:
- self.__switchoff = False
- def dump(self, __filename=None, __format="TUI"):
- if __format == "TUI":
- self.__dumper = _TUIViewer(self.__name, self.__objname, self.__logSerie)
- __text = self.__dumper.dump(__filename)
- else:
- raise ValueError("Dumping as \"%s\" is not available"%__format)
- return __text
-
-# ==============================================================================
-class _GenericViewer(object):
- """
- Etablissement des commandes de creation d'une vue
- """
- def __init__(self, __name="", __objname="case", __content=None):
- self._name = str(__name)
- self._objname = str(__objname)
- self._lineSerie = []
- self._switchoff = False
- self._numobservers = 1
- def _addLine(self, line=""):
- self._lineSerie.append(line)
- def _append(self):
- "Enregistrement d'une commande individuelle"
- raise NotImplementedError()
- def dump(self, __filename=None):
- "Restitution de la liste des commandes de creation d'un cas"
- raise NotImplementedError()
-
-class _TUIViewer(_GenericViewer):
- """
- Etablissement des commandes de creation d'un cas TUI
- """
- def __init__(self, __name="", __objname="case", __content=None):
- _GenericViewer.__init__(self, __name, __objname, __content)
- self._addLine("#\n# Python script for ADAO TUI\n#")
- self._addLine("from numpy import array, matrix")
- self._addLine("import adaoBuilder")
- self._addLine("%s = adaoBuilder.New('%s')"%(self._objname, self._name))
- if __content is not None:
- for command in __content:
- self._append(*command)
- def _append(self, __command=None, __keys=None, __local=None, __pre=None, __switchoff=False):
- if __command is not None and __keys is not None and __local is not None:
- __text = ""
- if __pre is not None:
- __text += "%s = "%__pre
- __text += "%s.%s( "%(self._objname,str(__command))
- if "self" in __keys: __keys.remove("self")
- for k in __keys:
- __v = __local[k]
- if __v is None: continue
- if k == "Checked" and not __v: continue
- if k == "Stored" and not __v: continue
- __text += "%s=%s, "%(k,repr(__v))
- __text += ")"
- self._addLine(__text)
- def dump(self, __filename=None):
- __text = "\n".join(self._lineSerie)
- if __filename is not None:
- fid = open(__filename,"w")
- fid.write(__text)
- fid.close()
- return __text
+ Aidsm.__init__(self, name)
# ==============================================================================
if __name__ == "__main__":
# -*- coding: utf-8 -*-
+#
# Copyright (C) 2008-2017 EDF R&D
#
# This file is part of SALOME ADAO module
# -*- coding: utf-8 -*-
+#
# Copyright (C) 2008-2017 EDF R&D
#
# This file is part of SALOME ADAO module
-#-*-coding:iso-8859-1-*-
+# -*- coding: utf-8 -*-
+#
# Copyright (C) 2008-2017 EDF R&D
#
# This file is part of SALOME ADAO module
def __init__(self, parent):
# Configuration de l'installation
- # Permet à EFICAS de faire ses import correctement
+ # Permet à EFICAS de faire ses import correctement
my_path = os.path.dirname(os.path.abspath(__file__))
ADAO_INSTALL_DIR = my_path + "/../daEficas"
sys.path.insert(0,ADAO_INSTALL_DIR)
#######
#
-# Gestion des évènements provenant des widgets QT d'Eficas
+# Gestion des évènements provenant des widgets QT d'Eficas
#
#######
#######
#
-# Méthodes gérant les boutons dans SALOME
+# Méthodes gérant les boutons dans SALOME
#
#######
-# Rq: Utilisation de la méthode str() pour passer d'un Qstring à un string
+# Rq: Utilisation de la méthode str() pour passer d'un Qstring à un string
def adaofileNew(self, adao_case):
#######
#
-# Méthodes auxiliares de gestion du GUI Eficas pour synchronisation
+# Méthodes auxiliares de gestion du GUI Eficas pour synchronisation
# avec la partie GUI de SALOME
#
#######
#######
#
-# Méthodes secondaires permettant de gérer les observeurs du
+# Méthodes secondaires permettant de gérer les observeurs du
# GUI d'Eficas
#
#######
- def addObserver(self, observer):
+ def addEWObserver(self, observer):
"""
In fact, only one observer may be defined for the moment.
"""
def _setContext( studyID ):
global __study2context__, __current_context__
QApplication.processEvents()
- if not __study2context__.has_key(studyID):
+ if studyID not in __study2context__:
__study2context__[studyID] = GUIcontext()
pass
__current_context__ = __study2context__[studyID]
# called when module is initialized
# return list of 2d/3d views to be used ny the module
def views():
- print "views"
+ print("views")
return []
def createPreferences():
import eficasSalome
from Ihm import CONNECTOR
-import adaoGuiHelper
-import adaoStudyEditor
+from . import adaoGuiHelper
+from . import adaoStudyEditor
class AdaoCase:
msg += "case with the ADAO/EFICAS editor."
return msg
- if not os.environ.has_key("ADAO_ROOT_DIR"):
+ if "ADAO_ROOT_DIR" not in os.environ:
return "Please add ADAO_ROOT_DIR to your environnement."
adao_path = os.environ["ADAO_ROOT_DIR"]
import SalomePyQt
__sgPyQt = SalomePyQt.SalomePyQt()
-import adaoModuleHelper
+from . import adaoModuleHelper
from daUtils.qtversion import useQT5
if useQT5:
from PyQt5 import QtGui, QtCore
from daEficasWrapper.adaoEficasWrapper import AdaoEficasWrapper
from daUtils.adaoEficasEvent import *
-import adaoGuiHelper
-import adaoStudyEditor
+from . import adaoGuiHelper
+from . import adaoStudyEditor
from daUtils import adaoLogger
__cases__ = {}
adaoLogger.debug("currentSelectionChanged")
salomeStudyItem = adaoGuiHelper.getSelectedItem()
if salomeStudyItem is not None:
- for case_editor, adao_case in self.cases.iteritems():
+ for case_editor, adao_case in list(self.cases.items()):
if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
self.eficas_manager.selectCase(adao_case.eficas_editor)
break
et la selection dans l'etude SALOME
"""
editor = eficasEvent.callbackId
- for case_editor, adao_case in self.cases.iteritems():
+ for case_editor, adao_case in list(self.cases.items()):
if case_editor is editor:
adaoGuiHelper.selectItem(adao_case.salome_study_item.GetID())
break
editor = self.eficas_manager.getCurrentEditor()
# 2: sync with SALOME GUI is a tab is opened
if editor:
- for case_editor, adao_case in self.cases.iteritems():
+ for case_editor, adao_case in list(self.cases.items()):
if case_editor is editor:
adaoGuiHelper.selectItem(adao_case.salome_study_item.GetID())
break
# dans le GUI d'Eficas
self.harmonizeSelectionFromEficas()
salomeStudyItem = adaoGuiHelper.getSelectedItem()
- for case_name, adao_case in self.cases.iteritems():
+ for case_name, adao_case in list(self.cases.items()):
if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
if not adao_case.isOk():
adaoLogger.debug("Cas invalide, donc il est sauvegarde, mais il ne peut pas etre exporte vers YACS ensuite")
# dans le GUI d'Eficas
self.harmonizeSelectionFromEficas()
salomeStudyItem = adaoGuiHelper.getSelectedItem()
- for case_name, adao_case in self.cases.iteritems():
+ for case_name, adao_case in list(self.cases.items()):
if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
if not adao_case.isOk():
adaoLogger.debug("Cas invalide, donc il est sauvegarde, mais il ne peut pas etre exporte vers YACS ensuite")
# dans le GUI d'Eficas
self.harmonizeSelectionFromEficas()
salomeStudyItem = adaoGuiHelper.getSelectedItem()
- for case_name, adao_case in self.cases.iteritems():
+ for case_name, adao_case in list(self.cases.items()):
if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
self.eficas_manager.adaoFileClose(adao_case)
break
adaoLogger.debug("Validation du cas par un rapport sur le JDC")
self.harmonizeSelectionFromEficas()
salomeStudyItem = adaoGuiHelper.getSelectedItem()
- for case_name, adao_case in self.cases.iteritems():
+ for case_name, adao_case in list(self.cases.items()):
if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
msg = adao_case.validationReportforJDC()
adaoGuiHelper.gui_information(SalomePyQt.SalomePyQt().getDesktop(), msg)
adaoLogger.debug("Validation du cas par un rapport sur le JDC")
self.harmonizeSelectionFromEficas()
salomeStudyItem = adaoGuiHelper.getSelectedItem()
- for case_name, adao_case in self.cases.iteritems():
+ for case_name, adao_case in list(self.cases.items()):
if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
msg = adao_case.showTreeAdaoCase()
break
# dans le GUI d'Eficas
self.harmonizeSelectionFromEficas()
salomeStudyItem = adaoGuiHelper.getSelectedItem()
- for case_name, adao_case in self.cases.iteritems():
+ for case_name, adao_case in list(self.cases.items()):
if adao_case.salome_study_item.GetID() == salomeStudyItem.GetID():
if adao_case.isOk():
msg = adao_case.exportCaseToYACS()
"""
Main switch function for ui actions processing
"""
- if ACTIONS_MAP.has_key(actionId):
+ if actionId in ACTIONS_MAP:
try:
functionName = ACTIONS_MAP[actionId]
getattr(self,functionName)()
from salome.kernel import studyedit
-import adaoModuleHelper
+from . import adaoModuleHelper
#
# ==============================================================================
-# -*- coding: iso-8859-1 -*-
+#-*- coding: utf-8 -*-
+#
# Copyright (C) 2008-2017 EDF R&D
#
# This file is part of SALOME ADAO module
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-__author__="André Ribes - EDF R&D"
+__author__="AndrÃ\83© Ribes - EDF R&D"
class DevelException(Exception):
def __init__(self, message):
# Interface of an eficas observer (for implementing the subject/observer pattern)
# ==============================================================================
#
-from enumerate import Enumerate
+from .enumerate import Enumerate
class EficasObserver:
"""
return (value in self._dict_keynumbers.values())
def listkeys(self):
- list = self._dict_keynumbers.keys()
- list.sort()
- return list
+ return sorted(self._dict_keynumbers.keys())
def listvalues(self):
- list = self._dict_keynumbers.values()
- list.sort()
- return list
+ return sorted(self._dict_keynumbers.values())
#
# ==============================================================================
'SEP',
'OTHER'
])
- print TYPES_LIST.listvalues()
+ print(TYPES_LIST.listvalues())
return True
def TEST_createFromList():
'MED',
'SMESH'])
- print codes.KERNEL
- print codes.GEOM
+ print(codes.KERNEL)
+ print(codes.GEOM)
if (codes.KERNEL == 0 and codes.GEOM == 2):
return True
else:
codes = Enumerate(aList.split())
- print codes.KERNEL
- print codes.GEOM
+ print(codes.KERNEL)
+ print(codes.GEOM)
if (codes.KERNEL == 0 and codes.GEOM == 2):
return True
else:
'MED',
'SMESH'])
- print "VISU in enumerate?", codes.contains("VISU")
+ print("VISU in enumerate?", codes.contains("VISU"))
if ( not codes.contains("VISU") ):
return True
else:
'MED',
'SMESH'], offset=20)
- print codes.KERNEL
- print codes.GEOM
+ print(codes.KERNEL)
+ print(codes.GEOM)
if (codes.KERNEL == 20 and codes.GEOM == 22):
return True
else:
'MED',
'SMESH'], offset=20)
- print codes.listvalues()
+ print(codes.listvalues())
if codes.listvalues() != [20,21,22,23,24]:
return False
return True
-#-*-coding:iso-8859-1-*-
+#-*- coding: utf-8 -*-
#
# Copyright (C) 2008-2017 EDF R&D
#
#-*- coding: utf-8 -*-
+#
# Copyright (C) 2008-2017 EDF R&D
#
# This file is part of SALOME ADAO module
#
# Author: André Ribes, andre.ribes@edf.fr, EDF R&D
-from daOptimizerLoop import *
+from .daOptimizerLoop import *
-#-*-coding:iso-8859-1-*-
+#-*-coding:utf-8-*-
#
# Copyright (C) 2008-2017 EDF R&D
#
import SALOMERuntime
import pilot
-import pickle, cPickle
+import cPickle
import numpy
import threading
+# Pour disposer des classes dans l'espace de nommage lors du pickle
from daCore.AssimilationStudy import AssimilationStudy
from daYacsIntegration import daStudy
self.optim_algo.pool.pushInSample(local_counter, sample)
# 3: Wait
- while 1:
+ while True:
#print "waiting"
self.optim_algo.signalMasterAndWait()
#print "signal"
#print "sync false is not yet implemented"
self.optim_algo.setError("sync == false not yet implemented")
- def Tangent(self, (X, dX), sync = 1):
+ def Tangent(self, xxx_todo_changeme, sync = 1):
# print "Call Tangent OptimizerHooks"
+ (X, dX) = xxx_todo_changeme
if sync == 1:
# 1: Get a unique sample number
self.optim_algo.counter_lock.acquire()
self.optim_algo.pool.pushInSample(local_counter, sample)
# 3: Wait
- while 1:
+ while True:
self.optim_algo.signalMasterAndWait()
if self.optim_algo.isTerminationRequested():
self.optim_algo.pool.destroyAll()
#print "sync false is not yet implemented"
self.optim_algo.setError("sync == false not yet implemented")
- def Adjoint(self, (X, Y), sync = 1):
+ def Adjoint(self, xxx_todo_changeme1, sync = 1):
# print "Call Adjoint OptimizerHooks"
+ (X, Y) = xxx_todo_changeme1
if sync == 1:
# 1: Get a unique sample number
self.optim_algo.counter_lock.acquire()
self.optim_algo.pool.pushInSample(local_counter, sample)
# 3: Wait
- while 1:
+ while True:
#print "waiting"
self.optim_algo.signalMasterAndWait()
#print "signal"
except ValueError as e:
raise ValueError("\n\n Handling internal error in study exchange (message: \"%s\").\n The case is probably too big (bigger than the physical plus the virtual memory available).\n Try if possible to store the covariance matrices in sparse format.\n"%(str(e),))
#print "[Debug] da_study is ", self.da_study
- self.da_study.initAlgorithm()
+ self.da_study.initYIAlgorithm()
self.ADD = self.da_study.getResults()
def startToTakeDecision(self):
# print "Algorithme startToTakeDecision"
# Check if ObservationOperator is already set
- if self.da_study.getObservationOperatorType("Direct") == "Function" or self.da_study.getObservationOperatorType("Tangent") == "Function" or self.da_study.getObservationOperatorType("Adjoint") == "Function" :
+ if self.da_study.getYIObservationOperatorType("Direct") == "Function" or self.da_study.getYIObservationOperatorType("Tangent") == "Function" or self.da_study.getYIObservationOperatorType("Adjoint") == "Function" :
# print "Set Hooks for ObservationOperator"
# Use proxy function for YACS
self.hooksOO = OptimizerHooks(self, switch_value=1)
direct = tangent = adjoint = None
- if self.da_study.getObservationOperatorType("Direct") == "Function":
+ if self.da_study.getYIObservationOperatorType("Direct") == "Function":
direct = self.hooksOO.Direct
- if self.da_study.getObservationOperatorType("Tangent") == "Function" :
+ if self.da_study.getYIObservationOperatorType("Tangent") == "Function" :
tangent = self.hooksOO.Tangent
- if self.da_study.getObservationOperatorType("Adjoint") == "Function" :
+ if self.da_study.getYIObservationOperatorType("Adjoint") == "Function" :
adjoint = self.hooksOO.Adjoint
# Set ObservationOperator
- self.ADD.setObservationOperator(asFunction = {"Direct":direct, "Tangent":tangent, "Adjoint":adjoint})
+ self.ADD.setObservationOperator(ThreeFunctions = {"Direct":direct, "Tangent":tangent, "Adjoint":adjoint})
# else:
# print "Not setting Hooks for ObservationOperator"
# Check if EvolutionModel is already set
- if self.da_study.getEvolutionModelType("Direct") == "Function" or self.da_study.getEvolutionModelType("Tangent") == "Function" or self.da_study.getEvolutionModelType("Adjoint") == "Function" :
+ if self.da_study.getYIEvolutionModelType("Direct") == "Function" or self.da_study.getYIEvolutionModelType("Tangent") == "Function" or self.da_study.getYIEvolutionModelType("Adjoint") == "Function" :
self.has_evolution_model = True
# print "Set Hooks for EvolutionModel"
# Use proxy function for YACS
self.hooksEM = OptimizerHooks(self, switch_value=2)
direct = tangent = adjoint = None
- if self.da_study.getEvolutionModelType("Direct") == "Function":
+ if self.da_study.getYIEvolutionModelType("Direct") == "Function":
direct = self.hooksEM.Direct
- if self.da_study.getEvolutionModelType("Tangent") == "Function" :
+ if self.da_study.getYIEvolutionModelType("Tangent") == "Function" :
tangent = self.hooksEM.Tangent
- if self.da_study.getEvolutionModelType("Adjoint") == "Function" :
+ if self.da_study.getYIEvolutionModelType("Adjoint") == "Function" :
adjoint = self.hooksEM.Adjoint
# Set EvolutionModel
- self.ADD.setEvolutionModel(asFunction = {"Direct":direct, "Tangent":tangent, "Adjoint":adjoint})
+ self.ADD.setEvolutionModel(ThreeFunctions = {"Direct":direct, "Tangent":tangent, "Adjoint":adjoint})
# else:
# print "Not setting Hooks for EvolutionModel"
# Set Observers
- for observer_name in self.da_study.observers_dict.keys():
+ for observer_name in list(self.da_study.observers_dict.keys()):
# print "observers %s found" % observer_name
self.has_observer = True
if self.da_study.observers_dict[observer_name]["scheduler"] != "":
- self.ADD.setDataObserver(observer_name, HookFunction=self.obs, Scheduler = self.da_study.observers_dict[observer_name]["scheduler"], HookParameters = observer_name)
+ self.ADD.setObserver(Variable = observer_name, ObjectFunction = self.obs, Scheduler = self.da_study.observers_dict[observer_name]["scheduler"], Info = observer_name)
else:
- self.ADD.setDataObserver(observer_name, HookFunction=self.obs, HookParameters = observer_name)
+ self.ADD.setObserver(Variable = observer_name, ObjectFunction = self.obs, Info = observer_name)
# Start Assimilation Study
- print "Launching the analysis\n"
+ print("Launching the analysis\n")
try:
- self.ADD.analyze()
+ self.ADD.execute()
except Exception as e:
- if type(e) == type(SyntaxError()): msg = "at %s: %s"%(e.offset, e.text)
+ if isinstance(e, type(SyntaxError())): msg = "at %s: %s"%(e.offset, e.text)
else: msg = ""
raise ValueError("during execution, the following error occurs:\n\n%s %s\n\nSee also the potential messages, which can show the origin of the above error, in the YACS GUI or in the launching terminal."%(str(e),msg))
var_str = cPickle.dumps(var)
# Add Again Data Observer
if self.da_study.observers_dict[info]["scheduler"] != "":
- self.ADD.setDataObserver(info, HookFunction=self.obs, Scheduler = self.da_study.observers_dict[info]["scheduler"], HookParameters = info)
+ self.ADD.setObserver(Variable = info, ObjectFunction = self.obs, Scheduler = self.da_study.observers_dict[info]["scheduler"], Info = info)
else:
- self.ADD.setDataObserver(info, HookFunction=self.obs, HookParameters = info)
+ self.ADD.setObserver(Variable = info, ObjectFunction = self.obs, Info = info)
var_struct.setEltAtRank("value", var_str)
specificParameters.pushBack(var_struct)
# Wait
import sys, traceback
try:
- while 1:
+ while True:
self.signalMasterAndWait()
if self.isTerminationRequested():
self.pool.destroyAll()
self.counter_lock.release()
break
except:
- print "Exception in user code:"
- print '-'*60
+ print("Exception in user code:")
+ print('-'*60)
traceback.print_exc(file=sys.stdout)
- print '-'*60
+ print('-'*60)
def getAlgoResult(self):
- # Remove data observers, required to pickle assimilation study object
- for observer_name in self.da_study.observers_dict.keys():
- self.ADD.removeDataObserver(observer_name, self.obs)
- self.ADD.prepare_to_pickle()
- result = pickle.dumps(self.da_study) # Careful : pickle is mandatory over cPickle !
+# # Remove data observers, required to pickle assimilation study object
+# for observer_name in list(self.da_study.observers_dict.keys()):
+# self.ADD.removeDataObserver(observer_name, self.obs)
+ self.da_study.YI_prepare_to_pickle()
+ result = cPickle.dumps(self.da_study)
return result
# Obligatoire ???
-#-*-coding:iso-8859-1-*-
+#-*-coding:utf-8-*-
#
# Copyright (C) 2008-2017 EDF R&D
#
self.EvolutionModelType = {}
self.FunctionEvolutionModel = {}
- #--------------------------------------
-
- def setInputVariable(self, name, size):
+ def setYIInputVariable(self, name, size):
self.InputVariables[name] = size
self.InputVariablesOrder.append(name)
- def setOutputVariable(self, name, size):
+ def setYIOutputVariable(self, name, size):
self.OutputVariables[name] = size
self.OutputVariablesOrder.append(name)
- #--------------------------------------
-
- def setAlgorithmParameters(self, parameters):
+ def setYIAlgorithmParameters(self, parameters):
self.algorithm_dict = parameters
- #--------------------------------------
-
- def initAlgorithm(self):
- self.ADD.setAlgorithm(choice=self.algorithm)
+ def initYIAlgorithm(self):
+ self.ADD.setAlgorithmParameters(Algorithm=self.algorithm)
if self.algorithm_dict != None:
logging.debug("DASTUDY AlgorithmParameters: "+str(self.algorithm_dict))
- self.ADD.setAlgorithmParameters(asDico=self.algorithm_dict)
+ self.ADD.updateAlgorithmParameters(Parameters=self.algorithm_dict)
+
+ def YI_prepare_to_pickle(self):
+ return self.ADD.prepare_to_pickle()
#--------------------------------------
def __dir__(self):
return ['getResults', '__doc__', '__init__', '__module__']
- def getAssimilationStudy(self):
- # Ancien appel a resorber
- return self.ADD
-
def getResults(self):
+ "Unique méthode à ne pas inclure YI"
return self.ADD
#--------------------------------------
# Methods to initialize AssimilationStudy
- def setBackgroundType(self, Type):
+ def setYIBackgroundType(self, Type):
if Type == "Vector":
self.BackgroundType = Type
else:
- raise daError("[daStudy::setBackgroundType] The following type is unkown : %s. Authorized types are : Vector"%(Type,))
+ raise daError("[daStudy::setYIBackgroundType] The following type is unkown : %s. Authorized types are : Vector"%(Type,))
- def setBackgroundStored(self, Stored):
+ def setYIBackgroundStored(self, Stored):
if Stored:
self.BackgroundStored = True
else:
self.BackgroundStored = False
- def setBackground(self, Background):
+ def setYIBackground(self, Background):
try:
self.BackgroundType
self.BackgroundStored
except AttributeError:
- raise daError("[daStudy::setBackground] Type or Storage is not defined !")
+ raise daError("[daStudy::setYIBackground] Type or Storage is not defined !")
self.Background = Background
if self.BackgroundType == "Vector":
- self.ADD.setBackground(asVector = Background, toBeStored = self.BackgroundStored)
+ self.ADD.setBackground(Vector = Background, Stored = self.BackgroundStored)
- def getBackground(self):
+ def getYIBackground(self):
return self.Background
#--------------------------------------
- def setCheckingPointType(self, Type):
+ def setYICheckingPointType(self, Type):
if Type == "Vector":
self.CheckingPointType = Type
else:
- raise daError("[daStudy::setCheckingPointType] The following type is unkown : %s. Authorized types are : Vector"%(Type,))
+ raise daError("[daStudy::setYICheckingPointType] The following type is unkown : %s. Authorized types are : Vector"%(Type,))
- def setCheckingPointStored(self, Stored):
+ def setYICheckingPointStored(self, Stored):
if Stored:
self.CheckingPointStored = True
else:
self.CheckingPointStored = False
- def setCheckingPoint(self, CheckingPoint):
+ def setYICheckingPoint(self, CheckingPoint):
try:
self.CheckingPointType
self.CheckingPointStored
except AttributeError:
- raise daError("[daStudy::setCheckingPoint] Type or Storage is not defined !")
+ raise daError("[daStudy::setYICheckingPoint] Type or Storage is not defined !")
self.CheckingPoint = CheckingPoint
if self.CheckingPointType == "Vector":
- self.ADD.setBackground(asVector = CheckingPoint, toBeStored = self.CheckingPointStored)
+ self.ADD.setBackground(Vector = CheckingPoint, Stored = self.CheckingPointStored)
#--------------------------------------
- def setBackgroundErrorType(self, Type):
+ def setYIBackgroundErrorType(self, Type):
if Type in ("Matrix", "ScalarSparseMatrix", "DiagonalSparseMatrix"):
self.BackgroundErrorType = Type
else:
- raise daError("[daStudy::setBackgroundErrorType] The following type is unkown : %s. Authorized types are : Matrix, ScalarSparseMatrix, DiagonalSparseMatrix"%(Type,))
+ raise daError("[daStudy::setYIBackgroundErrorType] The following type is unkown : %s. Authorized types are : Matrix, ScalarSparseMatrix, DiagonalSparseMatrix"%(Type,))
- def setBackgroundErrorStored(self, Stored):
+ def setYIBackgroundErrorStored(self, Stored):
if Stored:
self.BackgroundErrorStored = True
else:
self.BackgroundErrorStored = False
- def setBackgroundError(self, BackgroundError):
+ def setYIBackgroundError(self, BackgroundError):
try:
self.BackgroundErrorType
self.BackgroundErrorStored
except AttributeError:
- raise daError("[daStudy::setBackgroundError] Type or Storage is not defined !")
+ raise daError("[daStudy::setYIBackgroundError] Type or Storage is not defined !")
if self.BackgroundErrorType == "Matrix":
- self.ADD.setBackgroundError(asCovariance = BackgroundError, toBeStored = self.BackgroundErrorStored)
+ self.ADD.setBackgroundError(Matrix = BackgroundError, Stored = self.BackgroundErrorStored)
if self.BackgroundErrorType == "ScalarSparseMatrix":
- self.ADD.setBackgroundError(asEyeByScalar = BackgroundError, toBeStored = self.BackgroundErrorStored)
+ self.ADD.setBackgroundError(ScalarSparseMatrix = BackgroundError, Stored = self.BackgroundErrorStored)
if self.BackgroundErrorType == "DiagonalSparseMatrix":
- self.ADD.setBackgroundError(asEyeByVector = BackgroundError, toBeStored = self.BackgroundErrorStored)
+ self.ADD.setBackgroundError(DiagonalSparseMatrix = BackgroundError, Stored = self.BackgroundErrorStored)
#--------------------------------------
- def setControlInputType(self, Type):
+ def setYIControlInputType(self, Type):
if Type in ("Vector", "VectorSerie"):
self.ControlInputType = Type
else:
- raise daError("[daStudy::setControlInputType] The following type is unkown : %s. Authorized types are : Vector, VectorSerie"%(Type,))
+ raise daError("[daStudy::setYIControlInputType] The following type is unkown : %s. Authorized types are : Vector, VectorSerie"%(Type,))
- def setControlInputStored(self, Stored):
+ def setYIControlInputStored(self, Stored):
if Stored:
self.ControlInputStored = True
else:
self.ControlInputStored = False
- def setControlInput(self, ControlInput):
+ def setYIControlInput(self, ControlInput):
try:
self.ControlInputType
self.ControlInputStored
except AttributeError:
- raise daError("[daStudy::setControlInput] Type or Storage is not defined !")
+ raise daError("[daStudy::setYIControlInput] Type or Storage is not defined !")
if self.ControlInputType == "Vector":
- self.ADD.setControlInput(asVector = ControlInput, toBeStored = self.ControlInputStored)
+ self.ADD.setControlInput(Vector = ControlInput, Stored = self.ControlInputStored)
if self.ControlInputType == "VectorSerie":
- self.ADD.setControlInput(asPersistentVector = ControlInput, toBeStored = self.ControlInputStored)
+ self.ADD.setControlInput(VectorSerie = ControlInput, Stored = self.ControlInputStored)
#--------------------------------------
- def setObservationType(self, Type):
+ def setYIObservationType(self, Type):
if Type in ("Vector", "VectorSerie"):
self.ObservationType = Type
else:
- raise daError("[daStudy::setObservationType] The following type is unkown : %s. Authorized types are : Vector, VectorSerie"%(Type,))
+ raise daError("[daStudy::setYIObservationType] The following type is unkown : %s. Authorized types are : Vector, VectorSerie"%(Type,))
- def setObservationStored(self, Stored):
+ def setYIObservationStored(self, Stored):
if Stored:
self.ObservationStored = True
else:
self.ObservationStored = False
- def setObservation(self, Observation):
+ def setYIObservation(self, Observation):
try:
self.ObservationType
self.ObservationStored
except AttributeError:
- raise daError("[daStudy::setObservation] Type or Storage is not defined !")
+ raise daError("[daStudy::setYIObservation] Type or Storage is not defined !")
if self.ObservationType == "Vector":
- self.ADD.setObservation(asVector = Observation, toBeStored = self.ObservationStored)
+ self.ADD.setObservation(Vector = Observation, Stored = self.ObservationStored)
if self.ObservationType == "VectorSerie":
- self.ADD.setObservation(asPersistentVector = Observation, toBeStored = self.ObservationStored)
+ self.ADD.setObservation(VectorSerie = Observation, Stored = self.ObservationStored)
#--------------------------------------
- def setObservationErrorType(self, Type):
+ def setYIObservationErrorType(self, Type):
if Type in ("Matrix", "ScalarSparseMatrix", "DiagonalSparseMatrix"):
self.ObservationErrorType = Type
else:
- raise daError("[daStudy::setObservationErrorType] The following type is unkown : %s. Authorized types are : Matrix, ScalarSparseMatrix, DiagonalSparseMatrix"%(Type,))
+ raise daError("[daStudy::setYIObservationErrorType] The following type is unkown : %s. Authorized types are : Matrix, ScalarSparseMatrix, DiagonalSparseMatrix"%(Type,))
- def setObservationErrorStored(self, Stored):
+ def setYIObservationErrorStored(self, Stored):
if Stored:
self.ObservationErrorStored = True
else:
self.ObservationErrorStored = False
- def setObservationError(self, ObservationError):
+ def setYIObservationError(self, ObservationError):
try:
self.ObservationErrorType
self.ObservationErrorStored
except AttributeError:
- raise daError("[daStudy::setObservationError] Type or Storage is not defined !")
+ raise daError("[daStudy::setYIObservationError] Type or Storage is not defined !")
if self.ObservationErrorType == "Matrix":
- self.ADD.setObservationError(asCovariance = ObservationError, toBeStored = self.ObservationErrorStored)
+ self.ADD.setObservationError(Matrix = ObservationError, Stored = self.ObservationErrorStored)
if self.ObservationErrorType == "ScalarSparseMatrix":
- self.ADD.setObservationError(asEyeByScalar = ObservationError, toBeStored = self.ObservationErrorStored)
+ self.ADD.setObservationError(ScalarSparseMatrix = ObservationError, Stored = self.ObservationErrorStored)
if self.ObservationErrorType == "DiagonalSparseMatrix":
- self.ADD.setObservationError(asEyeByVector = ObservationError, toBeStored = self.ObservationErrorStored)
+ self.ADD.setObservationError(DiagonalSparseMatrix = ObservationError, Stored = self.ObservationErrorStored)
#--------------------------------------
- def getObservationOperatorType(self, Name):
+ def getYIObservationOperatorType(self, Name):
rtn = None
try:
rtn = self.ObservationOperatorType[Name]
pass
return rtn
- def setObservationOperatorType(self, Name, Type):
+ def setYIObservationOperatorType(self, Name, Type):
if Type in ("Matrix", "Function"):
self.ObservationOperatorType[Name] = Type
else:
- raise daError("[daStudy::setObservationOperatorType] The following type is unkown : %s. Authorized types are : Matrix, Function"%(Type,))
+ raise daError("[daStudy::setYIObservationOperatorType] The following type is unkown : %s. Authorized types are : Matrix, Function"%(Type,))
- def setObservationOperator(self, Name, ObservationOperator):
+ def setYIObservationOperator(self, Name, ObservationOperator):
try:
self.ObservationOperatorType[Name]
except AttributeError:
- raise daError("[daStudy::setObservationOperator] Type is not defined !")
+ raise daError("[daStudy::setYIObservationOperator] Type is not defined !")
if self.ObservationOperatorType[Name] == "Matrix":
- self.ADD.setObservationOperator(asMatrix = ObservationOperator)
+ self.ADD.setObservationOperator(Matrix = ObservationOperator)
elif self.ObservationOperatorType[Name] == "Function":
self.FunctionObservationOperator[Name] = ObservationOperator
#--------------------------------------
- def setEvolutionErrorType(self, Type):
+ def setYIEvolutionErrorType(self, Type):
if Type in ("Matrix", "ScalarSparseMatrix", "DiagonalSparseMatrix"):
self.EvolutionErrorType = Type
else:
- raise daError("[daStudy::setEvolutionErrorType] The following type is unkown : %s. Authorized types are : Matrix, ScalarSparseMatrix, DiagonalSparseMatrix"%(Type,))
+ raise daError("[daStudy::setYIEvolutionErrorType] The following type is unkown : %s. Authorized types are : Matrix, ScalarSparseMatrix, DiagonalSparseMatrix"%(Type,))
- def setEvolutionErrorStored(self, Stored):
+ def setYIEvolutionErrorStored(self, Stored):
if Stored:
self.EvolutionErrorStored = True
else:
self.EvolutionErrorStored = False
- def setEvolutionError(self, EvolutionError):
+ def setYIEvolutionError(self, EvolutionError):
try:
self.EvolutionErrorType
self.EvolutionErrorStored
except AttributeError:
- raise daError("[daStudy::setEvolutionError] Type or Storage is not defined !")
+ raise daError("[daStudy::setYIEvolutionError] Type or Storage is not defined !")
if self.EvolutionErrorType == "Matrix":
- self.ADD.setEvolutionError(asCovariance = EvolutionError, toBeStored = self.EvolutionErrorStored)
+ self.ADD.setEvolutionError(Matrix = EvolutionError, Stored = self.EvolutionErrorStored)
if self.EvolutionErrorType == "ScalarSparseMatrix":
- self.ADD.setEvolutionError(asEyeByScalar = EvolutionError, toBeStored = self.EvolutionErrorStored)
+ self.ADD.setEvolutionError(ScalarSparseMatrix = EvolutionError, Stored = self.EvolutionErrorStored)
if self.EvolutionErrorType == "DiagonalSparseMatrix":
- self.ADD.setEvolutionError(asEyeByVector = EvolutionError, toBeStored = self.EvolutionErrorStored)
+ self.ADD.setEvolutionError(DiagonalSparseMatrix = EvolutionError, Stored = self.EvolutionErrorStored)
#--------------------------------------
- def getEvolutionModelType(self, Name):
+ def getYIEvolutionModelType(self, Name):
rtn = None
try:
rtn = self.EvolutionModelType[Name]
pass
return rtn
- def setEvolutionModelType(self, Name, Type):
+ def setYIEvolutionModelType(self, Name, Type):
if Type in ("Matrix", "Function"):
self.EvolutionModelType[Name] = Type
else:
- raise daError("[daStudy::setEvolutionModelType] The following type is unkown : %s. Authorized types are : Matrix, Function"%(Type,))
+ raise daError("[daStudy::setYIEvolutionModelType] The following type is unkown : %s. Authorized types are : Matrix, Function"%(Type,))
- def setEvolutionModel(self, Name, EvolutionModel):
+ def setYIEvolutionModel(self, Name, EvolutionModel):
try:
self.EvolutionModelType[Name]
except AttributeError:
- raise daError("[daStudy::setEvolutionModel] Type is not defined !")
+ raise daError("[daStudy::setYIEvolutionModel] Type is not defined !")
if self.EvolutionModelType[Name] == "Matrix":
- self.ADD.setEvolutionModel(asMatrix = EvolutionModel)
+ self.ADD.setEvolutionModel(Matrix = EvolutionModel)
elif self.EvolutionModelType[Name] == "Function":
self.FunctionEvolutionModel[Name] = EvolutionModel
#--------------------------------------
- def addObserver(self, name, scheduler, info, number):
+ def addYIObserver(self, name, scheduler, info, number):
self.observers_dict[name] = {}
self.observers_dict[name]["scheduler"] = scheduler
self.observers_dict[name]["info"] = info
self.observers_dict[name]["number"] = number
- def getObservers(self):
- return self.observers_dict
#-*- coding: utf-8 -*-
+#
# Copyright (C) 2008-2017 EDF R&D
#
# This file is part of SALOME ADAO module
#-*- coding: utf-8 -*-
+#
# Copyright (C) 2008-2017 EDF R&D
#
# This file is part of SALOME ADAO module
raise ValueError("\n\n" + data_name +" found but " + data_name_type +" is not defined in the study configuration !\n")
else:
if data_config[data_name_type] not in AssimType[data_name]:
- raise ValueError("\n\n" + data_name_type + " of " + data_name + " defined in the study configuration does not have a correct type : " + str(data_config[data_name_type])
+ raise ValueError("\n\n" + data_name_type + " of " + data_name + " defined in the study configuration does not have a correct type : " + str(data_config[data_name_type])
+ "\n You can have : " + str(AssimType[data_name]) + "\n")
if data_name_from not in data_config:
raise ValueError("\n\n" + data_name + " found but " + data_name_from + " is not defined in the study configuration !\n")
else:
if data_config[data_name_from] not in FromNumpyList[data_config[data_name_type]]:
- raise ValueError("\n\n" + data_name_from + " of " + data_name + " defined in the study configuration does not have a correct value : " + str(data_config[data_name_from])
+ raise ValueError("\n\n" + data_name_from + " of " + data_name + " defined in the study configuration does not have a correct value : " + str(data_config[data_name_from])
+ "\n You can have : " + str(FromNumpyList[data_config[data_name_type]]) + "\n")
# Check des fichiers
#-*- coding: utf-8 -*-
+#
# Copyright (C) 2008-2017 EDF R&D
#
# This file is part of SALOME ADAO module
#-*- coding: utf-8 -*-
+#
# Copyright (C) 2008-2017 EDF R&D
#
# This file is part of SALOME ADAO module
t_bool = proc.getTypeCode("bool")
t_param_input = proc.getTypeCode("SALOME_TYPES/ParametricInput")
t_param_output = proc.getTypeCode("SALOME_TYPES/ParametricOutput")
- if "Repertory" in study_config.keys():
+ if "Repertory" in list(study_config.keys()):
base_repertory = study_config["Repertory"]
repertory = True
else:
CAS_node = factory_CAS_node.cloneNode("CreateAssimilationStudy")
CAS_node.getInputPort("Name").edInitPy(study_config["Name"])
CAS_node.getInputPort("Algorithm").edInitPy(study_config["Algorithm"])
- if study_config.has_key("Debug") and study_config["Debug"] == "1":
+ if "Debug" in study_config and study_config["Debug"] == "1":
CAS_node.getInputPort("Debug").edInitPy(True)
else:
CAS_node.getInputPort("Debug").edInitPy(False)
# Adding an observer init node if an user defines some
factory_init_observers_node = catalogAd.getNodeFromNodeMap("SetObserversNode")
init_observers_node = factory_init_observers_node.cloneNode("SetObservers")
- if "Observers" in study_config.keys():
+ if "Observers" in list(study_config.keys()):
node_script = init_observers_node.getScript()
node_script += "has_observers = True\n"
node_script += "observers = " + str(study_config["Observers"]) + "\n"
# Step 0.5: Find if there is a user init node
init_config = {}
init_config["Target"] = []
- if "UserDataInit" in study_config.keys():
+ if "UserDataInit" in list(study_config.keys()):
init_config = study_config["UserDataInit"]
factory_init_node = catalogAd.getNodeFromNodeMap("UserDataInitFromScript")
init_node = factory_init_node.cloneNode("UserDataInit")
# Step 1: get input data from user configuration
- st_keys = study_config.keys()
- st_keys.sort()
+ st_keys = sorted(list(study_config.keys()))
for key in st_keys:
- ad_keys = AssimData
- ad_keys.sort()
+ ad_keys = sorted(AssimData)
if key in ad_keys:
data_config = study_config[key]
back_node.edAddInputPort("init_data", t_pyobj)
ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), back_node.getInputPort("init_data"))
back_node_script += "# Import script and get data\n__import__(module_name)\nuser_script_module = sys.modules[module_name]\n\n"
- back_node_script += key + " = user_script_module." + key + "\n"
+ if key == "AlgorithmParameters":
+ back_node_script += "if hasattr(user_script_module,'" + key + "'):\n "
+ back_node_script += key + " = user_script_module." + key + "\n"
+ skey = "Parameters"
+ back_node_script += "elif hasattr(user_script_module,'" + skey + "'):\n "
+ back_node_script += key + " = user_script_module." + skey + "\n"
+ else:
+ back_node_script += key + " = user_script_module." + key + "\n"
back_node.setScript(back_node_script)
# Connect node with CreateAssimilationStudy
CAS_node.edAddInputPort(key, t_pyobj)
script_str= open(script_filename, 'r')
except:
raise ValueError("Exception in opening function script file: " + script_filename)
- node_script = "#-*-coding:iso-8859-1-*-\n"
+ node_script = "#-*- coding: utf-8 -*-\n"
node_script += "import sys, os \n"
node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
script_str= open(script_filename, 'r')
except:
raise ValueError("Exception in opening function script file: " + script_filename)
- node_script = "#-*-coding:iso-8859-1-*-\n"
+ node_script = "#-*- coding: utf-8 -*-\n"
node_script += "import sys, os, numpy, logging\n"
node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
script_str= open(script_filename, 'r')
except:
raise ValueError("Exception in opening function script file: " + script_filename)
- node_script = "#-*-coding:iso-8859-1-*-\n"
+ node_script = "#-*- coding: utf-8 -*-\n"
node_script += "import sys, os, numpy, logging\n"
node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
node_script += """ Function = DirectOperator,\n"""
node_script += """ increment = %s,\n"""%str(ScriptWithOneFunction['DifferentialIncrement'])
node_script += """ centeredDF = %s,\n"""%str(ScriptWithOneFunction['CenteredFiniteDifference'])
- if 'EnableMultiProcessing' in ScriptWithOneFunction.keys():
+ if 'EnableMultiProcessing' in list(ScriptWithOneFunction.keys()):
node_script += """ mpEnabled = %s,\n"""%str(ScriptWithOneFunction['EnableMultiProcessing'])
- if 'NumberOfProcesses' in ScriptWithOneFunction.keys():
+ if 'NumberOfProcesses' in list(ScriptWithOneFunction.keys()):
node_script += """ mpWorkers = %s,\n"""%str(ScriptWithOneFunction['NumberOfProcesses'])
node_script += """ )\n"""
node_script += """#\n"""
opt_script_nodeOO = factory_opt_script_node.cloneNode("FakeFunctionNode")
# Check if we have a python script for OptimizerLoopNode
- if "EvolutionModel" in study_config.keys():
+ if "EvolutionModel" in list(study_config.keys()):
data_config = study_config["EvolutionModel"]
opt_script_nodeEM = None
if data_config["Type"] == "Function" and (data_config["From"] == "ScriptWithSwitch" or data_config["From"] == "FunctionDict"):
script_str= open(script_filename, 'r')
except:
raise ValueError("Exception in opening function script file: " + script_filename)
- node_script = "#-*-coding:iso-8859-1-*-\n"
+ node_script = "#-*- coding: utf-8 -*-\n"
node_script += "import sys, os \n"
node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
script_str= open(script_filename, 'r')
except:
raise ValueError("Exception in opening function script file: " + script_filename)
- node_script = "#-*-coding:iso-8859-1-*-\n"
+ node_script = "#-*- coding: utf-8 -*-\n"
node_script += "import sys, os, numpy, logging\n"
node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
script_str= open(script_filename, 'r')
except:
raise ValueError("Exception in opening function script file: " + script_filename)
- node_script = "#-*-coding:iso-8859-1-*-\n"
+ node_script = "#-*- coding: utf-8 -*-\n"
node_script += "import sys, os, numpy, logging\n"
node_script += "filepath = \"" + os.path.dirname(script_filename) + "\"\n"
node_script += "filename = \"" + os.path.basename(script_filename) + "\"\n"
node_script += """ Function = DirectOperator,\n"""
node_script += """ increment = %s,\n"""%str(ScriptWithOneFunction['DifferentialIncrement'])
node_script += """ centeredDF = %s,\n"""%str(ScriptWithOneFunction['CenteredFiniteDifference'])
- if 'EnableMultiProcessing' in ScriptWithOneFunction.keys():
+ if 'EnableMultiProcessing' in list(ScriptWithOneFunction.keys()):
node_script += """ mpEnabled = %s,\n"""%str(ScriptWithOneFunction['EnableMultiProcessing'])
- if 'NumberOfProcesses' in ScriptWithOneFunction.keys():
+ if 'NumberOfProcesses' in list(ScriptWithOneFunction.keys()):
node_script += """ mpWorkers = %s,\n"""%str(ScriptWithOneFunction['NumberOfProcesses'])
node_script += """ )\n"""
node_script += """#\n"""
opt_script_nodeEM = factory_opt_script_node.cloneNode("FakeFunctionNode")
# Add computation bloc
- if "Observers" in study_config.keys():
+ if "Observers" in list(study_config.keys()):
execution_bloc = runtime.createBloc("Execution Bloc")
optimizer_node.edSetNode(execution_bloc)
ADAO_Case.edAddDFLink(opt_script_nodeOO.getOutputPort("result"), optimizer_node.edGetPortForOutPool())
# Second case: evolution bloc
- if "EvolutionModel" in study_config.keys():
+ if "EvolutionModel" in list(study_config.keys()):
computation_blocEM = runtime.createBloc("computation_blocEM")
computation_blocEM.edAddChild(opt_script_nodeEM)
switch_node.edSetNode(2, computation_blocEM)
ADAO_Case.edAddCFLink(observation_node, end_observation_node)
ADAO_Case.edAddDFLink(end_observation_node.getOutputPort("output"), optimizer_node.edGetPortForOutPool())
- elif "EvolutionModel" in study_config.keys():
+ elif "EvolutionModel" in list(study_config.keys()):
execution_bloc = runtime.createBloc("Execution Bloc")
optimizer_node.edSetNode(execution_bloc)
ADAO_Case.edAddDFLink(init_node.getOutputPort("init_data"), opt_script_nodeOO.getInputPort("init_data"))
# Step 4: create post-processing from user configuration
- if "UserPostAnalysis" in study_config.keys():
+ if "UserPostAnalysis" in list(study_config.keys()):
analysis_config = study_config["UserPostAnalysis"]
if analysis_config["From"] == "String":
factory_analysis_node = catalogAd.getNodeFromNodeMap("SimpleUserAnalysis")
analysis_file = open(analysis_file_name, 'r')
except:
raise ValueError("Exception in opening analysis file: " + str(analysis_config["Data"]))
- node_script = "#-*-coding:iso-8859-1-*-\n"
+ node_script = "#-*- coding: utf-8 -*-\n"
node_script += "import sys, os \n"
node_script += "filepath = \"" + os.path.dirname(analysis_file_name) + "\"\n"
node_script += "filename = \"" + os.path.basename(analysis_file_name) + "\"\n"
#-*- coding: utf-8 -*-
+#
# Copyright (C) 2008-2017 EDF R&D
#
# This file is part of SALOME ADAO module
import os
import traceback
import logging
-from optparse import OptionParser
from daYacsSchemaCreator.methods import *
from daYacsSchemaCreator.help_methods import *
# Import config_file
try:
- execfile(config_file)
- except:
- raise ValueError("\n\n Exception in loading %s"%config_file)
+ exec(compile(open(config_file).read(), config_file, 'exec'))
+ except Exception as e:
+ if isinstance(e, SyntaxError): msg = "at %s: %s"%(e.offset, e.text)
+ else: msg = ""
+ raise ValueError("\n\nexception in loading %s\n\nThe following error occurs:\n\n%s %s\n\nSee also the potential messages, which can show the origin of the above error, in the launching terminal.\n"%(config_file,str(e),msg))
if "study_config" not in locals():
raise ValueError("\n\n Cannot found study_config in %s\n"%str(config_file))