Aller au contenu

C02 Init Grid

Create a grid over the metropole or a selection of city and save it to DB

Command

Bases: BaseCommand

Source code in back/iarbre_data/management/commands/c02_init_grid.py
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
class Command(BaseCommand):
    help = "Create grid and save it to DB"

    def add_arguments(self, parser):
        """Add arguments to the command."""
        parser.add_argument(
            "--insee_code_city",
            type=str,
            required=False,
            default=None,
            help="The INSEE code of the city or cities to process. If multiple cities, please separate with comma (e.g. --insee_code='69266,69382')",
        )
        parser.add_argument(
            "--grid-size", type=int, default=4, help="Grid size in meters"
        )
        parser.add_argument(
            "--grid-type", type=int, default=1, help="Hexagonal (1) or square (2) grid."
        )
        parser.add_argument(
            "--delete",
            action="store_true",
            help="Delete already existing tiles.",
        )
        parser.add_argument(
            "--keep_outside",
            action="store_true",
            help="Keep tiles outside of the city selection (by default, they are deleted).",
        )

    @staticmethod
    def _create_grid_city(
        city: City,
        batch_size: int,
        logger: logging.Logger,
        grid_type: int,
        side_length: Optional[float],
        grid_size: float,
        delete: bool,
    ) -> None:
        """
        Create grid for a specific city.

        Args:
            city (City): The city object with geometry, id and name.
            batch_size (int): The size of the batch to save to the DB.
            logger (logging.Logger): The logger object.
            grid_type (int): The type of grid to create.
            side_length (float, optional): The size of equilateral triangles forming the hexagon. (for hexagonal grid only).
            grid_size (float): The size of the grid in meters (for square grid).
            delete (bool): Flag to indicate if existing tiles should be deleted.

        Returns:
            None
        """
        print(f"Selected city: {city.name} with id {city.id}.")
        # Get already existing tiles
        tiles_queryset = Tile.objects.filter(
            geometry__intersects=GEOSGeometry(city.geometry.wkt)
        )
        if len(tiles_queryset) > 0:  # Not empty database
            all_ids = load_geodataframe_from_db(tiles_queryset, ["id"]).id
            total_records = tiles_queryset.count()
            print(f"Number tiles already in the DB: {total_records}. \n")
            if delete or (city.tiles_generated is False):
                # Clean if asked or if not all Tiles have been generated
                print("These tiles will be deleted and new one recomputed.")
                City.objects.filter(id=city.id).update(tiles_generated=False)
                for start in tqdm(range(0, total_records, batch_size)):
                    batch_ids = all_ids[start : start + batch_size]
                    with transaction.atomic():
                        Tile.objects.filter(id__in=batch_ids).delete()
                print(f"Deleted {total_records} tiles.")
            elif city.tiles_generated:
                return
        print("Creating new tiles.")
        if grid_type == 1:  # Hexagonal grid
            create_tiles_for_city(
                city, grid_size, HexTileShape, logger, batch_size, side_length, SIN_60
            )
        elif grid_type == 2:  # square grid
            create_tiles_for_city(city, grid_size, SquareTileShape, logger, batch_size)

    def handle(self, *args, **options):
        """Create grid and save it to DB."""
        batch_size = int(1e4)  # Depends on your RAM
        logger = logging.getLogger(__name__)
        insee_code_city = options["insee_code_city"]
        grid_size = options["grid_size"]
        grid_type = options["grid_type"]
        keep_outside = options["keep_outside"]
        delete = options["delete"]
        if grid_type not in [1, 2]:
            raise ValueError("Grid type should be either 1 (hexagonal) or 2 (square).")
        selected_city = select_city(insee_code_city)
        desired_area = grid_size * grid_size
        side_length = np.sqrt((2 * desired_area) / (3 * np.sqrt(3)))
        total_city = len(selected_city)
        processed_city = 0
        with ThreadPoolExecutor(max_workers=12) as executor:
            future_to_city = {
                executor.submit(
                    self._create_grid_city,
                    city=city,
                    batch_size=batch_size,
                    logger=logger,
                    grid_type=grid_type,
                    side_length=side_length,
                    grid_size=grid_size,
                    delete=delete,
                ): city
                for city in selected_city.itertuples()
            }
            for future in as_completed(future_to_city):
                future.result()
                city = future_to_city.pop(future)
                processed_city += 1
                print(
                    f"Processed city: {processed_city} / {total_city} (city: {city.name})."
                )
                gc.collect()  # just to be sure gc is called...
        print("Removing duplicates...")
        remove_duplicates(Tile)
        if keep_outside is False:
            clean_outside(selected_city, batch_size)

_create_grid_city(city, batch_size, logger, grid_type, side_length, grid_size, delete) staticmethod

Create grid for a specific city.

Parameters:

Name Type Description Default
city City

The city object with geometry, id and name.

required
batch_size int

The size of the batch to save to the DB.

required
logger Logger

The logger object.

required
grid_type int

The type of grid to create.

required
side_length float

The size of equilateral triangles forming the hexagon. (for hexagonal grid only).

required
grid_size float

The size of the grid in meters (for square grid).

required
delete bool

Flag to indicate if existing tiles should be deleted.

required

Returns:

Type Description
None

None

Source code in back/iarbre_data/management/commands/c02_init_grid.py
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
@staticmethod
def _create_grid_city(
    city: City,
    batch_size: int,
    logger: logging.Logger,
    grid_type: int,
    side_length: Optional[float],
    grid_size: float,
    delete: bool,
) -> None:
    """
    Create grid for a specific city.

    Args:
        city (City): The city object with geometry, id and name.
        batch_size (int): The size of the batch to save to the DB.
        logger (logging.Logger): The logger object.
        grid_type (int): The type of grid to create.
        side_length (float, optional): The size of equilateral triangles forming the hexagon. (for hexagonal grid only).
        grid_size (float): The size of the grid in meters (for square grid).
        delete (bool): Flag to indicate if existing tiles should be deleted.

    Returns:
        None
    """
    print(f"Selected city: {city.name} with id {city.id}.")
    # Get already existing tiles
    tiles_queryset = Tile.objects.filter(
        geometry__intersects=GEOSGeometry(city.geometry.wkt)
    )
    if len(tiles_queryset) > 0:  # Not empty database
        all_ids = load_geodataframe_from_db(tiles_queryset, ["id"]).id
        total_records = tiles_queryset.count()
        print(f"Number tiles already in the DB: {total_records}. \n")
        if delete or (city.tiles_generated is False):
            # Clean if asked or if not all Tiles have been generated
            print("These tiles will be deleted and new one recomputed.")
            City.objects.filter(id=city.id).update(tiles_generated=False)
            for start in tqdm(range(0, total_records, batch_size)):
                batch_ids = all_ids[start : start + batch_size]
                with transaction.atomic():
                    Tile.objects.filter(id__in=batch_ids).delete()
            print(f"Deleted {total_records} tiles.")
        elif city.tiles_generated:
            return
    print("Creating new tiles.")
    if grid_type == 1:  # Hexagonal grid
        create_tiles_for_city(
            city, grid_size, HexTileShape, logger, batch_size, side_length, SIN_60
        )
    elif grid_type == 2:  # square grid
        create_tiles_for_city(city, grid_size, SquareTileShape, logger, batch_size)

add_arguments(parser)

Add arguments to the command.

Source code in back/iarbre_data/management/commands/c02_init_grid.py
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
def add_arguments(self, parser):
    """Add arguments to the command."""
    parser.add_argument(
        "--insee_code_city",
        type=str,
        required=False,
        default=None,
        help="The INSEE code of the city or cities to process. If multiple cities, please separate with comma (e.g. --insee_code='69266,69382')",
    )
    parser.add_argument(
        "--grid-size", type=int, default=4, help="Grid size in meters"
    )
    parser.add_argument(
        "--grid-type", type=int, default=1, help="Hexagonal (1) or square (2) grid."
    )
    parser.add_argument(
        "--delete",
        action="store_true",
        help="Delete already existing tiles.",
    )
    parser.add_argument(
        "--keep_outside",
        action="store_true",
        help="Keep tiles outside of the city selection (by default, they are deleted).",
    )

handle(*args, **options)

Create grid and save it to DB.

Source code in back/iarbre_data/management/commands/c02_init_grid.py
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
def handle(self, *args, **options):
    """Create grid and save it to DB."""
    batch_size = int(1e4)  # Depends on your RAM
    logger = logging.getLogger(__name__)
    insee_code_city = options["insee_code_city"]
    grid_size = options["grid_size"]
    grid_type = options["grid_type"]
    keep_outside = options["keep_outside"]
    delete = options["delete"]
    if grid_type not in [1, 2]:
        raise ValueError("Grid type should be either 1 (hexagonal) or 2 (square).")
    selected_city = select_city(insee_code_city)
    desired_area = grid_size * grid_size
    side_length = np.sqrt((2 * desired_area) / (3 * np.sqrt(3)))
    total_city = len(selected_city)
    processed_city = 0
    with ThreadPoolExecutor(max_workers=12) as executor:
        future_to_city = {
            executor.submit(
                self._create_grid_city,
                city=city,
                batch_size=batch_size,
                logger=logger,
                grid_type=grid_type,
                side_length=side_length,
                grid_size=grid_size,
                delete=delete,
            ): city
            for city in selected_city.itertuples()
        }
        for future in as_completed(future_to_city):
            future.result()
            city = future_to_city.pop(future)
            processed_city += 1
            print(
                f"Processed city: {processed_city} / {total_city} (city: {city.name})."
            )
            gc.collect()  # just to be sure gc is called...
    print("Removing duplicates...")
    remove_duplicates(Tile)
    if keep_outside is False:
        clean_outside(selected_city, batch_size)

HexTileShape

Bases: TileShape

Generate hexagonal tile.

Source code in back/iarbre_data/management/commands/c02_init_grid.py
 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
class HexTileShape(TileShape):
    """Generate hexagonal tile."""

    @staticmethod
    def adjust_bounds(xmin, ymin, xmax, ymax, grid_size, side_length):
        """Snap bounds to the nearest grid alignment."""
        hex_width = 3 * side_length
        hex_height = 2 * side_length * SIN_60
        xmin = hex_width * np.floor(xmin / hex_width)
        ymin = hex_height * np.floor(ymin / hex_height)
        xmax = hex_width * np.ceil(xmax / hex_width)
        ymax = hex_height * np.ceil(ymax / hex_height)
        return xmin, ymin, xmax, ymax

    @staticmethod
    def tile_positions(xmin, ymin, xmax, ymax, grid_size, side_length):
        """Generate an iterator for all the position where to create a tile."""
        hex_width = 3 * side_length
        cols = np.arange(xmin - hex_width, xmax + hex_width, hex_width)
        rows = np.arange(
            ymin / SIN_60 - side_length, ymax / SIN_60 + side_length, side_length
        )
        return itertools.product(cols, enumerate(rows))

    @staticmethod
    def create_tile_polygon(x, y, grid_size, side_length, i):
        """Create a single hexagon and round geometries to optimize storage."""
        offset = 1.5 * side_length if i % 2 != 0 else 0
        x0 = x - offset
        dim = [
            (x0, y * SIN_60),
            (x0 + side_length, y * SIN_60),
            (x0 + (1.5 * side_length), (y + side_length) * SIN_60),
            (x0 + side_length, (y + (2 * side_length)) * SIN_60),
            (x0, (y + (2 * side_length)) * SIN_60),
            (x0 - (0.5 * side_length), (y + side_length) * SIN_60),
            (x0, y * SIN_60),
        ]
        return Polygon([(round(x, 2), round(y, 2)) for (x, y) in dim], srid=TARGET_PROJ)

adjust_bounds(xmin, ymin, xmax, ymax, grid_size, side_length) staticmethod

Snap bounds to the nearest grid alignment.

Source code in back/iarbre_data/management/commands/c02_init_grid.py
74
75
76
77
78
79
80
81
82
83
@staticmethod
def adjust_bounds(xmin, ymin, xmax, ymax, grid_size, side_length):
    """Snap bounds to the nearest grid alignment."""
    hex_width = 3 * side_length
    hex_height = 2 * side_length * SIN_60
    xmin = hex_width * np.floor(xmin / hex_width)
    ymin = hex_height * np.floor(ymin / hex_height)
    xmax = hex_width * np.ceil(xmax / hex_width)
    ymax = hex_height * np.ceil(ymax / hex_height)
    return xmin, ymin, xmax, ymax

create_tile_polygon(x, y, grid_size, side_length, i) staticmethod

Create a single hexagon and round geometries to optimize storage.

Source code in back/iarbre_data/management/commands/c02_init_grid.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
@staticmethod
def create_tile_polygon(x, y, grid_size, side_length, i):
    """Create a single hexagon and round geometries to optimize storage."""
    offset = 1.5 * side_length if i % 2 != 0 else 0
    x0 = x - offset
    dim = [
        (x0, y * SIN_60),
        (x0 + side_length, y * SIN_60),
        (x0 + (1.5 * side_length), (y + side_length) * SIN_60),
        (x0 + side_length, (y + (2 * side_length)) * SIN_60),
        (x0, (y + (2 * side_length)) * SIN_60),
        (x0 - (0.5 * side_length), (y + side_length) * SIN_60),
        (x0, y * SIN_60),
    ]
    return Polygon([(round(x, 2), round(y, 2)) for (x, y) in dim], srid=TARGET_PROJ)

tile_positions(xmin, ymin, xmax, ymax, grid_size, side_length) staticmethod

Generate an iterator for all the position where to create a tile.

Source code in back/iarbre_data/management/commands/c02_init_grid.py
85
86
87
88
89
90
91
92
93
@staticmethod
def tile_positions(xmin, ymin, xmax, ymax, grid_size, side_length):
    """Generate an iterator for all the position where to create a tile."""
    hex_width = 3 * side_length
    cols = np.arange(xmin - hex_width, xmax + hex_width, hex_width)
    rows = np.arange(
        ymin / SIN_60 - side_length, ymax / SIN_60 + side_length, side_length
    )
    return itertools.product(cols, enumerate(rows))

SquareTileShape

Bases: TileShape

Generate square tile.

Source code in back/iarbre_data/management/commands/c02_init_grid.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class SquareTileShape(TileShape):
    """Generate square tile."""

    @staticmethod
    def adjust_bounds(xmin, ymin, xmax, ymax, grid_size, side_length=None):
        """Snap bounds to the nearest grid alignment."""
        xmin = np.floor(xmin / grid_size) * grid_size
        ymin = np.floor(ymin / grid_size) * grid_size
        xmax = np.ceil(xmax / grid_size) * grid_size
        ymax = np.ceil(ymax / grid_size) * grid_size
        return xmin, ymin, xmax, ymax

    @staticmethod
    def tile_positions(xmin, ymin, xmax, ymax, grid_size, side_length=None):
        """Generate an iterator for all the position where to create a tile."""
        return itertools.product(
            np.arange(xmin, xmax + grid_size, grid_size),
            enumerate(np.arange(ymin, ymax + grid_size, grid_size)),
        )

    @staticmethod
    def create_tile_polygon(x, y, grid_size, side_length=None, i=None):
        """Create a single square and round geometries to optimize storage."""
        x1 = x - grid_size
        y1 = y + grid_size
        return Polygon.from_bbox(round(v, 2) for v in [x, y, x1, y1])

adjust_bounds(xmin, ymin, xmax, ymax, grid_size, side_length=None) staticmethod

Snap bounds to the nearest grid alignment.

Source code in back/iarbre_data/management/commands/c02_init_grid.py
46
47
48
49
50
51
52
53
@staticmethod
def adjust_bounds(xmin, ymin, xmax, ymax, grid_size, side_length=None):
    """Snap bounds to the nearest grid alignment."""
    xmin = np.floor(xmin / grid_size) * grid_size
    ymin = np.floor(ymin / grid_size) * grid_size
    xmax = np.ceil(xmax / grid_size) * grid_size
    ymax = np.ceil(ymax / grid_size) * grid_size
    return xmin, ymin, xmax, ymax

create_tile_polygon(x, y, grid_size, side_length=None, i=None) staticmethod

Create a single square and round geometries to optimize storage.

Source code in back/iarbre_data/management/commands/c02_init_grid.py
63
64
65
66
67
68
@staticmethod
def create_tile_polygon(x, y, grid_size, side_length=None, i=None):
    """Create a single square and round geometries to optimize storage."""
    x1 = x - grid_size
    y1 = y + grid_size
    return Polygon.from_bbox(round(v, 2) for v in [x, y, x1, y1])

tile_positions(xmin, ymin, xmax, ymax, grid_size, side_length=None) staticmethod

Generate an iterator for all the position where to create a tile.

Source code in back/iarbre_data/management/commands/c02_init_grid.py
55
56
57
58
59
60
61
@staticmethod
def tile_positions(xmin, ymin, xmax, ymax, grid_size, side_length=None):
    """Generate an iterator for all the position where to create a tile."""
    return itertools.product(
        np.arange(xmin, xmax + grid_size, grid_size),
        enumerate(np.arange(ymin, ymax + grid_size, grid_size)),
    )

clean_outside(selected_city, batch_size)

Remove all tiles outside the selected cities.

Parameters:

Name Type Description Default
selected_city DataFrame

The DataFrame of the selected cities.

required
batch_size int

The size of the batch to delete.

required

Returns:

Type Description
None

None

Source code in back/iarbre_data/management/commands/c02_init_grid.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def clean_outside(selected_city: pd.DataFrame, batch_size: int) -> None:
    """
    Remove all tiles outside the selected cities.

    Args:
        selected_city (pd.DataFrame): The DataFrame of the selected cities.
        batch_size (int): The size of the batch to delete.

    Returns:
        None
    """
    if len(selected_city) > 1:
        city_union_geom = selected_city.geometry.union_all()
    else:
        city_union_geom = selected_city.geometry.values[0]
    print("Deleting tiles out of the cities")
    total_records = Tile.objects.all().count()
    total_deleted = 0
    qs = Tile.objects.all().values_list("id", flat=True)
    for start in tqdm(range(0, total_records, batch_size)):
        batch_ids = qs[start : start + batch_size]
        with transaction.atomic():
            deleted_count, _ = (
                Tile.objects.filter(id__in=batch_ids)
                .exclude(geometry__intersects=city_union_geom.wkt)
                .delete()
            )
            total_deleted += deleted_count
    print(f"Deleted {total_deleted} tiles")

create_tiles_for_city(city, grid_size, tile_shape_cls, logger, batch_size=int(1000000.0), side_length=None, height_ratio=1)

Create tiles (square or hexagonal) for a specific city.

Parameters:

Name Type Description Default
city GeoPandas DataFrame

City GeoDataFrame.

required
grid_size float

The size of the grid in meters.

required
tile_shape_cls class

Class to generate individual tile shapes.

required
logger Logger

The logger object.

required
batch_size int

The size of the batch to save to DB.

int(1000000.0)
side_length float

Size of equilateral triangles forming the hexagon.

None
height_ratio float)

The height ratio of the grid element (1 for square and sin(60) for hexs).

1

Returns:

Type Description
None

None

Source code in back/iarbre_data/management/commands/c02_init_grid.py
112
113
114
115
116
117
118
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
def create_tiles_for_city(
    city: DataSource,
    grid_size: float,
    tile_shape_cls: Type[TileShape],
    logger: logging.Logger,
    batch_size: int = int(1e6),
    side_length: Optional[float] = None,
    height_ratio: float = 1,
) -> None:
    """
    Create tiles (square or hexagonal) for a specific city.

    Args:
        city (GeoPandas DataFrame): City GeoDataFrame.
        grid_size (float): The size of the grid in meters.
        tile_shape_cls (class): Class to generate individual tile shapes.
        logger (logging.Logger): The logger object.
        batch_size (int): The size of the batch to save to DB.
        side_length (float, optional): Size of equilateral triangles forming the hexagon.
        height_ratio (float) : The height ratio of the grid element (1 for square and sin(60) for hexs).

    Returns:
        None
    """
    city_geom = city.geometry
    city_geom = city_geom.buffer(20)  # Margin for intersection
    city_id = city.id
    xmin, ymin, xmax, ymax = city_geom.bounds
    # Bounds for the generation
    xmin, ymin, xmax, ymax = tile_shape_cls.adjust_bounds(
        xmin, ymin, xmax, ymax, grid_size, side_length
    )

    tiles = []
    tile_count = 0

    previous_iris = None

    for x, (i, y) in tqdm(
        tile_shape_cls.tile_positions(xmin, ymin, xmax, ymax, grid_size, side_length)
    ):
        tile = box(x, y * height_ratio, x - grid_size, y * height_ratio + grid_size)

        is_intersecting = city_geom.intersects(tile)
        if not is_intersecting:
            continue

        tile_count += 1
        polygon = tile_shape_cls.create_tile_polygon(x, y, grid_size, side_length, i)
        if previous_iris is not None and previous_iris.geometry.intersects(polygon):
            iris_id = previous_iris.id
        else:
            qs = Iris.objects.filter(geometry__intersects=polygon)
            if qs:
                previous_iris = qs[0]
                iris_id = previous_iris.id
            else:
                iris_id = None

        transformed = []
        for c in polygon.coords[0]:
            transformed.append(TRANSFORMATION.transform(*c))

        tile = Tile(
            geometry=polygon,
            map_geometry=Polygon(transformed, srid=TARGET_MAP_PROJ),
            plantability_indice=None,
            plantability_normalized_indice=None,
            city_id=city_id,
            iris_id=iris_id,
        )
        tiles.append(tile)

        # Avoid OOM errors
        if tile_count % batch_size == 0:
            with transaction.atomic():
                Tile.objects.bulk_create(tiles, batch_size=batch_size)
            logger.info(f"Got {len(tiles)} tiles")
            tiles.clear()
            gc.collect()

    if tiles:  # Save last batch
        Tile.objects.bulk_create(tiles, batch_size=batch_size)
    City.objects.filter(id=city.id).update(tiles_generated=True)