Пример #1
0
signalNum = 2
r = 1
destinationNum = 12

#flow distribution
flow = Pd.ClassPdist(5, 15, totalNum)

# Initialize the CA model map
line = readfile.readline()
CAMap = [[] for i in range(xLength)]
for i in range(xLength):
    line = readfile.readline()
    #print line
    stateList = line.split(",")
    for j in range(yLength):
        CAMap[i].append(CE.Cell(i, j, int(stateList[j])))
#draw the map with more details: walking zones, no walking zones, signals(crosswalk), stadium exits
#Exits of stadiums
stadExits = []
exitLocation = [[609, 426, 609, 440], [591, 400, 591,
                                       414], [344, 416, 358, 416],
                [212, 416, 226, 416], [153, 446, 153,
                                       460], [103, 468, 103, 482],
                [103, 630, 103, 644], [110, 811, 124, 811],
                [444, 811, 458, 811], [689, 797, 689, 811]]
for i in range(stadiumExitNum):
    e = StadiumExit.StadiumExit(exitLocation[i][0], exitLocation[i][1],
                                exitLocation[i][2], exitLocation[i][3], i + 1,
                                flow)
    stadExits.append(e)
    # crosswalk signals
Пример #2
0
def makePOSCAR(header, a0, dest):
    """ Creates updated POSCAR with new lattice parameter """
    cell = Cell().loadFromPOSCAR('POSCAR')
    cell.setHeader(header)
    cell.setA0(a0)
    cell.sendToPOSCAR('%s/POSCAR' % dest)
Пример #3
0

def copy_without(dic, key):
    dic2 = {}
    for key_loop in dic.keys():
        if key_loop != key:
            dic2[key_loop] = dic[key_loop]

    return dic2


def transform_keys_to_list(dic):
    l = []
    for key in dic.keys():
        l += [key]
    return l


MAZE1 = Maze([[Cell(0, 0, True, False),
               Cell(1, 0, True, True)],
              [Cell(0, 1, False, True),
               Cell(1, 1, True, True)]])

MAZE2 = Maze([[
    Cell(0, 0, False, False),
    Cell(1, 0, False, False),
    Cell(2, 0, True, True)
], [Cell(0, 1, False, True),
    Cell(1, 1, True, True),
    Cell(2, 1, True, True)]])
Пример #4
0
 def __init__(self, size: int):
     self.size = size
     self.board = [[Cell.Cell(x, y) for x in range(size)]
                   for y in range(size)]
     self.flat_board = [item for row in self.board for item in row]
Пример #5
0

# ============================================================================
#  Main Program
# ============================================================================
print '\nAdd POSCAR, POTCAR and KPOINTS files to working directory.\n'

# Get user inputs
system = raw_input('System name: ')
print system, '\n'

# VASP Settings
ENCUT = 450
PREC = 'Accurate'
NPAR = 4
cell = Cell().loadFromPOSCAR('POSCAR')
nAtoms = sum(cell.elementCounts)
print '%d atoms detected' % nAtoms
if nAtoms > 20:
    LREAL = 'Auto'
else:
    LREAL = '.FALSE.'
print 'Using LREAL = %s' % LREAL, '\n'

# Get strains from user
perc = raw_input('Maximum percent strain (default 5): ')
if perc:
    perc = float(perc)
else:
    perc = 5.0
print str(perc) + ' %', '\n'
Пример #6
0
from Cell import *

if __name__ == "__main__":
    # Initial statement
    neighbor_array = [0, 0, 0, 0, 0, 0, 0, 0]
    is_alive = 1
    cell = Cell(neighbor_array, is_alive)
    print cell
Пример #7
0
import pygame as pg
import math
from settings import *
from Cell import *
pg.init()

for j in range(rows):
    for i in range(cols):
        c = Cell(i, j)
        grid.append(c)

current = grid[0]

running = True

clock = pg.time.Clock()

while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False

    clock.tick(fps)
    screen.fill(BLACK)
    for i in grid:
        i.show()
    current.visited = True
    current.head()
    next = current.checkSides()
    if next:
        next.visited = True
Пример #8
0
import time

import GameFinish
import HC
import sys
import Cell
import random

# Hardcoded information
DEBUG_MODE = True
BOARD_SIZE = 6

# Global variables
initial_cell = Cell.Cell(0, 0)
board = []
mines_left = round(BOARD_SIZE * BOARD_SIZE / 5)
total_mines = mines_left


def main(cell):

    # Init the board itself
    init_board()

    # Set the mines on the board
    init_mines()

    # Get the user's command.
    try:

        while not is_board_solved():
Пример #9
0
from Piece import *
from Cell import *
from Pawn import *
from Rook import *
from Bishop import *
from Knight import *
from Queen import *
from King import *

cells = []
pieces = [Rook, Bishop, Knight, Queen, King, Knight, Bishop, Rook]
for i in range(8):
    cells.append(Cell(i + 1, 2, Pawn))  # initializing white pawns at 2nd rank
    cells.append(Cell(i + 1, 7, Pawn))  # initializing black pawns at 7th rank
    cells.append(Cell(i + 1, 1, pieces[i]))  # initializing white pieces at 1st rank
    cells.append(Cell(i + 1, 8, pieces[i]))  # initializing black pieces at 7th rank
Пример #10
0
 def _notSolvedArrayInit(self):
     self._notSolvedIndex = []
     for r in range(len(self._array)):
         for c in range(len(self._array[r])):
             if not self._array[r][c]:
                 self._cells.append(Cell(r, c))
Пример #11
0
    def detailed_transformation_analysis(self):
        problem_helper = ProblemHelper()
        problem_figures = problem_helper.get_problem_figures(self.problem)
        solution_figures = problem_helper.get_solution_figures(self.problem)

        ATTRIBUTES = [
            'black_white_ratio', 'min_black_distance_l',
            'min_black_distance_r', 'min_black_distance_t',
            'min_black_distance_b', 'max_black_distance_l',
            'max_black_distance_r', 'max_black_distance_t',
            'max_black_distance_b', 'avg_black_distance_l',
            'avg_black_distance_r', 'avg_black_distance_t',
            'avg_black_distance_b'
        ]

        # Instantiate A,B,C cells with their images
        problem_cells = {}
        for figure in problem_figures:
            if "A.png" in figure.visualFilename:
                problem_cells['a'] = Cell(Image.open(figure.visualFilename))
            elif "B.png" in figure.visualFilename:
                problem_cells['b'] = Cell(Image.open(figure.visualFilename))
            elif "C.png" in figure.visualFilename:
                problem_cells['c'] = Cell(Image.open(figure.visualFilename))

        # Instantiate 1-6 cells with their images
        solution_cells = {}
        for figure in solution_figures:
            if "1.png" in figure.visualFilename:
                solution_cells['1'] = Cell(Image.open(figure.visualFilename))
            elif "2.png" in figure.visualFilename:
                solution_cells['2'] = Cell(Image.open(figure.visualFilename))
            elif "3.png" in figure.visualFilename:
                solution_cells['3'] = Cell(Image.open(figure.visualFilename))
            elif "4.png" in figure.visualFilename:
                solution_cells['4'] = Cell(Image.open(figure.visualFilename))
            elif "5.png" in figure.visualFilename:
                solution_cells['5'] = Cell(Image.open(figure.visualFilename))
            elif "6.png" in figure.visualFilename:
                solution_cells['6'] = Cell(Image.open(figure.visualFilename))

        # Generate an image analysis for each problem cell
        for _, problem_cell in problem_cells.items():
            problem_cell.generate_cell_analysis()

        # Generate an image analysis for each solution cell
        for _, solution_cell in solution_cells.items():
            solution_cell.generate_cell_analysis()

        # Find ABC, AB, AC transformations where attributes remain close to the same
        transformation_patterns = self.analyze_transformation_patterns(
            problem_cells, ATTRIBUTES)
        abc_pattern = transformation_patterns['abc']
        ab_pattern = transformation_patterns['ab']
        ac_pattern = transformation_patterns['ac']

        # If any ABC attribute or AB, AC transormation attribute remains exactly
        # the same, that attributes value should be expected in the solution.
        # Remove possible solutions cells that do not match these patterns.
        unsifted_cells = dict(solution_cells)
        sifted_solution_cells = self.sift_solution_cells(
            unsifted_cells, abc_pattern)  # Sift for ABC pattern
        sifted_solution_cells = self.sift_solution_cells(
            sifted_solution_cells, ab_pattern)  # Sift for AB pattern
        sifted_solution_cells = self.sift_solution_cells(
            sifted_solution_cells, ac_pattern)  # Sift for AC pattern
        if not sifted_solution_cells:
            sifted_solution_cells = solution_cells

        # Generate analyses for AB, AC transformations
        ab_transformation_analysis = problem_cells[
            'a'].generate_cell_transformation_analysis(problem_cells['b'])
        ac_transformation_analysis = problem_cells[
            'a'].generate_cell_transformation_analysis(problem_cells['b'])

        # Predict the attributes of D that AD, BD, CD transformations will
        # produce based on the observed AB, AC transformations
        ab_ac_transform_applied_to_a = problem_cells[
            'a'].predict_transformed_attrs(ab_transformation_analysis,
                                           ac_transformation_analysis)
        ac_transform_applied_to_b = problem_cells[
            'b'].predict_transformed_attrs(ac_transformation_analysis)
        ab_transform_applied_to_c = problem_cells[
            'c'].predict_transformed_attrs(ab_transformation_analysis)

        d_expected_attributes = {}
        for attr in ATTRIBUTES:
            total = ab_ac_transform_applied_to_a[
                attr] + ac_transform_applied_to_b[
                    attr] + ab_transform_applied_to_c[attr]
            average = total / 3
            d_expected_attributes[attr] = average

        # Generate similarity scores for each sifted solution compared to the
        # average expected attributes of D
        similarity_scores = {}
        for key, solution in sifted_solution_cells.items():
            solution_attrs = solution.get_attrs()
            similarity_score = self.generate_similarity_score(
                solution_attrs, d_expected_attributes)
            similarity_scores[key] = similarity_score

        # Choose the solution with the highest similarity score
        proposed_solution = int(
            max(similarity_scores, key=similarity_scores.get))
        similarity = similarity_scores[str(proposed_solution)]

        # If the combined similarity score is above the 95% threshold, then
        # return the number of the proposed solution cell, otherwise, if we
        # can sift out enough solutions, return the solution with the highest
        # similarity score, otherwise, return -1
        if proposed_solution and similarity > 0.95:
            return proposed_solution
        elif len(sifted_solution_cells) < 5:
            return proposed_solution
        else:
            return -1
Пример #12
0
def AStar2(world, DEBUG_MODE):  # start and goal are cells

    if(DEBUG_MODE == 1):
        print "running AStar2"

    start = world.getStart()
    goal = world.getGoal()
    if(DEBUG_MODE == 1):
        print goal.getCoord()

    frontier = []  # nodes
    visited = []  # nodes

    numberMoves = 0

    firstNode = Node(start, Cell(Coord(-1, -1), -1), [], 0, 0) # Last 0 is robot dir!

    frontier.append(firstNode)

    while len(frontier) is not 0:
        # HOPEFULLY ths sorts the list so that the least g+h is first
        frontier.sort(key=lambda node: node.total())
        # for node in frontier:
            # print node
        # after frontier is sorted the node with the lowest g+h becomes current

        current = frontier[0]
        # remove the node being looked at from the frontier
        del frontier[0]
        visited.append(current)  # add it to the visited list

        if(DEBUG_MODE == 1):
            print "------------------------------"
            print "len of frontier"
            print len(frontier)
            print "len of visited"
            print len(visited)
            
            print "current Coords"
            print current.getCell().getCoord()

        if(current.getCell().getIsGoal()):  # if its the goal, we are done
            if(DEBUG_MODE == 1):
                print "Goal Found!"
            return (visited, numberMoves)

        # print anydup(visited)
        # raw_input()

        if(DEBUG_MODE == 1):
            print "Building neighbors..."

        neighborCells = world.getNeighbors(current.getCell().getCoord())
        neighborNodes = cellsToNodes(current, neighborCells, current.getRobotDir(), False)
        bashCells = world.getBashNeighbors(current.getCell().getCoord())
        bashNodes = cellsToNodes(current, bashCells, current.getRobotDir(), True)
        moveNodes = list(neighborNodes + bashNodes)

        numberMoves += len(moveNodes)
        
        if(DEBUG_MODE == 1):
            print len(moveNodes)

        neibsRm = []
        frontRm = []
        for i in range(len(moveNodes)):
            neighborNode = moveNodes[i]
            for j in range(len(visited)):
                visitNode = visited[j]
                if neighborNode.getCell().getCoord() != visitNode.getCell().getCoord(): # I think This is where we are accidentally adding tons of things to visited
                    for f in range(len(frontier)):
                        frontNode = frontier[f]
                        if neighborNode.getCell().getCoord() == frontNode.getCell().getCoord():
                            if neighborNode.total() < frontNode.total():
                                frontRm.append(f)
                            else:
                                neibsRm.append(i)
                else:
                    neibsRm.append(i)

        removedFront = 0
        for rm in list(set(frontRm)):
            if(DEBUG_MODE == 1):
                print "FrontRM:",rm - removedFront
            del frontier[rm - removedFront]
            removedFront += 1

        removedNeibs = 0
        for rm in list(set(neibsRm)):
            if(DEBUG_MODE == 1):
                print "MovesRM:",rm - removedNeibs
            del moveNodes[rm - removedNeibs]
            removedNeibs += 1

        if(DEBUG_MODE == 1):
            print "len of moveNodes"
            print len(moveNodes)
        frontier += moveNodes


    if(DEBUG_MODE == 1):
        print "Goal not found!"
    return ([], numberMoves)
Пример #13
0
from Cell import *
import time
#from Grid import *

grid = [[
    Cell(0, 0),
    Cell(1, 0),
    Cell(2, 0),
    Cell(3, 1),
    Cell(4, 1),
    Cell(5, 1),
    Cell(6, 2),
    Cell(7, 2),
    Cell(8, 2)
],
        [
            Cell(9, 0),
            Cell(10, 0),
            Cell(11, 0),
            Cell(12, 1),
            Cell(13, 1),
            Cell(14, 1),
            Cell(15, 2),
            Cell(16, 2),
            Cell(17, 2)
        ],
        [
            Cell(18, 0),
            Cell(19, 0),
            Cell(20, 0),
            Cell(21, 1),
Пример #14
0
def AStar2(world):  # start and goal are cells
    print "running AStar2"

    start = world.getStart()
    goal = world.getGoal()
    print goal.getCoord()

    frontier = []  # nodes
    visited = []  # nodes

    firstNode = Node(start, Cell(Coord(-1, -1), -1), [], 0, 0) # Last 0 is robot dir!

    frontier.append(firstNode)

    while len(frontier) is not 0:
        # HOPEFULLY ths sorts the list so that the least g+h is first
        frontier.sort(key=lambda node: node.total())
        # for node in frontier:
            # print node
        # after frontier is sorted the node with the lowest g+h becomes current

        current = frontier[0]
        # remove the node being looked at from the frontier
        frontier.remove(current)
        visited.append(current)  # add it to the visited list

        print "------------------------------"
        print "len of frontier"
        print len(frontier)
        print "len of visited"
        print len(visited)
        
        print "current Coords"
        print current.getCell().getCoord()
        if(current.getCell().getIsGoal()):  # if its the goal, we are done
            visited.append(current)
            print "Goal Found!"
            return visited



        # print anydup(visited)
        # raw_input()

        print "Building neighbors..."
        neighborCells = world.getNeighbors(current.getCell().getCoord())
        neighborNodes = cellsToNodes(current, neighborCells, current.getRobotDir(), False)
        bashCells = world.getBashNeighbors(current.getCell().getCoord())
        bashNodes = cellsToNodes(current, bashCells, current.getRobotDir(), True)
        moveNodes = neighborNodes + bashNodes


        for moveNode in moveNodes: #for each possible move from the current cell
            for visitNode in visited: #see if that move would put us in a cell thats already been visited
                if moveNode.getCell().getCoord() is not visitNode.getCell().getCoord(): #if we've not visited this cell before
                    for frontNode in frontier: #ee if the move would put us in a cell that is already in the frontier
                        if moveNode.getCell().getCoord() is frontNode.getCell().getCoord(): # if it is
                            if moveNode.getCost() < frontNode.getCost(): # check if the new move is cheaper than the old move
                                frontier.remove(frontNode) # if it is, remove the old move from frontier
                                break
                            else: # otherwise, remove the new node from the list of nodes that will be added to frontier
                                # print "Removing: " + str(moveNode)
                                if moveNode in moveNodes:
                                    moveNodes.remove(moveNode)
                                break
                else: # if the node we are looking at would put us in a cell thats already been visited
                    #print "Removing: " + str(moveNode)
                    if moveNode in moveNodes:
                        moveNodes.remove(moveNode) # remove the new node  from the list of nodes to be added to the frontier

        print "len of moveNodes"
        print len(moveNodes)
        frontier += moveNodes


    print "Goal not found!"
Пример #15
0
 def new_cell(self, cellAttr):
     cellAttr["module"] = self
     # create new cell here
     cell = Cell.Cell(cellAttr)
     self.__cells[cell.name] = cell
     return cell
Пример #16
0
 def init_cells(self):
     return [[
         Cell(i * self.cell_size, j * self.cell_size,
              random.choice([True, False, False, False]), self.cell_size)
         for i in range(self.enviroment_width)
     ] for j in range(self.enviroment_height)]
Пример #17
0
 def __init__(self):
     self._cells = [[Cell() for i in range(7)] for j in range(7)]
 def make_maze(self):
     for x in range(self.maze_row):
         cells = []
         for y in range(self.maze_col):
             cells.append(Cell.Cell(Point(x, y)))
         self.maze_map.append(cells)
Пример #19
0
 def makeGrid(self):
     for i in range(20):
         row = [Cell(j, i) for j in range(20)]
         self._grid.append(row)
Пример #20
0
def solve_mine(gamemap, result):
    def map_to_list(field):
        field = field[1:]
        another_map = []
        line = []
        for element in field:
            if element == "\n":
                another_map.append(line)
                line = []
                continue
            if element != ' ':
                if element.isdigit():
                    line.append(int(element))
                else:
                    line.append(element)
        return another_map

    def check_boundary(x, y):
        return (-1 < x < len(cellmap)) and (-1 < y < len(cellmap[row]))

    def open(row, column):
        if result[row][column] == 'x':
            print(row, column)
            sys.exit('KABOOM!')
        return result[row][column]

    gamemap = map_to_list(gamemap)
    result = map_to_list(result)
    cellmap = list(gamemap)

    print('initial map')
    print("\n".join(" ".join(map(str, row)) for row in cellmap))

    for row in range(len(cellmap)):
        for column in range(len(cellmap[row])):
            cellmap[row][column] = Cell(cellmap[row][column], (row, column))

    # print('*********************************************************')

    for row in range(len(cellmap)):
        for column in range(len(cellmap[row])):
            if cellmap[row][column].weight == 0:
                for i in range(-1, 2):
                    for j in range(-1, 2):
                        x = row + i
                        y = column + j
                        if check_boundary(x, y):
                            cellmap[x][y].weight = open(x, y)
                            cellmap[x][y].is_open = True

    # print('*********************************************************')

    smth_changed = True

    while smth_changed:
        smth_changed = False
        groups = []
        for row in range(len(cellmap)):
            for column in range(len(cellmap[row])):
                if cellmap[row][column].is_open:
                    group = Group()
                    for i in range(-1, 2):
                        for j in range(-1, 2):
                            x = row + i
                            y = column + j
                            if check_boundary(
                                    x, y) and (cellmap[x][y].weight == '?'
                                               or cellmap[x][y].weight == 'x'):
                                group.cells.add(cellmap[x][y])
                                group.weight = cellmap[row][column].weight
                    if len(group.cells) > 0:
                        groups.append(group)

        repeat = True
        # print("********************begin of func********************")
        while repeat:
            repeat = False
            for current_group in groups:
                for compare_group in groups:
                    if current_group != compare_group:
                        if current_group.cells == compare_group.cells and current_group.weight == compare_group.weight:
                            # print("deleting", compare_group)
                            groups.remove(compare_group)
                            continue
                        if current_group.cells <= compare_group.cells:
                            compare_group.cells -= current_group.cells
                            compare_group.weight -= current_group.weight
                            repeat = True
                            continue
                        elif current_group.cells >= compare_group.cells:
                            current_group.cells -= compare_group.cells
                            current_group.weight -= compare_group.weight
                            repeat = True
                            continue
                        else:
                            if not current_group.cells.isdisjoint(
                                    compare_group.cells):
                                # print("MEETING", current_group, 'and', compare_group)
                                if current_group.weight > compare_group.weight:
                                    bigger = current_group
                                    smaller = compare_group
                                    # print('bigger is', bigger)
                                else:
                                    bigger = compare_group
                                    smaller = current_group
                                    # print('bigger is', bigger)
                                group = Group()
                                group.cells = current_group.cells.intersection(
                                    compare_group.cells)
                                # print ('New group cells is', group.cells)
                                group.weight = bigger.weight - (
                                    len(bigger.cells) - len(group.cells))
                                # print('New group weight is', group.weight)
                                if group.weight == smaller.weight:
                                    groups.append(group)
                                    bigger.cells -= group.cells
                                    bigger.weight -= group.weight
                                    smaller.cells -= group.cells
                                    smaller.weight -= group.weight
                                    # print('saving', bigger, smaller, group)
                                    repeat = True
        # print("***********************end of func************************")
        for group in groups:
            if group.weight == len(group.cells):
                for cell in group.cells:
                    row = cell.pos[0]
                    column = cell.pos[1]
                    cellmap[row][column].is_mine = True
                    cellmap[row][column].weight = 'x'
            if group.weight == 0:
                for cell in group.cells:
                    row = cell.pos[0]
                    column = cell.pos[1]
                    cellmap[row][column].weight = open(row, column)
                    cellmap[row][column].is_open = True
                    smth_changed = True

        # print('*********************************************************')
        #
        # for row in cellmap:
        #     print(row)
        # print('*********************************************************')

    for row in range(len(cellmap)):
        for column in range(len(cellmap[row])):
            if cellmap[row][column].weight == '?':
                print("solved")
                return ("?")
    print("solved")
    return "\n".join(" ".join(map(str, row)) for row in cellmap)