def train(args): convert_annotations(cfg.DATASET.ANNOT_PATH, cfg.DATASET.ANNOT_JSON_SAVE_PATH) assert (os.path.exists(cfg.DATASET.ANNOT_JSON_SAVE_PATH)) # prepare the data dataloaders = prepare_data() # initialize model model_state_dict = None resume_dict = None if cfg.RESUME != '': resume_dict = torch.load(cfg.RESUME) model_state_dict = resume_dict['model_state_dict'] elif cfg.WEIGHTS != '': param_dict = torch.load(cfg.WEIGHTS) model_state_dict = param_dict['parameters'] net = model.get_MaskGenNet(state_dict=model_state_dict) net = torch.nn.DataParallel(net) if torch.cuda.is_available(): net.cuda() # initialize solver train_solver = Solver(net, dataloaders, resume=resume_dict) # train train_solver.solve() print('Finished!')
def __init__(self, config): # Load the system calibration values from the calibration file. self.cal_dict = get_calibration('calibration.yaml') self.cal = np.array(self.cal_dict[1]) # Define system magnetic model and solver with specific loaded configuration self.model = MagneticModel(config['model']) self.solver = Solver(self.cal, self.model, config['solver']) self.channels = config['system']['channels'] # Create a dictionary to store previous sensor positions self.prevPositions = dict() self.flipflags = config['system']['flip_list'] # Define DAQ and Filter objects with their associated configuration self.daq = DAQ(config) self.filter = Filter(config) # Declare storage for sample data and field strengths self.data = np.matrix([]) self.magnitudes = np.matrix([]) # Create local OpenIGTLink server self.igtconn = None if config['system']['igt'] is True: self.igtconn = PyIGTLink(port=config['system']['igt_port'], localServer=config['system']['igt_local'])
def main(): colorama.init() namespace = parse_args() file_names = sorted( glob.glob('resources/puzzles/*.txt')) if not namespace.cube \ else sorted(glob.glob('resources/cube_puzzles/*.txt')) for filename in file_names: if namespace.cube: board = CubeGameBoard(filename) board.read_board() texture_factory = TextureFactory(board.boards) texture_factory.generate_textures() start(board.boards) continue board = GameBoard(filename) board.read_board() print(filename) solver = Solver(board) solver.backtrack() board.print_solution() if board.verify_solution(): print('Solved') else: print('Not solved')
def test_random_solvable_quadratics(self): for i in range(0, 3): g = Generator(1, 2, 3, True) e = Equation(g.generate_quadratic(), bound='linear') solver = Solver(e, True, verbose=False) solver.solve() self.assertTrue(solver.solvable)
def test_solves_quadratic(self): e = Equation("aXba*X*b*", bound='linear') solver = Solver(e, False, verbose=False) solver.solve() self.assertTrue(solver.solvable) solutions = solver.solution_printer.solutions for solution in solutions: self.assertTrue(e.solves(solution))
def display(self,file): os.system('cls') solv = Solver(file) if solv.solvesudoku()== False: return FileResolver().resolvefromfile() else: self.matrixtosave = solv.solvesudoku() return self.savesudoku(self.matrixtosave)
def test_solve_no_constants(self): e = Equation("XYZ") solver = Solver(e, False, verbose=False) solver.solve() self.assertTrue(solver.solvable) solutions = solver.solution_printer.solutions self.assertEqual(len(solutions), 1) for solution in solutions: self.assertTrue(e.solves(solution))
def test_unconstrained_problem(self): solver = Solver() var1 = solver.add_variable() var2 = solver.add_variable() solver.add_rule(Rule(var1, [(1, var2)], 3)) self.assertFalse(solver.is_constrained)
def solve_sudoku(digits): ''' Solving the sudoku ''' solver = Solver() solver.load_solver_model(SUDOKU_SOLVER_MODEL_NAME) solved = solver.solve_sudoku(digits) return solved
def main(args): # Construct Solver np.random.seed(1) torch.manual_seed(1) torch.cuda.manual_seed_all(1) torch.backends.cudnn.deterministic = True # 保证每次结果一样 # data tr_dataset = AudioDataset(args.train_mfccjson, args.batch_size, args.maxlen_in, args.maxlen_out, batch_frames=args.batch_frames) cv_dataset = AudioDataset(args.valid_mfccjson, args.batch_size, args.maxlen_in, args.maxlen_out, batch_frames=args.batch_frames) tr_loader = AudioDataLoader(tr_dataset, batch_size=1, num_workers=args.num_workers, shuffle=args.shuffle, LFR_m=args.LFR_m, LFR_n=args.LFR_n, model_choose=args.model_choose) cv_loader = AudioDataLoader(cv_dataset, batch_size=1, num_workers=args.num_workers, LFR_m=args.LFR_m, LFR_n=args.LFR_n, model_choose=args.model_choose) data = {'tr_loader': tr_loader, 'cv_loader': cv_loader} model = Baseline1(args) print(model) print('model parameters:', sum(param.numel() for param in model.parameters())) model.cuda() optimizier = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), betas=(0.9, 0.98), eps=1e-09, lr=args.lr) # solver solver = Solver(data, model, optimizier, args) solver.train()
def __init__(self, size: tuple, board: list, screen: pygame.Surface): super().__init__((size[1], size[1], size[0] - size[1]), screen) self.__board = board self.__solver = Solver(self) # create squares list self.__squares = [[ Square( self.__board[c][r], (r, c), (self.size[0], self.size[2]), self.screen, True if self.__board[c][r] == 0 else False, ) for r in range(9) ] for c in range(9)] self.__selected = None self.__wrong = None
def labyrinth(args): # create maze, set it with rows and columns option maze = Maze(args.rows, args.columns) # create printer and set it with print option printer = Printer(maze, pause=args.pause) maze.set_maze() # print according to display options if args.display == 'both' or args.display == 'without-solution': printer.print_maze() if args.no_solve == False: # create solver and set it with maze object solver = Solver(maze) solver.solve() # print according to display options if args.display == 'both' or args.display == 'with-solution': printer.print_maze() print('Shortest path:', ', '.join(map(str, solver.shortest))) return solver.shortest
def __init__(self, matrix): ''' Constructor ''' matrix_copy=copy.deepcopy(matrix) self.original_matrix = matrix_copy self.solve_matrix = Solver(file) matrix_aux = self.get_int_matrix(matrix) self.resolved_matrix_backtracking = self.solve_matrix.solve_sudoku_game_backtracking(matrix_aux) self.resolved_matrix = self.solve_matrix.solve_sudoku_game_norvig(self.original_matrix)
class Generator: """Random valid Sudoku board generator""" def __init__(self): self.__solver = Solver() def generate(self) -> list: """Generate valid random Sudoku board :returns: valid Sudoku board :rtype: list """ # fill random position with random value b = [[0 for r in range(9)] for c in range(9)] b[randint(0, 8)][randint(0, 8)] = randint(1, 9) # 40%(32) to 60%(48) unempty squares (random value) unempty = randint(32, 48) # random postions list ranpos = [] # get random positions counter = 0 while counter <= unempty: # get random row and random column r, c = randint(0, 8), randint(0, 8) # check for repeated values if (r, c) not in ranpos: ranpos.append((r, c)) counter += 1 # sovle the board self.__solver.solve(b) # apply solution in random positions b2 = [[] for i in range(9)] # iterate overall rows for r in range(9): # iterate overall columns for c in range(9): # check if (r, c) position in random positions list if (r, c) in ranpos: b2[r].append(b[r][c]) else: b2[r].append(0) return b2
def test_simple_constrained_problem(self): solver = Solver() var1 = solver.add_variable() var2 = solver.add_variable() solver.add_rule(Rule(var1, [(1, var2)], 3)) solver.add_rule(Rule(var2, [], 3)) self.assertTrue(solver.is_constrained)
class HintsDisplayer: columns = ['A','B','C','D','E','F','G','H','I'] def __init__(self, matrix): ''' Constructor ''' matrix_copy=copy.deepcopy(matrix) self.original_matrix = matrix_copy self.solve_matrix = Solver(file) matrix_aux = self.get_int_matrix(matrix) self.resolved_matrix_backtracking = self.solve_matrix.solve_sudoku_game_backtracking(matrix_aux) self.resolved_matrix = self.solve_matrix.solve_sudoku_game_norvig(self.original_matrix) def get_value_in_cell(self, position): if len(position) > 2: return "Error" else: #cell = position.split(':') column = position[0] row = position[1] column = self.get_column_number(column) return self.resolved_matrix[int(row)-1][int(column)] def get_column_number(self, col): for i in range(9): if self.columns[i] == col.upper(): return i def get_int_matrix(self, str_matrix): backtrack_matrix = [] for i in range(9): backtrack_matrix.append([0]*9) for k in range(9): for l in range(9): backtrack_matrix[k][l] = int(str_matrix[k][l]) return backtrack_matrix
def main(config): set_random_seed(config) # Environment env = get_environment(config) # Policy & Baseline policy = get_policy_for_env(config, env, hidden_sizes=config.hidden_sizes, nonlinearity=config.nonlinearity).to( config.device) # policy.share_memory() baseline = LinearFeatureBaseline( reduce(mul, env.observation_space.shape, 1)).to(config.device) # Meta Learner metalearner = MAMLTRPO(config, policy, adapt_lr=config.adapt_lr, first_order=config.first_order, device=config.device) # Sampler sampler = MultiTaskSampler(config, config.env_name, env_kwargs=config.env_kwargs, batch_size=config.fast_batch_size, adapt_lr=config.adapt_lr, policy=policy, baseline=baseline, env=env, seed=config.seed) # Solver solver = Solver(config, policy, sampler, metalearner) solver.train(config)
class TestSolverUtilities(unittest.TestCase): """ Verify solver utility methods. """ def setUp(self): self.solver = Solver() self.board = self.solver.board def test_find_possibles(self): self.board.set_color(0, 0, 'R') self.board.set_color(1, 1, 'R') self.board.set_color(5, 5, 'R') self.assertEquals( 2, len(list(self.solver.possibles_for(5, 'R'))), "only 2,2 and 4,4 should remain as options for cells with height 5")
def test_solves_linear(self): e = Equation("aXa") solver = Solver(e, True, verbose=False) solver.solve() self.assertTrue(solver.solvable) solutions = solver.solution_printer.solutions self.assertEqual(len(solutions), 1) self.assertTrue(e.solves(solutions[0])) e = Equation("aaXbbYba*") solver = Solver(e, False, verbose=False) solver.solve() self.assertTrue(solver.solvable) solutions = solver.solution_printer.solutions self.assertTrue(len(solutions) > 1) for solution in solutions: self.assertTrue(e.solves(solution))
def __init__(self): # set main pygame screen size self.__screen_size = (1000, 720) self.__screen = pygame.display.set_mode(self.__screen_size[:2]) # change display icon pygame.display.set_icon(pygame.image.load("../assets/icon.png")) self.__generator = Generator() self.__board = self.__generator.generate() # create board object self.__board_model = Board(self.__screen_size, self.__board, self.__screen) # create solver object self.__solver = Solver(self.__board_model, 500) # create left panel object self.__left_panel = LeftPanel(self.__solver, self.__screen_size, self.__screen) # set screen title pygame.display.set_caption("Sudoku")
#!/usr/bin/env python # coding=utf-8 ''' @Author: wjm @Date: 2019-10-12 23:50:07 @LastEditTime: 2020-06-23 17:46:46 @Description: main.py ''' from utils.config import get_config from solver.solver import Solver import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='N_SR') parser.add_argument('--option_path', type=str, default='option.yml') opt = parser.parse_args() cfg = get_config(opt.option_path) solver = Solver(cfg) solver.run()
#!/usr/local/bin/python3 from solver.solver import Solver solver = Solver() solver.run()
class Board(GUIBase): """Screen Board :param board: Sudoku board represent as two dimensional array :type board: list :param size: screen dimensions (pixels) (width, height) :type size: tuple :param screen: pygame screen :type screen: pygame.Surface """ def __init__(self, size: tuple, board: list, screen: pygame.Surface): super().__init__((size[1], size[1], size[0] - size[1]), screen) self.__board = board self.__solver = Solver(self) # create squares list self.__squares = [[ Square( self.__board[c][r], (r, c), (self.size[0], self.size[2]), self.screen, True if self.__board[c][r] == 0 else False, ) for r in range(9) ] for c in range(9)] self.__selected = None self.__wrong = None @property def wrong(self): """wrong property (getter)""" return self.__wrong @property def squares(self) -> list: """squares property (getter)""" return self.__squares def update_squares(self): """squares property (updatter)""" # iterate over all squares for r in range(9): for c in range(9): # update values self.__squares[r][c].value = self.__board[r][c] self.__squares[r][c].pencil = 0 @property def board(self) -> list: """board property (getter)""" return self.__board @board.setter def board(self, board: list): """board property (setter) & update squares :param board: Sudoku board represent as two dimensional array :type board: list """ # set new board self.__board = board # reinit squares self.__squares = [[ Square( self.__board[c][r], (r, c), (self.size[0], self.size[2]), self.screen, True if self.__board[c][r] == 0 else False, ) for r in range(9) ] for c in range(9)] @property def selected(self) -> tuple: """selected property (getter)""" return self.__selected @selected.setter def selected(self, pos: tuple): """selected property (setter) & refresh squares :param pos: selected square position (row, column) :type pos: tuple """ if not self.__wrong: # clear previous selection if self.__selected != None: self.__squares[self.__selected[0]][ self.__selected[1]].selected = False if pos: # select new square self.__selected = pos self.__squares[self.__selected[0]][ self.__selected[1]].selected = True else: # set selected to None if pos out of board self.__selected = None @property def get_pencil(self) -> int: """selected square pencil (getter)""" # get selected square r, c = self.__selected return self.__squares[r][c].pencil def set_pencil(self, value: int): """set pencil value :param value: pencil value :type value: int """ # get selected square r, c = self.__selected if self.__squares[r][c].value == 0: self.__squares[r][c].pencil = value @property def get_value(self) -> int: """selected square value (getter)""" # get selected square r, c = self.__selected return self.__squares[r][c].value def set_value(self) -> str: """set square value :returns: board state ('s' -> success, 'w' -> wrong, 'c' -> unsolvable board) :rtype: str """ # get selected square r, c = self.__selected if self.get_value == 0: # chock for non-0 pencil value pencil = self.get_pencil if pencil != 0: # check the number match Sudoku rules w = self.__solver.exists(self.__board, pencil, (r, c)) if w: # change squares state to wrong (red color) self.__squares[r][c].wrong = True self.__squares[w[0]][w[1]].wrong = True self.__squares[r][c].value = pencil self.__board[r][c] = pencil self.__wrong = w return "w" else: # change set square value and return true self.__squares[r][c].value = pencil self.__board[r][c] = pencil # copy board # init copy as two dimensional array with 9 rows copy = [[] for r in range(9)] # iterate over all rows for r in range(9): # iterate over all columns for c in range(9): # append the num copy[r].append(self.__board[r][c]) # check if the board unsolvable if not self.__solver.solve(copy): return "c" return "s" @property def clear(self): """clear selected square value""" # get selected square r, c = self.__selected # clear square value and pencil self.__squares[r][c].value = 0 self.__squares[r][c].pencil = 0 self.__board[r][c] = 0 # change wrong state if self.__wrong: self.__squares[r][c].wrong = False self.__squares[self.__wrong[0]][self.__wrong[1]].wrong = False self.__wrong = None @property def isfinished(self): """return true if there's no more empty squares else false :returns: true if there's no more empty squares else false :rtype: bool """ return not self.__solver.nextpos(self.board) def set_sq_value(self, value: int, pos: tuple): """change square value by position :param value: new square value :type value: int :param pos: square position :type pos: tuple """ self.__squares[pos[0]][pos[1]].value = value def draw(self): """Draw the board on the screen""" # Draw squares # iterate over all rows for r in range(9): # iterate over all columns for c in range(9): # draw square value self.__squares[c][r].draw() # Draw grid # set space between squares space = self.size[0] // 9 # drow 10 lines HvV for r in range(10): # set line weight (bold at the end of 3*3 area) w = 4 if r % 3 == 0 and r != 0 else 1 # draw horizontal line (screen, (color), (start_pos), (end_pos), width) pygame.draw.line( self.screen, (72, 234, 54), (self.size[2], r * space), (self.size[0] + self.size[2], r * space), w, ) # draw vertical line (screen, (color), (start_pos), (end_pos), width) pygame.draw.line( self.screen, (72, 234, 54), (r * space + self.size[2], 0), (r * space + self.size[2], self.size[1]), w, )
def setUp(self): self.solver = Solver() self.board = self.solver.board
def __init__(self, MBD_system, parent=None, flags=0): """ Constructor """ super(SimulationControlWidget, self).__init__(parent) self._parent = parent self.ui = Ui_Form() self.ui.setupUi(self) # set size independent of screen resolution to be equal for all resolutions self.setFixedWidth(.2 * self._parent.screen_geometry.width()) self.ui.simulationStopButton.setEnabled(False) self.ui.simulationResetButton.setEnabled(False) self.ui.forwardButton.setEnabled(False) self.ui.backwardButton.setEnabled(False) self.ui.playButton.setEnabled(False) # movie maker self.movie_maker = None # pool of tasks self.pool = QtCore.QThreadPool.globalInstance() self.pool.setMaxThreadCount(1) self.MBD_system = MBD_system # self.simulation_control_widget = self # when simulation is finishes # automatically load solution file self.ui.loadSolutionFileStatus.setChecked(self.MBD_system.loadSolutionFileWhenFinished) # restore initial conditions self.ui.restoreInitialConditionsStatus.setChecked(self.MBD_system.restoreInitialConditionsWhenFinished) # set visualization widget in central widget position self.vtkWidget = VTKWidget(MBD_system=self.MBD_system, parent=self._parent) self._status = "simulation" # simulation or animation # set integration method to display self.ui.integrationMethodComboBox.addItems(self.MBD_system.integrationMethods) _index = self.ui.integrationMethodComboBox.findText(self.MBD_system.integrationMethod) self.ui.integrationMethodComboBox.setCurrentIndex(_index) # signals self.step_num_signal = stepSignal() self.energy_signal = EnergySignal() self.status_signal = StatusSignal() self.signal_simulation_status = SignalSimulationStatus() # use BSM - baumgarte stabilization method self.ui.useBSM_checkBox.setChecked(self.MBD_system.use_BSM) # set validators to limit user input __validator_dbl = QtGui.QDoubleValidator() __validator_int = QtGui.QIntValidator() # predefined values # end time self.ui.endTime.setValidator(__validator_dbl) if self.MBD_system.t_n is not None: self.ui.endTime.setText(str(self.MBD_system.t_n)) # number of steps self.ui.stepsNumber.setValidator(__validator_int) if self.MBD_system.stepsNumber is not None: self.MBD_system.stepsNumber = int(self.MBD_system.stepsNumber) self.ui.stepsNumber.setText(str(self.MBD_system.stepsNumber)) # simulation time step self.step = 0 self._step = 0 # animation properties self._delta_step = None # H min self.MBD_system.evaluate_Hmin() # H max self.ui.Hmax.setText(str(self.MBD_system.Hmax)) self.ui.Hmax.setValidator(__validator_dbl) # H min self.ui.Hmin.setText(str(self.MBD_system.Hmin)) self.ui.Hmin.setValidator(__validator_dbl) # H contact self.ui.Hcontact.setText(str(self.MBD_system.Hcontact)) # abs tol self.ui.absTol.setText(str(self.MBD_system.absTol)) self.ui.absTol.setValidator(__validator_dbl) # rel tol self.ui.relTol.setText(str(self.MBD_system.relTol)) self.ui.relTol.setValidator(__validator_dbl) # tolerance for newton differences self.ui.TOL_dq_i.setText(str(self.MBD_system.TOL_dq_i)) # tolerance for constraint equations C self.ui.TOL_C.setText(str(self.MBD_system.TOL_C)) # create solver thread # solver thread self._solver_thread = QtCore.QThread() self._solver_thread.start() if not MBD_system.monte_carlo: self.solver = Solver(MBD_system, parent=self) else: # jobs of threads # self.solver = SolverThreadManager(MBD_system=self.MBD_system, parent=self) # jobs as processes self.solver = SolverProcessManager(MBD_system=self.MBD_system, parent=self) self.solver.moveToThread(self._solver_thread) # self.solver_process = psutil.Process(id(self._solver_thread)) # timer to update cpu, memory data in simulation control widget self._data_timer = QtCore.QTimer(self) self._data_timer.timeout.connect(self._update_cpu_memory_data) # display update self._update_display_type = self.MBD_system._update_display_type _index = self.ui.updateDisplay_comboBox.findText(self._update_display_type) self.ui.updateDisplay_comboBox.setCurrentIndex(_index) # available options self._update_display_types = ["dt", "step"] # update display on every i-th simulation step if hasattr(self.solver.analysis, "update_opengl_widget_every_Nth_step"): self.ui.updateStep_lineEdit.setText(str(int(self.solver.analysis.update_opengl_widget_every_Nth_step))) self._delta_step = self.solver.analysis.update_opengl_widget_every_Nth_step self.ui.updateStep_lineEdit.setValidator(__validator_int) self.ui.updateStep_lineEdit.setText(str(int(self.MBD_system.updateEveryIthStep))) # update display on dt of simulation time # default value if self.MBD_system._dt == 0: self._dt = self.MBD_system.t_n / 100. else: self._dt = self.MBD_system._dt self.ui.updateDt_lineEdit.setValidator(__validator_dbl) self.ui.updateDt_lineEdit.setText(str(self._dt)) self.ui.currentStep_lineEdit.setEnabled(False) self.ui.currentStep_lineEdit.setValidator(__validator_int) # profiler self.profile = cProfile.Profile() # analysis type self.ui.analysisTypeComboBox.currentIndexChanged.connect(self._analysis_type_changed) # set analysis type to display it in combobox if self.MBD_system.analysis_type is not None: _index = self.ui.analysisTypeComboBox.findText(QtCore.QString(self.MBD_system.analysis_type.title())) self.ui.analysisTypeComboBox.setCurrentIndex(_index) # tab widget of simulation control widget self.ui.tabWidget.setCurrentIndex(0) # video maker attribute object self.video_maker = None # initial start time and date self.ui.simulationStartTime_dateTimeEdit.setDate(QtCore.QDate().currentDate()) # progress bar style css_file = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "progress_bar_style_no_error.css"), 'r') self.progress_bar_no_error_css_stype = css_file.read() self.ui.simulation_progressBar.setStyleSheet(self.progress_bar_no_error_css_stype) css_file = open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "progress_bar_style_error.css"), 'r') self.progress_bar_error_css_stype = css_file.read() # signals self.connect_signals() # buttons self.connect_buttons() # connections self.connect_UIWidgetItems2variables() # check if solutionfile is defined and load it if self.MBD_system.solutionFilename is not None: solutionFilePath = os.path.join(self.MBD_system.MBD_folder_abs_path, self.MBD_system.solutionFilename) if os.path.isfile(solutionFilePath): self.__automaticaly_load_solution_file(filename=solutionFilePath) else: print "Solution File not found at path %s: " % self.MBD_system.MBD_folder_abs_path print "Check Filename: %s" % self.MBD_system.solutionFilename
from solver.solver import Solver global GLOBALS def path_(_root, _file): return path.join(_root, _file) if __name__ == "__main__": GLOBALS.BOOKS_SCANNED = [0 for _ in range(100009)] # Change this below variable accroding to the test case, range [0-5]. scan_file = 5 with Solver.read_file( path_(GLOBALS.INPUT_FOLDER_NAME, GLOBALS.FILES[scan_file])) as file: GLOBALS.TOTAL_BOOKS, GLOBALS.TOTAL_LIBRARIES, GLOBALS.TOTAL_DAYS = list( map(int, file.readline().split(' '))) GLOBALS.BOOK_SCORE = list(map(int, file.readline().split(' '))) for _ in range(GLOBALS.TOTAL_LIBRARIES): book, signup, scan = list(map(int, file.readline().split(' '))) book_ids = list(map(int, file.readline().split(' '))) books = [] for i in range(book): books.append(Book(book_ids[i], GLOBALS.BOOK_SCORE[i])) GLOBALS.LIBRARIES.append(
from solver.solver import Solver from model.baseline import Baseline """ 创建一个模型, 训练这个模型, 测试这个模型 """ if __name__ == '__main__': print('C2JD Start.') model = Baseline() solver = Solver(model) solver.solve() solver.evaluate() print('C2JD End.')
def __init__(self): self.__solver = Solver()
def train(args): #seed = 12345 #random.seed(seed) #np.random.seed(seed) #torch.random.manual_seed(seed) # initialize model model_state_dict = None model_state_dict_D = None resume_dict = None if cfg.RESUME != '': resume_dict = torch.load(cfg.RESUME, torch.device('cpu')) model_state_dict = resume_dict['model_state_dict'] elif cfg.WEIGHTS != '': param_dict = torch.load(cfg.WEIGHTS, torch.device('cpu')) model_state_dict = param_dict['weights'] model_state_dict_D = param_dict[ 'weights_D'] if 'weights_D' in param_dict else None net = SegNet.__dict__[cfg.MODEL.NETWORK_NAME]( pretrained=False, pretrained_backbone=False, num_classes=cfg.DATASET.NUM_CLASSES, aux_loss=cfg.MODEL.USE_AUX_CLASSIFIER) net = gen_utils.load_model(net, './model/resnet101-imagenet.pth', True) if args.distributed: net = torch.nn.SyncBatchNorm.convert_sync_batchnorm(net) #net = apex.parallel.convert_syncbn_model(net) if cfg.MODEL.DOMAIN_BN: net = DomainBN.convert_domain_batchnorm(net, num_domains=2) if model_state_dict is not None: try: net.load_state_dict(model_state_dict) except: net = DomainBN.convert_domain_batchnorm(net, num_domains=2) net.load_state_dict(model_state_dict) if cfg.TRAIN.FREEZE_BN: net.apply(freeze_BN) if torch.cuda.is_available(): net.cuda() if args.distributed: net = DistributedDataParallel(net, device_ids=[args.gpu]) #net = DistributedDataParallel(net) else: net = torch.nn.DataParallel(net) net_D = init_net_D(args, model_state_dict_D) if cfg.TRAIN.ADV_TRAIN else None dataloaders = prepare_data(args) # initialize solver train_solver = Solver(net, net_D, dataloaders, args.distributed, resume=resume_dict) # train train_solver.solve() print('Finished!')
class EMTracker: """ Class definition for Anser EMT system """ def __init__(self, config): # Load the system calibration values from the calibration file. self.cal_dict = get_calibration('calibration.yaml') self.cal = np.array(self.cal_dict[1]) # Define system magnetic model and solver with specific loaded configuration self.model = MagneticModel(config['model']) self.solver = Solver(self.cal, self.model, config['solver']) self.channels = config['system']['channels'] # Create a dictionary to store previous sensor positions self.prevPositions = dict() self.flipflags = config['system']['flip_list'] # Define DAQ and Filter objects with their associated configuration self.daq = DAQ(config) self.filter = Filter(config) # Declare storage for sample data and field strengths self.data = np.matrix([]) self.magnitudes = np.matrix([]) # Create local OpenIGTLink server self.igtconn = None if config['system']['igt'] is True: self.igtconn = PyIGTLink(port=config['system']['igt_port'], localServer=config['system']['igt_local']) def start_acquisition(self): """Start the DAQ acquisition background process""" self.daq.daqStart() def stop_acquisition(self): """Stop the DAQ acquisition background process""" self.daq.daqStop() def sample_update(self): """Retrieve new samples from the buffer. Sample data for each channel is obtained and stored simultaneously. Due to driver limitations, it is important that this function be called as often as possible on Linux and Mac operation systems""" self.data = self.daq.getData() # def get_position(self, sensorNo, igtname=''): """Wrapper to include igt connection""" # Set the solver to use the corresponding sensor calibration self.solver.calibration = np.array(self.cal_dict[sensorNo]) if sensorNo in self.prevPositions.keys(): self.solver.conditions = self.prevPositions[sensorNo] else: # Default initial conditionf for the solver self.solver.conditions = [0, 0, 0.2, 0, 0] # Resolve the position of the sensor indicated by sensorNo # Convert the resolved position to a 4x4 homogeneous transformation matrix position = self._resolve_position(sensorNo) positionmat = self.vec_2_mat_5dof(position) # Latest resolved position is saved as the initial condition for the next solver iteration self.prevPositions[sensorNo] = position # Send the resolved position over the system's OpenIGTLink connection # Optional sensor orientation correction (Theta + Pi) is applied before transmission if self.igtconn is not None: igtposition = position.copy() if str(sensorNo) not in self.flipflags: igtposition[3] = igtposition[3] + pi igtmat = self.vec_2_mat_5dof(igtposition) self._igt_send_transform(igtmat, igtname) # Return the sensor position in both vector and 4x4 homogeneous transformation matrix. return position, positionmat # Resolve the position of the sensor specified by sensorNo. Should not be called directly. Use get_position instead def _resolve_position(self, sensorNo): magnitudes = self.filter.demodulateSignalRef( self.data, self.channels.index(sensorNo) + 1) f = np.array(magnitudes) result = self.solver.solveLeastSquares(magnitudes) # Wrap around angles to preserve constraints wrapresult = self._angle_wrap(result) self.solver.initialCond = wrapresult.x return np.array(wrapresult.x) # Send a transformation matrix mat using the system's OpenIGTLink connection def _igt_send_transform(self, mat, device_name=''): matmsg = TransformMessage(mat, device_name=device_name) self.igtconn.add_message_to_send_queue(matmsg) @staticmethod def print_position(position): print('%0.4f %0.4f %0.4f %0.4f %0.4f' % (position[0] * 1000, position[1] * 1000, position[2] * 1000, position[3], position[4])) @staticmethod def _angle_wrap(result): if result.x[4] > 2 * pi: result.x[4] = result.x[4] - 2 * pi elif result.x[4] < -2 * pi: result.x[4] = result.x[4] + 2 * pi return result @staticmethod def vec_2_mat_5dof(array): mat = np.matrix( [[ np.cos(array[4]) * np.cos(array[3]), -np.sin(array[4]), np.cos(array[4]) * np.sin(array[3]), array[0] * 1000 ], [ np.sin(array[4]) * np.cos(array[3]), np.cos(array[4]), np.sin(array[4]) * np.sin(array[3]), array[1] * 1000 ], [-np.sin(array[3]), 0, np.cos(array[3]), array[2] * 1000], [0, 0, 0, 1]]) return mat @staticmethod def vec_2_mat_6dof(self, array=np.array(np.zeros([1, 6]))): pass
def run_experiment(self): """ Run Experiment with different configurations (input via --argument): 1) --model_type: linear, lstm, social-lstm 2) --socialforce: specify whether dataset is synthetic dataset (True), or real (False) 3) --phase: train or test Trained Models are saved under "Saved_Models/dataset_name/model_name". For a list of possible input arguments run script with --help. """ # ============================== # Check input-configurations # ============================== viz = self.connect2visdom(self.args.viz_server, self.args.viz_port, "losses") if self.args.lstm_pool and self.args.model_type != "social-lstm": print( "WARNING: model_type was changed to social-lstm since Social-Pooling was set to True!" ) self.args.model_type = "social-lstm" elif self.args.model_type == "social-lstm" and not self.args.lstm_pool: print( "WARNING: Social-Pooling was set to True because model_type is specified as social-lstm!" ) self.args.lstm_pool = True if self.args.socialforce: # Get name of dataset and model - for synthetic datasets model name will be of the form: ModelType_UniqueIdentifier parameterinfo = "V0" + str(self.args.V0).replace( ".", "u") + "b" + str(self.args.sigma).replace(".", "u") self.args.model_name = self.args.model_type + "_" + parameterinfo self.args.dataset_name = self.args.dataset_type + "simulated_" + parameterinfo else: # Get name of dataset and model - for real datasets model name will be of the form: ModelType_DatasetName_InputModelName if (self.args.model_type not in self.args.model_name) or ( self.args.dataset_name not in self.args.model_name): self.args.model_name = self.args.model_type + "_" + self.args.dataset_name + "_" + self.args.model_name if self.args.model_name[-1] == "_": self.args.model_name = self.args.model_name[:-1] if not os.path.exists( os.path.join(self.root_path, "datasets", self.args.dataset_name)): raise ValueError( "Specified dataset: %s does not exist! Please check existing datasets and specify one with flag: --dataset_name" % (self.args.dataset_name)) if self.args.phase == "test": # Ensure that for testing we only run one epoch and do not augment the data self.args.num_epochs = 1 self.args.load_model = True self.args.data_augmentation = False # Get configs for data preparation config_data = config_dataprep() # Configurations for logging losses self.log_configs() # ============== # Data prep # ============== dset, loader, dset_val, val_loader = self.load_data( config_data, logger) # ============= # Get model # ============= if self.args.model_type.lower() == "linear": model = LINEAR(self.args) elif self.args.model_type.lower() == "lstm": model = LSTM(self.args) elif self.args.model_type.lower() == "social-lstm": self.args.lstm_pool = True model = LSTM(self.args) else: raise ValueError( "Please choose model_type either: linear, lstm or social-lstm") # =============== # Optimizer # =============== # Define optimizer if self.args.optim.lower() == "adam": config_opt = config_Adam(lr=self.args.lr, weight_decay=self.args.wd) optimizer = torch.optim.Adam( model.parameters(), **{ "lr": config_opt.lr, "betas": config_opt.betas, "eps": config_opt.eps, "weight_decay": config_opt.weight_decay }) elif self.args.optim.lower() == "rmsprop": config_opt = config_RMSprop(lr=self.args.lr, weight_decay=self.args.wd) optimizer = torch.optim.RMSprop( model.parameters(), **{ "lr": config_opt.lr, "alpha": config_opt.alpha, "eps": config_opt.eps, "weight_decay": config_opt.weight_decay }) elif self.args.optim.lower() == "sgd": config_opt = config_SGD(lr=self.args.lr, weight_decay=self.args.wd) optimizer = torch.optim.SGD( model.parameters(), **{ "lr": config_opt.lr, "weight_decay": config_opt.weight_decay, "momentum": config_opt.momentum, "dampening": config_opt.dampening, "nesterov": config_opt.nesterov }) else: raise ValueError("Please specify a valid optimizer with optim!") # ================= # load Model # ================ # Define saving directory for Model saving_directory = os.path.join(self.root_path, "Saved_Models", str(self.args.dataset_name)) if not os.path.exists(saving_directory): print("Create path for saving model: %s" % (saving_directory)) os.makedirs(saving_directory) if self.args.save_model: print("Model will be saved under: " + saving_directory + "/" + self.args.model_name) else: print("Model " + self.args.model_name + " will not be saved") loaded_states = {} loss_history_all = { self.args.dataset_name: { "train": {}, "val": {}, "test": {} } } epochs = 0 if self.args.load_model: print("Loading Model...") if os.path.isfile( os.path.join(str(saving_directory), self.args.model_name)): loaded_states = torch.load( os.path.join(str(saving_directory), self.args.model_name)) model.load_state_dict(loaded_states["model_state_dict"]) device = torch.device("cpu") optimizer.load_state_dict( loaded_states["optimizer_state_dict"]) move_opt_state_to_GPU(optimizer) loss_history_all = loaded_states["loss"] if self.args.dataset_name not in loss_history_all: loss_history_all[self.args.dataset_name] = { "train": {}, "val": {}, "test": {} } if self.args.phase == "train": epochs = loaded_states["epochs"] print("Model loaded...") else: print( "Tried to load model, but model does not exist!\nContinued with new model" ) else: print("Create new Model...") # ================= # Train Model # ================= # Define solver solver = Solver(optim=optimizer, loss_all=loss_history_all, epochs=epochs, args=self.args, server=self.server) # Train/eval Model solver.train(model, self.args.model_type.lower(), loader, val_loader, phase=self.args.phase, log_nth=self.args.log_nth, num_epochs=self.args.num_epochs) # Save Model if self.args.save_model: model.save( solver.optim, solver.loss_history_all, solver.last_epoch, os.path.join(str(saving_directory), self.args.model_name)) # ============== # RESULTS # ============= # Plot Histogram for Distances to other pedestrians in order to avoid collision behavior of models if self.args.phase == "test": if self.args.analyse_coll_avoidance: histo = create_histogram(self.args, self.server) histo.plot_histogram_distances(solver) # Note Results of testing of Socialforce Experiment for further Analysis if self.args.socialforce: if self.args.phase == "test": print( "Writing test losses for Socialforce-Experiment to .xlsx-file..." ) # ============================================================== # For Analysis of overall ADE and FDE for specific V0 and sigma # ============================================================== result_path = os.path.join(self.root_path, "Analyse_Results", "Overall_Loss") if not os.path.exists(result_path): os.makedirs(result_path) file_name = "socialforce_" + str( self.args.model_type) + "_results" if self.args.model_type == "social-lstm": file_name += "_ns_" + str(int( self.args.neighborhood_size)) + "_gs_" + str( int(self.args.grid_size)) file_name += ".xlsx" filepath = os.path.join(result_path, file_name) final_ADE_loss = solver.loss_history_all[ self.args.dataset_name][self.args.phase]["G_ADE"][-1] final_FDE_loss = solver.loss_history_all[ self.args.dataset_name][self.args.phase]["G_FDE"][-1] # Create or Append Excel sheet with ADE and FDE of respective dataset note_test_results_for_socialforce(filepath, self.args, final_ADE_loss, final_FDE_loss) # =========================================== # For Analysis of ADE in non-linear regions # =========================================== if "G_ADE_nl_regions" in model.losses: print("Writing loss in nonlinear Regions to .xlsx-file...") result_path = os.path.join(self.root_path, "Analyse_Results", "Nonlinear_ADE") if not os.path.exists(result_path): os.makedirs(result_path) file_name = "socialforce_nl_loss.xlsx" filepath = os.path.join(result_path, file_name) final_nl_ADE_loss = solver.loss_history_all[ self.args.dataset_name][ self.args.phase]["G_ADE_nl_regions"][-1] note_nonlinear_loss(filepath, self.args, final_ADE_loss, final_nl_ADE_loss) # Note results of best validation ADE loss of training if self.args.phase == "train": print("Writing train losses with configs to .xlsx-file...") result_path = os.path.join(self.root_path, "Stats", "BestVal", self.args.dataset_name) if not os.path.exists(result_path): os.makedirs(result_path) xlsx_file = self.args.dataset_name + "_" + self.args.model_type + ".xlsx" filepath = os.path.join(result_path, xlsx_file) note_best_val(filepath, self.args, solver.best_val, solver.best_val_FDE, solver.best_val_epoch) # Plot losses if self.args.visdom: self.plot_loss_visdom(viz, solver.loss_history_all) else: self.plot_loss(solver.loss_history_all) # Print Hyperparameters as Summary self.log_HyperParameters()
#!/usr/bin/env python # coding=utf-8 ''' @Author: wjm @Date: 2019-10-12 23:50:07 @LastEditTime: 2020-06-23 17:46:46 @Description: main.py ''' from utils.config import get_config from solver.solver import Solver import argparse if __name__ == '__main__': parser = argparse.ArgumentParser(description='N_SR') parser.add_argument('--option_path', type=str, default='option.yml') opt = parser.parse_args() cfg = get_config(opt.option_path) for i in range(2, 3): solver = Solver(cfg, i) solver.run()
class CodenamesSolverApp(object): def __init__(self, data_dir): self.jinja_env = Environment( loader=PackageLoader('webserver', 'templates')) self.solver = Solver(data_dir, 100000) self.game_words = self.solver.filter_in_vocab(load_game_words()) @staticmethod def create_board(): board = Board(n_p1=9, n_p2=8, n_neutral=7, n_assassin=1) cherrypy.session['board'] = board return board @staticmethod def get_board(): try: return cherrypy.session['board'] except KeyError: raise cherrypy.HTTPRedirect('/') @cherrypy.expose def index(self): tmpl = self.jinja_env.get_template('setup.html') board = self.create_board() return tmpl.render(words=self.game_words, p1=board.get_html_names(PLAYER1), p2=board.get_html_names(PLAYER2), neutral=board.get_html_names(NEUTRAL), assassin=board.get_html_names(ASSASSIN)) @cherrypy.expose def display(self): board = self.get_board() tmpl = self.jinja_env.get_template('board.html') return tmpl.render(p1=board.get_filtered_words(PLAYER1), p2=board.get_filtered_words(PLAYER2), neutral=board.get_filtered_words(NEUTRAL), assassin=board.get_filtered_words(ASSASSIN), current=board.get_current_player()) @cherrypy.expose def start(self, **kwargs): board = self.get_board() for player in [PLAYER1, PLAYER2, NEUTRAL, ASSASSIN]: board.set_words(player, {kwargs[x] for x in board.get_html_names(player)}) board.reset_game() raise cherrypy.HTTPRedirect('/display/') @cherrypy.expose def random(self): board = self.get_board() board.generate_random_setup(self.game_words) board.reset_game() raise cherrypy.HTTPRedirect('/display/') @cherrypy.expose def turn(self, **kwargs): board = self.get_board() for key, item in kwargs.items(): if isinstance(item, list): board.set_words(COVERED, board.get_words(COVERED) | set(item)) else: board.set_words(COVERED, board.get_words(COVERED) | {item}) board.next_turn() raise cherrypy.HTTPRedirect('/display/') @cherrypy.expose def solve(self): board = self.get_board() suggested_moves = self.solver.solve( num_results=5, words={ solver.names.PLAYER: list(board.get_player_words()), solver.names.OPPONENT: list(board.get_opponent_words()), solver.names.NEUTRAL: list(board.get_words(NEUTRAL)), solver.names.ASSASSIN: list(board.get_words(ASSASSIN)), solver.names.COVERED: list(board.get_words(COVERED)) }) tmpl = self.jinja_env.get_template('suggestions.html') return tmpl.render(suggestions=suggested_moves)
def __init__(self, MBD_system, parent=None, flags=0): """ Constructor """ super(SimulationControlWidget, self).__init__(parent) self._parent = parent self.ui = Ui_Form() self.ui.setupUi(self) self.ui.simulationStopButton.setEnabled(False) self.ui.simulationResetButton.setEnabled(False) self.ui.forwardButton.setEnabled(False) self.ui.backwardButton.setEnabled(False) self.ui.playButton.setEnabled(False) self.MBD_system = MBD_system # when simulation is finishes # automatically load solution file self.ui.loadSolutionFileStatus.setChecked(self.MBD_system.loadSolutionFileWhenFinished) # restore initial conditions self.ui.restoreInitialConditionsStatus.setChecked(self.MBD_system.restoreInitialConditionsWhenFinished) # sets opengl widget in central widget position self.opengl_widget = OpenGLWidget(MBD_system=MBD_system, parent=self._parent) self._status = "simulation" # simulation or animation # set integration method to display try: _index = self.ui.integrationMethodComboBox.findText(QtCore.QString(self.MBD_system.integrationMethod.title())) except: _index = 0 if _index != -1: self.ui.integrationMethodComboBox.setCurrentIndex(_index) else: self.ui.integrationMethodComboBox.setCurrentIndex(_index) # signals self.step_num_signal = stepSignal() self.energy_signal = EnergySignal() self.status_signal = StatusSignal() # self.graphWidget = None # self.graphWidget = GraphWidget(MBD_system=MBD_system_, parent=parent) # self.graphWidget.setWindowFlags(parent.windowFlags()) # self.graphWidget.show() # set validators to limit user input __validator_dbl = QtGui.QDoubleValidator() __validator_int = QtGui.QIntValidator() # predefined values # end time self.ui.endTime.setText(str(self.MBD_system.t_n)) self.ui.endTime.setValidator(__validator_dbl) # self.ui.simulation_progressBar.setMinimum(0) # self.ui.simulation_progressBar.setMaximum(int(1/self.MBD_system.t_n)) # self.ui.simulation_progressBar.setValue(0) # Hmax if self.MBD_system.t_n/100 < self.MBD_system.Hmax: self.MBD_system.Hmax = 0.01*self.MBD_system.t_n # Hmin self.MBD_system.evaluate_Hmin() self.ui.Hmax.setText(str(self.MBD_system.Hmax)) self.ui.Hmax.setValidator(__validator_dbl) # Hmin self.ui.Hmin.setText(str(self.MBD_system.Hmin)) self.ui.Hmin.setValidator(__validator_dbl) # abs tol self.ui.absTol.setText(str(self.MBD_system.absTol)) self.ui.absTol.setValidator(__validator_dbl) # rel tol self.ui.relTol.setText(str(self.MBD_system.relTol)) self.ui.relTol.setValidator(__validator_dbl) # tolerance for newton differences self.ui.TOL_dq_i.setText(str(self.MBD_system.TOL_dq_i)) # tolerance for constraint equations C self.ui.TOL_C.setText(str(self.MBD_system.TOL_C)) # create solver thread self.solver = Solver(MBD_system=MBD_system, parent=self)#parent self._solver_thread = QThread() self._solver_thread.start() self.solver.moveToThread(self._solver_thread) # display update self._update_display_type = "dt" # available options self._update_display_types = ["dt", "step"] # update display on every i-th simulation step self.ui.updateStep_lineEdit.setText(str(int(self.solver.analysis.update_opengl_widget_every_Nth_step))) self.ui.updateStep_lineEdit.setValidator(__validator_int) self._delta_step = self.solver.analysis.update_opengl_widget_every_Nth_step # update display on dt of simulation time # default value self._dt = self.MBD_system.t_n / 100. self.ui.currentStep_lineEdit.setEnabled(False) self.ui.currentStep_lineEdit.setValidator(__validator_int) # connections and signals self.ui.simulationStartButton.clicked.connect(self.simulationStart) self.ui.simulationStartButton.clicked.connect(self.solver.start_solver) self.ui.simulationStopButton.clicked.connect(self.simulationStop) self.ui.simulationStopButton.clicked.connect(self.solver.stop_solver) self.solver.analysis.finished_signal.signal_finished.connect(self.simulationFinished) self.solver.analysis.filename_signal.signal_filename.connect(self.__automaticaly_load_solution_file) self.solver.analysis.solution_signal.solution_data.connect(self.__automaticaly_load_solution_file) self.solver.analysis.solution_signal.solution_data.connect(self._parent.TreeViewWidget.add_solution_data) self.ui.simulationResetButton.clicked.connect(self.simulationReset) self.ui.Hmax.textChanged.connect(self.__update_Hmax) self.ui.Hmin.textChanged.connect(self.__update_Hmin) self.ui.loadSolutionFileStatus.stateChanged.connect(self.__update_loadSolutionFileWhenFinished) self.ui.currentStep_lineEdit.textChanged.connect(self.__update_currentStep) self.ui.updateStep_lineEdit.textChanged.connect(self.__update_updateStep) self.ui.endTime.textChanged.connect(self.__update_endTime) self.ui.backwardButton.clicked.connect(self.animation_backward) #clicked self.ui.forwardButton.clicked.connect(self.animation_forward) self.ui.playButton.clicked.connect(self.animationPlay) # signal repaintGL.signal_repaintGL from self.solver triggers self.opengl_widget.repaintGL self.solver.analysis.repaintGL_signal.signal_repaintGL.connect(self.opengl_widget.repaintGL) # signal for take a snapshot self.solver.analysis.save_screenshot_signal.signal_saveScreenshot.connect(self.take_snapshot) # signal time integration error self.solver.analysis.error_time_integration_signal.signal_time_integration_error.connect(self._time_integration_error) # change integration method self.ui.integrationMethodComboBox.currentIndexChanged.connect(self.selectedIntegrationMethod) self._parent.TreeViewWidget.create_animation_file.signal_createAnimationFile.connect(self._create_animation_file) # profiler self.profile = cProfile.Profile() # analysis type self.ui.analysisTypeComboBox.currentIndexChanged.connect(self._analysis_type_changed) # set analysis type to display it in combobox if self.MBD_system.analysis_type is not None: _index = self.ui.analysisTypeComboBox.findText(QtCore.QString(self.MBD_system.analysis_type.title())) self.ui.analysisTypeComboBox.setCurrentIndex(_index) # video maker thread to create video self.video_maker = VideoMaker(parent=self)
class SimulationControlWidget(QtGui.QWidget): """ Control panel GUI """ def __init__(self, MBD_system, parent=None, flags=0): """ Constructor """ super(SimulationControlWidget, self).__init__(parent) self._parent = parent self.ui = Ui_Form() self.ui.setupUi(self) self.ui.simulationStopButton.setEnabled(False) self.ui.simulationResetButton.setEnabled(False) self.ui.forwardButton.setEnabled(False) self.ui.backwardButton.setEnabled(False) self.ui.playButton.setEnabled(False) self.MBD_system = MBD_system # when simulation is finishes # automatically load solution file self.ui.loadSolutionFileStatus.setChecked(self.MBD_system.loadSolutionFileWhenFinished) # restore initial conditions self.ui.restoreInitialConditionsStatus.setChecked(self.MBD_system.restoreInitialConditionsWhenFinished) # sets opengl widget in central widget position self.opengl_widget = OpenGLWidget(MBD_system=MBD_system, parent=self._parent) self._status = "simulation" # simulation or animation # set integration method to display try: _index = self.ui.integrationMethodComboBox.findText(QtCore.QString(self.MBD_system.integrationMethod.title())) except: _index = 0 if _index != -1: self.ui.integrationMethodComboBox.setCurrentIndex(_index) else: self.ui.integrationMethodComboBox.setCurrentIndex(_index) # signals self.step_num_signal = stepSignal() self.energy_signal = EnergySignal() self.status_signal = StatusSignal() # self.graphWidget = None # self.graphWidget = GraphWidget(MBD_system=MBD_system_, parent=parent) # self.graphWidget.setWindowFlags(parent.windowFlags()) # self.graphWidget.show() # set validators to limit user input __validator_dbl = QtGui.QDoubleValidator() __validator_int = QtGui.QIntValidator() # predefined values # end time self.ui.endTime.setText(str(self.MBD_system.t_n)) self.ui.endTime.setValidator(__validator_dbl) # self.ui.simulation_progressBar.setMinimum(0) # self.ui.simulation_progressBar.setMaximum(int(1/self.MBD_system.t_n)) # self.ui.simulation_progressBar.setValue(0) # Hmax if self.MBD_system.t_n/100 < self.MBD_system.Hmax: self.MBD_system.Hmax = 0.01*self.MBD_system.t_n # Hmin self.MBD_system.evaluate_Hmin() self.ui.Hmax.setText(str(self.MBD_system.Hmax)) self.ui.Hmax.setValidator(__validator_dbl) # Hmin self.ui.Hmin.setText(str(self.MBD_system.Hmin)) self.ui.Hmin.setValidator(__validator_dbl) # abs tol self.ui.absTol.setText(str(self.MBD_system.absTol)) self.ui.absTol.setValidator(__validator_dbl) # rel tol self.ui.relTol.setText(str(self.MBD_system.relTol)) self.ui.relTol.setValidator(__validator_dbl) # tolerance for newton differences self.ui.TOL_dq_i.setText(str(self.MBD_system.TOL_dq_i)) # tolerance for constraint equations C self.ui.TOL_C.setText(str(self.MBD_system.TOL_C)) # create solver thread self.solver = Solver(MBD_system=MBD_system, parent=self)#parent self._solver_thread = QThread() self._solver_thread.start() self.solver.moveToThread(self._solver_thread) # display update self._update_display_type = "dt" # available options self._update_display_types = ["dt", "step"] # update display on every i-th simulation step self.ui.updateStep_lineEdit.setText(str(int(self.solver.analysis.update_opengl_widget_every_Nth_step))) self.ui.updateStep_lineEdit.setValidator(__validator_int) self._delta_step = self.solver.analysis.update_opengl_widget_every_Nth_step # update display on dt of simulation time # default value self._dt = self.MBD_system.t_n / 100. self.ui.currentStep_lineEdit.setEnabled(False) self.ui.currentStep_lineEdit.setValidator(__validator_int) # connections and signals self.ui.simulationStartButton.clicked.connect(self.simulationStart) self.ui.simulationStartButton.clicked.connect(self.solver.start_solver) self.ui.simulationStopButton.clicked.connect(self.simulationStop) self.ui.simulationStopButton.clicked.connect(self.solver.stop_solver) self.solver.analysis.finished_signal.signal_finished.connect(self.simulationFinished) self.solver.analysis.filename_signal.signal_filename.connect(self.__automaticaly_load_solution_file) self.solver.analysis.solution_signal.solution_data.connect(self.__automaticaly_load_solution_file) self.solver.analysis.solution_signal.solution_data.connect(self._parent.TreeViewWidget.add_solution_data) self.ui.simulationResetButton.clicked.connect(self.simulationReset) self.ui.Hmax.textChanged.connect(self.__update_Hmax) self.ui.Hmin.textChanged.connect(self.__update_Hmin) self.ui.loadSolutionFileStatus.stateChanged.connect(self.__update_loadSolutionFileWhenFinished) self.ui.currentStep_lineEdit.textChanged.connect(self.__update_currentStep) self.ui.updateStep_lineEdit.textChanged.connect(self.__update_updateStep) self.ui.endTime.textChanged.connect(self.__update_endTime) self.ui.backwardButton.clicked.connect(self.animation_backward) #clicked self.ui.forwardButton.clicked.connect(self.animation_forward) self.ui.playButton.clicked.connect(self.animationPlay) # signal repaintGL.signal_repaintGL from self.solver triggers self.opengl_widget.repaintGL self.solver.analysis.repaintGL_signal.signal_repaintGL.connect(self.opengl_widget.repaintGL) # signal for take a snapshot self.solver.analysis.save_screenshot_signal.signal_saveScreenshot.connect(self.take_snapshot) # signal time integration error self.solver.analysis.error_time_integration_signal.signal_time_integration_error.connect(self._time_integration_error) # change integration method self.ui.integrationMethodComboBox.currentIndexChanged.connect(self.selectedIntegrationMethod) self._parent.TreeViewWidget.create_animation_file.signal_createAnimationFile.connect(self._create_animation_file) # profiler self.profile = cProfile.Profile() # analysis type self.ui.analysisTypeComboBox.currentIndexChanged.connect(self._analysis_type_changed) # set analysis type to display it in combobox if self.MBD_system.analysis_type is not None: _index = self.ui.analysisTypeComboBox.findText(QtCore.QString(self.MBD_system.analysis_type.title())) self.ui.analysisTypeComboBox.setCurrentIndex(_index) # video maker thread to create video self.video_maker = VideoMaker(parent=self) def _analysis_type_changed(self): """ Function assignes new value to object attribute if it is changed by user in combo box :return: """ self.MBD_system.analysis_type = self.ui.analysisTypeComboBox.currentText().toLower() if str(self.ui.analysisTypeComboBox.currentText()).lower() == "kinematic": self.ui.integrationMethodComboBox.setEnabled(False) else: self.ui.integrationMethodComboBox.setEnabled(True) @pyqtSlot() def profile_functions(self): """ Function profiles main functions that are used in numerical integration :return: """ print "profile here" self.profile.enable() self.solver.analysis.DAE_fun.evaluate_M() self.profile.disable() self.profile.print_stats() def _time_integration_error(self): """ :return: """ QtGui.QMessageBox.critical(self._parent, "Error!", "Hmin exceeded! Procedure failed!",QtGui.QMessageBox.Ok, QtGui.QMessageBox.NoButton,QtGui.QMessageBox.NoButton) def __update_loadSolutionFileWhenFinished(self): """ """ if self.ui.loadSolutionFileStatus.isChecked(): self.MBD_system.loadSolutionFileWhenFinished = True else: self.MBD_system.loadSolutionFileWhenFinished = False def __update_currentStep(self): """ """ try: self._step = int(self.ui.currentStep_lineEdit.text()) self.MBD_system.update_coordinates_and_angles_of_all_bodies(self.q[self._step, :]) self.MBD_system.update_simulation_properties(time=self.t[self._step], step_num=self._step) self.step_num_signal.signal_step.emit(self._step) self._update_GL() except: pass def __automaticaly_load_solution_file(self, solution_data_object_ID=None, filename=None): """ Function loads solution data from input: if input is filename solution data is read from specified file if input is solution data object, solution is read from object attribute solution_data :param filename: a filename of the solution data file :param solution_data_object: a solution data object with attribute solution_data :return: None """ if self.MBD_system.loadSolutionFileWhenFinished: self.load_solution_file(solution_data_object_ID, filename) def load_solution_file(self, solution_object_id=None, filename=None): """ Function loads solution data from object (first) or from file (second) """ if solution_object_id is None: # assign solution data from solution data object to ne variable solution_data = self.solver.analysis._solution_data.load_solution_data() elif filename is not None: pass else: print "Solution data not loaded!" # if filename is not None and solution_object_id is None: # solution_data = self.solver.analysis.load_simulation_solution_from_file(filename) # assign a solution data object to pointer of object attribute for sol in self.MBD_system.solutions: if id(sol) == solution_object_id: self.MBD_system.loaded_solution = sol solution_data = sol.solution_data self.step = solution_data[:, 0] self.energy = solution_data[:, 1] self.error = solution_data[:, 2] self.dt = solution_data[:, 3] self.t = solution_data[:, 4] self.q = solution_data[:, 5:] self._step = 0 self._status = "animation" self.ui.forwardButton.setEnabled(True) self.ui.backwardButton.setEnabled(False) self.ui.playButton.setEnabled(True) self.ui.currentStep_lineEdit.setEnabled(True) self.ui.currentStep_lineEdit.setText(str(int(self._step))) self.ui.solutionFileLoaded_display.setText(filename) self.ui.numberOfSteps_lineEdit.setText(str(int(len(self.step)-1))) self._update_GL() # self.status_signal.signal_status.emit("Animation") if self.MBD_system.restoreInitialConditionsWhenFinished: self.simulationReset() def _update_GL(self): """ """ self.ui.currentStep_lineEdit.setText(str(int(self._step))) self.MBD_system.update_coordinates_and_angles_of_all_bodies(self.q[int(self._step), :]) self.opengl_widget.repaintGL(int(self._step)) # energy data signal _energy = self.energy[self._step] _energy_delta = _energy - self.energy[int(self._step)-1] self.energy_signal.signal_energy.emit(_energy, _energy_delta) def animation_forward(self): """ Go to next solution time step """ if (self._step + self._delta_step) <= self.step[-1]: self._step += int(self._delta_step) self._update_GL() self.ui.backwardButton.setEnabled(True) else: self.ui.forwardButton.setEnabled(False) def animation_backward(self): """ Return to prevouos solution time step """ if (self._step - self._delta_step) >= self.step[0]: self._step -= int(self._delta_step) self._update_GL() self.ui.forwardButton.setEnabled(True) else: self.ui.backwardButton.setEnabled(False) def take_snapshot(self): """ Create a snapshot """ captured_figure = self.opengl_widget.takeSnapShot() captured_figure.save(self.solver.analysis.screenshot_filename_abs_path + '.png', 'png') def selectedIntegrationMethod(self, int): """ Assign a selected integration method to object attribute """ self.MBD_system.integrationMethod = str(self.ui.integrationMethodComboBox.currentText()) def __update_updateStep(self): """ :return: """ self.solver.analysis.update_opengl_widget_every_Nth_step = int(self.ui.updateStep_lineEdit.text()) self._delta_step = int(self.ui.updateStep_lineEdit.text()) self.MBD_system.updateEveryIthStep = self._delta_step def __update_Hmax(self): """ :return: """ try: self.Hmax = float(self.ui.Hmax.text()) self.MBD_system.Hmax = self.Hmax # self.solver.update_simulation_control_parameters(dt_=self.stepSize) except: None def __update_Hmin(self): try: self.Hmin = float(self.ui.Hmin.text()) self.MBD_system.Hmin = self.Hmin self.solver.update_simulation_control_parameters(dt_=self.stepSize) except: None def __update_endTime(self): """ :return: """ self.endTime = float(self.ui.endTime.text()) self.MBD_system.t_n = self.endTime def setWindowFlags(self, flags): super(SimulationControlWidget, self).setWindowFlags(flags) def simulationStart(self): if not self.solver.analysis.running: self.job_info_time_started = time.clock() self.solver.analysis.running = True self.solver.analysis.stopped = False self.solver.analysis.finished = False self.ui.simulationStartButton.setEnabled(False) self.ui.simulationResetButton.setEnabled(False) self.ui.simulationStopButton.setEnabled(True) def simulationStop(self): if self.solver.analysis.running: self.solver.analysis.stopped = True self.ui.simulationStartButton.setEnabled(True) self.ui.simulationStopButton.setEnabled(False) self.ui.simulationResetButton.setEnabled(True) def simulationFinished(self): self.ui.simulationStopButton.setEnabled(False) self.ui.simulationResetButton.setEnabled(True) self.job_info_time_finished = time.clock() def simulationReset(self): self.solver.analysis.restore_initial_condition() # self.ui.simulationResetButton.setEnabled(False) self.ui.simulationStartButton.setEnabled(True) def animationPlay(self): """ Function plays animation when solution data is loaded :return: """ if self._update_display_type == "step": for _step in xrange(0, len(self.step), int(self._delta_step)): self._step = int(_step) self._update_GL() time.sleep(self.ui.playbackSpeed_doubleSpinBox.value()*1E-2) if self._update_display_type == "dt": _t = np.arange(0, self.t[-1], self._dt) for i in xrange(0, len(_t)): indx = np.argmin(abs(self.t - _t[i])) self._step = self.step[indx] self._update_GL() time.sleep(self.ui.playbackSpeed_doubleSpinBox.value()*1E-2) def _create_animation_file(self): """ Function creates video file of animation :return: """ # starts video maker in new thread self.video_maker.start()
from solver.solver import Solver solver = Solver() solver.train()
def __init__(self, data_dir): self.jinja_env = Environment( loader=PackageLoader('webserver', 'templates')) self.solver = Solver(data_dir, 100000) self.game_words = self.solver.filter_in_vocab(load_game_words())