def _calculate_area_size(self): half_lat = (self.north_lat - self.south_lat) / 2 half_lng = (self.west_lng - self.east_lng) / 2 self.midpoint = { "lat": self.south_lat + half_lat, "lng": self.east_lng + half_lng } self.lat_km = haversine(self.midpoint["lng"], self.north_lat, self.midpoint["lng"], self.south_lat) self.lng_km = haversine(self.west_lng, self.midpoint["lat"], self.east_lng, self.midpoint["lat"]) return self.lat_km, self.lng_km
def prepare_system(server, arquivo): msg, client = server.recvfrom(1024) j_msg = json.loads(msg.decode()) server.sendto(str(j_msg['id']).encode(), client) print('Mensagem {} recebida'.format(str(j_msg['id']))) if j_msg['type'] == 'D': json.dump({ 'fuel': j_msg['fuel'], 'price': j_msg['price'], 'coord': j_msg['coord'] }, arquivo) arquivo.write('\n') arquivo.flush() else: arquivo.seek(0) data = arquivo.readlines() # json.load(arquivo) menor = sys.maxsize for i in range(len(data)): station = json.loads(data[i]) if util.haversine(station['coord'], j_msg['center'], j_msg['radius']) \ and station['fuel'] == j_msg['fuel'] \ and station['price'] < menor: menor = station['price'] server.sendto(str(menor).encode(), client)
def follow_tour(points, start_time, speed): last_station = None last_point = None distance = 0 duration = datetime.timedelta() for point in points: if last_point: distance += haversine(last_point.latitude, last_point.longitude, point.latitude, point.longitude) duration = datetime.timedelta(seconds=int(distance / speed * 60 * 60)) last_point = point nearest_station = dwd.get_nearest_station(point.latitude, point.longitude) if not last_station == nearest_station: last_station = nearest_station time = start_time + duration fc_time = min((abs((t-time).total_seconds()), t) for t in nearest_station.forecast)[1] fc = nearest_station.forecast[fc_time] print('{0:.0f}km\t{1}\t{2} ({3:.2f}km)'.format( distance, duration, last_station, last_station.distance(point.latitude, point.longitude)) ) print('\t{0}'.format(fc_time)) print('\tWind\t\t{0}m/s ({1}°)'.format(fc['FF'], fc['DD'])) print('\tTemperature\t{0:.1f}°C'.format(float(fc['TTT']) - 272.15)) print('\tCloud cover\t{0}%'.format(fc['N'])) print('\tPrecipitation\t{0}l/m²'.format(fc['RR1c']))
def __str__(self): if self.match: return "Match: %s <-> %s (score: %0.2f, d: %0.2fm)" % ( self.entity.name(), self.match.name(), self.score, util.haversine(self.entity.point(), self.match.point())) else: return "Match: %s <-> no result" % (self.entity.name())
def make_submission(): DATA_DIR = '../data' t0 = time.time() for filename in [ 'train_new_A_V5.csv', 'train_new_B_V5.csv', 'train_new_C_V5.csv' ]: print('reading training data from %s ...' % filename) df = pd.read_csv(os.path.join(DATA_DIR, filename)) df = df[df['len'] != -1] df = df[df['hour'] != -1] d1 = haversine(df[['xs', 'ys']].values, df[['xe', 'ye']].values) y = np.log(df['len'] * 15 + 1) df.drop(['year', 'CALL_TYPE', 'len', 'xs', 'ys', 'xe', 'ye'], axis=1, inplace=True) # if (filename == 'train_new_A_V5.csv'): # df.drop(['ORIGIN_STAND'], axis=1, inplace=True) # if (filename == 'train_new_B_V5.csv'): # df.drop(['ORIGIN_CALL'], axis=1, inplace=True) # if (filename == 'train_new_C_V5.csv'): # df.drop(['ORIGIN_STAND', 'ORIGIN_CALL'], axis=1, inplace=True) X = np.array(df, dtype=np.float) th1 = np.percentile(d1, [99.9]) X = X[(d1 < th1), :] y = y[(d1 < th1)] print('training a random forest regressor ...') clf = RandomForestRegressor(n_estimators=400, n_jobs=-1, random_state=21) clf.fit(X, y) print('predicting test data ...') df = pd.read_csv( os.path.join(DATA_DIR, filename.replace('train', 'test'))) ids = df['TRIP_ID'] # if (filename == 'train_new_A_V5.csv'): # df.drop(['ORIGIN_STAND'], axis=1, inplace=True) # if (filename == 'train_new_B_V5.csv'): # df.drop(['ORIGIN_CALL'], axis=1, inplace=True) # if (filename == 'train_new_C_V5.csv'): # df.drop(['ORIGIN_STAND', 'ORIGIN_CALL'], axis=1, inplace=True) df = df.drop(['CALL_TYPE', 'TRIP_ID', 'year'], axis=1) X_tst = np.array(df, dtype=np.float) y_pred = clf.predict(X_tst) # create submission file submission = pd.DataFrame(ids, columns=['TRIP_ID']) filename = filename.replace('train', 'my_submission') submission['TRAVEL_TIME'] = np.exp(y_pred) submission.to_csv(filename, index=False) print('Done in %.1f sec.' % (time.time() - t0))
def nearbyPoints(mainPoint, points, dist): nearPointNum = 0 for point in points: distBetween = haversine(mainPoint, point) if distBetween <= dist: nearPointNum += 1 if nearPointNum >= 2: return True else: return False
def __init__(self, data, reference_point): self.name = data["fields"]["name"] self.lat = data["fields"]["lat"] self.lon = data["fields"]["lon"] self.distance = haversine( reference_point[0], reference_point[1], self.lon, self.lat )
def len_map(self, ): len_np = np.zeros((30, 30), dtype=np.float) for i in range(30): for j in range(30): len_np[i, j] = haversine(self.np_df[i, 0], self.np_df[i, 1], self.np_df[j, 0], self.np_df[j, 1]) #len1 = self.haversine(120.70051409,36.38276987, 120.69986731, 36.37079794) #print(len_np) self.len_map = len_np
def __str__(self): if self.match: return "Match: %s <-> %s (score: %0.2f, d: %0.2fm)"%( self.entity.name(), self.match.name(), self.score, util.haversine(self.entity.point(), self.match.point()) ) else: return "Match: %s <-> no result"%( self.entity.name() )
def getImage(imagesData, lon2, lat2, radius): imageList = [] for image_name, image_data in imagesData.items(): lon1, lat1, alt1 = map(float, image_data) distance = haversine(lon1, lat1, lon2, lat2) if distance < radius: imageList.append(image_name) return imageList
def _calculate_distance_ratio(self): # Latitude is a fairly consistent ~111km per parallel, whereas # longitude distance changes with latitude. This approximates # the lng/lat ratio at the closest parallel and meridian lines. # In case a whole number is passed in, we offset it by 0.0001 so we # can get a proper ceil and floor. # Yes, someone could pass in 73.0009 and ruin everything, but they are # bad people. Okay, maybe they're not bad people, I just don't want to # check for this right now north_parallel = math.ceil(self.north_lat + 0.0001) south_parallel = math.floor(self.north_lat + 0.0001) west_meridian = math.ceil(self.east_lng + 0.0001) east_meridian = math.floor(self.east_lng + 0.0001) lat_distance = haversine(east_meridian, north_parallel, east_meridian, south_parallel) lng_distance = haversine(east_meridian, north_parallel, west_meridian, north_parallel) self.distance_ratio = lng_distance / lat_distance return self.distance_ratio
def simple_adjlist(graph, node_coords): """ """ adjlist = defaultdict(list) needed_coords = {} valid_nodes = (n for n in graph if n in node_coords) for vert in valid_nodes: needed_coords[vert] = node_coords[vert] node_ll = node_coords[vert] valid_arcs = (e for e in graph[vert] if e in node_coords) for arc in valid_arcs: needed_coords[str(arc)] = node_coords[arc] e_tuple = str(arc), haversine(node_ll, node_coords[arc]) adjlist[str(vert)].append(e_tuple) return dict(adjlist), needed_coords
def simple_adjlist(graph, node_coords): """ """ adjlist = defaultdict(list) needed_coords = {} valid_nodes = (n for n in graph if n in node_coords) for vert in valid_nodes: needed_coords[vert] = node_coords[vert] node_ll = node_coords[vert] valid_arcs = (e for e in graph[vert] if e in node_coords) for arc in valid_arcs: needed_coords[str(arc)] = node_coords[arc] print(node_coords[arc], type(node_ll)) e_tuple = str(arc), haversine(node_ll[0], node_ll[1], node_coords[arc][0], node_coords[arc][1]) adjlist[str(vert)].append(e_tuple) return dict(adjlist), needed_coords
def parse(self): # returns ne, sw dictionary: {"ne": (x,y), "sw": (x,y)} prev_point = None distance = 0 for track in self.gpx.tracks: for segment in track.segments: for point in segment.points: self._set_bounds(point) if prev_point: distance += haversine( prev_point.longitude, prev_point.latitude, point.longitude, point.latitude) self.distance.append(distance) else: self.distance.append(0) self.elevation.append(point.elevation) prev_point = point
def get_valid_pharmacies(): medicine_name = request.args.get('medicine_name') latitude = request.args.get('latitude') longitude = request.args.get('longitude') radius = request.args.get('radius') if medicine_name is None: raise InvalidUsage('Invalid medicine name provided', status_code=400) if latitude is None: raise InvalidUsage('Invalid latitude provided', status_code=400) if longitude is None: raise InvalidUsage('Invalid longitude provided', status_code=400) if radius is None: radius = 10 else: radius = float(radius) inventory = Inventory.query.filter(Inventory.name.like('%{}%'.format(medicine_name))).all() locations = [] for inv in inventory: pharm = Pharmacy.query.filter(Pharmacy.id == inv.pharm_id).first() dist = haversine(pharm.latitude, pharm.longitude, latitude, longitude) if dist < radius: locations.append({'name': pharm.name, 'approx_dist': dist, 'latitude': pharm.latitude, 'longitude': pharm.longitude, 'address': pharm.address, 'medicine_name': inv.name, 'price': inv.price}) return jsonify(num_locations=len(locations), locations=locations)
def compute_distance(df, address, categories=None, walking_time=None): ''' Compute the distance between user's location and all the facilities in our dataset Inputs: df: the full dataframe address:(str) address of user categories: (list of strings) the list of attempted service types walking_time: (int) the desired maximum walking time Returns: the new data frame ''' user_lon, user_lat = util.get_user_location(address) df = util.select_categories(df, categories) df = df[df["longitude"].notnull() & df["latitude"].notnull()] df['distance'] = df.apply(lambda x: util.haversine(x['longitude'],\ x['latitude'], user_lon, user_lat), axis=1) if walking_time is not None: df['walking_time'] = df.apply(lambda x: util.compute_walking_time(\ x['distance']), axis=1) filter_cond = df['walking_time'] <= walking_time df = df[filter_cond] return df
def score_distance(e1, e2): """Score on the inverse distance.""" d = util.haversine(e1.point(), e2.point()) return 1 / (d + 1.0)
def score_distance(e1, e2): """Score on the inverse distance.""" d = util.haversine(e1.point(), e2.point()) return 1/(d+1.0)
def distance(self, lat, lon): return haversine(lat, lon, self.lat, self.lon)