Exemple #1
0
def get_search_results(database, priority, requestId):
    """Get the search results from the travel planner"""
    travelPlanner = TravelPlanner(database)
    userTripJson = {}
    if (priority == "distance"):
        userTripJson = travelPlanner.getBestRoutes(requestID = requestId, mode = Mode.tripTime)
    else:
        userTripJson = travelPlanner.getBestRoutes(requestID = requestId, mode = Mode.waitTime)             
    return userTripJson
Exemple #2
0
    def test(self, start, end, time, timeMode, routeMode, profiling = False):
        self.tp = TravelPlanner(self.db)
        print ("Testing...")
        request = {
                "_id": ObjectId(),
                "userID": 4711,
                "requestTime": datetime.datetime.utcnow()
        }
        request["startBusStop"] = self.busStopDict[start]["_id"]
        request["endBusStop"] = self.busStopDict[end]["_id"]
        request["startPositionLatitude"] = self.busStopDict[start]["latitude"]
        request["startPositionLongitude"] = self.busStopDict[start]["longitude"]
        request["endPositionLatitude"] = self.busStopDict[end]["latitude"]
        request["endPositionLongitude"] = self.busStopDict[end]["longitude"]
        if (timeMode == Mode.startTime):
            request["startTime"] = time
            request["endTime"] = "null"
        elif (timeMode == Mode.arrivalTime):
            request["startTime"] = "null"
            request["endTime"] = time
        else:
            print ("Error while preparing the test: timeMode is " + str(timeMode))
            return None
        print ("Request ID: " + str(request["_id"]))
        self.db.TravelRequest.insert_one(request)

        if (profiling):
            pr = cProfile.Profile()
            pr.enable()
            json = self.tp.getBestRoutes(request["_id"], routeMode)
            pr.disable()
            pstats.Stats(pr).print_stats('planner')
        else:
            json = self.tp.getBestRoutes(request["_id"], routeMode)
        return json
Exemple #3
0
    def test(self, start, end, time, timeMode, routeMode, profiling=False):
        self.tp = TravelPlanner(self.db)
        print("Testing...")
        request = {
            "_id": ObjectId(),
            "userID": 4711,
            "requestTime": datetime.datetime.utcnow()
        }
        request["startBusStop"] = self.busStopDict[start]["_id"]
        request["endBusStop"] = self.busStopDict[end]["_id"]
        request["startPositionLatitude"] = self.busStopDict[start]["latitude"]
        request["startPositionLongitude"] = self.busStopDict[start][
            "longitude"]
        request["endPositionLatitude"] = self.busStopDict[end]["latitude"]
        request["endPositionLongitude"] = self.busStopDict[end]["longitude"]
        if (timeMode == Mode.startTime):
            request["startTime"] = time
            request["endTime"] = "null"
        elif (timeMode == Mode.arrivalTime):
            request["startTime"] = "null"
            request["endTime"] = time
        else:
            print("Error while preparing the test: timeMode is " +
                  str(timeMode))
            return None
        print("Request ID: " + str(request["_id"]))
        self.db.TravelRequest.insert_one(request)

        if (profiling):
            pr = cProfile.Profile()
            pr.enable()
            json = self.tp.getBestRoutes(request["_id"], routeMode)
            pr.disable()
            pstats.Stats(pr).print_stats('planner')
        else:
            json = self.tp.getBestRoutes(request["_id"], routeMode)
        return json
Exemple #4
0
class tester:
    def __init__(self):
        print("Setting up test system...")
        client = MongoClient()
        self.db = client.monad

        busStops = self.db.BusStop.find()
        self.busStopDict = {}
        for stop in busStops:
            self.busStopDict[stop["name"]] = stop

        print("Running UnitTests...")
        call(["python", "test_planner.py"])

    def test(self, start, end, time, timeMode, routeMode, profiling=False):
        self.tp = TravelPlanner(self.db)
        print("Testing...")
        request = {
            "_id": ObjectId(),
            "userID": 4711,
            "requestTime": datetime.datetime.utcnow()
        }
        request["startBusStop"] = self.busStopDict[start]["_id"]
        request["endBusStop"] = self.busStopDict[end]["_id"]
        request["startPositionLatitude"] = self.busStopDict[start]["latitude"]
        request["startPositionLongitude"] = self.busStopDict[start][
            "longitude"]
        request["endPositionLatitude"] = self.busStopDict[end]["latitude"]
        request["endPositionLongitude"] = self.busStopDict[end]["longitude"]
        if (timeMode == Mode.startTime):
            request["startTime"] = time
            request["endTime"] = "null"
        elif (timeMode == Mode.arrivalTime):
            request["startTime"] = "null"
            request["endTime"] = time
        else:
            print("Error while preparing the test: timeMode is " +
                  str(timeMode))
            return None
        print("Request ID: " + str(request["_id"]))
        self.db.TravelRequest.insert_one(request)

        if (profiling):
            pr = cProfile.Profile()
            pr.enable()
            json = self.tp.getBestRoutes(request["_id"], routeMode)
            pr.disable()
            pstats.Stats(pr).print_stats('planner')
        else:
            json = self.tp.getBestRoutes(request["_id"], routeMode)
        return json

    def printBestResult(self, jsonObject):
        if (jsonObject == None or jsonObject == {}):
            print("No route found!")
            return
        best = jsonObject[1]
        trip = "Route from " + best[0]["startBusStop"] + " to " + best[-1][
            "endBusStop"]
        time = "Trip starts at " + best[0][
            "startTime"] + " and ends at " + best[-1]["endTime"]
        line = "Taking line " + str(best[0]["line"])
        if (len(best) > 1):
            for i in range(1, len(best)):
                trip += " via " + best[i]["startBusStop"]
                line += " and " + str(best[i]["line"])
                if (i < len(best)):
                    time += ". Waiting at intermediate busstop from " + best[i - 1]["endTime"] + \
                            " to " + best[i]["startTime"]
        print(trip)
        print(time)
        print(line)

    def printJson(self, jsonObject):
        if (jsonObject == None or jsonObject == {}):
            print("No route found!")
            return
        best = jsonObject[1]
        route = "Route from " + best[0]["startBusStop"] + " to " + best[-1][
            "endBusStop"]
        print(route)
        for key in jsonObject.keys():
            tripLine = 'Trip ' + str(key)
            print(tripLine)
            for trip in jsonObject[key]:
                tour = "From " + trip["startBusStop"] + " to " + trip[
                    "endBusStop"]
                time = "Start " + str(trip["startTime"]) + " until " + str(
                    trip["endTime"])
                line = "Used line " + str(trip["line"])
                print(tour)
                print(time)
                print(line)
Exemple #5
0
class tester:

    def __init__(self):
        print ("Setting up test system...")
        client = MongoClient()
        self.db = client.monad

        busStops = self.db.BusStop.find()
        self.busStopDict = {}
        for stop in busStops:
            self.busStopDict[stop["name"]] = stop

        print ("Running UnitTests...")
        call(["python", "test_planner.py"])

    def test(self, start, end, time, timeMode, routeMode, profiling = False):
        self.tp = TravelPlanner(self.db)
        print ("Testing...")
        request = {
                "_id": ObjectId(),
                "userID": 4711,
                "requestTime": datetime.datetime.utcnow()
        }
        request["startBusStop"] = self.busStopDict[start]["_id"]
        request["endBusStop"] = self.busStopDict[end]["_id"]
        request["startPositionLatitude"] = self.busStopDict[start]["latitude"]
        request["startPositionLongitude"] = self.busStopDict[start]["longitude"]
        request["endPositionLatitude"] = self.busStopDict[end]["latitude"]
        request["endPositionLongitude"] = self.busStopDict[end]["longitude"]
        if (timeMode == Mode.startTime):
            request["startTime"] = time
            request["endTime"] = "null"
        elif (timeMode == Mode.arrivalTime):
            request["startTime"] = "null"
            request["endTime"] = time
        else:
            print ("Error while preparing the test: timeMode is " + str(timeMode))
            return None
        print ("Request ID: " + str(request["_id"]))
        self.db.TravelRequest.insert_one(request)

        if (profiling):
            pr = cProfile.Profile()
            pr.enable()
            json = self.tp.getBestRoutes(request["_id"], routeMode)
            pr.disable()
            pstats.Stats(pr).print_stats('planner')
        else:
            json = self.tp.getBestRoutes(request["_id"], routeMode)
        return json

    def printBestResult(self, jsonObject):
        if (jsonObject == None or jsonObject == {}):
            print ("No route found!")
            return
        best = jsonObject[1]
        trip = "Route from " + best[0]["startBusStop"] + " to " + best[-1]["endBusStop"]
        time = "Trip starts at " + best[0]["startTime"] + " and ends at " + best[-1]["endTime"]
        line = "Taking line " + str(best[0]["line"])
        if (len(best) > 1):
            for i in range(1, len(best)):
                trip += " via " + best[i]["startBusStop"]
                line += " and " + str(best[i]["line"])
                if (i < len(best)):
                    time += ". Waiting at intermediate busstop from " + best[i - 1]["endTime"] + \
                            " to " + best[i]["startTime"]
        print (trip)
        print (time)
        print (line)

    def printJson(self, jsonObject):
        if (jsonObject == None or jsonObject == {}):
            print ("No route found!")
            return
        best = jsonObject[1]
        route = "Route from " + best[0]["startBusStop"] + " to " + best[-1]["endBusStop"]
        print (route)
        for key in jsonObject.keys():
            tripLine = 'Trip ' + str(key)
            print (tripLine)
            for trip in jsonObject[key]:
                tour = "From " + trip["startBusStop"] + " to " + trip["endBusStop"]
                time = "Start " + str(trip["startTime"]) + " until " + str(trip["endTime"])
                line = "Used line " + str(trip["line"])
                print (tour)
                print (time)
                print (line)
Exemple #6
0
class TestTravelPlanner(unittest.TestCase):

    client = MongoClient()
    dbName = "monad1"
    db = client[dbName]
    tp = TravelPlanner(db)
    version = sys.version_info[0]

    def test_init(self):
        self.tp._prepareSearch()
        if (self.version == 2):
            mongoString = "Collection(Database(MongoClient('localhost', 27017), u'"
            requestDBString = mongoString + self.dbName + "'), u'TravelRequest')"
            routeDBString = mongoString + self.dbName + "'), u'Route')"
            timetableDBString = mongoString + self.dbName + "'), u'TimeTable')"
            usertripDBString = mongoString + self.dbName + "'), u'UserTrip')"
            busTripDBString = mongoString + self.dbName + "'), u'BusTrip')"
            busStopDBString = mongoString + self.dbName + "'), u'BusStop')"
        elif (self.version == 3):
            mongoString = "Collection(Database(MongoClient(host=['localhost:27017'], " + \
                    "document_class=dict, tz_aware=False, connect=True), '"
            requestDBString = mongoString + self.dbName + "'), 'TravelRequest')"
            routeDBString = mongoString + self.dbName + "'), 'Route')"
            timetableDBString = mongoString + self.dbName + "'), 'TimeTable')"
            usertripDBString = mongoString + self.dbName + "'), 'UserTrip')"
            busTripDBString = mongoString + self.dbName + "'), 'BusTrip')"
            busStopDBString = mongoString + self.dbName + "'), 'BusStop')"

        self.assertEqual(self.tp.singleRoutes, [])
        self.assertEqual(self.tp.multiRoutes, [])
        self.assertEqual(self.tp.possibleRoutes, [])
        self.assertEqual(self.tp.tripTuples, [])
        self.assertEqual(self.tp.lineTuples, [])

        self.assertEqual(str(self.tp.travelRequest), requestDBString)
        self.assertEqual(str(self.tp.route), routeDBString)
        self.assertEqual(str(self.tp.timeTable), timetableDBString)
        self.assertEqual(str(self.tp.userTrip), usertripDBString)
        self.assertEqual(str(self.tp.busTrip), busTripDBString)
        self.assertEqual(str(self.tp.busStop), busStopDBString)

    def test_range(self):
        r1 = [2, 1, 0]
        r2 = [0, 1, 2]
        self.assertEqual(r1, self.tp._range(4))
        self.assertNotEqual(r2, self.tp._range(4))

    def test_isBetterTripStartTime(self):
        self.tp.tripTuples = [("trip", TIMEDIFF_30MIN, TIME_1300H, TIME_1315H)]
        self.tp.timeMode = Mode.startTime

        self.tp.timeToArrival = TIMEDIFF_25MIN
        self.assertTrue(self.tp._isBetterTrip(0))

        self.tp.timeToArrival = TIMEDIFF_30MIN
        self.tp.dptTime = TIME_1305H
        self.tp.routeMode = Mode.tripTime
        self.assertTrue(self.tp._isBetterTrip(0))
        self.tp.routeMode = Mode.waitTime
        self.assertFalse(self.tp._isBetterTrip(0))

        self.tp.dptTime = TIME_1255H
        self.tp.routeMode = Mode.waitTime
        self.assertTrue(self.tp._isBetterTrip(0))
        self.tp.routeMode = Mode.tripTime
        self.assertFalse(self.tp._isBetterTrip(0))

        self.tp.timeToArrival = TIMEDIFF_60MIN
        self.assertFalse(self.tp._isBetterTrip(0))

    def test_isBetterTripArrivalTime(self):
        self.tp.tripTuples = [("trip", TIMEDIFF_30MIN, TIME_1300H, TIME_1315H)]
        self.tp.timeMode = Mode.arrivalTime

        self.tp.diffToArrTime = TIMEDIFF_25MIN
        self.assertTrue(self.tp._isBetterTrip(0))

        self.tp.diffToArrTime = TIMEDIFF_30MIN
        self.tp.dptTime = TIME_1305H
        self.tp.routeMode = Mode.tripTime
        self.assertTrue(self.tp._isBetterTrip(0))
        self.tp.routeMode = Mode.waitTime
        self.assertFalse(self.tp._isBetterTrip(0))

        self.tp.dptTime = TIME_1255H
        self.tp.routeMode = Mode.waitTime
        self.assertTrue(self.tp._isBetterTrip(0))
        self.tp.routeMode = Mode.tripTime
        self.assertFalse(self.tp._isBetterTrip(0))

        self.tp.diffToArrTime = TIMEDIFF_60MIN
        self.assertFalse(self.tp._isBetterTrip(0))

    def test_rankTripStartTime(self):
        trip1 = ("trip1", TIMEDIFF_15MIN, TIME_1305H, TIME_1315H)
        trip2 = ("trip2", TIMEDIFF_20MIN, TIME_1300H, TIME_1320H)
        trip3 = ("trip3", TIMEDIFF_30MIN, TIME_1315H, TIME_1330H)
        trip4 = ("trip4", TIMEDIFF_30MIN, TIME_1300H, TIME_1330H)
        self.tp.tripTuples = [trip1, trip2, trip3, trip4]
        self.tp.timeMode = Mode.startTime
        self.tp.routeMode = Mode.tripTime

        trip = "trip5"
        self.tp.timeToArrival = TIMEDIFF_60MIN
        self.tp.dptTime = TIME_1330H
        self.tp.arrTime = TIME_1400H
        trip5 = (trip, self.tp.timeToArrival, self.tp.dptTime, self.tp.arrTime)
        self.tp._rankTrip(trip)
        self.assertEqual(self.tp.tripTuples,
                         [trip1, trip2, trip3, trip4, trip5])

        trip = "trip6"
        self.tp.timeToArrival = TIMEDIFF_20MIN
        self.tp.dptTime = TIME_1305H
        self.tp.arrTime = TIME_1320H
        trip6 = (trip, self.tp.timeToArrival, self.tp.dptTime, self.tp.arrTime)
        self.tp._rankTrip(trip)
        self.assertEqual(self.tp.tripTuples,
                         [trip1, trip6, trip2, trip3, trip4])

        trip = "trip7"
        self.tp.timeToArrival = TIMEDIFF_60MIN
        self.tp.dptTime = TIME_1330H
        self.tp.arrTime = TIME_1400H
        trip7 = (trip, self.tp.timeToArrival, self.tp.dptTime, self.tp.arrTime)
        self.tp._rankTrip(trip)
        self.assertEqual(self.tp.tripTuples,
                         [trip1, trip6, trip2, trip3, trip4])

    def test_rankTripArrivalTime(self):
        trip1 = ("trip1", TIMEDIFF_0MIN, TIME_1330H, TIME_1400H)
        trip2 = ("trip2", TIMEDIFF_30MIN, TIME_1320H, TIME_1330H)
        trip3 = ("trip3", TIMEDIFF_30MIN, TIME_1315H, TIME_1330H)
        trip4 = ("trip4", TIMEDIFF_30MIN, TIME_1300H, TIME_1330H)
        self.tp.tripTuples = [trip1, trip2, trip3, trip4]
        self.tp.timeMode = Mode.arrivalTime
        self.tp.routeMode = Mode.tripTime

        trip = "trip5"
        self.tp.diffToArrTime = TIMEDIFF_45MIN
        self.tp.dptTime = TIME_1300H
        self.tp.arrTime = TIME_1315H
        trip5 = (trip, self.tp.diffToArrTime, self.tp.dptTime, self.tp.arrTime)
        self.tp._rankTrip(trip)
        self.assertEqual(self.tp.tripTuples,
                         [trip1, trip2, trip3, trip4, trip5])

        trip = "trip6"
        self.tp.diffToArrTime = TIMEDIFF_15MIN
        self.tp.dptTime = TIME_1330H
        self.tp.arrTime = TIME_1345H
        trip6 = (trip, self.tp.diffToArrTime, self.tp.dptTime, self.tp.arrTime)
        self.tp._rankTrip(trip)
        self.assertEqual(self.tp.tripTuples,
                         [trip1, trip6, trip2, trip3, trip4])

        trip = "trip7"
        self.tp.diffToArrTime = TIMEDIFF_60MIN
        self.tp.dptTime = TIME_1300H
        self.tp.arrTime = TIME_1255H
        trip7 = (trip, self.tp.diffToArrTime, self.tp.dptTime, self.tp.arrTime)
        self.tp._rankTrip(trip)
        self.assertEqual(self.tp.tripTuples,
                         [trip1, trip6, trip2, trip3, trip4])

    def test_insertTrip(self):
        self.tp.tripTuples = []
        self.tp.counter = 0
        self.tp.startingWaypoint = [0]
        self.tp.endingWaypoint = [1]
        self.tp.startTime = TIME_1300H
        self.tp.timeMode = Mode.startTime

        trip = "trip1"
        self.tp.dptTime = TIME_1305H
        self.tp.arrTime = TIME_1315H
        self.tp._insertTrip(trip)
        trip1 = (trip, TIMEDIFF_15MIN, TIME_1305H, TIME_1315H)
        self.assertEqual(self.tp.tripTuples, [trip1])

        trip = "trip2"
        self.tp.dptTime = TIME_1315H
        self.tp.arrTime = TIME_1320H
        self.tp._insertTrip(trip)
        trip2 = (trip, TIMEDIFF_20MIN, TIME_1315H, TIME_1320H)
        self.assertEqual(self.tp.tripTuples, [trip1, trip2])

        self.tp.tripTuples = []
        self.tp.endTime = TIME_1400H
        self.tp.timeMode = Mode.arrivalTime

        trip = "trip1"
        self.tp.dptTime = TIME_1330H
        self.tp.arrTime = TIME_1345H
        self.tp._insertTrip(trip)
        trip1 = (trip, TIMEDIFF_15MIN, TIME_1330H, TIME_1345H)
        self.assertEqual(self.tp.tripTuples, [trip1])

        trip = "trip2"
        self.tp.dptTime = TIME_1345H
        self.tp.arrTime = TIME_1400H
        self.tp._insertTrip(trip)
        trip2 = (trip, TIMEDIFF_0MIN, TIME_1345H, TIME_1400H)
        self.assertEqual(self.tp.tripTuples, [trip2, trip1])

    def test_isFastRoute(self):
        self.tp.tripTuples = []
        self.assertFalse(self.tp._isFastRoute())
        self.tp.tripTuples = [("trip", TIMEDIFF_15MIN, TIME_1305H, TIME_1315H)]
        self.assertTrue(self.tp._isFastRoute())
        self.tp.tripTuples = [("trip", TIMEDIFF_30MIN, TIME_1305H, TIME_1330H)]
        self.assertFalse(self.tp._isFastRoute())

    def test_convertToJason(self):
        stops = ["Stora Torget", "Centralstationen"]
        objectID = ObjectId()
        objectIDstr = str(objectID)
        time = TIME_1300H
        timeStr = str(time)
        self.tp.userTripDict = {
            1: [{
                "_id": objectID,
                "userID": 4711,
                "line": 2,
                "busID": 56,
                "startBusStop": stops[0],
                "endBusStop": stops[1],
                "startTime": time,
                "endTime": time,
                "requestTime": time,
                "feedback": -1,
                "requestID": objectID,
                "next": objectID,
                "busTripID": objectID,
                "booked": False,
                "trajectory": [stops[0], stops[1]]
            }, {
                "_id": objectID,
                "userID": 4711,
                "line": 14,
                "busID": 57,
                "startBusStop": stops[0],
                "endBusStop": stops[1],
                "startTime": time,
                "endTime": time,
                "requestTime": time,
                "feedback": -1,
                "requestID": objectID,
                "busTripID": objectID,
                "booked": False,
                "trajectory": [stops[0], stops[1]]
            }]
        }
        self.tp._convertToJson()
        jsonObject = self.tp.jsonObject
        self.assertEqual(objectIDstr, jsonObject[1][0]["_id"])
        self.assertEqual(objectIDstr, jsonObject[1][0]["requestID"])
        self.assertEqual(objectIDstr, jsonObject[1][1]["busTripID"])
        self.assertEqual(objectIDstr, jsonObject[1][0]["next"])
        self.assertEqual(objectIDstr, jsonObject[1][1]["_id"])
        self.assertEqual(objectIDstr, jsonObject[1][1]["requestID"])
        self.assertEqual(objectIDstr, jsonObject[1][1]["busTripID"])

        self.assertEqual(stops[0], jsonObject[1][0]["startBusStop"])
        self.assertEqual(stops[1], jsonObject[1][0]["endBusStop"])
        self.assertEqual(stops[0], jsonObject[1][0]["trajectory"][0])
        self.assertEqual(stops[1], jsonObject[1][0]["trajectory"][1])
        self.assertEqual(stops[0], jsonObject[1][1]["startBusStop"])
        self.assertEqual(stops[1], jsonObject[1][1]["endBusStop"])
        self.assertEqual(stops[0], jsonObject[1][1]["trajectory"][0])
        self.assertEqual(stops[1], jsonObject[1][1]["trajectory"][1])

        self.assertEqual(timeStr, jsonObject[1][0]["startTime"])
        self.assertEqual(timeStr, jsonObject[1][0]["endTime"])
        self.assertEqual(timeStr, jsonObject[1][0]["requestTime"])
        self.assertEqual(timeStr, jsonObject[1][1]["startTime"])
        self.assertEqual(timeStr, jsonObject[1][1]["endTime"])
        self.assertEqual(timeStr, jsonObject[1][1]["requestTime"])

        self.assertTrue("next" in jsonObject[1][0])
        self.assertFalse("next" in jsonObject[1][1])

    # The number of tests is very important!
    def test_hereIsOneMoreTestThatWillSucceed(self):
        self.assertTrue(True)