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
@@ -0,0 +1,178 @@
1
+ """Visual controls reference generated from the same public factories and renderer."""
2
+ from __future__ import annotations
3
+ from pathlib import Path
4
+ from html import escape
5
+ import json
6
+ from math import log1p
7
+ from .samples import build_example
8
+ from .gallery_page import gallery_page
9
+ from .node import NODE_SHAPES
10
+ from .edge import EDGE_STYLES
11
+ from .quality import AngleSettings
12
+ from .rendering import export_graph
13
+ from .styles import GraphStyle
14
+ from .validation import validate_graph
15
+ from .replay import EventRecorder, Playback
16
+ from .animation import ReplayRenderer
17
+ from .uk import population_field, population_region, WIDTH, HEIGHT, population_data
18
+
19
+ # Each CLI switch has a short definition and a visual example anchor. File-management
20
+ # switches share the artifact demonstration: they change storage, not graph geometry.
21
+ CLI_OPTIONS: tuple[tuple[str, str, str], ...] = (
22
+ ('--fill-area', 'Search unfilled space with periodic reseeding; nodes remains a safety cap. Stops report exhausted search or limits, not complete packing.', 'scene-files'),
23
+ ('--config', 'Load a complete JSON/YAML scene; file paths resolve beside that scene.', 'scene-files'),
24
+ ('--gif', 'Export an opaque looping GIF instead of individual PNG frames.', 'animation'),
25
+ ('--node-inner-radius / --node-outer-radius / --node-buffer', 'Inner and outer ring radii, and clearance to unrelated geometry, in world units.', 'scene-files'),
26
+ ('--edge-thickness / --edge-node-distance / --edge-length-min / --edge-length-max', 'Full stroke width, ring-to-line gap, and visible length range in world units.', 'scene-files'),
27
+ ('--example', 'Select a documented recipe; list shows names and describe explains it.', 'angles'),
28
+ ('--palette', 'Choose colours for the complete scene; geometry stays the same unless text width changes.', 'palettes'),
29
+ ('--seed', 'Change the random layout; reuse the seed to reproduce it.', 'seeds'),
30
+ ('--nodes', 'Requested total population including seeds. Constraints can stop growth below it.', 'population'),
31
+ ('--node-shape', 'Circle, square, diamond, triangle or hexagon; hollow unless inner radius is zero.', 'shapes'),
32
+ ('--edge-style', 'Solid, dashed, dotted or double lines inside a collision-protected corridor.', 'lines'),
33
+ ('--minimum-angle', 'Hard ban below this incident angle in degrees; straight continuation is 180.', 'angles'),
34
+ ('--preferred-angle', 'Soft angular target; must be at least the hard minimum when nonzero.', 'angles'),
35
+ ('--angle-penalty', 'Strength from 0 to 1 of soft rejection below the preferred angle.', 'angles'),
36
+ ('--scale', 'Output units per world unit: larger image, same geometry. Compare native dimensions below.', 'output'),
37
+ ('--margin', 'World-unit whitespace around the region, scaled with the image.', 'output'),
38
+ ('--transparent', 'Leave the background transparent. Checkerboard indicates alpha in these previews.', 'output'),
39
+ ('--output', 'PNG/SVG file for render; new folder for frames; gallery folder for gallery.', 'files'),
40
+ ('--record', 'Save accepted events as JSONL while rendering; later replay needs no growth rerun.', 'animation'),
41
+ ('--log', 'Read recorded geometry for frames. Recipe, seed and node target do not rebuild it.', 'animation'),
42
+ ('--fps', 'Frames per second. More samples make the same event timeline smoother.', 'animation'),
43
+ ('--seconds-per-event', 'Increase to slow the recorded growth; each event is given this duration.', 'animation'),
44
+ ('--max-frames', 'Safety cap: an oversized frame sequence is rejected, not silently truncated.', 'animation'),
45
+ ('--force', 'Allow render to replace its existing image or recording; does not affect appearance.', 'files'),
46
+ ('--all-palettes', 'Expand every regular recipe across all ten palettes instead of the curated selection.', 'palettes'),
47
+ ('--quick', 'Generate six small scenes plus this controls guide; omit for all recipes and large examples.', 'files'),
48
+ ('--help / -h', 'Show command-specific usage and defaults; no image is generated.', 'files'),
49
+ )
50
+
51
+
52
+ def generate_controls(destination: Path) -> Path:
53
+ figures = destination/'figures'
54
+ figures.mkdir(parents=True, exist_ok=True)
55
+ cards: list[str] = []
56
+ records: list[dict[str, object]] = []
57
+ generate_style_key(figures)
58
+
59
+ def case(group: str, name: str, explanation: str, *, recipe: str = 'sprawl', seed: int = 7, nodes: int = 480,
60
+ shape: str = 'circle', line: str = 'solid', palette: str = 'porcelain', scale: float = 1, margin: float = 16,
61
+ transparent: bool = False, angles: AngleSettings | None = None) -> None:
62
+ # Lookups retain the public Literal types after validating the gallery specification.
63
+ selected_shape = next(value for value in NODE_SHAPES if value == shape)
64
+ selected_line = next(value for value in EDGE_STYLES if value == line)
65
+ graph = build_example(recipe, seed=seed, nodes=nodes, palette=palette, node_shape=selected_shape, edge_style=selected_line, angles=angles)
66
+ graph.build()
67
+ validate_graph(graph)
68
+ stem = 'control-'+name
69
+ background = None if transparent else GraphStyle.named(palette).background
70
+ dimensions = export_graph(graph, figures/(stem+'.png'), background=background, scale=scale, margin=margin, frame='region')
71
+ export_graph(graph, figures/(stem+'.svg'), background=background, scale=scale, margin=margin, frame='region')
72
+ command = f'graph-ics render --example {recipe} --palette {palette} --nodes {nodes} --seed {seed} --node-shape {shape} --edge-style {line} --scale {scale} --margin {margin}'
73
+ if transparent: command += ' --transparent'
74
+ if angles is not None: command += f' --minimum-angle {angles.minimum} --preferred-angle {angles.preferred} --angle-penalty {angles.penalty}'
75
+ command += f' --output examples/output/{name}.png'
76
+ records.append(dict(group=group, name=name, explanation=explanation, command=command, dimensions=dimensions, nodes=len(graph.nodes)))
77
+ cards.append(f'<article class="{group}"><h3>{escape(name.replace("-", " ").title())}</h3><a class="alpha" href="figures/{stem}.png"><img src="figures/{stem}.png" loading="lazy" alt="{escape(name)}"></a><p>{escape(explanation)}</p><p>{dimensions[0]} &times; {dimensions[1]}; {len(graph.nodes)} nodes</p><details><summary>Reproduce / SVG</summary><pre class="command">{escape(command)}</pre><a href="figures/{stem}.svg">SVG</a></details></article>')
78
+
79
+ sections: list[str] = []
80
+ def section(group: str, title: str, explanation: str) -> None:
81
+ sections.append(f'<section id="{group}"><h2>{title}</h2><p>{explanation}</p><div class="grid">'+''.join(card for card in cards if card.startswith(f'<article class="{group}"'))+'</div></section>')
82
+
83
+ for shape in NODE_SHAPES: case('shapes', 'shape-'+shape, 'Same layout and outer radius. Polygon corners fit inside the reserved circle; endpoint gaps can therefore look larger.', shape=shape)
84
+ section('shapes', 'Node shapes', 'These vary only the visible node outline. Shape choice is preserved by replay.<br><img class="style-key" src="figures/style-key.png" alt="Enlarged shape and connection style key">')
85
+ for line in EDGE_STYLES: case('lines', 'line-'+line, 'Same layout and full-width collision corridor. Dashed gaps remain reserved; double lines split the width into thirds.', recipe='lines', line=line)
86
+ section('lines', 'Connection patterns', 'Line patterns are rendering styles on straight connections. Curves, arrows and moving paths are not implemented.')
87
+ for name, angles in (('free', AngleSettings()), ('hard-45', AngleSettings(45)), ('soft-80', AngleSettings(0,80,0.9)), ('strict-60-90', AngleSettings(60,90,0.9))):
88
+ case('angles', 'angles-'+name, f'Hard minimum {angles.minimum} degrees; preference {angles.preferred}; penalty {angles.penalty}. Identical seed and target, different rejection decisions.', angles=angles, nodes=480)
89
+ section('angles', 'Angle restrictions', 'Hard rules forbid small junctions; soft penalties merely make them less likely. Stricter settings change the subsequent random growth and can reduce coverage.')
90
+ for seed in (7,19): case('seeds', f'seed-{seed}', 'Same settings, different random layout.', seed=seed)
91
+ section('seeds', 'Random seeds', 'Compare patterns while holding all geometry controls fixed.')
92
+ for count in (60,180,480): case('population', f'nodes-{count}', 'Increasing the requested population fills more of the available canvas.', nodes=count)
93
+ section('population', 'Population target', 'A target is not a promise. Every candidate must fit and the attempt budget is finite.')
94
+ for name in GraphStyle.palette_names(): case('palettes', 'palette-'+name, 'Only the colour scheme changes here; no text means the exact same geometry.', palette=name)
95
+ section('palettes', 'Colour schemes', 'Porcelain is white; Linen and Light are warm near-white alternatives. Arctic is a dark blue ice palette.')
96
+ for name, scale, margin, alpha in (('normal',1,16,False),('double-resolution',2,16,False),('wide-margin',1,80,False),('transparent',1,16,True)):
97
+ case('output', name, 'Compare the dimensions and whitespace; growth geometry is unchanged.', scale=scale, margin=margin, transparent=alpha)
98
+ section('output', 'Export scale, margin and transparency', 'Thumbnails fit the same column width. Open the image to compare native resolution; SVG remains vector. Alpha is shown over a checkerboard.')
99
+
100
+ from .scene_gallery import generate_scene_gallery
101
+ sections.append(generate_scene_gallery(destination))
102
+ graph = build_example('sprawl', nodes=480, palette='porcelain')
103
+ with EventRecorder(graph, path=destination/'example-growth.jsonl') as recorder: graph.build()
104
+ log = recorder.snapshot()
105
+ renderer = ReplayRenderer(Playback(log, seconds_per_event=0.015), background='#ffffff')
106
+ gif = figures/'growth.gif'
107
+ if gif.exists(): gif.unlink()
108
+ renderer.export_gif(gif, fps=15, max_frames=300)
109
+ from PIL import Image
110
+ with Image.open(gif) as animation:
111
+ animation.seek(getattr(animation,'n_frames',1)-1)
112
+ animation.convert('RGB').save(figures/'growth-poster.png')
113
+ sections.append('<section id="animation"><h2>Watch the graph grow</h2><p>A complete 480-node growth run, followed by a pause on the finished artwork. Use Play animation to watch the sequence, or pause to return to the completed artwork. <a href="figures/growth.gif" download>Download GIF</a> or <a href="example-growth.jsonl">download the event log</a>.</p><img class="style-key" src="figures/growth-poster.png" data-poster="figures/growth-poster.png" data-animation="figures/growth.gif" alt="Animated growth from seeds to a filled graph"><p>Higher fps gives more samples of the same timeline; seconds per event changes speed. GIF needs an opaque background and has a limited colour palette; use PNG frames for transparency and full colour. The exporter rejects oversized frame or pixel budgets before rendering.</p><pre class="command">graph-ics frames --log docs/example-growth.jsonl --gif --palette porcelain --fps 15 --seconds-per-event 0.015 --max-frames 300 --output examples/output/growth.gif</pre></section>')
114
+ sections.append('<section id="files"><h2>Commands and files</h2><p>list and describe print information; render writes one PNG/SVG, optionally with a JSONL log; frames writes a numbered PNG sequence; gallery writes this library. --force only permits overwriting render outputs. --quick selects the six-scene smoke gallery; this controls page is still included. --output chooses their location, without altering the artwork.</p><pre class="command">graph-ics list\ngraph-ics describe density\ngraph-ics render --help\ngraph-ics gallery --output examples/gallery</pre><p>All generated figures sit in figures/ below the gallery index. Open the PNG/SVG links above to compare file formats visually.</p></section>')
115
+ rows = ''.join(f'<tr><td><code>{escape(option)}</code></td><td>{escape(note)}</td><td><a href="#{anchor}">Visual example</a></td></tr>' for option,note,anchor in CLI_OPTIONS)
116
+ anchors = [('scene-files','Dimensions & scenes'),('shapes','Shapes'),('lines','Connections'),('angles','Angles'),('seeds','Seeds'),('population','Population'),('palettes','Palettes'),('output','Export'),('animation','Replay'),('files','Files')]
117
+ navigation = '<nav class="section-nav" aria-label="Visual guide sections">'+''.join(f'<a href="#{anchor}">{label}</a>' for anchor,label in anchors)+'</nav>'
118
+ intro = '<header class="intro"><span class="eyebrow">Visual guide</span><h1>Change one thing.</h1><p>Compare the controls side by side. Each example explains what changes, what stays fixed, and how to reproduce the result.</p></header>'
119
+ reference = '<details id="cli"><summary>All command-line options</summary><div class="table-scroll"><table><thead><tr><th scope="col">Option</th><th scope="col">What it does</th><th scope="col">Example</th></tr></thead><tbody>'+rows+'</tbody></table></div></details>'
120
+ html = gallery_page('Visual guide', intro+navigation+reference+''.join(sections), active='controls')
121
+ path = destination/'controls.html'
122
+ path.write_text(html,encoding='utf-8')
123
+ (destination/'controls-manifest.json').write_text(json.dumps(records,indent=2)+'\n',encoding='utf-8')
124
+ generate_population_preview(destination)
125
+ return path
126
+
127
+
128
+ def generate_population_preview(destination: Path) -> None:
129
+ import cairo
130
+ from shapely.geometry import Point
131
+ raster, region = population_field(), population_region()
132
+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 550,1000)
133
+ context = cairo.Context(surface)
134
+ context.set_source_rgb(1,1,1)
135
+ context.paint()
136
+ for row in range(500):
137
+ for column in range(275):
138
+ x,y = (column+0.5)*WIDTH/275, (row+0.5)*HEIGHT/500
139
+ if not region.covers(Point(x,y)): continue
140
+ value = min(1,log1p(raster.sample(x,y))/log1p(10000))
141
+ context.set_source_rgb(0.86-0.75*value,0.94-0.55*value,0.97-0.4*value)
142
+ context.rectangle(column*2,row*2,2,2)
143
+ context.fill()
144
+ surface.write_to_png(str(destination/'figures'/'uk-density-input.png'))
145
+ metadata = population_data()['metadata']
146
+ graph_preview = '<a href="figures/uk_population-porcelain.png"><img src="figures/uk_population-porcelain.png" alt="UK density-guided graph"></a>' if (destination/'figures'/'uk_population-porcelain.png').exists() else '<p>Run the full gallery (omit --quick) or the command below to generate the UK graph.</p>'
147
+ content = '<header class="intro"><span class="eyebrow">Data-driven growth</span><h1>The shape of a population.</h1><p>UK population-density estimates guide a network inside the country boundary. Cities become finer and denser; rural areas leave more breathing room.</p></header>'
148
+ content += '<div class="comparison"><figure><img src="figures/uk-density-input.png" alt="WorldPop 2020 population density across the UK"><figcaption>Input: 2020 estimates, persons per square kilometre. Pale blue is near zero; dark blue is 10,000 or more. The colour scale is logarithmic.</figcaption></figure><figure>'+graph_preview+'<figcaption>Output: a density-guided graph. Open the image for its full resolution. Nodes do not represent individual people.</figcaption></figure></div>'
149
+ content += '<section><h2>Make this example</h2><pre class="command">graph-ics render --example uk_population --palette porcelain --output examples/output/uk.png</pre><p>The input is bundled with the library and runs offline. It includes Northern Ireland and UK islands, and excludes the Republic of Ireland. Small islands and narrow coastal features may remain empty.</p></section>'
150
+ content += '<section><h2>From density to spacing</h2><p>Population spans a wide range. A logarithmic mapping compresses the extremes so city structure remains readable: <code>t = min(1, log(1+density)/log(10001))</code>. Preferred spacing is <code>5 + 20*(1-t)</code>; geometry scale is <code>0.45 + 0.9*(1-t)</code>. Cities receive smaller, closer nodes. Collision checks and finite attempt budgets still limit packing.</p><p>This is an artistic transformation, not a linear population map. The source raster is resampled from approximately 1 km to 360 by 560 cells. The boundary is simplified; no-data samples become zero. Pixel centres share the boundary projection: longitude scaled by cos(55 degrees), north at the top. This display projection is not equal-area.</p></section>'
151
+ content += '<section><h2>Different uses of the same map</h2><p>Population is just one scalar input. Compare spacing-only, colour-only, and coordinated size/spacing below. The scene guide also demonstrates abstract radial fields and painted rasters, suitable for visual emphasis or any other spatial measurement.</p><div class="grid">'+''.join(f'<article><h3>{title} / {palette}</h3><a href="figures/{name}-{palette}.png"><img loading="lazy" src="figures/{name}-{palette}.png" alt="{title}"></a><pre class="command">graph-ics render --example {name} --palette {palette} --output examples/output/{name}-{palette}.png</pre></article>' for recipe,title in [('uk_population','UK: size and spacing'),('uk_density_only','UK: spacing only'),('uk_colors','UK: colour only'),('spain_population','Spain: size and spacing')] for palette in ('porcelain','arctic') for name in [recipe] if (destination/'figures'/f'{name}-{palette}.png').exists())+'</div><p>Spain uses the same 2020 WorldPop source and Natural Earth boundaries. The crop includes mainland Spain and the Balearic Islands; the Canary Islands are excluded. Small territories may be empty after geometric filtering.</p></section>'
152
+ content += '<section><h2>Sources</h2><p><a href="https://www.worldpop.org/doi/10.5258/SOTON/WP00674">WorldPop / CIESIN, Global High Resolution Population Denominators</a>, 2020 density estimates, distributed under <a href="https://creativecommons.org/licenses/by/4.0/">CC BY 4.0</a>. Boundary: <a href="https://www.naturalearthdata.com/about/terms-of-use/">Natural Earth</a> 5.1.2, public domain.</p><details><summary>Download query and provenance</summary><pre>'+escape(json.dumps(metadata,indent=2))+'</pre></details></section>'
153
+ (destination/'uk_population.html').write_text(gallery_page('UK population map', content, active='uk'),encoding='utf-8')
154
+
155
+
156
+
157
+ def generate_style_key(figures: Path) -> None:
158
+ import cairo
159
+ from .node import Node
160
+ from .edge import Edge
161
+ from .rendering import draw_node, draw_edge
162
+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 760, 280)
163
+ context = cairo.Context(surface)
164
+ context.set_source_rgb(1,1,1)
165
+ context.paint()
166
+ context.set_font_size(15)
167
+ for i, shape in enumerate(NODE_SHAPES):
168
+ draw_node(Node(75+i*150,55,outer_radius=25,inner_radius=15,color='#284d68',shape=shape),context)
169
+ context.move_to(40+i*150,105)
170
+ context.show_text(shape)
171
+ for i, style in enumerate(EDGE_STYLES):
172
+ first, second = Node(25+i*185,185,outer_radius=9,inner_radius=5), Node(155+i*185,185,outer_radius=9,inner_radius=5)
173
+ draw_edge(Edge(first,second,thickness=7,color='#284d68',style=style),context)
174
+ draw_node(first,context)
175
+ draw_node(second,context)
176
+ context.move_to(60+i*185,235)
177
+ context.show_text(style)
178
+ surface.write_to_png(str(figures/'style-key.png'))
graph_ics/py.typed ADDED
File without changes
graph_ics/quality.py ADDED
@@ -0,0 +1,42 @@
1
+ """Angular quality controls measured between outward center-to-center rays."""
2
+ from dataclasses import dataclass
3
+ from math import atan2, degrees, isfinite
4
+ from .node import Node
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class AngleSettings:
9
+ minimum: float = 0
10
+ preferred: float = 0
11
+ penalty: float = 0
12
+
13
+ def __post_init__(self) -> None:
14
+ if not all(isfinite(v) for v in (self.minimum, self.preferred, self.penalty)): raise ValueError('Angle settings must be finite')
15
+ if not 0 <= self.minimum <= 180 or not 0 <= self.preferred <= 180: raise ValueError('Angles must be between 0 and 180 degrees')
16
+ if self.preferred and self.preferred < self.minimum: raise ValueError('Preferred angle must be at least the hard minimum')
17
+ if not 0 <= self.penalty <= 1: raise ValueError('Penalty must be between 0 and 1')
18
+
19
+ def acceptance(self, angle: float) -> float:
20
+ if angle+1e-9 < self.minimum: return 0
21
+ if self.preferred <= self.minimum or angle >= self.preferred: return 1
22
+ return 1-self.penalty*(self.preferred-angle)/(self.preferred-self.minimum)
23
+
24
+
25
+ def incident_angle(center: Node, first: Node, second: Node) -> float:
26
+ ax, ay = first.center.x-center.center.x, first.center.y-center.center.y
27
+ bx, by = second.center.x-center.center.x, second.center.y-center.center.y
28
+ return degrees(atan2(abs(ax*by-ay*bx), ax*bx+ay*by))
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class QualityReport:
33
+ removed_nodes: int
34
+ refill_passes: int
35
+ refill_attempts: int
36
+ refill_additions: int
37
+ hard_rejections: int
38
+ soft_rejections: int
39
+ minimum_angle: float | None
40
+ angle_histogram: tuple[int, ...] # Six 30-degree bins, last includes 180.
41
+ achieved_nodes: int
42
+ target_shortfall: int
graph_ics/rendering.py ADDED
@@ -0,0 +1,159 @@
1
+ """Small static SVG/PNG exporter. Cairo is imported only when exporting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from math import ceil, isfinite, pi, cos, sin
6
+ from pathlib import Path
7
+ from typing import Literal, TYPE_CHECKING
8
+
9
+ from .colors import rgb_normalized
10
+ from .drawing import DrawingContext, BUTT_CAP, ROUND_JOIN
11
+ from .node import Node
12
+ from .edge import Edge
13
+ from shapely.geometry import Polygon
14
+ if TYPE_CHECKING:
15
+ from .graph import Graph
16
+
17
+
18
+
19
+ def draw_node(node: Node, context: DrawingContext, x_shift: float = 0, y_shift: float = 0) -> DrawingContext:
20
+ context.new_path()
21
+ x, y = node.center.x+x_shift, node.center.y+y_shift
22
+ context.set_source_rgba(*rgb_normalized(node.color), node.opacity)
23
+ if node.shape == 'circle':
24
+ context.arc(x, y, (node.outer_radius+node.inner_radius)/2, 0, 2*pi)
25
+ context.set_line_width(node.outer_radius-node.inner_radius)
26
+ context.stroke()
27
+ else:
28
+ sides = {'square': 4, 'diamond': 4, 'triangle': 3, 'hexagon': 6}[node.shape]
29
+ rotation = pi/4 if node.shape == 'square' else -pi/2
30
+ # Opposite winding cuts a hollow centre. Every vertex stays inside the reserved disk.
31
+ for radius, direction in ((node.outer_radius, 1), (node.inner_radius, -1)):
32
+ if radius == 0: continue
33
+ for i in range(sides):
34
+ angle = rotation+direction*i*2*pi/sides
35
+ point = (x+radius*cos(angle), y+radius*sin(angle))
36
+ if i == 0: context.move_to(*point)
37
+ else: context.line_to(*point)
38
+ context.close_path()
39
+ context.fill()
40
+ return context
41
+
42
+
43
+ def draw_edge(edge: Edge, context: DrawingContext, x_shift: float = 0, y_shift: float = 0) -> DrawingContext:
44
+ context.new_path()
45
+ context.set_line_cap(BUTT_CAP)
46
+ context.set_source_rgba(*rgb_normalized(edge.color), edge.opacity)
47
+ context.set_line_width(edge.thickness/3 if edge.style == 'double' else edge.thickness)
48
+ x, y = edge.start_point.x+x_shift, edge.start_point.y+y_shift
49
+ dx, dy = -edge.nx, -edge.ny
50
+ length = edge.length
51
+ if edge.style == 'dotted':
52
+ radius = min(edge.thickness/2, length/2)
53
+ count = max(1, int(length/(edge.thickness*2.5)))
54
+ for i in range(count):
55
+ distance = length*(i+0.5)/count
56
+ context.new_path()
57
+ context.arc(x+dx*distance, y+dy*distance, radius, 0, 2*pi)
58
+ context.fill()
59
+ return context
60
+ if edge.style == 'double':
61
+ for offset in (-edge.thickness/3, edge.thickness/3):
62
+ context.move_to(x-dy*offset, y+dx*offset)
63
+ context.line_to(x+dx*length-dy*offset, y+dy*length+dx*offset)
64
+ elif edge.style == 'dashed':
65
+ count = max(1, ceil(length/(edge.thickness*6)))
66
+ for i in range(count):
67
+ start, end = length*i/count, min(length, length*(i+0.65)/count)
68
+ context.move_to(x+dx*start, y+dy*start)
69
+ context.line_to(x+dx*end, y+dy*end)
70
+ else:
71
+ context.move_to(x, y)
72
+ context.line_to(x+dx*length, y+dy*length)
73
+ context.stroke()
74
+ return context
75
+
76
+
77
+ def draw_graph(graph: Graph, context: DrawingContext, x_shift: float = 0, y_shift: float = 0, *, draw_nodes: bool = True, draw_edges: bool = True,
78
+ draw_outline: bool = True, draw_text: bool = True) -> DrawingContext:
79
+ if draw_edges:
80
+ for edge in graph.edges: draw_edge(edge, context, x_shift, y_shift)
81
+ if draw_nodes:
82
+ for node in graph.nodes: draw_node(node, context, x_shift, y_shift)
83
+ if draw_outline and graph.draw_border:
84
+ context.new_path()
85
+ context.set_source_rgba(*rgb_normalized(graph.border_color), 1)
86
+ context.set_line_width(graph.border_width)
87
+ context.set_line_join(ROUND_JOIN)
88
+ polygons = [graph.outline_polygon] if isinstance(graph.outline_polygon, Polygon) else list(graph.outline_polygon.geoms)
89
+ for polygon in polygons:
90
+ for ring in [polygon.exterior, *polygon.interiors]:
91
+ for i, (x, y) in enumerate(ring.coords):
92
+ if i == 0: context.move_to(x+x_shift, y+y_shift)
93
+ else: context.line_to(x+x_shift, y+y_shift)
94
+ context.close_path()
95
+ context.stroke()
96
+ if draw_text:
97
+ for measured in graph.texts:
98
+ context.save()
99
+ try:
100
+ context.translate(x_shift, y_shift)
101
+ context.new_path()
102
+ context.append_path(measured.path)
103
+ context.set_source_rgba(*rgb_normalized(measured.text.color), measured.text.opacity)
104
+ context.fill()
105
+ finally:
106
+ context.restore()
107
+ return context
108
+
109
+
110
+ def export_graph(graph: Graph, path: str | Path, *, margin: float = 5, scale: float = 1, background: str | None = None,
111
+ frame: Literal['artwork', 'region'] = 'artwork') -> tuple[int, int]:
112
+ """Export built geometry and return output dimensions in pixels/world-scaled units.
113
+
114
+ Parameters
115
+ ----------
116
+ margin: Nonnegative world-unit margin around the selected frame.
117
+ scale: Positive output units per world unit; shared by PNG and SVG.
118
+ background: Hexadecimal RGB or None for transparency.
119
+ frame: Crop to visible artwork, or retain the entire allowed region.
120
+
121
+ Raises
122
+ ------
123
+ ValueError: Invalid options, unsupported suffix, or an empty artwork frame.
124
+ ImportError: The optional render dependency is not installed.
125
+ """
126
+ if not isfinite(margin) or margin < 0 or not isfinite(scale) or scale <= 0: raise ValueError('Require a nonnegative margin and positive finite scale')
127
+ if frame not in ('artwork', 'region'): raise ValueError('frame must be artwork or region')
128
+ if graph.contours is not None and scale < graph.contours.readability.output_scale: raise ValueError('Export scale is below the readability design scale; regenerate or increase export scale')
129
+ destination = Path(path)
130
+ if destination.suffix.lower() not in ('.svg', '.png'): raise ValueError('Export path must end in .svg or .png')
131
+ if frame == 'artwork' and not graph.nodes and not graph.draw_border and not graph.texts: raise ValueError('Cannot crop an empty graph to artwork')
132
+ if background is not None: rgb_normalized(background)
133
+ try:
134
+ import cairo
135
+ except ImportError as error:
136
+ raise ImportError('Install graph-ics[render] to export SVG or PNG') from error
137
+ if frame == 'artwork':
138
+ min_x, min_y, max_x, max_y = graph.get_extent()
139
+ else:
140
+ min_x, min_y, max_x, max_y = graph.get_bounds()
141
+ if graph.draw_border: min_x, min_y, max_x, max_y = min_x-graph.border_width/2, min_y-graph.border_width/2, max_x+graph.border_width/2, max_y+graph.border_width/2
142
+ for measured in graph.texts:
143
+ a, b, c, d = measured.bounds
144
+ min_x, min_y, max_x, max_y = min(min_x, a), min(min_y, b), max(max_x, c), max(max_y, d)
145
+ width, height = max(1, ceil((max_x-min_x+2*margin)*scale)), max(1, ceil((max_y-min_y+2*margin)*scale))
146
+ destination.parent.mkdir(parents=True, exist_ok=True)
147
+ surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) if destination.suffix.lower() == '.png' else cairo.SVGSurface(str(destination), width, height)
148
+ try:
149
+ context = cairo.Context(surface)
150
+ if background is not None:
151
+ context.set_source_rgb(*rgb_normalized(background))
152
+ context.paint()
153
+ context.scale(scale, scale)
154
+ context.translate(margin-min_x, margin-min_y)
155
+ draw_graph(graph, context)
156
+ if isinstance(surface, cairo.ImageSurface): surface.write_to_png(str(destination))
157
+ finally:
158
+ surface.finish()
159
+ return width, height