コード例 #1
0
ファイル: ml_model.py プロジェクト: tossetolab/ml-enabler
    def get_latest_predictions_in_bbox(model_id: int, version_id: int,
                                       bbox: list):
        """
        Fetch latest predictions for the specified model intersecting
        the given bbox

        :param model_id, version_id, bbox
        :return list of predictions
        """

        query = db.session.query(
            Prediction.id, Prediction.created, Prediction.dockerhub_hash,
            ST_AsGeoJSON(ST_Envelope(Prediction.bbox)).label('bbox'),
            Prediction.model_id, Prediction.tile_zoom,
            Prediction.version_id).filter(
                Prediction.model_id == model_id).filter(
                    Prediction.version_id == version_id).filter(
                        ST_Intersects(
                            Prediction.bbox,
                            ST_MakeEnvelope(
                                bbox[0], bbox[1], bbox[2], bbox[3],
                                4326))).order_by(
                                    Prediction.created.desc()).limit(1)

        return query.all()
コード例 #2
0
ファイル: ml_model.py プロジェクト: rustyb/ml-enabler
 def export(self):
     return (db.session.query(
         PredictionTile.id,
         PredictionTile.quadkey,
         ST_AsGeoJSON(PredictionTile.geom).label("geometry"),
         PredictionTile.predictions,
         PredictionTile.validity,
     ).filter(PredictionTile.prediction_id == self.id).yield_per(100))
コード例 #3
0
 def rafraichir(self):
     conducteurs = modeles.Conducteur.query.all()
     geojson = [
         json.loads(db.session.scalar(ST_AsGeoJSON(conducteur.position)))
         for conducteur in conducteurs
     ]
     return jsonify({
         'taxis': geojson,
         #'conducteurs': conducteurs
     })
コード例 #4
0
ファイル: ml_model.py プロジェクト: tossetolab/ml-enabler
 def get_predictions_by_model(model_id: int):
     """
     Gets predictions for a specified ML Model
     :param model_id: ml model ID in scope
     :return predictions if found otherwise None
     """
     query = db.session.query(
         Prediction.id, Prediction.created, Prediction.dockerhub_hash,
         ST_AsGeoJSON(ST_Envelope(Prediction.bbox)).label('bbox'),
         Prediction.model_id, Prediction.tile_zoom,
         Prediction.version_id).filter(Prediction.model_id == model_id)
     return query.all()
コード例 #5
0
ファイル: ml_model.py プロジェクト: tossetolab/ml-enabler
 def get(prediction_id: int):
     """
     Get prediction with the given ID
     :param prediction_id
     :return prediction if found otherwise None
     """
     query = db.session.query(
         Prediction.id, Prediction.created, Prediction.dockerhub_hash,
         ST_AsGeoJSON(ST_Envelope(Prediction.bbox)).label('bbox'),
         Prediction.model_id, Prediction.tile_zoom,
         Prediction.version_id).filter(Prediction.id == prediction_id)
     return query.one()
コード例 #6
0
class Property(Base):
    __tablename__ = 'properties'
    id = Column(String, primary_key=True)
    geocode_geo = Column(Geography)
    parcel_geo = Column(Geography)
    building_geo = Column(Geography)
    image_bounds = Column(ARRAY(Float))
    image_url = Column(String)
    geocode_geojson = column_property(ST_AsGeoJSON(geocode_geo))

    def __repr__(self):
        return "<Property(id='{}', image_url='{}')>"\
            .format(self.id, self.image_url)
コード例 #7
0
class Coverage(db.Model):
    __tablename__ = 'coverages'
    __table_args__ = {
        'schema': 'changes_app'
    }

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)
    geometry = db.Column(Geometry(geometry_type='Geometry', srid=4326), nullable=False)

    _geojson = column_property(
        ST_AsGeoJSON(geometry)
    )

    users = db.relationship(
        'User',
        secondary=user_coverage,
        backref='coverages'
    )

    def __init__(self, users, name, geojson):
        self.users = users
        self.name = name
        self.geojson = geojson

    @property
    def geojson(self):
        return self._geojson

    @geojson.setter
    def geojson(self, geojson):
        self.geometry = from_shape(asShape(geojson['geometry']), srid=4326)

    @property
    def json(self):
        return {
            'id': self.id,
            'name': self.name,
            'geometry': self.geojson
        }

    @classmethod
    def by_id(cls, id):
        q = cls.query.filter(cls.id == id)
        return q.first_or_404()

    @classmethod
    def by_ids(cls, ids):
        q = cls.query.filter(cls.id.in_(ids))
        return q.all()
コード例 #8
0
ファイル: models.py プロジェクト: revmischa/dancar
 def column_expression(self, col):
     return ST_AsGeoJSON(col, type_=self)
コード例 #9
0
ファイル: context.py プロジェクト: dgreyling/gbi-server
def get_context_document():
    init_user_boxes(g.user, current_app.config.get('COUCH_DB_URL'))

    wmts_sources = db.session.query(
        WMTS, ST_AsGeoJSON(ST_Transform(WMTS.view_coverage, 3857))).order_by(
            desc(WMTS.is_background_layer)).all()

    wms_sources = db.session.query(
        WMS, ST_AsGeoJSON(ST_Transform(WMS.view_coverage, 3857))).order_by(
            desc(WMS.is_background_layer)).all()
    wfs_sources = db.session.query(WFS).all()

    response = {
        "version": "0.2",
        "portal": {
            "prefix": current_app.config['PORTAL_PREFIX'],
            "title": current_app.config['PORTAL_TITLE'],
        },
        "wmts_sources": [],
        "wms_sources": [],
        "wfs_sources": [],
        "couchdb_sources": [],
    }

    couchdb = CouchDBBox(current_app.config['COUCH_DB_URL'],
                         '%s_%s' % (SystemConfig.AREA_BOX_NAME, g.user.id))

    for source in wmts_sources:
        wmts, view_coverage = source
        geom = json.loads(view_coverage)
        response['wmts_sources'].append({
            "name": wmts.name,
            "title": wmts.title,
            "url": wmts.client_url(external=True),
            "format": wmts.format,
            "overlay": wmts.is_overlay,
            "username": wmts.username,
            "password": wmts.password,
            "is_public": wmts.is_public,
            "is_protected": wmts.is_protected,
            "is_background_layer": wmts.is_background_layer,
            "max_tiles": wmts.max_tiles,
            "view_restriction": {
                "zoom_level_start": wmts.view_level_start,
                "zoom_level_end": wmts.view_level_end,
                "geometry": geom
            },
            "download_restriction": {
                "zoom_level_start": wmts.view_level_start,
                "zoom_level_end": wmts.view_level_end,
            }
        })

    for source in wms_sources:
        wms, view_coverage = source
        geom = json.loads(view_coverage)
        response['wms_sources'].append({
            "name": wms.name,
            "title": wms.title,
            "url": wms.url,
            "layer": wms.layer,
            "format": wms.format,
            "overlay": wms.is_overlay,
            "username": wms.username,
            "password": wms.password,
            "is_public": wms.is_public,
            "is_protected": wms.is_protected,
            "srs": wms.srs,
            "wms_version": wms.version,
            "view_restriction": {
                "zoom_level_start": wms.view_level_start,
                "zoom_level_end": wms.view_level_end,
                "geometry": geom
            },
            "download_restriction": {
                "zoom_level_start": wms.view_level_start,
                "zoom_level_end": wms.view_level_end,
            }
        })

    for wfs in wfs_sources:
        response['wfs_sources'].append({
            'id': wfs.id,
            'name': wfs.name,
            'layer': wfs.layer,
            'host': wfs.host,
            'url': wfs.url,
            'srs': wfs.srs,
            'geometry_field': wfs.geometry,
            'feature_ns': wfs.ns_uri,
            'typename': wfs.ns_prefix,
            'search_property': wfs.search_property,
            'username': wfs.username,
            'password': wfs.password,
            'is_protected': wfs.is_protected,
        })

    if current_app.config['FEATURE_AREA_BOXES']:
        response['couchdb_sources'].append({
            "name":
            _('area box'),
            "url":
            current_app.config['COUCH_DB_URL'],
            "dbname":
            '%s_%s' % (SystemConfig.AREA_BOX_NAME, g.user.id),
            "username":
            '******' % g.user.id,
            "password":
            g.user.authproxy_token,
            "writable":
            True,
            "dbname_user":
            SystemConfig.AREA_BOX_NAME_LOCAL,
        })

    if current_app.config['FEATURE_DOC_BOXES']:
        if g.user.is_consultant:
            response['couchdb_sources'].append({
                "name":
                _('file box'),
                "url":
                current_app.config['COUCH_DB_URL'],
                "dbname":
                '%s_%s' % (SystemConfig.FILE_BOX_NAME, g.user.id),
                "username":
                '******' % g.user.id,
                "password":
                g.user.authproxy_token,
                "writable":
                True,
                "dbname_user":
                SystemConfig.FILE_BOX_NAME_LOCAL,
            })
        else:
            response['couchdb_sources'].append({
                "name":
                _('consultant box'),
                "url":
                current_app.config['COUCH_DB_URL'],
                "dbname":
                '%s_%s' % (SystemConfig.DOWNLOAD_BOX_NAME, g.user.id),
                "username":
                '******' % g.user.id,
                "password":
                g.user.authproxy_token,
                "writable":
                False,
                "dbname_user":
                SystemConfig.DOWNLOAD_BOX_NAME_LOCAL,
            })
            response['couchdb_sources'].append({
                "name":
                _('uploadbox'),
                "url":
                current_app.config['COUCH_DB_URL'],
                "dbname":
                '%s_%s' % (SystemConfig.UPLOAD_BOX_NAME, g.user.id),
                "username":
                '******' % g.user.id,
                "password":
                g.user.authproxy_token,
                "writable":
                True,
                "dbname_user":
                SystemConfig.UPLOAD_BOX_NAME_LOCAL,
            })

    if current_app.config['PARCEL_SEARCH_DATABASE_URI']:
        response['parcel_search_url'] = url_for('search.query',
                                                token=g.user.authproxy_token,
                                                _external=True)

    response['logging'] = {
        'url':
        url_for('logserv.log',
                user_token=g.user.authproxy_token,
                _external=True),
    }

    response['update_coverage'] = {
        'url':
        url_for('authproxy.update_download_coverage',
                user_token=g.user.authproxy_token,
                _external=True),
    }

    response['user'] = {
        'email': g.user.email,
        'type': g.user.type,
        'type_name': g.user.type_name,
    }

    return json.dumps(response)
コード例 #10
0
 def to_geojson(self):
     geojson_geometry = db.session.scalar(ST_AsGeoJSON(self.geom))
     return geojson_geometry
コード例 #11
0
 def location(self):
     json_str = db.session.query(ST_AsGeoJSON(self._location)).scalar()
     if not json_str:
         return []
     data = json.loads(json_str)
     return data["coordinates"]
コード例 #12
0
ファイル: tarif.py プロジェクト: sid-ut3/taxisid
def estimation_precise(course):
    ''' Calculer le devis précis d'une course (en calculant le coût de trajet à vide). '''

    # on récupère la valeur estimée de la course lors de la première estimation
    prix = db.session.query(Course,Facture).filter(Course.numero == Facture.course).filter(Course.numero == course['numero']).first()
    prix_estimation = prix.Facture.estimation_1


    # On récupère les tarifs applicables
    tarifs = utile.lire_json('app/devis/data/tarifs.json')
    supplements = utile.lire_json('app/devis/data/supplements.json')

    # On déduit au prix estimé la valeur de trajet à vide fixée dans la première estimation
    tav = supplements['trajet_a_vide']
    prix_estimation -= tav
    

    # Simulation du trajet à vide

    # Récupération de la position du taxi qui effectuera la course
    pos = db.session.query(Course,Conducteur).filter(Course.conducteur == Conducteur.telephone).filter(Course.numero == course['numero']).first()
    pos_taxi = pos.Conducteur.position
    position = json.loads(db.session.scalar(
                    ST_AsGeoJSON(
                        pos_taxi
                    )
                ))
    position['lat'] = position['coordinates'][0]
    position['lon'] = position['coordinates'][1]




    # Extraction des information de départ
    dep = db.session.query(Course,Adresse).filter(Course.depart == Adresse.identifiant).filter(Course.numero == course['numero']).first()
    depart = dep.Adresse.position
    adresse_dep = json.loads(db.session.scalar(
                    ST_AsGeoJSON(
                        depart
                    )
                ))

    adresse_dep['lat'] = adresse_dep['coordinates'][0]
    adresse_dep['lon'] = adresse_dep['coordinates'][1]


    
    depart_taxi = position
    depart_course = adresse_dep

    deb = db.session.query(Course,Adresse).filter(Course.numero == course['numero']).first()   
    debut = deb.Course.debut



    # Calcul de la distance
    simulation = calculer.simuler(depart_taxi, depart_course, debut)
    duree = simulation['duree']
    distance = simulation['distance']
    jour = simulation['ratios']['jour']
    nuit = simulation['ratios']['nuit']

    # Savoir si c'est un jour ferié ou un dimanche
    date = '{0}/{1}'.format(debut.day, debut.month)
    jours_feries = calendrier.feries(debut.year)
    ferie = date in jours_feries
    dimanche = debut.weekday() == 6

    # Décider du tarif à appliquer
    if ferie or dimanche:
        prix_par_km = tarifs['B']
    else:
        prix_par_km = jour * tarifs['A'] + nuit * tarifs['B']

    # Calculer le prix de la course
    total = round(prix_estimation + distance * prix_par_km,2)
    # Prise en compte du tarif minimum
    total = max(total, supplements['tarif_minimum'])


    # On retourne la nouvelle estimation du prix du trajet
    return total