def create_square_grid(dim, springconstant_normal, springconstant_deviation, strain_normal, strain_deviation): """ Creates a square grid using the given size and values applicable for the springs. :param dim: The size of the grid :param springconstant_normal: The normal of the springconstant. :param springconstant_deviation: The deviation of the springconstant on this normal. :param strain_normal: The normal of the strain. :param strain_deviation: The deviation of the strain on this normal. :return: """ start_lambda = 1 points_grid = create_points(dim) springs = link_points(dim, springconstant_normal, springconstant_deviation, strain_normal, strain_deviation, points_grid) points = list() for h in range(1, len(points_grid)-1): for w in range(1, len(points_grid[h])-1): points.append(points_grid[h][w]) edge_points = list() for h in range(1, len(points_grid)-1): edge_points.append(points_grid[h][0]) edge_points.append(points_grid[h][-1]) for w in range(1, len(points_grid[0])-1): edge_points.append(points_grid[0][w]) edge_points.append(points_grid[-1][w]) return Grid(start_lambda, points, edge_points, springs)
def create_hex_point_grid(dim, springconstant_normal, springconstant_deviation, strain_normal, strain_deviation): """ Initialize a hexagonal grid according to the provided parameters. :param dim: Number of points in width and height :param springconstant_normal: Normal of spring constant :param springconstant_deviation: Deviation from spring constant :param strain_normal: Spring strain normal :param strain_deviation: Spring strain deviation :return: A hexagonal grid """ start_lambda = 1 points_grid = create_points(dim) springs = link_points(dim, springconstant_normal, springconstant_deviation, strain_normal, strain_deviation, points_grid) points = [] for h in range(1, len(points_grid) - 1): points += [ points_grid[h][w] for w in range(1, len(points_grid[h]) - 1) ] edge_points = points_grid[0] + points_grid[-1] + [ points_grid[h][w] for h in range(1, len(points_grid) - 1) for w in [0, -1] ] return Grid(start_lambda, points, edge_points, springs)
def main(file=None): if file is None: with open("data_file.json", "r") as read_file: data = json.load(read_file) else: try: with open(file, "r") as read_file: data = json.load(read_file) except: print("Cannot open json file") return -1 try: gd = GlobalData(data['H'], data['W'], data['nH'], data['nW']) grid = Grid(gd) result = simulate_heat_transfer(grid, data['initial_temp'], data['simulation_time'], data['simulation_step_time'], data['ambient_temp'], data['alpha'], data['specific_heat'], data['conductivity'], data['density']) with open("result.txt", "w") as write_file: for nr, temp in enumerate(result): if nr % int(data['nH']) == 0: write_file.write("\n") write_file.write(str(temp) + ";") write_file.close() except: print("Wrong json file") return -1
def create_try_grid(dim, springconstant_normal, springconstant_deviation, strain_normal, strain_deviation): points_grid = create_points_try(dim) springs = link_points(dim, points_grid, springconstant_normal, springconstant_deviation, strain_normal, strain_deviation) points = list() for h in range(1, len(points_grid) - 1): for w in range(1, len(points_grid[h]) - 1): points.append(points_grid[h][w]) edge_points = list() for h in range(1, len(points_grid) - 1): edge_points.append(points_grid[h][0]) edge_points.append(points_grid[h][-1]) for w in range(1, len(points_grid[0]) - 1, 2): edge_points.append(points_grid[0][w]) if dim % 2 == 0: edge_points.append(points_grid[-1][w]) else: if not w == dim - 2: edge_points.append(points_grid[-1][w + 1]) return Grid(1, points, edge_points, springs)
def decrease_lambda(grid, decrement_step_size): """ Creates a copy of the given grid and for this decreases the lambda value by the decrement_step_size. :param grid: The given grid. :param decrement_step_size: The amount lambda has to be decreased. :return: A copy of the given grid, where the lambda value is decreased. """ lambda_val = grid.lambda_val - decrement_step_size decreased_grid = Grid(lambda_val, list(), list(), list()) for edge_point in grid.edge_points: new_edge_point = Point(edge_point.position) edge_point.add_next_point(new_edge_point) decreased_grid.edge_points.append(new_edge_point) for point in grid.points: new_point = Point(point.position) point.add_next_point(new_point) decreased_grid.points.append(new_point) decreased_grid.springs = reconnect_grid(grid) return decreased_grid
def relax_grid(grid, mu, move_factor): """ Relaxes a given grid by relaxing each individual point and then reconnect them using the reconnect_grid. This function creates a new grid, so that the old one is preserved for visualization. :param grid: The given grid that has to be relaxed. :param mu: The force threshold for movement :param move_factor: The amount the point is allowed to move. :return: """ lambda_val = grid.lambda_val relaxed_grid = Grid(lambda_val, list(), list(), list()) for edge_point in grid.edge_points: new_edge_point = Point(edge_point.position) edge_point.add_next_point(new_edge_point) relaxed_grid.edge_points.append(new_edge_point) for point in grid.points: relaxed_grid.points.append( relax_point(point, lambda_val, mu, move_factor)) relaxed_grid.springs = reconnect_grid(grid) return relaxed_grid
[4, 5, 2, 1, 9, 7, 6, 8, 3], [8, 3, 5, 2, 1, 9, 7, 6, 4], [2, 6, 1, 7, 3, 4, 5, 9, 8], [9, 7, 4, 6, 8, 5, 1, 3, 0]] # setup window pygame.display.set_caption("Sudoku") WIN_DIMENSIONS = (650, 480) WIN_COLOUR = (255, 255, 255) win = pygame.display.set_mode(WIN_DIMENSIONS) win.fill(WIN_COLOUR) # setup grid GRID_WIDTH = 425 GRID_POS = (25, 25) grid = Grid(GRID_POS, GRID_WIDTH, 'easy', win) grid.draw('default') # setup button BUTTON_START_X = 475 BUTTON_START_Y = 120 LARGE_WIDTH = 129 LARGE_HEIGHT = 50 LARGE_FONT = 28 SMALL_WIDTH = 40 SMALL_HEIGHT = 25 SMALL_FONT = 18 GAP = 8 newGameButton = Button((BUTTON_START_X, BUTTON_START_Y), LARGE_WIDTH, LARGE_HEIGHT, LARGE_FONT, "New Game", GRID_WIDTH, win) easyButton = Button((BUTTON_START_X, BUTTON_START_Y + LARGE_HEIGHT),
from classes import Grid grille = Grid("../Grids/Probs/example.grid") s = grille.getSolution() f = open("../Outputs/test1.svg", "w") f.write(grille.writeSvgs(s)) f.close() grille = Grid("../Grids/Probs/example.grid") s = grille.getSolution() f = open("../Outputs/test2.svg", "w") grille.writeSvg(f, s) f.close()
from classes import Grid grille = Grid("../Grids/Probs/grid1x2_multiple_answer.grid") print("Grille : \n"+grille.getGrid(),"\n") print("\nSingle solution :") print(grille.getSolution()) print("\nAll solutions :") print("\n".join(str(s) for s in grille.getAllSolutions())) print("\nAll solutions by getNextSolution :") s = "" while s != None: # I miss do...while loops, why aren't they in python...? s = grille.getNextSolution() print(s) print("\nAll solutions using next :") try: while True: s = next(grille) print(s) except Exception as e: print("-> Ended") print("\nAll solutions by for loop :") for s in (grille): print(s)
def start_scanning(self): self.sessionStart=datetime.now() logger=self.logger # Make a grid of scannable boxes grid=Grid(self.bounds, self, self.GUI) self.boxesN = len(grid.boxes) self.boxesNinit = len(grid.boxes) print("Number of boxes to scan(initially): ", self.boxesN) # Scan each box toScan=list(grid.boxes) boxScanStart = None isFirstScan = True while(toScan): box=toScan[0] self.GUI.remove_box(box) self.GUI.add_box(box, 'yellow') # Timing interval between last box scan if isFirstScan: boxScanStart = datetime.now() isFirstScan = False else: boxScanPrev = copy.deepcopy(boxScanStart) boxScanStart = datetime.now() tdelta = boxScanStart - boxScanPrev secs = tdelta.total_seconds() if (secs > self.maxTimeInterval): self.maxTimeInterval = secs if (self.minTimeInterval=='INF' or secs < self.minTimeInterval): self.minTimeInterval = secs self.sumIntervalsSecs+=secs waitTime = self.config['scheduler']['NEXT_SEARCH_WAIT'] sleep(waitTime) # Scan box markers = self.service.search(box, logger) # Update costs after scan self.requestsTotal +=1 self.costTotal += self.config['service']['request']['COST_PER_REQUEST'] logger.update_session() # Max cost reached max_cost_day = self.config['service']['request']['MAX_COST_DAY'] if max_cost_day!='INF' and self.costTotal > max_cost_day: print("max cost per day reached") # Autosplit max_results = self.config['service']['response']['MAX_RESULTS'] if self.config['box']['AUTOSPLIT'] and max_results!='INF' and\ len(markers) >= max_results: logger.log_scan("Response had max possible results. Autosplitting..") boxes=grid.splitBoxIn4(box) self.boxesN-=1 toScan.pop(0) self.boxesN+=4 toScan.insert(0, boxes[0]) toScan.insert(1, boxes[1]) toScan.insert(2, boxes[2]) toScan.insert(3, boxes[3]) continue # Add markers on map for marker in markers: if (len(marker)>=2): self.GUI.add_marker(marker[0], marker[1]) self.resultsTotal+=1 # Remove finished box self.GUI.remove_box(box) self.GUI.add_box(box, 'green') toScan.pop(0) # Finish self.sessionEnd=datetime.now() logger.update_session() print("Scanning finished.") print("Press CTRL+C to stop application.")
from classes import Grid, Direction grille = Grid("../Grids/Probs/grid1.grid") print("Grille : \n" + grille.getGrid(), "\n") print("Groupes : \n" + "\n".join(", ".join( str(grille.getGroup(x, y)) for x in range(grille.l())) for y in range(grille.h() - 1, -1, -1)))
from classes import Grid #assuming you are in /Tests # Case where the arg is a path gridN1 = Grid("../Grids/Probs/grid1.grid") # Case where the arg is a file with open("../Grids/Probs/example.grid") as f: gridN2 = Grid(f) # Case where the arg is a string with open("../Grids/Probs/grid4x5N.grid") as f: txt = f.read() gridN3 = Grid(txt) # Case where the arg is a list with open("../Grids/Probs/bigGrid.grid") as f: txt = f.read().split("\n") gridN4 = Grid(txt) print("grid number 1 : ") print(gridN1.getGrid()) # print the grid in grid1 format print("grid number 2 : ") print(gridN2.getGrid()) # print the grid in grid1 format print("grid number 3 : ") print(gridN3.getGrid()) # print the grid in grid1 format print("grid number 4 : ") print(gridN4.getGrid()) # print the grid in grid1 format from classes import CNF a = CNF() print(a) print(CNF(("x", "y", "z"), ("-x", "-y", "z"))) # -> CNF{Cl['x', 'y', 'z'], Cl['-x', '-y', 'z']}
ascii_dict = {35: "█", 46: " ", 10: "\n", 94: "^"} # Get grid map = "" def output_func(val): global map map += ascii_dict[val] computer = IntcodeComputer(intcode, input, output_func) computer.run() grid = Grid([list(row) for row in map[:-2].split("\n")]) # Get bot pos bot = Bot() for y, row in enumerate(grid): for x, v in enumerate(row): if v == "^": bot.pos = np.array((x, y)) # Get bot path bot_path = [] new_dir = None while new_dir != "END": grid[bot.pos] = "B"
from classes import Grid grille = Grid("../Grids/Probs/example.grid") print(grille.getGrid()) cnf = grille.getTilesNbCNF() print(cnf)
import pygame import os import random import math import time from classes import GameWindow, BackGroundMusic, Block, GameStats, Grid, CollapsedBlocks gameWindow = GameWindow() clock = pygame.time.Clock() window = gameWindow.setMode() gameWindow.setCaption("Tetris - Aditya Chaturvedi") # collapsedBlocks = renderBlocksForTesting(window) backGroundMusic = BackGroundMusic() backGroundMusic.playRandomMusic() gameStats = GameStats() grid = Grid() blocksOnScreen = [] collapsedBlocks = CollapsedBlocks() possibleBlockShapes = ["cube-block", "i", "j", "L", "rs", "s", "t"] def renderBlocksForTesting(window): global collapsedBlocks cubeBlock = Block() jBlock = Block() lBlock = Block() cubeBlock.shape = cubeBlock.gameWindow.loadImage("cube-block.png") cubeBlock.blockShape = "cube" cubeBlock.row = 21 cubeBlock.column = 2 cubeBlock.isFalling = False
from classes import Grid, Direction (NORD, SUD, EST, OUEST) = (Direction.NORD, Direction.SUD, Direction.EST, Direction.OUEST) grille = Grid("../Grids/Probs/grid1.grid") print("Grille : \n", grille.getGrid(),"\n") print("NORD de chaque case : ") for i in range(5,-1,-1): print([grille.getBarrier(x,i,NORD) for x in range(6)]) print("SUD de chaque case : ") for i in range(5,-1,-1): print([grille.getBarrier(x,i,SUD) for x in range(6)]) print("EST de chaque case : ") for i in range(5,-1,-1): print([grille.getBarrier(x,i,EST) for x in range(6)]) print("OUEST de chaque case : ") for i in range(5,-1,-1): print([grille.getBarrier(x,i,OUEST) for x in range(6)])
def start_scanning(self): self.sessionStart = datetime.now() logger = self.logger # Make a grid of scannable boxes grid = Grid(self.bounds, self, self.GUI) self.boxesN = len(grid.boxes) self.boxesNinit = len(grid.boxes) print("Number of boxes to scan(initially): ", self.boxesN) # Scan each box toScan = list(grid.boxes) boxScanStart = None isFirstScan = True while (toScan): box = toScan[0] self.GUI.remove_box(box) self.GUI.add_box(box, 'yellow') # Timing interval between last box scan if isFirstScan: boxScanStart = datetime.now() isFirstScan = False else: boxScanPrev = copy.deepcopy(boxScanStart) boxScanStart = datetime.now() tdelta = boxScanStart - boxScanPrev secs = tdelta.total_seconds() if (secs > self.maxTimeInterval): self.maxTimeInterval = secs if (self.minTimeInterval == 'INF' or secs < self.minTimeInterval): self.minTimeInterval = secs self.sumIntervalsSecs += secs waitTime = self.config['scheduler']['NEXT_SEARCH_WAIT'] sleep(waitTime) # Scan box markers = self.service.search(box, logger) # Update costs after scan self.requestsTotal += 1 self.costTotal += self.config['service']['request'][ 'COST_PER_REQUEST'] logger.update_session() # Max cost reached max_cost_day = self.config['service']['request']['MAX_COST_DAY'] if max_cost_day != 'INF' and self.costTotal > max_cost_day: print("max cost per day reached") # Autosplit max_results = self.config['service']['response']['MAX_RESULTS'] if self.config['box']['AUTOSPLIT'] and max_results!='INF' and\ len(markers) >= max_results: logger.log_scan( "Response had max possible results. Autosplitting..") boxes = grid.splitBoxIn4(box) self.boxesN -= 1 toScan.pop(0) self.boxesN += 4 toScan.insert(0, boxes[0]) toScan.insert(1, boxes[1]) toScan.insert(2, boxes[2]) toScan.insert(3, boxes[3]) continue # Add markers on map for marker in markers: if (len(marker) >= 2): self.GUI.add_marker(marker[0], marker[1]) self.resultsTotal += 1 # Remove finished box self.GUI.remove_box(box) self.GUI.add_box(box, 'green') toScan.pop(0) # Finish self.sessionEnd = datetime.now() logger.update_session() print("Scanning finished.") print("Press CTRL+C to stop application.")
from classes import Grid grille = Grid("../Grids/Probs/example.grid") cnf = grille.getWaterPhys() n = 0 for clause in cnf: n += 1 print(clause, end = ", ") if n == 4: n = 0 print() print() print(grille.getGrid())