예제 #1
0
    def timezone(self):
        if self._timezone:
            return self._timezone

        tf = TimezoneFinder()
        coords = self.coordinates
        return tf.timezone_at(lng=coords[1], lat=coords[0])
예제 #2
0
        def check_speed_my_algor():
            start_time = datetime.now()

            timezonefinder = TimezoneFinder()

            end_time = datetime.now()

            timezonefinder.timezone_at(13.3, 53.2)

            return end_time - start_time
예제 #3
0
    def setUpClass(cls):
        # preparations which have to be made only once
        print("\nSTARTING PACKAGE TESTS\n\n")
        cls.print_tf_class_props(cls)

        global in_memory_mode
        in_memory_mode = cls.in_memory_mode
        t = timeit.timeit("TimezoneFinder(in_memory=in_memory_mode)", globals=globals(), number=1)
        print('startup time:', time_preprocess(t), '\n')

        cls.timezone_finder = TimezoneFinder(in_memory=cls.in_memory_mode)

        # create an array of points where timezone_finder finds something (realistic queries)
        print('collecting and storing', N, 'realistic points for the tests...')
        cls.realistic_points = []
        ps_for_10percent = int(N / 10)
        percent_done = 0

        i = 0
        while i < N:
            lng, lat = random_point()
            # a realistic point is a point where certain_timezone_at() finds something
            if cls.timezone_finder.certain_timezone_at(lng=lng, lat=lat):
                i += 1
                cls.realistic_points.append((lng, lat))
                if i % ps_for_10percent == 0:
                    percent_done += 10
                    print(percent_done, '%')

        print("Done.\n")
예제 #4
0
    def test_speed(self):
        print("\n\nSpeed Tests:\n-------------")

        # def check_speed_tzwhere(list_of_points):
        #     start_time = datetime.now()
        #     for point in list_of_points:
        #         self.tz_where.tzNameAt(latitude=point[1], longitude=point[0])
        #     end_time = datetime.now()
        #     return end_time - start_time

        def check_speed_my_algor(list_of_points):
            start_time = datetime.now()
            for point in list_of_points:
                self.timezone_finder.timezone_at(lng=point[0], lat=point[1])
            end_time = datetime.now()
            return end_time - start_time

        def print_speed_test(type_of_points, list_of_points):
            my_time = check_speed_my_algor(list_of_points)
            # his_time = check_speed_tzwhere(list_of_points)
            print('\nTIMES for ', N, type_of_points)
            print_speedup(timezoefinder_time=my_time)

        # if SHAPELY:
        #     print('shapely: ON (tzwhere)')
        # else:
        #     print('shapely: OFF (tzwhere)')

        if TimezoneFinder.using_numba():
            print('Numba: ON (timezonefinder)')
        else:
            print('Numba: OFF (timezonefinder)')
        print_speed_test('realistic points', self.realistic_points)
        print_speed_test('random points', list_of_random_points(length=N))
예제 #5
0
    def test_speed(self):
        print("\n\nSpeed Tests:\n-------------")

        def check_speed_of_algorithm(list_of_points):
            start_time = datetime.now()
            for point in list_of_points:
                self.timezone_finder.timezone_at(lng=point[0], lat=point[1])
            end_time = datetime.now()
            return end_time - start_time

        def print_speed_test(type_of_points, list_of_points):
            my_time = check_speed_of_algorithm(list_of_points)
            print('\nrequired time for ', N, type_of_points)
            print_time(timezoefinder_time=my_time)

        if TimezoneFinder.using_numba():
            print('Numba: ON (timezonefinder)')
        else:
            print('Numba: OFF (timezonefinder)')
        print_speed_test('realistic points', self.realistic_points)
        print_speed_test('random points', list_of_random_points(length=N))
예제 #6
0
    def test_speed(self):
        def check_speed_his_algor(list_of_points):
            start_time = datetime.now()
            for point in list_of_points:
                self.tz_where.tzNameAt(latitude=point[1], longitude=point[0])
            end_time = datetime.now()
            return end_time - start_time

        def check_speed_my_algor(list_of_points):
            start_time = datetime.now()
            for point in list_of_points:
                self.timezone_finder.timezone_at(lng=point[0], lat=point[1])
            end_time = datetime.now()
            return end_time - start_time

        def print_speed_test(type_of_points, list_of_points):
            my_time = check_speed_my_algor(list_of_points)
            his_time = check_speed_his_algor(list_of_points)
            print('')
            print('\nTIMES for ', N, type_of_points)
            print('tzwhere:', his_time)
            print('timezonefinder:', my_time)
            try:
                print(round(his_time / my_time, 2), 'times faster')
            except TypeError:
                pass
                # assert his_time > my_time

        print('\n\n')
        if SHAPELY:
            print('shapely: ON (tzwhere)')
        else:
            print('shapely: OFF (tzwhere)')
        if TimezoneFinder.using_numba():
            print('Numba: ON (timezonefinder)')
        else:
            print('Numba: OFF (timezonefinder)')
        print_speed_test('realistic points', self.realistic_points)
        print_speed_test('random points', list_of_random_points(length=N))
예제 #7
0
 def print_tf_class_props(self):
     print("in memory mode:", self.in_memory_mode)
     if TimezoneFinder.using_numba():
         print('Numba: ON (precompiled functions in use)')
     else:
         print('Numba: OFF (precompiled functions NOT in use)')
예제 #8
0
class PackageEqualityTest(unittest.TestCase):
    # do the preparations which have to be made only once

    if SHAPELY:
        print('shapely: ON (tzwhere)')
    else:
        print('shapely: OFF (tzwhere)')

    if TimezoneFinder.using_numba():
        print('Numba: ON (timezonefinder)')
    else:
        print('Numba: OFF (timezonefinder)')

    start_time = datetime.now()
    timezone_finder = TimezoneFinder()
    end_time = datetime.now()
    my_time = end_time - start_time

    print('Starting tz_where. This could take a moment...')

    # integrated start up time test:
    # (when doing this for multiple times things are already cached and therefore produce misleading results)
    start_time = datetime.now()
    tz_where = tzwhere(shapely=SHAPELY)
    end_time = datetime.now()
    his_time = end_time - start_time

    print('\nStartup times:')
    print('tzwhere:', his_time)
    print('timezonefinder:', my_time)
    try:
        print(round(his_time / my_time, 2), 'times faster')
    except TypeError:
        pass
    print('\n\n')

    # create an array of n points where tzwhere finds something (realistic queries)
    print('collecting and storing', N, 'realistic points for the tests...')
    realistic_points = []
    real_ps_results_tzwhere = []
    real_ps_results_certain = []

    ps_for_10percent = int(N / 10)
    percent_done = 0

    i = 0
    while i < N:
        lng, lat = random_point()
        # a realistic point is a point where certain_timezone_at() or tzwhere find something
        if not (tz_where.tzNameAt(lat, lng)
                or timezone_finder.certain_timezone_at(lng=lng, lat=lat)):
            i += 1
            realistic_points.append((lng, lat))
            if i % ps_for_10percent == 0:
                percent_done += 10
                print(percent_done, '%')

    print("Done.")

    def test_correctness(self):
        print('\nresults timezone_at()')
        template = '{0:20s} | {1:20s} | {2:20s} | {3:2s}'
        no_mistakes_made = True
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', '=='))
        print(
            '===================================================================='
        )
        for (lat, lng, loc, expected) in TEST_LOCATIONS:
            computed = self.timezone_finder.timezone_at(lng=lng, lat=lat)

            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        assert no_mistakes_made

        print('\ncertain_timezone_at():')
        no_mistakes_made = True
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', 'Status'))
        print(
            '===================================================================='
        )
        for (lat, lng, loc, expected) in TEST_LOCATIONS:
            computed = self.timezone_finder.certain_timezone_at(lng=lng,
                                                                lat=lat)
            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        assert no_mistakes_made

        print('\nclosest_timezone_at():')
        no_mistakes_made = True
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', 'Status'))
        print(
            '===================================================================='
        )
        for (lat, lng, loc, expected) in TEST_LOCATIONS_PROXIMITY:
            computed = self.timezone_finder.closest_timezone_at(lng=lng,
                                                                lat=lat)
            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        assert no_mistakes_made

    def test_equality(self):
        # Test the equality of the two packages for N realistic and N random points
        def print_equality_test(types_of_points, list_of_points):
            print('\ntesting', N, types_of_points)
            print('MISMATCHES:')
            template = '{0:40s} | {1:20s} | {2:21s} | {3:20s}'
            print(
                template.format('Point', 'timezone_at()',
                                'certain_timezone_at()', 'tzwhere'))
            print(
                '========================================================================='
            )
            mistakes = 0
            for lng, lat in list_of_points:
                his_result = self.tz_where.tzNameAt(lat, lng)
                my_result_certain = self.timezone_finder.certain_timezone_at(
                    lng=lng, lat=lat)
                # test only makes sense if certain_timezone_at() or tzwhere find something
                if his_result is not None or my_result_certain is not None:
                    my_result = self.timezone_finder.timezone_at(lng=lng,
                                                                 lat=lat)
                    if my_result != his_result or my_result_certain != his_result:
                        if his_result in excluded_zones_tzwhere and my_result in excluded_zones_timezonefinder:
                            print(
                                template.format((lat, lng), my_result,
                                                my_result_certain, his_result),
                                '(not counted, see issue section)')
                        else:
                            mistakes += 1
                            print(
                                template.format(str((lat, lng)),
                                                str(my_result),
                                                str(my_result_certain),
                                                str(his_result)))
            print('\nin', N, 'tries', mistakes, 'mismatches were made')
            fail_percentage = mistakes * 100 / (2 * N)
            assert fail_percentage < 5

        print_equality_test('realistic points', self.realistic_points)
        print_equality_test('random points', list_of_random_points(length=N))

    def test_speed(self):
        def check_speed_his_algor(list_of_points):
            start_time = datetime.now()
            for point in list_of_points:
                self.tz_where.tzNameAt(latitude=point[1], longitude=point[0])
            end_time = datetime.now()
            return end_time - start_time

        def check_speed_my_algor(list_of_points):
            start_time = datetime.now()
            for point in list_of_points:
                self.timezone_finder.timezone_at(lng=point[0], lat=point[1])
            end_time = datetime.now()
            return end_time - start_time

        def print_speed_test(type_of_points, list_of_points):
            my_time = check_speed_my_algor(list_of_points)
            his_time = check_speed_his_algor(list_of_points)
            print('')
            print('\nTIMES for ', N, type_of_points)
            print('tzwhere:', his_time)
            print('timezonefinder:', my_time)
            try:
                print(round(his_time / my_time, 2), 'times faster')
            except TypeError:
                pass
                # assert his_time > my_time

        print('\n\n')
        if SHAPELY:
            print('shapely: ON (tzwhere)')
        else:
            print('shapely: OFF (tzwhere)')
        if TimezoneFinder.using_numba():
            print('Numba: ON (timezonefinder)')
        else:
            print('Numba: OFF (timezonefinder)')
        print_speed_test('realistic points', self.realistic_points)
        print_speed_test('random points', list_of_random_points(length=N))
예제 #9
0
 def print_tf_class_props(self):
     print("in memory mode:", self.in_memory_mode)
     if TimezoneFinder.using_numba():
         print('Numba: ON (precompiled functions in use)')
     else:
         print('Numba: OFF (precompiled functions NOT in use)')
예제 #10
0
class PackageEqualityTest(unittest.TestCase):
    # do the preparations which have to be made only once

    print("startup time:")

    # if SHAPELY:
    #     print('shapely: ON (tzwhere)')
    # else:
    #     print('shapely: OFF (tzwhere)')

    if TimezoneFinder.using_numba():
        print('Numba: ON (timezonefinder)')
    else:
        print('Numba: OFF (timezonefinder)')

    start_time = datetime.now()
    timezone_finder = TimezoneFinder()
    end_time = datetime.now()
    my_time = end_time - start_time

    # print('Starting tz_where. This could take a while...')

    # integrated start up time test:
    # (when doing this for multiple times things are already cached and therefore produce misleading results)
    # start_time = datetime.now()
    # tz_where = tzwhere()
    # end_time = datetime.now()
    # his_time = end_time - start_time

    print_speedup(timezoefinder_time=my_time)
    print('\n')

    # create an array of n points where tzwhere finds something (realistic queries)
    print('collecting and storing', N, 'realistic points for the tests...')
    realistic_points = []
    # real_ps_results_tzwhere = []
    # real_ps_results_certain = []

    ps_for_10percent = int(N / 10)
    percent_done = 0

    i = 0
    while i < N:
        lng, lat = random_point()
        # a realistic point is a point where certain_timezone_at() or tzwhere find something
        # if not (tz_where.tzNameAt(lat, lng) or timezone_finder.certain_timezone_at(lng=lng, lat=lat)):
        if timezone_finder.certain_timezone_at(lng=lng, lat=lat):
            i += 1
            realistic_points.append((lng, lat))
            if i % ps_for_10percent == 0:
                percent_done += 10
                print(percent_done, '%')

    print("Done.\n")

    def test_speed(self):
        print("\n\nSpeed Tests:\n-------------")

        # def check_speed_tzwhere(list_of_points):
        #     start_time = datetime.now()
        #     for point in list_of_points:
        #         self.tz_where.tzNameAt(latitude=point[1], longitude=point[0])
        #     end_time = datetime.now()
        #     return end_time - start_time

        def check_speed_my_algor(list_of_points):
            start_time = datetime.now()
            for point in list_of_points:
                self.timezone_finder.timezone_at(lng=point[0], lat=point[1])
            end_time = datetime.now()
            return end_time - start_time

        def print_speed_test(type_of_points, list_of_points):
            my_time = check_speed_my_algor(list_of_points)
            # his_time = check_speed_tzwhere(list_of_points)
            print('\nTIMES for ', N, type_of_points)
            print_speedup(timezoefinder_time=my_time)

        # if SHAPELY:
        #     print('shapely: ON (tzwhere)')
        # else:
        #     print('shapely: OFF (tzwhere)')

        if TimezoneFinder.using_numba():
            print('Numba: ON (timezonefinder)')
        else:
            print('Numba: OFF (timezonefinder)')
        print_speed_test('realistic points', self.realistic_points)
        print_speed_test('random points', list_of_random_points(length=N))

    def test_shortcut_boundary(self):
        # at the boundaries of the shortcut grid (coordinate system) the algorithms should still be well defined!
        assert self.timezone_finder.timezone_at(lng=-180.0, lat=90.0) is None
        assert self.timezone_finder.timezone_at(lng=180.0, lat=90.0) is None
        assert self.timezone_finder.timezone_at(lng=180.0, lat=-90.0) is None
        assert self.timezone_finder.timezone_at(lng=-180.0, lat=-90.0) is None

        with pytest.raises(ValueError):
            self.timezone_finder.timezone_at(lng=180.01, lat=90.0)
            self.timezone_finder.timezone_at(lng=180.0, lat=90.01)
            self.timezone_finder.timezone_at(lng=-180.01, lat=90.0)
            self.timezone_finder.timezone_at(lng=-180.0, lat=90.01)
            self.timezone_finder.timezone_at(lng=180.01, lat=-90.0)
            self.timezone_finder.timezone_at(lng=180.0, lat=-90.01)
            self.timezone_finder.timezone_at(lng=-180.01, lat=-90.0)
            self.timezone_finder.timezone_at(lng=-180.0, lat=-90.01)

    def test_correctness(self):
        no_mistakes_made = True
        template = '{0:20s} | {1:20s} | {2:20s} | {3:2s}'

        print('\nresults timezone_at()')
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', '=='))
        print('====================================================================')
        for (lat, lng, loc, expected) in TEST_LOCATIONS:
            computed = self.timezone_finder.timezone_at(lng=lng, lat=lat)

            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        print('\ncertain_timezone_at():')
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', 'Status'))
        print('====================================================================')
        for (lat, lng, loc, expected) in TEST_LOCATIONS_CERTAIN:
            computed = self.timezone_finder.certain_timezone_at(lng=lng, lat=lat)
            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        print('\nclosest_timezone_at():')
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', 'Status'))
        print('====================================================================')
        print('testing this function does not make sense any more, because the tz polygons do not follow the shoreline')
        for (lat, lng, loc, expected) in TEST_LOCATIONS_PROXIMITY:
            computed = self.timezone_finder.closest_timezone_at(lng=lng, lat=lat)
            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        assert no_mistakes_made

    # disabled because underlying data is completely different atm
    # def test_equality(self):
    #     # Test the equality of the two packages for N realistic and N random points
    #     def print_equality_test(types_of_points, list_of_points):
    #         print('\ntesting', N, types_of_points)
    #         print('MISMATCHES:')
    #         template = '{0:40s} | {1:20s} | {2:21s} | {3:20s}'
    #         print(template.format('Point', 'timezone_at()', 'certain_timezone_at()', 'tzwhere'))
    #         print('=========================================================================')
    #         mistakes = 0
    #         for lng, lat in list_of_points:
    #             his_result = self.tz_where.tzNameAt(lat, lng)
    #             my_result_certain = self.timezone_finder.certain_timezone_at(lng=lng, lat=lat)
    #             # test only makes sense if certain_timezone_at() or tzwhere find something
    #             if his_result is not None or my_result_certain is not None:
    #                 my_result = self.timezone_finder.timezone_at(lng=lng, lat=lat)
    #                 if my_result != his_result or my_result_certain != his_result:
    #                     if his_result in excluded_zones_tzwhere and my_result in excluded_zones_timezonefinder:
    #                         print(template.format((lat, lng), my_result, my_result_certain,
    #                                               his_result), '(not counted, see issue section)')
    #                     else:
    #                         mistakes += 1
    #                         print(template.format(str((lat, lng)), str(my_result), str(my_result_certain),
    #                                               str(his_result)))
    #         print('\nin', N, 'tries', mistakes, 'mismatches were made')
    #         fail_percentage = mistakes * 100 / (2 * N)
    #         assert fail_percentage < 5
    #
    #     print_equality_test('realistic points', self.realistic_points)
    #     print_equality_test('random points', list_of_random_points(length=N))

    @staticmethod
    def test_convert2coord_pairs():
        data = [[10000000, 20000000, 30000000], [10000000, 20000000, 30000000]]
        # print(convert2coord_pairs(data))
        assert (convert2coord_pairs(data) == [(1.0, 1.0), (2.0, 2.0), (3.0, 3.0)])

    @staticmethod
    def test_convert2coords():
        data = [[10000000, 20000000, 30000000], [10000000, 20000000, 30000000]]
        assert (convert2coords(data) == [[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]])
예제 #11
0
class PackageEqualityTest(unittest.TestCase):
    # do the preparations which have to be made only once

    print("startup time:")

    # if SHAPELY:
    #     print('shapely: ON (tzwhere)')
    # else:
    #     print('shapely: OFF (tzwhere)')

    if TimezoneFinder.using_numba():
        print('Numba: ON (timezonefinder)')
    else:
        print('Numba: OFF (timezonefinder)')

    start_time = datetime.now()
    timezone_finder = TimezoneFinder()
    end_time = datetime.now()
    my_time = end_time - start_time

    # print('Starting tz_where. This could take a while...')

    # integrated start up time test:
    # (when doing this for multiple times things are already cached and therefore produce misleading results)
    # start_time = datetime.now()
    # tz_where = tzwhere()
    # end_time = datetime.now()
    # his_time = end_time - start_time

    print_speedup(timezoefinder_time=my_time)
    print('\n')

    # create an array of n points where tzwhere finds something (realistic queries)
    print('collecting and storing', N, 'realistic points for the tests...')
    realistic_points = []
    # real_ps_results_tzwhere = []
    # real_ps_results_certain = []

    ps_for_10percent = int(N / 10)
    percent_done = 0

    i = 0
    while i < N:
        lng, lat = random_point()
        # a realistic point is a point where certain_timezone_at() or tzwhere find something
        # if not (tz_where.tzNameAt(lat, lng) or timezone_finder.certain_timezone_at(lng=lng, lat=lat)):
        if timezone_finder.certain_timezone_at(lng=lng, lat=lat):
            i += 1
            realistic_points.append((lng, lat))
            if i % ps_for_10percent == 0:
                percent_done += 10
                print(percent_done, '%')

    print("Done.\n")

    def test_speed(self):
        print("\n\nSpeed Tests:\n-------------")

        # def check_speed_tzwhere(list_of_points):
        #     start_time = datetime.now()
        #     for point in list_of_points:
        #         self.tz_where.tzNameAt(latitude=point[1], longitude=point[0])
        #     end_time = datetime.now()
        #     return end_time - start_time

        def check_speed_my_algor(list_of_points):
            start_time = datetime.now()
            for point in list_of_points:
                self.timezone_finder.timezone_at(lng=point[0], lat=point[1])
            end_time = datetime.now()
            return end_time - start_time

        def print_speed_test(type_of_points, list_of_points):
            my_time = check_speed_my_algor(list_of_points)
            # his_time = check_speed_tzwhere(list_of_points)
            print('\nTIMES for ', N, type_of_points)
            print_speedup(timezoefinder_time=my_time)

        # if SHAPELY:
        #     print('shapely: ON (tzwhere)')
        # else:
        #     print('shapely: OFF (tzwhere)')

        if TimezoneFinder.using_numba():
            print('Numba: ON (timezonefinder)')
        else:
            print('Numba: OFF (timezonefinder)')
        print_speed_test('realistic points', self.realistic_points)
        print_speed_test('random points', list_of_random_points(length=N))

    def test_shortcut_boundary(self):
        # at the boundaries of the shortcut grid (coordinate system) the algorithms should still be well defined!
        assert self.timezone_finder.timezone_at(lng=-180.0, lat=90.0) is None
        assert self.timezone_finder.timezone_at(lng=180.0, lat=90.0) is None
        assert self.timezone_finder.timezone_at(
            lng=180.0, lat=-90.0) == 'Antarctica/McMurdo'
        assert self.timezone_finder.timezone_at(
            lng=-180.0, lat=-90.0) == 'Antarctica/McMurdo'

        with pytest.raises(ValueError):
            self.timezone_finder.timezone_at(lng=180.01, lat=90.0)
            self.timezone_finder.timezone_at(lng=180.0, lat=90.01)
            self.timezone_finder.timezone_at(lng=-180.01, lat=90.0)
            self.timezone_finder.timezone_at(lng=-180.0, lat=90.01)
            self.timezone_finder.timezone_at(lng=180.01, lat=-90.0)
            self.timezone_finder.timezone_at(lng=180.0, lat=-90.01)
            self.timezone_finder.timezone_at(lng=-180.01, lat=-90.0)
            self.timezone_finder.timezone_at(lng=-180.0, lat=-90.01)

    def test_kwargs_only(self):
        # calling timezonefinder fcts without keyword arguments should raise an error
        with pytest.raises(TypeError):
            self.timezone_finder.timezone_at(23.0, 42.0)
            self.timezone_finder.timezone_at(23.0, lng=42.0)
            self.timezone_finder.timezone_at(23.0, lat=42.0)

    def test_correctness(self):
        no_mistakes_made = True
        template = '{0:20s} | {1:20s} | {2:20s} | {3:2s}'

        print('\nresults timezone_at()')
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', '=='))
        print(
            '===================================================================='
        )
        for (lat, lng, loc, expected) in TEST_LOCATIONS:
            computed = self.timezone_finder.timezone_at(lng=lng, lat=lat)

            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        print('\ncertain_timezone_at():')
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', 'Status'))
        print(
            '===================================================================='
        )
        for (lat, lng, loc, expected) in TEST_LOCATIONS_CERTAIN:
            computed = self.timezone_finder.certain_timezone_at(lng=lng,
                                                                lat=lat)
            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        print('\nclosest_timezone_at():')
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', 'Status'))
        print(
            '===================================================================='
        )
        print(
            'testing this function does not make sense any more, because the tz polygons do not follow the shoreline'
        )
        for (lat, lng, loc, expected) in TEST_LOCATIONS_PROXIMITY:
            computed = self.timezone_finder.closest_timezone_at(lng=lng,
                                                                lat=lat)
            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        assert no_mistakes_made

    # disabled because underlying data is completely different atm
    # def test_equality(self):
    #     # Test the equality of the two packages for N realistic and N random points
    #     def print_equality_test(types_of_points, list_of_points):
    #         print('\ntesting', N, types_of_points)
    #         print('MISMATCHES:')
    #         template = '{0:40s} | {1:20s} | {2:21s} | {3:20s}'
    #         print(template.format('Point', 'timezone_at()', 'certain_timezone_at()', 'tzwhere'))
    #         print('=========================================================================')
    #         mistakes = 0
    #         for lng, lat in list_of_points:
    #             his_result = self.tz_where.tzNameAt(lat, lng)
    #             my_result_certain = self.timezone_finder.certain_timezone_at(lng=lng, lat=lat)
    #             # test only makes sense if certain_timezone_at() or tzwhere find something
    #             if his_result is not None or my_result_certain is not None:
    #                 my_result = self.timezone_finder.timezone_at(lng=lng, lat=lat)
    #                 if my_result != his_result or my_result_certain != his_result:
    #                     if his_result in excluded_zones_tzwhere and my_result in excluded_zones_timezonefinder:
    #                         print(template.format((lat, lng), my_result, my_result_certain,
    #                                               his_result), '(not counted, see issue section)')
    #                     else:
    #                         mistakes += 1
    #                         print(template.format(str((lat, lng)), str(my_result), str(my_result_certain),
    #                                               str(his_result)))
    #         print('\nin', N, 'tries', mistakes, 'mismatches were made')
    #         fail_percentage = mistakes * 100 / (2 * N)
    #         assert fail_percentage < 5
    #
    #     print_equality_test('realistic points', self.realistic_points)
    #     print_equality_test('random points', list_of_random_points(length=N))

    @staticmethod
    def test_convert2coord_pairs():
        data = [[10000000, 20000000, 30000000], [10000000, 20000000, 30000000]]
        # print(convert2coord_pairs(data))
        assert (convert2coord_pairs(data) == [(1.0, 1.0), (2.0, 2.0),
                                              (3.0, 3.0)])

    @staticmethod
    def test_convert2coords():
        data = [[10000000, 20000000, 30000000], [10000000, 20000000, 30000000]]
        assert (convert2coords(data) == [[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]])

    @staticmethod
    def test_coord2shortcut():
        def coord2shortcut_test_fct(input):
            (lng, lat) = input
            return coord2shortcut(lng, lat)

        data = [
            # shortcut numbering starts at "the top left" with x,y= 0,0
            # always (only) the "top" and "left" borders belong to a shortcut
            # the other borders belong to the next neighbouring shortcut
            ((-180.0, 90.0), (0, 0)),
            # shortcuts are constant for every 1 degree lng and 0.5 degree lat
            # defined with NR_SHORTCUTS_PER_LNG, NR_SHORTCUTS_PER_LAT in timezonefinder.file_converter
            ((-179.9, 89.9), (0, 0)),

            # shortcut numbering follows the lng, lat coordinate grid
            ((-179.0, 90.0), (1, 0)),
            ((-178.9, 89.9), (1, 0)),
            ((-180.0, 89.5), (0, 1)),
            ((-179.9, 89.4), (0, 1)),
            ((-180.0, 89.0), (0, 2)),
            ((-179.9, 88.9), (0, 2)),

            # shortcut numbering end at "the top left" with x,y= 359, 359
            # lng= 180.0 == -180.0
            # lat =-90.0 is not allowed (=bottom border of a shortcut)
            ((179.9, -89.9), (359, 359)),
            ((179.8, -89.8), (359, 359)),
        ]

        proto_test_case(data, coord2shortcut_test_fct)

    def test_overflow(self):
        longitude = -123.2
        latitude = 48.4
        # make numpy overflow runtime warning raise an error
        import numpy as np
        np.seterr(all='warn')
        import warnings
        warnings.filterwarnings('error')
        # must not raise a warning
        self.timezone_finder.certain_timezone_at(lat=float(latitude),
                                                 lng=float(longitude))
예제 #12
0
 def setUp(self):
     if sys.version_info[0] < 3:
         self.timezone_finder = TimezoneFinder()
     else:
         print("** In Memory test")
         self.timezone_finder = TimezoneFinder(in_memory=True)
예제 #13
0
 def setUp(self):
     self.timezone_finder = TimezoneFinder()
예제 #14
0
class MainPackageTest(unittest.TestCase):
    # do the preparations which have to be made only once

    print("startup time:")
    if TimezoneFinder.using_numba():
        print('Numba: ON (precompiled functions in use)')
    else:
        print('Numba: OFF (precompiled functions NOT in use)')

    start_time = datetime.now()
    timezone_finder = TimezoneFinder()
    end_time = datetime.now()
    my_time = end_time - start_time
    print_time(timezoefinder_time=my_time)
    print('\n')

    # create an array of points where timezone_finder finds something (realistic queries)
    print('collecting and storing', N, 'realistic points for the tests...')
    realistic_points = []
    ps_for_10percent = int(N / 10)
    percent_done = 0

    i = 0
    while i < N:
        lng, lat = random_point()
        # a realistic point is a point where certain_timezone_at() finds something
        if timezone_finder.certain_timezone_at(lng=lng, lat=lat):
            i += 1
            realistic_points.append((lng, lat))
            if i % ps_for_10percent == 0:
                percent_done += 10
                print(percent_done, '%')

    print("Done.\n")

    def setUp(self):
        self.timezone_finder = TimezoneFinder()

    def test_speed(self):
        print("\n\nSpeed Tests:\n-------------")

        def check_speed_of_algorithm(list_of_points):
            start_time = datetime.now()
            for point in list_of_points:
                self.timezone_finder.timezone_at(lng=point[0], lat=point[1])
            end_time = datetime.now()
            return end_time - start_time

        def print_speed_test(type_of_points, list_of_points):
            my_time = check_speed_of_algorithm(list_of_points)
            print('\nrequired time for ', N, type_of_points)
            print_time(timezoefinder_time=my_time)

        if TimezoneFinder.using_numba():
            print('Numba: ON (timezonefinder)')
        else:
            print('Numba: OFF (timezonefinder)')
        print_speed_test('realistic points', self.realistic_points)
        print_speed_test('random points', list_of_random_points(length=N))

    def test_shortcut_boundary(self):
        # at the boundaries of the shortcut grid (coordinate system) the algorithms should still be well defined!
        assert self.timezone_finder.timezone_at(lng=-180.0, lat=90.0) is None
        assert self.timezone_finder.timezone_at(lng=180.0, lat=90.0) is None
        assert self.timezone_finder.timezone_at(
            lng=180.0, lat=-90.0) == 'Antarctica/McMurdo'
        assert self.timezone_finder.timezone_at(
            lng=-180.0, lat=-90.0) == 'Antarctica/McMurdo'

        with pytest.raises(ValueError):
            self.timezone_finder.timezone_at(lng=180.0 + INT2COORD_FACTOR,
                                             lat=90.0)
            self.timezone_finder.timezone_at(lng=-180.0 - INT2COORD_FACTOR,
                                             lat=90.0 + INT2COORD_FACTOR)
            self.timezone_finder.timezone_at(lng=-180.0,
                                             lat=90.0 + INT2COORD_FACTOR)
            self.timezone_finder.timezone_at(lng=180.0 + INT2COORD_FACTOR,
                                             lat=-90.0)
            self.timezone_finder.timezone_at(lng=180.0,
                                             lat=-90.0 - INT2COORD_FACTOR)
            self.timezone_finder.timezone_at(lng=-180.0 - INT2COORD_FACTOR,
                                             lat=-90.0)
            self.timezone_finder.timezone_at(lng=-180.0 - INT2COORD_FACTOR,
                                             lat=-90.01 - INT2COORD_FACTOR)

    def test_kwargs_only(self):
        # calling timezonefinder fcts without keyword arguments should raise an error
        with pytest.raises(TypeError):
            self.timezone_finder.timezone_at(23.0, 42.0)
            self.timezone_finder.timezone_at(23.0, lng=42.0)
            self.timezone_finder.timezone_at(23.0, lat=42.0)

    def test_correctness(self):
        no_mistakes_made = True
        template = '{0:20s} | {1:20s} | {2:20s} | {3:2s}'

        print('\nresults timezone_at()')
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', '=='))
        print(
            '===================================================================='
        )
        for (lat, lng, loc, expected) in TEST_LOCATIONS:
            computed = self.timezone_finder.timezone_at(lng=lng, lat=lat)

            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        print('\ncertain_timezone_at():')
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', 'Status'))
        print(
            '===================================================================='
        )
        for (lat, lng, loc, expected) in TEST_LOCATIONS_CERTAIN:
            computed = self.timezone_finder.certain_timezone_at(lng=lng,
                                                                lat=lat)
            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        print('\nclosest_timezone_at():')
        print(template.format('LOCATION', 'EXPECTED', 'COMPUTED', 'Status'))
        print(
            '===================================================================='
        )
        print(
            'testing this function does not make sense any more, because the tz polygons do not follow the shoreline'
        )
        for (lat, lng, loc, expected) in TEST_LOCATIONS_PROXIMITY:
            computed = self.timezone_finder.closest_timezone_at(lng=lng,
                                                                lat=lat)
            if computed == expected:
                ok = 'OK'
            else:
                print(lat, lng)
                ok = 'XX'
                no_mistakes_made = False
            print(template.format(loc, str(expected), str(computed), ok))

        assert no_mistakes_made

    def test_overflow(self):
        longitude = -123.2
        latitude = 48.4
        # make numpy overflow runtime warning raise an error
        import numpy as np
        np.seterr(all='warn')
        import warnings
        warnings.filterwarnings('error')
        # must not raise a warning
        self.timezone_finder.certain_timezone_at(lat=float(latitude),
                                                 lng=float(longitude))
예제 #15
0
def random_point():
    # tzwhere does not work for points with more latitude!
    return random.uniform(-180, 180), random.uniform(-84, 84)


def list_of_random_points(length):
    return [random_point() for i in range(length)]


duration_idle_mem_test = 20
duration_in_use_mem_test = 20

if __name__ == '__main__':

    if TimezoneFinder.using_numba():
        print('Numba: ON (timezonefinder)')
    else:
        print('Numba: OFF (timezonefinder)')

    start_time = datetime.now()
    timezone_finder = TimezoneFinder()
    end_time = datetime.now()
    my_time = end_time - start_time

    print('\nStartup time:')
    print('timezonefinder:', my_time)

    print(
        "Check the memory usage of python in your process list (Task Manager, Activity Manager...)"
    )