__init__.py 1.96 KB
Newer Older
1
from math import floor
Jgiannelos's avatar
Jgiannelos committed
2
3
4
5
6
7
8
9
10
from dataclasses import dataclass


@dataclass(eq=True, frozen=True)
class Tile:
    z: int
    x: int
    y: int

11
    @property
Jgiannelos's avatar
Jgiannelos committed
12
13
14
15
16
17
18
19
20
    def children(self):
        """Calculate the children tiles of a tile"""
        return [
            Tile(self.z + 1, self.x * 2, self.y * 2),
            Tile(self.z + 1, self.x * 2 + 1, self.y * 2),
            Tile(self.z + 1, self.x * 2, self.y * 2 + 1),
            Tile(self.z + 1, self.x * 2 + 1, self.y * 2 + 1),
        ]

21
22
23
24
25
    @property
    def parent(self):
        """Calculate the parent tile of a tile"""
        return Tile(self.z - 1, floor(self.x / 2), floor(self.y / 2))

Jgiannelos's avatar
Jgiannelos committed
26
27

class TileSet:
28
29
    def __init__(self, tilelistFile, minzoom, maxzoom):
        self.tilelistFile = tilelistFile
Jgiannelos's avatar
Jgiannelos committed
30
31
        self.tileset = set()
        self.maxzoom = maxzoom
32
        self.minzoom = minzoom
Jgiannelos's avatar
Jgiannelos committed
33
34
35
36
37
38
39
40

    @staticmethod
    def parse(entry):
        """Parse tile list entries"""
        entry = entry.rstrip()
        (z, x, y) = map(int, entry.split("/"))
        return Tile(z, x, y)

41
42
    def addParent(self, tile):
        """Add parent tile in the tileset"""
43
        if tile.z < self.minzoom or tile in self.tileset:
Jgiannelos's avatar
Jgiannelos committed
44
45
            return

46
47
        if tile.z >= self.minzoom and tile.z <= self.maxzoom:
            self.tileset.add(tile)
48
49
50
51
52
53
54
        self.addParent(tile.parent)

    def addChildren(self, tiles):
        """Add children tiles in the tileset"""
        for tile in tiles:
            if tile.z > self.maxzoom or tile in self.tileset:
                return
Jgiannelos's avatar
Jgiannelos committed
55

56
57
            if tile.z >= self.minzoom and tile.z <= self.maxzoom:
                self.tileset.add(tile)
58
            self.addChildren(tile.children)
Jgiannelos's avatar
Jgiannelos committed
59
60
61

    def read(self):
        """Read tilelist as input"""
62
63
64
65
        for line in self.tilelistFile.readlines():
            tile = self.parse(line)
            self.addParent(tile.parent)
            self.addChildren(tile.children)
66
67
            if tile.z >= self.minzoom and tile.z <= self.maxzoom:
                self.tileset.add(tile)