예제 #1
0
def fcfs_nearest_idle(av_fleet, customers, t):
    idle_avs = list(j_veh for j_veh in av_fleet
                    if j_veh.status in ("idle", "relocating"))
    unassign_cust = list(i_cust for i_cust in customers
                         if i_cust.status == "unassigned")

    used_vehicles = []
    count_p = -1
    for i_cust in unassign_cust:
        count_p += 1
        min_dist = Set.inf
        win_veh_index = -1
        veh_index = -1
        for j_av in idle_avs:
            veh_index += 1
            dist = Distance.dist_manhat_pick(i_cust, j_av)
            # make sure that two persons aren't assigned to same vehicle
            if dist < min_dist and not (j_av.vehicle_id in used_vehicles):
                win_veh_index = veh_index
                min_dist = dist
        if win_veh_index >= 0:
            win_vehicle = idle_avs[win_veh_index]
            used_vehicles.append(win_vehicle.vehicle_id)

            temp_veh_status = "base_assign"
            Vehicle.update_vehicle(t, i_cust, win_vehicle, Regions.SubArea,
                                   temp_veh_status)
            Person.update_person(t, i_cust, win_vehicle)
    return
예제 #2
0
파일: Test.py 프로젝트: M20190649/GSC
def processDataCollection(vhId, controlled):
	if controlled :
		controlledVehicles.add(vhId)
	
	#Process speed, distance and fuel data.
	#	vehicleData[vhId] -> list of speed, travel distance and fuel consumption at each time step
	if vhId in vehicleData:
		vehicleData[vhId].append([Vehicle.getTotalDistanceDriven(vhId), traci.vehicle.getSpeed(vhId), vehicleData[vhId][len(vehicleData[vhId])-1][2] + traci.vehicle.getFuelConsumption(vhId)])
	else:
		vehicleData[vhId] = [[Vehicle.getTotalDistanceDriven(vhId), traci.vehicle.getSpeed(vhId), traci.vehicle.getFuelConsumption(vhId)]]

	#Process time
	#	vehicleTime[vhId] -> pair of depart and finish time
	if vhId in vehicleTime:
		vehicleTime[vhId][1] = traci.simulation.getCurrentTime()
	else:
		vehicleTime[vhId] = [traci.simulation.getCurrentTime(), 0]
	

	#Process stopped vehicles
	if traci.vehicle.getRoadID(vhId) in TSSegments:
		if not vhId in VhStops and Vehicle.getTotalDistanceDriven(vhId) > 30:
			VhStops[vhId] = []
		if vhId in VhStops:
			if traci.vehicle.getSpeed(vhId) < SpeedStop:
			 	if len(VhStops[vhId]) == 0 or VhStops[vhId][len(VhStops[vhId])-1] > max(0,Vehicle._getDistanceNextTrafficLight(vhId)) + MinStopRange:			
					VhStops[vhId].append(max(0,Vehicle._getDistanceNextTrafficLight(vhId)))
예제 #3
0
def create_events():
    """ Creates new accidental car by parameters of vehicle that already exist. """
    acc_time_step = 5.0
    acc_id = '0#acc'

    new_acc_domain = Domain(acc_id, 1037.67, 585.98, 252.64, '10249819',
                            acc_time_step, acc_time_step + DOMAIN_DURATION)

    DOMAINS[acc_id] = new_acc_domain

    acc_veh_x, acc_veh_y = point_pos(new_acc_domain.mid_x,
                                     new_acc_domain.mid_y, DOMAIN_RANGE / 2,
                                     new_acc_domain.angle)

    acc_vehicle = Vehicle(acc_id,
                          acc_veh_x,
                          acc_veh_y,
                          speed=0,
                          lane=new_acc_domain.lane,
                          in_accident=True,
                          angle=new_acc_domain.angle)

    EVENTS[acc_time_step] = acc_vehicle
    EVENTS_IS_ONLINE[acc_id] = True

    message = Message(message_id=acc_id,
                      lifetime=MESSAGES_LIFETIME,
                      event_time_stamp=acc_time_step,
                      vehicle_type=VehicleType.SOURCE,
                      version_time_stamp=acc_time_step)

    acc_vehicle.set_messages_element(acc_id, message)
예제 #4
0
def create_butterfly(canvas, speed, mass):
    # open butterfly png file, resize it and import it to tkinter:
    image = Image.open(
        '/Users/konstantinosdimou/PycharmProjects/Vehicles/butterfly.png')
    im = image.resize((50, 50))
    img_butterfly = ImageTk.PhotoImage(im)
    # create a butterfly and draw it:
    butterfly = Vehicle(canvas, WIDTH, HEIGHT, speed, mass, img_butterfly)
    butterfly.draw()
    return butterfly
예제 #5
0
def create_wasp(canvas, speed, mass):
    # open wasp png file, resize it and import it to tkinter:
    image = Image.open(
        '/Users/konstantinosdimou/PycharmProjects/Vehicles/wasp.png')
    im2 = image.resize((50, 50))
    img_wasp = ImageTk.PhotoImage(im2)
    wasp = Vehicle(canvas, WIDTH, HEIGHT, speed, mass,
                   img_wasp)  # max speed 10, mass 4
    wasp.draw()
    return wasp
예제 #6
0
    def park(self, regno, driver_age):
        try:
            if self.numOfOccupiedSlots < self.capacity:
                if regno in self.regnos:
                    print(
                        "The car registration number is not unique. Inform the cops !!!"
                    )
                    exit(0)
                slotid = self.getEmptySlot()
                self.slots[slotid] = {
                    "reg_no": Vehicle.Car(regno),
                    "driver_age": Driver.Driver(driver_age)
                }
                self.slotid = self.slotid + 1
                self.numOfOccupiedSlots = self.numOfOccupiedSlots + 1
                self.regnos.append(regno)
                return slotid + 1

            else:
                return -1
        except AttributeError as error:
            print(
                "~~~ Please make sure to create the parking lot before retrieving the information from it."
            )
            exit(0)
예제 #7
0
    def park(self, regNo, color, vehicleType):
        if self.occupancy < self.capacity:
            lotId = self.availableSlot()
            if (vehicleType == 'TwoWheeler'):
                self.slots[lotId] = Vehicle.TwoWheeler(regNo, color)
            if (vehicleType == 'HatchBack'):
                self.slots[lotId] = Vehicle.HatchBack(regNo, color)
            if (vehicleType == 'SuvCar'):
                self.slots[lotId] = Vehicle.SuvCar(regNo, color)
            self.lotId = self.lotId + 1
            self.timeIn = datetime.now()
            self.occupancy = self.occupancy + 1
            return lotId + 1

        else:
            return -1
예제 #8
0
    def __init__(self, init_state=State(), drone_type=DroneType.robot_drone):
        self.drone_type = drone_type

        self.ax = np.full(timesteps, .1)
        self.ax[0] = 1
        self.ay = np.zeros(timesteps)
        self.omega = np.full(timesteps, 2)

        self.omega_m = []
        self.ax_m = []
        self.ay_m = []
        self.vehicle = Vehicle(init_state)

        self.sig_x0 = 0.05  # initial uncertainty of x
        self.sig_y0 = 0.05  # initial uncertainty of y
        self.sig_th0 = 0.01  # initial uncertainty of theta
        self.sig_vx0 = 0.001  # initial uncertainty of vx
        self.sig_vy0 = 0.001  # initial uncertainty of vy

        # covariance of measurements
        self.Pm = [
            np.diag([
                self.sig_x0, self.sig_y0, self.sig_th0, self.sig_vx0,
                self.sig_vy0
            ])
        ]
예제 #9
0
파일: web.py 프로젝트: AshishKumar4/Arlton
def dashboard():
    global db
    if "login" in session:
        if request.method == "POST":
            try:
                vnum = request.form['number']
                a = db.getVehicle(vnum)
                if a:
                    vinfo = Vehicle(a)

            except Exception as ex:
                print(ex)
                return render_template("/500.html")
            return render_template(
                "/dashboard.html",
                milage=vinfo.values['milage'],
                fuel=vinfo.values['fuel'],
                total_distance=vinfo.values['total_distance'],
                vnum=vinfo.values['vnum'],
                total_tires=vinfo.values['total_tires'],
                tires=json.dumps(vinfo.tires))
        return render_template("/dashboard.html")
    else:
        return render_template(
            "/index.html"
        )  #Fool them, they would think it dosen't exist until they log in
예제 #10
0
def init_veh(n_v, nr_feat, init_pos_distr, init_feat_distr, var_init):
    veh = []
    for i in range(n_v):
        veh_temp = Vehicle.Vehicle(i, nr_feat, init_pos_distr[i],
                                   init_feat_distr, var_init[i])
        veh.append(veh_temp)
    return veh
예제 #11
0
 def get_demand(self, demand_path):
     with open(demand_path) as csv_file:
         reader = csv.reader(csv_file)
         data = [row[:] for row in reader]
         del data[0]
     Demand = []
     for i in range(len(data)):
         if len(data[i][1]) > 8:
             data[i][1] = data[i][1][:19]  #Remove milliseconds
             data[i][1] = data[i][1][11:]
         data[i][1] = datetime.datetime.strptime(data[i][1], r"%H:%M:%S")
         if self.stime <= data[i][1] < self.etime:
             # Organize path data in a list
             if '-' in data[i][2]:
                 data[i][2] = data[i][2].split('-')
             if '-' in data[i][3]:
                 data[i][3] = data[i][3].split('-')
             if isinstance(data[i][2], str) == True:
                 data[i][2] = [data[i][2]]
                 data[i][3] = [data[i][3]]
             hphm = data[i][0]
             entrytime = data[i][1]
             road_path = data[i][2]
             direction_path = data[i][3]
             one_veh = Vehicle.Vehicle(hphm, entrytime, 0, road_path,
                                       direction_path)
             Demand.append(one_veh)
     print("Demand number:", len(Demand))
     return Demand
예제 #12
0
    def vehicle_generate(self, time_stamp, car_type, car_direction, which_lane,
                         ID):
        print('generating vehicles ... in the scene')
        numberOfCar = len(time_stamp)
        global_q_list = []
        # create 6 empty list for each lane
        for i in range(6):
            global_q_list.append([])
        # Every car is from either one of 6 directions below
        # N1 = [];
        # N2 = [];
        # N3 = [];
        # N4 = [];
        # E1 = [];
        # W1 = [];
        for i in range(numberOfCar):
            car_i = Vehicle.Vehicle((time_stamp[i]), car_type[i],
                                    car_direction[i], which_lane[i], ID[i])
            global_q_list[int(which_lane[i])].append(car_i)
        # add each car to certain lane

        # for i in range(6):  # heapify each lane
        #     heapq.heapify(global_q_list[i])

        return global_q_list
예제 #13
0
def addCar(station, arrive_time, time):
    # DEFAULT VALUES FROM CAR
    packCapacity = 30 #kWh
    maxChargeRate = 16 #kW
    initialSOC = 5 #kWh

    # Bind socket & grab info from app, print info
    print("Collecting data from phone application...")
    data = gather_app_data()

    print("Data = ", data)
    departure_time = data[0] + data[1]
    requestedCharge = data[3] * packCapacity

    print("Driver arrives at %.2f and requests to leave at %.2f with charge of %.2f kWh\n"
          % (arrive_time, departure_time, requestedCharge),
          "Car has initial charge of %.2f kWh, pack capacity of %.2f kWh, and max charge rate of %.2f kW "
          % (initialSOC, packCapacity, maxChargeRate), sep="")


    # Put vehicle in last spot of port 3
    station.ports[3].vehicles[2] = Vehicle(packCapacity, arrive_time, departure_time,
                                           requestedCharge, maxChargeRate, initialSOC, time)

    return
예제 #14
0
def main(args):
    i = 0
    mode = 0
    amount = 0
    if len(args) >= 2:
        i = int(args[1])
        if len(args) >= 3:
            mode = int(args[2])
            if len(args) == 4:
                amount = args[3]

    vehicle = Vehicle.Vehicle(0, 0, i, mode, amount)

    frame_time = 0.1

    while True:
        time.sleep(frame_time)

        vehicle.update(frame_time)

        # Kill the process if the vehicle has no nodes to exchange and has reached its destination.
        if len(vehicle.rented_path) == 0 and vehicle.done:
            vehicle.update(frame_time)
            #print(i, 'dead')
            return
예제 #15
0
    def test_vehicle_is_initialized_with_zero_position_and_velocity(self):
        subject = Vehicle.Vehicle()

        self.assertEqual(subject.position[0], 0)
        self.assertEqual(subject.position[1], 0)
        self.assertEqual(subject.velocity[0], 0)
        self.assertEqual(subject.velocity[1], 0)
예제 #16
0
    def test_set_state_also_activates_state(self):
        subject = Vehicle.Vehicle()
        mock_state = Mock()
        mock_state_activate = mock_state.activate = Mock()

        subject.set_state(mock_state)

        mock_state_activate.assert_called_once_with(subject)
예제 #17
0
	def run(self):
		print "Ready"
		global steeringMode
		global vehicle
		vehicle = Vehicle()
		steeringMode = SteeringMode()
		vehicle.setSteeringMode(steeringMode)

		while running and (self._time < 1000):
			BrickPiUpdateValues() # Ask BrickPi to update values for sensors/motors
			time.sleep(self._period / 1000.0)
			self._time = self._time + self._period
		
		while running: 
			vehicle.move(self._time)
			BrickPiUpdateValues()
			time.sleep(self._period / 1000.0)
			self._time = self._time + self._period
예제 #18
0
    def test_draw_updates_state(self):
        subject = Vehicle.Vehicle()
        mock_state_update = subject.state.update = Mock()
        pygame.draw.circle = Mock()
        pygame.draw.line = Mock()

        subject.draw(None)

        mock_state_update.assert_called_once_with(subject)
 def park(self, Reg_no, color):
     if self.Occupied_slots < self.capacity:
         Slot_ID = self.Empty_Slots()
         self.slots[Slot_ID] = Vehicle.Car(Reg_no, color)
         self.Slot_ID = self.Slot_ID + 1
         self.Occupied_slots = self.Occupied_slots + 1
         return Slot_ID + 1
     else:
         return -1
예제 #20
0
    def createVehicles(self, amount, cap):
        print("Creating vehicles.. \n")
        vehicles = []

        for i in range (0, amount):
            vehicles.append(Vehicle(i, cap, self.pos))
        
        print(str(amount)+" Vehicles created.\n")
        return vehicles
예제 #21
0
 def park(self, regno, color):
     if self.numOfOccupiedSlots < self.capacity:
         slotid = self.getEmptySlot()
         self.slots[slotid] = Vehicle.Car(regno, color)
         self.slotid = self.slotid + 1
         self.numOfOccupiedSlots = self.numOfOccupiedSlots + 1
         return slotid + 1
     else:
         return -1
예제 #22
0
def fcfs_smart_nn(av_fleet, customers, t):
    idle_avs = list(j_veh for j_veh in av_fleet
                    if j_veh.status in ("idle", "relocating"))
    len_avs = len(idle_avs)
    unassign_cust = list(i_cust for i_cust in customers
                         if i_cust.status == "unassigned")
    len_custs = len(unassign_cust)

    if len_avs >= len_custs:
        used_vehicles = []
        for i_cust in unassign_cust:
            win_vehicle = Vehicle.Vehicle
            min_dist = Set.inf
            for j_av in idle_avs:
                dist = Distance.dist_manhat_pick(i_cust, j_av)
                # make sure that two persons aren't assigned to same vehicle
                if dist < min_dist and j_av not in used_vehicles:
                    win_vehicle = j_av
                    min_dist = dist
            if win_vehicle.vehicle_id >= 0:
                used_vehicles.append(win_vehicle)

                temp_veh_status = "base_assign"
                Vehicle.update_vehicle(t, i_cust, win_vehicle, Regions.SubArea,
                                       temp_veh_status)
                Person.update_person(t, i_cust, win_vehicle)
    else:
        win_cust_list = []
        for j_av in idle_avs:
            min_dist = Set.inf
            win_cust = Person.Person
            for i_cust in unassign_cust:
                dist = Distance.dist_manhat_pick(i_cust, j_av)
                if dist < min_dist and i_cust not in win_cust_list:
                    win_cust = i_cust
                    min_dist = dist
            if win_cust.person_id >= 0:
                win_cust_list.append(win_cust)

                temp_veh_status = "base_assign"
                Vehicle.update_vehicle(t, win_cust, j_av, Regions.SubArea,
                                       temp_veh_status)
                Person.update_person(t, win_cust, j_av)
    return
 def park(self, name, reg_no, color, current_time):
     if self.num_of_occupied_slots < self.capacity:
         slot_id = self.get_empty_slot()
         self.slots[slot_id] = Vehicle.Car(name, reg_no, color,
                                           current_time)
         self.slot_id = self.slot_id + 1
         self.num_of_occupied_slots = self.num_of_occupied_slots + 1
         return slot_id + 1
     else:
         return -1
예제 #24
0
 def park(self, regno, color):
     print("New Car parking: " + str(regno) + str(color),
           self.occupied_slot, self.capacity)
     if self.occupied_slot < self.capacity:
         slot_id = self.get_empty_slot()
         self.slots[slot_id] = Vehicle.Car(regno, color)
         self.slot_id = self.slot_id + 1
         self.occupied_slot = self.occupied_slot + 1
         return slot_id + 1
     else:
         return -1
예제 #25
0
    def test_draws_circle_with_pygame(self):
        subject = Vehicle.Vehicle()
        mock_pygame_draw_circle = pygame.draw.circle = Mock()
        mock_pygame_draw_line = pygame.draw.line = Mock()
        mock_pygame_surface = Mock()

        subject.draw(mock_pygame_surface)

        self.assertEqual(mock_pygame_draw_circle.call_count, 2)
        mock_pygame_draw_circle.assert_called_with(mock_pygame_surface, ANY, ANY, ANY, ANY)
        mock_pygame_draw_line.assert_called_once_with(mock_pygame_surface, ANY, ANY, ANY, ANY)
예제 #26
0
def fcfs_longest_idle(av_fleet, customers, t):
    idle_avs = list(j_veh for j_veh in av_fleet
                    if j_veh.status in ("idle", "relocating"))
    len_avs = len(idle_avs)
    unassign_cust = list(i_cust for i_cust in customers
                         if i_cust.status == "unassigned")
    len_custs = len(unassign_cust)

    most_match_count = min(len_custs, len_avs)
    for z_match in range(most_match_count):
        min_request_time = min(list(i.request_time for i in unassign_cust))
        max_wait_cust = list(i for i in unassign_cust
                             if i.request_time == min_request_time)[0]
        min_last_drop_time = min(list(j.last_drop_time for j in idle_avs))
        long_wait_av = list(j for j in idle_avs
                            if j.last_drop_time == min_last_drop_time)[0]

        temp_veh_status = "base_assign"
        Vehicle.update_vehicle(t, max_wait_cust, long_wait_av, Regions.SubArea,
                               temp_veh_status)
        Person.update_person(t, max_wait_cust, long_wait_av)
    return
예제 #27
0
 def park(self,registrationNumber,driverAge):
         
         #if vacant slot available then park the car and return the slot number allocated
         if self.numOfOccupiedSlots < self.totalNumberOfSlots: 
                 slotNumber = self.getNextEmptySlot()
                 self.slots[slotNumber] = Vehicle.Car(registrationNumber,driverAge)
                 
                 #increase the number of occupied slots by 1 for every successful parking
                 self.numOfOccupiedSlots = self.numOfOccupiedSlots + 1
                 
                 return slotNumber+1
         else:
                 return -1
    def create_vehicle(self, labeled_bbox):
        vehicle = Vehicle()
        vehicle.n_detections = 1
        vehicle.n_non_detections = 0
        box_corners = labeled_bbox[1]
        vehicle.recent_x_left.append(box_corners[0][0])
        vehicle.recent_x_right.append(box_corners[1][0])
        vehicle.recent_y_top.append(box_corners[0][1])
        vehicle.recent_y_bottom.append(box_corners[1][1])

        vehicle.current_x_left = box_corners[0][0]
        vehicle.current_x_right = box_corners[1][0]
        vehicle.current_y_top = box_corners[0][1]
        vehicle.current_y_bottom = box_corners[1][1]
        self.vehicle_list.append(vehicle)
예제 #29
0
def parse_file(rushhour_file):
    """
    this function parses the rush hour game
    """
    file = open(rushhour_file)
    vehicles_list = []
    for line in file:
        if line.endswith('\n'):
            line = line[:-1]
        vehicle_id, x_coordinate, y_coordinate, direction = line
        vehicles_list.append(
            Vehicle(vehicle_id, int(x_coordinate), int(y_coordinate),
                    direction))
    file.close()
    return vehicles_list
def create_vehicle(prob_arrival,ratio,v_params):
    type = car_arrival(prob_arrival,ratio)
    if (type==-1):
        return None
    else:
        v = None
        if(type==1):
            v = np.random.uniform(v_params["v_besar_min"],v_params["v_besar_max"])
        elif(type==2):
            v = np.random.uniform(v_params["v_sedang_min"], v_params["v_sedang_max"])
        elif(type==3):
            v = np.random.uniform(v_params["v_kecil_min"], v_params["v_kecil_max"])
        else:
            return None

        return Vehicle( type,v, Posisi(0,1) )
예제 #31
0
    def read_single_search_page(self):
        page = self.get_search_page()
        soup = parse_page(page)

        car_rows = soup.find_all(class_="make_and_model")

        for car_row in car_rows:
            car = car_row.find("a")
            identifier = car["href"].replace("/used/", "")
            if identifier.isnumeric():
                print(f"Doing URL https://www.auto24.ee/used/{identifier}\t",
                      end="")
                try:
                    vehicle = Vehicle.Vehicle(identifier)
                    self.add_to_dict(identifier, vehicle)
                except Vehicle.AuctionException:
                    print("Auction, skipping.")
예제 #32
0
파일: Main1.py 프로젝트: sturmke/scripts
	def run(self):
	
		global vehicle
		vehicle = Vehicle()
		#vehicle.setStrategy("AvoidObstaclesNew")
		vehicle.setStrategy("RemoteControl")
		vehicle.setSteeringMode(steeringMode)
		# negeer 1sec alle sensoren
		while running and (self._time < 1000) : 
			BrickPiUpdateValues()
			time.sleep(self._period / 1000.0)
			self._time = self._time + self._period
		
		while running: 
			vehicle.move(self._time)
			BrickPiUpdateValues()
			time.sleep(self._period / 1000.0)
			self._time = self._time + self._period
예제 #33
0
from Vehicle import *

v1 = Vehicle("Chris",100,"N")
v2 = Vehicle("Jordan",200,"S")


v1.print_info()
v2.print_info()

v1.speed = 400
v1.direction = "S"
v2.drection = "N"
v2.speed = 500

print("Updated Vehicles:")

v1.print_info()
v2.print_info()



print("------------------------------------- Cars")
v3 = Car("Patrick",100,"W",15,0,20)
v3.print_info()
print("\n")
v3.xyz()
print("\n")
v3.drive(102)
v3.print_info()
print("\n")
v3.fill_up(2)