当前位置: 首页>>代码示例>>Python>>正文


Python Simulation.step方法代码示例

本文整理汇总了Python中simulation.Simulation.step方法的典型用法代码示例。如果您正苦于以下问题:Python Simulation.step方法的具体用法?Python Simulation.step怎么用?Python Simulation.step使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在simulation.Simulation的用法示例。


在下文中一共展示了Simulation.step方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_simulation_can_have_a_room_and_roombas

# 需要导入模块: from simulation import Simulation [as 别名]
# 或者: from simulation.Simulation import step [as 别名]
def test_simulation_can_have_a_room_and_roombas(room):
    roomba = Roomba()
    sim = Simulation(room=room, roombas=[roomba])


    assert sim.room is room
    assert sim.roombas == [roomba]
    sim.step()

    assert roomba.position != start_position
    assert roomba.angle != 90
开发者ID:flowersw,项目名称:ultimate-pig,代码行数:13,代码来源:test_roomba_simulation.py

示例2: __init__

# 需要导入模块: from simulation import Simulation [as 别名]
# 或者: from simulation.Simulation import step [as 别名]
    def __init__(self):
        # get process info from mpi
        communicator = MPI.COMM_WORLD
        self.process_rank = communicator.Get_rank()
        number_of_processes = communicator.Get_size()

        self.log("Welcome to Streets4MPI!")
        # set random seed based on process rank
        random_seed = settings["random_seed"] + (37 * self.process_rank)
        seed(random_seed)

        self.log("Reading OpenStreetMap data...")
        data = GraphBuilder(settings["osm_file"])

        self.log("Building street network...")
        street_network = data.build_street_network()

        if self.process_rank == 0 and settings["persist_traffic_load"]:
            self.log_indent("Saving street network to disk...")
            persist_write("street_network_1.s4mpi", street_network)

        self.log("Locating area types...")
        data.find_node_categories()

        self.log("Generating trips...")
        trip_generator = TripGenerator()
        # distribute residents over processes
        number_of_residents = settings["number_of_residents"] / number_of_processes
        if settings["use_residential_origins"]:
            potential_origins = data.connected_residential_nodes
        else:
            potential_origins = street_network.get_nodes()
        potential_goals = data.connected_commercial_nodes | data.connected_industrial_nodes
        trips = trip_generator.generate_trips(number_of_residents, potential_origins, potential_goals)

        # set traffic jam tolerance for this process and its trips
        jam_tolerance = random()
        self.log("Setting traffic jam tolerance to", str(round(jam_tolerance, 2)) + "...")

        # run simulation
        simulation = Simulation(street_network, trips, jam_tolerance, self.log_indent)

        for step in range(settings["max_simulation_steps"]):

            if step > 0 and step % settings["steps_between_street_construction"] == 0:
                self.log_indent("Road construction taking place...")
                simulation.road_construction()
                if self.process_rank == 0 and settings["persist_traffic_load"]:
                    persist_write("street_network_" + str(step + 1) + ".s4mpi", simulation.street_network)

            self.log("Running simulation step", step + 1, "of", str(settings["max_simulation_steps"]) + "...")
            simulation.step()

            # gather local traffic loads from all other processes
            self.log("Exchanging traffic load data between nodes...")
            total_traffic_load = array("I", repeat(0, len(simulation.traffic_load)))
            communicator.Allreduce(simulation.traffic_load, total_traffic_load, MPI.SUM)
            simulation.traffic_load = total_traffic_load
            simulation.cumulative_traffic_load = merge_arrays((total_traffic_load, simulation.cumulative_traffic_load))

            if self.process_rank == 0 and settings["persist_traffic_load"]:
                self.log_indent("Saving traffic load to disk...")
                persist_write("traffic_load_" + str(step + 1) + ".s4mpi", total_traffic_load, is_array = True)

            del total_traffic_load

        self.log("Done!")
开发者ID:NeziheSozen,项目名称:Streets4MPI,代码行数:69,代码来源:streets4mpi.py

示例3: __init__

# 需要导入模块: from simulation import Simulation [as 别名]
# 或者: from simulation.Simulation import step [as 别名]
class Display:
	def __init__(self):
		self.width = Environment_s.width * Graphics_s.tile_length
		self.height = Environment_s.height * Graphics_s.tile_length
		self.restart = True

		while self.restart:
			self.sim = Simulation()
			self.restart = False
			self.bg_rendered = False
			self.start()

	def start(self):
		pygame.init()
		screen = pygame.display.set_mode((self.width, self.height))
		pygame.display.set_caption(Graphics_s.window_title)
		clock = pygame.time.Clock()

		status_exit = False
		move = False
		sleep_time = 0.05
		old_crits = []
		old_food = []

		while not status_exit:
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					status_exit = True
				if event.type == pygame.KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						status_exit  =True
					elif event.key == pygame.K_BACKSPACE:
						self.restart = True
						status_exit = True
					elif event.key == pygame.K_SPACE:
						move = (True, False)[move]
					elif event.key == pygame.K_TAB:
						for line in self.sim.stats():
							print line
						print "\n"
					elif event.key == pygame.K_PLUS:
						sleep_time += 0.05
						print sleep_time
					elif event.key == pygame.K_MINUS:
						sleep_time -= (0.05, 0)[sleep_time < 0.1]
						print sleep_time
					elif event.key == pygame.K_RIGHT:
						old_crits = self.sim.population.keys()
						old_food = self.sim.food.food.keys()
						self.sim.step()
					elif event.key == pygame.K_BACKSLASH:
						cmd = raw_input("insert command:")
						parse_cmd(cmd)
						print cmd
					elif event.key == pygame.K_s:
						for i, critter in enumerate(self.sim.population.values()):
							critter.brain.save(Graphics_s.brain_path + str(i) + Graphics_s.brain_ext)
						print "Saved"
					elif event.key == pygame.K_l:
						for i, critter in enumerate(self.sim.population.values()):
							critter.brain.load(Graphics_s.brain_path + str(i) + Graphics_s.brain_ext)
						print "Loaded"

			if move:
				old_crits = self.sim.population.keys()
				old_food = self.sim.food.food.keys()
				sleep(sleep_time)
				self.sim.step()

			render(screen, self.sim, old_crits, old_food, self.bg_rendered)
			if not self.bg_rendered:
				self.bg_rendered = True 
			pygame.display.update()

		pygame.quit()
开发者ID:nglgzz,项目名称:tale,代码行数:77,代码来源:graphics.py

示例4: EdenApp

# 需要导入模块: from simulation import Simulation [as 别名]
# 或者: from simulation.Simulation import step [as 别名]
class EdenApp():
    """The EdenApp class is the overall app.

    When it runs it creates two objects:
    The simulation, that runs the actual simulation.
    The ui, that presents visuals of the simulation on the screen.
    """

    def __init__(self, master):
        """Create the app."""
        self.master = master

        # create the simulation object
        utility.log_welcome()
        log("> Creating simulation")
        self.simulation = Simulation()

        # create the app
        log("> Creating UI")
        master.wm_title("Eden")
        self.frame = Frame(master)
        self.frame.grid()

        # create the ui
        self.ui = UI(self.master, self, self.frame)

        self.create_key_bindings()

        self.running = False
        self.time = 0

    def create_key_bindings(self):
        """Set up key bindings."""
        def leftKey(event):
            self.rotate_map(-10.0)

        def rightKey(event):
            self.rotate_map(10.0)

        def upKey(event):
            self.change_time_step(1)

        def downKey(event):
            self.change_time_step(-1)

        def spaceKey(event):
            self.toggle_running()

        self.master.bind('<Left>', leftKey)
        self.master.bind('<Right>', rightKey)
        self.master.bind('<Up>', upKey)
        self.master.bind('<Down>', downKey)
        self.master.bind('<space>', spaceKey)

    def step(self):
        """Advance one step in time."""
        self.time += settings.time_step_size
        self.ui.update_time_label(self.time)
        self.simulation.step()
        self.ui.paint_tiles()
        self.master.update()

    def rotate_map(self, degrees):
        """Spin the map."""
        for c in self.simulation.world.cells:
            c.longitude += degrees
            if c.longitude < 0:
                c.longitude += 360.0
            elif c.longitude >= 360.0:
                c.longitude -= 360.0

        self.simulation.world.cells = sorted(
            self.simulation.world.cells,
            key=attrgetter("latitude", "longitude"))
        self.ui.paint_tiles()

    def change_time_step(self, direction):
        """Change the time_step_size."""
        time_steps = [
            1,
            10,
            60,
            60*10,
            60*60,
            60*60*6,
            60*60*24,
            60*60*24*7,
            60*60*24*30,
            60*60*24*365,
            60*60*24*365*10,
            60*60*24*365*50,
            60*60*24*365*100,
            60*60*24*365*500,
            60*60*24*365*1000,
            60*60*24*365*10000,
            60*60*24*365*100000,
            60*60*24*365*1000000
        ]
        step_descriptions = [
            "1s",
#.........这里部分代码省略.........
开发者ID:thomasmorgan,项目名称:Eden,代码行数:103,代码来源:eden.py

示例5: MainWindow

# 需要导入模块: from simulation import Simulation [as 别名]
# 或者: from simulation.Simulation import step [as 别名]
class MainWindow(QtGui.QMainWindow, layoutgen.MainStats):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        uic.loadUi('ui/simulation.ui', self)

        self.sim = Simulation(400, negotiate_interval=90, submit_interval=200)
        self.sim.add_jobs()
        self.sim.farm.groups.update_quota(self.sim.farm)

        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.advance_interval)

        self.quitBtn.clicked.connect(self.close)
        self.stepBtn.clicked.connect(self.advance_interval)
        self.radioDepthFirst.toggled.connect(self.toggle_fill_algorithm)
        self.radioBreadthFirst.toggled.connect(self.toggle_fill_algorithm)
        self.startStop.clicked.connect(self.toggle_run)
        self.simspeedSlider.valueChanged.connect(self.change_speed)
        self.to_plot = set(g.name for g in self.sim.farm.groups.active_groups())
        self.all_groups = self.sim.display_order()

        # ms between firing timer
        self.period = 350
        self.auto_run = False

        self.qedit = ManageQueues(self.sim)
        self.quitBtn.clicked.connect(self.qedit.close)
        self.toolButton.clicked.connect(self.qedit.show)
        self.make_status_layout()

    def change_speed(self, val):

        self.simspeedSlider.setToolTip(str(val))
        self.simspeedLabel.setText('%dms delay' % val)
        self.period = val
        if self.auto_run:
            self.timer.start(val)

    def advance_interval(self):
        self.sim.step(self.stepSize.value())
        t = self.sim.farm.time
        st = 't=%d (n in %d, s in %d)' % (t,
             self.sim.next_negotiate - t, self.sim.next_submit - t)
        self.timeLabel.setText(st)
        for grp, lbl in self._stat_labels.items():
            group = self.sim.farm.groups.get_by_name(grp)
            lbl.setText(self._format_grpstr(group))
        self.update_plot()

    def update_plot(self):
        x, y = self.sim.make_plotdata(self.to_plot)
        self.mpl.canvas.ax.cla()
        self.mpl.canvas.ax.stackplot(x, y, colors=self.gen_color(), baseline='zero')
        self.mpl.canvas.draw()

    def gen_color(self):
        for n, grp in enumerate(self.all_groups):
            if grp in self.to_plot:
                yield colors[n]

    def toggle_fill_algorithm(self, state):
        if state and 'DepthFirst' in self.sender().objectName():
            self.sim._set_neg_df()
        elif state and 'BreadthFirst' in self.sender().objectName():
            self.sim._set_neg_bf()

    def toggle_run(self):
        if self.auto_run:
            self.timer.stop()
            self.startStop.setText('Run')
            self.auto_run = False
        else:
            self.timer.start(self.period)
            self.startStop.setText('Pause')
            self.auto_run = True
开发者ID:fubarwrangler,项目名称:atlassim,代码行数:78,代码来源:atlas.py


注:本文中的simulation.Simulation.step方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。