def setUp(self):
        # Manual construction
        column_type = ColumnType(**COLUMN_TYPE_DATA)
        resin = Resin(**RESIN_DATA)
        column = Column(column_type=column_type, resin=resin, **COLUMN_DATA)
        method = Method(**METHOD_DATA)

        self.sim_from_scratch = Simulation(name='Sim1',
                                           column=column,
                                           method=method,
                                           output=None)
        self.sim_from_std_exp = make_sample_simulation()
    def to_simulation(self):
        """ Returns a new Simulation object from current builder.
        """
        from kromatography.model.factories.method import \
            build_sim_method_from_method

        sim_method = build_sim_method_from_method(
            self.method, self.first_simulated_step_name,
            self.last_simulated_step_name, initial_buffer=self.initial_buffer,
        )

        simulation = Simulation(
            name=self.simulation_name,
            column=self.column,
            method=sim_method,
            first_simulated_step=self.first_simulated_step_name,
            last_simulated_step=self.last_simulated_step_name,
            transport_model=self.transport_model,
            binding_model=self.binding_model,
            solver=Solver(),
            discretization=Discretization(),
            sensitivity=Sensitivity(),
        )

        # Product is a property of a simulation, which isn't set until we set
        # the method.
        if not is_has_traits_almost_equal(simulation.product, self.product):
            msg = ("The simulation's product (read in the method) doesn't "
                   "match the selected product. Please review the product and"
                   " method selected.")
            logger.info(msg)
            warning(None, msg, "Review simulation data")

        return simulation
 def to_simulation(self):
     """ Export the current simulation to a regular simulation with its
     results data in memory.
     """
     new_sim = Simulation(name=self.name)
     new_sim.copy_traits(self)
     new_sim.uuid = uuid4()
     if self.has_run:
         new_sim.output = self.output
         new_sim.set_as_run()
     return new_sim
Example #4
0
    def get_instance(self, constructor_data):
        from kromatography.model.simulation import Simulation
        kwargs = constructor_data['kwargs']
        kwargs.pop("step_indices")
        instance = Simulation(**kwargs)
        # Back then, methods didn't store an initial buffer. Try to retrieve it
        if instance.method.initial_buffer is None:
            try:
                method = self.rebuild_method(instance)
            except Exception as e:
                msg = "Deserialized an old version of a Simulation and failed"\
                      " to rebuild the method: error was {}".format(e)
                logger.debug(msg)
                method = None

            if method:
                instance.method = method

        return instance
    def setUp(self):
        # Manual construction
        column_type = ColumnType(**COLUMN_TYPE_DATA.copy())
        resin = Resin(**RESIN_DATA.copy())
        column = Column(column_type=column_type,
                        resin=resin,
                        **COLUMN_DATA.copy())
        method = Method(**deepcopy(METHOD_DATA))

        self.sim_from_scratch = Simulation(name='Sim1',
                                           column=column,
                                           method=method,
                                           output=None)
        self.expected_sec_times = array([0., 540., 1080., 1620., 7668.])
    def to_simulations(self):
        """ Returns a list of simulations built from each experiment selected.
        """
        fstep, lstep = (self.first_simulated_step_name,
                        self.last_simulated_step_name)
        new_simulations = []
        for exp_name, sim_name in zip(self.experiment_selected,
                                      self.simulation_names):
            experiment = self.target_study.search_experiment_by_name(exp_name)
            try:
                sim_method = build_sim_method_from_method(
                    experiment.method,
                    fstep,
                    lstep,
                    initial_buffer=self.initial_buffer,
                )
            except StepLookupError as e:
                msg = "Failed to find the start/stop method steps for " \
                      "simulation {}. Its experiment doesn't seem to contain" \
                      " {} or {}. Please review these step names or treat " \
                      "this simulation separately from the others. Aborting..."
                msg = msg.format(sim_name, fstep, lstep)
                details = " Details: error was {}".format(e)
                logger.error(msg + details)
                warning(None, msg)
                return []

            simulation = Simulation(
                name=sim_name,
                column=experiment.column.clone_traits(copy="deep"),
                method=sim_method,
                first_simulated_step=self.first_simulated_step_name,
                last_simulated_step=self.last_simulated_step_name,
                transport_model=self.transport_model,
                binding_model=self.binding_model,
                source_experiment=experiment,
                solver=Solver(),
                discretization=Discretization(),
                sensitivity=Sensitivity(),
            )
            new_simulations.append(simulation)

        return new_simulations
Example #7
0
 def test_add_sim(self):
     from kromatography.model.simulation import Simulation
     sim = Simulation(name="foo")
     self.study.simulations.append(sim)
     self.assertFalse(self.study.is_blank)
 def test_load_wrong_obj_type(self):
     obj = Simulation(name="dslkjf")
     save_object(self.filepath_temp, obj)
     task, legacy = load_project(self.filepath_temp)
     self.assertFalse(legacy)
     assert_has_traits_almost_equal(task, obj)
Example #9
0
import logging

from traits.api import Any, Callable, HasStrictTraits, Property, Str

from app_common.pyface.monitored_actions import action_monitoring

from kromatography.model.simulation import Simulation
from kromatography.ui.gui_model_factory import DATASOURCE_OBJECT_FACTORIES, \
    STUDY_DATASOURCE_OBJECT_FACTORIES
from kromatography.model.chromatography_data import ChromatographyData

BLANK_SIMULATION = Simulation(name="New simulation")

logger = logging.getLogger(__name__)


class BaseEntryCreator(HasStrictTraits):
    """ Generic object to request, create and add a new datasource entry to the
    datasource object_catalog dict. This might require to have access to the
    study to pull data like the chosen product or the user datasource.
    It might also request to select a product if not already set.
    """
    #: Datsource being contributed to
    datasource = Any

    #: Type of object being contributed
    datasource_key = Str

    #: List of objects being contributed to
    data = Property
class TestSimulationCopy(TestCase, UnittestTools):
    @classmethod
    def setUpClass(cls):
        cls.real_study = make_sample_study2(add_transp_bind_models=True)
        cls.real_exp = cls.real_study.search_experiment_by_name('Run_1')
        cls.real_sim = build_simulation_from_experiment(cls.real_exp)
        cls.job_manager = create_start_job_manager(max_workers=1)

    @classmethod
    def tearDownClass(cls):
        cls.job_manager.shutdown()

    def setUp(self):
        # Manual construction
        column_type = ColumnType(**COLUMN_TYPE_DATA)
        resin = Resin(**RESIN_DATA)
        column = Column(column_type=column_type, resin=resin, **COLUMN_DATA)
        method = Method(**METHOD_DATA)

        self.sim_from_scratch = Simulation(name='Sim1',
                                           column=column,
                                           method=method,
                                           output=None)
        self.sim_from_std_exp = make_sample_simulation()

    def test_copy_sim_from_scratch_not_run(self):
        new_sim1 = self.sim_from_scratch.copy()
        self.assertValidCopy(new_sim1, self.sim_from_scratch)

    def test_copy_sim_with_bind_transp_not_run(self):
        # Using utility will contain a binding and transport model
        new_sim2 = self.sim_from_std_exp.copy()
        self.assertValidCopy(new_sim2, self.sim_from_std_exp)

    def test_copy_complete_sim_not_run(self):
        # Build a simulation from an experiment and add a fake output
        sim3 = self.real_sim
        sim3.output = SimulationResults(name='fake output')
        sim3.editable = False

        new_sim3 = sim3.copy()
        self.assertValidCopy(new_sim3, sim3)

    def test_copy_sim_run(self):
        self.real_sim.run(self.job_manager, wait=True)

        self.assertIsNotNone(self.real_sim.output)
        self.assertTrue(self.real_sim.has_run)
        sim = self.real_sim.copy()
        self.assertIsNone(sim.output)
        self.assertFalse(sim.has_run)
        self.assertTrue(sim.editable)
        self.assertFalse(isfile(sim.cadet_filepath))

    # Utilities ---------------------------------------------------------------

    def assertValidCopy(self, new_sim, orig_sim):
        """ Test that a copy leads to identical attributes except run related.
        """
        self.assertIsInstance(new_sim, orig_sim.__class__)

        # copies have no output
        self.assertIsNone(new_sim.output)
        # Copies use the same buffer in every step
        self.assertTrue(new_sim.editable)

        # All uses of buffers are the same object
        buffers = {}
        for step in new_sim.method.method_steps:
            for solution in step.solutions:
                if isinstance(solution, Buffer):
                    if solution.name in buffers:
                        self.assertIs(solution, buffers[solution.name])
                    else:
                        buffers[solution.name] = solution

        # All subobjects are equal except the outputs, the editable flag
        # and the events attributes.
        skip_attr = {
            "output", "editable", "has_run", "uuid", "cadet_filename",
            "cadet_filepath"
        }
        relevant_attrs = set(new_sim.trait_names()) - skip_attr

        for attr in relevant_attrs:
            if is_trait_event(orig_sim, attr):
                continue
            val1, val2 = getattr(new_sim, attr), getattr(orig_sim, attr)
            if isinstance(val1, HasTraits):
                assert_has_traits_almost_equal(val1, val2)
            else:
                assert_values_almost_equal(val1, val2)

        # The uuid and cadet input files on the other hand is guaranteed to be
        # different
        self.assertNotEqual(orig_sim.uuid, new_sim.uuid)
        self.assertNotEqual(orig_sim.cadet_filename, new_sim.cadet_filename)
        self.assertNotEqual(orig_sim.cadet_filepath, new_sim.cadet_filepath)