Skip to content

cj_geometry

Classes to handle the geometry of the CityJSON objects.

Classes:

Name Description
CityJSONGeometries

Class to handle a list of geometries and process them together.

Geometry

Base class for a CityJSON geometry object.

MultiSurface

CityJSONGeometries

Class to handle a list of geometries and process them together.

Methods:

Name Description
__init__

Create a handle for multiple geometry objects.

get_geometry_cj

Return all the geometries in CityJSON format, with deduplicated vertices.

get_optimal_translate

Compute the optimal translation for the list of geometries, computed as the average of all the unique vertices.

get_vertices_cj

Return all the deduplicated vertices in CityJSON format, scaled and translated according to the given arguments.

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
class CityJSONGeometries:
    """
    Class to handle a list of geometries and process them together.
    """

    def __init__(self, geometries: Sequence[Geometry]) -> None:
        """
        Create a handle for multiple geometry objects.

        Parameters
        ----------
        geometries : Sequence[Geometry]
            List of Geometry or subclasses to handle.
        """
        self.geometries = list(geometries)
        self.unique_vertices, self.boundaries = self._deduplicate_vertices()

    def get_optimal_translate(self, scale: NDArray[np.float64]) -> NDArray[np.float64]:
        """
        Compute the optimal translation for the list of geometries, computed as the average of all the unique vertices.

        Parameters
        ----------
        scale : NDArray[np.float64]
            Array of shape (3,) containing the scale used to store the vertices.
            Used to round the computed translation.

        Returns
        -------
        NDArray[np.float64]
            Array of shape (3,) containing the computed translation.
        """
        if self.unique_vertices.shape[0] == 0:
            return np.array([0, 0, 0], dtype=np.float64)
        translate = np.mean(self.unique_vertices, axis=0, dtype=np.float64)
        # Apply the scale to have a coherent precision
        translate = np.round(translate / scale) * scale
        assert isinstance(translate, np.ndarray)
        return translate

    def get_geometry_cj(self) -> list[dict[str, Any]]:
        """
        Return all the geometries in CityJSON format, with deduplicated vertices.

        Returns
        -------
        list[dict[str, Any]]
            The list of all geometries
        """
        formatted = []
        for geometry, true_boundaries in zip(self.geometries, self.boundaries):
            formatted.append(
                geometry.to_cityjson_format(replace_boundaries=true_boundaries)
            )
        return formatted

    def get_vertices_cj(
        self, scale: NDArray[np.float64], translate: NDArray[np.float64]
    ) -> list[list[int]]:
        """
        Return all the deduplicated vertices in CityJSON format, scaled and translated according to the given arguments.

        Parameters
        ----------
        scale : NDArray[np.float64]
            Array of shape (3,) containing the scale used to store the vertices.
        translate : NDArray[np.float64]
            Array of shape (3,) containing the translation used to store the vertices.

        Returns
        -------
        list[list[int]]
            List of shape (N, 3) containing all the vertices coordinates.
        """
        vertices = (self.unique_vertices - translate) / scale
        vertices_int64 = np.round(vertices).astype(np.int64)
        vertices_int = list(map(lambda v: list(map(int, v)), vertices_int64.tolist()))
        return vertices_int

    def _deduplicate_vertices(
        self,
    ) -> tuple[NDArray[np.float64], list[Any]]:
        """
        Deduplicate the vertices and recompute the boundaries accordingly.

        Returns
        -------
        unique_vertices: NDArray[np.float64]
            Array of shape (N, 3) with the deduplicated vertices
        new_boundaries: list[Any]
            List of the new boundaries
        """
        # Gather all vertices in the order they appear
        all_vertices: list[NDArray[np.float64]] = []
        offsets: list[int] = []

        last_offset = 0
        for geom in self.geometries:
            offsets.append(last_offset)
            all_vertices.append(geom.vertices)
            last_offset += all_vertices[-1].shape[0]

        # Concatenate into a single array
        if not all_vertices:
            return (np.empty((0, 3), dtype=np.float64), [])

        concat_vertices = np.vstack(all_vertices)

        # Remove duplicate vertices and store the index mapping
        unique_vertices, old_to_new_idx = np.unique(
            concat_vertices, return_inverse=True, axis=0
        )

        # Re‑index each geometry's boundaries
        new_boundaries: list[Any] = []

        for geom, offset in zip(self.geometries, offsets):
            # Translate to the deduplicated index space.
            remapped = _remap_boundaries(
                boundaries=geom.boundaries, offset=offset, mapping=old_to_new_idx
            )
            new_boundaries.append(remapped)

        return unique_vertices, new_boundaries

__init__(geometries)

Create a handle for multiple geometry objects.

Parameters:

Name Type Description Default
geometries typing.Sequence[cj_helpers.cj_geometry.Geometry]

List of Geometry or subclasses to handle.

required
Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
215
216
217
218
219
220
221
222
223
224
225
def __init__(self, geometries: Sequence[Geometry]) -> None:
    """
    Create a handle for multiple geometry objects.

    Parameters
    ----------
    geometries : Sequence[Geometry]
        List of Geometry or subclasses to handle.
    """
    self.geometries = list(geometries)
    self.unique_vertices, self.boundaries = self._deduplicate_vertices()

get_geometry_cj()

Return all the geometries in CityJSON format, with deduplicated vertices.

Returns:

Type Description
list[dict[str, typing.Any]]

The list of all geometries

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def get_geometry_cj(self) -> list[dict[str, Any]]:
    """
    Return all the geometries in CityJSON format, with deduplicated vertices.

    Returns
    -------
    list[dict[str, Any]]
        The list of all geometries
    """
    formatted = []
    for geometry, true_boundaries in zip(self.geometries, self.boundaries):
        formatted.append(
            geometry.to_cityjson_format(replace_boundaries=true_boundaries)
        )
    return formatted

get_optimal_translate(scale)

Compute the optimal translation for the list of geometries, computed as the average of all the unique vertices.

Parameters:

Name Type Description Default
scale numpy.typing.NDArray[numpy.float64]

Array of shape (3,) containing the scale used to store the vertices. Used to round the computed translation.

required

Returns:

Type Description
numpy.typing.NDArray[numpy.float64]

Array of shape (3,) containing the computed translation.

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def get_optimal_translate(self, scale: NDArray[np.float64]) -> NDArray[np.float64]:
    """
    Compute the optimal translation for the list of geometries, computed as the average of all the unique vertices.

    Parameters
    ----------
    scale : NDArray[np.float64]
        Array of shape (3,) containing the scale used to store the vertices.
        Used to round the computed translation.

    Returns
    -------
    NDArray[np.float64]
        Array of shape (3,) containing the computed translation.
    """
    if self.unique_vertices.shape[0] == 0:
        return np.array([0, 0, 0], dtype=np.float64)
    translate = np.mean(self.unique_vertices, axis=0, dtype=np.float64)
    # Apply the scale to have a coherent precision
    translate = np.round(translate / scale) * scale
    assert isinstance(translate, np.ndarray)
    return translate

get_vertices_cj(scale, translate)

Return all the deduplicated vertices in CityJSON format, scaled and translated according to the given arguments.

Parameters:

Name Type Description Default
scale numpy.typing.NDArray[numpy.float64]

Array of shape (3,) containing the scale used to store the vertices.

required
translate numpy.typing.NDArray[numpy.float64]

Array of shape (3,) containing the translation used to store the vertices.

required

Returns:

Type Description
list[list[int]]

List of shape (N, 3) containing all the vertices coordinates.

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def get_vertices_cj(
    self, scale: NDArray[np.float64], translate: NDArray[np.float64]
) -> list[list[int]]:
    """
    Return all the deduplicated vertices in CityJSON format, scaled and translated according to the given arguments.

    Parameters
    ----------
    scale : NDArray[np.float64]
        Array of shape (3,) containing the scale used to store the vertices.
    translate : NDArray[np.float64]
        Array of shape (3,) containing the translation used to store the vertices.

    Returns
    -------
    list[list[int]]
        List of shape (N, 3) containing all the vertices coordinates.
    """
    vertices = (self.unique_vertices - translate) / scale
    vertices_int64 = np.round(vertices).astype(np.int64)
    vertices_int = list(map(lambda v: list(map(int, v)), vertices_int64.tolist()))
    return vertices_int

Geometry

Bases: abc.ABC

Base class for a CityJSON geometry object.

Methods:

Name Description
__init__

Base class for a CityJSON geometry object.

to_cityjson_format

Export the geometry to the expected CityJSON format.

to_trimesh

Export the geometry to a Trimesh

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
class Geometry(ABC):
    """
    Base class for a CityJSON geometry object.
    """

    def __init__(
        self,
        lod: int,
        type_str: str,
        vertices: NDArray[np.float64],
        boundaries: list[Any],
    ) -> None:
        """
        Base class for a CityJSON geometry object.

        Parameters
        ----------
        lod : int
            Level of detail.
        type_str : str
            Type of geometry.
        vertices : NDArray[np.float64]
            Array of vertices coordinates.
        boundaries : list[Any]
            Array of indices referencing `vertices` to define the boundaries of the geometry.
        """
        self.lod = lod
        self.type = type_str
        self.vertices = vertices
        self.boundaries = boundaries

    @abstractmethod
    def to_cityjson_format(
        self, replace_boundaries: list[Any] | None
    ) -> dict[str, Any]:
        """
        Export the geometry to the expected CityJSON format.

        Parameters
        ----------
        replace_boundaries : list[Any] | None
            Whether to replace the current boundaries with new boundaries.

        Returns
        -------
        dict[str, Any]
            The CityJSON representation of this geometry.
        """
        raise NotImplementedError()

    @abstractmethod
    def to_trimesh(self) -> Trimesh:
        """
        Export the geometry to a Trimesh

        Returns
        -------
        Trimesh
            A Trimesh corresponding to this geometry.
        """
        raise NotImplementedError()

__init__(lod, type_str, vertices, boundaries)

Base class for a CityJSON geometry object.

Parameters:

Name Type Description Default
lod int

Level of detail.

required
type_str str

Type of geometry.

required
vertices numpy.typing.NDArray[numpy.float64]

Array of vertices coordinates.

required
boundaries list[typing.Any]

Array of indices referencing vertices to define the boundaries of the geometry.

required
Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
def __init__(
    self,
    lod: int,
    type_str: str,
    vertices: NDArray[np.float64],
    boundaries: list[Any],
) -> None:
    """
    Base class for a CityJSON geometry object.

    Parameters
    ----------
    lod : int
        Level of detail.
    type_str : str
        Type of geometry.
    vertices : NDArray[np.float64]
        Array of vertices coordinates.
    boundaries : list[Any]
        Array of indices referencing `vertices` to define the boundaries of the geometry.
    """
    self.lod = lod
    self.type = type_str
    self.vertices = vertices
    self.boundaries = boundaries

to_cityjson_format(replace_boundaries) abstractmethod

Export the geometry to the expected CityJSON format.

Parameters:

Name Type Description Default
replace_boundaries list[typing.Any] | None

Whether to replace the current boundaries with new boundaries.

required

Returns:

Type Description
dict[str, typing.Any]

The CityJSON representation of this geometry.

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@abstractmethod
def to_cityjson_format(
    self, replace_boundaries: list[Any] | None
) -> dict[str, Any]:
    """
    Export the geometry to the expected CityJSON format.

    Parameters
    ----------
    replace_boundaries : list[Any] | None
        Whether to replace the current boundaries with new boundaries.

    Returns
    -------
    dict[str, Any]
        The CityJSON representation of this geometry.
    """
    raise NotImplementedError()

to_trimesh() abstractmethod

Export the geometry to a Trimesh

Returns:

Type Description
trimesh.Trimesh

A Trimesh corresponding to this geometry.

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
106
107
108
109
110
111
112
113
114
115
116
@abstractmethod
def to_trimesh(self) -> Trimesh:
    """
    Export the geometry to a Trimesh

    Returns
    -------
    Trimesh
        A Trimesh corresponding to this geometry.
    """
    raise NotImplementedError()

MultiSurface

Bases: cj_helpers.cj_geometry.Geometry

Methods:

Name Description
__init__

MultiSurface geometry object.

from_mesh

Generate a MultiSurface from a Trimesh object, and set its lod.

to_cityjson_format

Export the geometry to the expected CityJSON format.

to_trimesh

Export the geometry to a Trimesh

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
class MultiSurface(Geometry):

    def __init__(
        self,
        lod: int,
        vertices: NDArray[np.float64],
        boundaries: list[list[NDArray[np.float64]]],
    ) -> None:
        """
        MultiSurface geometry object.

        Parameters
        ----------
        lod : int
            Level of detail.
        vertices : NDArray[np.float64]
            Array of vertices coordinates.
        boundaries : list[list[NDArray[np.float64]]]
            Array of indices referencing `vertices` to define the boundaries of the geometry.
        """

        super().__init__(
            type_str="MultiSurface", lod=lod, vertices=vertices, boundaries=boundaries
        )
        self.boundaries: list[list[NDArray[np.float64]]] = boundaries

    @classmethod
    def from_mesh(cls, lod: int, mesh: Trimesh) -> MultiSurface:
        """
        Generate a MultiSurface from a Trimesh object, and set its lod.

        Parameters
        ----------
        lod : int
            Level of detail.
        mesh : Trimesh
            Trimesh to store as a MultiSurface.

        Returns
        -------
        MultiSurface
            The generated MultiSurface.
        """
        vertices = mesh.vertices.astype(np.float64)
        tri_faces = mesh.faces.astype(np.int64)

        # Format for CityJSON
        surfaces = []
        for face in tri_faces:
            surfaces.append([face])

        return cls(lod=lod, vertices=vertices, boundaries=surfaces)

    def to_cityjson_format(
        self, replace_boundaries: list[list[NDArray[np.float64]]] | None
    ) -> dict[str, Any]:
        """
        Export the geometry to the expected CityJSON format.

        Parameters
        ----------
        replace_boundaries : list[list[NDArray[np.float64]]] | None
            Whether to replace the current boundaries with new boundaries.

        Returns
        -------
        dict[str, Any]
            The CityJSON representation of this geometry.
        """
        boundaries = (
            self.boundaries if replace_boundaries is None else replace_boundaries
        )
        boundaries = [[poly.tolist() for poly in surface] for surface in boundaries]
        return {"type": self.type, "lod": str(self.lod), "boundaries": boundaries}

    def to_trimesh(self) -> Trimesh:
        """
        Export the geometry to a Trimesh

        Returns
        -------
        Trimesh
            A Trimesh corresponding to this geometry.
        """
        tri_faces = []
        for boundary in self.boundaries:
            tri_faces.append(boundary[0])

        return Trimesh(vertices=self.vertices, faces=tri_faces)

__init__(lod, vertices, boundaries)

MultiSurface geometry object.

Parameters:

Name Type Description Default
lod int

Level of detail.

required
vertices numpy.typing.NDArray[numpy.float64]

Array of vertices coordinates.

required
boundaries list[list[numpy.typing.NDArray[numpy.float64]]]

Array of indices referencing vertices to define the boundaries of the geometry.

required
Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def __init__(
    self,
    lod: int,
    vertices: NDArray[np.float64],
    boundaries: list[list[NDArray[np.float64]]],
) -> None:
    """
    MultiSurface geometry object.

    Parameters
    ----------
    lod : int
        Level of detail.
    vertices : NDArray[np.float64]
        Array of vertices coordinates.
    boundaries : list[list[NDArray[np.float64]]]
        Array of indices referencing `vertices` to define the boundaries of the geometry.
    """

    super().__init__(
        type_str="MultiSurface", lod=lod, vertices=vertices, boundaries=boundaries
    )
    self.boundaries: list[list[NDArray[np.float64]]] = boundaries

from_mesh(lod, mesh) classmethod

Generate a MultiSurface from a Trimesh object, and set its lod.

Parameters:

Name Type Description Default
lod int

Level of detail.

required
mesh trimesh.Trimesh

Trimesh to store as a MultiSurface.

required

Returns:

Type Description
cj_helpers.cj_geometry.MultiSurface

The generated MultiSurface.

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
@classmethod
def from_mesh(cls, lod: int, mesh: Trimesh) -> MultiSurface:
    """
    Generate a MultiSurface from a Trimesh object, and set its lod.

    Parameters
    ----------
    lod : int
        Level of detail.
    mesh : Trimesh
        Trimesh to store as a MultiSurface.

    Returns
    -------
    MultiSurface
        The generated MultiSurface.
    """
    vertices = mesh.vertices.astype(np.float64)
    tri_faces = mesh.faces.astype(np.int64)

    # Format for CityJSON
    surfaces = []
    for face in tri_faces:
        surfaces.append([face])

    return cls(lod=lod, vertices=vertices, boundaries=surfaces)

to_cityjson_format(replace_boundaries)

Export the geometry to the expected CityJSON format.

Parameters:

Name Type Description Default
replace_boundaries list[list[numpy.typing.NDArray[numpy.float64]]] | None

Whether to replace the current boundaries with new boundaries.

required

Returns:

Type Description
dict[str, typing.Any]

The CityJSON representation of this geometry.

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def to_cityjson_format(
    self, replace_boundaries: list[list[NDArray[np.float64]]] | None
) -> dict[str, Any]:
    """
    Export the geometry to the expected CityJSON format.

    Parameters
    ----------
    replace_boundaries : list[list[NDArray[np.float64]]] | None
        Whether to replace the current boundaries with new boundaries.

    Returns
    -------
    dict[str, Any]
        The CityJSON representation of this geometry.
    """
    boundaries = (
        self.boundaries if replace_boundaries is None else replace_boundaries
    )
    boundaries = [[poly.tolist() for poly in surface] for surface in boundaries]
    return {"type": self.type, "lod": str(self.lod), "boundaries": boundaries}

to_trimesh()

Export the geometry to a Trimesh

Returns:

Type Description
trimesh.Trimesh

A Trimesh corresponding to this geometry.

Source code in python/src/data_pipeline/cj_helpers/cj_geometry.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def to_trimesh(self) -> Trimesh:
    """
    Export the geometry to a Trimesh

    Returns
    -------
    Trimesh
        A Trimesh corresponding to this geometry.
    """
    tri_faces = []
    for boundary in self.boundaries:
        tri_faces.append(boundary[0])

    return Trimesh(vertices=self.vertices, faces=tri_faces)