예제 #1
0
def crea_noeu_lig_coup(dimension, pt1, pt2, anglj, dnor):
    from Utilitai.Utmess import UTMESS
    from math import pi, sin, cos, sqrt

    a = pt1[0] - pt2[0]
    b = pt1[1] - pt2[1]
    eps = 0.00000001
    anglr = anglj * pi / 180.
    if dimension == 2:
        r = sqrt(a ** 2 + b ** 2)
        if abs(r) < eps:
            UTMESS('F', 'POST0_6')
        x = pt2[0] + a * cos(anglr) - b * sin(anglr)
        y = pt2[1] + b * cos(anglr) + a * sin(anglr)
        return x, y
    elif dimension == 3:
        c = pt1[2] - pt2[2]
        r = sqrt(a ** 2 + b ** 2 + c ** 2)
        if abs(r) < eps:
            UTMESS('F', 'POST0_6')
        d1 = dnor[0]
        d2 = dnor[1]
        d3 = dnor[2]
        d = sqrt(d1 ** 2 + d2 ** 2 + d3 ** 2)
        if abs(r) < eps:
            UTMESS('F', 'POST0_7')
        x = pt2[0] + a * cos(anglr) + sin(anglr) * (c * d2 - b * d3) / d
        y = pt2[1] + b * cos(anglr) + sin(anglr) * (a * d3 - c * d1) / d
        z = pt2[2] + c * cos(anglr) + sin(anglr) * (b * d1 - a * d2) / d
        return x, y, z
예제 #2
0
def INCLUDE(self, UNITE, DONNEE, **args):
    """Fonction sd_prod pour la macro INCLUDE"""
    self.show_children = args.get('INFO', 1) != 0
    if not (UNITE or DONNEE) or hasattr(self, '_mark'):
        return
    self._mark = 1
    if self.jdc and self.jdc.par_lot == 'NON':
        # On est en mode commande par commande, on appelle la methode speciale
        self.Execute_alone()
    if UNITE:
        fname = 'fort.%s' % UNITE
    else:
        fname = DONNEE
        if aster_exists:
            repdex = aster_core.get_option('repdex')
            fname = osp.join(repdex, fname)
    try:
        if aster_exists:
            self.make_include(fname=fname)
        else:
            # dans eficas
            if UNITE:
                self.make_include(unite=UNITE)
            else:
                self.make_include(fname=fname)
    except Accas.AsException:
        if aster_exists:
            UTMESS('F+', 'FICHIER_1', valk=fname)
            UTMESS('F', 'FICHIER_2')
        raise
예제 #3
0
def corrcoefmodel(Period, f_beta=None):
    # ---------------------------------------------------------
    # IN : Periods= liste des periodes 1/f  [s]
    #      optionnel: liste de beta (ecart-type)
    # OUT : mat_out= matrice de covariance pour periodes T
    #       >>>coef de correlation (ecart-type=1)  si beta=None
    #       >>>covariance si beta=tfonction
    #
    # REFERENCE     corrcoef selon le modele de Baker:
    #          Baker & Jayaram, Earthquake Spectra 24(1),299-317, 2008.
    #
    # ---------------------------------------------------------
    PMIN = min(Period)
    if PMIN < 0.01:
        UTMESS('F', 'SEISME_37', valk=(str(1. / PMIN)))
    if max(Period) > 10.:
        nb = len(NP.extract(Period > 10., Period))
        Periods = Period[nb:]
    else:
        Periods = Period
    nbT = len(Periods)
    Mat_Eps = NP.array([0.0] * nbT * nbT)
    Mat_Eps.resize(nbT, nbT)
    # Le modele de Baker est defini pour  max(Periods)<=10.

    if f_beta != None:
        if min(f_beta.vale_x) > 0.1:
            UTMESS('F', 'SEISME_82')
        else:
            f_beta = f_beta.evalfonc(1. / Periods)
            vale_beta = f_beta.vale_y

    for (ii, Ti) in enumerate(Periods):
        for (jj, Tj) in enumerate(Periods):
            Tmin = min(Ti, Tj)
            Tmax = max(Ti, Tj)
            C1 = 1. - cos(pi / 2. - 0.366 * log(Tmax / max(Tmin, 0.109)))
            C3 = C1
            if Tmax < 0.109:
                C2 = 1. - 0.105 * \
                    (1. - 1. / (1. + exp(100. * Tmax - 5.))) * (
                        (Tmax - Tmin) / (Tmax - 0.0099))
                Mat_Eps[ii, jj] = C2
            elif Tmin > 0.109:
                Mat_Eps[ii, jj] = C1
            elif Tmax < 0.2:
                C2 = 1. - 0.105 * \
                    (1 - 1 / (1 + exp(100 * Tmax - 5))) * (
                        (Tmax - Tmin) / (Tmax - 0.0099))
                C4 = C1 + 0.5 * (sqrt(C3) - C3) * (1 + cos(pi * Tmin / 0.109))
                Mat_Eps[ii, jj] = min(C2, C4)
            else:
                C4 = C1 + 0.5 * (sqrt(C3) - C3) * (1. + cos(pi * Tmin / 0.109))
                Mat_Eps[ii, jj] = C4
            if f_beta != None:
                Mat_Eps[ii,
                        jj] = Mat_Eps[ii, jj] * vale_beta[ii] * vale_beta[jj]

    Mat_Gx = NP.linalg.cholesky(Mat_Eps)
    return Periods, Mat_Gx
예제 #4
0
def lire_table_ops(self, UNITE, FORMAT, SEPARATEUR, NUME_TABLE, RENOMME_PARA,
                   INFO, TITRE, **args):
    """Méthode corps de la macro LIRE_TABLE
    """
    import aster
    from Utilitai.Utmess import UTMESS, raise_UTMESS
    from Utilitai.UniteAster import UniteAster
    from Utilitai.TableReader import TableReaderFactory, unique_parameters

    ier = 0
    # On importe les definitions des commandes a utiliser dans la macro
    CREA_TABLE = self.get_cmd('CREA_TABLE')

    # La macro compte pour 1 dans la numerotation des commandes
    self.set_icmd(1)

    # Lecture de la table dans un fichier d unité logique UNITE
    UL = UniteAster()
    nomfich = UL.Nom(UNITE)
    if not osp.isfile(nomfich):
        UTMESS('F', 'FONCT0_41', valk=nomfich)

    texte = open(nomfich, 'r').read()
    # remet UNITE dans son état initial
    UL.EtatInit()

    check_para = None
    if RENOMME_PARA == "UNIQUE":
        check_para = unique_parameters

    reader = TableReaderFactory(texte, FORMAT, SEPARATEUR, debug=(INFO == 2))
    try:
        tab = reader.read(NUME_TABLE, check_para=check_para)
    except TypeError, exc:
        UTMESS('F', 'TABLE0_45', valk=str(exc))
예제 #5
0
 def RCVALE(self, phenomene, nompar=(), valpar=(), nomres=(), stop=1):
    """Appel à la routine fortran RCVALE pour récupérer les valeurs des
    propriétés du matériau.
    """
    if not self.accessible():
       raise AsException("Erreur dans mater.RCVALE en PAR_LOT='OUI'")
    from Utilitai.Utmess import UTMESS
    # vérification des arguments
    if not type(nompar) in (list, tuple):
       nompar = [nompar,]
    if not type(valpar) in (list, tuple):
       valpar = [valpar,]
    if not type(nomres) in (list, tuple):
       nomres = [nomres,]
    nompar = tuple(nompar)
    valpar = tuple(valpar)
    nomres = tuple(nomres)
    if len(nompar) != len(valpar):
       vk1=', '.join(nompar)
       vk2=', '.join([repr(v) for v in valpar])
       UTMESS('F','SDVERI_4',valk=[vk1,vk2])
    if len(nomres) < 1:
       UTMESS('F', 'SDVERI_5')
    # appel à l'interface Python/C
    return aster.rcvale(self.nom, phenomene, nompar, valpar, nomres, stop)
예제 #6
0
def get_para_loi(loi, relation, l_para, l_vale, l_para1, l_vale1,
                 nom_mater, donnees, liste_fonc):
    """
        Lecture des paramètres de la loi 'loi'
    """
    cle = relation + '/' + loi
    if not cata_lois[cle].has_key('POSI_PARA'):
        posi_para = False
    else:
        posi_para = True
    for ipar, para in enumerate(cata_lois[cle]['PARA']):
        if donnees.has_key(para):
            para_epx = cata_lois[cle]['PARA_EPX'][ipar]
            type_donnee = cata_lois[cle]['TYPE'][ipar]
            if type_donnee == 'fonc':
                car_temp = donnees[para]
                nom_fonc = car_temp.get_name()
                ifonc = len(liste_fonc) + 1
                for dic_fonc in liste_fonc:
                    if type(dic_fonc) is dict:
                        nom = dic_fonc['NOM_FONC']
                        if nom == nom_fonc:
                            ifonc = dic_fonc['NUME']
                            break
                if ifonc > len(liste_fonc):
                    val = car_temp.Valeurs()
                    dic_fonc = {'VALE': val,
                                'NUME': ifonc,
                                'NOM_FONC': nom_fonc
                                }
                    liste_fonc.append(dic_fonc)
                vale = 'FONC %i' % ifonc
            elif type_donnee == 'mfac':
                raise Exception(
                    'Erreur de programmation : type de donnees mfac impossible')
            else:
                vale = donnees[para]
                if type(para_epx) == float or type(para_epx) == int:
                    if vale != para_epx:
                        UTMESS('F', 'PLEXUS_49', valk=(para, loi, nom_mater),
                                                 valr=(para_epx, vale))
            if not posi_para:
                l_para.append(para_epx)
                l_vale.append(vale)
            elif cata_lois[cle]['POSI_PARA'][ipar] == 0:
                l_para.append(para_epx)
                l_vale.append(vale)
            else:
                l_para1.append(para_epx)
                l_vale1.append(vale)
        else:
            bes_para = cata_lois[cle]['BESOIN'][ipar]
            if bes_para == 'o':
                UTMESS('F', 'PLEXUS_31', valk=(para, loi, nom_mater))
#   vérifcation que l'on utilise pas de mot-clé non pris en charge
    for para in donnees.keys():
        if para not in cata_lois[cle]['PARA']:
            UTMESS('A', 'PLEXUS_46', valk=(para, loi, nom_mater))

    return l_para, l_vale, l_para1, l_vale1, liste_fonc
예제 #7
0
def check_amor(amor_ref, amor):
    """
        Vérification que les deux listes d'amortissement sont identiques
    """

    if len(amor_ref) != len(amor): UTMESS('F', 'SPECTRAL0_18')

    for i in range(len(amor_ref)):
        if amor_ref[i] != amor[i]: UTMESS('F', 'SPECTRAL0_18')
예제 #8
0
    def _run(self):
        """INTERPOL_FFT"""
        import copy
        kw = self.kw
        t0 = self._lf[0].vale_x[0]

        dt_init = self._lf[0].vale_x[1] - t0
        N_init = len(self._lf[0].vale_x)

        dt_cible = kw['PAS_INST']
        if dt_init < dt_cible:
            UTMESS('F', 'FONCT0_35')
        # nombre d'intervalles
        N_init -= 1
        N_sortie = int((N_init) * dt_init / dt_cible)

        if N_init * dt_init / dt_cible - N_sortie >= 0.5:
            N_sortie += 1
        # retour au nombre de valeurs
        N_sortie += 1

        # FFT
        ft = self._lf[0].fft('COMPLET')

        # suppression de la partie symetrique du signal
        N = len(ft.vale_x)
        valex = list(ft.vale_x[:N / 2 + 1])
        valey = list(ft.vale_y[:N / 2 + 1])

        # zero padding
        dfreq = (valex[1] - valex[0]).real
        last_freq = valex[-1]
        N_pad = N_sortie / 2 + 1 - N / 2 - 1
        for i in range(N_pad):
            freq = last_freq + (i + 1) * dfreq
            valex.append(freq)
            valey.append(0.)
        ft.vale_x = NP.array(valex)
        ft.vale_y = NP.array(valey)

        # IFFT
        self.resu = ft.fft('COMPLET', 'NON')
        self.resu.vale_x = self.resu.vale_x + t0

        # dt fin reel
        dt_fin = self.resu.vale_x[1] - self.resu.vale_x[0]

        # normalisation
        coef_norm = dt_init / dt_fin
        self.resu.vale_y = self.resu.vale_y * coef_norm

        ecart = abs(dt_fin - kw['PAS_INST']) / kw['PAS_INST']
        if ecart > kw['PRECISION']:
            UTMESS('A',
                   'FONCT0_51',
                   valr=[dt_fin, kw['PAS_INST'], 100 * ecart])
예제 #9
0
    def __init__(self,
                 gr_max=10,
                 options=None,
                 xmgrace=os.path.join(aster_core.get_option('repout'),
                                      'xmgrace')):

        # Declaration
        global TERMINAL

        # Precondition
        if TERMINAL:
            raise Xmgr.DEJA_ACTIF

        # Initialisation
        TERMINAL = 1
        self.gr_max = gr_max  # nombre de graphes
        self.gr_act = 0  # numero du graphe actif
        self.sets = [0] * gr_max  # nombre de sets par graphe
        self.nom_pipe = 'xmgr.pipe'  # nom du pipe de communication
        self.xmgrace = xmgrace

        # Ouverture du pipe de communication avec xmgrace
        if os.path.exists(self.nom_pipe):
            os.remove(self.nom_pipe)
        os.mkfifo(self.nom_pipe)
        self.pipe = open(self.nom_pipe, 'a+')

        # Lancement de xmgrace
        if options != None:
            cmd = self.xmgrace + ' -noask ' + options + \
                ' -graph ' + repr(gr_max - 1) + ' -npipe ' + self.nom_pipe
        else:
            cmd = self.xmgrace + ' -noask ' + \
                ' -graph ' + repr(gr_max - 1) + ' -npipe ' + self.nom_pipe

        # Teste le DISPLAY avant de lancer xmgrace...
        if os.environ.has_key('DISPLAY'):

            UTMESS('I', 'STANLEY_9', valk=[cmd])
            self.controle = Popen(cmd, shell=True)

            # Mise a l'echelle des graphes
            for i in xrange(gr_max):
                gr = 'G' + repr(i)
                self.Send('WITH ' + gr)
                self.Send('VIEW XMIN 0.10')
                self.Send('VIEW XMAX 0.95')
                self.Send('VIEW YMIN 0.10')
                self.Send('VIEW YMAX 0.95')

            # Activation du graphe G0
            self.Active(0)

        else:
            TERMINAL = 0
            UTMESS('A', 'STANLEY_3', valk=['XMGRACE'])
예제 #10
0
def verif_reuse(OPERATION, obj_reuse):
    # verification que reuse est correctement employe
    if OPERATION in ('ABSC_CURV_NORM', 'ANGLE_BIFURCATION', 'LOI_PROPA',
                     'K1_NEGATIF'):
        if not obj_reuse:
            UTMESS('F', 'RUPTURE1_62', valk=(OPERATION))

    if OPERATION in ('COMPTAGE_CYCLES', 'CUMUL_CYCLES', 'PILO_PROPA'):
        if obj_reuse:
            UTMESS('F', 'RUPTURE1_63', valk=(OPERATION))
예제 #11
0
def recu_coor_z(noma, group, typ_group, tole_r):

    import aster
    from Utilitai.Utmess import UTMESS

    collcnx = aster.getcolljev(noma.nom.ljust(8) + '.CONNEX')
    coord = aster.getvectjev(noma.nom.ljust(8) + '.COORDO    .VALE')
    cnom = aster.getvectjev(noma.nom.ljust(8) + '.NOMNOE')

    coor_z = []

    if typ_group == 'group_ma':
        nomgrma = group
        collgrma = aster.getcolljev(noma.nom.ljust(8) + '.GROUPEMA')
        if nomgrma.ljust(24) not in collgrma:
            UTMESS("F", "MISS0_26", valk=group)
        else:
            numa = collgrma[nomgrma.ljust(24)]
            for ima in numa:
                n = collcnx[ima][0]
                uzmin = round(coord[3 * (n - 1) + 2], tole_r)
                uzmax = round(coord[3 * (n - 1) + 2], tole_r)
                for i in range(len(collcnx[ima])):
                    n = collcnx[ima][i]
                    uzmin = min(uzmin, round(coord[3 * (n - 1) + 2], tole_r))
                    uzmax = max(uzmax, round(coord[3 * (n - 1) + 2], tole_r))
                if uzmin not in coor_z:
                    coor_z.append(uzmin)
                if uzmax not in coor_z:
                    coor_z.append(uzmax)
    elif typ_group == 'group_no':
        collgrno = aster.getcolljev(noma.nom.ljust(8) + '.GROUPENO')
        nomgrno = group
        if nomgrno.ljust(24) not in collgrno:
            UTMESS("F", "MISS0_26", valk=group)
        else:
            grpn = collgrno[nomgrno.ljust(24)]
            l_coor_group = []
            i = 0
            for node in grpn:
                l_coor_group.append(
                    aster.getvectjev(
                        noma.nom.ljust(8) + '.COORDO    .VALE', 3 * (node - 1),
                        3))
                uz = round(l_coor_group[i][2], tole_r)
                i += 1
                if uz not in coor_z:
                    coor_z.append(uz)
    else:
        assert 0, 'recu_coor_z : erreur argument typ_group'

    prov = sorted(coor_z)
    coor_z = prov[::-1]

    return coor_z
예제 #12
0
 def _build_data(self):
     """Read keywords to build the data"""
     CalcFonctionOper._build_list_fonc(self)
     kw = self.kw
     self._dat = {}
     # amor
     if kw['AMOR_REDUIT'] is None:
         l_amor = [0.02, 0.05, 0.1]
         UTMESS('I', 'FONCT0_31', valr=l_amor)
     else:
         l_amor = force_list(kw['AMOR_REDUIT'])
     eps = 1.e-6
     for amor in l_amor:
         if amor > (1 - eps):
             UTMESS('S', 'FONCT0_36')
     self._dat['AMOR'] = l_amor
     # freq
     if kw['LIST_FREQ'] is not None:
         l_freq = kw['LIST_FREQ'].Valeurs()
     elif kw['FREQ'] is not None:
         l_freq = force_list(kw['FREQ'])
     else:
         l_freq = []
         for i in range(56):
             l_freq.append(0.2 + 0.050 * i)
         for i in range(8):
             l_freq.append(3.0 + 0.075 * i)
         for i in range(14):
             l_freq.append(3.6 + 0.100 * i)
         for i in range(24):
             l_freq.append(5.0 + 0.125 * i)
         for i in range(28):
             l_freq.append(8.0 + 0.250 * i)
         for i in range(6):
             l_freq.append(15.0 + 0.500 * i)
         for i in range(4):
             l_freq.append(18.0 + 1.0 * i)
         for i in range(10):
             l_freq.append(22.0 + 1.500 * i)
         texte = []
         for i in range(len(l_freq) / 5):
             texte.append(' %f %f %f %f %f' %
                          tuple(l_freq[i * 5:i * 5 + 5]))
         UTMESS('I',
                'FONCT0_32',
                vali=len(l_freq),
                valk=os.linesep.join(texte))
     if min(l_freq) < 1.E-10:
         UTMESS('F', 'FONCT0_43')
     self._dat['FREQ'] = l_freq
     # check
     if abs(kw['NORME']) < 1.E-10:
         UTMESS('S', 'FONCT0_33')
     if kw['NATURE_FONC'] == 'DSP':
         ASSERT(kw['METHODE'] == 'RICE')
예제 #13
0
def IniGrace(fich):
    """Retourne le numéro de la dernière courbe d'un fichier xmgrace (sinon 0).
    """
    ns = 0
    x0 = None
    x1 = None
    y0 = None
    y1 = None
    if os.path.exists(fich) and os.stat(fich).st_size <> 0:
        os.rename(fich, fich + '.prev')
        fpre = open(fich + '.prev', 'r')
        fnew = open(fich, 'w')
        for line in fpre:
            ikeep = True
            mat = re.search('@target g[0-9]+\.s([0-9]+)', line)
            if mat <> None and int(mat.group(1)) > ns:
                ns = int(mat.group(1))
            mat = re.search('@[ ]+world[ ]+xmin[ ]+([\-\+\.0-9eEdD]+)', line)
            if mat <> None:
                try:
                    x0 = float(mat.group(1))
                    ikeep = False
                except ValueError:
                    pass
            mat = re.search('@[ ]+world[ ]+xmax[ ]+([\-\+\.0-9eEdD]+)', line)
            if mat <> None:
                try:
                    x1 = float(mat.group(1))
                    ikeep = False
                except ValueError:
                    pass
            mat = re.search('@[ ]+world[ ]+ymin[ ]+([\-\+\.0-9eEdD]+)', line)
            if mat <> None:
                try:
                    y0 = float(mat.group(1))
                    ikeep = False
                except ValueError:
                    pass
            mat = re.search('@[ ]+world[ ]+ymax[ ]+([\-\+\.0-9eEdD]+)', line)
            if mat <> None:
                try:
                    y1 = float(mat.group(1))
                    ikeep = False
                except ValueError:
                    pass
            if ikeep:
                fnew.write(line)
        fpre.close()
        fnew.close()
        if None not in (x0, x1, y0, y1):
            UTMESS('I', 'GRAPH0_10', valk=fich, vali=ns, valr=(x0, x1, y0, y1))
        else:
            UTMESS('A', 'GRAPH0_11', valk=fich)
    return ns, x0, x1, y0, y1
예제 #14
0
    def _exec_boucle_lapl(self):
        """Exécute MISS3D dans une boucle sur toutes les fréquences complexes"""
        L_points = self.L_points
        dt = self.dt
        rho = self.rho
        reduc_factor = self.reducFactor
        # TODO la règle UN_PARMI(FREQ_MIN, LIST_FREQ, FREQ_IMAG) ne convient pas!
        # au moins mettre FREQ_MIN à None
        self.param.set('FREQ_MIN', None)
        if self.cutOffValue == 1:
            fc = self.cutOffValue * self.nbr_freq / float(reduc_factor)
        else:
            fc = NP.int_(
                NP.ceil(self.cutOffValue * self.nbr_freq / float(reduc_factor)))
        freq_list1 = NP.arange(0, fc * reduc_factor)
        freq_list2 = NP.arange(fc * reduc_factor, self.nbr_freq, reduc_factor)
        self.freq_list = freq_list1.tolist() + freq_list2.tolist()
        rank, size = aster_core.MPI_CommRankSize()

        for k in self.freq_list:
            # round-robin partition
            if k % size != rank:
                UTMESS('I', 'MISS0_24', vali=(k, k % size))
                continue
            UTMESS('I', 'MISS0_25', vali=(k, rank))

            if (k == 0) or (k == self.nbr_freq - 1):
                self.param.set('LIST_FREQ', (0.1E-4,))
                self.param.set(
                    'FREQ_IMAG', (1.5 - 2.0 * rho * cos(2 * pi * k / L_points) + 0.5 * rho * rho * cos(4 * pi * k / L_points)) / dt)
            else:
                self.param.set(
                    'LIST_FREQ', (-(-2.0 * rho * sin(2 * pi * k / L_points) + 0.5 * rho * rho * sin(4 * pi * k / L_points)) / dt / (2 * pi),))
                self.param.set(
                    'FREQ_IMAG', (1.5 - 2.0 * rho * cos(2 * pi * k / L_points) + 0.5 * rho * rho * cos(4 * pi * k / L_points)) / dt)

            self.param.set('_calc_impe', True)
            CalculMiss.cree_commande_miss(self)
            str00 = str(self.param['FREQ_IMAG']) + ' + i . ' + str(
                self.param['LIST_FREQ'][0]) + ' (' + str(k + 1) + '/' + str(self.nbr_freq) + ')'
            aster.affiche("MESSAGE", 'FREQUENCE COMPLEXE COURANTE =  ' + str00)
            CalculMiss.execute(self)
            resname = self._fichier_tmp('resu_impe_%04d' % k)
            copie_fichier(self._fichier_tmp("resu_impe"), resname)

            if rank != 0:
                UTMESS('I', 'PARALLEL_2', valk=(
                    resname, self._results_path[0]))
                send_file(resname, self._results_path[0])

        # libérer la structure contenant les données numériques
        CalculMiss.init_data(self)
        aster_core.MPI_Barrier()
예제 #15
0
    def AfficheTexteCommande(self, sortie=sys.stdout):
        """
        Methode : ETAPE.AfficheTexteCommande
        Intention : afficher sur la sortie standard (par defaut) le cartouche de
                        la commande avant son execution.
        """
        from Utilitai.Utmess import UTMESS
        voir = not isinstance(self.parent, MACRO_ETAPE) or \
            self.jdc.impr_macro == 1 or self.parent.show_children
        # top départ du chrono de la commande
        etiq = self.nom
        # id unique pour l'étape. L'attribut n'est pas déclaré dans
        # l'__init__...
        count = (self.icmd or 0)
        self.id_timer = str(time.time() + count)
        if isinstance(self.parent, MACRO_ETAPE):
            etiq = ' . ' + etiq
        if voir:
            self.jdc.timer.Start(self.id_timer, name=etiq)

        # impression du fichier .code : compte rendu des commandes et
        # mots clés activés par l'ETAPE
        if self.jdc.fico != None:
            fcode = CodeVisitor(self.jdc.fico)
            self.accept(fcode)
            aster.affiche('CODE', fcode.get_text())

        if voir:
            # Affichage numero de la commande (4 digits)
            if self.sd != None:
                type_concept = self.sd.__class__.__name__
            else:
                type_concept = '-'

            UTMESS('I', 'VIDE_1')
            UTMESS('I', 'SUPERVIS2_70')
            if self.icmd != None:
                UTMESS('I', 'SUPERVIS2_71', vali=self.icmd, valk=type_concept)
                UTMESS('I', 'SUPERVIS2_70')
            else:
                # commande non comptabilisée (INCLUDE)
                UTMESS('I', 'SUPERVIS2_72', valk=type_concept)

            # recuperation du texte de la commande courante
            if self.jdc.ctree:
                self.accept(self.jdc.ctree)
            cmdtext = CommandTextVisitor()
            self.accept(cmdtext)
            aster.affiche('MESSAGE', convert(cmdtext.get_text()))

        return
예제 #16
0
def commun_DEBUT_POURSUITE(jdc, PAR_LOT, IMPR_MACRO, CODE, DEBUG, IGNORE_ALARM,
                           LANG, INFO):
    """Fonction sdprod partie commune à DEBUT et POURSUITE.
    (on stocke un entier au lieu du logique)
    """
    global ipass
    ipass += 1
    # deux passages: build et exec
    if ipass > 2 and aster_exists:
        UTMESS('F', 'SUPERVIS_2')
    jdc.set_par_lot(PAR_LOT, user_value=True)
    jdc.impr_macro = int(IMPR_MACRO == 'OUI')
    jdc.jxveri = int(CODE != None
                     or (DEBUG != None and DEBUG['JXVERI'] == 'OUI'))
    jdc.sdveri = int(DEBUG != None and DEBUG['SDVERI'] == 'OUI')
    jdc.fico = None
    jdc.sd_checker = CheckLog()
    jdc.info_level = INFO
    jdc.hist_etape = (DEBUG != None and DEBUG['HIST_ETAPE'] == 'OUI')
    if CODE != None:
        jdc.fico = 'TEST'
    if aster_exists:
        if LANG:
            from code_aster.Cata.Syntax import tr
            from Execution.i18n import localization
            translation = localization.install(LANG)
            tr.set_translator(translation.ugettext)
        # pb en cas d'erreur dans FIN : appeler reset_print_function dans traiter_fin_exec ?
        # from functools import partial
        # asprint = partial(aster.affiche, 'MESSAGE')
        # message.register_print_function(asprint)
        # ne faire qu'une fois
        if not hasattr(jdc, 'msg_init'):
            # messages d'alarmes désactivés
            if IGNORE_ALARM:
                if not type(IGNORE_ALARM) in (list, tuple):
                    IGNORE_ALARM = [IGNORE_ALARM]
                for idmess in IGNORE_ALARM:
                    MessageLog.disable_alarm(idmess)
        # en POURSUITE, conserver le catalogue de comportement picklé
        if not hasattr(jdc, 'catalc'):
            from Comportement import catalc
            jdc.catalc = catalc
        # ne faire qu'une fois
        if not hasattr(jdc, 'msg_init') and jdc.syntax_check():
            if jdc.par_lot == 'NON':
                UTMESS('A', 'SUPERVIS_11')
                raise EOFError("can not check syntax with PAR_LOT='NON'.")
            else:
                UTMESS('I', 'SUPERVIS_10')
        jdc.msg_init = True
예제 #17
0
def _print_alarm():
    """Emet une alarme en cas de modification de la version du dépôt"""
    from Utilitai.Utmess import UTMESS
    changes = aster_pkginfo.version_info.changes
    uncommitted = aster_pkginfo.version_info.uncommitted
    if changes:
        UTMESS('I', 'SUPERVIS_41', valk=__version__, vali=changes)
    if uncommitted and type(uncommitted) is list:
        fnames = ', '.join(uncommitted)
        UTMESS(
            'A',
            'SUPERVIS_42',
            valk=(aster_pkginfo.version_info.parentid, fnames),
        )
예제 #18
0
    def calcul_F(self, val):
        """
           Calcul de F
        """
        UTMESS('I', 'RECAL0_25', valk=self.Affiche_Param(val))

        # Reset les variables deja calculees par les calculs precedents
        self.reset()

        # Calcul pour le jeu de parametre val
        fonctionnelle, gradient = self.calcul_Aster(val, dX=None)

        # Calcul de l'erreur par rapport aux donnees experimentale
        E = CALC_ERROR(
            experience=self.RESU_EXP,
            X0=val,
            calcul=self.RESU_CALC,
            poids=self.Simul.poids,
            objective_type='vector',
            info=self.INFO,
        )
        self.erreur = E.CalcError(self.Lcalc)

        # norme de l'erreur
        self.norme = NP.sum([x ** 2 for x in self.erreur])

        if debug:
            print "self.reponses=", self.reponses
            print "F=", E.F
            print "L_J=", E.L_J
            print "L_J_init=", E.L_J_init
            print "J=", E.J
            print 'erreur=', self.erreur
            print "norme de l'erreur=", self.norme
            print "norme de J (fonctionnelle)=", str(E.J)

        if self.INFO >= 2:
            UTMESS('I', 'RECAL0_30')
            if self.evaluation_fonction > 1:
                UTMESS('I', 'RECAL0_39', valk=str(self.evaluation_fonction))

        if self.vector_output:
            if self.INFO >= 2:
                UTMESS('I', 'RECAL0_35', valr=self.norme)
            return self.erreur
        else:
            if self.INFO >= 2:
                UTMESS('I', 'RECAL0_36', valr=self.norme)
            return self.norme
예제 #19
0
    def __salomeParam(self, param):
        """
        Construit les paramètres salome à partir des paramètres Stanley
        retourne {} si incorrect
        """
        result = {}
        try:
            if param['mode'] == 'LOCAL':
                lst = ['tmp']
                try:
                    amachineName = param['machine_salome']
                except:
                    UTMESS('A', 'STANLEY_15')
                    return {}

                result['machineName'] = amachineName
            elif param['mode'] == 'DISTANT':
                lst = ['machine_salome', 'tmp']
                key = 'machine_salome'
                amachineName = param[key]
                result['machineName'] = amachineName
            else:
                raise _(
                    "Erreur MODE non implémenté, choix possible : LOCAL, DISTANT")

            # Verifications
            for var in lst:
                if not param[var].strip():
                    UTMESS('A', 'STANLEY_16', valk=[var])
                    return {}

            # Construction du paramètre 'ORBInitRef'
            key = 'machine_salome_port'
            nsPort = param[key]
            if not nsPort:
                UTMESS('A', 'STANLEY_17')
                return {}
            aORBInitRef = 'NameService=corbaname::%s:%s' % (
                amachineName, nsPort)
            result['ORBInitRef'] = aORBInitRef

        except KeyError:
            UTMESS('A', 'STANLEY_16', valk=[key])
            return {}
        except:
            return {}

        return result
예제 #20
0
    def affiche_calcul_etat_final(self, para, Hessien, valeurs_propres,
                                  vecteurs_propres, sensible, insensible):
        """ Affichage des informations de l'optimisation (valeurs propres, vecteurs propres, etc.)
        """
        UTMESS('I',
               'RECAL0_60',
               valk=str(valeurs_propres),
               files=self.get_filename())
        UTMESS('I',
               'RECAL0_61',
               valk=str(vecteurs_propres),
               files=self.get_filename())
        UTMESS('I', 'RECAL0_62', files=self.get_filename())

        if (len(sensible) != 0 or len(insensible) != 0):
            UTMESS('I', 'RECAL0_63', files=self.get_filename())

        # Parametres sensibles
        if (len(sensible) != 0):
            UTMESS('I', 'RECAL0_64', files=self.get_filename())
            k = 0
            for i in sensible:
                k = k + 1
                colonne = vecteurs_propres[:, i]
                numero = NP.nonzero(
                    NP.greater(abs(colonne / max(abs(colonne))), 1.E-1))[0]
                txt = '\n   ' + str(k) + ') '
                for j in numero:
                    txt += '%+3.1E ' % colonne[j] + '* ' + para[j] + ' '
                UTMESS('I',
                       'RECAL0_65',
                       valk=(txt, str(valeurs_propres[i])),
                       files=self.get_filename())

        # Parametres insensibles
        if (len(insensible) != 0):
            UTMESS('I', 'RECAL0_66', files=self.get_filename())
            k = 0
            for i in insensible:
                k = k + 1
                colonne = vecteurs_propres[:, i]
                numero = NP.nonzero(
                    NP.greater(abs(colonne / max(abs(colonne))), 1.E-1))[0]
                txt = '\n   ' + str(k) + ') '
                for j in numero:
                    txt += '%+3.1E ' % colonne[j] + '* ' + para[j] + ' '
                UTMESS('I',
                       'RECAL0_65',
                       valk=(txt, str(valeurs_propres[i])),
                       files=self.get_filename())

        if (len(sensible) != 0 or len(insensible) != 0):
            UTMESS('I', 'RECAL0_62', files=self.get_filename())
예제 #21
0
    def __Show(self, medFilePath, medInfo, entity, visuType, salomeParam):
        """
        Lecture d'un fichier MED par le composant VISU de SALOME.

        @type     medFilePath : string
        @param  medFilePath:  chemin du fichier MED. Le chemin medFileName doit etre sur la meme machine que le composant VISU

        @type     medInfo:  class
        @param  medInfo:  informations sur le fichier MED ( meshName, fieldName, iteration )

        @type     entity: object ?
        @param  entity:  type d'entité

        @type     visuType :     integer
        @param  visuType:      type de visualisation

        @type     salomeParam:  dictionary.
        @param  salomeParam:  parametre Salome pour initialistion composant VISU de pylotage
        """

        try:
            salomeVisu = Visu.Visu(**salomeParam)
        except Exception, e:
            UTMESS('A', 'STANLEY_19', valk=[salomeParam['machineName']])
            raise _("Erreur lors de la visualisation.\n\nParametres Salome :%s\n\nErreur :\n%s\n\n") % (
                salomeParam, e)
예제 #22
0
    def __init_distant(self):
        """
        Stanley fonctionne sur une machine distante de l'utilisateur.
        Il faut rapatrier le fichier sur la machine contenant salome.
        """
        result = False
        fichier = os.path.basename(self.fichier)

        mdis = self.param['machine_salome']
            # machine
        fdis        = self.param['tmp'] + '/' + fichier + \
            '.pos'                     # /tmp/fort.33.pos
        fmdis       = self.param['machine_salome_login'] + \
            '@' + mdis + ":" + fdis   # user@machine:/tmp/fort.33.pos

        # Protocole de recopie et d'execution distante
        copie = self.param['protocole'].split(
            '/')[0]                            # rcp ou scp

        # Copie du fichier
        cmd = copie + " " + fichier + " " + fmdis
        UTMESS('I', 'STANLEY_9', valk=[cmd])
        code, output = commands.getstatusoutput(cmd)
        if code != 0:
            raise _("Erreur exécution commande : ") + cmd

        self.fichier = fdis
예제 #23
0
 def Valeurs(self):
     """
     Retourne deux listes de valeurs : abscisses et ordonnees
     """
     from Utilitai.Utmess import UTMESS
     if self.accessible():
         vale = '%-19s.VALE' % self.get_name()
         lbl = self.sdj.VALE.get()
         if lbl == None:
             UTMESS('F', 'SDVERI_2', valk=[vale])
         lbl = list(lbl)
         dim = len(lbl) / 2
         lx = lbl[0:dim]
         ly = lbl[dim:2 * dim]
     elif hasattr(self, 'etape') and self.etape.nom == 'DEFI_FONCTION':
         if self.etape['VALE'] is not None:
             lbl = list(self.etape['VALE'])
             dim = len(lbl)
             lx = [lbl[i] for i in range(0, dim, 2)]
             ly = [lbl[i] for i in range(1, dim, 2)]
         elif self.etape['VALE_PARA'] is not None:
             lx = self.etape['VALE_PARA'].Valeurs()
             ly = self.etape['VALE_FONC'].Valeurs()
         elif self.etape['ABSCISSE'] is not None:
             lx = self.etape['ABSCISSE']
             ly = self.etape['ORDONNEE']
         else:
             raise AsException("Erreur (fonction.Valeurs) : ne fonctionne en "
                               "PAR_LOT='OUI' que sur des fonctions produites "
                               "par DEFI_FONCTION dans le jdc courant.")
     else:
         raise AsException("Erreur (fonction.Valeurs) : ne fonctionne en "
                           "PAR_LOT='OUI' que sur des fonctions produites "
                           "par DEFI_FONCTION dans le jdc courant.")
     return [lx, ly]
예제 #24
0
 def Parametres(self):
     """
     Retourne un dictionnaire contenant les parametres de la nappe,
     le type jeveux (NAPPE) n'est pas retourne,
     le dictionnaire peut ainsi etre fourni a CALC_FONC_INTERP tel quel,
     et une liste de dictionnaire des parametres de chaque fonction.
     """
     from Utilitai.Utmess import UTMESS
     if not self.accessible():
         raise AsException(
             "Erreur dans nappe.Parametres en PAR_LOT='OUI'")
     TypeProl = {'E': 'EXCLU', 'L': 'LINEAIRE', 'C': 'CONSTANT'}
     objev = '%-19s.PROL' % self.get_name()
     prol = aster.getvectjev(objev)
     if prol == None:
         UTMESS('F', 'SDVERI_2', valk=[objev])
     dico = {
         'INTERPOL': [prol[1][0:3], prol[1][4:7]],
        'NOM_PARA': prol[2][0:16].strip(),
        'NOM_RESU': prol[3][0:16].strip(),
        'PROL_DROITE': TypeProl[prol[4][1]],
        'PROL_GAUCHE': TypeProl[prol[4][0]],
        'NOM_PARA_FONC': prol[6][0:4].strip(),
     }
     lparf = []
     nbf = (len(prol) - 7) / 2
     for i in range(nbf):
         dicf = {
             'INTERPOL_FONC': [prol[7 + i * 2][0:3], prol[7 + i * 2][4:7]],
            'PROL_DROITE_FONC': TypeProl[prol[8 + i * 2][1]],
            'PROL_GAUCHE_FONC': TypeProl[prol[8 + i * 2][0]],
         }
         lparf.append(dicf)
     return [dico, lparf]
예제 #25
0
 def Valeurs(self):
     """
     Retourne trois listes de valeurs : abscisses, parties reelles et imaginaires.
     """
     from Utilitai.Utmess import UTMESS
     if self.accessible():
         vale = '%-19s.VALE' % self.get_name()
         lbl = self.sdj.VALE.get()
         if lbl == None:
             UTMESS('F', 'SDVERI_2', valk=[vale])
         lbl = list(lbl)
         dim = len(lbl) / 3
         lx = lbl[0:dim]
         lr = []
         li = []
         for i in range(dim):
             lr.append(lbl[dim + 2 * i])
             li.append(lbl[dim + 2 * i + 1])
     elif hasattr(self, 'etape') and self.etape.nom == 'DEFI_FONCTION' \
             and self.etape['VALE_C'] is not None:
         lbl = list(self.etape['VALE_C'])
         dim = len(lbl)
         lx = [lbl[i] for i in range(0, dim, 3)]
         lr = [lbl[i] for i in range(1, dim, 3)]
         li = [lbl[i] for i in range(2, dim, 3)]
     else:
         raise AsException("Erreur (fonction_c.Valeurs) : ne fonctionne en "
                           "PAR_LOT='OUI' que sur des fonctions produites "
                           "par DEFI_FONCTION dans le jdc courant.")
     return [lx, lr, li]
예제 #26
0
def Sortie(LIST_NOM_PARA, LIST_PARA, val, CALCUL_ASTER, Mess):
    """ Sortie de la macro, on renvoie les parametres obtenus """

    import aster
    import Macro
    from code_aster.Cata.Commands import DEFI_LIST_REEL
    from code_aster.Cata.Syntax import _F
    from Macro import reca_message
    from Macro import reca_algo
    from Macro import reca_interp
    from Macro import reca_utilitaires
    from Macro import reca_calcul_aster
    from Macro.reca_controles import gestion
    from Utilitai.Utmess import UTMESS, MessageLog

    UTMESS('I', 'RECAL0_39', valk=str(CALCUL_ASTER.evaluation_fonction),
           files=Mess.get_filename())

    LIST_NOM_PARA_ALPHA = [para[0] for para in LIST_PARA]
    LIST_NOM_PARA_ALPHA.sort()
    lival = []
    for i in LIST_NOM_PARA:
        lival.append(val[LIST_NOM_PARA_ALPHA.index(i)])
    nomres = DEFI_LIST_REEL(VALE=lival)

    return nomres
예제 #27
0
    def orientation_cara_elem(self, ):
        """
            Récupération des orientations des poutres
        """
        dic_gma = {}
        etapes = self.CARA_ELEM.etape.valeur

        if not etapes.has_key('ORIENTATION'):
            return dic_gma

        orientation = tolist(etapes['ORIENTATION'])

        for ll in orientation:
            cara = ll['CARA']
            if cara in ['ANGL_VRIL', 'ANGL_NAUT', 'VECT_Y']:
                if ll.has_key('GROUP_MA'):
                    group_ma = tolist(ll['GROUP_MA'])
                    a = ll['VALE']
                    for gr in group_ma:
                        if not dic_gma.has_key(gr):
                            dic_gma[gr] = {}
                        dic_gma[gr][cara] = a

        for gr in dic_gma.keys():
            if not dic_gma[gr].has_key('VECT_Y'):
                if not dic_gma[gr].has_key('ANGL_VRIL'):
                    dic_gma[gr]['ANGL_VRIL'] = 0.0
                if dic_gma[gr].has_key('ANGL_NAUT'):
                    UTMESS('F', 'PLEXUS_10')
        return dic_gma
예제 #28
0
    def Calc_erreur(champ, contexte, numeros, phenomene, options=None):

        para = {
            'reuse': contexte.resultat,
            'RESULTAT': contexte.resultat,
            'MODELE': contexte.modele,
            #'OPTION'       : champ.nom,
            'CHAM_MATER': contexte.cham_mater,
            'NUME_ORDRE': tuple(numeros),
            phenomene: champ.nom
        }

        if contexte.cara_elem:
            para['CARA_ELEM'] = contexte.cara_elem

        # Options supplementaires passees a la commande
        if options:
            for cle in options.keys():
                para[cle] = options[cle]

        # Lancement de la commande
        try:
            CALC_ERREUR(**para)
        except aster.error, err:
            UTMESS('A', 'STANLEY_4', valk=[str(err)])
예제 #29
0
def vmis_isot_trac(donnees, para, para_epx, type_para, l_para, l_vale):
    """
        Transforme la fonction associée au paramètre SIGM de TRACTION afin
        d'obtenir les données attendues par EPX pour les mots-clés
        ELAS et TRAC du matériau VMIS ISOT.
    """
#   ajout des mots-clés
    l_para.extend(para_epx)
#   recuperation de la fonction associé à SIGM
    car_temp = donnees[para]
    val = car_temp.Valeurs()
    eps = val[0]
    sigm = val[1]
#   verif de la compatibilité de eps[0] et sigm[0] avec E
    if l_para[0][:4] != 'YOUN':
        raise Exception('Erreur de programmation')
    E = l_vale[0]
    diff = abs(sigm[0] / E - eps[0])
    if diff > 0.001 * eps[0]:
        nom_fonc = car_temp.get_name()
        UTMESS('F', 'PLEXUS_40', valk=[
               nom_fonc, para], valr=[sigm[0] / E, eps[0]])
    # ajout de la valeur de ELAS (limite élastique)
    l_vale.append(sigm[0])
    # préparation des valeurs de trac
    nb = len(eps)
    trac = [nb, ]
    for i in range(nb):
        trac.extend([sigm[i], eps[i]])
    l_vale.append(trac)

    return l_para, l_vale
예제 #30
0
 def executeCommand(self, capture=True, silent=False):
     """Execute the program"""
     cmd = self.cmdBuilder.build([self.prog] + self.args, self.shell)
     output, error, exitCode = self.executeCmdLine(cmd, capture, silent)
     ok = self.isOk(exitCode)
     # print the output
     if self.debug or not silent:
         UTMESS('I', 'EXECLOGICIEL0_11', vali=[self.exitCodeMax, exitCode])
         if capture:
             UTMESS('I', 'EXECLOGICIEL0_9', valk=output)
     # print error in debug mode or if it failed
     if (self.debug or not ok) and capture:
         UTMESS('I', 'EXECLOGICIEL0_10', valk=error, print_as='E')
     # error
     if not ok:
         UTMESS('F', 'EXECLOGICIEL0_3', vali=[self.exitCodeMax, exitCode])