GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — flowtopo/example.py at main · hellolulujiang/flowtopo Expand file tree/ Copy pathexample.pyMore file actions 331 lines (287 loc) · 14.9 KB / Copy pathexample.pyFile metadata and controls331 lines (287 loc) · 14.9 KB 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 """Run every structure, kernel and manner on the bundled example basin. The script 1. reads the D8 grid; 2. builds the three serial orderings, the three parallel layerings and the two spatial partitions; 3. counts, per layering, how many times a layer writes twice into one receiver; 4. runs the four kernels under every manner and checks they agree; 5. reports the memory-locality metrics; 6. writes the arrays to ``out/``. python example.py [--data data/dir_example.tif] [--out out] The output directory must not hold the files of another run: none is written over. """ import argparse import os import time import numpy as np import flowtopo from flowtopo import core from flowtopo.raster import write_geotiff ORDERINGS = ("dfs", "bfs", "topo") LAYERINGS = ("asap", "cfds", "alap") ORDER_LABEL = {"dfs": "seq_dfs", "bfs": "seq_bfs", "topo": "seq_topo"} LAYER_LABEL = {"asap": "lyr_asap", "cfds": "lyr_cfds", "alap": "lyr_alap"} def banner(title): print("\n" + "=" * 62) print(f" {title}") print("=" * 62) def timed(call, repeats=3): call() # compiled and run once first: the times below are the build alone times = [] for _ in range(repeats): start = time.perf_counter() result = call() times.append(time.perf_counter() - start) return float(np.median(times)), result def count_conflicts(decomp, idxs_ds): """Extra writes to a shared receiver within a layer, summed over the layers.""" total = 0 worst = 0 for members in decomp: ds = idxs_ds[members] ds = ds[(ds >= 0) & (ds != members)] if ds.size: repeats = ds.size - np.unique(ds).size total += repeats worst = max(worst, repeats) return total, worst def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data", default=os.path.join("data", "dir_example.tif")) parser.add_argument("--out", default="out") parser.add_argument("--upa-threshold", type=float, default=10.0, help="drainage area in km2 that defines the channel network") parser.add_argument("--repeats", type=int, default=3) args = parser.parse_args() banner("Input") topo = flowtopo.FlowTopo.from_raster(args.data) total = topo.idxs_ds.size print(f" grid : {topo.nrow} x {topo.ncol} = {total:,} cells") print(f" valid cells : {topo.ncells:,} " f"({100.0 * topo.ncells / total:.1f}% of the grid)") # nothing to compare on a grid without a valid cell, and a network with a cycle cannot be traversed: the # orderings leave its cells out, every method then agrees on the cells that are left, and the comparison # below would pass on a part of the network if topo.ncells == 0: print("\n The grid holds no valid cell: nothing to compute.") return 1 visited = int(topo.ordering("dfs").size) if visited != topo.ncells: print(f"\n FAIL: {topo.ncells - visited:,} cells lie on or above a cycle of the flow directions and " "cannot be ordered; the grid is not a river network.") return 1 print(f" basins : {topo.nbasins}") print(f" numba : {'yes' if flowtopo.HAS_NUMBA else 'no (pure python, slow)'}") # ---- Stage 1: the six orderings and layerings ---------------------------------- banner("Stage 1 Building the six orderings and layerings") # the builders themselves: the object keeps what it built, and asking it again would time the lookup builders = { "dfs": lambda: core.seq_dfs_from_pit(topo.idxs_ds), "bfs": lambda: core.seq_bfs_from_pit(topo.idxs_ds), "topo": lambda: core.seq_topo_from_source(topo.idxs_ds), "asap": lambda: core.layering_asap(topo.idxs_ds), "cfds": lambda: core.layering_cfds(topo.idxs_ds), "alap": lambda: core.layering_alap(topo.idxs_ds, topo.basins), } for name in ORDERINGS: seconds, seq = timed(builders[name], args.repeats) print(f" {ORDER_LABEL[name]:9s} {seq.size:10,} cells {seconds:8.4f} s") for name in LAYERINGS: seconds, (layers, nlayers) = timed(builders[name], args.repeats) print(f" {LAYER_LABEL[name]:9s} {nlayers:10,} layers {seconds:8.4f} s") # ---- Stage 2: spatial partitions ------------------------------------- banner("Stage 2 Spatial partitions") print(" Whole basins cannot be split, so one large basin leaves the other") print(" processors idle. Cutting an oversized basin along its mainstem") print(" spreads it. Set n_parts to the number of processors.\n") print(f" {'level':10s} {'load per subregion':>34s} {'imbalance':>10s} {'mainstem':>9s}") partitions = {} for level in ("basin", "subbasin"): part, load = topo.partition(n_parts=4, level=level) partitions[level] = part stem = int(np.count_nonzero(part == flowtopo.MAINSTEM)) spread = load.max() / load.mean() if load.mean() else float("nan") shown = " ".join(f"{int(v):>7,}" for v in load) print(f" {level:10s} {shown:>34s} {spread:10.2f} {stem:9,}") crossings = {} for level, part in partitions.items(): cells = np.nonzero(part >= 0)[0] ds = topo.idxs_ds[cells] moving = (ds >= 0) & (ds != cells) cells, ds = cells[moving], ds[moving] crossings[level] = int(np.count_nonzero( (part[ds] != part[cells]) & (part[ds] != flowtopo.MAINSTEM))) covered = (part >= 0) | (part == flowtopo.MAINSTEM) assert np.array_equal(covered, topo.mask), f"{level}: some cells unassigned" print(f"\n Values crossing a subregion boundary: " f"basin {crossings['basin']}, subbasin {crossings['subbasin']}.") print(" Zero either way: both cut along the drainage hierarchy, so the") print(" subregions never have to talk to each other.") # ---- Stage 3: write conflicts --------------------------------------- banner("Stage 3 Write conflicts inside a layer") print(" A push writes into the receiver. That is only safe if no two") print(" cells of a layer share one. This counts how often they do.\n") print(f" {'layering':10s} {'layers':>8s} {'conflicts':>12s} {'worst layer':>12s}") for name in LAYERINGS: decomp = topo.decomposition(name, "u2d") conflicts, worst = count_conflicts(decomp, topo.idxs_ds) print(f" {LAYER_LABEL[name]:10s} {decomp.nlayers:8,} " f"{conflicts:12,} {worst:12,}") print("\n The conflict-free downstream layering always reaches zero, and it") print(" is the only one under which a plain push is always safe.") # ---- Stage 4: the four kernels -------------------------------------- banner("Stage 4 The four kernels under every manner") ldn_ref = topo.distance_to_outlet(ordering="dfs") upa_ref = topo.upstream_area(ordering="dfs") lup_ref = topo.longest_upstream_path(ldn_ref, ordering="dfs") channel = topo.channel_mask(upa_ref, args.upa_threshold) ord_ref = topo.strahler_order(ordering="dfs", channel_mask=channel) print(f" channel network : {int(channel.sum()):,} cells above " f"{args.upa_threshold:g} km2") valid = topo.mask worst = {"ldn": 0.0, "upa": 0.0, "lup": 0.0, "ord": 0} unsafe_rows = [] print(f"\n {'structure':10s} {'kernel':24s} {'manner':12s} " f"{'median s':>9s} {'check':>12s}") def report(structure, kernel, manner, seconds, diff, unit, safe=True): flag = "" if safe else " <- unsafe" print(f" {structure:10s} {kernel:24s} {manner:12s} {seconds:9.4f} " f"{diff:9.3g} {unit}{flag}") for name in ORDERINGS: label = ORDER_LABEL[name] seconds, value = timed( lambda n=name: topo.distance_to_outlet(ordering=n), args.repeats) diff = float(np.abs(value[valid] - ldn_ref[valid]).max()) worst["ldn"] = max(worst["ldn"], diff) report(label, "flow length downstream", "serial", seconds, diff, "m") seconds, value = timed( lambda n=name: topo.upstream_area(ordering=n), args.repeats) diff = float(np.abs(value[valid] - upa_ref[valid]).max()) worst["upa"] = max(worst["upa"], diff) report(label, "upstream drainage area", "serial", seconds, diff, "km2") seconds, value = timed( lambda n=name: topo.longest_upstream_path(ldn_ref, ordering=n), args.repeats) diff = float(np.abs(value[valid] - lup_ref[valid]).max()) worst["lup"] = max(worst["lup"], diff) report(label, "flow length upstream", "serial", seconds, diff, "m") seconds, value = timed( lambda n=name: topo.strahler_order(ordering=n, channel_mask=channel), args.repeats) diff = int(np.count_nonzero(value[channel] != ord_ref[channel])) worst["ord"] = max(worst["ord"], diff) report(label, "Strahler stream order", "serial", seconds, diff, "cells") for name in LAYERINGS: label = LAYER_LABEL[name] conflicts, _ = count_conflicts(topo.decomposition(name, "u2d"), topo.idxs_ds) seconds, value = timed( lambda n=name: topo.distance_to_outlet(layering=n, manner="push"), args.repeats) diff = float(np.abs(value[valid] - ldn_ref[valid]).max()) worst["ldn"] = max(worst["ldn"], diff) report(label, "flow length downstream", "push", seconds, diff, "m") for manner in ("pull", "push", "atomic_push"): safe = manner != "push" or conflicts == 0 seconds, value = timed( lambda n=name, m=manner: topo.upstream_area(layering=n, manner=m), args.repeats) diff = float(np.abs(value[valid] - upa_ref[valid]).max()) if safe: worst["upa"] = max(worst["upa"], diff) else: unsafe_rows.append((label, "upstream drainage area", diff)) report(label, "upstream drainage area", manner, seconds, diff, "km2", safe) seconds, value = timed( lambda n=name, m=manner: topo.longest_upstream_path( ldn_ref, layering=n, manner=m), args.repeats) diff = float(np.abs(value[valid] - lup_ref[valid]).max()) if safe: worst["lup"] = max(worst["lup"], diff) else: unsafe_rows.append((label, "flow length upstream", diff)) report(label, "flow length upstream", manner, seconds, diff, "m", safe) for manner in ("pull", "push"): safe = manner != "push" or conflicts == 0 seconds, value = timed( lambda n=name, m=manner: topo.strahler_order( layering=n, manner=m, channel_mask=channel), args.repeats) diff = int(np.count_nonzero(value[channel] != ord_ref[channel])) if safe: worst["ord"] = max(worst["ord"], diff) else: unsafe_rows.append((label, "Strahler stream order", diff)) report(label, "Strahler stream order", manner, seconds, diff, "cells", safe) # ---- Stage 5: locality ---------------------------------------------- banner("Stage 5 Memory-locality metrics") print(f" {'structure':10s} {'L1 miss':>10s} {'L2 miss':>10s} " f"{'L3 miss':>10s} {'row jump':>10s}") for name in ORDERINGS: metrics = topo.serial_locality(name) print(f" {ORDER_LABEL[name]:10s} " f"{100 * metrics['miss_rate_L1']:9.4f}% " f"{100 * metrics['miss_rate_L2']:9.4f}% " f"{100 * metrics['miss_rate_L3']:9.4f}% " f"{metrics['row_jump_frac']:10.4f}") for name in LAYERINGS: metrics = topo.parallel_locality(name) print(f" {LAYER_LABEL[name]:10s} " f"{100 * metrics['miss_rate_L1']:9.4f}% " f"{100 * metrics['miss_rate_L2']:9.4f}% " f"{100 * metrics['miss_rate_L3']:9.4f}% " f"{'-':>10s} ({metrics['nlayers']} layers)") print("\n The simulated cache is the machine of the companion paper:") print(" 32 KB 8-way L1, 1 MB 16-way L2, 35.75 MB 11-way L3. The bundled") print(" basin fits inside L3, so its miss rates stay low; a larger grid need not.") # ---- Stage 6: write -------------------------------------------------- banner("Stage 6 Writing outputs") os.makedirs(args.out, exist_ok=True) def dump(name, array, dtype, nodata): path = os.path.join(args.out, f"{name}.tif") write_geotiff(path, np.ascontiguousarray(array, dtype=dtype), topo.header(dtype=np.dtype(dtype).name, nodata=nodata)) print(f" {path}") for name in ORDERINGS: seq = topo.ordering(name, "u2d") position = np.full(total, -1, dtype=np.int32) position[seq] = np.arange(seq.size, dtype=np.int32) dump(ORDER_LABEL[name], position, np.int32, -1) for name in LAYERINGS: dump(LAYER_LABEL[name], topo.layering(name)[0], np.int32, -1) dump("ldn", ldn_ref, np.float32, -9999.0) dump("lup", lup_ref, np.float32, -9999.0) dump("upa", upa_ref, np.float32, -9999.0) dump("ord", ord_ref, np.uint8, 0) # ---- verdict --------------------------------------------------------- tolerance_upa = float(upa_ref[valid].max()) * 1e-5 checks = [ ("flow length downstream", worst["ldn"], 1e-3, "m"), ("flow length upstream", worst["lup"], 1e-3, "m"), ("upstream drainage area", worst["upa"], tolerance_upa, "km2"), ("Strahler stream order", worst["ord"], 0, "cells"), ] passed = all(value <= limit for _, value, limit, _ in checks) banner("PASS" if passed else "FAIL") print(" Worst disagreement against the serial depth-first reference,") print(" over every safe combination of structure and manner:\n") for kernel, value, limit, unit in checks: verdict = "ok" if value <= limit else "FAILED" print(f" {kernel:24s} {value:12.6g} {unit:5s} " f"tolerance {limit:.4g} {unit:5s} {verdict}") print("\n Drainage area is the one result not expected to match bit for") print(" bit: floating-point addition is not associative and each manner") print(" sums a confluence's donors in a different order. The rest agree") print(" exactly, longest path included, since its confluence rule takes") print(" the larger of two donors rather than adding them.") if unsafe_rows: print("\n Rows marked unsafe above ran a plain push under a layering") print(" that puts two donors of one receiver in the same layer. They") print(" are excluded from the verdict; losing a write there is the") print(" expected behaviour, and it is what the layering is for:") for label, kernel, diff in unsafe_rows: print(f" {label:10s} {kernel:24s} off by {diff:g}") return 0 if passed else 1 if __name__ == "__main__": raise SystemExit(main()) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |