def spatop_connect_unconnected_assets(params):
            with self.flask_app.app_context():
                print(params)
                connect_asset_type = params["connect_asset_type"]
                connect_to_asset_type = params["connect_to_asset_type"]

                esh = get_handler()
                active_es_id = get_session('active_es_id')
                es = esh.get_energy_system(active_es_id)

                # Collect all assets of the required types
                connect_asset_list = list()
                connect_to_asset_list = list()
                for c in es.eAllContents():
                    if type(c).__name__ == connect_asset_type:
                        connect_asset_list.append(c)
                    if type(c).__name__ == connect_to_asset_type:
                        connect_to_asset_list.append(c)

                connections_list = list()
                # Iterate over connect_asset_list
                for c in connect_asset_list:
                    # TODO: fix assume one port
                    port_c = c.port[0]

                    if not port_c.connectedTo:
                        shape_c = Shape.create(c.geometry)
                        min_distance = 1e99
                        closest_ct = None

                        # Find closest asset to connect to
                        for ct in connect_to_asset_list:
                            shape_ct = Shape.create(ct.geometry)
                            if shape_ct.shape.distance(shape_c.shape) < min_distance:
                                min_distance = shape_ct.shape.distance(shape_c.shape)
                                closest_ct = ct

                        # Determine the type of port to connect to
                        if type(port_c) == esdl.InPort:
                            find_port_type = esdl.OutPort
                        else:
                            find_port_type = esdl.InPort

                        # Find first port that matches criteria
                        for p in closest_ct.port:
                            if isinstance(p, find_port_type):
                                p.connectedTo.append(port_c)

                                pct_coord = get_asset_and_coord_from_port_id(esh, active_es_id, p.id)['coord']
                                pc_coord = get_asset_and_coord_from_port_id(esh, active_es_id, port_c.id)['coord']

                                connections_list.append \
                                    ({'from-port-id': port_c.id, 'from-asset-id': c.id,
                                      'from-asset-coord': pc_coord,
                                      'to-port-id': p.id, 'to-asset-id': closest_ct.id,
                                      'to-asset-coord': pct_coord})
                                break

                emit('add_connections', {'es_id': active_es_id, 'conn_list': connections_list})
Exemple #2
0
    def newPiece(self):
        '''creates a new shape'''

        self.curPiece = Shape()
        self.curPiece.setRandomShape()
        self.curX = Board.BoardWidth // 2 + 1
        self.curY = Board.BoardHeight - 1 + self.curPiece.minY()

        if not self.tryMove(self.curPiece, self.curX, self.curY):
            self.curPiece.setShape(Tetrominoe.NoShape)
            self.timer.stop()
            self.isStarted = False
            self.msg2Statusbar.emit("Press Up to Restart")
 def add_boundary_to_shape_list(shape_list, area_id, boundary):
     sh = Shape.parse_geojson_geometry(boundary['geom'])
     num_sub_polygons = len(sh.shape.geoms)
     for i, pol in enumerate(sh.shape.geoms):
         if num_sub_polygons > 1:
             area_id_number = " ({} of {})".format(i + 1, num_sub_polygons)
         else:
             area_id_number = ""
         shape_polygon = Shape.create(pol)
         if shape_polygon.shape.area > 0.0001:
             shape_list.append({
                 'id': area_id + area_id_number,
                 'shape': shape_polygon,
             })
Exemple #4
0
    def __init__(self):
        self.right = False
        self.left = False
        self.down = False
        self.rotate_right = False
        self.rotate_left = False
        self.drop = False

        self.grid = Grid(10, 20, 20)
        self.shape = Shape(self.grid)
        self.shape_list = []

        for x in range(3):
            self.shape_list.insert(0, Shape(self.grid))
    def preprocess_area(self, area):
        user = get_session('user-email')
        year = self.boundary_service_instance.get_user_setting(user, 'boundaries_year')

        sub_area_shape_list = list()
        top_area_shape = list()
        if year and area.id and area.scope.name != 'UNDEFINED':
            if is_valid_boundary_id(area.id):
                boundary = self.boundary_service_instance.get_boundary_from_service(year, area.scope, str.upper(area.id))
                top_area_shape = Shape.parse_geojson_geometry(boundary['geom'])

                for ar in area.area:
                    if ar.id and ar.scope.name != 'UNDEFINED':
                        if is_valid_boundary_id(ar.id):
                            boundary = self.boundary_service_instance.get_boundary_from_service(year, ar.scope, str.upper(ar.id))
                            self.add_boundary_to_shape_list(sub_area_shape_list, ar.id, boundary)

        set_session('sub_area_shape_list', sub_area_shape_list)
        set_session('top_area_shape', top_area_shape)
        return len(sub_area_shape_list)
        def spatop_joint_middle_subarea():
            with self.flask_app.app_context():
                esh = get_handler()
                active_es_id = get_session('active_es_id')
                es = esh.get_energy_system(active_es_id)
                area = es.instance[0].area

                sub_area_shape_list = get_session('sub_area_shape_list')

                asset_to_ui_list = list()
                for ar in sub_area_shape_list:
                    shape = ar['shape']
                    id = ar['id']
                    if isinstance(shape.shape, Polygon):
                        # Calculate the center of the area
                        centroid = shape.shape.centroid
                        sh_centroid = Shape.create(centroid)
                        ar['shape_centroid'] = sh_centroid
                        ar['shape_centroid_wkt'] = sh_centroid.get_wkt()
                        esdl_centroid = sh_centroid.get_esdl()

                        # Generate a Joint at the center of the area
                        joint = esdl.Joint(id=str(uuid.uuid4()),name="Joint: "+id)
                        joint.geometry = esdl_centroid
                        joint.port.append(esdl.InPort(id=str(uuid.uuid4()), name="In"))
                        joint.port.append(esdl.OutPort(id=str(uuid.uuid4()), name="Out"))
                        area.asset.append(joint)
                        esh.add_object_to_dict(active_es_id, joint, recursive=True)
                        # Mapping to ESDL object, such that connecting can be done easily later on
                        ar['esdl_joint'] = joint

                        asset_to_ui, conn_list_to_ui = energy_asset_to_ui(esh, active_es_id, joint)
                        asset_to_ui_list.append(asset_to_ui)

                # Update the UI
                emit("add_esdl_objects", {
                    "es_id": active_es_id,
                    "asset_pot_list": asset_to_ui_list,
                    "zoom": False,
                 })
        def spatop_joint_delaunay():
            with self.flask_app.app_context():
                esh = get_handler()
                active_es_id = get_session('active_es_id')
                es = esh.get_energy_system(active_es_id)
                area = es.instance[0].area

                list_of_shapely_points = list()         # to feed the delaunay triangulation algorithm
                mapping_centroid_wkt_to_joint = dict()  # to find the joints at both sides of all edges

                for obj in area.eAllContents():
                    if isinstance(obj, esdl.Joint):
                        geom = obj.geometry
                        sh_geom = Shape.create(geom)
                        list_of_shapely_points.append(sh_geom.shape)
                        mapping_centroid_wkt_to_joint[sh_geom.get_wkt()] = obj

                if len(list_of_shapely_points):
                    shapely_multipoint = MultiPoint(list_of_shapely_points)
                    edges = triangulate(shapely_multipoint, edges=True)

                    self.create_pipes(edges, None, mapping_centroid_wkt_to_joint)
Exemple #8
0
class Board(QFrame):
    msg2Statusbar = pyqtSignal(str)

    BoardWidth = 10
    BoardHeight = 22
    Speed = 300

    def __init__(self, parent):
        super().__init__(parent)

        self.initBoard()

    def initBoard(self):
        '''initiates board'''

        self.timer = QBasicTimer()
        self.isWaitingAfterLine = False

        self.curX = 0
        self.curY = 0
        self.numLinesRemoved = 0
        self.board = []

        self.setFocusPolicy(Qt.StrongFocus)
        self.isStarted = False
        self.isPaused = False
        self.clearBoard()

    def drawVerticalLines(self, painter):
        pen = QPen(Qt.black, 2, Qt.DotLine)
        painter.setPen(pen)

        # TODO the drawing things

    def shapeAt(self, x, y):
        '''determines shape at the board position'''

        return self.board[(y * Board.BoardWidth) + x]

    def setShapeAt(self, x, y, shape):
        '''sets a shape at the board'''

        self.board[(y * Board.BoardWidth) + x] = shape

    def squareWidth(self):
        '''returns the width of one square'''

        return self.contentsRect().width() // Board.BoardWidth

    def squareHeight(self):
        '''returns the height of one square'''

        return self.contentsRect().height() // Board.BoardHeight

    def start(self):
        """starts game"""

        if self.isPaused:
            return

        self.isStarted = True
        self.isWaitingAfterLine = False
        self.numLinesRemoved = 0
        self.clearBoard()

        self.msg2Statusbar.emit(str(self.numLinesRemoved))

        self.newPiece()
        self.timer.start(Board.Speed, self)

    def pause(self):
        '''pauses game'''

        if not self.isStarted:
            return

        self.isPaused = not self.isPaused

        if self.isPaused:
            self.timer.stop()
            self.msg2Statusbar.emit("paused")

        else:
            self.timer.start(Board.Speed, self)
            self.msg2Statusbar.emit(str(self.numLinesRemoved))

        self.update()

    def paintEvent(self, event):
        '''paints all shapes of the game'''

        painter = QPainter(self)
        rect = self.contentsRect()
        self.drawVerticalLines(painter)

        boardTop = rect.bottom() - Board.BoardHeight * self.squareHeight()

        for i in range(Board.BoardHeight):
            for j in range(Board.BoardWidth):
                shape = self.shapeAt(j, Board.BoardHeight - i - 1)

                if shape != Tetrominoe.NoShape:
                    self.drawSquare(painter,
                                    rect.left() + j * self.squareWidth(),
                                    boardTop + i * self.squareHeight(), shape)

        if self.curPiece.shape() != Tetrominoe.NoShape:

            for i in range(4):
                x = self.curX + self.curPiece.x(i)
                y = self.curY - self.curPiece.y(i)
                self.drawSquare(
                    painter,
                    rect.left() + x * self.squareWidth(), boardTop +
                    (Board.BoardHeight - y - 1) * self.squareHeight(),
                    self.curPiece.shape())

    def keyPressEvent(self, event):
        """processes key press events"""

        key = event.key()

        if not self.isStarted or self.curPiece.shape() == Tetrominoe.NoShape:
            if key == Qt.Key_Up:
                self.initBoard()
                self.start()
                return
            super(Board, self).keyPressEvent(event)
            return

        if key == Qt.Key_Space:
            self.pause()
            return

        if self.isPaused:
            return

        elif key == Qt.Key_Left:
            self.tryMove(self.curPiece, self.curX - 1, self.curY)

        elif key == Qt.Key_Right:
            self.tryMove(self.curPiece, self.curX + 1, self.curY)

        elif key == Qt.Key_Down:
            self.dropDown()

        elif key == Qt.Key_A:
            self.tryMove(self.curPiece.rotate_left(), self.curX, self.curY)

        elif key == Qt.Key_D:
            self.tryMove(self.curPiece.rotateRight(), self.curX, self.curY)

        elif key == Qt.Key_3:
            # line shape
            self.curPiece.setShape(3)

        elif key == Qt.Key_0:
            self.curPiece.setShape(0)

        else:
            super(Board, self).keyPressEvent(event)

    def timerEvent(self, event):
        '''handles timer event'''

        if event.timerId() == self.timer.timerId():

            if self.isWaitingAfterLine:
                self.isWaitingAfterLine = False
                self.newPiece()
            else:
                self.oneLineDown()

        else:
            super(Board, self).timerEvent(event)

    def clearBoard(self):
        '''clears shapes from the board'''

        for i in range(Board.BoardHeight * Board.BoardWidth):
            self.board.append(Tetrominoe.NoShape)

    def dropDown(self):
        '''drops down a shape'''

        newY = self.curY

        while newY > 0:

            if not self.tryMove(self.curPiece, self.curX, newY - 1):
                break

            newY -= 1

        self.pieceDropped()

    def oneLineDown(self):
        '''goes one line down with a shape'''

        if not self.tryMove(self.curPiece, self.curX, self.curY - 1):
            self.pieceDropped()

    def pieceDropped(self):
        '''after dropping shape, remove full lines and create new shape'''

        for i in range(4):
            x = self.curX + self.curPiece.x(i)
            y = self.curY - self.curPiece.y(i)
            self.setShapeAt(x, y, self.curPiece.shape())

        self.removeFullLines()

        if not self.isWaitingAfterLine:
            self.newPiece()

    def removeFullLines(self):
        '''removes all full lines from the board'''

        numFullLines = 0
        rowsToRemove = []

        for i in range(Board.BoardHeight):

            n = 0
            for j in range(Board.BoardWidth):
                if not self.shapeAt(j, i) == Tetrominoe.NoShape:
                    n = n + 1

            if n == 10:
                rowsToRemove.append(i)

        rowsToRemove.reverse()

        for m in rowsToRemove:

            for k in range(m, Board.BoardHeight):
                for l in range(Board.BoardWidth):
                    self.setShapeAt(l, k, self.shapeAt(l, k + 1))

        numFullLines = numFullLines + len(rowsToRemove)

        if numFullLines > 0:
            self.numLinesRemoved = self.numLinesRemoved + numFullLines
            self.msg2Statusbar.emit(str(self.numLinesRemoved))

            self.isWaitingAfterLine = True
            self.curPiece.setShape(Tetrominoe.NoShape)
            self.update()

    def newPiece(self):
        '''creates a new shape'''

        self.curPiece = Shape()
        self.curPiece.setRandomShape()
        self.curX = Board.BoardWidth // 2 + 1
        self.curY = Board.BoardHeight - 1 + self.curPiece.minY()

        if not self.tryMove(self.curPiece, self.curX, self.curY):
            self.curPiece.setShape(Tetrominoe.NoShape)
            self.timer.stop()
            self.isStarted = False
            self.msg2Statusbar.emit("Press Up to Restart")

    def tryMove(self, newPiece, newX, newY):
        '''tries to move a shape'''

        for i in range(4):

            x = newX + newPiece.x(i)
            y = newY - newPiece.y(i)

            if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:
                return False

            if self.shapeAt(x, y) != Tetrominoe.NoShape:
                return False

        self.curPiece = newPiece
        self.curX = newX
        self.curY = newY
        self.update()

        return True

    def drawSquare(self, painter, x, y, shape):
        '''draws a square of a shape'''

        colorTable = [
            0x000000, 0xCC6666, 0x66CC66, 0x6666CC, 0xCCCC66, 0xCC66CC,
            0x66CCCC, 0xDAAA00
        ]

        color = QColor(colorTable[shape])
        painter.fillRect(x + 1, y + 1,
                         self.squareWidth() - 2,
                         self.squareHeight() - 2, color)

        painter.setPen(color.lighter())
        painter.drawLine(x, y + self.squareHeight() - 1, x, y)
        painter.drawLine(x, y, x + self.squareWidth() - 1, y)

        painter.setPen(color.darker())
        painter.drawLine(x + 1, y + self.squareHeight() - 1,
                         x + self.squareWidth() - 1,
                         y + self.squareHeight() - 1)
        painter.drawLine(x + self.squareWidth() - 1,
                         y + self.squareHeight() - 1,
                         x + self.squareWidth() - 1, y + 1)
Exemple #9
0
from src.pipeline import Pipeline
import OpenGL.GL as gl
from src.shape import Shape
import numpy

print("Numpy: {:s}".format(numpy.__version__))

# fg = FrameGrabber()
shape = Shape()
pipeline = Pipeline(shape, None)
pipeline.loadShaderFile('shaders/diffuse.vert', gl.GL_VERTEX_SHADER)
pipeline.loadShaderFile('shaders/diffuse.frag', gl.GL_FRAGMENT_SHADER)
pipeline.initGl()
pipeline.sendData()


pipeline.run()

# fg.finish()
Exemple #10
0
class PlayState(State):
    def __init__(self):
        self.right = False
        self.left = False
        self.down = False
        self.rotate_right = False
        self.rotate_left = False
        self.drop = False

        self.grid = Grid(10, 20, 20)
        self.shape = Shape(self.grid)
        self.shape_list = []

        for x in range(3):
            self.shape_list.insert(0, Shape(self.grid))

    def next_shape(self):
        self.shape = self.shape_list.pop()
        self.shape_list.insert(0, Shape(self.grid))

    def reset_input(self):
        self.right = False
        self.left = False
        self.down = False
        self.rotate_right = False
        self.rotate_left = False
        self.drop = False

    def input(self, engine, events):
        self.reset_input()
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                    self.left = True
                if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    self.right = True
                if event.key == pygame.K_DOWN or event.key == pygame.K_s:
                    self.down = True
                if event.key == pygame.K_UP or event.key == pygame.K_w or event.key == pygame.K_x:
                    self.rotate_right = True
                if event.key == pygame.K_z:
                    self.rotate_left = True
                if event.key == pygame.K_SPACE:
                    self.drop = True

    def update(self, engine, delta_time):

        if self.drop:
            print(self.drop)
            loaded_shape = self.shape.load_shape()
            self.shape.color = loaded_shape[0]
            self.shape.nodes = loaded_shape[1]
            self.drop = False

    def render(self, engine, surface):
        # for y in range(20):
        #     for x in range(10):
        #         if self.grid[x][y]:
        #             pass

        for cell in self.shape.nodes:
            pygame.draw.rect(surface, self.shape.color,
                             (self.shape.get_node_coordinate(cell).x,
                              self.shape.get_node_coordinate(cell).y, 20, 20),
                             0)
Exemple #11
0
 def next_shape(self):
     self.shape = self.shape_list.pop()
     self.shape_list.insert(0, Shape(self.grid))
from src.shape import Shape
from esdl.esdl_handler import EnergySystemHandler

esh = EnergySystemHandler()
esh.load_file('Nesselande contour warmtenet.esdl')
# esh.load_file('Arnhem Schuytgraaf contour warmtenet.esdl')

es = esh.get_energy_system()
polygon = es.instance[0].area.area[0].geometry

shape = Shape.create(polygon)
print(shape.get_wkt())

def find_area_info_geojson(area_list, pot_list, this_area):
    area_id = this_area.id
    area_name = this_area.name
    if not area_name: area_name = ""
    area_scope = this_area.scope
    area_geometry = this_area.geometry

    user = get_session('user-email')
    user_settings = BoundaryService.get_instance().get_user_settings(user)
    boundaries_year = user_settings['boundaries_year']

    geojson_KPIs = {}
    area_KPIs = this_area.KPIs
    if area_KPIs:
        for kpi in area_KPIs.kpi:
            if not isinstance(kpi, esdl.DistributionKPI):
                geojson_KPIs[kpi.name] = kpi.value

    area_shape = None

    if area_geometry:
        if isinstance(area_geometry, esdl.Polygon):
            shape_polygon = Shape.create(area_geometry)
            area_list.append(shape_polygon.get_geojson_feature({
                "id": area_id,
                "name": area_name,
                "KPIs": geojson_KPIs
            }))
            area_shape = shape_polygon
        if isinstance(area_geometry, esdl.MultiPolygon):
            boundary_wgs = ESDLGeometry.create_boundary_from_geometry(area_geometry)
            shape_multipolygon = Shape.parse_geojson_geometry(boundary_wgs)
            num_sub_polygons = len(shape_multipolygon.shape.geoms)
            for i, pol in enumerate(shape_multipolygon.shape.geoms):
                if num_sub_polygons > 1:
                    area_id_number = " ({} of {})".format(i + 1, num_sub_polygons)
                else:
                    area_id_number = ""
                shape_polygon = Shape.create(pol)
                area_list.append(shape_polygon.get_geojson_feature({
                    "id": str.upper(area_id) + area_id_number,
                    "name": area_name,
                    "KPIs": geojson_KPIs
                }))
            area_shape = shape_multipolygon
        if isinstance(area_geometry, esdl.WKT):
            shape_wkt = Shape.create(area_geometry)
            area_list.append(shape_wkt.get_geojson_feature({
                "id": area_id,
                "name": area_name,
                "KPIs": geojson_KPIs
            }))
            area_shape = shape_wkt
    else:
        if area_id and area_scope.name != 'UNDEFINED':
            if is_valid_boundary_id(area_id):
                # print('Retrieve boundary from boundary service')
                boundary_wgs = BoundaryService.get_instance().get_boundary_from_service(boundaries_year, area_scope, str.upper(area_id))
                if boundary_wgs:
                    sh = Shape.parse_geojson_geometry(boundary_wgs['geom'])
                    num_sub_polygons = len(sh.shape.geoms)
                    for i, pol in enumerate(sh.shape.geoms):
                        if num_sub_polygons > 1:
                            area_id_number = " ({} of {})".format(i + 1, num_sub_polygons)
                        else:
                            area_id_number = ""
                        shape_polygon = Shape.create(pol)
                        area_list.append(shape_polygon.get_geojson_feature({
                            "id": str.upper(area_id) + area_id_number,
                            "name": boundary_wgs['name'],
                            "KPIs": geojson_KPIs
                        }))

                    area_shape = sh

    # assign random coordinates if boundary is given and area contains assets without coordinates
    # and gives assets within buildings a proper coordinate
    if area_shape:
        update_asset_geometries_shape(this_area, area_shape)

    potentials = this_area.potential
    for potential in potentials:
        potential_geometry = potential.geometry
        potential_name = potential.name
        if not potential_name:
            potential_name = ""
        if potential_geometry:
            if isinstance(potential_geometry, esdl.WKT):
                shape = Shape.create(potential_geometry)
                pot_list.append(shape.get_geojson_feature({
                    "id": potential.id,
                    "name": potential_name,
                }))

    for area in this_area.area:
        find_area_info_geojson(area_list, pot_list, area)
from src.shape import Shape

wkt_geom_coll = "GEOMETRYCOLLECTION(MULTIPOLYGON(((181500 608151.670900693,181500 608440.329099307,181750 608584.670900693,182000 608440.329099307,182000 608151.670900693,181750 608007.329099307,181500 608151.670900693))),MULTIPOLYGON(((182000 608151.670900693,182000 608440.329099307,182250 608584.670900693,182500 608440.329099307,182500 608151.670900693,182250 608007.329099307,182000 608151.670900693))),MULTIPOLYGON(((181000 608151.670900693,181000 608440.329099307,181250 608584.670900693,181500 608440.329099307,181500 608151.670900693,181250 608007.329099307,181000 608151.670900693))))"
crs = "EPSG:28992"

if __name__ == '__main__':

    shp = Shape.parse_wkt(wkt_geom_coll, crs)

    print(shp.get_geojson_feature())
        def get_boundary_info(info):
            print('get_boundary_info:')
            print(info)

            user = get_session('user-email')
            user_settings = self.get_user_settings(user)
            boundaries_year = user_settings['boundaries_year']

            shape_dictionary = get_session('shape_dictionary')
            if not shape_dictionary:
                shape_dictionary = {}

            identifier = info["identifier"]
            toparea_name = info["toparea_name"]
            scope = info["scope"]
            subscope_enabled = info["subscope_enabled"]
            subscope = info["subscope"]
            select_subareas = info["select_subareas"]
            selected_subareas = info["selected_subareas"]
            initialize_ES = info["initialize_ES"]
            add_boundary_to_ESDL = info["add_boundary_to_ESDL"]

            if not is_valid_boundary_id(identifier):
                send_alert(
                    "Not a valid identifier. Try identifiers like PV27 (Noord-Holland) or GM0060 (Ameland)"
                )
                return

            active_es_id = get_session('active_es_id')
            esh = get_handler()
            es_edit = esh.get_energy_system(es_id=active_es_id)
            instance = es_edit.instance
            area = instance[0].area

            area_list = []
            boundary = None
            if subscope_enabled:
                self.__preload_subboundaries_in_cache(
                    boundaries_year,
                    esdl.AreaScopeEnum.from_string(str.upper(scope)),
                    esdl.AreaScopeEnum.from_string(str.upper(subscope)),
                    str.upper(identifier))
            else:
                boundary = self.get_boundary_from_service(
                    boundaries_year,
                    esdl.AreaScopeEnum.from_string(str.upper(scope)),
                    str.upper(identifier))
                if boundary:
                    geom = boundary['geom']
                    # geometry = ESDLGeometry.create_geometry_from_geom()

                    shape = Shape.parse_geojson_geometry(boundary['geom'])
                    if shape:
                        shape_dictionary[identifier] = shape

                    for i in range(0, len(geom['coordinates'])):
                        if len(geom['coordinates']) > 1:
                            area_id_number = " ({} of {})".format(
                                i + 1, len(geom['coordinates']))
                        else:
                            area_id_number = ""
                        area_list.append({
                            "type": "Feature",
                            "geometry": {
                                "type": "Polygon",
                                "coordinates": geom['coordinates'][i]
                            },
                            "properties": {
                                "id": area.id + area_id_number,
                                "name": area.name,
                                "KPIs": []
                            }
                        })

            if initialize_ES:
                # change ID, name and scope of ES
                if select_subareas:
                    area.id = "part of " + identifier
                else:
                    area.id = identifier

                # Area ID has changed, re-add to dictionairy
                esh.add_object_to_dict(active_es_id, area)

                area.scope = esdl.AreaScopeEnum.from_string(str.upper(scope))
                area.name = toparea_name
                if add_boundary_to_ESDL:
                    # returns boundary: { type: '', boundary: [[[[ ... ]]]] } (multipolygon in RD)
                    if not boundary:  # check if already requested
                        boundary = self.get_boundary_from_service(
                            boundaries_year,
                            esdl.AreaScopeEnum.from_string(str.upper(scope)),
                            str.upper(identifier))
                    if boundary:
                        geometry = ESDLGeometry.create_geometry_from_geom(
                            boundary['geom'])
                        area.geometry = geometry

                        shape = Shape.parse_geojson_geometry(boundary['geom'])
                        if shape:
                            shape_dictionary[identifier] = shape

                    # boundary = get_boundary_from_service(area_scope, area_id)
                    # if boundary:
                    #    emit('area_boundary', {'info-type': 'MP-RD', 'crs': 'RD', 'boundary': boundary})

            if subscope_enabled:
                boundaries = self.__get_subboundaries_from_service(
                    boundaries_year,
                    esdl.AreaScopeEnum.from_string(str.upper(scope)),
                    esdl.AreaScopeEnum.from_string(str.upper(subscope)),
                    str.upper(identifier))
                # result (boundaries) is an ARRAY of:
                # {'code': 'BU00140500', 'geom': '{"type":"MultiPolygon","bbox":[...],"coordinates":[[[[6.583651,53.209594],
                # [6.58477,...,53.208816],[6.583651,53.209594]]]]}'}

                if not boundaries:
                    send_alert(
                        'Error processing boundary information or no boundary information returned'
                    )

                for boundary in boundaries:
                    geom = None
                    try:
                        # geom = json.loads(boundary["geom"])
                        geom = boundary["geom"]

                        shape = Shape.parse_geojson_geometry(boundary['geom'])
                        if shape:
                            shape_dictionary[boundary['code']] = shape
                    except Exception as e:
                        print(
                            'Error parsing JSON from GEIS boundary service: ' +
                            str(e))

                    if geom:
                        skip_subarea = False
                        if select_subareas and selected_subareas and boundary[
                                "code"] not in selected_subareas:
                            skip_subarea = True

                        if not skip_subarea:
                            sub_area_id = boundary["code"]
                            sub_area_name = boundary["name"]

                            if initialize_ES:
                                sub_area = esdl.Area()
                                sub_area.id = sub_area_id
                                sub_area.name = sub_area_name
                                sub_area.scope = esdl.AreaScopeEnum.from_string(
                                    str.upper(subscope))

                                if add_boundary_to_ESDL:
                                    geometry = ESDLGeometry.create_geometry_from_geom(
                                        geom)
                                    sub_area.geometry = geometry

                                area.area.append(sub_area)
                                esh.add_object_to_dict(active_es_id, sub_area)

                            for i in range(0, len(geom['coordinates'])):
                                if len(geom['coordinates']) > 1:
                                    area_id_number = " ({} of {})".format(
                                        i + 1, len(geom['coordinates']))
                                else:
                                    area_id_number = ""
                                area_list.append({
                                    "type": "Feature",
                                    "geometry": {
                                        "type": "Polygon",
                                        "coordinates": geom['coordinates'][i]
                                    },
                                    "properties": {
                                        "id": sub_area_id + area_id_number,
                                        "name": sub_area_name,
                                        "KPIs": []
                                    }
                                })

            set_session('shape_dictionary', shape_dictionary)
            emit('geojson', {"layer": "area_layer", "geojson": area_list})
            print('Ready processing boundary information')
from src.process_es_area_bld import calc_possible_locations_in_area
from src.shape import Shape

if __name__ == '__main__':
    polygon = Shape.create([[{
        'lat': 53.24903770374274,
        'lng': 6.07997256161518
    }, {
        'lat': 53.00200032254604,
        'lng': 6.036034118922504
    }, {
        'lat': 52.98548065305836,
        'lng': 6.431480103156676
    }, {
        'lat': 53.216181402122956,
        'lng': 6.404018576473748
    }]])

    loc_list = calc_possible_locations_in_area(polygon, 10)
    for loc in loc_list:
        print(list(loc.coords))
Exemple #17
0
def find_area_info_geojson(area_list, pot_list, this_area, shape_dictionary):
    area_id = this_area.id
    area_name = this_area.name
    if not area_name: area_name = ""
    area_scope = this_area.scope
    area_geometry = this_area.geometry

    user = get_session('user-email')
    user_settings = BoundaryService.get_instance().get_user_settings(user)
    boundaries_year = user_settings['boundaries_year']

    geojson_KPIs = {}
    geojson_dist_kpis = {}
    area_KPIs = this_area.KPIs
    if area_KPIs:
        for kpi in area_KPIs.kpi:
            if not isinstance(kpi, esdl.DistributionKPI):
                kpi_qau = kpi.quantityAndUnit
                if kpi_qau:
                    if isinstance(kpi_qau, esdl.QuantityAndUnitReference):
                        kpi_qau = kpi_qau.reference

                    if not kpi_qau:  # Reference field in the ESDL could be "" (but should never be)
                        unit = ''
                    else:
                        unit = ESDLQuantityAndUnits.unit_to_string(kpi_qau)
                else:
                    unit = ''
                geojson_KPIs[kpi.name] = {'value': kpi.value, 'unit': unit}
            else:
                geojson_dist_kpis[kpi.name] = {
                    "type": "distributionKPI",
                    "value": []
                }
                for str_val in kpi.distribution.stringItem:
                    geojson_dist_kpis[kpi.name]["value"].append({
                        "name":
                        str_val.label,
                        "value":
                        str_val.value
                    })

                if area_geometry:
                    shape = Shape.create(area_geometry)
                    geojson_dist_kpis[kpi.name]["location"] = [
                        shape.shape.centroid.coords.xy[1][0],
                        shape.shape.centroid.coords.xy[0][0]
                    ]
                else:
                    geojson_dist_kpis[kpi.name]["location"] = None

    area_shape = None

    if area_geometry:
        if isinstance(area_geometry, esdl.Polygon):
            shape_polygon = Shape.create(area_geometry)
            area_list.append(
                shape_polygon.get_geojson_feature({
                    "id":
                    area_id,
                    "name":
                    area_name,
                    "KPIs":
                    geojson_KPIs,
                    "dist_KPIs":
                    geojson_dist_kpis
                }))
            area_shape = shape_polygon
        if isinstance(area_geometry, esdl.MultiPolygon):
            boundary_wgs = ESDLGeometry.create_boundary_from_geometry(
                area_geometry)
            shape_multipolygon = Shape.parse_geojson_geometry(boundary_wgs)
            num_sub_polygons = len(shape_multipolygon.shape.geoms)
            for i, pol in enumerate(shape_multipolygon.shape.geoms):
                if num_sub_polygons > 1:
                    area_id_number = " ({} of {})".format(
                        i + 1, num_sub_polygons)
                else:
                    area_id_number = ""
                shape_polygon = Shape.create(pol)
                area_list.append(
                    shape_polygon.get_geojson_feature({
                        "id":
                        area_id + area_id_number,
                        "name":
                        area_name,
                        "KPIs":
                        geojson_KPIs,
                        "dist_KPIs":
                        geojson_dist_kpis
                    }))
            area_shape = shape_multipolygon
        if isinstance(area_geometry, esdl.WKT):
            shape_wkt = Shape.create(area_geometry)
            area_list.append(
                shape_wkt.get_geojson_feature({
                    "id": area_id,
                    "name": area_name,
                    "KPIs": geojson_KPIs
                }))
            area_shape = shape_wkt
    else:
        if area_id and area_scope.name != 'UNDEFINED':
            if is_valid_boundary_id(area_id):
                # print('Retrieve boundary from boundary service')
                boundary_wgs = BoundaryService.get_instance(
                ).get_boundary_from_service(boundaries_year, area_scope,
                                            str.upper(area_id))
                if boundary_wgs:
                    sh = Shape.parse_geojson_geometry(boundary_wgs['geom'])
                    num_sub_polygons = len(sh.shape.geoms)
                    for i, pol in enumerate(sh.shape.geoms):
                        if num_sub_polygons > 1:
                            area_id_number = " ({} of {})".format(
                                i + 1, num_sub_polygons)
                        else:
                            area_id_number = ""
                        shape_polygon = Shape.create(pol)
                        # We still need to add the center of the area for the distribution KPI.
                        if area_KPIs:
                            for kpi in area_KPIs.kpi:
                                if isinstance(kpi, esdl.DistributionKPI):
                                    shape = sh
                                    geojson_dist_kpis[kpi.name]["location"] = [
                                        shape.shape.centroid.coords.xy[1][0],
                                        shape.shape.centroid.coords.xy[0][0]
                                    ]

                        area_list.append(
                            shape_polygon.get_geojson_feature({
                                "id":
                                area_id + area_id_number,
                                "name":
                                boundary_wgs['name'],
                                "KPIs":
                                geojson_KPIs,
                                "dist_KPIs":
                                geojson_dist_kpis
                            }))

                    area_shape = sh

    # assign random coordinates if boundary is given and area contains assets without coordinates
    # and gives assets within buildings a proper coordinate
    if area_shape:
        shape_dictionary[area_id] = area_shape
    # call this function even with area_shape == None, to position building assets inside a building
    update_asset_geometries_shape(this_area, area_shape)

    potentials = this_area.potential
    for potential in potentials:
        potential_geometry = potential.geometry
        potential_name = potential.name
        if not potential_name:
            potential_name = ""
        if potential_geometry:
            if isinstance(potential_geometry, esdl.WKT):
                shape = Shape.create(potential_geometry)
                pot_list.append(
                    shape.get_geojson_feature({
                        "id": potential.id,
                        "name": potential_name,
                    }))
                shape_dictionary[potential.id] = shape

    for area in this_area.area:
        find_area_info_geojson(area_list, pot_list, area, shape_dictionary)