Grid - Snailz Docs

Skip to content

# Grid

Sample grids.

## `Grid`

Bases: `BaseModel`

Create and fill an integer grid.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`grid_id` | `str` | unique ID | required
`size` | `int` | grid XY size | required
`spacing_` | `float` | grid cell spacing | required
`grid` | `list` | grid values | `<dynamic>`
`lat0` | `float` | southernmost latitude | `0.0`
`lon0` | `float` | westernmost longitude | `0.0`

Source code in `src/snailz/grid.py`

     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     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
     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
    class Grid(BaseModel):
        """Create and fill an integer grid."""

        _id_gen: ClassVar[utils.id_gen] = utils.id_gen("G", 4)

        grid_id: str = Field(
            min_length=1, description="unique ID", json_schema_extra={"primary_key": True}
        )
        size: int = Field(gt=0, description="grid XY size")
        spacing_: float = Field(gt=0, description="grid cell spacing")
        grid: list = Field(default_factory=list, description="grid values")
        lat0: float = Field(default=0.0, description="southernmost latitude")
        lon0: float = Field(default=0.0, description="westernmost longitude")

        @staticmethod
        def make(params):
            """Make grids."""

            origins = _grid_origins(params)
            result = []
            for lat0, lon0 in origins:
                grid = Grid(
                    grid_id=next(Grid._id_gen),
                    size=params.grid_size,
                    spacing_=params.grid_spacing,
                    lat0=lat0,
                    lon0=lon0
                )
                grid.fill()
                result.append(grid)
            return result

        @staticmethod
        def tidy(grids):
            """Convert all grids to tidy table."""

            result = [["grid_id", "x", "y", "lat", "lon", "pollution"]]
            for g in grids:
                for x in range(g.size):
                    for y in range(g.size):
                        if g[x, y] > 0:
                            lat, lon = g.lat_lon(x, y)
                            result.append([g.grid_id, x, y, lat, lon, g[x, y]])
            return result

        def __getitem__(self, key):
            """Get grid element."""

            x, y = key
            return self.grid[y * self.size + x]

        def __setitem__(self, key, value):
            """Set grid element."""

            x, y = key
            self.grid[y * self.size + x] = value

        def __str__(self):
            """Convert to CSV string."""

            result = []
            for y in range(self.size - 1, -1, -1):
                result.append(",".join([str(self[x, y]) for x in range(self.size)]))
            return "\n".join(result)

        def fill(self):
            """Fill in a grid."""

            center = self.size // 2
            size_1 = self.size - 1
            x, y = center, center

            self.grid = [0 for _ in range(self.size * self.size)]
            while (x != 0) and (y != 0) and (x != size_1) and (y != size_1):
                self[x, y] += 1
                m = random.choice(MOVES)
                x += m[0]
                y += m[1]

        def lat_lon(self, x, y):
            """Calculate latitude and longitude of grid cell."""

            lat = self.lat0 + (y * self.spacing_) / METERS_PER_DEGREE_LAT
            meters_per_degree_lon = METERS_PER_DEGREE_LAT * math.cos(math.radians(self.lat0))
            lon = self.lon0 + (x * self.spacing_) / meters_per_degree_lon
            return lat, lon

### `make(params)` `staticmethod`

Make grids.

Source code in `src/snailz/grid.py`

    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    @staticmethod
    def make(params):
        """Make grids."""

        origins = _grid_origins(params)
        result = []
        for lat0, lon0 in origins:
            grid = Grid(
                grid_id=next(Grid._id_gen),
                size=params.grid_size,
                spacing_=params.grid_spacing,
                lat0=lat0,
                lon0=lon0
            )
            grid.fill()
            result.append(grid)
        return result

### `tidy(grids)` `staticmethod`

Convert all grids to tidy table.

Source code in `src/snailz/grid.py`

    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    @staticmethod
    def tidy(grids):
        """Convert all grids to tidy table."""

        result = [["grid_id", "x", "y", "lat", "lon", "pollution"]]
        for g in grids:
            for x in range(g.size):
                for y in range(g.size):
                    if g[x, y] > 0:
                        lat, lon = g.lat_lon(x, y)
                        result.append([g.grid_id, x, y, lat, lon, g[x, y]])
        return result

### `__getitem__(key)`

Get grid element.

Source code in `src/snailz/grid.py`

    63
    64
    65
    66
    67
    def __getitem__(self, key):
        """Get grid element."""

        x, y = key
        return self.grid[y * self.size + x]

### `__setitem__(key, value)`

Set grid element.

Source code in `src/snailz/grid.py`

    69
    70
    71
    72
    73
    def __setitem__(self, key, value):
        """Set grid element."""

        x, y = key
        self.grid[y * self.size + x] = value

### `__str__()`

Convert to CSV string.

Source code in `src/snailz/grid.py`

    75
    76
    77
    78
    79
    80
    81
    def __str__(self):
        """Convert to CSV string."""

        result = []
        for y in range(self.size - 1, -1, -1):
            result.append(",".join([str(self[x, y]) for x in range(self.size)]))
        return "\n".join(result)

### `fill()`

Fill in a grid.

Source code in `src/snailz/grid.py`

    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    def fill(self):
        """Fill in a grid."""

        center = self.size // 2
        size_1 = self.size - 1
        x, y = center, center

        self.grid = [0 for _ in range(self.size * self.size)]
        while (x != 0) and (y != 0) and (x != size_1) and (y != size_1):
            self[x, y] += 1
            m = random.choice(MOVES)
            x += m[0]
            y += m[1]

### `lat_lon(x, y)`

Calculate latitude and longitude of grid cell.

Source code in `src/snailz/grid.py`

     98
     99
    100
    101
    102
    103
    104
    def lat_lon(self, x, y):
        """Calculate latitude and longitude of grid cell."""

        lat = self.lat0 + (y * self.spacing_) / METERS_PER_DEGREE_LAT
        meters_per_degree_lon = METERS_PER_DEGREE_LAT * math.cos(math.radians(self.lat0))
        lon = self.lon0 + (x * self.spacing_) / meters_per_degree_lon
        return lat, lon

## `_grid_origins(params)`

Generate non-overlapping lower-left (lat, lon) corners for grids.

Source code in `src/snailz/grid.py`

    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    def _grid_origins(params):
        """
        Generate non-overlapping lower-left (lat, lon) corners for grids.
        """

        grid_width_m = params.grid_size * params.grid_spacing
        stride_m = grid_width_m + params.grid_gap
        cols = math.ceil(math.sqrt(params.num_grids))
        meters_per_degree_lon = METERS_PER_DEGREE_LAT * math.cos(math.radians(params.lat0))

        origins = []
        for i in range(params.num_grids):
            dx = (i % cols) * stride_m
            dy = (i // cols) * stride_m
            origins.append(
                (
                    params.lat0 + dy / METERS_PER_DEGREE_LAT,
                    params.lon0 + dx / meters_per_degree_lon,
                )
            )

        return origins