本文整理汇总了Python中model.Model类的典型用法代码示例。如果您正苦于以下问题:Python Model类的具体用法?Python Model怎么用?Python Model使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Model类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: main
def main():
# NOTE: Cutoff can either be a single integer or it
# can be a dictionary where the keys are two-tuples
# of atomic numbers (e.g. (40,13)=3.5 for Zr,Al).
modelfile = sys.argv[1]
submodelfile = sys.argv[2]
rotatedsubmodelfile = sys.argv[3]
m = Model(modelfile)
try:
cut = 3.5 # float(sys.argv[2])
cutoff = {}
for z1 in m.atomtypes:
for z2 in m.atomtypes:
cutoff[(z1, z2)] = cut
cutoff[(z2, z1)] = cut
except:
print("You didn't input a cutoff so you much define it in the code.")
voronoi_3d(m, cutoff)
subm = Model(submodelfile)
rotsubm = Model(rotatedsubmodelfile)
for atom in subm.atoms:
if atom in m.atoms:
rotsubm.atoms[atom.id].vp = m.atoms[m.atoms.index(atom)].vp
else:
print("Couldn't find atom {0} in full model!".format(atom))
icofrac(rotsubm)
# rotsubm.write_real_xyz()
rotsubm.write_real_xyz(rotatedsubmodelfile[:-4] + ".icofrac.real.xyz")
开发者ID:adehgha,项目名称:model_analysis,代码行数:29,代码来源:submodel_vp.py
示例2: post
def post(self):
id = self.get_argument("id",None)
keyword = self.get_argument("keyword","")
handler = Model('LvsManagerConfig')
vipinstanceinfo = handler.getLvsManagerConfigVipInstanceList(id)
def build(vipinstanceinfo):
for row in vipinstanceinfo:
for k,v in row.items():
if k=='vip_group':
rs=[]
for r in v:
rs.append(r['vip']+':'+r['port'])
row[k]="<br>".join(rs)
else:
if isinstance(v,unicode):
row[k]=str(v.encode('utf-8'))
else:
row[k]=str(v)
return json.dumps(vipinstanceinfo)
result=[]
for row in vipinstanceinfo:
if str(row['descript']).find(keyword)!=-1:
result.append(row)
ret=""
if len(result)>0:
ret=build(result)
else:
ret=build(vipinstanceinfo)
self.write(ret)
开发者ID:sjqzhang,项目名称:lvs-manager,代码行数:31,代码来源:control.py
示例3: __init__
def __init__(self, tracks=None, devices=None, transport=None,
view_scale=None, units=None, patch_bay=None):
Model.__init__(self)
# the file path to save to
self.path = None
# transport
if (transport is None):
transport = Transport()
self.transport = transport
# time scale
if (view_scale is None):
view_scale = ViewScale()
self.view_scale = view_scale
# devices
if (devices is None):
devices = DeviceAdapterList()
self.devices = devices
# a list of units on the workspace
if (units is None):
units = UnitList()
self.units = units
self.units.add_observer(self.on_change)
self.units.add_observer(self.update_transport_duration)
self.update_transport_duration()
# a list of connections between units
if (patch_bay is None):
patch_bay = PatchBay()
self.patch_bay = patch_bay
self.patch_bay.add_observer(self.on_change)
开发者ID:jessecrossen,项目名称:jackdaw,代码行数:29,代码来源:doc.py
示例4: login
def login(name,password):
'''
:param name:
:param password:
:return: {"status":1, "username":user,"is_manager":False,"is_super_manager":False}
'''
try:
ret=requests.post(API_URL+'login', {'user_name':name,'password':password}).json()
if ret['status']=='1':
user= ret['username']
if user:
handler = Model('Account')
_find_user_result = handler.getAccountOne(user)
if _find_user_result:
time_now = timestamptodate(time.time())
handler.UpdateAccountPrivilege(user,ret['is_manager'],ret['is_super_manager'])
handler.updateAccountLogintime(user,time_now)
else:
time_now = timestamptodate(time.time())
user_data = {"username":user,"is_manager":ret['is_manager'],"is_super_manager":ret['is_super_manager'],"login_time":time_now,"register_time":time_now}
handler.InsertAccount(user_data)
return 1
else:
return 0
except Exception as er:
return 0
开发者ID:sjqzhang,项目名称:lvs-manager,代码行数:28,代码来源:control.py
示例5: get
def get(self):
'''
show publish.html page
'''
handler = Model('LvsPublish')
result = handler.getLvsPublish()
self.render2('publish.html',publish=result)
开发者ID:sjqzhang,项目名称:lvs-manager,代码行数:7,代码来源:control.py
示例6: test_small_model
def test_small_model(self):
# Create one input
X = helper.make_tensor_value_info('IN', TensorProto.FLOAT, [2, 3])
# Create one output
Y = helper.make_tensor_value_info('OUT', TensorProto.FLOAT, [2, 3])
# Create a node
node_def = helper.make_node('Abs', ['IN'], ['OUT'])
# Create the model
graph_def = helper.make_graph([node_def], "test-model", [X], [Y])
onnx_model = helper.make_model(graph_def,
producer_name='onnx-example')
model = Model()
model.BuildFromOnnxModel(onnx_model)
schedule = model.OptimizeSchedule()
schedule = schedule.replace('\n', ' ')
expected_schedule = r'// Target: .+// MachineParams: .+// Delete this line if not using Generator Pipeline pipeline = get_pipeline\(\);.+Func OUT = pipeline.get_func\(1\);.+{.+}.+'
self.assertRegex(schedule, expected_schedule)
input = np.random.rand(2, 3) - 0.5
outputs = model.run([input])
self.assertEqual(1, len(outputs))
output = outputs[0]
expected = np.abs(input)
np.testing.assert_allclose(expected, output)
开发者ID:halide,项目名称:Halide,代码行数:26,代码来源:model_test.py
示例7: initialize
def initialize(self,inputParameterValues):
# Inputs
self.windVelNED = mat('0.0;0.0;0.0')
# Received via message
self.altitude = 0.0
self.dcmBodyFromNED = mat([[0.,0.,0.],[0.,0.,0.],[0.,0.,0.]])
self.velECEFinBody = mat('0.;0.;0.')
# Internal
self.vwindmag = 0.0
self.speedofsound = 0.0
# Outputs
self.mach = 0.0
self.alpha = 0.0
self.beta = 0.0
self.density = 0.0
self.pressure = 0.0
self.temperature = 0.0
self.uvw = mat('0.0;0.0;0.0')
self.qbar = 0.0
self.qalpha = 0.0
# Call the base class initialize function, which sets all the input params
Model.initialize(self,inputParameterValues)
开发者ID:CookLabs,项目名称:lift,代码行数:27,代码来源:atmosphere.py
示例8: calc_entropy
def calc_entropy(K=20):
global grammar
global NORMALIZE
global VERBOSE
global start_cat
cat_priors = Model('Prior')
for cat in start_cat:
cat_priors[cat] = 1
normalize(cat_priors)
for k in range(0,K):
if VERBOSE:
sys.stderr.write('Iterating ('+str(k)+'/'+str(K)+'): ')
sys.stderr.write(str(cat_priors.keys())+'\n')
tot = 0.0
if NORMALIZE:
normalize(cat_priors)
cat_likes = Model('MarginL') #actually the new prior built from likelihoods
for parent in cat_priors:
for child in grammar[parent]:
cat_likes[child] += grammar[parent][child]*cat_priors[parent]/3.0
cat_priors = cat_likes.copy()
# sum over the probability of each category to obtain the overall likelihood of the
grammar_prob = 0.0
for cat in cat_priors:
grammar_prob += cat_priors[cat]
# output the entropy of the grammar
sys.stderr.write(str(-math.log(grammar_prob))+'\n')
sys.stdout.write(str(-math.log(grammar_prob))+'\n')
开发者ID:vansky,项目名称:tree_entropy,代码行数:30,代码来源:calc-entropy.py
示例9: run
def run(num_agents, num_items, prefs, dup_values):
# Randomly generate some data for N agents and M items
if prefs.dist_type == DistTypes.urand_int:
m = Model.generate_urand_int(num_agents, num_items, dup_values)
elif prefs.dist_type == DistTypes.urand_real:
m = Model.generate_urand_real(num_agents, num_items, dup_values)
elif prefs.dist_type == DistTypes.zipf_real:
m = Model.generate_zipf_real(num_agents, num_items, 2., dup_values)
elif prefs.dist_type == DistTypes.polya_urn_real:
m = Model.generate_polya_urn_real(num_agents, num_items, 2, 1)
elif prefs.dist_type == DistTypes.correlated_real:
m = Model.generate_correlated_real(num_agents, num_items)
else:
raise Exception("Distribution type {0} is not recognized.".format(prefs.dist_type))
# Do our bounding at the root to check for naive infeasibility
#is_possibly_feasible, bounding_s = bounds.max_contested_feasible(m)
#if not is_possibly_feasible:
# print "Bounded infeasible!"
# sys.exit(-1)
# Compute an envy-free allocation (if it exists)
stats = allocator.allocate(m, prefs)
return stats
开发者ID:JohnDickerson,项目名称:EnvyFree,代码行数:26,代码来源:driver.py
示例10: __init__
def __init__(self, topology, bead_repr=None):
"""Structure-based Model (SBM)
Parameters
----------
topology : mdtraj.Topology object
An mdtraj Topology object that describes the molecular topology.
bead_repr : str [CA, CACB]
A code specifying the desired coarse-grain mapping. The all-atom
to coarse-grain mapping.
Methods
-------
assign_* :
Methods assign which atoms have bonded constraints
(angle potentials, dihedral, etc.)
add_* :
Methods add potentials to the Hamiltonian.
"""
Model.__init__(self, topology, bead_repr=bead_repr)
self.Hamiltonian = potentials.StructureBasedHamiltonian()
self.mapping.add_atoms()
开发者ID:ajkluber,项目名称:model_builder,代码行数:28,代码来源:structurebasedmodel.py
示例11: predict
def predict(args):
with open(os.path.join(args.save_dir, 'config.pkl'), 'rb') as f:
saved_args = pickle.load(f)
with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'rb') as f:
chars, vocab = pickle.load(f)
with open(os.path.join(args.save_dir, 'labels.pkl'), 'rb') as f:
labels = pickle.load(f)
model = Model(saved_args, deterministic=True)
with open(args.data_path, 'r') as f:
reader = csv.reader(f)
texts = list(reader)
texts = map(lambda i: i[0], texts)
x = map(lambda i: transform(i.strip().decode('utf8'), saved_args.seq_length, vocab), texts)
with tf.Session() as sess:
saver =tf.train.Saver(tf.all_variables())
ckpt = tf.train.get_checkpoint_state(args.save_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
start = time.time()
results = model.predict_label(sess, labels, x)
end = time.time()
print 'prediction costs time: ', end - start
with open(args.result_path, 'w') as f:
writer = csv.writer(f)
writer.writerows(zip(texts, results))
开发者ID:12190143,项目名称:RNN-Classification,代码行数:31,代码来源:sample.py
示例12: main
def main():
modelfile = sys.argv[1]
m = Model(modelfile)
# Below is the identity rotation array.
#rot_arr = [1,0,0,0,1,0,0,0,1]
# Below is the correct rotation matrix for JWH t3 icofrac to get it into the orientation in his PRL paper.
#rot_arr = [-0.031777, 0.998843, 0.036102, 0.986602, 0.025563, 0.161133, 0.160023, 0.040739, -0.986272]
# Below is a (the?) rotation matrix for JWH t1 icofrac.
#rot_arr = [ 0.954646, -0.233932, 0.184194, 0.280650, 0.913581, -0.294287, -0.099433, 0.332633, 0.937800 ]
# Below is a (the?) rotation matrix of Pei's t1 that gives some planes. Oriented for a specific plane ~.
#rot_arr = [ -0.977103, -0.123352, -0.173361, -0.130450, 0.990997, 0.030118, 0.168085, 0.052043, -0.984398 ]
# Below is a (the?) rotation matrix of Pei's t2 that gives some planes. Oriented for a specific plane ~.
rot_arr = [ 0.985478, -0.010230, -0.169493, 0.009247, 0.999936, -0.006586, 0.169549, 0.004923, 0.985509]
# Below is a (the?) rotation matrix of Pei's t3 that gives some planes. Oriented for a specific plane ~.
#rot_arr = [0.981624,-0.002765,-0.190808, -0.003436,0.999477,-0.032163, 0.190797,0.032228,0.981100]
npra = np.asarray(rot_arr)
rot(m,npra)
# Write cif file to screen
#m.write_cif()
m.write_our_xyz()
开发者ID:jjmaldonis,项目名称:OdieCode,代码行数:28,代码来源:2d_rot.py
示例13: update_ststc_customer_shop
def update_ststc_customer_shop(self):
query = """REPLACE INTO ststc_customer_shop(seller_nick, buyer_nick, costs, buy_times, last_buy_time)
SELECT seller_nick,
buyer_nick,
SUM(costs) AS costs,
SUM(buy_times) AS buy_times,
MAX(last_buy_time) AS last_buy_time
FROM
((SELECT
r.nick AS seller_nick,
c.nick AS buyer_nick,
SUM(r.auctionPrice) AS costs,
COUNT(r.uid) AS buy_times,
MAX(`date`) AS last_buy_time
FROM rate_list AS r LEFT JOIN customer AS c ON r.uid = c.uid
WHERE c.nick=%s)
UNION
(SELECT
r.nick AS seller_nick,
c.nick AS buyer_nick,
SUM(r.price) AS costs,
COUNT(r.uid) AS buy_times,
MAX(`date`) AS last_buy_time
FROM rate_list_past AS r LEFT JOIN customer AS c ON r.uid = c.uid
WHERE c.nick=%s)) AS r"""
Model.execute_db(query, self.nick, self.nick)
开发者ID:perryhau,项目名称:taobao-abc,代码行数:26,代码来源:buyer.py
示例14: sim_channels_2_model
def sim_channels_2_model(sim_data, sim_key, group_key,):
# instantiate an empty model
model = Model(sim_key, objectives = [], meta = {})
#debug_p('model id ' + str(model.get_model_id()))
#debug_p('model num objectives before adding obj' + str(len(model.get_objectives())))
# add meta data to model
model.set_meta({'sim_id': sim_data['sim_id'], 'sim_meta':sim_data['meta'], 'sim_key':sim_key, 'group_key':group_key})
for channel_code in objectives_channel_codes:
# add model objective
m_points = []
for sample_point in channels_sample_points[channel_code]:
m_points.append(sim_data[channel_code][sample_point])
# assuming equal weights of objectives
#debug_p('adding obj to simulation ' + str(sim_key))
model.add_objective(channel_code, m_points)
#debug_p('model num objectives after adding obj' + str(len(model.get_objectives())))
return model
开发者ID:m-v-nikolov,项目名称:KaribaCalibration,代码行数:25,代码来源:sim_data_2_models.py
示例15: get_clusters_with_n_numneighs
def get_clusters_with_n_numneighs(self,cutoff,numneighs,cluster_types):
m = Model(self.model.comment, self.model.lx, self.model.ly, self.model.lz, self.model.atoms[:])
m.generate_neighbors(cutoff)
vp_atoms = []
#print(cluster_types)
neighs = [[]]*m.natoms
for i,atom in enumerate(m.atoms):
if(atom.vp.type in cluster_types):
vp_atoms.append(atom.copy())
numfound = 0
for i,atomi in enumerate(vp_atoms):
for j,atomj in enumerate(vp_atoms[vp_atoms.index(atomi)+1:]):
# Get all the neighbors they have in common
#common_neighs = [n for n in atomi.neighs if n in atomj.neighs if n.vp.type not in cluster_types]
common_neighs = [n for n in atomi.neighs if n in atomj.neighs]
if(len(common_neighs) >= numneighs):
ind = m.atoms.index(atomi)
neighs[ind] = neighs[ind] + copy.copy([x for x in common_neighs if x not in neighs[ind]])
ind = m.atoms.index(atomj)
neighs[ind] = neighs[ind] + copy.copy([x for x in common_neighs if x not in neighs[ind]])
for n in common_neighs:
ind = m.atoms.index(n)
neighs[ind] = neighs[ind] + [x for x in [atomi,atomj] if x not in neighs[ind]]
numfound += 1
for i,tf in enumerate(neighs):
m.atoms[i].neighs = tf
m.check_neighbors()
print('Total number of {0} atoms: {1}'.format(cluster_types,len(vp_atoms)))
print('Total number of {2}-sharing {0} atoms: {1}'.format(cluster_types,numfound,numneighs))
# Now I should be able to go through the graph/model's neighbors.
return self.search(m,cluster_types)
开发者ID:adehgha,项目名称:model_analysis,代码行数:31,代码来源:atom_graph.py
示例16: sample
def sample(args):
with open(os.path.join(args.save_dir, 'config.pkl'), 'rb') as f:
saved_args = cPickle.load(f)
with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'rb') as f:
chars, vocab = cPickle.load(f)
model = Model(saved_args, True)
with tf.Session() as sess:
tf.initialize_all_variables().run()
saver = tf.train.Saver(tf.all_variables())
ckpt = tf.train.get_checkpoint_state(args.save_dir)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(sess, ckpt.model_checkpoint_path)
ts = model.sample(sess, chars, vocab, args.n, args.prime, args.sample)
print("Sampled Output\n")
print(ts)
print("Converting Text to Speech")
tts = gTTS(text=ts, lang='en-uk')
tts.save("ts.mp3")
audio = MP3("ts.mp3")
audio_length = audio.info.length
print("Speaker is Getting Ready")
mixer.init()
mixer.music.load('ts.mp3')
mixer.music.play()
time.sleep(audio_length+5)
开发者ID:vyraun,项目名称:char-rnn-tensorflow,代码行数:25,代码来源:sample.py
示例17: loadXML
def loadXML(self, path):
Model.loadXML(path)
view.tree.Flush()
view.tree.SetPyData(view.tree.root, Model.mainNode)
self.setData(view.tree.root)
if g.conf.expandOnOpen:
view.tree.ExpandAll()
开发者ID:Bottersnike,项目名称:Everbot,代码行数:7,代码来源:presenter.py
示例18: main
def main():
print("""
skim Copyright (C) 2014 Tanay PrabhuDesai
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details. \n\n""")
mdl = Model(20,5)
print("Model?(y/n):")
choice = input()
if choice != 'n' and choice != 'N':
mdl.load_map()
mdl.load_model_base()
text = open('./raw_input_1/sherlock.txt','r')
strings = text.readlines()
text.close()
count = 1
for string in strings:
mdl.insert_string(string)
print("Inserted line: "+str(count))
count += 1
mdl.save_map()
print("Start typing: ")
while True:
inp = input()
if inp == "":
break
print("Predictions:")
print(mdl.search_string(inp, 5))
开发者ID:tanayseven,项目名称:skim,代码行数:28,代码来源:main.py
示例19: test_scalars
def test_scalars(self):
# Create 2 inputs
X = helper.make_tensor_value_info('A', TensorProto.INT32, [])
Y = helper.make_tensor_value_info('B', TensorProto.INT32, [])
# Create one output
Z = helper.make_tensor_value_info('C', TensorProto.INT32, [])
# Create a node
node_def = helper.make_node('Add', ['A', 'B'], ['C'])
# Create the model
graph_def = helper.make_graph([node_def], "scalar-model", [X, Y], [Z])
onnx_model = helper.make_model(graph_def,
producer_name='onnx-example')
model = Model()
model.BuildFromOnnxModel(onnx_model)
schedule = model.OptimizeSchedule()
schedule = schedule.replace('\n', ' ')
expected_schedule = r'// Target: .+// MachineParams: .+// Delete this line if not using Generator Pipeline pipeline = get_pipeline\(\);.+Func C = pipeline.get_func\(2\);.+{.+}.+'
self.assertRegex(schedule, expected_schedule)
input1 = np.random.randint(-10, 10, size=())
input2 = np.random.randint(-10, 10, size=())
outputs = model.run([input1, input2])
self.assertEqual(1, len(outputs))
output = outputs[0]
expected = input1 + input2
np.testing.assert_allclose(expected, output)
开发者ID:halide,项目名称:Halide,代码行数:28,代码来源:model_test.py
示例20: main
def main():
# sys.argv == [categorize_parameters.txt, modelfile]
if(len(sys.argv) <= 2): sys.exit("\nERROR! Fix your inputs!\n\nArg 1: input param file detailing each voronoi 'structure'.\nShould be of the form:\nCrystal:\n 0,2,8,*\n\nArg2: a model file.\n\nOutput is printed to screen.")
paramfile = sys.argv[1]
modelfiles = sys.argv[2:]
from cutoff import cutoff
vp_dict = load_param_file(paramfile)
m0 = Model(modelfiles[0])
m0.generate_neighbors(cutoff)
voronoi_3d(m0, cutoff)
set_atom_vp_types(m0, vp_dict)
stats0 = VPStatistics(m0)
print(modelfiles[0])
#stats0.print_indexes()
stats0.print_categories()
return
if len(modelfiles) > 1:
for modelfile in modelfiles[1:]:
print(modelfile)
m = Model(modelfile)
voronoi_3d(m, cutoff)
set_atom_vp_types(m, vp_dict)
stats = VPStatistics(m)
stats.print_categories()
开发者ID:jjmaldonis,项目名称:model_analysis,代码行数:29,代码来源:categorize_vor.py
注:本文中的model.Model类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论