예제 #1
0
 def __init__(self, program):
     """
     Runner to run PROZA simulation(s).
     """
     _Worker.__init__(self, program, 
                      java_exec=get_settings().proza.java,
                      jar_path=get_settings().proza.jar)
예제 #2
0
 def __init__(self, program):
     """
     Runner to run PROZA simulation(s).
     """
     _Worker.__init__(self,
                      program,
                      java_exec=get_settings().proza.java,
                      jar_path=get_settings().proza.jar)
예제 #3
0
    def __init__(self, program):
        """
        Runner to run NISTMonte simulation(s).
        """
        _Worker.__init__(self, program)

        self._java_exec = get_settings().nistmonte.java
        logging.debug('Java executable: %s', self._java_exec)

        self._jar_path = get_settings().nistmonte.jar
        logging.debug('pyMonteCarlo jar path: %s', self._jar_path)
예제 #4
0
    def __init__(self, program):
        """
        Runner to run NISTMonte simulation(s).
        """
        _Worker.__init__(self, program)

        self._java_exec = get_settings().nistmonte.java
        logging.debug('Java executable: %s', self._java_exec)

        self._jar_path = get_settings().nistmonte.jar
        logging.debug('pyMonteCarlo jar path: %s', self._jar_path)
예제 #5
0
    def __init__(self, program):
        """
        Runner to run Monaco simulation(s).
        """
        _Worker.__init__(self, program)

        self._monaco_basedir = get_settings().monaco.basedir

        try:
            self._mccli32exe = get_settings().monaco.exe
        except AttributeError:
            self._mccli32exe = os.path.join(self._monaco_basedir,
                                            'Mccli32.exe')
예제 #6
0
def run(argv=None):
    # Initialise programs
    get_settings().get_programs()

    # Initialise console
    console = Console()
    console.init()

    # Create parser
    usage = "%prog [options] [OPTION_FILE.xml or RESULTS_FILE.zip or RESULTS_FILE.h5 ...]"
    description = "pyMonteCarlo update tool. This script updates old version " + \
                  "of options or results file to the newer one."
    epilog = "For more information, see http://pymontecarlo.bitbucket.org"

    parser = OptionParser(usage=usage, description=description, epilog=epilog)

    parser.add_option('-v',
                      '--verbose',
                      dest='verbose',
                      default=False,
                      action='store_true',
                      help='Debug mode')

    # Parse arguments
    (values, args) = parser.parse_args(argv)

    if values.verbose:
        logging.getLogger().setLevel(logging.DEBUG)

    if not args:
        console.print_error('Please specify at least one file')

    for filepath in args:
        if not os.path.exists(filepath):
            console.print_error('File %s does not exists' % filepath)

        ext = os.path.splitext(filepath)[1]

        if ext == '.xml':
            console.print_info("Updating options %s" % filepath)
            filepath = OptionsUpdater().update(filepath)
            console.print_success("Successfully updated %s" % filepath)
        elif ext == '.zip' or ext == '.h5':
            console.print_info("Updating results %s" % filepath)
            filepath = ResultsUpdater().update(filepath)
            console.print_success("Successfully results %s" % filepath)
        else:
            console.print_error('Unknown extension %s' % ext)

    console.close()
예제 #7
0
    def validate(self):
        settings = get_settings()

        if 'monaco' not in settings:
            raise AssertionError("Missing 'monaco' section in settings")

        if 'basedir' not in settings.monaco:
            raise AssertionError(
                "Missing 'basedir' option in 'monaco' section of settings")

        basedir = settings.monaco.basedir
        if not os.path.isdir(basedir):
            raise AssertionError(
                "Specified Monaco base directory (%s) does not exist" %
                basedir)

        try:
            mccli32_exe = settings.monaco.exe
        except AttributeError:
            filename = 'Mccli32'
            if os.name == 'nt':
                filename += '.exe'
            mccli32_exe = os.path.join(settings.monaco.basedir, filename)
        if not os.path.isfile(mccli32_exe):
            raise AssertionError(
                "No Mccli32.exe in Monaco base directory (%s)" % basedir)
        if not os.access(mccli32_exe, os.X_OK):
            raise AssertionError(
                "Specified Monaco executable (%s) is not executable" %
                mccli32_exe)
예제 #8
0
    def __init__(self):
        """
        Creates a exporter to PENEPMA.
        """
        try:
            pendbase = get_settings().penepma.pendbase
        except AttributeError:
            pendbase = None
        _Exporter.__init__(self, pendbase)

        self._beam_exporters[GaussianBeam] = self._export_dummy

        self._detector_exporters[
            BackscatteredElectronEnergyDetector] = self._export_dummy
        self._detector_exporters[
            TransmittedElectronEnergyDetector] = self._export_dummy
        self._detector_exporters[PhotonSpectrumDetector] = self._export_dummy
        self._detector_exporters[PhotonIntensityDetector] = self._export_dummy
        self._detector_exporters[PhotonDepthDetector] = self._export_dummy
        self._detector_exporters[ElectronFractionDetector] = self._export_dummy
        self._detector_exporters[TimeDetector] = self._export_dummy
        self._detector_exporters[
            ShowersStatisticsDetector] = self._export_dummy

        self._limit_exporters[ShowersLimit] = self._export_dummy
        self._limit_exporters[TimeLimit] = self._export_dummy
        self._limit_exporters[UncertaintyLimit] = self._export_dummy
예제 #9
0
    def __init__(self, options=None, parent=None):
        QWizard.__init__(self, parent)
        if options is None:
            self.setWindowTitle("Create new options")
        else:
            self.setWindowTitle("Modify options")
        self.setWizardStyle(QWizard.WizardStyle.ClassicStyle)

        # Variables
        if options is None:
            options = Options()
        options = copy.deepcopy(options)
        self._options = options

        settings = get_settings()
        if not settings.get_programs():
            raise RuntimeError('No programs are defined. Run the configuration first.')

        # Pages
        self.addPage(NameWizardPage(options))
        self.addPage(ProgramWizardPage(options))
        self.addPage(BeamWizardPage(options))
        self.addPage(GeometryWizardPage(options))
        self.addPage(DetectorWizardPage(options))
        self.addPage(LimitWizardPage(options))
        self.addPage(ModelWizardPage(options))
        self.addPage(WarningWizardPage(options))
예제 #10
0
    def validate(self):
        _PenelopeProgram.validate(self)

        settings = get_settings()

        if 'penshower' not in settings:
            raise AssertionError("Missing 'penshower' section in settings")

        if 'exe' not in settings.penshower:
            raise AssertionError(
                "Missing 'exe' option in 'penshower' section of settings")

        pendbase = settings.penshower.pendbase
        if not os.path.isdir(pendbase):
            raise AssertionError(
                "Specified PENELOPE pendbase directory (%s) does not exist" %
                pendbase)

        exe = settings.penshower.exe
        if not os.path.isfile(exe):
            raise AssertionError(
                "Specified PENSHOWER executable (%s) does not exist" % exe)
        if not os.access(exe, os.X_OK):
            raise AssertionError(
                "Specified PENSHOWER executable (%s) is not executable" % exe)
예제 #11
0
    def autoconfig(self, programs_path):
        settings = get_settings()

        # Java
        try:
            if os.name == 'posix':
                java_path = subprocess.check_output(['which', 'java'])
            else:
                java_path = subprocess.check_output(
                    'for %i in (java.exe) do @echo.   %~$PATH:i', shell=True)
            java_path = java_path.decode('ascii').strip()
        except subprocess.CalledProcessError:
            return False
        settings.add_section('pap').java = java_path

        # jar
        if sys.platform == 'linux':
            jar_path = '/usr/share/libpymontecarlo-java/lib/pymontecarlo-dtsa2-pap.jar'
            if not os.path.exists(jar_path):
                return False
        else:
            jar_path = os.path.join(programs_path, self.alias,
                                    'pymontecarlo-dtsa2-pap.jar')
            if not os.path.exists(jar_path):
                return False
        settings.add_section('pap').jar = jar_path

        return True
예제 #12
0
    def autoconfig(self, programs_path):
        settings = get_settings()

        # Java
        try:
            if os.name == 'posix':
                java_path = subprocess.check_output(['which', 'java'])
            else:
                java_path = subprocess.check_output('for %i in (java.exe) do @echo.   %~$PATH:i', shell=True)
            java_path = java_path.decode('ascii').strip()
        except subprocess.CalledProcessError:
            return False
        settings.add_section('xpp').java = java_path

        # jar
        if sys.platform == 'linux':
            jar_path = '/usr/share/libpymontecarlo-java/lib/pymontecarlo-dtsa2-xpp.jar'
            if not os.path.exists(jar_path):
                return False
        else:
            jar_path = os.path.join(programs_path, self.alias, 'pymontecarlo-dtsa2-xpp.jar')
            if not os.path.exists(jar_path):
                return False
        settings.add_section('xpp').jar = jar_path

        return True
예제 #13
0
    def autoconfig(self, programs_path):
        settings = get_settings()

        # Java
        try:
            if os.name == "posix":
                java_path = subprocess.check_output(["which", "java"])
            else:
                java_path = subprocess.check_output("for %i in (java.exe) do @echo.   %~$PATH:i", shell=True)
            java_path = java_path.decode("ascii").strip()
        except subprocess.CalledProcessError:
            return False
        settings.add_section("pap").java = java_path

        # jar
        if sys.platform == "linux":
            jar_path = "/usr/share/libpymontecarlo-java/lib/pymontecarlo-dtsa2-pap.jar"
            if not os.path.exists(jar_path):
                return False
        else:
            jar_path = os.path.join(programs_path, self.alias, "pymontecarlo-dtsa2-pap.jar")
            if not os.path.exists(jar_path):
                return False
        settings.add_section("pap").jar = jar_path

        return True
예제 #14
0
    def _initUI(self):
        # Variable
        settings = get_settings()

        # Widgets
        self._checkboxes = {}
        for program in settings.get_programs():
            self._checkboxes[program] = QCheckBox(program.name)

        btn_selectall = QPushButton('Select all')
        btn_deselectall = QPushButton('Deselect all')

        # Layouts
        layout = _OptionsWizardPage._initUI(self)
        for program in sorted(self._checkboxes.keys() , key=attrgetter('name')):
            layout.addRow(self._checkboxes[program])

        spacer = QSpacerItem(0, 1000, QSizePolicy.Expanding, QSizePolicy.Expanding)
        layout.addItem(spacer)

        sublayout = QHBoxLayout()
        sublayout.addWidget(btn_selectall)
        sublayout.addWidget(btn_deselectall)
        layout.addRow(sublayout)

        # Signals
        btn_selectall.released.connect(self._onSelectAll)
        btn_deselectall.released.connect(self._onDeselectAll)

        return layout
예제 #15
0
    def validate(self):
        settings = get_settings()

        if 'pap' not in settings:
            raise AssertionError("Missing 'pap' section in settings")

        if 'java' not in settings.pap:
            raise AssertionError(
                "Missing 'java' option in 'pap' section of settings")

        java = settings.pap.java
        if not os.path.isfile(java):
            raise AssertionError(
                "Specified Java executable (%s) does not exist" % java)
        if not os.access(java, os.X_OK):
            raise AssertionError(
                "Specified Java executable (%s) is not executable" % java)

        if 'jar' not in settings.pap:
            raise AssertionError(
                "Missing 'jar' option in 'pap' section of settings")

        jar = settings.pap.jar
        if not os.path.isfile(jar):
            raise AssertionError("Specified jar path (%s) does not exist" %
                                 jar)
        if os.path.splitext(jar)[1] != '.jar':
            raise AssertionError("Specified jar path (%s) is not a jar" % jar)
예제 #16
0
    def run(self):
        # Extract choices
        settings = get_settings()
        programs = sorted(settings.get_available_programs(),
                          key=attrgetter('name'))
        attr = self.arguments[0]

        choices = {}
        for program in programs:
            converter = program.converter_class

            for clasz in getattr(converter, attr, []):
                modulepath = clasz.__module__ + '.' + clasz.__name__
                choices.setdefault(modulepath, set()).add(program)

        if 'only' in self.options:
            if self.options['only'] not in choices:
                raise ValueError("Unknown module in only flag")

        # Create table
        table_node = self._build_table(programs, choices)
        table_node['classes'] += self.options.get('class', [])

        self.add_name(table_node)
        return [table_node]
예제 #17
0
def run(argv=None):
    # Initialise programs
    get_settings().get_programs()

    # Initialise console
    console = Console()
    console.init()

    # Create parser
    usage = "%prog [options] [OPTION_FILE.xml or RESULTS_FILE.zip or RESULTS_FILE.h5 ...]"
    description = "pyMonteCarlo update tool. This script updates old version " + \
                  "of options or results file to the newer one."
    epilog = "For more information, see http://pymontecarlo.bitbucket.org"

    parser = OptionParser(usage=usage, description=description, epilog=epilog)

    parser.add_option('-v', '--verbose', dest='verbose', default=False,
                      action='store_true', help='Debug mode')

    # Parse arguments
    (values, args) = parser.parse_args(argv)

    if values.verbose:
        logging.getLogger().setLevel(logging.DEBUG)

    if not args:
        console.print_error('Please specify at least one file')

    for filepath in args:
        if not os.path.exists(filepath):
            console.print_error('File %s does not exists' % filepath)

        ext = os.path.splitext(filepath)[1]

        if ext == '.xml':
            console.print_info("Updating options %s" % filepath)
            filepath = OptionsUpdater().update(filepath)
            console.print_success("Successfully updated %s" % filepath)
        elif ext == '.zip' or ext == '.h5':
            console.print_info("Updating results %s" % filepath)
            filepath = ResultsUpdater().update(filepath)
            console.print_success("Successfully results %s" % filepath)
        else:
            console.print_error('Unknown extension %s' % ext)

    console.close()
예제 #18
0
    def __init__(self, queue_options, outputdir, workdir=None, overwrite=True):
        """
        Runner to run Casino 3 simulation(s).
        """
        _Worker.__init__(self, queue_options, outputdir, workdir, overwrite)

        self._executable = get_settings().casino3.exe
        if not os.path.isfile(self._executable):
            raise IOError('Casino 3 executable (%s) cannot be found' % self._executable)
        logging.debug('Casino 3 executable: %s', self._executable)
예제 #19
0
    def __init__(self, program):
        """
        Runner to run PENSHOWER simulation(s).
        """
        _Worker.__init__(self, program)

        self._executable = get_settings().penshower.exe
        if not os.path.isfile(self._executable):
            raise IOError('PENSHOWER executable (%s) cannot be found' % self._executable)
        logging.debug('PENSHOWER executable: %s', self._executable)
예제 #20
0
파일: worker.py 프로젝트: xghui/winXray-1
    def __init__(self, program):
        """
        Runner to run WinX-Ray simulation(s).
        """
        _Worker.__init__(self, program)

        self._executable = get_settings().winxray.exe
        logging.debug('WinX-Ray executable: %s', self._executable)

        self._executable_dir = os.path.dirname(self._executable)
        logging.debug('WinX-Ray directory: %s', self._executable_dir)
예제 #21
0
 def add(self, value):
     if isinstance(value, Program):
         alias = value.alias
         program = value
     else:
         alias = value
         try:
             program = get_settings().get_program(alias, validate=False)
         except ValueError:
             program = None
     self._programs[alias] = program
예제 #22
0
    def __init__(self, program):
        """
        Runner to run PENSHOWER simulation(s).
        """
        _Worker.__init__(self, program)

        self._executable = get_settings().penshower.exe
        if not os.path.isfile(self._executable):
            raise IOError('PENSHOWER executable (%s) cannot be found' %
                          self._executable)
        logging.debug('PENSHOWER executable: %s', self._executable)
예제 #23
0
    def __init__(self, program):
        """
        Runner to run Casino2 simulation(s).
        """
        _Worker.__init__(self, program)

        self._executable = get_settings().casino2.exe
        logging.debug('Casino2 executable: %s', self._executable)

        self._executable_dir = os.path.dirname(self._executable)
        logging.debug('Casino2 directory: %s', self._executable_dir)
예제 #24
0
    def validate(self):
        settings = get_settings()

        if 'casino3' not in settings:
            raise AssertionError("Missing 'casino3' section in settings")

        if 'exe' not in settings.casino3:
            raise AssertionError("Missing 'exe' option in 'casino3' section of settings")

        exe = settings.casino3.exe
        if not os.path.isfile(exe):
            raise AssertionError("Specified Casino 3 executable (%s) does not exist" % exe)
예제 #25
0
    def validate(self):
        settings = get_settings()

        if 'casino3' not in settings:
            raise AssertionError("Missing 'casino3' section in settings")

        if 'exe' not in settings.casino3:
            raise AssertionError(
                "Missing 'exe' option in 'casino3' section of settings")

        exe = settings.casino3.exe
        if not os.path.isfile(exe):
            raise AssertionError(
                "Specified Casino 3 executable (%s) does not exist" % exe)
예제 #26
0
    def autoconfig(self, programs_path):
        if sys.platform == 'linux':
            pendbase_path = '/usr/share/penelope-pendbase'
            if not os.path.exists(pendbase_path):
                return False
        else:
            pendbase_path = os.path.join(programs_path, 'penelope', 'pendbase')
            if not os.path.exists(pendbase_path):
                return False

        settings = get_settings()
        settings.add_section(self.alias).pendbase = pendbase_path

        return True
예제 #27
0
    def autoconfig(self, programs_path):
        if sys.platform == 'linux':
            exe_path = '/usr/bin/casino2'
            if not os.path.exists(exe_path):
                return False
        else:
            paths = glob.glob(os.path.join(programs_path, self.alias, '*casino*'))
            if len(paths) != 1:
                return False
            exe_path = paths[0]

        settings = get_settings()
        settings.add_section('casino2').exe = exe_path
        return True
예제 #28
0
    def validate(self):
        settings = get_settings()

        if 'winxray' not in settings:
            raise AssertionError("Missing 'winxray' section in settings")

        if 'exe' not in settings.winxray:
            raise AssertionError("Missing 'exe' option in 'winxray' section of settings")

        exe = settings.winxray.exe
        if os.path.splitext(exe)[1] != '.app' and not os.path.isfile(exe):
            raise AssertionError("Specified WinXRay executable (%s) does not exist" % exe)
        if not os.access(exe, os.X_OK):
            raise AssertionError("Specified WinXRay executable (%s) is not executable" % exe)
예제 #29
0
    def autoconfig(self, programs_path):
        if sys.platform == 'linux':
            pendbase_path = '/usr/share/penelope-pendbase'
            if not os.path.exists(pendbase_path):
                return False
        else:
            pendbase_path = os.path.join(programs_path, 'penelope', 'pendbase')
            if not os.path.exists(pendbase_path):
                return False

        settings = get_settings()
        settings.add_section(self.alias).pendbase = pendbase_path

        return True
예제 #30
0
    def __init__(self):
        """
        Creates a exporter to PENSHOWER.
        """
        try:
            pendbase = get_settings().penepma.pendbase
        except AttributeError:
            pendbase = None
        _Exporter.__init__(self, pendbase)

        self._beam_exporters[GaussianBeam] = self._export_dummy

        self._detector_exporters[TrajectoryDetector] = self._export_dummy

        self._limit_exporters[ShowersLimit] = self._export_dummy
예제 #31
0
    def __init__(self):
        """
        Creates a exporter to PENSHOWER.
        """
        try:
            pendbase = get_settings().penepma.pendbase
        except AttributeError:
            pendbase = None
        _Exporter.__init__(self, pendbase)

        self._beam_exporters[GaussianBeam] = self._export_dummy

        self._detector_exporters[TrajectoryDetector] = self._export_dummy

        self._limit_exporters[ShowersLimit] = self._export_dummy
예제 #32
0
    def _append_job_properties(self, lines, options, geoinfo, matinfos,
                               phdets_key_index, phdets_index_keys, *args):
        lines.append(self._COMMENT_JOBPROP())

        text = 'dump.dat'
        line = self._KEYWORD_RESUME(text)
        lines.append(line)

        text = 'dump.dat'
        line = self._KEYWORD_DUMPTO(text)
        lines.append(line)

        text = getattr(get_settings().penepma, 'dumpp', 60.0)
        line = self._KEYWORD_DUMPP(text)
        lines.append(line)

        lines.append(self._COMMENT_SKIP())

        #NOTE: No random number. PENEPMA will select them.

        limits = list(options.limits.iterclass(UncertaintyLimit))
        if limits:
            limit = limits[0]
            transition = limit.transition
            detector = phdets_key_index[limit.detector_key] + 1
            uncertainty = limit.uncertainty

            code = int(transition.z * 1e6 + \
                       transition.dest.index * 1e4 + \
                       transition.src.index * 1e2)
            text = [code, detector, uncertainty]
            line = self._KEYWORD_REFLIN(text)
            lines.append(line)

        limits = list(options.limits.iterclass(ShowersLimit))
        showers = limits[0].showers if limits else 1e38
        text = '%e' % showers
        line = self._KEYWORD_NSIMSH(text)
        lines.append(line)

        limits = list(options.limits.iterclass(TimeLimit))
        time_s = limits[0].time_s if limits else 1e38
        text = '%e' % time_s
        line = self._KEYWORD_TIME(text)
        lines.append(line)

        lines.append(self._COMMENT_SKIP())
예제 #33
0
    def _append_job_properties(self, lines, options, geoinfo, matinfos,
                               phdets_key_index, phdets_index_keys, *args):
        lines.append(self._COMMENT_JOBPROP())

        text = 'dump.dat'
        line = self._KEYWORD_RESUME(text)
        lines.append(line)

        text = 'dump.dat'
        line = self._KEYWORD_DUMPTO(text)
        lines.append(line)

        text = getattr(get_settings().penepma, 'dumpp', 60.0)
        line = self._KEYWORD_DUMPP(text)
        lines.append(line)

        lines.append(self._COMMENT_SKIP())

        #NOTE: No random number. PENEPMA will select them.

        limits = list(options.limits.iterclass(UncertaintyLimit))
        if limits:
            limit = limits[0]
            transition = limit.transition
            detector = phdets_key_index[limit.detector_key] + 1
            uncertainty = limit.uncertainty

            code = int(transition.z * 1e6 + \
                       transition.dest.index * 1e4 + \
                       transition.src.index * 1e2)
            text = [code, detector, uncertainty]
            line = self._KEYWORD_REFLIN(text)
            lines.append(line)

        limits = list(options.limits.iterclass(ShowersLimit))
        showers = limits[0].showers if limits else 1e38
        text = '%e' % showers
        line = self._KEYWORD_NSIMSH(text)
        lines.append(line)

        limits = list(options.limits.iterclass(TimeLimit))
        time_s = limits[0].time_s if limits else 1e38
        text = '%e' % time_s
        line = self._KEYWORD_TIME(text)
        lines.append(line)

        lines.append(self._COMMENT_SKIP())
예제 #34
0
    def autoconfig(self, programs_path):
        if not _PenelopeProgram.autoconfig(self, programs_path):
            return False

        if sys.platform == 'linux':
            exe_path = '/usr/bin/penepma'
        else:
            paths = glob.glob(os.path.join(programs_path, self.alias, 'bin', 'penepma'))
            if len(paths) != 1:
                return False
            exe_path = paths[0]

        settings = get_settings()
        settings.add_section('penepma').exe = exe_path
        settings.add_section('penepma').dumpp = 30

        return True
예제 #35
0
    def autoconfig(self, programs_path):
        if not _PenelopeProgram.autoconfig(self, programs_path):
            return False

        if sys.platform == "linux":
            exe_path = "/usr/bin/penshower"
            if not os.path.exists(exe_path):
                return False
        else:
            paths = glob.glob(os.path.join(programs_path, self.alias, "bin", "penshower"))
            if len(paths) != 1:
                return False
            exe_path = paths[0]

        settings = get_settings()
        settings.add_section("penshower").exe = exe_path

        return True
예제 #36
0
def run(argv=None):
    # Initialize
    console = Console()
    console.init()

    console.print_message("Configuration of pyMonteCarlo")
    console.print_line()

    # Find settings.cfg
    settings = get_settings()

    # Programs
    programs = []

    for program_alias in settings.get_available_program_aliases():
        default = program_alias in settings.get_program_aliases()
        answer = \
            console.prompt_boolean("Do you want to setup %s?" % program_alias, default)
        if answer:
            cli = settings.get_program_cli(program_alias)
            try:
                pass
            except Exception as ex:
                console.print_exception(ex)
                return

            cli.configure(console, settings)

            programs.append(program_alias)
        else:
            if program_alias in settings:
                delattr(settings, program_alias)

        console.print_line()

    settings.pymontecarlo.programs = ','.join(programs)

    # Save
    settings.write()
    console.print_success("Settings saved")

    # Finalize
    console.close()
예제 #37
0
    def validate(self):
        _PenelopeProgram.validate(self)

        settings = get_settings()

        if 'penepma' not in settings:
            raise AssertionError("Missing 'penepma' section in settings")

        if 'exe' not in settings.penepma:
            raise AssertionError("Missing 'exe' option in 'penepma' section of settings")

        pendbase = settings.penepma.pendbase
        if not os.path.isdir(pendbase):
            raise AssertionError("Specified PENELOPE pendbase directory (%s) does not exist" % pendbase)

        exe = settings.penepma.exe
        if not os.path.isfile(exe):
            raise AssertionError("Specified PENEPMA executable (%s) does not exist" % exe)
        if not os.access(exe, os.X_OK):
            raise AssertionError("Specified PENEPMA executable (%s) is not executable" % exe)
예제 #38
0
    def save(self):
        settings = get_settings()
        section = settings.add_section('gui')
        curdir = getattr(section, 'savedir', os.getcwd())
        namefilters = ';;'.join(sorted(self._save_namefilters.keys()))

        filepath, namefilter = \
            QFileDialog.getSaveFileName(self, "Save", curdir, namefilters)

        if not filepath:
            return
        section.savedir = os.path.dirname(filepath)

        exts = self._save_namefilters[namefilter]
        if not any(filter(lambda ext: filepath.endswith(ext), exts)):
            filepath += '.' + exts[0]

        ext = os.path.splitext(filepath)[1][1:]
        method = self._save_methods.get(ext)
        if method is not None:
            method(filepath)
예제 #39
0
    def autoconfig(self, programs_path):
        if sys.platform == 'linux':
            basedir_path = '/usr/share/monaco'
            if not os.path.exists(basedir_path):
                return False

            exe_path = '/usr/bin/mccli32'
            if not os.path.exists(exe_path):
                return False
        else:
            basedir_path = os.path.join(programs_path, self.alias)
            if not os.path.exists(basedir_path):
                return False

            exe_path = os.path.join(programs_path, self.alias, 'Mccli32.exe')
            if not os.path.exists(exe_path):
                return False

        settings = get_settings()
        settings.add_section('monaco').basedir = basedir_path
        settings.add_section('monaco').exe = exe_path
        return True
예제 #40
0
    def autoconfig(self, programs_path):
        if sys.platform == 'linux':
            basedir_path = '/usr/share/monaco'
            if not os.path.exists(basedir_path):
                return False

            exe_path = '/usr/bin/mccli32'
            if not os.path.exists(exe_path):
                return False
        else:
            basedir_path = os.path.join(programs_path, self.alias)
            if not os.path.exists(basedir_path):
                return False

            exe_path = os.path.join(programs_path, self.alias, 'Mccli32.exe')
            if not os.path.exists(exe_path):
                return False

        settings = get_settings()
        settings.add_section('monaco').basedir = basedir_path
        settings.add_section('monaco').exe = exe_path
        return True
예제 #41
0
    def validate(self):
        settings = get_settings()

        if 'xpp' not in settings:
            raise AssertionError("Missing 'xpp' section in settings")

        if 'java' not in settings.xpp:
            raise AssertionError("Missing 'java' option in 'xpp' section of settings")

        java = settings.xpp.java
        if not os.path.isfile(java):
            raise AssertionError("Specified Java executable (%s) does not exist" % java)
        if not os.access(java, os.X_OK):
            raise AssertionError("Specified Java executable (%s) is not executable" % java)

        if 'jar' not in settings.xpp:
            raise AssertionError("Missing 'jar' option in 'xpp' section of settings")

        jar = settings.xpp.jar
        if not os.path.isfile(jar):
            raise AssertionError("Specified jar path (%s) does not exist" % jar)
        if os.path.splitext(jar)[1] != '.jar':
            raise AssertionError("Specified jar path (%s) is not a jar" % jar)
예제 #42
0
    def closeEvent(self, event):
        if self.is_running():
            message = 'Runner is running. Do you want to continue?'
            answer = QMessageBox.question(self, 'Runner', message,
                                          QMessageBox.Yes | QMessageBox.No)
            if answer == QMessageBox.No:
                event.ignore()
                return

        self.cancel()
        self._dlg_progress.close()

        settings = get_settings()
        section = settings.add_section('gui')

        path = self._txt_outputdir.path()
        if path:
            section.outputdir = path
        section.maxworkers = str(self._spn_workers.value())
        section.overwrite = str(self._chk_overwrite.isChecked())

        settings.write()

        event.accept()
예제 #43
0
    def __init__(self):
        """
        Creates a exporter to PENEPMA.
        """
        try:
            pendbase = get_settings().penepma.pendbase
        except AttributeError:
            pendbase = None
        _Exporter.__init__(self, pendbase)

        self._beam_exporters[GaussianBeam] = self._export_dummy

        self._detector_exporters[BackscatteredElectronEnergyDetector] = self._export_dummy
        self._detector_exporters[TransmittedElectronEnergyDetector] = self._export_dummy
        self._detector_exporters[PhotonSpectrumDetector] = self._export_dummy
        self._detector_exporters[PhotonIntensityDetector] = self._export_dummy
        self._detector_exporters[PhotonDepthDetector] = self._export_dummy
        self._detector_exporters[ElectronFractionDetector] = self._export_dummy
        self._detector_exporters[TimeDetector] = self._export_dummy
        self._detector_exporters[ShowersStatisticsDetector] = self._export_dummy

        self._limit_exporters[ShowersLimit] = self._export_dummy
        self._limit_exporters[TimeLimit] = self._export_dummy
        self._limit_exporters[UncertaintyLimit] = self._export_dummy
예제 #44
0
    def _onOpen(self):
        settings = get_settings()
        curdir = getattr(settings.gui, 'opendir', os.getcwd())

        filepath, namefilter = \
            QFileDialog.getOpenFileName(self, "Open", curdir,
                                        'Options [*.xml] (*.xml)')

        if not filepath or not namefilter:
            return
        settings.gui.opendir = os.path.dirname(filepath)

        if not filepath.endswith('.xml'):
            filepath += '.xml'

        self._options_reader_thread = _OptionsReaderWrapperThread(filepath)
        self._dlg_progress.canceled.connect(self._onDialogProgressCancel)
        self._options_reader_thread.resultReady.connect(self._onOpened)
        self._options_reader_thread.progressUpdated.connect(self._onDialogProgressProgress)
        self._options_reader_thread.exceptionRaised.connect(self._onDialogProgressException)
        self._options_reader_thread.start()

        self._dlg_progress.reset()
        self._dlg_progress.show()
예제 #45
0
    def validate(self):
        settings = get_settings()

        if 'monaco' not in settings:
            raise AssertionError("Missing 'monaco' section in settings")

        if 'basedir' not in settings.monaco:
            raise AssertionError("Missing 'basedir' option in 'monaco' section of settings")

        basedir = settings.monaco.basedir
        if not os.path.isdir(basedir):
            raise AssertionError("Specified Monaco base directory (%s) does not exist" % basedir)

        try:
            mccli32_exe = settings.monaco.exe
        except AttributeError:
            filename = 'Mccli32'
            if os.name == 'nt':
                filename += '.exe'
            mccli32_exe = os.path.join(settings.monaco.basedir, filename)
        if not os.path.isfile(mccli32_exe):
            raise AssertionError("No Mccli32.exe in Monaco base directory (%s)" % basedir)
        if not os.access(mccli32_exe, os.X_OK):
            raise AssertionError("Specified Monaco executable (%s) is not executable" % mccli32_exe)
예제 #46
0
    def run(self):
        # Extract choices
        settings = get_settings()
        programs = sorted(settings.get_available_programs(), key=attrgetter('name'))
        attr = self.arguments[0]

        choices = {}
        for program in programs:
            converter = program.converter_class

            for clasz in getattr(converter, attr, []):
                modulepath = clasz.__module__ + '.' + clasz.__name__
                choices.setdefault(modulepath, set()).add(program)

        if 'only' in self.options:
            if self.options['only'] not in choices:
                raise ValueError("Unknown module in only flag")

        # Create table
        table_node = self._build_table(programs, choices)
        table_node['classes'] += self.options.get('class', [])

        self.add_name(table_node)
        return [table_node]
예제 #47
0
    def setUp(self):
        TestCase.setUp(self)

        self.tmpdir = tempfile.mkdtemp()
        self.e = Exporter(get_settings().penepma.pendbase)
        self.c = Converter()
예제 #48
0
def run(argv=None):
    # Initialize
    console = Console()
    console.init()

    programs = get_settings().get_programs()

    parser = create_parser(programs)

    # Parse arguments
    (values, args) = parser.parse_args(argv)

    # Check inputs
    outputdir = values.outputdir
    if not os.path.exists(outputdir):
        console.print_error("The specified output directory (%s) does not exist" % outputdir)

    workdir = values.workdir
    if workdir is not None and not os.path.exists(workdir):
        console.print_error("The specified work directory (%s) does not exist" % workdir)

    if values.verbose:
        logging.getLogger().setLevel(logging.DEBUG)

    quiet = values.quiet

    nbprocesses = values.nbprocesses
    if nbprocesses <= 0:
        parser.error("Number of processes must be greater than 0.")

    overwrite = not values.skip

    max_iterations = values.max_iterations
    if max_iterations < 0:
        raise ValueError, 'Maximum number of iterations must be greater or equal to 0'

    convergence_limit = values.convergence_limit
    if convergence_limit <= 0.0:
        raise ValueError, 'Convergence limit must be greater than 0.0'

    if values.linear:
        iterator_class = SimpleIterator
    elif values.pouchou1991:
        iterator_class = Pouchou1991Iterator
    elif values.wegstein1958:
        iterator_class = Wegstein1958Iterator
    else:
        iterator_class = Heinrich1972Iterator

    if values.kratio:
        convergor_class = KRatioConvergor
    else:
        convergor_class = CompositionConvergor

    if values.fluorescence:
        calculator_class = FluorescenceCalculator
    else:
        calculator_class = SimpleCalculator

    aliases = map(attrgetter('alias'), programs)
    selected_programs = [alias for alias in aliases if getattr(values, alias)]
    if not selected_programs:
        console.print_error("Please select one Monte Carlo program")
    if len(selected_programs) > 1:
        console.print_error("Please select only one Monte Carlo program")
    selected_program = selected_programs[0]

    workers = dict(zip(aliases, map(attrgetter('worker'), programs)))
    worker_class = workers[selected_program]

    measurements = []
    try:
        load_measurements(args, measurements)
    except Exception as ex:
        console.print_error(str(ex))

    if not measurements:
        console.print_error("Please specify a measurement file")

    # Setup
    runner = Runner(worker_class, iterator_class, convergor_class, calculator_class,
                    outputdir, workdir,
                    overwrite, max_iterations, nbprocesses,
                    limit=convergence_limit)

    progressbar = ProgressBar(console, len(measurements))
    if not quiet: progressbar.start()

    runner.start()

    for measurement in measurements:
        runner.put(measurement)

    try:
        while runner.is_alive():
            counter, progress, status = runner.report()
            if not quiet: progressbar.update(counter, progress, status)
            time.sleep(1)
    except Exception as ex:
        console.print_error('%s - %s' % (ex.__class__.__name__, str(ex)))

    runner.stop()
    if not quiet: progressbar.close()

    # Clean up
    console.close()
예제 #49
0
def run(argv=None):
    # Initialize
    console = Console()
    console.init()

    programs = get_settings().get_programs()

    parser = _create_parser(programs)

    # Parse arguments
    (values, args) = parser.parse_args(argv)

    # Check inputs
    outputdir = values.outputdir
    if not os.path.exists(outputdir):
        console.print_error(
            "The specified output directory (%s) does not exist" % outputdir)

    workdir = values.workdir
    if workdir is not None and not os.path.exists(workdir):
        console.print_error(
            "The specified work directory (%s) does not exist" % workdir)

    if values.verbose:
        logging.getLogger().setLevel(logging.DEBUG)

    quiet = values.quiet

    nbprocesses = values.nbprocesses
    if nbprocesses <= 0:
        parser.error("Number of processes must be greater than 0.")

    overwrite = not values.skip

    aliases = dict(zip(map(attrgetter('alias'), programs), programs))
    selected_aliases = [alias for alias in aliases if getattr(values, alias)]
    if not selected_aliases:
        console.print_error("Please select one Monte Carlo program")
    selected_programs = list(map(aliases.get, selected_aliases))

    list_options = []
    try:
        _load(args, list_options)
    except Exception as ex:
        console.print_error(str(ex))

    if not list_options:
        console.print_error("Please specify at least one options file")

    # Setup
    runner = LocalRunner(outputdir, workdir, overwrite, nbprocesses)

    progressbar = ProgressBar(console)
    if not quiet: progressbar.start()

    # Start simulation
    with runner:
        for options in list_options:
            options.programs.update(selected_programs)
            runner.put(options)

        try:
            while runner.is_alive() and not runner.is_finished():
                if not quiet:
                    progressbar.update(runner.progress, runner.status)
                time.sleep(1)

        except Exception as ex:
            console.print_exception(ex)

        runner.close()

    if not quiet: progressbar.close()

    # Clean up
    console.close()
예제 #50
0
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setWindowTitle('Runner')
        self.setMinimumWidth(750)

        # Runner
        self._runner = None

        self._running_timer = QTimer()
        self._running_timer.setInterval(500)

        # Widgets
        self._dlg_progress = QProgressDialog()
        self._dlg_progress.setRange(0, 100)
        self._dlg_progress.setModal(True)
        self._dlg_progress.hide()

        lbl_outputdir = QLabel("Output directory")
        self._txt_outputdir = DirBrowseWidget()

        max_workers = cpu_count() #@UndefinedVariable
        lbl_workers = QLabel('Number of workers')
        self._spn_workers = QSpinBox()
        self._spn_workers.setRange(1, max_workers)
        self._spn_workers.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        lbl_max_workers = QLabel('(max: %i)' % max_workers)

        self._chk_overwrite = QCheckBox("Overwrite existing results in output directory")
        self._chk_overwrite.setChecked(True)

        self._lbl_available = QLabel('Available')
        self._lst_available = QListView()
        self._lst_available.setModel(_AvailableOptionsListModel())
        self._lst_available.setSelectionMode(QListView.SelectionMode.MultiSelection)

        tlb_available = QToolBar()
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        tlb_available.addWidget(spacer)
        act_open = tlb_available.addAction(getIcon("document-open"), "Open")
        act_open.setShortcut(QKeySequence.Open)
        tlb_available.addSeparator()
        act_remove = tlb_available.addAction(getIcon("list-remove"), "Remove")
        act_clear = tlb_available.addAction(getIcon("edit-clear"), "Clear")

        self._btn_addtoqueue = QPushButton(getIcon("go-next"), "")
        self._btn_addtoqueue.setToolTip("Add to queue")
        self._btn_addtoqueue.setEnabled(False)

        self._btn_addalltoqueue = QPushButton(getIcon("go-last"), "")
        self._btn_addalltoqueue.setToolTip("Add all to queue")
        self._btn_addalltoqueue.setEnabled(False)

        self._lbl_options = QLabel('Queued/Running/Completed')
        self._tbl_options = QTableView()
        self._tbl_options.setModel(_StateOptionsTableModel())
        self._tbl_options.setItemDelegate(_StateOptionsItemDelegate())
        self._tbl_options.setSelectionMode(QListView.SelectionMode.NoSelection)
        self._tbl_options.setColumnWidth(1, 60)
        self._tbl_options.setColumnWidth(2, 80)
        header = self._tbl_options.horizontalHeader()
        header.setResizeMode(0, QHeaderView.Interactive)
        header.setResizeMode(1, QHeaderView.Fixed)
        header.setResizeMode(2, QHeaderView.Fixed)
        header.setResizeMode(3, QHeaderView.Stretch)

        self._btn_start = QPushButton(getIcon("media-playback-start"), "Start")

        self._btn_cancel = QPushButton("Cancel")
        self._btn_cancel.setEnabled(False)

        self._btn_close = QPushButton("Close")

        self._btn_import = QPushButton("Import")
        self._btn_import.setEnabled(False)

        # Layouts
        layout = QVBoxLayout()

        sublayout = QGridLayout()
        sublayout.addWidget(lbl_outputdir, 0, 0)
        sublayout.addWidget(self._txt_outputdir, 0, 1)
        sublayout.addWidget(lbl_workers, 1, 0)

        subsublayout = QHBoxLayout()
        subsublayout.addWidget(self._spn_workers)
        subsublayout.addWidget(lbl_max_workers)
        sublayout.addLayout(subsublayout, 1, 1)
        layout.addLayout(sublayout)

        sublayout.addWidget(self._chk_overwrite, 2, 0, 1, 3)

        sublayout = QGridLayout()
        sublayout.setColumnStretch(0, 1)
        sublayout.setColumnStretch(2, 3)
        sublayout.addWidget(self._lbl_available, 0, 0)
        sublayout.addWidget(self._lst_available, 1, 0)
        sublayout.addWidget(tlb_available, 2, 0)

        subsublayout = QVBoxLayout()
        subsublayout.addStretch()
        subsublayout.addWidget(self._btn_addtoqueue)
        subsublayout.addWidget(self._btn_addalltoqueue)
        subsublayout.addStretch()
        sublayout.addLayout(subsublayout, 1, 1)

        sublayout.addWidget(self._lbl_options, 0, 2)
        sublayout.addWidget(self._tbl_options, 1, 2)
        layout.addLayout(sublayout)

        sublayout = QHBoxLayout()
        sublayout.addStretch()
        sublayout.addWidget(self._btn_import)
        sublayout.addWidget(self._btn_start)
        sublayout.addWidget(self._btn_cancel)
        sublayout.addWidget(self._btn_close)
        layout.addLayout(sublayout)

        self.setLayout(layout)

        # Signal
        self._running_timer.timeout.connect(self._onRunningTimer)

        act_open.triggered.connect(self._onOpen)
        act_remove.triggered.connect(self._onRemove)
        act_clear.triggered.connect(self._onClear)

        self._btn_addtoqueue.released.connect(self._onAddToQueue)
        self._btn_addalltoqueue.released.connect(self._onAddAllToQueue)
        self._btn_start.released.connect(self._onStart)
        self._btn_cancel.released.connect(self._onCancel)
        self._btn_close.released.connect(self._onClose)
        self._btn_import.released.connect(self._onImport)

        self.options_added.connect(self._onOptionsAdded)
        self.options_running.connect(self._onOptionsRunning)
        self.options_simulated.connect(self._onOptionsSimulated)
        self.options_error.connect(self._onOptionsError)
        self.results_error.connect(self._onResultsError)

        # Defaults
        settings = get_settings()
        section = settings.add_section('gui')
        if hasattr(section, 'outputdir'):
            self._txt_outputdir.setPath(section.outputdir)
        if hasattr(section, 'maxworkers'):
            self._spn_workers.setValue(int(section.maxworkers))
        if hasattr(section, 'overwrite'):
            state = True if section.overwrite.lower() == 'true' else False
            self._chk_overwrite.setChecked(state)