def simulate_heat_transfer(grid: Grid, univ_elem: UniversalElement, initial_temp: float, simulation_time: float, step_time: float, layer_info: list, boundaries_info: dict, **kwargs): # vector t0 nodes_temp = np.array([[initial_temp for _ in range(grid.get_spec().mN)]]).reshape( (grid.get_spec().mN, 1)) steps = (int)(simulation_time / step_time) # list to store simulation time in every step steps_times = ((step + 1) * step_time for step in range(steps)) global_h = calculate_h_global(grid, univ_elem, layer_info, boundaries_info) global_c = calculate_c_global(grid, univ_elem, layer_info) global_p = calculate_p_global(grid, univ_elem, boundaries_info) global_p *= -1 global_c *= 1 / step_time global_h += global_c for step in steps_times: global_p_temp = global_p + np.dot(global_c, nodes_temp) nodes_temp = np.dot(np.linalg.inv(global_h), global_p_temp) print("Step time: {}\tMin temp: {}\tMax temp: {}".format( step, np.amin(nodes_temp), np.amax(nodes_temp))) # upgrade grid with temperatures for node_id, temp in enumerate(nodes_temp): grid.getNode(node_id + 1).value = temp[0] return nodes_temp
def run(self): self._grid = Grid(self._cw, self._image) self._image.draw() self._grid.draw() self._run_once() self._window.mainloop()
def calculate_p_global(grid: Grid, univ_ele: UniversalElement, boundaries_info: dict): nodes_count = grid.get_spec().mN global_p = np.zeros(shape=(nodes_count, 1)) for i in range(grid.get_spec().mE): element = grid.getElement(i + 1) local_p = calculate_p_matrix(element, univ_ele, boundaries_info) indexes = [element[i].id - 1 for i in range(4)] # -1 to align with matrix indexing for local_row_index, global_row_index in zip(range(4), indexes): global_p[global_row_index, 0] += local_p[local_row_index, 0] return global_p
def calculate_c_global(grid: Grid, univ_elem: UniversalElement, layer_info: dict): global_c = np.zeros(shape=(grid.get_spec().mN, grid.get_spec().mN)) for i in range(grid.get_spec().mE): element = grid.getElement(i + 1) local_c = calculate_c_matrix(element, univ_elem, layer_info) indexes = [element[i].id - 1 for i in range(4)] # -1 to align with matrix indexing for local_row_index, global_row_index in zip(range(4), indexes): for local_column_index, global_column_index in zip( range(4), indexes): global_c[global_row_index, global_column_index] += local_c[local_row_index, local_column_index] return global_c
def create_grid_object(self, protein): """ Create initial grid object with random chain in it. :param protein: protein chain :return: grid object """ grid_object = Grid(protein) grid_object = random_chain(grid_object) return grid_object
def __init__(self): self.score = 0 self.grid = Grid(*GRID_SIZE) self.snake = Snake(self.grid) self.apple = Apple(self.grid) self.screen = pg.display.set_mode(SCREEN_SIZE) self.clock = pg.time.Clock() self.paused = False self.curr_events = None self.lives = STARTING_LIVES
def run(self): self._grid = Grid(self._cw, self._image, self._args, gui=False) kpt_files = os.listdir(self._args.keypoints_dir) kpt_files.sort(key=lambda e: int(e.split('_')[0])) self._handles = self.add_bunch(os.path.join(self._args.keypoints_dir, kpt_files[0])) if not os.path.exists(self._args.output_dir): os.mkdir(self._args.output_dir) pose_num = 0 cv2.imwrite(os.path.join(self._args.output_dir, '{}.png'.format(pose_num)), self._image._data[:, :, ::-1]) for pose in tqdm(kpt_files[1:]): self.move_bunch(pose) pose_num += 1 for _ in range(self._args.num_iterations): self.run_once() cv2.imwrite(os.path.join(self._args.output_dir, '{}.png'.format(pose_num)), self._image._data[:, :, ::-1])
def calculate_h_global(grid: Grid, univ_elem: UniversalElement, layer_info: dict, boundaries_info: dict): # creating global matrix with mNxmN size(num_nodes_in_grid x num_nodes_in_grid) global_h = np.zeros(shape=(grid.get_spec().mN, grid.get_spec().mN)) # iterating over every element in grid for i in range(grid.get_spec().mE): element = grid.getElement(i + 1) local_h = calculate_h_matrix(element, univ_elem, layer_info, boundaries_info) # list to store id of element nodes corresponding to shape function order indexes = [element[i].id - 1 for i in range(4)] # -1 to align with matrix indexing # aggregating matrix for local_row_index, global_row_index in zip(range(4), indexes): for local_column_index, global_column_index in zip( range(4), indexes): global_h[global_row_index, global_column_index] += local_h[local_row_index, local_column_index] return global_h
def initialize(protein, start_temperature): """ Create Grid object of protein and initialize temperature. :param protein: protein string :param start_temperature: chosen start temperature :return: current_state, stability_over_time, temperature """ # make a grid object with a random chain configuration with this protein current_state = Grid(protein) current_state = random_chain(current_state) # for statistic plotting stability_over_time = [] # set initial temperature temperature = start_temperature return current_state, stability_over_time, temperature
def main(): if len(sys.argv) != 3: print( "Please use the format: python main.py [protein_string] [optimalization_type]" ) return optimalization_type = str(sys.argv[2]) protein = str(sys.argv[1]) # testing if only H, P, C combinations exist in protein. protein_test = [ amino for amino in protein if (amino == "H" or amino == "P" or amino == "C") ] if len(protein_test) != len(protein): print("Please only use H's, C's and P's for your protein.") return if optimalization_type == "R": # make random chain grid_object = Grid(protein) grid_object = random_chain(grid_object) # for plotting compatibility chains = {} chains[grid_object.stability] = [ grid_object.grid, grid_object.grid_chain ] plot_chain_request(chains) if optimalization_type == "SA": annealing_flow(protein) if optimalization_type == "RHC": restart_hill_climb_flow(protein) if optimalization_type == "SL": self_learning(protein) return
def main(): if (len(sys.argv) == 1): print( "Run with parameters: python Main.py <simulation data in json path> <filename to save in paraview format>") exit(-1) file_path = sys.argv[1] try: grid = Grid.LoadFromData(file_path) with open(sys.argv[1]) as data_file: data_json = json.load(data_file) univ_elem = UniversalElement(4) calc.isotropic_heat_transfer_simulation(grid, univ_elem, **data_json) # save to vtk if (len(sys.argv) == 3): grid.saveToVTK(sys.argv[2]) except IOError: print("File not found!")
def isotropic_heat_transfer_simulation(grid: Grid, univ_elem: UniversalElement, **simulation_data): boundary_data = { i: { "alpha": simulation_data["alpha"], "ambient_temp": simulation_data["ambient_temp"] } for i in range(4) } layer_info = [[ grid.get_spec().W + 1, { "conductivity": simulation_data["conductivity"], "density": simulation_data["density"], "specific_heat": simulation_data["specific_heat"] } ]] simulate_heat_transfer(grid, univ_elem, boundaries_info=boundary_data, layer_info=layer_info, **simulation_data)
class Application: def __init__(self, path): self._cw = CWrapper() self._window = tk.Tk() self._grid = None self._image = None self.load_image(path) self._canvas = tk.Canvas(self._window, width=self._image.width, height=self._image.height) self._canvas.pack() self._image.canvas = self._canvas self._active_handle = -1 self._loop = None self._t_last = 0 def load_image(self, path): self._image = ImageHelper(self._cw, path) def bind(self, event, fn): self._canvas.bind(event, fn) def run(self): self._grid = Grid(self._cw, self._image) self._image.draw() self._grid.draw() self._run_once() self._window.mainloop() def _run_once(self): self._grid.regularize() dt = datetime.now() delta = dt.timestamp() - self._t_last if 0 < delta > 0.03: # 0.03 - 30 FPS # dt = datetime.now() # t1 = dt.timestamp() self._grid.project() #dt = datetime.now() # print(dt.timestamp()-t1) self._image.draw() self._grid.draw() dt = datetime.now() self._t_last = dt.timestamp() self._loop = self._window.after(1, self._run_once) def select_handle(self, e): handle_id = self._image.select_handle(e.x, e.y) if handle_id == -1: handle_id = self._image.create_handle(e.x, e.y) if handle_id != -1: if not self._grid.create_control_point(handle_id, e.x, e.y): self._image.remove_handle(handle_id) return False else: return False self._active_handle = handle_id return True def deselect_handle(self, e): self._active_handle = -1 def remove_handle(self, e): handle_id = self._image.select_handle(e.x, e.y) if handle_id != -1: self._grid.remove_control_point(handle_id) self._image.remove_handle(handle_id) def move_handle(self, e): if self._active_handle != -1: self._image.move_handle(self._active_handle, e.x, e.y) self._grid.set_control_target(self._active_handle, e.x, e.y)
class Application: def __init__(self, path): self._cw = CWrapper() self._window = tk.Tk() self._grid = None self._image = None self.load_image(path) self._canvas = tk.Canvas(self._window, width=self._image.width, height=self._image.height) self._canvas.pack() self._image.canvas = self._canvas self._active_handle = -1 self._loop = None self._t_last = 0 def load_image(self, path): self._image = ImageHelper(self._cw, path) def bind(self, event, fn): self._canvas.bind(event, fn) def run(self): self._grid = Grid(self._cw, self._image) self._image.draw() self._grid.draw() self._run_once() self._window.mainloop() def _run_once(self): self._grid.regularize() dt = datetime.now() delta = dt.timestamp()-self._t_last if 0 < delta > 0.03: # 0.03 - 30 FPS # dt = datetime.now() # t1 = dt.timestamp() self._grid.project() #dt = datetime.now() # print(dt.timestamp()-t1) self._image.draw() self._grid.draw() dt = datetime.now() self._t_last = dt.timestamp() self._loop = self._window.after(1, self._run_once) def select_handle(self, e): handle_id = self._image.select_handle(e.x, e.y) if handle_id == -1: handle_id = self._image.create_handle(e.x, e.y) if handle_id != -1: if not self._grid.create_control_point(handle_id, e.x, e.y): self._image.remove_handle(handle_id) return False else: return False self._active_handle = handle_id return True def deselect_handle(self, e): self._active_handle = -1 def remove_handle(self, e): handle_id = self._image.select_handle(e.x, e.y) if handle_id != -1: self._grid.remove_control_point(handle_id) self._image.remove_handle(handle_id) def move_handle(self, e): if self._active_handle != -1: self._image.move_handle(self._active_handle, e.x, e.y) self._grid.set_control_target(self._active_handle, e.x, e.y)
class NoGuiRunner: def __init__(self, args): self._cw = CWrapper() self._args = args path = args.path self._grid = None self._image = None self._handles = None self.load_image(path) def run(self): self._grid = Grid(self._cw, self._image, self._args, gui=False) kpt_files = os.listdir(self._args.keypoints_dir) kpt_files.sort(key=lambda e: int(e.split('_')[0])) self._handles = self.add_bunch(os.path.join(self._args.keypoints_dir, kpt_files[0])) if not os.path.exists(self._args.output_dir): os.mkdir(self._args.output_dir) pose_num = 0 cv2.imwrite(os.path.join(self._args.output_dir, '{}.png'.format(pose_num)), self._image._data[:, :, ::-1]) for pose in tqdm(kpt_files[1:]): self.move_bunch(pose) pose_num += 1 for _ in range(self._args.num_iterations): self.run_once() cv2.imwrite(os.path.join(self._args.output_dir, '{}.png'.format(pose_num)), self._image._data[:, :, ::-1]) def run_once(self): # no time delay left self._grid.regularize() self._grid.project() def load_image(self, path): self._image = ImageHelper(self._cw, self._args, gui=False) def add_bunch(self, posepath): with open(posepath, 'r') as f: poss = json.load(f) kpts = poss['people'][0]['pose_keypoints_2d'] xs = kpts[::3] ys = kpts[1::3] new_handles = {} i = 0 for ptx, pty in zip(xs, ys): new_handles[i] = (ptx, pty) i += 1 self._grid.create_bunch_cp(new_handles=new_handles) return new_handles def move_bunch(self, filename): with open(os.path.join(self._args.keypoints_dir, filename)) as f: poss = json.load(f) newpos = poss['people'][0]['pose_keypoints_2d'] xs = newpos[::3] ys = newpos[1::3] for i, h_obj in self._handles.items(): self._grid.set_control_target(i, xs[i], ys[i])
def building_wall_simulation(): univ_elem = UniversalElement() simulation_data_builder = SimulationDataBuilder() print("Liczienie temperatur dla ściany nieocieplonej") simulation_data_builder.add_layer(0.015, conductivity=2, density=2500, specific_heat=1000) \ .add_layer(0.26, conductivity=0.5, density=1000, specific_heat=2100) \ .set_boundary(SimulationDataBuilder.Boundary.RIGHT, alpha=30, ambient_temp=-10) layer_info, boundary_info = simulation_data_builder.build() grid = Grid(31, 31, 0.265, 0.1) calc.simulate_heat_transfer(grid, univ_elem, 21, 17280, 30, layer_info, boundary_info) grid.saveToVTK("./grid_nieocieplonaSciana") print("Liczienie temperatur dla ściany starego domu") simulation_data_builder.add_layer(0.035, conductivity=2, density=2500, specific_heat=1000) \ .add_layer(0.32, conductivity=0.5, density=1000, specific_heat=2100) \ .set_boundary(SimulationDataBuilder.Boundary.RIGHT, alpha=30, ambient_temp=-10) layer_info, boundary_info = simulation_data_builder.build() grid = Grid(31, 31, 0.335, 0.1) calc.simulate_heat_transfer(grid, univ_elem, 21, 17280, 30, layer_info, boundary_info) grid.saveToVTK("./grid_staryDom") print("Liczienie temperatur dla ściany ocieplonej") simulation_data_builder.add_layer(0.015, conductivity=2, density=2500, specific_heat=1000) \ .add_layer(0.26, conductivity=0.5, density=1000, specific_heat=2100) \ .add_layer(0.05, conductivity=0.04, density=30, specific_heat=1500) \ .set_boundary(SimulationDataBuilder.Boundary.RIGHT, alpha=30, ambient_temp=-10) layer_info, boundary_info = simulation_data_builder.build() grid = Grid(31, 31, 0.325, 0.1) calc.simulate_heat_transfer(grid, univ_elem, 21, 17280, 30, layer_info, boundary_info) grid.saveToVTK("./grid_ocieplonaSciana")
# -*- coding: utf-8 -*- import pygame import ctypes from config import app_config, app_logger from classes.Game import Game from classes.Grid import Grid from classes.Ball import Ball from classes.UI import UI pygame.init() # Заглавие окна pygame.display.set_caption(app_config['app']['name'].get()) # Две строчки ниже хак, чтобы FULLSCREEN рисовался строго по границам монитора, а не шире, как по умолчанию ctypes.windll.user32.SetProcessDPIAware() true_res = (ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1)) window = pygame.display.set_mode(true_res, pygame.FULLSCREEN) # Инициализируем UI user_interface = UI(window) # Инициализируем Grid grid = Grid() grid.draw(window) # Головная игровая логика game = Game(window, grid, user_interface) game.start()