graph-graphics 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. graph_graphics-0.0.1.dist-info/METADATA +81 -0
  2. graph_graphics-0.0.1.dist-info/RECORD +49 -0
  3. graph_graphics-0.0.1.dist-info/WHEEL +5 -0
  4. graph_graphics-0.0.1.dist-info/entry_points.txt +2 -0
  5. graph_graphics-0.0.1.dist-info/licenses/LICENSE +131 -0
  6. graph_graphics-0.0.1.dist-info/licenses/LICENSE-ARTWORK +407 -0
  7. graph_graphics-0.0.1.dist-info/licenses/LICENSING.md +30 -0
  8. graph_graphics-0.0.1.dist-info/top_level.txt +1 -0
  9. graph_ics/__init__.py +46 -0
  10. graph_ics/__main__.py +4 -0
  11. graph_ics/animation.py +232 -0
  12. graph_ics/cli.py +121 -0
  13. graph_ics/colonies.py +145 -0
  14. graph_ics/color_fields.py +29 -0
  15. graph_ics/colors.py +17 -0
  16. graph_ics/contours.py +207 -0
  17. graph_ics/coverage.py +151 -0
  18. graph_ics/data/README.md +18 -0
  19. graph_ics/data/__init__.py +1 -0
  20. graph_ics/data/spain_population.json.gz +0 -0
  21. graph_ics/data/spain_population_sources.json +33 -0
  22. graph_ics/data/uk_population.json.gz +0 -0
  23. graph_ics/data/uk_population_sources.json +33 -0
  24. graph_ics/drawing.py +30 -0
  25. graph_ics/edge.py +72 -0
  26. graph_ics/fields.py +134 -0
  27. graph_ics/gallery.py +118 -0
  28. graph_ics/gallery_page.py +95 -0
  29. graph_ics/graph.py +548 -0
  30. graph_ics/growth.py +403 -0
  31. graph_ics/logo.py +144 -0
  32. graph_ics/node.py +92 -0
  33. graph_ics/obj.py +5 -0
  34. graph_ics/option_gallery.py +178 -0
  35. graph_ics/py.typed +0 -0
  36. graph_ics/quality.py +42 -0
  37. graph_ics/rendering.py +159 -0
  38. graph_ics/replay.py +314 -0
  39. graph_ics/samples.py +206 -0
  40. graph_ics/scene.py +103 -0
  41. graph_ics/scene_gallery.py +86 -0
  42. graph_ics/site_paths.py +33 -0
  43. graph_ics/site_structure.py +149 -0
  44. graph_ics/spatial.py +86 -0
  45. graph_ics/styles.py +98 -0
  46. graph_ics/text.py +114 -0
  47. graph_ics/uk.py +48 -0
  48. graph_ics/validation.py +45 -0
  49. graph_ics/vector.py +28 -0
graph_ics/contours.py ADDED
@@ -0,0 +1,207 @@
1
+ """Contour semantics, readable scale limits, and bounded geometric guidance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from math import atan2, ceil, hypot, isfinite
7
+ from typing import Literal
8
+
9
+ from shapely.geometry import LineString, MultiPolygon, Point, Polygon
10
+ from shapely.ops import nearest_points
11
+ from shapely.geometry.base import BaseGeometry
12
+
13
+ Area = Polygon | MultiPolygon
14
+
15
+
16
+ def valid_area(area: Area) -> None:
17
+ if not isinstance(area, (Polygon, MultiPolygon)) or area.is_empty or not area.is_valid or area.area <= 0:
18
+ raise ValueError('Contours must be valid nonempty polygons; repair is never implicit')
19
+ if not all(isfinite(v) for v in area.bounds): raise ValueError('Contour bounds must be finite')
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class RegionSpec:
24
+ shape: Area
25
+ mode: Literal['inside', 'outside', 'band'] = 'inside'
26
+ padding: float = 0
27
+ canvas: Area | None = None
28
+ band_width: float = 20
29
+
30
+ def resolve(self) -> Area:
31
+ valid_area(self.shape)
32
+ if not isfinite(self.padding) or self.padding < 0: raise ValueError('Padding must be finite and nonnegative')
33
+ if self.mode not in ('inside', 'outside', 'band'): raise ValueError('Unknown region mode')
34
+ if self.canvas is not None: valid_area(self.canvas)
35
+ result: BaseGeometry
36
+ if self.mode == 'inside': result = self.shape.buffer(-self.padding) if self.padding else self.shape
37
+ elif self.mode == 'outside':
38
+ if self.canvas is None: raise ValueError('Outside mode requires a finite canvas')
39
+ result = self.canvas.buffer(-self.padding).difference(self.shape.buffer(self.padding))
40
+ else:
41
+ if not isfinite(self.band_width) or self.band_width <= 0: raise ValueError('Band width must be finite and positive')
42
+ result = self.shape.boundary.buffer(self.band_width/2).buffer(-self.padding)
43
+ if self.canvas is not None: result = result.intersection(self.canvas)
44
+ if not isinstance(result, (Polygon, MultiPolygon)): raise ValueError('Region has no polygonal usable area')
45
+ valid_area(result)
46
+ return result
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Readability:
51
+ """Minimum dimensions in output pixels/points; scale is output units per world unit."""
52
+ output_scale: float = 1
53
+ stroke: float = 0.5
54
+ hole_diameter: float = 1
55
+ edge_gap: float = 0.75
56
+ separation: float = 0.75
57
+
58
+ def __post_init__(self) -> None:
59
+ if not isfinite(self.output_scale) or self.output_scale <= 0: raise ValueError('Output scale must be positive')
60
+ if not all(isfinite(v) and v >= 0 for v in (self.stroke, self.hole_diameter, self.edge_gap, self.separation)): raise ValueError('Readable dimensions must be finite and nonnegative')
61
+
62
+ def radius_minimum(self, ratio: float) -> float:
63
+ if ratio == 0 and self.hole_diameter: raise ValueError('A readable hole requires a positive ring ratio')
64
+ return max(self.stroke/(1-ratio), self.hole_diameter/(2*ratio) if ratio else 0)/self.output_scale
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class ContourSettings:
69
+ mode: Literal['contain', 'follow', 'terminate'] = 'contain'
70
+ adaptive: bool = True
71
+ minimum_radius: float = 1
72
+ maximum_neighbor_ratio: float = 2
73
+ width_resolution: float = 10
74
+ width_samples: int = 10000
75
+ width_divisor: float = 4
76
+ anchor_spacing: float = 15
77
+ max_anchors: int = 2000
78
+ boundary_fraction: float = 0.6
79
+ tangent_window: float = 10
80
+ guidance: float = 0.85
81
+ tolerance: float = 0.5 # Output units, converted with readability.output_scale.
82
+ strict_terminals: bool = False
83
+ readability: Readability = Readability()
84
+
85
+ def __post_init__(self) -> None:
86
+ if self.mode not in ('contain', 'follow', 'terminate'): raise ValueError('Unknown boundary treatment')
87
+ for value in (self.minimum_radius, self.width_resolution, self.width_divisor, self.anchor_spacing, self.tangent_window):
88
+ if not isfinite(value) or value <= 0: raise ValueError('Contour dimensions must be positive and finite')
89
+ if not isfinite(self.maximum_neighbor_ratio) or self.maximum_neighbor_ratio < 1: raise ValueError('Neighbor ratio must be at least one')
90
+ if not all(isfinite(v) and 0 <= v <= 1 for v in (self.boundary_fraction, self.guidance)): raise ValueError('Fractions must be in [0,1]')
91
+ if not isfinite(self.tolerance) or self.tolerance < 0: raise ValueError('Tolerance must be nonnegative')
92
+ for count in (self.width_samples, self.max_anchors):
93
+ if type(count) is not int or count < 4: raise ValueError('Sampling budgets must be integers of at least four')
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class BoundaryAnchor:
98
+ center: Point
99
+ component: int
100
+ arc: float
101
+ tangent: float
102
+
103
+
104
+ class DistanceField:
105
+ """Signed distance in world units; positive inside the resolved usable region."""
106
+ def __init__(self, region: Area) -> None:
107
+ valid_area(region)
108
+ self.region = region
109
+
110
+ def sample(self, x: float, y: float) -> float:
111
+ if not isfinite(x) or not isfinite(y): raise ValueError('Sample coordinates must be finite')
112
+ point = Point(x, y)
113
+ distance = float(self.region.boundary.distance(point))
114
+ return distance if self.region.covers(point) else -distance
115
+
116
+
117
+ class LocalWidth:
118
+ """Bounded sampled distance-ridge estimate, not an exact medial axis.
119
+
120
+ Eight-neighbor maxima approximate inscribed-disk ridges. Sampling automatically
121
+ coarsens to max_samples; features below this resolution may be missed.
122
+ """
123
+ def __init__(self, region: Area, resolution: float, max_samples: int) -> None:
124
+ if not isfinite(resolution) or resolution <= 0 or type(max_samples) is not int or max_samples < 4: raise ValueError('Width resolution and sampling budget must be positive')
125
+ self.distance = DistanceField(region)
126
+ x0, y0, x1, y1 = region.bounds
127
+ self.resolution = max(resolution, ((x1-x0)*(y1-y0)/max_samples)**0.5)
128
+ nx, ny = max(1, ceil((x1-x0)/self.resolution)), max(1, ceil((y1-y0)/self.resolution))
129
+ while nx*ny > max_samples:
130
+ self.resolution *= 1.1
131
+ nx, ny = max(1, ceil((x1-x0)/self.resolution)), max(1, ceil((y1-y0)/self.resolution))
132
+ values = {(i, j): self.distance.sample(x0+(i+0.5)*self.resolution, y0+(j+0.5)*self.resolution) for i in range(nx) for j in range(ny)}
133
+ self.ridges = [(x0+(i+0.5)*self.resolution, y0+(j+0.5)*self.resolution, radius) for (i, j), radius in values.items()
134
+ if radius > 0 and all(radius >= values.get((i+di, j+dj), -1) for di in (-1, 0, 1) for dj in (-1, 0, 1))]
135
+
136
+ def sample(self, x: float, y: float) -> float:
137
+ disks = [(hypot(x-cx, y-cy), radius) for cx, cy, radius in self.ridges if hypot(x-cx, y-cy) <= radius+self.resolution]
138
+ if disks: return 2*min(disks)[1]
139
+ return 2*max(0, self.distance.sample(x, y))
140
+
141
+
142
+ class ContourGuide:
143
+ def __init__(self, region: Area, settings: ContourSettings, minimum_radius: float, preferred_radius: float) -> None:
144
+ self.region, self.settings = region, settings
145
+ self.distance = DistanceField(region)
146
+ self.width = LocalWidth(region, settings.width_resolution, settings.width_samples)
147
+ inset = region.buffer(-(minimum_radius+1e-7))
148
+ original_polygons = [region] if isinstance(region, Polygon) else list(region.geoms)
149
+ original_rings = [LineString(r.coords) for polygon in original_polygons for r in (polygon.exterior, *polygon.interiors)]
150
+ perimeter = sum(r.length for r in original_rings)
151
+ self.boundary_samples: list[tuple[Point, float]] = []
152
+ for ring in original_rings:
153
+ count = max(1, int(settings.max_anchors*ring.length/perimeter))
154
+ for i in range(count):
155
+ if len(self.boundary_samples) >= settings.max_anchors: break
156
+ self.boundary_samples.append((ring.interpolate(i*ring.length/count), ring.length/count))
157
+ self.unreadable_boundary_samples = sum(inset.is_empty or inset.distance(point) > 2*minimum_radius for point, _ in self.boundary_samples)
158
+ polygons = [inset] if isinstance(inset, Polygon) else list(inset.geoms) if isinstance(inset, MultiPolygon) else []
159
+ rings = [LineString(ring.coords) for polygon in polygons for ring in (polygon.exterior, *polygon.interiors) if not ring.is_empty]
160
+ total = sum(ring.length for ring in rings)
161
+ spacing = max(settings.anchor_spacing, total/max(1, settings.max_anchors-len(rings)))
162
+ self.anchors: list[BoundaryAnchor] = []
163
+ for component, ring in enumerate(rings):
164
+ count = max(1, int(ring.length/spacing))
165
+ # Include vertices where direction changes sharply, subject to the same hard budget.
166
+ distances = {i*ring.length/count for i in range(count)}
167
+ coords = list(ring.coords)
168
+ for i in range(1, len(coords)-1):
169
+ a, b, c = coords[i-1], coords[i], coords[i+1]
170
+ u, v = (b[0]-a[0], b[1]-a[1]), (c[0]-b[0], c[1]-b[1])
171
+ if u[0]*v[0]+u[1]*v[1] < 0.7*hypot(*u)*hypot(*v): distances.add(float(ring.project(Point(b))))
172
+ for arc in sorted(distances):
173
+ if len(self.anchors) >= settings.max_anchors: break
174
+ point = ring.interpolate(arc)
175
+ radius = max(minimum_radius, min(preferred_radius, self.width.sample(point.x, point.y)/settings.width_divisor))
176
+ usable = region.buffer(-(radius+1e-7))
177
+ if not usable.is_empty:
178
+ shifted = nearest_points(point, usable.boundary)[1]
179
+ if point.distance(shifted) <= 2*radius: point = shifted
180
+ before, after = ring.interpolate((arc-settings.tangent_window/2)%ring.length), ring.interpolate((arc+settings.tangent_window/2)%ring.length)
181
+ self.anchors.append(BoundaryAnchor(point, component, arc, atan2(after.y-before.y, after.x-before.x)))
182
+
183
+ def nearest(self, point: Point) -> BoundaryAnchor | None:
184
+ return min(self.anchors, key=lambda anchor: anchor.center.distance(point)) if self.anchors else None
185
+
186
+ def terminal_center(self, point: Point, radius: float) -> Point | None:
187
+ inset = self.region.buffer(-(radius+1e-7))
188
+ if inset.is_empty: return None
189
+ return nearest_points(point, inset.boundary)[1]
190
+
191
+
192
+ @dataclass(frozen=True)
193
+ class ContourReport:
194
+ boundary_coverage: float
195
+ boundary_nodes: int
196
+ unreadable_boundary_samples: int
197
+ terminal_count: int
198
+ unanchored_terminals: tuple[str, ...]
199
+ terminal_distances: tuple[float, ...]
200
+ unanchored_reasons: tuple[tuple[str, str], ...]
201
+ readable_failures: int
202
+ width_failures: int
203
+ neighbor_ratio_failures: int
204
+ strict_satisfied: bool
205
+ sampled_width_resolution: float
206
+ minimum_radius: float
207
+ maximum_radius: float
graph_ics/coverage.py ADDED
@@ -0,0 +1,151 @@
1
+ """Approximate population coverage over clipped usable tiles, not empty-space area."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from math import ceil, floor, isfinite
7
+ from random import Random
8
+ from typing import TYPE_CHECKING
9
+
10
+ from shapely.geometry import box, Polygon, MultiPolygon
11
+ from shapely.geometry.base import BaseGeometry
12
+ from shapely.ops import unary_union
13
+
14
+ from .fields import positive_sample
15
+ from .node import Node
16
+
17
+ if TYPE_CHECKING:
18
+ from .graph import Graph
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class CoverageSettings:
23
+ tile_size: float = 25
24
+ max_tiles: int = 4096
25
+ parent_choices: int = 8
26
+ allow_components: bool = True
27
+ reseed_attempts: int = 200
28
+ boundary_weight: float = 1
29
+ boundary_band: float = 10
30
+ narrow_weight: float = 1
31
+ narrow_width: float = 20
32
+ reseed_interval: int = 0
33
+ seed_components: bool = False
34
+
35
+ def __post_init__(self) -> None:
36
+ if type(self.seed_components) is not bool: raise ValueError('seed_components must be boolean')
37
+ if type(self.reseed_interval) is not int or self.reseed_interval < 0: raise ValueError('reseed_interval must be a nonnegative integer')
38
+ for value in (self.tile_size, self.boundary_weight, self.boundary_band, self.narrow_weight, self.narrow_width):
39
+ if not isfinite(value) or value <= 0: raise ValueError('Coverage dimensions and weights must be positive and finite')
40
+ for value in (self.max_tiles, self.parent_choices):
41
+ if type(value) is not int or value <= 0: raise ValueError('Coverage sampling limits must be positive integers')
42
+ if type(self.reseed_attempts) is not int or self.reseed_attempts < 0: raise ValueError('Reseeding budget must be nonnegative')
43
+
44
+
45
+ @dataclass
46
+ class CoverageTile:
47
+ column: int
48
+ row: int
49
+ geometry: BaseGeometry
50
+ expected: float
51
+ actual: int = 0
52
+
53
+ @property
54
+ def deficit(self) -> float:
55
+ return max(0, self.expected-self.actual)
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class CoverageReport:
60
+ expected_nodes: float
61
+ actual_nodes: int
62
+ residual_underfill: float
63
+ occupied_tiles: int
64
+ usable_tiles: int
65
+ tile_size: float
66
+ reseed_attempts: int
67
+ reseeds: int
68
+ occupied_tile_area_fraction: float = 0
69
+
70
+
71
+ class CoverageTracker:
72
+ """Four area-weighted clipped quadrature samples per tile integrate density.
73
+
74
+ Without a density field, normalize usable area weights to target_nodes.
75
+ With a density field, retain the requested integral, even if unattainable.
76
+ Scheduling examines a fixed-size random tournament, not all active parents.
77
+ """
78
+ def __init__(self, graph: Graph, settings: CoverageSettings) -> None:
79
+ if settings.narrow_weight != 1 and graph.contour_guide is None: raise ValueError('Narrow-region weighting requires contour width estimates')
80
+ self.settings, self.graph = settings, graph
81
+ region = graph.outline_polygon.difference(unary_union(graph._illegal_areas))
82
+ self.pending_components = sorted(([region] if isinstance(region, Polygon) else list(region.geoms) if isinstance(region, MultiPolygon) else []), key=lambda part: part.area, reverse=True) if settings.seed_components else []
83
+ self.component_attempts = 0
84
+ self.x0, self.y0, x1, y1 = graph.outline_polygon.bounds
85
+ self.tile_size = settings.tile_size
86
+ while ceil((x1-self.x0)/self.tile_size)*ceil((y1-self.y0)/self.tile_size) > settings.max_tiles: self.tile_size *= 1.25
87
+ self.tiles: list[CoverageTile] = []
88
+ self.lookup: dict[tuple[int, int], CoverageTile] = {}
89
+ for column in range(ceil((x1-self.x0)/self.tile_size)):
90
+ for row in range(ceil((y1-self.y0)/self.tile_size)):
91
+ left, top = self.x0+column*self.tile_size, self.y0+row*self.tile_size
92
+ geometry = region.intersection(box(left, top, left+self.tile_size, top+self.tile_size))
93
+ if geometry.area <= 0: continue
94
+ expected = 0.0
95
+ for dx in (0, 0.5):
96
+ for dy in (0, 0.5):
97
+ part = geometry.intersection(box(left+dx*self.tile_size, top+dy*self.tile_size, left+(dx+0.5)*self.tile_size, top+(dy+0.5)*self.tile_size))
98
+ if part.area <= 0: continue
99
+ point = part.representative_point()
100
+ weight = settings.boundary_weight if region.boundary.distance(point) <= settings.boundary_band else 1
101
+ if graph.contour_guide is not None and graph.contour_guide.width.sample(point.x, point.y) < settings.narrow_width: weight *= settings.narrow_weight
102
+ expected += part.area*positive_sample(graph.fields.density, point.x, point.y)*weight
103
+ if not isfinite(expected): raise ValueError('Integrated density is too large')
104
+ tile = CoverageTile(column, row, geometry, expected)
105
+ self.tiles.append(tile)
106
+ self.lookup[column, row] = tile
107
+ total = sum(tile.expected for tile in self.tiles)
108
+ if not isfinite(total): raise ValueError('Total integrated density is too large')
109
+ if graph.fields.density is None:
110
+ for tile in self.tiles: tile.expected = graph.target_nodes*tile.expected/total if total else 0
111
+ for node in graph.nodes: self.accept(node)
112
+
113
+ def key(self, node: Node) -> tuple[int, int]:
114
+ return floor((node.center.x-self.x0)/self.tile_size), floor((node.center.y-self.y0)/self.tile_size)
115
+
116
+ def accept(self, node: Node) -> None:
117
+ tile = self.lookup.get(self.key(node))
118
+ if tile is not None: tile.actual += 1
119
+
120
+ def score(self, node: Node) -> float:
121
+ x, y = self.key(node)
122
+ return sum(tile.deficit for dx in (-1, 0, 1) for dy in (-1, 0, 1) if (tile := self.lookup.get((x+dx, y+dy))) is not None)
123
+
124
+ def select_parent(self, frontier: list[Node], rng: Random) -> int:
125
+ choices = rng.sample(range(len(frontier)), min(len(frontier), self.settings.parent_choices))
126
+ return max(choices, key=lambda index: self.score(frontier[index]))
127
+
128
+ def seed(self, rng: Random, *, fill_area: bool = False) -> Node | None:
129
+ if self.pending_components:
130
+ component = self.pending_components[0]
131
+ x0,y0,x1,y1 = component.bounds
132
+ point = component.representative_point()
133
+ x,y = (point.x,point.y) if self.component_attempts == 0 else (rng.uniform(x0,x1),rng.uniform(y0,y1))
134
+ node = self.graph._new_node(x,y,is_seed=True)
135
+ valid = component.covers(node.center) and self.graph.can_place_node(node)
136
+ self.component_attempts += 1
137
+ if valid or self.component_attempts >= 32:
138
+ self.pending_components.pop(0)
139
+ self.component_attempts = 0
140
+ return node if valid else None
141
+ candidates = [tile for tile in self.tiles if fill_area or tile.deficit > 0]
142
+ if not candidates: return None
143
+ tile = rng.choices(candidates, weights=[t.geometry.area/(1+t.actual)**2 if fill_area else t.deficit for t in candidates], k=1)[0]
144
+ x0, y0, x1, y1 = tile.geometry.bounds
145
+ node = self.graph._new_node(rng.uniform(x0, x1), rng.uniform(y0, y1), is_seed=True)
146
+ return node if tile.geometry.covers(node.center) and self.graph.can_place_node(node) else None
147
+
148
+ def report(self, attempts: int, reseeds: int) -> CoverageReport:
149
+ return CoverageReport(sum(t.expected for t in self.tiles), sum(t.actual for t in self.tiles), sum(t.deficit for t in self.tiles),
150
+ sum(t.actual > 0 for t in self.tiles), len(self.tiles), self.tile_size, attempts, reseeds,
151
+ sum(t.geometry.area for t in self.tiles if t.actual > 0)/sum(t.geometry.area for t in self.tiles) if self.tiles else 0)
@@ -0,0 +1,18 @@
1
+ # UK population sample provenance
2
+
3
+ The compressed `uk_population.json.gz` bundles a small educational derivative, not the full source raster. It is package data so CLI examples work offline. `uk_population_sources.json` records the exact query, retrieval date, source checksums, returned extent and dimensions.
4
+
5
+ Population: WorldPop / CIESIN (2018), Global High Resolution Population Denominators Project, **2020** annual density estimates, persons per square kilometre. DOI [10.5258/SOTON/WP00674](https://www.worldpop.org/doi/10.5258/SOTON/WP00674). Accessed through [WorldPop's 1-km density service](https://worldpop.arcgis.com/arcgis/rest/services/WorldPop_Population_Density_1km/ImageServer). WorldPop data attribution is retained under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). This derivative is not endorsed by the data producers.
6
+
7
+ Boundary: [Natural Earth](https://www.naturalearthdata.com/about/terms-of-use/), public domain, 1:50m Admin 0 Countries, version 5.1.2. The source URL is pinned to that release; the UK feature is extracted and simplified by 0.008 degrees with topology preservation. Includes Northern Ireland and UK islands; excludes the Republic of Ireland.
8
+
9
+ Preparation: select time 1577836800000 (2020-01-01), disable raster rendering, request raw F32 density for longitude -8.7 to 2.1 and latitude 49.8 to 61.1, bilinearly resample to 360 columns by 560 rows, map no-data to zero and round finite values to two decimals. Pixel centres are registered with the boundary, north at the top. Display uses longitude scaled by cos(55 degrees), height 4000 world units; it is not an equal-area projection.
10
+
11
+ The graph uses t = min(1, log(1+density)/log(10001)), preferred spacing 5 + 20*(1-t), and coordinated geometry scale 0.45 + 0.9*(1-t). This compresses urban extremes and preserves some rural coverage. Density is not represented linearly and nodes are not individual people. Small islands/coasts can remain empty due to spacing, simplified boundaries and finite generation budgets.
12
+
13
+ Refresh explicitly with `python scripts/prepare_uk_data.py` (network and Pillow required for preparation only). Runtime rendering uses the bundled data and existing Cairo dependency. Sources and exact query are recorded to make transformations reviewable.
14
+
15
+
16
+ ## Spain
17
+
18
+ `spain_population.json.gz` uses the same WorldPop 2020 source, CC BY 4.0 attribution, resampling method and Natural Earth release. `spain_population_sources.json` records the exact query, checksums, dimensions and extent. The crop is longitude -9.6 to 4.5, latitude 35.5 to 44.1: mainland Spain and the Balearics are included, the Canary Islands are excluded. Small North African territories inside that crop may remain unfilled by growth. Display scales longitude by cosine of the crop's central latitude; it is not equal-area. Refresh with `python scripts/prepare_uk_data.py spain`.
@@ -0,0 +1 @@
1
+ """Attributed, offline sample data; see README.md for provenance and transformations."""
Binary file
@@ -0,0 +1,33 @@
1
+ {
2
+ "year": 2020,
3
+ "units": "persons per square kilometre",
4
+ "accessed": "2026-10-23",
5
+ "raster_source": "https://worldpop.arcgis.com/arcgis/rest/services/WorldPop_Population_Density_1km/ImageServer",
6
+ "raster_query": "https://worldpop.arcgis.com/arcgis/rest/services/WorldPop_Population_Density_1km/ImageServer/exportImage?f=json&bbox=-9.6%2C35.5%2C4.5%2C44.1&bboxSR=4326&imageSR=4326&size=360%2C560&format=tiff&pixelType=F32&interpolation=RSP_BilinearInterpolation&time=1577836800000&adjustAspectRatio=false&renderingRule=%7B%22rasterFunction%22%3A+%22None%22%7D",
7
+ "raster_sha256": "2e143d0f21a6020e825010ecba5dd8d8540cd9ae62e2bfc6c7c761d341496071",
8
+ "boundary_source": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/v5.1.2/geojson/ne_50m_admin_0_countries.geojson",
9
+ "boundary_sha256": "3e458fc036ad0a66411f2c1e6cac49c5d7bfb81cb1123bc513b22511a2b7fdeb",
10
+ "raster_license": "CC BY 4.0",
11
+ "boundary_license": "Public domain",
12
+ "bbox": [
13
+ -9.6,
14
+ 35.5,
15
+ 4.5,
16
+ 44.1
17
+ ],
18
+ "dimensions": [
19
+ 360,
20
+ 560
21
+ ],
22
+ "extent": {
23
+ "xmin": -9.6,
24
+ "ymin": 35.5,
25
+ "xmax": 4.5,
26
+ "ymax": 44.1,
27
+ "spatialReference": {
28
+ "wkid": 4326,
29
+ "latestWkid": 4326
30
+ }
31
+ },
32
+ "note": "Bilinear resampling of 1-km estimates to an educational grid; not population totals. Simplified Natural Earth 5.1.2 boundary."
33
+ }
Binary file
@@ -0,0 +1,33 @@
1
+ {
2
+ "year": 2020,
3
+ "units": "persons per square kilometre",
4
+ "accessed": "2026-10-23",
5
+ "raster_source": "https://worldpop.arcgis.com/arcgis/rest/services/WorldPop_Population_Density_1km/ImageServer",
6
+ "raster_query": "https://worldpop.arcgis.com/arcgis/rest/services/WorldPop_Population_Density_1km/ImageServer/exportImage?f=json&bbox=-8.7%2C49.8%2C2.1%2C61.1&bboxSR=4326&imageSR=4326&size=360%2C560&format=tiff&pixelType=F32&interpolation=RSP_BilinearInterpolation&time=1577836800000&adjustAspectRatio=false&renderingRule=%7B%22rasterFunction%22%3A+%22None%22%7D",
7
+ "raster_sha256": "1d2b1c05badd6fb27cd552efe0997db428d4b8649ee1ca806c1769f4ada6ab00",
8
+ "boundary_source": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/v5.1.2/geojson/ne_50m_admin_0_countries.geojson",
9
+ "boundary_sha256": "3e458fc036ad0a66411f2c1e6cac49c5d7bfb81cb1123bc513b22511a2b7fdeb",
10
+ "raster_license": "CC BY 4.0",
11
+ "boundary_license": "Public domain",
12
+ "bbox": [
13
+ -8.7,
14
+ 49.8,
15
+ 2.1,
16
+ 61.1
17
+ ],
18
+ "dimensions": [
19
+ 360,
20
+ 560
21
+ ],
22
+ "extent": {
23
+ "xmin": -8.7,
24
+ "ymin": 49.8,
25
+ "xmax": 2.1,
26
+ "ymax": 61.1,
27
+ "spatialReference": {
28
+ "wkid": 4326,
29
+ "latestWkid": 4326
30
+ }
31
+ },
32
+ "note": "Bilinear resampling of 1-km estimates to an educational grid; not population totals. Simplified Natural Earth 5.1.2 boundary."
33
+ }
graph_ics/drawing.py ADDED
@@ -0,0 +1,30 @@
1
+ """The small drawing contract used by geometry, without a runtime Cairo import."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Protocol, cast
6
+
7
+ if TYPE_CHECKING:
8
+ from cairo import LineCap, LineJoin, Path
9
+
10
+ # Cairo's enum uses integer zero for butt caps; keep imports optional at runtime.
11
+ BUTT_CAP = cast('LineCap', 0)
12
+ ROUND_JOIN = cast('LineJoin', 1)
13
+
14
+
15
+ class DrawingContext(Protocol):
16
+ def save(self) -> None: ...
17
+ def restore(self) -> None: ...
18
+ def translate(self, tx: float, ty: float) -> None: ...
19
+ def append_path(self, path: Path) -> None: ...
20
+ def fill(self) -> None: ...
21
+ def close_path(self) -> None: ...
22
+ def set_line_join(self, line_join: LineJoin) -> None: ...
23
+ def new_path(self) -> None: ...
24
+ def arc(self, xc: float, yc: float, radius: float, angle1: float, angle2: float) -> None: ...
25
+ def move_to(self, x: float, y: float) -> None: ...
26
+ def line_to(self, x: float, y: float) -> None: ...
27
+ def set_source_rgba(self, red: float, green: float, blue: float, alpha: float = 1) -> None: ...
28
+ def set_line_width(self, width: float) -> None: ...
29
+ def set_line_cap(self, line_cap: LineCap) -> None: ...
30
+ def stroke(self) -> None: ...
graph_ics/edge.py ADDED
@@ -0,0 +1,72 @@
1
+ """Straight edges clipped away from node rings, with butt-ended strokes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from math import isfinite
6
+ from typing import Literal
7
+
8
+
9
+ from shapely.geometry import LineString, Point, Polygon
10
+
11
+ from .colors import hex2rgb
12
+ from .drawing import DrawingContext
13
+ from .node import Node
14
+ from .obj import Obj
15
+ from .vector import Vector
16
+
17
+ EdgeStyle = Literal["solid", "dashed", "dotted", "double"]
18
+ EDGE_STYLES: tuple[EdgeStyle, ...] = ("solid", "dashed", "dotted", "double")
19
+
20
+ EDGE_DEFAULT_THICKNESS = 1.0
21
+ EDGE_DEFAULT_COLOR = '#a6b7c8'
22
+ EDGE_DEFAULT_OPACITY = 1.0
23
+ EDGE_DEFAULT_NODE_DISTANCE = 1.0
24
+
25
+
26
+ class Edge(Obj):
27
+ """A visible segment separated from each endpoint ring by a fixed gap.
28
+
29
+ The footprint is the full butt-ended stroke rectangle. Node coordinates
30
+ must remain fixed after construction; moving geometry is a future stage.
31
+ """
32
+
33
+ def __init__(self, start_node: Node, end_node: Node, thickness: float = 1.0, color: str = EDGE_DEFAULT_COLOR,
34
+ opacity: float = 1.0, edge_node_distance: float = 1.0, style: EdgeStyle = "solid") -> None:
35
+ if style not in EDGE_STYLES: raise ValueError("Unknown edge style")
36
+ self.style = style
37
+ if not all(isfinite(v) for v in (thickness, opacity, edge_node_distance)): raise ValueError('Edge values must be finite')
38
+ if thickness <= 0 or edge_node_distance < 0: raise ValueError('Thickness must be positive and endpoint gap nonnegative')
39
+ if not 0 <= opacity <= 1: raise ValueError('Opacity must be between zero and one')
40
+ hex2rgb(color)
41
+ self.start_node, self.end_node = start_node, end_node
42
+ self.thickness, self.opacity = float(thickness), float(opacity)
43
+ self.color, self.edge_node_distance = color, float(edge_node_distance)
44
+ self.vector = Vector(start_node.center, end_node.center)
45
+ # Vector retains the historical p1-p2 direction; subtraction goes toward p2.
46
+ self.nx, self.ny = self.vector.get_normalized()
47
+ if self.vector.length <= start_node.outer_radius + end_node.outer_radius + 2*edge_node_distance:
48
+ raise ValueError('Nodes are too close for a positive visible edge length')
49
+ self.start_point = Point(start_node.center.x-self.nx*(start_node.outer_radius+edge_node_distance), start_node.center.y-self.ny*(start_node.outer_radius+edge_node_distance))
50
+ self.end_point = Point(end_node.center.x+self.nx*(end_node.outer_radius+edge_node_distance), end_node.center.y+self.ny*(end_node.outer_radius+edge_node_distance))
51
+ self.line_string = LineString([self.start_point, self.end_point])
52
+ self.footprint: Polygon = self.line_string.buffer(self.thickness/2, cap_style='flat')
53
+
54
+ @property
55
+ def length(self) -> float:
56
+ """Length of the visible segment, excluding endpoint gaps and rings."""
57
+ return float(self.line_string.length)
58
+
59
+ def overlap(self, other: Edge | Node) -> bool:
60
+ """Check full strokes and unrelated node clearances, including touching.
61
+
62
+ Endpoint nodes are allowed: their explicit edge gap controls attachment.
63
+ Shared-node edges still undergo visible-stroke collision checks.
64
+ """
65
+ if isinstance(other, Edge): return bool(self.footprint.intersects(other.footprint))
66
+ if other is self.start_node or other is self.end_node: return False
67
+ return float(self.footprint.distance(other.center)) <= other.buffer_radius
68
+
69
+ def draw(self, context: DrawingContext, x_shift: float = 0, y_shift: float = 0) -> DrawingContext:
70
+ """Compatibility wrapper for the shared renderer."""
71
+ from .rendering import draw_edge
72
+ return draw_edge(self, context, x_shift, y_shift)