+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-# Installation de tous les fichiers Python du repertoire et des sous-repertoires (sauf CVS)
-install ( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
- DESTINATION ${CMAKE_INSTALL_PREFIX}
- FILES_MATCHING PATTERN *.py
- PATTERN CVS EXCLUDE
- )
-
-
-### Local Variables:
-### mode: cmake
-### End:
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 2007 - 2012 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-# Installation de tous les fichiers Python, texte et images du repertoire et des sous-repertoires (sauf CVS)
-install ( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
- DESTINATION ${CMAKE_INSTALL_PREFIX}
- FILES_MATCHING PATTERN *.py PATTERN *.txt PATTERN *.gif PATTERN *.png PATTERN *.ppm
- PATTERN CMakeLists.txt EXCLUDE
- PATTERN Patrons EXCLUDE
- PATTERN CVS EXCLUDE
- )
-
-### Local Variables:
-### mode: cmake
-### End:
+++ /dev/null
-DEBUT();
-
-# 1 - MISE EN DONNEES :
-# LECTURE DU MAILLAGE MED
-
-MAIL=LIRE_MAILLAGE(UNITE=21,
- FORMAT='MED',);
-#
-# DEFINITION DES ELEMENTS FINIS UTILISES
-
-MODELE=AFFE_MODELE(MAILLAGE=MAIL,
- AFFE=_F(TOUT='OUI',
- PHENOMENE='MECANIQUE',
- MODELISATION='3D',),);
-#
-# DEFINITION DU MATERIAU UTILISE
-
-ACIER=DEFI_MATERIAU(ELAS=_F(E=2.1E11,
- NU=0.3,
- RHO=7800.0,),);
-
-CHMAT=AFFE_MATERIAU(MAILLAGE=MAIL,
- AFFE=_F(TOUT='OUI',
- MATER=ACIER,),);
-
-#
-# DEFINITION DES CONDITIONS AUX LIMITES
-
-BLOQUAGE=AFFE_CHAR_MECA(MODELE=MODELE,
- DDL_IMPO=_F(GROUP_MA='ABB1A1',
- DX=0.0,
- DY=0.0,
- DZ=0.0,),);
-
-# 2 - CALCUL DES CINQ PREMIERS MODES PROPRES
-#
-# CALCUL DES MATRICES ASSEMBLEES K ET M
-
-MACRO_MATR_ASSE(MODELE=MODELE,
- CHAM_MATER=CHMAT,
- CHARGE=BLOQUAGE,
- NUME_DDL=CO('NUMEDDL'),
- MATR_ASSE=(_F(MATRICE=CO('RIGIDITE'),
- OPTION='RIGI_MECA',),
- _F(MATRICE=CO('MASSE'),
- OPTION='MASS_MECA',),),);
-#
-
-MODES=MODE_ITER_SIMULT(MATR_A=RIGIDITE,
- MATR_B=MASSE,
- CALC_FREQ=_F(
- OPTION='PLUS_PETITE',
- NMAX_FREQ=5,),);
-#
-# ECRITURE DES MODES AU FORMAT MED
-
-IMPR_RESU(MODELE=MODELE,
- FORMAT='MED',
- RESU=_F(MAILLAGE=MAIL,
- RESULTAT=MODES,
- NOM_CHAM='DEPL',),);
-
-FIN();
-#
+++ /dev/null
-DEBUT();
-
-MA=DEFI_MATERIAU(ELAS=_F(E=210000000000,
- NU=0.3,),);
-
-
-
-MAIL=LIRE_MAILLAGE(UNITE=21,
- FORMAT='MED',
- INFO_MED=2,);
-
-MODE=AFFE_MODELE(MAILLAGE=MAIL,
- AFFE=_F(TOUT='OUI',
- PHENOMENE='MECANIQUE',
- MODELISATION= '3D',),);
-
-
-
-MATE=AFFE_MATERIAU(MAILLAGE=MAIL,
- AFFE=_F(TOUT='OUI',
- MATER=MA,),);
-
-CHAR=AFFE_CHAR_MECA(MODELE=MODE,
- FACE_IMPO=(
- _F(GROUP_MA='ABB1A1',
- DX=0,
- DY=0,
- DZ=0,),),
- PRES_REP=(
- _F(GROUP_MA='CDD1C1',
- PRES=10000,),),);
-
-RESU=MECA_STATIQUE(MODELE=MODE,
- CHAM_MATER=MATE,
- EXCIT=_F(CHARGE=CHAR,),);
-
-RESU=CALC_ELEM(reuse =RESU,
- MODELE=MODE,
- CHAM_MATER=MATE,
- RESULTAT=RESU,
- OPTION=('SIGM_ELNO_DEPL','EQUI_ELNO_SIGM',),
- EXCIT=_F(
- CHARGE=CHAR,),);
-
-RESU=CALC_NO(reuse =RESU,
- RESULTAT=RESU,
- OPTION=('SIGM_NOEU_DEPL', 'EQUI_NOEU_SIGM', ),);
-
-IMPR_RESU(FORMAT='MED',
- UNITE=80,
- RESU=_F(MAILLAGE=MAIL,
- RESULTAT=RESU,
- NOM_CHAM=('SIGM_NOEU_DEPL','EQUI_NOEU_SIGM','DEPL',),),);
-
-FIN();
\ No newline at end of file
+++ /dev/null
-
-
-DEBUT(CODE=_F(NOM='VIDE',
- NIV_PUB_WEB='INTERNET',),);
-#
-
-MA=LIRE_MAILLAGE();
-
-
-FIN();
-#
+++ /dev/null
-
-# PATRON
-# ANALYSE MODALE
-# 3D
-
-DEBUT();
-# MISE EN DONNEES
-
-MAIL=LIRE_MAILLAGE();
-
-MODELE=AFFE_MODELE(MAILLAGE=MAIL,
- AFFE=_F(GROUP_MA='OBJET',
- PHENOMENE='MECANIQUE',
- MODELISATION='3D',),);
-# MATERIAU
-
-ACIER=DEFI_MATERIAU(ELAS=_F(E=2.1E11,
- NU=0.3,
- RHO=7800.0,),);
-
-CHMAT=AFFE_MATERIAU(MAILLAGE=MAIL,
- AFFE=_F(GROUP_MA='OBJET',
- MATER=ACIER,),);
-
-# CONDITIONS AUX LIMITES ET CHARGEMENT
-# CONDITIONS AUX LIMITES
-
-BLOQUAGE=AFFE_CHAR_MECA(MODELE=MODELE,
- DDL_IMPO=_F(GROUP_MA='ENCAST',
- LIAISON='ENCASTRE',),);
-# CALCUL DES MATRICES ASSEMBLEES K ET M
-
-MACRO_MATR_ASSE(MODELE=MODELE,
- CHAM_MATER=CHMAT,
- CHARGE=BLOQUAGE,
- NUME_DDL=CO('NUMEDDL'),
- MATR_ASSE=(_F(MATRICE=CO('RIGIDITE'),
- OPTION='RIGI_MECA',),
- _F(MATRICE=CO('MASSE'),
- OPTION='MASS_MECA',),),);
-# CALCUL DES CINQ PREMIERS MODES
-
-MODES=MODE_ITER_SIMULT(MATR_A=RIGIDITE,
- MATR_B=MASSE,
- CALC_FREQ=_F(
- OPTION='PLUS_PETITE',
- NMAX_FREQ=5,),);
-# ECRITURE DES MODES AU FORMAT GMSH
-
-IMPR_RESU(MODELE=MODELE,
- FORMAT='GMSH',
- UNITE=19,
- RESU=_F(MAILLAGE=MAIL,
- RESULTAT=MODES,
- NOM_CHAM='DEPL',),);
-
-FIN();
+++ /dev/null
-
-# PATRON
-# ANALYSE MODALE
-# POUTRE
-
-DEBUT();
-# MISE EN DONNEES
-
-MAIL=LIRE_MAILLAGE();
-
-MODELE=AFFE_MODELE(MAILLAGE=MAIL,
- AFFE=_F(GROUP_MA='OBJET',
- PHENOMENE='MECANIQUE',
- MODELISATION='3D',),);
-# MATERIAU
-
-ACIER=DEFI_MATERIAU(ELAS=_F(E=2.1E11,
- NU=0.3,
- RHO=7800.0,),);
-
-CHMAT=AFFE_MATERIAU(MAILLAGE=MAIL,
- AFFE=_F(GROUP_MA='OBJET',
- MATER=ACIER,),);
-
-CARELEM=AFFE_CARA_ELEM(MODELE=MODELE,
- POUTRE=_F(GROUP_MA='OBJET',
- SECTION='CERCLE',
- CARA=('R','EP',),
- VALE=(1.0,0.01,),),);
-# CONDITIONS AUX LIMITES
-
-BLOQUAGE=AFFE_CHAR_MECA(MODELE=MODELE,
- DDL_IMPO=_F(GROUP_MA='ENCAST',
- LIAISON='ENCASTRE',),);
-#MATRICES ASSEMBLEES K, M
-#
-
-MACRO_MATR_ASSE(MODELE=MODELE,
- CHAM_MATER=CHMAT,
- CARA_ELEM=CARELEM,
- CHARGE=BLOQUAGE,
- NUME_DDL=CO('NUMEDDL'),
- MATR_ASSE=(_F(MATRICE=CO('RIGIDITE'),
- OPTION='RIGI_MECA',),
- _F(MATRICE=CO('MASSE'),
- OPTION='MASS_MECA',),),);
-#5 PREMIERS MODES
-
-MODES=MODE_ITER_SIMULT(MATR_A=RIGIDITE,
- MATR_B=MASSE,
- CALC_FREQ=_F(
- OPTION='PLUS_PETITE',
- NMAX_FREQ=5,),);
-# MODES AU FORMAT GMSH
-
-IMPR_RESU(MODELE=MODELE,
- FORMAT='GMSH',
- UNITE=19,
- RESU=_F(MAILLAGE=MAIL,
- RESULTAT=MODES,
- NOM_CHAM='DEPL',),);
-
-FIN();
+++ /dev/null
-
-# PATRON
-# ANALYSE STATIQUE
-# 3D
-
-DEBUT();
-# MISE EN DONNEES
-
-MAIL=LIRE_MAILLAGE();
-
-MAIL=DEFI_GROUP(reuse =MAIL,
- MAILLAGE=MAIL,
- CREA_GROUP_MA=_F(NOM='TOUT',
- TOUT='OUI',),);
-
-MODMECA=AFFE_MODELE(MAILLAGE=MAIL,
- AFFE=_F(GROUP_MA='TOUT',
- PHENOMENE='MECANIQUE',
- MODELISATION='3D',),);
-
-ACIER=DEFI_MATERIAU(ELAS=_F(E=2.E11,
- NU=0.3,),);
-
-CHMAT=AFFE_MATERIAU(MAILLAGE=MAIL,
- AFFE=_F(TOUT='OUI',
- MATER=ACIER,),);
-# CONDITIONS AUX LIMITES ET CHARGEMENT
-#POINT A : ENCASTREMENT
-
-BLOQUAGE=AFFE_CHAR_MECA(MODELE=MODMECA,
- DDL_IMPO=_F(GROUP_MA='ENCAST',
- LIAISON='ENCASTRE',),);
-#POINT B : FORCE IMPOSEE
-
-CHARGT=AFFE_CHAR_MECA(MODELE=MODMECA,
- FORCE_NODALE=_F(GROUP_NO='PB',
- FY=1000.0,),);
-# RESOLUTION DU PROBLEME ELASTIQUE
-
-RESU1=MECA_STATIQUE(MODELE=MODMECA,
- CHAM_MATER=CHMAT,
- EXCIT=(_F(CHARGE=BLOQUAGE,),
- _F(CHARGE=CHARGT,),),);
-# CALCUL DES EFFORTS
-
-RESU1=CALC_ELEM(reuse =RESU1,
- RESULTAT=RESU1,
- OPTION='EFGE_ELNO_DEPL',);
-# RESULTATS FORMAT GMSH
-
-IMPR_RESU(MODELE=MODMECA,
- FORMAT='GMSH',
- RESU=_F(MAILLAGE=MAIL,
- RESULTAT=RESU1,
- NOM_CHAM=('DEPL','EFGE_ELNO_DEPL',),),);
-
-FIN();
+++ /dev/null
-
-# PATRON
-# ANALYSE STATIQUE
-# POUTRE
-
-DEBUT();
-# MISE EN DONNEES
-
-MAIL=LIRE_MAILLAGE();
-
-MAIL=DEFI_GROUP(reuse =MAIL,
- MAILLAGE=MAIL,
- CREA_GROUP_MA=_F(NOM='TOUT',
- TOUT='OUI',),);
-
-MODMECA=AFFE_MODELE(MAILLAGE=MAIL,
- AFFE=_F(GROUP_MA='TOUT',
- PHENOMENE='MECANIQUE',
- MODELISATION='POU_D_T',),);
-
-ACIER=DEFI_MATERIAU(ELAS=_F(E=2.E10,
- NU=0.3,),);
-
-CHMAT=AFFE_MATERIAU(MAILLAGE=MAIL,
- AFFE=_F(TOUT='OUI',
- MATER=ACIER,),);
-R1 = 1.0;
-
-EP1 = 0.001;
-
-
-CARA_POU=AFFE_CARA_ELEM(MODELE=MODMECA,
- POUTRE=_F(GROUP_MA='TOUT',
- SECTION='CERCLE',
- CARA=('R','EP',),
- VALE=(R1,EP1,),),);
-
-# CONDITIONS AUX LIMITES ET CHARGEMENT
-
-#POINT A : ENCASTREMENT
-
-BLOQUAGE=AFFE_CHAR_MECA(MODELE=MODMECA,
- DDL_IMPO=_F(GROUP_NO='PA',
- LIAISON='ENCASTRE',),);
-#POINT B : FORCE IMPOSEE
-
-CHARGT=AFFE_CHAR_MECA(MODELE=MODMECA,
- FORCE_NODALE=_F(GROUP_NO='PB',
- FY=1000.0,),);
-# RESOLUTION DU PROBLEME ELASTIQUE
-
-RESU1=MECA_STATIQUE(MODELE=MODMECA,
- CHAM_MATER=CHMAT,
- CARA_ELEM=CARA_POU,
- EXCIT=(_F(CHARGE=BLOQUAGE,),
- _F(CHARGE=CHARGT,),),);
-# CALCUL DES EFFORTS
-
-RESU1=CALC_ELEM(reuse =RESU1,
- RESULTAT=RESU1,
- OPTION='EFGE_ELNO_DEPL',);
-# RESULTATS FORMAT GMSH
-
-IMPR_RESU(MODELE=MODMECA,
- FORMAT='GMSH',
- RESU=_F(MAILLAGE=MAIL,
- RESULTAT=RESU1,
- NOM_CHAM=('DEPL','EFGE_ELNO_DEPL',),),);
-
-FIN();
+++ /dev/null
-
-
-DEBUT();
-
-MESH=LIRE_MAILLAGE(UNITE=21,
- FORMAT='MED',);
-
-MATER=DEFI_MATERIAU(THER=_F(LAMBDA=1.2,),);
-
-MODEL=AFFE_MODELE(MAILLAGE=MESH,
- AFFE=_F(TOUT='OUI',
- PHENOMENE='THERMIQUE',
- MODELISATION='3D',),);
-
-MATFIELD=AFFE_MATERIAU(MAILLAGE=MESH,
- AFFE=_F(TOUT='OUI',
- MATER=MATER,),);
-
-LOADING=AFFE_CHAR_THER(MODELE=MODEL,
- TEMP_IMPO=_F(GROUP_MA='Bloq',
- TEMP=23.,),
- FLUX_REP=_F(GROUP_MA='Press',
- FLUN=2.,),
- SOURCE=_F(GROUP_MA='Source',
- SOUR=2.,),);
-
-TEMP=THER_LINEAIRE(MODELE=MODEL,
- CHAM_MATER=MATFIELD,
- EXCIT=_F(CHARGE=LOADING,),);
-
-IMPR_RESU(FORMAT='MED',
- RESU=_F(RESULTAT=TEMP,),);
-
-FIN();
+++ /dev/null
-
-# PATRON
-# ANALYSE MODALE
-# 3D
-
-DEBUT();
-# MISE EN DONNEES
-
-MAIL=LIRE_MAILLAGE();
-
-MODELE=AFFE_MODELE(MAILLAGE=MAIL,
- AFFE=_F(GROUP_MA='OBJET',
- PHENOMENE='MECANIQUE',
- MODELISATION='3D',),);
-# MATERIAU
-
-ACIER=DEFI_MATERIAU(ELAS=_F(E=2.1E11,
- NU=0.3,
- RHO=7800.0,),);
-
-CHMAT=AFFE_MATERIAU(MAILLAGE=MAIL,
- AFFE=_F(GROUP_MA='OBJET',
- MATER=ACIER,),);
-# CONDITIONS AUX LIMITES ET CHARGEMENT
-# CONDITIONS AUX LIMITES
-
-BLOQUAGE=AFFE_CHAR_MECA(MODELE=MODELE,
- DDL_IMPO=_F(GROUP_MA='ENCAST',
- LIAISON='ENCASTRE',),);
-# CALCUL DES MATRICES ASSEMBLEES K ET M
-
-MACRO_MATR_ASSE(MODELE=MODELE,
- CHAM_MATER=CHMAT,
- CHARGE=BLOQUAGE,
- NUME_DDL=CO('NUMEDDL'),
- MATR_ASSE=(_F(MATRICE=CO('RIGIDITE'),
- OPTION='RIGI_MECA',),
- _F(MATRICE=CO('MASSE'),
- OPTION='MASS_MECA',),),);
-# CALCUL DES CINQ PREMIERS MODES
-
-MODES=MODE_ITER_SIMULT(MATR_A=RIGIDITE,
- MATR_B=MASSE,
- CALC_FREQ=_F(
- OPTION='PLUS_PETITE',
- NMAX_FREQ=5,),);
-#CHARGEMENT
-
-EXCIT=AFFE_CHAR_MECA(MODELE=MODELE,
- PRES_REP=_F(GROUP_MA='PRESSE',
- PRES=100.e5,),);
-
-EXCEL=CALC_VECT_ELEM(OPTION='CHAR_MECA',
- CHARGE=EXCIT,);
-
-EXCASS=ASSE_VECTEUR(VECT_ELEM=EXCEL,
- NUME_DDL=NUMEDDL,);
-OMEGA = 10.0;
-
-
-SINU = FORMULE(VALE='sin(OMEGA*INST)',
- NOM_PARA='INST',);
-#CALCUL TRANSITOIRE
-
-TRADIR=DYNA_LINE_TRAN(MATR_MASS=MASSE,
- MATR_RIGI=RIGIDITE,
- NEWMARK=_F(),
- EXCIT=_F(VECT_ASSE=EXCASS,),
- INCREMENT=_F(PAS=.01,
- INST_FIN=10.,),);
-
-FIN();
+++ /dev/null
-
-# PATRON
-# ANALYSE MODALE
-# 3D
-
-DEBUT();
-# MISE EN DONNEES
-
-MAIL=LIRE_MAILLAGE();
-
-MODELE=AFFE_MODELE(MAILLAGE=MAIL,
- AFFE=_F(GROUP_MA='OBJET',
- PHENOMENE='MECANIQUE',
- MODELISATION='3D',),);
-# MATERIAU
-
-ACIER=DEFI_MATERIAU(ELAS=_F(E=2.1E11,
- NU=0.3,
- RHO=7800.0,),);
-
-CHMAT=AFFE_MATERIAU(MAILLAGE=MAIL,
- AFFE=_F(GROUP_MA='OBJET',
- MATER=ACIER,),);
-# CONDITIONS AUX LIMITES ET CHARGEMENT
-# CONDITIONS AUX LIMITES
-
-BLOQUAGE=AFFE_CHAR_MECA(MODELE=MODELE,
- DDL_IMPO=_F(GROUP_MA='ENCAST',
- LIAISON='ENCASTRE',),);
-# CALCUL DES MATRICES ASSEMBLEES K ET M
-
-MACRO_MATR_ASSE(MODELE=MODELE,
- CHAM_MATER=CHMAT,
- CHARGE=BLOQUAGE,
- NUME_DDL=CO('NUMEDDL'),
- MATR_ASSE=(_F(MATRICE=CO('RIGIDITE'),
- OPTION='RIGI_MECA',),
- _F(MATRICE=CO('MASSE'),
- OPTION='MASS_MECA',),),);
-
-P=POST_ELEM(MASS_INER=_F(TOUT='OUI',
- GROUP_MA='M',),);
-# CALCUL DES CINQ PREMIERS MODES
-
-MODES=MODE_ITER_SIMULT(MATR_A=RIGIDITE,
- MATR_B=MASSE,
- CALC_FREQ=_F(
- OPTION='PLUS_PETITE',
- NMAX_FREQ=5,),);
-#CHARGEMENT
-
-EXCIT=AFFE_CHAR_MECA(MODELE=MODELE,
- PRES_REP=_F(GROUP_MA='PRESSE',
- PRES=100.e5,),);
-
-EXCEL=CALC_VECT_ELEM(OPTION='CHAR_MECA',
- CHARGE=EXCIT,);
-
-EXCASS=ASSE_VECTEUR(VECT_ELEM=EXCEL,
- NUME_DDL=NUMEDDL,);
-OMEGA = 10.0;
-
-
-SINU = FORMULE(VALE='sin(OMEGA*INST)',
- NOM_PARA='INST',);
-#PROJECTION
-
-MACRO_PROJ_BASE(BASE=MODES,
- MATR_ASSE_GENE=(_F(MATRICE=CO('MASSPROJ'),
- MATR_ASSE=MASSE,),
- _F(MATRICE=CO('RIGIPROJ'),
- MATR_ASSE=RIGIDITE,),),
- VECT_ASSE_GENE=_F(VECTEUR=CO('EXCPROJ'),
- VECT_ASSE=EXCASS,),);
-#CALCUL TRANSITOIRE
-
-TRAMOD=DYNA_TRAN_MODAL(MASS_GENE=MASSPROJ,
- RIGI_GENE=RIGIPROJ,
- AMOR_REDUIT=(.02,.01,),
- INCREMENT=_F(INST_INIT=0.0,
- INST_FIN=10.0,
- PAS=.001,),
- EXCIT=_F(VECT_GENE=EXCPROJ,
- FONC_MULT=SINU,),);
-
-FIN();
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-# Question : Doit-on installer le repertoire Patrons meme s'il est vide ?
-
-# Installation des fichiers d'aide : Open TURNS
-#if (WITH_OPENTURNS)
-# install ( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/OPENTURNS_STUDY
-# DESTINATION ${CMAKE_INSTALL_PREFIX}/Editeur/Patrons
-# FILES_MATCHING PATTERN *.comm
-# PATTERN CVS EXCLUDE
-# )
-#endif (WITH_OPENTURNS)
-
-# Installation des fichiers d'aide : Aster
-if (WITH_ASTER)
- install ( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ASTER
- DESTINATION ${CMAKE_INSTALL_PREFIX}/Editeur/Patrons
- FILES_MATCHING PATTERN *.comm
- PATTERN CVS EXCLUDE
- )
-endif (WITH_ASTER)
-
-### Local Variables:
-### mode: cmake
-### End:
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-# Installation de tous les fichiers Python du repertoire et des sous-repertoires (sauf CVS)
-install ( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
- DESTINATION ${CMAKE_INSTALL_PREFIX}
- FILES_MATCHING PATTERN *.py
- PATTERN CVS EXCLUDE
- )
-
-
-### Local Variables:
-### mode: cmake
-### End:
+++ /dev/null
- convert/autre_parseur.py \
- convert/convert_ini.py \
- convert/convert_map.py \
- convert/convert_python.py \
- convert/parseur_python.py \
- convert/convert_TELEMAC.py \
- Editeur/analyse_catalogue_initial.py \
- Editeur/analyse_catalogue.py \
- Editeur/autre_analyse_cata.py \
- Editeur/basestyle.py \
- Editeur/catadesc.py \
- Editeur/comploader.py \
- Editeur/fontes.py \
- Editeur/import_code.py \
- Editeur/listePatrons.py \
- Editeur/Objecttreeitem.py \
- Editeur/session.py \
- Editeur/styles.py \
- Editeur/TroisDPal.py \
- Editeur/uiinfo.py \
- Extensions/commande_comm.py \
- Extensions/commentaire.py \
- Extensions/eficas_exception.py \
- Extensions/etape_niveau.py \
- Extensions/interpreteur_formule.py \
- Extensions/jdc_include.py \
- Extensions/jdc.py \
- Extensions/localisation.py \
- Extensions/mcnuplet.py \
- Extensions/niveau.py \
- Extensions/nuplet.py \
- Extensions/param2.py \
- Extensions/parametre_eval.py \
- Extensions/parametre.py \
- Extensions/pluginloader.py \
- generator/Formatage.py \
- generator/generator_aplat.py \
- generator/generator_dicoImbrique.py \
- generator/generator_dico.py \
- generator/generator_GroupMA.py \
- generator/generator_map.py \
- generator/generator_modification.py \
- generator/generator_python.py \
- generator/generator_vers3DSalome.py \
- Ihm/CONNECTOR.py \
- Ihm/I_A_CLASSER.py \
- Ihm/I_ASSD.py \
- Ihm/I_AVANT.py \
- Ihm/I_ENTITE.py \
- Ihm/I_ETAPE.py \
- Ihm/I_EVAL.py \
- Ihm/I_EXCLUS.py \
- Ihm/I_FONCTION.py \
- Ihm/I_FORM_ETAPE.py \
- Ihm/I_JDC_CATA.py \
- Ihm/I_JDC.py \
- Ihm/I_LASSD.py \
- Ihm/I_MACRO_ETAPE.py \
- Ihm/I_MCBLOC.py \
- Ihm/I_MCCOMPO.py \
- Ihm/I_MCFACT.py \
- Ihm/I_MCLIST.py \
- Ihm/I_MCSIMP.py \
- Ihm/I_OBJECT.py \
- Ihm/I_PRESENT_ABSENT.py \
- Ihm/I_PRESENT_PRESENT.py \
- Ihm/I_PROC_ETAPE.py \
- Ihm/I_REGLE.py \
- Ihm/I_UN_PARMI.py \
- Ihm/I_VALIDATOR.py \
- InterfaceQT4/browser.py \
- InterfaceQT4/compobloc.py \
- InterfaceQT4/compocommandecomm.py \
- InterfaceQT4/compocomm.py \
- InterfaceQT4/compofact.py \
- InterfaceQT4/compoformule.py \
- InterfaceQT4/compojdc.py \
- InterfaceQT4/compomacro.py \
- InterfaceQT4/compomclist.py \
- InterfaceQT4/compooper.py \
- InterfaceQT4/compoparam.py \
- InterfaceQT4/compoproc.py \
- InterfaceQT4/composimp.py \
- InterfaceQT4/configuration.py \
- InterfaceQT4/editor.py \
- InterfaceQT4/eficas_go.py \
- InterfaceQT4/feuille.py \
- InterfaceQT4/gereIcones.py \
- InterfaceQT4/gereListe.py \
- InterfaceQT4/gereRegles.py \
- InterfaceQT4/gereTraduction.py \
- InterfaceQT4/getVersion.py \
- InterfaceQT4/groupe.py \
- InterfaceQT4/monBoutonValide.py \
- InterfaceQT4/monChoixCata.py \
- InterfaceQT4/monChoixCode.py \
- InterfaceQT4/monChoixCommande.py \
- InterfaceQT4/monChoixLangue.py \
- InterfaceQT4/monFonctionPanel.py \
- InterfaceQT4/monLabelClic.py \
- InterfaceQT4/monRecherche.py \
- InterfaceQT4/monRechercheCatalogue.py \
- InterfaceQT4/monSelectVal.py \
- InterfaceQT4/monViewTexte.py \
- InterfaceQT4/monViewRegle.py \
- InterfaceQT4/monVisu.py \
- InterfaceQT4/monWidget4a6RadioButton.py \
- InterfaceQT4/monWidget4a6RadioButtonSD.py \
- InterfaceQT4/monWidgetBloc.py \
- InterfaceQT4/monWidgetCB.py \
- InterfaceQT4/monWidgetCBSD.py \
- InterfaceQT4/monWidgetCommande.py \
- InterfaceQT4/monWidgetCommentaire.py \
- InterfaceQT4/monWidgetCreeParam.py \
- InterfaceQT4/monWidgetDate.py \
- InterfaceQT4/monWidgetFactPlie.py \
- InterfaceQT4/monWidgetFact.py \
- InterfaceQT4/monWidgetFormule.py \
- InterfaceQT4/monWidgetHeure.py \
- InterfaceQT4/monWidgetInfo.py \
- InterfaceQT4/monWidgetInactif.py \
- InterfaceQT4/monWidgetMatrice.py \
- InterfaceQT4/monWidgetOptionnel.py \
- InterfaceQT4/monWidgetParam.py \
- InterfaceQT4/monWidgetPlusieursBase.py \
- InterfaceQT4/monWidgetPlusieursASSDIntoOrdonne.py \
- InterfaceQT4/monWidgetPlusieursIntoOrdonne.py \
- InterfaceQT4/monWidgetPlusieursInto.py \
- InterfaceQT4/monWidgetPlusieursTuple2.py \
- InterfaceQT4/monWidgetPlusieursTuple3.py \
- InterfaceQT4/monWidgetPlusieursTuple.py \
- InterfaceQT4/monWidgetPlusieursPlie.py \
- InterfaceQT4/monWidgetRadioButton.py \
- InterfaceQT4/monWidgetSDCOInto.py \
- InterfaceQT4/monWidgetSimpBase.py \
- InterfaceQT4/monWidgetSimpBool.py \
- InterfaceQT4/monWidgetSimpComplexe.py \
- InterfaceQT4/monWidgetSimpFichier.py \
- InterfaceQT4/monWidgetSimpTuple2.py \
- InterfaceQT4/monWidgetSimpTuple3.py \
- InterfaceQT4/monWidgetSimpTuple.py \
- InterfaceQT4/monWidgetSimpSalome.py \
- InterfaceQT4/monWidgetSimpTxt.py \
- InterfaceQT4/monWidgetUniqueSDCO.py \
- InterfaceQT4/monWidgetVide.py \
- InterfaceQT4/politiquesValidation.py \
- InterfaceQT4/qtEficas.py \
- InterfaceQT4/qtEficas_with_log.py \
- InterfaceQT4/qtSaisie.py \
- InterfaceQT4/readercata.py \
- InterfaceQT4/ssIhm.py \
- InterfaceQT4/typeNode.py \
- InterfaceQT4/viewManager.py \
- Traducteur/calcG.py \
- Traducteur/changeValeur.py \
- Traducteur/dictErreurs.py \
- Traducteur/inseremocle.py \
- Traducteur/load.py \
- Traducteur/log.py \
- Traducteur/mocles.py \
- Traducteur/movemocle.py \
- Traducteur/parseur.py \
- Traducteur/regles.py \
- Traducteur/removemocle.py \
- Traducteur/renamemocle.py \
- Traducteur/traduitV7V8.py \
- Traducteur/traduitV8V9.py \
- Traducteur/traduitV9V10.py \
- Traducteur/utils.py \
- Traducteur/visiteur.py \
- Noyau/N_VALIDATOR.py \
- Noyau/N_JDC.py \
- Validation/V_A_CLASSER.py \
- Validation/V_AU_MOINS_UN.py \
- Validation/V_AU_PLUS_UN.py \
- Validation/V_ENSEMBLE.py \
- Validation/V_ETAPE.py \
- Validation/V_EXCLUS.py \
- Validation/V_JDC.py \
- Validation/V_MACRO_ETAPE.py \
- Validation/V_MCBLOC.py \
- Validation/V_MCCOMPO.py \
- Validation/V_MCFACT.py \
- Validation/V_MCLIST.py \
- Validation/V_MCSIMP.py \
- Validation/V_MEME_NOMBRE.py \
- Validation/V_PRESENT_ABSENT.py \
- Validation/V_PRESENT_PRESENT.py \
- Validation/V_PROC_ETAPE.py \
- Validation/V_UN_PARMI.py
-
-FORMS = \
- UiQT5/desBaseWidget.ui \
- UiQT5/desChoixCata.ui \
- UiQT5/desChoixCode.ui \
- UiQT5/desChoixCommandes.ui \
- UiQT5/desChoixLangue.ui \
- UiQT5/desGroupeOptionnel.ui \
- UiQT5/desPBOptionnelMT.ui \
- UiQT5/desRechercheCatalogue.ui \
- UiQT5/desRecherche.ui \
- UiQT5/desSelectVal.ui \
- UiQT5/desViewRegles.ui \
- UiQT5/desViewTexte.ui \
- UiQT5/desVisu.ui \
- UiQT5/desWidget4a6RadioButton.ui \
- UiQT5/desWidgetBloc.ui \
- UiQT5/desWidgetCB.ui \
- UiQT5/desWidgetCommande.ui \
- UiQT5/desWidgetCommentaire.ui \
- UiQT5/desWidgetCreeParam.ui \
- UiQT5/desWidgetDate.ui \
- UiQT5/desWidgetFactHorizon.ui \
- UiQT5/desWidgetFactPlie.ui \
- UiQT5/desWidgetFact.ui \
- UiQT5/desWidgetFormule.ui \
- UiQT5/desWidgetHeure.ui \
- UiQT5/desWidgetInactif.ui \
- UiQT5/desWidgetInformation.ui \
- UiQT5/desWidgetIntoSug.ui \
- UiQT5/desWidgetMatrice.ui \
- UiQT5/desWidgetOptionnelMC.ui \
- UiQT5/desWidgetOptionnel.ui \
- UiQT5/desWidgetParam.ui \
- UiQT5/desWidgetPlusieursBase.ui \
- UiQT5/desWidgetPlusieursIntoOrdonne.ui \
- UiQT5/desWidgetPlusieursInto.ui \
- UiQT5/desWidgetPlusieursPlie.ui \
- UiQT5/desWidgetPlusieursTuple.ui \
- UiQT5/desWidgetRadioButton.ui \
- UiQT5/desWidgetSDCOInto.ui \
- UiQT5/desWidgetSimpBase.ui \
- UiQT5/desWidgetSimpBool.ui \
- UiQT5/desWidgetSimpComplexe.ui \
- UiQT5/desWidgetSimpFichier.ui \
- UiQT5/desWidgetSimpSalome.ui \
- UiQT5/desWidgetSimpTxt.ui \
- UiQT5/desWidgetTuple2.ui \
- UiQT5/desWidgetTuple3.ui \
- UiQT5/desWidgetUniqueSDCO.ui \
- UiQT5/desWidgetVide.ui \
- UiQT5/myMain.ui \
- UiQT5/Tuple2.ui \
- UiQT5/Tuple3.ui
-
-TRANSLATIONS = UiQT5/eficas_fr.ts UiQT5/eficas_en.ts
+++ /dev/null
-print tr("Mot-clé : %s obligatoire non valorisé")
-print tr("None n'est pas ujjjjjjjjjne valeur autorisée")
-print tr("Mot-cle simple : ")
-print tr("Fin Mot-clé simple : ")
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-# Installation de tous les fichiers Python du repertoire et des sous-repertoires (sauf CVS)
-install ( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
- DESTINATION ${CMAKE_INSTALL_PREFIX}
- FILES_MATCHING PATTERN *.py
- PATTERN CVS EXCLUDE
- )
-
-
-### Local Variables:
-### mode: cmake
-### End:
--- /dev/null
+# -*- coding: utf-8 -*-
+# Copyright (C) 2007-2013 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+from __future__ import absolute_import
+from __future__ import print_function
+try :
+ from builtins import str
+ from builtins import range
+except : pass
+
+import types,sys,os, re
+import subprocess
+import traceback
+
+import six
+from six.moves import range
+
+import traceback
+
+# Modules Eficas
+
+import convert, generator
+from Editeur import session
+from Editeur import comploader
+from Editeur import Objecttreeitem
+
+DictExtensions= {"MAP" : ".map", "TELEMAC" : '.cas'}
+debug = False
+
+
+
+class JDCEditorSsIhm :
+# ------------------- #
+ """
+ Editeur de jdc
+ """
+
+# ---------------------------------------------
+# Methodes Communes ou appelees depuis avec Ihm
+# ---------------------------------------------
+
+ def __init__ (self,appli,fichier = None, jdc = None, units = None, include=0 ):
+ #------------------------------------------------------------------------------#
+ # paticularisee avec Ihm
+
+ if debug : print ('dans le init de JDCEditorSsIhm')
+ self.appliEficas = appli
+ self.appli = appli
+ self.fichier = fichier
+ self.fichierComplet = fichier
+ self.jdc = jdc
+ self.first = True
+ self.jdc_item = None
+ self.dicoNouveauxMC = {}
+ self.dicoNouveauxFact = {}
+ self.dict_reels = {}
+ self.liste_simp_reel = []
+
+ if appli != None : self.salome = self.appliEficas.salome
+ else : self.salome = 0
+
+ # ces attributs sont mis a jour par definitCode appelee par newEditor
+ self.code = self.appliEficas.maConfiguration.code
+ self.maConfiguration = self.appliEficas.maConfiguration
+
+ self.version_code = session.d_env.cata
+
+
+ if not hasattr ( self.appliEficas, 'readercata') or self.appliEficas.readercata.demandeCatalogue==True or self.appliEficas.multi==True:
+ if self.maConfiguration.typeDeCata == 'XML' :
+ from . import readercataXML as readercata
+ else :
+ from . import readercata
+ self.readercata = readercata.ReaderCata( self, self.appliEficas )
+ self.appliEficas.readercata=self.readercata
+ self.appliEficas.code=self.code
+ else :
+ self.readercata=self.appliEficas.readercata
+ if self.readercata.fic_cata == None : return #Sortie Salome
+ self.titre=self.readercata.titre
+
+ self.format = self.appliEficas.format_fichier
+
+ if self.appliEficas.maConfiguration.dumpXSD==True : self.appliEficas.dumpXsd()
+ self.dict_reels={}
+ self.liste_simp_reel=[]
+ self.dicoNouveauxMC={}
+ self.dicoNouveauxFact={}
+
+
+ try:
+ self.maConfiguration.generator_module
+ _module = __import__(self.maConfiguration.generator_module)
+ info = _module.entryPoint()
+ generator.plugins.addEntryPoint(info)
+ except:
+ pass
+
+ try:
+ self.maConfiguration.convert_module
+ #print self.maConfiguration.convert_module
+ _module = __import__(self.maConfiguration.convert_module)
+ info = _module.entryPoint()
+ convert.plugins.addEntryPoint(info)
+ except :
+ pass
+
+ self.maConfiguration.mesGenerators = generator
+ self.maConfiguration.mesconvertisseurs = convert
+
+ self.fileInfo = None
+ self.lastModified = 0
+
+ self.modified = False
+ self.isReadOnly = False
+
+ #------- construction du jdc --------------
+
+
+ self.nouveau=0
+ if self.fichier is not None: # fichier jdc fourni
+ if jdc==None :
+ #print ('PNPN : chgt try en if')
+ try :
+ #if 1 :
+ self.jdc = self.readFile(self.fichier)
+ except :
+ print ("mauvaise lecture du fichier")
+ if self.salome :
+ try :
+ self.appliEficas.addJdcInSalome( self.fichier)
+ except :
+ print ("mauvais enregistrement dans Salome")
+ else :
+ self.jdc=jdc
+
+ if self.jdc is not None and units is not None:
+ self.jdc.recorded_units=units
+ self.jdc.old_recorded_units=units
+
+ else:
+ if not self.jdc: # nouveau jdc
+ if not include :
+ self.jdc = self._newJDC(units=units)
+ else :
+ self.jdc = self._newJDCInclude(units=units)
+ self.nouveau=1
+
+ if self.jdc:
+ self.jdc.appli = self # a resorber
+ self.jdc.editor = self
+ self.jdc.lang = self.appli.langue
+ self.jdc.aReafficher=False
+ txt_exception = None
+ if not jdc:
+ self.jdc.analyse()
+ txt_exception = self.jdc.cr.getMessException()
+ if txt_exception :
+ self.jdc = None
+ self.informe('pb chargement jdc',txt_exception)
+ else:
+ #comploader.chargerComposants()
+ #cette ligne devrait etre dans editor ???
+ self.jdc_item=Objecttreeitem.makeObjecttreeitem( self, "nom", self.jdc )
+
+ #-------------------------------#
+ def readFile(self, fn):
+ #--------------------------------#
+ """
+ Public slot to read the text from a file.
+ @param fn filename to read from (string or QString)
+ """
+
+ # charge un JDC
+ # paticularisee avec Ihm
+
+ fn = six.text_type(fn)
+ jdcName=os.path.basename(fn)
+
+ # Il faut convertir le contenu du fichier en fonction du format
+ if self.appliEficas.format_fichier_in in convert.plugins:
+ # Le convertisseur existe on l'utilise
+
+ p=convert.plugins[self.appliEficas.format_fichier_in]()
+ p.readfile(fn)
+
+ if p.text=="" : self.nouveau=1
+ #print ('PNPN --> CIST a faire')
+
+ pareil,texteNew=self.verifieChecksum(p.text)
+ if not pareil :
+ self.informe(("fichier modifie"),("Attention! fichier change hors EFICAS"),False)
+
+ p.text=texteNew
+ memeVersion,texteNew=self.verifieVersionCataDuJDC(p.text)
+ if memeVersion == 0 : texteNew=self.traduitCatalogue(texteNew)
+ p.text=texteNew
+
+ text=p.convert('exec',self.appliEficas)
+
+ if not p.cr.estvide(): self.afficheInfos("Erreur a la conversion",'red')
+ else :
+ self.afficheInfos("Type de fichier non reconnu",'red')
+ self.informe( "Type de fichier non reconnu",
+ "EFICAS ne sait pas ouvrir le type de fichier " + self.appliEficas.format_fichier_in)
+ return None
+
+ CONTEXT.unsetCurrentStep()
+
+ #jdc=self.readercata.cata[0].JdC(procedure=text,
+ jdc=self.readercata.cata.JdC(procedure=text,
+ appli=self,
+ cata=self.readercata.cata,
+ cata_ord_dico=self.readercata.cata_ordonne_dico,
+ nom=jdcName,
+ rep_mat=self.maConfiguration.rep_mat
+ )
+ self.modified = False
+ return jdc
+
+
+ #--------------------------------#
+ def _newJDC( self ,units = None):
+ #--------------------------------#
+ """
+ Initialise un nouveau JDC vierge
+ """
+ self.modified=1
+ CONTEXT.unsetCurrentStep()
+
+ texte=""
+ if self.code == "CARMELCND" : texte=self._newJDCCND()
+ if self.code == "ZCRACKS" : texte=self._newZCRACKS()
+ if self.code == "PSEN" : texte = self._newPSEN()
+ if self.code == "PSEN_N1" : texte = self._newPSEN_N1()
+
+ #if hasattr(self.readercata.cata[0],'TEXTE_NEW_JDC') : texte=self.readercata.cata[0].TEXTE_NEW_JDC
+ if hasattr(self.readercata.cata,'TEXTE_NEW_JDC') : texte=self.readercata.cata.TEXTE_NEW_JDC
+
+
+ #jdc=self.readercata.cata[0].JdC( procedure =texte,
+ #print (self.readercata.cata)
+ jdc=self.readercata.cata.JdC( procedure =texte,
+ appli=self,
+ cata=self.readercata.cata,
+ cata_ord_dico=self.readercata.cata_ordonne_dico,
+ rep_mat=self.maConfiguration.rep_mat
+ )
+
+ jdc.lang = self.appli.langue
+ if units is not None:
+ jdc.recorded_units=units
+ jdc.old_recorded_units=units
+ ## PNPN est ce que la ligne suivante est bien utile ?
+ # elle positionne le contexte
+ # est ce qu on ne doit pas changer le format en Accas si on vient d accas ?
+ if self.format == 'xml' : return jdc
+ if texte == "" :
+ jdc.editor=self
+ jdc.analyse()
+ return jdc
+
+ #--------------------------------#
+ def _newJDCInclude( self ,units = None):
+ #--------------------------------#
+ """
+ Initialise un nouveau JDC vierge
+ """
+ import Extensions.jdc_include
+ JdC_aux=Extensions.jdc_include.JdC_include
+ CONTEXT.unsetCurrentStep()
+
+ #jaux=self.readercata.cata[0].JdC( procedure="",
+ jaux=self.readercata.cata.JdC( procedure="",
+ appli=self,
+ cata=self.readercata.cata,
+ cata_ord_dico=self.readercata.cata_ordonne_dico,
+ rep_mat=self.maConfiguration.rep_mat,
+ )
+ jaux.analyse()
+
+ J=JdC_aux( procedure="",
+ appli=self,
+ cata=self.readercata.cata,
+ cata_ord_dico=self.readercata.cata_ordonne_dico,
+ jdc_pere=jaux,
+ rep_mat=self.maConfiguration.rep_mat,
+ )
+ J.analyse()
+ if units is not None:
+ J.recorded_units=units
+ J.old_recorded_units=units
+ return J
+
+
+
+ #-----------------------#
+ def getSource(self,file):
+ #-----------------------#
+
+ # Il faut convertir le contenu du fichier en fonction du format
+ if self.format in convert.plugins :
+ # Le convertisseur existe on l'utilise
+ p=convert.plugins[self.format]()
+ p.readfile(file)
+ text=p.convert('execnoparseur')
+ if not p.cr.estvide():
+ self.afficheInfos("Erreur a la conversion",'red')
+ return text
+ else:
+ # Il n'existe pas c'est une erreur
+ self.afficheInfos("Type de fichier non reconnu",'red')
+ self.informe( "Type de fichier non reconnu",
+ "EFICAS ne sait pas ouvrir le type de fichier " + self.appliEficas.format_fichier_in)
+ return None
+
+ #----------------------------------------------#
+ def __generateTempFilename(self, prefix, suffix):
+ #----------------------------------------------#
+ import tempfile
+ (fd, filename) = tempfile.mkstemp(prefix=prefix, suffix=suffix)
+ os.close(fd)
+ return filename
+
+ #-----------------------#
+ def generDico(self):
+ #-----------------------#
+ if 'dico' in generator.plugins:
+ self.generator=generator.plugins['dico']()
+ #print (self.generator)
+ jdc_formate=self.generator.gener(self.jdc)
+ #print (jdc_formate)
+ dico=self.generator.Dico
+ #print (dico)
+ return dico
+
+ #-----------------------#
+ def viewJdcSource(self):
+ #-----------------------#
+ if self.fichier == None : return
+ f=open(self.fichier,'r')
+ texteSource=f.read()
+ f.close()
+ self._viewText(texteSource, "JDC_SOURCE")
+
+ #-----------------------#
+ def viewJdcPy(self):
+ #-----------------------#
+ strSource = str( self.getTextJDC(self.format) )
+ self._viewText(strSource, "JDC_RESULTAT")
+
+ #-----------------------#
+ def viewJdcRapport(self):
+ #-----------------------#
+ # on ajoute les regles
+ strRapport = six.text_type( self.jdc.report() )
+ self._viewText(strRapport, "JDC_RAPPORT")
+
+ #-----------------------#
+ def viewJdcRegles(self):
+ #-----------------------#
+ # on ajoute les regles
+ texte_global, test_global = self.jdc.verifRegles()
+ self._viewText(texte_global, "JDC_REGLES")
+
+ #-----------------------#
+ def getJdcRapport(self):
+ #-----------------------#
+ # on ajoute les regles
+ strRapport = six.text_type( self.jdc.report() )
+ return strRapport
+
+ #---------------------#
+ def getFileName(self):
+ #---------------------#
+ return self.fichier
+
+ #-------------------#
+ def initModif(self):
+ #-------------------#
+ """
+ Met l'attribut modified a 'o' : utilise par Eficas pour savoir
+ si un JDC doit etre sauvegarde avant destruction ou non
+ """
+ self.modified = True
+
+
+ #--------------------------------------------------#
+ def writeFile(self, fn, txt = None,formatLigne="beautifie"):
+ #--------------------------------------------------#
+ """
+ Public slot to write the text to a file.
+
+ @param fn filename to write to string
+ @return flag indicating success
+ """
+
+ fn = six.text_type(fn)
+
+ if txt == None :
+ txt = self.getTextJDC(self.format,formatLigne=formatLigne)
+ eol = '\n'
+ if len(txt) >= len(eol):
+ if txt[-len(eol):] != eol:
+ txt += eol
+ else:
+ txt += eol
+ txt=self.ajoutVersionCataDsJDC(txt)
+ if self.code != 'PSEN' and self.code != 'PSEN_N1' : checksum=self.getChecksum(txt)
+ else : checksum=''
+ txt=txt+checksum
+ if self.code=="TELEMAC" : return 1
+ try:
+ f = open(fn, 'w')
+ f.write(txt)
+ f.close()
+ return 1
+ except IOError as why:
+ self.afficheInfos('Sauvegarde du Fichier', 'Le fichier'+str(fn) + 'n a pas pu etre sauvegarde :' + str(why))
+ return 0
+
+ #-----------------------------------------------------------#
+ def getTextJDC(self,format,pourRun=0,formatLigne="beautifie"):
+ #-----------------------------------------------------------#
+ if self.code == "MAP" and not(format in generator.plugins): format = "MAP"
+ if format in generator.plugins:
+
+ # Le generateur existe on l'utilise
+ self.generator=generator.plugins[format]()
+ try :
+ jdc_formate=self.generator.gener(self.jdc,format=formatLigne,config=self.appliEficas.maConfiguration,appli=self.appliEficas)
+ if pourRun : jdc_formate=self.generator.textePourRun
+ if self.code == 'TELEMAC' : jdc_formate=self.generator.texteDico
+ except ValueError as e:
+ self.informe( "Erreur a la generation",str(e),'red')
+ return
+
+ if not self.generator.cr.estvide():
+ self.informe("Erreur a la generation","EFICAS ne sait pas convertir ce JDC",'red')
+ return ""
+ else:
+ return jdc_formate
+ else:
+ # Il n'existe pas c'est une erreur
+ self.informe("Format inconnu", self.format + " non reconnu" )
+ return ""
+
+ #------------------------------#
+ def verifieChecksum(self,text):
+ #------------------------------#
+ # Attention : souci sous Windows
+ #
+ indexDeb=text.find("#CHECKSUM:")
+ if indexDeb < 0 : return 1, text
+ indexFin=text.find(":FIN CHECKSUM")
+ checkAvant=text[indexDeb:indexFin+13]
+ textJDC=text[0:indexDeb]+text[indexFin+13:-1]
+ if self.code != 'PSEN' and self.code != 'PSEN_N1':
+ checksum=self.getChecksum(textJDC)
+ pareil=(checkAvant==checksum)
+ else :
+ pareil=1
+ return pareil, textJDC
+
+ #---------------------------#
+ def getChecksum(self,texte):
+ #---------------------------#
+ try :
+ import haslib
+ newtexte=texte.replace('"','\\"')
+ hash_checksum = hashlib.md5()
+ hash_checksum.update(newtexte.encode('utf-8'))
+ checksum = hash_checksum.hexdigest()
+ ligne = "#CHECKSUM:"+checksum+":FIN CHECKSUM"
+ except :
+ try :
+ newtexte=texte.replace('"','\\"')
+ commande='echo "'+newtexte+'"|md5sum'
+ a=os.popen(commande)
+ checksum=a.read()
+ a.close()
+ except :
+ checksum='Fichier trop long \n'
+ ligne="#CHECKSUM:"+checksum[0:-1]+":FIN CHECKSUM"
+ return ligne
+
+ #----------------------#
+ def getDico(self):
+ #---------------------#
+ if 'dicoImbrique' in generator.plugins:
+ self.generator=generator.plugins['dicoImbrique']()
+ #print (self.generator)
+ jdc_formate=self.generator.gener(self.jdc)
+ dico=self.generator.Dico
+ return dico
+ else :
+ self.afficheInfos(tr("Format %s non reconnu" , self.format),Qt.red)
+ return ""
+
+ #-----------------------------------------#
+ def chercheGroupes(self):
+ #-----------------------------------------#
+ listeMA,listeNO=self.getTextJDC("GroupMA")
+ return listeMA,listeNO
+
+ #-----------------------------------------#
+ def chercheDico(self):
+ #-----------------------------------------#
+ dicoCourant={}
+ format = self.appliEficas.format_fichier
+ if format in generator.plugins:
+ # Le generateur existe on l'utilise
+ self.generator=generator.plugins[format]()
+ jdc_formate=self.generator.gener(self.jdc,format='beautifie',config=self.appliEficas.maConfiguration)
+ dicoCourant=self.generator.dico
+ return dicoCourant
+
+ #-----------------------------------------------------------------#
+ def saveFileLegerAs(self, fileName = None) :
+ #-----------------------------------------------------------------#
+ if fileName != None :
+ self.fichier = fileName
+ return self.saveFileLeger(fileName)
+ return self.saveFileLeger()
+
+ #-----------------------------------------------------------------#
+ def saveFileComplet(self, fichier = None, formatLigne="beautifie"):
+ #-----------------------------------------------------------------#
+ fn = fichier
+ self.generator=generator.plugins[self.format]()
+ print (self.generator)
+ if hasattr(self.generator, "writeComplet"):
+ self.generator.writeComplet(fichier,self.jdc,config=self.appliEficas.maConfiguration,appli=self.appliEficas)
+
+
+# ---------------------------------------------
+# Methodes Surchargees par avecIhm
+# ---------------------------------------------
+
+ #--------------------------------#
+ def ajoutCommentaire(self):
+ #--------------------------------#
+ print ('pas programme sans Ihm')
+ print ('prevenir la maintenance du besoin')
+
+
+ #--------------------------------------#
+ def informe(self,titre,txt,critique=True):
+ #--------------------------------------#
+ # methode differenre avec et sans ihm
+ if critique : print ('!!!!!!!!!!!!!!!!!!!!!!!!!!!')
+ print (titre)
+ print (txt)
+ if critique : print ('!!!!!!!!!!!!!!!!!!!!!!!!!!!')
+
+ #--------------------------------------#
+ def afficheInfos(self,txt,couleur=None):
+ #--------------------------------------#
+ # methode differenre avec et sans ihm
+ print (txt)
+
+ #-----------------------------------------------------------------------#
+ def _viewText(self, txt, caption = "FILE_VIEWER",largeur=1200,hauteur=600):
+ #--------------------------------------------------------------------#
+ print ('_____________________________')
+ print (txt)
+ print ('_____________________________')
+
+
+ #-----------------------------------------------------------------#
+ def saveFile(self, fichier, formatLigne="beautifie"):
+ #-----------------------------------------------------------------#
+ """
+ Public slot to save the text to a file.
+
+ @param path directory to save the file in (string or QString)
+ @return tuple of two values (boolean, string) giving a success indicator and
+ the name of the saved file
+ """
+
+
+ if not (self.writeFile(fichier,formatLigne=formatLigne)): return (0, None)
+ self.fichierOut = fichier
+
+ if self.jdc.isValid() != 0 and hasattr(self.generator, "writeDefault"):
+ self.generator.writeDefault(fichier)
+ elif self.code=="TELEMAC" and hasattr(self.generator, "writeDefault"):
+ self.generator.writeDefault(fichier)
+
+ self.modified = 0
+
+ return (1, self.fichier)
+#
+
+ #----------------------------------------------#
+ def sauveLigneFile(self):
+ #----------------------------------------------#
+ self.modified=1
+ return self.saveFile(formatLigne="Ligne")
+
+
+ #-----------------------------------#
+ def updateJdc(self, itemApres,texte):
+ #------------------------------------#
+ # ajoute une etape de JdC a partir d un texte
+ monItem=itemApres
+ etape=monItem.item.object
+ CONTEXT.setCurrentStep(etape)
+ etape.buildIncludeInclude(texte)
+ self.tree.racine.buildChildren()
+
+ #-----------------------------------#
+ def updateJdcEtape(self, itemApres,texte):
+ #------------------------------------#
+ # ajoute une etape de JdC a partir d un texte
+ monItem=itemApres
+ etape=monItem.item.object
+ CONTEXT.set_current_step(etape)
+ try :
+ ok=etape.build_includeEtape(texte)
+ except :
+ ok=0
+ if not ok :
+ QMessageBox.information( self,
+ tr("Import texte"),
+ tr("Impossible d importer le texte"))
+ self.tree.racine.build_children()
+ return ok
+
+
+
+ #-------------------------------------#
+ def deleteEtape(self,etape):
+ #-------------------------------------#
+ # dans le JDC
+ self.jdc.suppentite(etape)
+
+ #-------------------------------------#
+ def deleteMC(self,etape,MCFils,listeAvant=()):
+ #-------------------------------------#
+ # dans le JDC
+ ouChercher=etape
+ for mot in listeAvant :
+ ouChercher=ouChercher.getChild(mot,restreint="oui")
+ monMC=ouChercher.getChild(MCFils,restreint="oui")
+ if monMC != None : ouChercher.suppentite(monMC)
+ ouChercher.state='changed'
+ ouChercher.isvalid()
+
+ #--------------------------------------------------------#
+ def ajoutMC(self,etape,MCFils,valeurs,listeAvant=()):
+ #--------------------------------------------------------#
+ # dans le JDC
+ debug=False
+ if debug : print ('ajoutMC', etape,MCFils,valeurs,listeAvant)
+ ouChercher=etape
+ if debug : print (ouChercher)
+ for mot in listeAvant :
+ ouChercher=ouChercher.getChild(mot,restreint="oui", debug=1)
+ monMC=ouChercher.getChild(MCFils,restreint="oui")
+ if monMC == None : monMC = ouChercher.addEntite(MCFils)
+ monMC.valeur=valeurs
+ monMC.val=valeurs
+ monMC.state='changed'
+ monMC.isvalid()
+ return 1
+
+ #--------------------------------------------------------#
+ def ajoutMCinMCFactUnique(self,etape,MCFils,valeurs,listeAvant=()):
+ # Attention si +sieursMCFACT
+ #--------------------------------------------------------#
+ # dans le JDC
+ debug=False
+ if debug : print ('ajoutMC', etape,MCFils,valeurs,listeAvant)
+ ouChercher=etape
+ if debug : print (ouChercher)
+ for mot in listeAvant :
+ ouChercher=ouChercher.getChild(mot,restreint="oui", debug=1)
+ # Attention si +sieursMCFACT
+ ouChercher=ouChercher[0]
+ if debug : print (ouChercher)
+ monMC=ouChercher.getChild(MCFils,restreint="oui")
+ if monMC == None : monMC = ouChercher.addEntite(MCFils)
+ monMC.valeur=valeurs
+ monMC.val=valeurs
+ monMC.state='changed'
+ monMC.isValid()
+ return 1
+
+ #----------------------------------------------#
+ def ajoutMCFact(self,etape,MCFils,listeAvant=()):
+ #----------------------------------------------#
+ # dans le JDC
+ ouChercher=etape
+ for mot in listeAvant :
+ ouChercher=ouChercher.getChild(mot,restreint="oui")
+ monMC=etape.getChild(ouChercher,restreint="oui")
+ if monMC== None : monMC= ouChercher.addEntite(MCFils)
+ monMC.isvalid()
+
+ #-----------------------------------------------------------------#
+ def setValeurMCSimpInEtape(self,etape,listeAvant,valeur):
+ #-----------------------------------------------------------------#
+ # pour VP
+ monObj=etape
+ for mot in listeAvant :
+ monObj=monObj.getChild(mot,restreint="oui")
+ if monObj==None : return False
+ if monObj == None : return False
+ if monObj.valeur != valeur :
+ # PNPN le setValeur fait des bugs --> pourquoi
+ #monObj.setValeur(valeur)
+ monObj.valeur=valeur
+ monObj.isValid()
+ return True
+
+ #-------------------------------------------------#
+ def getValeur(self,nomEtape,MCFils,listeAvant=()):
+ #-------------------------------------------------#
+ # dans le JDC
+
+ debug=0
+ ouChercher=None
+ for e in self.jdc.etapes:
+ if e.nom == nomEtape : ouChercher=e; break
+ if debug : print ('etape trouvee', ouChercher)
+ if ouChercher==None : return None
+ for mot in listeAvant :
+ ouChercher=ouChercher.getChild(mot,restreint="oui")
+ if debug : print (mot, ouChercher)
+ if ouChercher==None : return None
+ monMC=ouChercher.getChild(MCFils,restreint="oui")
+ if debug : print ('monMC', monMC)
+ if monMC== None : return None
+ return monMC.valeur
+
+ #-------------------------------------------------#
+ def getMCDsEtape(self,etape,MCFils,listeAvant=()):
+ #-------------------------------------------------#
+ # dans le JDC
+
+ if etape==None : return None
+ ouChercher=etape
+ debug=0
+ for mot in listeAvant :
+ ouChercher=ouChercher.getChild(mot,restreint="oui")
+ if debug : print (mot, ouChercher)
+ if ouChercher==None : return None
+ monMC=ouChercher.getChild(MCFils,restreint="oui")
+ if debug : print ('monMC', monMC)
+ return monMC
+
+ #-----------------------------------------------------------#
+ def setValeur(self,nomEtape,MCFils,valeur,listeAvant=()):
+ #--------------------------------------------------------#
+ # dans le JDC
+
+ ouChercher=None
+ for e in self.jdc.etapes:
+ if e.nom == nomEtape : ouChercher=e; break
+ if ouChercher==None : return None
+ for mot in listeAvant :
+ ouChercher=ouChercher.getChild(mot,restreint="oui")
+ #print (mot, ouChercher)
+ if ouChercher==None : return None
+ monMC=ouChercher.getChild(MCFils,restreint="oui")
+ monMC.set_valeur(valeur)
+ monMC.isvalid()
+
+ #-----------------------------------------------------------#
+ def changeIntoMC(self,etape,MCFils,valeurs, listeAvant=()):
+ #-----------------------------------------------------------#
+ # dans le JDC
+ ouChercher=etape
+ if isinstance (etape, str):
+ ouChercher=None
+ for e in self.jdc.etapes:
+ if e.nom == etape : ouChercher=e; break
+ if ouChercher==None : return
+
+ for mot in listeAvant :
+ ouChercher=ouChercher.getChild(mot,restreint="oui")
+ if ouChercher==None : return
+ monMC=ouChercher.getChild(MCFils,restreint="oui")
+ if monMC== None : monMC= ouChercher.addEntite(MCFils)
+
+ monMC.definition.into=valeurs
+ from Noyau.N_VALIDATOR import IntoProtocol
+ monMC.definition.intoProto = IntoProtocol("into", into=monMC.definition.into, val_min=monMC.definition.val_min, val_max=monMC.definition.val_max)
+ monMC.state='changed'
+ monMC.isvalid()
+
+ #-------------------------------------------------------------------#
+ def reCalculeValiditeMCApresChgtInto(self,nomEtape,MCFils,listeAvant=()):
+ #-------------------------------------------------------------------#
+ # dans le JDC
+ for e in self.jdc.etapes:
+ if e.nom == nomEtape : ouChercher=e; break
+
+ for mot in listeAvant :
+ try :
+ ouChercher=ouChercher.getChild(mot,restreint="oui")
+ # Le mot clef n est pas la
+ except : return 0
+ try :
+ monMC=ouChercher.getChild(MCFils,restreint="oui")
+ # Le mot clef n est pas la
+ except : return 0
+ if monMC == None : return 0
+
+ if hasattr(monMC.definition,'into') :
+ if type(monMC.definition.into) ==types.FunctionType : maListeDeValeur=monMC.definition.into()
+ else : maListeDeValeur=monMC.definition.into
+ else :
+ return 0
+
+ monMC.state='changed'
+ return 1
+
+ #-------------------------------------#
+ def changeDefautDefMC(self,nomEtape,listeMC,valeurs):
+ #-------------------------------------#
+ # dans le MDD
+
+ #if isinstance (etape, str):
+ # for e in self.jdc.etapes:
+ # if e.nom == etape : etape=e; break
+ #if etape == None : return
+ definitionEtape=getattr(self.jdc.cata,nomEtape)
+ #definitionEtape=getattr(self.jdc.cata[0],nomEtape)
+ ouChercher=definitionEtape
+ if len(listeMC) > 1 :
+
+ for mc in listeMC[0:-1]:
+ mcfact=ouChercher.entites[mc]
+ ouChercher=mcfact
+
+ mcAccas=ouChercher.entites[listeMC[-1]]
+ mcAccas.defaut=valeurs
+ return 1
+
+ #------------------------------------------------#
+ def changeIntoDefMC(self,etape,listeMC,valeurs):
+ #------------------------------------------------#
+ # dans le MDD
+ #definitionEtape=getattr(self.jdc.cata[0],nomEtape)
+ #definitionEtape=getattr(self.jdc.cata,nomEtape)
+ print ( 'changeIntoDefMC ',etape,listeMC,valeurs)
+ ouChercher=getattr(self.jdc.cata,etape.nom)
+
+ #if len(listeMC) > 1 :
+ # for mc in listeMC[0:-1]:
+ # mcfact=ouChercher.entites[mc]
+ # ouChercher=mcfact
+ #mcAccas=ouChercher.entites[listeMC[-1]]
+
+ for mc in listeMC :
+ mcAccas=ouChercher.entites[mc]
+ ouChercher=mcAccas
+ if ouChercher == None : return 0
+
+ if hasattr(mcAccas,'into') : oldValeurs=mcAccas.into
+ else : oldValeurs=None
+
+ if oldValeurs==valeurs : return 1
+ mcAccas.into=valeurs
+ from Noyau.N_VALIDATOR import IntoProtocol
+ mcAccas.intoProto = IntoProtocol("into", into=valeurs, val_min=mcAccas.val_min, val_max=mcAccas.val_max)
+ return 1
+
+ #-------------------------------------------------------------#
+ def deleteDefinitionMC(self,etape,listeAvant,nomDuMC):
+ #-------------------------------------------------------------#
+ # dans le MDD
+ #print 'in deleteDefinitionMC', etape,listeAvant,nomDuMC
+ if isinstance (etape, str):
+ for e in self.jdc.etapes:
+ if e.nom == etape : etape=e; break
+ if etape == None : return
+ #definitionEtape=getattr(self.jdc.cata[0],etape)
+ definitionEtape=getattr(self.jdc.cata,etape)
+ ouChercher=definitionEtape
+ for k in listeAvant :
+ ouChercher=ouChercher.entites[k]
+ MCADetruire=ouChercher.entites[nomDuMC]
+ ouChercher.ordre_mc.remove(nomDuMC)
+ print ('remove de ', nomDuMC)
+ del ouChercher.entites[nomDuMC]
+ del self.dicoNouveauxMC[nomDuMC]
+
+
+ #-------------------------------------------------------------#
+ def ajoutDefinitionMC(self,nomEtape,listeAvant,nomDuMC,typ,**args):
+ #-------------------------------------------------------------#
+ # dans le MDD
+ #definitionEtape=getattr(self.jdc.cata[0],nomEtape)
+ definitionEtape=getattr(self.jdc.cata,nomEtape)
+ ouChercher=definitionEtape
+ for k in listeAvant :
+ ouChercher=ouChercher.entites[k]
+ from Accas import A_SIMP
+ Nouveau=A_SIMP.SIMP(typ,**args)
+ Nouveau.pere=ouChercher
+ Nouveau.nom=nomDuMC
+ #Nouveau.ordre_mc=[]
+ ouChercher.entites[nomDuMC]=Nouveau
+ ouChercher.ordre_mc.append(nomDuMC)
+ #print ('ajout de ', nomDuMC)
+ #traceback.print_stack()
+ # ajout CIST sauvegarde
+ if nomDuMC in self.dicoNouveauxMC : del self.dicoNouveauxMC[nomDuMC]
+ self.dicoNouveauxMC[nomDuMC]=('ajoutDefinitionMC',nomEtape,listeAvant,nomDuMC,typ,args)
+ #print self.dicoNouveauxMC
+
+ #---------------------------------------------------------------------#
+ def ajoutDefinitionMCFact(self,nomEtape,listeAvant,nomDuMC,listeMC,**args):
+ #---------------------------------------------------------------------#
+ # dans le MDD
+ print ('ajoutDefinitionMCFact', nomDuMC)
+ #definitionEtape=getattr(self.jdc.cata[0],nomEtape)
+ definitionEtape=getattr(self.jdc.cata,nomEtape)
+ ouChercher=definitionEtape
+ for k in listeAvant :
+ ouChercher=ouChercher.entites[k]
+ from Accas import A_SIMP
+ for mc in listeMC :
+ nomMC=mc[0]
+ typMC=mc[1]
+ argsMC=mc[2]
+ nouveauMC=A_SIMP.SIMP(typMC,**argsMC)
+ nouveauMC.nom=nomMC
+ args[nomMC]=nouveauMC
+ from Accas import A_FACT
+ nouveauFact=A_FACT.FACT(**args)
+ nouveauFact.pere=ouChercher
+ nouveauFact.nom=nomDuMC
+ from Editeur.autre_analyse_cata import traite_entite
+ traite_entite(nouveauFact,[])
+ ouChercher.entites[nomDuMC]=nouveauFact
+ ouChercher.ordre_mc.append(nomDuMC)
+ self.dicoNouveauxFact[nomDuMC]=('ajoutDefinitionMC',nomEtape,listeAvant,nomDuMC,listeMC,args)
+ #print self.dicoNouveauxMC
+
+ #----------------------------------------------------#
+
+ #----------------------------------------------------#
+ def changeIntoMCandSet(self,etape,listeMC,into,valeurs):
+ #----------------------------------------------------#
+ # dans le MDD et le JDC
+
+ self.changeIntoDefMC(etape,listeMC,into)
+
+ if isinstance (etape, str):
+ for e in self.jdc.etapes:
+ if e.nom == etape : etape=e; break
+ if etape == None : return
+
+ ouChercher = etape
+ for mot in listeMC[:-1] :
+ ouChercher=ouChercher.getChild(mot,restreint="oui")
+ if ouChercher==None : return
+ MCFils=listeMC[-1]
+ monMC=ouChercher.getChild(MCFils,restreint="oui")
+ if monMC== None : monMC= etape.addEntite(MCFils)
+
+ monMC.definition.into=into
+ monMC.valeur=valeurs
+ monMC.val=valeurs
+ monMC.state='changed'
+ monMC.isvalid()
+
+ #-------------------------------------#
+ def ajoutVersionCataDsJDC(self,txt):
+ #-------------------------------------#
+ #if not hasattr(self.readercata.cata[0],'VERSION_CATALOGUE'): return txt
+ if not hasattr(self.readercata.cata,'VERSION_CATALOGUE'): return txt
+ ligneVersion="#VERSION_CATALOGUE:"+self.readercata.cata.VERSION_CATALOGUE+":FIN VERSION_CATALOGUE\n"
+ texte=txt+ligneVersion
+ return texte
+
+ #-------------------------------------#
+ def verifieVersionCataDuJDC(self,text):
+ #-------------------------------------#
+ memeVersion=False
+ indexDeb=text.find("#VERSION_CATALOGUE:")
+ indexFin=text.find(":FIN VERSION_CATALOGUE")
+ if indexDeb < 0 :
+ self.versionCataDuJDC="sans"
+ textJDC=text
+ else :
+ self.versionCataDuJDC=text[indexDeb+19:indexFin]
+ textJDC=text[0:indexDeb]+text[indexFin+23:-1]
+
+ self.versionCata="sans"
+ if hasattr(self.readercata.cata,'VERSION_CATALOGUE'): self.versionCata=self.readercata.cata.VERSION_CATALOGUE
+
+ if self.versionCata==self.versionCataDuJDC : memeVersion=True
+ return memeVersion,textJDC
+
+ #-------------------------------#
+ def traduitCatalogue(self,texte):
+ #-------------------------------#
+ nomTraducteur="traduit"+self.readercata.code+self.versionCataDuJDC+"To"+self.versionCata
+ sys.path.append(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),"../Traducteur")))
+ try :
+ traducteur=__import__(nomTraducteur)
+ monTraducteur=traducteur.MonTraducteur(texte)
+ nouveauTexte=monTraducteur.traduit()
+ return nouveauTexte
+ except :
+ return texte
+
+
+# Methodes a resorber
+# il faut mettre a jour les catalogues avec
+# TEXTE_NEW_JDC
+#
+
+ #---------------------------#
+ def _new_CF(self):
+ #---------------------------#
+ texte="CONDUITE_FORCEE();"
+ return texte
+
+ #---------------------------#
+ def _newPSEN(self):
+ #---------------------------#
+ texte="DIRECTORY() ; PSSE_PARAMETERS() ; SIMULATION() ; sansnom=DISTRIBUTION() ; sansnom=DISTRIBUTION() ; CORRELATION() ;"
+ #texte=""
+ return texte
+
+ #---------------------------#
+ def _newPSEN_N1(self):
+ #---------------------------#
+ texte="CASE_SELECTION();N_PROCESSING_OPTIONS();CONTINGENCY_OPTIONS();CONTINGENCY_SELECTION();\nCONTINGENCY_PROCESSING(); "
+ #texte="CONTINGENCY_SELECTION();\nCONTINGENCY_PROCESSING(); "
+ return texte
+
+ #---------------------------#
+ def _newZCRACKS(self):
+ #---------------------------#
+ texte="MAILLAGES();REMESHING();"
+ return texte
+
+
+ #---------------------------#
+ def _newJDCCND(self):
+ #---------------------------#
+ extensions=tr('Fichiers Med (*.med);;''Tous les Fichiers (*)')
+
+ #if self.salome == 0 :
+ QMessageBox.information( self,
+ tr("Fichier Med"),
+ tr("Veuillez selectionner un fichier Med"))
+ QSfichier = QFileDialog.getOpenFileName(self.appliEficas,
+ caption='Fichier Med',
+ filter=extensions)
+ QSfichier=QSfichier[0]
+ self.fichierMED=QSfichier
+ from acquiertGroupes import getGroupes
+ erreur,self.listeGroupes,self.nomMaillage,self.dicoCoord=getGroupes(self.fichierMED)
+ if erreur != "" : print ("a traiter")
+ texteComm="COMMENTAIRE(u'Cree - fichier : "+self.fichierMED +" - Nom Maillage : "+self.nomMaillage+"');\nPARAMETRES()\n"
+ texteSources=""
+ texteCond=""
+ texteNoCond=""
+ texteVcut=""
+ texteZs=""
+ for groupe in self.listeGroupes :
+ if groupe[0:8]=='CURRENT_':
+ texteSources +=groupe[8:]+"=SOURCE("
+ texteSources +="VecteurDirecteur=(1.0,2.0,3.0,),);\n"
+ if groupe[0:5]=='COND_': texteCond +=groupe[5:]+"=CONDUCTEUR();\n"
+ if groupe[0:7]=='NOCOND_': texteNoCond +=groupe[7:]+"=NOCOND();\n"
+ if groupe[0:5]=='VCUT_': texteVcut +='V_'+groupe[5:]+"=VCUT();\n"
+ if groupe[0:3]=='ZS_': texteZs +=groupe[3:]+"=ZS();\n"
+ texte=texteComm+texteSources+texteCond+texteNoCond+texteVcut+texteZs
+ self.newTexteCND=texte
+ self.modified=1
+ return texte
+
+
+if __name__ == "__main__":
+ print ('a faire')
--- /dev/null
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Copyright (C) 2007-2021 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+
+# Modules Python
+from __future__ import absolute_import
+from __future__ import print_function
+try :
+ from builtins import str
+except : pass
+
+
+import sys,os
+repIni=os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)),".."))
+ihmQTDir=os.path.join(repIni,"UiQT5")
+editeurDir=os.path.join(repIni,"Editeur")
+ihmDir=os.path.join(repIni,"InterfaceQT4")
+
+if ihmDir not in sys.path : sys.path.append(ihmDir)
+if ihmQTDir not in sys.path : sys.path.append(ihmQTDir)
+if editeurDir not in sys.path :sys.path.append(editeurDir)
+
+def getEficasSsIhm(code=None,fichier=None,ssCode=None,multi=False,langue='en',versionCode=None):
+ #print (versionCode)
+ from .qtEficasSsIhm import AppliSsIhm
+ Eficas=AppliSsIhm(code=code,salome=0,ssCode=ssCode,multi=multi,langue=langue,versionCode=versionCode)
+ from Editeur import session
+ options=session.parse(['ssIhm','-k',code,'-v',versionCode])
+ return Eficas
+
+
+def lanceEficas(code=None,fichier=None,ssCode=None,multi=False,langue='en'):
+ """
+ Lance l'appli EFICAS
+ """
+ # Analyse des arguments de la ligne de commande
+ try :
+ from PyQt5.QtWidgets import QApplication
+ except :
+ print('Please, set qt environment')
+ return
+
+ from Editeur import session
+ options=session.parse(sys.argv)
+ if options.code!= None : code=options.code
+ if options.ssCode!= None : ssCode=options.ssCode
+
+ from InterfaceQT4.qtEficas import Appli
+ app = QApplication(sys.argv)
+
+ #import cProfile, pstats, StringIO
+ #pr = cProfile.Profile()
+ #pr.enable()
+
+ Eficas=Appli(code=code,salome=0,ssCode=ssCode,multi=multi,langue=langue)
+ #pr.disable()
+ #s = StringIO.StringIO()
+ #sortby = 'cumulative'
+ #ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
+ #ps.print_stats()
+ #print (s.getValue())
+
+ Eficas.show()
+
+ res=app.exec_()
+ sys.exit(res)
+
+
+def lanceEficas_ssIhm(code=None,fichier=None,ssCode=None,version=None,debug=False,langue='en'):
+ """
+ Lance l'appli EFICAS pour trouver les noms des groupes
+ """
+ # Analyse des arguments de la ligne de commande
+ from Editeur import session
+ options=session.parse(sys.argv)
+ if version!=None and options.cata==None : options.cata=version
+ if fichier==None : fichier=options.comm[0]
+ if code == None : code=options.code
+
+ from .qtEficas import Appli
+ Eficas=Appli(code=code,salome=0,ssCode=ssCode,ssIhm=True,langue=langue)
+
+ from .ssIhm import QWParentSSIhm
+ parent=QWParentSSIhm(code,Eficas,version)
+
+ from . import readercata
+ if not hasattr ( Eficas, 'readercata'):
+ monreadercata = readercata.ReaderCata( parent, Eficas )
+ Eficas.readercata=monreadercata
+
+ from .editor import JDCEditor
+ monEditeur=JDCEditor(Eficas,fichier)
+ return monEditeur
+
+def lanceEficas_ssIhm_chercheGroupes(code=None,fichier=None,ssCode=None,version=None):
+ monEditeur=lanceEficas_ssIhm(code,fichier,ssCode,version)
+ print((monEditeur.chercheGroupes()))
+
+def lanceEficas_ssIhm_cherche_cr(code=None,fichier=None,ssCode=None,version=None):
+ monEditeur=lanceEficas_ssIhm(code,fichier,ssCode,version)
+ print((monEditeur.jdc.cr))
+
+def lanceEficas_ssIhm_reecrit(code=None,fichier=None,ssCode=None,version=None,ou=None,cr=False,debug=False,leger=False,langue='ang'):
+ #print 'lanceEficas_ssIhm_reecrit', fichier
+ monEditeur=lanceEficas_ssIhm(code,fichier,ssCode,version,langue=langue)
+ if ou == None :
+ fileName=fichier.split(".")[0]+"_reecrit.comm"
+ fn=fichier.split(".")[0]+"_cr.txt"
+ else :
+ f=fichier.split(".")[0]+"_reecrit.comm"
+ f1=os.path.basename(f)
+ fn=fichier.split(".")[0]+"_cr.txt"
+ f2=os.path.basename(fn)
+ fileName=os.path.join(ou,f1)
+ fileCr=os.path.join(ou,f2)
+ debut=False
+ if debug :
+ import cProfile, pstats, StringIO
+ pr = cProfile.Profile()
+ pr.enable()
+ monEditeur.saveFileAs(fileName=fileName)
+ pr.disable()
+ s = StringIO.StringIO()
+ sortby = 'cumulative'
+ ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
+ ps.print_stats()
+ print (s.getValue())
+
+ elif not leger : monEditeur.saveFileAs(fileName=fileName)
+ else : monEditeur.saveFileLegerAs(fileName=fileName)
+ if cr:
+ f = open(fileCr, 'w')
+ f.write(str(monEditeur.jdc.report()))
+ f.close()
+
+def lanceEficas_param(code='Adao',fichier=None,version='V0',macro='ASSIMILATION_STUDY'):
+ """
+ Lance l'appli EFICAS pour trouver les noms des groupes
+ """
+ # Analyse des arguments de la ligne de commande
+ from Editeur import session
+ options=session.parse(sys.argv)
+
+ from .qtEficas import Appli
+ #app = QApplication(sys.argv)
+ #Eficas=Appli(code=code,ssCode=None,salome=0)
+
+ from .ssIhm import QWParentSSIhm
+ Eficas=QWParentSSIhm(code,version)
+
+ from . import readercata
+ if not hasattr ( Eficas, 'readercata'):
+ monreadercata = readercata.ReaderCata( parent, Eficas )
+ Eficas.readercata=monreadercata
+
+ from .editor import JDCEditor
+ monEditeur=JDCEditor(Eficas,fichier)
+ texte=loadJDC(fichier)
+ parameters=getJdcParameters(texte,macro)
+ return parameters
+
+#def getEficasSsIhm(code='Adao',versionCode='V0'):
+# from .qtEficasSsIhm import AppliSsIhm
+# Eficas=AppliSsIhm(code=code,ssCode=None,salome=0)
+# return Eficas
+
+def getJdcParameters(jdc,macro):
+ """
+ This function converts the data from the specified macro of the
+ specified jdc text to a python dictionnary whose keys are the
+ names of the data of the macro.
+ """
+ context = {}
+ source = "def args_to_dict(**kwargs): return kwargs \n"
+ source+= "%s = _F = args_to_dict \n"%macro
+ source+= "parameters="+jdc+" \n"
+ source+= "context['parameters'] = parameters \n"
+ code = compile(source, 'file.py', 'exec')
+ eval(code)
+ parameters = context['parameters']
+ return parameters
+
+def loadJDC(filename):
+ """
+ This function loads the text from the specified JdC file. A JdC
+ file is the persistence file of Eficas (*.comm).
+ """
+ fcomm=open(filename,'r')
+ jdc = ""
+ for line in fcomm.readlines():
+ if not (line[0]=='#'):
+ jdc+="%s"%line
+
+ # Warning, we have to make sure that the jdc comes as a simple
+ # string without any extra spaces/newlines
+ return jdc.strip()
+
+def lanceEficas_Web(code=None,fichier=None,ssCode=None,version=None,debug=False,langue='en',multi=False,versionCode=None):
+ from Editeur import session
+ options=session.parse(sys.argv)
+ if version!=None and options.cata == None : options.cata=version
+ if fichier==None and options.comm != [] : fichier=options.comm[0]
+ if code == None : code=options.code
+
+ from .qtEficasSsIhm import AppliSsIhm
+ Eficas=AppliSsIhm(code=code,salome=0,ssCode=ssCode,multi=multi,langue=langue,versionCode=versionCode)
+
+ from .ssIhm import QWParentSSIhm
+ parent=QWParentSSIhm(code,Eficas,version)
+
+ from . import readercata
+ if not hasattr ( Eficas, 'readercata'):
+ monreadercata = readercata.ReaderCata( parent, Eficas )
+ Eficas.readercata=monreadercata
+
+ from .editor import JDCEditor
+ monEditeur=JDCEditor(Eficas,fichier)
+ return monEditeur
+
+
+if __name__ == "__main__":
+ import sys
+ sys.path.insert(0,os.path.abspath(os.path.join(os.getcwd(),'..')))
+ lanceEficas(code=None,fichier=None,ssCode=None,multi=True)
+
+
--- /dev/null
+# -*- coding: utf-8 -*-
+# Copyright (C) 2007-2021 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+# Management of EFICAS version numbering.
+# A version has at least major and minor numbers, for easier comparison.
+
+__version = {
+ 'major': 9,
+ 'minor': 3
+ }
+
+def getEficasVersion():
+ """
+ Return the EFICAS current version number.
+ """
+ return "%s.%s"%(getMajor(),getMinor())
+#
+
+def getSalomeVersion():
+ """
+ Return the SALOME version number to which current EFICAS version is related.
+ """
+ return getEficasVersion()
+#
+
+def getMajor():
+ return __version['major']
+#
+
+def getMinor():
+ return __version['minor']
+#
+
+def getBaseVersion():
+ """
+ Returns [ major, minor ] array of integers.
+ """
+ return [ getMajor(), getMinor() ]
+#
--- /dev/null
+# -*- coding: iso-8859-1 -*-
+# Copyright (C) 2007-2021 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+
+from __future__ import absolute_import
+from __future__ import print_function
+try :
+ from builtins import str
+except : pass
+
+import os, sys
+import six
+
+from Extensions.eficas_exception import EficasException
+from Extensions import param2
+
+from .getVersion import getEficasVersion
+from .viewManagerSsIhm import MyViewManagerSsIhm
+
+
+class AppliSsIhm:
+ """
+ Class implementing the main user interface.
+ """
+ def __init__(self,code=None,salome=1,parent=None,ssCode=None,multi=False,langue='fr',ssIhm=True,versionCode=None):
+ """
+ Constructor
+ """
+ version=getEficasVersion()
+ self.VERSION_EFICAS="Eficas QT5 Salome " + version
+ self.versionCode=versionCode
+
+ self.salome=salome
+ self.ssIhm=True
+ self.code=code
+
+ self.dict_reels={}
+ self.fichierIn=None
+ self.fichierOut=None
+
+ self.recent = []
+ self.ficRecents={}
+ self.mesScripts={}
+ self.listeAEnlever=[]
+ self.ListePathCode=['Adao','ADAO','Carmel3D','Telemac','CF','MAP','ZCracks', 'SEP','SPECA','PSEN_Eficas','PSEN_N1']
+ self.listeCode=['Adao','ADAO','Carmel3D','Telemac','CF','MAP','ZCracks', 'SEP','SPECA','PSEN_Eficas','PSEN_N1']
+ self.repIcon=os.path.join( os.path.dirname(os.path.abspath(__file__)),'..','Editeur','icons')
+
+ if self.salome:
+ import Accas
+ try :
+ import eficasSalome
+ Accas.SalomeEntry = eficasSalome.SalomeEntry
+ except :
+ print ('eficas hors salome')
+
+ self.multi=multi
+ if self.multi :
+ print ('pas de multi sans ihm')
+
+
+ if langue=='fr': self.langue=langue
+ else : self.langue="ang"
+
+ if self.multi == False :
+ self.definitCode(code,ssCode)
+ if code==None: return
+
+ self.suiteTelemac=False
+ self.viewmanager=MyViewManagerSsIhm(self)
+
+
+ def definitCode(self,code,ssCode) :
+ self.code=code
+ self.ssCode=ssCode
+ if self.code == None:return # pour le cancel de la fenetre choix code
+
+ name='prefs_'+self.code
+ prefsCode=__import__(name)
+
+ self.repIni=prefsCode.repIni
+ if ssCode != None :
+ self.format_fichier= ssCode #par defaut
+ prefsCode.NAME_SCHEME=ssCode
+ else :
+ self.format_fichier="python" #par defaut
+
+ nameConf='configuration_'+self.code
+ configuration=__import__(nameConf)
+ self.maConfiguration = configuration.make_config(self,prefsCode.repIni)
+
+ if hasattr (self,'maConfiguration') and self.maConfiguration.translatorFichier :
+ from Extensions import localisation
+ localisation.localise(None,self.langue,translatorFichier=self.maConfiguration.translatorFichier)
+
+
+ def getSource(self,file):
+ # appele par Editeur/session.py
+ import convert
+ p=convert.plugins['python']()
+ p.readfile(file)
+ texte=p.convert('execnoparseur')
+ return texte
+
+
+ def initEditor(self,fichier = None,jdc = None, units = None,include=0):
+ if self.editor != None :
+ print ('un seul editeur par appli')
+ sys.Exit()
+ self.editor = JDCEditorSsIhm(self,fichier, jdc, self.myQtab,units=units,include=include)
+
+
+ def fileNew(self):
+ self.editor=initEditor(self)
+
+ def getEditor(self):
+ return self.editor
+
+ def fileOpen(self,fichier):
+ fichierIn = os.path.abspath(six.text_type(fichier))
+ try:
+ monEditor=self.viewmanager.handleOpen(fichierIn)
+ except EficasException as exc:
+ print ('poum')
+ monEditor=None
+ return monEditor
+
+ def fileSave(self):
+ if self.editor == None : return False
+ ok, newName = editor.saveFileAs()
+ print ('ok, newName ',ok, newName)
+
+ def fileSaveAs(self,fileName):
+ if self.editor == None : return False
+ ok = editor.saveFileAs()
+ print ('ok ',ok)
+
+ def dumpXsd(self):
+ current_cata = CONTEXT.getCurrentCata()
+ current_cata.dumpXsd()
+ if self.maConfiguration.afficheIhm==False : exit()
+
+#,self.fileSaveAs
+#,self.fileClose
+#,self.fileExit
+#,self.jdcRapport
+#,self.jdcRegles
+#,self.jdcFichierSource
+#,self.visuJdcPy
+
+
+
+if __name__=='__main__':
+
+ # Modules Eficas
+ monEficas= AppliSsIhm(code='Adao',salome=0,versionCode='V83')
--- /dev/null
+# -*- coding: utf-8 -*-
+# Copyright (C) 2007-2021 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+"""
+ Ce module sert a lire un catalogue et a construire
+ un objet CataItem pour Eficas.
+ Il s'appuie sur la classe READERCATA
+"""
+# Modules Python
+from __future__ import absolute_import
+from __future__ import print_function
+try :
+ from builtins import str
+ from builtins import object
+except : pass
+
+import os, sys
+
+# Modules Eficas
+from Noyau.N_CR import CR
+from Editeur.catadesc import CatalogDescription
+
+import analyse_catalogue
+import analyse_catalogue_initial
+import autre_analyse_cata
+import uiinfo
+from Extensions.i18n import tr
+from Extensions.eficas_exception import EficasException
+
+
+#-------------------------------
+class ReaderCataCommun(object):
+#-------------------------------
+
+ def askChoixCatalogue(self, cataListeChoix):
+ # ____________________________________________
+ """
+ Ouvre une fenetre de selection du catalogue dans le cas où plusieurs
+ ont ete definis dans Accas/editeur.ini
+ """
+ try :
+ from PyQt5.QtWidgets import QDialog
+ except :
+ print ('Pas de choix interactif sans qt')
+ return
+
+ code = getattr(self.appliEficas.maConfiguration, "code", None)
+ if code != None :
+ title=tr("Choix d une version du code ")+str(code)
+ else :
+ title=tr("Choix d une version ")
+
+ from InterfaceQT4.monChoixCata import MonChoixCata
+ widgetChoix = MonChoixCata(self.appliEficas, [cata.labelCode for cata in cataListeChoix], title)
+ ret=widgetChoix.exec_()
+
+
+ lab=str(self.VERSION_EFICAS)+" "
+ lab+=tr(" pour ")
+ lab+=str(self.code)
+ lab+=tr(" avec le catalogue ")
+ if ret == QDialog.Accepted:
+ cata = cataListeChoix[widgetChoix.CBChoixCata.currentIndex()]
+ self.fichierCata = cata.fichierCata
+ self.labelCode = cata.labelCode
+ self.appliEficas.formatFichierOut = cata.formatFichierOut
+ self.appliEficas.formatFichierIn = cata.formatFichierIn
+ lab+=self.labelCode
+ self.appliEficas.setWindowTitle(lab)
+ widgetChoix.close()
+ else:
+ widgetChoix.close()
+ raise EficasException()
+
+ def choisitCata(self):
+ # ____________________
+
+
+ listeCataPossibles=[]
+ self.Commandes_Ordre_Catalogue=[]
+
+
+ listeTousLesCatas = []
+ for catalogue in self.appliEficas.maConfiguration.catalogues:
+ if isinstance(catalogue, CatalogDescription): listeTousLesCatas.append(catalogue)
+ elif isinstance(catalogue, tuple) : listeTousLesCatas.append(CatalogDescription.createFromTuple(catalogue))
+ else: print(("Catalog description cannot be interpreted: ", catalogue))
+
+ # This filter is only useful for codes that have subcodes (like MAP).
+ # Otherwise, the "code" attribute of the catalog description can (should) be None.
+ if self.ssCode is None: listeCataPossibles = listeTousLesCatas
+ else:
+ for catalogue in listeTousLesCatas:
+ if catalogue.code == self.code and catalogue.ssCode == self.ssCode: listeCataPossibles.append(catalogue)
+
+ # le catalogue est fixe dans la ligne de commande
+ if self.appliEficas.fichierCata != None :
+ trouve=False
+ for catalogue in listeTousLesCatas:
+ if os.path.abspath(catalogue.fichierCata) == (os.path.abspath(self.appliEficas.fichierCata)) :
+ listeCataPossibles=(catalogue,)
+ trouve=True
+ break
+ if not trouve:
+ catalogue=CatalogDescription.createFromTuple((self.code ,self.code,self.appliEficas.fichierCata,'python','python'))
+ listeCataPossibles=(catalogue,)
+
+
+ if len(listeCataPossibles)==0:
+ try :
+ from PyQt5.QtWidgets import QMessageBox, QDialog
+ QMessageBox.critical(self.QWParent, tr("Import du catalogue"),
+ tr("Pas de catalogue defini pour le code ") + self.code)
+ except :
+ print ("Pas de catalogue defini pour le code " + self.code)
+ self.appliEficas.close()
+ if self.appliEficas.salome == 0 : sys.exit(1)
+ return
+
+
+ # le label est fixe dans la ligne de commande
+ if self.labelCode is not None:
+ # La version a ete fixee
+ for cata in listeCataPossibles:
+ if self.labelCode == cata.labelCode:
+ self.fichierCata = cata.fichierCata
+ self.appliEficas.formatFichierIn = cata.formatFichierIn
+ self.appliEficas.formatFichierOut = cata.formatFichierOut
+ else:
+ cataListeChoix = []
+ for cata in listeCataPossibles:
+ if cata.default : cataListeChoix.insert(0, cata)
+ else : cataListeChoix.append(cata)
+
+ if len(cataListeChoix) == 0:
+ try :
+ from PyQt5.QtWidgets import QMessageBox
+ QMessageBox.critical(self.QWParent, tr("Import du catalogue"),
+ tr("Aucun catalogue trouve"))
+ except :
+ print ("Pas de catalogue defini pour le code " + self.code)
+ self.appliEficas.close()
+ if self.appliEficas.salome == 0 : sys.exit(1)
+
+ elif len(cataListeChoix) == 1:
+ self.fichierCata = cataListeChoix[0].fichierCata
+ self.labelCode = cataListeChoix[0].labelCode
+ self.appliEficas.formatFichierOut = cataListeChoix[0].formatFichierOut
+ self.appliEficas.formatFichierIn = cataListeChoix[0].formatFichierIn
+
+ else:
+ # plusieurs catalogues sont disponibles : il faut demander a l'utilisateur
+ # lequel il veut utiliser ...
+ if self.appliEficas.ssIhm :
+ print ('Unable to know which catafile is choosen')
+ exit()
+ self.askChoixCatalogue(cataListeChoix)
+ self.demandeCatalogue=True
+
+ if self.fichierCata == None :
+ if self.appliEficas.salome == 0 :
+ print(("Pas de catalogue pour code %s, version %s" %(self.code,self.labelCode)))
+ sys.exit(1)
+ else :
+ self.appliEficas.close()
+ return
+
+
+#------------------------------------
+class ReaderCata (ReaderCataCommun):
+#------------------------------------
+
+ def __init__(self,QWParent, appliEficas):
+ # _______________________________________
+
+
+ self.QWParent=QWParent
+ self.appliEficas=self.QWParent.appliEficas
+ self.VERSION_EFICAS=self.appliEficas.VERSION_EFICAS
+ self.demandeCatalogue=False
+ self.code=self.appliEficas.code
+ self.ssCode=self.appliEficas.ssCode
+ # on positionne par defaut mais est-ce vraiment necessaire
+ self.appliEficas.formatFichierIn='python'
+ self.appliEficas.formatFichierOut='python'
+ self.labelCode=self.appliEficas.labelCode
+ self.fichierCata=self.appliEficas.fichierCata
+ self.openCata()
+ self.traiteIcones()
+ self.cataitem=None
+ self.creeDicoInverse()
+ if self.code=="TELEMAC": self.creeDicoCasToCata()
+
+
+ def openCata(self):
+ """
+ Ouvre le catalogue standard du code courant, cad le catalogue present
+ dans le repertoire Cata
+ """
+ # import du catalogue
+ self.choisitCata()
+
+ self.cata = self.importCata(self.fichierCata)
+ if self.code == 'NonConnu' : self.code = self.cata.JdC.code
+ modeleMetier = None
+ dicoEltDif = {}
+ if not (self.appliEficas.genereXSD) :
+ if (self.appliEficas.maConfiguration.withXSD or self.appliEficas.withXSD) :
+ try :
+ import pyxb
+ except :
+ self.QWParent.informe('environnement', 'please source pyxb environment')
+ exit()
+ try :
+ nomCataXsd = os.path.splitext(os.path.basename(self.fichierCata))[0]
+ fichierCataTrunc=os.path.splitext(os.path.basename(self.fichierCata))[0]
+ nomCataXsd = fichierCataTrunc+'_driver'
+ pathCata = os.path.dirname(self.fichierCata)+'/raw/'+nomCataXsd+'.py'
+ print ('nomCataXsd , pathCata ',nomCataXsd,pathCata)
+ import imp
+ modeleMetier= imp.load_source(nomCataXsd,pathCata)
+ print ('nomCataXsd , pathCata ',nomCataXsd,pathCata)
+ try :
+ #if 1 :
+ #monObjetAnnotation = getattr(modeleMetier,'PNEFdico_'+self.code)
+ monObjetAnnotation = getattr(modeleMetier,'PNEFdico')
+ texte=monObjetAnnotation.__doc__
+ except :
+ texte=None
+ if texte != None and texte != "":
+ l={}
+ texte='dicoEltDif = '+ texte
+ exec (texte, globals(),l)
+ dicoEltDif=l['dicoEltDif']
+ #print ('dans readerCata _________', dicoEltDif)
+
+ except :
+ if self.appliEficas.ssIhm == False :print ('______________ poum import cata_genere ')
+ self.QWParent.informe('XSD driver', 'unable to load xsd driver',critique=False)
+ modeleMetier = None
+
+ self.cata.DicoNomTypeDifferentNomElt=dicoEltDif
+
+ if hasattr(self.cata, 'implement'): self.cata.JdC.implement = self.cata.implement
+ else : self.cata.JdC.implement = ""
+ if hasattr(self.cata, 'importedBy'): self.cata.JdC.importedBy = self.cata.importedBy
+ else : self.cata.JdC.importedBy = []
+ self.cata.JdC.labelCode = self.labelCode
+ if not(hasattr(self.cata, 'dict_condition')): self.cata.dict_condition = {}
+
+ # pointeur pour le dumpXSD
+ self.cata.JdC.cata=self.cata
+
+ self.cata.modeleMetier = modeleMetier
+ if not self.cata :
+ #try:
+ #from PyQt5.QtWidgets import QMessageBox, QDialog
+ #QMessageBox.critical( self.QWParent, tr("Import du catalogue"),tr("Impossible d'importer le catalogue ")+ self.fichierCata)
+ #except :
+ # print ("Impossible d'importer le catalogue "+ self.fichierCata)
+ self.QWParent.informe("Catalogue","Impossible d'importer le catalogue "+ self.fichierCata)
+ self.appliEficas.close()
+ if self.appliEficas.salome == 0 :
+ sys.exit(1)
+ #
+ # analyse du catalogue (ordre des mots-cles)
+ #
+ # retrouveOrdreCataStandard fait une analyse textuelle du catalogue
+ # remplace par retrouveOrdreCataStandardAutre qui utilise une numerotation
+ # des mots cles a la creation
+ #print (dir(self.cata))
+ self.retrouveOrdreCataStandardAutre()
+ if self.appliEficas.maConfiguration.modeNouvCommande == "initial" : self.retrouveOrdreCataStandard()
+ if hasattr(self.cata, 'Ordre_Des_Commandes') : self.Ordre_Des_Commandes=self.cata.Ordre_Des_Commandes
+ else : self.Ordre_Des_Commandes=None
+
+ if hasattr(self.cata, 'Classement_Commandes_Ds_Arbre') :
+ self.Classement_Commandes_Ds_Arbre=self.cata.Classement_Commandes_Ds_Arbre
+ else : self.Classement_Commandes_Ds_Arbre=()
+ if hasattr(self.cata,'enum'):
+ try :
+ _temp= __import__(self.cata.enum,globals(), locals(), ['DicoEnumCasFrToEnumCasEn', 'TelemacdicoEn'], 0)
+ self.DicoEnumCasFrToEnumCasEn = _temp.DicoEnumCasFrToEnumCasEn
+ self.TelemacdicoEn = _temp.TelemacdicoEn
+ except : pass
+
+ #print self.cata.Ordre_Des_Commandes
+
+ #
+ # analyse des donnees liees l'IHM : UIinfo
+ #
+ uiinfo.traite_UIinfo(self.cata)
+
+ #
+ # traitement des clefs documentaires
+ #
+
+ self.titre=self.VERSION_EFICAS+" "+tr( " avec le catalogue ") + os.path.basename(self.fichierCata)
+ if self.appliEficas.ssIhm == False : self.appliEficas.setWindowTitle(self.titre)
+ self.appliEficas.titre=self.titre
+ self.QWParent.titre=self.titre
+
+
+ def importCata(self,cata):
+ """
+ Realise l'import du catalogue dont le chemin d'acces est donne par cata
+ """
+ nom_cata = os.path.splitext(os.path.basename(cata))[0]
+ rep_cata = os.path.dirname(cata)
+ sys.path[:0] = [rep_cata]
+ self.appliEficas.listeAEnlever.append(rep_cata)
+
+ # PNPNPN pas propre __ A reflechir
+ if 'cata_Vimmp' in list(sys.modules.keys()) :
+ del sys.modules['cata_Vimmp']
+
+ if nom_cata in list(sys.modules.keys()) :
+ del sys.modules[nom_cata]
+
+ for k in sys.modules:
+ if k[0:len(nom_cata)+1] == nom_cata+'.':
+ del sys.modules[k]
+
+ mesScriptsNomFichier='mesScripts_'+self.code.upper()
+ try :
+ self.appliEficas.mesScripts[self.code]=__import__(mesScriptsNomFichier)
+ except:
+ pass
+
+ #if 1 :
+ try :
+ o=__import__(nom_cata)
+ return o
+ except Exception as e:
+ self.QWParent.informe('catalog', 'unable to load catalog file')
+ import traceback
+ traceback.print_exc()
+ return 0
+
+
+
+ def retrouveOrdreCataStandardAutre(self):
+ """
+ Construit une structure de donnees dans le catalogue qui permet
+ a EFICAS de retrouver l'ordre des mots-cles dans le texte du catalogue.
+ Pour chaque entite du catlogue on cree une liste de nom ordre_mc qui
+ contient le nom des mots cles dans le bon ordre
+ """
+ self.cata_ordonne_dico, self.appliEficas.liste_simp_reel=autre_analyse_cata.analyseCatalogue(self.cata)
+ #print ('_________________________________________', self)
+ #print (self.cata_ordonne_dico)
+ #self.appliEficas.liste_simp_reel = ()
+ #self.cata_ordonne_dico = {}
+
+ def retrouveOrdreCataStandard(self):
+ """
+ Retrouve l'ordre des mots-cles dans le catalogue, cad :
+ Attention s appuie sur les commentaires
+ """
+ nom_cata = os.path.splitext(os.path.basename(self.fichierCata))[0]
+ rep_cata = os.path.dirname(self.fichierCata)
+ self.Commandes_Ordre_Catalogue = analyse_catalogue_initial.analyseCatalogue(self.fichierCata)
+ #print self.Commandes_Ordre_Catalogue
+
+ def traiteIcones(self):
+ if self.appliEficas.maConfiguration.ficIcones==None : return
+ try:
+ ficIcones=self.appliEficas.maConfiguration.ficIcones
+ fichierIcones = __import__(ficIcones, globals(), locals(), [], 0)
+ self.appliEficas.maConfiguration.dicoIcones=fichierIcones.dicoDesIcones.dicoIcones
+ self.appliEficas.maConfiguration.dicoImages=fichierIcones.dicoDesIcones.dicoImages
+ except:
+ print ("Pas de fichier associe contenant des liens sur les icones ")
+ self.appliEficas.maConfiguration.dicoIcones={}
+
+
+
+ def creeDicoInverse(self):
+ self.dicoInverse={}
+ self.dicoMC={}
+ listeEtapes=self.cata.JdC.commandes
+ for e in self.cata.JdC.commandes:
+ self.traiteEntite(e)
+
+
+ def creeDicoCasToCata(self):
+ if hasattr(self.cata,'dicoCasEn'):
+ _temp= __import__(self.cata.dicoCasEn,globals(), locals(), ['DicoCasEnToCata'], 0)
+ if self.appliEficas.langue=="ang" :
+ self.dicoCasToCata=_temp.dicoCasEnToCata
+ else :
+ self.dicoCasToCata=_temp.dicoCasFrToCata
+
+
+
+ def traiteEntite(self,e):
+ boolIn=0
+ for (nomFils, fils) in list(e.entites.items()) :
+ self.dicoMC[nomFils]=fils
+ self.traiteEntite(fils)
+ boolIn=1
+ if boolIn==0 :
+ liste=[]
+ moi=e
+ while hasattr(moi,'pere') :
+ liste.append((moi.nom,moi))
+ moi=moi.pere
+ liste.append((moi.nom,moi))
+ self.dicoInverse[e.nom]=liste
+ self.dicoInverse[tr(e.nom)]=liste
+
+ def creeRubrique(self,e,dico, niveau):
+ from Accas import A_BLOC
+ decale=niveau*" "
+ #if niveau != 0 :
+ # if isinstance(e,A_BLOC.BLOC): print decale, e.condition
+ # else : print decale, e. nom
+ for (nom, fils) in list(e.entites.items()) :
+ if list(fils.entites.items()) != [] : self.creeRubrique(fils,dico,niveau+1)
+ #else : print (niveau+1)*" ", nom
+
+
+ #def dumpToXsdEficas(self):
+ # Pas sur qu on ait jamais besoin de cela
+ # pass
+ #from Efi2Xsd import readerEfficas
+ #newSchema= xml = open('Cata_MED_FAM.xml').read()
+ #SchemaMed = efficas.CreateFromDocument(xml)
+ #SchemaMed.alimenteCata(self.cata)
--- /dev/null
+# -*- coding: utf-8 -*-
+# Copyright (C) 2007-2021 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+"""
+ Ce module sert a lire un catalogue et a construire
+ un objet CataItem pour Eficas.
+ Il s'appuie sur la classe READERCATA
+"""
+# Modules Python
+import sys, os
+import autre_analyse_cata
+
+
+# Modules Eficas
+
+from monChoixCata import MonChoixCata
+from Extensions.i18n import tr
+from Extensions.eficas_exception import EficasException
+import uiinfo
+from Efi2Xsd import readerEfiXsd
+# ATtention pas teste depuis le chgt de nom
+
+from readercata import ReaderCataCommun
+
+class ReaderCata (ReaderCataCommun):
+
+ def __init__(self,QWParent, appliEficas):
+ self.QWParent=QWParent
+ self.appliEficas=appliEficas
+ self.VERSION_EFICAS=self.appliEficas.VERSION_EFICAS
+ self.code=self.appliEficas.code
+ self.ssCode=self.appliEficas.ssCode
+ # PN ?? bizarre le 22/04/20
+ self.appliEficas.formatfichierOut='python'
+ self.appliEficas.formatfichierIn ='xml'
+ self.modeNouvCommande=self.appliEficas.maConfiguration.modeNouvCommande
+ self.labelCode=self.appliEficas.labelCode
+ self.version_cata=None
+ self.ficCata=None
+ self.OpenCata()
+ self.cataitem=None
+ self.titre='Eficas XML'
+ self.Ordre_Des_Commandes=None
+ self.Classement_Commandes_Ds_Arbre=()
+ self.demandeCatalogue=False
+
+ #self.traiteIcones()
+ #self.creeDicoInverse()
+
+
+ def OpenCata(self):
+
+ #self.ficCata = 'Cata_MED_FAM.xml'
+ #xml = open('/home/A96028/QT5GitEficasTravail/eficas/Med/Cata_MED_FAM.xml').read()
+ #xml = open('/home/A96028/QT5GitEficasTravail/eficas/CataTestXSD/cata_test1.xml').read()
+ self.choisitCata()
+ xml=open(self.ficCata).read()
+ SchemaMed = readerEfiXsd.efficas.CreateFromDocument(xml)
+ SchemaMed.exploreCata()
+ self.cata=SchemaMed
+ uiinfo.traite_UIinfo(self.cata)
+ self.Commandes_Ordre_Catalogue=[]
+ self.cata_ordonne_dico,self.appliEficas.liste_simp_reel=autre_analyse_cata.analyseCatalogue(self.cata)
+ self.liste_groupes=None
+
+ def dumpToXml(self):
+ # pour compatibilite
+ pass
--- /dev/null
+# -*- coding: utf-8 -*-
+# Copyright (C) 2007-2021 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+
+from __future__ import absolute_import
+try :
+ from builtins import str
+ from builtins import object
+except : pass
+
+import os
+from Extensions.i18n import tr
+import six
+from PyQt5.QtWidgets import QFileDialog, QMessageBox
+from PyQt5.QtCore import QFileInfo
+
+# --------------------------------
+class JdcSsIhmHandler(object):
+# --------------------------------
+# retourne a l utilisateur
+
+ def __init__(self,viewManager):
+# --------------------------------------
+ self.viewManagerSsIhm=viewManager
+
+ def viewJdcPy(self) :
+# ---------------------
+ self.viewManagerSsIhm.handleViewJdcPy(self)
+
+ def viewJdcSource(self) :
+# ---------------------
+ self.viewManagerSsIhm.handleViewJdcSource(self)
+
+ def getFileName(self):
+# ---------------------
+ self.viewManagerSsIhm.getFileName(self)
+
+ def viewJdcRapport(self) :
+# ---------------------
+ self.viewManagerSsIhm.handleViewJdcRapport(self)
+
+ def getJdcRapport(self) :
+# ---------------------
+ return self.viewManagerSsIhm.handleGetJdcRapport(self)
+
+ def getDicoPython(self) :
+# -------------------------
+ return self.viewManagerSsIhm.generDico(self)
+
+ def isJdcValid(self) :
+# -------------------------
+ return self.viewManagerSsIhm.isJdcValid(self)
+
+ def fileSaveAs(self,fileName):
+# -------------------------
+ return self.viewManagerSsIhm.fileSaveAs(self,fileName)
+
+ def fileLegerSaveAs(self,fileName):
+# -----------------------------------
+ return self.viewManagerSsIhm.fileLegerSaveAs(self,fileName)
+
+
+
+#--------------------------------
+class MyViewManagerSsIhm(object):
+#--------------------------------
+# Symetrique de ViewManager mais pas d heritage entre les 2
+# dans le viewManager pas de souci pour savoir qui est le jdc sur lequel on travaille
+# ici en revanche.... c est moins sur
+
+# --------------------------------
+ def __init__(self,appliEficas):
+# --------------------------------
+ self.appliEficas=appliEficas
+ self.tabWidgets = []
+ self.mesIndexes = {}
+ self.dictEditors={}
+ self.untitledCount = 0
+ self.doubles = {}
+
+# ------------------------------------------------------
+ def handleOpen(self,fichier=None, units=None):
+# ------------------------------------------------------
+ result = None
+ if fichier is None:
+ print ('nom de fichier obligatoire')
+ return None
+
+ for handler in self.dictEditors :
+ editor=self.dictEditors[handler]
+ if self.samePath(fichier, editor.getFileName()):
+ print ('fichier deja ouvert . pas de nouvel editor')
+ return handler
+
+ monNewHandler = self.getNewEditor(fichier,units)
+ return monNewHandler
+
+# ----------------------------------------------------------------------
+ def getNewEditor(self,fichier = None,jdc = None, units = None,include=0):
+# ----------------------------------------------------------------------
+
+ from .editorSsIhm import JDCEditorSsIhm
+ editor = JDCEditorSsIhm(self.appliEficas,fichier,jdc, units=units,include=include)
+
+ if editor.jdc: # le fichier est bien un jdc
+ monHandler = JdcSsIhmHandler(self)
+ self.dictEditors[monHandler]=editor
+ return monHandler
+ else:
+ print ('impossible de construire le jdc')
+ return None
+
+# -----------------------------
+ def samePath(self,f1, f2):
+# ------------------------------
+ """
+ compare two paths.
+ """
+ if f1 is None or f2 is None: return 0
+ if os.path.normcase(os.path.normpath(f1)) == os.path.normcase(os.path.normpath(f2)) : return 1
+ return 0
+
+# ---------------------------------
+ def handleViewJdcPy(self,handler):
+# ---------------------------------
+ if not (handler in self.dictEditors) :
+ print ('editor non trouve')
+ return
+ self.dictEditors[handler].viewJdcPy()
+
+# ---------------------------------
+ def getFileName(self,handler):
+# ---------------------------------
+ if not (handler in self.dictEditors) :
+ print ('editor non trouve')
+ return
+ return self.dictEditors[handler].getFileName()
+
+
+# ---------------------------------------------
+ def handleViewJdcSource(self,handler):
+# ---------------------------------------------
+ print (handler)
+ if not (handler in self.dictEditors) :
+ print ('editor non trouve')
+ return
+ self.dictEditors[handler].viewJdcSource()
+
+
+# ---------------------------------------------
+ def handleViewJdcRapport(self,handler):
+# ---------------------------------------------
+ print (handler)
+ if not (handler in self.dictEditors) :
+ print ('editor non trouve')
+ return
+ self.dictEditors[handler].viewJdcRapport()
+
+# ---------------------------------------------
+ def handleGetJdcRapport(self,handler):
+# ---------------------------------------------
+ if not (handler in self.dictEditors) :
+ print ('editor non trouve')
+ return
+ return self.dictEditors[handler].getJdcRapport()
+
+# ---------------------------------------------
+ def handleViewJdcRapport(self,handler):
+# ---------------------------------------------
+ print (handler)
+ if not (handler in self.dictEditors) :
+ print ('editor non trouve')
+ return
+ self.dictEditors[handler].viewJdcRapport()
+
+
+# ---------------------------------------------
+ def generDico(self,handler):
+# ---------------------------------------------
+ print (handler)
+ if not (handler in self.dictEditors) :
+ print ('editor non trouve')
+ return
+ return self.dictEditors[handler].generDico()
+
+
+# ---------------------------------------------
+ def isJdcValid(self,handler):
+# ---------------------------------------------
+ print (handler)
+ if not (handler in self.dictEditors) :
+ print ('editor non trouve')
+ return
+ return self.dictEditors[handler].jdc.isValid()
+
+
+# ---------------------------------------------
+ def fileSaveAs(self,handler,fileName):
+# ---------------------------------------------
+ print (handler)
+ if not (handler in self.dictEditors) :
+ print ('editor non trouve')
+ return
+ return self.dictEditors[handler].saveFile(fileName)
+
+# ---------------------------------------------
+ def fileLegerSaveAs(self, handler,fileName):
+# ---------------------------------------------
+# print (handler)
+ if not (handler in self.dictEditors) :
+ print ('editor non trouve')
+ return
+ self.dictEditors[handler].saveFileLegerAs(fileName)
+
+
+# def handleClose(self,doitSauverRecent = 1,texte=tr('&Quitter')):
+# if doitSauverRecent : self.appliEficas.sauveRecents()
+# index=self.myQtab.currentIndex()
+# if index < 0 : return
+# res=self.checkDirty(self.dict_editors[index],texte)
+# if res == 2 : return 2 # l utilisateur a annule
+# index=self.myQtab.currentIndex()
+# idx=index
+# while idx < len(self.dict_editors) -1 :
+# self.dict_editors[idx]=self.dict_editors[idx+1]
+# idx = idx + 1
+# del self.dict_editors[len (self.dict_editors) -1]
+# try :
+# del self.doubles[self.dict_editors[index]]
+# except :
+# pass
+# self.myQtab.removeTab(index)
+# return res
+#
+
+#
+# def handleCloseAll(self,texte=tr('Quitter')):
+# res=0
+# self.appliEficas.sauveRecents()
+# while len(self.dict_editors) > 0 :
+# self.myQtab.setCurrentIndex(0)
+# res=self.handleClose(0,texte)
+# if res==2 : return res # l utilsateur a annule
+# return res
+#
+#
+#
+# def newEditor(self,include=0):
+# if self.appliEficas.demande==True :
+# self.appliEficas.definitCode(None,None)
+# if self.appliEficas.code == None:return
+# maPage=self.getEditor(include=include)
+#
+
+#
+# def handleViewJdcRegles(self):
+# index=self.myQtab.currentIndex()
+# if index < 0 : return
+# self.dict_editors[index].viewJdcRegles()
+#
+# def handleGestionParam(self):
+# index=self.myQtab.currentIndex()
+# if index < 0 :
+# QMessageBox.warning( self.appliEficas,tr(u"Creation Parametre indisponible"),tr(u"les parametres sont lies a un jeu de donnees"))
+# return
+# self.dict_editors[index].gestionParam()
+#
+#
+#
+# def saveCurrentEditor(self):
+# index=self.myQtab.currentIndex()
+# if index < 0 : return
+# editor=self.dict_editors[index]
+# if editor in self.doubles :
+# QMessageBox.warning(
+# None,
+# tr("Fichier Duplique"),
+# tr("Le fichier ne sera pas sauvegarde."),)
+# return
+# ok, newName = editor.saveFile()
+# if ok :
+# fileName=os.path.basename(six.text_type(newName))
+# self.myQtab.setTabText(index,fileName)
+# return ok
+#
+# def saveLegerCurrentEditor(self):
+# index=self.myQtab.currentIndex()
+# if index < 0 : return
+# editor=self.dict_editors[index]
+# ok, newName = editor.saveFileLeger()
+# return ok
+#
+# def sauveLigneCurrentEditor(self):
+# index=self.myQtab.currentIndex()
+# if index < 0 : return
+# editor=self.dict_editors[index]
+# if editor in self.doubles :
+# QMessageBox.warning(
+# None,
+# tr("Fichier Duplique"),
+# tr("Le fichier ne sera pas sauvegarde."),)
+# return
+# ok, newName = editor.sauveLigneFile()
+# if ok :
+# fileName=os.path.basename(six.text_type(newName))
+# self.myQtab.setTabText(index,fileName)
+# return ok
+#
+#
+# def saveAsCurrentEditor(self):
+# index=self.myQtab.currentIndex()
+# editor=self.dict_editors[index]
+# oldName=editor.fichier
+# ok,newName = editor.saveFileAs()
+# if ok :
+# fileName=os.path.basename(six.text_type(newName))
+# self.myQtab.setTabText(index,fileName)
+# if editor in self.doubles :
+# if oldName != newName :
+# del self.doubles[editor]
+# return ok
+#
+# def displayJDC(self,jdc,fn=None):
+# """
+# Public slot to display a file in an editor.
+# @param fn name of file to be opened
+# # insert filename into list of recently opened files
+# """
+# titre=None
+# if fn != None : titre=fn.split("/")[-1]
+# editor = self.getEditor(fichier= fn, jdc = jdc ,include=1)
+# self.appliEficas.addToRecentList(editor.getFileName())
+#
+
+##PNPNPNPN --> a affiner
+# if fichier is None:
+# self.untitledCount += 1
+# self.myQtab.addTab(win, tr("Fichier non encore nomme ", self.untitledCount))
+# #self.myQtab.addTab(win, str(self.appliEficas.code))
+# else:
+# liste=fichier.split('/')
+# txt = liste[-1]
+# if not QFileInfo(fichier).isWritable():
+# txt = '%s (ro)' % txt
+# self.myQtab.addTab(win,txt )
+# self.myQtab.setCurrentWidget(win)
+# self.currentEditor=win
+# win.setFocus()
+#
+# def getOpenStartDir(self) :
+# #PN --> Les Preferences
+# try :
+# userDir=os.path.expanduser("~/Eficas_install/")
+# return userDir
+# except :
+# return ""
+#
+#
+# def checkDirty(self, editor,texte):
+# """
+# Private method to check dirty status and open a message window.
+#
+# @param editor editor window to check
+# @return flag indicating successful reset of the dirty flag (boolean)
+# """
+# res=1
+# if (editor.modified) and (editor in self.doubles) :
+# msgBox = QMessageBox(None)
+# msgBox.setWindowTitle(tr("Fichier Duplique"))
+# msgBox.setText(tr("Le fichier ne sera pas sauvegarde."))
+# msgBox.addButton(texte,0)
+# msgBox.addButton(tr("&Annuler"),1)
+# res=msgBox.exec_()
+# if res == 0 : return 1
+# return 2
+# if editor.modified:
+# fn = editor.getFileName()
+# if fn is None: fn = tr('Noname')
+# msgBox = QMessageBox(None)
+# msgBox.setWindowTitle(tr("Fichier Modifie"))
+# msgBox.setText(tr("Le fichier ne sera pas sauvegarde."))
+# msgBox.addButton(tr("&Sauvegarder"),1)
+# msgBox.addButton(tr("&Quitter sans sauvegarder"),0)
+# msgBox.addButton(tr("&Annuler"),2)
+# res=msgBox.exec_()
+# if res == 2 : return res
+# if res == 0:
+# (ok, newName) = editor.saveFile()
+# if ok:
+# fileName=os.path.basename(six.text_type(newName))
+# index=self.myQtab.currentIndex()
+# self.myQtab.setTabText(index,fileName)
+# return ok
+# return res
+#
+# def handleAjoutGroup(self,listeGroup):
+# index=self.myQtab.currentIndex()
+# if index < 0 : return
+# editor=self.dict_editors[index]
+# editor.handleAjoutGroup(listeGroup)
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-# Installation de tous les fichiers Python du repertoire et des sous-repertoires (sauf CVS)
-install ( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
- DESTINATION ${CMAKE_INSTALL_PREFIX}
- FILES_MATCHING PATTERN *.py
- PATTERN CVS EXCLUDE
- )
-
-
-### Local Variables:
-### mode: cmake
-### End:
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-# Installation de tous les fichiers Python du repertoire et des sous-repertoires (sauf CVS)
-install ( DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
- DESTINATION ${CMAKE_INSTALL_PREFIX}
- FILES_MATCHING PATTERN *.py
- PATTERN CVS EXCLUDE
- )
-
-
-### Local Variables:
-### mode: cmake
-### End:
--- /dev/null
+# coding: utf-8 -*-
+#
+
+from Accas import *
+
+JdC = JDC_CATA(code='Test1',)
+
+MonProc = PROC(nom='MonProc',
+ param1 = SIMP(statut='o',typ='R'),
+)
+
--- /dev/null
+# Copyright (C) 2007-2021 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+code="Essai"
+import sys, os
+if os.path.dirname(os.path.abspath(__file__)) not in sys.path :
+ sys.path.insert(0,os.path.dirname(os.path.abspath(__file__)))
--- /dev/null
+# -*- coding: utf-8 -*-
+# maConfiguration MANAGEMENT OF EDF VERSION
+# ======================================================================
+# COPYRIGHT (C) 2007-2021 EDF R&D
+# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
+# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
+# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
+# (AT YOUR OPTION) ANY LATER VERSION.
+#
+# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
+# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
+# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
+# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
+#
+# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
+# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
+# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
+#
+#
+# ======================================================================
+
+import os,sys
+# repIni sert a localiser le fichier editeur.ini
+# Obligatoire
+repIni=os.path.dirname(os.path.abspath(__file__))
+INSTALLDIR=os.path.join(repIni,'..')
+sys.path[:0]=[INSTALLDIR]
+
+
+# lang indique la langue utilisee pour les chaines d'aide : fr ou ang
+lang='ang'
+
+# Codage des strings qui accepte les accents (en remplacement de 'ascii')
+encoding='iso-8859-1'
+code = 'Essai'
+
+#
+catalogues=(
+ ('Essai','Essai',os.path.join(repIni,'cata_essai.py'),'python','python'),
+)
--- /dev/null
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Copyright (C) 2007-2021 EDF R&D
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+#
+"""
+ Ce module sert a lancer EFICAS configure pour MAP
+"""
+# Modules Python
+# Modules Eficas
+import prefs
+name='prefs_'+prefs.code
+__import__(name)
+
+import os, sys
+sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)),'..'))
+
+import prefs
+from InterfaceSsIhm import eficas_go
+eficas_go.lanceEficas_Web(code=prefs.code)
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-install ( FILES __init__.py parseur_python.py convert_python.py convert_TELEMAC.py
- convert_map.py
- DESTINATION ${CMAKE_INSTALL_PREFIX}/convert
- )
-
-
-
-
-### Local Variables:
-### mode: cmake
-### End:
+++ /dev/null
-tables.py:tables.tag
- python Translate.py -force tables.tag
+++ /dev/null
-Pour mettre à jour le parser de fichier au format Asterv5, il faut
-recompiler le fichier tables.tag en faisant :
- make
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-#!/bin/env python -d
-#!/tools/net/app/Python-1.5.2/bin/python1.5
-
-"""Translate - a first attempt at parsing my little language
-
-Usage: Translate [switches] <infile> [<outfile>]
-
- -stdout -- write to standard output instead of a file
- -force -- write to the <outfile> even if it already
- exists (overwrite any existing file)
-
- -import -- import tag table from Translate_tags.py,
- instead of using the internal table
-
- -compare -- compare the imported and internal tag tables
- (development option!)
-
- -test -- use our internal test data and write to stdout
- -pytag -- use the interpreted tagging engine
- -debug -- if -pytag, enable its debugger
- -diag -- enable general debugging
- Beware that this currently also writes line
- numbers to the start of each line in the output,
- so it doesn't emit legal Python...
-
- -help -- show this text
- -history -- show the module history
- -version -- show the module version
-
-If <outfile> is not specified, <infile> will be used with its extension
-replaced by ".py".
-"""
-
-__author__ = """Tibs (Tony J Ibbs)
-tony@lsl.co.uk or tibs@tibsnjoan.demon.co.uk or tibs@bigfoot.com
-http://www.tibsnjoan.demon.co.uk/
-"""
-__version__ = "0.3 (tiepin) of 1999-11-15"
-__history__ = """\
-Originally created 1999-08-13
-
-First released version is 0.2 (bootstrap)/1999-09-09, which gave
-an idea of how the thing would work, and nearly did.
-
-Second released version is 0.3 (tiepin)/1999-11-15, which is sufficient
-to allow the parser used within this utility to be written in the little
-language, translated and then used as such.
-"""
-
-import sys
-import os
-import string
-
-# ............................................................
-# How we want to work things - this is fudge for me in initial development
-if os.name == "posix":
- # Unix at work
- DEFAULT_DEBUG = 0
- DEFAULT_PYTAG = 0
-else:
- # Windows 95 at home
- TEXTTOOLS_PATH = "C:\\Program Files\\Python"
- PYTAG_PATH = "C:\\Program Files\\Python\\TextTools\\Examples"
- DEFAULT_DEBUG = 0
- DEFAULT_PYTAG = 0
-
- if TEXTTOOLS_PATH not in sys.path:
- print "Adding",TEXTTOOLS_PATH
- sys.path.append(TEXTTOOLS_PATH)
-
- if PYTAG_PATH not in sys.path:
- print "Adding",PYTAG_PATH
- sys.path.append(PYTAG_PATH)
-# ............................................................
-
-# Import the TextTools themselves
-# - I'm not personally too keen on import *, but it seems to be
-# the recommended thing, so I'll leave it for now...
-try:
- from TextTools import *
-except:
- from mx.TextTools import *
- #from TextTools.Constants.TagTables import *
- #from TextTools.Constants.Sets import *
-
-\f
-# ------------------------------------------------------------
-# Useful little constants for unpicking the parsed tuples
-OBJECT = 0
-LEFT = 1
-RIGHT = 2
-SUBLIST = 3
-
-# We want to align inline comments when possible - so this is
-# the column at which we will try to place their "#" marks...
-COMMENT_COLUMN = 40
-
-# Are we (generally) debugging?
-DEBUGGING = 0
-
-# Do we want a comma after the last tuple (or item) in a table?
-WANT_LAST_COMMA = 1
-
-\f
-# ------------------------------------------------------------
-def define_tagtable():
- """Returns our tag table, if we're not importing it."""
-
- # We are not, initially, going to try for anything very sophisticated
- # - just something that will get us bootstrapped, so that I can use the
- # "little language" to write more sophisticated stuff (without having
- # to worry about dropped commas between tuples, and so on!)
-
-
- # Whitespace is always useful
- t_whitespace = (None,AllIn,' \t')
- t_opt_whitespace = t_whitespace + (+1,)
-
- # Comments are fairly simple
- t_comment = ('comment',Table,
- ((None,Is,'#'),
- (None,AllNotIn,'\n\r',MatchOk))
- )
-
- # We care about the "content" of the indentation at the start of a line,
- # but note that it is optional
- t_indent = ('indent',AllIn,' \t')
- t_indentation = t_indent + (+1,) # zero indentation doesn't show
-
- # A string is text within single or double quotes
- # (of course, this is an oversimplification, because we should also
- # deal with things like "This is a \"substring\"", and it would be
- # nice to be able to cope with triple-quoted strings too, but it
- # will do for a start)
-
- # Major bug - doesn't recognised zero length strings...
- # (since "AllNotIn" must match at least one character)
- t_string = ('str',Table,
- ((None,Is,"'",+3,+1),
- ('text',AllNotIn,"'"),
- (None,Is,"'",MatchFail,MatchOk),
- (None,Is,'"'),
- ('text',AllNotIn,'"'),
- (None,Is,'"'),
- ))
-
- # An integer is a series of digits...
- t_integer = ('int',AllIn,number)
-
- t_signed_integer = ('signed_int',Table,
- (('sign',Is,"+",+1,+2),
- ('sign',Is,"-",+1,+1),
- t_integer
- ))
-
- # Remember to be careful to specify the LONGEST possible match first,
- # so that we try for "IsIn" before we try for "Is" (because "IsIn"
- # would *match* "Is", leaving us with a spurious "In" hanging around...)
- t_operation = ('op',Table,
- (('op',Word,"AllInSet", +1,MatchOk),
- ('op',Word,"AllIn", +1,MatchOk),
- ('op',Word,"AllNotIn", +1,MatchOk),
- ('op',Word,"CallArg", +1,MatchOk),
- ('op',Word,"Call", +1,MatchOk),
- ('op',Word,"EOF", +1,MatchOk),
- ('op',Word,"Fail", +1,MatchOk),
- ('op',Word,"IsInSet", +1,MatchOk),
- ('op',Word,"IsIn", +1,MatchOk),
- ('op',Word,"IsNotIn", +1,MatchOk),
- ('op',Word,"IsNot", +1,MatchOk),
- ('op',Word,"Is", +1,MatchOk),
- ('op',Word,"Jump", +1,MatchOk),
- ('op',Word,"LoopControl",+1,MatchOk),
- ('op',Word,"Loop", +1,MatchOk),
- ('op',Word,"Move", +1,MatchOk),
- ('op',Word,"NoWord", +1,MatchOk), # alias for WordStart
- ('op',Word,"Skip", +1,MatchOk),
- ('op',Word,"SubTableInList",+1,MatchOk),
- ('op',Word,"SubTable", +1,MatchOk),
- ('op',Word,"sFindWord", +1,MatchOk),
- ('op',Word,"sWordStart", +1,MatchOk),
- ('op',Word,"sWordEnd", +1,MatchOk),
- ('op',Word,"TableInList",+1,MatchOk),
- ('op',Word,"Table", +1,MatchOk),
- ('op',Word,"WordStart", +1,MatchOk),
- ('op',Word,"WordEnd", +1,MatchOk),
- ('op',Word,"Word", MatchFail,MatchOk),
- ))
-
- # Python keywords
- t_keyword = ('keyword',Table,
- ((None,Word,"and", +1,+28),
- (None,Word,"assert", +1,+27),
- (None,Word,"break", +1,+26),
- (None,Word,"class", +1,+25),
- (None,Word,"continue",+1,+24),
- (None,Word,"def", +1,+23),
- (None,Word,"del", +1,+22),
- (None,Word,"elif", +1,+21),
- (None,Word,"else", +1,+20),
- (None,Word,"except", +1,+19),
- (None,Word,"exec", +1,+18),
- (None,Word,"finally", +1,+17),
- (None,Word,"for", +1,+16),
- (None,Word,"from", +1,+15),
- (None,Word,"global", +1,+14),
- (None,Word,"if", +1,+13),
- (None,Word,"import", +1,+12),
- (None,Word,"in", +1,+11),
- (None,Word,"is", +1,+10),
- (None,Word,"lambda", +1,+9),
- (None,Word,"not", +1,+8),
- (None,Word,"or", +1,+7),
- (None,Word,"pass", +1,+6),
- (None,Word,"print", +1,+5),
- (None,Word,"raise", +1,+4),
- (None,Word,"return", +1,+3),
- (None,Word,"try", +1,+2),
- (None,Word,"while", MatchFail,+1),
- # In order to not recognise things like "in_THIS_CASE"
- # we must check that the next character is not legitimate
- # within an identifier
- (None,IsIn,alpha+'_'+number,+1,MatchFail),
- # If it wasn't another identifier character, we need to
- # unread it so that it can be recognised as something else
- # (so that, for instance, "else:" is seen as "else" followed
- # by ":")
- (None,Skip,-1)
- ))
-
- # Do the same for mxText commands
- t_mxkeyword = ('mxKeyword',Table,
- (t_operation,
- (None,IsIn,alpha+'_'+number,+1,MatchFail),
- (None,Skip,-1)
- ))
-
- # Traditional identifiers
- t_identifier = ('identifier',Table,
- (t_keyword + (+1,MatchFail), # don't allow Python keywords
- t_mxkeyword + (+1,MatchFail), # don't allow mxText commands
- (None,IsIn,alpha+'_'), # can't start with a digit
- (None,AllIn,alpha+'_'+number,MatchOk))
- )
-
- # We don't yet deal with the following with anything in parentheses,
- # which means we can't handle functions or command lists, or other
- # things which "look like" a tuple
- t_argument = ('arg',Table,
- (('arg',Word,"Here", +1,MatchOk), # EOF Here, Fail Here
- ('arg',Word,"ToEOF", +1,MatchOk), # Move ToEOF
- ('arg',Word,"To", +1,MatchOk), # Jump To
- ('arg',Word,"ThisTable",+1,MatchOk), # [Sub]Table ThisTable
- ('arg',Word,"back", +1,MatchOk), # Skip back
- ('arg',Word,"Break", +1,MatchOk), # LoopControl Break
- ('arg',Word,"Reset", +1,MatchOk), # LoopControl Reset
- t_string + (+1,MatchOk), # e.g., Word "Fred"
- t_signed_integer + (+1,MatchOk), # e.g., Skip -4, Move 3
- t_identifier # e.g., Table Fred
- ))
-
- t_plus = ('plus',Table,
- (t_opt_whitespace,
- (None,Is,"+"),
- t_opt_whitespace
- ))
-
- # Arguments can contain "+"
- t_plus_arg = ('plusarg',Table,
- (t_argument, # start with a single argument
- t_plus + (MatchOk,), # if we have a "+"
- t_argument, # then we expect another argument
- (None,Jump,To,-2), # then look for another "+"
- ))
-
- # Match, for example:
- # <fred>
- t_label = ('label',Table,
- ((None,Is,"<"),
- t_identifier,
- (None,Is,">")
- ))
-
- # Targets for Jump and F:/T:
- t_target = ('target',Table,
- (('tgt',Word,"next", +1,MatchOk),
- ('tgt',Word,"previous", +1,MatchOk),
- ('tgt',Word,"repeat", +1,MatchOk),
- ('tgt',Word,"MatchOk", +1,MatchOk),
- ('tgt',Word,"MatchOK", +1,MatchOk), # For kindness sake
- ('tgt',Word,"MatchFail",+1,MatchOk),
- t_label
- ))
-
- # A value is either an identifier, or a string, or an integer
- t_value = ('val',Table,
- (t_identifier +(+1,MatchOk),
- t_string +(+1,MatchOk),
- t_integer
- ))
-
- # An assignment is (optionally) used in Tuple and Table definitions...
- t_assignment = ('assignment',Table,
- (t_value,
- t_opt_whitespace,
- (None,Is,'='),
- ))
-
- # A common error when writing tuples is to miss off the "=" sign
- # - the following is used in diagnosing that (see t_bad_tuple below)
- # (it's useful to have something with identical structure to the
- # "real thing")
- t_bad_tagobj = ('tagobj',Table,
- (t_string,
- ))
-
- t_bad_assignment = ('assignment',Table,
- (t_value,
- ))
-
- # This is the line that starts the definition of a single tuple.
- # For the moment, restrict what it gets assigned to to a simple identifier.
- # Match, for example:
- # Fred is:
- t_tupleblock = ('tupleblock',Table,
- (t_identifier,
- t_whitespace,
- (None,Word,"is:")
- ))
-
- # This is the line that starts a new table or sub-table.
- # For the moment, we only cope with full Tables.
- # NOTE that this is used for the "outer" declaration of a tag table,
- # and also for the "inner" declaration of an inner table or sub-table.
- # The discrimination between these is done after initial parsing.
- # Match, for example:
- # 'keyword' = Table is: (inner)
- # tagtable = Table is: (outer)
- t_tableblock = ('tableblock',Table,
- (t_assignment + (+2,+1), # left hand side is optional
- t_opt_whitespace,
- ('type',Word,"Table",+1,+2), # Either "Table"
- ('type',Word,"SubTable"), # or "SubTable" is required
- t_whitespace, # whitespace is required
- (None,Word,"is:") # "is:" is required
- ))
-
- # This is the line that starts an "if" block
- # Match, for example:
- # Is "Fred":
- # controlsymbol:
- t_ifblock = ('ifblock',Table,
- (t_assignment + (+2,+1), # left hand side is optional
- t_opt_whitespace,
- t_operation + (+4,+1),
- t_whitespace,
- t_plus_arg,
- (None,Is,":",MatchFail,MatchOk),
- t_identifier,
- (None,Is,":")
- ))
-
- # Note that we don't allow spaces WITHIN our false and true thingies
-
- t_onfalse = ('onfalse',Table,
- (t_whitespace,
- (None,Word,"F:"),
- t_target
- ))
-
- t_ontrue = ('ontrue',Table,
- (t_whitespace,
- (None,Word,"T:"),
- t_target
- ))
-
- # Valid examples are things like:
- # 'fred' = Is "xxx" F:<wow> T:MatchOk
- # AllIn jim T:<foundJim>
- #
- # For the moment, we're not trying to recognise things in any detail
- t_tuple = ('tuple',Table,
- (t_assignment + (+2,+1), # left hand side is optional
- t_opt_whitespace,
- t_operation, # operation is required
- t_whitespace, # for the moment, we always require space here
- t_plus_arg, # argument is required
- t_onfalse + (+1,+1), # F:target is optional
- t_ontrue + (MatchOk,MatchOk) # T:target is also optional
- ))
-
- # If the user has defined a "partial" tuple, they might use something
- # of the form:
- # match_fred F:MatchFalse T:MatchOk
- t_tupleplus = ('tupleplus',Table,
- (t_identifier,
- t_onfalse + (+1,+1), # F:target is optional
- t_ontrue + (MatchOk,MatchOk) # T:target is also optional
- ))
-
- # Treat Jump To specially - for example:
- # Jump To <top>
- # so that they don't have to do the less obvious "Jump To F:<label>"
- # (although that will still be recognised, of course, for people who
- # are used to the tag tuple format itself)
- t_jumpto = ('jumpto',Table,
- ((None,Word,"Jump"),
- t_whitespace,
- (None,Word,"To"),
- t_whitespace,
- t_target
- ))
-
- # Is it worth coping with these?
- t_bad_jumpto = ('jumpto',Table,
- ((None,Word,"Jump",+2), # cope with Jump to
- (None,Word,"to",MatchFail,+2),
- (None,Word,"JumpTo"), # and with JumpTo
- t_target
- ))
-
- # The "content" of a line is the bit after any indentation, and before
- # any comment...
- # For the moment, we won't try to maintain ANY context, so it is up to the
- # user of the tuples produced to see if they make sense...
- t_content = ('content',Table,
- (t_label + (+1,MatchOk),
- t_tableblock + (+1,MatchOk), # [<value> =] [Sub]Table is:
- t_tupleblock + (+1,MatchOk), # <identifier> is:
- t_ifblock + (+1,MatchOk), # <cmd> <arg>: OR <identifier>:
- t_jumpto + (+1,MatchOk), # Jump To <target>
- t_tuple + (+1,MatchOk),
- t_tupleplus + (+1,MatchOk), # name [F:<label> [T:<label>]]
- ))
-
- t_contentline = ('contentline',Table,
- (t_content, # something that we care about
- t_opt_whitespace,
- t_comment +(+1,+1), # always allow a comment
- (None,IsIn,newline) # the end of the line
- ))
-
- # Sometimes, the user (e.g., me) writes:
- # 'fred' = Table:
- # instead of:
- # 'fred' = Table is:
- # Unfortunately, without the "is", it would get too confusing whether
- # we actually wanted an if block...
- t_bad_tableblock = ('tableblock',Table,
- (t_assignment + (+2,+1), # left hand side is optional
- t_opt_whitespace,
- (None,Word,"Table"), # "Table" is required
- (None,Is,":") # "is" is needed before the ":"
- ))
-
- # Sometimes, the use (e.g., me again) write:
- # 'fred' IsIn jim
- # instead of:
- # 'fred' = IsIn jim
- # Whilst I'm not entirely convinced that "=" is the best character
- # to use here, I think we do need something!
- t_bad_tuple = ('tuple',Table,
- (t_bad_assignment, # obviously we have to have this!
- t_whitespace, # in which case the whitespace IS needed
- t_operation, # operation is required
- t_whitespace, # for the moment, we must have space here
- t_plus_arg, # argument is required
- t_onfalse + (+1,+1), # F:target is optional
- t_ontrue + (MatchOk,MatchOk) # T:target is also optional
- ))
-
- # Make some attempt to recognise common errors...
- t_badcontent = ('badcontent',Table,
- (t_bad_tableblock +(+1,MatchOk),
- t_bad_tuple
- ))
-
- t_badline = ('badline',Table,
- (t_badcontent, # something that we sort of care about
- t_opt_whitespace,
- t_comment +(+1,+1), # always allow a comment
- (None,IsIn,newline) # the end of the line
- ))
-
- t_emptyline = ('emptyline',Table,
- (t_opt_whitespace,
- (None,IsIn,newline) # the end of the line
- ))
-
- t_commentline = ('commentline',Table,
- (t_comment,
- (None,IsIn,newline) # the end of the line
- ))
-
- t_passthruline = ('passthruline',Table,
- (('passthru',AllNotIn,newline,+1), # owt else on the line
- (None,IsIn,newline) # the end of the line
- ))
-
- # Basically, a file is a series of lines
- t_line = ('line',Table,
- (t_emptyline +(+1,MatchOk), # empty lines are simple enough
- t_indent +(+1,+1), # optional indentation
- t_commentline +(+1,MatchOk), # always allow a comment
- t_contentline +(+1,MatchOk), # a line we care about
- t_badline +(+1,MatchOk), # a line we think is wrong
- t_passthruline # a line we don't care about
- ))
-
- t_file = (t_line,
- (None,EOF,Here,-1)
- )
-
- return t_file
-
-\f
-# ------------------------------------------------------------
-# We'll define some moderately interesting test data
-
-test_data = """\
-# This example isn't *meant* to make any sense!
-# It's just an accumulation of things that got checked for various reasons
-from TextTools import *
-# Some Python code
-a = b;
-fred = 3;
-if a == 1:
- print "a == 1"
-else:
- print "a != 1"
-
-# And the rest is our business...
-t_integer is:
- 'int' = AllIn '0123456789'
-t_integer is:
- 'int' = AllIn number
-t_indent is:
- # A comment here is OK
- <label> # Strangely enough, so is a label
- 'indent' = AllIn ' \t'
-t_buggy = Table is:
- 'int' AllIn number # BUGGY LINE (missing "=")
- (None,"AllIn",number) # BUGGY LINE (an actual tuple)
- fred = jim # BUGGY LINE (not our business)
- tagobj F:<op> T:next # label <op> is undefined
- # The next line is totally empty
-
- # The next line contains just indentation
-
- # This line is just a comment
-# And this comment should be JUST after the preceding block...
-t_indentation is: # This should be "= Table is:"
- t_indent
- t_indent F:previous
- t_indent T:previous
- t_indent F:previous T:previous
-t_deep = Table is:
- 'a' = SubTable is:
- SubTable is:
- 'this' = Table ThisTable
- t_integer
-t_fred = Table is:
- <top>
- AllIn 'a'
- 'a' = AllIn 'a'
- 'a' = AllIn 'a' F:previous
- 'a' = AllIn 'a' T:previous
- 'a' = AllIn 'a' F:previous T:previous
- AllIn 'abcd':
- AllIn 'xyz' F:<later> T:<top>
- 'a' = AllIn 'abcd':
- AllIn 'xyz'
- <later>
- t_indent:
- AllIn 'xyz'
- AllIn number + '_'
- AllIn number+"_"+alpha
- Jump To <top>
-"""
-
-\f
-# ------------------------------------------------------------
-# Our own exceptions
-
-class OutsideError(Exception):
- """The entity is not permitted outside a block."""
- pass
-
-class IndentError(Exception):
- """An indentation error has been detected."""
- pass
-
-class NoIdentifier(Exception):
- """We're missing an identifier (to assign to)."""
- pass
-
-\f
-# ------------------------------------------------------------
-def LineFactory(lineno,tagtuple,text):
- """Take some tagged data and return an appropriate line class.
-
- lineno -- the line number in the "file". Note that the first line
- in the file is line 1
- tagtuple -- a tag tuple for a single line of data
- text -- the text for the "file". All the "left" and "right" offsets
- are relative to this text (i.e., it is the entire content
- of the file)
-
- The tag tuples we get back from the parser will be of the form:
-
- ('line',left,right,[
- ('indent',left,right,None), -- this is optional
- ('content',left,right,[<data>])
- ])
-
- Looking at <type> should enable us to decide what to do with
- the <data>.
- """
-
- # Extract the list of tuples from this 'line'
- tuples = tagtuple[SUBLIST]
-
- # First off, do we have any indentation?
- tup = tuples[0]
- if tup[OBJECT] == "indent":
- # This is inefficient, because it actually copies strings
- # around - better would be to duplicate the calculation
- # that string.expandtabs does internally...
- indent_str = string.expandtabs(text[tup[LEFT]:tup[RIGHT]])
- tuples = tuples[1:]
- else:
- indent_str = ""
- tuples = tuples
-
- # Now, work out which class we want an instance of
- # (this is the 'fun' bit)
-
- type = tuples[0][OBJECT]
- if type == 'emptyline':
- return EmptyLine(lineno,indent_str,tuples[0],text)
- elif type == 'commentline':
- return CommentLine(lineno,indent_str,tuples[0],text)
- elif type == 'passthruline':
- return PassThruLine(lineno,indent_str,tuples[0],text)
- elif type == 'contentline':
- # OK - we need to go down another level
- sublist = tuples[0][SUBLIST]
-
- # Do we also have an in-line comment?
- if len(sublist) > 1:
- comment = sublist[1]
- else:
- comment = None
-
- # And the actual DATA for our line is down yet another level...
- sublist = sublist[0][SUBLIST]
- type = sublist[0][OBJECT]
- if type == 'label':
- return LabelLine(lineno,indent_str,sublist[0],comment,text)
- elif type == 'tableblock':
- return TableBlockLine(lineno,indent_str,sublist[0],comment,text)
- elif type == 'tupleblock':
- return TupleBlockLine(lineno,indent_str,sublist[0],comment,text)
- elif type == 'ifblock':
- return IfBlockLine(lineno,indent_str,sublist[0],comment,text)
- elif type == 'tuple':
- return TupleLine(lineno,indent_str,sublist[0],comment,text)
- elif type == 'tupleplus':
- return TuplePlusLine(lineno,indent_str,sublist[0],comment,text)
- elif type == 'jumpto':
- return JumpToLine(lineno,indent_str,sublist[0],comment,text)
- else:
- raise ValueError,\
- "Line %d is of unexpected type 'contentline/%s'"%(lineno,
- type)
- elif type == 'badline':
- # OK - we need to go down another level
- sublist = tuples[0][SUBLIST]
-
- # Do we also have an in-line comment?
- if len(sublist) > 1:
- comment = sublist[1]
- else:
- comment = None
-
- # And the actual DATA for our line is down yet another level...
- sublist = sublist[0][SUBLIST]
- type = sublist[0][OBJECT]
- if type == 'tableblock':
- return BadTableBlockLine(lineno,indent_str,sublist[0],comment,text)
- if type == 'tuple':
- return BadTupleLine(lineno,indent_str,sublist[0],comment,text)
- else:
- raise ValueError,\
- "Line %d is of unexpected type 'badline/%s'"%(lineno,type)
- else:
- raise ValueError,"Line %d is of unexpected type '%s'"%(lineno,type)
-
-
-\f
-# ------------------------------------------------------------
-class BaseLine:
- """The base class on which the various line types depend
-
- Contains:
-
- tagtuple -- the tagtuple we (our subclass instance) represent(s)
- lineno -- the line number in the file (first line is line 1)
- indent -- our indentation (integer)
- indent_str -- our indentation (a string of spaces)
- text -- the text of the "file" we're within
- class_name -- the name of the actual class this instance belongs to
- (i.e., the name of the subclass, suitable for printing)
-
- Some things only get useful values after we've been instantiated
-
- next_indent -- the indentation of the next line
- index -- for a line in a block, its index therein
- """
-
- def __init__(self,lineno,indent_str,tagtuple,text):
- """Instantiate a BaseLine.
-
- lineno -- the line number in the "file". Note that the first line
- in the file is line 1
- indent_str -- the indentation of the line (a string of spaces)
- tagtuple -- the tag tuple for this line of data
- text -- the text for the "file". All the "left" and "right"
- offsets are relative to this text (i.e., it is the
- entire content of the file)
-
- The content of the tagtuple depends on which of our subclasses
- is being used. Refer to the relevant doc string.
- """
-
- self.tagtuple = tagtuple
- self.lineno = lineno
- self.text = text
-
- self.class_name = self._class_name()
- self.indent_str = indent_str
- self.indent = len(indent_str)
-
- # OK - we don't really know! (but this will do for "EOF")
- self.next_indent = 0
-
- # We don't always HAVE a sensible value for this
- self.index = None
-
- #if DEBUGGING:
- # print "Line %3d: %s%s"%(lineno,indent_str,self.class_name)
-
- def change_indent(self,count=None,spaces=""):
- """Change our indentation.
-
- Specify either "count" or "spaces" (if both are given,
- "count" will be used, if neither is given, then the
- indentation will be set to zero)
-
- count -- the number of spaces we're indented by
- spaces -- a string of spaces
- """
- if count:
- self.indent = count
- self.indent_str = count * " "
- else:
- self.indent_str = spaces
- self.indent = len(spaces)
-
- def _class_name(self):
- """Return a representation of the class name."""
-
- full_name = "%s"%self.__class__
- bits = string.split(full_name,".")
- return bits[-1]
-
- def starts_block(self):
- """Return true if we start a new block."""
- return 0
-
- def only_in_block(self):
- """Return true if we can only occur inside a block."""
- return 0
-
- def our_business(self):
- """Return true if we are a line we understand."""
- return 1
-
- def __str__(self):
- return "%3d %s%-10s"%(self.lineno,self.indent_str,self.class_name)
-
- def _intro(self):
- """Returns a useful 'introductory' string."""
- return "%3d %-10s %s"%(self.lineno,self.class_name,self.indent_str)
-
- def _trunc(self):
- """Returns a "truncated" representation of our text."""
-
- text = "%s %s"%(self._intro(),
- `self.text[self.tagtuple[LEFT]:self.tagtuple[RIGHT]]`)
-
- if len(text) > 60:
- return text[:60]+"..."
- else:
- return text
-
- def resolve_labels(self,block):
- """Called to resolve any labels use in this line.
-
- block -- the block that contains us
- """
- # The default is to do nothing as we don't HAVE any labels...
- return
-
- def expand(self,stream,block=None):
- """Write out the expanded equivalent of ourselves.
-
- stream -- an object with a "write" method, e.g., a file
- newline -- true if we should output a terminating newline
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
- """
-
- if DEBUGGING:
- stream.write("Line %3d: "%self.lineno)
-
- stream.write(self.indent_str)
- stream.write(self.text[self.tagtuple[LEFT]:self.tagtuple[RIGHT]])
- stream.write(",\n")
-
- def warning(self,text):
- """Report a warning message.
-
- text -- the text to report
- """
-
- lines = string.split(text,"\n")
- print "###WARNING: line %d (%s)"%(self.lineno,self.class_name)
- for line in lines:
- print "### %s"%line
-
- def error(self,text):
- """Report an error.
-
- text -- the error text to report
- """
-
- lines = string.split(text,"\n")
- print "###ERROR: line %d (%s)"%(self.lineno,self.class_name)
- for line in lines:
- print "### %s"%line
-
-\f
-# ------------------------------------------------------------
-class EmptyLine(BaseLine):
- """An empty line.
-
- Note that the indentation of an empty line is taken to be the
- same as that of the next (non-empty) line. This is because it
- seems to me that (a) an empty line should not per-se close a
- block (which it would do if it had indentation 0) and (b) we
- don't remember any whitespace in an empty line, so the user
- can't assign an indentation themselves (which is a Good Thing!)
- """
-
- def __init__(self,lineno,indent_str,tagtuple,text):
- """Instantiate an EmptyLine.
-
- The content of the tagtuple is:
- None
- """
-
- BaseLine.__init__(self,lineno,indent_str,tagtuple,text)
-
- def expand(self,stream,block=None):
- """Write out the expanded equivalent of ourselves.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
- """
-
- if DEBUGGING:
- stream.write("Line %3d: "%self.lineno)
-
- # um - there's nothing to do, folks
- stream.write("\n")
-
- def our_business(self):
- """Return true if we are a line we understand."""
- return 0
-
- def _trunc(self):
- """Returns a "truncated" representation of our text."""
-
- return self._intro()
-
-\f
-# ------------------------------------------------------------
-class CommentLine(BaseLine):
- """A comment line."""
-
- def __init__(self,lineno,indent_str,tagtuple,text):
- """Instantiate a CommentLine.
-
- The content of the tagtuple is:
- ('comment',left,right,None)
- and the demarcated text includes the initial '#' character
- """
-
- BaseLine.__init__(self,lineno,indent_str,tagtuple,text)
-
- # We actually want the next tuple down (so to speak) so that
- # we lose the trailing newline...
- tup = self.tagtuple[SUBLIST][0]
- self.data = self.text[tup[LEFT]:tup[RIGHT]]
-
- def our_business(self):
- """Return true if we are a line we understand."""
- return 0
-
- def expand(self,stream,block=None):
- """Write out the expanded equivalent of ourselves.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
- """
-
- if DEBUGGING:
- stream.write("Line %3d: "%self.lineno)
-
- stream.write(self.indent_str)
- stream.write("%s\n"%self.data)
-
-\f
-# ------------------------------------------------------------
-class PassThruLine(BaseLine):
- """A line we just pass throught without interpretation."""
-
- def __init__(self,lineno,indent_str,tagtuple,text):
- """Instantiate a PassThruLine.
-
- The content of the tagtuple is:
- ('passthru',left,right,None)
- """
-
- BaseLine.__init__(self,lineno,indent_str,tagtuple,text)
-
- # We actually want the next tuple down (so to speak) so that
- # we lose the trailing newline...
- tup = self.tagtuple[SUBLIST][0]
- self.data = self.text[tup[LEFT]:tup[RIGHT]]
-
- def our_business(self):
- """Return true if we are a line we understand."""
- return 0
-
- def expand(self,stream,block=None):
- """Write out the expanded equivalent of ourselves.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
- """
-
- if DEBUGGING:
- stream.write("Line %3d: "%self.lineno)
-
- if block:
- err_str = "Unparsed line inside a block"\
- " - it has been commented out"
- # Hmm - the following advice is less often useful than I
- # had hoped - leave it out for now...
- #if string.find(self.data,",") != -1:
- # err_str = err_str + "\nCheck for a trailing comma?"
-
- self.error(err_str)
-
- # Always output the indentation, 'cos otherwise it looks silly
- stream.write(self.indent_str)
-
- if block:
- stream.write("#[ignored]#")
-
- stream.write("%s\n"%self.data)
-
-\f
-# ------------------------------------------------------------
-class ContentLine(BaseLine):
- """A line we have to interpret - another base class.
-
- Adds the following variables:
-
- comment -- any in-line comment on this line
- """
-
- def __init__(self,lineno,indent_str,tagtuple,comment,text):
- """Instantiate a ContentLine.
-
- comment -- either a comment tuple or None
-
- The content of the tagtuple is:
- ('contentline',left,right,
- [('content',left,right,[<data>]),
- ('comment',left,right,None) -- optional
- ])
- where <data> is used in the internals of one of our subclasses
- (i.e., it is what is passed down in the "tagtuple" argument)
- """
-
- BaseLine.__init__(self,lineno,indent_str,tagtuple,text)
- self.comment = comment
-
- # Assume we're not the last "our business" line in a block...
- self.is_last = 0
-
- def _write_comment(self,stream,sofar):
- """Write out the in-line comment string.
-
- Since we're the only people to call this, we can safely
- rely on it only being called when there IS a comment tuple
- to output...
-
- stream -- an object with a "write" method, e.g., a file
- sofar -- the number of characters written to the line
- so far
- """
- if sofar < COMMENT_COLUMN:
- stream.write(" "*(COMMENT_COLUMN - sofar))
- else:
- # always write at least one space...
- stream.write(" ")
- stream.write(self.text[self.comment[LEFT]:self.comment[RIGHT]])
-
- def _write_text(self,stream,block):
- """Write out the main tuple text.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
-
- This should generally be the method that subclasses override.
- It returns the number of characters written, or -1 if we had
- an error.
- """
- stream.write(self.text[self.tagtuple[LEFT]:self.tagtuple[RIGHT]])
- return self.tagtuple[RIGHT] - self.tagtuple[LEFT]
-
- def expand(self,stream,block=None):
- """Write out the expanded equivalent of ourselves.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
- """
-
- if DEBUGGING:
- stream.write("Line %3d: "%self.lineno)
-
- stream.write(self.indent_str)
- nchars = self._write_text(stream,block)
- # Don't write any in-line comment out if we had an error,
- # as the layout won't work!
- if nchars > -1 and self.comment:
- self._write_comment(stream,sofar=nchars+self.indent)
- stream.write("\n")
-
-\f
-# ------------------------------------------------------------
-class LabelLine(ContentLine):
- """A line containing a label.
-
- Contains:
- label -- our label string
- """
-
- def __init__(self,lineno,indent_str,tagtuple,comment,text):
- """Instantiate a LabelLine.
-
- For instance:
-
- <fred>
-
- The content of the tagtuple is:
-
- ('label',left,right,[
- ('identifier',left,right,None)
- ])
- """
-
- ContentLine.__init__(self,lineno,indent_str,tagtuple,comment,text)
-
- self.label = self.text[self.tagtuple[LEFT]:self.tagtuple[RIGHT]]
-
- def _write_text(self,stream,block):
- """Write out the main tuple text.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
- """
- # Enough difficult length calculation - let's do this one
- # the easy way...
- if DEBUGGING:
- text = "# Label %s at index %d"%(self.label,self.index)
- else:
- text = "# %s"%(self.label) # surely enough for most people...
- stream.write(text)
- return len(text)
-
- def translate(self,index,block):
- """Return the translation of a use of this label as a target.
-
- index -- the index of the line which uses the label as a target
- block -- the Block we are within
- """
-
- # Hmm - I don't think this CAN go wrong at this point...
- return block.translate_label(self.label,self)
-
- def only_in_block(self):
- """Return true if we can only occur inside a block."""
- return 1
-
-\f
-# ------------------------------------------------------------
-class TableBlockLine(ContentLine):
- """A line starting a table block."""
-
- def __init__(self,lineno,indent_str,tagtuple,comment,text):
- """Instantiate a TableBlockLine.
-
- For instance:
-
- "fred" = Table is:
- Table is:
-
- This is used for two purposes:
- 1. To define the actual tag table itself (i.e., at the outer
- level). Only "Table" is allowed in this instance, but since
- that is all we recognised for now, we shan't worry about it...
- 2. To define an inner table (i.e., at an inner level)
-
- The content of the tagtuple is:
-
- ('tableblock',left,right,[
- ('assignment',left,right,[ -- optional if inner
- ('val',left,right,[
-
- ('identifier',left,right,[])
- OR
- ('str',left,right,[
- ('text',left,right,None)
- ])
- OR
- ('int',left,right,[])
-
- ])
- ])
- ('type',left,right,[]) -- either "Table" or "SubTable"
- ])
-
- NOTE: as an "emergency" measure (so we can `pretend' that a
- TupleBlock was actually a TableBlock as part of attempted
- error correction), if tagtuple == ("error",tagobj) then we
- short-circuit some of the initialisation...
- """
-
- ContentLine.__init__(self,lineno,indent_str,tagtuple,comment,text)
-
- if tagtuple[0] == "error":
- # We're "bluffing" at the creation of a TableBlock
- self.tagobj = tagtuple[1]
- self.is_subtable = 0
- elif len(self.tagtuple[SUBLIST]) == 1:
- self.tagobj = "None"
- tup = self.tagtuple[SUBLIST][0]
- self.is_subtable = (self.text[tup[LEFT]:tup[RIGHT]] == "SubTable")
- else:
- # The first tuple down gives us the "<value> = " string
- tup = self.tagtuple[SUBLIST][0]
- # The next tuple down gives us "<value>" which is what we want
- tup = tup[SUBLIST][0]
- self.tagobj = self.text[tup[LEFT]:tup[RIGHT]]
- # Then we have the type of table
- tup = self.tagtuple[SUBLIST][1]
- self.is_subtable = (self.text[tup[LEFT]:tup[RIGHT]] == "SubTable")
-
- def got_tagobj(self):
- return (self.tagobj != "None")
-
- def starts_block(self):
- """Return true if we start a new block."""
- return 1
-
- def _write_text(self,stream,block):
- """Write out the main tuple text.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
-
- It returns the number of characters written, or -1 if we had
- an error.
- """
-
- if block:
- if self.is_subtable:
- stream.write("(%s,SubTable,("%self.tagobj)
- return len(self.tagobj) + 11
- else:
- stream.write("(%s,Table,("%self.tagobj)
- return len(self.tagobj) + 8
- else:
- stream.write("%s = ("%self.tagobj)
- return len(self.tagobj) + 4
-
-\f
-# ------------------------------------------------------------
-class TupleBlockLine(ContentLine):
- """A line starting a tuple block (i.e., defining a single tuple)
-
- Contains:
-
- name -- the "name" of this tuple (i.e., what comes
- before the "is:")
- """
-
- def __init__(self,lineno,indent_str,tagtuple,comment,text):
- """Instantiate a TupleBlockLine.
-
- For instance:
-
- Fred is:
-
- The content of the tagtuple is:
-
- ('tupleblock',left,right,[
- ('identifier',left,right,None)
- ])
- """
-
- ContentLine.__init__(self,lineno,indent_str,tagtuple,comment,text)
-
- tup = self.tagtuple[SUBLIST][0]
- self.name = self.text[tup[LEFT]:tup[RIGHT]]
-
- def starts_block(self):
- """Return true if we start a new block."""
- return 1
-
- def only_in_block(self):
- """Return true if we can only occur inside a block."""
- return 0
-
- def _write_text(self,stream,block):
- """Write out the main tuple text.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
-
- It returns the number of characters written, or -1 if we had
- an error.
- """
- # The "\" at the end is somewhat clumsy looking, but the
- # only obvious way of preserving layout...
- stream.write("%s = \\"%self.name)
- return len(self.name) + 5
-
-\f
-# ------------------------------------------------------------
-class IfBlockLine(ContentLine):
- """A line starting an if block.
-
- Contains:
- cmd -- the command within this if block
- arg -- the argument for said command
- or:
- name -- the name within this if block
- """
-
- def __init__(self,lineno,indent_str,tagtuple,comment,text):
- """Instantiate an IfBlockLine.
-
- For instance:
-
- 'jim' = Is "Fred":
- Is "Fred":
- fred:
-
- The content of the tagtuple is:
-
- ('ifblock',left,right,[
- ('assignment',left,right,[
- ('val',left,right,[
-
- ('identifier',left,right,[])
- OR
- ('str',left,right,[
- ('text',left,right,None)
- ])
- OR
- ('int',left,right,[])
-
- ])
- ])
- ('op',left,right,None),
- ('arg',left,right,None),
- ])
- or:
- ('ifblock',left,right,[
- ('op',left,right,None),
- ('arg',left,right,None),
- ])
- or:
- ('ifblock',left,right,[
- ('identifier',left,right,None)
- ])
- """
-
- ContentLine.__init__(self,lineno,indent_str,tagtuple,comment,text)
-
- tuples = self.tagtuple[SUBLIST]
- if tuples[0][OBJECT] == 'op':
- tup1 = tuples[0]
- tup2 = tuples[1]
- self.tagobj = "None"
- self.cmd = self.text[tup1[LEFT]:tup1[RIGHT]]
- self.arg = self.text[tup2[LEFT]:tup2[RIGHT]]
- self.name = None
- elif tuples[0][OBJECT] == 'assignment':
- # The "<value>" in the "<value> = " string is down
- # one level more than the others
- tup0 = tuples[0][SUBLIST][0]
- self.tagobj = self.text[tup0[LEFT]:tup0[RIGHT]]
- tup1 = tuples[1]
- tup2 = tuples[2]
- self.cmd = self.text[tup1[LEFT]:tup1[RIGHT]]
- self.arg = self.text[tup2[LEFT]:tup2[RIGHT]]
- self.name = None
- elif tuples[0][OBJECT] == 'identifier':
- tup = tuples[0]
- self.name = self.text[tup[LEFT]:tup[RIGHT]]
- self.cmd = None
- self.arg = None
- self.tagobj = None
- else:
- # Hmm - try to continue with anything unexpected
- tup = tuples[0]
- self.error("Unexpected IfBlock subtype %s"%tup[OBJECT])
- self.name = self.text[tup[LEFT]:tup[RIGHT]]
- self.cmd = None
- self.arg = None
- self.tagobj = None
-
- # Currently, we have one 'special' argument
- if self.arg == "back": self.arg = "-1"
-
- # We don't yet know the offset of the "virtual label" at the
- # end of this if block...
- self.end_label = None
-
- def starts_block(self):
- """Return true if we start a new block."""
- return 1
-
- def only_in_block(self):
- """Return true if we can only occur inside a block."""
- return 1
-
- def resolve_labels(self,block):
- """Called to resolve any labels used in this line.
-
- block -- the block that contains us
-
- Note that this only does something the first time it
- is called - this will be when the IF block's startline
- is asked to resolve its labels. If it is called again,
- as a 'normal' line, it will do nothing...
- """
- if not self.end_label:
- self.end_label = "%+d"%(len(block.business)+1)
-
- def _write_text(self,stream,block):
- """Write out the main tuple text.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
-
- It returns the number of characters written, or -1 if we had
- an error.
- """
- if not self.end_label:
- # This should never happen, but just in case, warn the user!
- self.error("Unable to determine 'onFalse' destination in IF")
-
- if self.name:
- stream.write("%s + (%s,+1),"%(self.name,
- self.end_label or "<undefined>"))
- return len(self.name) + 20
- else:
- stream.write("(%s,%s,%s,%s,+1),"%(self.tagobj,self.cmd,self.arg,
- self.end_label or "<undefined>"))
- return len(self.tagobj) + len(self.cmd) + len(self.arg) + \
- len(self.end_label) + 20
-
-\f
-# ------------------------------------------------------------
-class TupleLine(ContentLine):
- """A line containing a basic tuple.
-
-
- Contains:
- tagobj -- optional
- cmd -- the command
- arg -- the argument
- ontrue -- what to do if true
- onfalse -- ditto false
- """
-
- def __init__(self,lineno,indent_str,tagtuple,comment,text):
- """Instantiate a TupleLine.
-
- The content of the tagtuple is:
-
- ('tuple',left,right,[
- ('tagobj',left,right,[ -- optional
- ('str',left,right,[
- ('text',left,right,None)
- ])
- ])
- ('op',left,right,None),
- ('arg',left,right,None),
- ('onfalse',left,right,[ -- optional
- ('target',left,right,[
- ('tgt',left,right,None)
- ]),
- ('ontrue',left,right,[ -- optional
- ('target',left,right,[
- ('tgt',left,right,None)
- ])
- ])
- ])
- """
-
- ContentLine.__init__(self,lineno,indent_str,tagtuple,comment,text)
-
- self.unpack()
-
-
- def unpack(self):
- """Unpack our contents from our tagtuple."""
-
- # This is doubtless not the most efficient way of doing this,
- # but it IS relatively simple...
- dict = {}
- #for key in ("assignment","op","arg","onfalse","ontrue"):
- for key in ("assignment","op","plusarg","onfalse","ontrue"):
- dict[key] = None
-
- tuples = self.tagtuple[SUBLIST]
- for item in tuples:
- name = item[OBJECT]
- if name == "onfalse" or name == "ontrue" or name == "assignment":
- # For these, we need to go "down one level" for our data
- tup = item[SUBLIST][0]
- dict[name] = (tup[LEFT],tup[RIGHT])
- else:
- dict[name] = (item[LEFT],item[RIGHT])
-
- # The tag object is optional
- if dict["assignment"]:
- left,right = dict["assignment"]
- self.tagobj = self.text[left:right]
- else:
- self.tagobj = "None"
-
- # The operation (command) and argument are required
- left,right = dict["op"]
- self.cmd = self.text[left:right]
-
- #left,right = dict["arg"]
- left,right = dict["plusarg"]
- self.arg = self.text[left:right]
-
- # Currently, we have one 'special' argument
- if self.arg == "back": self.arg = "-1"
-
- # Actually, we don't want the F and T jumps explicit if not
- # given, since we mustn't output them for a single tuple if
- # they're not given (so they can be "added in" later on)
- if dict["onfalse"]:
- left,right = dict["onfalse"]
- self.onfalse = self.text[left:right]
- else:
- self.onfalse = None # "MatchFail"
- if dict["ontrue"]:
- left,right = dict["ontrue"]
- self.ontrue = self.text[left:right]
- else:
- self.ontrue = None # "next"
-
- def only_in_block(self):
- """Return true if we can only occur inside a block."""
- return 1
-
- def resolve_labels(self,block):
- """Called to resolve any labels use in this line.
-
- block -- the block that contains us
- """
- if self.onfalse:
- self.onfalse = block.translate_label(self.onfalse,self)
- if self.ontrue:
- self.ontrue = block.translate_label(self.ontrue,self)
-
- def _write_text(self,stream,block):
- """Write out the main tuple text.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
-
- It returns the number of characters written, or -1 if we had
- an error.
- """
-
- # Start with the stuff we must have...
- stream.write("(%s,%s,%s"%(self.tagobj,self.cmd,self.arg))
- length = len(self.tagobj) + len(self.cmd) + len(self.arg) + 3
-
- if self.ontrue:
- if not self.onfalse:
- # OK, we didn't get an explicit F, but because it comes
- # before the T jump in the tuple, we need to fake it
- # anyway...
- stream.write(",%s,%s)"%("MatchFail",self.ontrue))
- length = length + len("MatchFail") + len(self.ontrue) + 3
- else:
- # We had both F and T
- stream.write(",%s,%s)"%(self.onfalse,self.ontrue))
- length = length + len(self.onfalse) + len(self.ontrue) + 3
- elif self.onfalse:
- # We only had F. We shan't "fake" the T jump, *just* in case
- # the user is defining a single tuple that they'll add the
- # T jump to later on (although that *is* a bit dodgy, I think)
- # [[The option would be to "fake" it if we're IN a block - I may
- # go for that approach later on]]
- stream.write(",%s)"%self.onfalse)
- length = length + len(self.onfalse) + 2
- else:
- # Neither F nor T - so don't write the defaults for either,
- # in case this is a top level tuple they're going to add to
- # later on...
- # [[Comments as for the case above, I think]]
- stream.write(")")
- length = length + 1
-
- if block and not self.is_last:
- stream.write(",")
- length = length + 1
-
- return length
-\f
-# ------------------------------------------------------------
-class TuplePlusLine(ContentLine):
- """A line containing a tuple "plus" (e.g., "fred + (+1,+1)").
-
- Contains:
-
- name -- the name/identifier
- ontrue -- what to do if true
- onfalse -- ditto false
- """
-
- def __init__(self,lineno,indent_str,tagtuple,comment,text):
- """Instantiate a TuplePlusLine.
-
- <identifier> + (onF,onT)
-
- The content of the tagtuple is:
-
- ('tupleplus',left,right,[
- ('identifier',left,right,None)
- ('onfalse',left,right,[ -- optional
- ('target',left,right,[
- ('tgt',left,right,None)
- ]),
- ('ontrue',left,right,[ -- optional
- ('target',left,right,[
- ('tgt',left,right,None)
- ])
- ])
- ])
- """
-
- ContentLine.__init__(self,lineno,indent_str,tagtuple,comment,text)
-
- self.unpack()
-
-
- def unpack(self):
- """Unpack our contents from our tagtuple."""
-
- # This is doubtless not the most efficient way of doing this,
- # but it IS relatively simple...
- dict = {}
- for key in ("identifier","onfalse","ontrue"):
- dict[key] = None
-
- tuples = self.tagtuple[SUBLIST]
- for item in tuples:
- name = item[OBJECT]
- if name == "onfalse" or name == "ontrue":
- # For these, we need to go "down one level" for our data
- tup = item[SUBLIST][0]
- dict[name] = (tup[LEFT],tup[RIGHT])
- else:
- dict[name] = (item[LEFT],item[RIGHT])
-
- # Start with the identifier
- left,right = dict["identifier"]
- self.name = self.text[left:right]
-
- # Actually, we don't want the F and T jumps explicit if not
- # given, since we mustn't output them for a single tuple if
- # they're not given (so they can be "added in" later on)
- if dict["onfalse"]:
- left,right = dict["onfalse"]
- self.onfalse = self.text[left:right]
- else:
- self.onfalse = None # "MatchFail"
- if dict["ontrue"]:
- left,right = dict["ontrue"]
- self.ontrue = self.text[left:right]
- else:
- self.ontrue = None # "next"
-
- def only_in_block(self):
- """Return true if we can only occur inside a block."""
- return 1
-
- def resolve_labels(self,block):
- """Called to resolve any labels use in this line.
-
- block -- the block that contains us
- """
- if self.onfalse:
- self.onfalse = block.translate_label(self.onfalse,self)
- if self.ontrue:
- self.ontrue = block.translate_label(self.ontrue,self)
-
- def _write_text(self,stream,block):
- """Write out the main tuple text.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
-
- It returns the number of characters written, or -1 if we had
- an error.
- """
-
- if not self.onfalse and not self.ontrue:
- stream.write("%s"%self.name)
- length = len(self.name)
- else:
- # Make a feeble attempt to cause successive such lines to
- # look neater, by aligning the "+" signs (if we output them)
- stream.write("%-15s + ("%(self.name))
- length = max(len(self.name),15) + 4
- if self.ontrue and self.onfalse:
- stream.write("%s,%s)"%(self.onfalse,self.ontrue))
- length = length + len(self.onfalse) + len(self.ontrue) + 2
- elif self.ontrue:
- stream.write("MatchFail,%s)"%(self.ontrue))
- length = length + len(self.ontrue) + 11
- else:
- # Don't forget that comma to make this a tuple!
- stream.write("%s,)"%(self.onfalse))
- length = length + len(self.onfalse) + 1
-
- if not self.is_last:
- stream.write(",")
- length = length + 1
-
- return length
-
-\f
-# ------------------------------------------------------------
-class JumpToLine(ContentLine):
- """A line containing "Jump To <label>"
-
- Contains:
-
- name -- the name/identifier
- onfalse -- the target (which is technically an "on false" jump)
- """
-
- def __init__(self,lineno,indent_str,tagtuple,comment,text):
- """Instantiate a JumpLine.
-
- Jump To <label>
-
- The content of the tagtuple is:
-
- ('jumpto',left,right,[
- ('target',left,right,[
- ('tgt',left,right,None)
- ]),
- ])
- """
-
- ContentLine.__init__(self,lineno,indent_str,tagtuple,comment,text)
-
- tup = self.tagtuple[SUBLIST][0]
- self.onfalse = self.text[tup[LEFT]:tup[RIGHT]]
-
- def only_in_block(self):
- """Return true if we can only occur inside a block."""
- return 1
-
- def resolve_labels(self,block):
- """Called to resolve any labels use in this line.
-
- block -- the block that contains us
- """
- self.onfalse = block.translate_label(self.onfalse,self)
-
- def _write_text(self,stream,block):
- """Write out the main tuple text.
-
- stream -- an object with a "write" method, e.g., a file
- block -- used to pass the containing Block down to lines
- within a block, or None if we're not in a block
-
- It returns the number of characters written, or -1 if we had
- an error.
- """
-
- stream.write("(None,Jump,To,%s)"%(self.onfalse))
- length = len(self.onfalse) + 15
-
- if not self.is_last:
- stream.write(",")
- length = length + 1
-
- return length
-
-\f
-# ------------------------------------------------------------
-class BadTableBlockLine(TableBlockLine):
- """We think they MEANT this to be a table block line."""
-
- def __init__(self,lineno,indent_str,tagtuple,comment,text):
- """Instantiate a BadTableBlockLine.
-
- For instance:
-
- "fred" = Table:
- Table:
- """
- TableBlockLine.__init__(self,lineno,indent_str,tagtuple,comment,text)
- self.error("Suspected missing 'is' before the colon\n"
- "pretending it's there")
-
-\f
-# ------------------------------------------------------------
-class BadTupleLine(TupleLine):
- """We think they MEANT this to be a tuple line."""
-
- def __init__(self,lineno,indent_str,tagtuple,comment,text):
- """Instantiate a BadTupleLine.
-
- For instance:
-
- "fred" = IsIn "abc"
- """
- TupleLine.__init__(self,lineno,indent_str,tagtuple,comment,text)
- self.error("Suspected missing '=' between tag object and command\n"
- "pretending it's there")
-
-\f
-# ------------------------------------------------------------
-class Block(ContentLine):
- """This class represents a "block".
-
- A "block" is a section of code which starts with a line ending in
- a colon (":"), with the next line and subsequent lines ("in" the
- block) having an extra indent. The block ends when a dedent is
- encountered.
-
- Each instance "eats" lines from the input until (if) it finds the first
- "sub" block. That then "eats" lines until it finds its own end, and
- then hands control back to the first instance, which does the same thing
- again, and so on.
-
- Note that we "pretend" to be a content line - it is convenient to
- look like a line class, so that line processing can cope with us,
- and indeed what we do is "pretend" to be a clone of our start line
- with some extra information...
-
- Contains:
- startline -- the line that "introduces" this block
- items -- a list of the lines and blocks within this block
- label_dict -- a dictionary of {label name : line index}
- inner_indent -- the indentation of our "inner" lines
- outer -- true if we are an "outer" block
- (i.e., not contained within another block)
- """
-
- def __init__(self,startline=None,outer=0,file=None):
- """Instantiate a new block.
-
- startline -- the line that introduces this block
- outer -- true if we are an outer block
- file -- the "file" we're reading lines from
- """
-
- # Pretend to be our own startline (as a generic)
- ContentLine.__init__(self,
- startline.lineno,startline.indent_str,
- startline.tagtuple,startline.comment,
- startline.text)
-
- # But also remember the specifics of the startline
- self.startline = startline
-
- # We "fudge" our class name
- self.class_name = self._block_class_name(startline)
-
- self.outer = outer
- self.file = file
-
- # If we're an outer table block, do we have a tagobj?
- if self.startline.class_name == "TableBlockLine" and outer:
- if not self.startline.got_tagobj():
- raise NoIdentifier,\
- "Tag table at line %d is not assigned to a variable"%\
- (self.lineno)
- elif self.startline.is_subtable:
- raise OutsideError,\
- "SubTable is not allowed outside a block at line %d"%\
- (self.lineno)
-
- self.items = [] # all lines within this block
- self.business = [] # just those that are "our business"
- self.label_dict = {} # remember our labels and their locations
- self.next_index = 0 # 'business' line indices
- self.inner_indent = None
-
- # Eat lines until we reach the end of our block...
- if DEBUGGING: print "%sStart %s"%(self.indent_str,self.class_name)
- self._eat_lines()
- self._end_block()
-
- def _block_class_name(self,startline):
- """Return a representation of the class name."""
-
- full_name = "%s"%self.__class__
- bits = string.split(full_name,".")
- return "%s/%s"%(bits[-1],startline.class_name)
-
- def _eat_lines(self):
- """Eat lines until we run out of block..."""
-
- while 1:
- try:
- nextline = self.file.next()
- except EOFError:
- return
-
- # Check the indentation makes sense...
- if self.inner_indent:
- # We already know how much our block is indented
- # - is this line part of the block?
- if nextline.indent < self.inner_indent:
- # Apparently a dedent - is it what we expect?
- if nextline.indent <= self.indent:
- # Unread that line - it isn't one of ours!
- self.file.unget()
- return
- else:
- raise IndentError,\
- "Line %d (%s) is indented less than the previous "\
- "line, but its indentation doesn't match the "\
- "start of the block at line %d"%\
- (nextline.lineno,nextline.class_name,self.lineno)
- elif nextline.indent > self.inner_indent:
- # A spurious indent
- # (note that doing this stops us from coping with,
- # for instance, things in (..), but then we also don't
- # cope with any form of continued line, or lots of other
- # things, so let's not worry too much for now!)
- raise IndentError,\
- "Line %d (%s) is indented more than the previous line"%\
- (nextline.lineno,nextline.class_name)
- else:
- # This is the first line of the (inside of) the block
- # - check its indentation makes sense...
- self.inner_indent = nextline.indent
- if self.inner_indent <= self.indent:
- raise IndentError,\
- "Line %d (%s) should be indented more than line %d (%s)"%\
- (nextline.lineno,nextline.class_name,
- self.lineno,self.startline.class_name)
-
- # Is it a line or the start of another block?
- if nextline.starts_block():
- # Heh - it's the start of an inner block - add it
- # (remember that instantiating it causes it to
- # "eat" the lines that belong to it)
- self.items.append(Block(startline=nextline,
- outer=0,file=self.file))
- else:
- self.items.append(nextline)
-
- def _end_block(self):
- """End our block"""
-
- if DEBUGGING: print "%sEnd %s"%(self.indent_str,self.class_name)
-
- # If we're a tuple block, we should only have one line...
- # (that is, one "business" line)
- if self.startline.class_name == "TupleBlockLine" and \
- len(self.items) > 1:
- # Are all but one of them not "our business"?
- count = 0
- for item in self.items:
- if item.our_business():
- count = count + 1
- if count > 1: break
- if count > 1:
- self.error("Tuple declaration can only contain one 'business'"
- " line, not %d\n"
- "Assuming it's a table instead (i.e.,"
- "'Table is:' instead of 'is:')"%len(self.items))
- # Can we correct this by "pretending" its a table?
- temp = TableBlockLine(self.startline.lineno,
- self.startline.indent_str,
- ("error",self.startline.name),
- self.startline.comment,
- self.text)
- self.startline = temp
-
- # We've now got all of our lines, and so we can go back over
- # them, expanding out any IF blocks (whose content is actually
- # within this block's scope, so who need to have their labels
- # (come from or go to) in that scope), working out the label
- # indices, and so on...
- # This uses "next_index" to calculate the indices of business
- # lines (needed for label calculation), and also populates the
- # "business" list with just the items that are "our_business()"
- if DEBUGGING:
- print "Expanding IF blocks, sorting out labels, etc."
-
- temp = self.items
- self.items = []
- for item in temp:
- if item.class_name == "Block/IfBlockLine":
- self._add(item.startline)
- for thing in item.items:
- self._add(thing)
- else:
- self._add(item)
-
- # Go back through our contents and resolve any labels
- if DEBUGGING:
- print "%s...processing labels (next_index=%d)"%(self.indent_str,
- self.next_index)
- self.startline.resolve_labels(self)
- # If we're an IF block, we mustn't try to resolve our component
- # lines' labels, as they're actually in our parent block's scope...
- if self.startline.class_name != "IfBlockLine":
- for item in self.items:
- item.resolve_labels(self)
-
- # If we're in a block that wants to suppress the comma at the
- # end of the last item in that block, tell the last item so...
- # (this is debatable for [Bad]TableBlockLine - it might be
- # better to leave the last comma there - so we have an option
- # to determine it...
- if self.startline.class_name == "TupleBlockLine" or \
- (not WANT_LAST_COMMA and \
- (self.startline.class_name == "TableBlockLine" or \
- self.startline.class_name == "BadTableBlockLine")):
- if len(self.business) > 0:
- self.business[-1].is_last = 1
-
- def _add(self,item):
- """Add a line or block to our list of items.
-
- item -- the Line or Block instance to add
-
- NB: Also adds it to our "business" list if it is our business
- (and not a label)
- """
-
- if item.class_name == "LabelLine":
- self.label_dict[item.label] = self.next_index
- if DEBUGGING:
- print "%sadd [%2d] %s"%(item.indent_str,self.next_index,item)
- # Might as well give it the index it is labelling
- item.index = self.next_index
- self.items.append(item)
- elif item.our_business():
- item.index = self.next_index
- self.items.append(item)
- self.business.append(item)
- if DEBUGGING:
- print "%sadd %2d %s"%(item.indent_str,
- self.next_index,item)
- self.next_index = self.next_index + 1
- else:
- # It's not something we can assign a sensible index to, so don't
- if DEBUGGING:
- print "%sadd xx %s"%(item.indent_str,item)
- self.items.append(item)
-
- def translate_label(self,label,line):
- """Given a label, return its translation.
-
- label -- either a string of the form "<...>" to look up in
- this block's label dictionary, or one of the special
- targets (e.g., next, MatchOk, etc.)
- line -- the line using this label
-
- Reports an error and just returns the original "label" if it
- can't translate it.
- """
- if self.label_dict.has_key(label):
- # How far do we have to jump?
- offset = self.label_dict[label] - line.index
- return "%+d"%offset
- elif label == "MatchOk":
- return "MatchOk"
- elif label == "MatchOK":
- line.warning("Label 'MatchOK' should be spelt 'MatchOk'"
- " (using 'MatchOk')")
- return "MatchOk"
- elif label == "MatchFail":
- return "MatchFail"
- elif label == "next":
- return "+1"
- elif label == "previous":
- return "-1"
- elif label == "repeat":
- return "0"
- else:
- line.error("Undefined label '%s'"%label)
- return label
-
- def expand(self,stream,block=None):
- """Write out the expanded equivalent of ourselves.
-
- stream -- an object with a "write" method, e.g., a file
- block -- if we're in a block, this is it, otherwise None
- """
-
- self.startline.expand(stream,block=block)
- for item in self.items[:-1]:
- item.expand(stream,block=self)
-
- self.items[-1].expand(stream,block=self)
-
- # Deal with closing any block parentheses
- if self.startline.class_name == "TableBlockLine" or \
- self.startline.class_name == "BadTableBlockLine":
- if DEBUGGING:
- stream.write("Line ...: ")
-
- stream.write(self.indent_str)
- if self.outer:
- # Outer block - just close it
- stream.write(")")
- else:
- # Inner block is a Table block, and we need to close both
- # the tuple-of-tuples, and also the tuple containing the
- # Table command...
- stream.write("))")
- if not self.is_last:
- stream.write(",")
- stream.write("\n")
-
-\f
-# ------------------------------------------------------------
-class File:
- """This is the class that holds our processed data
-
- Contains:
- lines -- a list of the line instances for each "line" in our text
- items -- a list of lines and BLOCKs
- """
-
- def __init__(self,tagtuples,text):
- """Instantiate a File
-
- tagtuples -- the list of mxTextTools tag tuples generated by
- parsing the data in "text"
- text -- the text we parsed
- """
-
- self.text = text
- self.tagtuples = tagtuples
-
- # Assemble our list of lines
- print "Pass 1: assembling lines"
- if DEBUGGING: print "~~~~~~~~~~~~~~~~~~~~~~~~"
- self.lines = []
- lineno = 0
- prevline = None
- for tagtuple in tagtuples:
- lineno = lineno + 1
- thisline = LineFactory(lineno,tagtuple,text)
-
- if prevline:
- prevline.next_indent = thisline.indent
-
- self.lines.append(thisline)
- prevline = thisline
-
- #if DEBUGGING: print
-
- # The indentation of an empty line is taken to be the same
- # as the indentation of the first following non-empty line
- # The easiest way to do that is to work backwards through
- # the list (is it better to take a copy and reverse THAT,
- # or to reverse our original list twice?)
- print "Pass 2: sorting out indentation of empty lines"
- if DEBUGGING: print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
- revlist = self.lines[:]
- revlist.reverse()
- indent = 0
- for line in revlist:
- if line.class_name == "EmptyLine":
- line.change_indent(indent)
- else:
- indent = line.indent
- del revlist
-
- if DEBUGGING:
- print "Pass 2.5 - the contents of those lines..."
- print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
- for line in self.lines:
- print "Line %d %s"%(line.lineno,line.class_name)
- #print_tuples([line.tagtuple],self.text," ")
- print
-
- # Now we need to assemble blocks
- print "Pass 3: assembling blocks"
- if DEBUGGING: print "~~~~~~~~~~~~~~~~~~~~~~~~~"
- self.reset()
- self.items = []
-
- while 1:
- try:
- item = self.next()
- except EOFError:
- break
-
- if DEBUGGING:
- print "%sTOP %s"%(item.indent_str,item)
- if item.starts_block():
- block = Block(startline=item,outer=1,file=self)
- self.items.append(block)
- block.is_last = 1 # Everything at outer level is "last"
- else:
- if item.only_in_block():
- item.error("This line is not allowed outside a block "
- "- continuing anyway")
- self.items.append(item)
- if item.our_business():
- item.is_last = 1 # Everything at outer level is "last"
-
- if DEBUGGING: print
-
-
- def reset(self):
- """Ensure that the next call of "nextline" returns the first line."""
- self.index = -1
-
- def unget(self):
- """Unread the current line."""
- self.index = self.index - 1
- if self.index < 0:
- self.index = 0
-
- def next(self):
- """Retrieve the next line from the list of lines in this "file".
-
- Raises EOFError if there is no next line (i.e., "end of file")
- """
- self.index = self.index + 1
- try:
- return self.lines[self.index]
- except IndexError:
- # leave the index off the end, so we get EOF again if
- # we're called again - but there's no point courting overflow...
- self.index = self.index -1
- raise EOFError
-
- def expand(self,stream):
- """Expand out the result."""
- for item in self.items:
- item.expand(stream)
-
-\f
-# ------------------------------------------------------------
-def print_tuples(tuples,text,indent=""):
- """Print out a list of tuples in a neat form
-
- tuples -- our tuple list
- text -- the text it tags
- indent -- our current indentation
- """
-
- # Tuples are of the form:
- # (object,left_index,right_index,sublist)
-
- for obj,left,right,sub in tuples:
- if sub:
- print "%s%s"%(indent,obj)
- print_tuples(sub,text,indent+" ")
- else:
- # Terminal node - show the actual text we've tagged!
- print "%s%s = %s"%(indent,obj,`text[left:right]`)
-
-\f
-# ------------------------------------------------------------
-def print_text(text):
- """Print out text with line numbers."""
- lines = string.split(text,"\n")
- lineno = 0
-
- print "Original text"
- print "============="
- for line in lines:
- lineno = lineno + 1
- print "%3d: %s"%(lineno,`line`)
-
-\f
-# ------------------------------------------------------------
-def print_usage(argv0):
- #script_name = string.split(argv0, os.sep)[-1]
- #print __doc__%(script_name)
- print argv0
- print __doc__
-
-\f
-# ------------------------------------------------------------
-def show_tup(indent,nn,tup):
- ll = []
- for item in tup:
- if type(item) == type((1,)) or type(item) == type([]):
- ll.append("(..)")
- else:
- ll.append(`item`)
-
- if nn:
- print "%s%d: (%s)"%(indent,nn,string.join(ll,","))
- else:
- print "%s(%s)"%(indent,string.join(ll,","))
-
-def comp_sub(indent,one,two):
- len1 = len(one)
- if len(two) != len(one):
- print "%sTuple lengths differ - 1:%d, 2:%d"%(indent,len1,len(two))
- show_tup(indent,1,one)
- show_tup(indent,2,two)
- # If this is all, let's try to continue...
- len1 = min(len1,len(two))
-
- for count in range(len1):
- a = one[count]
- b = two[count]
- if type(a) != type(b):
- print "%sValue types differ, item %d: 1:%s, 2:%s"%(indent,count,
- type(a),type(b))
- show_tupe(indent,1,one)
- show_tupe(indent2,two)
- return 0
- if type(a) == type((1,)) or type(a) == type([]):
- if not comp_sub(indent+" ",a,b):
- # They're the same at this level, so show only one...
- show_tup(indent,0,one)
- return 0
- else:
- if a != b:
- print "%sValues differ, item %d: 1:%s, 2:%s"%(indent,count,
- `a`,`b`)
- show_tup(indent,1,one)
- show_tup(indent,2,two)
- return 0
- return 1
-
-def compare_tagtables(one,two):
- # Each table is made up of tuples of the form
- # (tagobj,action,arg,onfalse,ontrue)
- # but if action is Table or SubTable then arg may be a tuple
- # itself...
- if comp_sub("",one,two):
- print "They appear to be the same"
-
-\f
-# ------------------------------------------------------------
-def main():
- """Used to test the module."""
-
- debug_pytag = DEFAULT_DEBUG
- use_pytag = DEFAULT_PYTAG
- use_stdout = 0
- import_tags = 0
- force_overwrite = 0
- compare_tables = 0
-
- if os.name == "posix":
- use_testdata = 0
- else:
- # At home...
- use_testdata = 1
- use_stdout = 1
- global DEBUGGING
- DEBUGGING = 0
-
- # Do we have command line arguments?
- arg_list = sys.argv[1:]
- args = []
-
- while 1:
- if len(arg_list) == 0:
- break
-
- word = arg_list[0]
-
- if word == "-pytag":
- use_pytag = 1
- elif word == "-debug":
- debug_pytag = 1
- elif word == "-stdout":
- use_stdout = 1
- elif word == "-force":
- force_overwrite = 1
- elif word == "-import":
- import_tags = 1
- elif word == "-compare":
- compare_tables = 1
- elif word == "-diag":
- global DEBUGGING
- DEBUGGING = 1
- elif word == "-test":
- use_testdata = 1
- use_stdout = 1
- elif word == "-help":
- print_usage(sys.argv[0])
- return
- elif word == "-version":
- print "Version:",__version__
- return
- elif word == "-history":
- print "History:"
- print __history__
- return
- else:
- args.append(word)
-
- arg_list = arg_list[1:]
- continue
-
- if compare_tables:
- from Translate_tags import t_file
- i_file = define_tagtable()
- print "Comparing internal table (1) against external (2)"
- compare_tagtables(i_file,t_file)
- return
-
- if not use_testdata and (not args or len(args) > 2):
- print_usage(sys.argv[0])
- return
-
- if not use_testdata:
- infile = args[0]
-
- if import_tags:
- print "Importing tag table definition"
- from Translate_tags import t_file
- else:
- print "Using internal tag table definition"
- t_file = define_tagtable()
-
- if use_stdout:
- outfile = "standard output"
- elif len(args) > 1:
- outfile = args[1]
- else:
- base,ext = os.path.splitext(infile)
- if ext != ".py":
- outfile = base + ".py"
- else:
- print "Input file has extension .py so won't guess"\
- " an output file"
- return
-
- if outfile != "standard output":
- if outfile == infile:
- print "The output file is the same as the input file"
- print "Refusing to overwrite %s"%outfile
- return
- elif os.path.exists(outfile):
- if force_overwrite:
- print "Output file %s already exists"\
- " - overwriting it"%outfile
- else:
- print "Output file %s already exists"%outfile
- return
-
- # Read the input file
- if use_testdata:
- if DEBUGGING: print
- print "Using test data"
- if DEBUGGING: print "==============="
- text = test_data
- else:
- if DEBUGGING: print
- print "Reading text from %s"%infile
- if DEBUGGING: print "=================="+"="*len(infile)
- file = open(infile,"r")
- text = file.read()
- file.close()
-
- # Show what we are trying to parse
- if DEBUGGING or use_testdata:
- print
- print_text(text)
-
- # Tag it
- print
- print "Tagging text"
- if DEBUGGING: print "============"
- if use_pytag:
- import pytag
- pytag.set_verbosity(0)
- if debug_pytag:
- pytag.set_verbosity(1)
- pytag.use_debugger()
- result,taglist,next = pytag.pytag(text,t_file)
- else:
- timer = TextTools._timer()
- timer.start()
- result, taglist, next = tag(text,t_file)
- #result, taglist, next = tag(text,t_file,0,len(text),taglist)
- print "Tagging took",timer.stop()[0],"seconds"
-
- # Now print out the result of the tagging
- print
- print "Manipulating tagged data"
- if DEBUGGING: print "========================"
- tagfile = File(taglist,text)
-
- print
- print "Writing translation to %s"%outfile
- if DEBUGGING: print "======================="+"="*len(outfile)
-
- # Open the output file, if necessary
- if use_stdout:
- file = sys.stdout
- else:
- file = open(outfile,"w")
-
- tagfile.expand(file)
-
-\f
-# ------------------------------------------------------------
-if __name__ == '__main__':
- main()
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-try:
- import mx.TextTools
- import sys
- sys.modules['TextTools']=mx.TextTools
-except:
- # Le package mx n'est pas installé. On essaie d'importer
- # directement TextTools au cas ou
- try:
- import TextTools
- except:
- # Aucun des deux packages n'est installé
- #print """ Le package mx.TextTools ou TextTools doit etre
- #installé pour pouvoir relire des fichiers de commandes
- #au format Aster V5
- #voir : http://www.lemburg.com/python/mxExtensions.html
- #"""
- pass
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-import sys,string
-try :
- import TextTools
-except :
- ""
-try :
- from tables import ERRORS
-except :
- ""
-
-#
-__version__="$Name: V7_main $"
-__Id__="$Id: conv.py,v 1.6.52.1 2013-01-24 14:25:23 pnoyret Exp $"
-#
-
-Keywords=('MAILLE_1','MAILLE_2','MAILLE_ESCL','MAILLE_FOND','MAILLE_MAIT','MAILLE_ORIG','MAILLE',
- 'NOEUD', 'NOEUD_1','NOEUD_2','NOEUD_INIT','NOEUD_FIN', 'NOEUD_ORIG','NOEUD_REFE','NOEUD_EXTR',
- 'NOEUD_I', 'NOEUD_J','NOEUD_CHOC','NOEUD_ANCRAGE','NOEUD_CENTRE','NOEUD_CMP','NOEUD_DOUBLE',
- 'NOEUD_ESCL','NOEUD_FOND','NOEUD_PARA','NOEUD_POIN_TANG',
- 'GROUP_MA', 'GROUP_MA_1','GROUP_MA_2','GROUP_MA_INT','GROUP_MA_EXT', 'GROUP_MA_ORIG',
- 'GROUP_MA_BORD','GROUP_MA_INTE','GROUP_MA_FLUIDE', 'GROUP_MA_INTERF','GROUP_MA_BETON',
- 'GROUP_MA_ESCL','GROUP_MA_FINAL','GROUP_MA_FLU_SOL','GROUP_MA_FLU_STR','GROUP_MA_FOND',
- 'GROUP_MA_MAIT','GROUP_MA_RADIER','GROUP_MA_SOL_SOL','GROUP_MA_INIT',
- 'GROUP_NO', 'GROUP_NO_1','GROUP_NO_2','GROUP_NO_EXT', 'GROUP_NO_ORIG','GROUP_NO_CHOC',
- 'GROUP_NO_ANCRAGE','GROUP_NO_CENTRE','GROUP_NO_ESCL','GROUP_NO_EXTR','GROUP_NO_FIN',
- 'GROUP_NO_FOND','GROUP_NO_INIT','GROUP_NO_POIN_TG','GROUP_NO_RADIER',
- 'NOM','NOM_GROUP_MA',
- 'SANS_NOEUD', 'SANS_GROUP_NO',
- 'INTERSEC', 'UNION','DIFFE',
- 'VECT_GRNO_ORIG','VECT_GRNO_EXTR',
- 'VALE_CO'
- )
-
-liste_macros=('MACRO_MATR_ASSE','MACRO_ELAS_MULT','MACR_ASCOUF_MAIL','MACR_ASCOUF_CALC','MACR_ASPIC_MAIL',
- 'MACR_ASPIC_CALC','MACRO_MATR_AJOU','MACRO_ELAS_MULT','MACRO_MODE_MECA','MACRO_PROJ_BASE',
- 'MACR_ADAP_MAIL',
- )
-liste_concepts_produits=[]
-commande_courante=''
-
-def text_nom_ope(text,tags,left,right):
- global commande_courante
- if len(tags) :
- tag,l,r,subtags=tags[0]
- commande_courante=text[left:l]
- return text[left:l]+'('+text[l:r]
- else :
- commande_courante=text[left:right]
- return text[left:right]+'('
-
-def text_reuse(text,tags):
- s=''
- for tag,l,r,subtags in tags:
- if tag == 'ident' :
- sd=text[l:r]
- s=s+ sd
- elif tag == 'nom_ope' : s=s+ '='+text_nom_ope(text,subtags,l,r)
- elif tag == 'affe' :
- s=s+ '='+text_affe(text,subtags)
- elif tag == 'comm' :
- if commande_courante in liste_macros:
- s=s+'reuse='+sd+','+text_macro(text,subtags)+')'
- else:
- s=s+'reuse='+sd+','+text_com(text,subtags)+')'
- else:pass
- s=s+'\n'
- return s
-
-def text_noreuse(text,tags):
- global commande_courante
- s=''
- for tag,l,r,subtags in tags:
- if tag == 'ident' :
- sd=text[l:r]
- s=s+ text[l:r]
- elif tag == 'nom_ope' :
- s=s+ '='+ text_nom_ope(text,subtags,l,r)
- elif tag == 'affe' :
- liste_concepts_produits.append(sd)
- s=s+ '='+text_affe(text,subtags)
- elif tag == 'comm' :
- if oldtag=='ident':
- if sd in liste_macros:
- s=s+'('+text_macro(text,subtags)+')'
- else:
- s=s+'('+text_com(text,subtags)+')'
- else:
- liste_concepts_produits.append(sd)
- if commande_courante in liste_macros:
- s=s+text_macro(text,subtags)+')'
- else:
- s=s+text_com(text,subtags)+')'
- else:pass
- oldtag=tag
- s=s+'\n'
- return s
-
-def list_mc(lmc,mcs):
- s=''
- for k in lmc:
- v=mcs[k]
- if len(v) ==1:
- va,c=v[0]
- s=s+c+k+'='+va+','
- elif len(v) > 1:
- s=s+k+'=('
- for va,c in v:
- s=s+string.join((c,va,','),'')
- s=s[:-1]+'),'
- s=s[:-1]
- return s
-
-def text_com(text,tags):
- mcs={}
- lmc=[]
- currid=None
- comment=''
- for tag,l,r,subtags in tags:
- if tag == 'ident' :
- currid=text[l:r]
- if not mcs.has_key(currid):
- mcs[currid]=[]
- lmc.append(currid)
- elif tag == 'mcf':
- ll=text_mcf(text,subtags)
- mcs[currid].append((ll,comment))
- comment=''
- elif tag == 'num' :
- a=string.replace(text[l:r],'D','E')
- mcs[currid].append((a,comment))
- comment=''
- elif tag == 'CPLX' :
- a=text_cplx(text,text[l:r],subtags)
- mcs[currid].append((a,comment))
- comment=''
- elif tag == 'arg' :
- a=''
- if currid in Keywords :
- # FR : (SGDG) il faut tester s'il n'y a pas déjà des cotes !!!
- if text[l]!="'" and text[r-1]!="'":
- a=a+"'"+text[l:r]+"'"
- else:
- a=a+text[l:r]
- else:
- a=a+text[l:r]
- mcs[currid].append((a,comment))
- comment=''
- elif tag == 'EVAL' :
- a=text_eval(text,subtags)
- mcs[currid].append((a,comment))
- comment=''
- elif tag == 'comment' :
- comment=comment + '#'+text[l+1:r]
- elif tag == 'comments' :
- comment=comment + text[l:r]
- elif tag == 'larg' :
- if currid in Keywords:mcs[currid].append((text_larg2(text,subtags),comment))
- else:mcs[currid].append((text_larg(text,subtags),comment))
- comment=''
- else :pass
- s=list_mc(lmc,mcs)
- if comment :s=s+comment
- return s
-
-def text_macro(text,tags):
- mcs={}
- lmc=[]
- currid=None
- comment=''
- for tag,l,r,subtags in tags:
- if tag == 'ident' :
- currid=text[l:r]
- if not mcs.has_key(currid):
- mcs[currid]=[]
- lmc.append(currid)
- elif tag == 'mcf':
- ll=text_macro_mcf(text,subtags)
- mcs[currid].append((ll,comment))
- comment=''
- elif tag == 'num' :
- a=string.replace(text[l:r],'D','E')
- mcs[currid].append((a,comment))
- comment=''
- elif tag == 'CPLX' :
- a=text_cplx(text,text[l:r],subtags)
- mcs[currid].append((a,comment))
- comment=''
- elif tag == 'arg' :
- a=''
- if text[l] == "'":
- # FR : (SGDG) il faut tester s'il n'y a pas déjà des cotes !!!
- a=a+text[l:r]
- elif currid in Keywords :
- a=a+"'"+text[l:r]+"'"
- else:
- sd=text[l:r]
- if sd not in liste_concepts_produits:
- # Il s agit d un concept produit par la macro mais situe à droite de =
- a=a+'CO("'+sd+'")'
- liste_concepts_produits.append(sd)
- else:
- a=a+sd
- mcs[currid].append((a,comment))
- comment=''
- elif tag == 'EVAL' :
- a=text_eval(text,subtags)
- mcs[currid].append((a,comment))
- comment=''
- elif tag == 'comment' :
- comment=comment + '#'+text[l+1:r]
- elif tag == 'comments' :
- comment=comment + text[l:r]
- elif tag == 'larg' :
- if currid in Keywords:mcs[currid].append((text_larg2(text,subtags),comment))
- else:mcs[currid].append((text_larg(text,subtags),comment))
- comment=''
- else :pass
- s=list_mc(lmc,mcs)
- if comment :s=s+comment
- return s
-
-def comments_text(text):
- l=string.replace(text,'%','#')
- return l
-
-def text_eval(text,tags):
- # on retourne l expression sans conversion dans un objet EVAL et entre quotes
- for tag,l,r,subtags in tags:
- if tag == 'vexpr':
- s='EVAL("""'+text[l:r]+'""")'
- return s
- return ''
-
-def text_mcf(text,tags):
- s='_F( '
- comment=''
- for tag,l,r,subtags in tags:
- if tag == 'ident' :
- s=s+comment
- comment=''
- currid=text[l:r]
- s=s+ currid +' = '
- elif tag == 'arg' :
- if currid in Keywords :
- # FR : (SGDG) il faut tester s'il n'y a pas déjà des cotes !!!
- if text[l]!="'" and text[r-1]!="'":
- s=s+"'"+text[l:r]+"',"
- else:
- s=s+text[l:r]+","
- else:s=s+text[l:r]+","
- elif tag == 'num' :
- s=s+string.replace(text[l:r],'D','E')+','
- elif tag == 'CPLX' :
- s=s+text_cplx(text,text[l:r],subtags)+','
- elif tag == 'EVAL' :
- s=s+text_eval(text,subtags)+','
- elif tag == 'larg' :
- if currid in Keywords:s=s+text_larg2(text,subtags)+','
- else: s=s+text_larg(text,subtags)+','
- elif tag == 'comments' :
- comment=comment+text[l:r]
- if comment != '':
- s=s+comment
- return s+')'
-
-def text_macro_mcf(text,tags):
- s='_F( '
- comment=''
- for tag,l,r,subtags in tags:
- if tag == 'ident' :
- s=s+comment
- currid=text[l:r]
- s=s+ currid +' = '
- elif tag == 'arg' :
- if text[l] == "'":
- # FR : (SGDG) il faut tester s'il n'y a pas déjà des cotes !!!
- s=s+text[l:r]+","
- elif currid in Keywords :
- s=s+"'"+text[l:r]+"',"
- else:
- sd=text[l:r]
- if sd not in liste_concepts_produits:
- # Il s agit d un concept produit par la macro mais situe à droite de =
- s=s+'CO("'+sd+'"),'
- liste_concepts_produits.append(sd)
- else:
- s=s+sd+','
- comment=''
- elif tag == 'num' :
- s=s+string.replace(text[l:r],'D','E')+','
- elif tag == 'CPLX' :
- s=s+text_cplx(text,text[l:r],subtags)+','
- comment=''
- elif tag == 'EVAL' :
- s=s+text_eval(text,subtags)+','
- comment=''
- elif tag == 'larg' :
- if currid in Keywords:s=s+text_larg2(text,subtags)+','
- else: s=s+text_larg(text,subtags)+','
- comment=''
- elif tag == 'comments' :
- comment=comment+text[l:r]
- return s[:-1]+')'
-
-def text_cplx(texte,text,tags):
- """ Retourne une chaîne de caractères représentant un complexe """
- s="('"+text[0:2]+"'," #text[0:2] = RI ou MP
- for tag,l,r,subtags in tags:
- if tag == 'num' :
- s=s+string.replace(texte[l:r],'D','E')+','
- s=s+')'
- return s
-
-def text_larg2(text,tags):
- """ Pareil que text_larg mais ajoute des cotes autour des arg """
- ll=[]
- for tag,l,r,subtags in tags:
- if tag == 'arg' :
- # FR : (SGDG) il faut tester le cas où les cotes sont déjà là !!!!
- if text[l] != "'" and text[r-1] != "'":
- ll.append( "'"+text[l:r]+"',")
- else:
- ll.append(text[l:r]+",")
- elif tag == 'num' :
- ll.append(string.replace(text[l:r],'D','E')+',')
- elif tag == 'CPLX' :
- ll.append(text_cplx(text,text[l:r],subtags)+',')
- elif tag == 'comments' :
- ll.append(text[l:r])
- return '('+string.join(ll,'')+')'
-
-def text_larg(text,tags):
- # Pour les listes d arguments il semble plus rapide de construire
- # une liste puis de faire join (ne pas exagerer : voir ajout ,)
- ll=[]
- for tag,l,r,subtags in tags:
- if tag == 'arg' :
- ll.append((text,l,r))
- ll.append(',')
- elif tag == 'num' :
- # cette facon de faire est un peu plus rapide que la suivante
- ll.append(string.replace(text[l:r],'D','E')+',')
- elif tag == 'comments' :
- ll.append((text,l,r))
- elif tag == 'EVAL' :
- ll.append(text_eval(text,subtags)+',')
- else:
- print "Argument ignore: ",text[l:r]
- return '('+TextTools.join(ll,'')+')'
-
-def comment_text(text):
- l=string.replace(text,'\n','\n#')
- if l[-1]=='#':return '#'+l[:-1]
- else:return '#'+l
-
-def text_affe(text,tags):
- s=''
- for tag,l,r,subtags in tags:
- if tag == 'arg' :
- s=s+text[l:r]
- elif tag == 'EVAL' :
- s=s+text_eval(text,subtags)
- elif tag == 'larg' :
- s=s+text_larg(text,subtags)
- elif tag == 'num' :
- s=s+string.replace(text[l:r],'D','E')
- elif tag == 'CPLX' :
- s=s+text_cplx(text,text[l:r],subtags)+','
- return s
-
-def text_commande(text,tags):
- """
- Convertit une taglist de type commande en une chaine de caracteres
- à la syntaxe Python représentative d'une commande
- """
- s=''
- for tag,l,r,subtags in tags:
- if tag == 'noreuse':
- s=s+text_noreuse(text,subtags)
- elif tag == 'reuse':s=s+text_reuse(text,subtags)
- return s
-
-def text_formule(text,tags):
- """
- Convertit une taglist de type formule en une chaine de caracteres
- à la syntaxe Python représentative d'une formule
- """
- s=''
- count=0
- typ=''
- for tag,l,r,subtags in tags:
- if tag == 'id':
- if count == 0:
- s=text[l:r]+' = FORMULE('+ty+'="""('
- else:
- if count > 1:s=s+','
- s=s+typ+text[l:r]
- typ=''
- count = count +1
- elif tag == 'typ':
- typ=text[l:r]
- elif tag == 'vexpr':
- s=s+ ') =\n'+text[l:r]
- elif tag == 'type':
- ty=text[l:r]
- return s +'""")\n'
-
-def text_comms(text,tags):
- """
- Convertit une taglist resultat d'un appel à TextTools.tag avec une table de type Aster
- en une chaine de caracteres à la syntaxe Python
- """
- # On met la liste globale des concepts produits à zero
- global liste_concepts_produits
- liste_concepts_produits=[]
-
- s=''
- for tag,l,r,subtags in tags:
- if tag == 'comment':
- s=s+ '#'+text[l+1:r]
- elif tag == 'Null':
- s=s+ '\n'
- elif tag == 'formule':
- s=s+ text_formule(text,subtags)
- elif tag == 'commande' :
- s=s+text_commande(text,subtags)
- else:
- s=s+ comment_text(text[l:r])
- return s
-
-def format_errs(text,tags):
- s=''
- warnings=''
- for tag,l,r,subtags in tags:
- if subtags:
- err,warn=format_errs(text,subtags)
- s=s+err
- warnings=warnings+warn
- if tag in ERRORS:
- s=s+ tag+" ligne : "+`TextTools.countlines(text[:l])`+" texte erroné : "+text[l-10:l]+'?'+text[l:r]+'\n'
- if tag == 'passline':
- warnings=warnings+ " ligne "+`TextTools.countlines(text[:l])`+" ignorée : " +text[l:r]+'\n'
- return s,warnings
-
-def conver(text):
- from tables import aster_script
- import re
- # On ajoute un '\n' en fin au cas ou il serait absent
- text=text+'\n'
- text=string.upper(text)
- result, taglist, next = TextTools.tag(text,aster_script)
- # Pour vérifier les résultats intermédiaires décommenter la ligne suivante
- #TextTools.print_tags(text,taglist)
- text=string.replace(text,'%','#')
- s_errors,warnings = format_errs(text,taglist)
- if s_errors:
- return None,s_errors,warnings
- else:
- ss=text_comms(text,taglist)
- return string.replace(ss,'\r\n','\n'),s_errors,warnings
-
-
-
-
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-"""
- Ce fichier définit une table de tags à utiliser avec le package
- mxTextTools pour décoder un fichier au format Asterv5.
-
- XXX Ce fichier doit etre corrigé pour incorporer deux modifications
- réalisées dans la version V1_1p1 d'EFICAS
-"""
-from TextTools import *
-
-#
-__version__="$Name: V7_main $"
-__Id__="$Id: tables.py,v 1.5.52.1 2013-01-24 14:25:23 pnoyret Exp $"
-#
-
-err0='ERR0 , erreur non identifiee : '
-err1='ERR1 , arguments commande errones : '
-err2='ERR2 , parenthese obligatoire : '
-err3='ERR3 , point virgule obligatoire : '
-err4='ERR4 , ":" obligatoire avant mot cle : '
-err5='ERR5 , mot cle facteur ou arg obligatoire : '
-err6='ERR6 , identificateur obligatoire : '
-err7='ERR7 , mot cle facteur errone : '
-err8='ERR8 , signe = ou ( attendu : '
-err9='ERR9 , ( attendue : '
-err10='ERR10 , vexpr attendue : '
-err11='ERR11 , ) attendue : '
-
-ERRORS=(err0,err1,err2,err3,err4,err5,err6,err7,err8,err9,
- err10,err11)
-
-white_set=set(whitespace)
-
-delim=" ();:=,!&*/%\n"
-
-whitespace = \
- (None,AllIn,' \t')
-
-opt_whitespace = \
- whitespace + (MatchOk,)
-
-t_opt_whitespace = \
- whitespace + (+1,)
-
-t_opt_whitenl = \
- (None,AllIn,' \t\n\r',+1)
-
-t_err = (
- (None,AllNotIn,';',+1),
- (None,Is,';'),
- (None,Skip,-1),
-)
-
-commespaces = \
- ('comments',Table,(
- (None,IsInSet,white_set,+1,+4),
- (None,Is,'%',MatchFail),
- # <comment>
- (None,AllNotIn,'\n\r',+1),
- (None,AllIn,'\n\r',+1),
- # <blancs>
- (None,AllInSet,white_set,+1),
- (None,Is,'%',MatchOk,-3),
- ))
-
-t_commespaces = (
- (None,IsInSet,white_set,+1,+4),
- (None,Is,'%',MatchFail),
- # <comment>
- (None,AllNotIn,'\n\r',+1),
- (None,AllIn,'\n\r',+1),
- # <blancs>
- (None,AllInSet,white_set,+1),
- (None,Is,'%',MatchOk,-3),
-)
-
-x_commespaces = \
- ('comments',Table,(
- # <debut>
- (None,Is,'%',+3,+1),
- (None,AllNotIn,'\n\r',+1),
- (None,AllIn,'\n\r',+1,-2),
- (None,AllInSet,white_set,+1,-3),
- ))
-
-t_ident = \
- ('ident',Table,(
- (None,IsIn,alpha+'_'),
- (None,AllIn,alpha+'_'+number,MatchOk),
- ))
-
-t_identificateur = (
- (None,IsIn,alpha+'_'),
- (None,AllIn,alpha+'_'+number,MatchOk),
-)
-
-t_identmc = (
- (None,IsIn,alpha+'_'),
- (None,AllIn,alpha+'_'+number,+1),
- (None,Table,t_commespaces,+1),
- (None,Is,':',MatchFail),
-)
-
-n_ident = \
- (None,Table,(
- (None,IsIn,alpha+'_'),
- (None,AllIn,alpha+'_'+number,MatchOk),
- ))
-
-n_string = \
- (None,Table,(
- (None,Is,"'"),
- # <loop>
- (None,AllNotIn,"'",+1),
- (None,Word,"''",+1,-1),
- (None,Is,"'",MatchFail,MatchOk),
- ))
-
-t_number = \
- ('num',Table,(
- (None,IsIn,'-+',+1),
- (None,Is,'.',+2),
- (None,IsIn,number,MatchFail,+4),
- # <entiere>
- (None,IsIn,number,MatchFail),
- (None,AllIn,number,+1),
- (None,Is,'.',+2),
- # <decimal>
- (None,AllIn,number,+1),
- # <exposant> # si pas exposant termine number trouve
- (None,IsIn,'deDE',MatchOk),
- (None,IsIn,'-+',+1),
- (None,AllIn,number,MatchFail,MatchOk),
- ))
-
-n_number = \
- (None,Table,(
- (None,IsIn,'-+',+1),
- (None,Is,'.',+2),
- (None,IsIn,number,MatchFail,+4),
- # <entiere>
- (None,IsIn,number,MatchFail),
- (None,AllIn,number,+1),
- (None,Is,'.',+2),
- # <decimal>
- (None,AllIn,number,+1),
- # <exposant> # si pas exposant termine number trouve
- (None,IsIn,'deDE',MatchOk),
- (None,IsIn,'-+',+1),
- (None,AllIn,number,MatchFail,MatchOk),
- ))
-
-t_complexe = \
- ('CPLX',Table,(
- ("RI",Word,'RI',+7),
- commespaces + (+1,),
- t_number + (MatchFail,), # ce n est pas un complexe
- commespaces + (+1,), # a partir d ici c est un complexe => produire erreurs
- (None,Is,',',+1),
- commespaces + (+1,),
- t_number + (MatchFail,MatchOk),
- # <mp>
- ("MP",Word,'MP',MatchFail),
- commespaces + (+1,),
- t_number + (MatchFail,), # ce n est pas un complexe
- commespaces + (+1,), # a partir d ici c est un complexe => produire erreurs
- (None,Is,',',+1),
- commespaces + (+1,),
- t_number + (MatchFail,MatchOk),
- # <err>
- (err7,Table,t_err,MatchFail,MatchOk),
- ))
-
-# Table pour identifier le keyword PI
-
-t_PI = \
- ('PI',Table,(
- (None,Word,'PI',MatchFail),
- (None,IsIn,alpha+'_'+number,MatchOk,+1),
- (None,Skip,-1),
- (None,Jump,To,MatchFail),
- ))
-
-t_vexpr = (
- ('par',Is,'(',+5,+1),
- commespaces + (+1,),
- ('vexpr',Table,ThisTable,+26),
- commespaces + (+1,),
- ('par2',Is,')',+25,+15),
- t_number + (+1,+14),
- t_complexe + (+1,+13),
- ('sign',IsIn,'+-',+3,+1),
- commespaces + (+1,),
- ('vexpr',Table,ThisTable,+19,+10),
- t_PI + (+1,+9),
- t_ident + (MatchFail,),
- commespaces + (+1,),
- ('listpar',Is,'(',+6,+1), # on peut avoir une liste de parametres
- # <params>
- commespaces + (+1,),
- ('param',Table,ThisTable,+13),
- commespaces + (+1,),
- (None,Is,',',+1,-3),
- ('finlist',Is,')',+11),
- # <op>
- commespaces + (+1,),
- ('exp',Word,'**',+3,+1),
- commespaces + (+1,),
- ('vexpr',Table,ThisTable,+6,MatchOk),
- ('op',IsIn,'+-*/',+3,+1),
- commespaces + (+1,),
- ('vexpr',Table,ThisTable,+3,MatchOk),
- (None,Jump,To,MatchOk),
- # <err>
- (err0,Table,t_err,MatchFail,MatchOk),
- # <err10>
- (err10,Table,t_err,MatchFail,MatchOk),
- # <err9>
- (err9,Table,t_err,MatchFail,MatchOk),
-)
-
-t_liste_param = \
- ('liste',Table,(
- t_ident,
- commespaces + (+1,),
- (None,Is,'('),
- commespaces + (+1,),
- t_vexpr + (MatchFail,),
- # <suite>
- commespaces + (+1,),
- (None,Is,',',+3),
- commespaces + (+1,),
- t_vexpr + (+3,-3),
- # <fin>
- commespaces + (+1,),
- (None,Is,')',+1,MatchOk),
- # <err>
- (err7,Table,t_err,MatchFail,MatchOk),
- ))
-
-t_eval_expr = \
- ('EVAL',Table,(
- (None,Word,'EVAL'),
- commespaces + (+1,),
- (None,Is,'(',+5),
- commespaces + (+1,),
- ('vexpr',Table,t_vexpr,+3),
- commespaces + (+1,),
- (None,Is,')',+1,MatchOk),
- # <err>
- (err7,Table,t_err,MatchFail,MatchOk),
- ))
-
-t_entier = \
- ('entier',Table,(
- (None,IsIn,number),
- (None,AllIn,number,+1),
- (None,IsIn,delim,MatchFail,+1),
- (None,Skip,-1),
- ))
-
-t_comment = \
- ('comment',Table,(
- (None,Is,'%'),
- (None,AllNotIn,'\n\r',+1),
- (None,AllIn,'\n\r',MatchOk),
- ))
-
-t_nullline = \
- ('Null',AllIn,' ;\t\n\r')
-
-t_passline = \
- ('passline',Table,(
- (None,AllNotIn,newline,+1),
- (None,IsIn,newline),
- ))
-
-t_reste = \
- ('reste',Table,(
- (None,AllNotIn,';',+1),
- ))
-
-t_rest2 = \
- ('reste',Table,(
- (None,AllNotIn,';',+1),
- (None,Is,';'),
- (None,AllNotIn,'\n',+1),
- (None,Is,'\n',MatchOk,MatchOk),
- ))
-
-t_formule = \
- ('formule',Table,(
- commespaces + (+1,),
- (None,Word,'!FORMULE'),
- commespaces + (+1,),
- (None,Is,'(',+32),
- commespaces + (+1,),
- ('type',Table,t_identificateur,+29),
- commespaces + (+1,),
- (None,Is,':',+27),
- commespaces + (+1,),
- (None,Is,'(',+26),
- commespaces + (+1,),
- ('id',Table,t_identificateur,+23),
- commespaces + (+1,),
- (None,Is,'(',+22),
- # <params>
- commespaces + (+1,),
- ('typ',Table,t_identmc,+1),
- commespaces + (+1,),
- ('id',Table,t_identificateur,+17),
- commespaces + (+1,),
- (None,Is,',',+1,-5),
- commespaces + (+1,),
- (None,Is,')',-7),
- commespaces + (+1,),
- (None,Is,'=',+11),
- commespaces + (+1,),
- ('vexpr',Table,t_vexpr,+9),
- commespaces + (+1,),
- (None,Is,')',+9),
- commespaces + (+1,),
- (None,Is,')',+7),
- commespaces + (+1,),
- (None,Is,';',+3),
- (None,AllNotIn,'\n',+1),
- (None,Is,'\n',MatchOk,MatchOk),
- # <err>
- (err0,Table,t_err,MatchFail,MatchOk),
- # <err9>
- (err9,Table,t_err,MatchFail,MatchOk),
- # <err11>
- (err11,Table,t_err,MatchFail,MatchOk),
- ))
-
-t_nom_ope = \
- ('nom_ope',Table,(
- (None,Word,'EVAL',+1,MatchFail), # EVAL n est pas un nom d operateur, il est reserve
- (None,IsIn,alpha+'_'),
- (None,AllIn,alpha+'_'+number,+1),
- commespaces + (+1,),
- (None,Is,'(',MatchFail),
- (None,Skip,-1),
- ))
-
-t_arg = \
- ('arg',Table,(
- n_string + (+1,MatchOk),
- n_ident,
- ))
-
-t_larg = \
- ('larg',Table,(
- (None,Is,'(',MatchFail),
- # <arg>
- commespaces + (+1,),
- t_complexe + (+1,+4),
- t_number + (+1,+3),
- t_eval_expr + (+1,+2),
- t_arg + (MatchFail,+1),
- # <suite>
- commespaces + (+1,),
- (None,Is,',',+1),
- (None,Is,')',-7,MatchOk),
- ))
-
-t_mcf = \
- ('mcf',Table,(
- (None,Is,'(',MatchFail),
- ("comments",Table,t_commespaces,+1),
- (None,Is,')',+1,MatchOk),
- t_ident + (MatchFail,),
- ("comments",Table,t_commespaces,+1),
- (None,Is,':',MatchFail), # a partir d ici on est dans un mot cle facteur (erreurs eventuelles)
- # <args>
- ("comments",Table,t_commespaces,+1),
- t_larg + (+1,+5),
- t_complexe + (+1,+4),
- t_number + (+1,+3),
- t_eval_expr + (+1,+2),
- t_arg + (+8,),
- # <suite>
- ("comments",Table,t_commespaces,+1),
- (None,Is,',',+1),
- ("comments",Table,t_commespaces,+1),
- (None,Is,')',+1,MatchOk),
- t_ident + (+3,),
- ("comments",Table,t_commespaces,+1),
- (None,Is,':',+1,-12),
- # <err>
- (err7,Table,t_err,MatchFail,MatchOk),
- ))
-
-t_comm = \
- ('comm',Table,( # on attend les arguments entre () sinon erreur
- (None,Is,'(',+21),
- commespaces + (+1,),
- (None,Is,')',+1,MatchOk),
- # <call>
- t_ident + (+18,),
- commespaces + (+1,),
- (None,Is,':',+16),
- commespaces + (+1,),
- t_mcf + (+5,),
- # <mcfsuite>
- commespaces + (+1,),
- (None,Is,',',+1),
- commespaces + (+1,),
- t_mcf + (+7,-3),
- # <args>
- t_larg + (+1,+5),
- t_complexe + (+1,+4),
- t_number + (+1,+3),
- t_eval_expr + (+1,+2),
- t_arg + (+5,),
- # <suite>
- commespaces + (+1,),
- # <sep>
- (None,Is,',',+1),
- commespaces + (+1,),
- (None,Is,')',-17,MatchOk),
- # <err>
- (err1,Table,t_err,MatchFail,MatchOk),
- ))
-
-t_affe = \
- ('affe',Table,(
- commespaces + (+1,),
- t_larg + (+1,+6),
- t_complexe + (+1,+5),
- t_number + (+1,+4),
- t_eval_expr + (+1,+3),
- t_arg + (+1,+2),
- (None,Jump,To,+2),
- # <suite>
- (None,Jump,To,MatchOk),
- # <err>
- (err0,Table,t_err,MatchFail,MatchOk),
- ))
-
-t_reuse = \
- ('reuse',Table,(
- t_opt_whitespace,
- t_ident,
- t_opt_whitespace,
- (None,Is,'=',+5),
- t_opt_whitespace,
- t_nom_ope + (+2,+1),
- # <comm>
- t_comm + (MatchFail,MatchOk),
- # <affe>
- t_affe + (MatchFail,MatchOk),
- # <err>
- (err8,Table,t_err,MatchFail,MatchOk),
- ))
-
-t_noreuse = \
- ('noreuse',Table,(
- t_opt_whitespace,
- t_ident,
- t_opt_whitenl,
- (None,Is,'=',+3,+1), # on a affaire a un operateur ou une affectation
- t_opt_whitespace,
- t_nom_ope + (+4,+3),
- (None,Is,'(',+5,+1),
- (None,Skip,-1),
- # <comm>
- t_comm + (+2,MatchOk),
- # <affe>
- t_affe + (+1,MatchOk),
- # <err>
- (err0,Table,t_err,MatchFail,MatchOk),
- # <err8>
- (err8,Table,t_err,MatchFail,MatchOk),
- ))
-
-t_fin = \
- ('commande',Table,(
- ('noreuse',Table,(
- t_opt_whitespace,
- ('ident',Word,"FIN"),
- t_opt_whitenl,
- (None,Is,'(',MatchFail), # On est vraiment sur d avoir la commande FIN apres avoir identifie (
- # On recule d un caractere pour identifier les arguments entre parenthèses
- (None,Skip,-1),
- t_comm + (+1,MatchOk),
- (err0,Table,t_err,MatchFail,MatchOk),
- )),
- commespaces + (+1,),
- (None,Is,';',+1,MatchOk),
- # <err>
- (err0,Table,t_err,MatchFail,MatchOk),
- ))
-
-t_commande = \
- ('commande',Table,(
- t_opt_whitespace,
- (None,Is,'&',+2,+1),
- t_reuse + (MatchFail,+2),
- t_noreuse + (MatchFail,),
- # <fin>
- commespaces + (+1,),
- (None,Is,';',+1,MatchOk),
- # <err>
- (err0,Table,t_err,MatchFail,MatchOk),
- ))
-
-aster_script = (
- # <top>
- t_nullline + (+1,+0),
- t_comment + (+1,-1),
- t_formule + (+1,-2),
- t_fin + (+1,+4),
- t_commande + (+1,-4),
- t_passline + (+1,-5),
- (None,EOF,Here,-6),
- # <AfterFin>
- t_nullline + (+1,+0),
- t_passline + (+1,-1),
- (None,EOF,Here,-2),
-)
-
-
-
+++ /dev/null
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-"""
- Ce fichier définit une table de tags à utiliser avec le package
- mxTextTools pour décoder un fichier au format Asterv5.
-
- XXX Ce fichier doit etre corrigé pour incorporer deux modifications
- réalisées dans la version V1_1p1 d'EFICAS
-"""
-from TextTools import *
-
-#
-__version__="$Name: V7_main $"
-__Id__="$Id: tables.tag,v 1.2.62.1 2013-01-24 14:25:23 pnoyret Exp $"
-#
-
-err0='ERR0 , erreur non identifiee : '
-err1='ERR1 , arguments commande errones : '
-err2='ERR2 , parenthese obligatoire : '
-err3='ERR3 , point virgule obligatoire : '
-err4='ERR4 , ":" obligatoire avant mot cle : '
-err5='ERR5 , mot cle facteur ou arg obligatoire : '
-err6='ERR6 , identificateur obligatoire : '
-err7='ERR7 , mot cle facteur errone : '
-err8='ERR8 , signe = ou ( attendu : '
-err9='ERR9 , ( attendue : '
-err10='ERR10 , vexpr attendue : '
-err11='ERR11 , ) attendue : '
-
-ERRORS=(err0,err1,err2,err3,err4,err5,err6,err7,err8,err9,
- err10,err11)
-
-white_set=set(whitespace)
-
-delim=" ();:=,!&*/%\n"
-
-whitespace is:
- AllIn ' \t'
-
-opt_whitespace is:
- whitespace F:MatchOk
-
-t_opt_whitespace is:
- whitespace F:next
-
-t_opt_whitenl is:
- AllIn ' \t\n\r' F:next
-
-t_err = Table is:
- AllNotIn ';' F:next
- Is ';'
- Skip back
-
-commespaces is:
- 'comments' = Table is:
- IsInSet white_set F:next T:<blancs>
- Is '%' F:MatchFail
- <comment>
- AllNotIn '\n\r' F:next
- AllIn '\n\r' F:next
- <blancs>
- AllInSet white_set F:next
- Is '%' F:MatchOk T:<comment>
-
-t_commespaces = Table is:
- IsInSet white_set F:next T:<blancs>
- Is '%' F:MatchFail
- <comment>
- AllNotIn '\n\r' F:next
- AllIn '\n\r' F:next
- <blancs>
- AllInSet white_set F:next
- Is '%' F:MatchOk T:<comment>
-
-x_commespaces is:
- 'comments' = Table is:
- <debut>
- Is '%':
- AllNotIn '\n\r' F:next
- AllIn '\n\r' F:next T:<debut>
- AllInSet white_set F:next T:<debut>
-
-t_ident is:
- 'ident' = Table is:
- IsIn alpha+'_'
- AllIn alpha+'_'+number F:MatchOk
-
-t_identificateur = Table is:
- IsIn alpha+'_'
- AllIn alpha+'_'+number F:MatchOk
-
-t_identmc = Table is:
- IsIn alpha+'_'
- AllIn alpha+'_'+number F:next
- None = Table t_commespaces F:next
- Is ':' F:MatchFail
-
-n_ident is:
- None = Table is:
- IsIn alpha+'_'
- AllIn alpha+'_'+number F:MatchOk
-
-n_string is:
- None = Table is:
- Is "'"
- <loop>
- AllNotIn "'" F:next
- Word "''" F:next T:<loop>
- Is "'" F:MatchFail T:MatchOk
-
-t_number is:
- 'num' = Table is:
- IsIn '-+' F:next
- Is '.' F:<entiere>
- IsIn number F:MatchFail T:<decimal>
- <entiere>
- IsIn number F:MatchFail
- AllIn number F:next
- Is '.' F:<exposant>
- <decimal>
- AllIn number F:next
- <exposant> # si pas exposant termine number trouve
- IsIn 'deDE' F:MatchOk
- IsIn '-+' F:next
- AllIn number F:MatchFail T:MatchOk
-
-n_number is:
- None = Table is:
- IsIn '-+' F:next
- Is '.' F:<entiere>
- IsIn number F:MatchFail T:<decimal>
- <entiere>
- IsIn number F:MatchFail
- AllIn number F:next
- Is '.' F:<exposant>
- <decimal>
- AllIn number F:next
- <exposant> # si pas exposant termine number trouve
- IsIn 'deDE' F:MatchOk
- IsIn '-+' F:next
- AllIn number F:MatchFail T:MatchOk
-
-t_complexe is:
- 'CPLX' = Table is:
- "RI" = Word 'RI' F:<mp>
- commespaces F:next
- t_number F:MatchFail # ce n est pas un complexe
- commespaces F:next # a partir d ici c est un complexe => produire erreurs
- Is ',' F:next
- commespaces F:next
- t_number F:MatchFail T:MatchOk
- <mp>
- "MP" = Word 'MP' F:MatchFail
- commespaces F:next
- t_number F:MatchFail # ce n est pas un complexe
- commespaces F:next # a partir d ici c est un complexe => produire erreurs
- Is ',' F:next
- commespaces F:next
- t_number F:MatchFail T:MatchOk
- <err>
- err7 = Table t_err F:MatchFail T:MatchOk
-
-# Table pour identifier le keyword PI
-
-t_PI is:
- 'PI' = Table is:
- Word 'PI' F:MatchFail
- IsIn alpha+'_'+number F:MatchOk T:next
- Skip back
- Jump To MatchFail
-
-t_vexpr = Table is:
- 'par' = Is '(':
- commespaces F:next
- 'vexpr' = Table ThisTable F:<err10>
- commespaces F:next
- 'par2' = Is ')' F:<err9> T:<op>
- t_number F:next T:<op>
- t_complexe F:next T:<op>
- 'sign' = IsIn '+-':
- commespaces F:next
- 'vexpr' = Table ThisTable F:<err10> T:<op>
- t_PI F:next T:<op>
- t_ident F:MatchFail
- commespaces F:next
- 'listpar' = Is '(': # on peut avoir une liste de parametres
- <params>
- commespaces F:next
- 'param' = Table ThisTable F:<err10>
- commespaces F:next
- Is ',' F:next T:<params>
- 'finlist' = Is ')' F:<err9>
- <op>
- commespaces F:next
- 'exp' = Word '**':
- commespaces F:next
- 'vexpr' = Table ThisTable F:<err10> T:MatchOk
- 'op' = IsIn '+-*/':
- commespaces F:next
- 'vexpr' = Table ThisTable F:<err10> T:MatchOk
- Jump To MatchOk
- <err>
- err0 = Table t_err F:MatchFail T:MatchOk
- <err10>
- err10 = Table t_err F:MatchFail T:MatchOk
- <err9>
- err9 = Table t_err F:MatchFail T:MatchOk
-
-t_liste_param is:
- 'liste' = Table is:
- t_ident
- commespaces F:next
- Is '('
- commespaces F:next
- t_vexpr F:MatchFail
- <suite>
- commespaces F:next
- Is ',' F:<fin>
- commespaces F:next
- t_vexpr F:<err> T:<suite>
- <fin>
- commespaces F:next
- Is ')' F:<err> T:MatchOk
- <err>
- err7 = Table t_err F:MatchFail T:MatchOk
-
-t_eval_expr is:
- 'EVAL' = Table is:
- Word 'EVAL'
- commespaces F:next
- Is '(' F:<err>
- commespaces F:next
- 'vexpr' = Table t_vexpr F:<err>
- commespaces F:next
- Is ')' F:<err> T:MatchOk
- <err>
- err7 = Table t_err F:MatchFail T:MatchOk
-
-t_entier is:
- 'entier' = Table is:
- IsIn number
- AllIn number F:next
- IsIn delim T:next
- Skip back
-
-t_comment is:
- 'comment' = Table is:
- Is '%'
- AllNotIn '\n\r' F:next
- AllIn '\n\r' F:MatchOk
-
-t_nullline is:
- 'Null' = AllIn ' ;\t\n\r'
-
-t_passline is:
- 'passline' = Table is:
- AllNotIn newline F:next
- IsIn newline
-
-t_reste is:
- 'reste' = Table is:
- AllNotIn ';' F:next
-
-t_rest2 is:
- 'reste' = Table is:
- AllNotIn ';' F:next
- Is ';'
- AllNotIn '\n' F:next
- Is '\n' F:MatchOk T:MatchOk
-
-t_formule is:
- 'formule' = Table is:
- commespaces F:next
- Word '!FORMULE'
- commespaces F:next
- Is '(' F:<err9>
- commespaces F:next
- 'type' = Table t_identificateur F:<err>
- commespaces F:next
- Is ':' F:<err>
- commespaces F:next
- Is '(' F:<err9>
- commespaces F:next
- 'id' = Table t_identificateur F:<err>
- commespaces F:next
- Is '(' F:<err9>
- <params>
- commespaces F:next
- 'typ' = Table t_identmc F:next
- commespaces F:next
- 'id' = Table t_identificateur F:<err>
- commespaces F:next
- Is ',' F:next T:<params>
- commespaces F:next
- Is ')' F:<params>
- commespaces F:next
- Is '=' F:<err>
- commespaces F:next
- 'vexpr' = Table t_vexpr F:<err>
- commespaces F:next
- Is ')' F:<err11>
- commespaces F:next
- Is ')' F:<err11>
- commespaces F:next
- Is ';' F:<err>
- AllNotIn '\n' F:next
- Is '\n' F:MatchOk T:MatchOk
- <err>
- err0 = Table t_err F:MatchFail T:MatchOk
- <err9>
- err9 = Table t_err F:MatchFail T:MatchOk
- <err11>
- err11 = Table t_err F:MatchFail T:MatchOk
-
-t_nom_ope is:
- 'nom_ope' = Table is:
- Word 'EVAL' F:next T:MatchFail # EVAL n est pas un nom d operateur, il est reserve
- IsIn alpha+'_'
- AllIn alpha+'_'+number F:next
- commespaces F:next
- Is '(' F:MatchFail
- Skip back
-
-t_arg is:
- 'arg' = Table is:
- n_string F:next T:MatchOk
- n_ident
-
-t_larg is:
- 'larg' = Table is:
- Is '(' F:MatchFail
- <arg>
- commespaces F:next
- t_complexe F:next T:<suite>
- t_number F:next T:<suite>
- t_eval_expr F:next T:<suite>
- t_arg F:MatchFail T:<suite>
- <suite>
- commespaces F:next
- Is ',' F:next
- Is ')' F:<arg> T:MatchOk
-
-t_mcf is:
- 'mcf' = Table is:
- Is '(' F:MatchFail
- "comments" = Table t_commespaces F:next
- Is ')' F:next T:MatchOk
- t_ident F:MatchFail
- "comments" = Table t_commespaces F:next
- Is ':' F:MatchFail # a partir d ici on est dans un mot cle facteur (erreurs eventuelles)
- <args>
- "comments" = Table t_commespaces F:next
- t_larg F:next T:<suite>
- t_complexe F:next T:<suite>
- t_number F:next T:<suite>
- t_eval_expr F:next T:<suite>
- t_arg F:<err>
- <suite>
- "comments" = Table t_commespaces F:next
- Is ',' F:next
- "comments" = Table t_commespaces F:next
- Is ')' F:next T:MatchOk
- t_ident F:<err>
- "comments" = Table t_commespaces F:next
- Is ':' F:<err> T:<args>
- <err>
- err7 = Table t_err F:MatchFail T:MatchOk
-
-t_comm is:
- 'comm' = Table is: # on attend les arguments entre () sinon erreur
- Is '(' F:<err>
- commespaces F:next
- Is ')' F:<call> T:MatchOk
- <call>
- t_ident F:<err>
- commespaces F:next
- Is ':' F:<err>
- commespaces F:next
- t_mcf F:<args>
- <mcfsuite>
- commespaces F:next
- Is ',' F:next
- commespaces F:next
- t_mcf F:<sep> T:<mcfsuite>
- <args>
- t_larg F:next T:<suite>
- t_complexe F:next T:<suite>
- t_number F:next T:<suite>
- t_eval_expr F:next T:<suite>
- t_arg F:<err>
- <suite>
- commespaces F:next
- <sep>
- Is ',' F:next
- commespaces F:next
- Is ')' F:<call> T:MatchOk
- <err>
- err1 = Table t_err F:MatchFail T:MatchOk
-
-t_affe is:
- 'affe' = Table is:
- commespaces F:next
- t_larg F:next T:<suite>
- t_complexe F:next T:<suite>
- t_number F:next T:<suite>
- t_eval_expr F:next T:<suite>
- t_arg F:next T:<suite>
- Jump To <err>
- <suite>
- Jump To MatchOk
- <err>
- err0 = Table t_err F:MatchFail T:MatchOk
-
-t_reuse is:
- 'reuse' = Table is:
- t_opt_whitespace
- t_ident
- t_opt_whitespace
- Is '=' F:<err>
- t_opt_whitespace
- t_nom_ope F:<affe> T:<comm>
- <comm>
- t_comm F:MatchFail T:MatchOk
- <affe>
- t_affe F:MatchFail T:MatchOk
- <err>
- err8 = Table t_err F:MatchFail T:MatchOk
-
-t_noreuse is:
- 'noreuse' = Table is:
- t_opt_whitespace
- t_ident
- t_opt_whitenl
- Is '=': # on a affaire a un operateur ou une affectation
- t_opt_whitespace
- t_nom_ope F:<affe> T:<comm>
- Is '(' F:<err8> T:next
- Skip back
- <comm>
- t_comm F:<err> T:MatchOk
- <affe>
- t_affe F:<err> T:MatchOk
- <err>
- err0 = Table t_err F:MatchFail T:MatchOk
- <err8>
- err8 = Table t_err F:MatchFail T:MatchOk
-
-t_fin is:
- 'commande' = Table is:
- 'noreuse' = Table is:
- t_opt_whitespace
- 'ident' = Word "FIN"
- t_opt_whitenl
- Is '(' F:MatchFail # On est vraiment sur d avoir la commande FIN apres avoir identifie (
- # On recule d un caractere pour identifier les arguments entre parenthèses
- Skip back
- t_comm F:next T:MatchOk
- err0 = Table t_err F:MatchFail T:MatchOk
- commespaces F:next
- Is ';' F:<err> T:MatchOk
- <err>
- err0 = Table t_err F:MatchFail T:MatchOk
-
-t_commande is:
- 'commande' = Table is:
- t_opt_whitespace
- Is '&':
- t_reuse F:MatchFail T:<fin>
- t_noreuse F:MatchFail
- <fin>
- commespaces F:next
- Is ';' F:<err> T:MatchOk
- <err>
- err0 = Table t_err F:MatchFail T:MatchOk
-
-aster_script = Table is:
- <top>
- t_nullline F:next T:<top>
- t_comment F:next T:<top>
- t_formule F:next T:<top>
- t_fin F:next T:<AfterFin>
- t_commande F:next T:<top>
- t_passline F:next T:<top>
- EOF Here F:<top>
- <AfterFin>
- t_nullline F:next T:<AfterFin>
- t_passline F:next T:<AfterFin>
- EOF Here F:<AfterFin>
-
-
-
+++ /dev/null
-# Copyright (C) 2007-2017 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-import re
-from convert_python import Pythonparser
-
-def entryPoint():
- """
- Return a dictionary containing the description needed to load the plugin
- """
- return {
- 'name' : 'openturns_study',
- 'factory' : OTStudyparser
- }
-
-class OTStudyparser(Pythonparser):
- """
- This converter works like Pythonparser, except that it also initializes all
- model variables to None in order to avoid Python syntax errors when loading
- a file with a different or inexistent definition of variables.
- """
- # We look for pattern "ModelVariable=NOMVAR,"
- pattern_model_variable = re.compile(r'ModelVariable\s*=\s*(\w+)\s*,')
-
- def convert(self, outformat, appli=None):
- text = Pythonparser.convert(self, outformat, appli)
- varnames = self.pattern_model_variable.findall(text)
- newtext = ""
- for var in varnames:
- newtext += "%s = None\n" % var
- newtext += text
- return newtext
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2017 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
-"""
-
-import parseur_python
-from convert_python import *
-
-def entryPoint():
- """
- Retourne les informations nécessaires pour le chargeur de plugins
- Ces informations sont retournées dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'openturns_wrapper',
- # La factory pour créer une instance du plugin
- 'factory' : Pythonparser,
- }
-
-
+++ /dev/null
-# -*- coding: utf-8 -*-
-# CONFIGURATION MANAGEMENT OF EDF VERSION
-# ======================================================================
-# COPYRIGHT (C) 1991 - 2002 EDF R&D WWW.CODE-ASTER.ORG
-# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
-# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
-# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
-# (AT YOUR OPTION) ANY LATER VERSION.
-#
-# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
-# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
-# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
-# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
-#
-# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
-# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
-# 1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
-#
-#
-# ======================================================================
-
-
-install ( FILES __init__.py generator_python.py Formatage.py generator_aplat.py
- generator_dicoImbrique.py generator_dico.py generator_modification.py generator_vers3DSalome.py
- generator_TELEMAC.py generator_map.py generator_GroupMA.py
- DESTINATION ${CMAKE_INSTALL_PREFIX}/generator
- )
-
-
-
-# Installation des fichiers : CARMEL
-if (WITH_CARMEL)
- install ( FILES generator_CARMEL3D_frequentiel.py generator_CARMEL3D_temporel.py
- DESTINATION ${CMAKE_INSTALL_PREFIX}/generator
- )
-endif (WITH_CARMEL)
-
-
-
-
-### Local Variables:
-### mode: cmake
-### End:
+++ /dev/null
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
-Ce module contient les variables
-par defaut pour Aster
-"""
-
-from OpenturnsSTD import STDGenerateur
-from OpenturnsXML import XMLGenerateur
-
-#====================================================
-# Preparation du fichier STD
-#====================================================
-# C.1. Parties du texte en dur dans le fichier STD
-#-------------------------------------------------
-
-DecalSTD = " "
-DecalSTDsaut = "\n "
-
-TexteSTDFIN ="\n\nexcept : \n"
-TexteSTDFIN += DecalSTD + "error_message = sys.exc_type\n"
-TexteSTDFIN += "\nif error_message is not None :\n"
-TexteSTDFIN += DecalSTD + "texte = \"\\n=================================================\""
-TexteSTDFIN += DecalSTD + "texte += \"\\nMessage d'erreur : \" + str(error_message)"
-TexteSTDFIN += DecalSTD + "texte += \"\\n=================================================\\n\""
-TexteSTDFIN += DecalSTD + "print (texte)"
-TexteSTDFIN += DecalSTD + "\nsys.exit(error_message)\n"
-
-# C.2. Definition de composants dans le fichier STD
-#--------------------------------------------------
-
-NomFunction = "myFunction"
-NomPhysicalStartingPoint = "myPhysicalStartingPoint"
-NomCollection = "myCollection"
-NomCopule = "myCopula"
-NomDistribution = "myDistribution"
-NomRandomVector_in = "myRandomVector_in"
-NomRandomVector_out = "myRandomVector_out"
-NomEvent = "myEvent"
-NomMethod = "myMethod"
-NomAlgo = "myAlgo"
-NomRoot = "myRoot"
-NomSampling = "mySampling"
-NomSolverSD = "mySolver"
-NomResu = "myResu"
-
-class Defaut :
-# Cette classe ajoute les parametres par defaut propres au Solver Aster
-# Elle va d abord enrichir le dictionnaire DictMCVal avec des valeurs par defaut
-# C est la methode enrichitMCVal
-# Elle va ensuite enrichir les variables
-# C est la methode enrichitListeVariables
-
- def __init__(self, parent) :
- self.parent=parent
- self.enrichitMCVal()
- self.enrichitListeVariables()
-
-
- def enrichitMCVal(self) :
- #=====================
- # InformationSolver : nom du wrapper, type de fichiers d'echange, etc
- #----------------------------------------------------------------------
- # Ajoute les informations sur le wrapper
- # nom du wrapper, type de fichiers d'echange, etc.
- dico = { "WrapperPath" : "Code_Aster.so",
- "FunctionName" : "Code_Aster",
- "WrapCouplingMode" : "fork",
- "State" : "shared",
- "InDataTransfer" : "files",
- "OutDataTransfer" : "files",
- }
-
- self.parent.ajouteDictMCVal(dico)
-
- #InformationSolverFile : parametres par defaut pour les fichiers d'echange
- #--------------------------------------------------------------------------
-
- liste = []
- dicoIn = { "Id" : "file_in", "Type" : "in", "Name" : "StdIn", "Path" : "commandes_aster" }
- liste.append(dicoIn)
- dicoOut = { "Id" : "file_out", "Type" : "out", "Name" : "StdOut", "Path" : "resultats_aster", }
- liste.append(dicoOut)
- dicoFile={"exchange_file" : liste}
- self.parent.ajouteDictMCVal(dicoFile)
-
-# D.2. InformationSolverCommande : arguments, etc
-#-------------------------------------------------------------------------
-# InformationSolverCommande est un dictionnaire indexe par le nom du solveur externe appele.
-# InformationSolverCommande[solveur] est lui-meme un dictionnaire qui contient les parametres
-# supplementaires pour la commande.
-# Des parametres sont donnes sous forme de tuple : (ok/nok, "mot-cle") ou (ok/nok, "mot-cle", valeur)
-# . On ajoute seulement si ok
-# . Avec (ok/nok, "mot-cle"), on ajoute en arguments les couples ("mot-cle", nom_du_parametre)
-# . Avec (ok/nok, "mot-cle", valeur), on ajoute en arguments les couples ("mot-cle", valeur)
-
-
-# dico = { "file_out" : (1, "-fic_de_aster_vers_ot"),
-# "variable_in" : (1, "-variable") }
-# self.parent.InformationSolverCommande["Code_Aster"] = dico
-
-
- def enrichitListeVariables(self) :
- # parametres par defaut pour chaque variable
- #--------------------------------------------
-
- dico_in = { "Regexp" : '"^" , "Name", "(.*)= *[0-9eE.+-]+([)]?;?)$"',
- "Format" : '"Name", "\\1=%20.13G\\2"'
- }
- dico_out = { "Regexp" : '"(.*)"' }
- self.parent.ajouteInfoVariables(dico_in,dico_out)
-
-class MonSTDGenerateur(STDGenerateur) :
-
- def CreeResu (self) :
- #------------------
- '''
- Le resultat :
- . Donnees :
- . l'algorithme choisi.
- . Resultats :
- . Ecriture des odres d'impression.
- '''
- if self.DictMCVal.has_key("Analysis"):
- self.Analysis = str(self.DictMCVal["Analysis"])
- else :
- self.Analysis = None
- self.fic_resu_OpenTURNS = "fic_resu_OpenTURNS_glop"
- Algorithm = str (self.DictMCVal["Algorithm"])
- texte = "\n\n# Le resultat\n"
- texte += DecalSTDsaut + NomResu + " = " + NomAlgo + ".getResult()"
- texte += DecalSTDsaut + "###" + "print ( " + NomResu+")"
- texte += DecalSTDsaut + "text_resu = \"Resultats\\n=======\\n\""
-
-# Particularites des algorithmes de fiabilite
-
- if self.Analysis in ( "Reliability", ) :
- texte += DecalSTDsaut + "aux = " + NomResu + ".getIsStandardPointOriginInFailureSpace()"
- texte += DecalSTDsaut + "if aux :"
- texte += DecalSTDsaut + DecalSTD + "texte_bis = \"est\""
- texte += DecalSTDsaut + "else :"
- texte += DecalSTDsaut + DecalSTD + "texte_bis = \"n\'est pas\""
- texte += DecalSTDsaut + "text_resu += \"\\nLe point initial \" + texte_bis + \" dans l\'espace de defaillance.\""
- l_aux = [ ("Probabilite de defaillance", "EventProbability") ]
- l_aux.append ( ("Indice de confiance generalise", "GeneralisedReliabilityIndex") )
- l_aux.append ( ("Indice de confiance de Hasofer", "HasoferReliabilityIndex") )
- for t_aux in l_aux :
- texte += DecalSTDsaut + "text_resu += \"\\n" + t_aux[0] + " = \" + str(" \
- + NomResu + ".get" + t_aux[1] + "())"
- l_aux = []
- l_aux.append("StandardSpaceDesignPoint")
- l_aux.append("PhysicalSpaceDesignPoint")
- l_aux.append("ImportanceFactors")
- texte += DecalSTDsaut + "l_aux_var = []"
- for DictVariable in self.ListeVariables :
- if ( DictVariable["Type"] == "in" ) :
- texte += DecalSTDsaut + "l_aux_var.append(\"" + DictVariable["Name"] + "\")"
- texte += DecalSTDsaut + "l_aux = []"
- for type_resu in l_aux :
- texte += DecalSTDsaut + "l_aux.append(" + NomResu + ".get" + type_resu + "())"
- texte += DecalSTDsaut + "for resu in l_aux :"
- texte += DecalSTDsaut + DecalSTD + "if not resu.isEmpty() :"
- texte += DecalSTDsaut + DecalSTD + DecalSTD + "text_resu += \"\\n\" + resu.getName() + \" :\""
- texte += DecalSTDsaut + DecalSTD + DecalSTD + "size = resu.getDimension()"
- texte += DecalSTDsaut + DecalSTD + DecalSTD + "l_aux_1 = resu.getCollection()"
- texte += DecalSTDsaut + DecalSTD + DecalSTD + "for iaux in range(size) :"
- texte += DecalSTDsaut + DecalSTD + DecalSTD + DecalSTD + "text_resu += \"\\n. \" + l_aux_var[iaux] + \" : \" + str(l_aux_1[iaux])"
-
-# Particularites des algorithmes de simulation
-
- if self.Analysis in ( "Simulation", ) :
- l_aux = [ ("Probabilite de defaillance", "ProbabilityEstimate") ]
- l_aux.append ( ("Variance", "VarianceEstimate") )
- l_aux.append ( ("Nombre d\'iterations", "OuterSampling") )
- for t_aux in l_aux :
- texte += DecalSTDsaut + "text_resu += \"\\n" + t_aux[0] + " = \" + str(" \
- + NomResu + ".get" + t_aux[1] + "())"
- texte += DecalSTDsaut + "text_resu += \"\\nNombre d'evaluations de l'etat limite = \" + str(" \
- + NomResu + ".getOuterSampling()*" + NomResu + ".getBlockSize())"
- if self.DictMCVal.has_key("ConfidenceIntervalProbability") :
- aux = self.DictMCVal["ConfidenceIntervalProbability"]
- texte += DecalSTDsaut + "proba = " + NomResu + ".getProbabilityEstimate()"
- texte += DecalSTDsaut + "t_aux = "
- if ( type(aux) is type(0.) ) :
- texte += "(" + str(aux) + ")"
- t_aux = [ str(aux) ]
- else :
- texte += str(aux)
- texte += DecalSTDsaut + "for val in t_aux :"
- texte += DecalSTDsaut + DecalSTD + "length = " + NomResu + ".getConfidenceLength(val)"
- texte += DecalSTDsaut + DecalSTD + "vinf = str( proba - 0.5*length )"
- texte += DecalSTDsaut + DecalSTD + "vsup = str( proba + 0.5*length )"
- texte += DecalSTDsaut + DecalSTD + "text_resu += \"\\nIntervalle de confiance a \" + str(val) + \" = [ \" "
- texte += "+ vinf + \" , \" + vsup + \" ]\""
-
-# Generalites
-
- texte += DecalSTDsaut + "d_aux = {}"
- texte += DecalSTDsaut + "d_aux[\"E\"] = ( \"de la fonction\", " + NomFunction + ".getEvaluationCallsNumber() )"
- texte += DecalSTDsaut + "d_aux[\"G\"] = ( \"du gradient\", " + NomFunction + ".getGradientCallsNumber() )"
- texte += DecalSTDsaut + "d_aux[\"H\"] = ( \"du hessien\", " + NomFunction + ".getHessianCallsNumber() )"
- texte += DecalSTDsaut + "for cle in d_aux.keys() :"
- texte += DecalSTDsaut + DecalSTD + "if d_aux[cle][1] > 0 :"
- texte += DecalSTDsaut + DecalSTD + DecalSTD + "text_resu += \"\\nNombre d\'appels au solveur pour le calcul \"" \
- + " + d_aux[cle][0] + \" = \" + str(d_aux[cle][1])"
-
-# Impression
-
- texte += DecalSTDsaut + "print ( \"\\n\", text_resu, \" ) \\n\""
- texte += DecalSTDsaut + "file_resu = open(\"" + self.fic_resu_OpenTURNS + "\", \"w\")"
- texte += DecalSTDsaut + "file_resu.write(text_resu)"
- texte += DecalSTDsaut + "file_resu.close()"
- texte += DecalSTDsaut + "probability = " + NomResu + ".getEventProbability()"
-
- return texte
-
+++ /dev/null
-# -*- coding: iso-8859-1 -*-
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-
-"""
-Ce module contient la partie commune
-aux generateurs XML et Etude d Openturns
-"""
-
-__revision__ = "V1.0"
-
-import os
-import sys
-
-path=os.getcwd()
-pathDef=path+"DefautOpenturns"
-
-sys.path.append(pathDef)
-
-
-#=============================================
-# La classe generale
-#=============================================
-
-class Generateur :
-
- '''
- Classe generale du generateur
- DictMCVal : dictionnaire des mots-cles
- ListeVariables : chaque variable est decrite par un dictionnaire ; cette liste les regroupe
- DictLois : dictionnaires des lois
- '''
- def __init__ (self, appli, DictMCVal = {}, ListeVariables = [], DictLois = {}, DictVariables = {} ) :
- #---------------------------------------------------------#
- self.ListeVariables = ListeVariables
- self.ListeVariablesIn = []
- self.ListeVariablesOut = []
- self.DictLois = DictLois
- self.DictVariables = DictVariables
- self.DictMCVal = DictMCVal
- self.DictTypeVar = {}
- self.nbVarIn = 0
- self.nbVarOut = 0
- self.creeInfoVar()
- self.appli = appli
- #
- # On charge eventuellement le Solver par defaut
- # et les valeurs par defaut du Solver (dans l init)
- #
- try :
- #if 1 :
- Solver = self.DictMCVal["PhysicalSolver"]
- import_name = "Defaut"+Solver
- self.module = __import__( import_name, globals(), locals() )
- monDefaut = self.module.Defaut( self )
- #else :
- except:
- self.module = None
-
-
- def getSTDGenerateur(self) :
- #--------------------------#
- try :
- gener = self.module.__dict__["MonSTDGenerateur"]
- monSTDGenerateur=gener( self.DictMCVal, self.ListeVariablesIn, self.ListeVariablesOut, self.DictLois )
- except :
- from OpenturnsSTD import STDGenerateur
- monSTDGenerateur = STDGenerateur( self.appli, self.DictMCVal, self.ListeVariablesIn, self.ListeVariablesOut, self.DictLois )
- return monSTDGenerateur
-
- def getXMLGenerateur(self) :
- #--------------------------#
- try :
- gener = self.module.__dict__["MonXMLGenerateur"]
- monXMLGenerateur=gener( self.DictMCVal, self.ListeVariables, self.DictLois )
- except :
- from OpenturnsXML import XMLGenerateur
- monXMLGenerateur = XMLGenerateur( self.appli, self.DictMCVal, self.DictVariables )
- return monXMLGenerateur
-
- def creeInfoVar (self) :
- #----------------------#
- """
- On repere les variables in/out et on les numerote.
- """
- num = 0
- liste = []
- for DictVariable in self.ListeVariables :
- if not DictVariable.has_key("Type") : DictVariable["Type"] = "in"
- self.DictTypeVar[num] = DictVariable["Type"]
- if DictVariable["Type"] == "in" :
- self.nbVarIn = self.nbVarIn + 1
- self.ListeVariablesIn.append( DictVariable )
- print "OpenturnsBase.py: new input variable = ", DictVariable
- else:
- self.nbVarOut = self.nbVarOut + 1
- self.ListeVariablesOut.append( DictVariable )
- print "OpenturnsBase.py: new output variable = ", DictVariable
- liste.append( DictVariable )
- num = num + 1
- self.ListeVariables = liste
-
-
- def ajouteDictMCVal(self, dicoPlus) :
- #-----------------------------------#
- # Appele par le classe Defaut du python specifique au code (exple DefautASTER.py)
- # enrichit self.DictMCVal avec les valeurs donnees dans dicoPlus
- # si elles ne sont pas deja dans le dictionnaire
-
- for clef in dicoPlus.keys():
- if not self.DictMCVal.has_key(clef) :
- self.DictMCVal[clef] = dicoPlus[clef]
-
- def ajouteInfoVariables (self, dicoVariablesIn, dicoVariablesOut) :
- #-----------------------------------------------------------------#
- # Appele par le classe Defaut du python specifique au code (exple DefautASTER.py)
- # met a jour les dictionnaires qui decrivent les variables (regexp par exemple)
- liste=[]
- num = 0
- for dictVariable in self.ListeVariables:
- if self.DictTypeVar[num] == "in" :
- dico = dicoVariablesIn
- else :
- dico = dicoVariablesOut
- for nouvelleVariable in dico.keys() :
- if not dictVariable.has_key(nouvelleVariable):
- dictVariable[nouvelleVariable] = dico[nouvelleVariable]
- liste.append( dictVariable )
- num = num + 1
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-
-"""
-Ce module contient le generateur Etude pour Openturns
-"""
-
-from Extensions.i18n import tr
-
-__revision__ = "V1.0"
-
-defaultSTD = """#! /usr/bin/env python
-
-class StudyFileGenerationError:
- def __init__ (self, st):
- self.st = st
- def __str__(self):
- return "'%s'" % self.st
-
-raise StudyFileGenerationError, "The study file was not generated. Check analysis type."
-"""
-
-headerSTD = """#! /usr/bin/env python
-
-# Chargement du module systeme
-import sys
-sys.path[:0]=['%s']
-
-# Chargement du module math
-import math
-
-# Chargement du module Open TURNS
-from openturns import *
-
-# Fonction verifiant si un echantillon contient des valeurs non valides (NaN)
-def contain_nan_values(sample):
- for point in sample:
- for val in point:
- if math.isnan(val):
- return True
- return False
-
-results = {}
-
-"""
-
-viewerSTD = """
-from openturns.viewer import View
-
-# Fonction de test du serveur X
-import subprocess
-xserver_available = None
-def is_xserver_available():
- global xserver_available
- if xserver_available is None:
- xserver_available = True
- try:
- subprocess.check_call('python -c "from matplotlib import pyplot;pyplot.figure()" >/dev/null 2>&1', shell = True)
- except:
- xserver_available = False
- return xserver_available
-
-"""
-
-footerSTD = """
-
-# Flush des messages en attente
-Log.Flush()
-
-# Terminaison du fichier
-#sys.exit( 0 )
-"""
-
-#=============================================
-# La classe de creation du fichier STD
-#=============================================
-
-class STDGenerateur :
-
- '''
- Generation du fichier python
- '''
- def __init__ (self, appli, DictMCVal, ListeVariablesIn, ListeVariablesOut, DictLois ) :
- self.DictMCVal = DictMCVal
- self.ListeVariablesIn = ListeVariablesIn
- self.ListeVariablesOut = ListeVariablesOut
- self.DictLois = DictLois
- #print "DictMCVal=", DictMCVal
- print "ListeVariablesIn= %s", ListeVariablesIn
-
-# A REPRENDRE DEPUIS ICI !!
- print "ListeVariablesOut= %s", ListeVariablesOut
- #print "DictLois=", DictLois
- self.texteSTD = defaultSTD
- self.OpenTURNS_path = appli.maConfiguration.OpenTURNS_path
-
- # Ce dictionnaire fait la correspondance entre le mot lu dans le dictionnaire des mots-clefs et la methode a appeler
- self.traitement = {
- "Min/Max" :
- ( "MinMax",
- { "Experiment Plane" : "ExperimentPlane",
- "Random Sampling" : "MinMaxRandomSampling",
- },
- ),
- "Central Uncertainty" :
- ( "CentralUncertainty",
- { "Taylor Variance Decomposition" : "TaylorVarianceDecomposition",
- "Random Sampling" : "CentralUncertaintyRandomSampling",
- },
- ),
- "Threshold Exceedence" :
- ( "ThresholdExceedence",
- { "Simulation" : "Simulation",
- "FORM_SORM" : "Analytical",
- "MonteCarlo" : "MonteCarlo",
- "LHS" : "LHS",
- "ImportanceSampling" : "ImportanceSampling",
- "FirstOrder" : "FORM",
- "SecondOrder" : "SORM",
- "Cobyla" : "Cobyla",
- "AbdoRackwitz" : "AbdoRackwitz",
- },
- ),
- }
-
- # Ce dictionnaire liste le nom des variables utilisees dans le script
- # La clef est le nom attendu par les methodes, la valeur est le nom produit dans le fichier de sortie
- # Le fait de passer par un dictionnaire permet de controler que les variables existent et sont correctement nommees
- # meme si clef == valeur
- self.variable = {
- "n" : "n",
- "p" : "p",
- "wrapper" : "wrapper",
- "wrapperdata" : "wrapperdata",
- "frameworkdata" : "frameworkdata",
- "framework" : "framework",
- "studyid" : "studyid",
- "studycase" : "studycase",
- "componentname" : "componentname",
- "model" : "model",
- "scaledVector" : "scaledVector",
- "translationVector" : "translationVector",
- "levels" : "levels",
- "myCenteredReductedGrid" : "myCenteredReductedGrid",
- "myExperimentPlane" : "myExperimentPlane",
- "inputSample" : "inputSample",
- "outputSample" : "outputSample",
- "minValue" : 'results["minValue"]',
- "maxValue" : 'results["maxValue"]',
- "flags" : "flags",
- "inSize" : "inSize",
- "distribution" : "distribution",
- "marginal" : "marginal",
- "collection" : "collection",
- "copula" : "copula",
- "correlation" : "correlation",
- "R" : "R",
- "vars" : "vars",
- "description" : "description",
- "inputRandomVector" : "inputRandomVector",
- "outputRandomVector" : "outputRandomVector",
- "myQuadraticCumul" : "myQuadraticCumul",
- "meanFirstOrder" : 'results["meanFirstOrder"]',
- "meanSecondOrder" : 'results["meanSecondOrder"]',
- "standardDeviationFirstOrder" : 'results["standardDeviationFirstOrder"]',
- "importanceFactors" : 'results["importanceFactors"]',
- "importanceFactorsGraph" : "importanceFactorsGraph",
- "importanceFactorsDrawing" : "importanceFactorsDrawing",
- "empiricalMean" : 'results["empiricalMean"]',
- "empiricalStandardDeviation" : 'results["empiricalStandardDeviation"]',
- "empiricalQuantile" : 'results["empiricalQuantile"]',
- "alpha" : "alpha",
- "beta" : "beta",
- "PCCcoefficient" : 'results["PCCcoefficient"]',
- "PRCCcoefficient" : 'results["PRCCcoefficient"]',
- "SRCcoefficient" : 'results["SRCcoefficient"]',
- "SRRCcoefficient" : 'results["SRRCcoefficient"]',
- "kernel" : "kernel",
- "kernelSmoothedDist" : "kernelSmoothedDist",
- "kernelSmoothedPDFDrawing" : "kernelSmoothedPDFDrawing",
- "kernelSmoothedGraph" : "kernelSmoothedGraph",
- "meanVector" : "meanVector",
- "importanceDensity" : "importanceDensity",
- "myEvent" : "myEvent",
- "myAlgo" : "myAlgo",
- "myResult" : "myResult",
- "probability" : 'results["probability"]',
- "standardDeviation" : 'results["standardDeviation"]',
- "level" : "level",
- "length" : "length",
- "coefficientOfVariation" : 'results["coefficientOfVariation"]',
- "convergenceGraph" : "convergenceGraph",
- "convergenceDrawing" : "convergenceDrawing",
- "simulationNumbers" : 'results["simulationNumbers"]',
- "myOptimizer" : "myOptimizer",
- "specificParameters" : "specificParameters",
- "startingPoint" : "startingPoint",
- "hasoferReliabilityIndex" : 'results["hasoferReliabilityIndex"]',
- "standardSpaceDesignPoint" : 'results["standardSpaceDesignPoint"]',
- "physicalSpaceDesignPoint" : 'results["physicalSpaceDesignPoint"]',
- "eventProbabilitySensitivity" : 'results["eventProbabilitySensitivity"]',
- "hasoferReliabilityIndexSensitivity" : 'results["hasoferReliabilityIndexSensitivity"]',
- "eventProbabilitySensitivityGraph" : "eventProbabilitySensitivityGraph",
- "eventProbabilitySensitivityDrawing" : "eventProbabilitySensitivityDrawing",
- "hasoferReliabilityIndexSensitivityGraph" : "hasoferReliabilityIndexSensitivityGraph",
- "hasoferReliabilityIndexSensitivityDrawing" : "hasoferReliabilityIndexSensitivityDrawing",
- "modelEvaluationCalls" : 'results["modelEvaluationCalls"]',
- "modelGradientCalls" : 'results["modelGradientCalls"]',
- "modelHessianCalls" : 'results["modelHessianCalls"]',
- "tvedtApproximation" : 'results["tvedtApproximation"]',
- "hohenBichlerApproximation" : 'results["hohenBichlerApproximation"]',
- "breitungApproximation" : 'results["breitungApproximation"]',
- }
-
- # Ce dictionnaire fait la correspondance entre le mot-clef du catalogue et le flag de la bibliotheque
- self.logFlags = {
- "DebugMessages" : "Log.DBG",
- "WrapperMessages" : "Log.WRAPPER",
- "UserMessages" : "Log.USER",
- "InfoMessages" : "Log.INFO",
- "WarningMessages" : "Log.WARN",
- "ErrorMessages" : "Log.ERROR",
- }
-
- def CreeSTD (self) :
- '''
- Pilotage de la creation du fichier python
- '''
- TypeAnalyse = None
- if ( self.DictMCVal.has_key( 'Type' ) ):
- TypeAnalyse = self.DictMCVal[ 'Type' ]
-
- traitement = None
- subDict = {}
- if ( self.traitement.has_key( TypeAnalyse ) ):
- (traitement, subDict) = self.traitement[ TypeAnalyse ]
-
- if ( traitement is not None ):
- self.texteSTD = apply( STDGenerateur.__dict__[ traitement ], (self, subDict) )
-
- return self.texteSTD
-
- def Header (self) :
- '''
- Imprime l entete commun a tous les fichiers
- '''
- txt = headerSTD % self.OpenTURNS_path
- txt += viewerSTD
- txt += "# Definit le niveau d'affichage de la log\n"
- txt += "%s = Log.NONE\n" % self.variable["flags"]
- for flag in self.logFlags.keys():
- if ( self.DictMCVal.has_key( flag ) ):
- val = self.DictMCVal[ flag ]
- op = "-"
- if val == 'yes' :
- op = "+"
- txt += "%s = %s %s %s\n" % (self.variable["flags"], self.variable["flags"], op, self.logFlags[ flag ])
- txt += "Log.Show( %s )\n" % self.variable["flags"]
- txt += "\n"
- return txt
-
- def Footer (self) :
- '''
- Imprime le pied de page commun a tous les fichiers
- '''
- return footerSTD
-
- def MinMax (self, subDict):
- '''
- Produit le fichier study correspondant a une analyse Min/Max
- '''
- txt = self.Header()
- txt += self.Model()
-
- Methode = None
- if ( self.DictMCVal.has_key( 'Method' ) ):
- Methode = self.DictMCVal[ 'Method' ]
-
- traitement = None
- if ( subDict.has_key( Methode ) ):
- traitement = subDict[ Methode ]
-
- if ( traitement is not None ):
- txt += apply( STDGenerateur.__dict__[ traitement ], (self,) )
-
- txt += self.MinMaxResult()
-
- txt += self.Footer()
- return txt
-
- def Model (self):
- '''
- Importe le modele physique
- '''
- if ( self.DictMCVal.has_key( 'FileName' ) ):
- name = self.DictMCVal[ 'FileName' ]
-
- txt = "# Charge le modele physique\n"
- txt += "%s = WrapperFile( '%s' )\n" % (self.variable["wrapper"], name)
- txt += "%s = %s.getWrapperData()\n" % (self.variable["wrapperdata"], self.variable["wrapper"])
-
- txt += "# Ces lignes sont utiles pour le fonctionnement du script sous Salome\n"
- txt += "if globals().has_key('%s'):\n" % self.variable["framework"]
- txt += " %s = %s.getFrameworkData()\n" % (self.variable["frameworkdata"], self.variable["wrapperdata"])
- txt += " %s.studyid_ = %s['%s']\n" % (self.variable["frameworkdata"], self.variable["framework"], self.variable["studyid"])
- txt += " %s.studycase_ = %s['%s']\n" % (self.variable["frameworkdata"], self.variable["framework"], self.variable["studycase"])
- txt += " %s.componentname_ = %s['%s']\n" % (self.variable["frameworkdata"], self.variable["framework"], self.variable["componentname"])
- txt += " %s.setFrameworkData( %s )\n" % (self.variable["wrapperdata"], self.variable["frameworkdata"])
- txt += " %s.setWrapperData( %s )\n" % (self.variable["wrapper"], self.variable["wrapperdata"])
- txt += "# Fin des lignes pour Salome\n"
-
- txt += "%s = NumericalMathFunction( %s )\n" % (self.variable["model"], self.variable["wrapper"],)
- txt += "%s = %s.getInputDimension()\n" % (self.variable["n"], self.variable["model"])
- txt += "\n"
- return txt
-
- def ExperimentPlane (self):
- '''
- Etude par plan d experience
- '''
- txt = "# Etude par plan d'experience\n"
- txt += self.Levels()
- txt += self.CenteredReductedGrid()
- txt += self.ScaledVector()
- txt += self.TranslationVector()
- txt += "%s = %s\n" % (self.variable["inputSample"], self.variable["myExperimentPlane"])
- txt += "\n"
- txt += "# Etude 'Min/Max'\n"
- txt += "# Calcul\n"
- txt += "%s = %s( %s )\n" % (self.variable["outputSample"], self.variable["model"], self.variable["inputSample"])
- txt += "if contain_nan_values( %s ):\n" % (self.variable["outputSample"])
- txt += " raise Exception('Some computations failed')\n"
- txt += "\n"
- return txt
-
- def MinMaxRandomSampling (self):
- '''
- Etude par echantillonage aleatoire
- '''
- size = 0
- if ( self.DictMCVal.has_key( 'SimulationsNumber' ) ):
- size = self.DictMCVal[ 'SimulationsNumber' ]
-
- txt = "# Etude par echantillonage aleatoire\n"
- txt += self.InputDistribution()
- txt += self.InputRandomVector()
- txt += "\n"
- txt += "# Etude 'Min/Max'\n"
- txt += "# Calcul\n"
- txt += "%s = %d\n" % (self.variable["inSize"], size)
- txt += "%s = RandomVector( %s, %s )\n" % (self.variable["outputRandomVector"], self.variable["model"], self.variable["inputRandomVector"])
- txt += "%s = %s.getSample( %s )\n" % (self.variable["outputSample"], self.variable["outputRandomVector"], self.variable["inSize"])
- txt += "if contain_nan_values( %s ):\n" % (self.variable["outputSample"])
- txt += " raise Exception('Some computations failed')\n"
- return txt
-
- def InputDistribution (self):
- '''
- Cree la loi jointe des variables d entree
- '''
- txt = "# Definit la loi jointe des variables d'entree\n"
- txt += "%s = DistributionCollection( %s )\n" % (self.variable["collection"], self.variable["n"])
- txt += "%s = Description( %s )\n" % (self.variable["description"], self.variable["n"])
- txt += "\n"
-
- dictVariables = {}
- for variable in self.ListeVariablesIn:
- nomVar = variable['ModelVariable'].getName()
- dictVariables[ nomVar ] = variable['Distribution']
-
- i = 0
- sortedVarNames = dictVariables.keys()
- sortedVarNames.sort()
- for variable in sortedVarNames:
- conceptloi = dictVariables[ variable ]
- loi = self.DictLois[ conceptloi ]
- if loi.has_key( 'Kind' ):
- marginale = "%s_%d" % (self.variable["marginal"], i)
- txt += "# Definit la loi marginale de la composante %d\n" % i
- txt += "%s = %s\n" % (marginale, apply( STDGenerateur.__dict__[ loi[ 'Kind' ] ], (self, loi) ))
- txt += "%s.setName( '%s' )\n" % (marginale, conceptloi.getName())
- txt += "%s[ %d ] = '%s'\n" % (self.variable["description"], i, variable)
- txt += "%s[ %d ] = Distribution( %s )\n" % (self.variable["collection"], i, marginale)
- txt += "\n"
- i += 1
-
- txt += self.Copula()
-
- txt += "# Definit la loi jointe\n"
- txt += "%s = ComposedDistribution( %s, Copula( %s ) )\n" % (self.variable["distribution"], self.variable["collection"], self.variable["copula"])
- txt += "%s.setDescription( %s )\n" % (self.variable["distribution"], self.variable["description"])
- txt += "\n"
- return txt
-
- def Copula (self):
- '''
- Cree la copule de la loi jointe
- '''
- txt = "# Definit la copule de la loi jointe\n"
-
- if ( not self.DictMCVal.has_key( 'Copula' ) ):
- self.DictMCVal[ 'Copula' ] = 'Independent'
-
- if ( self.DictMCVal[ 'Copula' ] in ( 'Independent', ) ):
- txt += "%s = IndependentCopula( %s )\n" % (self.variable["copula"], self.variable["n"])
- elif ( self.DictMCVal[ 'Copula' ] in ( 'Normal', ) ):
- varList = self.DictMCVal[ 'CorrelationMatrix' ][0]
- dimension = len(varList)
- txt += "%s = {}\n" % self.variable["correlation"]
- for i in range( dimension ):
- txt += "%s['%s'] = {}\n" % (self.variable["correlation"], varList[i])
- for j in range ( dimension ):
- txt += "%s['%s']['%s'] = %g\n" % (self.variable["correlation"], varList[i], varList[j], self.DictMCVal[ 'CorrelationMatrix' ][i+1][j])
- txt += "%s = getCorrelationMatrixFromMap( %s.getVariableList(), %s )\n" % (self.variable["R"], self.variable["wrapperdata"], self.variable["correlation"])
- txt += "%s = NormalCopula( %s )\n" % (self.variable["copula"], self.variable["R"])
-
- txt += "\n"
- return txt
-
- def InputRandomVector (self):
- '''
- Cree le vector aleatoire d entree
- '''
- txt = "# Definit le vecteur aleatoire d'entree\n"
- txt += "%s = RandomVector( %s )\n" % (self.variable["inputRandomVector"], self.variable["distribution"])
- txt += "\n"
- return txt
-
- def OutputRandomVector (self):
- '''
- Cree le vector aleatoire de sortie
- '''
- nomVar = "output"
- for variable in self.ListeVariablesOut:
- nomVar = variable['ModelVariable'].getName()
-
- txt = "# Definit le vecteur aleatoire de sortie\n"
- txt += "%s = RandomVector( %s, %s )\n" % (self.variable["outputRandomVector"], self.variable["model"], self.variable["inputRandomVector"])
- txt += "%s.setName( '%s' )\n" % (self.variable["outputRandomVector"], nomVar)
- txt += "\n"
- return txt
-
- def ScaledVector (self):
- '''
- Definit les coefficients multiplicateurs par composante du vecteur
- '''
- dimension = 0
- if ( self.DictMCVal.has_key( 'UnitsPerDimension' ) ):
- unitsPerDimension = self.DictMCVal[ 'UnitsPerDimension' ]
- dimension = len( unitsPerDimension )
-
- txt = "# Definit les facteurs d'echelle dans chaque direction\n"
- txt += "%s = NumericalPoint( %s )\n" % (self.variable["scaledVector"], self.variable["n"])
- for i in range(dimension):
- txt += "%s[%d] = %g\n" % (self.variable["scaledVector"], i, unitsPerDimension[i])
- txt += "%s.scale( %s )\n" % (self.variable["myExperimentPlane"], self.variable["scaledVector"])
- txt += "\n"
- return txt
-
- def TranslationVector (self):
- '''
- Definit le vecteur de translation
- '''
- dimension = 0
- if ( self.DictMCVal.has_key( 'Center' ) ):
- center = self.DictMCVal[ 'Center' ]
- dimension = len( center )
-
- txt = "# Definit le vecteur de translation\n"
- txt += "%s = NumericalPoint( %s )\n" % (self.variable["translationVector"], self.variable["n"])
- for i in range(dimension):
- txt += "%s[%d] = %g\n" % (self.variable["translationVector"], i, center[i])
- txt += "%s.translate( %s )\n" % (self.variable["myExperimentPlane"], self.variable["translationVector"])
- txt += "\n"
- return txt
-
- def Levels (self):
- '''
- Definit les niveaux du plan d experience
- '''
- dimension = 0
- if ( self.DictMCVal.has_key( 'Levels' ) ):
- levels = self.DictMCVal[ 'Levels' ]
- dimension = len( levels )
-
- txt = "# Definit les niveaux de la structure de grille\n"
- txt += "%s = NumericalPoint( %d )\n" % (self.variable["levels"], dimension)
- for i in range(dimension):
- txt += "%s[%d] = %g\n" % (self.variable["levels"], i, levels[i])
- txt += "\n"
- return txt
-
- def CenteredReductedGrid (self):
- '''
- Definit la grille reduite du plan d experience
- '''
- plane = None
- if ( self.DictMCVal.has_key( 'ExperimentPlane' ) ):
- plane = self.DictMCVal[ 'ExperimentPlane' ]
-
- txt = "# Cree le plan d'experience centre reduit\n"
- txt += "%s = %s(%s, %s)\n" % (self.variable["myCenteredReductedGrid"], plane, self.variable["n"], self.variable["levels"])
- txt += "%s = %s.generate()\n" % (self.variable["myExperimentPlane"], self.variable["myCenteredReductedGrid"])
- txt += "\n"
- return txt
-
- def MinMaxResult (self):
- '''
- Produit les resultats de l etude
- '''
- txt = "# Resultats\n"
- txt += "%s = %s.getMin()\n" % (self.variable["minValue"], self.variable["outputSample"])
- txt += "print '%s = ', %s\n" % ("minValue", self.variable["minValue"])
- txt += "\n"
- txt += "%s = %s.getMax()\n" % (self.variable["maxValue"], self.variable["outputSample"])
- txt += "print '%s = ', %s\n" % ("maxValue", self.variable["maxValue"])
- txt += "\n"
- return txt
-
- def CentralUncertainty (self, subDict):
- '''
- Produit le fichier study correspondant a une analyse d incertitude en valeur centrale
- '''
- txt = self.Header()
- txt += self.Model()
- txt += self.InputDistribution()
- txt += self.InputRandomVector()
- txt += self.OutputRandomVector()
-
- Methode = None
- if ( self.DictMCVal.has_key( 'Method' ) ):
- Methode = self.DictMCVal[ 'Method' ]
-
- traitement = None
- if ( subDict.has_key( Methode ) ):
- traitement = subDict[ Methode ]
-
- if ( traitement is not None ):
- txt += "# Etude 'Central Uncertainty'\n"
- txt += apply( STDGenerateur.__dict__[ traitement ], (self,) )
-
- txt += self.Footer()
- return txt
-
-
- def TaylorVarianceDecomposition (self):
- '''
- Etude par decomposition de Taylor
- '''
- txt = "# Cumul quadratique (decomposition de Taylor)\n"
- txt += "%s = QuadraticCumul( %s )\n" % (self.variable["myQuadraticCumul"], self.variable["outputRandomVector"])
- txt += "\n"
- txt += "# Resultats\n"
-
- if ( self.DictMCVal.has_key( 'MeanFirstOrder' ) ):
- if ( self.DictMCVal[ 'MeanFirstOrder' ] == "yes" ):
- txt += "%s = %s.getMeanFirstOrder()\n" % (self.variable["meanFirstOrder"], self.variable["myQuadraticCumul"])
- txt += "print '%s = ', %s\n" % ("mean First Order", self.variable["meanFirstOrder"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'MeanSecondOrder' ) ):
- if ( self.DictMCVal[ 'MeanSecondOrder' ] == "yes" ):
- txt += "%s = %s.getMeanSecondOrder()\n" % (self.variable["meanSecondOrder"], self.variable["myQuadraticCumul"])
- txt += "print '%s = ', %s\n" % ("mean Second Order", self.variable["meanSecondOrder"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'StandardDeviationFirstOrder' ) ):
- if ( self.DictMCVal[ 'StandardDeviationFirstOrder' ] == "yes" ):
- txt += "%s = %s.getCovariance()\n" % (self.variable["standardDeviationFirstOrder"], self.variable["myQuadraticCumul"])
- txt += "dim = %s.getDimension()\n" % self.variable["standardDeviationFirstOrder"]
- txt += "for i in range( dim ):\n"
- txt += " %s[ i, i ] = math.sqrt( %s[ i, i ] )\n" % (self.variable["standardDeviationFirstOrder"], self.variable["standardDeviationFirstOrder"])
- txt += " print '%s = ', %s[ i, i ]\n" % ("standard Deviation First Order", self.variable["standardDeviationFirstOrder"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'ImportanceFactor' ) ):
- if ( self.DictMCVal[ 'ImportanceFactor' ] == "yes" ):
- txt += "%s = %s.getImportanceFactors()\n" % (self.variable["importanceFactors"], self.variable["myQuadraticCumul"])
- txt += "for i in range(%s.getDimension()):\n" % self.variable["importanceFactors"]
- txt += " print %s.getDescription()[i], ':', %s[i]*100., '%%'\n" % (self.variable["distribution"], self.variable["importanceFactors"])
- txt += "\n"
- txt += "%s = %s.drawImportanceFactors()\n" % (self.variable["importanceFactorsGraph"], self.variable["myQuadraticCumul"])
- txt += "%s = '%s'\n" % (self.variable["importanceFactorsDrawing"], self.DictMCVal[ 'ImportanceFactorDrawingFilename' ])
- txt += "%s.draw( %s )\n" % (self.variable["importanceFactorsGraph"], self.variable["importanceFactorsDrawing"])
- txt += "#if is_xserver_available():\n"
- txt += "# view = View(%s)\n" % self.variable["importanceFactorsGraph"]
- txt += "# view.show(block=True)\n"
- txt += "#else:\n"
- txt += "# print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["importanceFactorsGraph"]
- txt += "print 'bitmap =', %s.getBitmap()\n" % self.variable["importanceFactorsGraph"]
- txt += "print 'postscript =', %s.getPostscript()\n" % self.variable["importanceFactorsGraph"]
- txt += "\n"
-
- txt += "\n"
- return txt
-
- def CentralUncertaintyRandomSampling (self):
- '''
- Etude par echantillonage aleatoire
- '''
- size = 0
- if ( self.DictMCVal.has_key( 'SimulationsNumber' ) ):
- size = self.DictMCVal[ 'SimulationsNumber' ]
-
- txt = "# Echantillonnage aleatoire de la variable de sortie\n"
- txt += "%s = %d\n" % (self.variable["inSize"], size)
- txt += "%s = %s.getSample( %s )\n" % (self.variable["inputSample"], self.variable["inputRandomVector"], self.variable["inSize"])
- txt += "%s = %s( %s )\n" % (self.variable["outputSample"], self.variable["model"], self.variable["inputSample"])
- txt += "if contain_nan_values( %s ):\n" % (self.variable["outputSample"])
- txt += " raise Exception('Some computations failed')\n"
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'EmpiricalMean' ) ):
- if ( self.DictMCVal[ 'EmpiricalMean' ] == "yes" ):
- txt += "%s = %s.computeMean()\n" % (self.variable["empiricalMean"], self.variable["outputSample"])
- txt += "print '%s =', %s[0]\n" % ("empirical Mean", self.variable["empiricalMean"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'EmpiricalStandardDeviation' ) ):
- if ( self.DictMCVal[ 'EmpiricalStandardDeviation' ] == "yes" ):
- txt += "%s = %s.computeCovariance()\n" % (self.variable["empiricalStandardDeviation"], self.variable["outputSample"])
- txt += "dim = %s.getDimension()\n" % self.variable["empiricalStandardDeviation"]
- txt += "for i in range( dim ):\n"
- txt += " %s[ i, i ] = math.sqrt( %s[ i, i ] )\n" % (self.variable["empiricalStandardDeviation"], self.variable["empiricalStandardDeviation"])
- txt += " print '%s = ', %s[ i, i ]\n" % ("empirical Standard Deviation", self.variable["empiricalStandardDeviation"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'EmpiricalQuantile_Order' ) ):
- ordre = self.DictMCVal[ 'EmpiricalQuantile_Order' ]
- txt += "%s = %s.computeQuantile( %s )\n" % (self.variable["empiricalQuantile"], self.variable["outputSample"], ordre)
- txt += "print '%s ( %s ) =', %s\n" % ("empirical Quantile", ordre, self.variable["empiricalQuantile"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'CorrelationAnalysis' ) ):
- if ( self.DictMCVal[ 'CorrelationAnalysis' ] == "yes" ):
- txt += "if ( %s.getDimension() == 1 ):\n" % self.variable["outputSample"]
- txt += " %s = CorrelationAnalysis.PCC( %s, %s )\n" % (self.variable["PCCcoefficient"], self.variable["inputSample"], self.variable["outputSample"])
- txt += " print 'PCC Coefficients:'\n"
- txt += " for i in range( %s ):\n" % self.variable["n"]
- txt += " print %s.getDescription()[i], ':', %s[i]\n" % (self.variable["distribution"], self.variable["PCCcoefficient"])
- txt += "\n"
- txt += " %s = CorrelationAnalysis.PRCC( %s, %s )\n" % (self.variable["PRCCcoefficient"], self.variable["inputSample"], self.variable["outputSample"])
- txt += " print 'PRCC Coefficients:'\n"
- txt += " for i in range( %s ):\n" % self.variable["n"]
- txt += " print %s.getDescription()[i], ':', %s[i]\n" % (self.variable["distribution"], self.variable["PRCCcoefficient"])
- txt += "\n"
- txt += " %s = CorrelationAnalysis.SRC( %s, %s )\n" % (self.variable["SRCcoefficient"], self.variable["inputSample"], self.variable["outputSample"])
- txt += " print 'SRC Coefficients:'\n"
- txt += " for i in range( %s ):\n" % self.variable["n"]
- txt += " print %s.getDescription()[i], ':', %s[i]\n" % (self.variable["distribution"], self.variable["SRCcoefficient"])
- txt += "\n"
- txt += " %s = CorrelationAnalysis.SRRC( %s, %s )\n" % (self.variable["SRRCcoefficient"], self.variable["inputSample"], self.variable["outputSample"])
- txt += " print 'SRRC Coefficients:'\n"
- txt += " for i in range( %s ):\n" % self.variable["n"]
- txt += " print %s.getDescription()[i], ':', %s[i]\n" % (self.variable["distribution"], self.variable["SRRCcoefficient"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'KernelSmoothing' ) ):
- if ( self.DictMCVal[ 'KernelSmoothing' ] == "yes" ):
- txt += "# Kernel Smoohing\n"
- txt += "%s = KernelSmoothing()\n" % self.variable["kernel"]
- txt += "if ( %s.getDimension() == 1 ):\n" % self.variable["outputSample"]
- txt += " %s.setName( 'Output' )\n" % self.variable["outputSample"]
- txt += " %s = %s.build( %s, 'TRUE')\n" % (self.variable["kernelSmoothedDist"], self.variable["kernel"], self.variable["outputSample"])
- txt += " %s = %s.drawPDF()\n" % (self.variable["kernelSmoothedGraph"], self.variable["kernelSmoothedDist"])
- txt += " %s = '%s'\n" % (self.variable["kernelSmoothedPDFDrawing"], self.DictMCVal[ 'KernelSmoothingDrawingFilename' ])
- txt += " %s.draw( %s )\n" % (self.variable["kernelSmoothedGraph"], self.variable["kernelSmoothedPDFDrawing"])
- txt += " #if is_xserver_available():\n"
- txt += " # view = View(%s)\n" % self.variable["kernelSmoothedGraph"]
- txt += " # view.show(block=True)\n"
- txt += " #else:\n"
- txt += " # print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["kernelSmoothedGraph"]
- txt += " print 'bitmap =', %s.getBitmap()\n" % self.variable["kernelSmoothedGraph"]
- txt += " print 'postscript =', %s.getPostscript()\n" % self.variable["kernelSmoothedGraph"]
- txt += "\n"
-
- return txt
-
- def ThresholdExceedence (self, subDict):
- '''
- Produit le fichier study correspondant a une analyse de depassement de seuil
- '''
- txt = self.Header()
- txt += "# Etude 'Threshold Exceedence'\n"
-
- txt += self.RandomGenerator()
- txt += self.Model()
- txt += self.InputDistribution()
- txt += self.InputRandomVector()
- txt += self.OutputRandomVector()
- txt += self.Event()
-
- Methode = None
- if ( self.DictMCVal.has_key( 'Method' ) ):
- Methode = self.DictMCVal[ 'Method' ]
-
- traitement = None
- if ( subDict.has_key( Methode ) ):
- traitement = subDict[ Methode ]
-
- if ( traitement is not None ):
- txt += apply( STDGenerateur.__dict__[ traitement ], (self, subDict) )
-
- txt += self.Footer()
- return txt
-
- def Simulation (self, subDict):
- '''
- Methodes de simulation
- '''
- Algorithme = None
- if ( self.DictMCVal.has_key( 'Algorithm' ) ):
- Algorithme = self.DictMCVal[ 'Algorithm' ]
-
- traitement = None
- if ( subDict.has_key( Algorithme ) ):
- traitement = subDict[ Algorithme ]
-
- if ( traitement is not None ):
- txt = apply( STDGenerateur.__dict__[ traitement ], (self,) )
-
- maxOuterSampling = None
- if ( self.DictMCVal.has_key( 'MaximumOuterSampling' ) ):
- maxOuterSampling = self.DictMCVal[ 'MaximumOuterSampling' ]
- txt += "%s.setMaximumOuterSampling( %s )\n" % (self.variable["myAlgo"], maxOuterSampling)
-
- blockSize = None
- if ( self.DictMCVal.has_key( 'BlockSize' ) ):
- blockSize = self.DictMCVal[ 'BlockSize' ]
- txt += "%s.setBlockSize( %s )\n" % (self.variable["myAlgo"], blockSize)
-
- maxCoefficientOfVariation = None
- if ( self.DictMCVal.has_key( 'MaximumCoefficientOfVariation' ) ):
- maxCoefficientOfVariation = self.DictMCVal[ 'MaximumCoefficientOfVariation' ]
- txt += "%s.setMaximumCoefficientOfVariation( %s )\n" % (self.variable["myAlgo"], maxCoefficientOfVariation)
-
- txt += "%s.run()\n" % self.variable["myAlgo"]
- txt += "\n"
- txt += "# Resultats de la simulation\n"
- txt += "%s = %s.getResult()\n" % (self.variable["myResult"], self.variable["myAlgo"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'Probability' ) ):
- if ( self.DictMCVal[ 'Probability' ] == "yes" ):
- txt += "%s = %s.getProbabilityEstimate()\n" % (self.variable["probability"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % ("probability", self.variable["probability"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'StandardDeviation' ) ):
- if ( self.DictMCVal[ 'StandardDeviation' ] == "yes" ):
- txt += "%s = math.sqrt( %s.getProbabilityEstimate() )\n" % (self.variable["standardDeviation"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % ("standard Deviation", self.variable["standardDeviation"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'ConfidenceInterval' ) and self.DictMCVal.has_key( 'Probability' ) ):
- if ( ( self.DictMCVal[ 'ConfidenceInterval' ] == "yes" ) and ( self.DictMCVal[ 'Probability' ] == "yes" ) ):
- level = self.DictMCVal[ 'Level' ]
- txt += "%s = %s.getConfidenceLength( %s )\n" % (self.variable["length"], self.variable["myResult"], level)
- txt += "print 'confidence interval at %s = [', %s-0.5*%s, ',', %s+0.5*%s, ']'\n" % (level, self.variable["probability"], self.variable["length"], self.variable["probability"], self.variable["length"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'VariationCoefficient' ) ):
- if ( self.DictMCVal[ 'VariationCoefficient' ] == "yes" ):
- txt += "%s = %s.getCoefficientOfVariation()\n" % (self.variable["coefficientOfVariation"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % ("coefficient of Variation", self.variable["coefficientOfVariation"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'SimulationsNumber' ) ):
- if ( self.DictMCVal[ 'SimulationsNumber' ] == "yes" ):
- txt += "%s = %s.getOuterSampling()\n" % (self.variable["simulationNumbers"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % ("simulation Numbers", self.variable["simulationNumbers"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'ConvergenceGraph' ) and self.DictMCVal.has_key( 'ConfidenceInterval' ) ):
- if ( ( self.DictMCVal[ 'ConvergenceGraph' ] == "yes" ) and ( self.DictMCVal[ 'ConfidenceInterval' ] == "yes" ) ):
- txt += "%s = %s\n" % (self.variable["alpha"], self.DictMCVal[ 'Level' ])
- txt += "%s = %s.drawProbabilityConvergence( %s )\n" % (self.variable["convergenceGraph"], self.variable["myAlgo"], self.variable["alpha"])
- txt += "%s = '%s'\n" % (self.variable["convergenceDrawing"], self.DictMCVal[ 'ConvergenceDrawingFilename' ])
- txt += "%s.draw( %s )\n" % (self.variable["convergenceGraph"], self.variable["convergenceDrawing"])
- txt += "#if is_xserver_available():\n"
- txt += "# view = View(%s)\n" % self.variable["convergenceGraph"]
- txt += "# view.show(block=True)\n"
- txt += "#else:\n"
- txt += "# print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["convergenceGraph"]
- txt += "\n"
-
- return txt
-
- def Analytical (self, subDict):
- '''
- Methodes analytiques
- '''
- txt = ""
-
- OptimizationAlgo = None
- if ( self.DictMCVal.has_key( 'OptimizationAlgorithm' ) ):
- OptimizationAlgo = self.DictMCVal[ 'OptimizationAlgorithm' ]
-
- traitement = None
- if ( subDict.has_key( OptimizationAlgo ) ):
- traitement = subDict[ OptimizationAlgo ]
-
- if ( traitement is not None ):
- txt += apply( STDGenerateur.__dict__[ traitement ], (self,) )
-
- txt += self.OptimizerSettings()
- txt += self.PhysicalStartingPoint()
-
- Approximation = None
- if ( self.DictMCVal.has_key( 'Approximation' ) ):
- Approximation = self.DictMCVal[ 'Approximation' ]
-
- traitement = None
- if ( subDict.has_key( Approximation ) ):
- traitement = subDict[ Approximation ]
-
- if ( traitement is not None ):
- txt += apply( STDGenerateur.__dict__[ traitement ], (self,) )
-
- txt += self.RunAlgorithm()
- txt += self.AnalyticalResult()
-
- return txt
-
- def OptimizerSettings (self):
- '''
- Parametrage de l optimiseur
- '''
- txt = ""
-
- simulationNumbers = None
- if ( self.DictMCVal.has_key( 'MaximumIterationsNumber' ) ):
- simulationNumbers = self.DictMCVal[ 'MaximumIterationsNumber' ]
- txt += "%s.setMaximumIterationsNumber( %s )\n" % (self.variable["myOptimizer"], simulationNumbers)
-
- absoluteError = None
- if ( self.DictMCVal.has_key( 'MaximumAbsoluteError' ) ):
- absoluteError = self.DictMCVal[ 'MaximumAbsoluteError' ]
- txt += "%s.setMaximumAbsoluteError( %s )\n" % (self.variable["myOptimizer"], absoluteError)
-
- relativeError = None
- if ( self.DictMCVal.has_key( 'MaximumRelativeError' ) ):
- relativeError = self.DictMCVal[ 'MaximumRelativeError' ]
- txt += "%s.setMaximumRelativeError( %s )\n" % (self.variable["myOptimizer"], relativeError)
-
- residualError = None
- if ( self.DictMCVal.has_key( 'MaximumResidualError' ) ):
- residualError = self.DictMCVal[ 'MaximumResidualError' ]
- txt += "%s.setMaximumResidualError( %s )\n" % (self.variable["myOptimizer"], residualError)
-
- constraintError = None
- if ( self.DictMCVal.has_key( 'MaximumConstraintError' ) ):
- constraintError = self.DictMCVal[ 'MaximumConstraintError' ]
- txt += "%s.setMaximumConstraintError( %s )\n" % (self.variable["myOptimizer"], constraintError)
-
- txt += "\n"
-
- return txt
-
- def PhysicalStartingPoint (self):
- '''
- Point physique de depart
- '''
- txt = "# Point physique de depart\n"
-
- if ( self.DictMCVal.has_key( 'PhysicalStartingPoint' ) ):
- point = self.DictMCVal[ 'PhysicalStartingPoint' ]
- dimension = len( point )
- txt += "%s = NumericalPoint( %d )\n" % (self.variable["startingPoint"], dimension)
- for i in range( dimension ):
- txt += "%s[ %d ] = %g\n" % (self.variable["startingPoint"], i, point[i])
- else:
- txt += "%s = %s.getMean()\n" % (self.variable["startingPoint"], self.variable["inputRandomVector"])
-
- txt += "\n"
-
- return txt
-
- def AnalyticalResult (self):
- '''
- Resultat des methodes analytiques
- '''
- txt = "# Resultat des methodes analytiques\n"
- txt += "%s = %s.getResult()\n" % (self.variable["myResult"], self.variable["myAlgo"])
-
- if ( self.DictMCVal.has_key( 'Probability' ) ):
- if ( self.DictMCVal[ 'Probability' ] == "yes" ):
- txt += "%s = %s.getEventProbability()\n" % (self.variable["probability"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % (self.variable["probability"], self.variable["probability"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'HasoferReliabilityIndex' ) ):
- if ( self.DictMCVal[ 'HasoferReliabilityIndex' ] == "yes" ):
- txt += "%s = %s.getHasoferReliabilityIndex()\n" % (self.variable["hasoferReliabilityIndex"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % ("hasofer Reliability Index", self.variable["hasoferReliabilityIndex"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'DesignPoint' ) ):
- if ( self.DictMCVal[ 'DesignPoint' ] == "yes" ):
- txt += "%s = %s.getStandardSpaceDesignPoint()\n" % (self.variable["standardSpaceDesignPoint"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % ("standard Space Design Point", self.variable["standardSpaceDesignPoint"])
- txt += "%s = %s.getPhysicalSpaceDesignPoint()\n" % (self.variable["physicalSpaceDesignPoint"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % ("physical Space Design Point", self.variable["physicalSpaceDesignPoint"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'ImportanceFactor' ) ):
- if ( self.DictMCVal[ 'ImportanceFactor' ] == "yes" ):
- txt += "print 'Importance Factors:'\n"
- txt += "%s = %s.getImportanceFactors()\n" % (self.variable["importanceFactors"], self.variable["myResult"])
- txt += "for i in range(%s.getDimension()):\n" % self.variable["importanceFactors"]
- txt += " print %s.getDescription()[i], ':', %s[i]*100., '%%'\n" % (self.variable["distribution"], self.variable["importanceFactors"])
- txt += "\n"
- txt += "%s = %s.drawImportanceFactors()\n" % (self.variable["importanceFactorsGraph"], self.variable["myResult"])
- txt += "%s = '%s'\n" % (self.variable["importanceFactorsDrawing"], self.DictMCVal[ 'ImportanceFactorDrawingFilename' ])
- txt += "%s.draw( %s )\n" % (self.variable["importanceFactorsGraph"], self.variable["importanceFactorsDrawing"])
- txt += "#if is_xserver_available():\n"
- txt += "# view = View(%s)\n" % self.variable["importanceFactorsGraph"]
- txt += "# view.show(block=True)\n"
- txt += "#else:\n"
- txt += "# print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["importanceFactorsGraph"]
- txt += "print 'bitmap =', %s.getBitmap()\n" % self.variable["importanceFactorsGraph"]
- txt += "print 'postscript =', %s.getPostscript()\n" % self.variable["importanceFactorsGraph"]
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'FORMEventProbabilitySensitivity' ) ):
- if ( self.DictMCVal[ 'FORMEventProbabilitySensitivity' ] == "yes" ):
- txt += "%s = %s.getEventProbabilitySensitivity()\n" % (self.variable["eventProbabilitySensitivity"], self.variable["myResult"])
- txt += "print 'FORM Event Probability Sensitivity:'\n"
- txt += "for i in range( %s ):\n" % self.variable["n"]
- txt += " print %s.getDescription()[i], ':'\n" % self.variable["distribution"]
- txt += " for j in range( %s[i].getDimension() ):\n" % self.variable["eventProbabilitySensitivity"]
- txt += " print ' ', %s[i].getDescription()[j], ':', %s[i][j]\n" % (self.variable["eventProbabilitySensitivity"], self.variable["eventProbabilitySensitivity"])
- txt += "\n"
- txt += "%s = %s.drawEventProbabilitySensitivity()[0]\n" % (self.variable["eventProbabilitySensitivityGraph"], self.variable["myResult"])
- txt += "%s = '%s'\n" % (self.variable["eventProbabilitySensitivityDrawing"], self.DictMCVal[ 'FORMEventProbabilitySensitivityDrawingFilename' ])
- txt += "%s.draw( %s )\n" % (self.variable["eventProbabilitySensitivityGraph"], self.variable["eventProbabilitySensitivityDrawing"])
- txt += "#if is_xserver_available():\n"
- txt += "# view = View(%s)\n" % self.variable["eventProbabilitySensitivityGraph"]
- txt += "# view.show(block=True)\n"
- txt += "#else:\n"
- txt += "# print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["eventProbabilitySensitivityGraph"]
- txt += "print 'bitmap =', %s.getBitmap()\n" % self.variable["eventProbabilitySensitivityGraph"]
- txt += "print 'postscript =', %s.getPostscript()\n" % self.variable["eventProbabilitySensitivityGraph"]
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'HasoferReliabilityIndexSensitivity' ) ):
- if ( self.DictMCVal[ 'HasoferReliabilityIndexSensitivity' ] == "yes" ):
- txt += "%s = %s.getHasoferReliabilityIndexSensitivity()\n" % (self.variable["hasoferReliabilityIndexSensitivity"], self.variable["myResult"])
- txt += "print 'Hasofer Reliability Index Sensitivity:'\n"
- txt += "for i in range( %s ):\n" % self.variable["n"]
- txt += " print %s.getDescription()[i], ':'\n" % self.variable["distribution"]
- txt += " for j in range( %s[i].getDimension() ):\n" % self.variable["hasoferReliabilityIndexSensitivity"]
- txt += " print ' ', %s[i].getDescription()[j], ':', %s[i][j]\n" % (self.variable["hasoferReliabilityIndexSensitivity"], self.variable["hasoferReliabilityIndexSensitivity"])
- txt += "\n"
- txt += "%s = %s.drawHasoferReliabilityIndexSensitivity()[0]\n" % (self.variable["hasoferReliabilityIndexSensitivityGraph"], self.variable["myResult"])
- txt += "%s = '%s'\n" % (self.variable["hasoferReliabilityIndexSensitivityDrawing"], self.DictMCVal[ 'HasoferReliabilityIndexSensitivityDrawingFilename' ])
- txt += "%s.draw( %s )\n" % (self.variable["hasoferReliabilityIndexSensitivityGraph"], self.variable["hasoferReliabilityIndexSensitivityDrawing"])
- txt += "#if is_xserver_available():\n"
- txt += "# view = View(%s)\n" % self.variable["hasoferReliabilityIndexSensitivityGraph"]
- txt += "# view.show(block=True)\n"
- txt += "#else:\n"
- txt += "# print 'Warning: cannot display image', %s.getBitmap(), '(probably because no X server was found)'\n" % self.variable["hasoferReliabilityIndexSensitivityGraph"]
- txt += "print 'bitmap =', %s.getBitmap()\n" % self.variable["hasoferReliabilityIndexSensitivityGraph"]
- txt += "print 'postscript =', %s.getPostscript()\n" % self.variable["hasoferReliabilityIndexSensitivityGraph"]
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'TvedtApproximation' ) ):
- if ( self.DictMCVal[ 'TvedtApproximation' ] == "yes" ):
- txt += "%s = %s.getEventProbabilityTvedt()\n" % (self.variable["tvedtApproximation"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % ("Tvedt Approximation", self.variable["tvedtApproximation"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'HohenBichlerApproximation' ) ):
- if ( self.DictMCVal[ 'HohenBichlerApproximation' ] == "yes" ):
- txt += "%s = %s.getEventProbabilityHohenBichler()\n" % (self.variable["hohenBichlerApproximation"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % ("HohenBichler Approximation", self.variable["tvedtApproximation"])
- txt += "\n"
-
- if ( self.DictMCVal.has_key( 'BreitungApproximation' ) ):
- if ( self.DictMCVal[ 'BreitungApproximation' ] == "yes" ):
- txt += "%s = %s.getEventProbabilityBreitung()\n" % (self.variable["breitungApproximation"], self.variable["myResult"])
- txt += "print '%s =', %s\n" % ("Breitung Approximation", self.variable["breitungApproximation"])
- txt += "\n"
-
-
- return txt
-
- def RandomGenerator (self):
- '''
- Generateur Aleatoire
- '''
- txt = ""
-
- seed = None
- if ( self.DictMCVal.has_key( 'RandomGeneratorSeed' ) ):
- seed = self.DictMCVal[ 'RandomGeneratorSeed' ]
- txt += "# Initialise le generateur aleatoire\n"
- txt += "RandomGenerator.SetSeed( %s )\n" % seed
- txt += "\n"
-
- return txt
-
- def Event (self):
- '''
- Definition de l evenement de defaillance
- '''
- operator = None
- if ( self.DictMCVal.has_key( 'ComparisonOperator' ) ):
- operator = self.DictMCVal[ 'ComparisonOperator' ]
-
- threshold = None
- if ( self.DictMCVal.has_key( 'Threshold' ) ):
- threshold = self.DictMCVal[ 'Threshold' ]
-
- txt = "# Evenement de defaillance\n"
- txt += "%s = Event( %s, ComparisonOperator( %s() ), %s )\n" % (self.variable["myEvent"], self.variable["outputRandomVector"], operator, threshold)
- txt += "%s.setName( '%s' )\n" % (self.variable["myEvent"], "myEvent")
- txt += "\n"
- return txt
-
- def MonteCarlo (self):
- '''
- Methode de MonteCarlo
- '''
- txt = "# Simulation par MonteCarlo\n"
- txt += "%s = MonteCarlo( %s )\n" % (self.variable["myAlgo"], self.variable["myEvent"])
- txt += "\n"
-
- return txt
-
- def LHS (self):
- '''
- Methode LHS
- '''
- txt = "# Simulation par LHS\n"
- txt += "%s = LHS( %s )\n" % (self.variable["myAlgo"], self.variable["myEvent"])
- txt += "\n"
-
- return txt
-
- def ImportanceSampling (self):
- '''
- Methode de tirage d importance
- '''
- dimension = 0
- if ( self.DictMCVal.has_key( 'MeanVector' ) ):
- meanVector = self.DictMCVal[ 'MeanVector' ]
- dimension = len( meanVector )
-
- txt = "# Simulation par Tirage d'importance\n"
- txt += "# Densite d'importance\n"
- txt += "%s = NumericalPoint( %s )\n" % (self.variable["meanVector"], self.variable["n"])
- for i in range(dimension):
- txt += "%s[%d] = %g\n" % (self.variable["meanVector"], i, meanVector[i])
-
- txt += "%s = Normal( %s, CovarianceMatrix( IdentityMatrix( %s ) ) )\n" % (self.variable["importanceDensity"], self.variable["meanVector"], self.variable["n"])
- txt += "%s = ImportanceSampling( %s, Distribution( %s ) )\n" % (self.variable["myAlgo"], self.variable["myEvent"], self.variable["importanceDensity"])
- txt += "\n"
-
- return txt
-
- def FORM (self):
- '''
- Methode FORM
- '''
- txt = "# Algorithme FORM\n"
- txt += "%s = FORM ( NearestPointAlgorithm( %s ), %s, %s )\n" % (self.variable["myAlgo"], self.variable["myOptimizer"], self.variable["myEvent"], self.variable["startingPoint"])
- txt += "\n"
-
- return txt
-
- def SORM (self):
- '''
- Methode SORM
- '''
- txt = "# Algorithme SORM\n"
- txt += "%s = SORM ( NearestPointAlgorithm( %s ), %s, %s )\n" % (self.variable["myAlgo"], self.variable["myOptimizer"], self.variable["myEvent"], self.variable["startingPoint"])
- txt += "\n"
-
- return txt
-
- def RunAlgorithm (self):
- '''
- Do the computation
- '''
- txt = ""
- if ( self.DictMCVal.has_key( 'FunctionCallsNumber' ) ):
- if ( self.DictMCVal[ 'FunctionCallsNumber' ] == "yes" ):
- txt += "%s = %s.getEvaluationCallsNumber()\n" % (self.variable["modelEvaluationCalls"], self.variable["model"])
- txt += "%s = %s.getGradientCallsNumber()\n" % (self.variable["modelGradientCalls"], self.variable["model"])
- txt += "%s = %s.getHessianCallsNumber()\n" % (self.variable["modelHessianCalls"], self.variable["model"])
- txt += "\n"
-
- txt += "# Perform the computation\n"
- txt += "%s.run()\n" % self.variable["myAlgo"]
- txt += "\n"
-
-
- if ( self.DictMCVal.has_key( 'FunctionCallsNumber' ) ):
- if ( self.DictMCVal[ 'FunctionCallsNumber' ] == "yes" ):
- txt += "%s = %s.getEvaluationCallsNumber() - %s\n" % (self.variable["modelEvaluationCalls"], self.variable["model"], self.variable["modelEvaluationCalls"])
- txt += "%s = %s.getGradientCallsNumber() - %s\n" % (self.variable["modelGradientCalls"], self.variable["model"], self.variable["modelGradientCalls"])
- txt += "%s = %s.getHessianCallsNumber() - %s\n" % (self.variable["modelHessianCalls"], self.variable["model"], self.variable["modelHessianCalls"])
- txt += "\n"
- txt += "print '%s =', %s\n" % ("model Evaluation Calls", self.variable["modelEvaluationCalls"])
- txt += "print '%s =', %s\n" % ("model Gradient Calls", self.variable["modelGradientCalls"])
- txt += "print '%s =', %s\n" % ("model Hessian Calls", self.variable["modelHessianCalls"])
- txt += "\n"
-
- return txt
-
- def Cobyla (self):
- '''
- Methode Cobyla
- '''
- txt = "# Optimisation par Cobyla\n"
- txt += "%s = Cobyla()\n" % self.variable["myOptimizer"]
- txt += "#%s = CobylaSpecificParameters()\n" % self.variable["specificParameters"]
- txt += "#%s.setSpecificParameters( %s )\n" % (self.variable["myOptimizer"], self.variable["specificParameters"])
- txt += "\n"
-
- return txt
-
- def AbdoRackwitz (self):
- '''
- Methode AbdoRackwitz
- '''
- txt = "# Optimisation par AbdoRackwitz\n"
- txt += "%s = AbdoRackwitz()\n" % self.variable["myOptimizer"]
- txt += "#%s = AbdoRackwitzSpecificParameters()\n" % self.variable["specificParameters"]
- txt += "#%s.setSpecificParameters( %s )\n" % (self.variable["myOptimizer"], self.variable["specificParameters"])
- txt += "\n"
- return txt
-
- def Beta (self, loi):
- '''
- Definition de la loi Beta
- '''
- settings = {
- "RT" : "Beta.RT",
- "MuSigma" : "Beta.MUSIGMA",
- }
- if loi[ 'Settings' ] == 'RT' :
- arg1 = loi[ 'R' ]
- arg2 = loi[ 'T' ]
- else :
- arg1 = loi[ 'Mu' ]
- arg2 = loi[ 'Sigma' ]
-
- arg3 = loi[ 'A' ]
- arg4 = loi[ 'B' ]
- txt = "Beta( %g, %g, %g, %g, %s )" % (arg1, arg2, arg3, arg4, settings[ loi[ 'Settings' ] ])
- return txt
-
- def Exponential (self, loi):
- '''
- Definition de la loi Exponential
- '''
- arg1 = loi[ 'Lambda' ]
- arg2 = loi[ 'Gamma' ]
- txt = "Exponential( %g, %g )" % (arg1, arg2)
- return txt
-
- def Gamma (self, loi):
- '''
- Definition de la loi Gamma
- '''
- settings = {
- "KLambda" : "Gamma.KLAMBDA",
- "MuSigma" : "Gamma.MUSIGMA",
- }
- if loi[ 'Settings' ] == 'KLambda' :
- arg1 = loi[ 'K' ]
- arg2 = loi[ 'Lambda' ]
- else :
- arg1 = loi[ 'Mu' ]
- arg2 = loi[ 'Sigma' ]
-
- arg3 = loi[ 'Gamma' ]
- txt = "Gamma( %g, %g, %g, %s )" % (arg1, arg2, arg3, settings[ loi[ 'Settings' ] ])
- return txt
-
- def Geometric (self, loi):
- '''
- Definition de la loi Geometric
- '''
- txt = "Geometric( %g )" % loi[ 'P' ]
- return txt
-
- def Gumbel (self, loi):
- '''
- Definition de la loi Gumbel
- '''
- settings = {
- "AlphaBeta" : "Gumbel.ALPHABETA",
- "MuSigma" : "Gumbel.MUSIGMA",
- }
- if loi[ 'Settings' ] == 'AlphaBeta' :
- arg1 = loi[ 'Alpha' ]
- arg2 = loi[ 'Beta' ]
- else :
- arg1 = loi[ 'Mu' ]
- arg2 = loi[ 'Sigma' ]
-
- txt = "Gumbel( %g, %g, %s )" % (arg1, arg2, settings[ loi[ 'Settings' ] ])
- return txt
-
- def Histogram (self, loi):
- '''
- Definition de la loi Histogram
- '''
- arg1 = loi[ 'First' ]
- arg2 = loi[ 'Values' ]
- txt = "Histogram( %g, %s )" % (arg1, arg2)
- return txt
-
- def Laplace (self, loi):
- '''
- Definition de la loi Laplace
- '''
- arg1 = loi[ 'Lambda' ]
- arg2 = loi[ 'Mu' ]
- txt = "Laplace( %g, %g )" % (arg1, arg2)
- return txt
-
- def Logistic (self, loi):
- '''
- Definition de la loi Logistic
- '''
- arg1 = loi[ 'Alpha' ]
- arg2 = loi[ 'Beta' ]
- txt = "Logistic( %g, %g )" % (arg1, arg2)
- return txt
-
- def LogNormal (self, loi):
- '''
- Definition de la loi LogNormal
- '''
- settings = {
- "MuSigmaLog" : "LogNormal.MUSIGMA_LOG",
- "MuSigma" : "LogNormal.MUSIGMA",
- "MuSigmaOverMu" : "LogNormal.MU_SIGMAOVERMU",
- }
- if loi[ 'Settings' ] == 'MuSigmaLog' :
- arg1 = loi[ 'MuLog' ]
- arg2 = loi[ 'SigmaLog' ]
- elif loi[ 'Settings' ] == 'MuSigmaOverMu' :
- arg1 = loi[ 'Mu' ]
- arg2 = loi[ 'SigmaOverMu' ]
- else :
- arg1 = loi[ 'Mu' ]
- arg2 = loi[ 'Sigma' ]
-
- arg3 = loi[ 'Gamma' ]
- txt = "LogNormal( %g, %g, %g, %s )" % (arg1, arg2, arg3, settings[ loi[ 'Settings' ] ])
- return txt
-
- def MultiNomial (self, loi):
- '''
- Definition de la loi MultiNomial
- '''
- arg1 = loi[ 'Values' ]
- arg2 = loi[ 'N' ]
- txt = "MultiNomial( NumericalPoint( %s ) , %d)" % (arg1, arg2)
- return txt
-
- def NonCentralStudent (self, loi):
- '''
- Definition de la loi NonCentralStudent
- '''
- arg1 = loi[ 'Nu' ]
- arg2 = loi[ 'Delta' ]
- arg3 = loi[ 'Gamma' ]
- txt = "NonCentralStudent( %g, %g )" % (arg1, arg2, arg3)
- return txt
-
- def Normal (self, loi):
- '''
- Definition de la loi Normal
- '''
- arg1 = loi[ 'Mu' ]
- arg2 = loi[ 'Sigma' ]
- txt = "Normal( %g, %g )" % (arg1, arg2)
- return txt
-
- def TruncatedNormal (self, loi):
- '''
- Definition de la loi TruncatedNormal
- '''
- arg1 = loi[ 'MuN' ]
- arg2 = loi[ 'SigmaN' ]
- arg3 = loi[ 'A' ]
- arg4 = loi[ 'B' ]
- txt = "TruncatedNormal( %g, %g, %g, %g )" % (arg1, arg2, arg3, arg4)
- return txt
-
- def Poisson (self, loi):
- '''
- Definition de la loi Poisson
- '''
- txt = "Poisson( %g )" % loi[ 'Lambda' ]
- return txt
-
- def Rayleigh (self, loi):
- '''
- Definition de la loi Rayleigh
- '''
- arg1 = loi[ 'Sigma' ]
- arg2 = loi[ 'Gamma' ]
- txt = "Rayleigh( %g, %g )" % (arg1, arg2)
- return txt
-
- def Student (self, loi):
- '''
- Definition de la loi Student
- '''
- arg1 = loi[ 'Mu' ]
- arg2 = loi[ 'Nu' ]
- arg3 = loi[ 'Sigma' ]
- txt = "Student( %g, %g, %g )" % (arg1, arg2, arg3)
- return txt
-
- def Triangular (self, loi):
- '''
- Definition de la loi Triangular
- '''
- arg1 = loi[ 'A' ]
- arg2 = loi[ 'M' ]
- arg3 = loi[ 'B' ]
- txt = "Triangular( %g, %g, %g )" % (arg1, arg2, arg3)
- return txt
-
- def Uniform (self, loi):
- '''
- Definition de la loi Uniform
- '''
- arg1 = loi[ 'A' ]
- arg2 = loi[ 'B' ]
- txt = "Uniform( %g, %g )" % (arg1, arg2)
- return txt
-
- def UserDefined (self, loi):
- '''
- Definition de la loi UserDefined
- '''
- txt = "** UserDefined not defined yet **"
- return txt
-
- def Weibull (self, loi):
- '''
- Definition de la loi Weibull
- '''
- settings = {
- "AlphaBeta" : "Weibull.ALPHABETA",
- "MuSigma" : "Weibull.MUSIGMA",
- }
- if loi[ 'Settings' ] == 'AlphaBeta' :
- arg1 = loi[ 'Alpha' ]
- arg2 = loi[ 'Beta' ]
- else :
- arg1 = loi[ 'Mu' ]
- arg2 = loi[ 'Sigma' ]
-
- arg3 = loi[ 'Gamma' ]
- txt = "Weibull( %g, %g, %g, %s )" % (arg1, arg2, arg3, settings[ loi[ 'Settings' ] ])
- return txt
-
-
-
- def GraphiquePDF (self, loi, chemin, fichier):
- '''
- Produit une image PNG representant la PDF de la loi
- '''
- txt = headerSTD % self.OpenTURNS_path
- txt += "dist = %s\n" % apply( STDGenerateur.__dict__[ loi[ 'Kind' ] ], (self, loi) )
- txt += "graph = dist.drawPDF()\n"
- txt += "graph.draw( '%s/%s' , 640, 480, GraphImplementation.PNG)\n" % (chemin, fichier)
- txt += footerSTD
- return txt
-
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
-Ce module contient le generateur XML pour Openturns
-"""
-import sys
-print sys.path
-from Extensions.i18n import tr
-import openturns
-
-# Dictionnaires de conversion des valeurs lues dans EFICAS
-# en valeurs reconnues par Open TURNS
-# Les clefs 'None' sont les valeurs par defaut
-
-VariableTypeByName = {
- "in" : openturns.WrapperDataVariableType.IN,
- "out" : openturns.WrapperDataVariableType.OUT,
- None : openturns.WrapperDataVariableType.IN,
- }
-
-FileTypeByName = {
- "in" : openturns.WrapperDataFileType.IN,
- "out" : openturns.WrapperDataFileType.OUT,
- None : openturns.WrapperDataFileType.IN,
- }
-
-SymbolProvidedByName = {
- "no" : openturns.WrapperSymbolProvided.NO,
- "yes" : openturns.WrapperSymbolProvided.YES,
- None : openturns.WrapperSymbolProvided.NO,
- }
-
-WrapperStateByName = {
- "shared" : openturns.WrapperState.SHARED,
- "specific" : openturns.WrapperState.SPECIFIC,
- None : openturns.WrapperState.SPECIFIC,
- }
-
-WrapperModeByName = {
- "static-link" : openturns.WrapperMode.STATICLINK,
- "dynamic-link" : openturns.WrapperMode.DYNAMICLINK,
- "fork" : openturns.WrapperMode.FORK,
- None : openturns.WrapperMode.FORK,
- }
-
-WrapperDataTransferByName = {
- "files" : openturns.WrapperDataTransfer.FILES,
- "pipe" : openturns.WrapperDataTransfer.PIPE,
- "arguments" : openturns.WrapperDataTransfer.ARGUMENTS,
- "socket" : openturns.WrapperDataTransfer.SOCKET,
- "corba" : openturns.WrapperDataTransfer.CORBA,
- None : openturns.WrapperDataTransfer.FILES,
- }
-
-#==========================
-# La classe de creation XML
-#==========================
-
-class XMLGenerateur :
-
- '''
- Generation du fichier XML
- '''
- def __init__ (self, appli, DictMCVal, DictVariables ) :
- self.DictMCVal = DictMCVal
- self.DictVariables = DictVariables
- self.appli = appli
-
- def CreeXML (self) :
- '''
- Pilotage general de la creation du fichier XML
- '''
- data = openturns.WrapperData()
- data.setLibraryPath( self.GetMCVal('WrapperPath','') )
- data.setVariableList( self.VariableList() )
- data.setFunctionDescription( self.FunctionDefinition() )
- data.setGradientDescription( self.GradientDefinition() )
- data.setHessianDescription( self.HessianDefinition() )
- data.setFileList( self.FileList() )
- data.setParameters( self.Parameters() )
- #data.setFrameworkData( self.FrameworkData() )
-
- wrapper=openturns.WrapperFile()
- wrapper.setWrapperData( data )
-
- return wrapper
-
-
- class __variable_ordering:
- def __init__ (self, dictVar) :
- self.dictVar = dictVar
-
- def __call__(self, a, b):
- return self.dictVar[a]['numOrdre'] - self.dictVar[b]['numOrdre']
-
- def VariableList (self) :
- '''
- Ecrit la liste des variables
- '''
- varList = openturns.WrapperDataVariableCollection()
- for var in sorted( self.DictVariables.keys(), self.__variable_ordering( self.DictVariables ) ) :
- varList.add( self.Variable( var, self.DictVariables[var] ) )
- return varList
-
- def Variable (self, var, dictVar) :
- '''
- Ecrit le parametrage d une variable
- '''
- variable = openturns.WrapperDataVariable()
- variable.id_ = var
- if dictVar[ 'Type' ] in VariableTypeByName.keys() :
- variable.type_ = VariableTypeByName[ dictVar[ 'Type' ] ]
- if dictVar.has_key('Comment') : variable.comment_ = dictVar[ 'Comment' ]
- if dictVar.has_key('Unit') : variable.unit_ = dictVar[ 'Unit' ]
- if dictVar.has_key('Regexp') : variable.regexp_ = dictVar[ 'Regexp' ]
- if dictVar.has_key('Format') : variable.format_ = dictVar[ 'Format' ]
- return variable
-
- def FunctionDefinition (self) :
- '''
- Ecrit la description de la Fonction
- '''
- func = openturns.WrapperFunctionDescription()
- func.name_ = self.GetMCVal( 'FunctionName', '' )
- if (len(func.name_) != 0) : func.provided_ = SymbolProvidedByName[ 'yes' ]
- return func
-
- def GradientDefinition (self) :
- '''
- Ecrit la description du Gradient
- '''
- grad = openturns.WrapperFunctionDescription()
- grad.name_ = self.GetMCVal( 'GradientName', '' )
- if (len(grad.name_) != 0) : grad.provided_ = SymbolProvidedByName[ 'yes' ]
- return grad
-
- def HessianDefinition (self) :
- '''
- Ecrit la description de la Hessienne
- '''
- hess = openturns.WrapperFunctionDescription()
- hess.name_ = self.GetMCVal( 'HessianName', '' )
- if (len(hess.name_) != 0) : hess.provided_ = SymbolProvidedByName[ 'yes' ]
- return hess
-
-
-
- def FileList (self) :
- '''
- Ecrit la liste des fichiers
- '''
- fileList = openturns.WrapperDataFileCollection()
- for dictFile in self.GetMCVal('Files', []) :
- fileList.add( self.File( dictFile ) )
- return fileList
-
- def File (self, dictFile ) :
- '''
- Ecrit le parametrage d un fichier
- '''
- fich = openturns.WrapperDataFile()
- fich.id_ = dictFile[ 'Id' ]
- if dictFile[ 'Type' ] in FileTypeByName.keys() :
- fich.type_ = FileTypeByName[ dictFile[ 'Type' ] ]
- if dictFile.has_key('Name') : fich.name_ = dictFile[ 'Name' ]
- if dictFile.has_key('Path') : fich.path_ = dictFile[ 'Path' ]
- if dictFile.has_key('Subst') :
- import string
- fich.subst_ = string.join( dictFile[ 'Subst' ], ',' )
- return fich
-
- def Parameters (self) :
- '''
- Ecrit les parametres de couplage au code externe
- '''
- parameters = openturns.WrapperParameter()
- parameters.mode_ = WrapperModeByName[ self.GetMCVal('WrapCouplingMode') ]
- if (parameters.mode_ == openturns.WrapperMode.FORK ):
- parameters.command_ = self.GetMCVal('Command')
- userPrefix = self.GetMCVal('UserPrefix', None)
- if userPrefix != None : parameters.userPrefix_ = userPrefix
- parameters.state_ = WrapperStateByName[ self.GetMCVal('State') ]
- parameters.in_ = WrapperDataTransferByName[ self.GetMCVal('InDataTransfer') ]
- parameters.out_ = WrapperDataTransferByName[ self.GetMCVal('OutDataTransfer') ]
- return parameters
-
- def FrameworkData (self) :
- '''
- Ecrit les donnees liees a l utilisation d un framework englobant
- '''
- framework = openturns.WrapperFrameworkData()
-# framework.studycase_ = "12:23:34"
-# framework.componentname_ = self.GetMCVal('SolverComponentName', 'UNDEFINED')
- CN = self.GetMCVal('SolverComponentName', 'UNDEFINED')
- print 'CN = %s', CN
- framework.componentname_ = CN
- return framework
-
-
- # ---------------------------------------------------------------------------------
-
-
- def GetTag (self, tag) :
- '''
- Recupere la chaine associee au tag dans la table dictTagsXML.
- Leve une exception si le tag n est pas trouve
- '''
- if ( dictTagsXML.has_key(tag) ) :
- return dictTagsXML[tag]
- else :
- raise KeyError, tr("Tag %s non-defini. Ceci est un bogue interne. en informer les developpeurs.", tag)
- pass
-
- def GetMCVal (self, MC, default = None, mandatory = False) :
- '''
- Recupere la chaine associee au MC dans la table DictMCVal.
- Leve une exception si le MC n est pas trouve et mandatory vaut True
- '''
- if ( self.DictMCVal.has_key(MC) and self.DictMCVal[MC] != None ) :
- return self.DictMCVal[MC]
- else :
- if ( mandatory ) :
- raise KeyError, tr(" Le mot-cle %s est obligatoire.", MC)
- else :
- return default
- pass
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2017 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""Ce module contient le plugin generateur de fichier au format Code_Carmel3D pour EFICAS.
-"""
-
-import traceback
-import types,string,re,os
-from Extensions.i18n import tr
-from generator_python import PythonGenerator
-
-# Groupes de mailles dont les types sont definis par des prefixes dans leur nom
-usePrefix = False # les noms ont des prefixes (True) ou non (False)
-# liste des prefixes des groupes de mailles, sans le caractere _ separant le prefixe du reste du nom
-# Ce prefixe (et caractere _) doivent etre supprimes dans le fichier .phys
-listePrefixesGroupeMaille = ("DIEL","NOCOND","COND","CURRENT","EPORT","HPORT","TOPO","PB_MOBILE","NILMAT",
- "VCUT","VCUTN","EWALL","HWALL","GAMMAJ","PERIODIC","APERIODIC",
- "HPROBE","EPROBE","BFLUX","BFLUXN","JFLUX","JFLUXN",
- "PORT_OMEGA","POST_PHI","PB_GRID",
- "SCUTE","SCUTN","ZS","ZJ","ZT")
-# liste des prefixes des groupes de mailles, sans le separateur, par type de bloc du fichier PHYS sous la forme d'un dictionnaire
-dictPrefixesGroupeMaille = {'DIELECTRIC':('DIEL','NOCOND'),
- 'CONDUCTOR':('COND',),
- 'STRANDED_INDUCTOR':('CURRENT', ),
- 'EPORT':('EPORT', ),
- 'HPORT':('HPORT', ),
- 'ZSURFACIC':('ZS', ),
- 'ZINSULATOR':('ZJ', ),
- 'NILMAT':('NILMAT', )}
-# separateur entre le prefixe et le reste du nom du groupe de maille
-sepNomGroupeMaille = '_'
-
-# types de problemes
-HARMONIC = 'HARMONIC' # probleme frequentiel
-TIME_DOMAIN = 'TIME_DOMAIN' # probleme temporel
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'CARMEL3D',
- # La factory pour creer une instance du plugin
- 'factory' : CARMEL3DGenerator,
- }
-
-
-class CARMEL3DGenerator(PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un texte au format eficas et
- un texte au format attendu par le code Code_Carmel3D (fichier '.PHYS')
-
- """
- # Les extensions de fichier permis?
- extensions=('.comm',)
-
-#----------------------------------------------------------------------------------------
- def gener(self,obj,format='brut',config=None):
-
- self.initDico()
-
- # Cette instruction genere le contenu du fichier de commandes (persistance)
- self.text=PythonGenerator.gener(self,obj,format)
-
- if self.debug:
- print "self.text = %s", self.text
-
- # Cette instruction genere le contenu du fichier de parametres pour le code Carmel3D
- # si le jdc est valide (sinon cela n a pas de sens)
- if obj.isValid() :
- # constitution du bloc VERSION du fichier PHYS (existe toujours)
- try :
- self.generBLOC_VERSION(obj)
- except ValueError, err:
- raise ValueError(str(err))
-
- # constitution du bloc MATERIALS du fichier PHYS (existe toujours)
- self.generBLOC_MATERIALS()
-
- # constitution du bloc SOURCES du fichier PHYS (existe toujours)
- self.generBLOC_SOURCES()
-
-# print "texte carmel3d :\n",self.texteCarmel3D
-# print "dictMaterDielectric : ",self.dictMaterDielectric
- if self.debug:
- print "dictMaterConductor : %s", repr(self.dictMaterConductor)
-
- return self.text
-
-
-#----------------------------------------------------------------------------------------
-# initialisations
-#----------------------------------------------------------------------------------------
-
- def initDico(self) :
-
- self.texteCarmel3D=""
- self.debug = True # affichage de messages pour deboguage (.true.) ou non
- self.dicoEtapeCourant=None
- self.dicoMCFACTCourant=None
- self.dicoCourant=None
- self.dictGroupesMaillage = {'ordreMateriauxJdC':[], 'ordreSourcesJdC':[]} # association des noms de groupes de maillage avec les noms de materiaux ou de sources, en sauvegardant l'ordre du JdC en separant les groupes associes a des materiaux de ceux associes a des sources
- self.dictMaterConductor={}
- self.dictMaterDielectric={}
- self.dictMaterZsurfacic={}
- self.dictMaterEmIso={}
- self.dictMaterEmAnIso={}
- self.dictMaterNilmat={}
- self.dictMaterZinsulator={}
- self.dictSourceStInd={}
- self.dictSourceEport={}
- self.dictSourceHport={}
- # on force le probleme a etre frequentiel, seul possible en l'etat des choses
- self.problem = HARMONIC
-
-
-#----------------------------------------------------------------------------------------
-# ecriture
-#----------------------------------------------------------------------------------------
-
- def writeDefault(self,fn) :
- """Ecrit le fichier de parametres (PHYS) pour le code Carmel3D"""
- if self.debug:
- print "ecriture du fichier de parametres (PHYS)"
- filePHYS = fn[:fn.rfind(".")] + '.phys'
- f = open( str(filePHYS), 'wb')
- f.write( self.texteCarmel3D)
- f.close()
-
-#----------------------------------------------------------------------------------------
-# analyse de chaque noeud de l'arbre
-#----------------------------------------------------------------------------------------
-
- def generMCSIMP(self,obj) :
- """recuperation de l objet MCSIMP"""
- if self.debug:
- print "MCSIMP %(v_1)s %(v_2)s", {'v_1': obj.nom, "v_2": obj.valeur}
- s=PythonGenerator.generMCSIMP(self,obj)
- self.dicoCourant[obj.nom]=obj.valeurFormatee
- return s
-
-
-#----------------------------------------------------------------------------------------
- def generMCFACT(self,obj) :
- """recuperation de l objet MCFACT"""
- dico={}
- self.dicoMCFACTCourant=dico
- self.dicoCourant=self.dicoMCFACTCourant
- s=PythonGenerator.generMCFACT(self,obj)
- self.dicoEtapeCourant[obj.nom]=self.dicoMCFACTCourant
- self.dicoMCFACTCourant=None
- self.dicoCourant=self.dicoEtapeCourant
- return s
-
-#----------------------------------------------------------------------------------------
- def generPROC_ETAPE(self,obj):
- """analyse des PROC du catalogue ( VERSION )"""
- dico={}
- self.dicoEtapeCourant=dico
- self.dicoCourant=self.dicoEtapeCourant
- s=PythonGenerator.generPROC_ETAPE(self,obj)
- obj.valeur=self.dicoEtapeCourant
- if self.debug:
- print "PROC_ETAPE %(v_1)s %(v_2)s", \
- {'v_1': unicode(obj.nom), "v_2": unicode(obj.valeur)}
- s=PythonGenerator.generPROC_ETAPE(self,obj)
- return s
-
-#----------------------------------------------------------------------------------------
- def generETAPE(self,obj):
- """analyse des OPER du catalogue"""
- dico={}
- self.dicoEtapeCourant=dico
- self.dicoCourant=self.dicoEtapeCourant
- s=PythonGenerator.generETAPE(self,obj)
- obj.valeur=self.dicoEtapeCourant
- if self.debug:
- print "ETAPE : obj.nom = %(v_1)s , obj.valeur= %(v_2)s", \
- {'v_1': obj.nom, 'v_2': obj.valeur}
- if obj.nom=="MESHGROUP" : self.generMESHGROUP(obj)
- if obj.nom=="MATERIAL" : self.generMATERIAL(obj)
- if obj.nom=="SOURCE" : self.generSOURCE(obj)
- s=PythonGenerator.generETAPE(self,obj)
- return s
-
-#----------------------------------------------------------------------------------------
- def generMACRO_ETAPE(self,obj):
- dico={}
- self.dicoEtapeCourant=dico
- self.dicoCourant=self.dicoEtapeCourant
- import generator
- monGenerateur=generator.plugins["CARMEL3D"]()
- jdc_aux_texte=monGenerateur.gener(obj.jdc_aux)
- if self.debug:
- print "jdc_aux_texte : %s", jdc_aux_texte
-
- for cle in monGenerateur.dictMaterConductor:
- self.dictMaterConductor[cle] = monGenerateur.dictMaterConductor[cle]
- for cle in monGenerateur.dictMaterDielectric:
- self.dictMaterDielectric[cle] = monGenerateur.dictMaterDielectric[cle]
- for cle in monGenerateur.dictMaterZsurfacic:
- self.dictMaterZsurfacic[cle] = monGenerateur.dictMaterZsurfacic[cle]
- for cle in monGenerateur.dictMaterEmIso:
- self.dictMaterEmIso[cle] = monGenerateur.dictMaterEmIso[cle]
- for cle in monGenerateur.dictMaterEmAnIso:
- self.dictMaterEmAnIso[cle] = monGenerateur.dictMaterEmAnIso[cle]
- for cle in monGenerateur.dictMaterNilmat:
- self.dictMaterNilMat[cle] = monGenerateur.dictMaterNilMat[cle]
- for cle in monGenerateur.dictMaterZinsulator:
- self.dictMaterZinsulator[cle] = monGenerateur.dictMaterZinsulator[cle]
-
- print "________FIN MACRO______________________________________"
- s=PythonGenerator.generMACRO_ETAPE(self,obj)
- return s
-
-#----------------------------------------------------------------------------------------
-#----------------------------------------------------------------------------------------
- def generMESHGROUP(self,obj):
- """preparation de la ligne NAME referencant le groupe de mailles
- associe le groupe de mailles au materiau ou a la source utilisateur
- on sauvegarde aussi les noms des groupes de maillage
- """
-
- try:
- if usePrefix:
- nomGroupeMaillage = self.nomReelGroupeMaillage(obj.getSdname()) # nom du groupe de maillage, i.e. nom du concept, avec prefixes enleves
- else:
- nomGroupeMaillage = obj.getSdname() # nom du groupe de maillage, i.e. nom du concept
- # test: un et un seul nom de materiau ou source doit etre associe a ce groupe de maillage, via les cles MATERIAL et SOURCE, respectivement.
- # test sur un seul attribut, non pertinent car il peut y en avoir plusieurs.
- #assert len(obj.valeur.keys())==1,"Un et un seul nom de materiau ou source doit etre associe a ce groupe du maillage :"+nomGroupeMaillage
- #
- # on utilise le fait que obj.valeur est un dictionnaire
- if self.debug:
- print "obj.valeur.keys()= %s", obj.valeur.keys()
- if 'MATERIAL' in obj.valeur.keys() and 'SOURCE' in obj.valeur.keys(): # test d'erreur lors de presence de materiau et source a la fois
- raise ValueError,tr(" ce groupe de maillage %s est associe a au moins un materiau et au moins une source.", nomGroupeMaillage)
- # association a un materiau
- if 'MATERIAL' in obj.valeur.keys():
- self.dictGroupesMaillage[nomGroupeMaillage] = obj.valeur['MATERIAL'].nom # sauvegarde de l'association entre ce groupe de maillage et un materiau ou source, par son nom, i.e. nom du concept du materiau ou de la source
- self.dictGroupesMaillage['ordreMateriauxJdC'].append(nomGroupeMaillage) # sauvegarde du nom du groupe de maillage associe a un materiau, dans l'ordre du JdC
- # association a une source
- elif 'SOURCE' in obj.valeur.keys():
- self.dictGroupesMaillage[nomGroupeMaillage] = obj.valeur['SOURCE'].nom # sauvegarde de l'association entre ce groupe de maillage et un materiau ou source, par son nom, i.e. nom du concept du materiau ou de la source
- self.dictGroupesMaillage['ordreSourcesJdC'].append(nomGroupeMaillage) # sauvegarde du nom du groupe de maillage associe a une source, dans l'ordre du JdC
- # erreur ni materiau ni source associee
- else:
- raise ValueError, tr("ce groupe de maillage %s n'est associe a aucun materiau ou source.", nomGroupeMaillage)
- if self.debug:
- print "self.dictGroupesMaillage= %s", repr(self.dictGroupesMaillage)
- except:
- pass
-
-
- def generMATERIAL(self,obj):
- """preparation du bloc correspondant a un materiau du fichier PHYS"""
- texte=""
- if self.debug:
- print "generation material obj valeur = %s", obj.valeur
- try :
- nature = obj.valeur['TYPE'] # la nature est le parametre TYPE du MATERIAL
- if nature=="CONDUCTOR" : self.generMATERIAL_CONDUCTOR(obj)
- if nature=="DIELECTRIC" : self.generMATERIAL_DIELECTRIC(obj)
- if nature=="ZSURFACIC" : self.generMATERIAL_ZSURFACIC(obj)
- if nature=="EM_ISOTROPIC" : self.generMATERIAL_EMISO(obj)
- if nature=="EM_ANISOTROPIC" : self.generMATERIAL_EMANISO(obj)
- if nature=="NILMAT" : self.generMATERIAL_NILMAT(obj)
- if nature=="ZINSULATOR" : self.generMATERIAL_ZINSULATOR(obj)
- except:
- pass
-
- def generMATERIAL_CONDUCTOR(self,obj):
- """preparation du sous bloc CONDUCTOR"""
- texte=""
- if self.debug:
- print "_____________cond_____________"
- # verification des proprietes du sous bloc CONDUCTOR (PERMEABILITY, CONDUCTIVITY)
- if 'PERMEABILITY' not in obj.valeur or 'CONDUCTIVITY' not in obj.valeur:
- print "ERREUR! Le bloc CONDUCTOR doit contenir PERMEABILITY et CONDUCTIVITY."
- else:
- # parcours des proprietes du sous bloc CONDUCTOR (PERMEABILITY, CONDUCTIVITY)
- for keyN1 in ('PERMEABILITY','CONDUCTIVITY') :
- # debut du sous bloc de propriete du DIELECTRIC
- texte+=" ["+keyN1+"\n"
- texte+=" HOMOGENEOUS "+str(obj.valeur[keyN1]["HOMOGENEOUS"])+"\n"
- texte+=" ISOTROPIC "+str(obj.valeur[keyN1]["ISOTROPIC"])+"\n"
- # Ecriture des valeurs seulement pour un materiau homogene et isotrope,
- # car sinon ces valeurs sont definies dans des fichiers annexes
- homogeneous = str(obj.valeur[keyN1]["HOMOGENEOUS"]) == 'TRUE'
- isotropic = str(obj.valeur[keyN1]["ISOTROPIC"]) == 'TRUE'
- if homogeneous and isotropic:
- # loi (lineaire ou non)
- texte+=" LAW "+str(obj.valeur[keyN1]["LAW"])+"\n"
- # valeur de la loi lineaire
- texte+=" VALUE "+self.formateCOMPLEX(obj.valeur[keyN1]["VALUE"])+"\n"
- # loi non lineaire de nature spline, Marrocco ou Marrocco et Saturation
- # seuls les reels sont pris en compte
- if obj.valeur[keyN1]['LAW']=='NONLINEAR' :
- texte+=" [NONLINEAR \n"
- texte+=" ISOTROPY TRUE\n"
- texte+=" NATURE "+str(obj.valeur[keyN1]['NATURE'])+"\n"
- # ajout des autres parametres autres que ISOTROPY, NATURE, VALUE, LAW, HOMOGENEOUS, ISOTROPIC
- for keyN2 in obj.valeur[keyN1] :
- if keyN2 not in ('ISOTROPY','NATURE','VALUE','LAW','HOMOGENEOUS','ISOTROPIC') :
- texte+=" "+keyN2+" "+str(obj.valeur[keyN1][keyN2])+"\n"
- # fin du sous-bloc NONLINEAR
- texte+=" ]"+"\n"
- # fin du sous bloc de propriete
- texte+=" ]"+"\n"
- if self.debug:
- print "texte = %s", texte
- self.dictMaterConductor[obj.getSdname()]=texte # sauvegarde du texte pour ce bloc
-
- def generMATERIAL_DIELECTRIC(self,obj):
- """preparation du sous bloc DIELECTRIC"""
- texte=""
- if self.debug:
- print "______________nocond_____________"
- # verification des proprietes du sous bloc DIELECTRIC (PERMEABILITY, PERMITTIVITY)
- if 'PERMEABILITY' not in obj.valeur or 'PERMITTIVITY' not in obj.valeur:
- print "ERREUR! Le bloc DIELECTRIC doit contenir PERMEABILITY et PERMITTIVITY."
- else:
- # parcours des proprietes du sous bloc DIELECTRIC (PERMEABILITY, PERMITTIVITY)
- for keyN1 in ('PERMEABILITY','PERMITTIVITY') :
- # debut du sous bloc de propriete du DIELECTRIC
- texte+=" ["+keyN1+"\n"
- texte+=" HOMOGENEOUS "+str(obj.valeur[keyN1]["HOMOGENEOUS"])+"\n"
- texte+=" ISOTROPIC "+str(obj.valeur[keyN1]["ISOTROPIC"])+"\n"
- # Ecriture des valeurs seulement pour un materiau homogene et isotrope,
- # car sinon ces valeurs sont definies dans des fichiers annexes
- homogeneous = str(obj.valeur[keyN1]["HOMOGENEOUS"]) == 'TRUE'
- isotropic = str(obj.valeur[keyN1]["ISOTROPIC"]) == 'TRUE'
- if homogeneous and isotropic:
- # loi (lineaire ou non)
- texte+=" LAW "+str(obj.valeur[keyN1]["LAW"])+"\n"
- # valeur de la loi lineaire
- texte+=" VALUE "+self.formateCOMPLEX(obj.valeur[keyN1]["VALUE"])+"\n"
- # loi non lineaire de nature spline, Marrocco ou Marrocco et Saturation
- # seuls les reels sont pris en compte
- if obj.valeur[keyN1]['LAW']=='NONLINEAR' :
- texte+=" [NONLINEAR \n"
- texte+=" ISOTROPY TRUE\n"
- texte+=" NATURE "+str(obj.valeur[keyN1]['NATURE'])+"\n"
- # ajout des autres parametres autres que ISOTROPY, NATURE, VALUE, LAW, HOMOGENEOUS, ISOTROPIC
- for keyN2 in obj.valeur[keyN1] :
- if keyN2 not in ('ISOTROPY','NATURE','VALUE','LAW','HOMOGENEOUS','ISOTROPIC') :
- texte+=" "+keyN2+" "+str(obj.valeur[keyN1][keyN2])+"\n"
- # fin du sous-bloc NONLINEAR
- texte+=" ]"+"\n"
- # fin du sous bloc de propriete
- texte+=" ]"+"\n"
- if self.debug:
- print "texte = %s", texte
- self.dictMaterDielectric[obj.getSdname()]=texte # sauvegarde du texte pour ce bloc
-
- def generMATERIAL_ZSURFACIC(self,obj):
- """preparation du sous bloc ZSURFACIC"""
- texte=""
- if self.debug:
- print "______________zsurf_____________"
- # verification des proprietes du sous bloc ZSURFACIC (PERMEABILITY, CONDUCTIVITY)
- if 'PERMEABILITY' not in obj.valeur or 'CONDUCTIVITY' not in obj.valeur:
- print "ERREUR! Le bloc ZSURFACIC doit contenir PERMEABILITY et CONDUCTIVITY."
- else:
- # parcours des proprietes du sous bloc ZSURFACIC (PERMEABILITY, CONDUCTIVITY)
- for keyN1 in obj.valeur :
- if keyN1=='TYPE': continue
- # print "type loi = ", obj.valeur[keyN1]['LAW']
- # debut du sous bloc de propriete du DIELECTRIC
- texte+=" ["+keyN1+"\n"
- texte+=" HOMOGENEOUS "+str(obj.valeur[keyN1]["HOMOGENEOUS"])+"\n"
- texte+=" ISOTROPIC "+str(obj.valeur[keyN1]["ISOTROPIC"])+"\n"
- # Ecriture des valeurs seulement pour un materiau homogene et isotrope,
- # car sinon ces valeurs sont definies dans des fichiers annexes
- homogeneous = str(obj.valeur[keyN1]["HOMOGENEOUS"]) == 'TRUE'
- isotropic = str(obj.valeur[keyN1]["ISOTROPIC"]) == 'TRUE'
- if homogeneous and isotropic:
- # loi (lineaire ou non)
- texte+=" LAW "+str(obj.valeur[keyN1]["LAW"])+"\n"
- # valeur de la loi lineaire
- texte+=" VALUE "+self.formateCOMPLEX(obj.valeur[keyN1]["VALUE"])+"\n"
- # fin du sous bloc de propriete
- texte+=" ]"+"\n"
- if self.debug:
- print "texte = %s", texte
- self.dictMaterZsurfacic[obj.getSdname()]=texte # sauvegarde du texte pour ce bloc
-
- def generMATERIAL_EMISO(self,obj):
- """preparation du sous bloc EM_ISOTROPIC_FILES.
- Les fichiers sont indiques par le chemin absolu, i.e. le nom complet du JdC,
- ce qui permet de deplacer les dossiers contenant le modele complet puisque le JdC permet les chemins relatifs.
- """
- texte =" CONDUCTIVITY MED "+str(obj.valeur["CONDUCTIVITY_File"])+"\n"
- texte+=" PERMEABILITY MED "+str(obj.valeur["PERMEABILITY_File"])+"\n"
- # Possibilite de forcer le chemin relatif (nom de fichier seulement) plutot que le chemin absolu par defaut
- #from os.path import basename
- #texte =" CONDUCTIVITY MED "+basename(str(obj.valeur["CONDUCTIVITY_File"]))+"\n"
- #texte+=" PERMEABILITY MED "+basename(str(obj.valeur["PERMEABILITY_File"]))+"\n"
- # print "obj get sdname= ", obj.getSdname()
- # if obj.getSdname() in self.dictMaterEmIso.keys() :
- # self.dictMaterEmIso[obj.getSdname()].append(texte)
- # else :
- self.dictMaterEmIso[obj.getSdname()]=texte
-
- def generMATERIAL_EMANISO(self,obj):
- """preparation du sous bloc EM_ANISOTROPIC_FILES.
- Les fichiers sont indiques par le chemin absolu, i.e. le nom complet du JdC,
- ce qui permet de deplacer les dossiers contenant le modele complet puisque le JdC permet les chemins relatifs.
- """
- texte =" CONDUCTIVITY MATER "+str(obj.valeur["CONDUCTIVITY_File"])+"\n"
- texte+=" PERMEABILITY MATER "+str(obj.valeur["PERMEABILITY_File"])+"\n"
- # print "obj get sdname= ", obj.getSdname()
- # if obj.getSdname() in self.dictMaterEmAnIso.keys() :
- # self.dictMaterEmAnIso[obj.getSdname()].append(texte)
- # else :
- self.dictMaterEmAnIso[obj.getSdname()]=texte
-
- def generMATERIAL_NILMAT(self,obj):
- """preparation du sous bloc NILMAT"""
- texte=""
- self.dictMaterNilmat[obj.getSdname()]=texte
-
- def generMATERIAL_ZINSULATOR(self,obj):
- """"preparation du sous bloc ZINSULATOR"""
- texte=""
- self.dictMaterZinsulator[obj.getSdname()]=texte
-
-#-------------------------------------------------------------------
-
- def generSOURCE(self,obj):
- """preparation du bloc correspondant a une source du fichier PHYS"""
- if self.debug:
- print "generation source obj valeur = %s", obj.valeur
- texte=""
- try :
- # test de la presence des types de sources reconnus
- # commes ces sources sont des mot-cles facteurs, i.e. une cle de dictionnaire,
- # la source ne peut contenir au plus qu'un type de source.
- if "STRANDED_INDUCTOR" in obj.valeur:
- self.generSOURCE_STRANDED_INDUCTOR(obj)
- elif "HPORT" in obj.valeur:
- self.generSOURCE_HPORT(obj)
- elif "EPORT" in obj.valeur:
- self.generSOURCE_EPORT(obj)
- else:
- print "ERREUR! Une source du type STRANDED_INDUCTOR, HPORT ou EPORT est attendue."
- except:
- pass
-
- def generSOURCE_STRANDED_INDUCTOR(self,obj):
- """preparation du sous bloc STRANDED_INDUCTOR"""
- texte=""
- sdict = obj.valeur['STRANDED_INDUCTOR'] # dictionnaire contenant les parametres de la source, outre la forme de la source
- try :
- texte+=" NTURNS %s\n" % str(sdict['NTURNS'])
- # test de la presence d'une forme de source reconnue
- # commes ces formes sont des mot-cles facteurs, i.e. une cle de dictionnaire,
- # la source ne peut contenir au plus qu'un type de source.
- if "WAVEFORM_CONSTANT" in obj.valeur:
- wdict = obj.valeur['WAVEFORM_CONSTANT'] # dictionnaire contenant les parametres de la forme de la source
- if self.problem == HARMONIC:
- texte+=" CURJ POLAR %s 0\n" % str(wdict['AMPLITUDE'])
- print tr("ATTENTION! Une source constante \
- n'est possible qu'a frequence nulle \
- en regime frequentiel")
- elif "WAVEFORM_SINUS" in obj.valeur:
- wdict = obj.valeur['WAVEFORM_SINUS'] # dictionnaire contenant les parametres de la forme de la source
- if self.problem == HARMONIC:
- texte+=" CURJ POLAR %(ampli)s %(phase)s\n" \
- % {'ampli': str(wdict['AMPLITUDE']), 'phase': str(wdict['PHASE'])}
- else:
- print tr("ERREUR! Une forme de la source du \
- type WAVEFORM_CONSTANT ou WAVEFORM_SINUS est attendue.")
- self.dictSourceStInd[obj.getSdname()]=texte
- if self.debug:
- print texte
- except Exception:
- pass
-
- def generSOURCE_HPORT(self,obj):
- """preparation du sous bloc HPORT"""
- texte=""
- sdict = obj.valeur['HPORT'] # dictionnaire contenant les parametres de la source, outre la forme de la source
- try :
- texte+=" TYPE %s\n" % str(sdict['TYPE'])
- # test de la presence d'une forme de source reconnue
- # commes ces formes sont des mot-cles facteurs, i.e. une cle de dictionnaire,
- # la source ne peut contenir au plus qu'un type de source.
- if "WAVEFORM_CONSTANT" in obj.valeur:
- wdict = obj.valeur['WAVEFORM_CONSTANT'] # dictionnaire contenant les parametres de la forme de la source
- if self.problem == HARMONIC:
- texte+=" AMP POLAR %s 0\n" % str(wdict['AMPLITUDE'])
- print tr("ATTENTION! Une source constante n'est \
- possible qu'a frequence nulle en regime frequentiel")
- elif "WAVEFORM_SINUS" in obj.valeur:
- wdict = obj.valeur['WAVEFORM_SINUS'] # dictionnaire contenant les parametres de la forme de la source
- if self.problem == HARMONIC:
- texte+=" AMP POLAR %(ampli)s %(phase)s\n" \
- % {'ampli': str(wdict['AMPLITUDE']), 'phase': str(wdict['PHASE'])}
- else:
- print tr("ERREUR! Une forme de la source du type \
- WAVEFORM_CONSTANT ou WAVEFORM_SINUS est attendue.")
- self.dictSourceHport[obj.getSdname()]=texte
- if self.debug:
- print texte
- except:
- pass
-
- def generSOURCE_EPORT(self,obj):
- """preparation du sous bloc EPORT"""
- texte=""
- sdict = obj.valeur['EPORT'] # dictionnaire contenant les parametres de la source, outre la forme de la source
- try :
- texte+=" TYPE %s\n" % str(sdict['TYPE'])
- # test de la presence d'une forme de source reconnue
- # commes ces formes sont des mot-cles facteurs, i.e. une cle de dictionnaire,
- # la source ne peut contenir au plus qu'un type de source.
- if "WAVEFORM_CONSTANT" in obj.valeur:
- wdict = obj.valeur['WAVEFORM_CONSTANT'] # dictionnaire contenant les parametres de la forme de la source
- if self.problem == HARMONIC:
- texte+=" AMP POLAR %s 0\n" % str(wdict['AMPLITUDE'])
- print tr("ATTENTION! Une source constante n'est possible qu'a frequence nulle en regime frequentiel")
- elif "WAVEFORM_SINUS" in obj.valeur:
- wdict = obj.valeur['WAVEFORM_SINUS'] # dictionnaire contenant les parametres de la forme de la source
- if self.problem == HARMONIC:
- texte+=" AMP POLAR %(ampli)s %(phase)s\n" \
- % {'ampli': str(wdict['AMPLITUDE']), 'phase': str(wdict['PHASE'])}
- else:
- print tr("ERREUR! Une forme de la source du type \
- WAVEFORM_CONSTANT ou WAVEFORM_SINUS est attendue.")
- self.dictSourceEport[obj.getSdname()]=texte
- if self.debug:
- print texte
- except:
- pass
-
-#---------------------------------------------------------------------------------------
-# traitement fichier PHYS
-#---------------------------------------------------------------------------------------
-
- def generBLOC_VERSION(self,obj) :
- # constitution du bloc VERSION du fichier PHYS
- # creation d une entite VERSION ; elle sera du type PROC car decrit ainsi
- # dans le du catalogue
- version=obj.addEntite('VERSION',pos=None)
- self.generPROC_ETAPE(obj.etapes[0])
- self.texteCarmel3D+="["+obj.etapes[0].nom+"\n"
- for cle in obj.etapes[0].valeur :
- self.texteCarmel3D+=" "+cle+" "+str(obj.etapes[0].valeur[cle])+"\n"
- self.texteCarmel3D+="]\n"
- # destruction de l entite creee
- obj.suppEntite(version)
-
-#----------------------------------------------------------------------------------------
- def generBLOC_MATERIALS(self) :
- """Prepare une partie du contenu du fichier de parametres (PHYS) pour le code Carmel3D (bloc MATERIALS).
- Le bloc MATERIALS existe toujours !
- """
- if self.debug:
- print "cle dictionnaire materconductor : %s", self.dictMaterConductor.keys()
- print "cle dictionnaire materdielectric : %s", self.dictMaterDielectric.keys()
- # constitution du bloc MATERIALS du fichier PHYS
- self.texteCarmel3D+="[MATERIALS\n"
- # tri alphabetique de tous les groupes de maillage associes a des sources (plus necessaire Code_Carmel3D V_2_3_1 et +, mais avant oui)
- nomsGroupesMaillage = self.dictGroupesMaillage['ordreMateriauxJdC'][:] # copie de l'original, qui est une liste
- nomsGroupesMaillage.sort() # tri alphabetique, avec les prefixes eventuels
- if self.debug:
- print "noms groupes de mailles associes a des materiaux \
- (ordre JdC puis tri)= %(v_1)s %(v_2)s", \
- {'v_1': self.dictGroupesMaillage['ordreMateriauxJdC'], \
- 'v_2': nomsGroupesMaillage}
- # constitution du bloc CONDUCTOR du fichier PHYS si existe
- if self.dictMaterConductor != {} : self.creaBLOC_CONDUCTOR(nomsGroupesMaillage)
- # constitution du bloc DIELECTRIC du fichier PHYS si exixte
- if self.dictMaterDielectric != {} : self.creaBLOC_DIELECTRIC(nomsGroupesMaillage)
- # constitution du bloc ZSURFACIC du fichier PHYS si exixte
- if self.dictMaterZsurfacic != {} : self.creaBLOC_ZSURFACIC(nomsGroupesMaillage)
- # constitution du bloc NILMAT du fichier PHYS si exixte
- if self.dictMaterNilmat != {} : self.creaBLOC_NILMAT(nomsGroupesMaillage)
- # constitution du bloc ZINSULATOR du fichier PHYS si exixte
- if self.dictMaterZinsulator != {} : self.creaBLOC_ZINSULATOR(nomsGroupesMaillage)
- # Les blocs EM_ISOTROPIC_FILES et EM_ANISOTROPIC_FILES sont places en dernier dans le fichier PHYS
- # constitution du bloc EM_ISOTROPIC_FILES du fichier PHYS si exixte
- if self.dictMaterEmIso != {} : self.creaBLOC_EMISO()
- # constitution du bloc EM_ANISOTROPIC_FILES du fichier PHYS si exixte
- if self.dictMaterEmAnIso != {} : self.creaBLOC_EMANISO()
- # fin du bloc MATERIALS du fichier PHYS
- self.texteCarmel3D+="]\n"
-
- def creaBLOC_CONDUCTOR(self, nomsGroupesMaillage) :
- """Constitution du bloc CONDUCTOR du fichier PHYS"""
- typeBloc = 'CONDUCTOR' # initialisation du type de bloc
- dictProprietes = self.dictMaterConductor # initialisation du dictionnaire des proprietes du bloc
- if self.debug:
- print 'cles materiaux de type %(type_bloc)s = %(cle_bloc)s', \
- {'type_bloc': typeBloc, 'cle_bloc': dictProprietes.keys()}
- for nom in nomsGroupesMaillage: # parcours des noms des groupes de maillage
- if self.dictGroupesMaillage[nom] in dictProprietes.keys(): # test si le nom du materiau associe est du bon type
- # ecriture du bloc complet
- self.texteCarmel3D+=" ["+typeBloc+"\n" # debut de bloc
- if usePrefix:
- nomReel = self.nomReelGroupeMaillage(nom, typeBloc)
- else:
- nomReel = nom
- self.texteCarmel3D+=" NAME "+nomReel+"\n" # ecriture du nom (reel) du groupe du maillage
- self.texteCarmel3D+= dictProprietes[self.dictGroupesMaillage[nom]] # ecriture des proprietes du type associe
- self.texteCarmel3D+=" ]\n" # fin de bloc
-
- def creaBLOC_DIELECTRIC(self, nomsGroupesMaillage) :
- """Constitution du bloc DIELECTRIC du fichier PHYS"""
- typeBloc = 'DIELECTRIC' # initialisation du type de bloc
- dictProprietes = self.dictMaterDielectric # initialisation du dictionnaire des proprietes du bloc
- if self.debug:
- print 'cles materiaux de type %(type_bloc)s=%(cle_bloc)s', \
- {'type_bloc': typeBloc, 'cle_bloc': dictProprietes.keys()}
- for nom in nomsGroupesMaillage: # parcours des noms des groupes de maillage
- if self.dictGroupesMaillage[nom] in dictProprietes.keys(): # test si le nom du materiau associe est du bon type
- # ecriture du bloc complet
- self.texteCarmel3D+=" ["+typeBloc+"\n" # debut de bloc
- self.texteCarmel3D+=" NAME "+nom+"\n" # ecriture du nom (reel) du groupe du maillage
- self.texteCarmel3D+= dictProprietes[self.dictGroupesMaillage[nom]] # ecriture des proprietes du type associe
- self.texteCarmel3D+=" ]\n" # fin de bloc
-
- def creaBLOC_ZSURFACIC(self, nomsGroupesMaillage) :
- """Constitution du bloc ZSURFACIC du fichier PHYS"""
- typeBloc = 'ZSURFACIC' # initialisation du type de bloc
- dictProprietes = self.dictMaterZsurfacic # initialisation du dictionnaire des proprietes du bloc
- if self.debug:
- print 'cles materiaux de type %(type_bloc)s=%(cle_bloc)s', \
- {'type_bloc': typeBloc, 'cle_bloc': dictProprietes.keys()}
- for nom in nomsGroupesMaillage: # parcours des noms des groupes de maillage
- if self.dictGroupesMaillage[nom] in dictProprietes.keys(): # test si le nom du materiau associe est du bon type
- # ecriture du bloc complet
- self.texteCarmel3D+=" ["+typeBloc+"\n" # debut de bloc
- if usePrefix:
- nomReel = self.nomReelGroupeMaillage(nom, typeBloc)
- else:
- nomReel = nom
- self.texteCarmel3D+=" NAME "+nomReel+"\n" # ecriture du nom (reel) du groupe du maillage
- self.texteCarmel3D+= dictProprietes[self.dictGroupesMaillage[nom]] # ecriture des proprietes du type associe
- self.texteCarmel3D+=" ]\n" # fin de bloc
-
- def creaBLOC_EMISO(self) :
- """constitution du bloc EM_ISOTROPIC_FILES du fichier PHYS"""
- for cle in self.dictMaterEmIso.keys():
- self.texteCarmel3D+=" [EM_ISOTROPIC_FILES\n"
- self.texteCarmel3D+= self.dictMaterEmIso[cle]
- self.texteCarmel3D+=" ]\n"
-
- def creaBLOC_EMANISO(self) :
- """constitution du bloc EM_ANISOTROPIC_FILES du fichier PHYS"""
- for cle in self.dictMaterEmAnIso.keys():
- self.texteCarmel3D+=" [EM_ANISOTROPIC_FILES\n"
- self.texteCarmel3D+= self.dictMaterEmAnIso[cle]
- self.texteCarmel3D+=" ]\n"
-
- def creaBLOC_ZINSULATOR(self, nomsGroupesMaillage) :
- """Constitution du bloc ZINSULATOR du fichier PHYS"""
- typeBloc = 'ZINSULATOR' # initialisation du type de bloc
- dictProprietes = self.dictMaterZinsulator # initialisation du dictionnaire des proprietes du bloc
- if self.debug: print 'cles materiaux de type '+typeBloc+'=', dictProprietes.keys()
- for nom in nomsGroupesMaillage: # parcours des noms des groupes de maillage
- if self.dictGroupesMaillage[nom] in dictProprietes.keys(): # test si le nom du materiau associe est du bon type
- # ecriture du bloc complet
- self.texteCarmel3D+=" ["+typeBloc+"\n" # debut de bloc
- if usePrefix:
- nomReel = self.nomReelGroupeMaillage(nom, typeBloc)
- else:
- nomReel = nom
- self.texteCarmel3D+=" NAME "+nomReel+"\n" # ecriture du nom (reel) du groupe du maillage
- self.texteCarmel3D+= dictProprietes[self.dictGroupesMaillage[nom]] # ecriture des proprietes du type associe
- self.texteCarmel3D+=" ]\n" # fin de bloc
-
- def creaBLOC_NILMAT(self, nomsGroupesMaillage) :
- """Constitution du bloc NILMAT du fichier PHYS"""
- typeBloc = 'NILMAT' # initialisation du type de bloc
- dictProprietes = self.dictMaterNilmat # initialisation du dictionnaire des proprietes du bloc
- if self.debug:
- print 'cles materiaux de type %(type_bloc)s=%(cle_bloc)s', \
- {'type_bloc': typeBloc, 'cle_bloc': dictProprietes.keys()}
- for nom in nomsGroupesMaillage: # parcours des noms des groupes de maillage
- if self.dictGroupesMaillage[nom] in dictProprietes.keys(): # test si le nom du materiau associe est du bon type
- # ecriture du bloc complet
- self.texteCarmel3D+=" ["+typeBloc+"\n" # debut de bloc
- if usePrefix:
- nomReel = self.nomReelGroupeMaillage(nom, typeBloc)
- else:
- nomReel = nom
- self.texteCarmel3D+=" NAME "+nomReel+"\n" # ecriture du nom (reel) du groupe du maillage
- self.texteCarmel3D+= dictProprietes[self.dictGroupesMaillage[nom]] # ecriture des proprietes du type associe
- self.texteCarmel3D+=" ]\n" # fin de bloc
-
-#----------------------------------------------------------------------------------------
- def generBLOC_SOURCES(self):
- """constitution du bloc SOURCES du fichier PHYS"""
- self.texteCarmel3D+="[SOURCES\n"
- # tri alphabetique de tous les groupes de maillage associes a des sources
- nomsGroupesMaillage = self.dictGroupesMaillage['ordreSourcesJdC'][:] # copie de l'original, qui est une liste
- nomsGroupesMaillage.sort() # tri alphabetique, avec les prefixes eventuels
- if self.debug:
- print 'noms groupes de mailles associes a des sources \
- (ordre JdC puis tri)=%(g_maillage_orig)s %(g_maillage_trie)s', \
- {'g_maillage_orig': self.dictGroupesMaillage['ordreSourcesJdC'], \
- 'g_maillage_trie': nomsGroupesMaillage}
- if self.dictSourceStInd != {}: self.creaBLOC_STRANDED_INDUCTOR(nomsGroupesMaillage)
- if self.dictSourceEport != {}: self.creaBLOC_EPORT(nomsGroupesMaillage)
- if self.dictSourceHport != {}: self.creaBLOC_HPORT(nomsGroupesMaillage)
- # fin du bloc SOURCES du fichier PHYS
- self.texteCarmel3D+="]\n"
-
-
- def creaBLOC_STRANDED_INDUCTOR(self, nomsGroupesMaillage) :
- """constitution du bloc STRANDED_INDUCTOR du fichier PHYS"""
- if self.debug:
- print 'cles sources STRANDED_INDUCTOR= %s', self.dictSourceStInd.keys()
- typeBloc = 'STRANDED_INDUCTOR'
- for nom in nomsGroupesMaillage: # parcours des noms des groupes de maillage
- if self.dictGroupesMaillage[nom] in self.dictSourceStInd.keys(): # test si le nom de la source associee est un inducteur bobine
- # ecriture du bloc de l'inducteur bobine
- self.texteCarmel3D+=" [STRANDED_INDUCTOR\n" # debut de bloc
- self.texteCarmel3D+=" NAME "+nom+"\n" # ecriture du nom (reel) du groupe du maillage
- self.texteCarmel3D+= self.dictSourceStInd[self.dictGroupesMaillage[nom]] # ecriture des proprietes de l'inducteur bobine
- self.texteCarmel3D+=" ]\n" # fin de bloc
-
- def creaBLOC_EPORT(self, nomsGroupesMaillage) :
- """constitution du bloc EPORT du fichier PHYS"""
- if self.debug:
- print 'cles sources EPORT= %s', self.dictSourceEport.keys()
- typeBloc = 'EPORT'
- for nom in nomsGroupesMaillage: # parcours des noms des groupes de maillage
- if self.dictGroupesMaillage[nom] in self.dictSourceEport.keys(): # test si le nom de la source associee est un port electrique
- # ecriture du bloc du port electrique
- self.texteCarmel3D+=" [EPORT\n" # debut de bloc
- if usePrefix:
- nomReel = self.nomReelGroupeMaillage(nom, typeBloc)
- else:
- nomReel = nom
- self.texteCarmel3D+=" NAME "+nomReel+"\n" # ecriture du nom (reel) du groupe du maillage
- self.texteCarmel3D+= self.dictSourceEport[self.dictGroupesMaillage[nom]] # ecriture des proprietes du port electrique
- self.texteCarmel3D+=" ]\n" # fin de bloc
-
- def creaBLOC_HPORT(self, nomsGroupesMaillage) :
- """constitution du bloc HPORT du fichier PHYS"""
- if self.debug:
- print 'cles sources HPORT= %s', self.dictSourceHport.keys()
- typeBloc = 'HPORT'
- for nom in nomsGroupesMaillage: # parcours des noms des groupes de maillage
- if self.dictGroupesMaillage[nom] in self.dictSourceHport.keys(): # test si le nom de la source associee est un port magnetique
- # ecriture du bloc du port magnetique
- self.texteCarmel3D+=" [HPORT\n" # debut de bloc
- if usePrefix:
- nomReel = self.nomReelGroupeMaillage(nom, typeBloc)
- else:
- nomReel = nom
- self.texteCarmel3D+=" NAME "+nomReel+"\n" # ecriture du nom (reel) du groupe du maillage
- self.texteCarmel3D+= self.dictSourceHport[self.dictGroupesMaillage[nom]] # ecriture des proprietes du port magnetique
- self.texteCarmel3D+=" ]\n" # fin de bloc
-
-#-------------------------------------
-# Methodes utilitaires
-# ------------------------------------
- def formateCOMPLEX(self,nbC):
- """prise en compte des differentes formes de description d un nombre complexe
- 3 formats possibles : 2 listes (anciennement tuples?) et 1 nombre complexe
- """
- if self.debug:
- print "formatage "
- print "type : %(type_nb_c)s pour %(nb_c)s", \
- {'type_nb_c': type(nbC), 'nb_c': nbC}
- nbformate =""
- if isinstance(nbC,(tuple,list)):
- if nbC[0] == "'RI'" :
- nbformate = "COMPLEX " + str(nbC[1])+" "+str(nbC[2])
- if nbC[0] == "'MP'" :
- nbformate = "POLAR " + str(nbC[1])+" "+str(nbC[2])
- else:
- nbformate = "COMPLEX " + str(nbC.real)+" "+str(nbC.imag)
- if self.debug:
- print "nbformate : %s", nbformate
- return nbformate
-
- def nomReelGroupeMaillage(self, nom, typeBloc=None):
- """Calcule et retourne le nom reel du groupe de maillage donne en entree,
- en tenant compte de l'utilisation de prefixes ou pas, et cela pour le type
- de bloc du fichier PHYS specifie.
- Cette routine verifie aussi, en cas d'utilisation de prefixes, si le prefixe est en adequation avec le type du bloc.
- """
- from string import join
- if self.debug:
- print "nom groupe original : %(nom)s avec usePrefix=%(use_prefix)s devient...", \
- {'nom': nom, 'use_prefix': str(usePrefix)}
- nomReel= None # nom affiche dans le fichier PHYS, sans prefixe a priori
- if usePrefix:
- # suppression du prefixe si present
- partiesNom = nom.split(sepNomGroupeMaille) # separation du nom du groupe en parties
- # les tests suivants ne generent une erreur que si le prefixe est obligatoire
- if len(partiesNom) < 2: # test d'erreur, pas de separateur donc nom incorrect, i.e. sans prefixe c'est sur
- print tr("ERREUR! ce groupe de maille (%s) n'a pas de prefixe \
- indiquant le type de materiau ou de source associee", nom)
- elif partiesNom[0] not in listePrefixesGroupeMaille: # prefixe non defini
- print tr("ERREUR! ce groupe de maille (%s) n'a pas de prefixe valable", nom)
- else:
- # verification de l'adequation du prefixe avec le type de bloc demande, si fourni
- if typeBloc is not None:
- if typeBloc not in dictPrefixesGroupeMaille: # test validite de typeBloc, devant etre une cle du dictionnaire
- print tr("ERREUR! ce type de bloc (%s) n'est pas valable", str(typeBloc))
- elif partiesNom[0] not in dictPrefixesGroupeMaille[typeBloc]: # pas de prefixe correct pour ce type de bloc
- print tr("ERREUR! ce groupe de maille (%(nom)s) n'a pas \
- le prefixe correct pour etre associe a un type %(type_bloc)s", \
- {'nom': nom, 'type_bloc': str(typeBloc)})
- else: # c'est bon
- nomReel = join(partiesNom[1:], sepNomGroupeMaille) # reconstruction du nom du groupe sans prefixe complet
- if self.debug:
- print "ce groupe de maille (%(nom)s) a un prefixe qui \
- est supprime automatiquement pour devenir : %(nom_reel)s", \
- {'nom': nom, 'nom_reel': nomReel}
- else: # c'est bon
- nomReel = join(partiesNom[1:], sepNomGroupeMaille) # reconstruction du nom du groupe sans prefixe complet
- if self.debug:
- print "ce groupe de maille (%(nom)s) a un prefixe qui \
- est supprime automatiquement pour devenir : %(nom_reel)s", \
- {'nom': nom, 'nom_reel': nomReel}
- if self.debug:
- print "... %s", nomReel
- return nomReel
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2017 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""Ce module contient le plugin generateur de fichier au format Code_Carmel3D pour EFICAS.
-"""
-
-import traceback
-import types,string,re,os
-from Extensions.i18n import tr
-from generator_python import PythonGenerator
-import Accas
-
-debutTextePhys ="[VERSION\n NUM 1\n FILETYPE PHYS\n]\n"
-debutTextePhys+="[MATERIALS\n"
-texteConductor =" [CONDUCTIVITY\n LAW LINEAR\n"
-texteConductor+=" HOMOGENEOUS TRUE\n"
-texteConductor+=" ISOTROPIC TRUE\n"
-texteConducto2 =" 0.0000000000000000E+00\n ]\n"
-texteConducto2+=" [PERMEABILITY\n LAW LINEAR\n"
-texteConducto2+=" HOMOGENEOUS TRUE\n"
-texteConducto2+=" ISOTROPIC TRUE\n"
-texteNoCond =" [PERMITTIVITY\n LAW LINEAR\n"
-texteNoCond+=" HOMOGENEOUS TRUE\n ISOTROPIC TRUE\n"
-texteNoCond+=" VALUE COMPLEX 0.1000000000000000E+01 0.0000000000000000E+00\n"
-texteNoCond+=" ]\n [PERMEABILITY\n LAW LINEAR\n"
-texteNoCond+=" HOMOGENEOUS TRUE\n ISOTROPIC TRUE\n"
-
-debutTexteParam ="[VERSION\n NUM 1\n FILETYPE PARAM\n]\n"
-debutTexteParam+="[PROBLEM\n NAME HARMONIC\n]\n"
-debutTexteParam+="[CAR_FILES\n NAME "
-
-debutTexteZs0 =" [ZSURFACIC\n NAME "
-debutTexteZs ="\n [CONDUCTIVITY\n"
-debutTexteZs+=" LAW LINEAR\n"
-debutTexteZs+=" HOMOGENEOUS TRUE\n"
-debutTexteZs+=" ISOTROPIC TRUE\n"
-debutTexteZs+=" VALUE COMPLEX "
-texteZs2 =" 0.0000000000000000E+00\n ]\n"
-texteZs2 +=" [PERMEABILITY\n LAW LINEAR\n"
-texteZs2 +=" HOMOGENEOUS TRUE\n"
-texteZs2 +=" ISOTROPIC TRUE\n VALUE COMPLEX "
-finTexteZs =" 0.0000000000000000E+00\n ]\n ]\n"
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'CARMELCND',
- # La factory pour creer une instance du plugin
- 'factory' : CARMELCNDGenerator,
- }
-
-
-class CARMELCNDGenerator(PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un texte au format eficas et
- un texte au format dictionnaire
-
- """
- # Les extensions de fichier permis?
- extensions=('.comm',)
-
-#----------------------------------------------------------------------------------------
- def gener(self,obj,format='brut',config=None):
-
- self.initDico()
-
- # Cette instruction genere le contenu du fichier de commandes (persistance)
- self.text=PythonGenerator.gener(self,obj,format)
- self.racine=obj
- return self.text
-
-
-#----------------------------------------------------------------------------------------
-# initialisations
-#----------------------------------------------------------------------------------------
-
- def initDico(self) :
-
- self.dictMCVal={}
-
-#----------------------------------------------------------------------------------------
-# ecriture
-#----------------------------------------------------------------------------------------
-
- def writeDefault(self,file) :
-#file ne sert pas
-
- self.texteIngendof=""
- self.texteParam=debutTexteParam
- self.chercheFichier()
- self.traiteSourceVCut()
-
- fn=self.fnBase
- fileIngendofDeb = fn[:fn.rfind(".")] + '.ingendof'
- fileIngendof = os.path.join(self.sauveDirectory,fileIngendofDeb)
- f = open( str(fileIngendof), 'wb')
- f.write( self.texteIngendof )
- f.close()
-
- self.textePhys=debutTextePhys
- self.traiteMateriaux()
- filePhysDeb = fn[:fn.rfind(".")] + '.phys'
- filePhys = os.path.join(self.sauveDirectory,filePhysDeb)
- f = open( str(filePhys), 'wb')
- f.write( self.textePhys )
- f.close()
-
- fileParamDeb = fn[:fn.rfind(".")] + '.param'
- fileParam = os.path.join(self.sauveDirectory,fileParamDeb)
- self.traiteParam()
- f = open( str(fileParam), 'wb')
- f.write( self.texteParam )
- f.close()
-
- self.texteCMD="[ \n GLOBAL \n] \n[ \nVISU \n"+self.fnBase.split(".med")[0]+"\nMED \nELEMENT \n] "
- fileCMDDeb = fn[:fn.rfind(".")] + '.cmd'
- fileCMD =os.path.join(self.sauveDirectory,fileCMDDeb)
- f = open( str(fileCMD), 'wb')
- f.write( self.texteCMD )
- f.close()
-
- nomBaseFichier=os.path.basename(fileParam).split(".med")[0]
-
- self.texteInfcarmel=nomBaseFichier
- fileInfcarmelDeb = fn[:fn.rfind(".")] + '.infcarmel'
- fileInfcarmel=os.path.join(self.sauveDirectory,fileInfcarmelDeb)
- f = open( str(fileInfcarmel), 'wb')
- f.write( self.texteInfcarmel )
- f.close()
-
- self.texteInpostpro=nomBaseFichier+"\n"+nomBaseFichier.split(".param")[0]+'.xmat\n'+nomBaseFichier.split(".param")[0]+'.cmd'
- fileInpostproDeb = fn[:fn.rfind(".")] + '.inpostprocess'
- fileInpostpro = os.path.join(self.sauveDirectory,fileInpostproDeb)
- f = open( str(fileInpostpro), 'wb')
- f.write( self.texteInpostpro )
- f.close()
-
-#----------------------------------------------------------------------------------------
-# analyse des commentaires pour trouver le nom du fichier
-#----------------------------------------------------------------------------------------
-
- def chercheFichier(self) :
- nomFichier="inconnu"
- for e in self.racine.etapes:
- if isinstance(e,Accas.COMMENTAIRE):
- print 'ùmasdkfh=',e.valeur[0:17]
- if e.valeur[0:17]=="Cree - fichier : ":
- debut=e.valeur[17:]
- liste=debut.split(" - ")
- nomFichier=liste[0]
- #print 'nom=',nomFichier
- #print 'e.va=',e.valeur.split(" ")[-1]
- #print 'liste=',liste
- nomDomaine=e.valeur.split(" ")[-1]
- break
- self.sauveDirectory=os.path.dirname(nomFichier)
- self.fnBase=os.path.basename(nomFichier)
- self.texteIngendof =os.path.basename(nomFichier)+"\n"
- self.texteParam += os.path.basename(nomFichier).split(".med")[0]+".car\n]\n"
- self.texteParam +="[PHYS_FILES\n NAME "+os.path.basename(nomFichier).split(".med")[0]+".phys\n]\n"
-
-#----------------------------------------------------------------------------------------
-# analyse du dictionnaire pour trouver les sources et les VCut et les ZS
-#----------------------------------------------------------------------------------------
-
- def traiteSourceVCut(self) :
- listeSource=[]
- listeVCut=[]
- self.listeZS=[]
- self.texteSourcePhys="[SOURCES\n"
- for k in self.dictMCVal.keys():
- if k.find ("______SOURCE__") > -1 :
- noms=k.split("_____")
- if noms[0] not in listeSource : listeSource.append(noms[0])
- if k.find ("______VCUT__") > -1 :
- noms=k.split("_____")
- if noms[0] not in listeVCut : listeVCut.append(noms[0])
- if k.find ("______ZS") > -1 :
- noms=k.split("_____")
- if noms[0] not in self.listeZS : self.listeZS.append(noms[0])
- listeSource.sort()
- for source in listeSource:
- debutKey=source+"______SOURCE__"
- texteSource=self.dictMCVal[debutKey+"EnveloppeConnexeInducteur"]+"\n"
- texteSource+="2\n"
- for val in self.dictMCVal[debutKey+"VecteurDirecteur"] :
- texteSource+=str(val)+" "
- texteSource+="\n"
- for val in self.dictMCVal[debutKey+"Centre"] :
- texteSource+=str(val)+" "
- texteSource+="\n"
- texteSource+=str(self.dictMCVal[debutKey+"SectionBobine"])+"\n"
- self.texteIngendof+=texteSource
- self.texteSourcePhys+=" [STRANDED_INDUCTOR\n"
- self.texteSourcePhys+=" NAME "+source+"\n"
- self.texteSourcePhys+=" NTURNS "+str(self.dictMCVal[debutKey+"NbdeTours"])+"\n"
- self.texteSourcePhys+=" CURJ POLAR "+str(self.dictMCVal[debutKey+"Amplitude"])
- self.texteSourcePhys+=" 0.0000000000000000E+00\n ]\n"
-
- self.texteSourcePhys+="]\n"
- for vcut in listeVCut:
- self.texteIngendof+="1\n"
- debutKey=vcut+"______VCUT__"
- if self.dictMCVal[debutKey+"Orientation"] == "Oppose" :self.texteIngendof+="0\n"
- else : self.texteIngendof+="1\n"
- if self.dictMCVal["__PARAMETRES__TypedeFormule"]=="APHI" :self.texteIngendof+="1\n"
- else : self.texteIngendof+="2\n"
-
-
-
-#----------------------------------------------------------------------------------------
- def traiteMateriaux(self) :
-#----------------------------------------------------------------------------------------
- listeCond=[]
- listeNoCond=[]
- for k in self.dictMCVal.keys():
- if k.find ("______CONDUCTEUR") > -1 :
- noms=k.split("_____")
- if noms[0] not in listeCond : listeCond.append(noms[0])
- if k.find ("______NOCOND") > -1 :
- noms=k.split("_____")
- if noms[0] not in listeNoCond : listeNoCond.append(noms[0])
-
- for c in listeCond:
- self.textePhys +=" [CONDUCTOR\n"
- self.textePhys +=" NAME "+c+"\n"
- self.textePhys +=texteConductor
- self.textePhys+=" VALUE COMPLEX "
- self.textePhys+=str(self.dictMCVal[c+"______CONDUCTEUR__Conductivite"])
- self.textePhys+=texteConducto2
- self.textePhys+=" VALUE COMPLEX "
- self.textePhys+=str(self.dictMCVal[c+"______CONDUCTEUR__PermeabiliteRelative"])
- self.textePhys+=" 0.0000000000000000E+00\n ]\n ]\n"
-
- for c in listeNoCond:
- self.textePhys+=" [DIELECTRIC\n"
- self.textePhys +=" NAME "+c+"\n"
- self.textePhys += texteNoCond
- self.textePhys+=" VALUE COMPLEX "
- self.textePhys+=str(self.dictMCVal[c+"______NOCOND__PermeabiliteRelative"])
- self.textePhys+=" 0.0000000000000000E+00\n ]\n ]\n"
-
- for zs in self.listeZS:
- self.textePhys+=debutTexteZs0+zs
- self.textePhys+=debutTexteZs
- self.textePhys+=str(self.dictMCVal[zs+"______ZS__Conductivite"])
- self.textePhys+=texteZs2
- self.textePhys+=str(self.dictMCVal[zs+"______ZS__PermeabiliteRelative"])
- self.textePhys+=finTexteZs
-
- self.textePhys+="]\n"
- self.textePhys+=self.texteSourcePhys
-
-#----------------------------------------------------------------------------------------
-# Creation du fichier Param
-#----------------------------------------------------------------------------------------
- def traiteParam(self):
- self.texteParam +="[FREQUENCY\n SINGLE "+str(self.dictMCVal["__PARAMETRES__Frequence"])+"\n]\n"
- self.texteParam +="[SOLVER\n NAME BICGCR\n"
- self.texteParam +=" [ITERATIVE_PARAM\n"
- self.texteParam +=" NITERMAX "+str(self.dictMCVal["__PARAMETRES__Nb_Max_Iterations"])+"\n"
- self.texteParam +=" EPSILON "+ str(self.dictMCVal["__PARAMETRES__Erreur_Max"])+"\n ]\n]"
-
-
-#----------------------------------------------------------------------------------------
-# analyse de chaque noeud de l'arbre
-#----------------------------------------------------------------------------------------
-
- def generMCSIMP(self,obj) :
- """recuperation de l objet MCSIMP"""
- s=PythonGenerator.generMCSIMP(self,obj)
- if hasattr(obj.etape,'sdnom'): clef=obj.etape.sdnom+"____"
- else: clef=""
- for i in obj.getGenealogie() :
- clef=clef+"__"+i
- self.dictMCVal[clef]=obj.valeur
-
- return s
-
- def get_repExeCarmel(self) :
- return self.dictMCVal["__PARAMETRES__RepCarmel"]
-
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2017 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""Ce module contient le plugin generateur de fichier au format Code_Carmel3D pour EFICAS.
-"""
-
-import traceback
-import types,string,re,os
-from Extensions.i18n import tr
-from generator_python import PythonGenerator
-import Accas
-
-
-
-
-#keys = ['Carmel3D_StudyDirectory','Syrthes_StudyDirectory']
-
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'CARMELCS',
- # La factory pour creer une instance du plugin
- 'factory' : CARMELCSGenerator,
- }
-
-
-class CARMELCSGenerator(PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un texte au format eficas et
- un texte au format dictionnaire
-
- """
- # Les extensions de fichier permis?
- extensions=('.comm',)
-
-#----------------------------------------------------------------------------------------
- def gener(self,obj,format='brut',config=None):
-
- self.initDico()
-
- # Cette instruction genere le contenu du fichier de commandes (persistance)
- self.text=PythonGenerator.gener(self,obj,format)
- self.racine=obj
- return self.text
-
- def generxml(self,obj,format='brut',config=None):
-
- texte = self.gener(obj,format,config)
-# print 'self.dictMCVal = ',self.dictMCVal
- textePourRun = self.update_XMLYacsSchemaForRunning()
- return textePourRun
-
-#----------------------------------------------------------------------------------------
-# initialisations
-#----------------------------------------------------------------------------------------
-
- def initDico(self) :
-
- self.texteDico = ""
- self.dictMCVal={}
- self.dicoCS={}
- self.debutKey = '__PARAM_CS__'
-
-#----------------------------------------------------------------------------------------
-# ecriture
-#----------------------------------------------------------------------------------------
-
- def getdico(self) :
- #print 'getdico : self.dictMCVal.keys() = ',self.dictMCVal.keys()
- for k in self.dictMCVal.keys():
- if k.find (self.debutKey) > -1 :
- a,kproperty=k.split(self.debutKey)
- self.dicoCS[kproperty] = self.dictMCVal[k]
- #print "self.dicoCS = ",self.dicoCS
- return self.dicoCS
-
- def getXMLYacsSchemaFileTemplate(self) :
-
- for k in self.dictMCVal.keys():
- if k.find (self.debutKey) > -1 :
- a,kproperty=k.split(self.debutKey)
- if kproperty == 'XMLYacsFile' :
- return self.dictMCVal[k]
-
- def getXMLYacsSchemaFileRun(self) :
- xmlYacsSchemaFilePath = self.getXMLYacsSchemaFileTemplate()
- filename = os.path.basename(xmlYacsSchemaFilePath)
- dirname = os.path.dirname(xmlYacsSchemaFilePath)
- prefix = '_run_'
- runxmlfile = os.path.join(dirname,prefix+filename)
- return xmlYacsSchemaFilePath,runxmlfile
-
- def update_XMLYacsSchemaForRunning(self) :
- """
- Creation du fichier _run_XXX.xml, a partir des elements donnes par l'utilisateur dans l'interface :
- Carmel3D_StudyDirectory : YYY (path du repertoire de l'etude CARMEL3D de couplage)
- Syrthes_StudyDirectory : YYY/THERMIQUE (path du repertoire de l'etude SYRTHES de couplage)
- XMLYacsFile : PATH du fichier template du schema yacs d'execution du couplage
- """
- xmlYacsSchemaFilePath,runxmlfile = self.getXMLYacsSchemaFileRun()
- f_xml = open( str(xmlYacsSchemaFilePath), 'r')
- texte_template_xml = f_xml.read()
- f_xml.close()
- dicoCS = self.getdico()
- print "dicoCS = ",dicoCS
- # ajout dans dicoCS des elements pour SYRTHES qui sont deja sous cette forme la dans le fichier xml sinon ca pose pb
- dicoCS['DEB']='%(DEB)s'
- dicoCS['FIN']='%(FIN)s'
- newTexteXml = texte_template_xml%dicoCS
- f = open(runxmlfile,'w')
- f.write(newTexteXml)
- f.close()
- return runxmlfile
-
- def writeDefault(self,fn) :
- fileDico = fn[:fn.rfind(".")] + '.py'
- f = open( str(fileDico), 'wb')
- f.write( self.texteDico )
- f.close()
- runxmlfile = self.update_XMLYacsSchemaForRunning()
-
-#----------------------------------------------------------------------------------------
-# analyse de chaque noeud de l'arbre
-#----------------------------------------------------------------------------------------
-
- def generMCSIMP(self,obj) :
- """recuperation de l objet MCSIMP"""
- s=PythonGenerator.generMCSIMP(self,obj)
- self.texteDico+=obj.nom+ "=" + s[0:-1]+ "\n"
-# print 'generMCSIMP self.texteDico = ',self.texteDico
- if hasattr(obj.etape,'sdnom'): clef=obj.etape.sdnom+"____"
- else: clef=""
- for i in obj.getGenealogie() :
- clef=clef+"__"+i
- self.dictMCVal[clef]=obj.valeur
-
- return s
-
-
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
- Ce module contient le plugin generateur de fichier au format
- SEP pour EFICAS.
-
-"""
-import traceback
-import types,string,re,os
-
-from generator_python import PythonGenerator
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
-
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'SEP',
- # La factory pour creer une instance du plugin
- 'factory' : SEPGenerator,
- }
-
-
-class SEPGenerator(PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un texte au format eficas et
- un texte au format py
-
- """
- # Les extensions de fichier permis?
- extensions=('.comm',)
-
- def gener(self,obj,format='brut',config=None):
- self.initDico()
- # Cette instruction génère le contenu du fichier de commandes (persistance)
- self.text=PythonGenerator.gener(self,obj,format)
- # Cette instruction génère le contenu du fichier de paramètres python
- self.genereSEP()
- return self.text
-
- def getTubePy(self) :
- return self.texteTubePy
-
- def genereSEP(self) :
- '''
- Prépare le contenu du fichier de paramètres python. Le contenu
- peut ensuite être obtenu au moyen de la fonction getTubePy().
- '''
- #self.__genereSEP_withVariables()
- self.__genereSEP_withDico()
-
- def __genereSEP_withVariables(self) :
- '''
- Les paramètres sont transcrits sous forme de variables nom=valeur.
- '''
- self.texteTubePy="# Parametres generes par Eficas \n"
- for MC in self.dictMCVal.keys():
- ligne = MC +"="+ repr(self.dictMCVal[MC])+'\n'
- self.texteTubePy=self.texteTubePy+ligne
-
- print self.texteTubePy
-
- # __GBO__: Tester self.tube pour aiguiller en fonction du cas (au besoin)
- fichier=os.path.join(os.path.dirname(__file__),"tube.py")
- f=open(fichier,'r')
- for ligne in f.readlines():
- self.texteTubePy=self.texteTubePy+ligne
- f.close
-
- def __genereSEP_withDico(self) :
- """
- Les paramètres sont transcrits sous la forme d'un dictionnaire nom=valeur.
- """
- from Sep import properties
- self.texteTubePy="# -*- coding: utf-8 -*-\n"
- self.texteTubePy+="# ======================================================================================\n"
- self.texteTubePy+="# FICHIER GENERE PAR EFICAS - OUTIL MÉTIER SOUS-EPAISSEUR - "
- self.texteTubePy+="VERSION "+str(properties.version)+" du "+str(properties.date)+"\n"
- self.texteTubePy+="# ======================================================================================\n"
- self.texteTubePy+="\n"
- self.texteTubePy+="# Parametres Utilisateur Eficas \n"
- self.texteTubePy+="parameters={}\n"
-
- for MC in self.dictMCVal.keys():
- ligne = "parameters['"+MC+"']="+ repr(self.dictMCVal[MC])+'\n'
- self.texteTubePy=self.texteTubePy+ligne
-
- # On ajoute des paramètres de configuration pour contrôle de
- # cohérence avec la procédure outil métier
- self.texteTubePy+="# Parametres de Configuration Eficas \n"
- ligne = "parameters['OMVERSION']="+str(properties.version)+"\n"
- self.texteTubePy+=ligne
-
- # __GBO__: Tester self.tube pour aiguiller en fonction du cas (au besoin)
- self.texteTubePy+="\n"
- self.texteTubePy+="# Exécution de la procédure outil métier \n"
- self.texteTubePy+="import os,sys\n"
- self.texteTubePy+="sys.path.insert(0,os.environ['OM_ROOT_DIR'])\n"
- self.texteTubePy+="import om_data\n"
- self.texteTubePy+="om_data.setParameters(parameters)\n"
- self.texteTubePy+="def run():\n"
- self.texteTubePy+=" import om_smeca\n"
- self.texteTubePy+="\n"
- self.texteTubePy+='if __name__ == "__main__":\n'
- self.texteTubePy+=" run()\n"
-
- # For debug only
- print self.texteTubePy
-
-
- def initDico(self) :
- self.tube=0
- self.coude=0
- self.dictMCVal={}
- self.texteTubePy=""
-
- # __GBO__: surcharge de PythonGenerator:
- # voir example generator_cuve2dg.py (genea)
- def generMCSIMP(self,obj) :
- """
- Convertit un objet MCSIMP en texte python
- Remplit le dictionnaire des MCSIMP si nous ne sommes ni dans une loi, ni dans une variable
- """
- clef=""
- for i in obj.getGenealogie() :
- clef=clef+"__"+i
- #self.dictMCVal[obj.nom]=obj.valeur
- self.dictMCVal[clef]=obj.valeur
-
- s=PythonGenerator.generMCSIMP(self,obj)
- return s
-
- # __GBO__: surcharge de PythonGenerator
- def generMACRO_ETAPE(self,obj):
- print obj.nom
- if obj.nom == "S_EP_INTERNE" :
- self.tube=1
- if obj.nom == "M_COUDE" :
- self.coude=1
- s=PythonGenerator.generMACRO_ETAPE(self,obj)
- return s
-
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2017 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""Ce module contient le plugin generateur de fichier au format Code_Carmel3D pour EFICAS.
-"""
-from __future__ import absolute_import
-from __future__ import print_function
-try :
- from builtins import str
-except : pass
-
-import pickle
-texte_debut="#include <Zcracks_base.z7p> \n int main() \n{ \n init_var();\n"
-texte_debut+=' format="med";\n'
-import traceback
-import types,re,os
-from Extensions.i18n import tr
-from .generator_python import PythonGenerator
-#ListeConcatene=('ridge_names','topo_names','geom_names','elsetNames','fasetNames','lisetNames','nsetNames','center','normal','dir')
-ListeConcatene=('ridge_names','topo_names','geom_names','elsetNames','fasetNames','lisetNames','nsetNames')
-ListeConcatene2=('center','normal','dir')
-ListeConcatene3=('ra','rb')
-if_ellipse=False
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'ZCRACKS',
- # La factory pour creer une instance du plugin
- 'factory' : ZCrackGenerator,
- }
-
-
-class ZCrackGenerator(PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un texte au format eficas et
- un texte au format dictionnaire
-
- """
- # Les extensions de fichier permis?
- extensions=('.comm',)
-
-#----------------------------------------------------------------------------------------
- def gener(self,obj,format='brut',config=None):
-
- self.initDico()
-
- # Cette instruction genere le contenu du fichier de commandes (persistance)
- self.text=PythonGenerator.gener(self,obj,format)
- return self.text
-
-
-#----------------------------------------------------------------------------------------
-# initialisations
-#----------------------------------------------------------------------------------------
-
- def initDico(self) :
- self.textePourRun = texte_debut
-
-
-#----------------------------------------------------------------------------------------
-# ecriture
-#----------------------------------------------------------------------------------------
-
- def writeDefault(self,fn) :
- fileZcrack = fn[:fn.rfind(".")] + '.z7p'
- f = open( str(fileZcrack), 'wb')
- print((self.textePourRun))
-
- self.ajoutRun()
- self.textePourRunAvecDouble=self.textePourRun.replace("'",'"')
- f.write( self.textePourRunAvecDouble)
- f.close()
-
- def ajoutRun(self) :
- self.textePourRun+=" write_mesh_crack();\n"
- self.textePourRun+=" do_mesh_crack(0);\n"
- self.textePourRun+=" write_refine_mesh();\n"
- self.textePourRun+=" do_refine_mesh(0);\n"
- self.textePourRun+=" write_cut_mesh();\n"
- self.textePourRun+=" do_cut_mesh(0);\n"
-# self.textePourRun+=" nice_cut("+str(self.maximum_aspect_ratio)+");\n"
- self.textePourRun+=' export_mesh("'+self.cracked_name+'","med");\n'
- self.textePourRun+="}"
-
-#----------------------------------------------------------------------------------------
-# analyse de chaque noeud de l'arbre
-#----------------------------------------------------------------------------------------
-
- def generMCSIMP(self,obj) :
- """recuperation de l objet MCSIMP"""
- #print dir(obj)
- s=PythonGenerator.generMCSIMP(self,obj)
- if obj.nom=="sane_name" :
- self.textePourRun+=' import_mesh("'+obj.val+'", "med");\n'
- if obj.nom in ListeConcatene :
-# obj.val=obj.val+" "
- stringListe=""
- for val in obj.val:
- stringListe+=val+""
-# pickle.dump( stringListe, open( "/home/H60874/test.pickle", "wb" ) )
-# self.textePourRun+=" "+obj.nom+ "='"+ stringListe[0:-1]+ "';\n"
-# self.textePourRun+=" "+obj.nom+ "='"+ stringListe+ "';\n"
- return s
- if obj.nom in ListeConcatene3 :
- if (obj.nom=="ra") :
- self.textePourRun+=" "+"if_ellipse=1;\n"
- self.textePourRun+=" "+obj.nom+ "="+str(obj.val)+";\n"
- if_ellipse_ellipse=True
- return s
-
- if obj.nom in ListeConcatene2 :
- stringListe=""
-# self.textePourRun+="GGGGGGG%"+obj.nom+"\n"
-# if (len(val)>1) :
- for val in obj.val:
- stringListe+=str(val)+","
- self.textePourRun+=" "+obj.nom+ "=set_vector3("+ stringListe[0:-1]+ ");\n"
-# else :
-# self.textePourRun+=" "+obj.nom+ str(obj.val+ ";\n"
-# stringListe+=str(val)+" "
-# self.textePourRun+=" "+obj.nom+ "=set_vector3("+stringListe[0]+","+stringListe[1]+","+stringListe[2]+");\n"
-# self.textePourRun+=" "+obj.nom+ "=set_vector3("+obj.val+","+");\n"
- return s
-# if obj.nom=="center" :
-# self.textePourRun+=" set_vector3("+obj.val+'");\n"
-# if obj.nom=="center" :
-# self.textePourRun+=" set_vector3("+obj.val+'");\n"
-# if obj.nom=="normal" :
-# self.textePourRun+=" set_vector3("+obj.val+'");\n"
-# if obj.nom=="dir" :
-# self.textePourRun+=" set_vector3("+obj.val+'");\n"
- if obj.nom=="elset_radius" :
- self.textePourRun+=" if_must_define_elset=1;\n"
-
-
- if obj.nom=="cracked_name" : self.cracked_name=obj.val
- if obj.nom=="maximum_aspect_ratio" : self.maximum_aspect_ratio=obj.val
- if obj.nom=="repertoire" :
- print ("PNPNPN a traiter")
- return s
- self.textePourRun+=" "+obj.nom+ "=" + s[0:-1]+ ";\n"
- return s
-
-
-# si repertoire on change tous les noms de fichier
-# exple repertoire='/home' __> fichier='/home/crack.med
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
- Ce module contient le plugin generateur de fichier au format asterv5 pour EFICAS.
-
-
-"""
-import traceback
-import types,string
-from Extensions.i18n import tr
-from Extensions.eficas_exception import EficasException
-from Noyau import N_CR
-from Accas import ETAPE,PROC_ETAPE,MACRO_ETAPE,ETAPE_NIVEAU,JDC,FORM_ETAPE
-from Accas import MCSIMP,MCFACT,MCBLOC,MCList,EVAL
-from Accas import GEOM,ASSD
-from Accas import COMMENTAIRE,PARAMETRE, PARAMETRE_EVAL,COMMANDE_COMM
-from Formatage import Formatage
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
-
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'asterv5',
- # La factory pour creer une instance du plugin
- 'factory' : AsterGenerator,
- }
-
-
-class AsterGenerator:
- """
- Ce generateur parcourt un objet de type JDC et produit
- un fichier au format asterv5
-
- L'acquisition et le parcours sont realises par la methode
- generator.gener(objet_jdc,format)
-
- L'ecriture du fichier au format asterv5 est realisee par appel de la methode
- generator.writefile(nom_fichier)
-
- Ses caracteristiques principales sont exposees dans des attributs
- de classe :
- - extensions : qui donne une liste d'extensions de fichier preconisees
-
- """
- # Les extensions de fichier preconisees
- extensions=('.comm',)
-
- def __init__(self,cr=None):
- # Si l'objet compte-rendu n'est pas fourni, on utilise le compte-rendu standard
- if cr :
- self.cr=cr
- else:
- self.cr=N_CR.CR(debut='CR generateur format asterv5',
- fin='fin CR format asterv5')
- # Le texte au format asterv5 est stocke dans l'attribut text
- self.text=''
-
- def writefile(self,filename):
- fp=open(filename,'w')
- fp.write(self.text)
- fp.close()
-
- def gener(self,obj,format='brut'):
- """
- Retourne une representation du JDC obj sous une
- forme qui est parametree par format.
- Si format vaut 'brut', retourne une liste de listes de ...
- Si format vaut 'standard', retourne un texte obtenu par concatenation de la liste
- Si format vaut 'beautifie', retourne le meme texte beautifie
- """
- liste= self.generator(obj)
- if format == 'brut':
- self.text=liste
- elif format == 'standard':
- self.text=string.join(liste)
- elif format == 'beautifie':
- jdc_formate = Formatage(liste,sep=':',l_max=72)
- self.text=jdc_formate.formateJdc()
- else:
- raise EficasException(tr("Format pas implemente : %s", format))
- return self.text
-
- def generator(self,obj):
- """
- Cette methode joue un role d'aiguillage en fonction du type de obj
- On pourrait utiliser les methodes accept et visitxxx à la
- place (depend des gouts !!!)
- """
- # ATTENTION a l'ordre des tests : il peut avoir de l'importance (heritage)
- if isinstance(obj,PROC_ETAPE):
- return self.generPROC_ETAPE(obj)
- elif isinstance(obj,MACRO_ETAPE):
- return self.generMACRO_ETAPE(obj)
- elif isinstance(obj,FORM_ETAPE):
- return self.generFORM_ETAPE(obj)
- elif isinstance(obj,ETAPE):
- return self.generETAPE(obj)
- elif isinstance(obj,MCFACT):
- return self.generMCFACT(obj)
- elif isinstance(obj,MCList):
- return self.generMCList(obj)
- elif isinstance(obj,MCBLOC):
- return self.generMCBLOC(obj)
- elif isinstance(obj,MCSIMP):
- return self.generMCSIMP(obj)
- elif isinstance(obj,ASSD):
- return self.generASSD(obj)
- elif isinstance(obj,ETAPE_NIVEAU):
- return self.generETAPE_NIVEAU(obj)
- elif isinstance(obj,COMMENTAIRE):
- return self.generCOMMENTAIRE(obj)
- # Attention doit etre place avant PARAMETRE (raison : heritage)
- elif isinstance(obj,PARAMETRE_EVAL):
- return self.generPARAMETRE_EVAL(obj)
- elif isinstance(obj,PARAMETRE):
- return self.generPARAMETRE(obj)
- elif isinstance(obj,EVAL):
- return self.generEVAL(obj)
- elif isinstance(obj,COMMANDE_COMM):
- return self.generCOMMANDE_COMM(obj)
- elif isinstance(obj,JDC):
- return self.generJDC(obj)
- else:
- raise EficasException(tr("Type d'objet non prevu : %s", repr(obj)))
-
- def generJDC(self,obj):
- """
- Cette methode convertit un objet JDC en une liste de chaines de
- caracteres à la syntaxe asterv5
- """
- l=[]
- if obj.definition.l_niveaux == ():
- # Il n'y a pas de niveaux
- for etape in obj.etapes:
- l.append(self.generator(etape))
- else:
- # Il y a des niveaux
- for etape_niveau in obj.etapes_niveaux:
- l.extend(self.generator(etape_niveau))
- if l != [] :
- # Si au moins une etape, on ajoute le retour chariot sur la derniere etape
- if type(l[-1])==types.ListType:
- l[-1][-1] = l[-1][-1]+'\n'
- elif type(l[-1])==types.StringType:
- l[-1] = l[-1]+'\n'
- return l
-
- def generCOMMANDE_COMM(self,obj):
- """
- Cette methode convertit un COMMANDE_COMM
- en une liste de chaines de caracteres à la syntaxe asterv5
- """
- l_lignes = string.split(obj.valeur,'\n')
- txt=''
- for ligne in l_lignes:
- txt = txt + '%%'+ligne+'\n'
- return txt
-
- def generEVAL(self,obj):
- """
- Cette methode convertit un EVAL
- en une liste de chaines de caracteres à la syntaxe asterv5
- """
- return 'EVAL(u"'+ obj.valeur +'")'
-
- def generCOMMENTAIRE(self,obj):
- """
- Cette methode convertit un COMMENTAIRE
- en une liste de chaines de caracteres à la syntaxe asterv5
- """
- l_lignes = string.split(obj.valeur,'\n')
- txt=''
- for ligne in l_lignes:
- txt = txt + '%'+ligne+'\n'
- return txt
-
- def generPARAMETRE_EVAL(self,obj):
- """
- Cette methode convertit un PARAMETRE_EVAL
- en une liste de chaines de caracteres à la syntaxe asterv5
- """
- if obj.valeur == None:
- return obj.nom + ' = None ;\n'
- else:
- return obj.nom + ' = '+ self.generator(obj.valeur) +';\n'
-
- def generPARAMETRE(self,obj):
- """
- Cette methode convertit un PARAMETRE
- en une liste de chaines de caracteres à la syntaxe asterv5
- """
- if type(obj.valeur) == types.StringType:
- return obj.nom + " = '" + obj.valeur + "';\n"
- else:
- return obj.nom + ' = ' + str(obj.valeur) + ';\n'
-
- def generETAPE_NIVEAU(self,obj):
- """
- Cette methode convertit une etape niveau
- en une liste de chaines de caracteres à la syntaxe asterv5
- """
- l=[]
- if obj.etapes_niveaux == []:
- for etape in obj.etapes:
- l.append(self.generator(etape))
- else:
- for etape_niveau in obj.etapes_niveaux:
- l.extend(self.generator(etape_niveau))
- return l
-
- def generETAPE(self,obj):
- """
- Cette methode convertit une etape
- en une liste de chaines de caracteres à la syntaxe asterv5
- """
- try:
- if obj.reuse != None:
- sdname= "&" + self.generator(obj.reuse)
- else:
- sdname= self.generator(obj.sd)
- except:
- sdname='sansnom'
- l=[]
- label=sdname + '='+obj.definition.nom+'('
- l.append(label)
- for v in obj.mc_liste:
- if isinstance(v,MCBLOC) or isinstance(v,MCList):
- liste=self.generator(v)
- for mocle in liste :
- l.append(mocle)
- else:
- l.append(self.generator(v))
- if len(l) == 1:
- l[0]=label+');'
- else :
- l.append(');')
- return l
-
- def generFORM_ETAPE(self,obj):
- """
- Methode particuliere pour les objets de type FORMULE
- """
- l=[]
- nom = obj.getNom()
- if nom == '' : nom = 'sansnom'
- if len(obj.mc_liste)>0:
- l.append(nom + ' = FORMULE(')
- s=obj.type_retourne + ' = ' + "'''" + obj.arguments + ' = ' + obj.corps+"'''"
- l.append(s)
- l.append(');')
- else:
- l.append(nom+' = FORMULE();')
- return l
-
- def generMACRO_ETAPE(self,obj):
- """
- Cette methode convertit une macro-etape
- en une liste de chaines de caracteres à la syntaxe asterv5
- """
- if obj.definition.nom == 'FORMULE' : return self.gen_ast_formule(obj)
- try:
- if obj.reuse != None:
- sdname= "&" + self.generator(obj.reuse)+'='
- elif obj.sd == None:
- sdname=''
- else:
- sdname= self.generator(obj.sd)+'='
- except:
- sdname='sansnom='
- l=[]
- label = sdname + obj.definition.nom+'('
- l.append(label)
- for v in obj.mc_liste:
- if isinstance(v,MCBLOC) or isinstance(v,MCList):
- liste=self.generator(v)
- for mocle in liste :
- l.append(mocle)
- else:
- # MCFACT ou MCSIMP
- l.append(self.generator(v))
- if len(l) == 1:
- l[0]=label+');'
- else :
- l.append(');')
- return l
-
- def gen_ast_formule(self,obj):
- """
- Methode gen_ast particuliere aux objets de type FORMULE
- """
- label='!FORMULE('
- try:
- sdname= self.generator(obj.sd)
- except:
- sdname='sansnom'
- l=[]
- l.append(label)
- for v in obj.mc_liste:
- s=''
- s= v.nom+':'+sdname+'('+v.valeur+')'
- l.append(s)
- if len(l) == 1:
- l[0]=label+');'
- else :
- l.append(');')
- return l
-
- def generPROC_ETAPE(self,obj):
- """
- Cette methode convertit une etape
- en une liste de chaines de caracteres à la syntaxe asterv5
- """
- l=[]
- label=obj.definition.nom+'('
- l.append(label)
- for v in obj.mc_liste:
- if isinstance(v,MCBLOC) or isinstance(v,MCList):
- liste=self.generator(v)
- for mocle in liste :
- l.append(mocle)
- else:
- l.append(self.generator(v))
- if len(l) == 1:
- l[0]=label+');'
- else :
- l.append(');')
- return l
-
- def generMCSIMP(self,obj) :
- """
- Convertit un objet MCSIMP en une liste de chaines de caracteres à la
- syntaxe asterv5
- """
- if type(obj.valeur) == types.TupleType :
- s = '('
- for val in obj.valeur :
- if s != '(': s = s + ','
- if type(val) == types.InstanceType :
- if isinstance(val,PARAMETRE):
- # il ne faut pas prendre la string que retourne gen_ast
- # mais seulement le nom dans le cas d'un parametre
- s = s + val.nom
- else:
- s = s + self.generator(val)
- elif self.wait_geom(obj):
- s = s + val
- elif type(val) == types.FloatType :
- #s = s + self.repr_float(val)
- s = s + str(val)
- else :
- s = s + `val`
- s = s + ')'
- s=obj.nom+':'+s+' '
- return s
- else :
- if type(obj.valeur) == types.InstanceType :
- if isinstance(obj.valeur,PARAMETRE):
- # il ne faut pas prendre la string que retourne gen_ast
- # mais seulement str dans le cas d'un parametre
- s = obj.valeur.nom
- else:
- s = self.generator(obj.valeur)
- elif self.wait_geom(obj):
- s = obj.valeur
- elif type(obj.valeur) == types.FloatType :
- #s = self.repr_float(obj.valeur)
- s = str(obj.valeur)
- else :
- s = `obj.valeur`
- s=obj.nom+':'+s+' '
- return s
-
- def wait_geom(self,obj):
- for typ in obj.definition.type:
- if type(typ) == types.ClassType :
- if issubclass(typ,GEOM) : return 1
- return 0
-
- def repr_float(self,valeur):
- """
- Cette fonction represente le reel valeur comme une chaîne de caracteres
- sous forme mantisse exposant si necessaire cad si le nombre contient plus de 5 caracteres
- NB : valeur est un reel au format Python ou une chaîne de caracteres representant un reel
- """
- if type(valeur) == types.StringType : valeur = eval(valeur)
- if valeur == 0. : return '0.0'
- if abs(valeur) > 1. :
- if abs(valeur) < 10000. : return repr(valeur)
- else :
- if abs(valeur) > 0.01 : return repr(valeur)
- t=repr(valeur)
- if string.find(t,'e') != -1 or string.find(t,'E') != -1 :
- # le reel est dejà sous forme mantisse exposant !
- # --> on remplace e par E
- t=string.replace(t,'e','E')
- # --> on doit encore verifier que la mantisse contient bien un '.'
- if string.find(t,'.')!= -1:
- return t
- else:
- # -->il faut rajouter le point avant le E
- t=string.replace(t,'E','.E')
- return t
- s=''
- neg = 0
- if t[0]=='-':
- s=s+t[0]
- t=t[1:]
- cpt = 0
- if string.atof(t[0]) == 0.:
- # reel plus petit que 1
- neg = 1
- t=t[2:]
- cpt=1
- while string.atof(t[0]) == 0. :
- cpt = cpt+1
- t=t[1:]
- s=s+t[0]+'.'
- for c in t[1:]:
- s=s+c
- else:
- # reel plus grand que 1
- s=s+t[0]+'.'
- if string.atof(t[1:]) == 0.:
- l=string.split(t[1:],'.')
- cpt = len(l[0])
- else:
- r=0
- pt=0
- for c in t[1:]:
- r=r+1
- if c != '.' :
- if pt != 1 : cpt = cpt + 1
- s=s+c
- else:
- pt = 1
- if r+1 == len(t) or string.atof(t[r+1:]) == 0.:break
- s=s+'E'+neg*'-'+repr(cpt)
- return s
-
- def generASSD(self,obj):
- """
- Convertit un objet derive d'ASSD en une chaine de caracteres à la
- syntaxe asterv5
- """
- return obj.getName()
-
- def generMCFACT(self,obj):
- """
- Convertit un objet MCFACT en une liste de chaines de caracteres à la
- syntaxe asterv5
- """
- l=[]
- label=obj.nom + ':('
- l.append(label)
- for v in obj.mc_liste:
- if isinstance(v,MCBLOC) or isinstance(v,MCList):
- liste=self.generator(v)
- for mocle in liste :
- l.append(mocle)
- else:
- l.append(self.generator(v))
- l.append(')')
- return l
-
- def generMCList(self,obj):
- """
- Convertit un objet MCList en une liste de chaines de caracteres à la
- syntaxe asterv5
- """
- l=[]
- for mcfact in obj.data:
- l.append(self.generator(mcfact))
- return l
-
- def generMCBLOC(self,obj):
- """
- Convertit un objet MCBLOC en une liste de chaines de caracteres à la
- syntaxe asterv5
- """
- l=[]
- for v in obj.mc_liste:
- if isinstance(v,MCBLOC) or isinstance(v,MCList):
- liste=self.generator(v)
- for mocle in liste :
- l.append(mocle)
- else:
- l.append(self.generator(v))
- return l
-
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
- Ce module contient le plugin generateur de fichier au format
- DefaillCUVE pour EFICAS.
-
-"""
-import traceback
-import types,string,re
-
-from Noyau import N_CR
-from Accas import MCSIMP
-from generator_python import PythonGenerator
-
-def entryPoint():
- """
- Retourne les informations nécessaires pour le chargeur de plugins
-
- Ces informations sont retournées dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'cuve2dg',
- # La factory pour créer une instance du plugin
- 'factory' : Cuve2dgGenerator,
- }
-
-
-class Cuve2dgGenerator(PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un texte au format eficas et
- un texte au format DefaillCUVE
-
- """
- # Les extensions de fichier préconisées
- extensions=('.comm',)
-
- def __init__(self,cr=None):
- # Si l'objet compte-rendu n'est pas fourni, on utilise le compte-rendu standard
- if cr :
- self.cr=cr
- else:
- self.cr=N_CR.CR(debut='CR generateur format DefaillCUVE pour DefaillCUVE',
- fin='fin CR format DefaillCUVE pour DefaillCUVE')
- # Le texte au format DefaillCUVE est stocké dans l'attribut textCuve
- self.textCuve=''
-
- # Ce dictionnaire liste le nom des variables utilisees dans le script
- self.variable = {
- "NiveauImpression" : "MESSAGE_LEVEL",
- "FichierDataIn" : "DATARESUME_FILE",
- "FichierTempSigma" : "TEMPSIG_FILE",
- "FichierCSV" : "CSV_FILE",
- "FichierRESTART" : "RESTART_FILE",
- "FichierEXTR" : "EXTR_FILE",
- "ChoixPlugin" : "CHOIPLUG",
- "GrandeurEvaluee" : "GRANDEUR",
- "IncrementTemporel" : "INCRTPS",
- "IncrementMaxTemperature" : "DTPREC",
- "ChoixExtractionTransitoires" : "CHOIEXTR",
- "IncrementMaxTempsAffichage" : "DTARCH",
- "traitementGeometrie" : "TYPEGEOM",
- "RayonInterne" : "RINT",
- "RayonInterne_mess" : "RINT_MESSAGE",
- "RayonExterne" : "REXT",
- "RayonExterne_mess" : "REXT_MESSAGE",
- "EpaisseurRevetement" : "LREV",
- "EpaisseurRevetement_mess" : "LREV_MESSAGE",
- "LigamentExterneMin" : "LIGMIN",
- "LigamentExterneMin_mess" : "LIGMIN_MESSAGE",
- "NombreNoeudsMaillage" : "NBNO",
- "TypeInitial" : "TYPEDEF",
- "Orientation" : "ORIEDEF",
- "Position" : "POSDEF",
- "ProfondeurRadiale" : "PROFDEF",
- "ProfondeurRadiale_mess" : "PROFDEF_MESSAGE",
- "ModeCalculLongueur" : "OPTLONG",
- "Longueur" : "LONGDEF",
- "Longueur_mess" : "LONGDEF_MESSAGE",
- "CoefDirecteur" : "PROFSURLONG",
- "CoefDirecteur_mess" : "PROFSURLONG_MESSAGE",
- "Constante" : "LONGCONST",
- "ModeCalculDecalage" : "DECATYP",
- "DecalageNormalise" : "DECANOR",
- "DecalageNormalise_mess" : "DECANOR_MESSAGE",
- "DecalageRadial" : "DECADEF",
- "DecalageRadial_mess" : "DECADEF_MESSAGE",
- "Azimut" : "ANGLDEF",
- "Azimut_mess" : "ANGLDEF_MESSAGE",
- "Altitude_mess" : "ANGLDEF_MESSAGE",
- "Altitude" : "ALTIDEF",
- "Altitude_mess" : "ALTIDEF_MESSAGE",
- "Pointe" : "POINDEF",
- "ModeleFluence" : "MODELFLUENCE",
- "ZoneActiveCoeur_AltitudeSup" : "H1COEUR",
- "ZoneActiveCoeur_AltitudeInf" : "H2COEUR",
- "FluenceMax" : "fmax",
- "KPFrance" : "KPFRANCE",
- "KPUS" : "KPUS",
- "Azimut_0deg" : "COEFFLUENCE1",
- "Azimut_5deg" : "COEFFLUENCE2",
- "Azimut_10deg" : "COEFFLUENCE3",
- "Azimut_15deg" : "COEFFLUENCE4",
- "Azimut_20deg" : "COEFFLUENCE5",
- "Azimut_25deg" : "COEFFLUENCE6",
- "Azimut_30deg" : "COEFFLUENCE7",
- "Azimut_35deg" : "COEFFLUENCE8",
- "Azimut_40deg" : "COEFFLUENCE9",
- "Azimut_45deg" : "COEFFLUENCE10",
- "TypeIrradiation" : "TYPEIRR",
- "RTNDT" : "RTNDT",
- "ModeleIrradiation" : "MODELIRR",
- "TeneurCuivre" : "CU",
- "TeneurCuivre_mess" : "CU_MESSAGE",
- "TeneurNickel" : "NI",
- "TeneurNickel_mess" : "NI_MESSAGE",
- "TeneurPhosphore" : "P",
- "TeneurPhosphore_mess" : "P_MESSAGE",
- "MoyenneRTndt" : "RTimoy",
- "MoyenneRTndt_mess" : "RTimoy_MESSAGE",
- "CoefVariationRTndt" : "RTicov",
- "CoefVariationRTndt_mess" : "RTicov_MESSAGE",
- "EcartTypeRTndt" : "USectDRT",
- "EcartTypeRTndt_mess" : "USectDRT_MESSAGE",
- "NombreEcartTypeRTndt" : "nbectDRTNDT",
- "NombreEcartTypeRTndt_mess" : "nbectDRTNDT_MESSAGE",
- "ModeleTenacite" : "MODELKIC",
- "NombreCaracteristique" : "NBCARAC",
- "NbEcartType_MoyKIc" : "nbectKIc",
- "NbEcartType_MoyKIc_mess" : "nbectKIc_MESSAGE",
- "PalierDuctile_KIc" : "KICPAL",
- "CoefficientVariation_KIc" : "KICCDV",
- "Fractile_KIc" : "fractKIc",
- "Fractile_KIc_mess" : "fractKIc_MESSAGE",
- "Temperature_KIc100" : "T0WALLIN",
- "A1" : "A1",
- "A2" : "A2",
- "A3" : "A3",
- "B1" : "B1",
- "B2" : "B2",
- "B3" : "B3",
- "C1" : "C1",
- "C2" : "C2",
- "C3" : "C3",
- "ChoixCorrectionLongueur" : "CHOIXCL",
- "AttnCorrBeta" : "ATTNCORRBETA",
- "CorrIrwin" : "CORRIRWIN",
- "ArretDeFissure" : "ARRETFISSURE",
- "IncrementTailleFissure" : "INCRDEF",
- "IncrementTailleFissure_mess" : "INCRDEF_MESSAGE",
- "NbEcartType_MoyKIa" : "nbectKIa",
- "PalierDuctile_KIa" : "KIAPAL",
- "CoefficientVariation_KIa" : "KIACDV",
- "ChoixCoefficientChargement" : "CHOIXSIGM",
- "CoefficientDuctile" : "COEFSIGM1",
- "CoefficientFragile" : "COEFSIGM2",
- "InstantInitialisation" : "INSTINIT",
- "ConditionLimiteThermiqueREV" : "KTHREV",
- "TemperatureDeformationNulleREV" : "TREFREV",
- "TemperaturePourCoefDilatThermREV" : "TDETREV",
- "CoefficientPoissonREV" : "NUREV",
- "ConditionLimiteThermiqueMDB" : "KTHMDB",
- "TemperatureDeformationNulleMDB" : "TREFMDB",
- "TemperaturePourCoefDilatThermMDB" : "TDETMDB",
- "CoefficientPoissonMDB" : "NUMDB",
- "TypeConditionLimiteThermique" : "TYPCLTH",
- "Instant_1" : "INSTANT1",
- "Instant_2" : "INSTANT2",
- "Instant_3" : "INSTANT3",
- "DebitAccumule" : "QACCU",
- "DebitInjectionSecurite" : "QIS",
- "TempInjectionSecurite" : "TIS",
- "TempInjectionSecurite_mess" : "TIS_MESSAGE",
- "DiametreHydraulique" : "DH",
- "DiametreHydraulique_mess" : "DH_MESSAGE",
- "SectionEspaceAnnulaire" : "SECTION",
- "SectionEspaceAnnulaire_mess" : "SECTION_MESSAGE",
- "HauteurCaracConvectionNaturelle" : "DELTA",
- "HauteurCaracConvectionNaturelle_mess" : "DELTA_MESSAGE",
- "CritereConvergenceRelative" : "EPS",
- "CoefficientsVestale" : "COEFVESTALE",
- "VolumeMelange_CREARE" : "VMTAB",
- "TemperatureInitiale_CREARE" : "T0",
- "TemperatureInitiale_CREARE_mess" : "T0_MESSAGE",
- "SurfaceEchange_FluideStructure" : "SE",
- "SurfaceEchange_FluideStructure_mess" : "SE_MESSAGE",
- "InstantPerteCirculationNaturelle" : "INST_PCN",
- }
-
- # Ce dictionnaire liste le nom des valeurs proposées utilisees dans le script
- self.valeurproposee = {
- "Aucune impression" : "0",
- "Temps total" : "1",
- "Temps intermediaires" : "2",
- "Facteur de marge KIc/KCP" : "FM_KICSURKCP",
- "Marge KIc-KI" : "MARGE_KI",
- "Marge KIc-KCP" : "MARGE_KCP",
- "Topologie" : "GEOMETRIE",
- "Maillage" : "MAILLAGE",
- "Defaut Sous Revetement" : "DSR",
- "Defaut Decale" : "DECALE",
- "Defaut Debouchant" : "DEBOUCHANT",
- "Longitudinale" : "LONGITUD",
- "Circonferentielle" : "CIRCONF",
- "Virole" : "VIROLE",
- "Joint soude" : "JSOUDE",
- "Valeur" : "VALEUR",
- "Fonction affine de la profondeur" : "FCTAFFINE",
- "Valeur normalisee" : "NORMALISE",
- "A" : "A",
- "B" : "B",
- "A et B" : "BOTH",
- "Exponentiel sans revetement k=9.7 (Reglementaire)" : "Reglementaire",
- "Exponentiel sans revetement k=12.7 (France)" : "France",
- "Exponentiel sans revetement k=0. (ValeurImposee)" : "ValeurImposee",
- "Donnees francaises du palier CPY (SDM)" : "SDM",
- "Regulatory Guide 1.99 rev 2 (USNRC)" : "USNRC",
- "Dossier 900 MWe AP9701 rev 2 (REV_2)" : "REV_2",
- "Lissage du modele ajuste (SDM_Lissage)" : "SDM_Lissage",
- "Donnees francaises du palier CPY ajustees par secteur angulaire (GrandeDev)" : "GrandeDev",
- "Grand developpement (GD_Cuve)" : "GD_Cuve",
- "Exponentiel sans revetement k=9.7 (Reglementaire CUVE1D)" : "Cuve1D",
- "RTndt de la cuve a l instant de l analyse" : "RTNDT",
- "Modele d irradiation" : "FLUENCE",
- "Formule de FIM/FIS Lefebvre modifiee" : "LEFEBnew",
- "Metal de Base : formule de FIM/FIS Houssin" : "HOUSSIN",
- "Metal de Base : formule de FIM/FIS Persoz" : "PERSOZ",
- "Metal de Base : formule de FIM/FIS Lefebvre" : "LEFEBVRE",
- "Metal de Base : Regulatory Guide 1.00 rev 2" : "USNRCmdb",
- "Joint Soude : formulation de FIM/FIS Brillaud" : "BRILLAUD",
- "Joint Soude : Regulatory Guide 1.00 rev 2" : "USNRCsoud",
- "RCC-M/ASME coefficient=2" : "RCC-M",
- "RCC-M/ASME coefficient=2 CUVE1D" : "RCC-M_simpl",
- "RCC-M/ASME coefficient=2.33 (Houssin)" : "Houssin_RC",
- "RCC-M/ASME avec KI=KIpalier" : "RCC-M_pal",
- "RCC-M/ASME avec KI~exponentiel" : "RCC-M_exp",
- "Weibull basee sur la master cuve" : "Wallin",
- "Weibull basee sur la master cuve (REME)" : "REME",
- "Weibull n\xb01 (etude ORNL)" : "ORNL",
- "Weibull n\xb02" : "WEIB2",
- "Weibull n\xb03" : "WEIB3",
- "Weibull generalisee" : "WEIB-GEN",
- "Exponentielle n\xb01 (Frama)" : "Frama",
- "Exponentielle n\xb02 (LOGWOLF)" : "LOGWOLF",
- "Quantile" : "QUANTILE",
- "Ordre" : "ORDRE",
- "Enthalpie" : "ENTHALPIE",
- "Chaleur" : "CHALEUR",
- "Temperature imposee en paroi" : "TEMP_IMPO",
- "Flux de chaleur impose en paroi" : "FLUX_REP",
- "Temperature imposee du fluide et coefficient echange" : "ECHANGE",
- "Debit massique et temperature d injection de securite" : "DEBIT",
- "Temperature imposee du fluide et debit d injection de securite" : "TEMP_FLU",
- "Courbe APRP" : "APRP",
- "Calcul TEMPFLU puis DEBIT" : "TFDEBIT",
- }
-
- # Ce dictionnaire liste le commentaire des variables utilisees dans le script
- self.comment = {
- "NiveauImpression" : "Niveau d impression des messages a l ecran (=0 : rien, =1 : temps calcul total, =2 : temps intermediaires)",
- "FichierDataIn" : "sortie du fichier recapitulatif des donnees d entree {OUI ; NON}",
- "FichierTempSigma" : "sortie des fichiers temperature et contraintes {OUI ; NON}",
- "FichierCSV" : "sortie du fichier resultat template_DEFAILLCUVE.CSV {OUI ; NON}",
- "FichierRESTART" : "sortie du fichier de re-demarrage",
- "FichierEXTR" : "sortie du fichier d extraction des transitoires",
- "ChoixPlugin" : "choix d'un repertoire de plug-in",
- "GrandeurEvaluee" : "choix de la grandeur sous critere evaluee {FM_KICSURKCP ; MARGE_KI ; MARGE_KCP}",
- "IncrementTemporel" : "increment temporel pour l analyse PROBABILISTE (si DETERMINISTE, fixer a 1)",
- "IncrementMaxTemperature" : "increment max de temp/noeud/instant (degC)",
- "ChoixExtractionTransitoires" : "choix d'extraction de transitoires de temp et contraintes",
- "IncrementMaxTempsAffichage" : "increment max de temps pour affichage (s)",
- "traitementGeometrie" : "traitement de la geometrie de la cuve : {GEOMETRIE, MAILLAGE}",
- "RayonInterne" : "rayon interne (m)",
- "RayonInterne_mess" : "affichage ecran du rayon interne (m)",
- "RayonExterne" : "rayon externe (m)",
- "RayonExterne_mess" : "affichage ecran du rayon externe (m)",
- "EpaisseurRevetement" : "epaisseur revetement (m)",
- "EpaisseurRevetement_mess" : "affichage ecran de l epaisseur revetement (m)",
- "LigamentExterneMin" : "ligament externe minimal avant rupture (% de l'epaisseur de cuve)",
- "LigamentExterneMin_mess" : "affichage ecran du ligament externe minimal avant rupture (% de l'epaisseur de cuve)",
- "NombreNoeudsMaillage" : "nbre de noeuds dans l'epaisseur de la cuve",
- "TypeInitial" : "type initial du defaut : DEBOUCHANT=Defaut Debouchant, DSR=Defaut Sous Revetement, DECALE=Defaut Decale",
- "Orientation" : "orientation (LONGITUD / CIRCONF)",
- "Position" : "Position du defaut (VIROLE / JSOUDE)",
- "ProfondeurRadiale" : "profondeur radiale ou encore hauteur (m)",
- "ProfondeurRadiale_mess" : "affichage ecran de la profondeur radiale ou encore hauteur (m)",
- "ModeCalculLongueur" : "option pour definir la longueur du defaut (VALEUR pour une valeur fixe, FCTAFFINE pour une fct affine de la profondeur)",
- "Longueur" : "longueur (m) pour defaut Sous Revetement",
- "Longueur_mess" : "affichage ecran de la longueur (m) pour defaut Sous Revetement",
- "CoefDirecteur" : "pente de la fonction affine l = h/profsurlong + a0",
- "CoefDirecteur_mess" : "affichage ecran de la pente de la fonction affine l = h/profsurlong + a0",
- "Constante" : "constante de la fonction affine a0",
- "ModeCalculDecalage" : "type de decalage : normalise (NORMALISE) ou reel (VALEUR)",
- "DecalageNormalise" : "decalage radial normalise (valeur comprise entre 0. et 1.) pour defaut Sous Revetement",
- "DecalageNormalise_mess" : "affichage ecran du decalage radial normalise (valeur comprise entre 0. et 1.) pour defaut Sous Revetement",
- "DecalageRadial" : "decalage radial reel (m) pour defaut decale",
- "DecalageRadial_mess" : "affichage ecran du decalage radial reel (m) pour defaut decale",
- "Azimut" : "coordonnee angulaire (degre)",
- "Azimut_mess" : "affichage ecran de la coordonnee angulaire (degre)",
- "Altitude" : "altitude (m) : valeur negative",
- "Altitude_mess" : "affichage ecran de l altitude (m) : valeur negative",
- "Pointe" : "choix du(des) point(s) du defaut considere {'A','B','BOTH'} pour DSR et DECALE (pour DEBOUCHANT : automatiquement 'B')",
- "ModeleFluence" : "modele de fluence : {Reglementaire, France, ValeurImposee, SDM, USNRC, REV_2, SDM_Lissage, GrandeDev, GD_Cuve, Cuve1D}",
- "ZoneActiveCoeur_AltitudeSup" : "cote superieure de la zone active de coeur (ici pour cuve palier 900Mw)",
- "ZoneActiveCoeur_AltitudeInf" : "cote inferieure de la zone active de coeur (ici pour cuve palier 900Mw)",
- "FluenceMax" : "fluence maximale assimilee par la cuve (n/cm2)",
- "KPFrance" : "parametre exponentiel du modele France",
- "KPUS" : "parametre exponentiel du modele US",
- "Azimut_0deg" : "fluence a l'azimut 0 (10^19 n/cm)",
- "Azimut_5deg" : "fluence a l'azimut 5 (10^19 n/cm)",
- "Azimut_10deg" : "fluence a l'azimut 10 (10^19 n/cm)",
- "Azimut_15deg" : "fluence a l'azimut 15 (10^19 n/cm)",
- "Azimut_20deg" : "fluence a l'azimut 20 (10^19 n/cm)",
- "Azimut_25deg" : "fluence a l'azimut 25 (10^19 n/cm)",
- "Azimut_30deg" : "fluence a l'azimut 30 (10^19 n/cm)",
- "Azimut_35deg" : "fluence a l'azimut 35 (10^19 n/cm)",
- "Azimut_40deg" : "fluence a l'azimut 40 (10^19 n/cm)",
- "Azimut_45deg" : "fluence a l'azimut 45 (10^19 n/cm)",
- "TypeIrradiation" : "type irradiation : {RTNDT, FLUENCE}",
- "RTNDT" : "RTNDT finale (degC)",
- "ModeleIrradiation" : "modele d irradiation : LEFEBnew, ou {HOUSSIN, PERSOZ, LEFEBVRE, USNRCmdb} pour virole et {BRILLAUD,USNRCsoud} pour jointsoude",
- "TeneurCuivre" : "teneur en cuivre (%)",
- "TeneurCuivre_mess" : "affichage ecran de la teneur en cuivre (%)",
- "TeneurNickel" : "teneur en nickel (%)",
- "TeneurNickel_mess" : "affichage ecran de la teneur en nickel (%)",
- "TeneurPhosphore" : "teneur en phosphore (%)",
- "TeneurPhosphore_mess" : "affichage ecran de la teneur en phosphore (%)",
- "MoyenneRTndt" : "moyenne de la RTNDT initiale : virole C1 de cuve Chinon : mdb=>-17.degC et js=>42.degC (HT-56/05/038 : p.52)",
- "MoyenneRTndt_mess" : "affichage ecran de la moyenne de la RTNDT initiale",
- "CoefVariationRTndt" : "coef de variation de la RTNDT initiale",
- "CoefVariationRTndt_mess" : "affichage ecran du coef de variation de la RTNDT initiale",
- "EcartTypeRTndt" : "pour modeles USNRCsoud ou USNRCmdb, ecart-type du decalage de RTNDT (°F) (28. pour js et 17. pour mdb)",
- "EcartTypeRTndt_mess" : "affichage ecran, pour modeles USNRCsoud ou USNRCmdb, ecart-type du decalage de RTNDT (°F) (28. pour js et 17. pour mdb)",
- "NombreEcartTypeRTndt" : "Nbre d ecart-type par rapport a la moyenne de DRTNDT si analyse PROBABILISTE (en DETERMINISTE, fixer a 2.)",
- "NombreEcartTypeRTndt_mess" : "affichage ecran du nbre d ecart-type par rapport a la moyenne de DRTNDT si analyse PROBABILISTE",
- "ModeleTenacite" : "modele de tenacite : {RCC-M, RCC-M_pal, RCC-M_exp, RCC-M_simpl, Houssin_RC, Wallin, REME, ORNL, Frama, WEIB3, WEIB2, LOGWOLF, WEIB-GEN}",
- "NombreCaracteristique" : "Nb caracteristique : ORDRE ou QUANTILE",
- "NbEcartType_MoyKIc" : "Nbre d ecart-type par rapport a la moyenne de KIc si analyse PROBABILISTE (en DETERMINISTE, fixer a -2.)",
- "NbEcartType_MoyKIc_mess" : "affichage ecran du nbre d ecart-type par rapport a la moyenne de KIc si analyse PROBABILISTE",
- "PalierDuctile_KIc" : "palier deterministe de K1c (MPa(m^0.5))",
- "CoefficientVariation_KIc" : "coef de variation de la loi normale de K1c",
- "Fractile_KIc" : "valeur caracteristique de KIc exprimee en ordre de fractile (%)",
- "Fractile_KIc_mess" : "affichage ecran de la valeur caracteristique de KIc exprimee en ordre de fractile (%)",
- "Temperature_KIc100" : "parametre T0 du modele Wallin (degC)",
- "A1" : "coef des coefs d une WEIBULL generale",
- "A2" : "",
- "A3" : "",
- "B1" : "",
- "B2" : "",
- "B3" : "",
- "C1" : "",
- "C2" : "",
- "C3" : "",
- "ChoixCorrectionLongueur" : "Activation ou non de la correction de longueur {OUI ; NON}",
- "AttnCorrBeta" : "Attenuation de la correction plastique : {OUI, NON} ==> uniquement pour DSR ou DECALE",
- "CorrIrwin" : "Correction plastique IRWIN : {OUI, NON} ==> uniquement pour DEBOUCHANT",
- "ArretDeFissure" : "prise en compte de l arret de fissure {OUI, NON} (en PROBABILISTE, fixer a NON)",
- "IncrementTailleFissure" : "increment de la taille de fissure (m)",
- "IncrementTailleFissure_mess" : "affichage ecran de l increment de la taille de fissure (m)",
- "NbEcartType_MoyKIa" : "Nbre d ecart-type par rapport a la moyenne de KIa (nb sigma)",
- "PalierDuctile_KIa" : "palier deterministe de K1a quand modele RCC-M (MPa(m^0.5))",
- "CoefficientVariation_KIa" : "coef de variation de la loi normale de K1a",
- "ChoixCoefficientChargement" : "prise en compte de coefficients sur le chargement (OUI/NON)",
- "CoefficientDuctile" : "coefficient multiplicateur pour rupture ductile",
- "CoefficientFragile" : "coefficient multiplicateur pour rupture fragile",
- "InstantInitialisation" : "instant initial (s)",
- "ConditionLimiteThermiqueREV" : "Option 'ENTHALPIE' ou 'CHALEUR'",
- "TemperatureDeformationNulleREV" : "temperature de deformation nulle (degC)",
- "TemperaturePourCoefDilatThermREV" : "temperature de definition du coefficient de dilatation thermique (degC)",
- "CoefficientPoissonREV" : "coefficient de Poisson",
- "ConditionLimiteThermiqueMDB" : "Option 'ENTHALPIE' ou 'CHALEUR'",
- "TemperatureDeformationNulleMDB" : "temperature de deformation nulle (degC)",
- "TemperaturePourCoefDilatThermMDB" : "temperature de definition du coefficient de dilatation thermique (degC)",
- "CoefficientPoissonMDB" : "coefficient de Poisson",
- "TypeConditionLimiteThermique" : "Type de condition thermique en paroi interne {TEMP_IMPO,FLUX_REP,ECHANGE,DEBIT,TEMP_FLU,APRP}",
- "Instant_1" : "Borne superieure de l intervalle de temps du 1er palier TACCU",
- "Instant_2" : "Borne superieure de l intervalle de temps du 2nd palier T1",
- "Instant_3" : "Borne superieure de l intervalle de temps du 3eme palier TIS",
- "DebitAccumule" : "Debit accumule (en m3/h)",
- "DebitInjectionSecurite" : "Debit injection de securite (en m3/h)",
- "TempInjectionSecurite" : "Temperature injection de securite (en degC)",
- "TempInjectionSecurite_mess" : "affichage ecran de la temperature injection de securite",
- "DiametreHydraulique" : "Diametre hydraulique (m)",
- "DiametreHydraulique_mess" : "affichage ecran du diametre hydraulique (m)",
- "SectionEspaceAnnulaire" : "Section espace annulaire (m2)",
- "SectionEspaceAnnulaire_mess" : "affichage ecran de la section espace annulaire (m2)",
- "HauteurCaracConvectionNaturelle" : "Hauteur caracteristique convection naturelle (m)",
- "HauteurCaracConvectionNaturelle_mess" : "affichage ecran de la hauteur caracteristique convection naturelle (m)",
- "CritereConvergenceRelative" : "Critere convergence relative (-)",
- "CoefficientsVestale" : "Application des coefs de Vestale {OUI;NON}",
- "VolumeMelange_CREARE" : "Transitoire de volume de melange CREARE (m3)",
- "TemperatureInitiale_CREARE" : "Temperature initiale CREARE (degC)",
- "TemperatureInitiale_CREARE_mess" : "affichage ecran de la temperature initiale CREARE (degC)",
- "SurfaceEchange_FluideStructure" : "Surface d'echange fluide/structure (m2)",
- "SurfaceEchange_FluideStructure_mess" : "affichage ecran de la surface d'echange fluide/structure (m2)",
- "InstantPerteCirculationNaturelle" : "Instant de perte de circulation naturelle",
- }
-
- # Ce dictionnaire liste la valeur par defaut des variables utilisees dans le script
- self.default = {
- "NiveauImpression" : "1",
- "FichierDataIn" : "NON",
- "FichierTempSigma" : "NON",
- "FichierCSV" : "NON",
- "FichierRESTART" : "NON",
- "FichierEXTR" : "NON",
- "ChoixPlugin" : "NON",
- "GrandeurEvaluee" : "FM_KICSURKCP",
- "IncrementTemporel" : "1",
- "IncrementMaxTemperature" : "0.1",
- "ChoixExtractionTransitoires" : "NON",
- "IncrementMaxTempsAffichage" : "1000.",
- "traitementGeometrie" : "GEOMETRIE",
- "RayonInterne" : "1.994",
- "RayonInterne_mess" : "NON",
- "RayonExterne" : "2.2015",
- "RayonExterne_mess" : "NON",
- "EpaisseurRevetement" : "0.0075",
- "EpaisseurRevetement_mess" : "NON",
- "LigamentExterneMin" : "0.75",
- "LigamentExterneMin_mess" : "NON",
- "NombreNoeudsMaillage" : "300",
- "TypeInitial" : "DSR",
- "Position" : "VIROLE",
- "ProfondeurRadiale" : "0.006",
- "ProfondeurRadiale_mess" : "NON",
- "ModeCalculLongueur" : "VALEUR",
- "Longueur" : "0.060",
- "Longueur_mess" : "NON",
- "CoefDirecteur" : "10.",
- "CoefDirecteur_mess" : "NON",
- "Constante" : "0.",
- "ModeCalculDecalage" : "VALEUR",
- "DecalageNormalise" : "0.1",
- "DecalageNormalise_mess" : "NON",
- "DecalageRadial" : "0.",
- "DecalageRadial_mess" : "NON",
- "Azimut" : "0.",
- "Azimut_mess" : "NON",
- "Altitude" : "-4.",
- "Altitude_mess" : "NON",
- "Pointe" : "B",
- "ModeleFluence" : "Reglementaire",
- "ZoneActiveCoeur_AltitudeSup" : "-3.536",
- "ZoneActiveCoeur_AltitudeInf" : "-7.194",
- "FluenceMax" : "6.5",
- "KPFrance" : "12.7",
- "KPUS" : "9.4488",
- "Azimut_0deg" : "5.8",
- "Azimut_5deg" : "5.48",
- "Azimut_10deg" : "4.46",
- "Azimut_15deg" : "3.41",
- "Azimut_20deg" : "3.37",
- "Azimut_25deg" : "3.16",
- "Azimut_30deg" : "2.74",
- "Azimut_35deg" : "2.25",
- "Azimut_40deg" : "1.89",
- "Azimut_45deg" : "1.78",
- "TypeIrradiation" : "RTNDT",
- "RTNDT" : "64.",
- "ModeleIrradiation" : "HOUSSIN",
- "TeneurCuivre" : "0.0972",
- "TeneurCuivre_mess" : "NON",
- "TeneurNickel" : "0.72",
- "TeneurNickel_mess" : "NON",
- "TeneurPhosphore" : "0.00912",
- "TeneurPhosphore_mess" : "NON",
- "MoyenneRTndt" : "-12.0",
- "MoyenneRTndt_mess" : "NON",
- "CoefVariationRTndt" : "0.1",
- "CoefVariationRTndt_mess" : "NON",
- "EcartTypeRTndt" : "-2.",
- "EcartTypeRTndt_mess" : "NON",
- "NombreEcartTypeRTndt" : "2.",
- "NombreEcartTypeRTndt_mess" : "NON",
- "ModeleTenacite" : "RCC-M",
- "NombreCaracteristique" : "Quantile",
- "NbEcartType_MoyKIc" : "-2.",
- "NbEcartType_MoyKIc_mess" : "NON",
- "PalierDuctile_KIc" : "195.",
- "CoefficientVariation_KIc" : "0.15",
- "Fractile_KIc" : "5.",
- "Fractile_KIc_mess" : "NON",
- "Temperature_KIc100" : "-27.",
- "A1" : "21.263",
- "A2" : "9.159",
- "A3" : "0.04057",
- "B1" : "17.153",
- "B2" : "55.089",
- "B3" : "0.0144",
- "C1" : "4.",
- "C2" : "0.",
- "C3" : "0.",
- "ChoixCorrectionLongueur" : "OUI",
- "AttnCorrBeta" : "NON",
- "CorrIrwin" : "NON",
- "ArretDeFissure" : "NON",
- "IncrementTailleFissure" : "0.",
- "IncrementTailleFissure_mess" : "NON",
- "NbEcartType_MoyKIa" : "0.",
- "PalierDuctile_KIa" : "0.",
- "CoefficientVariation_KIa" : "0.",
- "ChoixCoefficientChargement" : "NON",
- "CoefficientDuctile" : "1.0",
- "CoefficientFragile" : "1.0",
- "InstantInitialisation" : "-1.",
- "ConditionLimiteThermiqueREV" : "CHALEUR",
- "TemperatureDeformationNulleREV" : "20.",
- "TemperaturePourCoefDilatThermREV" : "287.",
- "CoefficientPoissonREV" : "0.3",
- "ConditionLimiteThermiqueMDB" : "CHALEUR",
- "TemperatureDeformationNulleMDB" : "20.",
- "TemperaturePourCoefDilatThermMDB" : "287.",
- "CoefficientPoissonMDB" : "0.3",
- "TypeConditionLimiteThermique" : "TEMP_IMPO",
- "Instant_1" : "21.",
- "Instant_2" : "45.",
- "Instant_3" : "5870.",
- "DebitAccumule" : "2.3",
- "DebitInjectionSecurite" : "0.375",
- "TempInjectionSecurite" : "9.",
- "TempInjectionSecurite_mess" : "NON",
- "DiametreHydraulique" : "0.3816",
- "DiametreHydraulique_mess" : "NON",
- "SectionEspaceAnnulaire" : "0.21712",
- "SectionEspaceAnnulaire_mess" : "NON",
- "HauteurCaracConvectionNaturelle" : "6.",
- "HauteurCaracConvectionNaturelle_mess" : "NON",
- "CritereConvergenceRelative" : "0.00001",
- "CoefficientsVestale" : "NON",
-# "VolumeMelange_CREARE" : "14.9",
- "TemperatureInitiale_CREARE" : "250.",
- "TemperatureInitiale_CREARE_mess" : "NON",
- "SurfaceEchange_FluideStructure" : "0.",
- "SurfaceEchange_FluideStructure_mess" : "NON",
- "InstantPerteCirculationNaturelle" : "400.",
- }
-
- # Ce dictionnaire liste la rubrique d'appartenance des variables utilisees dans le script
- self.bloc = {
- "NiveauImpression" : "OPTIONS",
- "FichierDataIn" : "OPTIONS",
- "FichierTempSigma" : "OPTIONS",
- "FichierCSV" : "OPTIONS",
- "FichierRESTART" : "OPTIONS",
- "FichierEXTR" : "OPTIONS",
- "ChoixPlugin" : "OPTIONS",
- "GrandeurEvaluee" : "OPTIONS",
- "IncrementTemporel" : "OPTIONS",
- "IncrementMaxTemperature" : "OPTIONS",
- "ChoixExtractionTransitoires" : "OPTIONS",
- "IncrementMaxTempsAffichage" : "OPTIONS",
- "traitementGeometrie" : "DONNEES DE LA CUVE",
- "RayonInterne" : "DONNEES DE LA CUVE",
- "RayonInterne_mess" : "DONNEES DE LA CUVE",
- "RayonExterne" : "DONNEES DE LA CUVE",
- "RayonExterne_mess" : "DONNEES DE LA CUVE",
- "EpaisseurRevetement" : "DONNEES DE LA CUVE",
- "EpaisseurRevetement_mess" : "DONNEES DE LA CUVE",
- "LigamentExterneMin" : "DONNEES DE LA CUVE",
- "LigamentExterneMin_mess" : "DONNEES DE LA CUVE",
- "NombreNoeudsMaillage" : "DONNEES DE LA CUVE",
- "TypeInitial" : "CARACTERISTIQUES DU DEFAUT",
- "Orientation" : "CARACTERISTIQUES DU DEFAUT",
- "Position" : "CARACTERISTIQUES DU DEFAUT",
- "ProfondeurRadiale" : "CARACTERISTIQUES DU DEFAUT",
- "ProfondeurRadiale_mess" : "CARACTERISTIQUES DU DEFAUT",
- "ModeCalculLongueur" : "CARACTERISTIQUES DU DEFAUT",
- "Longueur" : "CARACTERISTIQUES DU DEFAUT",
- "Longueur_mess" : "CARACTERISTIQUES DU DEFAUT",
- "CoefDirecteur" : "CARACTERISTIQUES DU DEFAUT",
- "CoefDirecteur_mess" : "CARACTERISTIQUES DU DEFAUT",
- "Constante" : "CARACTERISTIQUES DU DEFAUT",
- "ModeCalculDecalage" : "CARACTERISTIQUES DU DEFAUT",
- "DecalageNormalise" : "CARACTERISTIQUES DU DEFAUT",
- "DecalageNormalise_mess" : "CARACTERISTIQUES DU DEFAUT",
- "DecalageRadial" : "CARACTERISTIQUES DU DEFAUT",
- "DecalageRadial_mess" : "CARACTERISTIQUES DU DEFAUT",
- "Azimut" : "CARACTERISTIQUES DU DEFAUT",
- "Azimut_mess" : "CARACTERISTIQUES DU DEFAUT",
- "Altitude" : "CARACTERISTIQUES DU DEFAUT",
- "Altitude_mess" : "CARACTERISTIQUES DU DEFAUT",
- "Pointe" : "CARACTERISTIQUES DU DEFAUT",
- "ModeleFluence" : "MODELES",
- "ZoneActiveCoeur_AltitudeSup" : "MODELES",
- "ZoneActiveCoeur_AltitudeInf" : "MODELES",
- "FluenceMax" : "MODELES",
- "KPFrance" : "MODELES",
- "KPUS" : "MODELES",
- "Azimut_0deg" : "MODELES",
- "Azimut_5deg" : "MODELES",
- "Azimut_10deg" : "MODELES",
- "Azimut_15deg" : "MODELES",
- "Azimut_20deg" : "MODELES",
- "Azimut_25deg" : "MODELES",
- "Azimut_30deg" : "MODELES",
- "Azimut_35deg" : "MODELES",
- "Azimut_40deg" : "MODELES",
- "Azimut_45deg" : "MODELES",
- "TypeIrradiation" : "MODELES",
- "RTNDT" : "MODELES",
- "ModeleIrradiation" : "MODELES",
- "TeneurCuivre" : "MODELES",
- "TeneurCuivre_mess" : "MODELES",
- "TeneurNickel" : "MODELES",
- "TeneurNickel_mess" : "MODELES",
- "TeneurPhosphore" : "MODELES",
- "TeneurPhosphore_mess" : "MODELES",
- "MoyenneRTndt" : "MODELES",
- "MoyenneRTndt_mess" : "MODELES",
- "CoefVariationRTndt" : "MODELES",
- "CoefVariationRTndt_mess" : "MODELES",
- "EcartTypeRTndt" : "MODELES",
- "EcartTypeRTndt_mess" : "MODELES",
- "NombreEcartTypeRTndt" : "MODELES",
- "NombreEcartTypeRTndt_mess" : "MODELES",
- "ModeleTenacite" : "MODELES",
- "NombreCaracteristique" : "MODELES",
- "NbEcartType_MoyKIc" : "MODELES",
- "NbEcartType_MoyKIc_mess" : "MODELES",
- "PalierDuctile_KIc" : "MODELES",
- "CoefficientVariation_KIc" : "MODELES",
- "Fractile_KIc" : "MODELES",
- "Fractile_KIc_mess" : "MODELES",
- "Temperature_KIc100" : "MODELES",
- "A1" : "MODELES",
- "A2" : "MODELES",
- "A3" : "MODELES",
- "B1" : "MODELES",
- "B2" : "MODELES",
- "B3" : "MODELES",
- "C1" : "MODELES",
- "C2" : "MODELES",
- "C3" : "MODELES",
- "ChoixCorrectionLongueur" : "MODELES",
- "AttnCorrBeta" : "MODELES",
- "CorrIrwin" : "MODELES",
- "ArretDeFissure" : "MODELES",
- "IncrementTailleFissure" : "MODELES",
- "IncrementTailleFissure_mess" : "MODELES",
- "NbEcartType_MoyKIa" : "MODELES",
- "PalierDuctile_KIa" : "MODELES",
- "CoefficientVariation_KIa" : "MODELES",
- "ChoixCoefficientChargement" : "ETAT INITIAL",
- "CoefficientDuctile" : "ETAT INITIAL",
- "CoefficientFragile" : "ETAT INITIAL",
- "InstantInitialisation" : "ETAT INITIAL",
- "ConditionLimiteThermiqueREV" : "CARACTERISTIQUES DU REVETEMENT",
- "TemperatureDeformationNulleREV" : "CARACTERISTIQUES DU REVETEMENT",
- "TemperaturePourCoefDilatThermREV" : "CARACTERISTIQUES DU REVETEMENT",
- "CoefficientPoissonREV" : "CARACTERISTIQUES DU REVETEMENT",
- "ConditionLimiteThermiqueMDB" : "CARACTERISTIQUES DU MDB",
- "TemperatureDeformationNulleMDB" : "CARACTERISTIQUES DU MDB",
- "TemperaturePourCoefDilatThermMDB" : "CARACTERISTIQUES DU MDB",
- "CoefficientPoissonMDB" : "CARACTERISTIQUES DU MDB",
- "TypeConditionLimiteThermique" : "TRANSITOIRE",
- "Instant_1" : "TRANSITOIRE",
- "Instant_2" : "TRANSITOIRE",
- "Instant_3" : "TRANSITOIRE",
- "DebitAccumule" : "TRANSITOIRE",
- "DebitInjectionSecurite" : "TRANSITOIRE",
- "TempInjectionSecurite" : "TRANSITOIRE",
- "TempInjectionSecurite_mess" : "TRANSITOIRE",
- "DiametreHydraulique" : "TRANSITOIRE",
- "DiametreHydraulique_mess" : "TRANSITOIRE",
- "SectionEspaceAnnulaire" : "TRANSITOIRE",
- "SectionEspaceAnnulaire_mess" : "TRANSITOIRE",
- "HauteurCaracConvectionNaturelle" : "TRANSITOIRE",
- "HauteurCaracConvectionNaturelle_mess" : "TRANSITOIRE",
- "CritereConvergenceRelative" : "TRANSITOIRE",
- "CoefficientsVestale" : "TRANSITOIRE",
- "VolumeMelange_CREARE" : "TRANSITOIRE",
- "TemperatureInitiale_CREARE" : "TRANSITOIRE",
- "TemperatureInitiale_CREARE_mess" : "TRANSITOIRE",
- "SurfaceEchange_FluideStructure" : "TRANSITOIRE",
- "SurfaceEchange_FluideStructure_mess" : "TRANSITOIRE",
- "InstantPerteCirculationNaturelle" : "TRANSITOIRE",
- }
-
- def gener(self,obj,format='brut'):
- self.text=''
- self.textCuve=''
- self.texteTFDEBIT=''
- self.dico_mot={}
- self.dico_genea={}
- self.text=PythonGenerator.gener(self,obj,format)
- return self.text
-
- def generMCSIMP(self,obj) :
- self.dico_mot[obj.nom]=obj.valeur
- clef=""
- for i in obj.getGenealogie() :
- clef=clef+"_"+i
- self.dico_genea[clef]=obj.valeur
- s=PythonGenerator.generMCSIMP(self,obj)
- return s
-
- def writeCuve2DG(self, filename, file2):
- print "je passe dans writeCuve2DG"
- self.genereTexteCuve()
- f = open( filename, 'wb')
- print self.texteCuve
- f.write( self.texteCuve )
- f.close()
- ftmp = open( "/tmp/data_template", 'wb')
- ftmp.write( self.texteCuve )
- ftmp.close()
-
- self.genereTexteTFDEBIT()
- f2 = open( file2, 'wb')
- print self.texteTFDEBIT
- f2.write( self.texteTFDEBIT )
- f2.close()
-
-
- def entete(self):
- '''
- Ecrit l'entete du fichier data_template
- '''
- texte = "############################################################################################"+"\n"
- texte += "#"+"\n"
- texte += "# OUTIL D'ANALYSE PROBABILISTE DE LA DUREE DE VIE DES CUVES REP"+"\n"
- texte += "# ---------------"+"\n"
- texte += "# FICHIER DE MISE EN DONNEES"+"\n"
- texte += "#"+"\n"
- texte += "# SI CALCUL DETERMINISTE :"+"\n"
- texte += "# - fixer INCRTPS=1, nbectDRTNDT=2., nbectKIc=-2."+"\n"
- texte += "# - les calculs ne sont possibles qu'en une seule pointe du defaut (POINDEF<>BOTH)"+"\n"
- texte += "# SI CALCUL PROBABILISTE :"+"\n"
- texte += "# - fixer ARRETFISSURE=NON"+"\n"
- texte += "#"+"\n"
- texte += "############################################################################################"+"\n"
- texte += "#"+"\n"
- return texte
-
- def rubrique(self, titre):
- '''
- Rubrique
- '''
- texte = "#"+"\n"
- texte += "############################################################################################"+"\n"
- texte += "# " + titre + "\n"
- texte += "############################################################################################"+"\n"
- texte += "#"+"\n"
- return texte
-
- def sousRubrique(self, soustitre, numtitre):
- '''
- Sous-rubrique
- '''
- texte = "#"+"\n"
- texte += "# " + numtitre + soustitre + "\n"
- texte += "#==========================================================================================="+"\n"
- texte += "#"+"\n"
- return texte
-
- def ecritLigne(self, variablelue):
- '''
- Ecrit l'affectation d'une valeur a sa variable, suivie d'un commentaire
- '''
- texte = "%s = %s # %s\n" % (self.variable[variablelue], str(self.dico_mot[variablelue]), self.comment[variablelue])
- return texte
-
- def affecteValeurDefaut(self, variablelue):
- '''
- Affecte une valeur par defaut a une variable, suivie d'un commentaire
- '''
- print "Warning ==> Dans la rubrique",self.bloc[variablelue],", valeur par defaut pour ",variablelue," = ",self.default[variablelue]
- texte = "%s = %s # %s\n" % (self.variable[variablelue], self.default[variablelue], self.comment[variablelue])
- return texte
-
- def affecteValeur(self, variablelue, valeuraffectee):
- '''
- Affecte une valeur a une variable, suivie d'un commentaire
- '''
- texte = "%s = %s # %s\n" % (self.variable[variablelue], valeuraffectee, self.comment[variablelue])
- return texte
-
- def ecritVariable(self, variablelue):
- if self.dico_mot.has_key(variablelue):
- texte = self.ecritLigne(variablelue)
- else :
- texte = self.affecteValeurDefaut(variablelue)
- return texte
-
- def amontAval(self, amont, aval):
- if str(self.dico_mot[amont])=='Continu':
- if str(self.dico_mot[aval])=='Continu':
- texte = 'CC'+"\n"
- if str(self.dico_mot[aval])=='Lineaire':
- texte = 'CL'+"\n"
- if str(self.dico_mot[aval])=='Exclu':
- texte = 'CE'+"\n"
- if str(self.dico_mot[amont])=='Lineaire':
- if str(self.dico_mot[aval])=='Continu':
- texte = 'LC'+"\n"
- if str(self.dico_mot[aval])=='Lineaire':
- texte = 'LL'+"\n"
- if str(self.dico_mot[aval])=='Exclu':
- texte = 'LE'+"\n"
- if str(self.dico_mot[amont])=='Exclu':
- if str(self.dico_mot[aval])=='Continu':
- texte = 'EC'+"\n"
- if str(self.dico_mot[aval])=='Lineaire':
- texte = 'EL'+"\n"
- if str(self.dico_mot[aval])=='Exclu':
- texte = 'EE'+"\n"
- return texte
-
- def genereTexteCuve(self):
- self.texteCuve = ""
- self.texteCuve += self.entete()
-
- # Rubrique OPTIONS
- self.texteCuve += self.rubrique('OPTIONS')
-
- self.texteCuve += self.sousRubrique('Impression a l ecran', '')
- if self.dico_mot.has_key('NiveauImpression'):
- self.texteCuve += self.affecteValeur('NiveauImpression', self.valeurproposee[str(self.dico_mot["NiveauImpression"])])
-
- self.texteCuve += self.sousRubrique('Generation de fichiers', '')
- self.texteCuve += self.ecritVariable('FichierDataIn')
- self.texteCuve += self.ecritVariable('FichierTempSigma')
- self.texteCuve += self.ecritVariable('FichierCSV')
- self.texteCuve += self.ecritVariable('FichierRESTART')
- self.texteCuve += self.ecritVariable('FichierEXTR')
- self.texteCuve += self.ecritVariable('ChoixPlugin')
-
- self.texteCuve += self.sousRubrique('Grandeur evaluee', '')
- if self.dico_mot.has_key('GrandeurEvaluee'):
- self.texteCuve += self.affecteValeur('GrandeurEvaluee', self.valeurproposee[str(self.dico_mot["GrandeurEvaluee"])])
-
- self.texteCuve += self.sousRubrique('Divers', '')
- self.texteCuve += self.ecritVariable('IncrementTemporel')
- self.texteCuve += self.ecritVariable('IncrementMaxTemperature')
-
- #self.texteCuve += self.ecritVariable('ChoixExtractionTransitoires')
- if self.dico_mot.has_key('ChoixExtractionTransitoires'):
- self.texteCuve += self.ecritVariable('ChoixExtractionTransitoires')
- if str(self.dico_mot["ChoixExtractionTransitoires"])=='OUI':
- if self.dico_mot.has_key('ListeAbscisses'):
- self.texteCuve += "# liste des abscisses pour ecriture des transitoires de T et SIG (5 ou moins)"+"\n"
- self.imprime(1,(self.dico_mot["ListeAbscisses"]))
- self.texteCuve+="#"+"\n"
- else :
- print "Warning ==> Dans la rubrique OPTIONS, fournir ListeAbscisses."
- self.texteCuve += "# liste des abscisses pour ecriture des transitoires de T et SIG (5 ou moins)"+"\n"
- self.texteCuve += " 1.994\n"
- self.texteCuve += " 2.000\n"
- self.texteCuve+="#"+"\n"
- else :
- self.texteCuve+="#"+"\n"
-
- self.texteCuve += self.ecritVariable('IncrementMaxTempsAffichage')
- if self.dico_mot.has_key('ListeInstants'):
- self.texteCuve += "# liste des instants pour ecriture des resultats (s)"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- self.imprime(1,(self.dico_mot["ListeInstants"]))
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- self.texteCuve+="#"+"\n"
- else :
- print "Warning ==> Dans la rubrique OPTIONS, fournir ListeInstants."
- self.texteCuve += "# liste des instants pour ecriture des resultats (s)"+"\n"
- self.texteCuve += " 0.\n"
- self.texteCuve += " 1.\n"
- self.texteCuve+="#"+"\n"
-
-
- # Rubrique DONNEES DE LA CUVE
- self.texteCuve += self.rubrique('DONNEES DE LA CUVE')
- if self.dico_mot.has_key('traitementGeometrie'):
- self.texteCuve += self.affecteValeur('traitementGeometrie', self.valeurproposee[str(self.dico_mot["traitementGeometrie"])])
- if str(self.dico_mot["traitementGeometrie"])=='Topologie':
- self.texteCuve+="# - si MAILLAGE, fournir NBNO et liste des abscisses (m)"+"\n"
- self.texteCuve+="# - si GEOMETRIE, fournir (RINT, RINT_MESSAGE),"+"\n"
- self.texteCuve+="# (REXT, REXT_MESSAGE),"+"\n"
- self.texteCuve+="# (LREV, LREV_MESSAGE),"+"\n"
- self.texteCuve+="# (LIGMIN, LIGMIN_MESSAGE),"+"\n"
- self.texteCuve+="# NBNO"+"\n"
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('RayonInterne')
- self.texteCuve += self.ecritVariable('RayonInterne_mess')
- self.texteCuve += self.ecritVariable('RayonExterne')
- self.texteCuve += self.ecritVariable('RayonExterne_mess')
- self.texteCuve += self.ecritVariable('EpaisseurRevetement')
- self.texteCuve += self.ecritVariable('EpaisseurRevetement_mess')
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('LigamentExterneMin')
- self.texteCuve += self.ecritVariable('LigamentExterneMin_mess')
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('NombreNoeudsMaillage')
- if str(self.dico_mot["traitementGeometrie"])=='Maillage':
- self.texteCuve+="# - si MAILLAGE, fournir NBNO et liste des abscisses (m)"+"\n"
- self.texteCuve+="# - si GEOMETRIE, fournir (RINT, RINT_MESSAGE),"+"\n"
- self.texteCuve+="# (REXT, REXT_MESSAGE),"+"\n"
- self.texteCuve+="# (LREV, LREV_MESSAGE),"+"\n"
- self.texteCuve+="# (LIGMIN, LIGMIN_MESSAGE),"+"\n"
- self.texteCuve+="# NBNO"+"\n"
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('NombreNoeudsMaillage')
- self.imprime(1,(self.dico_mot["ListeAbscisses"]))
- else :
- self.texteCuve += self.affecteValeurDefaut('traitementGeometrie')
- self.texteCuve+="# - si MAILLAGE, fournir NBNO et liste des abscisses (m)"+"\n"
- self.texteCuve+="# - si GEOMETRIE, fournir (RINT, RINT_MESSAGE),"+"\n"
- self.texteCuve+="# (REXT, REXT_MESSAGE),"+"\n"
- self.texteCuve+="# (LREV, LREV_MESSAGE),"+"\n"
- self.texteCuve+="# (LIGMIN, LIGMIN_MESSAGE),"+"\n"
- self.texteCuve+="# NBNO"+"\n"
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.affecteValeurDefaut('RayonInterne')
- self.texteCuve += self.affecteValeurDefaut('RayonInterne_mess')
- self.texteCuve += self.affecteValeurDefaut('RayonExterne')
- self.texteCuve += self.affecteValeurDefaut('RayonExterne_mess')
- self.texteCuve += self.affecteValeurDefaut('EpaisseurRevetement')
- self.texteCuve += self.affecteValeurDefaut('EpaisseurRevetement_mess')
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.affecteValeurDefaut('LigamentExterneMin')
- self.texteCuve += self.affecteValeurDefaut('LigamentExterneMin_mess')
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.affecteValeurDefaut('NombreNoeudsMaillage')
-
-
- # Rubrique CARACTERISTIQUES DU DEFAUT
- self.texteCuve += self.rubrique('CARACTERISTIQUES DU DEFAUT')
-
- if self.dico_mot.has_key('TypeInitial'):
- self.texteCuve += self.affecteValeur('TypeInitial', self.valeurproposee[str(self.dico_mot["TypeInitial"])])
- else :
- self.texteCuve += self.affecteValeurDefaut('TypeInitial')
-
- self.texteCuve+="# Fournir ORIEDEF, (PROFDEF, PROFDEF_MESSAGE)"+"\n"
- self.texteCuve+="# - Si DSR, fournir OPTLONG, (LONGDEF,LONGDEF_MESSAGE) ou (PROFSURLONG,PROFSURLONG_MESSAGE,LONGCONST)"+"\n"
- self.texteCuve+="# - Si DECALE, fournir OPTLONG, (LONGDEF,LONGDEF_MESSAGE) ou (PROFSURLONG,PROFSURLONG_MESSAGE,LONGCONST), DECATYP, (DECANOR,DECANOR_MESSAGE) ou (DECADEF,DECADEF_MESSAGE)"+"\n"
- self.texteCuve+="# - Si DEBOUCHANT, fournir IRWIN"+"\n"
- self.texteCuve+="# Fournir (ANGLDEF, ANGLDEF_MESSAGE), (ALTIDEF, ALTIDEF_MESSAGE)"+"\n"
- self.texteCuve+="# - Si DSR ou DECALE, fournir POINDEF"+"\n"
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Remarque :"+"\n"
- self.texteCuve+="# - si DSR ou DECALE, dans la rubrique 'Modele de tenacite', fournir ATTNCORRBETA (ne pas fournir CORRIRWIN)"+"\n"
- self.texteCuve+="# - si DEBOUCHANT, dans la rubrique 'Modele de tenacite', fournir CORRIRWIN (ne pas fournir ATTNCORRBETA)"+"\n"
-
- self.texteCuve+="#"+"\n"
-
- if self.dico_mot.has_key('Orientation'):
- self.texteCuve += self.affecteValeur('Orientation', self.valeurproposee[str(self.dico_mot["Orientation"])])
- else :
- self.texteCuve += self.affecteValeurDefaut('Orientation')
-
- if self.dico_mot.has_key('Position'):
- self.texteCuve += self.affecteValeur('Position', self.valeurproposee[str(self.dico_mot["Position"])])
- else :
- self.texteCuve += self.affecteValeurDefaut('Position')
-
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('ProfondeurRadiale')
- self.texteCuve += self.ecritVariable('ProfondeurRadiale_mess')
-
- self.texteCuve+="#"+"\n"
- if self.dico_mot.has_key('TypeInitial'):
- if str(self.dico_mot["TypeInitial"])!='Defaut Debouchant':
- if self.dico_mot.has_key('ModeCalculLongueur'):
- self.texteCuve += self.affecteValeur('ModeCalculLongueur', self.valeurproposee[str(self.dico_mot["ModeCalculLongueur"])])
- if str(self.dico_mot["ModeCalculLongueur"])=='Valeur':
- self.texteCuve+="# - Si VALEUR, fournir (LONGDEF, LONGDEF_MESSAGE)"+"\n"
- self.texteCuve+="# - Si FCTAFFINE, fournir (PROFSURLONG, PROFSURLONG_MESSAGE) et LONGCONST : LONGDEF=PROFDEF/PROFSURLONG + LONGCONST"+"\n"
- self.texteCuve += self.ecritVariable('Longueur')
- self.texteCuve += self.ecritVariable('Longueur_mess')
- if str(self.dico_mot["ModeCalculLongueur"])=='Fonction affine de la profondeur':
- self.texteCuve+="# - Si VALEUR, fournir (LONGDEF, LONGDEF_MESSAGE)"+"\n"
- self.texteCuve+="# - Si FCTAFFINE, fournir (PROFSURLONG, PROFSURLONG_MESSAGE) et LONGCONST : LONGDEF=PROFDEF/PROFSURLONG + LONGCONST"+"\n"
- self.texteCuve += self.ecritVariable('CoefDirecteur')
- self.texteCuve += self.ecritVariable('CoefDirecteur_mess')
- self.texteCuve += self.ecritVariable('Constante')
- else :
- self.texteCuve += self.affecteValeurDefaut('ModeCalculLongueur')
- self.texteCuve+="# - Si VALEUR, fournir (LONGDEF, LONGDEF_MESSAGE)"+"\n"
- self.texteCuve+="# - Si FCTAFFINE, fournir (PROFSURLONG, PROFSURLONG_MESSAGE) et LONGCONST : LONGDEF=PROFDEF/PROFSURLONG + LONGCONST"+"\n"
- self.texteCuve += self.affecteValeurDefaut('Longueur')
- self.texteCuve += self.affecteValeurDefaut('Longueur_mess')
-
- if self.dico_mot.has_key('TypeInitial'):
- if str(self.dico_mot["TypeInitial"])=='Defaut Decale':
- self.texteCuve+="#"+"\n"
- if self.dico_mot.has_key('ModeCalculDecalage'):
- self.texteCuve += self.affecteValeur('ModeCalculDecalage', self.valeurproposee[str(self.dico_mot["ModeCalculDecalage"])])
- if str(self.dico_mot["ModeCalculDecalage"])=='Valeur normalisee':
- self.texteCuve+="# - Si NORMALISE, fournir (DECANOR, DECANOR_MESSAGE)"+"\n"
- self.texteCuve+="# - Si VALEUR, fournir (DECADEF, DECADEF_MESSAGE)"+"\n"
- self.texteCuve += self.ecritVariable('DecalageNormalise')
- self.texteCuve += self.ecritVariable('DecalageNormalise_mess')
- if str(self.dico_mot["ModeCalculDecalage"])=='Valeur':
- self.texteCuve+="# - Si NORMALISE, fournir (DECANOR, DECANOR_MESSAGE)"+"\n"
- self.texteCuve+="# - Si VALEUR, fournir (DECADEF, DECADEF_MESSAGE)"+"\n"
- self.texteCuve += self.ecritVariable('DecalageRadial')
- self.texteCuve += self.ecritVariable('DecalageRadial_mess')
- else :
- self.texteCuve += self.affecteValeurDefaut('ModeCalculDecalage')
- self.texteCuve+="# - Si NORMALISE, fournir (DECANOR, DECANOR_MESSAGE)"+"\n"
- self.texteCuve+="# - Si VALEUR, fournir (DECADEF, DECADEF_MESSAGE)"+"\n"
- self.texteCuve += self.affecteValeurDefaut('DecalageRadial')
- self.texteCuve += self.affecteValeurDefaut('DecalageRadial_mess')
-
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('Azimut')
- self.texteCuve += self.ecritVariable('Azimut_mess')
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('Altitude')
- self.texteCuve += self.ecritVariable('Altitude_mess')
- self.texteCuve+="#"+"\n"
- if self.dico_mot.has_key('Pointe'):
- self.texteCuve += self.affecteValeur('Pointe', self.valeurproposee[str(self.dico_mot["Pointe"])])
- #else :
- # self.texteCuve += self.affecteValeurDefaut('Pointe')
-
- # Rubrique MODELES FLUENCE, IRRADIATION, TENACITE
- self.texteCuve += self.rubrique('MODELES FLUENCE, IRRADIATION, TENACITE')
- self.texteCuve += self.sousRubrique('Modele d attenuation de la fluence dans l epaisseur','A.')
-
- if self.dico_mot.has_key('ModeleFluence'):
- self.texteCuve += self.affecteValeur('ModeleFluence', self.valeurproposee[str(self.dico_mot["ModeleFluence"])])
- else :
- self.texteCuve += self.affecteValeurDefaut('ModeleFluence')
-
- self.texteCuve+="# - si France, fournir KPFRANCE"+"\n"
- self.texteCuve+="# - si USNRC, fournir KPUS"+"\n"
- self.texteCuve+="# - si modele GD_Cuve, fournir COEFFLUENCE1, COEFFLUENCE2, ..., COEFFLUENCE9, COEFFLUENCE10"+"\n"
- self.texteCuve+="#"+"\n"
-
- self.texteCuve += self.ecritVariable('ZoneActiveCoeur_AltitudeSup')
- self.texteCuve += self.ecritVariable('ZoneActiveCoeur_AltitudeInf')
- self.texteCuve += self.ecritVariable('FluenceMax')
- if self.dico_mot.has_key('ModeleFluence'):
- if str(self.dico_mot["ModeleFluence"])=='Exponentiel sans revetement k=12.7 (France)':
- self.texteCuve += self.ecritVariable('KPFrance')
- if str(self.dico_mot["ModeleFluence"])=='Regulatory Guide 1.99 rev 2 (USNRC)':
- self.texteCuve += self.ecritVariable('KPUS')
- if str(self.dico_mot["ModeleFluence"])=='Grand developpement (GD_Cuve)':
- self.texteCuve += self.ecritVariable('Azimut_0deg')
- self.texteCuve += self.ecritVariable('Azimut_5deg')
- self.texteCuve += self.ecritVariable('Azimut_10deg')
- self.texteCuve += self.ecritVariable('Azimut_15deg')
- self.texteCuve += self.ecritVariable('Azimut_20deg')
- self.texteCuve += self.ecritVariable('Azimut_25deg')
- self.texteCuve += self.ecritVariable('Azimut_30deg')
- self.texteCuve += self.ecritVariable('Azimut_35deg')
- self.texteCuve += self.ecritVariable('Azimut_40deg')
- self.texteCuve += self.ecritVariable('Azimut_45deg')
-
- self.texteCuve += self.sousRubrique('Irradiation','B.')
-
- if self.dico_mot.has_key('TypeIrradiation'):
- self.texteCuve += self.affecteValeur('TypeIrradiation', self.valeurproposee[str(self.dico_mot["TypeIrradiation"])])
-
- if str(self.dico_mot["TypeIrradiation"])=='RTndt de la cuve a l instant de l analyse':
- self.texteCuve+="# - si RTNDT, fournir RTNDT"+"\n"
- self.texteCuve+="# - si FLUENCE, fournir MODELIRR, et autres parametres selon MODELIRR (voir ci-dessous)"+"\n"
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('RTNDT')
-
- if str(self.dico_mot["TypeIrradiation"])=='Modele d irradiation':
- self.texteCuve+="# - si RTNDT, fournir RTNDT"+"\n"
- self.texteCuve+="# - si FLUENCE, fournir MODELIRR, et autres parametres selon MODELIRR (voir ci-dessous)"+"\n"
- self.texteCuve+="#"+"\n"
- if self.dico_mot.has_key('ModeleIrradiation'):
- self.texteCuve += self.affecteValeur('ModeleIrradiation', self.valeurproposee[str(self.dico_mot["ModeleIrradiation"])])
- else :
- self.texteCuve += self.affecteValeurDefaut('ModeleIrradiation')
- self.texteCuve+="# - pour tout modele, fournir (CU, CU_MESSAGE),"+"\n"
- self.texteCuve+="# (NI, NI_MESSAGE),"+"\n"
- self.texteCuve+="# - si HOUSSIN, PERSOZ, LEFEBVRE, BRILLAUD, LEFEBnew, fournir (P, P_MESSAGE)"+"\n"
- self.texteCuve+="# - pour tout modele, fournir (RTimoy, RTimoy_MESSAGE),"+"\n"
- self.texteCuve+="# - si USNRCsoud ou USNRCmdb, fournir (RTicov, RTicov_MESSAGE)"+"\n"
- self.texteCuve+="# (USectDRT, USectDRT_MESSAGE)"+"\n"
- self.texteCuve+="# - pour tout modele, fournir (nbectDRTNDT, nbectDRTNDT_MESSAGE)"+"\n"
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('TeneurCuivre')
- self.texteCuve += self.ecritVariable('TeneurCuivre_mess')
- self.texteCuve += self.ecritVariable('TeneurNickel')
- self.texteCuve += self.ecritVariable('TeneurNickel_mess')
- if str(self.dico_mot["ModeleIrradiation"])=='Metal de Base : formule de FIM/FIS Houssin' or str(self.dico_mot["ModeleIrradiation"])=='Metal de Base : formule de FIM/FIS Persoz' or str(self.dico_mot["ModeleIrradiation"])=='Metal de Base : formule de FIM/FIS Lefebvre' or str(self.dico_mot["ModeleIrradiation"])=='Joint Soude : formulation de FIM/FIS Brillaud' or str(self.dico_mot["ModeleIrradiation"])=='Formule de FIM/FIS Lefebvre modifiee':
- self.texteCuve += self.ecritVariable('TeneurPhosphore')
- self.texteCuve += self.ecritVariable('TeneurPhosphore_mess')
- self.texteCuve += self.ecritVariable('MoyenneRTndt')
- self.texteCuve += self.ecritVariable('MoyenneRTndt_mess')
- if str(self.dico_mot["ModeleIrradiation"])=='Metal de Base : Regulatory Guide 1.00 rev 2' or str(self.dico_mot["ModeleIrradiation"])=='Joint Soude : Regulatory Guide 1.00 rev 2':
- self.texteCuve += self.ecritVariable('CoefVariationRTndt')
- self.texteCuve += self.ecritVariable('CoefVariationRTndt_mess')
- self.texteCuve += self.ecritVariable('EcartTypeRTndt')
- self.texteCuve += self.ecritVariable('EcartTypeRTndt_mess')
- self.texteCuve += self.ecritVariable('NombreEcartTypeRTndt')
- self.texteCuve += self.ecritVariable('NombreEcartTypeRTndt_mess')
- else :
- self.texteCuve += self.affecteValeurDefaut('TypeIrradiation')
- self.texteCuve+="# - si RTNDT, fournir RTNDT"+"\n"
- self.texteCuve+="# - si FLUENCE, fournir MODELIRR, et autres parametres selon MODELIRR (voir ci-dessous)"+"\n"
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.affecteValeurDefaut('RTNDT')
-
- self.texteCuve += self.sousRubrique('Modele de tenacite','C.')
- self.texteCuve+="# tenacite d amorcage"+"\n"
-
- if self.dico_mot.has_key('ModeleTenacite'):
- self.texteCuve += self.affecteValeur('ModeleTenacite', self.valeurproposee[str(self.dico_mot["ModeleTenacite"])])
- else :
- self.texteCuve += self.affecteValeurDefaut('ModeleTenacite')
- self.texteCuve+="# - si RCC-M, RCC-M_pal, Houssin_RC, fournir (nbectKIc, nbectKIc_MESSAGE), KICPAL, KICCDV"+"\n"
- self.texteCuve+="# - si RCC-M_exp, fournir (nbectKIc, nbectKIc_MESSAGE), KICCDV"+"\n"
- self.texteCuve+="# - si RCC-M_simpl, ne rien fournir"+"\n"
- self.texteCuve+="# - si Frama, LOGWOLF, fournir (nbectKIc, nbectKIc_MESSAGE)"+"\n"
- self.texteCuve+="# - si REME, ORNL, WEIB3, WEIB2, fournir NBCARAC, puis (nbectKIc, nbectKIc_MESSAGE) ou (fractKIc, fractKIc_MESSAGE) selon valeur de NBCARAC"+"\n"
- self.texteCuve+="# - si Wallin, fournir NBCARAC, puis (nbectKIc, nbectKIc_MESSAGE) ou (fractKIc, fractKIc_MESSAGE) selon valeur de NBCARAC,"+"\n"
- self.texteCuve+="# puis T0WALLIN"+"\n"
- self.texteCuve+="# - si WEIB-GEN, fournir NBCARAC, puis (nbectKIc, nbectKIc_MESSAGE) ou (fractKIc, fractKIc_MESSAGE) selon valeur de NBCARAC,"+"\n"
- self.texteCuve+="# puis A1, A2, A3, B1, B2, B3, C1, C2, C3"+"\n"
- self.texteCuve+="# loi de Weibull P(K<x) = 1 - exp{-[ (x-a(T)) / b(T) ]^c(T) }"+"\n"
- self.texteCuve+="# avec a(T) = A1 + A2*exp[A3*(T-RTNDT)]"+"\n"
- self.texteCuve+="# b(T) = B1 + B2*exp[B3*(T-RTNDT)]"+"\n"
- self.texteCuve+="# c(T) = C1 + C2*exp[C3*(T-RTNDT)]"+"\n"
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Correction de la longueur"+"\n"
- self.texteCuve += self.ecritVariable('ChoixCorrectionLongueur')
- self.texteCuve+="#"+"\n"
- if self.dico_mot.has_key('ModeleTenacite'):
- if str(self.dico_mot["ModeleTenacite"])=='Weibull basee sur la master cuve' or str(self.dico_mot["ModeleTenacite"])=='Weibull basee sur la master cuve (REME)' or str(self.dico_mot["ModeleTenacite"])=='Weibull n\xb01 (etude ORNL)' or str(self.dico_mot["ModeleTenacite"])=='Weibull n\xb03' or str(self.dico_mot["ModeleTenacite"])=='Weibull n\xb02' or str(self.dico_mot["ModeleTenacite"])=='Weibull generalisee' :
- if self.dico_mot.has_key('NombreCaracteristique'):
- self.texteCuve += self.affecteValeur('NombreCaracteristique', self.valeurproposee[str(self.dico_mot["NombreCaracteristique"])])
- else :
- self.texteCuve += self.affecteValeurDefaut('NombreCaracteristique')
- self.texteCuve+="# - Si NBCARAC = QUANTILE, fournir (nbectKIc, nbectKIc_MESSAGE)"+"\n"
- self.texteCuve+="# - Si NBCARAC = ORDRE, fournir (fractKIc, fractKIc_MESSAGE)"+"\n"
-
- if str(self.dico_mot["ModeleTenacite"])=='RCC-M/ASME coefficient=2' or str(self.dico_mot["ModeleTenacite"])=='RCC-M/ASME avec KI=KIpalier' or str(self.dico_mot["ModeleTenacite"])=='RCC-M/ASME coefficient=2.33 (Houssin)' :
- self.texteCuve += self.ecritVariable('NbEcartType_MoyKIc')
- self.texteCuve += self.ecritVariable('NbEcartType_MoyKIc_mess')
- self.texteCuve += self.ecritVariable('PalierDuctile_KIc')
- self.texteCuve += self.ecritVariable('CoefficientVariation_KIc')
-
- if str(self.dico_mot["ModeleTenacite"])=='Exponentielle n\xb01 (Frama)' or str(self.dico_mot["ModeleTenacite"])=='Exponentielle n\xb02 (LOGWOLF)' :
- self.texteCuve += self.ecritVariable('NbEcartType_MoyKIc')
- self.texteCuve += self.ecritVariable('NbEcartType_MoyKIc_mess')
-
- if str(self.dico_mot["ModeleTenacite"])=='Weibull basee sur la master cuve (REME)' or str(self.dico_mot["ModeleTenacite"])=='Weibull n\xb01 (etude ORNL)' or str(self.dico_mot["ModeleTenacite"])=='Weibull n\xb03' or str(self.dico_mot["ModeleTenacite"])=='Weibull n\xb02' or str(self.dico_mot["ModeleTenacite"])=='Weibull basee sur la master cuve' or str(self.dico_mot["ModeleTenacite"])=='Weibull generalisee':
- if str(self.dico_mot["NombreCaracteristique"])=='Quantile' :
- self.texteCuve += self.ecritVariable('NbEcartType_MoyKIc')
- self.texteCuve += self.ecritVariable('NbEcartType_MoyKIc_mess')
- if str(self.dico_mot["NombreCaracteristique"])=='Ordre' :
- self.texteCuve += self.ecritVariable('Fractile_KIc')
- self.texteCuve += self.ecritVariable('Fractile_KIc_mess')
-
- if str(self.dico_mot["ModeleTenacite"])=='Weibull basee sur la master cuve' :
- self.texteCuve += self.ecritVariable('Temperature_KIc100')
-
- if str(self.dico_mot["ModeleTenacite"])=='Weibull generalisee' :
- self.texteCuve += self.ecritVariable('A1')
- self.texteCuve += self.ecritVariable('A2')
- self.texteCuve += self.ecritVariable('A3')
- self.texteCuve += self.ecritVariable('B1')
- self.texteCuve += self.ecritVariable('B2')
- self.texteCuve += self.ecritVariable('B3')
- self.texteCuve += self.ecritVariable('C1')
- self.texteCuve += self.ecritVariable('C2')
- self.texteCuve += self.ecritVariable('C3')
- else :
- self.texteCuve += self.affecteValeurDefaut('NbEcartType_MoyKIc')
- self.texteCuve += self.affecteValeurDefaut('NbEcartType_MoyKIc_mess')
- self.texteCuve += self.affecteValeurDefaut('PalierDuctile_KIc')
- self.texteCuve += self.affecteValeurDefaut('CoefficientVariation_KIc')
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Correction plastique"+"\n"
-
- #DTV if self.dico_mot.has_key('TypeInitial'):
- #DTV if str(self.dico_mot["TypeInitial"])!='Defaut Debouchant':
- if self.dico_mot.has_key('CorrectionPlastique'):
- if str(self.dico_mot["CorrectionPlastique"])=='Correction plastique BETA (pour DSR et defaut decale)':
- self.texteCuve += self.affecteValeur('AttnCorrBeta','NON')
- if str(self.dico_mot["CorrectionPlastique"])=='Correction plastique BETA attenuee (pour DSR et defaut decale)':
- self.texteCuve += self.affecteValeur('AttnCorrBeta','OUI')
- if str(self.dico_mot["CorrectionPlastique"])=='Correction plastique IRWIN (pour defaut debouchant)':
- self.texteCuve += self.affecteValeur('CorrIrwin','OUI')
- else :
- self.texteCuve += self.affecteValeurDefaut('AttnCorrBeta')
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Prise en compte de l'arret de fissure si DETERMINISTE"+"\n"
-
- self.texteCuve += self.ecritVariable('ArretDeFissure')
- self.texteCuve+="# - si ARRETFISSURE=OUI, fournir (INCRDEF, INCRDEF_MESSAGE), nbectKIa, KIAPAL, KIACDV"+"\n"
- if self.dico_mot.has_key('ArretDeFissure'):
- if str(self.dico_mot["ArretDeFissure"])=='OUI':
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('IncrementTailleFissure')
- self.texteCuve += self.ecritVariable('IncrementTailleFissure_mess')
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Parametres pour le calcul de la tenacite a l arret"+"\n"
- self.texteCuve += self.ecritVariable('NbEcartType_MoyKIa')
- self.texteCuve += self.ecritVariable('PalierDuctile_KIa')
- self.texteCuve += self.ecritVariable('CoefficientVariation_KIa')
-
- # Rubrique Etat initial
- self.texteCuve += self.rubrique('ETAT INITIAL')
-
- self.texteCuve+="# Profil radial de la temperature initiale dans la cuve"+"\n"
- self.texteCuve+="# abscisse (m) / temp initiale dans la cuve"+"\n"
- self.texteCuve+="# Prolongation aux frontieres amont et aval: C = constant / E = exclu / L = lineaire"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- if self.dico_mot.has_key('ProfilRadial_TemperatureInitiale'):
- self.imprime(2,(self.dico_mot["ProfilRadial_TemperatureInitiale"]))
- self.texteCuve += self.amontAval('Amont_TemperatureInitiale','Aval_TemperatureInitiale')
- else :
- self.texteCuve+=" 1.9940 287."+"\n"
- self.texteCuve+="CC"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Profils radiaux des contraintes residuelles dans la cuve"+"\n"
- self.texteCuve+="# abscisse (m) / sigma rr / sigma tt / sigma zz"+"\n"
- self.texteCuve+="# Prolongation aux frontieres amont et aval: C = constant / E = exclu / L = lineaire"+"\n"
- if self.dico_mot.has_key('ProfilRadial_ContraintesInitiales'):
- self.imprime(4,(self.dico_mot["ProfilRadial_ContraintesInitiales"]))
- self.texteCuve += self.amontAval('Amont_ContraintesInitiales','Aval_ContraintesInitiales')
- else :
- self.texteCuve+="1.994 0. 0. 0."+"\n"
- self.texteCuve+="CC"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Prise en compte de coefficients sur les contraintes"+"\n"
- self.texteCuve += self.ecritVariable('ChoixCoefficientChargement')
- if str(self.dico_mot["ChoixCoefficientChargement"])=='OUI':
- self.texteCuve += self.ecritVariable('CoefficientDuctile')
- self.texteCuve += self.ecritVariable('CoefficientFragile')
- else :
- self.texteCuve+="#"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Instant initial"+"\n"
- self.texteCuve += self.ecritVariable('InstantInitialisation')
-
- # Rubrique CARACTERISTIQUES DU REVETEMENT
- self.texteCuve += self.rubrique('CARACTERISTIQUES DU REVETEMENT')
-
- if self.dico_mot.has_key('ConditionLimiteThermiqueREV'):
- self.texteCuve += self.affecteValeur('ConditionLimiteThermiqueREV', self.valeurproposee[str(self.dico_mot["ConditionLimiteThermiqueREV"])])
- else :
- self.texteCuve += self.affecteValeurDefaut('ConditionLimiteThermiqueREV')
- self.texteCuve+="# - si CHALEUR, fournir Temperature (degC) / chaleur volumique (J/kg/K)"+"\n"
- self.texteCuve+="# - si ENTHALPIE, fournir Temperature (degC) / enthalpie (J/kg)"+"\n"
- self.texteCuve+="# Finir chacune des listes par la prolongation aux frontieres amont et aval: C = constant / E = exclu / L = lineaire"+"\n"
- self.texteCuve+="#"+"\n"
- if self.dico_mot.has_key('ChaleurREV_Fct_Temperature'):
- self.texteCuve+="# Temperature (degC) / chaleur volumique (J/kg/K)"+"\n"
- self.imprime(2,(self.dico_mot["ChaleurREV_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Amont_ChaleurREV','Aval_ChaleurREV')
- elif self.dico_mot.has_key('EnthalpieREV_Fct_Temperature'):
- self.texteCuve+="# Temperature (degC) / enthalpie (J/kg)"+"\n"
- self.imprime(2,(self.dico_mot["EnthalpieREV_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Amont_EnthalpieREV','Aval_EnthalpieREV')
- else :
- self.texteCuve+="# Temperature (degC) / chaleur volumique (J/kg/K)"+"\n"
- self.texteCuve+="0. 36.03E5 "+"\n"
- self.texteCuve+="20. 36.03E5 "+"\n"
- self.texteCuve+="200. 41.65E5 "+"\n"
- self.texteCuve+="350. 43.47E5 "+"\n"
- self.texteCuve+="CC"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Temperature (degC) / conductivite thermique (W/m/degC)"+"\n"
- if self.dico_mot.has_key('ConductiviteREV_Fct_Temperature'):
- self.imprime(2,(self.dico_mot["ConductiviteREV_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Amont_ConductiviteREV','Aval_ConductiviteREV')
- else :
- self.texteCuve+="0. 14.7 "+"\n"
- self.texteCuve+="20. 14.7 "+"\n"
- self.texteCuve+="200. 17.2 "+"\n"
- self.texteCuve+="350. 19.3 "+"\n"
- self.texteCuve+="CC"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Temperature (degC) / module d'Young (MPa)"+"\n"
- if self.dico_mot.has_key('ModuleYoungREV_Fct_Temperature'):
- self.imprime(2,(self.dico_mot["ModuleYoungREV_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Amont_ModuleYoungREV','Aval_ModuleYoungREV')
- else :
- self.texteCuve+="0. 198500. "+"\n"
- self.texteCuve+="20. 197000. "+"\n"
- self.texteCuve+="200. 184000. "+"\n"
- self.texteCuve+="350. 172000. "+"\n"
- self.texteCuve+="CC"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Temperature (degC) / coefficient de dilatation thermique (degC-1)"+"\n"
- if self.dico_mot.has_key('CoeffDilatThermREV_Fct_Temperature'):
- self.imprime(2,(self.dico_mot["CoeffDilatThermREV_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Amont_CoeffDilatThermREV','Aval_CoeffDilatThermREV')
- else :
- self.texteCuve+="0. 16.40E-6 "+"\n"
- self.texteCuve+="20. 16.40E-6 "+"\n"
- self.texteCuve+="200. 17.20E-6 "+"\n"
- self.texteCuve+="350. 17.77E-6 "+"\n"
- self.texteCuve+="CC"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Temperature (degC) / limite d'elasticite (MPa)"+"\n"
- if self.dico_mot.has_key('LimiteElasticiteREV_Fct_Temperature'):
- self.imprime(2,(self.dico_mot["LimiteElasticiteREV_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Amont_LimiteElasticiteREV','Aval_LimiteElasticiteREV')
- else :
- self.texteCuve+="0. 380. "+"\n"
- self.texteCuve+="20. 370. "+"\n"
- self.texteCuve+="100. 330. "+"\n"
- self.texteCuve+="300. 270. "+"\n"
- self.texteCuve+="LL"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('TemperatureDeformationNulleREV')
- self.texteCuve += self.ecritVariable('TemperaturePourCoefDilatThermREV')
- self.texteCuve += self.ecritVariable('CoefficientPoissonREV')
-
- # Rubrique CARACTERISTIQUES DU METAL DE BASE
- self.texteCuve += self.rubrique('CARACTERISTIQUES DU METAL DE BASE')
-
- if self.dico_mot.has_key('ConditionLimiteThermiqueMDB'):
- self.texteCuve += self.affecteValeur('ConditionLimiteThermiqueMDB', self.valeurproposee[str(self.dico_mot["ConditionLimiteThermiqueMDB"])])
- else :
- self.texteCuve += self.affecteValeurDefaut('ConditionLimiteThermiqueMDB')
-
- self.texteCuve+="# - si CHALEUR, fournir Temperature (degC) / chaleur volumique (J/kg/K)"+"\n"
- self.texteCuve+="# - si ENTHALPIE, fournir Temperature (degC) / enthalpie (J/kg)"+"\n"
- self.texteCuve+="# Finir chacune des listes par la prolongation aux frontieres amont et aval: C = constant / E = exclu / L = lineaire"+"\n"
- self.texteCuve+="#"+"\n"
-
- if self.dico_mot.has_key('ChaleurMDB_Fct_Temperature'):
- self.texteCuve+="# Temperature (degC) / chaleur volumique (J/kg/K)"+"\n"
- self.imprime(2,(self.dico_mot["ChaleurMDB_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Amont_ChaleurMDB','Aval_ChaleurMDB')
- elif self.dico_mot.has_key('EnthalpieMDB_Fct_Temperature'):
- self.texteCuve+="# Temperature (degC) / enthalpie (J/kg)"+"\n"
- self.imprime(2,(self.dico_mot["EnthalpieMDB_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Amont_EnthalpieMDB','Aval_EnthalpieMDB')
- else :
- self.texteCuve+="# Temperature (degC) / chaleur volumique (J/kg/K)"+"\n"
- self.texteCuve+="0. 34.88E+05 "+"\n"
- self.texteCuve+="20. 34.88E+05 "+"\n"
- self.texteCuve+="200. 40.87E+05 "+"\n"
- self.texteCuve+="350. 46.02E+05 "+"\n"
- self.texteCuve+="CC"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Temperature (degC) / conductivite thermique (W/m/degC)"+"\n"
- if self.dico_mot.has_key('ConductiviteMDB_Fct_Temperature'):
- self.imprime(2,(self.dico_mot["ConductiviteMDB_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Amont_ConductiviteMDB','Aval_ConductiviteMDB')
- else :
- self.texteCuve+="0. 37.7 "+"\n"
- self.texteCuve+="20. 37.7 "+"\n"
- self.texteCuve+="200. 40.5 "+"\n"
- self.texteCuve+="350. 38.7 "+"\n"
- self.texteCuve+="CC"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Temperature (degC) / module d'Young (MPa)"+"\n"
- if self.dico_mot.has_key('ModuleYoungMDB_Fct_Temperature'):
- self.imprime(2,(self.dico_mot["ModuleYoungMDB_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Aval_ModuleYoungMDB','Aval_ModuleYoungMDB')
- else :
- self.texteCuve+="0. 205000. "+"\n"
- self.texteCuve+="20. 204000. "+"\n"
- self.texteCuve+="200. 193000. "+"\n"
- self.texteCuve+="350. 180000. "+"\n"
- self.texteCuve+="CC"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Temperature (degC) / coefficient de dilatation thermique (degC-1)"+"\n"
- if self.dico_mot.has_key('CoeffDilatThermMDB_Fct_Temperature'):
- self.imprime(2,(self.dico_mot["CoeffDilatThermMDB_Fct_Temperature"]))
- self.texteCuve += self.amontAval('Amont_CoeffDilatThermMDB','Aval_CoeffDilatThermMDB')
- else :
- self.texteCuve+="0. 11.22E-6 "+"\n"
- self.texteCuve+="20. 11.22E-6 "+"\n"
- self.texteCuve+="200. 12.47E-6 "+"\n"
- self.texteCuve+="350. 13.08E-6 "+"\n"
- self.texteCuve+="CC"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('TemperatureDeformationNulleMDB')
- self.texteCuve += self.ecritVariable('TemperaturePourCoefDilatThermMDB')
- self.texteCuve += self.ecritVariable('CoefficientPoissonMDB')
-
- # Rubrique CARACTERISTIQUES DU TRANSITOIRE MECANIQUE-THERMOHYDRAULIQUE
- self.texteCuve += self.rubrique('CARACTERISTIQUES DU TRANSITOIRE MECANIQUE-THERMOHYDRAULIQUE')
- self.texteCuve += self.sousRubrique('Chargement mecanique : transitoire de pression','')
-
- self.texteCuve+="# instant (s) / pression (MPa)"+"\n"
- self.texteCuve+="# Prolongation aux frontieres amont et aval: C = constant / E = exclu / L = lineaire"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- if self.dico_mot.has_key('ProfilTemporel_Pression'):
- self.imprime(2,(self.dico_mot["ProfilTemporel_Pression"]))
- self.texteCuve += self.amontAval('Amont_Pression','Aval_Pression')
- else :
- self.texteCuve+="0. 15.5 "+"\n"
- self.texteCuve+="20. 0.1 "+"\n"
- self.texteCuve+="200. 0.1 "+"\n"
- self.texteCuve+="1000. 0.1 "+"\n"
- self.texteCuve+="CC"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
-
- self.texteCuve += self.sousRubrique('Chargement thermo-hydraulique','')
- if self.dico_mot.has_key('TypeConditionLimiteThermique'):
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- self.texteCuve += self.affecteValeur('TypeConditionLimiteThermique', self.valeurproposee[str(self.dico_mot["TypeConditionLimiteThermique"])])
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- else :
- self.texteCuve += self.affecteValeurDefaut('TypeConditionLimiteThermique')
-
- self.texteCuve+="# - si TEMP_IMPO, fournir Instant (s) / Temperature imposee (degC)"+"\n"
- self.texteCuve+="# - si FLUX_REP, fournir Instant (s) / Flux de chaleur impose (W/m2)"+"\n"
- self.texteCuve+="# - si ECHANGE, fournir Instant (s) / Temperature impose (degC)"+"\n"
- self.texteCuve+="# puis Instant (s) / Coefficient d echange (W/m2/K)"+"\n"
- self.texteCuve+="# - si DEBIT, fournir Instant (s) / Debit massique (kg/s)"+"\n"
- self.texteCuve+="# puis Instant (s) / Temperature d injection de securite (degC)"+"\n"
- self.texteCuve+="# puis Modele VESTALE : (DH, DH_MESSAGE), (SECTION, SECTION_MESSAGE), (DELTA, DELTA_MESSAGE), EPS, COEFVESTALE"+"\n"
- self.texteCuve+="# puis Modele CREARE : "+"\n"
- self.texteCuve+="# Instants(s) / Volume de melange CREARE (m3)"+"\n"
- self.texteCuve+="# puis (T0, T0_MESSAGE), (SE, SE_MESSAGE)"+"\n"
- self.texteCuve+="# - si TEMP_FLU, fournir Instant (s) / Temperature du fluide (degC)"+"\n"
- self.texteCuve+="# puis Instant (s) / Debit d injection de securite (kg/s)"+"\n"
- self.texteCuve+="# puis Modele VESTALE : (DH, DH_MESSAGE), (SECTION, SECTION_MESSAGE), (DELTA, DELTA_MESSAGE), EPS, COEFVESTALE"+"\n"
- self.texteCuve+="# - si TFDEBIT, fournir INST_PCN et TIS"+"\n"
- self.texteCuve+="# fournir Instant (s) / Temperature du fluide (degC)"+"\n"
- self.texteCuve+="# puis Instant (s) / Debit d injection de securite (kg/s)"+"\n"
- self.texteCuve+="# puis Modele VESTALE : (DH, DH_MESSAGE), (SECTION, SECTION_MESSAGE), (DELTA, DELTA_MESSAGE), EPS, COEFVESTALE"+"\n"
- self.texteCuve+="# puis Modele CREARE : "+"\n"
- self.texteCuve+="# Instants(s) / Volume de melange CREARE (m3)"+"\n"
- self.texteCuve+="# puis (T0, T0_MESSAGE), (SE, SE_MESSAGE)"+"\n"
- self.texteCuve+="# - si APRP, fournir INSTANT1, INSTANT2, INSTANT3, QACCU, QIS, (TIS, TIS_MESSAGE)"+"\n"
- self.texteCuve+="# puis Instant (s) / Temperature du fluide (degC) tel que dans l'exemple ci-dessous"+"\n"
- self.texteCuve+="# 0. 286."+"\n"
- self.texteCuve+="# 12. 20. # 1er palier à T=TACCU"+"\n"
- self.texteCuve+="# 20. 20. # idem que ci-dessus : T=TACCU"+"\n"
- self.texteCuve+="# 21. 999999. # 2nd palier à T=T1 : sera remplace par nouvelle valeur calculee par fonction idoine"+"\n"
- self.texteCuve+="# 45. 999999. # idem que ci-dessus : T=T1"+"\n"
- self.texteCuve+="# 46. 9. # 3eme palier à T=TIS, temperature d injection de securite : sa valeur est reactualisee avec la donnee de TIS ci-dessous"+"\n"
- self.texteCuve+="# 1870. 9. # idem que ci-dessus : T=TIS"+"\n"
- self.texteCuve+="# 1871. 80."+"\n"
- self.texteCuve+="# 3871. 80."+"\n"
- self.texteCuve+="# CC # C pour Constant, E pour Exclu, L pour Lineaire"+"\n"
- self.texteCuve+="# puis Instant (s) / Debit d injection de securite (kg/s)"+"\n"
- self.texteCuve+="# puis Modele VESTALE : (DH, DH_MESSAGE), (SECTION, SECTION_MESSAGE), (DELTA, DELTA_MESSAGE), EPS, COEFVESTALE"+"\n"
- self.texteCuve+="# Finir chacune des listes par la prolongation aux frontieres amont et aval: C = constant / E = exclu / L = lineaire"+"\n"
- self.texteCuve+="#"+"\n"
-
- if self.dico_mot.has_key('TypeConditionLimiteThermique'):
-
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#"+"\n"
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- self.texteCuve += self.ecritVariable('InstantPerteCirculationNaturelle')
- self.texteCuve += self.ecritVariable('TempInjectionSecurite')
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
-
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Courbe APRP':
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Definition de parametres pour le cas d un transitoire APRP"+"\n"
- self.texteCuve += self.ecritVariable('Instant_1')
- self.texteCuve += self.ecritVariable('Instant_2')
- self.texteCuve += self.ecritVariable('Instant_3')
- self.texteCuve += self.ecritVariable('DebitAccumule')
- self.texteCuve += self.ecritVariable('DebitInjectionSecurite')
- self.texteCuve += self.ecritVariable('TempInjectionSecurite')
- self.texteCuve += self.ecritVariable('TempInjectionSecurite_mess')
-
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Temperature imposee en paroi' or str(self.dico_mot["TypeConditionLimiteThermique"])=='Temperature imposee du fluide et coefficient echange' or str(self.dico_mot["TypeConditionLimiteThermique"])=='Temperature imposee du fluide et debit d injection de securite' or str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT' or str(self.dico_mot["TypeConditionLimiteThermique"])=='Courbe APRP' :
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# instant (s) / temperature imposee du fluide (degC)"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- if self.dico_mot.has_key('ProfilTemporel_TemperatureImposeeFluide'):
- self.imprime(2,(self.dico_mot["ProfilTemporel_TemperatureImposeeFluide"]))
- self.texteCuve += self.amontAval('Amont_TemperatureImposeeFluide','Aval_TemperatureImposeeFluide')
- else :
- self.texteCuve+="0. 286. "+"\n"
- self.texteCuve+="20. 20. "+"\n"
- self.texteCuve+="200. 7. "+"\n"
- self.texteCuve+="1000. 80. "+"\n"
- self.texteCuve+="CC"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
-
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Flux de chaleur impose en paroi':
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# instant (s) / flux de chaleur impose (W/m2)"+"\n"
- if self.dico_mot.has_key('ProfilTemporel_FluxChaleur'):
- self.imprime(2,(self.dico_mot["ProfilTemporel_FluxChaleur"]))
- self.texteCuve += self.amontAval('Amont_FluxChaleur','Aval_FluxChaleur')
- self.texteCuve+="#"+"\n"
- else :
- self.texteCuve+="0. -0. "+"\n"
- self.texteCuve+="20. -366290. "+"\n"
- self.texteCuve+="200. -121076. "+"\n"
- self.texteCuve+="1000. -56372."+"\n"
- self.texteCuve+="CC"+"\n"
-
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Temperature imposee du fluide et debit d injection de securite' or str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT' or str(self.dico_mot["TypeConditionLimiteThermique"])=='Courbe APRP':
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# instant (s) / Debit d injection de securite (kg/s)"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- if self.dico_mot.has_key('ProfilTemporel_DebitInjection'):
- self.imprime(2,(self.dico_mot["ProfilTemporel_DebitInjection"]))
- self.texteCuve += self.amontAval('Amont_DebitInjection','Aval_DebitInjection')
- else :
- self.texteCuve+="0. 4590. "+"\n"
- self.texteCuve+="20. 4590. "+"\n"
- self.texteCuve+="200. 340. "+"\n"
- self.texteCuve+="1000. 31.1 "+"\n"
- self.texteCuve+="CC"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
-
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Temperature imposee du fluide et coefficient echange' :
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# instant (s) / Coefficient d echange (W/m2/K)"+"\n"
- if self.dico_mot.has_key('ProfilTemporel_CoefficientEchange'):
- self.imprime(2,(self.dico_mot["ProfilTemporel_CoefficientEchange"]))
- self.texteCuve += self.amontAval('Amont_CoefficientEchange','Aval_CoefficientEchange')
- else :
- self.texteCuve+="0. 138454. "+"\n"
- self.texteCuve+="20. 19972. "+"\n"
- self.texteCuve+="200. 2668. "+"\n"
- self.texteCuve+="1000. 2668. "+"\n"
- self.texteCuve+="CC"+"\n"
-
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Debit massique et temperature d injection de securite' :
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# instant (s) / Debit massique (kg/s)"+"\n"
- if self.dico_mot.has_key('ProfilTemporel_DebitMassique'):
- self.imprime(2,(self.dico_mot["ProfilTemporel_DebitMassique"]))
- self.texteCuve += self.amontAval('Amont_DebitMassique','Aval_DebitMassique')
- else :
- self.texteCuve+="0. 18.4 "+"\n"
- self.texteCuve+="20. 18.4 "+"\n"
- self.texteCuve+="200. 31.1 "+"\n"
- self.texteCuve+="1000. 31.1 "+"\n"
- self.texteCuve+="CC"+"\n"
-
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# instant (s) / Temperature d injection de securite (degC)"+"\n"
- if self.dico_mot.has_key('ProfilTemporel_TemperatureInjection'):
- self.imprime(2,(self.dico_mot["ProfilTemporel_TemperatureInjection"]))
- self.texteCuve += self.amontAval('Amont_TemperatureInjection','Aval_TemperatureInjection')
- else :
- self.texteCuve+="0. 7.0 "+"\n"
- self.texteCuve+="20. 7.0 "+"\n"
- self.texteCuve+="200. 7.0 "+"\n"
- self.texteCuve+="1000. 7.0 "+"\n"
- self.texteCuve+="CC"+"\n"
-
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Debit massique et temperature d injection de securite' or str(self.dico_mot["TypeConditionLimiteThermique"])=='Temperature imposee du fluide et debit d injection de securite' or str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT' or str(self.dico_mot["TypeConditionLimiteThermique"])=='Courbe APRP' :
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Transitoire des coefficients d echange : modele VESTALE"+"\n"
- self.texteCuve+="#"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- self.texteCuve += self.ecritVariable('DiametreHydraulique')
- self.texteCuve += self.ecritVariable('DiametreHydraulique_mess')
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('SectionEspaceAnnulaire')
- self.texteCuve += self.ecritVariable('SectionEspaceAnnulaire_mess')
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('HauteurCaracConvectionNaturelle')
- self.texteCuve += self.ecritVariable('HauteurCaracConvectionNaturelle_mess')
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('CritereConvergenceRelative')
- self.texteCuve += self.ecritVariable('CoefficientsVestale')
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
-
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Debit massique et temperature d injection de securite' or str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT' :
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# Transitoire de temperature fluide locale : modele CREARE"+"\n"
- self.texteCuve+="#"+"\n"
- #self.texteCuve += self.ecritVariable('VolumeMelange_CREARE')
- self.texteCuve+="# instant (s) / Volume de melange CREARE (m3)"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- if self.dico_mot.has_key('ProfilTemporel_VolumeMelange_CREARE'):
- self.imprime(2,(self.dico_mot["ProfilTemporel_VolumeMelange_CREARE"]))
- self.texteCuve += self.amontAval('Amont_VolumeMelange_CREARE','Aval_VolumeMelange_CREARE')
- else :
- self.texteCuve+="0. 14.3 "+"\n"
- self.texteCuve+="20. 14.2 "+"\n"
- self.texteCuve+="CC"+"\n"
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- else :
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('TemperatureInitiale_CREARE')
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- self.texteCuve += self.ecritVariable('TemperatureInitiale_CREARE_mess')
- self.texteCuve+="#"+"\n"
- self.texteCuve += self.ecritVariable('SurfaceEchange_FluideStructure')
- self.texteCuve += self.ecritVariable('SurfaceEchange_FluideStructure_mess')
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT':
- self.texteCuve+="#BLOC_TFDEBIT"+"\n"
- else :
- self.texteCuve+="#"+"\n"
- self.texteCuve+="# instant (s) / temperature imposee du fluide (degC)"+"\n"
- self.texteCuve+="0. 286. "+"\n"
- self.texteCuve+="20. 20. "+"\n"
- self.texteCuve+="200. 7. "+"\n"
- self.texteCuve+="1000. 80. "+"\n"
- self.texteCuve+="CC"+"\n"
- self.texteCuve+="#"+"\n"
- self.texteCuve+="############################################################################################"+"\n"
-
-
- def genereTexteTFDEBIT(self):
-
- self.texteTFDEBIT = ""
-
- if self.dico_mot.has_key('TypeConditionLimiteThermique'):
- if str(self.dico_mot["TypeConditionLimiteThermique"])=='Calcul TEMPFLU puis DEBIT' :
- self.texteTFDEBIT+="# instant (s) / pression (MPa)"+"\n"
- self.texteTFDEBIT+=" "+"\n"
- self.imprime2(2,(self.dico_mot["ProfilTemporel_Pression"]))
- self.texteTFDEBIT += self.amontAval('Amont_Pression','Aval_Pression')
-
- # self.texteTFDEBIT+=" "+"\n"
- # self.texteTFDEBIT += self.affecteValeur('TypeConditionLimiteThermique', self.valeurproposee[str(self.dico_mot["TypeConditionLimiteThermique"])])
-
- self.texteTFDEBIT+=" "+"\n"
- self.imprime2(2,(self.dico_mot["ProfilTemporel_TemperatureImposeeFluide"]))
- self.texteTFDEBIT += self.amontAval('Amont_TemperatureImposeeFluide','Aval_TemperatureImposeeFluide')
-
- self.texteTFDEBIT+=" "+"\n"
- self.imprime2(2,(self.dico_mot["ProfilTemporel_DebitInjection"]))
- self.texteTFDEBIT += self.amontAval('Amont_DebitInjection','Aval_DebitInjection')
-
- self.texteTFDEBIT+=" "+"\n"
- self.texteTFDEBIT += self.ecritVariable('DiametreHydraulique')
- self.texteTFDEBIT += self.ecritVariable('DiametreHydraulique_mess')
- self.texteTFDEBIT+="#"+"\n"
- self.texteTFDEBIT += self.ecritVariable('SectionEspaceAnnulaire')
- self.texteTFDEBIT += self.ecritVariable('SectionEspaceAnnulaire_mess')
- self.texteTFDEBIT+="#"+"\n"
- self.texteTFDEBIT += self.ecritVariable('HauteurCaracConvectionNaturelle')
- self.texteTFDEBIT += self.ecritVariable('HauteurCaracConvectionNaturelle_mess')
- self.texteTFDEBIT+="#"+"\n"
- self.texteTFDEBIT += self.ecritVariable('CritereConvergenceRelative')
- self.texteTFDEBIT += self.ecritVariable('CoefficientsVestale')
-
- self.texteTFDEBIT+=" "+"\n"
- self.imprime2(2,(self.dico_mot["ProfilTemporel_VolumeMelange_CREARE"]))
- self.texteTFDEBIT += self.amontAval('Amont_VolumeMelange_CREARE','Aval_VolumeMelange_CREARE')
-
- self.texteTFDEBIT+=" "+"\n"
- self.texteTFDEBIT += self.ecritVariable('SurfaceEchange_FluideStructure')
- self.texteTFDEBIT += self.ecritVariable('SurfaceEchange_FluideStructure_mess')
- self.texteTFDEBIT += self.ecritVariable('InstantPerteCirculationNaturelle')
- self.texteTFDEBIT += self.ecritVariable('TempInjectionSecurite')
- else :
- self.texteTFDEBIT+="Fichier inutile"+"\n"
-
-
- def imprime(self,nbdeColonnes,valeur):
- self.liste=[]
- self.transforme(valeur)
- i=0
- while i < len(self.liste):
- for k in range(nbdeColonnes) :
- self.texteCuve+=str(self.liste[i+k]) +" "
- self.texteCuve+="\n"
- i=i+k+1
-
- def imprime2(self,nbdeColonnes,valeur):
- self.liste=[]
- self.transforme(valeur)
- i=0
- while i < len(self.liste):
- for k in range(nbdeColonnes) :
- self.texteTFDEBIT+=str(self.liste[i+k]) +" "
- self.texteTFDEBIT+="\n"
- i=i+k+1
-
-
- def transforme(self,valeur):
- for i in valeur :
- if type(i) == tuple :
- self.transforme(i)
- else :
- self.liste.append(i)
-
-
-
-
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2017 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-from __future__ import absolute_import
-try :
- from builtins import str
-except : pass
-import os
-
-from Extensions.i18n import tr
-from Extensions.eficas_exception import EficasException
-from .generator_python import PythonGenerator
-import six
-
-def entryPoint():
- """
- Return a dictionary containing the description needed to load the plugin
- """
- return {'name' : 'file_from_template',
- 'factory' : FileFromTemplateGenerator}
-
-
-class FileFromTemplateGenerator(PythonGenerator):
- """
- This generator creates an output file from a template (file with holes) in
- addition to Eficas .comm file. The parts to replace in the template must be
- in the form %KEYWORD%, where KEYWORD may be either the name of the Eficas
- element (short form, for instance MY_MCSIMP) or the "path" to the Eficas
- element (long form, for instance MYPROC.MYBLOC.MY_MCSIMP).
-
- To use this generator, the configuration of the code must implement two
- methods: get_extension() that must return the extension of the output file
- and get_template_file() that must return the path of the template file. Be
- sure also that your catalog is coherent with your template file.
- """
-
- def gener(self, obj, format = 'brut', config = None):
- self.config = config
- self.kw_dict = {}
- self.text = PythonGenerator.gener(self, obj, format)
- return self.text
-
- def generate_output_from_template(self) :
- """
- Generate the output text from the template file and the keywords
- """
- templateFileName = self.config.get_template_file()
- if not os.path.isfile(templateFileName):
- raise EficasException(tr("Fichier patron %s n'existe pas.",
- str( templateFileName)))
- f = open(templateFileName, "r")
- template = f.read()
- f.close()
- self.output_text = self.replace_keywords(template)
-
- def generMCSIMP(self, obj) :
- """
- Save object value in the keyword dict for further use, then generate
- the text corresponding to the MCSIMP element.
- """
- short_keyword = obj.nom.strip()
- long_keyword = ""
- for i in obj.getGenealogie()[:-1]:
- long_keyword += i + "."
- long_keyword += short_keyword
- self.kw_dict[short_keyword] = obj.valeur
- self.kw_dict[long_keyword] = obj.valeur
- return PythonGenerator.generMCSIMP(self, obj)
-
- def replace_keywords(self, template_string):
- result = template_string
- for item in six.iteritems(self.kw_dict):
- replace_str = "%" + item[0] + "%"
- result = result.replace(replace_str, str(item[1]))
- return result
-
- def writeDefault(self, basefilename):
- self.generate_output_from_template()
- output_filename = os.path.splitext(basefilename)[0] + \
- self.config.get_extension()
- f = open(output_filename, 'w')
- f.write(self.output_text)
- f.close()
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
- Ce module contient le plugin generateur de fichier au format
- homard pour EFICAS.
-
-"""
-import traceback
-import types,string,re
-
-from Noyau import N_CR
-from Noyau.N_utils import repr_float
-from Accas import ETAPE,PROC_ETAPE,MACRO_ETAPE,ETAPE_NIVEAU,JDC,FORM_ETAPE
-from Accas import MCSIMP,MCFACT,MCBLOC,MCList,EVAL
-from Accas import GEOM,ASSD,MCNUPLET
-from Accas import COMMENTAIRE,PARAMETRE, PARAMETRE_EVAL,COMMANDE_COMM
-from Formatage import Formatage
-from generator_python import PythonGenerator
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
-
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'homard',
- # La factory pour creer une instance du plugin
- 'factory' : HomardGenerator,
- }
-
-
-class HomardGenerator(PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un texte au format eficas et
- un texte au format homard
-
- """
- # Les extensions de fichier preconis�es
- extensions=('.comm',)
-
- def __init__(self,cr=None):
- # Si l'objet compte-rendu n'est pas fourni, on utilise le compte-rendu standard
- if cr :
- self.cr=cr
- else:
- self.cr=N_CR.CR(debut='CR generateur format homard pour homard',
- fin='fin CR format homard pour homard')
- # Le texte au format homard est stock� dans l'attribut text
- self.dico_mot_clef={}
- self.assoc={}
- self.init_assoc()
- self.text=''
- self.textehomard=[]
-
- def init_assoc(self):
- self.lmots_clef_calcules = ('SuivFron','TypeBila','ModeHOMA','CCAssoci', 'CCNoChaI','HOMaiN__','HOMaiNP1','CCNumOrI', 'CCNumPTI')
- self.lmot_clef = ('CCMaiN__', 'CCNoMN__', 'CCIndica', 'CCSolN__', 'CCFronti', 'CCNoMFro', 'CCMaiNP1',
- 'CCNoMNP1', 'CCSolNP1', 'TypeRaff', 'TypeDera', 'NiveauMa', 'SeuilHau', 'SeuilHRe',
- 'SeuilHPE', 'NiveauMi', 'SeuilBas', 'SeuilBRe', 'SeuilBPE', 'ListeStd', 'NumeIter',
- 'Langue ', 'CCGroFro', 'CCNoChaI', 'CCNumOrI', 'CCNumPTI', 'SuivFron', 'TypeBila',
- 'ModeHOMA', 'HOMaiN__', 'HOMaiNP1','CCCoChaI')
-
-# Bizarre demander a Gerald :
-# CVSolNP1
- self.assoc['CCMaiN__']='FICHIER_MED_MAILLAGE_N'
- self.assoc['CCNoMN__']='NOM_MED_MAILLAGE_N'
- self.assoc['CCIndica']='FICHIER_MED_MAILLAGE_N'
- self.assoc['CCSolN__']='FICHIER_MED_MAILLAGE_N'
- self.assoc['CCFronti']='FIC_FRON'
- self.assoc['CCNoMFro']='NOM_MED_MAILLAGE_FRONTIERE'
- self.assoc['CCMaiNP1']='FICHIER_MED_MAILLAGE_NP1'
- self.assoc['CCNoMNP1']='NOM_MED_MAILLAGE_NP1'
- self.assoc['CCSolNP1']='FICHIER_MED_MAILLAGE_NP1'
- self.assoc['TypeRaff']='RAFFINEMENT'
- self.assoc['TypeDera']='DERAFFINEMENT'
- self.assoc['NiveauMa']='NIVE_MAX'
- self.assoc['SeuilHau']='CRIT_RAFF_ABS'
- self.assoc['SeuilHRe']='CRIT_RAFF_REL'
- self.assoc['SeuilHPE']='CRIT_RAFF_PE'
- self.assoc['NiveauMi']='NIVE_MIN'
- self.assoc['SeuilBas']='CRIT_DERA_ABS'
- self.assoc['SeuilBRe']='CRIT_DERA_REL'
- self.assoc['SeuilBPE']='CRIT_DERA_PE'
- self.assoc['ListeStd']='MESSAGES'
- self.assoc['NumeIter']='NITER'
- self.assoc['Langue ']='LANGUE'
- self.assoc['CCGroFro']='GROUP_MA'
-# self.assoc['CCNoChaI']='NOM_MED' (on doit aussi ajouter 'COMPOSANTE')
- self.assoc['CCNumOrI']='NUME_ORDRE'
- self.assoc['CCNumPTI']='NUME_PAS_TEMPS'
- self.assoc['CCCoChaI']='COMPOSANTE'
-
- self.dico_mot_depend={}
-
- # Attention a la synthaxe
- self.dico_mot_depend['CCIndica'] ='self.dico_mot_clef["RAFFINEMENT"] == "LIBRE" or self.dico_mot_clef["DERAFFINEMENT"] == "LIBRE"'
- self.dico_mot_depend['CCSolN__'] ='self.dico_mot_clef.has_key("NITER")'
- self.dico_mot_depend['CCSolNP1'] ='self.dico_mot_clef.has_key("NITER")'
-
- def gener(self,obj,format='brut',config=None):
- self.text=PythonGenerator.gener(self,obj,format)
- self.genereConfiguration()
- return self.text
-
- def generMCSIMP(self,obj) :
- """
- Convertit un objet MCSIMP en une liste de chaines de caract�res � la
- syntaxe homard
- """
- s=PythonGenerator.generMCSIMP(self,obj)
- clef=obj.nom
- self.dico_mot_clef[clef]=obj.val
- return s
-
- def cherche_dependance(self,mot):
- b_eval = 0
- a_eval=self.dico_mot_depend[mot]
- try :
- b_eval=eval(self.dico_mot_depend[mot])
- except :
- for l in a_eval.split(" or "):
- try:
- b_eval=eval(l)
- if not (b_eval == 0 ):
- break
- except :
- pass
- return b_eval
-
-
- def genereConfiguration(self):
- ligbla=31*' '
- self.textehomard=[]
- for mot in self.lmot_clef:
-
-# on verifie d'abord que le mot clef doit bien etre calcule
- if self.dico_mot_depend.has_key(mot) :
- if self.cherche_dependance(mot) == 0 :
- continue
-
- if mot not in self.lmots_clef_calcules :
- clef_eficas=self.assoc[mot]
- if self.dico_mot_clef.has_key(clef_eficas):
- val=self.dico_mot_clef[clef_eficas]
- if val != None:
- try :
- ligne=mot+' '+val
- except:
- ligne=mot+' '+repr(val)
- ligne.rjust(32)
- self.textehomard.append(ligne)
- else:
- val=apply(HomardGenerator.__dict__[mot],(self,))
- if val != None:
- mot.rjust(8)
- ligne=mot+' '+val
- ligne.rjust(32)
- self.textehomard.append(ligne)
-
- def get_homard(self):
- return self.textehomard
-
- def SuivFron(self):
- val="non"
- if self.dico_mot_clef.has_key('NOM_MED_MAILLAGE_FRONTIERE'):
- if self.dico_mot_clef['NOM_MED_MAILLAGE_FRONTIERE'] != None:
- val="oui"
- return val
-
- def TypeBila(self):
- inttypeBilan = 1
- retour=None
- dict_val={'NOMBRE':7,'INTERPENETRATION':3,'QUALITE':5,'CONNEXITE':11,'TAILLE':13}
- for mot in ('NOMBRE','QUALITE','INTERPENETRATION','CONNEXITE','TAILLE'):
- if self.dico_mot_clef.has_key(mot):
- if (self.dico_mot_clef[mot] == "OUI"):
- inttypeBilan=inttypeBilan*dict_val[mot]
- retour = repr(inttypeBilan)
- return retour
-
-
- def ModeHOMA(self):
- intModeHOMA=1
- if self.dico_mot_clef.has_key('INFORMATION'):
- if self.dico_mot_clef['INFORMATION'] == "OUI":
- intModeHOMA=2
- return repr(intModeHOMA)
-
- def CCAssoci(self):
- return 'MED'
-
- def CCNoChaI(self):
- if not (self.dico_mot_clef.has_key('NOM_MED')):
- return None
- if (self.dico_mot_clef['NOM_MED']== None):
- return None
- if not (self.dico_mot_clef.has_key('COMPOSANTE')):
- return None
- if (self.dico_mot_clef['COMPOSANTE']== None):
- return None
- chaine=self.dico_mot_clef['COMPOSANTE']+' '+self.dico_mot_clef['NOM_MED']
- return chaine
-
- def HOMaiN__(self):
- chaine=None
- if self.dico_mot_clef.has_key('NITER'):
- if self.dico_mot_clef['NITER'] != None :
- num="M"+repr(self.dico_mot_clef['NITER'])
- chaine=num+" "+num+".hom"
- return chaine
-
- def HOMaiNP1(self):
- chaine=None
- if self.dico_mot_clef.has_key('NITER'):
- if self.dico_mot_clef['NITER'] != None :
- num="M"+repr(self.dico_mot_clef['NITER']+1)
- chaine=num+" "+num+".hom"
- return chaine
-
- def CCNumOrI(self):
- chaine=repr(1)
- if self.dico_mot_clef.has_key('NUME_ORDRE'):
- if self.dico_mot_clef['NUME_ORDRE'] != None :
- chaine=repr(self.dico_mot_clef['NUME_ORDRE'])
- return chaine
-
- def CCNumPTI(self):
- chaine=repr(1)
- if self.dico_mot_clef.has_key('NUME_PAS_TEMPS'):
- if self.dico_mot_clef['NUME_PAS_TEMPS'] != None :
- chaine=repr(self.dico_mot_clef['NUME_PAS_TEMPS'])
- return chaine
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2017 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
- Ce module contient le plugin generateur de fichier
- au format ini pour EFICAS.
-"""
-from __future__ import absolute_import
-try :
- from builtins import str
- from builtins import object
-except : pass
-
-import traceback
-import types
-from Extensions.i18n import tr
-from Extensions.eficas_exception import EficasException
-
-
-from Noyau import N_CR
-from Accas import MCSIMP,MCFACT,MCList
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'ini',
- # La factory pour creer une instance du plugin
- 'factory' : IniGenerator,
- }
-
-
-class IniGenerator(object):
- """
- Ce generateur parcourt un objet de type MCFACT et produit
- un fichier au format ini
- L'acquisition et le parcours sont realises par le methode
- generator.gener(objet_mcfact)
- L'ecriture du fichier au format ini par appel de la methode
- generator.writefile(nom_fichier)
-
- Ses caracteristiques principales sont exposees dans des attributs
- de classe :
- - extensions : qui donne une liste d'extensions de fichier preconisees
-
- """
- # Les extensions de fichier preconisees
- extensions=('.ini','.conf')
-
- def __init__(self,cr=None):
- # Si l'objet compte-rendu n'est pas fourni, on utilise le compte-rendu standard
- if cr :
- self.cr=cr
- else:
- self.cr=N_CR.CR(debut='CR generateur format ini',
- fin='fin CR format ini')
- # Le texte au format ini est stocke dans l'attribut text
- self.text=''
-
- def writefile(self,filename):
- fp=open(filename,'w')
- fp.write(self.text)
- fp.close()
-
- def gener(self,obj,config=None):
- """
- Tous les mots-cles simples du niveau haut sont mis dans la section DEFAUT
- Tous les mots-cles facteurs sont convertis en sections
- Un mot-cle facteur ne peut contenir que des mots-cles simples. Sinon => erreur
- """
- listeMcFact=[]
- sect_defaut=''
- if isinstance(obj,MCList):
- if len(obj.data) > 1:
- raise EficasException(tr("Pas supporte"))
- else:
- obj=obj.data[0]
-
- for mocle in obj.mc_liste:
- if isinstance(mocle,MCList):
- if len(mocle.data) > 1:
- raise EficasException(tr("Pas supporte"))
- else:
- listeMcFact.append(self.generMCFACT(mocle.data[0]))
- elif isinstance(mocle,MCFACT):
- listeMcFact.append(self.generMCFACT(mocle))
- elif isinstance(mocle,MCSIMP):
- sect_defaut=sect_defaut+self.generMCSIMP(mocle)
- else:
- self.cr.fatal(tr("Entite inconnue ou interdite :%s",repr(mocle)))
-
- self.text=''
- if sect_defaut != '':
- self.text="[DEFAULT]\n"+sect_defaut
- self.text=self.text + ''.join(listeMcFact,'\n')
- return self.text
-
- def generMCFACT(self,obj):
- """
- Cette methode convertit un mot-cle facteur ne contenant que des mots-cles
- simples en une chaine de caracteres
- """
- sect_text='[%s]\n' % obj.nom
- for mocle in obj.mc_liste:
- if isinstance(mocle,MCSIMP):
- sect_text=sect_text+self.generMCSIMP(mocle)
- else:
- self.cr.fatal(tr("Entite inconnue ou interdite :%s. Elle est ignoree",repr(mocle)))
- return sect_text
-
- def generMCSIMP(self,obj):
- """
- Cette methode convertit un mot-cle simple en une chaine de caracteres
- au format ini
- """
- s=''
- if type(obj.valeur) == tuple :
- self.cr.fatal(tr("Les tuples ne sont pas supportes pour le format ini :%s ", obj.nom))
- s="%s = %s\n" % (obj.nom,"ERREUR")
- else :
- try:
- s="%s = %s\n" % (obj.nom,obj.valeur)
- except Exception as e :
- self.cr.fatal(tr("Type de valeur non supportee par le format ini :%(nom)s\n%(exception)s", \
- {'nom': obj.nom, 'exception': str(e)}))
- return s
-
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
- Ce module contient le plugin generateur de fichier au format
- openturns pour EFICAS.
-
-"""
-import traceback
-import types,string,re
-from Extensions.i18n import tr
-
-
-from generator_python import PythonGenerator
-from OpenturnsBase import Generateur
-#from OpenturnsXML import XMLGenerateur
-#from OpenturnsSTD import STDGenerateur
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
-
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'openturns',
- # La factory pour creer une instance du plugin
- 'factory' : OpenturnsGenerator,
- }
-
-
-class OpenturnsGenerator(PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un texte au format eficas et
- un texte au format xml
-
- """
- # Les extensions de fichier permis?
- extensions=('.comm',)
-
- def initDico(self):
- self.dictMCVal={}
- self.listeVariables=[]
- self.listeFichiers=[]
- self.dictMCLois={}
- self.dictTempo={}
- self.TraiteMCSIMP=1
-
- def gener(self,obj,format='brut',config=None):
- #print "IDM: gener dans generator_openturns.py"
- self.initDico()
- self.text=PythonGenerator.gener(self,obj,format)
- self.genereXML()
- self.genereSTD()
- return self.text
-
- def generMCSIMP(self,obj) :
- """
- Convertit un objet MCSIMP en texte python
- Remplit le dictionnaire des MCSIMP si nous ne sommes pas ni dans une loi, ni dans une variable
- """
- s=PythonGenerator.generMCSIMP(self,obj)
- if self.TraiteMCSIMP == 1 :
- self.dictMCVal[obj.nom]=obj.valeur
- else :
- self.dictTempo[obj.nom]=obj.valeur
- return s
-
- def generMCFACT(self,obj):
- # Il n est pas possible d utiliser obj.valeur qui n est pas
- # a jour pour les nouvelles variables ou les modifications
- if obj.nom == "Variables" or "Files":
- self.TraiteMCSIMP=0
- self.dictTempo={}
- s=PythonGenerator.generMCFACT(self,obj)
- if obj.nom == "Variables" :
- self.listeVariables.append(self.dictTempo)
- self.dictTempo={}
- else :
- self.listeFichiers.append(self.dictTempo)
- self.TraiteMCSIMP=1
- return s
-
- def generETAPE(self,obj):
- if obj.nom == "DISTRIBUTION" :
- self.TraiteMCSIMP=0
- self.dictTempo={}
- s=PythonGenerator.generETAPE(self,obj)
- if obj.nom == "DISTRIBUTION" :
- self.dictMCLois[obj.sd]=self.dictTempo
- self.dictTempo={}
- self.TraiteMCSIMP=1
- return s
-
- def genereXML(self):
- #print "IDM: genereXML dans generator_openturns.py"
- if self.listeFichiers != [] :
- self.dictMCVal["exchange_file"]=self.listeFichiers
- MonBaseGenerateur=Generateur(self.dictMCVal, self.listeVariables, self.dictMCLois)
- MonGenerateur=MonBaseGenerateur.getXMLGenerateur()
- #try :
- if 1== 1 :
- self.texteXML=MonGenerateur.CreeXML()
- #except :
- else :
- self.texteXML=tr("Il y a un pb a la Creation du XML")
-
- def genereSTD(self):
- MonBaseGenerateur=Generateur(self.dictMCVal, self.listeVariables, self.dictMCLois)
- MonGenerateur=MonBaseGenerateur.getSTDGenerateur()
- #try :
- if 1== 1 :
- self.texteSTD=MonGenerateur.CreeSTD()
- #except :
- else :
- self.texteSTD=tr("Il y a un pb a la Creation du STD")
-
- def getOpenturnsXML(self):
- return self.texteXML
-
- def getOpenturnsSTD(self):
- return self.texteSTD
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
- Ce module contient le plugin generateur de fichier au format
- openturns pour EFICAS.
-
-"""
-import traceback
-import types,string,re
-from Extensions.i18n import tr
-
-
-from generator_python import PythonGenerator
-from OpenturnsBase import Generateur
-#from OpenturnsXML import XMLGenerateur
-#from OpenturnsSTD import STDGenerateur
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
-
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'openturns_study',
- # La factory pour creer une instance du plugin
- 'factory' : OpenturnsGenerator,
- }
-
-
-class OpenturnsGenerator(PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un texte au format eficas et
- un texte au format xml
-
- """
- # Les extensions de fichier permis?
- extensions=('.comm',)
-
- def initDico(self):
- self.dictMCVal={}
- self.listeVariables=[]
- self.listeFichiers=[]
- self.dictMCLois={}
- self.dictTempo={}
- self.TraiteMCSIMP=1
- self.texteSTD="""#!/usr/bin/env python
- import sys
- print "Invalid file. Check build process."
- sys.exit(1)
- """
-
- def gener(self,obj,format='brut',config=None):
- print "IDM: gener dans generator_openturns_study.py"
- self.initDico()
- self.text=PythonGenerator.gener(self,obj,format)
- self.genereSTD()
- return self.text
-
- def generMCSIMP(self,obj) :
- """
- Convertit un objet MCSIMP en texte python
- Remplit le dictionnaire des MCSIMP si nous ne sommes ni dans une loi, ni dans une variable
- """
- s=PythonGenerator.generMCSIMP(self,obj)
- if self.TraiteMCSIMP == 1 :
- self.dictMCVal[obj.nom]=obj.valeur
- else :
- self.dictTempo[obj.nom]=obj.valeur
- return s
-
-
- def generETAPE(self,obj):
- print "IDM: generETAPE dans generator_openturns_study.py"
- print "IDM: obj.nom=", obj.nom
- if obj.nom in ( "DISTRIBUTION", ) :
- self.TraiteMCSIMP=0
- self.dictTempo={}
- s=PythonGenerator.generETAPE(self,obj)
- if obj.nom in ( "DISTRIBUTION", ) :
- self.dictMCLois[obj.sd]=self.dictTempo
- self.dictTempo={}
- self.TraiteMCSIMP=1
- return s
-
- def generPROC_ETAPE(self,obj):
- print "IDM: generPROC_ETAPE dans generator_openturns_study.py"
- print "IDM: obj.nom=", obj.nom
- if obj.nom in ( "VARIABLE", ) :
- self.TraiteMCSIMP=0
- self.dictTempo={}
- s=PythonGenerator.generPROC_ETAPE(self,obj)
- if obj.nom in ( "VARIABLE", ) :
- self.listeVariables.append(self.dictTempo)
- self.dictTempo={}
- self.TraiteMCSIMP=1
- return s
-
- def genereSTD(self):
- print "IDM: genereSTD dans generator_openturns_study.py"
- print "IDM: self.listeVariables=", self.listeVariables
- MonGenerateur=self.getGenerateur()
- #try :
- if 1== 1 :
- self.texteSTD=MonGenerateur.CreeSTD()
- #except :
- else :
- self.texteSTD=tr("Il y a un pb a la Creation du STD")
-
- def writeDefault(self, fn):
- fileSTD = fn[:fn.rfind(".")] + '.py'
- with open(fileSTD, 'w') as f:
- f.write(self.texteSTD)
-
- def getGenerateur (self):
- print "IDM: getGenerateur dans generator_openturns_study.py"
- print "IDM: self.dictMCVal=", self.dictMCVal
- print "IDM: self.listeVariables=", self.listeVariables
- print "IDM: self.dictMCLois=", self.dictMCLois
- MonBaseGenerateur=Generateur(self.appli,self.dictMCVal, self.listeVariables, self.dictMCLois)
- MonGenerateur=MonBaseGenerateur.getSTDGenerateur()
- return MonGenerateur
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2013 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
- Ce module contient le plugin generateur de fichier au format
- openturns pour EFICAS.
-
-"""
-import traceback
-import types,string,re
-from Extensions.i18n import tr
-
-
-from generator_python import PythonGenerator
-from OpenturnsBase import Generateur
-#from OpenturnsXML import XMLGenerateur
-#from OpenturnsSTD import STDGenerateur
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
-
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'openturns_wrapper',
- # La factory pour creer une instance du plugin
- 'factory' : OpenturnsGenerator,
- }
-
-
-class OpenturnsGenerator(PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un texte au format eficas et
- un texte au format xml
-
- """
- # Les extensions de fichier permis?
- extensions=('.comm',)
-
- def initDico(self):
- self.dictMCVal={}
- self.dictVariables={}
- self.listeFichiers=[]
- self.dictTempo={}
- self.traiteMCSIMP=1
- self.numOrdre=0
- self.texteSTD="""#!/usr/bin/env python
- import sys
- print "Invalid file. Check build process."
- sys.exit(1)
- """
- self.wrapperXML=None
-
- def gener(self,obj,format='brut',config=None):
- #print "IDM: gener dans generator_openturns_wrapper.py"
- self.initDico()
- self.text=PythonGenerator.gener(self,obj,format)
- self.genereXML()
- #self.genereSTD()
- return self.text
-
- def generMCSIMP(self,obj) :
- """
- Convertit un objet MCSIMP en texte python
- Remplit le dictionnaire des MCSIMP si nous ne sommes ni dans une loi, ni dans une variable
- """
- s=PythonGenerator.generMCSIMP(self,obj)
- if not( type(obj.valeur) in (list, tuple)) and (obj.getMinMax()[1] != 1):
- valeur=(obj.valeur,)
- else :
- valeur=obj.valeur
- if self.traiteMCSIMP == 1 :
- self.dictMCVal[obj.nom]=valeur
- else :
- self.dictTempo[obj.nom]=valeur
- return s
-
- def generETAPE(self,obj):
- #print "generETAPE" , obj.nom
- if obj.nom == "VARIABLE" :
- self.traiteMCSIMP=0
- self.dictTempo={}
- s=PythonGenerator.generETAPE(self,obj)
- if obj.nom == "VARIABLE" :
- self.dictTempo["numOrdre"]=self.numOrdre
- self.numOrdre = self.numOrdre +1
- if obj.sd == None :
- self.dictVariables["SansNom"]=self.dictTempo
- else :
- self.dictVariables[obj.sd.nom]=self.dictTempo
- self.dictTempo={}
- self.traiteMCSIMP=1
- return s
-
- def generMCFACT(self,obj):
- # Il n est pas possible d utiliser obj.valeur qui n est pas
- # a jour pour les nouvelles variables ou les modifications
- if obj.nom in ( "Files", ) :
- self.traiteMCSIMP=0
- self.dictTempo={}
- s=PythonGenerator.generMCFACT(self,obj)
- self.listeFichiers.append(self.dictTempo)
- self.traiteMCSIMP=1
- return s
-
- def genereXML(self):
- print "IDM: genereXML dans generator_openturns_wrapper.py"
- #print "appli.maConfiguration=",self.appli.maConfiguration.__dict__
- if self.listeFichiers != [] :
- self.dictMCVal["Files"]=self.listeFichiers
- print "dictMCVal", self.dictMCVal, "dictVariables", self.dictVariables
- MonBaseGenerateur=Generateur(self.appli,self.dictMCVal, [], {} ,self.dictVariables)
- MonGenerateur=MonBaseGenerateur.getXMLGenerateur()
- try :
- #if 1== 1 :
- self.wrapperXML=MonGenerateur.CreeXML()
- except :
- #else :
- self.wrapperXML=None
-
- def writeDefault(self, filename):
- fileXML = filename[:filename.rfind(".")] + '.xml'
- self.wrapperXML.writeFile( str(fileXML) )
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2017 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
- Ce module contient le plugin generateur de fichier au format pyth pour EFICAS.
-
-
-"""
-try :
- from builtins import str
- from builtins import object
-except : pass
-
-import traceback
-import types
-
-from Noyau import N_CR
-from Accas import MCSIMP,MCFACT,MCList
-from Extensions.i18n import tr
-from Extensions.eficas_exception import EficasException
-
-
-def entryPoint():
- """
- Retourne les informations necessaires pour le chargeur de plugins
-
- Ces informations sont retournees dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'pyth',
- # La factory pour creer une instance du plugin
- 'factory' : PythGenerator,
- }
-
-
-class PythGenerator(object):
- """
- Ce generateur parcourt un objet de type MCFACT et produit
- un fichier au format pyth
-
- L'acquisition et le parcours sont realises par la methode
- generator.gener(objet_mcfact)
-
- L'ecriture du fichier au format ini par appel de la methode
- generator.writefile(nom_fichier)
-
- Ses caracteristiques principales sont exposees dans des attributs
- de classe :
- - extensions : qui donne une liste d'extensions de fichier preconisees
-
- """
- # Les extensions de fichier preconisees
- extensions=('.py','.comm')
-
- def __init__(self,cr=None):
- # Si l'objet compte-rendu n'est pas fourni, on utilise le compte-rendu standard
- if cr :
- self.cr=cr
- else:
- self.cr=N_CR.CR(debut='CR generateur format ini',
- fin='fin CR format ini')
- # Le texte au format pyth est stocke dans l'attribut text
- self.text=''
-
- def writefile(self,filename):
- fp=open(filename,'w')
- fp.write(self.text)
- fp.close()
-
- def gener(self,obj,format='standard',config=None):
- """
- Tous les mots-cles simples du niveau haut sont transformes en variables
-
- Tous les mots-cles facteurs sont convertis en dictionnaires
-
- Les mots-cles multiples ne sont pas traites
- """
- s=''
- if isinstance(obj,MCList):
- if len(obj.data) > 1:
- raise EficasException(tr("Pas supporte"))
- else:
- obj=obj.data[0]
-
- for mocle in obj.mc_liste:
- if isinstance(mocle,MCList):
- if len(mocle.data) > 1:
- raise EficasException(tr("Pas supporte"))
- else:
- valeur=self.generMCFACT(mocle.data[0])
- s=s+"%s = %s\n" % (mocle.nom,valeur)
- elif isinstance(mocle,MCFACT):
- valeur=self.generMCFACT(mocle)
- s=s+"%s = %s\n" % (mocle.nom,valeur)
- elif isinstance(v,MCSIMP):
- valeur = self.generMCSIMP(mocle)
- s=s+"%s = %s\n" % (mocle.nom,valeur)
- else:
- self.cr.fatal("Entite inconnue ou interdite : "+repr(mocle))
-
- self.text=s
- return self.text
-
- def generMCFACT(self,obj):
- """
- Cette methode convertit un mot-cle facteur
- en une chaine de caracteres representative d'un dictionnaire
- """
- s = '{'
- for mocle in obj.mc_liste:
- if isinstance(mocle,MCSIMP):
- valeur = self.generMCSIMP(mocle)
- s=s+"'%s' : %s,\n" % (mocle.nom,valeur)
- elif isinstance(mocle,MCFACT):
- valeur=self.generMCFACT(mocle)
- s=s+"'%s' : %s,\n" % (mocle.nom,valeur)
- else:
- self.cr.fatal(tr("Entite inconnue ou interdite : %s. Elle est ignoree", repr(mocle)))
-
- s=s+'}'
- return s
-
- def generMCSIMP(self,obj):
- """
- Cette methode convertit un mot-cle simple en une chaine de caracteres
- au format pyth
- """
- try:
- s="%s" % obj.valeur
- except Exception as e :
- self.cr.fatal(tr("Type de valeur non supporte par le format pyth : n %(exception)s", \
- {'nom': obj.nom, 'exception': str(e)}))
-
-
- s="ERREUR"
- return s
-
+++ /dev/null
-# -*- coding: utf-8 -*-
-# Copyright (C) 2007-2017 EDF R&D
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-#
-# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
-#
-"""
- Ce module contient le plugin generateur de fichier au format
- python pour EFICAS.
-
-"""
-import traceback
-import types,string,re
-
-from Noyau import N_CR
-from Noyau.N_utils import repr_float
-from Accas import ETAPE,PROC_ETAPE,MACRO_ETAPE,ETAPE_NIVEAU,JDC,FORM_ETAPE
-from Accas import MCSIMP,MCFACT,MCBLOC,MCList,EVAL
-from Accas import GEOM,ASSD,MCNUPLET
-from Accas import COMMENTAIRE,PARAMETRE, PARAMETRE_EVAL,COMMANDE_COMM
-from Formatage import Formatage
-
-import generator_python
-
-def entryPoint():
- """
- Retourne les informations nécessaires pour le chargeur de plugins
-
- Ces informations sont retournées dans un dictionnaire
- """
- return {
- # Le nom du plugin
- 'name' : 'python6',
- # La factory pour créer une instance du plugin
- 'factory' : PythonGenerator,
- }
-
-
-class PythonGenerator(generator_python.PythonGenerator):
- """
- Ce generateur parcourt un objet de type JDC et produit
- un fichier au format python6
-
- L'acquisition et le parcours sont réalisés par la méthode
- generator.gener(objet_jdc,format)
-
- L'écriture du fichier au format python6 par appel de la méthode
- generator.writefile(nom_fichier)
-
- Ses caractéristiques principales sont exposées dans des attributs
- de classe :
- - extensions : qui donne une liste d'extensions de fichier préconisées
-
- """
- # Les extensions de fichier préconisées
- extensions=('.comm',)
-
- def generFORM_ETAPE(self,obj):
- """
- Méthode particulière pour les objets de type FORMULE
- """
- l=[]
- nom = obj.getNom()
- if nom == '' : nom = 'sansnom'
- l.append(nom + ' = FORMULE(')
- for v in obj.mc_liste:
- text=self.generator(v)
- l.append(v.nom+'='+text)
- l.append(');')
- return l
-
- def gen_formule(self,obj):
- """
- Méthode particuliere aux objets de type FORMULE
- """
- try:
- if obj.sd == None:
- sdname=''
- else:
- sdname= self.generator(obj.sd)
- except:
- sdname='sansnom'
- l=[]
- label=sdname + ' = FORMULE('
- l.append(label)
- for v in obj.mc_liste:
- s=''
- s= v.nom+':'+sdname+'('+v.valeur+')'
- l.append(s)
- if len(l) == 1:
- l[0]=label+');'
- else :
- l.append(');')
- return l