def test_reward(self):
        model_keys = ["000000100", "000210100", "020112001"]

        model_probs = ["112111011", "211001011", "101000120"]
        model = Model(load_model=False)

        for i, k in enumerate(model_keys):
            model.states[k] = self.to_int_list(model_probs[i])

        ai_keys = ["001000000", "001012000", "001112020"]
        ai_boards = [
            BoardState.from_board(self.to_int_list(s)) for s in ai_keys
        ]

        ai_moves = [5, 7, 1]
        progress = list(zip(ai_boards, ai_moves))

        model.reward(progress, Result.X_WINS)

        target_probs = ["110110211", "110100102", "110000101"]
        target_probs = [
            list(map(float, self.to_int_list(p))) for p in target_probs
        ]

        self.assertEqual(len(model.states), len(model_keys),
                         "Too much state entries in model.")

        for i, k in enumerate(ai_keys):
            model_probs = model.states[k]
            self.assertEqual(model_probs, target_probs[i])
    def on_run_regex(self):
        """ Passes clinician note file to Model """

        self.phrases = self.regex_text.get(1.0, 'end-1c').strip()

        # GETS FILE NAMe, passes global path to ReadRPDR
        file_loc = self.data_model.input_fname
        self.dirname = os.path.dirname(file_loc)

        opts = {
            'r_encoding': 'utf-8',
            'preserve_header': True,
            'patient_id': self.patient_id_entry.get(),
            'note_key': self.note_key_entry.get(),
            'rpdr': self.rpdr_checkbox.var.get()
        }

        phrases = [p.strip() for p in self.phrases.split(",")]

        self.model = Model(options_=opts,
                           file_location_=file_loc,
                           keywords_=phrases)

        if self.checkvar:

            self.num_notes = self.model.get_num_notes_positive()

        else:

            self.num_notes = self.model.get_num_notes()

        first_note, index = self.model.first(self.checkvar)

        self.display_output_note(first_note, index)
Exemple #3
0
def main():
    f = open("iris.dataset")
    dataset = [[(float(x)) for x in line.split(" ")] for line in f]
    dataset = dataset[0:150]
    f.close()

    model = Model(0.2, [4, 10, 3])

    # k-fold cross validation
    k = 5
    fold = []
    fold_len = int(len(dataset) / k)
    # print(dataset)
    for i in range(0, k):
        r = {
            'validation_data': dataset[0:fold_len],
            'training_data': dataset[fold_len:len(dataset)]
        }
        fold.append(r)
        dataset = shift(dataset, -fold_len)

    print("init weights:", model.layer_weights)

    for j in range(0, k):
        print(fold[j]['training_data'])
        model.train(fold[j]['training_data'], fold[j]['validation_data'], 100)

    print("final weights:", model.layer_weights)

    plt.plot(model.error)
    plt.plot(model.accuracy)
    plt.xlabel('epoch')
    plt.yscale('log')
    plt.legend(['Error', 'Accuracy'], loc='upper left')
    plt.show()
Exemple #4
0
def main(config) -> None:
    logger.info(f"\n{config.pretty()}")

    pl.seed_everything(config.hparams.seed)

    datamodule = MNISTDataModule(
        data_dir=config.dataset.path,
        batch_size=config.hparams.batch_size,
        num_workers=config.hparams.num_workers,
    )

    trainer = pl.Trainer(
        **config.trainer,
        checkpoint_callback=ModelCheckpoint(**config.model_checkpoint),
        callbacks=[EarlyStopping(**config.early_stopping)]
        + [hydra.utils.instantiate(i) for i in config.callbacks],
        logger=[hydra.utils.instantiate(i) for i in config.loggers],
        auto_lr_find=config.hparams.lr == 0,
    )

    model = Model(**config.hparams)

    trainer.tune(model, datamodule=datamodule)
    assert model.hparams.lr > 0, f'model.hparams.lr > 0={model.hparams.lr > 0}'
    config.hparams.lr = model.hparams.lr

    # 更新したhparamsをlogに出力するには↓がいる
    model = Model(**config.hparams)

    trainer.fit(model, datamodule=datamodule)
    trainer.test()
def calc_operating_income(new_trucks: int, num_customers: float) -> float:
    # initialize the model
    model = Model()
    model.inputs.num_customers = num_customers

    # get total trucks, demand, and the trucks needed to serve it
    model.inputs.trucks_total = (model.operations.productivity.avg_num_trucks +
                                 new_trucks)
    trucks_utilized = min([model.trucks_required(), model.inputs.trucks_total])

    available_capacity_per_truck = (
        model.inputs.lifts_per_truck_day *
        model.operations.avg_vol_per_lift() *
        model.operations.productivity.working_days_per_year)

    # what demand is met
    served_demand = model.demand_served()
    revenue = served_demand * model.inputs.revenue_per_m3
    disposal_cost = model.new_disposal_cost()

    # depot related costs
    depot_overhead = model.depot_overhead_cost(
        model.inputs.trucks_total)  # assume each depot incurs OH
    depot_labor = model.depot_labor_cost(
        trucks_utilized)  # but only "active" ones incur labor cost

    # driver costs
    driver_labor = model.driver_labor_cost(trucks_utilized)

    # fuel and maintenance
    fuel = model.fuel_cost(trucks_utilized)
    maintenance = model.maintenance_cost(trucks_utilized)

    return (revenue - disposal_cost - depot_overhead - depot_labor -
            driver_labor - fuel - maintenance)
Exemple #6
0
    def test_tensor_size_valid(self) -> None:
        t1: torch.Tensor = torch.tensor([1, 2])

        same_size: bool = Model._tensor_size_valid(t1, [2])
        diff_size: bool = Model._tensor_size_valid(t1, [3])

        self.assertTrue(same_size)
        self.assertFalse(diff_size)
Exemple #7
0
    def __init__(self, loop):
        self.loop = loop

        controller = Controller()
        self.model = Model(controller=controller)
        view = View(controller=controller)
        controller.segundo_init(model=self.model, view=view)
        self.model.segundo_init()
Exemple #8
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--mel-path')
    args = parser.parse_args()
    print('Loading model')
    model = Model(FITTED_MODEL_PATH)
    print('Successfully loaded model')
    preds = model.predict(args.mel_path)
    print(preds)
Exemple #9
0
def test_model_predict():
    """Test if model can extract entities and accompanying sentence"""
    with open("tests/processed_html_text.txt", "r", encoding="utf-8") as f:
        data = f.read()

    model = Model()
    output = model.predict(data)

    assert len(output) > 0, "model did not return any prediction"
    assert len(output[0]) == 2, "model did not return entity and sentence"
Exemple #10
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.view = Ui_View()
        self.mainwindow = QMainWindow()
        self.model = Model()

        self.view.setupUi(self.mainwindow)
        self.setFixedSize(620, 250)
        self.setup_signals()
 def test_discrete_line(self):
     self.assertSequenceEqual(Model.discrete_line(Point(1, 2), Point(3, 6)),
                              [Point(1, 2), Point(1, 3), Point(2, 3), Point(2, 4), Point(2, 5), Point(3, 5),
                               Point(3, 6)])
     self.assertSequenceEqual(Model.discrete_line(Point(1, 1), Point(4, 4)),
                              [Point(1, 1), Point(2, 2), Point(3, 3), Point(4, 4)])
     self.assertSequenceEqual(Model.discrete_line(Point(1, 1), Point(1, 4)),
                              [Point(1, 1), Point(1, 2), Point(1, 3), Point(1, 4)])
     self.assertSequenceEqual(Model.discrete_line(Point(1, 4), Point(1, 1)),
                              [Point(1, 4), Point(1, 3), Point(1, 2), Point(1, 1)])
Exemple #12
0
def main(config):

    config_proto = tf.ConfigProto()
    config_proto.gpu_options.allow_growth = True
    sess = tf.InteractiveSession(config=config_proto)
    dataloader = Dataloader(sess, config, prefetch_buffer_size=10)
    model = Model(sess, dataloader, config)
    model.build_model()
    logger = Logger(sess, config)
    trainer = Trainer(sess, model, dataloader, logger, config)
    trainer.train()
Exemple #13
0
 def __init__(self):
     self.iteration_number = 0
     self.solution_type = ""
     self.solution_name = ""
     self.model = Model()
     self.solver_data = SolverData()
     self.data = DataStore()
     self.iteration_results = IterationResults()
     self.sequence_list = SequenceList()
     self.current_sequence = Sequence()
     self.iteration_saved = False
def main(model_dir, data_dir):

    best_train_result_path = os.path.join(model_dir, "best03.pth")

    checkpoint = torch.load(best_train_result_path)

    model = Model().cuda()
    model.load_state_dict(checkpoint["model"])

    input = torch.randn(1, 3, 96, 96, device='cuda')

    torch.onnx.export(model, input, './model.onnx')
Exemple #15
0
    def get(self):
        '''
        Import the model
            write prediction module
                outputs datetime, price, trade amount as JSON
        pull data from poloniex
        use model.prediction
        return model.prediction output
        '''
        m = Model(symbols=['BTC'])

        return m.predict_for_api(5900, self.funds)
        def search_t(mock_key, test_key):
            mock_probs = self.mock_state_probs(mock_key)
            model = Model(load_model=False)
            model.states[mock_key] = mock_probs

            searched_board = self.to_int_list(test_key)
            searched_board_state = BoardState.from_board(searched_board)

            for _ in range(0, 100):
                picked_move = model.pick_move(searched_board_state, 1)
                self.assertEqual(
                    searched_board[picked_move], 0,
                    "Search Error with keys " + mock_key + " and " + test_key)
Exemple #17
0
    def solve_data_set(self):
        self.model = Model()
        self.model.set_data(self.solver_data.data_set_number, self.data)
        self.annealing.set_data_set_number(self.solver_data.data_set_number,
                                           self.data)
        self.annealing.start_sequence1()
        self.annealing.sequence.set_sequences()

        self.model.current_sequence = self.annealing.next_sequence()
        self.model.set_sequence()
        # calculate sequence
        #self.model.current_sequence = self.current_sequence
        self.model.solve()
def prepare(
    test_path=params["common"]["test-path"],
    train_path=params["common"]["train-path"],
    data_path=params["common"]["all-data-path"],
    indices_path=params["common"]["indices-path"],
    output_path=params["train"]["output-path"],
    model_output_path=params["train"]["model-output-path"],
    lowercase=params["train"]["lowercase"],
    seq_length=params["train"]["seq-length"],
    num_words=params["train"]["num-words"],
    oov_token=params["train"]["oov-token"],
    padding_style=params["train"]["padding-style"],
    trunc_style=params["train"]["trunc-style"],
    test_prop=params["prepare"]["test-prop"],
):
    for path in [
            output_path,
            model_output_path,
            os.path.split(data_path)[0],
            os.path.split(test_path)[0],
            os.path.split(train_path)[0],
    ]:
        os.makedirs(path, exist_ok=True)

    model = Model(
        output_path=output_path,
        model_output_path=model_output_path,
        seq_length=int(seq_length),
    )

    # Load the data from disk

    model.load_data(data_path, test_prop)

    # Prepare the data with tokenisation, padding, etc.

    model.prep_data(
        oov_token=oov_token,
        trunc_style=trunc_style,
        padding_style=padding_style,
        num_words=int(num_words),
        lowercase=lowercase,
    )

    # Save the intermediate objects to disk

    model.save_indices(indices_path)

    # Save split data to disk as np arrays

    model.save_train_test_data(test_path, train_path)
Exemple #19
0
    def _loadFromFile(self):
        """
        It opens a dialog to load a xml file, which is then parsed and shown
        in the main window.
        """

        fileName = QFileDialog.getOpenFileName(self, 'Open file',
                                               '../puzzles/')[0]
        # continue only if some file was really loaded
        if len(fileName) > 0:
            self.model = Model(fileName)
            self._showModel()
            self.rawHeuristicAction.setEnabled(True)
            self.solveAction.setEnabled(True)
def main():
    alpha = 1.5
    mu = 0.8

    model = Model(alpha, mu)
    curr = (1.5, 1.5)
    values = [curr[0]]
    count = 100
    while curr[0] > 0 and count > 0:
        curr = model.next(curr)
        values.append(curr[0])
        count -= 1
    points = list(enumerate(values))
    write_to_files('../files/time_series', points)
Exemple #21
0
def main(config) -> None:
    all_done = False
    try:
        logger.info('\n' + OmegaConf.to_yaml(config))

        shutil.copytree(
            Path(hydra.utils.get_original_cwd()) / 'src',
            Path.cwd() / 'copied' / 'src')

        pl.seed_everything(config.hparams.seed)

        datamodule = hydra.utils.instantiate(config.data.datamodule)

        trainer = pl.Trainer(
            **config.trainer,
            checkpoint_callback=ModelCheckpoint(**config.model_checkpoint),
            callbacks=[EarlyStopping(**config.early_stopping)] +
            [hydra.utils.instantiate(i) for i in config.callbacks],
            logger=[hydra.utils.instantiate(i) for i in config.loggers],
            auto_lr_find=config.hparams.lr == 0,
        )

        model = Model(**config.hparams)
        torchsummary.summary(model)

        trainer.tune(model, datamodule=datamodule)
        if config.debug == True:
            # fast_dev_runモードではauto_lr_findが失敗し,model.hparams.lrにNoneが代入される
            assert model.hparams.lr is None
            model.hparams.lr = 1
        assert model.hparams.lr > 0, f'model.hparams.lr > 0={model.hparams.lr > 0}'
        config.hparams.lr = model.hparams.lr

        # 更新したhparamsをロガーに出力するには↓がいる
        model = Model(**config.hparams)

        trainer.fit(model, datamodule=datamodule)
        trainer.test()

        logger.info('All done.')
        all_done = True
    finally:
        if all_done == False:
            path = Path.cwd()
            if 'outputs' in path.parts or 'multirun' in path.parts:
                logger.info(
                    f'Rename directory name. "{path}" -> "{path}__interrupted"'
                )
                path.rename(path.parent / (path.name + '__interrupted__'))
Exemple #22
0
def create_model(args, device, logger, storage, storage_test):

    start_time = time.time()
    model = Model(args, logger, storage, storage_test, model_type=args.model_type)
    logger.info(model)
    logger.info('Trainable parameters:')

    for n, p in model.named_parameters():
        logger.info('{} - {}'.format(n, p.shape))

    logger.info("Number of trainable parameters: {}".format(utils.count_parameters(model)))
    logger.info("Estimated size (under fp32): {:.3f} MB".format(utils.count_parameters(model) * 4. / 10**6))
    logger.info('Model init {:.3f}s'.format(time.time() - start_time))

    return model
Exemple #23
0
def gen_data() -> pd.DataFrame:
    model = Model()
    # assume their performance slips
    model.inputs.lifts_per_truck_day = 10
    current_customers = model.inputs.num_customers
    customers_3x = current_customers * 3
    n_customers = range(current_customers, customers_3x, 500)
    roics = []
    for n in n_customers:
        model.inputs.num_customers = n
        model.set_trucks()
        r = model.new_roic()
        roics.append(r)

    return pd.DataFrame({"customers": n_customers, "ROIC": roics})
    def __init__(self, list_players, start_money):
        QObject.__init__(self)

        self.gui = ViewMainFrame(list_players, start_money)
        self.gui.show()
        self.m = Model(list_players, start_money)

        # Signals
        self.gui.central_widget.sig_player_bank = self.sig_bank_player
        self.sig_bank_player.connect(self.player_bank)

        self.gui.central_widget.sig_trade = self.sig_trade
        self.sig_trade.connect(self.player_trade)

        self.list_players = list_players
Exemple #25
0
    def generate(self, solution: Solution[Model]) -> Solution[Model]:
        model = solution.getvalue()
        connection: torch.Tensor = model.connection
        weight: torch.Tensor = model.weight
        self.device = model.device

        connection, weight = self._regulate_neural(connection,
                                                   weight,
                                                   removable=model.input_dim +
                                                   model.output_dim)
        flip_mask = torch.ones_like(connection) * self.possibility_of_invert
        flip_mask = torch.bernoulli(flip_mask).to(torch.int8)
        new_connection = connection.to(torch.int8).__xor__(flip_mask)

        uniform_from_distance = torch.empty_like(weight).uniform_(
            -1 * self.distance, self.distance)
        new_weight = weight + uniform_from_distance

        new_model = Model(
            model.activation, model.input_dim, model.output_dim,
            connection.size()[0] - model.input_dim - model.output_dim,
            new_connection, new_weight, model.delay, model.device)

        return Solution(new_model, solution.get_generator(),
                        solution.get_evaluator())
Exemple #26
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model", default="assets/model/model.h5")
    parser.add_argument("--total-samples", type=int, default=10)

    args = parser.parse_args()

    from src.app import D3DScreenshot, MSSScreenshot
    bounding_box = (0, 0, 400, 500)
    d3d_screenshotter = D3DScreenshot()
    mss_screenshotter = MSSScreenshot()

    print("Taking {:d} samples".format(args.total_samples))

    dt = profile_time(d3d_screenshotter.get_screen_shot,
                      args.total_samples)(bounding_box)
    print("D3D took {:.02f}ms".format(dt * 1000))

    dt = profile_time(mss_screenshotter.get_screen_shot,
                      args.total_samples)(bounding_box)
    print("MSS took {:.02f}ms".format(dt * 1000))

    from src.model import Model
    model = Model.load(args.model)
    test_image = np.full((1, 160, 227, 3), 125) / 255
    dt = profile_time(model.predict, args.total_samples)(test_image)
    print("Model took {:.02f}ms".format(dt * 1000))
Exemple #27
0
def update_alphas(generic_model, model_name, model_configs, alpha, l1_ratio,
                  prefix):

    refined_alphas = model_configs['update_alphas'] * alpha
    refined_l1_ratios = model_configs['update_alphas'] * l1_ratio

    if model_name == 'Ridge':
        model = generic_model(alphas=refined_alphas,
                              cv=model_configs['cross_val'])

    elif model_name == 'Lasso':
        model = generic_model(alphas=refined_alphas,
                              cv=model_configs['cross_val'],
                              max_iter=model_configs['max_iter'])

    elif model_name == 'ElasticNet':

        model = generic_model(l1_ratio=refined_l1_ratios,
                              alphas=refined_alphas,
                              cv=model_configs['cross_val'],
                              max_iter=model_configs['max_iter'])

    model = Model(model,
                  model_name,
                  prefix,
                  cross_val=model_configs['cross_val'])
    return model
Exemple #28
0
def run_cv(data, target, base_model, params, tags, k=5):
    """
    Performing a CV training

    Args:
        data (pd.DataFrame):        DataFrame with the filtered data
        target (str):               Name of the prediction target.              
        base_model (sklearn model): Scikit-learn object that will be used as base model for training.
      
    Returns:
        model:                      Trained model
        metrics (dict):             Dictionary with all the metrics for the model
    """
    experiment_name = "StockForecasting_PROD"

    print('{:=^80}'.format('  RUN  '))
    print("Starting RUN on project {}.".format(experiment_name))

    # Init model
    norm = Normalize()
    pipeline = Pipeline([("norm", norm), ("model", base_model)])
    model = Model(pipeline)

    # Get CV metrics
    cv_metrics = cross_validate(model, data, target, k)
    print(cv_metrics)

    # Log in mlflow with no artifacts
    log_mlflow(experiment_name, None, params, cv_metrics, tags)

    return cv_metrics
Exemple #29
0
def run(app):
    dir_name = os.path.dirname(__file__)
    os.environ['QML_IMPORT_PATH'] = os.path.join(dir_name, 'resources')
    os.environ['QML2_IMPORT_PATH'] = os.path.join(dir_name, 'resources')

    #QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)

    # Create the application instance.
    #app = QGuiApplication(sys.argv)

    # Create QML engine
    engine = QQmlApplicationEngine()
    context = engine.rootContext()

    # Testor
    manage = ManageThreads()
    context.setContextProperty("manage", manage)

    # Model
    TestorModel = Model()
    manage.runtimeSig.connect(TestorModel.addData)
    context.setContextProperty("TestorModel", TestorModel)

    engine.load(QUrl('src/resources/main.qml'))

    engine.quit.connect(app.quit)
    sys.exit(app.exec_())
Exemple #30
0
class Controller(QWidget):
    """
    MVC Pattern: Represents the controller class

    """
    def __init__(self, parent=None):
        super().__init__(parent)

        self.view = Ui_View()
        self.mainwindow = QMainWindow()
        self.model = Model()

        self.view.setupUi(self.mainwindow)
        self.setFixedSize(620, 250)
        self.setup_signals()

    def setup_signals(self):
        self.view.open.clicked.connect(lambda: self.open_clicked())

    def open_clicked(self):
        fname = QFileDialog.getOpenFileName(self.mainwindow, 'Öffnen ...',
                                            os.getcwd())
        csv = self.model.read_csv(fname[0], delimiter=';')
        self.view.text_area.clear()
        self.view.text_area.insertPlainText(csv)
Exemple #31
0
def main():
    # Load train dataset
    data = dataLoader(directory='./dataset/captcha', dataset_dir='train',\
                      dataset_name='train.txt', max_steps=6, image_width=200,\
                      image_height=64, grd_attn=True, mode='Train')
    # Load Model
    model = Model(dim_feature=[672, 128],
                  dim_hidden=128,
                  n_time_step=8,
                  alpha_c=1.0,
                  image_height=64,
                  image_width=200,
                  mode='train')
    # Load Trainer
    trainer = Train(model,
                    data,
                    val_data=None,
                    n_epochs=1000,
                    batch_size=64,
                    update_rule='adam',
                    learning_rate=0.0001,
                    print_every=100,
                    save_every=5,
                    pretrained_model=None,
                    model_path='model/lstm1/',
                    log_path='log1/')
    # Begin Training
    trainer.train()
    def __init__(self, parent=None):
        super().__init__(parent)

        self.view = Ui_View()
        self.mainwindow = QMainWindow()
        self.model = Model()

        self.view.setupUi(self.mainwindow)
        self.setFixedSize(620, 250)
        self.setup_signals()
 def __init__(self):
     self.iteration_number = 0
     self.solution_type = ""
     self.solution_name = ""
     self.model = Model()
     self.solver_data = SolverData()
     self.data = DataStore()
     self.iteration_results = IterationResults()
     self.sequence_list = SequenceList()
     self.current_sequence = Sequence()
     self.iteration_saved = False
    def test_fitness(self):
        terrain_map = [
            [0.1, 0.1, 0.1, 0.1, 0.1],
            [0.1, 1, 1,  0.1, 0.1],
            [1, 1, 1, 0.1, 1],
            [1, 1, 0.1, 0.1, 1],
            [1, 1, 0.1, 0.1, 0.1]
        ]

        start = Point(3, 4)
        finish = Point(0, 1)
        model = Model(terrain_map, n_turns=3, start=start, finish=finish,
                      weight_segment=1, weight_turn=0)

        turns = [Point(*x) for x in [(3, 2), (3, 0), (1, 0)]]

        fitness = model.get_fitness(turns)

        # self.assertAlmostEqual(fitness, 6 + math.sqrt(2))
        self.assertAlmostEqual(fitness, 4.4) #TODO wyliczyc co tu powinno
    def solve_data_set(self):
        self.model = Model()
        self.model.set_data(self.solver_data.data_set_number, self.data)
        self.annealing.set_data_set_number(self.solver_data.data_set_number, self.data)
        self.annealing.start_sequence1()
        self.annealing.sequence.set_sequences()

        self.model.current_sequence = self.annealing.next_sequence()
        self.model.set_sequence()
        # calculate sequence
        #self.model.current_sequence = self.current_sequence
        self.model.solve()
    def test_segments(self):
        terrain_map = [
            [0, 0, 0, 0, 0],
            [0, 1, 1, 0, 0],
            [1, 1, 1, 0, 1],
            [1, 1, 0, 0, 1],
            [1, 1, 0, 0, 0]
        ]

        start = (3, 4)
        finish = (0, 1)
        model = Model(terrain_map, n_turns=3, start=start, finish=finish,
                      weight_segment=1, weight_turn=1)

        turns = [(3, 2), (3, 0), (1, 0)]
        # turns = [Point(*x) for x in turns]
        expected = [((3, 4), (3, 2)),
                    ((3, 2), (3, 0)),
                    ((3, 0), (1, 0)),
                    ((1, 0), (0, 1))]
        # expected = [(Point(*x), Point(*y)) for x, y in expected]
        self.assertSequenceEqual(model._segments(turns), expected)
    def solve_simluation(self):
        self.model = Model()
        self.model.simulator = self.simulator
        self.model.simulation_on = True
        self.model.set_data(self.solver_data.data_set_number, self.data)
        self.simulator.reset()
        self.simulator.trucks = self.model.all_trucks
        self.simulator.doors = self.model.all_doors
        self.simulator.station = self.model.station
        self.annealing.set_data_set_number(self.solver_data.data_set_number, self.data)
        self.annealing.start_sequence1()
        self.annealing.sequence.set_sequences()

        self.model.current_sequence = self.annealing.next_sequence()
        self.model.set_sequence()

        self.model.solve()
class Controller(QWidget):
    """
    MVC Pattern: Represents the controller class

    """
    def __init__(self, parent=None):
        super().__init__(parent)

        self.view = Ui_View()
        self.mainwindow = QMainWindow()
        self.model = Model()

        self.view.setupUi(self.mainwindow)
        self.setFixedSize(620, 250)
        self.setup_signals()

    def setup_signals(self):
        self.view.open.clicked.connect(lambda: self.open_clicked())

    def open_clicked(self):
        fname = QFileDialog.getOpenFileName(self.mainwindow, 'Öffnen ...', os.getcwd())
        csv = self.model.read_csv(fname[0], delimiter=';')
        self.view.text_area.clear()
        self.view.text_area.insertPlainText(csv)
    def test_angle_metric_order(self):
        """Test that the closer the angle is to straight line, the smaller it costs is"""
        terrain_map = [[1]*6 for _ in range(7)]
        A = Point(0, 0)
        B = Point(1, 2)
        C = Point(3, 4)
        D = Point(2, 1)
        E = Point(3, 5)
        F = Point(0, 3)
        model = Model(terrain_map, None, None, None, None, None,
                      turn_penalty=lambda x: x**2)
        gentle_angle_weight = model._calculate_turn_penalty([A, B], [B, C])
        harsh_angle_weight = model._calculate_turn_penalty([A, B], [B, D])
        self.assertLess(gentle_angle_weight, harsh_angle_weight)

        zero_angle_weight = model._calculate_turn_penalty([A, B], [B, A])
        self.assertLess(harsh_angle_weight, zero_angle_weight)

        straight_angle_weight = model._calculate_turn_penalty([A, B], [B, E])
        self.assertLess(straight_angle_weight, gentle_angle_weight)

        medium_angle_weight = model._calculate_turn_penalty([A, B], [B, F])
        self.assertLess(medium_angle_weight, harsh_angle_weight)
import sys
src_directory = '../../../'
sys.path.append(src_directory)

from src.model import Model
from pylab     import zeros, linspace, sqrt
from dolfin    import project, Function, File, as_vector

nx = 40
ny = 40
nz = 7

model = Model()
model.generate_uniform_mesh(nx,ny,nz,0,1,0,1,deform=False,generate_pbcs=True)

Q = model.Q
U_obs = project(dolfin.as_vector([Function(Q),Function(Q)]))
b_obs = Function(Q)
U_opt = project(as_vector([Function(Q),Function(Q),Function(Q)]))
b_opt = Function(Q)

rcParams['text.usetex']=True
rcParams['font.size'] = 12
rcParams['font.family'] = 'serif'

for L in [10000]:
    
    File('./results/U_obs.xml') >> U_obs
    File('./results/U_opt.xml') >> U_opt
    File('./results/beta2_obs.xml') >> b_obs
    File('./results/beta2_opt.xml') >> b_opt
class Solver(QObject):

    def __init__(self,  data=DataStore(), solver_data=SolverData()):
        QObject.__init__(self)
        self.data = data
        self.solver_data = solver_data
        self.annealing = Annealing(self.data)
        self.current_iteration = 0

    def solve_data_set(self):
        self.model = Model()
        self.model.set_data(self.solver_data.data_set_number, self.data)
        self.annealing.set_data_set_number(self.solver_data.data_set_number, self.data)
        self.annealing.start_sequence1()
        self.annealing.sequence.set_sequences()

        self.model.current_sequence = self.annealing.next_sequence()
        self.model.set_sequence()
        # calculate sequence
        #self.model.current_sequence = self.current_sequence
        self.model.solve()

    def solve_simluation(self):
        self.model = Model()
        self.model.simulator = self.simulator
        self.model.simulation_on = True
        self.model.set_data(self.solver_data.data_set_number, self.data)
        self.simulator.reset()
        self.simulator.trucks = self.model.all_trucks
        self.simulator.doors = self.model.all_doors
        self.simulator.station = self.model.station
        self.annealing.set_data_set_number(self.solver_data.data_set_number, self.data)
        self.annealing.start_sequence1()
        self.annealing.sequence.set_sequences()

        self.model.current_sequence = self.annealing.next_sequence()
        self.model.set_sequence()

        self.model.solve()

    def simulation_step(self):
        self.model.solve()
 def new_model(self):
     self.model = Model()
M_max = 0.5

T_min = 238.15
S_T = 1.67e-5

class MassBalance(Expression):
  def eval(self,values,x):
    values[0] = min(M_max,S_b*(R_el-sqrt(x[0]**2 + x[1]**2))) 

class SurfaceTemperature(Expression):
  def eval(self,values,x):
    values[0] =  T_min + S_T*sqrt(x[0]**2 + x[1]**2)

mesh  = MeshFactory.get_circle()

model = Model()
model.set_mesh(mesh, deform=False)

Surface = Expression('S_0', S_0 = S_0, element = model.Q.ufl_element())
Bed     = Expression('0.0', element = model.Q.ufl_element())

model.set_geometry(Surface, Bed)
model.deform_mesh_to_geometry()

model.set_parameters(IceParameters())
model.initialize_variables()

nonlin_solver_params = default_nonlin_solver_params()
nonlin_solver_params['newton_solver']['relaxation_parameter'] = 1.0
nonlin_solver_params['newton_solver']['absolute_tolerance']   = 1.0
nonlin_solver_params['newton_solver']['linear_solver']        = 'gmres'
class GeneralSolver(object):

    def __init__(self):
        self.iteration_number = 0
        self.solution_type = ""
        self.solution_name = ""
        self.model = Model()
        self.solver_data = SolverData()
        self.data = DataStore()
        self.iteration_results = IterationResults()
        self.sequence_list = SequenceList()
        self.current_sequence = Sequence()
        self.iteration_saved = False

    def new_model(self):
        self.model = Model()

    def set_data(self, solver_data=SolverData(), data=DataStore()):
        self.new_model()
        self.solver_data = solver_data
        self.data = data
        self.model.set_data(solver_data, data)
        self.sequence_algorithms = SequenceAlgorithm(data)
        self.sequence_algorithms.set_data_set_number(solver_data.data_set_number,data)

    def set_sequence(self, sequence=Sequence()):
        self.current_sequence = sequence
        self.sequence_list.add_sequence(self.current_sequence)
        self.model.set_sequence(self.current_sequence)
    # gets a sequence and sets model

    def solve_iteration(self):
        while not self.iteration_saved:
            if not self.model.check_done():
                self.model.next_time()
                #print(self.model.current_time)
            else:
                self.iteration_saved = True
                self.save_results(self.model)


    def start_iteration(self):
        self.model.reset_model()
        # start model solve

    def step_forward(self):
        """
        moves the model forward
        """
        if not self.model.check_done():
            self.model.next_time()
            return True
        else:
            self.save_results(self.model)
            return False

    def save_results(self, model):
        pass
 def _angle_tester(self, A, B, P, expected):
         ang = Model._angle((A, P), (P, B))
         self.assertAlmostEqual(ang, expected)
             'adjoint' :
             { 
               'alpha'               : None,
               'beta'                : None,
               'max_fun'             : None,
               'objective_function'  : 'logarithmic',
               'animate'             : False
             }}


  nx = 50
  ny = 50 
  nz = 10
  

  model = Model()
  model.generate_uniform_mesh(nx, ny, nz, xmin=0, xmax=L, ymin=0, ymax=L, 
                              generate_pbcs=True)
  
  Surface = Expression('- x[0] * tan(alpha)', alpha=alpha, 
                       element=model.Q.ufl_element())
  Bed     = Expression(  '- x[0] * tan(alpha) - 1000.0 + 500.0 * ' \
                       + ' sin(2*pi*x[0]/L) * sin(2*pi*x[1]/L)',
                       alpha=alpha, L=L, element=model.Q.ufl_element())
  
  model.set_geometry(Surface, Bed, deform=True)
  model.set_parameters(IceParameters())
  model.initialize_variables()
   
  F = SteadySolver(model, config)
  F.solve()
             'T_ma'   : None,
             'T_ju'   : None,
             'beta_w' : None,
             'sigma'  : None,
             'precip' : None
           },
           'adjoint' :
           { 
             'alpha'              : None,
             'beta'               : None,
             'max_fun'            : None,
             'objective_function' : 'logarithmic',
             'animate'            : False
           }}

model = Model()
model.set_geometry(Surface(), Bed())

mesh      = MeshFactory.get_circle()
flat_mesh = MeshFactory.get_circle()
model.set_mesh(mesh, flat_mesh=flat_mesh, deform=True)

model.mesh.coordinates()[:,2] = model.mesh.coordinates()[:,2]/1000.0
model.set_parameters(IceParameters())
model.initialize_variables()

F = SteadySolver(model,config)
F.solve()

T = TransientSolver(model,config)
T.solve()