Esempio n. 1
0
	def decide_route(self, decision_node, last_visited_node, target):
		"""
		decision routine, decision depends on already visited nodes. 
		See thesis for further algorithm details. 
		"""

		# get adjacent edge
		node_neighbours = [neighbor for neighbor in self.graph.successors(decision_node) if neighbor != last_visited_node]

		# random choice pick two nearest (if only one possibility there, use it)
		if len(node_neighbours) > 1:
			s = [(self.graph.node[node]["geom"].distance(target), node) for node in node_neighbours]
			s.sort()
			s = [(s[0][1],2), (s[1][1],1)]
			target_node = wr.choice(s)
		else:
			target_node = node_neighbours[0]

		# get full edge path
		tmp = {}
		tmp["start_node"] = decision_node
		tmp["end_node"] = target_node
		tmp["eid"] = self.graph.edge[decision_node][target_node]["eid"]
		tmp["speed"] =  self.graph.edge[decision_node][target_node]["speed"]
		tmp["vecs"] = self.graph.edge[decision_node][target_node]["geom"].coords[:]
		tmp["start_pos"] = tmp["vecs"][0]
		tmp["end_pos"] = tmp["vecs"][-1]
		return tmp
Esempio n. 2
0
	def choose_exit(self, pos):
		""" weighted exit choosing depending on distance and attraction of exit"""
		exit_choices = []
		for exit in self.exits:
			exit_choices.append((1/shapely.geometry.Point(pos).distance(shapely.geometry.Point(exit["pos"])) / exit["weight"], exit["node"]))
		
		total = sum([choice[0] for choice in exit_choices])
		exit_choices = [(choice[1], int(choice[0] / total*100)) for choice in exit_choices]
		choice = wr.choice(exit_choices)
		return choice
Esempio n. 3
0
    def test_tuple(self):
        times = 10000
        data = [(('cat'), (60)), (('dog'), (30)), (('bird'), (10))]
        testcase = []
        for _ in range(times):
            testcase.append(wr.choice(data))
        counter = Counter(testcase)
        result =  dict(counter.most_common(3))

        self.assertTrue(result['cat'] > result['dog'])
        self.assertTrue(result['cat'] > result['bird'])
        self.assertTrue(result['dog'] < result['cat'])
        self.assertTrue(result['dog'] > result['bird'])
        self.assertTrue(result['bird'] < result['dog'])
        self.assertTrue(result['bird'] < result['cat'])
Esempio n. 4
0
 def test_dict(self):
     times = 10000
     data = {'cat': 60, 'dog': 30, 'bird': 10}
     testcase = []
     for _ in range(times):
         testcase.append(wr.choice(data))
     counter = Counter(testcase)
     result =  dict(counter.most_common(3))
     
     self.assertTrue(result['cat'] > result['dog'])
     self.assertTrue(result['cat'] > result['bird'])
     self.assertTrue(result['dog'] < result['cat'])
     self.assertTrue(result['dog'] > result['bird'])
     self.assertTrue(result['bird'] < result['dog'])
     self.assertTrue(result['bird'] < result['cat'])
Esempio n. 5
0
 def get_destination(self):
     destination = wr.choice(self.destinations)
     return destination
Esempio n. 6
0
 def get_destination(self):
     destination = wr.choice(self.destinations)
     return destination
Esempio n. 7
0
	def _fill(self, fill_config, actor_config):
		""" 
		Initial filling of lots. 
		First, the configuration files of the simulation scenario are parsed, then every lot is filled to its specified value.
		The actors' parameters which are used to fill the lot are taken from the config JSOBN via a weighted random choice.
		"""

		''' parse config files '''
		fill_file = open(os.path.dirname(__file__) +  "/" + fill_config)
		fill_json = json.load(fill_file)
		init_attributes = fill_json

		actor_file = open(os.path.dirname(__file__) +  "/" + actor_config)
		actor_json = json.load(actor_file)
		actor_attributes = actor_json

		for i,lot in enumerate(self.lots):
			self.percent_occupancy = 0

			# do until the lot is full
			while self.percent_occupancy < 70:

				# get size of actor
				size_choices = [(ix*0.5, el) for ix, el in enumerate(actor_attributes["residential"]["size_distribution"])]
				size = wr.choice(size_choices)

				# get remaining parking time of actor
				remaining_park_time_choices = [(ix, el) for ix, el in enumerate(init_attributes["remaining_duration"])]
				# parking_time = wr.choice(remaining_park_time_choices) + random.randint(0,1800)
				parking_time = wr.choice(remaining_park_time_choices)*3600 + random.randint(-1800,1800)

				# build actor attributes
				params = {
					"size": size,
					"color": actor_attributes["residential"]["color"],
					"name": actor_attributes["residential"]["name"],
					"forbidden_lot_types": actor_attributes["residential"]["forbidden_lot_types"],
					"pos":  lot.geometry.coords[0],
					"rot": 0,
					"speed": 0,
					"target_speed": 0,
					"target_location": None,
					"target_node_id": None,
					"parking_start_time": self.simulation.start_time,
					"parking_time": parking_time-self.simulation.start_time,
					"parking_size": size + 2 * random.random(),
					"search_tolerance": random.gauss(0.6, 0.1),
					"max_search_time": 0,
					"init_time": 0,
					"technology": None
				}

				# look for space , occupy and initialize actor there
				space = lot.look_for_space(params["pos"], params["parking_size"])
				if space == False:
					percent_occupancy = lot.lot_percentage()
					break
				else:
					#create actor
					actor = Actor(self.simulation.actor_manager, self.simulation.router, params, {"lot": lot, "space":space})

					# occupy, place and add actor to lot
					lot.occupy(space)
					self.simulation.actor_manager.add(actor)

					# give current edge parameters to actor:
					actor.current_route_element = {
						"eid": lot.edge[2]["eid"],
						"start_node":lot.edge[2]["start_nid"],
						"end_node":lot.edge[2]["end_nid"],
						"start_pos": lot.edge[2]["geom"].coords[0],
						"end_pos": lot.edge[2]["geom"].coords[-1],
						"vecs": []
					}
					actor.route = []

				self.percent_occupancy = lot.lot_percentage()


		print "--> filled lots with initial data"
Esempio n. 8
0
	def spawn(self, time, dt):
	
		''' get appropriate spawn rate '''
		current_hour = self.spawner.get_hour()
		spawn_rate = self.spawn_rate[current_hour]
		elapsed_hour_part = dt / 3600

		''' spawn or not '''
		if elapsed_hour_part*spawn_rate >= random.random():
			''' weighted random pick type '''
			type_dict_at_current_hour = [(key,value["spawn_percentage"][current_hour]) for key, value in self.actor_attributes.iteritems()]
			actor_type = wr.choice(type_dict_at_current_hour)

			''' get size '''
			size_choices = [(ix*0.5, el) for ix, el in enumerate(self.actor_attributes[actor_type]["size_distribution"])]
			size = wr.choice(size_choices)

			''' get target building (and nearest nodes to it):'''
			building_choices = [(building.geom, building.propabilities[actor_type]) for building in self.spawner.simulation.building_manager.buildings if building.propabilities[actor_type]]
			building = self.weighted_pick(building_choices) #needs float picking functionality
			nearest_nodes_to_building = [n["nid"] for n in self.spawner.simulation.spatial_db.nodes.find({"pos": {"$near": [building.x, building.y]}}).limit(2) if n["nid"] != self.node_id]
			target_node_id = random.choice(nearest_nodes_to_building)
			target_location = building

			''' get full path '''
			full_path = self.spawner.simulation.router.full_path(self.node_id, target_node_id)
			# if full path is empty (if the target node is the source node) do not spawn)
			if full_path == []:
				print "path is empty!"
				return False

			''' get parking time of actor '''
			park_time_choices = [(ix, el) for ix, el in enumerate(self.actor_attributes[actor_type]["parking_time"])]
			parking_time = wr.choice(park_time_choices)*3600 + random.randint(0,1800)

			''' specify actor params '''
			params = {
				"size": size,
				"color": self.actor_attributes[actor_type]["color"],
				"name": self.actor_attributes[actor_type]["name"],
				"forbidden_lot_types": self.actor_attributes[actor_type]["forbidden_lot_types"],
				"pos": self.node_pos,
				"rot": 0,
				"speed": 0,
				"target_speed": 10,
				"target_location": target_location,
				"source_node": self.node_id,
				"target_node": target_node_id,
				"parking_start_time": None,
				"parking_time": parking_time,
				"parking_size": size + 2 * random.random(),
				"max_search_time": random.gauss(600, 200),
				"search_tolerance": random.gauss(100, 50),
				"init_time": self.spawner.simulation.current_time, 
				"technology": wr.choice([(None, 80), ("reserve", 20)])
			}

			''' add actor to the actor manager object. maybe this could be done more elegantly '''
			actr = Actor(self.spawner.simulation.actor_manager, self.spawner.simulation.router, params)
			self.spawner.simulation.actor_manager.add(actr)
			self.spawned +=1

			''' non public parking options '''
			if actr.params["name"] == "residential":
				if random.random() < 0.3:
					actr.stats["result"] = "private_parking"
					actr.has_private_parking()

			elif actr.params["name"] == "shopping":
				if random.random() < 0.3:
					actr.stats["result"] = "parking_garage"
					actr.has_private_parking()

			elif actr.params["name"] == "visiting":
				if random.random() < 0.1:
					actr.stats["result"] = "private_parking"
					actr.has_private_parking()

			elif actr.params["name"] == "working":
				if random.random() < 0.8:
					actr.stats["result"] = "company_parking"
					actr.has_private_parking()