def api_search_store(): category_list = ["카페", "편의점/마트", "음식점", "디저트", "병원/약국", "의류"] list = [ ["비알코올 음료점업"], [ "음ㆍ식료품 위주 종합 소매업", "식료품 소매업", "서적 및 문구용품 소매업", "신선 식품 및 단순 가공 식품 도매업" ], ["한식 음식점업", "외국식 음식점업", "기타 간이 음식점업", "주점업"], ["떡, 빵 및 과자류 제조업"], ["수의업", "병원", "의약품, 의료%", "의원"], ["의복 소매업"], ] q = request.form.get('q', '') c = request.form.getlist('c[]') lng = request.form.get('lng', 0) lat = request.form.get('lat', 0) qArr = q.split(' ') cArr = [] if len(c) > 0 and c[0] == "전체": cArr.append("%%") elif len(c) == 0: cArr.append("") else: for i in range(0, len(c)): try: type = category_list.index(c[i]) except ValueError: continue for j in range(0, len(list[type])): cArr.append(list[type][j]) for i in range(0, len(qArr)): qArr[i] = "%" + qArr[i] + "%" store = Store.query \ .filter(and_(Store.lng != 0, Store.lat != 0)) \ .filter((func.acos( func.sin(func.radians(lat)) * func.sin(func.radians(Store.lat)) + func.cos(func.radians(lat)) * func.cos( func.radians(Store.lat)) * func.cos(func.radians(Store.lng) - (func.radians(lng)))) * 6371) < 0.5) \ .order_by(asc((func.acos( func.sin(func.radians(lat)) * func.sin(func.radians(Store.lat)) + func.cos(func.radians(lat)) * func.cos( func.radians(Store.lat)) * func.cos(func.radians(Store.lng) - (func.radians(lng)))) * 6371))) \ .filter(or_(or_(*[Store.name.like(name) for name in qArr]), or_(*[Store.category.like(name) for name in qArr]))) \ .filter(or_(*[Store.category.like(name) for name in cArr])) \ .limit(100) result = { "code": 200, "message": "success", "stores": StoreSchema(many=True).dump(store) } return dump(result)
def great_circle_distance(cls, p, l): radius = 6371 # Radius of earth p1 = cls.latitude l1 = cls.longitude print(p1, l1) p2 = p l2 = l dl = func.radians(func.abs(l1 - l2)) p1 = func.radians(p1) p2 = func.radians(p2) l1 = func.radians(l1) l2 = func.radians(l2) ds = func.acos((func.sin(p1) * func.sin(p2)) + (func.cos(p1) * func.cos(p2) * func.cos(dl))) dist = radius * ds return dist
def get_nearme_orders(store_id): """ Retrieve all the existing orders as a user or as a store, steps to proceed are: 1. Check user's role is "store". 2. Retrieve and check the store with the given id. 3. Search all near orders using the store's location. 4. Returns every order found. """ # Step 1 user = _request_ctx_stack.top.current_user if user['app_metadata']['user_role'] != 'store': abort(401) # Step 2 store = session.query(Store).filter(Store.id == store_id).first() if not store: abort(404) # Step 3 radius = store.rad or DEFAULT_ORDER_RADIUS distance = KM_UNIT *\ func.acos(func.cos(func.radians(store.lat)) *\ func.cos(func.radians(Order.lat)) *\ func.cos(func.radians(Order.lon) -\ func.radians(store.lon)) +\ func.sin(func.radians(store.lat)) *\ func.sin(func.radians(Order.lat))) orders = session.query(Order).filter(and_(distance <= radius, Order.status == ORDER_MADE)).order_by(desc(Order.created_at)).all() # Step 4 return jsonify(json_list=[order.serialize for order in orders]), 200
def is_nearby(self, latitude, longitude, radius): sin_rad_lat = math.sin(math.pi * latitude / 180) cos_rad_lat = math.cos(math.pi * latitude / 180) rad_lng = math.pi * longitude / 180 return func.acos(self.cos_rad_lat * cos_rad_lat * func.cos(self.rad_lng - rad_lng) + self.sin_rad_lat * sin_rad_lat) * 6371 <= radius
def distance(self, center_latitude, center_longitude): return ( GeoLocation.EARTH_RADIUS * func.acos( func.cos(func.radians(center_latitude)) * func.cos(func.radians(self.latitude)) * func.cos(func.radians(self.longitude) - func.radians(center_longitude)) + func.sin(func.radians(center_latitude)) * func.sin(func.radians(self.latitude))) )
def api_store(): lng = request.form.get('lng', 0) lat = request.form.get('lat', 0) store = Store.query \ .filter(and_(Store.lng != 0, Store.lat != 0)) \ .filter((func.acos( func.sin(func.radians(lat)) * func.sin(func.radians(Store.lat)) + func.cos(func.radians(lat)) * func.cos( func.radians(Store.lat)) * func.cos(func.radians(Store.lng) - (func.radians(lng)))) * 6371) < 0.5) \ .order_by(asc((func.acos( func.sin(func.radians(lat)) * func.sin(func.radians(Store.lat)) + func.cos(func.radians(lat)) * func.cos( func.radians(Store.lat)) * func.cos(func.radians(Store.lng) - (func.radians(lng)))) * 6371))) \ .limit(100) result = { "code": 200, "message": "success", "stores": StoreSchema(many=True).dump(store) } return dump(result)
def location_subquery(self, latitude, longitude, radius, locable_only=False, fields=['id']): from math import degrees, radians, cos R = 6371 # earth's mean radius, km latitude = float(latitude) longitude = float(longitude) radius = float(radius) # first-cut bounding box (in degrees) maxLat = latitude + degrees(radius / R) minLat = latitude - degrees(radius / R) # compensate for degrees longitude # getting smaller with increasing latitude maxLon = longitude + degrees(radius / R / cos(radians(latitude))) minLon = longitude - degrees(radius / R / cos(radians(latitude))) filters = [self.latitude.between(minLat, maxLat), self.longitude.between(minLon, maxLon)] if locable_only: filters.append(self.locable == True) rlat = radians(latitude) rlng = radians(longitude) distance = ( func.acos( func.sin(rlat) * func.sin(func.radians(column('latitude'))) + func.cos(rlat) * func.cos(func.radians(column('latitude'))) * func.cos(func.radians(column('longitude')) - rlng) ) * R ).label('distance') subquery = db.session.query( self.id, self.latitude, self.longitude, self.method, self.city, self.country, self.country_code, self.modified, distance) \ .filter(*filters) \ .subquery('FirstCut') sub = select(map(column, fields)) \ .select_from(subquery) \ .where(distance <= radius) return sub
def location_subquery(self, latitude, longitude, radius, locable_only=False, fields=['id']): from math import degrees, radians, cos R = 6371 # earth's mean radius, km latitude = float(latitude) longitude = float(longitude) radius = float(radius) # first-cut bounding box (in degrees) maxLat = latitude + degrees(radius / R) minLat = latitude - degrees(radius / R) # compensate for degrees longitude # getting smaller with increasing latitude maxLon = longitude + degrees(radius / R / cos(radians(latitude))) minLon = longitude - degrees(radius / R / cos(radians(latitude))) filters = [ self.latitude.between(minLat, maxLat), self.longitude.between(minLon, maxLon) ] if locable_only: filters.append(self.locable == True) rlat = radians(latitude) rlng = radians(longitude) distance = (func.acos( func.sin(rlat) * func.sin(func.radians(column('latitude'))) + func.cos(rlat) * func.cos(func.radians(column('latitude'))) * func.cos(func.radians(column('longitude')) - rlng)) * R).label('distance') subquery = db.session.query( self.id, self.latitude, self.longitude, self.method, self.city, self.country, self.country_code, self.modified, distance) \ .filter(*filters) \ .subquery('FirstCut') sub = select(map(column, fields)) \ .select_from(subquery) \ .where(distance <= radius) return sub
def map_vehicles(session, a, b): """Computes association between vehicle annotations.""" mapping = {} for vehicle in a.vehicles: overlap_score = overlap(vehicle, database.Vehicle) if len(b.vehicles) == 0: mapping[vehicle.id] = None continue selected = session.query(database.Vehicle) \ .filter(database.Vehicle.id.in_([elt.id for elt in b.vehicles])) \ .filter(overlap_score > 0.7) \ .filter(database.Vehicle.type == vehicle.type) \ .filter(func.acos(func.cos((database.Vehicle.theta - vehicle.theta)/180*math.pi)) < math.radians(10)) \ .order_by(desc(overlap_score)) \ .first() mapping[vehicle.id] = None if not selected else selected.id return mapping
def convert_vehicle(nyc3dcars_session, labeler_vehicle): """Converts the vehicle from Labeler format to NYC3DCars format.""" photo, lat, lon, alt = nyc3dcars_session.query( Photo, func.ST_Y(Photo.lla), func.ST_X(Photo.lla), func.ST_Z(Photo.lla)) \ .filter_by(id=labeler_vehicle.revision.annotation.pid) \ .options(joinedload('dataset')) \ .one() left = labeler_vehicle.x1 right = labeler_vehicle.x2 top = labeler_vehicle.y1 bottom = labeler_vehicle.y2 camera_lla = numpy.array([[lat], [lon], [alt]]) camera_enu = pygeo.LLAToENU(camera_lla.T).reshape((3, 3)) dataset_correction = numpy.array([ [photo.dataset.t1], [photo.dataset.t2], [photo.dataset.t3], ]) camera_rotation = numpy.array([ [photo.r11, photo.r12, photo.r13], [photo.r21, photo.r22, photo.r23], [photo.r31, photo.r32, photo.r33], ]) camera_up = camera_enu.T.dot( camera_rotation.T.dot(numpy.array([[0], [1], [0]]))) offset = numpy.array([[-labeler_vehicle.x], [-labeler_vehicle.z], [0]]) camera_offset = camera_up * \ labeler_vehicle.revision.cameraheight / camera_up[2] total_offset = offset - camera_offset ecef_camera = pygeo.LLAToECEF(camera_lla.T).T ecef_camera += dataset_correction ecef_total_offset = camera_enu.dot(total_offset) vehicle_ecef = ecef_camera + ecef_total_offset vehicle_type = labeler_vehicle.type model = nyc3dcars_session.query(VehicleType) \ .filter_by(label=vehicle_type) \ .one() vehicle_lla = pygeo.ECEFToLLA(vehicle_ecef.T).T theta = math.radians(-labeler_vehicle.theta) mlength = model.length mwidth = model.width car_a = -math.sin(theta) * 0.3048 * \ mlength / 2 + math.cos(theta) * 0.3048 * mwidth / 2 car_b = math.cos(theta) * 0.3048 * mlength / \ 2 + math.sin(theta) * 0.3048 * mwidth / 2 car_c = math.sin(theta) * 0.3048 * mlength / \ 2 + math.cos(theta) * 0.3048 * mwidth / 2 car_d = -math.cos(theta) * 0.3048 * \ mlength / 2 + math.sin(theta) * 0.3048 * mwidth / 2 car_corner_offset1 = camera_enu.dot(numpy.array([[car_a], [car_b], [0]])) car_corner_offset2 = camera_enu.dot(numpy.array([[car_c], [car_d], [0]])) car_corner1 = pygeo.ECEFToLLA( (vehicle_ecef + car_corner_offset1).T).T.flatten() car_corner2 = pygeo.ECEFToLLA( (vehicle_ecef - car_corner_offset1).T).T.flatten() car_corner3 = pygeo.ECEFToLLA( (vehicle_ecef + car_corner_offset2).T).T.flatten() car_corner4 = pygeo.ECEFToLLA( (vehicle_ecef - car_corner_offset2).T).T.flatten() pg_corner1 = func.ST_SetSRID( func.ST_MakePoint(car_corner1[1], car_corner1[0], car_corner1[2]), 4326) pg_corner2 = func.ST_SetSRID( func.ST_MakePoint(car_corner2[1], car_corner2[0], car_corner2[2]), 4326) pg_corner3 = func.ST_SetSRID( func.ST_MakePoint(car_corner3[1], car_corner3[0], car_corner3[2]), 4326) pg_corner4 = func.ST_SetSRID( func.ST_MakePoint(car_corner4[1], car_corner4[0], car_corner4[2]), 4326) collection = func.ST_Collect(pg_corner1, pg_corner2) collection = func.ST_Collect(collection, pg_corner3) collection = func.ST_Collect(collection, pg_corner4) car_polygon = func.ST_ConvexHull(collection) camera_ecef = pygeo.LLAToECEF(camera_lla.T).T vehicle_ecef = pygeo.LLAToECEF(vehicle_lla.T).T diff = camera_ecef - vehicle_ecef normalized = diff / numpy.linalg.norm(diff) vehicle_enu = pygeo.LLAToENU(vehicle_lla.T).reshape((3, 3)) rotated = vehicle_enu.T.dot(normalized) theta = func.acos(rotated[2][0]) view_phi = func.atan2(rotated[1][0], rotated[0][0]) vehicle_phi = math.radians(-labeler_vehicle.theta) phi = vehicle_phi - view_phi out = nyc3dcars_session.query( theta.label('theta'), phi.label('phi')) \ .one() out.phi = ((out.phi + math.pi) % (2 * math.pi)) - math.pi out.theta = ((out.theta + math.pi) % (2 * math.pi)) - math.pi view_phi = out.phi view_theta = out.theta left = labeler_vehicle.x1 right = labeler_vehicle.x2 top = labeler_vehicle.y1 bottom = labeler_vehicle.y2 for bbox_session in labeler_vehicle.bbox_sessions: if not bbox_session.user.trust: continue print(( bbox_session.user.username, labeler_vehicle.revision.annotation.pid )) left = bbox_session.x1 right = bbox_session.x2 top = bbox_session.y1 bottom = bbox_session.y2 break occlusions = [ occlusion.category for occlusion in labeler_vehicle.occlusionrankings if occlusion.occlusion_session.user.trust and occlusion.category != 5 ] if len(occlusions) == 0: return pg_lla = func.ST_SetSRID( func.ST_MakePoint(vehicle_lla[1][0], vehicle_lla[0][0], vehicle_lla[2][0]), 4326) nyc3dcars_vehicle = Vehicle( id=labeler_vehicle.id, pid=photo.id, x=labeler_vehicle.x, z=labeler_vehicle.z, theta=labeler_vehicle.theta, x1=left, x2=right, y1=top, y2=bottom, type_id=model.id, occlusion=min(occlusions), geom=car_polygon, lla=pg_lla, view_theta=view_theta, view_phi=view_phi, cropped=labeler_vehicle.cropped, ) nyc3dcars_session.add(nyc3dcars_vehicle)
def calcSQLDist(ra1, dec1, ra2, dec2): from sqlalchemy import func from math import pi return func.acos(func.sin(dec1*pi/180.0)*func.sin(dec2*pi/180.0) + func.cos(dec1*pi/180.0)*func.cos(dec2*pi/180.0)*func.cos((ra1-ra2)*pi/180.0))
def convert_vehicle(nyc3dcars_session, labeler_vehicle): """Converts the vehicle from Labeler format to NYC3DCars format.""" photo, lat, lon, alt = nyc3dcars_session.query( Photo, func.ST_Y(Photo.lla), func.ST_X(Photo.lla), func.ST_Z(Photo.lla)) \ .filter_by(id=labeler_vehicle.revision.annotation.pid) \ .options(joinedload('dataset')) \ .one() left = labeler_vehicle.x1 right = labeler_vehicle.x2 top = labeler_vehicle.y1 bottom = labeler_vehicle.y2 camera_lla = numpy.array([[lat], [lon], [alt]]) camera_enu = pygeo.LLAToENU(camera_lla.T).reshape((3, 3)) dataset_correction = numpy.array([ [photo.dataset.t1], [photo.dataset.t2], [photo.dataset.t3], ]) camera_rotation = numpy.array([ [photo.r11, photo.r12, photo.r13], [photo.r21, photo.r22, photo.r23], [photo.r31, photo.r32, photo.r33], ]) camera_up = camera_enu.T.dot( camera_rotation.T.dot(numpy.array([[0], [1], [0]]))) offset = numpy.array([[-labeler_vehicle.x], [-labeler_vehicle.z], [0]]) camera_offset = camera_up * \ labeler_vehicle.revision.cameraheight / camera_up[2] total_offset = offset - camera_offset ecef_camera = pygeo.LLAToECEF(camera_lla.T).T ecef_camera += dataset_correction ecef_total_offset = camera_enu.dot(total_offset) vehicle_ecef = ecef_camera + ecef_total_offset vehicle_type = labeler_vehicle.type model = nyc3dcars_session.query(VehicleType) \ .filter_by(label=vehicle_type) \ .one() vehicle_lla = pygeo.ECEFToLLA(vehicle_ecef.T).T theta = math.radians(-labeler_vehicle.theta) mlength = model.length mwidth = model.width car_a = -math.sin(theta) * 0.3048 * \ mlength / 2 + math.cos(theta) * 0.3048 * mwidth / 2 car_b = math.cos(theta) * 0.3048 * mlength / \ 2 + math.sin(theta) * 0.3048 * mwidth / 2 car_c = math.sin(theta) * 0.3048 * mlength / \ 2 + math.cos(theta) * 0.3048 * mwidth / 2 car_d = -math.cos(theta) * 0.3048 * \ mlength / 2 + math.sin(theta) * 0.3048 * mwidth / 2 car_corner_offset1 = camera_enu.dot(numpy.array([[car_a], [car_b], [0]])) car_corner_offset2 = camera_enu.dot(numpy.array([[car_c], [car_d], [0]])) car_corner1 = pygeo.ECEFToLLA( (vehicle_ecef + car_corner_offset1).T).T.flatten() car_corner2 = pygeo.ECEFToLLA( (vehicle_ecef - car_corner_offset1).T).T.flatten() car_corner3 = pygeo.ECEFToLLA( (vehicle_ecef + car_corner_offset2).T).T.flatten() car_corner4 = pygeo.ECEFToLLA( (vehicle_ecef - car_corner_offset2).T).T.flatten() pg_corner1 = func.ST_SetSRID( func.ST_MakePoint(car_corner1[1], car_corner1[0], car_corner1[2]), 4326) pg_corner2 = func.ST_SetSRID( func.ST_MakePoint(car_corner2[1], car_corner2[0], car_corner2[2]), 4326) pg_corner3 = func.ST_SetSRID( func.ST_MakePoint(car_corner3[1], car_corner3[0], car_corner3[2]), 4326) pg_corner4 = func.ST_SetSRID( func.ST_MakePoint(car_corner4[1], car_corner4[0], car_corner4[2]), 4326) collection = func.ST_Collect(pg_corner1, pg_corner2) collection = func.ST_Collect(collection, pg_corner3) collection = func.ST_Collect(collection, pg_corner4) car_polygon = func.ST_ConvexHull(collection) camera_ecef = pygeo.LLAToECEF(camera_lla.T).T vehicle_ecef = pygeo.LLAToECEF(vehicle_lla.T).T diff = camera_ecef - vehicle_ecef normalized = diff / numpy.linalg.norm(diff) vehicle_enu = pygeo.LLAToENU(vehicle_lla.T).reshape((3, 3)) rotated = vehicle_enu.T.dot(normalized) theta = func.acos(rotated[2][0]) view_phi = func.atan2(rotated[1][0], rotated[0][0]) vehicle_phi = math.radians(-labeler_vehicle.theta) phi = vehicle_phi - view_phi out = nyc3dcars_session.query( theta.label('theta'), phi.label('phi')) \ .one() out.phi = ((out.phi + math.pi) % (2 * math.pi)) - math.pi out.theta = ((out.theta + math.pi) % (2 * math.pi)) - math.pi view_phi = out.phi view_theta = out.theta left = labeler_vehicle.x1 right = labeler_vehicle.x2 top = labeler_vehicle.y1 bottom = labeler_vehicle.y2 for bbox_session in labeler_vehicle.bbox_sessions: if not bbox_session.user.trust: continue print((bbox_session.user.username, labeler_vehicle.revision.annotation.pid)) left = bbox_session.x1 right = bbox_session.x2 top = bbox_session.y1 bottom = bbox_session.y2 break occlusions = [ occlusion.category for occlusion in labeler_vehicle.occlusionrankings if occlusion.occlusion_session.user.trust and occlusion.category != 5 ] if len(occlusions) == 0: return pg_lla = func.ST_SetSRID( func.ST_MakePoint(vehicle_lla[1][0], vehicle_lla[0][0], vehicle_lla[2][0]), 4326) nyc3dcars_vehicle = Vehicle( id=labeler_vehicle.id, pid=photo.id, x=labeler_vehicle.x, z=labeler_vehicle.z, theta=labeler_vehicle.theta, x1=left, x2=right, y1=top, y2=bottom, type_id=model.id, occlusion=min(occlusions), geom=car_polygon, lla=pg_lla, view_theta=view_theta, view_phi=view_phi, cropped=labeler_vehicle.cropped, ) nyc3dcars_session.add(nyc3dcars_vehicle)