Exemple #1
0
def Fetch_Location(request):
    if request.method == 'POST':
        # serializer = OutputRecordSerializer(data=request.data)
        if (request.data.get('user_id') != ''):
            try:
                validated_data = request.data
                temp_points = Activity_Record.objects.get(
                    user_id_id=validated_data.get('user_id'))
                print(temp_points)
                g = temp_points
                buffer = GEOSGeometry.buffer(g.location, 0.0005, 4)
                print(buffer.geojson)
                # return serialize('geojson', [buffer],
                #           geometry_field='location', fields=('user_id','location'))
                response_data = {}
                response_data['type'] = 'FeatureCollection'
                response_data['features'] = []
                geo_obj = dict()
                geo_obj['type'] = 'Feature'
                geo_obj['properties'] = {}
                geo_obj['geometry'] = json.JSONDecoder().decode(buffer.geojson)
                response_data['features'].append(geo_obj)
                # response_data['buffer'] = json.JSONDecoder().decode( buffer.geojson )
                # response_data['user_id'] = validated_data.get('user_id')
            except Activity_Record.DoesNotExist:
                response_data = {}
                response_data['status'] = "User id not found"
                response_data['user_id'] = validated_data.get('user_id')

            return HttpResponse(json.dumps(response_data),
                                status=status.HTTP_201_CREATED)
Exemple #2
0
def load_kml(verbose=True):
    """ Recorre la carpeta/data/kml --> introduce en la BD los linestrings de los KML 
    https://medium.com/@kitcharoenpoolperm/geodjango-import-data-from-kml-file-de110dba1f60 """
    # Ruta al archivo que queremos introducir en la BD BikeLanes
    kml_file = os.path.abspath(
        os.path.join(os.path.dirname(__file__), 'data', 'kml',
                     'bidegorris.kml'), )
    # Reading Data by DataSource
    ds = DataSource(kml_file)
    # Writes the Well-Known Text representation of a Geometry.
    wkt_w = WKTWriter()
    # Iterating Over Layers
    for layer in ds:
        for feat in layer:
            if (feat.geom.geom_type.name.startswith('Line')):
                # Get the feature geometry.
                geom = feat.geom
                # get the feature property
                property = get_feat_property(feat)
                if (len(geom.coords) >= 2):
                    # Make a GEOSGeometry object
                    lstring = GEOSGeometry(wkt_w.write(geom.geos), srid=4326)
                    lstring.transform(3035)
                    dist = lstring.length
                    line = BikeLane.objects.create(
                        name=property['name'],
                        distance=dist,
                        lstring=lstring,
                        # ST_Buffer() --> Poligonizamos los bidegorris a una anchura de 10m
                        # https://www.usna.edu/Users/oceano/pguth/md_help/html/approx_equivalents.htm#:~:text=0.00001%C2%B0%20%3D%201.11%20m
                        poly=lstring.buffer(10, quadsegs=8))
                    logger.info(line)
Exemple #3
0
    def post(self, request, *args, **kwargs):
        print(request.POST)
        if request.POST['location'] == '':
            form = FindGymForm(request.POST)
            form.errors['location'][0] = form.errors['location'][0].replace(
                "No geometry value provided.",
                "Need your location to find nearby gyms!")
            return render(request, "gymfinder.html", {
                "form": form,
            })
        radius = int(request.POST['max_distance'])
        location = GEOSGeometry(request.POST["location"])
        location = Point(location.coords)
        area = location.buffer(radius / 40000 * 360)
        gyms_found = list(Gym.objects.all())

        for i in range(len(gyms_found)):
            dist = requests.get(
                "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
                + str(location.coords[1]) + "," + str(location.coords[0]) +
                "&destinations=" + str(gyms_found[i].location.coords[1]) +
                "," + str(gyms_found[i].location.coords[0])).json(
                )["rows"][0]['elements'][0]['distance']['text'].split(" ")[0]
            gyms_found[i] = (gyms_found[i], dist)

        gyms_found = list(
            filter(lambda gym: float(gym[-1]) < radius, gyms_found))

        context = {
            "gyms_found": len(gyms_found),
            "max_distance": radius,
            "gyms": gyms_found,
            "location": location,
        }
        return render(request, "gyms_found.html", context)
Exemple #4
0
def get_geoms():
    cntr = GEOSGeometry('SRID=3857;POINT(-13842474.0 5280123.1)')

    stand_geoms = []
    for i in range(NUM_STANDS):
        cntr.set_x(cntr.x + 150)
        g1 = cntr.buffer(75)
        g1.transform(settings.GEOMETRY_DB_SRID)
        stand_geoms.append(wkt.loads(g1.wkt))

    casc_poly = cascaded_union(stand_geoms)

    if casc_poly.type == 'MultiPolygon':
        polys = []
        for c in casc_poly:
            interiors = [
                x for x in c.interiors
                if Polygon(x).area > settings.SLIVER_THRESHOLD
            ]
            polys.append(Polygon(shell=c.exterior, holes=interiors))
    elif casc_poly.type == 'Polygon':
        interiors = [
            x for x in casc_poly.interiors
            if Polygon(x).area > settings.SLIVER_THRESHOLD
        ]
        polys = [Polygon(shell=casc_poly.exterior, holes=interiors)]

    property_geom = MultiPolygon(polys)

    return stand_geoms, property_geom
Exemple #5
0
def find_overlapping(request):
    '''This function queries ES when called via Ajax when a new geometry is created in the Location tab. If pre-existing resources are found within the perimeter of the polygon (or the buffered zone around a point/line/polygon), an alert is raised.'''
    geomString = request.GET.get('geom', '')
    geom = GEOSGeometry(geomString, srid=4326)
    mindistance = settings.METER_RADIUS
    if not mindistance:
        mindistance = 1000  # if settings.METER_RADIUS isn't set, default to 1Km
    geom.transform(3857)
    buffered_geom = geom.buffer(mindistance)
    buffered_geom.transform(4326)
    print geom, buffered_geom
    se = SearchEngineFactory().create()
    query = Query(se)
    boolfilter = Bool()
    geoshape = GeoShape(field='geometries.value',
                        type=buffered_geom.geom_type,
                        coordinates=buffered_geom.coords)
    nested = Nested(path='geometries', query=geoshape)
    boolfilter.must(nested)
    query.add_filter(boolfilter)
    results = query.search(index='entity', doc_type='')
    overlaps = []
    for hit in results['hits']['hits']:
        overlaps.append({
            'id': hit['_id'],
            'type': hit['_type'],
            'primaryname': hit['_source']['primaryname']
        })
    return JSONResponse(overlaps)
 def test_bad_variant(self):
     self.assertEqual(self.prop1.variant, self.real)
     cntr = GEOSGeometry("SRID=3857;POINT(-638474.0 980123.1)")  # not on the map, but close to SO
     g2 = cntr.buffer(75)
     g2.transform(settings.GEOMETRY_DB_SRID)
     p2 = MultiPolygon(g2)
     self.prop1.geometry_final = p2
     self.prop1.save()
     self.assertEqual(self.prop1.variant, self.other)
Exemple #7
0
 def test_bad_variant(self):
     self.assertEqual(self.prop1.variant, self.real)
     cntr = GEOSGeometry('SRID=3857;POINT(-638474.0 980123.1)')  # not on the map, but close to SO
     g2 = cntr.buffer(75)
     g2.transform(settings.GEOMETRY_DB_SRID)
     p2 = MultiPolygon(g2)
     self.prop1.geometry_final = p2
     self.prop1.save()
     self.assertEqual(self.prop1.variant, self.other)
Exemple #8
0
 def test_bad_location(self):
     self.assertEqual(self.prop1.location, self.realloc)
     cntr = GEOSGeometry('SRID=3857;POINT(-638474.0 980123.1)') # not on the map
     g2 = cntr.buffer(75)
     g2.transform(settings.GEOMETRY_DB_SRID)
     p2 = MultiPolygon(g2)
     self.prop1.geometry_final = p2
     self.prop1.save()
     self.assertEqual(self.prop1.location, (None, None))
 def test_bad_location(self):
     self.assertEqual(self.prop1.location, self.realloc)
     cntr = GEOSGeometry("SRID=3857;POINT(-638474.0 980123.1)")  # not on the map
     g2 = cntr.buffer(75)
     g2.transform(settings.GEOMETRY_DB_SRID)
     p2 = MultiPolygon(g2)
     self.prop1.geometry_final = p2
     self.prop1.save()
     self.assertEqual(self.prop1.location, (None, None))
Exemple #10
0
    def handle(self, *args, **options):

                                                                                                                                                                                                 
        api_client = ApiClient()
        api_client.configuration.host = "https://deims.org/api"
        api = swagger_client.DefaultApi(api_client=api_client)
        sites = api.sites_get()

        for s in sites:
            site = api.sites_resource_id_get(resource_id=s.id.suffix)
            if not (set(['Italy', 'Slovenia', 'Croatia']) & set(site.attributes.geographic.country)):
                continue
            print(site.id.prefix, site.id.suffix, site.title, site.attributes.geographic.country)

            domain_area = None
            if site.attributes.geographic.boundaries is not None:
                domain_area = GEOSGeometry(site.attributes.geographic.boundaries, srid=4326)

                if domain_area and (isinstance(domain_area, LineString) 
                                    or (domain_area, MultiLineString)):
                    domain_area = domain_area.buffer(0.0001)

                if domain_area and isinstance(domain_area, Polygon):
                    domain_area = MultiPolygon(domain_area)

            obj, created = EcosSite.objects.get_or_create(
                suffix = site.id.suffix,
                defaults= {'location' : GEOSGeometry(site.attributes.geographic.coordinates, srid=4326)}
                
            )
            
            obj.data = json.loads(api_client.last_response.data) 
            obj.denomination = site.title
            obj.description = site.attributes.general.abstract
            obj.domain_area = domain_area 
            obj.website= site.id.prefix+site.id.suffix
            obj.last_update = site.changed
            obj.img = imgimport(site.id.suffix)
            obj.location = GEOSGeometry(site.attributes.geographic.coordinates, srid=4326)

            obj.save()

            if site.attributes.focus_design_scale.parameters is not None:
                #print(site.attributes.focus_design_scale.parameters.__class__, site.attributes.focus_design_scale.parameters.__dict__)
                #print(site.attributes.focus_design_scale.parameters)
                #print(site.attributes.focus_design_scale.parameters[0].label)
                #print(site.attributes.focus_design_scale.parameters[0].uri)

                preferred_label_en = site.attributes.focus_design_scale.parameters[0].label
                
                obj, created = Parameter.objects.get_or_create(
                    uri = site.attributes.focus_design_scale.parameters[0].uri,
                    defaults={'preferred_label_en': preferred_label_en}
                )

                preferred_label_en = preferred_label_en
Exemple #11
0
 def run(self):
     try:
         g = GEOSGeometry('SRID=4326;POINT(%s %s)' % (self.input_lon, self.input_lat))
         g.transform(settings.GEOMETRY_DB_SRID)
         self.output_point_geom = g
         self.output_poly_geom = g.buffer(self.input_buffer_distance)
         self.output_area = self.output_poly_geom.area
     except:
         return False
     return True
Exemple #12
0
 def test_search_then_ad(self):
     house, create = HabitationType.objects.get_or_create(label="Maison")
     apartment, create = HabitationType.objects.get_or_create(label="Appartement")
     # create a search with search.location contaning ad.location
     pnt = GEOSGeometry(geo_from_address("22 rue esquirol Paris"))
     search = SearchFactory(location=geos.MultiPolygon(pnt.buffer(2)), price_max=700000, surface_min=50, habitation_types=[apartment, ])
     # create an ad
     ad = AdFactory(address="22 rue esquirol Paris", price=600000, surface=60, habitation_type=apartment)
     # here we should have results ...
     self.assertEqual(AdSearchRelation.objects.all().count(), 1)
Exemple #13
0
 def run(self):
     try:
         g = GEOSGeometry('SRID=4326;POINT(%s %s)' %
                          (self.input_lon, self.input_lat))
         g.transform(settings.GEOMETRY_DB_SRID)
         self.output_point_geom = g
         self.output_poly_geom = g.buffer(self.input_buffer_distance)
         self.output_area = self.output_poly_geom.area
     except:
         return False
     return True
Exemple #14
0
    def test_ad_then_search_then_update_ad(self):
        house, create = HabitationType.objects.get_or_create(label="Maison")
        apartment, create = HabitationType.objects.get_or_create(label="Appartement")
        # create an ad
        ad = AdFactory(address="22 rue esquirol Paris", price=600000, surface=60, habitation_type=apartment)
        pnt = GEOSGeometry(geo_from_address(u"52 W 52nd St, New York, NY 10019, États-Unis"))
        # create a search with ad.location inside search.location
        search = SearchFactory(location=geos.MultiPolygon(pnt.buffer(2)), price_max=700000, surface_min=50, habitation_types=[apartment, ])
        # here we should have results ...
        self.assertEqual(AdSearchRelation.objects.all().count(), 0)

        search.location = geos.MultiPolygon(ad.location.buffer(2))
        search.save()
        self.assertEqual(AdSearchRelation.objects.all().count(), 1)
Exemple #15
0
    def target_to_valid_geom(self, shape):
        try:
            if iskml(shape):
                target = parsekml(shape)
            else:
                target = GEOSGeometry(shape)
        except Exception as e:
            raise self.InvalidGeometryException(e.message)

        if not target.valid:
            target = target.buffer(0)
            if not target.valid:
                raise self.InvalidGeometryException()

        target.set_srid(settings.GEOMETRY_CLIENT_SRID)
        return target
Exemple #16
0
    def _get_users(zip, radius):
        """Identify users for a zip radius

        :param zip:
        :param radius:
        :return:
        """
        radius = float(radius)
        logger.debug('finding users within %s miles of zip code %s' % (radius, zip))

        zipcode = ZipGeocode.objects.get(pk=zip)
        geom = GEOSGeometry('POINT(%s %s)' % (zipcode.longitude, zipcode.latitude))
        buffered_geom = geom.buffer(radius)

        extended_users = ExtendedUserData.objects.filter(location__intersects=buffered_geom)

        return extended_users
Exemple #17
0
def _buffer(geojson, width=0, unit='ft'):
    geojson = JSONSerializer().serialize(geojson)
    geom = GEOSGeometry(geojson, srid=4326)

    try:
        width = float(width)
    except:
        width = 0

    if width > 0:
        if unit == 'ft':
            width = width / 3.28084

        geom.transform(3857)
        geom = geom.buffer(width)
        geom.transform(4326)

    return geom
Exemple #18
0
 def create(self, validated_data):
     try:
         temp_points = Activity_Record.objects.get(user_id_id=validated_data.get('user_id'))
         print(temp_points)
         g = temp_points
         buffer = GEOSGeometry.buffer(g.location,1)
         print(buffer.geojson)
         # return serialize('geojson', [buffer],
         #           geometry_field='location', fields=('user_id','location'))
         response_data = {}
         response_data['buffer'] = buffer.geojson
         response_data['user_id'] = validated_data.get('user_id')
         json.dumps(response_data)
     except Activity_Record.DoesNotExist:
         response_data = {}
         response_data['status'] = "User id not found"
         response_data['user_id'] =  validated_data.get('user_id')
         json.dumps(response_data)
Exemple #19
0
def _buffer(geojson, width=0, unit='ft'):
    geojson = JSONSerializer().serialize(geojson)
    geom = GEOSGeometry(geojson, srid=4326)

    try:
        width = float(width)
    except:
        width = 0

    if width > 0:
        if unit == 'ft':
            width = width/3.28084

        geom.transform(settings.ANALYSIS_COORDINATE_SYSTEM_SRID)
        geom = geom.buffer(width)
        geom.transform(4326)

    return geom
Exemple #20
0
def _buffer(geojson, width=0, unit="ft"):
    geojson = JSONSerializer().serialize(geojson)
    geom = GEOSGeometry(geojson, srid=4326)

    try:
        width = float(width)
    except Exception:
        width = 0

    if width > 0:
        if unit == "ft":
            width = width / 3.28084

        geom.transform(settings.ANALYSIS_COORDINATE_SYSTEM_SRID)
        geom = geom.buffer(width)
        geom.transform(4326)

    return geom
Exemple #21
0
def _buffer(geojson, width=0, unit='ft'):
    geojson = JSONSerializer().serialize(geojson)
    geom = GEOSGeometry(geojson, srid=4326)

    try:
        width = float(width)
    except:
        width = 0

    if width > 0:
        if unit == 'ft':
            width = width/3.28084

        geom.transform(3857)
        geom = geom.buffer(width)
        geom.transform(4326)

    return geom
Exemple #22
0
def update_registered_organizations(request):
    URL = 'http://xmaps.indy.gov/arcgis/rest/services/RegisteredOrganizations/RegisteredOrganizations/MapServer'
    LAYER = 0

    # clear out the db of previous registered organizations
    number_deleted = registered_organization.objects.all().delete()

    service = ArcGIS(URL)
    geojson = service.get(LAYER, fields='*')
    records = geojson['features']
    number_created = 0
    number_errors = 0
    for record in records:
        try:
            geometry = GEOSGeometry(str(record['geometry']))
            if not geometry.valid:
                geometry = geometry.buffer(0)
        except (GDALException, ValueError):
            number_errors = number_errors + 1
            #print "Error on", record['properties']['ORG_NAME']
        try:
            x = registered_organization(
                name=record['properties']['ORG_NAME'],
                first_name=record['properties']['FIRSTNAME'],
                last_name=record['properties']['LASTNAME'],
                email=record['properties']['EMAIL'],
                geometry=geometry,
            )
            x.save()
            if registered_organization.objects.filter(
                    geometry__isvalid=True).filter(id=x.id).count() == 0:
                #print "Error, invalid geometry", record['properties']['ORG_NAME']
                pass
            else:
                number_created = number_created + 1
        except IntegrityError:
            number_errors = number_errors + 1
            #print "IntegrityError on ", record['properties']['ORG_NAME']
    return HttpResponse(
        '<html><body><ul><li>Number deleted: {0}</li><li>Number created: {1}</li><li>Number errors: {2}</li></ul></body></html>'
        .format(number_deleted[0], number_created, number_errors))
Exemple #23
0
def _buffer(geojson, width=0, unit='ft'):
    geojson = JSONSerializer().serialize(geojson)
    
    try:
        width = float(width)
    except:
        width = 0

    if width > 0:
        geom = GEOSGeometry(geojson, srid=4326)
        geom.transform(3857)
        
# Below 2 lines are deprecated in EAMENA's Arches as the unit of choice is EPSG3857's default metres
        if unit == 'ft':
            width = width/3.28084

        buffered_geom = geom.buffer(width)
        buffered_geom.transform(4326)
        return buffered_geom
    else:
        return GEOSGeometry(geojson)
Exemple #24
0
def _buffer(geojson, width=0, unit='ft'):
    geojson = JSONSerializer().serialize(geojson)
    
    try:
        width = float(width)
    except:
        width = 0

    if width > 0:
        geom = GEOSGeometry(geojson, srid=4326)
        geom.transform(3857)
        
# Below 2 lines are deprecated in EAMENA's Arches as the unit of choice is EPSG3857's default metres
        if unit == 'ft':
            width = width/3.28084

        buffered_geom = geom.buffer(width)
        buffered_geom.transform(4326)
        return buffered_geom
    else:
        return GEOSGeometry(geojson)
def get_geoms():
    cntr = GEOSGeometry("SRID=3857;POINT(-13842474.0 5280123.1)")

    stand_geoms = []
    for i in range(NUM_STANDS):
        cntr.set_x(cntr.x + 150)
        g1 = cntr.buffer(75)
        g1.transform(settings.GEOMETRY_DB_SRID)
        stand_geoms.append(wkt.loads(g1.wkt))

    casc_poly = cascaded_union(stand_geoms)

    if casc_poly.type == "MultiPolygon":
        polys = []
        for c in casc_poly:
            interiors = [x for x in c.interiors if Polygon(x).area > settings.SLIVER_THRESHOLD]
            polys.append(Polygon(shell=c.exterior, holes=interiors))
    elif casc_poly.type == "Polygon":
        interiors = [x for x in casc_poly.interiors if Polygon(x).area > settings.SLIVER_THRESHOLD]
        polys = [Polygon(shell=casc_poly.exterior, holes=interiors)]

    property_geom = MultiPolygon(polys)

    return stand_geoms, property_geom
from django.contrib.auth.models import User
from django.test.client import Client
from django.contrib.gis.geos import GEOSGeometry
from shapely.ops import cascaded_union
from shapely.geometry import Polygon, MultiPolygon
from shapely import wkt

cntr = GEOSGeometry('SRID=3857;POINT(-13842500.0 5280100.0)')

NUM_STANDS = 10 * 10 
geoms = []
for i in range(int(NUM_STANDS**0.5)):
    cntr.set_y(cntr.y - 150)
    for j in range(int(NUM_STANDS**0.5)):
        cntr.set_x(cntr.x + 150)
        g1 = cntr.buffer(75).envelope
        g1.transform(settings.GEOMETRY_DB_SRID)
        geoms.append(wkt.loads(g1.wkt))
    cntr.set_x(cntr.x - int(NUM_STANDS**0.5)*150)

casc_poly = cascaded_union(geoms)

if casc_poly.type == 'MultiPolygon':
    polys = []
    for c in casc_poly:
        interiors = [x for x in c.interiors if Polygon(x).area > settings.SLIVER_THRESHOLD]
        polys.append(Polygon(shell=c.exterior, holes=interiors))
elif casc_poly.type == 'Polygon':
    interiors = [x for x in casc_poly.interiors if Polygon(x).area > settings.SLIVER_THRESHOLD]
    polys = [Polygon(shell=casc_poly.exterior, holes=interiors)]
Exemple #27
0
from django.test.client import Client
from django.contrib.gis.geos import GEOSGeometry, MultiPolygon

from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.conf import settings
from json import loads, dumps
from madrona.features import *
from madrona.common.utils import kml_errors, enable_sharing
from madrona.raster_stats.models import RasterDataset
from trees.models import Stand, Strata, ForestProperty, County, FVSVariant, Scenario, Rx, FVSAggregate
from trees.utils import StandImporter
from django.core.management import call_command

cntr = GEOSGeometry('SRID=3857;POINT(-13842474.0 5280123.1)')
g1 = cntr.buffer(75)
g1.transform(settings.GEOMETRY_DB_SRID)

single_p1 = g1.buffer(1000)
p1 = MultiPolygon(single_p1)


def import_rasters():
    d = os.path.dirname(__file__)
    rast_path = os.path.abspath(os.path.join(d, '..', 'fixtures',
        'testdata'))
    # Here we'll need to create dummy rasterdatasets for everything
    # in the IMPUTE_RASTERS setting
    elev = RasterDataset.objects.create(name="elevation",
            filepath=os.path.join(rast_path,'elevation.tif'), type='continuous')
    aspect = RasterDataset.objects.create(name="aspect",
def run_task_remote(run_uid):  # noqa
    run = ExportRun.objects.get(uid=run_uid)
    run.status = 'RUNNING'
    run.started_at = timezone.now()
    run.save()
    LOG.debug('Running ExportRun with id: {0}'.format(run_uid))
    job = run.job

    try:
        stage_dir = os.path.join(settings.EXPORT_STAGING_ROOT,
                                 str(run_uid)) + '/'
        os.makedirs(stage_dir, 6600)
        run_dir = os.path.join(settings.EXPORT_DOWNLOAD_ROOT, run_uid)
        if not os.path.exists(run_dir):
            os.makedirs(run_dir)

        aoi = GEOSGeometry(job.the_geom)
        if job.buffer_aoi:
            aoi = aoi.buffer(
                0.02
            )  # 0.02 degrees is a reasonable amount for an admin 0 boundary
        aoi = simplify_max_points(aoi)
        try:
            feature_selection = job.feature_selection_object
        except Exception:
            feature_selection = FeatureSelection(SIMPLE)

        export_formats = map_names_to_formats(job.export_formats)

        download_dir = os.path.join(settings.EXPORT_DOWNLOAD_ROOT, run_uid)
        zipper = Zipper(job.name, stage_dir, download_dir, aoi)

        def on_task_start(formatcls):
            LOG.debug('Task Start: {0} for run: {1}'.format(
                formatcls.name, run_uid))
            if formatcls in export_formats:
                task = ExportTask.objects.get(run__uid=run_uid,
                                              name=formatcls.name)
                task.status = 'RUNNING'
                task.started_at = timezone.now()
                task.save()

        def on_task_success(formatcls, results):
            LOG.debug('Task Success: {0} for run: {1}'.format(
                formatcls.name, run_uid))
            if formatcls in export_formats:
                task = ExportTask.objects.get(run__uid=run_uid,
                                              name=formatcls.name)
                zipfiles = zipper.run(results)
                task.filesize_bytes = sum(
                    os.stat(zipfile).st_size for zipfile in zipfiles)
                task.filenames = [
                    os.path.basename(zipfile) for zipfile in zipfiles
                ]
                task.status = 'SUCCESS'
                task.finished_at = timezone.now()
                task.save()

        r = RunManager(export_formats,
                       aoi,
                       feature_selection,
                       stage_dir,
                       map_creator_dir=settings.OSMAND_MAP_CREATOR_DIR,
                       garmin_splitter=settings.GARMIN_SPLITTER,
                       garmin_mkgmap=settings.GARMIN_MKGMAP,
                       per_theme=True,
                       on_task_start=on_task_start,
                       on_task_success=on_task_success,
                       overpass_api_url=settings.OVERPASS_API_URL)
        r.run()

        public_dir = settings.HOSTNAME + os.path.join(
            settings.EXPORT_MEDIA_ROOT, run_uid)

        if settings.SYNC_TO_HDX and HDXExportRegion.objects.filter(
                job_id=run.job_id).exists():
            LOG.debug("Adding resources to HDX")
            region = HDXExportRegion.objects.get(job_id=run.job_id)
            export_set = region.hdx_dataset
            export_set.sync_resources(zipper.zipped_resources, public_dir)

        if run.job.hdx_export_region_set.count() == 0:
            # not associated with an HDX Export Regon; send mail
            send_completion_notification(run)
        else:
            send_hdx_completion_notification(
                run, run.job.hdx_export_region_set.first())

        run.status = 'COMPLETED'
        LOG.debug('Finished ExportRun with id: {0}'.format(run_uid))
    except Exception as e:
        client.captureException(extra={
            'run_uid': run_uid,
        })
        run.status = 'FAILED'
        LOG.warn('ExportRun {0} failed: {1}'.format(run_uid, e))
        LOG.warn(traceback.format_exc())

        send_error_notification(run)
        if run.job.hdx_export_region_set.count() >= 0:
            send_hdx_error_notification(run,
                                        run.job.hdx_export_region_set.first())
    finally:
        shutil.rmtree(stage_dir)

        run.finished_at = timezone.now()
        run.save()
Exemple #29
0
def toDownload(request):
    ctx = {}
    pointExist = Point_Cloud.objects.all()[:1]
    if pointExist:
        if request.POST:
            if '_download' in request.POST:
                #check which forms are filled in
                if request.POST['x'] and request.POST['y'] and request.POST[
                        'r']:
                    x0 = float(str(request.POST['x']))
                    y0 = float(str(request.POST['y']))
                    radius = float(str(request.POST['r']))
                elif request.POST['x'] and request.POST['y']:
                    x0 = float(str(request.POST['x']))
                    y0 = float(str(request.POST['y']))
                    radius = 459.494
                elif request.POST['y'] and request.POST['r']:
                    x0 = '85168.41'
                    y0 = float(str(request.POST['y']))
                    radius = float(str(request.POST['r']))
                elif request.POST['x'] and request.POST['r']:
                    x0 = float(str(request.POST['x']))
                    y0 = '446709.42'
                    radius = float(str(request.POST['r']))
                elif request.POST['x']:
                    x0 = float(str(request.POST['x']))
                    y0 = '446709.42'
                    radius = 459.494
                elif request.POST['y']:
                    x0 = '85168.41'
                    y0 = float(str(request.POST['y']))
                    radius = 459.494
                elif request.POST['r']:
                    x0 = '85168.41'
                    y0 = '446709.42'
                    radius = float(str(request.POST['r']))
                else:
                    x0 = '85168.41'
                    y0 = '446709.42'
                    radius = 459.494
                center = GEOSGeometry('SRID=28992;POINT (' + str(x0) + ' ' +
                                      str(y0) + ')')
                polygon = center.buffer(radius)
                if request.POST['filename']:
                    f_name = str(request.POST['filename'])
                else:
                    f_name = 'downloadedpc'

                outfile = laspy.file.File(settings.MEDIA_ROOT + '/' + f_name +
                                          '.las',
                                          mode='w',
                                          header=laspy.header.Header())

                outfile.define_new_dimension(name="imp",
                                             data_type=9,
                                             description="Importance value")
                temp1 = Point_Cloud.objects.values('id', 'imp', 'xypoint')
                temp2 = []
                for p in temp1:
                    if p['xypoint'].distance(
                            center) / radius < p['imp']:  #distance query
                        temp2.append(p['id'])
                #ST_Within query
                allx = np.array([
                    x for x in Point_Cloud.objects.filter(
                        xypoint__within=polygon, id__in=temp2).values_list(
                            'x', flat=True)
                ])
                ally = np.array([
                    y for y in Point_Cloud.objects.filter(
                        xypoint__within=polygon, id__in=temp2).values_list(
                            'y', flat=True)
                ])
                allz = np.array([
                    z for z in Point_Cloud.objects.filter(
                        xypoint__within=polygon, id__in=temp2).values_list(
                            'z', flat=True)
                ])
                allimp = np.array([
                    imp for imp in Point_Cloud.objects.filter(
                        xypoint__within=polygon, id__in=temp2).values_list(
                            'imp', flat=True).order_by('imp')
                ])

                outfile.X = allx
                outfile.Y = ally
                outfile.Z = allz
                outfile.imp = allimp
                outfile.header.offset = [
                    min(allx), min(ally),
                    min(allz), min(allimp)
                ]
                outfile.header.scale = [0.001, 0.001, 0.001, 0.001]
                outfile.close()
                ctx['done'] = 'File ' + f_name + ' is downloaded!'

            elif '_viewer' in request.POST:
                if request.POST['x'] and request.POST['y'] and request.POST[
                        'r']:
                    x0 = float(str(request.POST['x']))
                    y0 = float(str(request.POST['y']))
                    radius = float(str(request.POST['r']))
                elif request.POST['x'] and request.POST['y']:
                    x0 = float(str(request.POST['x']))
                    y0 = float(str(request.POST['y']))
                    radius = 459.494
                elif request.POST['y'] and request.POST['r']:
                    x0 = '85168.41'
                    y0 = float(str(request.POST['y']))
                    radius = float(str(request.POST['r']))
                elif request.POST['x'] and request.POST['r']:
                    x0 = float(str(request.POST['x']))
                    y0 = '446709.42'
                    radius = float(str(request.POST['r']))
                elif request.POST['x']:
                    x0 = float(str(request.POST['x']))
                    y0 = '446709.42'
                    radius = 459.494
                elif request.POST['y']:
                    x0 = '85168.41'
                    y0 = float(str(request.POST['y']))
                    radius = 459.494
                elif request.POST['r']:
                    x0 = '85168.41'
                    y0 = '446709.42'
                    radius = float(str(request.POST['r']))
                else:
                    x0 = '85168.41'
                    y0 = '446709.42'
                    radius = 459.494
                center = GEOSGeometry('SRID=28992;POINT (' + str(x0) + ' ' +
                                      str(y0) + ')')
                polygon = center.buffer(radius)

                temp1 = Point_Cloud.objects.values('id', 'imp', 'xypoint')
                temp2 = []
                for p in temp1:
                    if p['xypoint'].distance(
                            center) / radius < p['imp']:  #**2:
                        temp2.append(p['id'])
                selected = Point_Cloud.objects.filter(
                    xypoint__within=polygon, id__in=temp2).order_by('imp')

                points = []

                for i in range(len(selected)):
                    points.append(selected[i].x)
                    points.append(selected[i].y)
                    points.append(selected[i].z)
                    points.append(selected[i].imp)

                string = 'var visualisation = ' + str(
                    points) + ';\n' + 'var centre = ' + str([x0, y0, 0.0
                                                             ]) + ';'
                outfile = file(settings.MEDIA_ROOT + '/visualisation.js',
                               mode='w')
                outfile.write(string)
                outfile.close()
                ctx['done'] = 'File is ready for the viewer!'
    else:
        ctx['done'] = 'No point cloud available!'
        return render(request, 'upload.html', ctx)
    return render(request, 'download.html', ctx)
from django.test.client import Client
from django.contrib.gis.geos import GEOSGeometry, MultiPolygon

from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.conf import settings
from json import loads, dumps
from madrona.features import *
from madrona.common.utils import kml_errors, enable_sharing
from madrona.raster_stats.models import RasterDataset
from trees.models import Stand, Strata, ForestProperty, County, FVSVariant, Scenario, Rx, FVSAggregate
from trees.utils import StandImporter
from django.core.management import call_command

cntr = GEOSGeometry("SRID=3857;POINT(-13842474.0 5280123.1)")
g1 = cntr.buffer(75)
g1.transform(settings.GEOMETRY_DB_SRID)

single_p1 = g1.buffer(1000)
p1 = MultiPolygon(single_p1)


def import_rasters():
    d = os.path.dirname(__file__)
    rast_path = os.path.abspath(os.path.join(d, "..", "fixtures", "testdata"))
    # Here we'll need to create dummy rasterdatasets for everything
    # in the IMPUTE_RASTERS setting
    elev = RasterDataset.objects.create(
        name="elevation", filepath=os.path.join(rast_path, "elevation.tif"), type="continuous"
    )
    aspect = RasterDataset.objects.create(
Exemple #31
0
def geosearch(request):
    """
    Returns geocoded results in MERCATOR projection
    First tries coordinates, then a series of geocoding engines
    """
    from geopy import distance
    if request.method != 'GET':
        return HttpResponse('Invalid http method; use GET', status=405)

    try:
        txt = unicode(request.GET['search'])
    except:
        return HttpResponseBadRequest()

    searchtype = lat = lon = None
    place = txt
    try:
        p = Point(txt)
        lat, lon, altitude = p
        searchtype = 'coordinates'
    except:
        pass  # not a point

    centerloc = Point("45.54 N 120.64 W")
    max_dist = 315  # should be everything in WA and Oregon

    searches = [
        geocoders.GeoNames(),
        geocoders.OpenMapQuest(),
        geocoders.Yahoo(app_id=settings.APP_NAME),
        geocoders.Bing(api_key=settings.BING_API_KEY),
        # these are tried in reverse order, fastest first
        # TODO thread them and try them as they come in.
    ]

    while not (searchtype and lat and lon):  # try a geocoder
        try:
            g = searches.pop()
        except IndexError:
            break  # no more search engines left to try

        try:
            for p, loc in g.geocode(txt, exactly_one=False):
                d = distance.distance(loc, centerloc).miles
                if d < max_dist:
                    # TODO maybe compile these and return the closest to map center?
                    # print g, p, loc
                    place = p
                    lat = loc[0]
                    lon = loc[1]
                    max_dist = d
                else:
                    pass
            searchtype = g.__class__.__name__
        except:
            pass

    if searchtype and lat and lon:  # we have a winner
        cntr = GEOSGeometry('SRID=4326;POINT(%f %f)' % (lon, lat))
        cntr.transform(settings.GEOMETRY_DB_SRID)
        cntrbuf = cntr.buffer(settings.POINT_BUFFER)
        extent = cntrbuf.extent
        loc = {
            'status': 'ok',
            'search': txt,
            'place': place,
            'type': searchtype,
            'extent': extent,
            'latlon': [lat, lon],
            'center': (cntr[0], cntr[1]),
        }
        json_loc = json.dumps(loc)
        return HttpResponse(json_loc, mimetype='application/json', status=200)
    else:
        loc = {
            'status': 'failed',
            'search': txt,
            'type': None,
            'extent': None,
            'center': None,
        }
        json_loc = json.dumps(loc)
        return HttpResponse(json_loc, mimetype='application/json', status=404)
Exemple #32
0
def geosearch(request):
    """
    Returns geocoded results in MERCATOR projection
    First tries coordinates, then a series of geocoding engines
    """
    from geopy import distance
    if request.method != 'GET':
        return HttpResponse('Invalid http method; use GET', status=405)

    try:
        txt = unicode(request.GET['search'])
    except:
        return HttpResponseBadRequest()

    searchtype = lat = lon = None
    place = txt
    try:
        p = Point(txt)
        lat, lon, altitude = p
        searchtype = 'coordinates'
    except:
        pass  # not a point

    centerloc = Point("45.54 N 120.64 W")
    max_dist = 315  # should be everything in WA and Oregon

    searches = [
        geocoders.GeoNames(),
        geocoders.OpenMapQuest(), 
        geocoders.Yahoo(app_id=settings.APP_NAME), 
        geocoders.Bing(api_key=settings.BING_API_KEY),
        # these are tried in reverse order, fastest first
        # TODO thread them and try them as they come in.
    ]

    while not (searchtype and lat and lon):  # try a geocoder
        try:
            g = searches.pop()
        except IndexError:
            break  # no more search engines left to try

        try:
            for p, loc in g.geocode(txt, exactly_one=False):
                d = distance.distance(loc, centerloc).miles
                if d < max_dist:
                    # TODO maybe compile these and return the closest to map center?
                    # print g, p, loc 
                    place = p
                    lat = loc[0]
                    lon = loc[1]
                    max_dist = d
                else:
                    pass
            searchtype = g.__class__.__name__
        except:
            pass

    if searchtype and lat and lon:  # we have a winner
        cntr = GEOSGeometry('SRID=4326;POINT(%f %f)' % (lon, lat))
        cntr.transform(settings.GEOMETRY_DB_SRID)
        cntrbuf = cntr.buffer(settings.POINT_BUFFER)
        extent = cntrbuf.extent
        loc = {
            'status': 'ok',
            'search': txt,
            'place': place,
            'type': searchtype,
            'extent': extent,
            'latlon': [lat, lon],
            'center': (cntr[0], cntr[1]),
        }
        json_loc = json.dumps(loc)
        return HttpResponse(json_loc, mimetype='application/json', status=200)
    else:
        loc = {
            'status': 'failed',
            'search': txt,
            'type': None,
            'extent': None,
            'center': None,
        }
        json_loc = json.dumps(loc)
        return HttpResponse(json_loc, mimetype='application/json', status=404)
Exemple #33
0
from django.contrib.auth.models import User
from django.test.client import Client
from django.contrib.gis.geos import GEOSGeometry
from shapely.ops import cascaded_union
from shapely.geometry import Polygon, MultiPolygon
from shapely import wkt

cntr = GEOSGeometry('SRID=3857;POINT(-13842500.0 5280100.0)')

NUM_STANDS = 10 * 10
geoms = []
for i in range(int(NUM_STANDS**0.5)):
    cntr.set_y(cntr.y - 150)
    for j in range(int(NUM_STANDS**0.5)):
        cntr.set_x(cntr.x + 150)
        g1 = cntr.buffer(75).envelope
        g1.transform(settings.GEOMETRY_DB_SRID)
        geoms.append(wkt.loads(g1.wkt))
    cntr.set_x(cntr.x - int(NUM_STANDS**0.5) * 150)

casc_poly = cascaded_union(geoms)

if casc_poly.type == 'MultiPolygon':
    polys = []
    for c in casc_poly:
        interiors = [
            x for x in c.interiors
            if Polygon(x).area > settings.SLIVER_THRESHOLD
        ]
        polys.append(Polygon(shell=c.exterior, holes=interiors))
elif casc_poly.type == 'Polygon':