Exemple #1
0
def test():
    #~ #define the grids
    bd=grid.grid()
    struktur=grid.grid()
    nahr=grid.grid()
    # load the grids
    bd.read_hdf('../../hdf/schreiadler_all.h5','bd_all')
    struktur.read_hdf('../../hdf/schreiadler_all.h5','struktur')
    nahr.read_hdf('../../hdf/schreiadler_all.h5','nahr_schreiadler')
    #~ # draw a sample of a size of 2000
    X,Y=grid.sample(g1=bd,g2=struktur,g4=nahr,n=2000,filename='s_nahr.csv')
    X=np.array(X)
    Y=np.array(Y)
    print X.shape, Y.shape
    # define the model
    t0=time.time()
    model=svm('bd','struktur')
    model.def_model()
    # train the model
    model.train(X,Y)
    # test model
    bias,rsme,r2=model.test(X,Y)
    print 'Bias=', bias, 'RSME=', rsme, 'R^2=', r2
    # write the model
    model.write_model('bd_struk.svm')
    print 'after read:', model.get_names()
    # gen the output
    out=model.calc(bd,struktur)
    print 'time=',time.time()-t0
    out.show()
Exemple #2
0
def test():
    #~ #define the grids
    bd = grid.grid()
    struktur = grid.grid()
    nahr = grid.grid()
    # load the grids
    bd.read_hdf('../../hdf/schreiadler_all.h5', 'bd_all')
    struktur.read_hdf('../../hdf/schreiadler_all.h5', 'struktur')
    nahr.read_hdf('../../hdf/schreiadler_all.h5', 'nahr_schreiadler')
    #~ # draw a sample of a size of 2000
    X, Y = grid.sample(g1=bd,
                       g2=struktur,
                       g4=nahr,
                       n=2000,
                       filename='s_nahr.csv')
    X = np.array(X)
    Y = np.array(Y)
    print X.shape, Y.shape
    # define the model
    t0 = time.time()
    model = svm('bd', 'struktur')
    model.def_model()
    # train the model
    model.train(X, Y)
    # test model
    bias, rsme, r2 = model.test(X, Y)
    print 'Bias=', bias, 'RSME=', rsme, 'R^2=', r2
    # write the model
    model.write_model('bd_struk.svm')
    print 'after read:', model.get_names()
    # gen the output
    out = model.calc(bd, struktur)
    print 'time=', time.time() - t0
    out.show()
    def test_counts(self):
        a = grid(2, 4)
        a.set(0, 0, OPEN)
        a.set(0, 1, OPEN)
        a.set(0, 2, OPEN)
        a.set(1, 0, OPEN)
        self.assertEqual(count_placements(a), 1)

        b = grid(2, 4, list(OPEN * 8))
        self.assertEqual(count_placements(b), 2)

        c = grid(3, 3, list(OPEN * 9))
        c.set(1, 1, BLOCKED)
        self.assertEqual(count_placements(c), 4)
Exemple #4
0
def Run(n):
   Ngl1 = 70 + 4 * n
   #Ngl2 = 10 + 2 * n
   mygrid = grid(xmin, xmax, ymin, ymax, Ngl1, 18)
   mygrid.train(df1, 6, 7)
   print
   print "Run(n), Ngl1 = %d" % Ngl1
   #print "Run(n), Ngl2 = %d" % Ngl2
   #print "Run(n), n = %d" % n
   with open('out.csv','wb') as f_handle:
      csvw = csv.writer(f_handle, delimiter=',', quoting=csv.QUOTE_MINIMAL)
      csvw.writerow(s1)
      i = 0
      #for i in range(nc):
      for idx, row in df2.iterrows():
         s2 = '%d,' % i
         f_handle.write(s2)
         pr = mygrid.predict(df2.Address[idx], df2.X[idx], df2.Y[idx], df2.PdDistrict[idx])
         crm = df2.Category[idx]
         j = iccl[crm]         
         if pr[j] > 1.0E-15: s[i] = -math.log(pr[j])
         else: s[i] = -math.log(1.0E-15)
         se2[i] = Entropy(pr)
         csvw.writerow(pr)
         if i % 5000 == 0:
            print "i = %d, s = %f, se2 = %f" % (i, s[:i+1].mean(), se2[:i+1].mean())
         i += 1
   #print "n = %d, S = %f, Se2 = %f" % (n, s.mean(), se2.mean())
   print "Ngl1 = %d, S = %f, Se2 = %f" % (Ngl1, s.mean(), se2.mean())
   #print "Ngl2 = %d, S = %f, Se2 = %f" % (Ngl2, s.mean(), se2.mean())
   print "\n\n"
def repeatedAStar(origMap,start,goal):
    """
    Implementation of Repeated Forward A* algorithm
    """
    
    agentMap = grid.grid(origMap.size,origMap.width,origMap.height,origMap.margin)
    agentPos = start
    path = []
    expandedCells = 0
    
    while not (agentPos.row == goal.row and agentPos.column == goal.column):
           
            #Update map           
            for neighbor in origMap.neighbors(agentPos):
                if(neighbor.isBlocked()):
                    agentMap.getCell(neighbor.row, neighbor.column).setBlocked(True)

            #Calculate best path as per available input
            bestPath,aStarExpandedCells = aStarPath.aStar(agentMap, agentPos, goal)
            expandedCells = expandedCells + aStarExpandedCells
            
            #If no path is available
            if(not bestPath):
                return None,expandedCells
            
            #Traverse 1 step in the direction
            l = len(bestPath)-2
            (pathStepX,pathStepY) = bestPath[l]
            agentPos = origMap.getCell(pathStepX,pathStepY)
            
            #recordPath
            path.append(bestPath[l])
            
    return path,expandedCells
Exemple #6
0
def ID_DFTS(state, goal, spawnList, gridSize):
    frontier = queue.LifoQueue()  # Stack implementation

    root = grid(state, '', 0, spawnList, gridSize)
    bound = 0  # Initializing max depth to zero.
    natural_failure = False  # Setting it to false, so that we toggle only we run out of any more nodes to explore.
    while not natural_failure:
        frontier.put(root)
        while True:
            if frontier.empty():
                break

            curNode = frontier.get()

            if isGoal(curNode.STATE,
                      goal):  # Checks if the goal state is reached.
                return curNode.PATH, curNode
            children = curNode.CHILDREN(spawnList, bound, gridSize)
            if len(curNode.PATH
                   ) < bound:  # As long as it is within the depth limit.
                if not children:  # Sets natural failure to True only when we run out of states to explore.
                    natural_failure = True
                else:
                    for child in children:
                        natural_failure = False  # Sets it to false to keep the loop running as along as there are
                        # more children nodes to explore.
                        frontier.put(child)
        bound += 1
Exemple #7
0
 def __init__(self, ships):
     '''Initializes player object. Add ships to fleet, grid object
     and defines valid initial player move options.'''
     self.ships = self.addShips(ships)
     self.board = grid()
     self.sonarRemaining = 2
     self.validAttack = {'c': 'coordinate attack', 'm': 'move fleet'}
Exemple #8
0
 def grid_calc3(self, g1,g2,g3):
     cdef int i,j
     cdef np.ndarray[DTYPE_t,ndim=2] mat1=g1.get_matp()
     cdef np.ndarray[DTYPE_t,ndim=2] mat2=g2.get_matp()
     cdef np.ndarray[DTYPE_t,ndim=2] mat3=g3.get_matp()
     cdef np.ndarray[DTYPE_t,ndim=2] matx=g1.get_matc()
     cdef int ii1,jj1, ii2,jj2,ii3,jj3
     (ii1,jj1)=g1.size()
     (ii2,jj2)=g2.size()
     (ii3,jj3)=g3.size()
     if(ii1!=ii2 or jj1!=jj2 or ii1!=ii3 or jj1!=jj3):
         return None
     for i in range(ii1):
         for j in range(jj1):
             if(int(mat1[i,j])==g1.get_nodata() or
                int(mat2[i,j])==g2.get_nodata() or
                int(mat3[i,j])==g3.get_nodata()):
                 matx[i,j]=g1.get_nodata()
             else:
                 matx[i,j]=self.calc3(mat1[i,j],mat2[i,j],mat3[i,j])
     gx=samt2.grid()
     (nrows,ncols,x,y,csize,nodata)=g1.get_header()
     gx.set_header(nrows,ncols,x,y,csize,nodata)
     gx.set_mat(matx)
     return gx
Exemple #9
0
 def __init__(self):
     self.grid = grid()
     self.__vis = visualization(self.grid.grid)
     self.changedcounter = 0
     self.iteration_counter = 0
     self.reward_in = 0
     self.filled_before = np.count_nonzero(self.grid.grid)
Exemple #10
0
def repeatedAStar(origMap,start,goal):
    
    
    agentMap = grid.grid(origMap.size,origMap.width,origMap.height,origMap.margin)
    agentPos = start
    path = []
    expandedCells = 0
    
    while not (agentPos.row == goal.row and agentPos.column == goal.column):
           
            #Update map           
            for neighbor in origMap.neighbors(agentPos):
                if(neighbor.isBlocked()):
                    agentMap.getCell(neighbor.row, neighbor.column).setBlocked(True)

            #Calculate best path as per available input
            bestPath,aStarExpandedCells = aStarPath.aStar(agentMap, agentPos, goal)
            expandedCells = expandedCells + aStarExpandedCells
            
            #If no path is available
            if(not bestPath):
                return None,expandedCells
            
            #Traverse 1 step in the direction
            l = len(bestPath)-2
            (pathStepX,pathStepY) = bestPath[l]
            agentPos = origMap.getCell(pathStepX,pathStepY)
            
            #recordPath
            path.append(bestPath[l])
            
    return path,expandedCells
Exemple #11
0
 def grid_calc3(self, g1,g2,g3):
     cdef int i,j
     cdef np.ndarray[DTYPE_t,ndim=2] mat1=g1.get_matp()
     cdef np.ndarray[DTYPE_t,ndim=2] mat2=g2.get_matp()
     cdef np.ndarray[DTYPE_t,ndim=2] mat3=g3.get_matp()
     cdef np.ndarray[DTYPE_t,ndim=2] matx=g1.get_matc()
     cdef int ii1,jj1, ii2,jj2,ii3,jj3
     (ii1,jj1)=g1.size()
     (ii2,jj2)=g2.size()
     (ii3,jj3)=g3.size()
     if(ii1!=ii2 or jj1!=jj2 or ii1!=ii3 or jj1!=jj3):
         return None
     for i in range(ii1):
         for j in range(jj1):
             if(int(mat1[i,j])==g1.get_nodata() or
                int(mat2[i,j])==g2.get_nodata() or
                int(mat3[i,j])==g3.get_nodata()):
                 matx[i,j]=g1.get_nodata()
             else:
                 matx[i,j]=self.calc3(mat1[i,j],mat2[i,j],mat3[i,j])
     gx=samt2.grid()
     (nrows,ncols,x,y,csize,nodata)=g1.get_header()
     gx.set_header(nrows,ncols,x,y,csize,nodata)
     gx.set_mat(matx)
     return gx
Exemple #12
0
def initializeNewGrid():
    dataKeywords = ['gridHeight', 'gridWidth', 'cellSize']
    gridDatas = {}

    # creates a dictionary, with the key originating from dataKeywords
    # this dictionary will then be used as a keyword argument
    for i in dataKeywords:
        dataEntered = False
        while not dataEntered:
            clear()
            print("Enter 0 for default value")

            # checks for invalid input
            try:
                gridData = int(
                    input("Enter " + i[:4] + " " + i[4:].lower() + " : "))
                if (gridData != 0):
                    gridDatas[i] = gridData
                    dataEntered = True
                else:
                    dataEntered = True
            except:
                continue

    # creates a grid object, with the information provided by the dictionary
    grids.append(g.grid(**gridDatas))
Exemple #13
0
def play_game():

    game = grid(4, 3, actions, (0, 0))

    # initialise random start
    idx = np.random.randint(0, 10)
    start = game.all_states[idx]

    game.set_state(start)

    # play game
    game_over = False

    states_visited = []
    n = 0
    for i in range(1000):
        n += 1
        if game.current_state not in states_visited:
            states_visited.append(game.current_state)

        idx = np.random.randint(0, len(actions[game.current_state]))
        action = actions[game.current_state][idx]
        game.take_move(actions[game.current_state][idx])

        if game.current_state == (1, 3):
            game_over = True
            break

        if game.current_state == (0, 3):
            game_over = True
            break

    return states_visited
Exemple #14
0
    def __init__(self):
        g = grid.grid(120,160,4,4,1)
        g.generate()
#f = open('120x160Map', 'w+')
#pickle.dump(g,f)
#f.close()
        g.printGrid()
Exemple #15
0
def main():

    #we define our non-constant parameters
    generations = 20
    width = 5
    height = 5

    #we randomize the seed of the game
    seed = np.empty([width, height], dtype=bool)
    for i in range(width):
        for j in range(height):
            seed[i][j] = random.choice([True, False])

    #we define our grid
    gridMap = grid.grid(seed, height, width)

    #we print out the seed generation
    print("(Seed) Generation #0:")
    gridMap.printGrid()
    print("*************")
    print("*************")

    #we loop through our grid, each time updating
    for i in range(generations):
        print("Generation #", (i + 1), ":")
        gridMap.updateGrid()
        gridMap.printGrid()
        print("*************")
        print("*************")
Exemple #16
0
def Run(n):
    Ngl1 = 70 + 4 * n
    #Ngl2 = 10 + 2 * n
    mygrid = grid(xmin, xmax, ymin, ymax, Ngl1, 18)
    mygrid.train(df1, 6, 7)
    print
    print "Run(n), Ngl1 = %d" % Ngl1
    #print "Run(n), Ngl2 = %d" % Ngl2
    #print "Run(n), n = %d" % n
    with open('out.csv', 'wb') as f_handle:
        csvw = csv.writer(f_handle, delimiter=',', quoting=csv.QUOTE_MINIMAL)
        csvw.writerow(s1)
        i = 0
        #for i in range(nc):
        for idx, row in df2.iterrows():
            s2 = '%d,' % i
            f_handle.write(s2)
            pr = mygrid.predict(df2.Address[idx], df2.X[idx], df2.Y[idx],
                                df2.PdDistrict[idx])
            crm = df2.Category[idx]
            j = iccl[crm]
            if pr[j] > 1.0E-15: s[i] = -math.log(pr[j])
            else: s[i] = -math.log(1.0E-15)
            se2[i] = Entropy(pr)
            csvw.writerow(pr)
            if i % 5000 == 0:
                print "i = %d, s = %f, se2 = %f" % (i, s[:i + 1].mean(),
                                                    se2[:i + 1].mean())
            i += 1
    #print "n = %d, S = %f, Se2 = %f" % (n, s.mean(), se2.mean())
    print "Ngl1 = %d, S = %f, Se2 = %f" % (Ngl1, s.mean(), se2.mean())
    #print "Ngl2 = %d, S = %f, Se2 = %f" % (Ngl2, s.mean(), se2.mean())
    print "\n\n"
def Main(in_board):
    board = grid.grid(constants.empty, len(in_board))
    board.massSet(in_board)  #Need to set the grid object to the starting board
    while master(
            board
    ):  #Loop function until it doesn't change anything in the grid
        pass
    return board.getGrid()
Exemple #18
0
def main():
    g = grid.grid(40,120)
    ml = Model(g)
    vw=view.View(ml,g)

    main_loop = urwid.MainLoop(vw.fill, vw.palette,unhandled_input=vw.unhandled_input)
    main_loop.set_alarm_in(1, vw.callback,user_data={"mod":ml,"vw":vw})
    main_loop.run()
Exemple #19
0
    def get_list_grids(self, hdf_name):
	"""
	   in:	hdf  str
	   out: list of all grids in hdf
	   call from slotHDF_Open_All
	"""
	gx = grid.grid()
	return gx.list_hdf(hdf_name)   
Exemple #20
0
    def CHILDREN(self, sl): # Function to try out all the moves and add it to the childList.
        childList = []
        curLayout = self.STATE
        curGrid = grid(current_grid=curLayout, spawn_list=sl)
        currState = self
        if grid.move(curGrid, 'Up', self.SPAWN):
            # Generate the state for the child
            childState = []
            for line in curGrid.get_current_grid():
                childState.append(line)
            child = Node(childState, self, 'U', self.PATHCOST + 1, self.SPAWN + 1)
            childList.append(child)
            curLayout = self.STATE
            curGrid = grid(current_grid=curLayout, spawn_list=sl)

        if grid.move(curGrid, 'Down', self.SPAWN):
            childState = []

            for line in curGrid.get_current_grid():
                childState.append(line)
            child = Node(childState, self, 'D', self.PATHCOST + 1, self.SPAWN + 1)
            childList.append(child)
            curLayout = self.STATE
            curGrid = grid(current_grid=curLayout, spawn_list=sl)

        if grid.move(curGrid, 'Left', self.SPAWN):
            childState = []

            for line in curGrid.get_current_grid():
                childState.append(line)
            child = Node(childState, self, 'L', self.PATHCOST + 1, self.SPAWN + 1)
            childList.append(child)
            curLayout = self.STATE
            curGrid = grid(current_grid=curLayout, spawn_list=sl)

        if grid.move(curGrid, 'Right', self.SPAWN):
            childState = []

            for line in curGrid.get_current_grid():
                childState.append(line)
            child = Node(childState, self, 'R', self.PATHCOST + 1, self.SPAWN + 1)
            childList.append(child)
            curLayout = self.STATE
            curGrid = grid(current_grid=curLayout, spawn_list=sl)

        return childList
Exemple #21
0
 def __init__(gridsize,xcount,ycount,zcount):
     self.xcount = xcount
     self.ycount = ycount
     self.zcount = zcount
     self.grids = np.array((self.xcount,self.ycount,self.zcount))
     for i in range(xcount):
         for j in range(ycount):
             for k in range(zcount):
                 self.grids[i][j][k] = grid(i,j,k,gridsize)
Exemple #22
0
 def __init__(self, nodes_in_layer=[18, 16, 8, 4]):
     self.grid = grid()
     self.layers = 4
     self.nodes_in_layer = nodes_in_layer
     self.weights_layer_2 = np.array([[0.] * (18 + 1)] * 16)
     self.weights_layer_3 = np.array([[0.] * (16 + 1)] * 16)
     self.weights_layer_4 = np.array([[0.] * (16 + 1)] * 4)
     self.moves_done = []
     self.food_pos = []
Exemple #23
0
 def test_write(self):
     """ tests the read write of ASCII files """
     self.gx.write_ascii('xxx.asc')
     g1=samt2.grid()
     g1.read_ascii('xxx.asc')
     os.system('rm xxx.asc')
     sx,sy=g1.size()
     print sx,sy
     assert sx==500 and sy==500
def Main(in_board):
    board = grid.grid(constants.empty, len(in_board))
    board.massSet(in_board)  #Need to set the grid object to the starting board
    keep_going = True
    while keep_going:  #Loop functions until it doesn't change anything in the grid
        keep_going = solve_rules(board)
        keep_going = keep_going or fill_master(board)
        keep_going = keep_going or logic(board)
    return board.getGrid()
Exemple #25
0
    def grid_create(self, gname, nrows, ncols):
	gx = grid.grid(nrows,ncols)
	# add grid
	gname_new = self.add_grid(gname, gx)
	# fill with random 
	retu = self.get_grid_rand_float(gname_new)
	if retu is None:
	    return False
	return gname_new    
Exemple #26
0
def init(width, height, square_size, map_generator, height_generator, name,
         h_border, v_border):
    global window
    #create the screen
    window = pygame.display.set_mode(
        (width * square_size, height * square_size))
    pygame.init()
    return grid.grid(width, height, square_size, map_generator,
                     height_generator, name, h_border, v_border)
Exemple #27
0
def constructBoard(_board, _temp_board):
    row = 0
    for i in _board:
        _temp_board.append([])
        for idx, j in enumerate(i):
            tempgrid = grid(row, idx)
            tempgrid.value = j.value
            tempgrid.occupied = j.occupied
            _temp_board[row].append(tempgrid)
        row = row + 1
Exemple #28
0
    def create_routing_grid(self):
        """ 
        Create a routing grid that spans given area. Wires cannot exist outside region. 
        """
        # We will add a halo around the boundary
        # of this many tracks
        size = self.ur - self.ll
        debug.info(1, "Size: {0} x {1}".format(size.x, size.y))

        self.rg = grid.grid()
Exemple #29
0
 def test_grid(self):
     """ A test for training sample data and apply it to the
         grid
     """
     # define the grids
     gwd=samt2.grid()
     rise=samt2.grid()
     ufc=samt2.grid()
     relyield=samt2.grid()
     # load the grids
     gwd.read_hdf('../data/training.h5','gwd')
     rise.read_hdf('../data/training.h5','rise')
     ufc.read_hdf('../data/training.h5','ufc')
     relyield.read_hdf('../data/training.h5','relyield')
     # normalize the inputs
     gwd.norm()
     rise.norm()
     ufc.norm()
     # generate the training sample
     size=500
     inp=[]
     y=np.zeros(size)     # outputs 1
     nrows,ncols=gwd.size()
     k=0                  # counter for the sample
     while(k<size):
         i=np.random.randint(nrows)
         j=np.random.randint(ncols)
         if(gwd.get(i,j)==gwd.get_nodata() or
             rise.get(i,j)==rise.get_nodata() or
             ufc.get(i,j)==ufc.get_nodata() or
             relyield.get(i,j)==relyield.get_nodata()):
             continue
         inp.append([gwd.get(i,j),rise.get(i,j),ufc.get(i,j)])
         y[k]=np.sign(relyield.get(i,j)-1.0)
         k+=1
     # start training
     m=lm.svm()
     m.set_names('gwd','rise','ufc')
     m.train(inp,y)
     res=m.calc(gwd,rise,ufc)
     m.write_model("test3.svm")
     assert np.fabs(res.corr(relyield))>0.6
Exemple #30
0
 def __init__(self):
     self.startingBoard = [[" ", "w", " ", "w", " ", "w", " ", "w"],
                           ["w", " ", "w", " ", "w", " ", "w", " "],
                           [" ", "w", " ", "w", " ", "w", " ", "w"],
                           [" ", " ", " ", " ", " ", " ", " ", " "],
                           [" ", " ", " ", " ", " ", " ", " ", " "],
                           ["b", " ", "b", " ", "b", " ", "b", " "],
                           [" ", "b", " ", "b", " ", "b", " ", "b"],
                           ["b", " ", "b", " ", "b", " ", "b", " "]]
     self.realBoard = grid.grid(" ")
     self.realBoard.massSet(self.startingBoard)  #init board
Exemple #31
0
    def move(self):
        from grid import grid

        self.direction = movement(self.exits)
        if self.direction == 'n':
            grid([self.coord[0], self.coord[1] - 1]).enter()
        elif self.direction == 's':
            grid([self.coord[0], self.coord[1] + 1]).enter()
        elif self.direction == 'e':
            grid([self.coord[0] + 1, self.coord[1]]).enter()
        elif self.direction == 'w':
            grid([self.coord[0] - 1, self.coord[1]]).enter()
        else:
            print("Error: Room.move() was passed an invalid argument.")
            exit(0)
Exemple #32
0
def batch_grid():
	parser = argparse.ArgumentParser(description="multi grid works")
	parser.add_argument('-s', '--src', help='data folder', required=True)
	parser.add_argument('-i', '--id', help='case id', required=True)
	args = vars(parser.parse_args())
	if args['src'][-1] != '/': args['src'] = args['src'] + "/"

	for fn in glob.glob(args['src']+"*.avi"):
		name = args['src'] + os.path.basename(fn).split('.')[0] + "_%s"%args['id']
		if not os.path.exists(name): os.makedirs(name)
		params = {'src' : fn, 
				"dst" : "%s/init.csv"%name,
				"grid" : "%s/grid"%name}
		#print params
		if not os.path.isfile(params['dst']):	#init already existed
			mapping(params)

	for fn in glob.glob(args['src']+"*.avi"):
		name = args['src'] + os.path.basename(fn).split('.')[0] + "_%s"%args['id']
		params = {'src' : fn, 
				"dst" : "%s/init.csv"%name,
				"grid" : "%s/grid"%name}
		grid(params)
Exemple #33
0
    def __init__(self):
        logging.debug("client init")
        #pygame.init();
        pygame.font.init()

        self.running = True

        self.m = grid.grid()
        self.start_frame()
        self.start_renderer()

        self.clgame = clgame.clgame(self.m)
        self.clgame.frame = self
        self.si = server_interface(self, self.r, self.clgame)
        self.ih = input_handler.input_handler(self.si, self.clgame, self.r)
Exemple #34
0
 def grid_calc1(self, g1):
     cdef int i,j
     cdef np.ndarray[DTYPE_t,ndim=2] mat1=g1.get_matp()
     cdef np.ndarray[DTYPE_t,ndim=2] matx=g1.get_matc()
     cdef int ii,jj
     (ii,jj)=g1.size()
     for i in range(ii):
         for j in range(jj):
             if(int(mat1[i,j])!=g1.get_nodata()):
                 matx[i,j]=self.calc1(mat1[i,j])
     gx=samt2.grid()
     (nrows,ncols,x,y,csize,nodata)=g1.get_header()
     gx.set_header(nrows,ncols,x,y,csize,nodata)
     gx.set_mat(matx)
     return gx
Exemple #35
0
 def grid_calc1(self, g1):
     cdef int i,j
     cdef np.ndarray[DTYPE_t,ndim=2] mat1=g1.get_matp()
     cdef np.ndarray[DTYPE_t,ndim=2] matx=g1.get_matc()
     cdef int ii,jj
     (ii,jj)=g1.size()
     for i in range(ii):
         for j in range(jj):
             if(int(mat1[i,j])!=g1.get_nodata()):
                 matx[i,j]=self.calc1(mat1[i,j])
     gx=samt2.grid()
     (nrows,ncols,x,y,csize,nodata)=g1.get_header()
     gx.set_header(nrows,ncols,x,y,csize,nodata)
     gx.set_mat(matx)
     return gx
Exemple #36
0
 def __init__(self):
     self.scanData = [[0, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0],
                      [0, 1, 0, 1, 0, 1, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0],
                      [0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 1, 0, 1, 0, 1, 0],
                      [0, 1, 0, 1, 0, 1, 0, 1], [1, 0, 1, 0, 1, 0, 1, 0]]
     self.startingBoard = [[" ", "w", " ", "w", " ", "w", " ", "w"],
                           ["w", " ", "w", " ", "w", " ", "w", " "],
                           [" ", "w", " ", "w", " ", "w", " ", "w"],
                           [" ", " ", " ", " ", " ", " ", " ", " "],
                           [" ", " ", " ", " ", " ", " ", " ", " "],
                           ["b", " ", "b", " ", "b", " ", "b", " "],
                           [" ", "b", " ", "b", " ", "b", " ", "b"],
                           ["b", " ", "b", " ", "b", " ", "b", " "]]
     self.board = grid.grid(" ")
     self.board.massSet(self.startingBoard)  #init board
     self.turnM = t.turnManager(['w', 'b'])
Exemple #37
0
def gbfs(state, goal, spawnList, gridSize):
    frontier = queue.PriorityQueue()  # Priority Queue Implementation

    root = grid(state, '', 0, spawnList, gridSize)
    frontier.put(root)

    explored = set()  # A python set to store explored states. Using a set as it has O(1) look up time.

    while not frontier.empty(): # Exits when the frontier is out of states to explore.

        curNode = frontier.get()
        if isGoal(curNode.STATE, goal):
            return curNode.PATH, curNode
        else:
            for child in curNode.CHILDREN(spawnList, gridSize):
                visited = child in explored # Checks if the child node is in explored set.
                if not visited:
                    frontier.put(child)
                    explored.add(child) # Adds child node to visited set if it has just been explored.
Exemple #38
0
    def initalizeGrid(self):
        """ Initialize the grid and the human and mosquito classes """
        config = self.config

        # Numpy array with the size of the grid
        self.grid = np.ndarray(shape=(config["grid-x"], config["grid-y"]), dtype=object)

        self.plotX = []
        self.plotY = []
        self.plotType = []
        self.plotSize = []

        # Add a grid instance to the array
        for x in xrange(0, config["grid-y"]):
            for y in xrange(0, config["grid-x"]):
                self.grid[x][y] = g.grid(x, y, config)

        self.addHumans()
        self.addMosquitos()
Exemple #39
0
 def updateBoardfromScan(self, board, scanData, currentPlayer):
     #Compares board to scan
     #finds differences and updates board
     #returns false if two pieces different
     pieceToSet = p.location(
         -1,
         -1)  #Stores the location of the piece to be set to currentPlayer
     oldPieces = list(
     )  #Stores the locations of the piece to that need to be removed
     scan = grid.grid(0)
     scan.massSet(scanData)
     pieceTypeToSet = currentPlayer  #this gets changed if their is a missing king, therefore piece moved was a king kindof hacky
     for i in range(8):
         for j in range(8):
             currentPos = p.location(i, j)
             if scan.get(
                     currentPos) == 1 and not board.get(currentPos) == " ":
                 continue
             elif scan.get(currentPos) == 1 and board.get(
                     currentPos) == " ":
                 pieceToSet = currentPos
             elif scan.get(
                     currentPos) == 0 and not board.get(currentPos) == " ":
                 if board.get(currentPos)[0] == currentPlayer:
                     pieceTypeToSet = board.get(
                         currentPos
                     )  #if the piece removed was of the current player, set that type to be set
                 oldPieces.append(currentPos)
             elif scan.get(currentPos) == 0 and board.get(
                     currentPos) == " ":
                 continue
             else:
                 print("ERROR IN SETTING BOARD")
                 return False
     done = board.set(pieceToSet, pieceTypeToSet)
     if done == None:
         print("no move done")
         return False
     for l in oldPieces:
         board.set(l, " ")
     self.updateToKings(board)
     return None
Exemple #40
0
    def add_hdf(self, hdf_name, dataset_name):
        """a
	    adds a new grid from a hdf filesystem with:
	    in:		hdf_name
			dataset_name
	    out:	name of the new grid  or False
			dataset_new	str
	    if dataset_name is already in the dict self.d_grids then:
	    add a 1 to the name to make it unique
	    result: add the grid in self.d_grids
        """
        dataset_new = dataset_name
        while(dataset_new in self.d_grids):
            dataset_new += "1"
        gx = grid.grid()
        if gx.read_hdf(hdf_name, dataset_name) == True:
            self.d_grids[dataset_new] = gx
	    return dataset_new
	else:
	    return None
Exemple #41
0
def start_game():
    """Function that starts the game"""
    # Screen is the native surface to which we blit other surfaces
    screen = pygame.display.set_mode((const.grid_size, const.grid_size), pygame.SRCALPHA, 32)
    pygame.display.set_caption('Pseudoku')
    # Graphic canvas is the surface that displays the background color and dividing borders
    graphic_canvas = pygame.Surface(screen.get_size())
    # Number canvas is the surface that displays the numbers in their boxes in Alpha
    number_canvas = pygame.Surface(screen.get_size(), pygame.SRCALPHA, 32)
    graphic_canvas.fill(const.plain)
    draw_vertical(graphic_canvas)
    draw_horizontal(graphic_canvas)
    # Game over canvas is the canvas that displays the end game message.
    game_over_canvas = pygame.Surface(screen.get_size())
    game_over_canvas.set_alpha(215)
    game_over_canvas.fill(const.white)
    grid_model = grid("")
    grid_model.init_grid()
    grid_model.remove_boxes()
    clock = pygame.time.Clock()
    gameloop(clock, screen, graphic_canvas, number_canvas, grid_model, game_over_canvas)
Exemple #42
0
    def add_ascii(self, filename, ascii_name):
	"""
	    adds a new grid from filesystem  (.asc) with:
	    in:		filename incl. path     str
			ascii_name		str 
	    out:	name of the new grid or None
			dataset_new		str
	    if dataset_name is already in the dict self.d_grids then:
	    add a 1 to the name to make it unique
	    result: add the grid in self.d_grids
        """
	dataset_new = ascii_name
        while(dataset_new in self.d_grids):
            dataset_new += "1"
        gx = grid.grid()
        if gx.read_ascii(filename) == True:
            self.d_grids[dataset_new] = gx
	    return dataset_new
	else:
	    print "error: ascii-filename not found"
	    return None
Exemple #43
0
def main():
    pygame.init()
    screen = display.set_mode((640, 480))
    display.set_caption('shard gui')

    screen.fill(colours['white'])
    pygame.display.update()

    t = toolbar(things=[box('label.png'), box('label.png')])
    c = cancel('label.png')
    cl = clear('label.png')
    f = forward('label.png')
    b = back('label.png')
    t.add([c, cl, b, f])
    g = grid(screen, 0, t.height, screen.get_width(),
             screen.get_height() - t.height)

    con = container(t, g, screen)

    done = False
    while not done:
        rs = con.draw(screen)
        display.update(rs)

        events = pygame.event.get()
        for e in events:
            if (e.type == QUIT):
                done = True
                break
            elif (e.type == KEYDOWN):
                if (e.key == K_ESCAPE):
                    done = True
                    break
            else:
                con.handleEvent(e)

    return
    def __init__(self,
                 rows=10,
                 cols=10,
                 start=(0, 0),
                 end=None,
                 obstructions=None,
                 obstruction_density=30,
                 block_size=20) -> None:
        self.__rows = rows
        self.__cols = cols
        self.__start = start
        self.__end = end if end else (self.__rows, self.__cols)
        self.__grid = grid(rows=self.__rows,
                           cols=self.__cols,
                           start=self.__start,
                           end=self.__end,
                           obstructions=obstructions,
                           obstruction_density=obstruction_density,
                           block_size=block_size)
        self.__obstructions = self.__grid.get_obstructions()

        print(len(self.__obstructions))
        self.__visited = {}
        self.__steps = {}
Exemple #45
0
def main():
    pygame.init()
    screen = display.set_mode((640, 480))
    display.set_caption('shard gui')
    
    screen.fill(colours['white'])
    pygame.display.update()
    
    t = toolbar(things = [box('label.png'), box('label.png')])
    c = cancel('label.png')
    cl = clear('label.png')
    f = forward('label.png')
    b = back('label.png')
    t.add([c, cl, b, f])
    g = grid(screen, 0, t.height, screen.get_width(), screen.get_height()-t.height)
    
    con = container(t, g, screen)
    
    done = False
    while not done:
        rs = con.draw(screen)
        display.update(rs)
        
        events = pygame.event.get()
        for e in events:
            if(e.type == QUIT):
                done = True
                break
            elif(e.type == KEYDOWN):
                if(e.key == K_ESCAPE):
                    done = True
                    break
            else:
                con.handleEvent(e)

    return
Exemple #46
0
#!/usr/bin/env python3


import numpy as np
import time
import sys
import os
sys.path.append(os.environ['SAMT2MASTER']+"/src")
import grid as samt2

# test the poisson solver using random distributed values

nsamples=50        # number of random samples
xsize=100          # size of the grid, can be slow if xsize>100
ysize=100
maxiter=100000     # maximum number of iterations


# define the grid and the random inputs
gx=samt2.grid(ysize,xsize)
x=np.random.randint(0,xsize,nsamples)
y=np.random.randint(0,ysize,nsamples)
z=np.ones(nsamples)

# activate the poisson solver
t0=time.time()
gx.poisson(y,x,z,0.001*nsamples,maxiter)
print("t=",time.time()-t0)

gx.show_contour()
Exemple #47
0
'''
Created on 07-Feb-2016

@author: Shreepad Patil
@Ruid: 169005770
'''

"""
Program to generate 50 101x101 Maps. 
"""

import grid
import pickle

for i in range(1,51):
    g = grid.grid(101,5,5,1)
    g.generate()
    f = open('Map' + str(i), 'wb+')
    pickle.dump(g,f)
    f.close()
info.num_factions = 4
info.faction_colors = [ vector3(255,0,0), vector3(0,0,255),
                        vector3(255,255,0), vector3(0,255,255) ]
info.faction_names = [ "orcs", "humans", "elves", "fairies" ]

grid.global_info = info
area.global_info = info

#initialize pygame
pygame.init()
screen = pygame.display.set_mode( (800,600), 0, 24 )
screen.fill( (0,0,0) )

#create information display structures
out = output.output( screen, 14 )
world = grid.grid( out, screen, (64,64), random_generator(10000, 15000) )

#create the factions
factions = []
for ident in range( info.num_factions ):
    area = world.get_random_unclaimed_area()
    area.faction_control[ ident ] = 100

    citypos = world.get_city_location( area )
    newcity = world.cities[ citypos ]

    newcity.faction_ident = ident
    newcity.population = 100
    
    fac = faction.faction( ident, out,
                           name = info.faction_names[ ident ],
import blob as bl

#opening video file
cap = cv2.VideoCapture("/home/erik/videos/videoplayback.mp4")

#creating named fixed windows
cv2.namedWindow("video",cv2.WINDOW_AUTOSIZE)
cv2.namedWindow("possessed",cv2.WINDOW_AUTOSIZE)

#lower and upper hsv values for thresholding the pigs in the video
lower = (26,74,3)
upper = (125,225,254)

#creating grid
ret, frame = cap.read()
dirg = grid.grid(frame)

#vector of times
timevec = []

while True:
	#start counting time
	benchInit = time.clock()

	#process frames 5 times
	for i in range(5):	
		#reading from video file
		ret, frame = cap.read()
		#checking if video is over
		if frame is None:
			break
#loads image in grayscale
img = cv2.imread(sys.argv[1],0)

#error while reading image
if img is None:
   print "ERROR: file could not be opened!"
   exit()

#displaying image
cv2.namedWindow("img",cv2.WINDOW_AUTOSIZE)  
cv2.imshow("img",img)
cv2.waitKey(0)

#creating grid and finding objects
dirg = gr.grid(img,32)

for i in range(1):
   blobs = dirg.locate(img)

   for blob in blobs:
      print "pt, area: ",blob.pt,blob.area()
   
   blobs = bl.ordered(blobs)
   
   print " "
   for blob in blobs:
      print "pt, area: ",blob.pt,blob.area()

   for blob in blobs:
      blob.mark(img)
info = global_info.global_info()
info.num_factions = 2
info.faction_colors = [ vector3(255,0,0), vector3(0,0,255) ]
info.faction_names = [ "orcs", "humans" ]

grid.global_info = info
area.global_info = info

#initialize pygame
pygame.init()
screen = pygame.display.set_mode( (800,600), 0, 24 )
screen.fill( (0,0,0) )

#create information display structures
out = output.output( screen, 14 )
world = grid.grid( out, screen, (64,64), random_generator(36, 64) )

#create the factions
area = world.get_area_at( 0, 0 )
area.faction_control[0] = 100

Thragg = world.cities[0] = city.city(area.pos,
                                     out,
                                     faction_ident=0,
                                     population=100,
                                     name="Thragg",
                                     area=area)

orcs = faction.faction( 0, out, name = "orcs",
                        cities = [ Thragg ],
                        areas = world.linearize() )
Exemple #52
0
def main():
    argparser = argparse.ArgumentParser(description="text file")
    argparser.add_argument("file", type=str, help="file to produce frequency distribution for")
    argparser.add_argument("-m", "--pLen", type=int, default=4, help="length of the patterns to look for")
    argparser.add_argument("-n", "--nRes", type=int, default=5, help="number of results to show")
    argparser.add_argument("-k", "--findKey", help="find patterns from repeating key", action="store_true")
    argparser.add_argument(
        "-p",
        "--plotByAlpha",
        help="-p N: split cipher text by N alphabets and save plots. specify dir to save with -d. default is the current directory",
        type=int,
        default=0,
    )
    argparser.add_argument("-l", "--cipherLen", help="display the length of the cipher text", action="store_true")
    argparser.add_argument("-d", "--outDir", type=str, default=".", help="directory to save files to")
    argparser.add_argument("-a", "--ascii", help="text is ascii", action="store_true")
    argparser.add_argument(
        "-s",
        "--shiftByAlpha",
        help="-s N: split cipher text by N alphabets and shift on the basis of frequency analysis",
        type=int,
        default=0,
    )
    argparser.add_argument("-r", "--reverseShift", help="shift charcters backwards", action="store_true")
    argparser.add_argument(
        "-x",
        "--xorByAlpha",
        help="-x N: split cipher text by N alphabets and xor on the basis of frequency analysis",
        type=int,
        default=0,
    )
    argparser.add_argument("-c", "--common", help="most common letter in plain text alphabet", default="e")
    argparser.add_argument(
        "-g", "--grid", help="-g N: output the cipher text in a grid N chars wide", type=int, default=0
    )
    argparser.add_argument(
        "-t",
        "--transpose",
        help="-t N: output the cipher text in a grid N chars wide",
        metavar="N",
        nargs="+",
        type=int,
        default=0,
    )
    argparser.add_argument(
        "-i", "--perpGrid", help="-g N: output the cipher text in a grid N chars wide", type=int, default=0
    )

    args = argparser.parse_args()

    toker = WhitespaceTokenizer()

    f = open(args.file)
    if args.ascii:
        text = f.read().split()
        arry = []
        for e in text:
            arry.append(chr(int(e, 16)))
            # ascString = string.join(arry)
        ascString = arry
    else:
        ascString = f.read()
        tmp = ""
        for c in ascString:
            if ord(c) < 128:
                tmp = tmp + c

        ascString = tmp
    if args.cipherLen:
        print("cipher text length: " + str(len(ascString)))

    if args.findKey:
        print(findKey.getNgramsDispersion(string.join(ascString), args.pLen, args.nRes))

    if args.plotByAlpha > 0:
        alphas = split.splitByAlpha(args.plotByAlpha, ascString)
        g = 0
        for group in alphas:
            g += 1
            myFreqDist.MyFreqDist(group).createPlot(args.outDir + "s" + str(args.plotByAlpha) + "g" + str(g), 10)

    if args.shiftByAlpha > 0:
        alphas = split.splitByAlpha(args.shiftByAlpha, ascString)
        candidate = shift.shiftByAlpha(alphas, ascString, args.common, args.reverseShift)
        file = open(args.outDir + "candidate.pln", "w")
        print(candidate)

    if args.xorByAlpha > 0:
        alphas = split.splitByAlpha(args.xorByAlpha, ascString)
        candidate = xor.xorByAlpha(alphas, ascString, args.common)
        file = open(args.outDir + "candidate.pln", "w")
        print(candidate)

    if args.grid > 0:
        grid.grid(ascString, args.grid)

    if args.perpGrid > 0:
        perpGrid.grid(ascString, args.perpGrid)

    if len(args.transpose) > 0:
        transpose.transpose(ascString, args.transpose)
Exemple #53
0
import numpy as np
import sys
import os
# sys.path.append('/home/ralf/master/samt2')
sys.path.append(os.environ['SAMT2MASTER']+"/src")
import grid as samt2

inch   = 2.54      # cm
width  = 14.8      # cm postcard
height = 10.5      # cm postcard

res    = 300       # dots/inch
nrows  = int(height/inch*res)
ncols  = int(width/inch*res)

print('nrows:', nrows, 'ncols:', ncols)
size=25           # random points

# define the grid
gx=samt2.grid(nrows,ncols)
# generate random points x,y,z
x=np.random.randint(ncols,size=size)
y=np.random.randint(nrows,size=size)
z=np.random.rand(size)
# interpolation
intmeth=['linear','cubic','thin_plate']
for method in intmeth:
    print(method)
    gx.interpolate(x,y,z,method=method)
    gx.show_contour()
 def test_placements_from_head(self):
     a = grid(4, 4, list(OPEN * 16))
     rotations = placements_from_head(a, 0, 0)
     self.assertEqual(rotations,
             [[(0, 0), (1, 0), (2, 0), (2, 1)], [(0, 0), (0, 1), (0, 2), (1, 2)]])
Exemple #55
0
'''
Created on 10-Feb-2016

@author: Shreepad Patil
'''

"""
Program to generate 5x5 Maps. 
"""

import grid
import pickle

g = grid.grid(5,20,20,5)
g.generate()
f = open('10x10Map', 'wb+')
pickle.dump(g,f)
f.close()

g.printGrid()


Exemple #56
0
min_speed = 5
speed = min_speed

done = False
pause = False

pygame.init()



pygame.display.set_caption("Game of Life")

clock = pygame.time.Clock()


main = grid()

if len(sys.argv) > 1:
	main.load_map(sys.argv[1])
else:
	main.load_random(ROW, COL)

window_size = [WIDTH * len(main.grid[0]) + MARGIN * len(main.grid[0]) + MARGIN, HEIGHT * len(main.grid)+ MARGIN * len(main.grid) + MARGIN]
screen = pygame.display.set_mode(window_size)
screen.fill(gray)

def draw_grid():
	for row in range(len(main.grid)):
		for col in range(len(main.grid[row])):
			if main.grid[row][col] == 0:
				color = white 
Exemple #57
0
 def __init__(self):
     self.__grid = grid.grid()
     self.loadSolver()
Exemple #58
0
#!/usr/bin/env python3
# simple test for different interpolation methods

import numpy as np
import sys
import os
# sys.path.append('/home/ralf/master/samt2')
sys.path.append(os.environ['SAMT2MASTER']+"/src")
import grid as samt2


gx=samt2.grid()
gx.read_hdf(os.environ['SAMT2MASTER']+'/data/ziethen.hdf','zie_dgm')

for i in xrange(5,51):
    print  gx.complexity(i)

    
import sys
import os
import grid

# test data
px=50 # pixel size
nx=6 
ny=10
ll_x=-800 # lower left x
ll_y=-800
tl_x=-800 # top left x
tl_y=-250 

# create grid object instances
ll=grid.grid(ll_x,ll_y,nx,ny,px,corner='lower_left')
tl=grid.grid(tl_x, tl_y, nx, ny, px, corner='top_left')


def test_tl_corner_mesh():

	tl_corner=tl.cell_corner_mesh()

	#tl_corner[0] = the x coordiante mesh
	#tl_corner[1] = the x coordiante mesh

	try:
		assert tl_corner[0].min() == ll_x
	except AssertionError:
		sys.exit("Corner mesh output incorrect")

	try:
Exemple #60
0
            se2[i] = Entropy(pr)
            csvw.writerow(pr)
            if i % 5000 == 0:
                print "i = %d, s = %f, se2 = %f" % (i, s[:i + 1].mean(),
                                                    se2[:i + 1].mean())
            i += 1
    #print "n = %d, S = %f, Se2 = %f" % (n, s.mean(), se2.mean())
    print "Ngl1 = %d, S = %f, Se2 = %f" % (Ngl1, s.mean(), se2.mean())
    #print "Ngl2 = %d, S = %f, Se2 = %f" % (Ngl2, s.mean(), se2.mean())
    print "\n\n"


#for i in range(0, 40):
#   Run(i)

with open('out.csv', 'wb') as f_handle:
    csvw = csv.writer(f_handle, delimiter=',', quoting=csv.QUOTE_MINIMAL)
    csvw.writerow(s1)
    mygrid = grid(xmin, xmax, ymin, ymax, 80, 18)
    mygrid.train(df1, 6, 7)
    i = 0
    for idx, row in df2.iterrows():
        s2 = '%d,' % i
        f_handle.write(s2)
        pr = mygrid.predict(df2.Address[idx], df2.X[idx], df2.Y[idx],
                            df2.PdDistrict[idx])
        csvw.writerow(pr)
        if i % 5000 == 0:
            print "i = %d" % i
        i += 1