Skip to content

Commit

Permalink
format
Browse files Browse the repository at this point in the history
  • Loading branch information
cnheider committed Jun 30, 2023
1 parent 1434bd6 commit 8e2af2a
Show file tree
Hide file tree
Showing 12 changed files with 192 additions and 39 deletions.
1 change: 1 addition & 0 deletions jord/geopandas_utilities/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .geometry_filtering import *
from .importing import *
3 changes: 2 additions & 1 deletion jord/geopandas_utilities/geometry_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@ def split_on_geom_type(
gdf3 = gdf[gdf.geometry.type=="MultiPolygon"]
"""
return {
t: data_frame[data_frame.geom_type == t.value] for t in ShapelyGeometryTypesEnum
t: data_frame[data_frame.geom_type == t.value.__name__]
for t in ShapelyGeometryTypesEnum
}
7 changes: 7 additions & 0 deletions jord/geopandas_utilities/importing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import os

os.environ["USE_PYGEOS"] = "0"

import geopandas

__all__ = ["geopandas"]
1 change: 1 addition & 0 deletions jord/qgis_utilities/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from .conversion import *
from .categorisation import *
from .styling import *
from .plugin_version import *
except ImportError as ix:
this_package_name = Path(__file__).parent.name
print(f"Make sure qgis module is available for {this_package_name}")
Expand Down
11 changes: 11 additions & 0 deletions jord/qgis_utilities/plugin_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from pyplugin_installer.installer_data import repositories, plugins


__all__ = ["plugin_status"]


def plugin_status(plugin_key) -> str:
return plugins.all()[plugin_key]["status"]


# utils.reloadPlugin()
94 changes: 92 additions & 2 deletions jord/qlive_utilities/client.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,93 @@
from typing import Any
from enum import Enum
from functools import partial
from typing import Any, Callable

import zmq
from warg import AlsoDecorator


__all__ = ["QliveClient"]

from jord.qlive_utilities import QliveRPCMethodEnum, build_package, QliveRPCMethodMap

import inspect


class DisSatisfactionEnum(Enum):
none = "none"
args = "args"
kws = "kws"
argskws = "argskws"


def partial_satisfied(partial_fn: Callable) -> bool:
signature = inspect.signature(partial_fn.func)
try:
signature.bind(*partial_fn.args, **partial_fn.keywords)
return True
except TypeError:
return False


class QliveClient(AlsoDecorator):
"""
Client for sending data to qgis instance
"""

def __init__(self, addr: str = "tcp://localhost:5555"):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.REQ)
self.addr = addr

for method in QliveRPCMethodEnum:
actual_callable = QliveRPCMethodMap[method]

if False:
partial_build_package = partial(build_package, method.value)
if False and partial_satisfied(
partial_build_package
): # TODO: RESOLVE PARTIAL APPLICATION SATISFACTION.

def a():
self.send(partial_build_package())

rpc_method = a
elif True:

def a(*args):
self.send(partial_build_package(*args))

rpc_method = a
elif False:

def a(**kwargs):
self.send(partial_build_package(**kwargs))

rpc_method = a
elif False:

def a(*args, **kwargs):
self.send(partial_build_package(*args, **kwargs))

rpc_method = a
else:
raise NotImplementedError
elif False:
rpc_method = lambda *args: self.send(
partial(build_package, method)(*args)
)
elif False:
rpc_method = lambda *args: self.send(build_package(method, *args))
else:

def a(*args):
return self.send(build_package(method, *args))

rpc_method = a

rpc_method.__doc__ = actual_callable.__doc__
print(method.value, rpc_method)
setattr(self, method.value, rpc_method)

def __enter__(self):
self.socket.connect(self.addr)
return self
Expand All @@ -23,3 +98,18 @@ def __exit__(self, exc_type, exc_val, exc_tb):
def send(self, *args) -> Any:
self.socket.send(*args)
return self.socket.recv()


if __name__ == "__main__":
# QliveClient().clear_all()
# QliveClient().remove_layers()
# print(QliveClient().clear_all.__doc__)
# print(QliveClient().__dict__)
def uahdsuh():
with QliveClient() as qlive:
print("calling", qlive.add_wkts)
qlive.add_wkts({"a": "POINT (-66.86 10.48)"})

# QliveClient().add_dataframe(None)

uahdsuh()
70 changes: 49 additions & 21 deletions jord/qlive_utilities/procedures.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,16 @@
import time
from enum import Enum

__all__ = ["QliveRPCMethodEnum", "QliveRPCMethodMap"]

from typing import Mapping, Any, Tuple, Optional

import geopandas.geodataframe

import numpy
import shapely.geometry.base
from warg import passes_kws_to, Number
from pandas import DataFrame
from shapely.geometry.base import BaseGeometry
from jord.geopandas_utilities import split_on_geom_type
from shapely.geometry import GeometryCollection


APPEND_TIMESTAMP = True
SKIP_MEMORY_LAYER_CHECK_AT_CLOSE = True
Expand All @@ -31,9 +30,10 @@
"add_rasters",
"add_wkt",
"add_dataframe",
"add_geom_layer",
"clear_all",
"remove_layers",
"QliveRPCMethodEnum",
"QliveRPCMethodMap",
]


Expand All @@ -45,7 +45,7 @@ def add_raster(
extent_tuple: Tuple[Number, Number, Number, Number] = None,
pixel_size: Tuple[Number, Number] = PIXEL_SIZE,
crs_str: str = DEFAULT_LAYER_CRS,
default_value=DEFAULT_NUMBER,
default_value: Number = DEFAULT_NUMBER,
field: str = None,
) -> None:
"""
Expand Down Expand Up @@ -225,9 +225,13 @@ def add_rasters(qgis_instance_handle, rasters: Mapping, **kwargs) -> None:
add_raster(qgis_instance_handle, raster, name=layer_name, **kwargs)


def add_geom_layer(
def add_geometries():
...


def add_geometry(
qgis_instance_handle: Any,
geom: BaseGeometry,
geom, #: QgsGeometry,
name: Optional[str] = None,
crs: Optional[str] = None,
fields: Mapping = None,
Expand Down Expand Up @@ -293,6 +297,12 @@ def add_geom_layer(

qgis_instance_handle.qgis_project.addMapLayer(sub_layer, False)
gm_group.insertLayer(0, sub_layer)
elif uri == "MultiPoint":
...
elif uri == "MultiLineString":
...
elif uri == "MultiPolygon":
...
else:
if crs:
uri += f"?crs={crs}"
Expand All @@ -316,7 +326,7 @@ def add_geom_layer(
qgis_instance_handle.temporary_group.insertLayer(0, layer)


@passes_kws_to(add_geom_layer)
@passes_kws_to(add_geometry)
def add_wkb(qgis_instance_handle: Any, wkb: str, **kwargs) -> None:
"""
Expand All @@ -327,10 +337,10 @@ def add_wkb(qgis_instance_handle: Any, wkb: str, **kwargs) -> None:
"""
from qgis.core import QgsGeometry

add_geom_layer(qgis_instance_handle, QgsGeometry.fromWkb(wkb), **kwargs)
add_geometry(qgis_instance_handle, QgsGeometry.fromWkb(wkb), **kwargs)


@passes_kws_to(add_geom_layer)
@passes_kws_to(add_geometry)
def add_wkt(qgis_instance_handle: Any, wkt: str, **kwargs) -> None:
"""
Expand All @@ -341,7 +351,7 @@ def add_wkt(qgis_instance_handle: Any, wkt: str, **kwargs) -> None:
"""
from qgis.core import QgsGeometry

add_geom_layer(qgis_instance_handle, QgsGeometry.fromWkt(wkt), **kwargs)
add_geometry(qgis_instance_handle, QgsGeometry.fromWkt(wkt), **kwargs)


@passes_kws_to(add_wkb)
Expand Down Expand Up @@ -370,7 +380,7 @@ def add_wkts(qgis_instance_handle: Any, wkts: Mapping, **kwargs) -> None:
add_wkt(qgis_instance_handle, wkt, name=layer_name, **kwargs)


@passes_kws_to(add_geom_layer)
@passes_kws_to(add_geometry)
def add_dataframe(qgis_instance_handle: Any, dataframe: DataFrame, **kwargs) -> None:
"""
Expand All @@ -379,12 +389,21 @@ def add_dataframe(qgis_instance_handle: Any, dataframe: DataFrame, **kwargs) ->
:param kwargs:
:return:
"""
if isinstance(dataframe, geopandas.geodataframe.GeoDataFrame):
from geopandas import GeoDataFrame
from jord.geopandas_utilities import split_on_geom_type

if isinstance(dataframe, GeoDataFrame):
columns_to_include = ("layer",)
geom_dict = split_on_geom_type(dataframe)
for df in geom_dict.values():
add_wkt(qgis_instance_handle, df.to_wkt())
elif isinstance(dataframe, DataFrame):
if False:
for w in df.geometry.to_wkt():
add_wkt(qgis_instance_handle, w)
else:
for w in df.geometry.to_wkb():
add_wkb(qgis_instance_handle, w)

elif isinstance(dataframe, DataFrame) and False:
geometry_column = "geometry"
if isinstance(
dataframe[geometry_column][0], shapely.geometry.base.BaseGeometry
Expand All @@ -398,7 +417,10 @@ def add_dataframe(qgis_instance_handle: Any, dataframe: DataFrame, **kwargs) ->
raise NotImplemented

for row in wkts:
add_geom_layer(qgis_instance_handle, row)
add_geometry(qgis_instance_handle, row)
else:
if VERBOSE:
print("SKIP!")


def remove_layers(qgis_instance_handle: Any, *args) -> None:
Expand All @@ -411,27 +433,33 @@ def remove_layers(qgis_instance_handle: Any, *args) -> None:
qgis_instance_handle.on_clear_temporary()


def clear_all(qgis_instance_handle: Any) -> None:
def clear_all(qgis_instance_handle: Any, *args) -> None: # TODO: REMOVE THIS!
"""
:param qgis_instance_handle:
:return:
"""
remove_layers(qgis_instance_handle)
print("CLEAR ALL!")
if VERBOSE:
print("CLEAR ALL!")


def add_shapely(qgis_instance_handle: Any, geom: BaseGeometry, **kwargs) -> None:
...


class QliveRPCMethodEnum(Enum):
# add_layers = add_layers.__name__
remove_layers = remove_layers.__name__
clear_all = clear_all.__name__
add_wkt = add_wkt.__name__
add_wkb = add_wkb.__name__
add_wkts = add_wkts.__name__
add_wkbs = add_wkbs.__name__
add_dataframe = add_dataframe.__name__
add_shapely = add_shapely.__name__
add_raster = add_raster.__name__
add_rasters = add_rasters.__name__
remove_layers = remove_layers.__name__
clear_all = clear_all.__name__


funcs = locals() # In local scope for name
Expand Down
14 changes: 13 additions & 1 deletion jord/qlive_utilities/serialisation.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class SerialisationMethodEnum(Enum):


SERIALISATION_METHOD = SerialisationMethodEnum.pickle
VERBOSE = True


def build_package(method: QliveRPCMethodEnum, *args) -> bytes:
Expand All @@ -25,6 +26,17 @@ def build_package(method: QliveRPCMethodEnum, *args) -> bytes:
:param args:
:return:
"""
if VERBOSE:
print(type(method), method, args)

if not isinstance(method, QliveRPCMethodEnum):
assert method
assert isinstance(method, str), method
method = QliveRPCMethodEnum(method)

if VERBOSE:
print(type(method.value), method.value, args)

if SERIALISATION_METHOD == SerialisationMethodEnum.pickle:
return pickle.dumps({"method": method.value, "args": args})
elif SERIALISATION_METHOD == SERIALISATION_METHOD.json:
Expand Down Expand Up @@ -59,4 +71,4 @@ def read_package(package: bytes) -> Tuple[QliveRPCMethodEnum, Sequence[str]]:


if __name__ == "__main__":
print(read_package(build_package(method=QliveRPCMethodEnum.clear_all)))
print(read_package(build_package(method=QliveRPCMethodEnum.add_wkt)))
4 changes: 4 additions & 0 deletions jord/shapely_utilities/geometry_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,7 @@ class ShapelyGeometryTypesEnum(Enum):
)

geometry_collection = GeometryCollection # GeometryCollection([geoms]) # A collection of one or more geometries that may contain more than one type of geometry.


if __name__ == "__main__":
print([p.value.__name__ for p in ShapelyGeometryTypesEnum])
2 changes: 1 addition & 1 deletion samples/qgis/qlive/slim.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

socket = context.socket(zmq.REQ)

socket.connect("tcp://localhost:5556")
socket.connect("tcp://localhost:5555")

DEFAULT_CRS = "EPSG:3857" # "EPSG:4326"
crs = DEFAULT_CRS
Expand Down
Loading

0 comments on commit 8e2af2a

Please sign in to comment.