Example #1
0
    def __init__(self, seed, height, width):
                
        #initialize the width and height parameters
        self.height = height
        self.width = width

        #we define the grid to be a 2D numpy array of object
        self.gridCurrent = [[cell.cell(seed[i][j]) for i in range(self.width)] for j in range(self.height)]

        #we initialize the array based upon the seed
        for i in range(self.height):
            for j in range(self.width):
                self.gridCurrent[i][j] = cell.cell(seed[i][j])
Example #2
0
def createCells():
    color = (0, 0, 0)
    for j in range(row):
        for i in range(column):
            cells.append(
                cell.cell(i * blockSize, j * blockSize, blockSize, color,
                          screen))
Example #3
0
def computePath(curr, target):
    # print("------------------")
    # print(target.x, target.y)
    closedset = set()
    direction = [[0,1],[1,0],[-1,0],[0,-1]]
    openlist = []
    heapq.heappush(openlist, curr)
    # closedset.add((curr.x, curr.y))
    while len(openlist) != 0:

        pt = heapq.heappop(openlist)
        # print("expanding: ")
        # print(pt.x, pt.y)
        closedset.add((pt.x, pt.y))
        if pt.x == target.x and pt.y == target.y:
            return pt, closedset
            break
        for dir in direction:
            a = pt.x + dir[0]
            b = pt.y + dir[1]
            if a >= 0 and b >= 0 and a < len(visit) and b < len(visit[0]) and visit[a][b] == 0 and (a, b) not in closedset:

                tmp = cell(a, b)
                # closedset.add((a, b))
                checkandremove(tmp, openlist)
                tmp.parent = pt
                tmp.g = pt.g + 1
                tmp.getHeuristic(target.x, target.y)
                # print(tmp.x, tmp.y, tmp.f, tmp.g)
                heapq.heappush(openlist, tmp)
                # print(len(openlist))
    return None, None
Example #4
0
def setup_grid():
    grid = []
    for row in range(100):
        grid.append([])
        for col in range(100):
            grid[row].append(cell(row, col))
    return grid
Example #5
0
    def readMCNP(self, u, l_line, l_blocklist):
        self.id = u
        i = l_line.count('LAT')  #默认不含LAT的UNIVERSE都是包含CELL子单元的
        if i == 0:
            c_cell = cell.cell()
            c_cell.readMCNP(u, l_line)
            self.cells.append(c_cell)
        else:
            l_line = rm.format_line(l_line)
            j = l_line.index('LAT')
            self.lat = l_line[j + 1]
            if l_line.count('IMP:N') != 0:
                j = l_line.index('IMP:N')
                self.void = str(1 - int(l_line[j + 1]))
            if l_line[1] == '0':
                i = 2
            else:
                i = 3
            j = i
            while l_line[j] != 'U':
                j = j + 1
            self.surf_bool = l_line[i:j]
            j = l_line.index('FILL')
            self.scope[0] = mr.getscope(l_line[j + 1:j + 4])
            self.scope[1] = mr.getscope(l_line[j + 4:j + 7])
            self.scope[2] = mr.getscope(l_line[j + 7:j + 10])
            self.fill = l_line[j + 10:]
            self.pitch = mr.getpitch(self.surf_bool, l_blocklist)

        self.move = mr.getmove(u, l_blocklist, self)
Example #6
0
    def __init__(self, reactor, x, y, depth):
        self.reactor = reactor
        self.simulation_instance = self.reactor.simulation_instance
        self.object_path = "%s/rod/%d/%d" % (self.reactor.object_path, x, y)
        self.bus_name = dbus.service.BusName("fi.hacklab.reactorsimulator.engine.reactor.rod.x%d.y%d" % (x, y), bus=self.simulation_instance.bus)
        dbus.service.Object.__init__(self, self.bus_name, self.object_path)
        self.config = self.simulation_instance.config['rod']

        self.x = x
        self.y = y
        self.well_depth = depth
        self.set_depth(self.config['initial_position'])
        #self.set_depth(7.0) # all-in
        #self.set_depth(-2) # all-out
        self.current_max_speed = self.config['default_max_speed']
        self.current_max_flow = self.config['default_max_flow']
        self.current_water_flow = self.config['default_water_flow']
        self.current_velocity = self.config['initial_speed'] # initialize to at rest

        self.water_level = 1.0 # This is basically percentage of the full depth 1.0 means full of water
        self.steam_pressure = 0.0 # In whatever unit we feel is most convinient
        self.avg_temp = 0.0
        self.max_temp = 0.0
        # When scram is active other move commands are ignored
        self.scram_active = False

        
        self.cells = []
        for i in range(self.well_depth):
            self.cells.append(cell.cell(self, i))

        # Final debug statement
        print "%s initialized" % self.object_path
Example #7
0
 def newDestinationCell(self, cid, lane, model):
     c = cell(cid, lane, model, self.TIME)
     c.type = "destination"
     c.downstream = None
     self.destinationCell.append(c)
     self.all.append(c)
     return c
def init(json):
    #Se inicia la pantalla de Turtle
    screen1 = turtle.Screen()
    screen1.screensize(300, 300)
    screen1.title("Tarea Programada 1")
    t = turtle.Turtle()
    t.hideturtle()
    screen1.tracer(0, 0)
    t.speed(0)
    t.penup()
    t.goto(-250, 250)
    t.pendown()
    t.pencolor('maroon')
    t.fillcolor('maroon')
    t.begin_fill()
    t.goto(-250, -250)
    t.goto(250, -250)
    t.goto(250, 250)
    t.goto(-250, 250)
    t.end_fill()
    #Se comienza con el arreglo de las celdas
    cells = []
    #Se llena el arreglo
    for i in range(0, 10000):
        cells.append(cell.cell(i, t))
    for i in range(0, 10000):
        cells[i].currentState = json[i]
    redrawAll(cells, screen1)
Example #9
0
    def __init__(self, reactor, x, y, depth):
        self.reactor = reactor
        self.simulation_instance = self.reactor.simulation_instance
        self.object_path = "%s/rod/%d/%d" % (self.reactor.object_path, x, y)
        self.bus_name = dbus.service.BusName(
            "fi.hacklab.reactorsimulator.engine.reactor.rod.x%d.y%d" % (x, y),
            bus=self.simulation_instance.bus)
        dbus.service.Object.__init__(self, self.bus_name, self.object_path)
        self.config = self.simulation_instance.config['rod']

        self.x = x
        self.y = y
        self.well_depth = depth
        self.set_depth(self.config['initial_position'])
        #self.set_depth(7.0) # all-in
        #self.set_depth(-2) # all-out
        self.current_max_speed = self.config['default_max_speed']
        self.current_max_flow = self.config['default_max_flow']
        self.current_water_flow = self.config['default_water_flow']
        self.current_velocity = self.config[
            'initial_speed']  # initialize to at rest

        self.water_level = 1.0  # This is basically percentage of the full depth 1.0 means full of water
        self.steam_pressure = 0.0  # In whatever unit we feel is most convinient
        self.avg_temp = 0.0
        self.max_temp = 0.0
        # When scram is active other move commands are ignored
        self.scram_active = False

        self.cells = []
        for i in range(self.well_depth):
            self.cells.append(cell.cell(self, i))

        # Final debug statement
        print "%s initialized" % self.object_path
Example #10
0
def calculate(iterations, file):
    import cell
    if os.path.exists(file):
        os.remove(file)  #this deletes the file
    f = open(file, "w")
    #Se comienza con el arreglo de las celdas
    cells = []
    #Se llena el arreglo
    for i in range(0, 10000):
        cells.append(cell.cell(i))
    #Se hace la relación entre vecinos
    for cell in cells:
        cell.setNeighbors(cells)
    #Código itrativo de la simulación
    JSON = '['
    for i in range(0, iterations):
        if i != 0:
            calculateNext(cells)
        JSON += '['
        for cell in cells:
            JSON += str(int(cell.currentState))
            if cell.index != 9999:
                JSON += ','
        JSON += ']\n'
        if (i != iterations - 1):
            JSON += ',\n'
    JSON += ']'
    f.write(JSON)
    f.close()
Example #11
0
    def cell(self, matl):
        """ ``geo.cell(matl)`` returns a cell of this geometry with
            material ``matl``

            :param wig.matl.matl matl: The material to make this cell
            :returns: ``mcnpce.cell`` object
        """
        return mcnpce.cell(self, matl)
Example #12
0
 def __init__(self,puzzleStart):
     print("Board Initializing")
     for eachRow in range(9):
         row = []
         for eachCell in range(9):
             row.append(cell(eachRow,eachCell))
         self.__AllCells.append(row)
     self.__setWholeTable(puzzleStart)
Example #13
0
    def readRMC(self, s_block):
        l_line = s_block.split('\n')
        if len(l_line) == 1:
            l_line = l_line[0].split(' ')
            l_line = rm.format_line(l_line)
            l_line.pop(0)
            self.id = l_line.pop(0)
            i = l_line.count('MOVE')
            if i != 0:
                j = l_line.index('MOVE')
                l_move = l_line[j + 1:j + 4]
                self.move = [float(s) for s in l_move]
                del l_line[j:j + 4]

            i = l_line.count('ROTATE')
            if i != 0:
                j = l_line.index('ROTATE')
                l_rotate = l_line[j + 1:j + 10]
                self.rotate = [float(s) for s in l_rotate]
                del l_line[j:j + 10]
            i = l_line.count('FILL')
            if i != 0:
                j = l_line.index('FILL')
                l_fill = l_line[j + 1:]
                self.fill = [int(s) for s in l_fill]
                del l_line[j:]
            i = l_line.count('LAT')
            if i != 0:
                j = l_line.index('LAT')
                self.lat = l_line[j + 1]
                j = l_line.index('PITCH')
                l_pitch = l_line[j + 1:j + 4]
                self.pitch = [float(s) for s in l_pitch]
                if self.lat == '1':
                    j = l_line.index('SCOPE')
                    l_scope = l_line[j + 1:j + 4]
                    self.scope = [int(s) for s in l_scope]
                elif self.lat == '2':
                    j = l_line.index('SCOPE')
                    self.scope = l_line[j + 1:j + 3]
                    l_scope = l_line[j + 1:j + 4]
                    self.scope = [int(s) for s in l_scope]
                    j = l_line.index('SITA')
                    self.sita = float(l_line[j + 1])
        else:
            l_line0 = l_line[0].split(' ')
            l_line0.pop()
            self.id = l_line0.pop(0)
            i = l_line.count('MOVE')
            if i != 0:
                j = l_line.index('MOVE')
                l_move = l_line[j + 1:j + 4]
                self.move = [float(s) for s in l_move]
                del l_line[j:j + 4]
            for i in range(1, len(l_line)):
                c_cell = cell.cell()
                c_cell.readRMC(l_line[i])
                self.cells.append(c_cell)
Example #14
0
def main():
    #connect mongodb
    client = MongoClient()
    client.data_platform_dev.authenticate('app', 'wenhui')
    db = client.data_platform_dev
    cells_collection = db.cells

    #randomly batch read in samples
    samples = []
    randomly_skip_list = []
    fault_list = []
    success = True

    for i in xrange(0, REPEAT_FETCH):
        randomly_skip_list.append(randint(0, 14000000))

    for skip in randomly_skip_list:
        print skip
        for sample in cells_collection.find().skip(skip).limit(BATCH_READS):
            samples.append(sample)

    #randomly duplicate some samples
    for i in xrange(0, REPEAT_DUPLICATE):
        for duplicate in do_sampling(samples, BATCH_DUPLICATE):
            samples.append(duplicate)

    #request api service and verify result
    for sample in samples:
        #for each request sample
        oneObjAllHit = False
        othersParamHit = True

        #get request return list
        result_list = json.loads(
            cell(sample['mnc'], sample['lac'], sample['cell']))

        #there should be one cell object all hit
        for returned_obj in result_list:
            #one returned object get all hit with request sample
            if allHit(sample, returned_obj):
                oneObjAllHit = True
                break

        #others get param hit
        for returned_obj in result_list:
            if not paramHit(sample, returned_obj):
                othersParamHit = False
                break

        if not (oneObjAllHit and othersParamHit):
            print 'Wrong!!!!'
            fault_list.append(sample)
            success = False

    if success:
        print 'Vola!!'
    else:
        print 'Ahoh'
def createnetwork(points, polygons):

    #points : array with all the coordinates of the vertices
    #polygons : array with n-integer-array for each cell that
    #represent the numero of the vertices that are in this cell

    vertices = []
    links = []
    cells = []

    # Find the boundary vertices
    boundary = ConvexHull(points)

    #Creation of the vertices with the argument 1 for boundary and 0 for bulk
    for i in range(len(points)):
        if i in boundary.vertices:
            vertices.append(vertice(i, points[i], 1))
        else:
            vertices.append(vertice(i, points[i], 0))

    #Creation of the cells and adding the vertices
    for i in range(len(polygons)):
        cells.append(cell(i))
        for j in range(len(polygons[i])):
            cells[i].add_vertice(vertices[polygons[i][j]])
        cells[i].orderingvertices()

    #Creation of the links and adding to the cells.
    for i in range(len(cells)):
        for j in range(len(cells[i].vertices)):
            if j != len(cells[i].vertices) - 1:
                link_0 = link([cells[i].vertices[j], cells[i].vertices[j + 1]],
                              "membrane")
                cells[i].add_link(link_0)
            else:
                link_0 = link([cells[i].vertices[j], cells[i].vertices[0]],
                              "membrane")
                cells[i].add_link(link_0)

            if link_0 not in links:
                links.append(link_0)

        for j in range(len(cells[i].vertices)):
            if j == 0:
                for k in range(2, len(cells[i].vertices) - 1):
                    link_0 = link([cells[i].vertices[j], cells[i].vertices[k]],
                                  "inside")
                    cells[i].add_link(link_0)
                    links.append(link_0)
            else:
                for k in range(j + 2, len(cells[i].vertices)):
                    link_0 = link([cells[i].vertices[j], cells[i].vertices[k]],
                                  "inside")
                    cells[i].add_link(link_0)
                    links.append(link_0)

    return [vertices, links, cells]
Example #16
0
    def _buildSparseSystem(self, xyPoints):
        """
        Build sparse matrix system
        @param xyPoints list of unique (x, y) tuples, ordered counterclockwise
        @return ellipt2d objects in a dictionary
        """

        grid, bcs = self._triangulatePoints(xyPoints)
        #grid.plot()
        numPoints = len(xyPoints)

        # Laplace equation solver
        eq = ellipt2d.ellipt2d(grid, '1.0', '0.0', '0.0')
        amat, bvec = eq.stiffnessMat()

        #
        # rho field
        #

        rhoMat = copy.deepcopy(amat)
        rhoBVec = copy.deepcopy(bvec)

        bcData = {}
        for i, g in grid.data.items():
            if g[2]:
                # boundary
                #print 'x, y = {} rho Dirichlet BC is {}'.format(grid[i][0], bcs[i][0])
                bcData[i] = bcs[i][0]
        bc = DirichletBound.DirichletBound(bcData)
        # modify the matrix and source vector
        eq.dirichletB(bc, rhoMat, rhoBVec)

        #
        # theta field
        #

        theMat = copy.deepcopy(amat)
        theBVec = copy.deepcopy(bvec)

        bcData = {}
        for i, g in grid.data.items():
            if g[2]:
                # boundary
                #print 'x, y = {} theta Dirichlet BC is {}'.format(grid[i][0], bcs[i][1])
                bcData[i] = bcs[i][1]
        bc = DirichletBound.DirichletBound(bcData)
        eq.dirichletB(bc, theMat, theBVec)

        return {
            'eq': eq,
            'grid': grid,
            'cells': cell.cell(grid),
            'rhoMat': rhoMat,
            'rhoBVec': rhoBVec,
            'theMat': theMat,
            'theBVec': theBVec
        }
Example #17
0
def readData(GRID, GRID_DATA, COL, ROW, CELL_SIZE):
    for i in range(COL):
        column = []
        for j in range(ROW):
            column.append(cell(screen, GRID_DATA[i][j][0], i, j,
                                                    margin + (CELL_SIZE + margin)*i, 
                                                    margin + (CELL_SIZE + margin)*j, 
                                                    grid_color, CELL_SIZE ))
        GRID.append(column)
def main():
	#connect mongodb
	client = MongoClient()
	client.data_platform_dev.authenticate('app', 'wenhui')
	db = client.data_platform_dev
	cells_collection = db.cells

	#randomly batch read in samples
	samples = []
	randomly_skip_list = []
	fault_list = []
	success = True

	for i in xrange(0, REPEAT_FETCH):
		randomly_skip_list.append( randint(0, 14000000) )

	for skip in randomly_skip_list:
		print skip
		for sample in cells_collection.find().skip(skip).limit(BATCH_READS):
			samples.append(sample)

	#randomly duplicate some samples
	for i in xrange(0, REPEAT_DUPLICATE):
		for duplicate in do_sampling(samples, BATCH_DUPLICATE):
			samples.append(duplicate)

	#request api service and verify result
	for sample in samples:
		#for each request sample
		oneObjAllHit = False
		othersParamHit = True

		#get request return list
		result_list = json.loads( cell(sample['mnc'], sample['lac'], sample['cell']) )

		#there should be one cell object all hit
		for returned_obj in result_list:
			#one returned object get all hit with request sample
			if allHit(sample, returned_obj):
				oneObjAllHit = True
				break

		#others get param hit
		for returned_obj in result_list:
			if not paramHit(sample, returned_obj):
				othersParamHit = False
				break

		if not (oneObjAllHit and othersParamHit):
			print 'Wrong!!!!'
			fault_list.append(sample)
			success = False

	if success:
		print 'Vola!!'
	else:
		print 'Ahoh'
Example #19
0
def setup():
    board = []
    size = 20
    for x in range(28):
        currow = [] 
        for y in range(28):
            currow.append(cell(size*(x+1), (y+1)*size, size))
        board.append(currow)
    return board
def create_board(board):
    global board_objects
    board_objects = []
    for i in range(9):
        board_objects_row = []
        for j in range(9):
            board_objects_row.append(c.cell(board[i][j], i, j))

        board_objects.append(board_objects_row)
Example #21
0
 def newOriginCell(self, cid, lane, model, D):
     c = cell(cid, lane, model, self.TIME)
     c.type = "origin"
     # to avoid too full
     c.jam = lane * 1000
     c.D = D  # new vehicles generated here
     c.upstream = None
     self.originCell.append(c)
     self.all.append(c)
     return c
Example #22
0
	def test_split1(self):
		dim = 0

		c = cell.cell()
		g = ndgrid.ndgrid(c)
		self.assertRaises(ValueError, g.split, cell.cell(), dim)

		for c in g.get_cells():
			g.split(c, dim)
		cells = g.get_cells()
		self.assertEqual(len(cells), 2)

		for c in cells:
			self.assertIn(dim, c.volume)

		for c in cells:
			ext = c.get_extent(dim)
			self.assertTrue(ext[0] == 0.0 or ext[1] == 0.0)
			self.assertTrue(ext[0] == -1.0 or ext[1] == +1.0)
Example #23
0
 def __init__(self,width,height):
     """
     width=x coordinate
     height=y coordinate
     :param width:
     :param height:
     :return:
     """
     self.height=height
     self.width=width
     self.b=[[cell.cell() for x in range(width)] for y in range(height)]
Example #24
0
 def __init__(self, width, height):
     """
     width=x coordinate
     height=y coordinate
     :param width:
     :param height:
     :return:
     """
     self.height = height
     self.width = width
     self.b = [[cell.cell() for x in range(width)] for x in range(height)]
Example #25
0
 def newIntersectionCell(self, cid, lanewidth, model):
     # lanewidth = [1,2,1,3] left, straight, right, special
     c = cell(cid, 10, model, self.TIME)
     c.type = "intersection"
     c.virtualCell = []
     for index, dirction in enumerate(["l", "s", "r", "u"]):
         vc = self.newVirtualCell(c.id + dirction, lanewidth[index], model)
         c.virtualCell.append(vc)
     self.intersectionCell.append(c)
     self.all.append(c)
     return c
Example #26
0
def createnetwork(points, polygons):

    #points : array with all the coordinates of the vertices
    #polygons : array with n-integer-array for each cell that
    #represent the numero of the vertices that are in this cell

    vertices = []
    links = []
    cells = []

    #Creation of the vertices with the argument 1 for boundary and 0 for bulk
    for i in range(len(points)):
        vertices.append(vertice(i, points[i]))
    #Creation of the cells and adding the vertices
    for i in range(len(polygons)):
        cells.append(cell(i))
        for j in range(len(polygons[i])):
            cells[i].add_vertice(vertices[polygons[i][j]])
        cells[i].orderingvertices()
        cells[i].A0 = cells[i].area()
        cells[i].A_ac = cells[i].A0
        cells[i].K = 10.

    # Finding the vertices on the boundary
    count = np.zeros(len(vertices))
    for i in range(len(cells)):
        for j in range(len(cells[i].vertices)):
            count[cells[i].vertices[j].n] += 1

    for i in range(len(count)):
        if count[i] < 3:
            vertices[i].boundary = True

    for i in range(len(cells)):
        for j in range(len(cells[i].vertices)):
            if cells[i].vertices[j].boundary == True:
                cells[i].boundary = True

    #Creation of the links and adding to the cells.
    for i in range(len(cells)):
        for j in range(len(cells[i].vertices)):
            if j != len(cells[i].vertices) - 1:
                link_0 = link([cells[i].vertices[j], cells[i].vertices[j + 1]])
                cells[i].add_link(link_0)
            else:
                link_0 = link([cells[i].vertices[j], cells[i].vertices[0]])
                cells[i].add_link(link_0)

            if link_0 not in links:
                links.append(link_0)

    return [vertices, links, cells]
Example #27
0
    def __init__(self, rows, cols, wall_density, pill_density, fruit_chance, fruit_score, time_mult):
        self.rows = rows
        self.cols = cols
        self.wall_density = wall_density
        self.pill_density = pill_density
        self.fruit_chance = fruit_chance
        self.fruit_score = fruit_score
        self.time_mult = time_mult
        self.time = int((rows-2)*(cols-2)*time_mult)
        self.score = 0
        self.pills_eaten = 0
        self.fruit_exist = False
        self.fruit_consumed = 0

        #String to be updated as the game progresses. Will be world file when game ends
        self.world_string = ""

        #The standard numner of ghost, will add to a config file later
        self.NUM_GHOST = 3

        #total number of pills in the game after generation
        self.total_pills = 0

        #Map of cells
        self.map = [[cell(i, j) for j in range(cols)] for i in range(rows)]

        #List of pellet coords to check for ditance
        self.pill_dict = {}

        #(y, x) pair for fruit location
        self.fruit_location = (-1, -1)

        #Member constants
        #Cells for pacman and chost
        self.PACMAN_START = self.map[1][1]
        self.GHOST_START = self.map[rows-2][cols-2]

        #Make sure the _CARVED is zero. When doing multiple runs this value needs to be reset
        self.fast_generate()

        #NBow place pacman epnices on board
        self.pac = pacman(self.PACMAN_START, self)
        self.PACMAN_START.place_occupents(self.pac)

        #create ghost
        self.ghost = []
        for i in range(0, self.NUM_GHOST):
            self.ghost.append(ghost(self.GHOST_START, self))
            self.GHOST_START.place_occupents(self.ghost[i])

        #Completed creating ghost
        self.world_string_start()
Example #28
0
 def newVirtualCell(self, cid, lane, model):
     c = cell(cid, lane, model, self.TIME)
     c.type = "virtual"
     # debug
     c.jam = lane * 1000
     c.q = {}  # actual capacity
     for t in range(self.TIME):
         c.q[t] = model.addVar(lb=0,
                               vtype=GRB.CONTINUOUS,
                               name="q" + str(c.id) + "_" + str(t))
     self.virtualCell.append(c)
     self.all.append(c)
     return c
Example #29
0
    def __init__(self,
                 board_size,
                 game_height,
                 game_width,
                 line_colour=(255, 255, 255)):
        self.board_size = board_size
        self.passable = True
        self.game_height = game_height
        self.game_width = game_width

        self.cells = [[cell(x, y) for y in range(board_size[1])]
                      for x in range(board_size[0])]
        self.cell_size = self.game_width / self.board_size[0]
Example #30
0
    def __init__(self):
        try:
            f=open('map.txt','r')
        except IOError:
            print "file don't exist, please check!"
        Alllines = f.readlines()
        count = 0
        self.hardcenter = set()
        self.Matrix = []
        self.path=set()
        WIDTH = 4
        HEIGHT =4
        MARGIN =1
        ROWS=0
        COLUMNS =0

        for i in range(120):
            self.Matrix.append([])
        for eachline in Alllines:
            count=count+1
            line = eachline.split(',')
            if count == 1:
                self.startRow = int(line[0])
                self.startColumn = int(line[1])
            if count == 2:
                self.endRow =int(line[0])
                self.endColumn = int(line[1])
            if count<=10 and count >=3:
                self.hardcenter.add((int(line[0]),int(line[1])))
            if count == 11:
                self.ROWS=int(line[0])
                self.COLUMNS=int(line[1])
            if count>=12 and count<=131:
                #print count
                for i in range(160):
                    self.Matrix[count-12].append(cell.cell(count-12, i))
                    if(i!=159):
                        if((line[i] == '0') or (line[i] == '1') or (line[i] =='2')):
                            self.Matrix[count - 12][i].setState(int(line[i]))
                        else:
                            self.Matrix[count - 12][i].setState(line[i][0])
                            self.Matrix[count - 12][i].setHighway(int(line[i][1]))
                    else:
                        if((line[i][0] == '0') or (line[i][0] == '1') or (line[i][0] =='2')):
                            self.Matrix[count - 12][i].setState(int(line[i][0]))
                        else:
                            self.Matrix[count - 12][i].setState(line[i][0])
                            self.Matrix[count - 12][i].setHighway(int(line[i][1]))
        self.path.add((self.startRow , self.startColumn))
        self.path.add((self.endRow, self.endColumn))
        f.close()
Example #31
0
    def _buildSparseSystem(self, xyPoints):
        """
        Build sparse matrix system
        @param xyPoints list of unique (x, y) tuples, ordered counterclockwise
        @return ellipt2d objects in a dictionary
        """
    
        grid, bcs = self._triangulatePoints(xyPoints)
        #grid.plot()
        numPoints = len(xyPoints)
    
        # Laplace equation solver
        eq = ellipt2d.ellipt2d(grid, '1.0', '0.0', '0.0')
        amat, bvec = eq.stiffnessMat()
    
        #
        # rho field
        #
    
        rhoMat = copy.deepcopy(amat)
        rhoBVec = copy.deepcopy(bvec)
    
        bcData = {}
        for i, g in grid.data.items():
            if g[2]:
                # boundary
                #print 'x, y = {} rho Dirichlet BC is {}'.format(grid[i][0], bcs[i][0])
                bcData[i] = bcs[i][0]
        bc = DirichletBound.DirichletBound(bcData)
        # modify the matrix and source vector
        eq.dirichletB(bc, rhoMat, rhoBVec)
    
        #
        # theta field
        #
    
        theMat = copy.deepcopy(amat)
        theBVec = copy.deepcopy(bvec)
    
        bcData = {}
        for i, g in grid.data.items():
            if g[2]:
                # boundary
                #print 'x, y = {} theta Dirichlet BC is {}'.format(grid[i][0], bcs[i][1])
                bcData[i] = bcs[i][1]
        bc = DirichletBound.DirichletBound(bcData)
        eq.dirichletB(bc, theMat, theBVec)

        return {'eq': eq, 'grid': grid, 'cells': cell.cell(grid),
            'rhoMat': rhoMat, 'rhoBVec': rhoBVec,
            'theMat': theMat, 'theBVec': theBVec}
Example #32
0
	def test_remove(self):
		c = cell.cell()
		c.set_extent(0, -1, 1)
		c.set_extent(3, -1, 1)
		g = ndgrid.ndgrid(c)
		g.split(c, 0)
		for c in g.get_cells():
			g.split(c, 3)
		g.remove(g.get_cells()[0])
		self.assertEqual(len(g.get_cells()), 3)
		nr_neighbors = []
		for c in g.get_cells():
			nr_neighbors.append(len(list(g.get_neighbors(c))))
		nr_neighbors.sort()
		self.assertEqual(nr_neighbors, [1, 1, 2])
Example #33
0
    def __init__(self, rows, columns, width, height, margin):
        #Return a grid object with initial values.

        self.Matrix = []
        for row in range(rows):
            # Add an empty array that will hold each cell in this row
            self.Matrix.append([])
            for column in range(columns):
                # Append a cell
                self.Matrix[row].append(cell.cell(row, column))

        self.rows = rows
        self.columns = columns
        self.width = width
        self.height = height
        self.margin = margin
Example #34
0
    def draw(self, rho, the, xyPath=[]):

        border_x, border_y = 0.2, 0.2
        scale = min((1.-border_x)*self.width/(self.xmax-self.xmin), \
                    (1.-border_y)*self.height/(self.ymax-self.ymin))
        a = max(border_x * self.width / 2.,
                (self.width - scale * (self.xmax - self.xmin)) / 2.)
        b = max(border_y * self.height / 2.,
                (self.height - scale * (self.ymax - self.ymin)) / 2.)

        box_pix = (a, self.height - scale * (self.ymax - self.ymin) - b,
                   scale * (self.xmax - self.xmin) + a, self.height - b)
        # draw the box
        self.addBox((self.xmin, self.ymin, self.xmax, self.ymax), box_pix)

        # color plot
        cells = cell.cell(self.grid)
        for index in range(len(cells.data)):
            ia, ib, ic = cells.data[index]
            xa, ya = scale*(self.grid.x(ia)-self.xmin) + a, \
                     self.height -scale*(self.grid.y(ia)-self.ymin) - b
            xb, yb = scale*(self.grid.x(ib)-self.xmin) + a, \
                     self.height -scale*(self.grid.y(ib)-self.ymin) - b
            xc, yc = scale*(self.grid.x(ic)-self.xmin) + a, \
                     self.height -scale*(self.grid.y(ic)-self.ymin) - b

            rhoAbc = (rho[ia] + rho[ib] + rho[ic]) / 3.0
            theAbc = (the[ia] + the[ib] + the[ic]) / 3.0
            color = colormap(rhoAbc, theAbc)
            self.canvas.create_polygon(xa, ya, xb, yb, xc, yc, fill=color)

        # add path if present
        index = 0
        for (x, y) in xyPath:
            xa, ya = scale*(x - self.xmin) + a, \
                self.height -scale*(y - self.ymin) - b
            self.canvas.create_oval(xa - 5, ya - 5, xa + 5, ya + 5)
            #self.canvas.create_text(xa+2, ya+1, text=str(index))
            index += 1

        # add title
        x, y = self.width / 3., self.height / 15.0
        self.canvas.create_text(x,
                                y,
                                text=str(self.title),
                                font=("Helvetica", 24),
                                fill='black')
Example #35
0
    def __init__(self,size,width,height,margin):
        """
        Return a grid object with initial values.
        """ 
        
        self.Matrix = []
        for row in range(size):
            # Add an empty array that will hold each cell
            # in this row
            self.Matrix.append([])
            for column in range(size):
                self.Matrix[row].append(cell.cell(row,column))  # Append a cell

        self.size = size
        self.width=width
        self.height=height
        self.margin=margin
Example #36
0
	def test_split2(self):
		dim = 123
		g = ndgrid.ndgrid(cell.cell())
		for c in g.get_cells():
			g.split(c, dim)
		self.assertEqual(len(g.get_cells()), 2)
		for c in g.get_cells():
			g.split(c, dim)
		cells = g.get_cells()
		self.assertEqual(len(cells), 4)

		for c in cells:
			self.assertIn(dim, c.volume)
			self.assertNotIn(0, c.volume)
			self.assertTrue(len(list(g.get_neighbors(c))) <= 2)
			self.assertTrue(c.get_extent(dim)[0] < +1)
			self.assertTrue(c.get_extent(dim)[1] > -1)
Example #37
0
    def draw(self, rho, the, xyPath=[]):
        
        border_x, border_y = 0.2, 0.2
        scale = min((1.-border_x)*self.width/(self.xmax-self.xmin), \
                    (1.-border_y)*self.height/(self.ymax-self.ymin))
        a = max(border_x * self.width/2., (self.width-scale*(self.xmax-self.xmin))/2.)
        b = max(border_y * self.height/2.,(self.height-scale*(self.ymax-self.ymin))/2.)
    
        box_pix = (a, self.height-scale*(self.ymax-self.ymin) - b,
                   scale*(self.xmax-self.xmin) + a, self.height - b)
        # draw the box
        self.addBox((self.xmin, self.ymin, self.xmax, self.ymax), box_pix)
    
        # color plot
        cells = cell.cell(self.grid)
        for index in range(len(cells.data)):
                ia, ib, ic = cells.data[index]
                xa, ya = scale*(self.grid.x(ia)-self.xmin) + a, \
                         self.height -scale*(self.grid.y(ia)-self.ymin) - b
                xb, yb = scale*(self.grid.x(ib)-self.xmin) + a, \
                         self.height -scale*(self.grid.y(ib)-self.ymin) - b
                xc, yc = scale*(self.grid.x(ic)-self.xmin) + a, \
                         self.height -scale*(self.grid.y(ic)-self.ymin) - b

                rhoAbc = (rho[ia] + rho[ib] + rho[ic])/3.0
                theAbc = (the[ia] + the[ib] + the[ic])/3.0
                color = colormap(rhoAbc, theAbc)
                self.canvas.create_polygon(xa, ya, xb, yb, xc, yc, fill=color)
        
        # add path if present
        index = 0
        for (x, y) in xyPath:
            xa, ya = scale*(x - self.xmin) + a, \
                self.height -scale*(y - self.ymin) - b
            self.canvas.create_oval(xa-5, ya-5,
                                    xa+5, ya+5)
            #self.canvas.create_text(xa+2, ya+1, text=str(index))
            index += 1
    
        # add title
        x, y = self.width/3., self.height/15.0
        self.canvas.create_text(x, y, text=str(self.title),
                                font =("Helvetica", 24),
                                fill='black')
Example #38
0
def initialize_cells(width,length, perc):
	# how do you want to initialize the state of the cell?
	area=[[cell.cell((x,y), random_state(perc)) for x in range(width)] for y in range(length)]
	return area
Example #39
0
	def create_cells(self):
		for x in range(self.gridsize['x']):
			for y in range(self.gridsize['y']):
				self.cells[(x,y)] = cell((x,y), self.shape)
Example #40
0
#101x101 Map
s = 'Map1'

#5x5 Map
#s = '5x5Map'

#10x10 Map
#s = '10x10Map'

f = open(s, 'rb+')
g = pickle.load(f)
f.close() 

# For 101x101
start = cell.cell(10,4)
goal = cell.cell(75,90)

#For 5x5 
#start = cell.cell(0,1)
#goal = cell.cell(0,4)

#For 10x10
#start = cell.cell(6,4)
#goal = cell.cell(2,7)


t0 = time.time()
path=[]

#Forward A Star
Example #41
0
def request():
	cell.cell(0, 1, 1)
Example #42
0
def request():
	print cell.cell(0, 1, 1)