Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import numpy as np
- import sys, time, string
- def timeWrap(func):
- def wrapper(*args, **kwargs):
- t0 = time.time()
- result = func(*args, **kwargs)
- print "It took:", time.time() - t0, "seconds"
- return result
- return wrapper
- def load_map(mapFilename):
- maxRC = 0
- atemp = []
- with open(mapFilename, 'r') as F:
- for line in F.readlines():
- ltemp = string.split(line, " ")
- ltemp[3] = ltemp[3][:-1]
- ltemp = [int(i) for i in ltemp]
- atemp.append(ltemp)
- maxRC = max(maxRC, ltemp[0], ltemp[1])
- maxRC += 1
- mitKey = np.zeros((maxRC), dtype=np.int32)
- mitMap = np.zeros((maxRC, maxRC, 2), dtype=np.int32)
- for i in range(len(atemp)):
- mitKey[atemp[i][0]] += 1
- tot = mitMap[atemp[i][0], atemp[i][1], 0]
- out = mitMap[atemp[i][0], atemp[i][1], 1]
- if tot == 0 or atemp[i][2] < tot or (atemp[i][2] == tot and atemp[i][3]):
- mitMap[atemp[i][0], atemp[i][1], 0] = atemp[i][2]
- mitMap[atemp[i][0], atemp[i][1], 1] = atemp[i][3]
- return mitKey, mitMap
- @timeWrap
- def bruteForceSearch(digraph, dikey, start, end, maxTotalDist, maxDistOutdoors):
- def bFS(digraph, dikey, start, end, maxTotalDist, maxDistOutdoors, path = None, shortest = None):
- def lenPath(path):
- tlen = olen = 0
- for i in range(len(path)-1):
- td, od = digraph[path[i], path[i+1]]
- tlen += td
- olen += od
- return (tlen, olen)
- path = (path or []) + [start]
- size = len(dikey)
- if start == end:
- td, od = lenPath(path)
- if td > maxTotalDist or od > maxDistOutdoors:
- return
- # print td, '.',
- if shortest is None or td < lenPath(shortest)[0]:
- if shortest is not None: print path, td, lenPath(shortest)[0], '_:_'
- return path
- return
- def childrenOf(digraph, s):
- d = 0
- childrenList = []
- for d in range(size):
- if digraph[s, d, 0] != 0:
- childrenList.append(d)
- return childrenList
- for node in childrenOf(digraph, start):
- if node not in path: #avoid cycles
- newPath = bFS(digraph, dikey, node, end, maxTotalDist, maxDistOutdoors, path, shortest)
- if newPath is not None:
- td, od = lenPath(path)
- if shortest is not None:
- st, od = lenPath(shortest)
- if (td <= st):
- shortest = newPath
- else:
- shortest = newPath
- return shortest
- shortestpath = bFS(digraph, dikey, start, end, maxTotalDist, maxDistOutdoors)
- if shortestpath is None:
- pass
- # raise ValueError('No such path!')
- return shortestpath
- if __name__ == '__main__':
- LARGE_DIST = 1000000
- mitKey, mitMap = load_map("mit_map.txt")
- brutePath1 = bruteForceSearch(mitMap, mitKey, 32, 56, LARGE_DIST, LARGE_DIST)
- print "Brute-force: ", brutePath1
- # SDSize = maxSourceOrDestNumber+1
- # mitKey = np.array SDSize 1 dimensional
- # mitMap = np.array (SDSize, SDSize, 2)
- # path = [[s,d,t,o], .... ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement