Run the test suite on a single model and collect results.

    MODEL: Path to model file. Can also be supplied via the environment variable
    MEMOTE_MODEL or configured in 'setup.cfg' or 'memote.ini'.
421683
def run(model, collect, filename, location, ignore_git, pytest_args, exclusive,
        skip, solver, experimental, custom_tests, deployment,
        skip_unchanged):
    
    def is_verbose(arg):
        return (arg.startswith("--verbosity") or
                arg.startswith("-v") or arg.startswith("--verbose") or
                arg.startswith("-q") or arg.startswith("--quiet"))

    if ignore_git:
        repo = None
    else:
        callbacks.git_installed()
        repo = callbacks.probe_git()
    if collect:
        if repo is not None:
            if location is None:
                LOGGER.critical(
                    "Working with a repository requires a storage location.")
                sys.exit(1)
    if not any(a.startswith("--tb") for a in pytest_args):
        pytest_args = ["--tb", "short"] + pytest_args
    if not any(is_verbose(a) for a in pytest_args):
        pytest_args.append("-vv")
    # Check if the model was changed in this commit. Exit `memote run` if this
    # was not the case.
    if skip_unchanged and repo is not None:
        commit = repo.head.commit
        if not is_modified(model, commit):
            LOGGER.info("The model was not modified in commit '%s'. Skipping.",
                        commit.hexsha)
            sys.exit(0)
    # Add further directories to search for tests.
    pytest_args.extend(custom_tests)
    # Check if the model can be loaded at all.
    model, sbml_ver, notifications = api.validate_model(model)
    if model is None:
        LOGGER.critical(
            "The model could not be loaded due to the following SBML errors.")
        stdout_notifications(notifications)
        sys.exit(1)
    model.solver = solver
    # Load the experimental configuration using model information.
    if experimental is not None:
        experimental.load(model)
    code, result = api.test_model(
        model=model, sbml_version=sbml_ver, results=True,
        pytest_args=pytest_args, skip=skip,
        exclusive=exclusive, experimental=experimental)
    if collect:
        if repo is None:
            manager = ResultManager()
            manager.store(result, filename=filename)
        else:
            LOGGER.info("Checking out deployment branch.")
            # If the repo HEAD is pointing to the most recent branch then
            # GitPython's `repo.active_branch` works. Yet, if the repo is in
            # detached HEAD state, i.e., when a user has checked out a specific
            # commit as opposed to a branch, this won't work and throw a
            # `TypeError`, which we are circumventing below.
            try:
                previous = repo.active_branch
                previous_cmt = previous.commit
                is_branch = True
            except TypeError:
                previous_cmt = repo.head.commit
                is_branch = False
            repo.git.checkout(deployment)
            try:
                manager = SQLResultManager(repository=repo, location=location)
            except (AttributeError, ArgumentError):
                manager = RepoResultManager(repository=repo, location=location)
            LOGGER.info(
                "Committing result and changing back to working branch.")
            manager.store(result, commit=previous_cmt.hexsha)
            repo.git.add(".")
            check_call(
                ['git', 'commit',
                 '-m', "chore: add result for {}".format(previous_cmt.hexsha)]
            )
            if is_branch:
                previous.checkout()
            else:
                repo.commit(previous_cmt)
1123518
def cached_stan_file(model_name='anon_model', file=None, model_code=None,
                  cache_dir=None, fit_cachefile=None, cache_only=None, force=False,
                  include_modelfile=False, prefix_only=False,
                  **kwargs
                  ):
    ''' 
    '''
    model_prefix, model_cachefile = cached_model_file(model_name=model_name, file=file, model_code=model_code,
                                                      cache_dir=cache_dir, fit_cachefile=fit_cachefile, include_prefix=True)
    if not fit_cachefile:
        fit_cachefile = '.'.join([model_prefix, 'stanfit', _make_digest(dict(**kwargs)), 'pkl'])
    if include_modelfile:
        return model_cachefile, fit_cachefile
    if prefix_only:
        fit_cachefile = re.sub(string=fit_cachefile, pattern='.pkl$', repl='')
    return fit_cachefile
394685
def model_export(model, file_name, repo=None):
    
    with codecs.open(file_name, 'w', encoding="utf-8") as f:
        model_export_to_file(f, model, repo)
1009063
def train_model_from_args(args: argparse.Namespace):
    
    train_model_from_file(args.param_path,
                          args.serialization_dir,
                          args.overrides,
                          args.file_friendly_logging,
                          args.recover,
                          args.force,
                          args.cache_directory,
                          args.cache_prefix)
905995
def load_model(model_file):
    
    # Extract tar
    with tarfile.open(model_file) as tar:
        tarfolder = tempfile.mkdtemp()
        tar.extractall(path=tarfolder)

    from . import features
    from . import preprocessing

    # Get the preprocessing
    with open(os.path.join(tarfolder, "preprocessing.yml"), 'r') as ymlfile:
        preprocessing_description = yaml.load(ymlfile)
    preprocessing_queue = preprocessing.get_preprocessing_queue(
        preprocessing_description['queue'])

    # Get the features
    with open(os.path.join(tarfolder, "features.yml"), 'r') as ymlfile:
        feature_description = yaml.load(ymlfile)
    feature_str_list = feature_description['features']
    feature_list = features.get_features(feature_str_list)

    # Get the model
    import nntoolkit.utils
    model = nntoolkit.utils.get_model(model_file)

    output_semantics_file = os.path.join(tarfolder, 'output_semantics.csv')
    output_semantics = nntoolkit.utils.get_outputs(output_semantics_file)

    # Cleanup
    shutil.rmtree(tarfolder)

    return (preprocessing_queue, feature_list, model, output_semantics)
1161994
def run(self):
        
        from zengine.lib.cache import WFSpecNames

        if self.manager.args.clear:
            self._clear_models()
            return

        if self.manager.args.wf_path:
            paths = self.get_wf_from_path(self.manager.args.wf_path)
        else:
            paths = self.get_workflows()

        self.count = 0

        self.do_with_submit(self.load_diagram, paths, threads=self.manager.args.threads)

        WFSpecNames().refresh()

        print("%s BPMN file loaded" % self.count)
1189948
def run_model(self, model_run, run_url):
        
        # Create model run request
        request = RequestFactory().get_request(model_run, run_url)
        # Write request and connector information into buffer
        self.collection.insert_one({
            'connector' : self.connector,
            'request' : request.to_dict()
        })
597774
def get_mg_path(model_run, model_num):
    
    fsdb.switch_base("minigo-pub/v{:d}-19x19".format(model_run))
    model = fsdb.get_model(model_num)
    return os.path.join(fsdb.models_dir(), model)
864092
def run(suite, type, options={})
      @conf = Conf.instance
      reporter = Reporter.new(type)

      reporter.header

      suite.each do |test|
        case type
        when :test
          run_test(test) if expected_exists?(test)

        when :generate
          if expected_exists?(test)
            run_test(test, true) if options[:overwrite]
          else
            run_test(test, true)
          end
        end

        reporter.report(test)
      end

      reporter.summary
    end
1116214
def run_with_search(model_path, config, num_days):
    """"""
    from indra.tools.machine.machine import run_with_search_helper
    run_with_search_helper(model_path, config, num_days=num_days)
112989
def handle_model_generation(config, raml_resource):
    
    model_name = generate_model_name(raml_resource)
    try:
        return setup_data_model(config, raml_resource, model_name)
    except ValueError as ex:
        raise ValueError('{}: {}'.format(model_name, str(ex)))
123692
def run(self, path, pretend=False):
        
        self._notes = []

        files = self._get_migration_files(path)

        ran = self._repository.get_ran()

        migrations = [f for f in files if f not in ran]

        self.run_migration_list(path, migrations, pretend)
1049676
def load_suite_from_file(self, filename):
        
        suite = unittest.TestSuite()
        rules = Rules(filename, suite)

        if not os.path.exists(filename):
            rules.handle_file_does_not_exist()
            return suite

        line_generator = self._parser.parse_file(filename)
        return self._load_lines(filename, line_generator, suite, rules)
483259
def diff(models, filename, pytest_args, exclusive, skip, solver,
         experimental, custom_tests, custom_config):
    
    if not any(a.startswith("--tb") for a in pytest_args):
        pytest_args = ["--tb", "no"] + pytest_args
    # Add further directories to search for tests.
    pytest_args.extend(custom_tests)
    config = ReportConfiguration.load()
    # Update the default test configuration with custom ones (if any).
    for custom in custom_config:
        config.merge(ReportConfiguration.load(custom))
    # Build the diff report specific data structure
    diff_results = dict()
    model_and_model_ver_tuple = list()
    for model_path in models:
        try:
            model_filename = os.path.basename(model_path)
            diff_results.setdefault(model_filename, dict())
            model, model_ver, notifications = api.validate_model(model_path)
            if model is None:
                head, tail = os.path.split(filename)
                report_path = os.path.join(
                    head, '{}_structural_report.html'.format(model_filename))
                api.validation_report(
                    model_path, notifications, report_path)
                LOGGER.critical(
                    "The model {} could not be loaded due to SBML errors "
                    "reported in {}.".format(model_filename, report_path))
                continue
            model.solver = solver
            model_and_model_ver_tuple.append((model, model_ver))
        except (IOError, SBMLError):
            LOGGER.debug(exc_info=True)
            LOGGER.warning("An error occurred while loading the model '%s'. "
                           "Skipping.", model_filename)
    # Abort the diff report unless at least two models can be loaded
    # successfully.
    if len(model_and_model_ver_tuple) < 2:
        LOGGER.critical(
            "Out of the %d provided models only %d could be loaded. Please, "
            "check if the models that could not be loaded are valid SBML. "
            "Aborting.",
            len(models), len(model_and_model_ver_tuple))
        sys.exit(1)
    # Running pytest in individual processes to avoid interference
    partial_test_diff = partial(_test_diff, pytest_args=pytest_args,
                                skip=skip, exclusive=exclusive,
                                experimental=experimental)
    pool = Pool(min(len(models), cpu_count()))
    results = pool.map(partial_test_diff, model_and_model_ver_tuple)

    for model_path, result in zip(models, results):
        model_filename = os.path.basename(model_path)
        diff_results[model_filename] = result

    with open(filename, "w", encoding="utf-8") as file_handle:
        LOGGER.info("Writing diff report to '%s'.", filename)
        file_handle.write(api.diff_report(diff_results, config))
786899
def _loadModels(self):
        
        modelsPath = os.path.join(self.path, "model")
        if not os.path.isdir(modelsPath):
            return

        for modelFile in os.listdir(modelsPath):
            modelName = modelFile.replace(".py", "")
            modelPath = os.path.join(
                self.path, "model", modelFile
            )

            if not os.path.isfile(modelPath):
                continue

            # importing model
            modelSpec = importlib.util.spec_from_file_location(
                modelName,
                modelPath
            )
            model = importlib.util.module_from_spec(modelSpec)
            modelSpec.loader.exec_module(model)

            # initializing model
            modelInstance = model.Model(self.application)
            self.application.addModel(self.name, modelName, modelInstance)
1227591
def evaluate_model_single_recording(model_file, recording):
    
    (preprocessing_queue, feature_list, model,
     output_semantics) = load_model(model_file)
    results = evaluate_model_single_recording_preloaded(preprocessing_queue,
                                                        feature_list,
                                                        model,
                                                        output_semantics,
                                                        recording)
    return results
315514
def monkey_patch_behave(django_test_runner):
    
    behave_run_hook = ModelRunner.run_hook

    def run_hook(self, name, context, *args):
        if name == 'before_all':
            django_test_runner.patch_context(context)

        behave_run_hook(self, name, context, *args)

        if name == 'before_scenario':
            django_test_runner.setup_testclass(context)
            django_test_runner.setup_fixtures(context)
            django_test_runner.setup_test(context)
            behave_run_hook(self, 'django_ready', context)

        if name == 'after_scenario':
            django_test_runner.teardown_test(context)

    ModelRunner.run_hook = run_hook