Esempio n. 1
0
 def _estimate_action(self, action):
     action = action.replace('act', '').replace(',', '')
     if action == '':
         pos = self.board.me.pos
     else:
         dir = Direction(action)
         pos = self.board.me.pos + dir.get_delta()
     return self._estimate_pos(pos)
Esempio n. 2
0
 def save_directions(route_xml, route_obj, api_call):
     directions = route_xml.findall('direction')
     for direction in directions:
         d =  Direction.get_or_create(db.session,
             tag = direction.get('tag'),
             title = direction.get('title'),
             name = direction.get('name'),
             route_id = route_obj.id,
             api_call_id = api_call.id)
Esempio n. 3
0
 def save_directions(route_xml, route_obj, api_call):
     directions = route_xml.findall('direction')
     for direction in directions:
         d = Direction.get_or_create(
             db.session,
             tag=direction.get('tag'),
             title=direction.get('title'),
             name=direction.get('name'),
             route_id=route_obj.id,
             api_call_id=api_call.id)
Esempio n. 4
0
 def parse_nn_output(self, y):
     """Return dictionary decoding numpy array of nn output."""
     output = {}
     # [0:2] Direction
     output['direction'] = Direction(int(''.join(str(i) for i in y[0:2]),
                                         2))
     # [2:3] Move
     output['move'] = bool(y[2])
     # [3:4] Comm Out
     output['comm_out'] = [bool(x) for x in y[3:4]]
     # [4:4+self.recurrent_nodes]
     output['recurrent_memory'] = y[4:4 + self.recurrent_nodes]
     return output
Esempio n. 5
0
 def initialize_agent(self, world, i, team, nn_model=None, nn_weights=None):
     agent = Agent(i)
     agent.move = bool(random.getrandbits(1))
     agent.direction = Direction(random.randrange(4))
     agent.team = team
     agent.recurrent_memory = np.array(self.recurrent_nodes * [0.0])
     if nn_model:
         agent.model = nn_model
     else:
         agent.model = self.initialize_agent_nn()
         if nn_weights:
             agent.model.set_weights(nn_weights)
     x = random.randrange(world.width)
     y = random.randrange(world.height)
     while (x, y) in world.agents:
         x = random.randrange(world.width)
         y = random.randrange(world.height)
     world.agents[(x, y)] = agent
     return (x, y)
Esempio n. 6
0
def new_recipe(root):
    title = root.find('recipe/head/title')
    try:
        quantity = root.find('recipe/head/yield').text.strip()
    except AttributeError:
        quantity = None

    cats = root.findall('recipe/head/categories/cat')
    cats_name = set([
        el.text for el in cats
        if el.text and len(el.text) > 1 and not el.text == 'None'
    ])
    categories = []
    for cat in cats_name:
        category = get_one_or_create(db.session, Category, title=cat)
        categories.append(category)

    # XXX check ingredients validity (None)
    ings = root.findall('recipe/ingredients/ing')
    ingredients = []
    for ing in ings:
        quantity = ing.find('amt/qty').text
        u, unit = ing.find('amt/unit'), None
        if u is not None:
            unit = u.text
        item = ing.find('item').text
        ingredients.append(Ingredient(quantity=quantity, unit=unit, item=item))

    # XXX split paragraph when only one step
    steps = root.findall('recipe/directions/step')
    directions = []
    for step in steps:
        if step.text:
            directions.append(Direction(step=step.text.strip()))

    return Recipe(title=title.text,
                  quantity=quantity,
                  directions=directions,
                  ingredients=ingredients,
                  categories=categories)
Esempio n. 7
0
	def connect_catalysis(self, control,places):
		"""
		this function connects the 2 catalysis places to the transitions which are part of the reaction they point to

		"""
		#get transitions
		transitions = self.net.get_transition(split_uri(control.controlled)[1])
		if len(transitions) ==1:
			existing_transition = transitions[0]
			new_transition = self.net.create_transition(existing_transition.id+"_"+split_uri(control.participant)[1],Direction.reverse(existing_transition.direction),existing_transition.control)

			#add arcs to controller
			self.connect_both_ways(new_transition,places[1])

			#add arcs to places
			#get arcs from existing_transition
			#Here it goes wrong...
			arcs = self.net.get_arcs(existing_transition)

			#reverse direction and connect to new_transition
			for arc in arcs:
				if arc.source.id == existing_transition.id and arc.target.id != split_uri(control.controlledId)[1]:
					self.net.create_arc(arc.target, new_transition)
				if arc.target.id == existing_transition.id and arc.source.id != split_uri(control.controlledId)[1]:
					self.net.create_arc(new_transition, arc.source)
		else:
			print("Error: More than 1 transition found")
Esempio n. 8
0
def add_user_navigation():
#     """Add a users navigation directions to the database for their route."""
#     from math import cos, asin, sqrt

    path_id = request.form.get('pathId')
    route_id = request.form.get('routeId')
    u_latitude = request.form.get('latitude')
    u_longitude = request.form.get('longitude')
    photo = request.files['imgFile']
    direction_text = request.form.get('directions')
    
    img_url = UPLOAD_FOLDER + photo.filename
    photo.save(img_url)

    route = Route.query.filter(Route.route_id == route_id).first()

    #route_waypoints is a list of integers representing the waypoints
    route_waypoints = route.waypoints
    w_latlongs = []

    for waypoint in route_waypoints:
        temp_dict = {}
        waypoint = Waypoint.query.filter(Waypoint.waypoint_id == waypoint).first()
        w_latitude = waypoint.latitude
        w_longitude = waypoint.longitude
        w_id = waypoint.waypoint_id
        temp_dict[w_id] = {'lat': w_latitude, 'lon': w_longitude}
        w_latlongs.append(temp_dict)

    for i in range(len(route_waypoints)):
        temp = {}
        w_id = route_waypoints[i]
        waypoint = Waypoint.query.filter(Waypoint.waypoint_id == w_id).first()
        w_latitude = waypoint.latitude
        w_longitude = waypoint.longitude
        temp['lat'] = w_latitude
        temp['long'] = w_longitude
        w_latlongs.append(temp)

    # def distance(lat1, lon1, lat2, lon2):
    #     # haversine formula. calculating distances b/w points on the globe
    #     p = 0.017453292519943295
    #     a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2
    #     return 12742 * asin(sqrt(a))

    # def closest(data, v):
    #     #data is a list of dictionaries containing the latitude and longitude

    #     return min(data, key=lambda p: distance(1.0,1.0,float(p['lat']),float(p['long'])))
    # v = {'lat':u_latitude,'long':u_longitude}

    # #for w_latlong in w_latlongs:
    #     #tempDataList.append(w_latlongs[w_id])
    # closest = closest(w_latlongs, v)


    # if abs(closest['lat'] - v['lat']) <= 5.0 and abs(closest['long'] - v['long']) <= 5.0:
    #     # for w_id in w_latlongs:
    #     #     if w_latlongs[w_id] == closest:
    #     step = Step.query.filter(Step.path_id == path_id).first()
    #     setattr(step, 'end_point', w_id)
    #     session.commit()

    #     step_start = w_id
    #     path_id = path_id
    #     step = Step(path_id=path_id,
    #                 step_start=step_start
    #                 )
    #     db.session.add(step)
    #     db.session.commit()
    # else:
    step = Step.query.filter(Step.path_id == path_id).all()
    step_id = step[-1]

    new_direction = Direction(step_id=step_id,
                              image_url=image_url,
                              direction_text=direction_text)

    db.session.add(new_direction)
    db.session.commit()
Esempio n. 9
0
 def received_command(self, command):
     decoded = loads(command)
     direction = Direction.create(decoded["direction"])
     for board in self.boards:
         board.turn_client(self.id, direction)
Esempio n. 10
0
 def direction(self, agency_tag, route_tag, direction_tag):
     return formatter.JSON(Direction.properties(agency_tag, route_tag, direction_tag))
Esempio n. 11
0
 def directions(self, agency_tag, route_tag):
     return formatter.JSON(Direction.get_or_fetch(agency_tag, route_tag))