def create_flights(self): """ Create flights """ self.flights.append(Flight(1200, 10500, "Arlanda", "Berlin")) self.flights.append(Flight(2230, 18630, "Kastrup", "Arlanda")) self.flights.append(Flight(1725, 16123, "Kastrup", "London"))
def adicionar_voo(malha): os.system("cls") res = Caminho(malha) quit = False while (quit == False): while (True): origem = input_cidade("Digite a origem do voo:") res.buscaGeral(malha, origem) if (len(res.correspondencias) != 0): break else: res.correspondencias.clear() print("Origem não registrada na malha da empresa!") dest = input_cidade("Digite o destino: ") add = Voo(dest) try: distancia = int(input("Digite a distância do voo: ")) except: print("Valor inválido!!!") continue add.setDistancia(distancia) for i in res.correspondencias: if (novo_voo(i, add) == 0): quit = True break else: print("Não foi possível associar o novo voo a um nó/escala!") res.correspondencias.clear()
class TestAirport(unittest.TestCase): def setUp(self): self.airport = Airport() self.flight = Flight() self.flight2 = Flight(start_time=Date(day=29, month=11, year=2016, hour='17:30'), from_dest="Vancouver", to_dest="New York") self.terminal = Terminal() self.airport.add_terminal(self.terminal) def test_init(self): # passed self.assertEqual(self.airport.name, "Sofia") self.assertEqual(self.airport.terminals, [self.terminal]) def test_add_terminal(self): self.assertEqual(self.airport.add_terminal(self.terminal), [self.terminal, self.terminal]) def test_passengers_from_terminal(self): passenger = Passenger(first_name="Georgi", second_name="Atanasov", age=20, flight=self.flight) passenger2 = Passenger(flight=self.flight2) self.flight.add_passenger(passenger) self.flight2.add_passenger(passenger2) self.terminal.add_flight(self.flight) self.terminal.add_flight(self.flight2) self.assertEqual(self.airport.passengers_from_terminal(self.terminal), [passenger, passenger2])
def readAndRewrite(self): try: with open(self.dataFile, 'r') as source: avgVector = [] lineNum = 0 for line in source: line = line.strip() if line != "" and line[0] != "#": f = Flight(line,self.vocabulary) rewr = f.rewrite() if lineNum == 0: avgVector = rewr else: for x in range(len(avgVector)): avgVector[x] = (avgVector[x] * lineNum + rewr[x]) / (lineNum + 1) lineNum = lineNum + 1 #print(rewr) print('Vecteur moyen') return(avgVector) except: raise Exception("Error while loading the dataFile %s"%(self.dataFile))
def setUp(self): term = Terminal(1, 20) self.flight_1 = Flight(DateHour(18, 11, 2016, "12:00"), DateHour(18, 11, 2016, "16:20"), 100, 120, "Sofia", "Madrid", term) self.flight_2 = Flight(DateHour(19, 11, 2016, "15:45"), DateHour(19, 11, 2016, "20:30"), 90, 120, "Sofia", "London", term)
def get_flight(): """ Get a flight as a GeoJSON LineString """ christchurch = AIRPORT_SERVICE.get_airport('NZCH') auckland = AIRPORT_SERVICE.get_airport('NZAA') flight = Flight(christchurch, auckland, 0, 'km') return flight.to_geojson()
def setUp(self): self.terminal = Terminal() self.flight = Flight() self.flight2 = Flight(start_time=Date(day=29, month=11, year=2016, hour='17:30'), from_dest="Vancouver", to_dest="New York", end_time=Date(day=29, month=11, year=2016, hour='20:40')) self.terminal.add_flight(self.flight) self.terminal.add_flight(self.flight2)
def setUp(self): self.airport = Airport() self.flight = Flight() self.flight2 = Flight(start_time=Date(day=29, month=11, year=2016, hour='17:30'), from_dest="Vancouver", to_dest="New York") self.terminal = Terminal() self.airport.add_terminal(self.terminal)
def __init__(self): flight1 = Flight('VNA360', 'Vietnam', 'Netherlands', 100, datetime(2019, 12, 30, 11, 45), timedelta(hours=12, minutes=30)) flight2 = Flight('VJ974', 'VietNam', 'USA', 100, datetime(2019, 9, 30, 16, 15), timedelta(hours=18, minutes=15)) flight3 = Flight('VJ332', 'VietNam', 'NewZealand', 100, datetime(2019, 1, 24, 4, 35), timedelta(hours=5, minutes=40)) self.flights = [flight1, flight2, flight3]
def test_get_terminal_flights(self): flight_1 = Flight(DateHour(18, 11, 2016, "12:00"), DateHour(18, 11, 2016, "16:20"), 100, 120, "Sofia", "Madrid", self.term_1) flight_2 = Flight(DateHour(19, 11, 2016, "15:45"), DateHour(19, 11, 2016, "20:30"), 100, 120, "Sofia", "London", self.term_1) flight_3 = Flight(DateHour(18, 11, 2016, "22:00"), DateHour(19, 11, 2016, "00:55"), 100, 120, "Sofia", "Berlin", self.term_1) flights = [flight_1, flight_2, flight_3] self.assertEqual(self.term_1.get_terminal_flights(), flights)
def filteredRead (self, conditions): # conditions comme liste de conditions chacune de la forme [attName, modName, trigg] try: with open(self.dataFile, 'r') as source: res = [] for line in source: line = line.strip() if line != "" and line[0] != "#": f = Flight(line, self.vocabulary) if f.satisfaisant(conditions): res.append(f) return res except: raise Exception("Error while loading the dataFile %s"%(self.dataFile))
def fromDict(self, data): """ Takes a JSON object as parameter and populate attributes :param data: JSON object representing a duty """ self.nature = data['nature'] self.setStart(datetime.strptime(data['start'], datetime_format)) self.setEnd(datetime.strptime(data['end'], datetime_format)) self.departure = data['departure'] self.arrival = data['arrival'] for raw_flight in data['flights']: flight = Flight() flight.fromDict(raw_flight) self.addFlight(flight)
def buildDutiesAndFlights(self): """ Parses the raw strings to extract Duty and Flight instances """ full_time_pattern = re.compile( r'\s*(\d{2}\w{3}\d{4})\s+?(\d{2}:\d{2})\s+?\((\d{2}:\d{2})\)\s*') leg_pattern = re.compile(r'\d') duty_pattern = re.compile(r'\S') airport_pattern = re.compile(r'\D{3}') trip_pattern = re.compile(r'\s*\w+\s*') for raw_duty in self.raw_duties: # Start start_match = re.match(full_time_pattern, raw_duty['Start']) if start_match: start_time = self.getTimeFromMatch(start_match) else: start_time = None # End end_match = re.match(full_time_pattern, raw_duty['End']) if end_match: end_time = self.getTimeFromMatch(end_match) else: end_time = None # Departure departure_match = re.match(airport_pattern, raw_duty['From']) if departure_match: departure = departure_match.group(0) else: departure = "" # Arrival arrival_match = re.match(airport_pattern, raw_duty['To']) if arrival_match: arrival = arrival_match.group(0) else: arrival = "" if re.match(leg_pattern, raw_duty['Leg']): flight = Flight() flight.flight_number = raw_duty['Flight'] flight.setStart(start_time) flight.setEnd(end_time) flight.departure = departure flight.arrival = arrival last_duty = self.duties[len(self.duties) - 1] last_duty.addFlight(flight) elif (re.match(duty_pattern, raw_duty['Duty']) or re.match(trip_pattern, raw_duty['Trip'])): duty = Duty() if not duty.setNatureFromIOBCodes(raw_duty['Trip']): duty.nature = 'FLIGHT' duty.setStart(start_time) duty.setEnd(end_time) self.duties.append(duty)
def test_flight_creation(self): # Create a new airport - LAX self.LAX = Airport() self.LAX.set_name("LAX") # Check that the LAX airport currently has no flights LAXflights = self.LAX.get_flights() self.assertEqual(len(LAXflights), 0) # Create a new flight from LAX to Logan self.flightLAXToLogan = Flight.airports_to_from(self.LAX, self.Logan) self.flightLAXToLogan.set_flight_number("UA2274") self.flightLAXToLogan.set_flight_date("04-26-2020") self.flightLAXToLogan.set_flight_time("9:30pm") self.flightLAXToLogan.set_airline("United Airlines") # Add the new flight to LAX and Logan's flights self.Logan.add_flight(self.flightLAXToLogan) self.LAX.add_flight(self.flightLAXToLogan) # Check that the LAX airport now has this flight outgoing LAXflights = self.LAX.get_outgoing_flights() self.assertEqual(len(LAXflights), 1) self.assertEqual(LAXflights, [self.flightLAXToLogan]) # Check that Logan airport now has this flight incoming Loganflights = self.Logan.get_incoming_flights() self.assertEqual(Loganflights, [self.flightLAXToLogan]) # Remove flight in order to clean up for next test case self.Logan.remove_flight(self.flightLAXToLogan) self.LAX.remove_flight(self.flightLAXToLogan)
def setUpClass(cls): print("setUpClass()") # Initialize airports cls.Logan = Airport() cls.JFK = Airport() cls.Logan.set_name("Logan") cls.JFK.set_name("JFK") # Initialize passengers cls.Ben = Passenger("Ben") cls.Julia = Passenger("Julia") cls.Jamie = Passenger("Jamie") # Initialize flights cls.flightLoganToJFK = Flight.airports_to_from(cls.Logan, cls.JFK) # Flight 1 cls.flightLoganToJFK.set_flight_number("UA1161") cls.flightLoganToJFK.set_flight_date("04-27-2020") cls.flightLoganToJFK.set_flight_time("4:30pm") cls.flightLoganToJFK.set_airline("United Airlines") # Add flights to airport cls.Logan.add_flight(cls.flightLoganToJFK) cls.JFK.add_flight(cls.flightLoganToJFK)
def return_to_origin(cls, previous_airport, units): dest_airports = [cls._origin] close_airport = previous_airport.closest_airport(dest_airports, units) close_dist = previous_airport.distance_to(close_airport, units) flight = Flight(previous_airport, close_airport, close_dist, units) return flight
def __init__(self, conn, vehicle, flight_config): """ Read the config and set the initial transition map """ self.conn = conn state_cfgfile = str(flight_config) + "/states_transitions" state_commands_cfgfile = str(flight_config) + "/states_command" state_config = ConfigParser() state_config.readfp(open(state_cfgfile)) state_commands_config = ConfigParser() state_commands_config.readfp(open(state_commands_cfgfile)) states = state_config.sections() for state in states: transitions = state_config.get(state, 'transitions').split(",") self.abort_map[state] = state_config.get(state, 'abort') self.transition_map[state] = transitions self.commands_map[state] = state_commands_config.items(state) try: is_initial_state = state_config.get(state, 'initial_state') if is_initial_state: self.initial_state = state except Exception: pass self.state = self.initial_state self.vehicle = conn.space_center.active_vessel self.flight = Flight(conn)
def test_flight_cancel(self): # Create new flight from JFK to Logan self.flightJFKToLogan = Flight.airports_to_from(self.JFK, self.Logan) self.flightJFKToLogan.set_flight_number("SP9374") self.flightJFKToLogan.set_flight_date("04-28-2020") self.flightJFKToLogan.set_flight_time("6:30am") self.flightJFKToLogan.set_airline("Spirit Airlines") # Add flight to Logan and JFK self.Logan.add_flight(self.flightJFKToLogan) self.JFK.add_flight(self.flightJFKToLogan) # Double check that Logan has this flight self.assertEqual([self.flightJFKToLogan], self.Logan.get_incoming_flights()) # Add a new passenger to flight self.flightJFKToLogan.add_passenger(self.Jamie) # Double check that the passenger has this flight and vice versa self.assertEqual([self.Jamie], self.flightJFKToLogan.get_passengers()) self.assertEqual(self.Jamie.get_flight(), self.flightJFKToLogan) # Now, the flight got cancelled. Remove from airport self.Logan.remove_flight(self.flightJFKToLogan) self.JFK.remove_flight(self.flightJFKToLogan) # Check that the airport does not have this flight LoganIncoming = self.Logan.get_incoming_flights() self.assertEqual(len(LoganIncoming), 0) # Check that the passenger no longer has this flight as it is cancelled self.assertEqual(self.Jamie.get_flight(), None)
def fillFlights(): src = "resources//flights.json" with open(src, "r") as f: for line in f: print(line) cust = Flight(line) backend.add(cust)
def init_synthethic_dataset(self): self.database = {} passengers = [Passenger(name) for name in ["john green", \ "louie anderson", \ "liza koshy"]] bookings = [Booking(*booking) for booking in [("AMS", "ZRH", "10-Dec-2018"), \ ("LHR", "AMS", "01-Jan-2019"), \ ("BER", "ARN", "02-Mar-2019")]] flights = [Flight(*flight) for flight in \ [("KLM", "AMS", "BSL", "10-Dec-2018", 200), \ ("SWISS", "BSL", "ZRH", "10-Dec-2018", 100), \ ("KLM", "LHR", "AMS", "01-Jan-2019", 300), \ ("Eurowings", "BER", "ARN", "02-Mar-2019", 300)]] tickets = [Ticket(*ticket) for ticket in \ [(passengers[0], flights[0], "economy"), (passengers[0], flights[1], "economy"), (passengers[1], flights[2], "business"), \ (passengers[2], flights[3], "economy")]] bookings[0].add_ticket(tickets[0]) bookings[0].add_ticket(tickets[1]) bookings[1].add_ticket(tickets[2]) bookings[2].add_ticket(tickets[3]) self.database["passengers"] = passengers self.database["bookings"] = bookings self.database["flights"] = flights self.database["tickets"] = tickets self.database["name_to_tickets"] = { passenger.name: [] for passenger in passengers } for ticket in tickets: self.database["name_to_tickets"][ticket.client.name] += [ticket]
def _simulated_agent_init(self, experiment): # defaults self.mass = 2.88e-6 # avg. mass of our colony (kg) =2.88 mg, self.time_max = 15. self.dt = 0.01 self.max_bins = int(np.ceil(self.time_max / self.dt)) # N bins # from gassian fit to experimental control data self.initial_velocity_mu = 0.18 self.initial_velocity_stdev = 0.08 # useful aliases self.experiment = experiment self.windtunnel = self.experiment.environment.windtunnel self.bounded = self.experiment.experiment_conditions['bounded'] self.boundary = self.windtunnel.boundary self.heat = self.experiment.environment.heat # useful lists TODO: get rid of? self.kinematics_list = ['position', 'velocity', 'acceleration'] # curvature? self.forces_list = ['total_f', 'random_f', 'stim_f'] self.other_list = ['tsi', 'times', 'decision', 'heat_signal', 'in_plume'] # mk forces self.flight = Flight(self.random_f_strength, self.stim_f_strength, self.damping_coeff)
def setUp(self): self.flight = Flight(start_time=Date(29, 11, 2016, hour='12:20'), end_time=Date(29, 11, 2016, hour='15:30'), passengers=100, max_passengers=120, from_dest="Sofia", to_dest="London", terminal=Terminal(2, 30), declined=False)
def create_app(): app = Flask(__name__) app.config.from_object("settings") app.add_url_rule("/", view_func=views.home_page) app.add_url_rule("/flights", view_func=views.flights_page) app.add_url_rule("/flights/<int:flight_key>", view_func=views.flight_page) app.add_url_rule("/add_country", view_func=views.add_page, methods=["GET", "POST"]) app.add_url_rule("/countries", view_func=views.countries_page) db = Database() db.add_flight(Flight("IST-ESB", date="10-10-2018", airport="IST")) db.add_flight(Flight("IST-LON", date="09-10-2018", airport="IST")) app.config["db"] = db return app
def parse_flight_info(flight): results = flight.split(",") results[2] = datetime.strptime(results[2], DATE_FORMAT) results[3] = datetime.strptime(results[3], DATE_FORMAT) results[5] = int(results[5]) results[6] = int(results[6]) results[7] = int(results[7]) return Flight(*results)
def parse_flight(flight): params = flight.split(",") params[2] = datetime.strptime(params[2], DATE_FORMAT) params[3] = datetime.strptime(params[3], DATE_FORMAT) params[5] = int(params[5]) params[6] = int(params[6]) params[7] = int(params[7]) return Flight(*params)
def GetFlightDetail(flightno): cur = con.cursor() cur.execute("SELECT * FROM FLIGHT WHERE flightno=" + str(flightno)) data = cur.fetchone() if (data == None): return None flight = Flight(data[0], data[1], data[2], data[3], data[4], data[5]) return flight
def traverse_airports(dest_airports, previous_airport, units): flights = [] dest_airports.remove(previous_airport) while len(dest_airports) >= 1: close_airport = previous_airport.closest_airport(dest_airports, units) close_dist = previous_airport.distance_to(close_airport, units) flight = Flight(previous_airport, close_airport, close_dist, units) flights.append(flight) previous_airport = close_airport dest_airports.remove(close_airport) return flights
def create(self,flightno,takeofftime,takepoint,registrationNo,destination,landingtime,price): aircraft = self.acmgr.find(registrationNo) if aircraft == None: print("Aircraft", registrationNo, "is not available") return False else: avalFlight = Flight(flightno,takeofftime,takepoint,destination,landingtime,price) self.Flights.append(avalFlight) self.file.write(f"{str(avalFlight)}\n") self.file.flush() return True
def readFlight(self): line = self.source.readline() if len(line) == 0: return None line = line.strip() while line == "" or line[0] == "#": line = self.source.readline() if len(line) == 0: return None line = line.strip() return Flight(line, self.vocabulary)
def GetFlightDetails(): cur = con.cursor() cur.execute("SELECT * FROM FLIGHT") data = cur.fetchall() flights = [] for record in data: flight = Flight(record[0], record[1], record[2], record[3], record[4], record[5]) flights.append(flight) return flights
def readAndFilterAndRewrite(self, conditions) : res = [] avgVector = [] try: with open(self.dataFile, 'r') as source: for line in source: line = line.strip() if line != "" and line[0] != "#": f = Flight(line,self.vocabulary) if f.satisfaisant(conditions): res.append(f) print(f.rewrite()) print(len(res)) for i in range(len(res[0].rewrite())): avgVector.append(sum([f.rewrite()[i] for f in res])/len(res)) print(avgVector) return avgVector except: raise Exception("Error while loading the dataFile %s"%(self.dataFile))
class Simulator: """Our simulated mosquito. """ def __init__(self, experiment, agent_kwargs): """ Load params """ # dump kwarg dictionary into the agent object for key, value in agent_kwargs.iteritems(): setattr(self, key, value) self.decisions = Decisions(self.decision_policy, self.stimulus_memory_n_timesteps) if experiment.is_simulation: self._simulated_agent_init(experiment) def _simulated_agent_init(self, experiment): # defaults self.mass = 2.88e-6 # avg. mass of our colony (kg) =2.88 mg, self.time_max = 15. self.dt = 0.01 self.max_bins = int(np.ceil(self.time_max / self.dt)) # N bins # from gassian fit to experimental control data self.initial_velocity_mu = 0.18 self.initial_velocity_stdev = 0.08 # useful aliases self.experiment = experiment self.windtunnel = self.experiment.environment.windtunnel self.bounded = self.experiment.experiment_conditions['bounded'] self.boundary = self.windtunnel.boundary self.heat = self.experiment.environment.heat # useful lists TODO: get rid of? self.kinematics_list = ['position', 'velocity', 'acceleration'] # curvature? self.forces_list = ['total_f', 'random_f', 'stim_f'] self.other_list = ['tsi', 'times', 'decision', 'heat_signal', 'in_plume'] # mk forces self.flight = Flight(self.random_f_strength, self.stim_f_strength, self.damping_coeff) # turn thresh, in units deg s-1. # From Sharri: # it is the stdev of the broader of two Gaussians that fit the distribution of angular velocity # # create repulsion landscape # self._repulsion_funcs = repulsion_landscape3D.landscape(boundary=self.boundary) def fly(self, n_trajectories=1): """ runs _generate_flight n_trajectories times """ df_list = [] traj_i = 0 try: if self.verbose: print """Starting simulations with {} heat model and {} decision policy. If you run out of patience, press <CTL>-C to stop generating simulations and cut to the chase scene.""".format( self.heat.heat_model_name, self.decision_policy) while traj_i < n_trajectories: # print updates if self.verbose: sys.stdout.write("\rTrajectory {}/{}".format(traj_i + 1, n_trajectories)) sys.stdout.flush() array_dict = self._generate_flight() # if len(array_dict['velocity_x']) < 5: # hack to catch when optimizer makes trajectories explode # print "catching explosion" # break # add label column to enumerate the trajectories array_len = len(array_dict['tsi']) array_dict['trajectory_num'] = [traj_i] * array_len # mk df, add to list of dfs df = pd.DataFrame(array_dict) # df = df.set_index(['trajectory_num']) df_list.append(df) traj_i += 1 if traj_i == n_trajectories: if self.verbose: sys.stdout.write("\rSimulations finished. Performing deep magic.") sys.stdout.flush() except KeyboardInterrupt: print "\n Simulations interrupted at iteration {}. Moving along...".format(traj_i) pass observations = Observations() observations.kinematics = pd.concat(df_list) # concatenate all the data frames at once for performance boost. return observations def _generate_flight(self): """Generate a single trajectory using our model. First put everything into np arrays stored inside of a dictionary """ dt = self.dt m = self.mass vector_dict = self._initialize_vector_dict() # # dynamically create easy-to-read aliases for the contents of vector_dict # for key, value in vector_dict.iteritems(): # exec(key + " = vector_dict['" + key + "']") # unpack vector dict into nicer aliases in_plume = vector_dict['in_plume'] heat_signal = vector_dict['heat_signal'] position = vector_dict['position'] velocity = vector_dict['velocity'] acceleration = vector_dict['acceleration'] random_f = vector_dict['random_f'] stim_f = vector_dict['stim_f'] total_f = vector_dict['total_f'] decision = vector_dict['decision'] position[0] = self._set_init_position() velocity[0] = self._set_init_velocity() for tsi in vector_dict['tsi']: in_plume[tsi] = self.heat.check_in_plume_bounds(position[tsi]) # returns False for non-Bool plume decision[tsi], heat_signal[tsi] = self.decisions.make_decision(in_plume[tsi], velocity[tsi][1]) if heat_signal[tsi] == 'X': # this is an awful hack telling us to look up the gradient heat_signal[tsi] = self.heat.get_nearest_gradient(position[tsi]) stim_f[tsi], random_f[tsi], total_f[tsi] = self.flight.calc_forces(velocity[tsi], decision[tsi], heat_signal[tsi]) # calculate current acceleration acceleration[tsi] = total_f[tsi] / m # check if time is out, end loop before we solve for future velo, position if tsi == self.max_bins-1: # -1 because of how range() works vector_dict = self._land(tsi, vector_dict) break ################################################ # Calculate candidate velocity and positions ################################################ candidate_velo = velocity[tsi] + acceleration[tsi] * dt # make sure velocity doesn't diverge to infinity if system is unstable # this stops the optimizer from crashing candidate_velo = self._velocity_ceiling(candidate_velo) candidate_pos = position[tsi] + candidate_velo * dt ################################################ # test candidates ################################################ if self.bounded: candidate_pos, candidate_velo = self._collide_with_wall(candidate_pos, candidate_velo) position[tsi + 1] = candidate_pos velocity[tsi + 1] = candidate_velo # once flight is finished, make dictionary ready to be loaded into DF vector_dict = self._fix_vector_dict(vector_dict) return vector_dict def _land(self, tsi, V): ''' trim excess timebins in arrays ''' if tsi == 0: # hack for if we need to chop a trajectory at the very start for k, array in V.iteritems(): V[k] = array[:1] else: for k, array in V.iteritems(): V[k] = array[:tsi - 1] V[k] = array[:tsi - 1] return V def _collide_with_wall(self, candidate_pos, candidate_velo): walls = self.windtunnel.walls xpos, ypos, zpos = candidate_pos xvelo, yvelo, zvelo = candidate_velo teleport_distance = 0.005 # this is arbitrary crash = False # print "test", candidate_velo # x dim if xpos < walls.downwind: # too far behind crash = True xpos = walls.downwind + teleport_distance # teleport back inside if self.collision_type == 'elastic': xvelo *= -1. elif self.collision_type == 'part_elastic': xvelo *= -self.restitution_coeff elif self.collision_type == 'crash': xvelo = 0. else: raise ValueError("unknown collision type {}".format(self.collision_type)) if xpos > walls.upwind: # reached far (upwind) wall (end) crash = True xpos = walls.upwind - teleport_distance # teleport back inside if self.collision_type == 'elastic': xvelo *= -1. elif self.collision_type == 'part_elastic': xvelo *= -self.restitution_coeff elif self.collision_type == 'crash': xvelo = 0. # y dim if ypos < walls.left: # too left crash = True ypos = walls.left + teleport_distance if self.collision_type == 'elastic': yvelo *= -1. elif self.collision_type == 'part_elastic': yvelo *= -self.restitution_coeff elif self.collision_type == "crash": yvelo = 0. if ypos > walls.right: # too far right crash = True ypos = walls.right - teleport_distance if self.collision_type == 'elastic': yvelo *= -1. elif self.collision_type == 'part_elastic': yvelo *= -self.restitution_coeff elif self.collision_type == 'crash': yvelo = 0. # z dim if zpos > walls.ceiling: # too far above crash = True zpos = walls.ceiling - teleport_distance if self.collision_type == 'elastic': zvelo *= -1. elif self.collision_type == 'part_elastic': zvelo *= -self.restitution_coeff elif self.collision_type == "crash": zvelo = 0. if zpos < walls.floor: # too far below crash = True zpos = walls.floor + teleport_distance if self.collision_type == 'elastic': zvelo *= -1. elif self.collision_type == 'part_elastic': zvelo *= -self.restitution_coeff elif self.collision_type == 'crash': zvelo = 0. try: candidate_pos, candidate_velo = np.array([xpos, ypos, zpos]), np.array([xvelo, yvelo, zvelo]) except: print " cand velo", [xvelo, yvelo, zvelo], "before", candidate_velo return candidate_pos, candidate_velo def _initialize_vector_dict(self): """ initialize np arrays, store in dictionary """ V = {} for name in self.kinematics_list + self.forces_list: V[name] = np.full((self.max_bins, 3), np.nan) V['tsi'] = np.arange(self.max_bins) V['times'] = np.linspace(0, self.time_max, self.max_bins) V['in_plume'] = np.zeros(self.max_bins, dtype=bool) V['heat_signal'] = np.array([None] * self.max_bins) V['decision'] = np.array([None] * self.max_bins) return V def _set_init_velocity(self): initial_velocity_norm = np.random.normal(self.initial_velocity_mu, self.initial_velocity_stdev, 1) unit_vector = generate_random_unit_vector() velocity_vec = initial_velocity_norm * unit_vector return velocity_vec def _set_init_position(self): ''' puts the agent in an initial position, usually within the bounds of the cage Options: [the cage] door, or anywhere in the plane at x=.1 meters set initial velocity from fitted distribution ''' # generate random intial velocity condition using normal distribution fitted to experimental data if self.initial_position_selection == 'realistic': """these were calculated by taking selecting the initial positions of all observed trajectories in all conditions. Then, for each dimension, I calculated the distance of each initial position to the nearest wall in that dimension (i.e. for each z I calculated the distance to the floor and ceiling and selected the smallest distance. Then, Decisions aand""" downwind, upwind, left, right, floor, ceiling = self.boundary x_avg_dist_to_wall = 0.268 y_avg_dist_to_wall = 0.044 z_avg_dist_to_wall = 0.049 x = choose([(downwind + x_avg_dist_to_wall), (upwind - x_avg_dist_to_wall)]) y = choose([left + y_avg_dist_to_wall, (right - y_avg_dist_to_wall)]) z = ceiling - z_avg_dist_to_wall initial_position = np.array([x,y,z]) elif self.initial_position_selection == 'downwind_high': initial_position = np.array( [0.05, np.random.uniform(-0.127, 0.127), 0.2373]) # 0.2373 is mode of z pos distribution elif type(self.initial_position_selection) is list: initial_position = np.array(self.initial_position_selection) elif self.initial_position_selection == "door": # start trajectories as they exit the front door initial_position = np.array([0.1909, np.random.uniform(-0.0381, 0.0381), np.random.uniform(0., 0.1016)]) # FIXME cage is actually suspending above floor elif self.initial_position_selection == 'downwind_plane': initial_position = np.array([0.1, np.random.uniform(-0.127, 0.127), np.random.uniform(0., 0.254)]) else: raise Exception('invalid agent position specified: {}'.format(self.initial_position_selection)) return initial_position def _velocity_ceiling(self, candidate_velo): """check if we're seeing enormous velocities, which sometimes happens when running the optimization algoirithm. if so, cap the velocity instead of landing. this allows the optimizer to keep running. """ for i, velo in enumerate(candidate_velo): if velo > 20: candidate_velo[i] = 20. elif velo < -20: candidate_velo[i] = -20. return candidate_velo def _fix_vector_dict(self, dct): # prepare dict for loading into pandas (dataframe only accepts 1D vectors) # split xyz dicts into separate x, y, z vectors for dataframe fixed_dct = {} for kinematic in self.kinematics_list + self.forces_list: fixed_dct[kinematic + '_x'], fixed_dct[kinematic + '_y'], fixed_dct[kinematic + '_z'] = np.split( dct[kinematic], 3, axis=1) # migrate rest of dict for v in self.other_list: fixed_dct[v] = dct[v] # fix pandas bug when trying to load (R,1) arrays when it expects (R,) arrays for key, dct in fixed_dct.iteritems(): fixed_dct[key] = fixed_dct[key].reshape(len(dct)) if fixed_dct[key].size == 0: fixed_dct[key] = np.array([0.]) # hack so that kde calculation doesn't freeze on empty arrays return fixed_dct