def get_all_vehicles() -> List[Vehicle]: """ Recover all useful information about vehicles and creates a vehicles list :return: A list of vehicles instances """ vehicles = list() for veh_id in traci.vehicle.getIDList(): veh_pos = traci.vehicle.getPosition(veh_id) vehicle = Vehicle(veh_id, veh_pos) vehicle.emissions = compute_vehicle_emissions(veh_id) vehicles.append(vehicle) return vehicles
def _dataframe_to_vehicles(project, df, number_of_days): # Day of the project date = project.date tot_sec = (date - datetime.datetime.utcfromtimestamp(0)).total_seconds() from_mile_to_km = 1.60934 # Initialize a car model for the project project.car_models = [BasicCarModel(name='Leaf')] # Initialize itinerary data for each vehicle # Group the dataframe by vehicle_id, and for each vehicle_id, for vehicle_id, vehicle_data in df.groupby('id'): # Create a vehicle instance vehicle = Vehicle(vehicle_id, project.car_models[0]) try: vehicle.weight = vehicle_data.weight.iloc[0] except AttributeError: vehicle.weight = 0 # Create a list of activities parked and driving for index, row in vehicle_data.iterrows(): # Round the start and end time to correspond with project.timestep start = datetime.datetime.utcfromtimestamp(tot_sec + int( (row['start'] * 3600) / project.timestep) * project.timestep) end = datetime.datetime.utcfromtimestamp(tot_sec + int( (row['end'] * 3600) / project.timestep) * project.timestep) # Accordingly to the state create a driving or parked activity if row['state'] in 'Driving': vehicle.activities.append(Driving(start, end, row['distance'] * from_mile_to_km)) elif row['state'] in ['Parked', 'Charging']: vehicle.activities.append( Parked(start, end, unique_location_category(row['location'], project))) else: print('State should either be Driving, Parked or Charging') print('State was: ' + str(row['state'])) # Check time gap before appending vehicle to the project if not vehicle.check_activities(start_date=date, end_date=date + datetime.timedelta(days=number_of_days)): print('Itinerary does not respect the constraints') print(vehicle) project.vehicles.append(vehicle) # Initialize charging station at each location reset_charging_infrastructures(project) return project
def add_vehicle_info(input_fuel, input_mpg, user_id): seed_vehicle_info = Vehicle(fuel_type=input_fuel, mpg=input_mpg, user_id=user_id) db.session.add(seed_vehicle_info) db.session.commit() return seed_vehicle_info
def create_vehicle(mpg, fuel_type, user_id): """create and return a new users vehicle""" mileage = Vehicle(mpg=mpg, fuel_type=fuel_type, user_id= user_id) db.session.add(mileage) db.session.commit() return mileage
def generate_random_routefile(counter): file_location = "data/junction" + str(counter) + ".rou.xml" rn.seed() amount_of_cars = rn.randint(0, 10) # 0, 10 print("Hoeveel auto's: ", amount_of_cars) temp_amount = amount_of_cars #CARS.append("AUTO") while (temp_amount + 2) != 0 and amount_of_cars != 0: carname = 'AUTO' + str(temp_amount + 1) CARS.append(carname) temp_amount -= 1 if 'AUTO1' not in CARS and amount_of_cars > 0: CARS.append("AUTO1") if 'AUTO0' not in CARS and amount_of_cars >= 0: #print("hij append") CARS.append("AUTO0") save = CARS vtype_left = VehicleType.VehicleType("right_car") vtype_right = VehicleType.VehicleType("left_car") vtype_right.impatience = 1.0 vtype_right.jmIgnoreFoeProb = 1.0 vehicle = Vehicle.Vehicle(VEH_ID, depart=DEPART_TIME, route='4to2', color="1,0,0") with open(file_location, "w") as route_file: print("""<routes> """, vtype_left.printXML(), """" """, vtype_right.printXML(), """" <route id="4to2" edges="4to1 1to2" /> <route id="4to3" edges="4to1 1to3" /> <route id="4to5" edges="4to1 1to5" /> <route id="5to3" edges="5to1 1to3" /> <route id="3to5" edges="3to1 1to5" /> """, printvehicle(CARS, len(CARS), "", amount_of_cars), """ """, file=route_file) """" Route generation without flows """ # route = rn.choice(['5to3', '3to5']) # depart_time = float(rn.randint(0, 15))/10 # for i in range(1, rn.randint(2, 12)): # vehicle = Vehicle.Vehicle(i, route=route, depart=depart_time) # depart_time += 0.1 # print(vehicle.printXML(), file=route_file) # created_cars.append(str(i)) print("</routes>", file=route_file) route_file.flush() return save
def generate_routefile(file_location="data/junction.rou.xml"): created_cars = [VEH_ID] vtype_left = VehicleType.VehicleType("right_car") vtype_right = VehicleType.VehicleType("left_car") vtype_right.impatience = 1.0 vtype_right.jmIgnoreFoeProb = 1.0 route = rn.choice(['4to2', '4to3', '4to5']) vehicle = Vehicle.Vehicle(VEH_ID, depart=DEPART_TIME, route='4to2', color="1,0,0") with open(file_location, "w") as route_file: print("""<routes> """, vtype_left.printXML(), """" """, vtype_right.printXML(), """" <route id="4to2" edges="4to1 1to2" /> <route id="4to3" edges="4to1 1to3" /> <route id="4to5" edges="4to1 1to5" /> <route id="5to3" edges="5to1 1to3" /> <route id="3to5" edges="3to1 1to5" /> <flow id="up" color="1,1,0" begin="0" end= "200" probability="0.15" type="right_car"> <route edges="5to1 1to3"/> </flow> <flow id="down" color="1,1,0" begin="0" end= "200" probability="0.15" type="left_car"> <route edges="3to1 1to5"/> </flow> """, vehicle.printXML(), """ """, file=route_file) """" Route generation without flows """ # route = rn.choice(['5to3', '3to5']) # depart_time = float(rn.randint(0, 15))/10 # for i in range(1, rn.randint(2, 12)): # vehicle = Vehicle.Vehicle(i, route=route, depart=depart_time) # depart_time += 0.1 # print(vehicle.printXML(), file=route_file) # created_cars.append(str(i)) print("</routes>", file=route_file) return created_cars
def load_vehicles(vehicles_filename): """Load vehicles.""" print("Vehicle") for i, row in enumerate(open(vehicles_filename)): row = row.rstrip() vehicle_make, vehicle_model_name, vehicle_year = row.split("|") vehicle = Vehicle(vehicle_make=vehicle_make, vehicle_model_name=vehicle_model_name, vehicle_year=vehicle_year) db.session.add(vehicle) if i % 10 == 0: print(i) db.session.commit()
class CalcTest(unittest.TestCase): MIN_OPERATORS_PER_VEHICLE = 1 MAX_OPERATORS_PER_VEHICLE = 3 def setUp(self): self.vehicle = Vehicle() def test_initial_properties(self): self.assertTrue(hasattr(self.vehicle, 'health')) self.assertTrue(hasattr(self.vehicle, 'operators')) def test_initial_health(self): self.assertEqual(self.vehicle.health, 100) def test_initial_operators(self): self.assertTrue( len(self.vehicle.operators) >= self.MIN_OPERATORS_PER_VEHICLE) self.assertTrue( len(self.vehicle.operators) <= self.MAX_OPERATORS_PER_VEHICLE) def test_is_alive(self): self.assertTrue(self.vehicle.is_alive()) def test_is_not_alive_when_it_health_equal_null(self): self.vehicle.health = 0 self.assertFalse(self.vehicle.is_alive()) def test_is_not_alive_when_operators_died(self): self.vehicle.operators = [] self.assertFalse(self.vehicle.is_alive()) def test_get_take_damage_return_correct_value(self): self.assertGreaterEqual(self.vehicle.take_damage(), 0) self.assertLessEqual(self.vehicle.take_damage(), 100) def test_get_attack_success_probability_return_correct_value(self): self.assertGreaterEqual(self.vehicle.get_attack_success_probability(), 0) self.assertLessEqual(self.vehicle.get_attack_success_probability(), 1)
def setUp(self): self.vehicle = Vehicle()
def create_vehicles_from_stat(current_id, itinerary, project): """Create a new vehicle from a statistical itinerary Args: current_id (Integer): id assigned to the new vehicle itinerary (DataFrame): a row of project.itinerary_statistics project (Project): a project to append new locations if necessary Return: a vehicle object with a full day of activities """ not_completed = True max_iteration = 100 iteration = 0 # Duration shortening is to avoid itineraries to overpass 24h duration_shortening = 0 iteration_before_reducing_parked_duration = 25 while not_completed and iteration < max_iteration: iteration += 1 vehicle = Vehicle(current_id, project.car_models[0]) is_first_activity = lambda x: True if x == 0 else False is_last_activity = lambda x, y=len(itinerary.activity_statistics ) - 1: True if x == y else False is_duration_enough = lambda x: x if x > 60 else 60 if iteration % iteration_before_reducing_parked_duration == 0 and iteration != 0: duration_shortening += 0.1 # The activities one by one location_index = 0 parked = True try_again = False for index, activity in itinerary.activity_statistics.iterrows(): if is_first_activity(index): # This activity is assumed to be parked start = project.date # duration is int() to avoid milliseconds duration = int( scipy.stats.norm.rvs(activity.duration_loc, activity.duration_scale, 1)[0]) # duration is rounded at project.timestep duration -= duration % project.timestep duration = is_duration_enough(duration) duration -= duration * duration_shortening end = start + datetime.timedelta(seconds=duration) location = itinerary.locations[location_index] location_index += 1 parked = False # Append the activity vehicle.activities.append( Parked(start, end, unique_location_category(location, project))) elif is_last_activity(index): # This activity is assumed to be parked start = vehicle.activities[-1].end end = project.date + datetime.timedelta(days=1) location = itinerary.locations[location_index] # Append the activity vehicle.activities.append( Parked(start, end, unique_location_category(location, project))) elif parked: start = vehicle.activities[-1].end duration = int( scipy.stats.norm.rvs(activity.duration_loc, activity.duration_scale, 1)[0]) duration -= duration % project.timestep duration = is_duration_enough(duration) duration -= duration * duration_shortening end = start + datetime.timedelta(seconds=duration) location = itinerary.locations[location_index] location_index += 1 parked = False # Append the activity vehicle.activities.append( Parked(start, end, unique_location_category(location, project))) elif not parked: start = vehicle.activities[-1].end duration = int( scipy.stats.norm.rvs(activity.duration_loc, activity.duration_scale, 1)[0]) duration -= duration % project.timestep duration = is_duration_enough(duration) mean_speed = scipy.stats.norm.rvs(activity.mean_speed_loc, activity.mean_speed_scale, 1)[0] end = start + datetime.timedelta(seconds=duration) distance = ( duration / 3600 ) * mean_speed # duration in seconds and mean_speed in km/h vehicle.activities.append(Driving(start, end, distance)) parked = True # Post activity check if end > project.date + datetime.timedelta(days=1): # Some activity took too much time try_again = True break if not try_again: not_completed = False return vehicle
def from_excel(project, filename): """Read itineraries from an excel file. Excel header: Vehicle ID, Start time (hour), End time (hour), Distance (mi), P_max (W), Location, NHTS HH Wt. Args: project (Project): empty project filename (string): relative or absolute path to the excel file Return: project (Project): project assigned with vehicles """ print('itinerary.from_excel(project, ' + filename + ')') print('Loading ...') # Day of the project date = project.date tot_sec = (date - datetime.datetime.utcfromtimestamp(0)).total_seconds() df = pandas.read_excel(io=filename, sheetname='Activity') df = df.drop('Nothing', axis=1) df = df.rename( columns={ 'Vehicle ID': 'id', 'State': 'state', 'Start time (hour)': 'start', 'End time (hour)': 'end', 'Distance (mi)': 'distance', 'P_max (W)': 'maximum_power', 'Location': 'location', 'NHTS HH Wt': 'weight' }) from_mile_to_km = 1.60934 # Initialize a car model for the project project.car_models = [FuelCell()] # Initialize itinerary data for each vehicle # Group the dataframe by vehicle_id, and for each vehicle_id, for vehicle_id, vehicle_data in df.groupby('id'): # Create a vehicle instance vehicle = Vehicle(vehicle_id, project.car_models[0]) vehicle.weight = vehicle_data.weight.iloc[0] # Create a list of activities parked and driving for index, row in vehicle_data.iterrows(): # Round the start and end time to correspond with project.timestep start = datetime.datetime.utcfromtimestamp(tot_sec + int( (row['start'] * 3600) / project.timestep) * project.timestep) end = datetime.datetime.utcfromtimestamp(tot_sec + int( (row['end'] * 3600) / project.timestep) * project.timestep) # Accordingly to the state create a driving or parked activity if row['state'] in 'Driving': vehicle.activities.append( Driving(start, end, row['distance'] * from_mile_to_km)) elif row['state'] in ['Parked', 'Charging']: vehicle.activities.append( Parked(start, end, unique_location_category(row['location'], project))) else: print('State should either be Driving, Parked or Charging') print('State was: ' + str(row['state'])) # Check time gap before appending vehicle to the project if not vehicle.check_activities( start_date=date, end_date=date + datetime.timedelta(days=1)): print('Itinerary does not respect the constraints') print(vehicle) project.vehicles.append(vehicle) # Initialize charging station at each location reset_charging_infrastructures(project) print('') return project
def post_add_json(): """Add a post.""" user_id = session.get("user_id") if not user_id: flash("Please log in to access posts.") return redirect("/login") # raise Exception("No user logged in.") # Get form variables event_date = request.form.get("event_date") ptype = request.form.get("ptype") topic = request.form.get("topic") latitude = request.form.get("latitude") longitude = request.form.get("longitude") vehicle_plate = request.form.get("vehicle_plate") # event_date = request.form["event_date"] # ptype = request.form["ptype"] # topic = request.form["topic"] # latitude = request.form["latitude"] # longitude = request.form["longitude"] # vehicle_plate = request.form["vehicle_plate"] print latitude, longitude vehicle_plate = vehicle_plate.upper() # if not (latitude and longitude): # street = request.form["street"] # city = request.form["city"] # state = request.form["state"] # zipcode = request.form["zipcode"] # address = street + ", " + city + ", " + state + " " + zipcode # print address # location = Geocoder.geocode(address) # print location # print location.latitude # print location.longitude # print location[0] # print location[1] # vtype = request.form["vtype"] # make = request.form["make"] # model = request.form["model"] # color = request.form["color"] # TODO: iterate through form variables to eliminate blanks # TODO: iterate through form variables to verify data formats vehicle_check = Vehicle.query.filter_by(vehicle_plate=vehicle_plate).first() # vehicle must exist in db before post can be added if not (vehicle_check): vehicle = Vehicle(vehicle_plate=vehicle_plate, user_id_adder=user_id) # vehicle = Vehicle(vehicle_plate=vehicle_plate, vtype=vtype, make=make, model=model, color=color) db.session.add(vehicle) db.session.commit() post = Post(event_date=event_date, ptype=ptype, topic=topic, vehicle_plate=vehicle_plate, latitude=latitude, longitude=longitude, user_id=user_id) # print post db.session.add(post) db.session.commit() flash("Post added.") url = "/posts/detail/comments/" url = url + str(post.post_id) print url # return redirect("/posts/detail/comments/%s" % post.post_id) # return jsonify({'status': 'success'}) return jsonify({'status': 'success', 'redirect': url})