コード例 #1
0
    def getRandomDriverTrips(self, numtrips, numNotDrivers, feat):

        #get list of drivers and shuffle
        notDrivers = os.listdir("../drivers/")
        copy = notDrivers[1:]
        random.shuffle(copy)
        notDrivers[1:] = copy

        #process number of 'other' drivers
        if numNotDrivers == 0 or numNotDrivers >= len(notDrivers):
            numNotDrivers = len(notDrivers) - 1

        #if we are comparing to only one driver and that driver is the same as
        #the original driver
        if numNotDrivers == 1:
            while notDrivers[1] == self.name:
                copy = notDrivers[1:]
                random.shuffle(copy)
                notDrivers[1:] = copy

        #sample trips and output desired features
        tripList = []
        for i in range(numtrips):
            dnum = notDrivers[random.randint(
                1, numNotDrivers)]  #sample a random driver
            #print self.name  + " " + dnum
            while dnum == self.name:  #don't sample from self
                dnum = notDrivers[random.randint(1, numNotDrivers)]
            tnum = random.randint(1, 200)  #sample a random trip
            t = Trip("../drivers/" + str(dnum) + "/" + str(tnum) + ".csv",
                     feat)
            tripList.append(t.printFeatures())

        return tripList
コード例 #2
0
ファイル: Database.py プロジェクト: lukstafi/subte
 def export_gtfs(cls, directory):
     Agency.write_agencies(directory)
     Calendar.write_calendars(directory)
     Stop.write_stops(directory)
     Route.write_routes(directory)
     Trip.write_trips(directory)
     Frequency.write_frequencies(directory)
     Path.write_paths(directory)
コード例 #3
0
ファイル: Database.py プロジェクト: lukstafi/subte
 def import_gtfs(cls, directory):
     Agency.import_agencies(directory)
     Calendar.import_calendars(directory)
     Stop.import_stops(directory)
     Path.import_paths(directory)
     Route.import_routes(directory)
     Trip.import_trips(directory)
     Frequency.import_frequencies(directory)
コード例 #4
0
ファイル: Driver.py プロジェクト: cmona93/CS349-roads
	def writeCSV(self, numTrips=training_self):
		g = open ("driver_stats/"+str(self.name)+"_trips.csv", "w")
		#a header and then the features for each trip
		g.write("advSpeed,tripDist\n")
		for i in range (1, numTrips+1):
			t = Trip("../drivers/"+str(self.name)+"/"+str(i)+".csv")
			g.write(t.printFeatures())
		g.close()
コード例 #5
0
ファイル: ClarkeWright.py プロジェクト: philipboeken/verolog
 def initRoutingDay(self):
     routingDay = RoutingDay(self.instance)
     for request in self.scheduleDay.deliveries:
         trip = Trip(self.instance, request)
         routingDay.addTrip(trip)
     for request in self.scheduleDay.pickups:
         trip = Trip(self.instance, request)
         routingDay.addTrip(trip)
     return routingDay
コード例 #6
0
ファイル: TripRoute.py プロジェクト: CodeforBirmingham/subte
    def add_trip(self):
        trip = Trip('', self, self.calendar)

        # add the stops
        for stop in self._stops:
            trip.add_trip_stop(TripStop(stop))

        self.trips.append(trip)

        return trip
コード例 #7
0
ファイル: Driver_val.py プロジェクト: nnWhisperer/Variolite
 def writeCSV_test(self):
     g = open("driver_stats/" + str(self.name) + "_test.csv", "w")
     #first trips from this driver
     for i in range(num_selfTrips + 1, num_selfTrips + num_testTrips + 1):
         t = Trip("../drivers/" + str(self.name) + "/" + str(i) + ".csv")
         g.write(t.printFeatures())
     #trips from other drivers
     tripList = self.getRandomDriverTrips(num_testTrips)
     for other in tripList:
         g.write(other)
     g.close()
コード例 #8
0
ファイル: Driver.py プロジェクト: cmona93/CS349-roads
	def writeCSV_notDriver(self, numTrips = training_others):
		#list other drivers in directory, since their numbers skip around
		notDrivers = os.listdir("../drivers/")

		g = open ("driver_stats/"+str(self.name)+"_NOTtrips.csv", "w")
		for i in range(numTrips):
			dnum = notDrivers[random.randint(1, len(notDrivers))] #sample a random driver
			while dnum == self.name: #don't sample from self
				dnum = notDrivers[random.randint(1, len(notDrivers))]
			tnum = random.randint(1,201)#sample a random trip
			t = Trip("../drivers/"+str(dnum)+"/"+str(tnum)+".csv")
			g.write(t.printFeatures())
		g.close()
コード例 #9
0
ファイル: Driver_val.py プロジェクト: nnWhisperer/Variolite
 def writeCSV_training(self):
     g = open("driver_stats/" + str(self.name) + "_training.csv", "w")
     #a header and then the features for each trip
     #g.write("advSpeed,tripDist\n")
     #first trips from this driver
     for i in range(1, num_selfTrips + 1):
         t = Trip("../drivers/" + str(self.name) + "/" + str(i) + ".csv")
         g.write(t.printFeatures())
     #trips from other drivers
     tripList = self.getRandomDriverTrips(num_NOTselfTrips)
     for other in tripList:
         g.write(other)
     g.close()
コード例 #10
0
ファイル: Database.py プロジェクト: lukstafi/subte
 def close(self):
     self._is_open = False
     self._dbname = None
     
     # clear everything
     Agency.clear()
     Calendar.clear()
     Stop.clear()
     Path.clear()
     Route.clear()
     TripRoute.clear()
     Trip.clear()
     Frequency.clear()
     Picture.clear()
コード例 #11
0
ファイル: Driver_val.py プロジェクト: nnWhisperer/Variolite
 def getRandomDriverTrips(self, numtrips):
     notDrivers = os.listdir("../drivers/")
     numNotDrivers = len(
         notDrivers)  #change this parameter to consider a different number
     tripList = []
     for i in range(numtrips):
         dnum = notDrivers[random.randint(1,
                                          len(notDrivers) -
                                          1)]  #sample a random driver
         while dnum == self.name:  #don't sample from self
             dnum = notDrivers[random.randint(1, numNotDrivers - 1)]
         tnum = random.randint(1, 200)  #sample a random trip
         t = Trip("../drivers/" + str(dnum) + "/" + str(tnum) + ".csv")
         tripList.append(t.printFeatures())
     return tripList
コード例 #12
0
ファイル: mini-uber.py プロジェクト: RideGreg/LintCode
    def request(self, rider_id, lat, lng):
        minDistance, minDriverId = float('inf'), None
        for dId, loc in self.driver2Location.items():
            curDistance = Helper.get_distance(lat, lng, loc[0], loc[1])
            if minDistance > curDistance:
                minDistance, minDriverId = curDistance, dId

        trip = Trip(rider_id, lat, lng)
        trip.driver_id = minDriverId

        if minDriverId:
            self.driver2Trip[minDriverId] = trip
            del self.driver2Location[minDriverId]

        return trip
コード例 #13
0
    def __get_trip(self, trip):
        """
        Gets the trip information out of the json returned from ITA
        This should only be called if the caller understands the json returned by ITA
        """
        price = float(trip['ext']['price'][3:])
        ppm = float(trip['ext']['pricePerMile'][3:])
        ppm = round(ppm, 4)
        itin = trip['itinerary']
        distance = int(itin['distance']['value'])

        flights = []
        #get the flights out of the itinerary
        for flight in itin['slices']:
            stops = []
            layovers = flight.get('stops')
            if not layovers is None:
                for layover in layovers:
                    stops.append(layover['code'])

            fl = Flight(flight['origin']['code'],
                        flight['destination']['code'], flight['departure'],
                        flight['arrival'], flight['duration'], stops)
            flights.append(fl)

        return Trip(flights[0], flights[1], ppm, price, distance)
コード例 #14
0
ファイル: Frequency.py プロジェクト: CodeforBirmingham/subte
    def import_frequencies(cls, directory):
        from Trip import Trip

        try:
            f = open(os.path.join(directory, 'frequencies.txt'), 'rb')
            reader = csv.reader(f)

            mappings = {'trip_id': ('trip_route', lambda x: Trip.get_by_gtfs_id(x).trip_route),
                        'start_time': ('start', lambda x: x),
                        'end_time': ('end', lambda x: x),
                        'headway_secs': ('headway', lambda x: x),
                    }

            # create a headers with an index
            headers = reader.next()
            r_headers = dict([(x, i) for i, x in enumerate(headers)])

            for l2 in reader:
                if len(l2) != len(headers):
                    print >> sys.stderr, 'Invalid line', l2, headers
                    continue
                
                kw = {}
                for i, a in enumerate(l2):
                    key = headers[i]
                    if key in mappings:
                        kw[mappings[key][0]] = mappings[key][1](BaseObject.unquote(a))
                # create the frequency
                frequency = Frequency(**kw)
                trip_route = frequency.trip_route.frequencies.append(frequency)

        except IOError, e:
            print >> sys.stderr, 'Unable to open frequencies.txt:', e
コード例 #15
0
    def request(self, rider_id, lat, lng):
        # Write your code here
        dist = -1
        driver = -1
        for key, value in self.locs.items():
            td = Helper.get_distance(value[0], value[1], lat, lng)
            if dist == -1 or td < dist:
                dist = td
                driver = key

        trip = Trip(rider_id, lat, lng)
        trip.driver_id = driver
        if dist != -1:
            del self.locs[driver]
            self.trips[driver] = trip
        return trip
コード例 #16
0
 def trip_for_stopnames(self, stopnames=[]):
     """
         :param: stopnames: array that hold name of the stops
         :return: Object of Trip
     """
     matching_stations = [self.stations_by_name[name] for name in stopnames]
     return Trip(matching_stations)
コード例 #17
0
ファイル: mymain.py プロジェクト: ziper02/TravelScanner
def test_order_hotel():
    flights_data = flight_general.get_all_updated_data()

    data_in_range = [
        flight for flight in flights_data
        if (4 <= flight.days <= 6) and flight.destination_value == 10 and (
            flight.label == 4 or flight.label == 3) and datetime.strptime(
                flight.return_date, '%Y-%m-%d') < datetime(2021, 5, 1)
    ]

    data_in_range.sort()
    trip_list = []
    time_start = time.time()
    i = 0
    j = 0
    my_set = set()
    while i < 2:
        flight = data_in_range[j]
        if flight.destination.city not in my_set:
            trip_list.append(Trip(flight))
            my_set.update([flight.destination.city])
            i += 1
        j = j + 1

    for trip in trip_list:
        trip.get_hotel_for_trip()

    trip_list.sort(reverse=True)
    for trip in trip_list:
        print(trip)

    time_end = time.time()
    print((time_end - time_start) / 60)
コード例 #18
0
    def writeCSV(self, order, numNotDrivers, feat):
        g = open("driver_stats/" + str(self.name) + "_training.csv", "w")

        #first trips from this driver
        for i in range(0, num_selfTrips + num_testTrips):
            #print i
            t = Trip(
                "../drivers/" + str(self.name) + "/" + str(order[i]) + ".csv",
                feat)
            g.write(t.printFeatures())

        #trips from other drivers
        tripList = self.getRandomDriverTrips(num_NOTselfTrips + num_testTrips,
                                             numNotDrivers, feat)
        for other in tripList:
            g.write(other)
        g.close()
コード例 #19
0
def test_order_hotel():
    flights_data = flight_general.get_all_updated_data()
    data_in_range = [
        flight for flight in flights_data
        if (flight.days == 5 or flight.days == 6) and flight.destination_value
        < 25 and (flight.label == 4 or flight.label == 3)
    ]
    data_in_range.sort()
    trip_list = []
    for i in range(0, 3):
        flight = data_in_range[i]
        trip = Trip(flight)
        trip.get_hotel_for_trip()
        trip_list.append(trip)

    trip_list.sort(reverse=True)
    return trip_list
コード例 #20
0
    def request(self, rider_id, lat, lng):
        trip = Trip(rider_id, lat, lng)
        distance, driver_id = -1, -1

        for key, value in self.driver2Location.items():
            dis = Helper.get_distance(value.lat, value.lng, lat, lng)
            if distance < 0 or distance > dis:
                driver_id = key
                distance = dis

        if driver_id != -1:
            del self.driver2Location[driver_id]

        trip.driver_id = driver_id
        self.driver2Trip[driver_id] = trip

        return trip
コード例 #21
0
ファイル: mini-uber.py プロジェクト: kid1211/AlgoPrep
    def request(self, rider_id, lat, lng):
        # Write your code here
        minD = sys.maxsize
        closestD = None
        for driver in self.driverLocation.keys():
            if driver in self.trip:
                continue
            lat1, lng1 = self.driverLocation[driver]
            dis = Helper.get_distance(lat1, lng1, lat, lng)
            if dis < minD:
                minD = dis
                closestD = driver

        trip = Trip(rider_id, lat, lng)
        trip.driver_id = closestD
        self.trip[closestD] = trip
        return trip
コード例 #22
0
    def request(self, rider_id, lat, lng):
        trip = Trip(rider_id, lat, lng)
        min_dist = float('inf')
        closest_driver_id = -1
        for driver_id, driver in self.drivers.items():
            dist = Helper.get_distance(lat, lng, driver.lat, driver.lng)

            if dist < min_dist:
                min_dist = dist
                closest_driver_id = driver_id

        print(dist, closest_driver_id)
        trip.driver_id = closest_driver_id
        self.trip_serial_id += 1
        self.trips[self.trip_serial_id] = trip
        self.drivers[closest_driver_id].trip_id = self.trip_serial_id

        return trip
コード例 #23
0
    def _generate_all_combinations(self):
        logging.info("Generating trip candidates with {0} cities each".format(
            self.cities_per_trip_candidate))

        if self.total_cities < self.cities_per_trip_candidate:
            only_trip = self.requested_cities.keys()
            trip_votes = self._get_trip_total_votes(only_trip)
            trip_votees = self._get_trip_total_votees(only_trip)
            self.all_combinations = [Trip(only_trip, trip_votes, trip_votees)]

        candidate_list = list(
            combinations(self.requested_cities.keys(),
                         self.cities_per_trip_candidate))
        self.all_combinations = [
            Trip(trip_cities, self._get_trip_total_votes(trip_cities),
                 self._get_trip_total_votees(trip_cities))
            for trip_cities in candidate_list
        ]
コード例 #24
0
ファイル: Mini_Uber.py プロジェクト: hanrick2000/LC-1
 def request(self, rider_id, lat, lng):
     # create a trip first
     # find the closest available driver from self.driver2Location
     # if no driver return none, if yes, fill in trip driver_id,
     # remove from driver2Location, add to driver2Trip
     trip = Trip(rider_id, lat, lng)
     driver_id, distance = -1, -1
     for id, loc in self.driver2Location.items():
         dis = Helper.get_distance(lat, lng, loc.lat, loc.lng)
         if distance == -1 or dis < distance:
             distance = dis
             driver_id = id
     if driver_id == -1:
         print("No available drivers")
         return None
     trip.driver_id = driver_id
     self.driver2Trip[driver_id] = trip
     del self.driver2Location[driver_id]
     return trip
コード例 #25
0
 def request(self, rider_id, lat, lng):
     # Write your code here
     t = Trip(rider_id, lat, lng)
     min_diff = sys.maxint
     match_driver = []
     for driver in self.driver_id_to_location:
         driver_tuple = self.driver_id_to_location[driver]
         diff = Helper.get_distance(lat, lng, driver_tuple[0], driver_tuple[1])
         if diff < min_diff:
             min_diff = diff
             match_driver = [driver, driver_tuple[0], driver_tuple[1]]
     
     if len(match_driver) != 0:
         del self.driver_id_to_location[match_driver[0]]
         t.driver_id = match_driver[0]
         self.driver_id_to_trip[match_driver[0]] = t
         return t
     else:
         return None
コード例 #26
0
    def request(self, rider_id, lat, lng):
        the_dvr_id = None
        min_distance = float("inf")
        for dvr_id, dvr in self.drivers.items():
            if dvr[2]:
                continue

            distance = Helper.get_distance(lat, lng, dvr[0], dvr[1])
            if distance < min_distance:
                min_distance = distance
                the_dvr_id = dvr_id

        if not the_dvr_id:
            return None

        trip = Trip(rider_id, lat, lng)
        trip.driver_id = the_dvr_id
        self.drivers[the_dvr_id][2] = trip
        return trip
コード例 #27
0
ファイル: TrafficEstimation.py プロジェクト: giserh/taxisim
def load_trips(filename, limit=float('inf')):
    trips = []
    with open(filename, "r") as f:
        reader = csv.reader(f)
        reader.next()
        for line in reader:
            trips.append(Trip(line))
            if (len(trips) >= limit):
                break

    return trips
コード例 #28
0
    def request(self, rider_id, lat, lng):
        if not rider_id:
            return
        trip = Trip(rider_id, lat, lng)
        _distance = distance = self.INFINITY
        driver_id = -1

        for _driver_id, _loc in self.driver_to_locs.items():
            _distance = Helper.get_distance(_loc['lat'], _loc['lng'], lat, lng)
            if _distance < distance:
                driver_id = _driver_id
                distance = _distance

        if driver_id == -1:
            return trip

        trip.driver_id = driver_id
        self.driver_to_trip[driver_id] = trip
        del self.driver_to_locs[driver_id]

        return trip
コード例 #29
0
ファイル: TrafficEstimation.py プロジェクト: giserh/taxisim
def plot_unique_trips():
    from matplotlib import pyplot as plt
    trip_lookup = {}
    print("Loading map")
    road_map = Map("nyc_map4/nodes.csv", "nyc_map4/links.csv")

    print("Matching nodes")
    sizes = []
    with open("sample.csv", "r") as f:
        reader = csv.reader(f)
        reader.next()
        for line in reader:
            trip = Trip(line)

            trip.num_occurrences = 1
            trip.origin_node = road_map.get_nearest_node(
                trip.fromLat, trip.fromLon)
            trip.dest_node = road_map.get_nearest_node(trip.toLat, trip.toLon)

            if ((trip.origin_node, trip.dest_node) in trip_lookup):
                #Already seen this trip at least once
                trip_lookup[trip.origin_node,
                            trip.dest_node].num_occurrences += 1
            elif trip.origin_node != None and trip.dest_node != None:
                #Never seen this trip before
                trip_lookup[trip.origin_node, trip.dest_node] = trip

            sizes.append(len(trip_lookup))
    plt.plot(range(len(sizes)), sizes)
    plt.xlabel("Inner Loop Iteration")
    plt.ylabel("L1 Error (sec)")
    fig = plt.gcf()
    fig.set_size_inches(20, 10)
    fig.savefig('test2png.png', dpi=100)

    #Make unique trips into a list and return
    new_trips = [trip_lookup[key] for key in trip_lookup]
    return new_trips
コード例 #30
0
ファイル: mini_uber.py プロジェクト: Yang-YZ/System-Design
    def request(self, rider_id, lat, lng):
        # @param rider_id an integer
        # @param lat, lng rider's location
        # return a trip

        # find a closest driver
        closest_driver, closest_dist = None, sys.maxsize
        for driver, location in self.drivers2location.items():
            distance = Helper.get_distance(lat, lng, location[0], location[1])
            if distance < closest_dist:
                closest_driver = driver
                closest_dist = distance

        # create a trip with rider's information.
        trip = Trip(rider_id, lat, lng)
        # fill driver_id into this trip.
        trip.driver_id = closest_driver

        # mark this driver not available.
        del self.drivers2location[closest_driver]
        self.drivers2trip[closest_driver] = trip

        return trip
コード例 #31
0
def plot_unique_trips():
    from matplotlib import pyplot as plt
    trip_lookup = {}
    print("Loading map")
    road_map = Map("nyc_map4/nodes.csv", "nyc_map4/links.csv")
    
    print("Matching nodes")
    sizes = []
    with open("sample.csv", "r") as f:
        reader = csv.reader(f)
        reader.next()
        for line in reader:
            trip = Trip(line)

            trip.num_occurrences = 1
            trip.origin_node = road_map.get_nearest_node(trip.fromLat, trip.fromLon)
            trip.dest_node = road_map.get_nearest_node(trip.toLat, trip.toLon)
            
            if((trip.origin_node, trip.dest_node) in trip_lookup):
                #Already seen this trip at least once
                trip_lookup[trip.origin_node, trip.dest_node].num_occurrences += 1
            elif trip.origin_node !=None and trip.dest_node != None:
                #Never seen this trip before
                trip_lookup[trip.origin_node, trip.dest_node] = trip
        
            sizes.append(len(trip_lookup))
    plt.plot(range(len(sizes)), sizes)
    plt.xlabel("Inner Loop Iteration")
    plt.ylabel("L1 Error (sec)")
    fig = plt.gcf()
    fig.set_size_inches(20,10)
    fig.savefig('test2png.png',dpi=100)

    
    #Make unique trips into a list and return
    new_trips = [trip_lookup[key] for key in trip_lookup]
    return new_trips
コード例 #32
0
ファイル: KaggleSubmission10.py プロジェクト: bilykigor/qimb
def GetFeatures(driverID,j):
    driverDir = '/home/user1/Desktop/Share2Windows/Kaggle/DriversCleaned/'+str(driverID)
    tripFiles = range(1,201)
   
    cacc = pd.DataFrame(np.zeros((1,51)))
    for index,tripID in enumerate(tripFiles):                       
        trip = Trip(driverID,tripID,pd.read_csv(driverDir+'_' + str(tripID) + '.csv'))
        trip.getSpeed()
        trip.getRadius()
        trip.getCacc()
        cacc.loc[index] = asarray(trip.Quantiles(trip.cacc.val)) 
    
    cacc.to_csv('/home/user1/Desktop/Share2Windows/Kaggle/FeaturesCleaned/CaccQuantiles/' + str(driverID) + '.csv', index=False)
    del cacc

    return 0
コード例 #33
0
ファイル: KaggleSubmission12.py プロジェクト: bilykigor/qimb
def GetProba(drive,driverID,tripInd):
    driverDir = '/home/user1/Desktop/SharedFolder/Kaggle/DriversCleaned/'+str(driverID)
    df = pd.read_csv(driverDir+'_' + str(tripInd)+'.csv')
    trip = Trip(driverID,tripInd,df)
    trip.getSpeed()
    trip.getAcc()
    #trip.getRadius()
    #trip.getCacc()
    trip.getFeatures()
    X=trip.features[['v','acc']]
    
    probas = np.zeros((X.shape[0],drive.shape[0]))
    for i in range(drive.shape[0]):
        probas[:,i]=multivariate_normal.pdf(X, mean=array(drive.ix[i,:2]), cov=[array(drive.ix[i,2:4]),array(drive.ix[i,4:])])

    probas=np.max(probas,axis=1)
    return probas.mean()
コード例 #34
0
ファイル: KaggleAnalysis.py プロジェクト: bilykigor/qimb
def GetProba(clf,driverID,tripID):
    #print driverID,tripID
    driverDir = '/home/user1/Desktop/SharedFolder/Kaggle/DriversCleaned/'+str(driverID)
    df = pd.read_csv(driverDir+'_' + str(tripInd)+'.csv')
    trip = Trip(driverID,tripInd,df)
    trip.getSpeed()
    trip.getAcc()
    #trip.getRadius()
    #trip.getCacc()
    trip.getFeatures()
    X=trip.features[['v','acc']]
    
    probas = np.zeros(X.shape[0])
    
    for i in range(X.shape[0]):
        probas[i]=clf.score(X.loc[i])
    print probas.mean()
    return probas.mean()
コード例 #35
0
ファイル: KaggleSubmission12.py プロジェクト: bilykigor/qimb
def GetFeatures(driverID,j):
    driverDir = '/home/user1/Desktop/SharedFolder/Kaggle/DriversCleaned/'+str(driverID)

    tripFiles = range(1,201)
   
    
    X = pd.DataFrame(columns=selectedCols)
    for index,tripID in enumerate(tripFiles):       
        #print index,tripID
        trip = Trip(driverID,tripID,pd.read_csv(driverDir+'_' + str(tripID) + '.csv'))
        trip.getSpeed()
        trip.getAcc()
        #trip.getRadius()
        #trip.getCacc()
        trip.getFeatures()
        
        '''z=array(list(set(np.asarray([range(x-5,x+5) for x in (trip.features.v<vlim[0]).nonzero()[0]]).flatten())))
        z=z[z<trip.features.shape[0]]
        z=z[z>=0]
        #z=array(list(set(range(trip.features.shape[0]))-set(z)))
    
        Xz=trip.features.loc[z]
        Xz=Xz.reset_index(drop=True)

        Xz=Xz.loc[Xz.v!=0]
        Xz=Xz.reset_index(drop=True)

        X = X.append(Xz)'''
        X = X.append(trip.features)
        
    X=X.reset_index(drop=True) 
    
    X=X[(X.v<vlim[1]) & (X.v>vlim[0])]
    X=X[(X.acc<clim[1]) & (X.acc>clim[0])]
    X=X.reset_index(drop=True) 
    
    clf=GetGmm(np.asanyarray(X[['v','acc']]))
    cos = SaveGmm(clf)
    
    cos.to_csv('/home/user1/Desktop/SharedFolder/Kaggle/FeaturesCleaned/GMM/All/' + str(driverID) + '.csv', index=False)
    #del cos

    return 0
コード例 #36
0
ファイル: ClarkeWright.py プロジェクト: philipboeken/verolog
 def algorithm(self):
     self.routingDay = self.initRoutingDay()
     for pair, saving in self.savings:
         trip1 = self.routingDay.tripContainingRequest(pair[0], True)
         trip2 = self.routingDay.tripContainingRequest(pair[1], True)
         if trip1 and trip2:
             if not trip1.equals(trip2):
                 newTrip = Trip(self.instance)
                 newTrip.concatenateTrips(trip2, trip1, pair)
                 if newTrip.isValid():
                     validChange = True
                     benefit = True
                     for toolID, tool in self.instance.tools.items():
                         if self.inventory[toolID] < 0:
                             benefit = False
                     newInventory = newTrip.inventoryChange()
                     inventory1 = trip1.inventoryChange()
                     inventory2 = trip2.inventoryChange()
                     for toolID, tool in self.instance.tools.items():
                         change = newInventory[toolID] - inventory1[
                             toolID] - inventory2[toolID]
                         if change < 0 and self.inventory[
                                 toolID] + change < 0:
                             validChange = False
                             break
                         if self.inventory[toolID] < 0 and change > 0:
                             benefit = True
                     if validChange and benefit:
                         self.routingDay.addTrip(newTrip)
                         self.routingDay.deleteTrip(trip1)
                         self.routingDay.deleteTrip(trip2)
                         for toolID, tool in self.instance.tools.items():
                             change = newInventory[toolID] - inventory1[
                                 toolID] - inventory2[toolID]
                             self.inventory[
                                 toolID] = self.inventory[toolID] + change
コード例 #37
0
ファイル: Driver_val.py プロジェクト: nnWhisperer/Variolite
 def writeCSV_selfDriver(self):
     g = open("driver_stats/" + str(self.name) + "_selfTrips.csv", "w")
     for i in range(1, 201):  #get features for all driver trips
         t = Trip("../drivers/" + str(self.name) + "/" + str(i) + ".csv")
         g.write(t.printFeatures())
     g.close()
コード例 #38
0
ファイル: first_trip.py プロジェクト: alanvenneman/Practice
from Trip import Trip
from MaxMileageException import MaxMileageException

try:
    miles = int(input("How many miles to your destination? \n"))
    trip = Trip()
    trip.setMiles(miles)
    hours = miles / 65
    print("The trip will be {} hours.".format(hours))
    trip.stop_for_food(hours)
    trip.rest_for_day(hours)
    # print(miles)
    loop = 0
    while miles > 0:
        if loop == 350:
            print("You are getting low on gas. Please fill up.")
        loop += 1
        # print(miles)
        miles -= 1
except MaxMileageException:
    print("You must not go on a trip over 500 miles.")
コード例 #39
0
ファイル: KaggleAnalysis.py プロジェクト: bilykigor/qimb
import itertools
from scipy import linalg
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn.mixture import GMM
from sklearn.neighbors import KernelDensity as kde
from scipy.stats import multivariate_normal
from scipy.spatial.distance import mahalanobis

# <codecell>

driverID = 1
driverDir = '/home/user1/Desktop/SharedFolder/Kaggle/DriversCleaned/'+str(driverID)
tripInd = 1
df = pd.read_csv(driverDir+'_' + str(tripInd)+'.csv')
trip = Trip(driverID,tripInd,df)
trip.getSpeed()
trip.getAcc()
#trip.getRadius()
#trip.getCacc()
trip.getFeatures()
X=trip.features[['v','acc']]

# <codecell>

def GetProba(drive,driverID,tripInd):
    driverDir = '/home/user1/Desktop/SharedFolder/Kaggle/DriversCleaned/'+str(driverID)
    df = pd.read_csv(driverDir+'_' + str(tripInd)+'.csv')
    trip = Trip(driverID,tripInd,df)
    trip.getSpeed()
    trip.getAcc()
コード例 #40
0
ファイル: MyPSACC.py プロジェクト: jlayec/psa_car_controller
 def get_trips() -> List[Trip]:
     conn = get_db()
     res = conn.execute(
         'SELECT * FROM position ORDER BY Timestamp').fetchall()
     trips = []
     if len(res) > 1:
         start = res[0]
         end = res[1]
         tr = Trip()
         #res = list(map(dict,res))
         for x in range(0, len(res) - 2):
             next_el = res[x + 2]
             if end["mileage"] - start["mileage"] == 0 or \
                     (end["Timestamp"] - start["Timestamp"]).total_seconds() / 3600 > 3:
                 start = end
                 tr = Trip()
             else:
                 distance = next_el["mileage"] - end["mileage"]  # km
                 duration = (next_el["Timestamp"] -
                             end["Timestamp"]).total_seconds() / 3600
                 if (
                         distance == 0 and duration > 0.08
                 ) or duration > 2:  # check the speed to handle missing point
                     tr.distance = end["mileage"] - start["mileage"]  # km
                     if tr.distance > 0:
                         tr.start_at = start["Timestamp"]
                         tr.end_at = end["Timestamp"]
                         tr.add_points(end["longitude"], end["latitude"])
                         tr.duration = (
                             end["Timestamp"] -
                             start["Timestamp"]).total_seconds() / 3600
                         tr.speed_average = tr.distance / tr.duration
                         diff_level = start["level"] - end["level"]
                         tr.consumption = diff_level / 100 * BATTERY_POWER  # kw
                         tr.consumption_km = 100 * tr.consumption / tr.distance  # kw/100 km
                         #  logger.debug(
                         #     f"Trip: {start['Timestamp']}  {tr.distance:.1f}km {tr.duration:.2f}h {tr.speed_average:.2f} km/h {tr.consumption:.2f} kw {tr.consumption_km:.2f}kw/100km")
                         # filter bad value
                         if tr.consumption_km < 70:
                             trips.append(tr)
                     start = next_el
                     tr = Trip()
                 else:
                     tr.add_points(end["longitude"], end["latitude"])
             end = next_el
     return trips
コード例 #41
0
    result_dict['schedule'].append({
        "job":
        j.job_id,
        "delivery time":
        j.find_delivery_time().strftime("%m/%d/%Y, %H:%M:%S"),
        "user company":
        j.user_company,
        "location":
        j.vessel_loading_location,
        "pick up":
        j.check_pickup_time(),
        "items":
        j.process_items(),
        "terminal":
        j.terminal
    })

pp = pprint.PrettyPrinter(indent=4)
unassigned_jobs_list.sort(key=lambda x: x.find_delivery_time())
for i in range(len(unassigned_jobs_list) - 1):
    j = unassigned_jobs_list[i]
    for k in range(1, len(unassigned_jobs_list) - i):
        o = unassigned_jobs_list[i + k]
        print(
            str(j.job_id) + " and " + str(o.job_id) + ": " +
            str(j.use_same_truck(o)))
        if (j.use_same_truck(o)):
            trip = Trip(j, o)
            print(trip.get_truck())

pp.pprint(sorted(result_dict['schedule'], key=lambda x: x['delivery time']))
コード例 #42
0
ファイル: Database.py プロジェクト: lukstafi/subte
                    stop_id = stop_node.get('id')

                    stop = Stop.get(int(stop_id))
                    tr.add_stop(stop)

                # trips
                trips_node = trip_route_node.find('Trips')
                for trip_node in trips_node.findall('Trip'):
                    trip_id = trip_node.get('id')

                    trip = tr.add_trip()
                    trip.trip_id = int(trip_id)


            for trip_node in tree.getroot().findall('Trip'):
                trip_id = trip_node.get('id', Trip.new_id())
                gtfs_id = trip_node.get('gtfs_id', None)
                name = trip_node.findtext('name')
                calendar_id = trip_node.findtext('calendar_id')
                route_id = trip_node.findtext('route_id')

                route = Route.get(int(route_id))

                trip = Trip.get(int(trip_id))
                trip.name = name
                trip.gtfs_id = gtfs_id

                # trip stops
                trip_stops_node = trip_node.find('TripStops')
                for i, trip_stop_node in enumerate(trip_stops_node.findall('TripStop')):
                    stop_id = trip_stop_node.findtext('stop_id')
コード例 #43
0
# Holds a set of random trips
all_trips = []
header = True
# Get 20000 trips
for t in trip_file:
    if header:
        # First row is just descriptions of data, not data at all
        header = False
        continue
    if i > 20000:
        break
    i += 1
    # This list is used to initialize a Trip object
    new_trip_list = [t[0], t[8], t[9], float(t[10]), float(t[11]),
                     float(t[12]), float(t[13]), -1, -1, 1]
    new_trip = Trip(new_trip_list)
    all_trips.append(new_trip)
grid_arcs = get_correct_nodes(n, "speeds_per_hour/0_0",
                              "ArcFlags/20Regions0_0.csv")
grid_a_star = get_correct_nodes(n, "speeds_per_hour/0_0", None)
node_info = get_node_range(grid_a_star)
max_speed = 0
# Iterates through every edge to find te fastest speed
for column in grid_a_star:
    for region in column:
        for node in region.nodes:
            for connection in node.speed_connections:
                if node.speed_connections[connection] > max_speed:
                    max_speed = node.speed_connections[connection]
all_trips_arcs = []
all_trips_star = []