本文整理汇总了Python中msmbuilder.Project.load_from方法的典型用法代码示例。如果您正苦于以下问题:Python Project.load_from方法的具体用法?Python Project.load_from怎么用?Python Project.load_from使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类msmbuilder.Project
的用法示例。
在下文中一共展示了Project.load_from方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_a_ConvertDataToHDF
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def test_a_ConvertDataToHDF(self):
os.chdir(WorkingDir)
shutil.copy(PDBFn,"./")
#def run(projectfn, PDBfn, InputDir, source, mingen, stride, rmsd_cutoff, parallel='None'):
ConvertDataToHDF.run(ProjectFn, PDBFn, TutorialDir+"/XTC", "file", 0, 1, None)
P1 = Project.load_from(ProjectFn)
r_P1 = Project.load_from(os.path.abspath(os.path.join('..', ReferenceDir, ProjectFn)))
eq_(P1.n_trajs, r_P1.n_trajs)
npt.assert_equal(P1.traj_lengths, r_P1.traj_lengths)
eq_(os.path.basename(P1.traj_filename(0)), os.path.basename(r_P1.traj_filename(0)))
示例2: save
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def save(self):
"Save the trajs as a n MSMBuilder project"
traj_dir = pjoin(self.project_dir, 'Trajectories')
if not os.path.exists(traj_dir):
os.makedirs(traj_dir)
t = Trajectory.load_trajectory_file(self.conf_filename)
traj_paths = []
for i, xyz in enumerate(self.trajectories):
t['IndexList'] = None # bug in msmbuilder
t['XYZList'] = xyz
traj_paths.append(pjoin(traj_dir, 'trj%d.lh5' % i))
t.save(traj_paths[-1])
p = Project({'conf_filename': os.path.abspath(self.conf_filename),
'traj_lengths': self.n_frames*np.ones(self.n_trajs),
'traj_paths': [os.path.abspath(e) for e in traj_paths],
'traj_converted_from': [[] for i in range(self.n_trajs)],
'traj_errors': [None for i in range(self.n_trajs)],
}, project_dir=self.project_dir, validate=True)
p.save(pjoin(self.project_dir,'Project.yaml'))
# just check again
p = Project.load_from(pjoin(self.project_dir,'Project.yaml'))
p._validate()
assert np.all((p.load_traj(0)['XYZList'] - self.trajectories[0])**2 < 1e-6)
示例3: main
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def main():
global data2d
global As
# First I need to turn the assignments matrix into a 1D list of assignments
sys.stdout = os.fdopen(sys.stdout.fileno(),'w',0)
print "Reading in Assignments... from %s " % options.assFN
As = io.loadh(options.assFN)['arr_0'].astype(int)
print "Reading in data... from %s " % options.dataFN
try:
f = io.loadh( options.dataFN )
try:
data2d = f['arr_0']
except:
data2d = f['Data']
except:
data = load(options.dataFN)
proj = Project.load_from( options.projFN )
data2d = msmTools.reshapeRawData( data, proj )
print "Calculating averages for:"
pool = mp.Pool(options.procs)
clusters = range( As.max() + 1)
result = pool.map_async(calcAvg,clusters[:])
result.wait()
sol = result.get()
sol = array(sol)
savetxt(options.outFN, sol)
return
示例4: main
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def main():
"""Parse command line inputs, load up files, and build a movie."""
parser = arglib.ArgumentParser(description="""
Create an MSM movie by sampling a sequence of states and sampling a
random conformation from each state in the sequence.
""")
parser.add_argument('project')
parser.add_argument('assignments', default='Data/Assignments.Fixed.h5')
parser.add_argument('tprob', default='Data/tProb.mtx')
parser.add_argument('num_steps')
parser.add_argument('starting_state', type=int, help='''Which state to start trajectory from.''')
parser.add_argument('output', default='sample_traj.pdb', help="""The filename of your output trajectory. The filetype suffix will be used to select the output file format.""")
args = parser.parse_args()
try:
assignments = io.loadh(args.assignments, 'arr_0')
except KeyError:
assignments = io.loadh(args.assignments, 'Data')
num_steps = int(args.num_steps)
starting_state = int(args.starting_state)
project = Project.load_from(args.project)
T = scipy.io.mmread(args.tprob).tocsr()
state_traj = msm_analysis.sample(T, starting_state, num_steps)
sampled_traj = project.get_random_confs_from_states(assignments, state_traj, 1)
traj = sampled_traj[0]
traj["XYZList"] = np.array([t["XYZList"][0] for t in sampled_traj])
traj.save(args.output)
示例5: run
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def run(projectfn, conf_filename, input_dir, source, min_length, stride, rmsd_cutoff, atom_indices, iext):
# check if we are doing an update or a fresh run
# if os.path.exists(projectfn):
# logger.info("Found project info file encoding previous work, running in update mode...")
# update = True
# else:
# update = False
#
# logger.info("Looking for %s style data in %s", source, input_dir)
# if update:
# raise NotImplementedError("Ack! Update mode is not yet ready yet.")
# if the source is fah, we'll use some special FaH specific loading functions
# to (1) try to recover in case of errors and (2) load the specific directory
# hierarchy of FaH (RUN/CLONE/GEN/frame.xtc)
if os.path.exists(projectfn):
project = Project.load_from(projectfn)
logger.warn(
"%s exists, will modify it and update the trajectories in %s",
projectfn, '/'.join(project._traj_paths[0].split('/')[:-1]))
else:
project = None
if source.startswith('file'):
pb = ProjectBuilder(
input_dir, input_traj_ext=iext, conf_filename=conf_filename,
stride=stride, project=project, atom_indices=atom_indices)
elif source == 'fah':
pb = FahProjectBuilder(
input_dir, input_traj_ext=iext, conf_filename=conf_filename,
stride=stride, project=project, atom_indices=atom_indices)
else:
raise ValueError("Invalid argument for source: %s" % source)
# check that trajectories to not go farther than a certain RMSD
# from the PDB. Useful to check for blowing up or other numerical
# instabilities
if rmsd_cutoff is not None:
# TODO: this is going to use ALL of the atom_indices, including hydrogen. This is
# probably not the desired functionality
# KAB: Apparently needed to use correctly subsetted atom_indices here to avoid an error
validator = validators.RMSDExplosionValidator(
conf_filename, max_rmsd=rmsd_cutoff, atom_indices=atom_indices)
pb.add_validator(validator)
# Only accept trajectories with more snapshots than min_length.
if min_length > 0:
validator = validators.MinLengthValidator(min_length)
pb.add_validator(validator)
# everyone wants to be centered
pb.add_validator(validators.TrajCenterer())
pb.get_project().save(projectfn)
assert os.path.exists(projectfn), '%s does not exist' % projectfn
logger.info("Finished data conversion successfully.")
logger.info("Generated: %s, Trajectories/", projectfn)
return
示例6: main
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def main():
"""Parse command line inputs, load up files, then call run() and save() to do
the real work"""
parser.add_argument('output_dir', default='PDBs')
args = parser.parse_args()
# load...
# project
project = Project.load_from(args.project)
# assignments
try:
assignments = io.loadh(args.assignments, 'arr_0')
except KeyError:
assignments = io.loadh(args.assignments, 'Data')
# states
if -1 in args.states:
states = np.unique(assigments[np.where(assignments != -1)])
logger.info('Yanking from all %d states', len(states))
else:
# ensure that the states are sorted, and that they're unique -- you
# can only request each state once
states = np.unique(args.states)
logger.info("Yanking from the following states: %s", states)
# extract the conformations using np.random for the randomness
confs_by_state = project.get_random_confs_from_states(
assignments, states=states, num_confs=args.conformations_per_state,
replacement=args.replacement)
# save the conformations to disk, in the requested style
save(confs_by_state=confs_by_state, states=states, style=args.style,
format=args.format, outdir=args.output_dir)
示例7: main
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def main(file):
ass=io.loadh(file)
dir=os.path.dirname(file)
base=os.path.basename(file)
newdir='%s/subsample' % dir
if not os.path.exists(newdir):
os.mkdir(newdir)
p=Project.load_from('%s/ProjectInfo.yaml' % dir.split('Data')[0])
data=dict()
totals=dict()
iterations=int(ass['arr_0'].shape[1]/10.0)
start=max(p.traj_lengths)
for iter in range(0, iterations):
new=start-10
if new < 10:
break
totals[new]=0
data[new]=-numpy.ones((ass['arr_0'].shape[0], new), dtype=int)
for i in range(0, ass['arr_0'].shape[0]):
data[new][i]=ass['arr_0'][i][:new]
frames=numpy.where(data[new][i]!=-1)[0]
totals[new]+=len(frames)
start=new
ohandle=open('%s/times.h5' % (newdir), 'w')
for key in sorted(data.keys()):
print data[key].shape
print "total time is %s" % totals[key]
ohandle.write('%s\t%s\t%s\n' % (data[key].shape[0], data[key].shape[1], totals[key]))
示例8: main
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument('assignments', default='Macro4/MacroAssignments.h5', help='Path to an assignments file. (default=Macro4/MacroAssignments.h5)')
parser.add_argument('--project', default='ProjectInfo.yaml', help='Path to ProjectInfo.yaml file. (default=ProjectInfo.yaml)')
args = parser.parse_args()
project = Project.load_from(args.project)
t = reduce(operator.add, (project.load_traj(i) for i in range(project.n_trajs)))
phi_angles = md.compute_dihedrals(t, [PHI_INDICES]) * 180.0 / np.pi
psi_angles = md.compute_dihedrals(t, [PSI_INDICES]) * 180.0 / np.pi
state_index = np.hstack(io.loadh(args.assignments)['arr_0'])
for i in np.unique(state_index):
pp.plot(phi_angles[np.where(state_index == i)],
psi_angles[np.where(state_index == i)],
'x', label='State %d' % i)
pp.title("Alanine Dipeptide Macrostates")
pp.xlabel(r"$\phi$")
pp.ylabel(r"$\psi$")
annotate()
pp.legend(loc=1, labelspacing=0.075, prop={'size': 8.0}, scatterpoints=1,
markerscale=0.5, numpoints=1)
pp.xlim([-180, 180])
pp.ylim([-180, 180])
pp.show()
示例9: main
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def main(modeldir, genfile, type):
project=Project.load_from('%s/ProjectInfo.yaml' % modeldir.split('Data')[0])
data=dict()
pops=numpy.loadtxt('%s/Populations.dat' % modeldir)
map=numpy.loadtxt('%s/Mapping.dat' % modeldir)
frames=numpy.where(map!=-1)[0]
data['rmsd']=numpy.loadtxt('%s.rmsd.dat' % genfile.split('.lh5')[0])
data['rmsd']=data['rmsd'][frames]
com=numpy.loadtxt('%s.vmd_com.dat' % genfile.split('.lh5')[0], usecols=(1,))
refcom=com[0]
data['com']=com[1:]
data['com']=numpy.array(data['com'])
data['com']=data['com'][frames]
ass=io.loadh('%s/Assignments.Fixed.h5' % modeldir)
T=mmread('%s/tProb.mtx' % modeldir)
paths=io.loadh('%s/tpt-rmsd-%s/Paths.h5' % (modeldir, type))
for p in range(0, 20):
movie=project.empty_traj()
path=paths['Paths'][p]
flux=paths['fluxes'][p]/paths['fluxes'][0]
if flux < 0.2:
break
print "flux %s" % flux
frames=numpy.where(path!=-1)[0]
path=numpy.array(path[frames], dtype=int)
for (n, state) in enumerate(path):
t=project.get_random_confs_from_states(ass['arr_0'], [int(state),], 20)
if n==0:
movie['XYZList']=t[0]['XYZList']
else:
movie['XYZList']=numpy.vstack((movie['XYZList'], t[0]['XYZList']))
movie.save_to_xtc('%s/tpt-rmsd-%s/path%s_sample20.xtc' % (modeldir, type, p))
示例10: main
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def main(modeldir, genfile, type, write=False):
proj=Project.load_from('%s/ProjectInfo.yaml' % modeldir.split('Data')[0])
pops=numpy.loadtxt('%s/Populations.dat' % modeldir)
map=numpy.loadtxt('%s/Mapping.dat' % modeldir)
frames=numpy.where(map!=-1)[0]
data=dict()
data['rmsd']=numpy.loadtxt('%s.rmsd.dat' % genfile.split('.lh5')[0])
data['rmsd']=data['rmsd'][frames]
com=numpy.loadtxt('%s.vmd_com.dat' % genfile.split('.lh5')[0], usecols=(1,))
refcom=com[0]
data['com']=com[1:]
data['com']=numpy.array(data['com'][frames])
residues=['F36', 'H87', 'I56', 'I90', 'W59', 'Y82', 'hydrophob_dist', 'oxos_dist']
loops=['loop1', 'loop2', 'loop3']
for loop in loops:
data[loop]=numpy.loadtxt('%s.%srmsd.dat' % (genfile.split('.lh5')[0], loop))
data[loop]=data[loop][frames]
for res in residues:
file='%s_%spair.dat' % (genfile.split('.lh5')[0], res)
if os.path.exists(file):
data[res]=numpy.loadtxt(file)
data[res]=data[res][frames]
angles=['phi', 'omega']
for ang in angles:
file='%s_%s.dat' % (genfile.split('.lh5')[0], ang)
if os.path.exists(file):
data[ang]=numpy.loadtxt(file)
data[ang]=data[ang][frames]
ass=io.loadh('%s/Assignments.Fixed.h5' % modeldir)
T=mmread('%s/tProb.mtx' % modeldir)
unbound=numpy.loadtxt('%s/tpt-%s/unbound_%s_states.txt' % (modeldir, type, type), dtype=int)
bound=numpy.loadtxt('%s/tpt-%s/bound_%s_states.txt' % (modeldir, type, type), dtype=int)
Tdense=T.todense()
Tdata=dict()
for i in unbound:
for j in unbound:
if Tdense[i,j]!=0:
if i not in Tdata.keys():
Tdata[i]=[]
Tdata[i].append(j)
#print Tdata
cm=pylab.cm.get_cmap('RdYlBu_r') #blue will be negative components, red positive
Q=tpt.calculate_committors(unbound, bound, T)
ohandle=open('%s/commitor_states.txt' % modeldir, 'w')
for i in range(0,len(Q)):
if Q[i]>0.40 and Q[i]<0.6:
ohandle.write('%s\n' % i)
#t=project.get_random_confs_from_states(ass['arr_0'], [int(i),], 20)
#t[0].save_to_xtc('%s/commottor_state%s.xtc' % (modeldir, i))
if write==True:
for op in sorted(data.keys()):
pylab.figure()
pylab.scatter(data['com'], data[op], c=Q, cmap=cm, alpha=0.7, s=[map_size(i) for i in Q])
pylab.xlabel('L RMSD')
pylab.ylabel(op)
pylab.colorbar()
pylab.show()
示例11: main
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def main(assfile, lag, nproc):
lag=int(lag)
nproc=int(nproc)
Assignments=io.loadh(assfile)
num=int(assfile.split('Assignments_sub')[1].split('.h5')[0])
dir=os.path.dirname(assfile)
newdir='%s/boot-sub%s' % (dir, num)
ref_sub=numpy.loadtxt('%s/times.h5' % dir, usecols=(1,))
ref_total=numpy.loadtxt('%s/times.h5' % dir, usecols=(2,))
times=dict()
for (i,j) in zip(ref_sub, ref_total):
times[i]=j
proj=Project.load_from('%s/ProjectInfo.yaml' % dir.split('Data')[0])
multinom=int(times[num])
if not os.path.exists(newdir):
os.mkdir(newdir)
if 'Data' in Assignments.keys():
Assignments=Assignments['Data']
else:
Assignments=Assignments['arr_0']
print Assignments.shape
NumStates = max(Assignments.flatten()) + 1
Counts = MSMLib.get_count_matrix_from_assignments(Assignments, lag_time=int(lag), sliding_window=True)
Counts=Counts.todense()
Counts=Counts*(1.0/lag)
T=numpy.array(Counts)
frames=numpy.where(T==0)
T[frames]=1
Popsample=dict()
iteration=0
total_iteration=100/nproc
print "%s total iterations" % total_iteration
if 100 % nproc != 0:
remain=100 % nproc
else:
remain=False
print "iterating thru tCount samples"
count=0
while iteration < 100:
if count*nproc > 100:
nproc=remain
print "sampling iteration %s" % iteration
Tfresh=T.copy()
input = zip([Tfresh]*nproc, [multinom]*nproc, range(0, NumStates))
pool = multiprocessing.Pool(processes=nproc)
result = pool.map_async(parallel_get_matrix, input)
result.wait()
all = result.get()
pool.terminate()
for c_matrix in all:
scipy.io.mmwrite('%s/tCounts-%s' % (newdir, iteration), c_matrix)
#rev_counts, t_matrix, Populations, Mapping=x
#scipy.io.mmwrite('%s/tProb-%s' % (newdir, iteration), t_matrix)
#numpy.savetxt('%s/Populations-%s' % (newdir, iteration), Populations)
#numpy.savetxt('%s/Mapping-%s' % (newdir, iteration), Mapping)
iteration+=1
count+=1
print "dont with iteration %s" % iteration*nproc
示例12: test_rg_1
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def test_rg_1():
project = Project.load_from(os.path.join(fixtures_dir(), 'ProjectInfo.h5'))
traj = project.load_traj(0)
xyzlist = traj['XYZList']
a = rgcalc.calculate_rg(xyzlist)
b = reference_rg(xyzlist)
npt.assert_array_almost_equal(a, b)
示例13: test_g_GetRandomConfs
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def test_g_GetRandomConfs(self):
P1 = Project.load_from(ProjectFn)
Assignments = io.loadh("Data/Assignments.Fixed.h5", 'arr_0')
# make a predictable stream of random numbers by seeding the RNG with 42
random_source = np.random.RandomState(42)
randomconfs = GetRandomConfs.run(P1, Assignments, NumRandomConformations, random_source)
reference = Trajectory.load_trajectory_file(os.path.join(ReferenceDir, "2RandomConfs.lh5"))
self.assert_trajectories_equal(reference, randomconfs)
示例14: main
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def main(args, metric):
assignments_path = os.path.join(args.output_dir, "Assignments.h5")
distances_path = os.path.join(args.output_dir, "Assignments.h5.distances")
project = Project.load_from(args.project)
gens = Trajectory.load_trajectory_file(args.generators)
# this runs assignment and prints them to disk
assign_with_checkpoint(metric, project, gens, assignments_path, distances_path)
logger.info('All Done!')
示例15: main
# 需要导入模块: from msmbuilder import Project [as 别名]
# 或者: from msmbuilder.Project import load_from [as 别名]
def main(assfile, lag, nproc):
lag=int(lag)
nproc=int(nproc)
Assignments=io.loadh(assfile)
dir=os.path.dirname(assfile)
newdir='%s/sample-counts' % dir
proj=Project.load_from('%s/ProjectInfo.yaml' % dir.split('Data')[0])
multinom=sum(proj.traj_lengths)
if not os.path.exists(newdir):
os.mkdir(newdir)
if 'Data' in Assignments.keys():
Assignments=Assignments['Data']
else:
Assignments=Assignments['arr_0']
print Assignments.shape
NumStates = max(Assignments.flatten()) + 1
Counts = MSMLib.get_count_matrix_from_assignments(Assignments, lag_time=int(lag), sliding_window=True)
Counts=Counts.todense()
Counts=Counts*(1.0/lag)
T=numpy.array(Counts)
frames=numpy.where(T==0)
T[frames]=1
Popsample=dict()
iteration=0
total_iteration=100/nproc
print "%s total iterations" % total_iteration
if 100 % nproc != 0:
remain=100 % nproc
else:
remain=False
print "iterating thru tCount samples"
count=0
while iteration < 100:
if count*nproc > 100:
nproc=remain
print "sampling iteration %s" % iteration
Tfresh=T.copy()
counts=range(0, nproc)
input = zip([Tfresh]*nproc, [multinom]*nproc, [NumStates]*nproc, counts)
pool = multiprocessing.Pool(processes=nproc)
result = pool.map_async(parallel_get_matrix, input)
result.wait()
all = result.get()
print "computed resampled matrices"
pool.terminate()
for count_matrix in all:
#rev_counts, t_matrix, Populations, Mapping=x
scipy.io.mmwrite('%s/tCounts-%s' % (newdir, iteration), count_matrix)
# scipy.io.mmwrite('%s/tProb-%s' % (newdir, iteration), t_matrix)
# numpy.savetxt('%s/Populations-%s' % (newdir, iteration), Populations)
# numpy.savetxt('%s/Mapping-%s' % (newdir, iteration), Mapping)
iteration+=1
count+=1
print "dont with iteration %s" % iteration*nproc