def test_distance_between_two_points(): cord1 = [Decimal(75.3425), Decimal(-95.300)] cord2 = [Decimal(76.6543), Decimal(-95.3566)] expectedDistance = Distance(146.44140729201737) difference = expectedDistance.km - unit.calculate_distance(cord1, cord2).km assert abs(difference) <= 0.00001
def filter(self, *args, **kwargs): """Override filter to support custom lookups""" filters = None for key in kwargs.keys(): if not key.endswith( (APPROX_DISTANCE_POSTFIX, EXACT_DISTANCE_POSTFIX)): continue location, radius = kwargs.pop(key) radius = Distance(radius) is_exact = key.endswith(EXACT_DISTANCE_POSTFIX) field_name = key.replace(APPROX_DISTANCE_POSTFIX, '').replace(EXACT_DISTANCE_POSTFIX, '') filters = self._create_approx_distance_filter( field_name, location, radius) if is_exact: self._postprocess['field_name'] = field_name self._postprocess['location'] = location self._postprocess['radius'] = radius result = super(GeoQuerySet, self).filter(*args, **kwargs) if filters: return result.filter(filters) return result
def mock_trail(id, length, start_node_id=None, end_node_id=None): trail = Trail([MagicMock()], id, f"trail{id}") trail.length = MagicMock(return_value=Distance(meters=length)) trail.length_m = MagicMock(return_value=length) trail.reverse = MagicMock(return_value=trail) trail.nodes = [Node(start_node_id, 0, 0), Node(end_node_id, 0, 0)] return trail
def lazyDistance(P, Q): """ Fastest but inaccurate distance function. Radius Error ~10km 0.002% ~100km 0.0016% (sometimes even better than GreatCircleDistance) ~3000km 0.00074% Speed: 11.8x faster than VincentyDistance """ latP, lngP = radians(degrees=P[0]), radians(degrees=P[1]) latQ, lngQ = radians(degrees=Q[0]), radians(degrees=Q[1]) sphericalCos = sin(latP) * sin(latQ) + cos(latP) * cos(latQ) * cos(lngQ - lngP) return Distance(acos(sphericalCos) * 6371)
def hobby_search(search_text, hobby_obj_list, flage=""): global return_list, origin list_of_key = search_text.split(" ") for hobby_obj in hobby_obj_list: if flage: query = hobby_obj.states(statename).filter(city=flage) else: query1 = list(hobby_obj.statename.all().values("city")) queryr1 = [d['city'] for d in query1] #print(queryr1) query = states.objectss.filter( city__in=queryr1, location__distance_lt=(origin, Distance( miles=20000))).order_by_distance() if len(list_of_key) == 1 or flage: for states_obj in query: temp = {} temp["title"] = hobby_obj.name + " in " + states_obj.city temp["url"] = "/logan/?q=" + temp["title"] return_list.append(temp) else: for hobby_obj in hobby_obj_list: states_obj_list = search_in_waston(list_of_key, hobby_obj.statename) #print(states_obj_list) if states_obj_list: for states_obj in states_obj_list: temp = {} temp[ "title"] = hobby_obj.name + " in " + states_obj.city temp["url"] = "/logan/?q=" + temp["title"] return_list.append(temp) else: place_search(hobby_obj.name + "in", search_text) return HttpResponse(JsonResponse({"places": return_list}))
def test_should_not_be_able_to_give_multiple_points(self): assert_raises(NotImplementedError, lambda: Distance(1, 2, 3, 4))
def test_should_not_be_able_to_give_multiple_points(self): with self.assertRaises(NotImplementedError): Distance(1, 2, 3, 4)
mapValues = list(repo['biel_otis.BostonZoning'].find()) correlations = list(repo['biel_otis.ObesityPropertyCorrelation'].find()) total_propVal = 0 count = 0 for x in propertyValues: total_propVal += float(x['AV_TOTAL']) count += 1 if count != 0: retDict["AveragePropVal"] = total_propVal / count else: retDict["AveragePropVal"] = 0 obeseAgg = [('*', 1) for x in obesityValues if Distance((float(x["geolocation"]["latitude"]), float(x["geolocation"]["longitude"])), (userLat, userLng)).miles < 1.0] total = aggregate(obeseAgg, sum) if (total != []): retDict["TotalObese"] = total[0][1] for f in mapValues[0]: if (f == '_id'): continue else: if (f == "South Boston" or f == "South Boston Neighborhood"): mapValues[0][f]['coordinates'][0][0] = [(x,y) for (y,x) in mapValues[0][f]['coordinates'][0][0]] else: mapValues[0][f]['coordinates'][0] = [(x,y) for (y,x) in mapValues[0][f]['coordinates'][0]] p = Point(userLat, userLng)
def get_geocode(self, *options): qs = self.filter( location__distance_lt=(tuple(options), Distance(miles=500))).order_by_distance() return qs
def execute(trial=False): startTime = datetime.datetime.now() # Set up the database connection. client = dml.pymongo.MongoClient() repo = client['biel_otis'] repo.authenticate('biel_otis', 'biel_otis') obesityValues = list(repo['biel_otis.ObesityData'].find()) if (trial == True): obesityValues = obesityValues[0:100] else: sys.stdout.flush() mapValues = list(repo['biel_otis.BostonZoning'].find()) obesityValues = [x for x in obesityValues if x['cityname'] == 'Boston'] obesityLoc = project( obesityValues, lambda x: (float(x['geolocation']['latitude']), float(x['geolocation']['longitude']))) avg_dist = 9999999 num_means = 1 dist_sum = 0 dists = [] lats = [x for (x, y) in obesityLoc] longs = [y for (x, y) in obesityLoc] means = [] while (avg_dist >= 0.5): dist_sum = 0 means = k_means(obesityLoc, n_clusters=num_means)[0] pds = [(p, Distance(m, p).miles) for (m, p) in product(means, obesityLoc)] pd = aggregate(pds, min) for x in pd: dist_sum += x[1] avg_dist = dist_sum / len(pd) num_means += 1 correctedMeans = [] means = means.tolist() inputs = {} inputs['means'] = means adjustedMeans = [Point(m) for m in means] for m in adjustedMeans: flag = False for f in mapValues[0]: if (f == '_id'): continue else: if (f == "South Boston" or f == "South Boston Neighborhood"): mapValues[0][f]['coordinates'][0][0] = [ (x, y) for (y, x) in mapValues[0][f]['coordinates'][0][0] ] else: mapValues[0][f]['coordinates'][0] = [ (x, y) for (y, x) in mapValues[0][f]['coordinates'][0] ] poly = shape(mapValues[0][f]) if poly.contains(m): flag = True break correctedMeans.append((str(m), flag)) goodMeans = [x[0] for x in correctedMeans if x[1] == True] badMeans = [x[0] for x in correctedMeans if x[1] == False] tempMeans = [] for x in badMeans: minDist = 9999999 minPoint = None arr = str(x).replace("(", "").replace(")", "").split(" ") coord = (float(arr[1]), float(arr[2])) for f in mapValues[0]: if (f == '_id'): continue else: if (f == "South Boston" or f == "South Boston Neighborhood"): for p in mapValues[0][f]['coordinates'][0][0]: dist = Distance(coord, p).miles if dist < minDist: minDist = dist minPoint = p else: for p in mapValues[0][f]['coordinates'][0]: dist = Distance(coord, p).miles if dist < minDist: minDist = dist minPoint = p tempMeans.append(minPoint) finalMeans = [] for x in tempMeans: finalMeans.append(x) for x in goodMeans: arr = x.replace("(", "").replace(")", "").split(" ") finalMeans.append((float(arr[1]), float(arr[2]))) inputs = {} inputs['optimalMarketLocation'] = finalMeans repo.dropCollection("OptimalHealthMarkets") repo.createCollection("OptimalHealthMarkets") repo['biel_otis.OptimalHealthMarkets'].insert_many([inputs]) repo['biel_otis.OptimalHealthMarkets'].metadata({'complete': True}) print(repo['biel_otis.OptimalHealthMarkets'].metadata()) repo.logout() endTime = datetime.datetime.now() return {"start": startTime, "end": endTime}
def test_should_not_be_able_to_instantiate(self): with self.assertRaises(TypeError): Distance((0, 0), (0, 180))
obesityValues = list(repo['biel_otis.UserObesityData'].find()) mapValues = list(repo['biel_otis.BostonZoning'].find()) obesityLocs = [(x['lat'], x['lng']) for x in obesityValues] avg_dist = 9999999 num_means = 1 dist_sum = 0 dists = [] means = [] while (avg_dist >= 0.5): dist_sum = 0 means = k_means(obesityLocs, n_clusters=num_means)[0] pds = [(p, Distance(m, p).miles) for (m, p) in product(means, obesityLocs)] pd = aggregate(pds, min) for x in pd: dist_sum += x[1] avg_dist = dist_sum / len(pd) num_means += 1 correctedMeans = [] means = means.tolist() inputs = {} inputs['means'] = means adjustedMeans = [Point(m) for m in means] for m in adjustedMeans: flag = False for f in mapValues[0]: if (f == '_id'):
def setUp(self): self.address = "Sunnersta" #static address to be found self.address2 = "Mackenzie" #static address for DataBC only self.userlocation = (59.8585107, 17.6368508) self.addrNone = "abcdefghijklmnopqrstuvwxyz zyxwvutsrqponmlkjihgfedcba" #non-existing address self.scheme = "https" self.plainscheme = "http" self.geolocators = [] #set up for Google self.geolocator1 = GoogleV3() self.googleurl = "https://maps.googleapis.com/maps/api/geocode/json" self.googledomain = "maps.googleapis.com" self.geolocators.append(self.geolocator1) #set up for ArcGIS self.geolocator2auth = ArcGIS("asailona", "uppsala00", "asailona.maps.arcgis.com") self.geolocator2 = ArcGIS() self.arcgisurl = "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find" self.arcgisgenerate = "https://www.arcgis.com/sharing/generateToken?username=asailona&password=uppsala00&expiration=3600&f=json&referer=asailona.maps.arcgis.com" self.geolocators.append(self.geolocator2auth) self.geolocators.append(self.geolocator2) #set up for Bing self.geolocator3auth = Bing( "AjIo4Ums4724tF5U5V7t91SHwwvjm8GP8wf0b3HZmVJWVQLlGJtSwv04IlwJ6971") self.bingapikey = "AjIo4Ums4724tF5U5V7t91SHwwvjm8GP8wf0b3HZmVJWVQLlGJtSwv04IlwJ6971" self.bingurlapi = "https://dev.virtualearth.net/REST/v1/Locations" self.geolocators.append(self.geolocator3auth) #set up for Data BC self.geolocator4 = DataBC() self.databcurlapi = "https://apps.gov.bc.ca/pub/geocoder/addresses.geojson" self.geolocators.append(self.geolocator4) #set up for geocodeFarm self.geolocator5 = GeocodeFarm() self.geourlapi = "https://www.geocode.farm/v3/json/forward/" self.geolocators.append(self.geolocator5) #set up for GeoNames self.geolocator6 = GeoNames(None, "asailona") self.gnameapi = "http://api.geonames.org/searchJSON" self.geolocators.append(self.geolocator6) #set up for MapZen self.geolocator7 = Mapzen("mapzen-yJXCFyc") self.mapzenapikey = "mapzen-yJXCFyc" self.mapzenapi = "https://search.mapzen.com/v1/search" self.geolocators.append(self.geolocator7) #set up for OpenCage self.geolocator8 = OpenCage("1aea82c9f55149dc1acc6ae04be7747c") self.openapikey = "1aea82c9f55149dc1acc6ae04be7747c" self.opendomain = "api.opencagedata.com" self.openapi = "https://api.opencagedata.com/geocode/v1/json" self.geolocators.append(self.geolocator8) #set up for Open Street Map self.geolocator9 = Nominatim() self.osmdomain = "nominatim.openstreetmap.org" self.osmapi = "https://nominatim.openstreetmap.org/search" self.geolocators.append(self.geolocator9) #set up for Photon self.geolocator10 = Photon() self.photondomain = "photon.komoot.de" self.photonapi = "https://photon.komoot.de/api" self.geolocators.append(self.geolocator10) #set up for vincenty distance test cases self.myLocation = Point(59.849904, 17.621000) self.northPole = Point(90.0, 0.0) self.southPole = Point(-90.0, 0.0) self.antiPodal1 = Point(0.0, 0.0) self.antiPodal2 = Point(0.5, 179.7) self.earthCircunference = Distance(2 * math.pi * EARTH_RADIUS)