本文整理汇总了Python中simulator.Simulator.simulate方法的典型用法代码示例。如果您正苦于以下问题:Python Simulator.simulate方法的具体用法?Python Simulator.simulate怎么用?Python Simulator.simulate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类simulator.Simulator
的用法示例。
在下文中一共展示了Simulator.simulate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
def run():
drone = Drone()
controller = Controller(drone)
simulator = Simulator(drone, controller)
deviation = 1; # Simulate some disturbance in the angular velocity.
#angular_disturbance=simulator.deg2rad(2 * deviation * np.random.rand(3, 1) - deviation).transpose()
angular_disturbance = np.array([[0.0],[0.1],[0.0]])
#drone.thetadot = angular_disturbance # Simulate some disturbance in the angular velocity.
simulator.simulate(60) # simulate n secs
import matplotlib.pyplot
matplotlib.pyplot.pause(60)
示例2: test_simulator
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
def test_simulator():
'''test function on Simulator'''
# First approach: full hedge
s = Simulator()
s.simulate()
print('Full Hedge approach - \n', s)
# Second approach: partial hedge
s.FullHedge = False
res = s.simulate()
print('Partial Hedge approach - \n', s)
示例3: main
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
def main():
from argparse import ArgumentParser
argparser = ArgumentParser()
argparser.add_argument('team1')
argparser.add_argument('team2')
argparser.add_argument('--depth', type=int, default=2)
argparser.add_argument('--gamestate', type=str)
argparser.add_argument('--player', type=int, default=0)
args = argparser.parse_args()
pokedata = load_data("data")
players = [None, None]
# players[args.player] = HumanAgent()
players[args.player] = PessimisticMinimaxAgent(2, pokedata, log_file="normal.txt")
# players[1 - args.player] = PessimisticMinimaxAgent(2, pokedata, log_file="no_cache.txt", use_cache=False)
# players[1 - args.player] = DumbAgent()
players[1 - args.player] = HumanAgent()
with open(args.team1) as f1, open(args.team2) as f2, open("data/poke2.json") as f3:
data = json.loads(f3.read())
poke_dict = Smogon.convert_to_dict(data)
teams = [Team.make_team(f1.read(), poke_dict), Team.make_team(f2.read(), poke_dict)]
gamestate = GameState(teams)
if args.gamestate is not None:
with open(args.gamestate, 'rb') as fp:
gamestate = pickle.load(fp)
with open('cur2.gs', 'wb') as fp:
pickle.dump(gamestate, fp)
gamestate.create_gamestate_arff(0)
gamestate.print_readable_data(0)
gamestate.print_readable_data(1)
simulator = Simulator(pokedata)
while not gamestate.is_over():
print "=========================================================================================="
print "Player 1 primary:", gamestate.get_team(0).primary(), gamestate.get_team(0).primary().status
print "Player 2 primary:", gamestate.get_team(1).primary(), gamestate.get_team(1).primary().status
print ""
my_action = players[0].get_action(gamestate, 0)
opp_action = players[1].get_action(gamestate, 1)
gamestate = simulator.simulate(gamestate, [my_action, opp_action], 0, log=True)
if gamestate.get_team(0).alive():
print "You win!"
print "Congrats to", gamestate.opp_team
print "Sucks for", gamestate.my_team
else:
print "You lose!"
print "Congrats to", gamestate.my_team
print "Sucks for", gamestate.opp_team
gamestate.turn += 1
示例4: get_users
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
def get_users(self):
## Read in the survey data or simulate new data
if os.path.isfile(self.survey_data_filename):
parser = Parser(self.survey_data_filename)
all_users = parser.get_users()
## Remember all previous matches
## TODO: Update analyze function to exclude previous pairs (Don't want the same person each week)
## TODO: Persist to a database instead of a file
previous_pairs = set([])
previous_pairs_filename = "c:/users/aaron/desktop/previous_pairs.txt"
if os.path.isfile(previous_pairs_filename):
with open (previous_pairs_filename) as prev:
for line in prev:
usera, userb = line.strip().split(",")
previous_pairs.add((usera,userb))
previous_pairs.add((userb,usera))
## Grabs the list of people interested in being matched this week
## From the Meetup event API
opt_ins = self.get_weekly_opt_ins()
## Filter to just opted-in users
self.users = set([i for i in all_users if int(i.user_id) in opt_ins])
else:
print "Simulating data"
## Simulate some number of survey responses
sim = Simulator()
sim.simulate(200) ## By adding a seed parameter, you can have reproducible sims
self.users = sim.get_users()
# ## Print some summaries
# for user in users:
# user.to_string()
# Print some descriptive stats
print "# Users", len(self.users), [u.name for u in self.users]
示例5: run
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
def run():
if (sys.argv[1] == "-advanced"):
print "Running advanced simulations..."
s = Simulator(2000, [1, 0.5, 0.25, 0.125])
s.simulate(Decoder.SUM_PROD)
s.compute_error()
s.save_results()
s.plot('ro-')
s.save_graph()
s = Simulator(2000, [1, 0.5, 0.25, 0.125])
s.simulate(Decoder.MAX_PROD)
s.compute_error()
s.save_results()
s.plot('g^--')
s.save_graph()
s = Simulator(1000, [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])
s.simulate(Decoder.SUM_PROD)
s.compute_error()
s.save_results()
s.plot('ro--')
s.save_graph()
s = Simulator(1000, [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0])
s.simulate(Decoder.MAX_PROD)
s.compute_error()
s.save_results()
s.plot('g^--')
s.save_graph()
print "See graphs/advanced-run and stats/advanced-run for detailed results."
else:
print sys.argv
print "Running default simulation at variance levels %(var)s with %(num)s codewords..." % \
{"var": [1, 0.5, 0.25, 0.125],
"num": sys.argv[1]}
s = Simulator(int(sys.argv[1]), [1, 0.5, 0.25, 0.125])
s.default_run()
示例6: len
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
from scanner import Scanner
from parser import Parser
from simulator import Simulator
import sys
if __name__ == '__main__':
if len(sys.argv) != 2:
print "invalid argument"
print "python /compiler/run.py examples/test code"
sys.exit(0)
filename = sys.argv[1]
#set up scanner
scanner = Scanner(1,1,False,'', False, False,[],'',[], False)
tokens = scanner.scan(filename)
#set parser
parser = Parser(tokens, 0)
e = parser.parse()
#set simulator
simulator = Simulator(e['symtable'], e['d_nodes'])
simulate = simulator.simulate()
示例7: terminate_whenStateIsReached
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
def terminate_whenStateIsReached(clock, model):
return model.trafficLight.state.get() == "manual"
sim.setTerminationCondition(terminate_whenStateIsReached)
# A termination time is prefered over a termination condition,
# as it is much simpler to use.
# e.g. to simulate until simulation time 100.0 is reached
sim.setTerminationTime(300.0)
# B. Set the use of a tracer to show what happened during the simulation run
# Both writing to stdout or file is possible:
# pass None for stdout, or a filename for writing to that file
sim.setVerbose(None)
# C. Use Classic DEVS instead of Parallel DEVS
# If your model uses Classic DEVS, this configuration MUST be set as
# otherwise errors are guaranteed to happen.
# Without this option, events will be remapped and the select function
# will never be called.
sim.setClassicDEVS()
# ======================================================================
# 4. Simulate the model
sim.simulate()
# ======================================================================
# 5. (optional) Extract data from the simulated model
print("Simulation terminated with traffic light in state %s" % (trafficSystem.trafficLight.state.get()))
示例8: ArgumentParser
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
desc = u'{0} [Args] [Options]\nDetailed options -h or --help'.format(__file__)
parser = ArgumentParser(description=desc)
parser.add_argument(
dest = 'filename',
action = 'store',
type = str,
help = 'target testbench name')
parser.add_argument(
'-v', '--verbose',
action = 'store_true',
dest = 'verbose',
help = "use verbose output")
parser.add_argument(
'-f', '--float',
action = 'store_true',
dest = 'get_float',
help = "get return value as float")
args = parser.parse_args()
sim = Simulator(args.filename)
v0 = sim.simulate(verbose = args.verbose)
if args.get_float:
v0 = v0[1]
else:
v0 = v0[0]
sys.stderr.write("\n===== RESULT =====\nbin : {}\nint : {}\nfloat: {}".format(v0, int(v0, 2), utils.reg2float(v0)))
示例9: MonteCarloAgent
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
class MonteCarloAgent(Agent):
def __init__(self, maxtime, pokedata, sl_policy=None):
self.lmbda = 0.8
sl_model_file = 'models/sl/sl_simple.bst'
sl_feature_labels_file = 'models/sl/sl_X_encoders.pickle'
sl_cats_file = 'models/sl/sl_cats.pickle'
sl_target_label_file = 'models/sl/sl_Y_encoder.pickle'
sl_files = [sl_model_file, sl_feature_labels_file, sl_cats_file, sl_target_label_file]
rollout_model_file = 'models/sl/sl_simple.bst'
rollout_files = [rollout_model_file, sl_feature_labels_file, sl_cats_file, sl_target_label_file]
value_model_file = 'models/value/value_func.bst'
value_feature_labels_file = 'models/value/value_func_X_encoders.pickle'
value_cats_file = 'models/value/value_func_cats.pickle'
value_target_label_file = 'models/value/value_func_Y_encoder.pickle'
value_files = [value_model_file, value_feature_labels_file, value_cats_file, value_target_label_file]
self.maxtime = maxtime
self.simulator = Simulator(pokedata)
self.tree = MonteCarloTree(sl_files, rollout_files, value_files)
self.sl_policy = sl_policy
print "Monte Carlo tree created"
def get_action(self, state, who, log=True):
print "Getting action"
start = time.time()
best_action, value, opp_action = self.search(state, who, start, log=log)
'''if best_action:
if best_action.is_move():
my_move_name = state.get_team(who).primary().moveset.known_moves[best_action.move_index]
if opp_action.is_move():
opp_move_name = state.get_team(1 - who).primary().moveset.moves[opp_action.move_index]
if best_action.is_switch():
my_move_name = "Switch[%s]" % state.get_team(who).poke_list[best_action.switch_index]
if opp_action.is_switch():
opp_move_name = "Switch[%s]" % state.get_team(1 - who).poke_list[opp_action.switch_index]
if log:
print "I think you are going to use %s(%s, %s, %s) and I will use %s(%s, %s, %s)." % (
opp_move_name, opp_action.backup_switch, opp_action.mega, opp_action.volt_turn,
my_move_name, best_action.backup_switch, best_action.mega, best_action.volt_turn,
)'''
return best_action
def rollout(self, state, turn_num):
try:
winner = state.get_winner()
start = time.time()
while not winner and (time.time() - start) < self.maxtime:
my_action_probs = state.get_legal_actions_probs(self.tree.rollout_classifier, turn_num, 0, probs=False)
if random.random() < 0.05:
opp_action_probs = state.get_legal_actions_probs(self.tree.rollout_classifier, turn_num, 1, probs=True)
else:
opp_action_probs = state.get_legal_actions_probs(self.tree.rollout_classifier, turn_num, 1, probs=False)
my_action = numpy.random.choice(my_action_probs[0], p=my_action_probs[1])
opp_action = numpy.random.choice(opp_action_probs[0], p=opp_action_probs[1])
state = self.simulator.simulate(state, (my_action, opp_action), 0, add_action=True, deep_copy=False)
winner = state.get_winner()
turn_num += 1
if winner == 0:
return 0.5
else:
return int(winner == 1)
except:
# print "Error in rollout"
pass
return 0.5
def search(self, state, who, start, log=False):
self.tree.re_root(state)
count = 0
while (time.time() - start) < self.maxtime:
# select an action pair and get new actionpair node
child = self.tree.select_add_actionpair()
# run simulation given previous state and action chosen, return new state
parent_state = child.parent.state.deep_copy()
winner = parent_state.get_winner()
if winner != 0:
outcome = int(winner==1)
self.tree.back_propogate(child.parent, outcome)
else:
new_state = self.simulator.simulate(parent_state, child.action_pair, who, add_action=True, deep_copy=False)
# add new gamestate node to tree
leaf = self.tree.add_gamestate(child, new_state)
# run rollout policy and backpropogate outcome
num_times = 2
outcome = 0.0
outcomes = (self.rollout(new_state.deep_copy(), child.parent.turn_num + 1) for i in range(num_times))
#for i in range(num_times):
# outcome += self.rollout(new_state.deep_copy(), child.parent.turn_num + 1)
outcome = sum(outcomes)/num_times
value = new_state.value_function(self.tree.value_function, child.parent.turn_num + 1, 0)
#.........这里部分代码省略.........
示例10: f
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
def f(n):
s = Simulator()
s.Parallel = True
s.Seed = n
s.simulate()
return s.NRuns, s.PNLMean, s.PNLStdDev
示例11: prepare_directory
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
'queen_name': queen.get_name(),
'amount_of_ants': amount_of_ants,
'run_id': run_id,
},
)
if os.path.exists(artifact_directory):
continue
#import pycallgraph
#pycallgraph.start_trace()
prepare_directory(artifact_directory)
simulator = Simulator(reality, simulation_class, [vaporizator, edge_mutator])
stats_saver = statssaver_class(artifact_directory)
simulation = simulator.simulate(queen, amount_of_ants, stats_saver)
if simulation_class == MultiSpawnStepSimulation and options.force_spawn_amount:
simulation.spawn_amount = force_spawn_amount
draw_link_costs(simulation, artifact_directory, reality)
start_time = time.time()
director.direct(simulation, artifact_directory)
total_real_time = time.time() - start_time
elapsed, ticks, queenstats = simulator.get_results(simulation)
# this used to agregate data from several runs
elapsed_balanced = elapsed / amount_of_ants
data = {
'world': world_name,
'world_filepath': file_,
示例12: Simulator
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
import cPickle as pickle
from settings import *
if __name__ == '__main__':
simulator = Simulator()
ev = Evolutor()
x = len(li) if p_testcases else 1
try:
for o in range(x):
if p_testcases:
change()
for i in range(p_nr_itrations):
last = i == (p_nr_itrations - 1)
ev.step(last)
simulator.simulate(ev.actuall_best_net, i % 20 == 0)
if i == 119 or not p_testcases:
print "Generation: ", i, " Best: ", ev.actuall_best_net_val/float(p_cases), " Total: ", ev.actuall_population_performance
finally:
f = file("network.pickle", "wb")
#for w in ev.population[0].weights.values():
# print w
#print "bias: \n"
#for l in ev.population[0].layers:
# for n in l:
# print n.b
pickle.dump(ev.actuall_best_net, f, 0)
f.close()
示例13: int
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
try:
properties['window'] = int(properties['window'])
except:
print "Invalid window argument: '{}'".format(properties['window'])
exit(-1)
if properties['output'] == None:
properties['output'] = "{}-simulation-{}-{}.log".format(properties['input'], properties['payload'][:15], properties['window']).replace(",", "_").replace("(", "_")
print "Output file not specified, will use '{}".format(properties['output'])
start = time.time()
link_file = LinkFile(properties['input'])
simulator_ab = Simulator(link_file.links_ab, properties['output'], properties['window'])
simulator_ba = Simulator(link_file.links_ba, properties['output'], properties['window'])
print "\nsimulating A->B"
simulator_ab.simulate(properties['payload'])
print "\nsimulating B->A"
simulator_ba.simulate(properties['payload'])
print "Done in {}s.".format(time.time() - start)
示例14: SolarPanel
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
# solar_panel = SolarPanel(name_="Solar Panel", nominal_power_capacity_=800, temperature_coefficient_=0.02,
# storage_=storageA)
components_of_HRES = [total_consumption, solar_panel, storageA, storageB]
benchmark_relay = BenchmarkControlRelay()
hres = HRES(components_of_HRES, location)
prices = priceGenerator([0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673,
0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, 0.0673, .0673, 0.0673, 0.0673, 0.0673,
0.0673, 0.0673, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243,
0.1243, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893,
0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893,
0.0893, 0.0893, 0.0893, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243,
0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.1243, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893, 0.0893,
0.0893, 0.0673, 0.0673, 0.0673, 0.0673])
# Create the description of the experiment
lg.append_list_of_paragraphs(station.get_description())
lg.append_list_of_paragraphs(hres.get_description)
# default_HRES.print_components_list()
description, simulation_matrix = Simulator.simulate(prices, benchmark_relay, hres, ws, datetime_simulation_start,
iteration_timedelta, number_of_iterations)
columns = simulation_matrix.columns
# print(columns)
draw_results(lg)
print("Simulation is over")
# wdg = WeatherDataGenerator()
# print(wdg.generate())
示例15: Simulator
# 需要导入模块: from simulator import Simulator [as 别名]
# 或者: from simulator.Simulator import simulate [as 别名]
# Return the AST using tokens
ast = parser.parse()
simulator = Simulator(ast['decorated_nodes'], ast['symtable'] )
instructions = []
for inst in ast['decorated_nodes']:
instructions.append( [inst['instruction'], inst['value']] )
print "\n"
print "[Simulator]: Generated instructions for stack machine"
print "\n"
ip = 0
for inst in instructions:
if ip > 9:
print "I" + str(ip) + ": " + str(instructions[ip])
else:
print "I" + str(ip) + ": " + str(instructions[ip])
ip += 1
print "\n"
simulator.simulate()