Skip to content

Commit

Permalink
set projstr in builder as optional argument
Browse files Browse the repository at this point in the history
  • Loading branch information
chenchenplus committed Sep 16, 2024
1 parent 3899a12 commit c175277
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 36 deletions.
27 changes: 17 additions & 10 deletions mosstool/map/_map_util/aois/append_aois_matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -906,7 +906,7 @@ def map_land_use(euluc: int) -> int:
}
return mapper.get(euluc, 12)

if not shp_path:
if not shp_path or not projstr:
for _, aoi in aois.items():
aoi["land_use"] = map_land_use(-1)
return aois
Expand Down Expand Up @@ -1559,12 +1559,11 @@ def get_aoi_name(aoi: dict) -> str:
return aois


def _add_pois(aois, pois, projstr):
def _add_pois(aois, pois):
"""
add POIs
Add poi ids information to aoi
"""
projector = pyproj.Proj(projstr)
# 读取poi原始数据,构建poi数据
# {
# "id": "10001234807567065271",
Expand Down Expand Up @@ -1769,9 +1768,17 @@ def _add_aoi(aois, stops, workers, merge_aoi: bool = False):
value = tags["building"]
if not "yes" in value:
external["land_types"]["building|" + value] += geo.area
if "name" in tags:
value = tags["name"]
external["names"][value] += geo.area
for _name_key in ["name", "name:zh", "name:en"]:
if _name_key in tags:
value = tags[_name_key]
external["names"][value] += geo.area
break
else:
for _k, value in tags.items():
if "name" in _k:
external["names"][value] += geo.area
break

aois_poly.append(aoi)
else:
x, y = aoi["coords"][0][:2]
Expand Down Expand Up @@ -1859,8 +1866,8 @@ def add_aoi_to_map(
input_pois: list,
input_stops: list,
bbox,
projstr: str,
shp_path: Optional[str],
projstr: Optional[str] = None,
shp_path: Optional[str] = None,
workers: int = 32,
):
"""match AOIs to lanes"""
Expand All @@ -1885,7 +1892,7 @@ def add_aoi_to_map(
aois = _add_aoi_land_use(aois, shp_path, bbox, projstr)
aois = _add_aoi_name(aois)
aois = _add_aoi_urban_land_use(aois)
(aois, pois) = _add_pois(aois, raw_pois, projstr)
(aois, pois) = _add_pois(aois, raw_pois)
return (aois, pois)


Expand Down Expand Up @@ -1934,5 +1941,5 @@ def add_sumo_aoi_to_map(
logging.info(f"Added POI num: {len(added_ex_pois)}")
# Post-compute
logging.info("Post Compute")
(aois, pois) = _add_pois(aois, raw_pois, projstr)
(aois, pois) = _add_pois(aois, raw_pois)
return (aois, pois)
20 changes: 14 additions & 6 deletions mosstool/map/_map_util/aois/convert_aoi_poi.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,13 @@ def _shape2geo(shape_str):


def convert_aoi(
geos: FeatureCollection, public_transport_data: Dict[str, dict], projstr: str
geos: FeatureCollection,
public_transport_data: Dict[str, dict],
projstr: Optional[str] = None,
) -> Tuple[list, list]:
aois = []
stops = []
projector = pyproj.Proj(projstr)
projector = pyproj.Proj(projstr) if projstr is not None else None
if geos["features"] is not None:
for i, feature in enumerate(geos["features"]):
if not feature["geometry"]["type"] == "Polygon":
Expand All @@ -50,7 +52,11 @@ def convert_aoi(
aois.append(
{
"id": aoi_id,
"coords": [projector(*c) for c in coords],
"coords": (
[projector(*c) for c in coords]
if projector is not None
else coords
),
"external": {
"population": 0,
"inner_poi": [],
Expand Down Expand Up @@ -86,9 +92,9 @@ def convert_aoi(
return (aois, stops)


def convert_poi(geos: FeatureCollection, projstr: str) -> list:
def convert_poi(geos: FeatureCollection, projstr: Optional[str] = None) -> list:
pois = []
projector = pyproj.Proj(projstr)
projector = pyproj.Proj(projstr) if projstr is not None else None
if geos["features"] is not None:
for feature in geos["features"]:
if not feature["geometry"]["type"] == "Point":
Expand All @@ -102,7 +108,9 @@ def convert_poi(geos: FeatureCollection, projstr: str) -> list:
pois.append(
{
"id": poi_id,
"coords": [projector(*coords)],
"coords": (
[projector(*coords)] if projector is not None else [coords]
),
"name": name,
"category": catg,
"external": {
Expand Down
57 changes: 38 additions & 19 deletions mosstool/map/builder/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
generate_traffic_light)
from .._util.angle import abs_delta_angle, delta_angle
from .._util.line import (align_line, connect_line_string, get_line_angle,
get_start_vector, line_extend, line_max_curvature,
line_extend, line_max_curvature,
merge_line_start_end, offset_lane)

__all__ = ["Builder"]
Expand All @@ -48,7 +48,7 @@ class Builder:
def __init__(
self,
net: Union[FeatureCollection, Map],
proj_str: str,
proj_str: Optional[str] = None,
aois: Optional[FeatureCollection] = None,
pois: Optional[FeatureCollection] = None,
public_transport: Optional[Dict[str, List]] = None,
Expand All @@ -69,7 +69,7 @@ def __init__(
"""
Args:
- net (FeatureCollection | Map): road network
- proj_str (str): projection string
- proj_str (str): projection string, if not provided, all coordinates in input geojson files will be seen as xyz coords.
- aois (FeatureCollection): area of interest
- pois (FeatureCollection): point of interest
- public_transport (Dict[str, List]): public transports in json format
Expand Down Expand Up @@ -103,7 +103,7 @@ def __init__(
self.junc_uid = JUNC_START_ID
self.public_transport_uid = PUBLIC_LINE_START_ID
self.proj_str = proj_str
self.projector = pyproj.Proj(proj_str)
self.projector = pyproj.Proj(proj_str) if proj_str is not None else None
self.pop_tif_path = pop_tif_path
self.landuse_shp_path = landuse_shp_path
self.traffic_light_min_direction_group = traffic_light_min_direction_group
Expand Down Expand Up @@ -136,29 +136,38 @@ def __init__(
"""There is no way id for the right sidewalk"""
self.public_transport_data = {"lines": {}, "stations": {}}
self.from_pb = False
# Perform coordinate conversion
all_coords_lonlat = []
if net_type == FeatureCollection:
self.net = FeatureCollection(deepcopy(net))
geojson_format_check(self.net)
# Perform coordinate conversion
all_coords_lonlat = []
for feature in self.net["features"]:
if feature["geometry"]["type"] not in ("MultiPoint", "LineString"):
raise ValueError("bad geometry type: " + feature)
if "properties" not in feature:
raise ValueError("no properties in feature: " + feature)
if "id" not in feature:
feature["id"] = feature["properties"]["id"]
all_coords_lonlat.extend(
[c[:2] for c in feature["geometry"]["coordinates"]]
)
coords = np.array(feature["geometry"]["coordinates"], dtype=np.float64)
z_coords = (
coords[:, 2]
if coords.shape[1] > 2
else np.zeros((coords.shape[0], 1), dtype=np.float64)
)
xy_coords = np.stack(self.projector(*coords.T[:2]), axis=1) # (N, 2)
xyz_coords = np.column_stack([xy_coords, z_coords]) # (N, 3)
if self.projector is not None:
z_coords = (
coords[:, 2]
if coords.shape[1] > 2
else np.zeros((coords.shape[0], 1), dtype=np.float64)
)
all_coords_lonlat.extend(
[c[:2] for c in feature["geometry"]["coordinates"]]
)
xy_coords = np.stack(
self.projector(*coords.T[:2]), axis=1
) # (N, 2)
xyz_coords = np.column_stack([xy_coords, z_coords]) # (N, 3)
else:
xy_coords = np.array(
[c[:2] for c in feature["geometry"]["coordinates"]],
dtype=np.float64,
)
xyz_coords = coords
feature["geometry"]["coordinates_xy"] = xy_coords
feature["geometry"]["coordinates_xyz"] = xyz_coords
if feature["geometry"]["type"] == "LineString":
Expand All @@ -174,8 +183,12 @@ def __init__(
feature["uid"] = self.junc_uid
self.junc_uid += 1
all_coords_lonlat = np.array(all_coords_lonlat)
self.min_lon, self.min_lat = np.min(all_coords_lonlat, axis=0)
self.max_lon, self.max_lat = np.max(all_coords_lonlat, axis=0)
self.min_lon, self.min_lat = (
np.min(all_coords_lonlat, axis=0) if self.projector else (-180, -90)
)
self.max_lon, self.max_lat = (
np.max(all_coords_lonlat, axis=0) if self.projector else (180, 90)
)
# Classify and store
self.junctions = {}
"""id -> junction data"""
Expand Down Expand Up @@ -288,6 +301,7 @@ def __init__(
}
self.junc_uid = max(pb_junc_uids) + 1
# bbox
assert self.projector is not None, "building from pb must provide projstr!"
self.max_lon, self.max_lat = self.projector(
net.header.east, net.header.north, inverse=True
)
Expand Down Expand Up @@ -3786,8 +3800,14 @@ def _add_traffic_light(self):
)

def _add_public_transport(self) -> Set[int]:
if self.public_transport is None:
return set()
logging.info("Adding public transport to map")
public_road_uids = set()
projector = self.projector
assert (
projector is not None
), "building with public_transport must provide projstr!"

def create_subway_connections(geos: list, stas: list) -> List[List[int]]:
# Create new subway lane road and junction
Expand Down Expand Up @@ -3894,7 +3914,6 @@ def create_subway_connections(geos: list, stas: list) -> List[List[int]]:
next_junc_id += 1
return station_connection_road_ids

projector = self.projector
public_transport = self.public_transport
raw_stations = (
public_transport["stations"] if public_transport is not None else []
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "mosstool"
version = "0.2.34"
version = "0.2.35"
description = "MObility Simulation System toolbox "
authors = ["Jun Zhang <[email protected]>"]
license = "MIT"
Expand Down

0 comments on commit c175277

Please sign in to comment.