本文整理汇总了Python中pypar.barrier函数的典型用法代码示例。如果您正苦于以下问题:Python barrier函数的具体用法?Python barrier怎么用?Python barrier使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了barrier函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: TestSolveOverlapSpeed
def TestSolveOverlapSpeed():
def timeIt(func):
t1 = time.time()
func()
t2 = time.time()
Print(" Function '%s' took %4.1f s." % (func.func_name, (t2-t1)))
numSolves = 100
Print("")
Print("Now testing multiple S^-1 * psi...")
pyprop.Redirect.Enable(silent=True)
seed(0)
conf = pyprop.Load("config_eigenvalues.ini")
psi = pyprop.CreateWavefunction(conf)
tmpPsi = psi.Copy()
Print(" Size of wavefunction is: %s" % repr(psi.GetData().shape))
#Calculate S^-1 * psi
Print(" Performing %i solves..." % numSolves)
def solve():
for i in range(numSolves):
psi.GetRepresentation().MultiplyOverlap(tmpPsi)
timeIt(solve)
#finish and cleanup
pypar.barrier()
pyprop.Redirect.Disable()
Print("\n...done!")
开发者ID:realblackwisen,项目名称:PyProp,代码行数:32,代码来源:distributed_nonorth_tests.py
示例2: wait
def wait(self, error=False):
'''This method will not return until all process in the environment have called it.
This is a wrapper around MPI_Barrier which handles the case where MPI is not available'''
from inspect import stack
if self.verbose is True:
string = '(%s) Waiting at line %d of %s' % (datetime.datetime.now().strftime('%H:%M:%S'),
stack()[1][0].f_lineno, stack()[1][0].f_code.co_filename)
self.log(string)
if Environment.isParallel:
import pypar
pypar.barrier()
#Because MPI_ABORT doesn't work in pypar if called from one process
#we need a way for process to communicate to each other if an error occurred
#during the code they executed before this barrier. We do a scatter/gather of
#the error parameter - This isn't very efficient but it's all we can do now
errors = self.combineArray([error])
if True in errors:
self.exit(1)
if self.verbose is True:
string = '(%s) Finished waiting' % (datetime.datetime.now().strftime('%H:%M:%S'))
self.log(string)
开发者ID:shambo001,项目名称:peat,代码行数:27,代码来源:Environment.py
示例3: run
def run():
"""
Run the process, handling any parallelisation.
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--config",
help="Configuration file",
type=str)
parser.add_argument("-i", "--inputfile",
help="Input DEM file (ascii format)",
type=str)
parser.add_argument("-o", "--output",
help="Output path",
type=str)
parser.add_argument("-v", "--verbose",
help=("Verbose output (not available when invoking"
"parallel run)") )
args = parser.parse_args()
logfile = 'topomult.log'
loglevel = 'INFO'
if args.verbose:
verbose = args.verbose
else:
verbose = False
if args.config:
cfg = ConfigParser.ConfigParser()
cfg.read(args.config)
input_file = cfg.get('Input', 'Filename')
output_path = cfg.get('Output', 'Path')
logfile = cfg.get('Logging', 'LogFile')
loglevel = cfg.get('Logging', 'LogLevel')
verbose = cfg.get('Logging', 'Verbose')
if args.inputfile:
input_file = args.inputfile
if args.output:
output_path = args.output
attemptParallel()
if pp.size() > 1 and pp.rank() > 0:
logfile += '-' + str(pp.rank())
verbose = False # to stop output to console
flStartLog(logfile, loglevel, verbose)
pp.barrier()
work(input_file, output_path,
['n','s','e','w','ne','nw','se','sw'])
pp.barrier()
pp.finalize()
开发者ID:wcarthur,项目名称:topomultipliers,代码行数:59,代码来源:topomult.py
示例4: barrier
def barrier(self):
"""
Synchronisation point. Makes processors wait until all
processors have reached this point.
"""
if self.is_parallel is True:
import pypar
pypar.barrier()
开发者ID:dynaryu,项目名称:eqrm,代码行数:8,代码来源:parallel.py
示例5: abnormalexit
def abnormalexit(reason):
"""this tells each worker node to exit, then kills the server process.
this should only be called by the server node"""
print 'abnormal exit'
print reason
sendtoall(('Die', 0))
pypar.barrier()
pypar.finalize()
sys.exit(2)
开发者ID:qiuxing,项目名称:corrperm,代码行数:9,代码来源:mpi_nstat.py
示例6: CreatePath
def CreatePath(absFileName):
"""Create directories in abspath
"""
logger = GetFunctionLogger()
if pyprop.ProcId == 0:
filePath = os.path.dirname(absFileName)
if not os.path.exists(filePath) and len(filePath) > 0:
logger.debug("Creating folder: %s" % filePath)
os.makedirs(filePath)
pypar.barrier()
开发者ID:AtomAleks,项目名称:einelektron,代码行数:11,代码来源:tasks.py
示例7: SerialPrint
def SerialPrint(str, proc=-1):
if ProcCount == 1:
print str
else:
if proc==-1: procList = range(ProcCount)
else: procList = [proc]
for i in procList:
if i == ProcId:
print "Proc %4i: %s" % (ProcId, str,)
sys.stdout.flush()
pypar.barrier()
开发者ID:AtomAleks,项目名称:PyProp,代码行数:11,代码来源:__init__.py
示例8: callback
def callback(self, prop):
if self.StoreDuringPropagation:
#create unique filename
filename = "%s_%03i.h5" % (self.OutputFileName.strip(".h5"), self.Counter)
#store current wavefunction and propagation time
prop.SaveWavefunctionHDF(filename, "/wavefunction")
if pyprop.ProcId == 0:
with tables.openFile(filename, "r+", MAX_THREADS=1) as h5:
h5.setNodeAttr("/wavefunction", "prop_time", prop.PropagatedTime)
pypar.barrier()
self.Counter += 1
开发者ID:AtomAleks,项目名称:pyprop-helium,代码行数:13,代码来源:tasks.py
示例9: TestEpetraMatvecSpeed
def TestEpetraMatvecSpeed():
numMatVecs = 500
Print("")
Print("Now testing Epetra matvec speed...")
pyprop.Redirect.Enable(silent=True)
#Test
conf = pyprop.Load("config_propagation.ini")
psi = pyprop.CreateWavefunction(conf)
Print(" Size of wavefunction is: %s" % repr(psi.GetData().shape))
#Setup problem
Print(" Setting up propagator w/potentials...")
prop = SetupProblem(config='config_propagation.ini')
psi = prop.psi
tmpPsi = psi.Copy()
tmpPsi.Clear()
Print(" Local size of wavefunction is: %s" % str(prop.psi.GetData().shape))
Print(" Global size of wavefunction is: %s" % str(prop.psi.GetRepresentation().GetFullShape()))
#Get Epetra potential
#pot = prop.Propagator.BasePropagator.PotentialList[1]
Print(" Number of potentials: %s" % len(prop.Propagator.BasePropagator.PotentialList))
#Calculate S^-1 * psi
Print(" Performing %i matvecs..." % numMatVecs)
def matvecs():
for i in range(numMatVecs):
#pot.MultiplyPotential(psi, tmpPsi, 0, 0)
prop.Propagator.BasePropagator.MultiplyHamiltonianNoOverlap(psi, tmpPsi, 0, 0)
#tmpPsi.GetRepresentation().SolveOverlap(tmpPsi)
timeIt(matvecs)
#finish and cleanup
pypar.barrier()
pyprop.Redirect.Disable()
pyprop.PrintOut("\n...done!")
开发者ID:realblackwisen,项目名称:PyProp,代码行数:40,代码来源:distributed_nonorth_tests.py
示例10: test_lock
def test_lock(Nmpi,fields,pbc_opt=None):
if myrank == 0:
print 'PBC : %s, start' % pbc_opt
mpi.barrier()
for i in xrange(len(fields)):
fields[i][:,:,:6] = 1.
fields[i][:,:,6:] = 0.
#print 'I`m', myrank,'Field %s Direction x1 sum before = '%i,fields[i][:,:,6].sum()
#print 'I`m', myrank,'Field %s Direction x2 sum before = '%i,fields[i][:,:,7].sum()
#print 'I`m', myrank,'Field %s Direction y1 sum before = '%i,fields[i][:,:,8].sum()
#print 'I`m', myrank,'Field %s Direction y2 sum before = '%i,fields[i][:,:,9].sum()
#print 'I`m', myrank,'Field %s Direction z1 sum before = '%i,fields[i][:,:,10].sum()
#print 'I`m', myrank,'Field %s Direction z2 sum before = '%i,fields[i][:,:,11].sum()
mpi.barrier()
if myrank != 0:
targets = MPI.calc_mpitarget(Nmpi, myrank)
targets_pbc = MPI.calc_mpitarget_pbc(Nmpi, myrank, pbc_opt)
message_range = MPI.test_making_message_range()
MPI.test_mpi_exchange(fields, Nmpi, myrank, targets, message_range)
MPI.test_mpi_exchange_pbc(fields, myrank,targets_pbc, message_range, pbc_opt)
for i in xrange(len(fields)):
print 'I`m', myrank,'Field %s Direction x1 sum after = '%i,fields[i][:,:,6].sum()
print 'I`m', myrank,'Field %s Direction x2 sum after = '%i,fields[i][:,:,7].sum()
print 'I`m', myrank,'Field %s Direction y1 sum after = '%i,fields[i][:,:,8].sum()
print 'I`m', myrank,'Field %s Direction y2 sum after = '%i,fields[i][:,:,9].sum()
print 'I`m', myrank,'Field %s Direction z1 sum after = '%i,fields[i][:,:,10].sum()
print 'I`m', myrank,'Field %s Direction z2 sum after = '%i,fields[i][:,:,11].sum()
mpi.barrier()
if myrank == 0:
print 'PBC : %s, Done' % pbc_opt
print
print
print
开发者ID:wbkifun,项目名称:fdtd_accelerate,代码行数:35,代码来源:test_deadlock.py
示例11: main
def main():
# Ensure all Processors are ready
pypar.barrier()
print "Processor %d is ready" % (myid)
# Connect to MySQL db
db = MySQLdb.connect(host="localhost",
user = "root",
passwd = "samsung",
db = "sat")
cur = db.cursor()
# Option parser from wrapper script
parser = optparse.OptionParser()
# PDB
parser.add_option("-p", "--pdb",
help="Choose all or a pdb id",
dest="pdb", default ="all")
# PDB directory
parser.add_option("-d", "--dir",
help="i",
dest="i", default ="all")
parser.add_option("-m", "--mutationList",
help="Location of mutation list file",
dest="m", default="ALA")
(opts, args) = parser.parse_args()
# Run calculations
do_run(opts.pdb, opts.i, cur, db, opts.m)
# Finalize and exit
pypar.finalize()
开发者ID:yongwangCPH,项目名称:peat,代码行数:36,代码来源:ProteinComplexTool_execute.py
示例12: mrmpi
if a+b+c+d != 1.0:
if me == 0: print "ERROR: a,b,c,d must sum to 1"
sys.exit()
if fraction >= 1.0:
if me == 0: print "ERROR: fraction must be < 1"
sys.exit()
random.seed(seed+me)
order = 1 << nlevels
mr = mrmpi()
# loop until desired number of unique nonzero entries
pypar.barrier()
tstart = pypar.time()
niterate = 0
ntotal = (1 << nlevels) * nnonzero
nremain = ntotal
while nremain:
niterate += 1
ngenerate = nremain/nprocs
if me < nremain % nprocs: ngenerate += 1
mr.map(nprocs,generate,None,1)
nunique = mr.collate()
if nunique == ntotal: break
mr.reduce(cull)
nremain = ntotal - nunique
开发者ID:AndreasFetzer,项目名称:VTK,代码行数:30,代码来源:rmat.py
示例13: run_multiple_windfields
def run_multiple_windfields(scenario,
windfield_directory=None,
hazard_output_folder=None,
dircomment=None,
echo=False,
verbose=True):
"""Run volcanic ash impact model for multiple wind fields.
The wind fields are assumed to be in subfolder specified by windfield_directory,
have the extension *.profile and follow the format use with scenarios.
This function makes use of Open MPI and Pypar to execute in parallel but can also run sequentially.
"""
try:
import pypar
except:
P = 1
p = 0
processor_name = os.uname()[1]
print 'Pypar could not be imported. Running sequentially on node %s' % processor_name,
else:
time.sleep(1)
P = pypar.size()
p = pypar.rank()
processor_name = pypar.get_processor_name()
print 'Processor %d initialised on node %s' % (p, processor_name)
pypar.barrier()
if p == 0:
# Put logs along with the results
logdir = os.path.join(hazard_output_folder, 'logs')
makedir(logdir)
header('Hazard modelling using multiple wind fields')
print '* Wind profiles obtained from: %s' % windfield_directory
print '* Scenario results stored in: %s' % hazard_output_folder
print '* Log files:'
t_start = time.time()
# Communicate hazard output directory name to all nodes to ensure they have exactly the same time stamp.
for i in range(P):
pypar.send((hazard_output_folder), i)
else:
# Receive correctly timestamped output directory names
hazard_output_folder = pypar.receive(0)
logdir = os.path.join(hazard_output_folder, 'logs')
try:
name = os.path.splitext(scenario)[0]
except:
name = 'run'
# Wait until log dir has been created
pypar.barrier()
params = get_scenario_parameters(scenario)
# Start processes staggered to avoid race conditions for disk access (otherwise it is slow to get started)
time.sleep(2*p)
# Logging
s = 'Proc %i' % p
print ' %s -' % string.ljust(s, 8),
AIM_logfile = os.path.join(logdir, 'P%i.log' % p)
start_logging(filename=AIM_logfile, echo=False)
# Get cracking
basename, _ = os.path.splitext(scenario)
count_local = 0
count_all = 0
for i, file in enumerate(os.listdir(windfield_directory)):
count_all += 1
# Distribute jobs cyclically to processors
if i%P == p:
if not file.endswith('.profile'):
continue
count_local += 1
windfield = '%s/%s' % (windfield_directory, file)
windname, _ = os.path.splitext(file)
header('Computing event %i on processor %i using wind field: %s' % (i, p, windfield))
if dircomment is None:
dircomment = params['eruption_comment']
#.........这里部分代码省略.........
开发者ID:GeoscienceAustralia,项目名称:PF3D,代码行数:101,代码来源:interface.py
示例14: main
def main():
#--------------------#
# server code
#--------------------#
if rank == 0:
print 'server running on ', procname
opts = task(sys.argv)
opts.printruninfo()
sendtoall(('Start', sys.argv))
server = serverdata(opts)
#set up the collector and generator
start = time.time()
collector = resultcollector(server)
end = time.time()
print end-start
jobs = jobgenerator(server)
numjobsreceived = 0
#begin distributing work
for proc in xrange(1, min(numnodes, jobs.numjobs+1)):
job = jobs.next(proc)
pypar.send(('job',job), proc, tag=OUT)
while numjobsreceived < jobs.jobindex:#while any job is still running
#wait for any node to send a result
msg, status = pypar.receive(pypar.any_source, return_status=True, tag=RETURN)
numjobsreceived += 1
proc, response = msg
if jobs.hasnext(proc):#see if there is more work to be done
job = jobs.next(proc)
pypar.send(('job',job), proc, tag=OUT)#send it to the node that just completed
#combine the results *after* sending the new job
#(this way the worker can proceed while the results are being combined)
collector.collect(response)
#all jobs collected, kill the workers
sendtoall(('Done', 0))
#finish up the computation
collector.finish()
#--------------------#
# worker code
#--------------------#
else:
while True:
start = time.time()
(code, msg), status = pypar.receive(0, return_status=True, tag=OUT)
end = time.time()
print 'waiting', end-start
if code == 'Done':#all work is done
opts.printruninfo()
break
elif code == 'Die':#abnormal exit
break
elif code == 'Start':
opts = task(msg)
sys.stdout = open(opts.logprefix+'%02d.log'%rank, 'w') #logfile
print 'client', rank, 'running on', procname
else:
start = time.time()
jobnum, job = msg
print jobnum
result = opts.dojob(job)#do the job
end = time.time()
print 'working',msg[0], end-start
start = time.time()
pypar.send((rank, (jobnum, result)), 0, tag=RETURN)#return the result to the server
end = time.time()
print 'sending', end-start
#------------------#
#end of parallel code
pypar.barrier()
pypar.finalize()
开发者ID:qiuxing,项目名称:corrperm,代码行数:84,代码来源:mpi_nstat.py
示例15: xrange
print p.rank(), res
if True:
v = [ 2 for i in xrange(10000000) ]
res = p_dot_all(v,v)
#import time
#time.sleep(p.rank()*2+1)
print p.rank(), res
if False:
s = 0
for i in xrange(100):
r = p.rank()
r = broadcast(r)
s += (r + 1)
p.barrier()
print "%d %d" % ( p.rank(), s )
if False:
m = None
v = None
if root():
m = eye_matrix(3000)
v = range(3000)
r = p_mv(m,v)
if root():
print r
if root():
end = p.time()
total = end - start
开发者ID:lelou6666,项目名称:PySOL,代码行数:31,代码来源:mpi.py
示例16: run
def run():
"""
Run the wind multiplier calculations.
This will attempt to run the calculation in parallel by tiling the
domain, but also provides a sane fallback mechanism to execute
in serial.
"""
# add subfolders into path
cmd_folder = os.path.realpath(
os.path.abspath(
os.path.split(
inspect.getfile(
inspect.currentframe()))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
cmd_subfolder1 = pjoin(cmd_folder, "terrain")
if cmd_subfolder1 not in sys.path:
sys.path.insert(0, cmd_subfolder1)
cmd_subfolder2 = pjoin(cmd_folder, "shielding")
if cmd_subfolder2 not in sys.path:
sys.path.insert(0, cmd_subfolder2)
cmd_subfolder3 = pjoin(cmd_folder, "topographic")
if cmd_subfolder3 not in sys.path:
sys.path.insert(0, cmd_subfolder2)
cmd_subfolder4 = pjoin(cmd_folder, "utilities")
if cmd_subfolder4 not in sys.path:
sys.path.insert(0, cmd_subfolder2)
config = ConfigParser.RawConfigParser()
config.read(pjoin(cmd_folder, 'multiplier_conf.cfg'))
root = config.get('inputValues', 'root')
upwind_length = float(config.get('inputValues', 'upwind_length'))
logfile = config.get('Logging', 'LogFile')
logdir = dirname(realpath(logfile))
# If log file directory does not exist, create it
if not isdir(logdir):
try:
os.makedirs(logdir)
except OSError:
logfile = pjoin(os.getcwd(), 'multipliers.log')
loglevel = config.get('Logging', 'LogLevel')
verbose = config.getboolean('Logging', 'Verbose')
attempt_parallel()
if pp.size() > 1 and pp.rank() > 0:
logfile += '_' + str(pp.rank())
verbose = False
else:
pass
fl_start_log(logfile, loglevel, verbose)
# set input maps and output folder
terrain_map = pjoin(pjoin(root, 'input'), "lc_terrain_class.img")
dem = pjoin(pjoin(root, 'input'), "dems1_whole.img")
cyclone_area = pjoin(pjoin(root, 'input'), "cyclone_dem_extent.img")
do_output_directory_creation(root)
global output_folder
output_folder = pjoin(root, 'output')
log.info("get the tiles")
tg = TileGrid(upwind_length, terrain_map)
tiles = get_tiles(tg)
log.info('the number of tiles is {0}'.format(str(len(tiles))))
pp.barrier()
multiplier = Multipliers(terrain_map, dem, cyclone_area)
multiplier.parallelise_on_tiles(tiles)
pp.barrier()
log.info("Successfully completed wind multipliers calculation")
开发者ID:dynaryu,项目名称:Wind_multipliers,代码行数:86,代码来源:all_multipliers.py
示例17: save_electronic_eigenstates
#.........这里部分代码省略.........
#Number of basis functions.
basis_size = (2 * m_max + 1) * (nu_max + 1) * (mu_max + 1)
#Generate a filename.
filename = name_gen.electronic_eigenstates_R(my_config)
f = tables.openFile(filename, 'w')
try:
f.createArray("/", "R_grid", R_grid)
#Looping over the m values.
for m in range(-1 * m_max, m_max + 1):
#Creating an m group in the file.
m_group = name_gen.m_name(m)
f.createGroup("/", m_group)
#Looping over th q values.
for q in range(mu_max + 1):
#Creating a q group in the m group in the file.
q_group = name_gen.q_name(q)
f.createGroup("/%s/"%m_group, q_group)
#Initializing the arrays for the eigenvalues and states.
f.createCArray('/%s/%s/'%(m_group, q_group),'E',
tables.atom.FloatAtom(),
(basis_size/(mu_max + 1), nr_tasks),
chunkshape=(basis_size/(mu_max + 1), 1))
f.createCArray('/%s/%s/'%(m_group, q_group),'V',
tables.atom.ComplexAtom(16),
(basis_size, basis_size/(mu_max + 1), nr_tasks),
chunkshape=(basis_size, basis_size/(mu_max + 1), 1))
finally:
f.close()
#Save config instance.
my_config.save_config(filename)
#----------------------------------
#Solving the TISE
#----------------
#Looping over the tasks of this processor.
for i in my_tasks:
#Creating TISE instance.
tise = tise_electron.TISE_electron(m = m_max, nu = nu_max,
mu = mu_max, R = R_grid[i], beta = beta, theta = theta)
#Diagonalizing the hamiltonian.
E,V = tise.solve()
#First file write. (Send, but not receive baton.)
if starter == my_id:
#Write to file.
tise.save_eigenfunctions_R(E, V, R_grid[i])
#Avoiding this statement 2nd time around.
starter = -1
#Sending the baton to the next writer.
pypar.send(baton, send_to, use_buffer = True)
#Last file write. (Receive, but not send baton.)
elif i == my_tasks[-1] and ender == my_id :
#Receiving the baton from the previous writer.
pypar.receive(receive_from, buffer = baton)
#Write to file.
tise.save_eigenfunctions_R(E, V, R_grid[i])
#The rest of the file writes.
else:
#Receiving the baton from the previous writer.
pypar.receive(receive_from, buffer = baton)
#Write to file.
tise.save_eigenfunctions_R(E, V, R_grid[i])
#Sending the baton to the next writer.
pypar.send(baton, send_to, use_buffer = True)
#Showing the progress of the work.
if my_id == 0:
nice_stuff.status_bar("Electronic BO calculations",
i, len(my_tasks))
#----------------------------
#Letting everyone catch up.
pypar.barrier()
#Since the sign of the eigenfunctions are completely arbitrary, one must
#make sure they do not change sign from one R to another.
if my_id == 0:
tise.align_all_phases()
#Letting 0 catch up.
pypar.barrier()
开发者ID:sas044,项目名称:H2plus_Born_Oppenheimer,代码行数:101,代码来源:electronic_BO.py
示例18: save_all_eigenstates
#.........这里部分代码省略.........
f = tables.openFile(filename, 'w')
try:
f.createArray("/", "electronicFilename", [filename_el])
f.createArray("/", "R_grid", r_grid)
f.createArray("/", "overlap", spline_basis.overlap_matrix)
#Initializing the arrays for the eigenvalues and states.
f.createCArray('/','E',
tables.atom.FloatAtom(),
(nr_kept, nr_tasks),
chunkshape=(nr_kept, 1))
f.createCArray('/','V',
tables.atom.FloatAtom(),
(spline_basis.nr_splines, nr_kept, nr_tasks),
chunkshape=(spline_basis.nr_splines, nr_kept, 1))
f.createCArray('/','hamiltonian',
tables.atom.FloatAtom(),
(spline_basis.nr_splines, spline_basis.nr_splines, nr_tasks),
chunkshape=(spline_basis.nr_splines, spline_basis.nr_splines,
1))
finally:
f.close()
#Save spline info.
spline_basis.bsplines.save_spline_info(filename)
#----------------------------------
#Solving the TISE
#----------------
#Looping over the tasks of this processor.
for i in my_tasks:
#TODO REMOVE?
#remove_spikes removes points where the diagonalization has failed.
#potential_hamiltonian = spline_basis.setup_potential_matrix(
# r_grid, remove_spikes(energy_curves[i,:]) + 1/r_grid)
####
#Setup potential matrix.
potential_hamiltonian = spline_basis.setup_potential_matrix(
r_grid, energy_curves[i,:] + 1/r_grid)
#The total hamiltonian.
hamiltonian_matrix = (spline_basis.kinetic_hamiltonian +
potential_hamiltonian)
#Diagonalizing the hamiltonian.
E, V = spline_basis.solve(hamiltonian_matrix, nr_kept)
#First file write. (Send, but not receive baton.)
if starter == my_id:
#Write to file.
spline_basis.save_eigenstates(filename, E, V,
hamiltonian_matrix, i)
#Avoiding this statement 2nd time around.
starter = -1
#Sending the baton to the next writer.
pypar.send(baton, send_to, use_buffer = True)
#Last file write. (Receive, but not send baton.)
elif i == my_tasks[-1] and ender == my_id :
#Receiving the baton from the previous writer.
pypar.receive(receive_from, buffer = baton)
#Write to file.
spline_basis.save_eigenstates(filename, E, V,
hamiltonian_matrix, i)
#The rest of the file writes.
else:
#Receiving the baton from the previous writer.
pypar.receive(receive_from, buffer = baton)
#Write to file.
spline_basis.save_eigenstates(filename, E, V,
hamiltonian_matrix, i)
#Sending the baton to the next writer.
pypar.send(baton, send_to, use_buffer = True)
#Showing the progress of the work.
if my_id == 0:
nice_stuff.status_bar("Vibrational BO calculations",
i, len(my_tasks))
#----------------------------
#Letting everyone catch up.
pypar.barrier()
开发者ID:sas044,项目名称:H2plus_Born_Oppenheimer,代码行数:101,代码来源:vibrational_BO.py
示例19: CreatePath
def CreatePath(absFileName):
if pyprop.ProcId == 0:
filePath = os.path.dirname(absFileName)
if not os.path.exists(filePath):
os.makedirs(filePath)
pypar.barrier()
开发者ID:AtomAleks,项目名称:pyprop-helium,代码行数:6,代码来源:tasks.py
示例20: BO_dipole_couplings
#.........这里部分代码省略.........
else:
#Collect indices of the basis functions.
index_array.append(r_[m, q, i])
finally:
f.close()
#Cast index list as an array.
index_array = array(index_array)
#Number of eigenstates in the basis.
basis_size = len(index_array)
print basis_size, "is the basis size"
basis_size_buffer[0] = basis_size
f = tables.openFile(self.coupling_file, 'w')
try:
f.createArray("/", "R_grid", R_grid)
#Saving the index array.
f.createArray("/", "index_array", index_array)
#Initializing the arrays for the couplings and energies.
f.createCArray('/', 'E',
tables.atom.FloatAtom(),
(basis_size, nr_tasks),
chunkshape=(basis_size, 1))
f.createCArray('/', 'couplings',
tables.atom.ComplexAtom(16),
(basis_size, basis_size, nr_tasks),
chunkshape=(basis_size, basis_size, 1))
finally:
f.close()
#Save config instance.
self.config.save_config(self.coupling_file)
#----------------------------------
#Calculating the dipole couplings
#--------------------------------
#Broadcasting the basis size from processor 0.
pypar.broadcast(basis_size_buffer, 0)
#Initializing the index array.
if my_id != 0:
index_array = zeros([basis_size_buffer[0], 3], dtype=int)
#Broadcasting the index array from proc. 0.
pypar.broadcast(index_array, 0)
#Looping over the tasks of this processor.
for i in my_tasks:
#Calculate the dipole couplings for one value of R.
couplings, E = self.calculate_dipole_eig_R(index_array, R_grid[i])
#First file write. (Send, but not receive baton.)
if starter == my_id:
#Write to file.
self.save_dipole_eig_R(couplings, E, R_grid[i])
#Avoiding this statement 2nd time around.
starter = -1
#Sending the baton to the next writer.
pypar.send(baton, send_to, use_buffer = True)
#Last file write. (Receive, but not send baton.)
elif i == my_tasks[-1] and ender == my_id :
#Receiving the baton from the previous writer.
pypar.receive(receive_from, buffer = baton)
#Write to file.
self.save_dipole_eig_R(couplings, E, R_grid[i])
#The rest of the file writes.
else:
#Receiving the baton from the previous writer.
pypar.receive(receive_from, buffer = baton)
#Write to file.
self.save_dipole_eig_R(couplings, E, R_grid[i])
#Sending the baton to the next writer.
pypar.send(baton, send_to, use_buffer = True)
#Showing the progress of the work.
if my_id == 0:
nice_stuff.status_bar("Electronic dipole couplings:",
i, len(my_tasks))
#----------------------------
#Letting everyone catch up.
pypar.barrier()
开发者ID:sas044,项目名称:H2plus_Born_Oppenheimer,代码行数:101,代码来源:tdse_electron.py
注:本文中的pypar.barrier函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论