from dataclasses import dataclass import math import torch @dataclass(frozen=True) class Layout: width: int height: int stride: int = 32 subdivisions: int = 32 def __post_init__(self): if min(self.width, self.height) < 1 or self.stride != 32: raise ValueError('Positive image dimensions and the native 32-pixel stride required') if self.subdivisions < 1 or self.stride % self.subdivisions: raise ValueError('Subdivisions must divide the native stride') @property def cols(self): return math.ceil(self.width / self.stride) @property def rows(self): return math.ceil(self.height / self.stride) @property def count(self): return self.rows * self.cols @property def canvas_size(self): return self.cols * self.stride, self.rows * self.stride @property def fine_count(self): return self.subdivisions**2 def positions(self, device=None): parent = torch.arange(self.count, device=device) fine = torch.arange(self.fine_count, device=device) unit = self.stride / self.subdivisions horizontal = (parent[:, None] % self.cols) * self.stride + (fine[None] % self.subdivisions + .5) * unit vertical = (parent[:, None] // self.cols) * self.stride + (fine[None] // self.subdivisions + .5) * unit return torch.stack((horizontal, vertical), -1) def valid(self, device=None): positions = self.positions(device) return (positions[..., 0] < self.width) & (positions[..., 1] < self.height)