def assign_ride(self, ride: Ride):
     self.assigned_rides.append(ride.id)
     self.current_ride = ride
     ride.is_taken = True
     self.busy = True
     self.wait_for = self.calculate_distance(
         ride) + ride.calculate_distance()
Пример #2
0
def main():
    filename = argv[1]
    numvehicles = 0
    timesteps = 0
    rides = []
    with open(filename, 'r') as file:
        content = file.readlines()
        for idx, line in enumerate(content):
            values = [int(x) for x in line.rstrip().split(" ")]
            if idx == 0:
                numvehicles = values[2]
                timesteps = values[5]
            else:
                rides.append(
                    Ride(idx, (values[0], values[1]), (values[2], values[3]),
                         values[4], values[5]))
    vehicles = generateVehicles(numvehicles)
    for t in range(timesteps):
        removeImpossible(rides, t)
        for vehicle in vehicles:
            if (vehicle.t_free <= t):
                ride_index = pickRide(rides, vehicle.position, t)
                if ride_index != -1:
                    vehicle.rides_started.append(ride_index)
                    vehicle.t_free = t + calcDistance(
                        vehicle.position, rides[ride_index].s_position) + max(
                            0, rides[ride_index].earliest_start -
                            (t + calcDistance(vehicle.position,
                                              rides[ride_index].s_position))
                        ) + rides[ride_index].distance
                    rides[ride_index].valid = False
    write_output(vehicles)
Пример #3
0
def read_from_file(filename):
    """

    :rtype:
    R - number of rows in grid
    C – number of columns of the grid
    F – number of vehicles in the fleet
    N – number of rides
    B – per-ride bonus for starting the ride on time
    T – number of steps in the simulation
    Rides - list of rides
    """
    with open(filename, "r") as file:
        counter = 0
        constants = []
        rides = []
        for line in file:
            line = line.strip("\n")
            
            if counter == 0:
                constants = line.split(" ")
            else:
                ride_raw = line.split(" ")
                rides.append(Ride(counter - 1, *ride_raw))

            counter += 1

        return constants, rides
Пример #4
0
def process_input(filename):
    output = {}
    with open(filename) as file:
        metadata = list(map(lambda x: int(x), file.readline().split(" ")))
        output["rows"] = metadata[0]
        output["cols"] = metadata[1]
        output["vehicles"] = metadata[2]
        output["numRides"] = metadata[3]
        output["startBonus"] = metadata[4]
        output["steps"] = metadata[5]
        rides = []
        for index, line in enumerate(file):
            ride = {}
            lineProcessed = list(map(lambda x: int(x), line.split(" ")))
            ride["startRow"] = lineProcessed[0]
            ride["startCol"] = lineProcessed[1]
            ride["finishRow"] = lineProcessed[2]
            ride["finishCol"] = lineProcessed[3]
            ride["earliestStart"] = lineProcessed[4]
            ride["latestFinish"] = lineProcessed[5]
            rides.append(
                Ride(index, lineProcessed[0], lineProcessed[1],
                     lineProcessed[2], lineProcessed[3], lineProcessed[4],
                     lineProcessed[5]))
        output["rides"] = rides
    return output
Пример #5
0
def read_input(file):

    input = open(file, "r")
    content = input.readlines()
    input.close()

    #first line
    elems = content[0].strip().split(" ")
    R = int(elems[0])
    C = int(elems[1])
    F = int(elems[2])
    N = int(elems[3])
    B = int(elems[4])
    T = int(elems[5])

    rides = []

    #read lines
    for i in range(1, len(content)):
        line = content[i].strip().split(" ")
        num = i - 1
        x0 = int(line[0])
        y0 = int(line[1])
        x1 = int(line[2])
        y1 = int(line[3])
        es = int(line[4])
        lf = int(line[5])

        rides.append(Ride(x0, y0, x1, y1, es, lf, num))
    return R, C, F, N, B, T, rides
Пример #6
0
 def get_solution(self, rides_list, rows, columns, vehicles, rides, bonus,
                  steps, args):
     cars = [Car() for _ in range(vehicles)]
     score = Score()
     rides_instance_list = [
         Ride(rid, *data) for rid, data in enumerate(rides_list)
     ]
     rides_earliest_departure = sorted(rides_instance_list,
                                       key=lambda ride: ride.step_min)
     rides_earliest_departure = tqdm(
         rides_earliest_departure
     ) if args.progress else rides_earliest_departure
     for r in rides_earliest_departure:
         candidates = [c for c in cars if c.can_finish_in_time(r, steps)]
         cars_with_bonus = [c for c in candidates if c.can_start_on_time(r)]
         if cars_with_bonus:
             best_car = min(cars_with_bonus, key=lambda c: c.wait_time(r))
             score.bonus_score += bonus
             score.raw_score += r.distance()
             score.wait_time += best_car.wait_time(r)
             score.assigned += 1
             best_car.assign(r)
         elif candidates:
             best_car = min(candidates,
                            key=lambda c: c.distance_to_ride_start(r))
             score.raw_score += r.distance()
             score.assigned += 1
             best_car.assign(r)
         else:
             score.unassigned += 1
     rides_solution = [c.assigned_rides for c in cars]
     return rides_solution, score
Пример #7
0
	def __init__(self, file_path):
		with open(file_path, 'r') as f:
			a = f.read()

		arr = [b.split() for b in a.split('\n') if len(b) > 0]
		arr = np.array(arr).astype(int)

		self.n_rows = arr[0][0]
		self.n_cols = arr[0][1]
		self.n_cars = arr[0][2]
		self.n_rides = arr[0][3]
		self.bonus = arr[0][4]
		self.n_steps = arr[0][5]

		arr = arr[1:]
		start_locs = arr[:,0:2]
		end_locs = arr[:,2:4]
		start_times = arr[:,4]
		end_times = arr[:,5]

		self.cars = [Car(i) for i in range(self.n_cars)] # create list of cars. i is the ID of the car
		self.rides = [Ride(i, start_locs[i], end_locs[i], start_times[i], end_times[i]) for i in range(self.n_rides)]
		self.rides_status = {i:False for i in range(self.n_rides)}

		self.time_step = 0

		self.ride_assignments = {} # job_number : car_number
Пример #8
0
    def generateRidesForDay(self, day):
        """ Have a person iterate over their activities to generate potential rides for one day. """

        rides = list()

        # current location (starts from home every day)
        origin = self.home

        # ride back, if any
        returnRide = None
        for activity in self.activities:
            # for every activiy, check whether it occurs
            if not activity.sampleOccurence():
                continue

            arrive = activity.sampleStartTime(day)
            destination = activity.sampleLocation()

            # check if possible, given return ride
            if returnRide is not None:
                ride = Ride(self, returnRide.destination, destination, arrive,
                            self.passengers)
                if ride.departBy < returnRide.arriveBy:
                    pass  # cancel return ride, leave from previous location
                else:
                    # return ride valid, add it
                    rides.append(returnRide)
                    origin = returnRide.destination
                    returnRide = None

            # create the actual ride
            ride = Ride(self, origin, destination, arrive, self.passengers)
            rides.append(ride)
            origin = destination

            # Check if return ride needs to be made. If not, person will not go home in between activities for example.
            if not activity.sampleBridge():
                duration = activity.sampleDuration()
                returnRide = Ride(self, origin, self.home, arrive + duration,
                                  self.passengers)

        if returnRide is not None:
            rides.append(returnRide)

        return rides
Пример #9
0
 def addRide(self, ride: Ride):
     #print("eklenecek ride: ",ride.rideNumber)
     #print(ride)
     #print("bos mu: ",self.isEmpty())
     if self.isEmpty():
         #Musteri 20 birimlik mesafeyi 10 birimde gitmeni istiyorsa
         self.rideOnProgress = ride
         #print("setting ride ",ride.rideNumber," taken")
         ride.taken()
         #print("result: ",ride.isTaken)
         self.destination = ride.to
         #Arac earliestStarttan yakınsa araç bekliycek ve sonra gidicek yoksa arac direk gazliycak
         self.movements = max(
             self.distanceBetweenRideAndCar(ride),
             ride.earliestStart) + self.distanceBetweenEndAndBeginning(ride)
         return ride
     else:
         pass
Пример #10
0
def _parse_rides(lines):
    idx = 0
    rides = list()
    for line in lines:
        values = line.split()
        values = map(int, values)
        rides.append(Ride(idx, (values[0], values[1]), (values[2], values[3]), values[4], values[5]))
        idx += 1
    return rides
Пример #11
0
def parse_problem (filename):
	with open(filename, "r") as file:
		header = file.readline().strip()
		nb_rows, nb_cols, nb_cars, nb_rides, bonus, steps = [int(x) for x in header.split()]

		rides = []
		for ride_idx in range(nb_rides):
			rides.append(Ride(ride_idx, tuple([*[int(x) for x in file.readline().strip().split()]])))

	return nb_rows, nb_cols, nb_cars, nb_rides, bonus, steps, rides
Пример #12
0
    def __init__(self, input):

        self.R = input[0][0]
        self.C = input[0][1]
        self.F = input[0][2]
        self.N = input[0][3]
        self.B = input[0][4]
        self.T = input[0][5]

        self.rides = []
        self.rides_dict = {}
        for k, v in enumerate(input[1:]):
            self.rides.append(Ride(v, k))
            self.rides_dict[k] = Ride(v, k)

        self.riders = []

        for i in range(0, self.F):
            self.riders.append(Riders(self))
    def __init__(self, solution: dict, data):
        self.solution = solution

        self.data = data
        self.rides = dict()
        self.vehicles = dict()
        timers = [Timer() for t in range(data["vehicles"])]

        for ride in range(data["rides"]):
            self.rides[ride] = Ride(data["rides_list"][ride], ride)
        for vehicle in range(data["vehicles"]):
            self.vehicles[vehicle] = Vehicle(vehicle, timers[vehicle],
                                             data["bonus"])
Пример #14
0
    def ParseInput(f):
        p = [list(map(int, line.split(" "))) for line in open("./data/" + f).read().split("\n") if line.__len__()!=0]
        
        R = p[0][0]
        C = p[0][1]
        B = p[0][4]
        T = p[0][5]

        F = [Car(i) for i in range(p[0][2])]
        N = [Ride(r[0], r[1], r[2], r[3], r[4], r[5], i-1) for i,r in enumerate(p) if i>0]

        N.sort(key=lambda x: x.f, reverse=False)

        return R, C, F, N, B, T
Пример #15
0
def parsefile():
    log = []

    while True:
        filename = input('The file to parse: ')

        entries = Entry.from_xml(filename)
        
        log.append(Ride(entries))
        print(len(log))
        if 'n' == input('Parse another .bin file? y/n: '):
            savefile = input('Output filename: ')
            pickle.dump(log, open(savefile, 'wb'))
            break
Пример #16
0
def read_input(fname):
    with open('./In/{}'.format(fname), 'r') as reader:
        R, C, F, N, B, T = [int(i) for i in reader.readline().split(" ")]

        cars = []

        for car in range(0, F):
            cars.append(Car())

        rides = []
        for ride in range(0, N):
            a, b, x, y, s, f = [int(i) for i in reader.readline().split(" ")]
            rides.append(Ride(a, b, x, y, s, f))

    return R, C, B, T, cars, rides
Пример #17
0
    def load_problem(self, file_name):
        with open(file_name, 'r') as input_file:
            lines = input_file.readlines()
            split_line = lines[0].split(' ')
            R = int(split_line[0])
            C = int(split_line[1])
            F = int(split_line[2])
            N = int(split_line[3])
            B = int(split_line[4])
            T = int(split_line[5])
            rides = []

            for i in range(1, len(lines)):
                rides.append(Ride(i - 1, lines[i]))

            return R, C, F, N, B, T, rides
Пример #18
0
    def __init__(self, file_name):
        file = open(file_name, mode='r')
        lines = file.read().split('\n')
        file.close()

        info = map(int, lines[0].split(' '))
        R, C, F, N, B, T = info;
        self.meta_info = MetaInfo(R, C, F, N, B, T)
        self.rides = []

        for id in range(len(lines) - 2):
            line_index = id + 1
            info = map(int, lines[line_index].split(' '))
            a, b, x, y, s, f = info;
            ride = Ride(a, b, x, y, s, f, id)
            self.rides.append(ride)
    def __init__(self, filepath="b_should_be_easy.in"):
        data = parse(filepath)
        self.cars = []
        for vehicle_id in range(data.get('vehicles')):
            self.cars.append(Car(vehicle_id))

        self.rides = []
        for ride_id in data.get('rides'):
            ride_info = data.get('rides').get(ride_id)
            self.rides.append(Ride(ride_id, **ride_info))

        self.rows = data.get('rows')
        self.columns = data.get('columns')
        self.number_of_rides = data.get('number_of_rides')
        self.bonus = data.get('bonus')
        self.total_steps = data.get('total_steps')
    def __init__(self, data, T=100, n_iter=1000, temp_update=.9):
        self.data = data
        self.rides = dict()
        self.T = T
        self.n_iter = n_iter
        self.cur_score = 0
        self.temp_update = temp_update

        for ride in range(data["rides"]):
            self.rides[ride] = Ride(data["rides_list"][ride], ride)

        self.solution = self.get_greedy_solution()

        simulator = Simulator(self.solution, self.data)
        # if not simulator.validate():
        #     print("Something is wrong with solution")
        self.cur_score = simulator.start()
Пример #21
0
def read_input():
    rows, columns, num_vehicles, num_rides, ride_bonus, num_steps = [
        int(s) for s in input().split(" ")
    ]
    OurMap = Map(rows, columns, num_vehicles, num_rides, ride_bonus, num_steps)
    Vehicles = [Vehicle() for i in range(num_vehicles)]
    Rides = []

    for i in range(0, num_rides):
        start_row, start_column, finish_row, finish_column, earliest_start, latest_finish = [
            int(s) for s in input().split(" ")
        ]
        Rides.append(
            Ride(i, (start_row, start_column), (finish_row, finish_column),
                 earliest_start, latest_finish))

    return (OurMap, Vehicles, Rides)
Пример #22
0
def solver(inputs):
    rides_list = inputs['rides_list']
    rides_list = sorted(
        [Ride(ride_info, i) for i, ride_info in enumerate(rides_list)])
    sol = defaultdict(list)
    vehicles = [
        Vehicle(i + 1, inputs['bonus']) for i in range(inputs['vehicles'])
    ]
    for ride in rides_list:
        best, vehicle = None, None
        for v in vehicles:
            cur = v.score_if_assigned(ride)
            if (not vehicle) or (cur[0] > best[0]
                                 or cur[0] == best[0] and cur[1] < best[1]):
                best, vehicle = cur, v
        vehicle.assign(ride)
    sol = {v.id: v.get_idx() for v in vehicles}
    return sol
Пример #23
0
def read_subject(subject):
    rides = []
    cars = []
    STEP_COUNT = 0
    BONUS = 0
    with open(subject, "r") as f:
        for i, line in enumerate(f.readlines()):
            if i == 0:
                constants = line.split()
                STEP_COUNT = int(constants[5])
                BONUS = int(constants[4])
                for j in range(int(constants[2])):
                    cars.append(Car())
            else:
                integers = [int(elt) for elt in line.split()]
                integers.append(i - 1)
                ride = Ride(*integers)
                rides.append(ride)
    return STEP_COUNT, BONUS, rides, cars
Пример #24
0
def read_file(file_name):
    rides = []
    with open(file_name, "r") as file:
        first_line = file.readline()
        R, C, F, N, B, T = first_line.split()
        R = int(R)
        C = int(C)
        F = int(F)
        N = int(N)
        B = int(B)
        T = int(T)
        # print matrix
        # print ("%s - %s - %s - %s" %(r,c,l,h))
        for nr in range(0, R):
            ride_line = file.readline()
            if len(ride_line) > 0:
                a, b, x, y, s, f = ride_line.split()
                rides.append(
                    Ride(int(a), int(b), int(x), int(y), int(s), int(f), nr))

        return R, C, F, N, B, T, rides
Пример #25
0
def processInputFile(inputFileName):
    """Read the input file, pull the data."""
    print("processing", os.path.basename(inputFileName))
    with open(inputFileName) as flines:
        inputData = [line.strip().split(" ") for line in flines]

    R, C, F, N, B, T = [int(x) for x in inputData[0]]

    # initialise the fleet
    fleet = [Car() for i in range(F)]

    rides = []
    for ind, line in enumerate(inputData[1:]):
        start_row, start_column, finish_row, finish_column, earliest_start, latest_finish = line
        ryder = Ride(ride_id=ind,
                     origin=(start_row, start_column),
                     destination=(finish_row, finish_column),
                     start_time=earliest_start,
                     finish_time=latest_finish)
        rides.append(ryder)

    return fleet, rides, T, B
Пример #26
0
    def __init__(self, in_file):
        # LOAD THE INPUT
        with open(in_file, 'r') as f:
            lines = f.readlines()

        # First line is R C number_of_cars, number_of_rides, bonus_for_starting_on_time and maximum Time
        nums = [int(s) for s in lines[0].split(' ')]
        self.R, self.C, self.n_cars, self.n_rides, self.bonus, self.T = nums[
            0], nums[1], nums[2], nums[3], nums[4], nums[5]

        print "LOADED FILE: ", in_file
        print "City size: rowsxcols = ", self.R, "x", self.C
        print "n_cars =  ", self.n_cars
        print "n_rides =  ", self.n_rides
        print "bouns for starting a ride on time =  ", self.bonus
        print "Number of stis in sim: ", self.T

        # Now read in the rides
        self.rides = []
        for r_id, line in enumerate(lines[1:]):
            nums = [int(s) for s in line.split(' ')]

            start_x, start_y = nums[0], nums[1]
            end_x, end_y = nums[2], nums[3]
            earlist_start = nums[4]
            earlist_end = nums[5]

            self.rides.append(
                Ride([start_x, start_y], [end_x, end_y], earlist_start,
                     earlist_end, r_id))

        # Create the queue
        self.ride_queue = RideQueue(self.rides, self.bonus)

        #
        self.cars = []
        for i in xrange(self.n_cars):
            self.cars.append(Car())
            self.cars[-1].initialise_ride_queue(self.ride_queue)
Пример #27
0
def parser(filename):
    filedir = os.getcwd()
    filedir = os.path.join(filedir, "input_files")
    filename = os.path.join(filedir, filename)

    f = open(filename, "r")

    FirstInfo = f.readline()
    FirstInfo = FirstInfo.split()

    rows = int(FirstInfo[0])
    columns = int(FirstInfo[1])
    vechicles = int(FirstInfo[2])
    rides = int(FirstInfo[3])
    bonus = int(FirstInfo[4])
    steps = int(FirstInfo[5])

    out = []

    ID = 0
    for line in f:

        lineInfo = line.split()
        a = int(lineInfo[0])
        b = int(lineInfo[1])
        c = int(lineInfo[2])
        d = int(lineInfo[3])
        start = (a, b)
        end = (c, d)
        es = int(lineInfo[4])
        lf = int(lineInfo[5])

        newride = Ride(start, end, es, lf, ID)
        out.append(newride)
        ID += 1

    f.close()

    return rows, columns, vechicles, rides, bonus, steps, out
Пример #28
0
def run():
    for i in range(num_vehicles):
        vehicle = Vehicle(i + 1)
        vehicles.append(vehicle)

    for i in range(len(rides_data)):
        ride = Ride(rides_data[i], i + 1)
        rides.append(ride)

    for i in range(steps):
        grouped_vehicles = get_grouped_vehicles()
        moves = []

        for group in grouped_vehicles:
            possible_moves = get_all_possible_moves(group)
            best_move_for_group = find_best_moves(possible_moves)
            moves.append(best_move_for_group)

        move_vehicles(moves)
        cur_step += 1 # TODO: This might need to come before

    generate_output()
Пример #29
0
 def get_solution(self, rides_list, rows, columns, vehicles, rides, bonus, steps, args):
     cars = [Car() for _ in range(vehicles)]
     score = Score()
     rides_unassigned = [Ride(rid, *data) for rid, data in enumerate(rides_list)]
     cars = tqdm(cars) if args.progress else cars
     for car in cars:
         rides_possible = [r for r in rides_unassigned if car.can_finish_in_time(r, steps)]
         with tqdm(total=len(rides_possible)) as pbar:
             while rides_possible:
                 pbar.update(1)
                 ride = min(rides_possible, key=lambda r: car.arrival(r))  # earliest arrival
                 if car.can_start_on_time(ride):
                     score.bonus_score += bonus
                 score.raw_score += ride.distance()
                 score.wait_time += car.wait_time(ride)
                 score.assigned += 1
                 car.assign(ride)
                 rides_unassigned.remove(ride)  # remove ride for other cars
                 rides_possible.remove(ride)
                 rides_possible = [r for r in rides_possible if car.can_finish_in_time(r, steps)]
     score.unassigned = len(rides_unassigned)
     rides_solution = [c.assigned_rides for c in cars]
     return rides_solution, score
Пример #30
0
def parse_rides(data_set, bonus, simulation_duration):
    """Parse all lines, except the first, from the data set and return a list of Ride
       instances in the same order as they were read from the file.

    The subsequent lines of the input file describe the individual rides, from ride 0
    to ride N − 1.  Each line contains the following integer numbers separated by single
    spaces:
        - the row of the start intersection
        - the column of the start intersection
        - the row of the finish intersection
        - the column of the finish intersection
        - the earliest start
        - the latest finish

    Args:
        data_set: path to the data set file
        bonus: bonus value for a ride started on time
        simulation_duration: duration of the simulation (in steps)

    Returns:
        A list of Ride instances
    """
    keys = ('start_row', 'start_col', 'end_row', 'end_col', 'earliest_start',
            'latest_finish')
    rides = []
    with open(data_set, 'r') as f:
        f.readline()  # Skip the first line

        for i, line in enumerate(f):
            values = [int(v) for v in line.split()]
            ride_properties = dict(zip(keys, values))
            ride_properties['identifier'] = i
            ride_properties['bonus'] = bonus
            ride_properties['simulation_duration'] = simulation_duration
            rides.append(Ride(**ride_properties))

    return rides