Skip to content

Commit

Permalink
feat: Find from cadastral registry function implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
JCruiz15 authored and jfaldanam committed Jun 26, 2024
1 parent 009bc1a commit 04c644a
Show file tree
Hide file tree
Showing 10 changed files with 348 additions and 29 deletions.
27 changes: 23 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# [SIGPAC-Tools](https://github.com/KhaosResearch/sigpac-tools)

![Python Version from PEP 621 TOML](https://img.shields.io/python/required-version-toml?tomlFilePath=https%3A%2F%2Fraw.githubusercontent.com%2FKhaosResearch%2Fsigpac-tools%2Fmain%2Fpyproject.toml)
![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)
![Status: Active](https://img.shields.io/badge/Status-Active-00aa00.svg)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
![Status: Active](https://img.shields.io/badge/Status-Active-00aa00.svg)
![Code style: Ruff](https://img.shields.io/badge/code%20style-Ruff-aa0000.svg)


Expand All @@ -22,7 +22,7 @@ python -m pip install ./sigpac-tools
or you can install it directly from the repository:

```bash
python -m pip install https://github.com/KhaosResearch/sigpac-tools
python -m pip install git+https://github.com/KhaosResearch/sigpac-tools
```

## Usage
Expand Down Expand Up @@ -100,6 +100,25 @@ geometry = geometry_from_coords(
)
```

### Get information from a specific cadastral registry

Known a cadastral registry, you can get the polygon and metadata from it using the `find_from_cadastral_registry` from the module `find`.
This function will return a tuple with a GeoJSON object of the polygon and a dictionary with the metadata of the plot. It will only return the metadata of the "parcela" layer.

Note that urban cadastral registries are not supported yet, due to the lack of information about them in the SIGPAC database.

If an invalid cadastral registry is provided, the function will raise a `ValueError`. If it detects that the cadastral registry is urban, it will raise a `NotImplementedError`.

An example of how to use this function is shown below:

```python
from sigpac_tools.find import find_from_cadastral_registry

cadastral_registry = "06001A028000380000LH"
geom, metadata = find_from_cadastral_registry(cadastral_registry)
```


## Acknowledgements

This inspired by the JavaScript [SIGPAC client](https://github.com/dan96ct/sigpac-client) made by Daniel Cebrián.
Expand All @@ -108,4 +127,4 @@ This inspired by the JavaScript [SIGPAC client](https://github.com/dan96ct/sigpa

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Copyright 2023 Khaos Research, all rights reserved.
Copyright 2024 Khaos Research, all rights reserved.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "sigpac-tools"
version = "1.0.0"
version = "1.1.0"
authors = [
{ name="Juan Carlos Ruiz Ruiz", email="juancaruru@uma.es" },
]
Expand Down
29 changes: 27 additions & 2 deletions sigpac_tools/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,20 @@ def get_parser():
metavar="INT",
)

# Find cadastral registry command

find_parser = subparsers.add_parser(
"find", help="Find a cadastral registry in the SIGPAC database"
)
find_parser.add_argument(
"--registry",
"-r",
type=str,
help="Cadastral registry to search for",
required=True,
metavar="STRING"
)

return parser


Expand All @@ -170,8 +184,6 @@ def main():
from sigpac_tools.locate import geometry_from_coords
import json

print(args)

layer = args.layer
lat = args.lat
lon = args.lon
Expand Down Expand Up @@ -199,6 +211,19 @@ def main():
metadata = get_metadata(layer, data)
logger.info(f"Metadata:\n{json.dumps(metadata, indent=2)}")
return metadata
case "find":
from sigpac_tools.find import find_from_cadastral_registry
import json

registry = args.registry
geom, metadata = find_from_cadastral_registry(registry)
logger.info(
f"Geometry for cadastral registry {registry}:\n{json.dumps(geom, indent=2)}"
)
logger.info(
f"Metadata for cadastral registry {registry}:\n{json.dumps(metadata, indent=2)}"
)
return geom, metadata
case _:
raise ValueError("Invalid command")

Expand Down
13 changes: 11 additions & 2 deletions sigpac_tools/anotate.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ def __query(
"id": f"{province},{municipality},{aggregate},{zone},{polygon},{parcel},{enclosure}",
}
response = requests.get(url, params=params)
print(response.url)
return response.json()
case _:
raise KeyError(
Expand Down Expand Up @@ -125,7 +124,8 @@ def get_metadata(layer: str, data: dict):
logger.info(
f"Searching for the metadata of the location (province {prov}, municipality {muni}, polygon {polg}, parcel {parc}) in the SIGPAC database..."
)
return __query(

res = __query(
layer=layer,
province=prov,
municipality=muni,
Expand All @@ -135,3 +135,12 @@ def get_metadata(layer: str, data: dict):
aggregate=aggr,
zone=zone,
)
if res is None:
raise ValueError(
f"The location (province {prov}, municipality {muni}, polygon {polg}, parcel {parc}) does not exist in the SIGPAC database. Please check the data and try again."
)
else:
logger.info(
f"Metadata of the location (province {prov}, municipality {muni}, polygon {polg}, parcel {parc}{f', enclosure {encl}' if layer == 'recinto' else ''}) found in the SIGPAC database."
)
return res
83 changes: 83 additions & 0 deletions sigpac_tools/find.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import structlog

from sigpac_tools.search import search
from sigpac_tools.anotate import get_metadata
from sigpac_tools.locate import geometry_from_coords
from sigpac_tools.utils import read_cadastral_registry


logger = structlog.get_logger()


def find_from_cadastral_registry(cadastral_reg : str):
"""
Find the geometry and metadata of a cadastral reference in the SIGPAC database. The reference must be rural. Urban references are not supported.
The expected cadastral registry is a 20 character string with the following format:
- 2 characters for the province
- 3 characters for the municipality
- 1 character for the section
- 3 characters for the polygon
- 5 characters for the parcel
- 4 characters for the id
- 2 characters for the control
Parameters
----------
cadastral_reg : str
Cadastral reference to search for
Returns
-------
dict
Geojson geometry of the found reference
dict
Metadata of the found reference
Raises
-------
ValueError
If the cadastral reference does not exist in the SIGPAC database
ValueError
If the length of the cadastral reference is not 20 characters
ValueError
If the province of the cadastral reference is not valid
ValueError
If the reference is not valid
NotImplementedError
If the reference is urban
"""
reg = read_cadastral_registry(cadastral_reg)

# Search for coordinates

search_data = search(
reg
)
if search_data["features"] == []:
raise ValueError(f"The cadastral reference {cadastral_reg} does not exist in the SIGPAC database. Please check the if the reference is correct and try again. Urban references are not supported.")

coords_x = []
coords_y = []
for feat in search_data["features"]:
coords_x.append((feat["properties"]["x1"] + feat["properties"]["x2"]) / 2)
coords_y.append((feat["properties"]["y1"] + feat["properties"]["y2"]) / 2)
coords = [sum(coords_x) / len(coords_x), sum(coords_y) / len(coords_y)]

# Get geometry

geometry = geometry_from_coords(
layer="parcela",
lat=coords[1],
lon=coords[0],
reference=reg["parcel"]
)

# Get metadata

metadata = get_metadata(
layer="parcela",
data=reg
)

return geometry, metadata
4 changes: 4 additions & 0 deletions sigpac_tools/locate.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ def geometry_from_coords(layer: str, lat: float, lon: float, reference: int) ->
logger.warning(
f"Reference '{reference}' not found in the layer '{layer}' at coordinates ({lat}, {lon})"
)
else:
logger.info(
f"Reference '{reference}' found in the layer '{layer}' at coordinates ({lat}, {lon})"
)
return result

else:
Expand Down
4 changes: 2 additions & 2 deletions sigpac_tools/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import structlog

from sigpac_tools._globals import BASE_URL
from sigpac_tools.utils import findCommunity
from sigpac_tools.utils import find_community

logger = structlog.get_logger()

Expand Down Expand Up @@ -39,7 +39,7 @@ def search(data: dict) -> dict:
'"Community" has not been specified, neither has been "province" and it is compulsory to find the community associated'
)
else:
comm = findCommunity(prov)
comm = find_community(prov)

if comm:
if prov:
Expand Down
Loading

0 comments on commit 04c644a

Please sign in to comment.