本文整理汇总了Python中Simulation类的典型用法代码示例。如果您正苦于以下问题:Python Simulation类的具体用法?Python Simulation怎么用?Python Simulation使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Simulation类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: CommandsListener
class CommandsListener(threading.Thread):
def __init__(self, thymioController, mainLogger):
threading.Thread.__init__(self)
# Create socket for listening to simulation commands
self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.__sock.bind((cl.COMMANDS_LISTENER_HOST, cl.COMMANDS_LISTENER_PORT))
self.__sock.listen(5)
self.__thymioController = thymioController
self.__mainLogger = mainLogger
self.__simulation = None
self.__counter = pr.starter_number
def run(self):
while 1:
try:
# Waiting for client...
self.__mainLogger.debug("CommandListener - Waiting on accept...")
conn, (addr, port) = self.__sock.accept()
self.__mainLogger.debug('CommandListener - Received command from (' + addr + ', ' + str(port) + ')')
if addr not in cl.TRUSTED_CLIENTS:
self.__mainLogger.error(
'CommandListener - Received connection request from untrusted client (' + addr + ', ' + str(
port) + ')')
continue
# Receive one message
self.__mainLogger.debug('CommandListener - Receiving command...')
recvOptions = recvOneMessage(conn)
self.__mainLogger.debug('CommandListener - Received ' + str(recvOptions))
if recvOptions.kill:
# Received killing command -> Stop everything
self.__thymioController.killRequest()
if self.__simulation:
self.__simulation.stop()
break
elif recvOptions.start and (not self.__simulation or self.__simulation.isStopped()):
# Adding experiment number to pr.EXPERIMENT_NAME
experiment_name = pr.EXPERIMENT_NAME + "_" + str(self.__counter)
self.__counter += 1
# Received start request AND simulation is not running -> Start a new simulation
self.__mainLogger.debug("CommandListener - Starting simulation...")
self.__simulation = Simulation(self.__thymioController, recvOptions.debug, experiment_name)
self.__thymioController.setSimulation(self.__simulation)
self.__simulation.start()
elif recvOptions.stop and self.__simulation and not self.__simulation.isStopped(): # TODO: Stop properly
# Received stop request AND simulation is up and running -> Stop the simulation
self.__mainLogger.debug("CommandListener - Stopping simulation...")
self.__simulation.stop()
self.__simulation = None
elif recvOptions.stopthymio:
self.__mainLogger.debug("CommandListener - Stopping Thymio...")
self.__thymioController.stopThymio()
except:
self.__mainLogger.critical(
'Error in CommandsListener: ' + str(sys.exc_info()[0]) + ' - ' + traceback.format_exc())
self.__mainLogger.debug('CommandListener - KILLED -> Exiting...')
示例2: handlePerformedActionShow
def handlePerformedActionShow(words, writeFile):
global opponentName
global numBoardCards
global preflopBets
global postflopBets
global turnBets
global riverBets
global boardCards
global d
if(words[5] == opponentName):
opponentHand = []
for card in words[1:5]:
opponentHand.append(parseCard(card))
preflopRating = Pokerini.pokeriniLookup(opponentHand, d)
writeFile.write(str(preflopRating)+","+','.join(preflopBets))
writeFile.write('\n')
if(numBoardCards >= 3):
postflopRanking = Simulation.simulateOld(opponentHand, boardCards[0:3], 3, 100)
writeFile.write(str(postflopRanking)+","+','.join(postflopBets))
writeFile.write('\n')
if(numBoardCards >= 4):
turnRanking = Simulation.simulateOld(opponentHand, boardCards[0:4], 4, 100)
writeFile.write(str(turnRanking)+","+','.join(turnBets))
writeFile.write('\n')
if(numBoardCards == 5):
riverRanking = Simulation.simulateOld(opponentHand, boardCards[0:5], 5, 100)
writeFile.write(str(riverRanking)+","+','.join(riverBets))
writeFile.write('\n')
示例3: main
def main():
battlesimulator = Master()
battlesimulator.introMessage()
setupPlayers = SetupPlayers()
setupPlayers.askPlayer()
battlesimulator.displayStats(Warrior(1, 2, 3), Warrior(4, 5, 6))
warriorSet = WarriorSet(Warrior(1, 2, 3), Warrior(4, 5, 6))
warriorSet.printWarriors()
simulation = Simulation()
simulation.setWarriors(Warrior(1, 2, 3), Warrior(4, 5, 6))
simulation.run()
示例4: setUp
def setUp(self):
Simulation.setupJobEffMC()
cores = 3000
bandwidth = 3000
self.system = Site.Batch( cores, bandwidth )
file1 = "/store/data/1"
file2 = "/store/data/2"
theStore = Data.EventStore()
theStore.addFile( file1, 10000 )
theStore.addFile( file2, 20000 )
inputData = { file1, file2 }
aJob = Job.Job( "T2_CH_CERN", inputData, 0.1, 220, 200, theStore )
self.system.addJob( aJob )
self.system.runJob( aJob, 0 )
示例5: Simulation_launch
def Simulation_launch(self):
if self.busy > 0:
return False
# A new simulation thread is created
if self.Simulation_stop():
self.simulation = Simulation(self.OneStep)
self.simulation.start()
return True
示例6: get_sample
def get_sample(traj_dist,experiment_id):
#Start a simulation and do the stuff
functions = {}
args = {}
real_fun(functions)
states = np.genfromtxt('/home/elias/[email protected]/_Winter2015/CSC494/Trajectories/Traj'+str(experiment_id+1)+'state.txt', delimiter=',',dtype=np.float32)
actions = np.genfromtxt('/home/elias/etraga[email protected]/_Winter2015/CSC494/Trajectories/Traj'+str(experiment_id+1)+'action.txt' ,dtype=np.float32)
T,d = states.shape
#Create simulation
Sim = Simulation(function=functions["Traj{}".format(str(experiment_id+1))], args=[[0,0,3],0])
Sim.restart()
f = open('/home/elias/[email protected]/_Winter2015/CSC494/Trajectories/Traj{}pred.txt'.format(experiment_id+1),'w+')
r = open('/home/elias/[email protected]/_Winter2015/CSC494/Trajectories/Traj{}residuals.txt'.format(experiment_id+1),'w+')
for timestep in range(T):
states[timestep,:] = normalize(state_norms[experiment_id],controller.getDif(Sim.cid,Sim.copter,Sim.target))
old = actions[timestep,:].copy()
actions[timestep,:] = denormalize(action_norms[experiment_id], get_action(traj_dist,states[timestep,:],timestep)[0])
Sim.forward(actions[timestep,:].tolist())
f.write(str(actions[timestep,:])+'\n')
r.write(str(old-actions[timestep,:])+'\n')
#Sim.forward()
Sim.sync()
print(vrep.simxStopSimulation(Sim.cid,vrep.simx_opmode_oneshot_wait))
f.close()
r.close()
return states,actions
示例7: updateHandRanking
def updateHandRanking(self):
if(self.cardsChanged == True):
if(self.numBoardCards == 0): #preflop
self.pokeriniRank = Pokerini.pokeriniLookup(self.myHand, pokeriniDict)
self.calculatePreflopBetLimit()
if(self.numBoardCards >= 3):#postflop
#self.simulationWinChance = Simulation.simulate(self.myHand, self.boardCards, self.numBoardCards, 200, handEvalDict, translationDict)
self.simulationWinChance = Simulation.simulateOld(self.myHand, self.boardCards, self.numBoardCards, self.numSimulations)
self.cardsChanged = False
示例8: Simulation_Control
class Simulation_Control(object):
""" Controls the simulation, either step by step, or in
a continuous mode.
"""
def __init__(self, SimulationStep):
self.OneStep = SimulationStep # function that launches one step of the simulation
## Status of the simulation programme
self.simulation = None # name of the simulation thread
self.busy = 0 # busy meter to avoid fatal parallelism between simulation and display
#self.previous_Disp_period = self.Disp_period = 1 # display period
def RunButtonClick(self, event=None):
self.simulation_steady_mode = True # Continuous functioning
self.Simulation_resume()
def PauseButtonClick(self,event=None):
self.Simulation_stop()
def Simulation_stop(self):
if self.simulation is not None:
self.simulation.stop()
if self.simulation.isAlive():
#print 'strange...'
#sleep(2)
self.simulation = None # well...
return False
self.simulation = None
return True
def Simulation_launch(self):
if self.busy > 0:
return False
# A new simulation thread is created
if self.Simulation_stop():
self.simulation = Simulation(self.OneStep)
self.simulation.start()
return True
def Simulation_resume(self):
return self.Simulation_launch()
示例9: startStandalone
def startStandalone():
import Simulation
print('MagneticPendulum -Standalone')
print('--------------------------------------------')
print('Image resolution: {0}x{0} Output: {1}'.format(Parameter.RESOLUTION, Parameter.IMG_NAME))
print('Working with {0} sub-processes in total.'.format(Parameter.MAX_PROCESSES))
print('============================================')
start = time.time()
im= Image.new('RGB', (Parameter.RESOLUTION, Parameter.RESOLUTION))
data = []
pixel = [] + [0]*(Parameter.RESOLUTION**2)
manager = Manager()
coordinates = manager.Queue()
values = manager.Queue()
workerRunning = manager.Value('i', 0)
Simulation.createAllCoordinates(coordinates, data)
while workerRunning.get() < Parameter.MAX_PROCESSES:
Process(target=Simulation.workerThread,args=(coordinates, workerRunning, values)).start()
time.sleep(1)
while workerRunning.value > 0:
Simulation.drawImage(im, data, pixel, values)
time.sleep(Parameter.REPAINT)
Simulation.drawImage(im, data, pixel, values)
print('Image succeeded. Time consumed: {0:.2f}s'.format((time.time() - start)))
print('Exiting...')
sys.exit(0)
示例10: startServer
def startServer():
freeze_support()
print('MagneticPendulum -Cluster/Server')
print('--------------------------------------------')
print('Image resolution: {0}x{0} Output: {1}'.format(Parameter.RESOLUTION, Parameter.IMG_NAME))
print('============================================')
print('Now waiting to have some working clients.')
import Simulation
manager = ClusterQueueManager()
data = []
coordinates = manager.getCoordinates()
values = manager.getValues()
im= Image.new('RGB', (Parameter.RESOLUTION, Parameter.RESOLUTION))
pixel = [] + [0]*(Parameter.RESOLUTION**2)
Simulation.createAllCoordinates(coordinates, data)
start = time.time()
manager.start()
while not coordinates.empty():
while manager.getRunningClients() > 0:
if not values.empty():
Simulation.drawImage(im, data, pixel, values)
time.sleep(Parameter.REPAINT)
time.sleep(.5)
print("Coordinates are now completely distributed.")
while manager.getRunningClients() > 0:
time.sleep(Parameter.REPAINT)
print('Waiting for {0} clients to be done'.format(manager.getRunningClients()))
Simulation.drawImage(im, data, pixel, values)
print('Image succeeded. Time consumed: {0:.2f}s'.format((time.time() - start)))
print('Exiting...')
sys.exit(0)
示例11: run
def run(self):
while 1:
try:
# Waiting for client...
self.__mainLogger.debug("CommandListener - Waiting on accept...")
conn, (addr, port) = self.__sock.accept()
self.__mainLogger.debug('CommandListener - Received command from (' + addr + ', ' + str(port) + ')')
if addr not in cl.TRUSTED_CLIENTS:
self.__mainLogger.error(
'CommandListener - Received connection request from untrusted client (' + addr + ', ' + str(
port) + ')')
continue
# Receive one message
self.__mainLogger.debug('CommandListener - Receiving command...')
recvOptions = recvOneMessage(conn)
self.__mainLogger.debug('CommandListener - Received ' + str(recvOptions))
if recvOptions.kill:
# Received killing command -> Stop everything
self.__thymioController.killRequest()
if self.__simulation:
self.__simulation.stop()
break
elif recvOptions.start and (not self.__simulation or self.__simulation.isStopped()):
# Adding experiment number to pr.EXPERIMENT_NAME
experiment_name = pr.EXPERIMENT_NAME + "_" + str(self.__counter)
self.__counter += 1
# Received start request AND simulation is not running -> Start a new simulation
self.__mainLogger.debug("CommandListener - Starting simulation...")
self.__simulation = Simulation(self.__thymioController, recvOptions.debug, experiment_name)
self.__thymioController.setSimulation(self.__simulation)
self.__simulation.start()
elif recvOptions.stop and self.__simulation and not self.__simulation.isStopped(): # TODO: Stop properly
# Received stop request AND simulation is up and running -> Stop the simulation
self.__mainLogger.debug("CommandListener - Stopping simulation...")
self.__simulation.stop()
self.__simulation = None
elif recvOptions.stopthymio:
self.__mainLogger.debug("CommandListener - Stopping Thymio...")
self.__thymioController.stopThymio()
except:
self.__mainLogger.critical(
'Error in CommandsListener: ' + str(sys.exc_info()[0]) + ' - ' + traceback.format_exc())
self.__mainLogger.debug('CommandListener - KILLED -> Exiting...')
示例12: setup_cpus
def setup_cpus(options):
# By default, set workload to path of user-specified binary
workloads = options.cmd
numThreads = 1
if options.cpu_type == "detailed" or options.cpu_type == "inorder":
# check for SMT workload
workloads = options.cmd.split(";")
if len(workloads) > 1:
process = []
smt_idx = 0
inputs = []
outputs = []
errouts = []
if options.input != "":
inputs = options.input.split(";")
if options.output != "":
outputs = options.output.split(";")
if options.errout != "":
errouts = options.errout.split(";")
for wrkld in workloads:
smt_process = LiveProcess()
smt_process.executable = wrkld
smt_process.cmd = wrkld + " " + options.options
if inputs and inputs[smt_idx]:
smt_process.input = inputs[smt_idx]
if outputs and outputs[smt_idx]:
smt_process.output = outputs[smt_idx]
if errouts and errouts[smt_idx]:
smt_process.errout = errouts[smt_idx]
process += [smt_process]
smt_idx += 1
numThreads = len(workloads)
(CPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)
CPUClass.clock = options.clock
CPUClass.numThreads = numThreads
return (CPUClass, test_mem_mode, FutureClass)
示例13:
parser = optparse.OptionParser()
Options.addCommonOptions(parser)
Options.addFSOptions(parser)
# Add the ruby specific and protocol specific options
if '--ruby' in sys.argv:
Ruby.define_options(parser)
(options, args) = parser.parse_args()
if args:
print "Error: script doesn't take any positional arguments"
sys.exit(1)
# system under test can be any CPU
(TestCPUClass, test_mem_mode, FutureClass) = Simulation.setCPUClass(options)
# Match the memories with the CPUs, based on the options for the test system
TestMemClass = Simulation.setMemClass(options)
if options.benchmark:
try:
bm = Benchmarks[options.benchmark]
except KeyError:
print "Error benchmark %s has not been defined." % options.benchmark
print "Valid benchmarks are: %s" % DefinedBenchmarks
sys.exit(1)
else:
if options.dual:
bm = [SysConfig(disk=options.disk_image, rootdev=options.root_device,
mem=options.mem_size, os_type=options.os_type),
示例14: EtherSwitch
# instantiate an EtherSwitch
switch = EtherSwitch()
# instantiate distEtherLinks to connect switch ports
# to other gem5 instances
switch.portlink = [DistEtherLink(speed = options.ethernet_linkspeed,
delay = options.ethernet_linkdelay,
dist_rank = options.dist_rank,
dist_size = options.dist_size,
server_name = options.dist_server_name,
server_port = options.dist_server_port,
sync_start = options.dist_sync_start,
sync_repeat = options.dist_sync_repeat,
is_switch = True,
num_nodes = options.dist_size)
for i in xrange(options.dist_size)]
for (i, link) in enumerate(switch.portlink):
link.int0 = switch.interface[i]
return switch
# Add options
parser = optparse.OptionParser()
Options.addCommonOptions(parser)
Options.addFSOptions(parser)
(options, args) = parser.parse_args()
system = build_switch(options)
root = Root(full_system = True, system = system)
Simulation.run(options, root, None, None)
示例15: input
# Copyright © 2016 Jalel Benerrami. All rights reserved.
# from /Users/jalelbenerrami/Desktop/project_Python/Point2D import*
# from /Users/jalelbenerrami/Desktop/project_Python/Simulation import*
from Point2D import *
from Simulation import *
#
# Run programm by choosing parameters into the terminal
#
# Number of random points
n = input("\nEnter the number of points you want to generate : ")
n = int(n)
print(n, "\n")
# Choose a strategy
s = input("Choose a strategy : " )
s = int(s)
print(s, "\n")
# Create a simulation with given number of points
Sim = Simulation(n)
# Execute the created simulation
Sim.execute(s)
# Display the information about executed simulation
print(Sim, "\n")