Example #1
0
    def store_model_and_advance(self):
        # 'save' the model (by parsing the ReactionEntryPanel widgets) and push it up
        # to the 'main' app, so that other pages have access to the model
        reaction_strings_dict = {}
        for reaction_id, reaction_widget in self.current_reaction_widget_dict.items(
        ):

            reactant_str = reaction_widget.reactants.get()
            product_str = reaction_widget.products.get()
            ka = reaction_widget.ka.get()
            kd = reaction_widget.kd.get()
            direction_symbol = reaction_widget.direction_symbol.get()
            reaction_strings_dict[reaction_id] = '%s %s %s, %s, %s' % (
                reactant_str, direction_symbol, product_str, ka, kd)

        try:

            # even if the model was loaded from a file (with initial conditions, etc) the user could have edited it,
            # so we get the most recent state here.  However, in the case that the model was loaded from a file, a model
            # instance exists somewhere.  We *might* be able to get initial conditions and/or simulation time from that
            # We then insert those parameters into the 'new' Model instance below
            reaction_factory = reaction_factories.GUIReactionFactory(
                reaction_strings_dict)
            model = models.Model(reaction_factory)

            # if we happened to load the data from a file, get any initial conditions from that
            if self.model:
                initial_conditions_from_file = self.model.get_initial_conditions(
                )
                initial_conditions_from_file = {
                    x: initial_conditions_from_file[x]
                    for x in initial_conditions_from_file.keys()
                    if x in model.get_all_species()
                }
                model.set_initial_conditions(initial_conditions_from_file)
                simulation_time_from_file = self.model.get_simulation_time()
                model.set_simulation_time(simulation_time_from_file)

            self.controller.set_model(model)

            # move on to the next page
            self.controller.show_frame(self.order_index + 1)
            self.submission_error_text.set('')
        except Exception as ex:
            print ex.message
            self.submission_error_text.set(ex.detailed_message)
            self.current_reaction_widget_dict[
                ex.error_index].reactant_entry.focus()
            print ex.error_index
            print ex.detailed_message
Example #2
0
def trainval():
    print("train")
    num_epochs = 50
    results = {}
    train_dl = datasets.get_dataset(dataroot="data", image_size=64, batch_size=32, num_workers=2)
    
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model = models.Model(device)
    
    score_list = []
    for epoch in range(0, num_epochs):
        print(f'epoch {epoch} of {num_epochs}')
        lossD, lossG = model.train_on_dataset(train_dl)
        results["lossD"] = lossD
        results["lossG"] = lossG
        model.vis_on_dataset(fname=os.path.join('training_image_results', f'epcoch{epoch}_results.png'))
Example #3
0
def trainval(exp_dict, savedir, args):
    """
    exp_dict: dictionary defining the hyperparameters of the experiment
    savedir: the directory where the experiment will be saved
    args: arguments passed through the command line
    """
    # -- Datasets
    train_set = datasets.get_dataset(dataset_name=exp_dict["dataset"],
                                     train_flag=True,
                                     datadir=args.datadir)

    val_set = datasets.get_dataset(dataset_name=exp_dict["dataset"],
                                   train_flag=False,
                                   datadir=args.datadir)

    # -- Model
    model = models.Model(exp_dict, device=torch.device('cuda'))

    # -- Train & Val Loop
    score_list = []
    for e in range(0, 50):
        # Compute metrics
        score_dict = {"epoch": e}
        score_dict["train_loss"] = model.val_on_dataset(
            val_set, metric_name='softmax_loss')
        score_dict["val_acc"] = model.val_on_dataset(val_set,
                                                     metric_name='softmax_acc')
        score_list += [score_dict]

        # Train model for one epoch
        model.train_on_dataset(train_set)

        # Visualize
        images = model.vis_on_dataset(val_set,
                                      fname=os.path.join(
                                          savedir, 'images', 'results.png'))

        # Report & Save
        score_df = pd.DataFrame(score_list)
        print("\n", score_df.tail(), "\n")
        hu.save_pkl(os.path.join(savedir, 'score_list.pkl'), score_list)
        hu.torch_save(os.path.join(savedir, 'model.pth'), model.state_dict())
        print("Checkpoint Saved: %s" % savedir)

    print('Experiment completed et epoch %d' % e)
Example #4
0
    def test_negative_initial_condition_raises_exception(self):
        # equation1:
        rx1 = Reaction([Reactant('A', 2), Reactant('B', 1)], [Product('C', 1)],
                       0.2, 0.5)

        # equation2:
        rx2 = Reaction([Reactant('C', 3), Reactant('D', 1)], [Product('E', 1)],
                       5, 0.0)
        reactions = [rx1, rx2]

        reaction_factory = MockedReactionFactory()
        reaction_factory.set_reaction(reactions)
        reaction_factory.set_initial_conditions({'A': 1.0, 'E': 0.2})

        with self.assertRaises(
                custom_exceptions.InvalidInitialConditionException):
            model = models.Model(reaction_factory)
            solver = model_solvers.ODESolverWJacobian(model)
            bad_new_initial_conditions = {'A': -1.0, 'B': 2}
            solver.equilibrium_solution(X0=bad_new_initial_conditions)
Example #5
0
    def test_initial_condition_specified_for_nonexistent_element(self):
        # equation1:
        rx1 = Reaction(
            [Reactant('A',2), Reactant('B',1)],
            [Product('C',1)],
            0.2,
            0.5
        )

        # equation2:
        rx2 = Reaction(
            [Reactant('C', 3), Reactant('D',1)],
            [Product('E', 1)],
            5,
            0.0
        )
        reactions = [rx1, rx2]

        reaction_factory = MockedReactionFactory()
        reaction_factory.set_reaction(reactions)
        reaction_factory.set_initial_conditions({'A':1.0, 'F':0.2})

        with self.assertRaises(custom_exceptions.InitialConditionGivenForMissingElement):
            model = models.Model(reaction_factory)
Example #6
0
 def load_model_from_file(f):
     print 'load from %s' % f
     factory = reaction_factories.FileReactionFactory(f)
     model = models.Model(factory)
     return model