コード例 #1
0
class base_map_geological_zone(geo_model.GeoModel):
    _name="base_map.geological_zone"
    _columns={
        'name':fields.char('Geological Zone',size=256),
        'code':fields.char('Code',size=128),
        'shape':fields.geo_multi_polygon('Shape'),
    }
コード例 #2
0
class base_map_district(geo_model.GeoModel):
    _name="base_map.district"
    _columns = {
        'name':fields.char('District Name',size=256),
        'code':fields.char('District Code',size=256),
        'shape':fields.geo_multi_polygon('Shape'),
    }
コード例 #3
0
class base_map_sub_district(geo_model.GeoModel):
    _name="base_map.sub_district"
    _columns={
        'shape':fields.geo_multi_polygon('Shape'),
        'code':fields.char('Code',size=256),
        'name':fields.char('Name',size=256),
        'classification':fields.integer('Classification'),
    }
コード例 #4
0
class ocs_sub_district(geo_model.GeoModel):
    """ Contains geografic information about especific territories """
    _name = 'ocs.sub_district'
    _order = 'name asc'
    _columns= {
        'name' : fields.char('Sub District Name :',size=150, help='Sub-District name'),
        'code' : fields.char('Territory Code :',size=150,help='Territory Code'),
        'geo_polygon':fields.geo_multi_polygon('Geometry'),
    }
コード例 #5
0
class ocs_neighborhood(geo_model.GeoModel):
    """Contains geographic information about all towns in the city"""
    _name = 'ocs.neighborhood'
    _order = 'name asc'
    _columns = {
        'code': fields.char('Neighborhood Code',size=30,help='Identify a Cadastral Code'),
        'name': fields.char('Neighborhood Name', size = 128),
        'geo_polygon':fields.geo_multi_polygon('Geometry'),
    }
コード例 #6
0
class base_map_micro_seismicity(geo_model.GeoModel):
    _name="base_map.micro_seismicity"
    _columns={
        'zone_name':fields.char('Zone Name',size=128),
        'colour':fields.char('Colour', size=128),
        'micr_measure1':fields.float('Measure 1'),
        'micr_measure2':fields.float('Measure 2'),
        'shape':fields.geo_multi_polygon('Shape'),
    }
コード例 #7
0
class base_map_neighborhood(geo_model.GeoModel):
    """Contains geographic information about all neighborhoods in the city"""
    _name = 'base_map.neighborhood'
    _order = 'name asc'
    _columns = {
        'code': fields.char('Neighborhood Code',size=30,help='Identify a Neighborhood Code'),
        'name': fields.char('Neighborhood Name', size = 128),
        'shape':fields.geo_multi_polygon('Geometry'),
    }
コード例 #8
0
class urban_pavement_roadway(geo_model.GeoModel):
    """ 
    Roadway Base Polygon
    """
    _name="urban_pavement.roadway"
    _columns={
        'shape':fields.geo_multi_polygon('Coordinate'),
        'id':fields.integer('Polygon ID'),
        'ric':fields.integer('Rodway Idenfication Code'),#CIV Codigo de Identificacion de la Via
        'create_date':fields.date('Create Date'),
        'adherence':fields.float('Adherence',digits=(12,6)),
    }
コード例 #9
0
class base_map_cadastral_zone(geo_model.GeoModel):
    """
    This layer must be re-factored
    """
    _name="base_map.cadastral_zone"
    _columns={
        'name':fields.char('Name',size=256),
        'code':fields.char('Code',size=128),
        'alt_code':fields.char('Alternative Code',size=128),
        'start_date':fields.date('Create Date'),
        'update_0':fields.date('First Update'),
        'update_1':fields.date('Second Update'),
        'update_2':fields.date('Third Update'),
        'update_3':fields.date('Fourth Update'),
        'zone_code':fields.char('Zone Code', size=128),
        'shape':fields.geo_multi_polygon('Shape'),
    }
コード例 #10
0
class ocs_district(geo_model.GeoModel):
    """ Contaihow to delete a field from parent class openerpns geografic information about localities"""
    _name = 'ocs.district'
    _order = 'name asc'
    _columns = {
        'code': fields.char('District Code',size=30),
        'name': fields.char('District Name',size=20),
        'geo_polygon':fields.geo_multi_polygon('Geometry'),
    }

    def neighborhood_ids(self, cr, uid, id, default=None, context=None):
        """Return a list with neighborhoods from the district uses a postgis query
        """
        #neighborhoods = self.pool.get('ocs.neighborhood').geo_search(cr, uid, geo_domain=[('geo_polygon', 'geo_intersect', {'ocs.district.geo_polygon': []})])
        query = 'SELECT DISTINCT(n.id) FROM ocs_neighborhood AS n, ocs_district AS d ' \
            "WHERE intersects(n.geo_polygon, d.geo_polygon) = TRUE AND d.id = {0};".format(id[0])
        cr.execute(query)
        n_ids = []
        for n_id in cr.fetchall():
            n_ids.append(n_id[0])
        return n_ids
コード例 #11
0
class urban_bridge_structure_element_value(geo_model.GeoModel):
    """
    EAV Value Definition for elements of Structure
    """
    _name = "urban_bridge.structure_element_value"
    _columns = {
        'element_id':
        fields.many2one('urban_bridge.structure_element',
                        'Element',
                        ondelete="cascade"),
        'element_attribute_id':
        fields.many2one('urban_bridge.structure_element_attribute',
                        'Attribute'),
        'value_integer':
        fields.integer('Integer'),
        'value_char':
        fields.char('Char', size=256),
        'value_date':
        fields.date('Date'),
        'value_datetime':
        fields.datetime('Date Time'),
        'value_text':
        fields.text('Text'),
        'value_float':
        fields.float('Float'),
        'value_bool':
        fields.boolean('Boolean'),
        'value_binary':
        fields.binary('Photo'),
        'value_selection':
        fields.char('Selection', size=10),
        'value_point':
        fields.geo_multi_point('Shape Point'),
        'value_line':
        fields.geo_multi_line('Shape Line'),
        'value_polygon':
        fields.geo_multi_polygon('Shape Polygon'),
    }
コード例 #12
0
ファイル: geo_npa.py プロジェクト: diassynthesis/geospatial
class NPA(geo_model.GeoModel):
    """GEO OSV SAMPLE"""
    def _get_ZIP_total_sales(self, cursor, uid, ids, name, args, context=None):
        """Return the total of the invoiced sales for this npa"""
        to_return = {}
        if not ids:
            return {}
        if not isinstance(ids, list):
            ids = [ids]
        inv_obj = self.pool.get('account.invoice')
        mach_obj = self.pool.get('geoengine.demo.automatic.retailing.machine')
        for zip_id in ids:
            res = mach_obj.geo_search(cursor,
                                      uid,
                                      domain=[],
                                      geo_domain=[('the_point',
                                                   'geo_intersect', {
                                                       'dummy.zip.the_geom':
                                                       [('id', '=', zip_id)]
                                                   })])

            if res:
                cursor.execute(
                    "SELECT sum(total_sales) from"
                    " geoengine_demo_automatic_retailing_machine where id in %s;",
                    (tuple(res), ))
                res = cursor.fetchone()
                if res:
                    to_return[zip_id] = res[0] or 0.0
                else:
                    to_return[zip_id] = 0.0
            else:
                to_return[zip_id] = 0.0
        return to_return

    _name = "dummy.zip"
    _columns = {
        'priority':
        fields.integer('Priority'),
        'name':
        fields.char('ZIP', size=64, required=True),
        'city':
        fields.char('City', size=64, required=True),
        'the_geom':
        fields.geo_multi_polygon('NPA Shape'),
        'total_sales':
        fields.function(_get_ZIP_total_sales,
                        method=True,
                        string='Spatial! Total Sales',
                        type='float'),
    }

    _defaults = {'priority': lambda *x: 100}

    def name_get(self, cursor, uid, ids, context=None):
        res = []
        for r in self.browse(cursor, uid, ids):
            res.append((r.id, u"%s %s" % (r.name, r.city)))
        return res

    def test_func(self, cursor, uid, ids):
        """Test function only use for devel. TO DELETE"""
        print 'a = self.browse(cursor, uid, 1)'
        a = self.browse(cursor, uid, 1)
        print 'print a.name'
        print a.name
        print 'a.the_geom.area'
        print a.the_geom.area
        print 'shape_a = wktloads(a.the_geom.wkt)'
        shape_a = wktloads(a.the_geom.wkt)
        print 'tmp1 = Polygon([(0, 0), (1, 1), (1, 0)])'
        tmp1 = Polygon([(0, 0), (1, 1), (1, 0)])
        print 'Polygon([(3, 0), (4, 1), (4, 0)])'
        tmp2 = Polygon([(3, 0), (4, 1), (4, 0)])
        print 'shape_b = MultiPolygon([tmp1, tmp2])'
        shape_b = MultiPolygon([tmp1, tmp2])
        print "a.write({'the_geom':shape_b})"
        a.write({'the_geom': shape_b})
        print "self.browse(cursor, uid, 1)"
        a = self.browse(cursor, uid, 1)
        print "print a.the_geom.wkt"
        print a.the_geom.wkt
        print "a.write({'the_geom':shape_b})"
        a.write({'the_geom': shape_b})
        print "a = self.browse(cursor, uid, 1)"
        a = self.browse(cursor, uid, 1)
        print "print a.the_geom"
        print a.the_geom
        print "a.write({'the_geom':shape_b.wkt})"
        a.write({'the_geom': shape_b.wkt})
        print "a = self.browse(cursor, uid, 1)"
        a = self.browse(cursor, uid, 1)
        print "print a.the_geom.wkt"
        print a.the_geom.wkt
        print "a.write({'the_geom':geojson.dumps(shape_a)})"
        a.write({'the_geom': geojson.dumps(shape_a)})
        print "a = self.browse(cursor, uid, 1)"
        a = self.browse(cursor, uid, 1)
        print "print a.the_geom.wkt"
        print a.the_geom.wkt
        b = self.create(cursor, uid, {
            'name': '1100',
            'city': 'lausanne',
            'the_geom': a.the_geom
        })
        b = self.browse(cursor, uid, b)
        #self.unlink(cursor, uid, [b.id])
        view_id = self.pool.get('ir.ui.view').search(
            cursor, uid, [('model', '=', 'dummy.zip'),
                          ('type', '=', 'geoengine')])[0]
        import pprint
        pprint.pprint(
            self.fields_view_get(cursor,
                                 uid,
                                 view_id=view_id,
                                 view_type='geoengine',
                                 context=None,
                                 toolbar=False,
                                 submenu=False))
        import pprint
        pprint.pprint(
            self.fields_view_get(cursor,
                                 uid,
                                 view_id=False,
                                 view_type='geoengine',
                                 context=None,
                                 toolbar=False,
                                 submenu=False))
        print self.geo_search(cursor,
                              uid,
                              domain=[('name', 'ilike', 'Lausanne')],
                              geo_domain=[('the_geom', 'geo_greater',
                                           Polygon([(3, 0), (4, 1), (4, 0)]))])
        print self.geo_search(cursor,
                              uid,
                              domain=[('name', 'ilike', 'Lausanne')],
                              geo_domain=[('the_geom', 'geo_greater', 0)])
        print self.geo_search(
            cursor,
            uid,
            domain=[('name', 'ilike', 'Lausanne')],
            geo_domain=[('the_geom', 'geo_intersect', {
                'geoengine.demo.automatic.retailing.machine.the_point': []
            })])
        print self.geo_search(
            cursor,
            uid,
            domain=[('name', 'ilike', 'Lausanne')],
            geo_domain=[('the_geom', 'geo_intersect', {
                'geoengine.demo.automatic.retailing.machine.the_point':
                [('name', '!=', 'Vallorbe')]
            })])
        return True
コード例 #13
0
class urban_bridge_bridge(geo_model.GeoModel):
    """ 
    Bridge Infraestructure Data
    """
    def _get_district(self, cr, uid, ids, fieldname, arg, context=None):
        res = {}
        #Este bloque try es porque a veces los datos vienen con inconsistencia topológica y se pretende evitar que deje de funcionar
        #la página cuando se manda el query, en ves de eso mejor que siga funcionando y deje un log de eventos
        for bridge in self.browse(cr, uid, ids, context=context):
            try:
                geom = bridge.shape.wkt
                districts = ""
                if geom != False:
                    if bridge.shape.is_valid:
                        query = "SELECT name FROM base_map_district WHERE st_intersects(shape,st_geomfromtext('{0}',900913)) = true".format(
                            geom)
                        cr.execute(query)
                        for row in cr.fetchall():
                            districts = row[0] + "," + districts
                res[bridge.id] = districts
            except Exception as e:
                _logger.debug("Geoprocessing error: {0}".format(e))
                res[bridge.id] = ""
        return res

    def _get_sub_district(self, cr, uid, ids, fieldname, arg, context=None):
        res = {}
        for bridge in self.browse(cr, uid, ids, context=context):
            try:
                geom = bridge.shape
                sub_districts = ""
                if geom != False:
                    if bridge.shape.is_valid:
                        query = "SELECT name FROM base_map_sub_district WHERE st_intersects(shape,st_geomfromtext('{0}',900913)) = true".format(
                            geom)
                        cr.execute(query)
                        for row in cr.fetchall():
                            sub_districts = row[0] + "," + sub_districts
                res[bridge.id] = sub_districts
            except Exception as ex:
                _logger.debug("Geoprocessing error: {0}".format(ex))
                res[bridge.id] = ""
        return res

    def _get_cadastral_zone(self, cr, uid, ids, fieldname, arg, context=None):
        res = {}
        for bridge in self.browse(cr, uid, ids, context=context):
            try:
                cad_zone = ""
                geom = bridge.shape
                if bridge.shape.is_valid:
                    if (geom != False):
                        query = "SELECT name FROM base_map_cadastral_zone WHERE st_intersects(shape,st_geomfromtext('{0}',900913)) = true".format(
                            geom)
                        cr.execute(query)
                        for row in cr.fetchall():
                            cad_zone = row[0] + "," + cad_zone
                res[bridge.id] = cad_zone
            except Exception as e:
                _logger.debug("Geoprocessing error: {0}".format(e))
                res[bridge.id] = ""
        return res

    def _get_micro_seismicity(self,
                              cr,
                              uid,
                              ids,
                              fieldname,
                              arg,
                              context=None):
        res = {}
        for bridge in self.browse(cr, uid, ids, context=context):
            try:
                micr_seism = ""
                geom = bridge.shape
                if geom != False:
                    if bridge.shape.is_valid:
                        query = "SELECT zone_name,micr_measure1 FROM base_map_micro_seismicity WHERE st_intersects(shape,st_geomfromtext('{0}',900913)) = true".format(
                            geom)
                        cr.execute(query)
                        for row in cr.fetchall():
                            micr_seism = row[0] + "-" + str(
                                row[1]) + "," + micr_seism
                res[bridge.id] = micr_seism
            except Exception as ex:
                _logger.debug("Geoprocessing error: {0}".format(ex))
                res[bridge.id] = ""
        return res

    def _get_area(self, cr, uid, ids, fieldname, arg, context=None):
        res = {}
        for bridge in self.browse(cr, uid, ids, context=context):
            try:
                bridge_id = bridge.id
                spatial_ref_sys = self.pool.get(
                    'ir.config_parameter').get_param(
                        cr,
                        uid,
                        'urban_bridge.local_spatial_reference',
                        default='',
                        context=context)
                query = """
                select st_area(pmagna) as area from (
                select st_transform(shape,%s) as pmagna from urban_bridge_bridge where id = %s
                ) as t1
                """
                cr.execute(query, (spatial_ref_sys, bridge_id))
                area = 0.0
                for row in cr.fetchall():
                    #Crear un diccionario para almacenar areas por
                    if row[0] != None:
                        area = float(row[0])
                res[bridge.id] = area
            except Exception as e:
                _logger.debug("Geoprocessing error: {0}".format(e))
                res[bridge.id] = ""
        return res

    def _get_perimeter(self, cr, uid, ids, fieldname, arg, context=None):
        res = {}
        for bridge in self.browse(cr, uid, ids, context=context):
            try:
                bridge_id = bridge.id
                spatial_ref_sys = self.pool.get(
                    'ir.config_parameter').get_param(
                        cr,
                        uid,
                        'urban_bridge.local_spatial_reference',
                        default='',
                        context=context)
                query = """
                select st_perimeter(pmagna) as area from (
                select st_transform(shape,%s) as pmagna from urban_bridge_bridge where id = %s
                ) as t1
                """
                cr.execute(query, (spatial_ref_sys, bridge_id))
                perimeter = 0.0
                for row in cr.fetchall():
                    #Crear un diccionario para almacenar areas por
                    if row[0] != None:
                        perimeter = float(row[0])
                res[bridge.id] = perimeter
            except Exception as e:
                _logger.debug("Geoprocessing error: {0}".format(e))
                res[bridge.id] = ""
        return res

    def web_service_save(self, cr, uid, data, context=None):
        #1.Check Geography Type-- and translate to multipoly
        #Geography come in geojsCheckliston
        try:
            jgeometry = data["shape"]
            geography = asShape(jgeometry)
            shape = ""
            if geography.geom_type == "Polygon":
                mpoly = MultiPolygon([geography])
                shape = mpoly.wkt
            else:
                shape = geography.wkt
            data["shape"] = shape
            #Check date
            if (data.has_key("construction_date")):
                construction_date = datetime.strptime(
                    data["construction_date"], "%Y-%m-%d %H:%M:%S")
                data["contruction_date"] = str(construction_date.date())
        except Exception as e:
            print e
        #2. Read Category Type
        if (data.has_key("structure_type")):
            structure_type_ids = self.pool.get(
                "urban_bridge.structure_type").search(
                    cr, uid, [('code', '=', data["structure_type"])])
        if structure_type_ids.__len__() == 0:
            return {'result': 'Error, Structure Type Code Not defined!'}
        else:
            data["structure_type"] = structure_type_ids[0]
        #3. Check if bridge_code Exist if does not exist then create, if exist update from code --
        search_result_ids = []
        if data.has_key("code"):
            search_result_ids = self.search(cr, uid,
                                            [('code', '=', data["code"])])
        try:
            if search_result_ids.__len__() == 0:
                #Create
                id_bridge = self.create(cr, uid, data)
                return {"result": "Insertion success ", "id": id_bridge}
            else:
                #If Update, only update Geography
                self.write(cr, uid, search_result_ids[0],
                           {"shape": data["shape"]})
                return {
                    "result":
                    "Geometry Update success! attributes does not modified!",
                    "id": search_result_ids[0]
                }
        except Exception as e:
            print e
            return {"result": "Save Failed!"}

    _name = "urban_bridge.bridge"
    _columns = {
        'shape':
        fields.geo_multi_polygon('Shape', help="Shape"),
        'code':
        fields.char('Bridge Code', size=128, help="Bridge Code"),
        'name':
        fields.char('Identifier', size=128, help="Identifier"),
        'classification':
        fields.selection([('PPC', 'PPC'), ('PPE', 'PPE'), ('PVC', 'PVC'),
                          ('PVE', 'PVE')], 'Bridge Classification'),
        'structure_type':
        fields.many2one('urban_bridge.structure_type',
                        'Bridge Type',
                        required=True),
        'address':
        fields.char('Bridge Address', size=256),
        'last_address':
        fields.char('Last Address', size=256),
        'construction_date':
        fields.date('Construction Date'),
        'inventory_date':
        fields.date('Inventory Date'),
        'length':
        fields.float('Total Length'),
        'width':
        fields.float('Total Width'),
        'superstructure_area':
        fields.float('Bridge Super-Structure Area'),
        'vertical_gauge':
        fields.float('Vertical Gauge'),
        'horizontal_gauge':
        fields.float('Horizontal Gauge'),
        'design_load_capacity':
        fields.float('Design Load Capacity'),
        'level':
        fields.selection([('-2', '-2'), ('-1', '-1'), ('0', '0'), ('1', '1'),
                          ('2', '2'), ('3', '3'), ('4', '4')], 'Bridge Level'),
        'structure_material':
        fields.many2one('urban_bridge.structure_material',
                        'Structure Materials'),
        'design_load_code':
        fields.many2one('urban_bridge.design_load_code', 'Design Load Code'),
        'photo':
        fields.binary('Photo'),
        'geological_zone':
        fields.many2one('base_map.geological_zone', 'Geological Zone'),
        'district':
        fields.function(_get_district,
                        string='Districts',
                        method=True,
                        type="char"),
        'sub_district':
        fields.function(_get_sub_district,
                        string='Sub Districts',
                        method=True,
                        type="char"),
        'cadastral_zone':
        fields.function(_get_cadastral_zone,
                        string="Cadastral Zone",
                        method=True,
                        type="char"),
        'micro_seismicity':
        fields.function(_get_micro_seismicity,
                        string="Micro-Seismicity",
                        method=True,
                        type="char"),
        'calc_area':
        fields.function(_get_area,
                        string="Calculated Area",
                        method=True,
                        type="float"),
        'calc_perimeter':
        fields.function(_get_perimeter,
                        string="Calculated Perimeter",
                        method=True,
                        type="float"),
        'elements':
        fields.one2many('urban_bridge.structure_element', 'bridge_id',
                        'Elements'),
        'survey_id':
        fields.one2many('urban_bridge.inspection_survey', 'bridge_id',
                        'Inspection Survey'),
        'state':
        fields.selection([('draft', 'Draft'), ('updated', 'Updated'),
                          ('maintenance', 'Maintenance'),
                          ('warranty', 'Warranty')], 'State'),
    }

    _sql_contraints = [
        ('cc_bridge_code_unique', 'unique(code)',
         '¡Bridge Code must be unique!'),
    ]