In [1]:
import sys, os
import math, random
import numpy as np
import pandas as pd
import operator
from scipy.sparse import csr_matrix, lil_matrix
from scipy.sparse.csgraph import dijkstra
from tqdm import tqdm
In [2]:
class Raster(np.ndarray):
def __new__(cls, input_array, cellsize, xllcorner, yllcorner):
obj = np.asarray(input_array).view(cls)
obj.cellsize = cellsize
obj.xllcorner = xllcorner
obj.yllcorner = yllcorner
# 1-D list of the raster's values
v = obj.flatten()
obj.values = v[~np.isnan(v)]
return obj
@classmethod
def load(cls, filename):
data = [ ]
attrs = { }
with open(filename) as f:
for i in range(6):
key,value = next(f).strip().split()
attrs[key] = value
NODATA_value = attrs.get("NODATA_value", "-9999")
for line in f:
row = list(map(lambda x: np.nan if x == NODATA_value else float(x), line.split()))
#row = [ x if x < 1e3 else np.nan for x in row ]
if row:
data.append(row)
return Raster(np.asarray(data), float(attrs["cellsize"])
, float(attrs["xllcorner"])
, float(attrs["yllcorner"]))
In [3]:
%%time
I = Raster.load("../bb450_final.asc")
In [4]:
%%time
R = Raster.load("../../BB450/bb_resist450.asc")
In [5]:
nodes = Raster.load("../../BB450/bb_nodes450.asc")
nodes = np.argwhere(~np.isnan(nodes))+1 # only care about the indicies
len(nodes)
Out[5]:
In [6]:
N = len(I.values)
print("N = {:,}\nsqr(N) = {:,}\n9N = {:,}".format(N, N**2, 9*N))
In [7]:
%%time
indices = { (int(x),int(y)):index for index,(x,y) in enumerate(np.argwhere(~np.isnan(I))) }
print(len(indices))
In [8]:
%%time
coordinates = [ (int(x),int(y)) for (x,y) in np.argwhere(~np.isnan(I)) ]
In [9]:
G1 = lil_matrix((N, N))
for (i,j),id1 in tqdm(indices.items()):
try:
id2 = indices[i+1,j]
value = (R[i,j] + R[i+1,j]) / 2.
G1[id1,id2] = value
G1[id2,id1] = value
except KeyError:
pass
try:
id2 = indices[i,j+1]
value = (R[i,j] + R[i,j+1]) / 2.
G1[id1,id2] = value
G1[id2,id1] = value
except KeyError:
pass
G1
Out[9]:
In [10]:
%%time
G = csr_matrix(G1)
In [11]:
G
Out[11]:
In [12]:
nindices = list(filter(lambda i: i is not None, [ indices.get((y,x)) for y,x in nodes ]))
In [13]:
len(nindices)
Out[13]:
In [14]:
%%time
dist_matrix,predecessors = dijkstra(G, directed=False, return_predecessors=True, indices=nindices)
In [15]:
print(repr(predecessors))
In [16]:
def getPaths(origin):
lines = [ ]
for index,start in enumerate(nindices):
if index == origin:
continue
i = start
lines.append((dist_matrix[origin][i], [ ], [ ]))
while i != -9999:
lines[-1][1].append(coordinates[i][1])
lines[-1][2].append(coordinates[i][0])
i = predecessors[origin][i]
return lines
In [17]:
def savePaths(origin, output_name):
paths = getPaths(origin)
rmin = min(map(operator.itemgetter(0), paths))
rmax = max(map(operator.itemgetter(0), paths))
with open(output_name.format(origin), "w") as f:
print(len(paths), rmin, rmax, file=f)
for rdist,xs,ys in paths:
print(len(xs), rdist, file=f)
print(*xs, file=f)
print(*ys, file=f)
In [18]:
for i in tqdm(range(len(nindices))):
savePaths(i, "/Users/eduffy/Research/BB450/LCP/BB450_{:06d}.lcp")
In [ ]: