summaryrefslogtreecommitdiff
path: root/render.py
blob: bad2d01f860cd7f67f6cd01c2b659cb12d6546ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import cairo

def parse_indental(filename):
	"""Reads a geometry file into a tree of dictionaries."""
	with open(filename) as f:
		indents = [0]
		stack = [{}]
		key = ""
		for no, line in enumerate(f):
			# Compute indent
			indent = 0
			while indent < len(line) and line[indent] in " \t":
				indent += 1
			line = line.strip()

			# Skip comments and blank lines
			if not line or line[0] == "#" or line[0] == ";": continue

			try:
				# Find appropriate parent for the indent
				if indent > indents[-1]:
					indents.append(indent)
					entry = stack[-1][key] = {}
					stack.append(entry)
				else:
					while indent < indents[-1]:
						indents.pop()
						stack.pop()
					if indent != indents[-1]:
						raise SyntaxError("Improper indent, " + filename + ":" + str(no))

				# Parse & store line
				key, value = line.split(":") if ":" in line else (line, "")
				stack[-1][key.strip()] = value.strip()
			except:
				raise SyntaxError("Malformed line, " + filename + ":" + str(no))
		return stack[0]

def parseCSV(filename):
	with open(filename) as f:
		f.readline() # Ignore header
		for line in readline:
			try:
				name, value = line.split(",")
				yield name.strip(), [
					zone.split("#")[1].strip() if "#" in zone else zone.strip()
					for zone in value.split() if zone
				]

class Geom(object):
	"""Represents an area on earth, utilizing a trie datastructure and DGGS."""
	def __init__(self, present = False):
		self.present = present
		self.child_present = False
		self.children = {}
		self.attrs = {}

	def insert(self, key):
		"""Adds a new DDGS zone ID to the geometry."""
		if not key:
			# Reached the correct leaf, mark as such.
			self.present = True
			return self

		# Recursively insert into appropriate child, creating if necessary.
		self.child_present = True
		if key[0] not in self.children:
			self.children[key[0]] = Geom()
		return self.children[key[0]].insert(key[1:])

	def insert_all(self, *keys, **attrs):
		"""Inserts all given zone IDs into the geometry."""
		for key in keys: self.insert(key).attrs = attrs

	def crop(self, key):
		"""Returns the node for the specified key, are the closest parent thereof."""
		ret = self
		for c in key:
			if c not in ret.children: break
			ret = ret.children[c]
		return ret

	@staticmethod
	def parse(filename):
		"""Parses a DGGS geometry from an indental file."""
		ret = Geom()
		data = parse_indental(filename)
		for geom in data.values():
			attrs = {k:v for k, v in geom.items() if type(v) != dict}
			for zone, zoneAttrs in geom.items():
				if zoneAttrs and type(zoneAttrs) != dict: continue
				child = ret.insert(zone)
				child.attrs = dict(zoneAttrs, **attrs)
		return ret

	@staticmethod
	def csv(filename):
		from random import random
		ret = Geom()
		for name, zones in parseCSV(filename):
			self.insert_all(zones, red=random(), green=random(), blue=random(), alpha=0.5, label=name)

	# Syntactic sugar for looking up attached attributes.
	def __getattr__(self, key): return self.attrs.get(key, False)
	def __getitem__(self, key): return self.attrs.get(key, False)

	def render(self, target, width, height, x = 0, y = 0, depth = -1):
		"""Render this geometry into the given PyCairo Context within a given bounding box.

			depth indicates how many layers down to go, -1 for infinity."""
		if self.present:
			# This zone's present, render it.
			target.set_source_rgba(float(self.red), float(self.green),
					float(self.blue), float(self.alpha))
			target.rectangle(x, y, width, height)
			target.fill()

		# Render the children
		subwidth, subheight = width / 3.0, height / 3.0
		for key, child in self.children.items():
			row, col = int(int(key)/3), int(int(key)%3)
			_x, _y = x + col*subwidth, y + row*subheight

			if (child.child_present and depth == 0) or child.present:
				# This child's present, render it.
				target.set_source_rgba(float(child.red), float(child.green),
						float(child.blue), float(child.alpha))
				target.rectangle(_x, _y, subwidth, subheight)
				target.fill()
			elif child.child_present:
				# A descendant is present, recurse to render them.
				child.render(target, subwidth, subheight, _x, _y, depth-1)


	def to_png(self, zone="", dest=None, width=730, height=730, depth=6):
		"""Render to the given file (or file-like object),
			or return a Jupyter Notebook image, for the given zone ID."""
		# Prepare PyCairo Context to render into
		surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
		ctx = cairo.Context(surface)

		# Render it!
		self.crop(zone).render(ctx, width, height, depth = depth)

		# Save it
		if dest is not None:
			surface.write_to_png(dest)
		else:
			# Jupyter Notebook integration, optional
			from io import BytesIO
			from IPython import display

			b = BytesIO()
			surface.write_to_png(b)
			return display.Image(data=b.getvalue(), format="png", embed=True)

	display = to_png # Alternate name, specifically for Jupyter Notebook

	## DGGS processing methods
	# Collections methods
	def __iter__(self, key = ""):
		"""Iterate over all zone IDs in this geometry"""
		if self.present: yield key

		if self.child_present:
			for k, child in self.children.items():
				yield from child.__iter__(self, key + k)

	def __len__(self):
		"""How many zone IDs are in this geometry? Use the len() function."""
		return sum(1 for _ in self)

	def __contains__(self, zone):
		"""Is the given zone ID in this geometry? Use the `in` operator."""
		if not zone: return False # No zone ID? Not in it.

		# Lookup the appropriate node
		node = self
		for c in zone:
			# Return early if necessary.
			if node.present: return True
			if not node.child_present: return False
			if c not in node.children: return False

			node = node.children[c]
		return node.present

	# Set methods
	def __or__(self, other):
		"""Yields a new geometry containing all zones in either (or both) geometries."""
		ret = Geom()
		ret.insert_all(*self)
		ret.insert_all(*other)
		return ret

	def __and__(self, other):
		"""Yields a new geometry containing all zones in common between both geometries."""
		ret = Geom()
		ret.insert_all(x for x in self if x in other)
		ret.insert_all(y for y in other if y in self)
		return ret

	def __sub__(self, other):
		"""Yields a new geometry containing all zones in self but not other."""
		ret = Geom()
		ret.insert_all(x for x in self if x not in other)

		# Do we have any parents of a zone in other?
		for zone in other:
			parent = max((x for x in self if zone.startswith(x)), default=None, key=len)
			if parent is None: continue

			# If so, remove and expand that parent...
			self.crop(parent).exists = False

			newzone = list(parent)
			for i, k in enumerate(zone):
				if i < len(parent): continue # Haven't reached parent yet...

				for c in range(9):
					if c == int(k): continue # So we can remove this zone.
					newzone[i] = c
					ret.insert("".join(newzone))
				newzone[i] = k

		return ret

	def __xor__(self, other):
		"""Yields a new geometry that contains any cell in either geometry but not both."""
		return self - other | other - self

	# DE9IM
	def __eq__(self, other):
		return set(self) == set(other)
	def __ne__(self, other): return not (self == other)

	def covers(self, other):
		return all(y in self for y in other)

	def __le__(self, other): return self.contains(other)
	def __lt__(self, other): return self.contains(other) and self != other

	def intersects(self, other):
		return any(x in other for x in self) or any(y in self for y in other)

	def disjoint(self, other):
		return not self.intersects(other)

	def contains(self, other):
		return other.child_present and all(y in self for y in other)

	def coveredby(self, other):
		return other.covers(self)

	def __ge__(self, other): return self.coveredby(other)
	def __gt__(self, other): return self.coveredby(other) and self != other

	def overlaps(self, other):
		has_inner = has_outer = False
		for x in self:
			contained = x in other
			has_inner |= contained
			has_outer |= not contained

			# Parent cells are both inside and out...
			if not contained: continue
			for i in range(len(x), 0, -1):
				if x[:i] in other: return True
		return has_inner and has_outer

	def within(self, other):
		return other.contains(self)

class TiledLayer(object):
	"""A map layer constructed out of tiled imagery"""
	def __init__(self, path):
		self.path = path

	def render(self, zone, ctx, width, height, x = 0, y = 0, depth = 5):
		"""Renders the image for the given DGGS zone ID (or children thereof)
			to the given PyCairo Context."""
		source = None
		try:
			source = cairo.ImageSurface.create_from_png(self.path.replace("?", zone))
		except:
			# Failed to find image, recurse instead.
			if depth < 0: depth = 5 # Normally -1 depth means infinite, but the image probably doesn't exist.
			if depth == 0: return # Reached the depth, stop.

			# Recurse into drawing the child zone IDs.
			subwidth, subheight = width/3, height/3
			for i in range(9):
				row, col = int(i/3), int(i%3)
				_x, _y = x + col*subwidth, y + row*subheight

				self.render(zone+str(i), ctx, subwidth, subheight, _x, _y, depth-1)
			return

		# Compute ammount to resize by
		width_ratio = float(width)/float(source.get_width())
		height_ratio = float(height)/float(source.get_height())

		ctx.save()
		# Scale/translate into place.
		ctx.translate(x, y)
		ctx.scale(width_ratio, height_ratio)
		# Render image.
		ctx.set_source_surface(source)
		ctx.paint()
		ctx.restore()

	def to_png(self, zone, dest=None, width=730, height=730, depth=6):
		"""Render to the given destination file (or file-like object) for the given zone ID."""
		surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
		ctx = cairo.Context(surface)
		self.render(zone, ctx, width, height, depth)

		if dest is not None:
			surface.write_to_png(dest)
		else:
			from io import BytesIO
			from IPython import display

			b = BytesIO()
			surface.write_to_png(b)
			return display.Image(data=b.getvalue(), format="png", embed=True)

	display = to_png # Alternate name, specifically for Jupyter Notebook

class LayeredMap(object):
	"""A map constructed out of multiple layers."""
	def __init__(self, *layers):
		self.layers = layers

	def to_png(self, zone, dest=None, width=730, height=730, depth=6):
		"""Render to the given destination file cropped by the given zone ID."""
		surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
		ctx = cairo.Context(surface)

		for layer in self.layers:
			if type(layer) == str: layer = TiledLayer(layer)
			if hasattr(layer, "crop"):
				layer.crop(zone).render(ctx, width, height, depth)
			else:
				layer.render(zone, ctx, width, height, depth=depth)

		if dest is not None:
			surface.write_to_png(dest)
		else:
			from io import BytesIO
			from IPython import display

			b = BytesIO()
			surface.write_to_png(b)
			return display.Image(data=b.getvalue(), format="png", embed=True)

	display = to_png # Alternate name, specifically for Jupyter Notebook

# Commandline interface
if __name__ == "__main__":
	from sys import argv, exit
	if len(argv) < 4 or len(argv) > 7:
		print("USAGE:", argv[0], "ZONEID FILE OUTFILE [WIDTH [HEIGHT [DEPTH]]]")
		exit(1)

	width = int(argv[4]) if len(argv) > 4 else 730
	height = int(argv[5]) if len(argv) > 5 else width
	depth = int(argv[6]) if len(argv) > 6 else -1

	geom = Geom.parse(argv[2]).crop(argv[1])
	geom.to_png(argv[3], width, height, depth)