Exemplo n.º 1
0
    def runtest(self):
        """Run an AnyScript test item."""
        tmpdir = self.config._tmpdirhandler.mktemp(self.name)
        if self.compare_filename:
            os.makedirs(os.path.dirname(self.compare_filename))
        with change_dir(tmpdir.strpath):
            app = AnyPyProcess(**self.apt_opts)
            result = app.start_macro(self.macro)[0]
            self.app = app
        # Ignore error due to missing Main.RunTest
        if 'ERROR' in result:
            for i, err in enumerate(result['ERROR']):
                runtest_errros = (
                    'Error : Main.RunTest : Unresolved object',
                    'Main.RunTest : Select Operation is not expected')
                if any(s in err for s in runtest_errros):
                    del result['ERROR'][i]
                    break
        # Check that the expected errors are present
        if self.expect_errors:
            error_list = result.get('ERROR', [])
            for xerr in self.expect_errors:
                xerr_found = False
                for i, error in enumerate(error_list):
                    if xerr in error:
                        xerr_found = True
                        del error_list[i]
                if not xerr_found:
                    self.errors.append('TEST ERROR: Expected error not '
                                       'found: "{}"'.format(xerr))
        # Add remaining errors to item's error list
        if 'ERROR' in result and len(result['ERROR']) > 0:
            self.errors.extend(result['ERROR'])
        # Add info to the hdf5 file if compare output was set
        if self.compare_filename is not None:
            import h5py
            f = h5py.File(self.compare_filename, 'a')
            f.attrs['anytest_processtime'] = result['task_processtime']
            f.attrs['anytest_macro'] = '\n'.join(result['task_macro'][:-1])
            f.attrs['anytest_ammr_version'] = pytest.anytest.ammr_version
            f.attrs['anytest_ams_version'] = pytest.anytest.ams_version
            f.close()
            basedir = os.path.dirname(self.compare_filename)
            macrofile = write_macro_file(basedir, self.compare_study,
                                         self.macro[:-1])
            with open(os.path.join(basedir, self.compare_study + '.bat'),
                      'w') as f:
                anybodygui = re.sub(r"(?i)anybodycon\.exe", r"anybody\.exe",
                                    self.anybodycon_path)
                f.write('"{}" -m "{}"'.format(anybodygui, macrofile))

        if len(self.errors) > 0:
            if self.config.getoption("--create-macros"):
                macro_name = write_macro_file(self.fspath.dirname, self.name,
                                              self.macro)
                self.macro_file = macro_name
            raise AnyException(self)
        return
Exemplo n.º 2
0
def run_model(saddle_height, saddle_pos, silent=False):
    """Run the AnyBody model and return the metabolism results"""
    macro = [
        Load("BikeModel2D.main.any"),
        SetValue("Main.BikeParameters.SaddleHeight", saddle_height),
        SetValue("Main.BikeParameters.SaddlePos", saddle_pos),
        OperationRun("Main.Study.InverseDynamics"),
        Dump("Main.Study.Output.Pmet_total"),
        Dump("Main.Study.Output.Abscissa.t"),
    ]
    app = AnyPyProcess(silent=silent)
    results = app.start_macro(macro)
    return results[0]
Exemplo n.º 3
0
 def runtest(self):
     tmpdir = self.config._tmpdirhandler.mktemp(self.name)
     with change_dir(tmpdir.strpath):
         app = AnyPyProcess(**self.apt_opts)
         result = app.start_macro(self.macro)[0]
         self.app = app
     # Ignore error due to missing Main.RunTest
     if 'ERROR' in result:
         for i, e in enumerate(result['ERROR']):
             if 'Error : Main.RunTest : Unresolved object' in e:
                 del result['ERROR'][i]
                 break
     # Check that the expected errors are present
     if self.expect_errors is not None:
         if 'ERROR' in result:
             # Remove any failures due to RunTest not working on failed models
             for i, e in enumerate(result['ERROR']):
                 if 'Main.RunTest : Select Operation is not expected' in e:
                     del result['ERROR'][i]
                     break
             error_list = result['ERROR']
         else:
             error_list = []
         for xerr in self.expect_errors:
             xerr_found = False
             for i, error in enumerate(error_list):
                 if xerr in error:
                     xerr_found = True
                     del error_list[i]
             if not xerr_found:
                 self.errors.append('TEST ERROR: Expected error not '
                                     'found: "{}"'.format(xerr))
     # Add remaining errors to item's error list
     if 'ERROR' in result and len(result['ERROR']) > 0:
         self.errors.extend(result['ERROR'])
     if len(self.errors) > 0:
         if self.config.getoption("--create-macros"):
             macro_file = 'run_{}.anymcr'.format(self.name)
             macro_file = os.path.join(self.fspath.dirname, macro_file)
             with open(macro_file,'w') as f:
                 f.writelines([str(mcr)+'\n' for mcr in self.macro])
             self.macro_file = macro_file
         raise  AnyException(self)
     return
Exemplo n.º 4
0
    def run(self):
        if not self.macrolist:
            print(
                "No operation for AnyBody was selected -> will terminate now")
            return False

        # print('Starting Anybody with the operations: {}'.format(self.operations))
        print('Starting Anybody with the macros:\n{}'.format(
            AnyMacro(self.macrolist)))
        print('Executing "{}" in "{}"'.format(self.any_path, self.any_model))

        # save current working directory and change to Anybody project folder
        cwd = os.getcwd()
        os.chdir(self.any_path)
        app = AnyPyProcess()

        self.output = app.start_macro(macrolist=self.macrolist,
                                      logfile=AnyPy.LOG_FILE)

        # change back to original folder
        os.chdir(cwd)
        return True
Exemplo n.º 5
0
def test_hdf5save(tmpdir, default_macro):
    setup_simple_model( tmpdir )
    tmpdir.chdir()
    app = AnyPyProcess(keep_logfiles=True)
    app.start_macro(default_macro)
    
    app.save_to_hdf5('test.hdf5', 'LungeTLEM1')        
        
    assert(os.path.exists('test.hdf5'))
Exemplo n.º 6
0
              'operation Main.ArmModelStudy.InverseDynamics',
              'run',
              'classoperation Main.ArmModelStudy.Output.MaxMuscleActivity "Dump"',
              'classoperation Main.ArmModel.GlobalRef.t "Dump"'
              ]]*5
    return macro


def test_hdf5save(tmpdir, default_macro):
    setup_simple_model( tmpdir )
    tmpdir.chdir()
    app = AnyPyProcess(keep_logfiles=True)
    app.start_macro(default_macro)
    
    app.save_to_hdf5('test.hdf5', 'LungeTLEM1')        
        
    assert(os.path.exists('test.hdf5'))
    
    
    
if __name__ == '__main__':
    macro = [['load "Demo.Arm2D.any"',
              'operation Main.ArmModelStudy.InverseDynamics',
              'run',
              'classoperation Main.ArmModelStudy.Output.MaxMuscleActivity "Dump"',
              'classoperation Main.ArmModel.GlobalRef.t "Dump"'
              ]]*5
    app = AnyPyProcess(keep_logfiles=True)
    app.start_macro(macro)
    
    app.save_to_hdf5('test2.hdf5', 'Lunge11dec')
    def runtest(self):
        """Run an AnyScript test item."""
        tmpdir = self.config._tmpdirhandler.mktemp(self.name)
        if self.save_filename:
            dirname = os.path.dirname(self.save_filename)
            if os.path.exists(dirname):
                shutil.rmtree(dirname, ignore_errors=True)
            os.makedirs(dirname)
        with change_dir(tmpdir.strpath):
            app = AnyPyProcess(**self.app_opts)
            result = app.start_macro(self.macro)[0]
            self.app = app
        # Ignore error due to missing Main.RunTest
        if "ERROR" in result:
            runtest_missing = any(
                "Error : Main.RunTest :" in err for err in result["ERROR"]
            )
            if runtest_missing:
                runtest_errros = (
                    "Error : Main.RunTest : Unresolved",
                    "Main.RunTest : Select Operation",
                    "Error : run : command unexpected while",
                )
                result["ERROR"][:] = [
                    err
                    for err in result["ERROR"]
                    if not any(s in err for s in runtest_errros)
                ]
        # Check that the expected errors are present
        if self.expect_errors:
            error_list = result.get("ERROR", [])
            for xerr in self.expect_errors:
                xerr_found = False
                for i, error in enumerate(error_list):
                    if xerr in error:
                        xerr_found = True
                        del error_list[i]
                if not xerr_found:
                    self.errors.append(
                        "TEST ERROR: Expected error not " 'found: "{}"'.format(xerr)
                    )
        # Add remaining errors to item's error list
        if "ERROR" in result and len(result["ERROR"]) > 0:
            self.errors.extend(result["ERROR"])
        # Add info to the hdf5 file if compare output was set
        if self.save_filename is not None:
            import h5py

            if not os.path.exists(self.save_filename):
                self.errors.append(
                    "TEST ERROR: No HDF5 data were save from: " + self.save_study
                )
            f = h5py.File(self.save_filename, "a")
            f.attrs["anytest_processtime"] = result["task_processtime"]
            f.attrs["anytest_macro"] = "\n".join(result["task_macro"][:-1])
            f.attrs["anytest_ammr_version"] = pytest.anytest.ammr_version
            f.attrs["anytest_ams_version"] = pytest.anytest.ams_version
            f.close()
            basedir = os.path.dirname(self.save_filename)

            logfile = result["task_logfile"]
            macrofile = os.path.splitext(logfile)[0] + ".anymcr"
            shutil.copyfile(logfile, os.path.join(basedir, "logfile.txt"))
            shutil.copyfile(macrofile, os.path.join(basedir, "macro.anymcr"))

            with open(os.path.join(basedir, "run.bat"), "w") as f:
                anybodygui = re.sub(
                    r"(?i)anybodycon\.exe", "anybody.exe", self.anybodycon_path
                )
                f.write('"{}" -m "macro.anymcr"'.format(anybodygui, macrofile))

        if len(self.errors) > 0:
            if self.config.getoption("--create-macros"):
                macro_name = write_macro_file(
                    self.fspath.dirname, self.name, self.macro
                )
                self.macro_file = macro_name
            raise AnyException(self)

        shutil.rmtree(tmpdir.strpath, ignore_errors=True)

        return
Exemplo n.º 8
0
from anypytools import AnyPyProcess
from anypytools.macro_commands import Load, OperationRun

app = AnyPyProcess(num_processes=3)

macro = [Load("main.any"), OperationRun("Main.Study.InverseDynamics")]

app.start_macro(macro, search_subdirs="model[1-9].*main.any")
Exemplo n.º 9
0
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 16 14:35:15 2018

@author: zhuxu
"""

from anypytools import AnyPyProcess
app = AnyPyProcess(num_processes=1)
from anypytools import AnyMacro
from anypytools.macro_commands import (Load, SetValue, Dump, OperationRun)
from colorama import Back, Style, Fore
import numpy as np
from math import degrees


#%%
def Check_Scaling(Height):
    F_or_L = 'Lower'
    Body_Height = 1.8
    Mechanical_Output = 5
    Cadence = 5
    Saddle_Height = Height
    Saddle_Pos = -0.25
    Pedal_Arm_Length = 0.2
    Pedal_Arm_Width = 0.107
    macro = [
        Load('../Application/Examples/BikeModel/BikeModel-' + F_or_L +
             'Body.main.any'),
        SetValue('Main.HumanModel.Scaling.Scaling.AnthroData.body_height',
                 Body_Height),
Exemplo n.º 10
0
from anypytools import AnyPyProcess
from anypytools.macro_commands import Load, OperationRun

app = AnyPyProcess(num_processes = 3)

macro = [Load("main.any"),
         OperationRun('Main.Study.InverseDynamics') ]
         
app.start_macro(macro, search_subdirs= "model[1-9].*main.any" )


Exemplo n.º 11
0
    def runtest(self):
        """Run an AnyScript test item."""

        tmpdir = Path(
            TempdirFactory(TempPathFactory.from_config(self.config)).mktemp(
                self.name))

        with change_dir(tmpdir):
            self.app = AnyPyProcess(**self.app_opts)
            result = self.app.start_macro(self.macro)[0]

        # Ignore error due to missing Main.RunTest
        if "ERROR" in result:
            runtest_missing = any("Error : Main.RunTest :" in err
                                  for err in result["ERROR"])
            if runtest_missing:
                runtest_errros = (
                    "Error : Main.RunTest : Unresolved",
                    "Main.RunTest : Select Operation",
                    "Error : run : command unexpected while",
                )
                result["ERROR"][:] = [
                    err for err in result["ERROR"]
                    if not any(s in err for s in runtest_errros)
                ]
        # Check that the expected errors are present
        error_list = result.get("ERROR", [])
        if self.expect_errors:
            for xerr in self.expect_errors:
                xerr_found = False
                for error in error_list[:]:
                    if xerr in error:
                        xerr_found = True
                        error_list.remove(error)
                if not xerr_found:
                    self.errors.append("TEST ERROR: Expected error not "
                                       'found: "{}"'.format(xerr))

        # Add remaining errors to item's error list
        if error_list:
            self.errors.extend(error_list)

        # Add info to the hdf5 file if compare output was set
        if self.hdf5_outputs:
            base = Path(self.config.getoption("--anytest-output"))
            subfolder = Path(self.config.getoption("--anytest-name"))
            target = base / subfolder / self.name
            self.save_output_files(tmpdir, target, result, self.hdf5_outputs)

        if self.errors and self.config.getoption("--create-macros"):
            logfile = result["task_logfile"]
            shutil.copyfile(logfile, self.fspath / (self.name + ".txt"))
            shutil.copyfile(logfile.with_suffix(".anymcr"),
                            self.fspath / (self.name + ".anymcr"))
            macro_name = _write_macro_file(self.fspath.dirname, self.name,
                                           self.macro)

        shutil.rmtree(tmpdir, ignore_errors=True)

        if len(self.errors) > 0:
            raise AnyException(self)

        return
Exemplo n.º 12
0
class AnyTestItem(pytest.Item):
    """pytest.Item subclass representing individual collected tests."""
    def __init__(self, name, id, parent, defs, paths, **kwargs):
        test_name = "{}_{}".format(name, id)
        super().__init__(test_name, parent)
        self.defs = defs
        for k, v in self.config.getoption("define_kw") or {}:
            self.defs[k] = v
        self.defs["TEST_NAME"] = '"{}"'.format(test_name)
        if self.config.getoption("--ammr"):
            paths["AMMR_PATH"] = self.config.getoption("--ammr")
            paths["ANYBODY_PATH_AMMR"] = self.config.getoption("--ammr")
        self.paths = _as_absolute_paths(paths,
                                        start=self.config.rootdir.strpath)
        self.name = test_name
        self.expect_errors = kwargs.get("expect_errors", [])

        for marker in kwargs.get("pytest_markers", []):
            self.add_marker(marker)

        self.timeout = self.config.getoption("--timeout")
        self.errors = []
        self.macro = [
            macro_commands.Load(self.fspath.strpath, self.defs, self.paths)
        ]

        fatal_warnings = kwargs.get("fatal_warnings", False)
        warnings_to_include = kwargs.get("warnings_to_include", None)
        if warnings_to_include:
            warnings.warn(
                f"\n{name}:`warnings_to_include` is deprecated. \nSpecify the `fatal_warnings` variable as "
                "a list to select specific warnings",
                DeprecationWarning,
            )
            if not isinstance(fatal_warnings, collections.abc.Sequence):
                fatal_warnings = warnings_to_include

        if not isinstance(fatal_warnings, collections.abc.Sequence):
            fatal_warnings = ["WARNING"] if fatal_warnings else []

        self.app_opts = {
            "silent": True,
            "debug_mode": self.config.getoption("--anybody_debug_mode"),
            "anybodycon_path": pytest.anytest.ams_path,
            "timeout": self.timeout,
            "ignore_errors": kwargs.get("ignore_errors", []),
            "warnings_to_include": fatal_warnings,
            "fatal_warnings": bool(fatal_warnings),
            "keep_logfiles": kwargs.get("keep_logfiles", True),
            "logfile_prefix": kwargs.get("logfile_prefix", None),
            "use_gui": kwargs.get("use_gui", False),
        }
        if not self.config.getoption("--only-load"):
            self.macro.append(macro_commands.OperationRun("Main.RunTest"))

        self.hdf5_outputs = []
        save_study = kwargs.get("save_study", None)
        if self.config.getoption("--anytest-output") and save_study:
            save_study = [save_study] if isinstance(save_study,
                                                    str) else save_study
            for study in save_study:
                fname = f"{study}.anydata.h5"
                self.macro.append(
                    f'classoperation {study}.Output "Save data" --type="Deep" --file="{fname}"'
                )
                self.hdf5_outputs.append(fname)
        return

    def runtest(self):
        """Run an AnyScript test item."""

        tmpdir = Path(
            TempdirFactory(TempPathFactory.from_config(self.config)).mktemp(
                self.name))

        with change_dir(tmpdir):
            self.app = AnyPyProcess(**self.app_opts)
            result = self.app.start_macro(self.macro)[0]

        # Ignore error due to missing Main.RunTest
        if "ERROR" in result:
            runtest_missing = any("Error : Main.RunTest :" in err
                                  for err in result["ERROR"])
            if runtest_missing:
                runtest_errros = (
                    "Error : Main.RunTest : Unresolved",
                    "Main.RunTest : Select Operation",
                    "Error : run : command unexpected while",
                )
                result["ERROR"][:] = [
                    err for err in result["ERROR"]
                    if not any(s in err for s in runtest_errros)
                ]
        # Check that the expected errors are present
        error_list = result.get("ERROR", [])
        if self.expect_errors:
            for xerr in self.expect_errors:
                xerr_found = False
                for error in error_list[:]:
                    if xerr in error:
                        xerr_found = True
                        error_list.remove(error)
                if not xerr_found:
                    self.errors.append("TEST ERROR: Expected error not "
                                       'found: "{}"'.format(xerr))

        # Add remaining errors to item's error list
        if error_list:
            self.errors.extend(error_list)

        # Add info to the hdf5 file if compare output was set
        if self.hdf5_outputs:
            base = Path(self.config.getoption("--anytest-output"))
            subfolder = Path(self.config.getoption("--anytest-name"))
            target = base / subfolder / self.name
            self.save_output_files(tmpdir, target, result, self.hdf5_outputs)

        if self.errors and self.config.getoption("--create-macros"):
            logfile = result["task_logfile"]
            shutil.copyfile(logfile, self.fspath / (self.name + ".txt"))
            shutil.copyfile(logfile.with_suffix(".anymcr"),
                            self.fspath / (self.name + ".anymcr"))
            macro_name = _write_macro_file(self.fspath.dirname, self.name,
                                           self.macro)

        shutil.rmtree(tmpdir, ignore_errors=True)

        if len(self.errors) > 0:
            raise AnyException(self)

        return

    def save_output_files(self, src_folder, target_folder, result, hdf5files):
        """ Saves hdf5, macro, and log files from a test run
            and copy it to the target_folder
        """
        import h5py

        target_folder = Path(target_folder)
        src_folder = Path(src_folder)
        src_log = Path(result["task_logfile"])

        if target_folder.exists():
            shutil.rmtree(target_folder)
        os.makedirs(target_folder)

        for fn in hdf5files:
            if (src_folder / fn).exists():
                shutil.copyfile(src_folder / fn, target_folder / fn)
                f = h5py.File(target_folder / fn, "a")
                f.attrs["anytest_processtime"] = result["task_processtime"]
                f.attrs["anytest_macro"] = "\n".join(result["task_macro"][:-1])
                f.attrs["anytest_ammr_version"] = pytest.anytest.ammr_version
                f.attrs["anytest_ams_version"] = pytest.anytest.ams_version
                f.close()
            else:
                self.errors.append(f"ERROR: No HDF5 data were saved: {fn}")

        target_log = target_folder / "logfile.txt"
        shutil.copyfile(src_log, target_log)
        src_macrofile = src_log.with_suffix(".anymcr")
        target_macro = target_folder / "macro.anymcr"
        shutil.copyfile(src_macrofile, target_macro)

        with open(target_folder / "run.bat", "w") as f:
            anybodygui = re.sub(r"(?i)anybodycon\.exe", "anybody.exe",
                                pytest.anytest.ams_path)
            f.write(f'"{anybodygui}" -m "%~dp0{target_macro.name}"')

    def repr_failure(self, excinfo):
        """Print a representation when a test failes."""
        if isinstance(excinfo.value, AnyException):
            rtn = "Main file:\n"
            rtn += wraptext(self.fspath.strpath, initial_indent="  ")
            rtn += "\nSpecial model configuration:"
            for k, v in self.defs.items():
                rtn += "\n  #define {} {}".format(k, v)
            for k, v in self.paths.items():
                rtn += "\n  #path {} {}".format(k, v)
            rtn += "\nErrors:"
            for elem in self.errors:
                rtn += "\n"
                rtn += wraptext(elem,
                                initial_indent="> ",
                                subsequent_indent="  ")
            return rtn
        else:
            return str(excinfo.value)

    def reportinfo(self):
        return self.fspath, 0, "AnyBody Simulation: %s" % self.name