2 # -*- coding: iso-8859-1 -*-
4 import os, sys, shutil, tempfile, glob
16 #===============================================================================
17 def UTMESS(code='I', txt=''):
19 if code=='F': sys.exit()
21 #===============================================================================
22 def get_tables(tables_calc,tmp_repe_table,prof):
23 """ Recupere les resultats Aster (Table Aster -> Numeric Python)
27 assert (tables_calc is not None)
28 assert (tmp_repe_table is not None)
30 # Import du module lire_table
31 if os.environ.has_key('ASTER_ROOT'):
32 version = prof['version'][0]
33 bibpyt = os.path.join(os.environ['ASTER_ROOT'], version, 'bibpyt')
34 sys.path.append(bibpyt)
35 for mdl in glob.glob(os.path.join(bibpyt, '*')):
36 sys.path.append(os.path.join(os.environ['ASTER_ROOT'], version, 'bibpyt', mdl))
38 from lire_table_ops import lecture_table
40 UTMESS('F', "Impossible d'importer le module lire_table!")
42 reponses = tables_calc
44 _TB = [None]*len(reponses)
45 for i in range(len(reponses)):
46 _fic_table = tmp_repe_table + os.sep + "fort."+str(int(100+i))
49 file=open(_fic_table,'r')
52 except Exception, err:
54 message = "Erreur 1!\n" + str(err)
58 table_lue = lecture_table(texte, 1, ' ')
59 list_para = table_lue.para
60 tab_lue = table_lue.values()
61 except Exception, err:
63 message = "Erreur 2!\n" + str(err)
67 if ier!=0 : UTMESS('F', message)
70 nb_val = len(tab_lue[ list_para[0] ])
71 F = Numeric.zeros((nb_val,2), Numeric.Float)
72 for k in range(nb_val):
73 F[k][0] = tab_lue[ str(reponses[i][1]) ][k]
74 F[k][1] = tab_lue[ str(reponses[i][2]) ][k]
76 except Exception, err:
77 message = "Erreur 3!\n" + str(err)
80 if debug: print 'resu_calc:', resu_calc
83 #===============================================================================
86 #===============================================================================
87 def Calcul_Aster_Ponctuel( X0 = None ):
98 if type(X0) is type(numpy.matrix([])):
102 # ----------------------------------------------------------------------------
104 #isFromYacs = globals().get('ASTER_ROOT', None) # execution via YACS ou en externe
105 #isFromYacs = ASTER_ROOT
106 #print "isFromYacs:", isFromYacs
108 # from N_Parameters import ASTER_ROOT, debug, SOURCES_ROOT, DISPLAY
109 # from N_Study_Parameters import export
110 # from N_MR_Parameters import calcul, parametres
111 os.environ['ASTER_ROOT'] = ASTER_ROOT
113 # ----------------------------------------------------------------------------
114 # Repertoire contenant les resultats des calculs Aster (None = un rep temp est cree)
115 resudir = globals().get('resudir', None)
117 # ----------------------------------------------------------------------------
118 # Parametres remis en forme
119 list_params = [x[0] for x in parametres]
122 # ----------------------------------------------------------------------------
123 # Procedure de calculs distribues
125 # Import des modules python d'ASTK
126 astk_serv_root = os.path.join(ASTER_ROOT, 'ASTK', 'ASTK_SERV')
127 sys.path.append(os.path.join(astk_serv_root, 'lib'))
128 sys.path.append(os.path.join(ASTER_ROOT, 'lib', python_version, 'site-packages'))
132 from asrun.run import AsRunFactory
133 from asrun.profil import ASTER_PROFIL
134 from asrun.common_func import get_hostrc
135 from asrun.utils import get_timeout
136 from asrun.parametric import is_list_of_dict
137 from asrun.thread import Dispatcher
138 from asrun.distrib import DistribParametricTask
141 UTMESS('F', "Impossible de determiner l'emplacement d'Aster ! Fixer le chemin avec la variable d'environnement ASTER_ROOT.")
143 # Import des modules supplementaires
144 sys.path.insert(0, SOURCES_ROOT)
145 sys.path.insert(0, os.path.join(SOURCES_ROOT, 'sources'))
150 if not os.path.isdir(resudir):
151 try: os.mkdir(resudir)
153 UTMESS('A', "Impossible de creer le repertoire : %s. On utilise un repertoire temporaire" % resudir)
155 if not resudir: resudir = tempfile.mkdtemp(prefix='tmp_macr_recal_')
156 flashdir = os.path.join(resudir,'flash')
157 UTMESS('I', "\n ASTER Exécution simple\n Répertoire temporaire de résultats : %s" % resudir)
163 prof = ASTER_PROFIL(filename=export)
164 #prof = init_profil_from(run, prof, keep_surch=True)
166 'type' : 'repe', 'isrep' : True, 'ul' : 0, 'compr' : False,
167 'path' : '/tmp/test_param' })
170 prof.WriteExportTo( os.path.join(resudir, 'master.export') )
173 hostrc = get_hostrc(run, prof)
175 # timeout before rejected a job
176 timeout = get_timeout(prof)
182 # Dictionnaire des parametres du point courant
183 dic = dict( zip( list_params, X0 ) )
184 list_val.append( dic )
186 assert is_list_of_dict(list_val)
187 nbval = len(list_val)
190 # Ajout des impressions de tables a la fin du .comm
193 for i in range(len(reponses)):
194 _ul = str(int(100+i))
197 try: os.remove( tmp_macr_recal+os.sep+"REPE_TABLE"+os.sep+"fort."+_ul )
200 t.append("\n# Recuperation de la table : " + str(reponses[i][0]) + "\n")
201 t.append("DEFI_FICHIER(UNITE=" + num_ul + ", FICHIER='" + os.path.join('.', 'REPE_OUT', 'fort.'+_ul) + "',);\n" )
202 t.append("IMPR_TABLE(TABLE="+str(reponses[i][0])+", FORMAT='ASTER', UNITE="+num_ul+", INFO=1, FORMAT_R='E30.20',);\n")
203 t.append("DEFI_FICHIER(ACTION='LIBERER', UNITE="+num_ul+",);\n")
206 # number of threads to follow execution
209 # ----- Execute calcutions in parallel using a Dispatcher object
211 task = DistribParametricTask(run=run, prof=prof, # IN
213 nbmaxitem=0, timeout=timeout,
214 resudir=resudir, flashdir=flashdir,
215 keywords={'POST_CALCUL': '\n'.join(t)},
217 nbnook=0, exec_result=[]) # OUT
218 # ... and dispatch task on 'list_tests'
219 etiq = 'calc_%%0%dd' % (int(log10(nbval)) + 1)
220 labels = [etiq % (i+1) for i in range(nbval)]
221 couples = zip(labels, list_val)
222 execution = Dispatcher(couples, task, numthread=numthread)
229 # Recuperation des tables calculees
237 tbl = get_tables(tables_calc=list_calc, tmp_repe_table=os.path.join(resudir, c, 'REPE_OUT'), prof=prof)
242 # print 'AA1:', array
244 FX.extend([ x[0] for x in array ])
245 FY.extend([ x[1] for x in array ])
246 ldims.append(len(array))
248 # Agregation des resultats
251 seq_DIMS.append(ldims)
255 # Liste des diagnostics
257 for result in task.exec_result:
261 lst_DIAG = [ d_diag[label] for label in labels]
265 print "list_calc =",list_calc
266 print "seq_FX =",seq_FX
267 print "seq_FY =",seq_FY
268 print "seq_DIMS =",seq_DIMS
269 print "lst_DIAG =",lst_DIAG
270 print "lst_iter =",lst_iter
273 # ----------------------------------------------------------------------------
274 # Procedure d'assemblage du gradient
276 # Calcul maitre (point X0)
277 idx0 = lst_iter.index(0) # index (les calculs arrivent-ils dans le desordre?)
281 # Arret si tous les jobs ne se sont pas deroules correctement
282 for diag in lst_DIAG:
283 if not diag[0:2] in ['OK', '<A']:
284 raise ValueError("Au moins un calcul ne s'est pas deroule normalement")
287 print "\nH_de_X (calcul ponstuel) au point X0: \n%s" % str(H_de_X)
291 #===============================================================================
292 def Calcul_Aster_Jacobienne( X0 = None ):
299 global python_version
302 if type(X0) is type(numpy.matrix([])):
306 # ----------------------------------------------------------------------------
308 dX = globals().get('dX', [ x*FacteurdX for x in X0 ]) # execution via YACS ou en externe
309 # dX = globals().get('dX', [ 0.1, 0.1, 0.001]) # execution via YACS ou en externe
310 # ----------------------------------------------------------------------------
312 #isFromYacs = globals().get('ASTER_ROOT', None) # execution via YACS ou en externe
314 # from N_Parameters import ASTER_ROOT, debug, SOURCES_ROOT, DISPLAY
315 # from N_Study_Parameters import export
316 # from N_MR_Parameters import calcul, parametres
317 os.environ['ASTER_ROOT'] = ASTER_ROOT
319 # ----------------------------------------------------------------------------
320 # Repertoire contenant les resultats des calculs Aster (None = un rep temp est cree)
321 resudir = globals().get('resudir', None)
323 # ----------------------------------------------------------------------------
324 # Parametres remis en forme
325 list_params = [x[0] for x in parametres]
328 # ----------------------------------------------------------------------------
329 # Procedure de calculs distribues
331 # Import des modules python d'ASTK
332 astk_serv_root = os.path.join(ASTER_ROOT, 'ASTK', 'ASTK_SERV')
333 sys.path.append(os.path.join(astk_serv_root, 'lib'))
334 sys.path.append(os.path.join(ASTER_ROOT, 'lib', python_version, 'site-packages'))
338 from asrun.run import AsRunFactory
339 from asrun.profil import ASTER_PROFIL
340 from asrun.common_func import get_hostrc
341 from asrun.utils import get_timeout
342 from asrun.parametric import is_list_of_dict
343 from asrun.thread import Dispatcher
344 from asrun.distrib import DistribParametricTask
347 UTMESS('F', "Impossible de determiner l'emplacement d'Aster ! Fixer le chemin avec la variable d'environnement ASTER_ROOT.")
349 # Import des modules supplementaires
350 sys.path.insert(0, SOURCES_ROOT)
351 sys.path.insert(0, os.path.join(SOURCES_ROOT, 'sources'))
356 if not os.path.isdir(resudir):
357 try: os.mkdir(resudir)
359 UTMESS('A', "Impossible de creer le repertoire : %s. On utilise un repertoire temporaire" % resudir)
361 if not resudir: resudir = tempfile.mkdtemp(prefix='tmp_macr_recal_')
362 flashdir = os.path.join(resudir,'flash')
363 UTMESS('I', "\n ASTER Exécutions multiples\n Répertoire temporaire de résultats : %s" % resudir)
369 prof = ASTER_PROFIL(filename=export)
370 #prof = init_profil_from(run, prof, keep_surch=True)
372 'type' : 'repe', 'isrep' : True, 'ul' : 0, 'compr' : False,
373 'path' : '/tmp/test_param' })
376 prof.WriteExportTo( os.path.join(resudir, 'master.export') )
379 hostrc = get_hostrc(run, prof)
381 # timeout before rejected a job
382 timeout = get_timeout(prof)
388 # Dictionnaire des parametres du point courant
389 dic = dict( zip( list_params, X0 ) )
390 list_val.append( dic )
392 # Dictionnaires des parametres des calculs esclaves (perturbations des differences finies)
393 for n in range(1,len(dX)+1):
396 X = [ X0[i] + l[i] for i in range(len(dX)) ]
397 dic = dict( zip( list_params, X ) )
398 list_val.append( dic )
400 assert is_list_of_dict(list_val)
401 nbval = len(list_val)
404 # Ajout des impressions de tables a la fin du .comm
407 for i in range(len(reponses)):
408 _ul = str(int(100+i))
411 try: os.remove( tmp_macr_recal+os.sep+"REPE_TABLE"+os.sep+"fort."+_ul )
414 t.append("\n# Recuperation de la table : " + str(reponses[i][0]) + "\n")
415 t.append("DEFI_FICHIER(UNITE=" + num_ul + ", FICHIER='" + os.path.join('.', 'REPE_OUT', 'fort.'+_ul) + "',);\n" )
416 t.append("IMPR_TABLE(TABLE="+str(reponses[i][0])+", FORMAT='ASTER', UNITE="+num_ul+", INFO=1, FORMAT_R='E30.20',);\n")
417 t.append("DEFI_FICHIER(ACTION='LIBERER', UNITE="+num_ul+",);\n")
420 # number of threads to follow execution
423 # ----- Execute calcutions in parallel using a Dispatcher object
425 task = DistribParametricTask(run=run, prof=prof, # IN
427 nbmaxitem=0, timeout=timeout,
428 resudir=resudir, flashdir=flashdir,
429 keywords={'POST_CALCUL': '\n'.join(t)},
431 nbnook=0, exec_result=[]) # OUT
432 # ... and dispatch task on 'list_tests'
433 etiq = 'calc_%%0%dd' % (int(log10(nbval)) + 1)
434 labels = [etiq % (i+1) for i in range(nbval)]
435 couples = zip(labels, list_val)
436 execution = Dispatcher(couples, task, numthread=numthread)
443 # Recuperation des tables calculees
451 tbl = get_tables(tables_calc=list_calc, tmp_repe_table=os.path.join(resudir, c, 'REPE_OUT'), prof=prof)
456 # print 'AA1:', array
458 FX.extend([ x[0] for x in array ])
459 FY.extend([ x[1] for x in array ])
460 ldims.append(len(array))
462 # Agregation des resultats
465 seq_DIMS.append(ldims)
469 # Liste des diagnostics
471 for result in task.exec_result:
475 lst_DIAG = [ d_diag[label] for label in labels]
479 print "list_calc =",list_calc
480 print "seq_FX =",seq_FX
481 print "seq_FY =",seq_FY
482 print "seq_DIMS =",seq_DIMS
483 print "lst_DIAG =",lst_DIAG
484 print "lst_iter =",lst_iter
488 # ----------------------------------------------------------------------------
489 # Procedure d'assemblage du gradient
491 # Calcul maitre (point X0)
492 idx0 = lst_iter.index(0) # index (les calculs arrivent-ils dans le desordre?)
496 # Arret si tous les jobs ne se sont pas deroules correctement
497 for diag in lst_DIAG:
498 if not diag[0:2] in ['OK', '<A']:
499 raise ValueError("Au moins un calcul ne s'est pas deroule normalement")
501 # Calcul du gradient (une liste de liste)
502 Gradient_de_H_en_X = []
504 for n in range(len(lst_iter))[1:]:
505 idx = lst_iter.index(n)
507 col = [ -(y-x)/dX[idx-1] for x, y in zip(FY, FY_X0) ]
508 Gradient_de_H_en_X.append(col)
509 if debug: print 'Calcul numero: %s - Diagnostic: %s' % (n, lst_DIAG[idx])
512 print "\nCalcul H au point X0: \n%s" % str(H_de_X)
514 print "\nGradient au point X0:"
515 pprint.pprint(Gradient_de_H_en_X)
517 return Gradient_de_H_en_X
519 #===============================================================================
520 def Calcul_Aster_Adjoint( (X0, dY) ):
524 print "CALCUL ADJOINT"
530 Y0 = numpy.asmatrix(dY).flatten().T
532 Delta_HX = Calcul_Aster_Jacobienne( X0 )
533 Delta_HX = numpy.matrix( Delta_HX )
535 HtY = numpy.dot(Delta_HX, Y0)
538 print "dHX =",Delta_HX