Esempio n. 1
0
def initEnv():
    from prophesy.config import configuration
    ensure_dir_exists(web_configuration.get_sessions_dir())
    ensure_dir_exists(web_configuration.get_results_dir())
    ensure_dir_exists(web_configuration.get_examples_dir())

    # Check available model checkers, solvers and various other regions
    # and adjust capabilities based on that
    global satSolvers, samplers, ppmcs
    satSolvers = configuration.getAvailableSMTSolvers()
    samplers = configuration.getAvailableSamplers()
    ppmcs = configuration.getAvailableParametricMCs()

    # Preload some result files for easy startup
    print("Loading default result files...")
    rat_path = web_configuration.get_examples_dir()
    try:
        ratfiles = os.listdir(rat_path)
        for rfile in ratfiles:
            fullpath = os.path.join(rat_path, rfile)
            try:
                read_pstorm_result(fullpath)
                default_results[rfile] = fullpath
            except:
                pass
    except:
        pass

    print("Done checking environment")
def load_solution_function(state, solution_file):
    result = read_pstorm_result(solution_file)
    state.problem_description.parameters = result.parameters
    state.problem_description.solution_function = result.ratfunc
    state.problem_description.welldefined_constraints = result.welldefined_constraints
    state.problem_description.graph_preserving_constraints = result.graph_preservation_constraints
    return state
Esempio n. 3
0
    def get_rational_function(self):
        logger.info("Compute solution function")

        if self.pctlformula is None:
            raise NotEnoughInformationError("pctl formula missing")
        if not self._has_model_set():
            raise NotEnoughInformationError("model missing")

        if self.drnfile:
            if self.drnfile.model_type != ModelType.DTMC:
                raise UnsupportedModel(
                    "Rational functions can only be computed for DTMCs.")
        elif self.prismfile:
            if self.prismfile.model_type != ModelType.DTMC:
                raise UnsupportedModel(
                    "Rational functions can only be computed for DTMCs.")

        # create a temporary file for the result.
        ensure_dir_exists(prophesy.config.configuration.get_intermediate_dir())
        fd, resultfile = tempfile.mkstemp(
            suffix=".txt",
            dir=prophesy.config.configuration.get_intermediate_dir(),
            text=True)
        os.close(fd)

        constants_string = self.constants.to_key_value_string(
            to_float=False) if self.constants else ""

        args = [
            self.parameter_location, '--prop',
            str(self.pctlformula), '--parametric', '--parametric:resultfile',
            resultfile, '--elimination:order', 'fwrev'
        ]
        if self.bisimulation == BisimulationType.strong:
            args.append('--bisimulation')
        if constants_string != "":
            args.append('-const')
            args.append(constants_string)

        if self.drnfile:
            args += ['-drn', self.drnfile.location]
        elif self.prismfile:
            args += ['--prism', self.prismfile.location]

        logger.info("Call storm")
        ret_code = run_tool(args, False)
        if ret_code != 0:
            raise RuntimeError("Storm crashed with return code %s.", ret_code)
        else:
            logger.info("Storm call finished successfully")

        param_result = read_pstorm_result(resultfile)
        os.remove(resultfile)
        return param_result
Esempio n. 4
0
    def post(self):
        logger.info("Upload result post request")
        tool = self.get_argument('result-type')
        upload = self.request.files['result-file'][0]
        # Note: this is not the list of pmcCheckers, but of available result parsers
        if tool not in ['storm', 'param']:
            return self._json_error("Invalid tool selected")
        if upload is None:
            return self._json_error("Missing result file")

        result_files = self._get_session('result_files', {})

        (res_fd,
         res_file) = tempfile.mkstemp(".result",
                                      dir=web_configuration.get_results_dir())
        with os.fdopen(res_fd, "wb") as res_f:
            res_f.write(upload.body)

        try:
            if tool == 'storm':
                result = read_pstorm_result(res_file)
            elif tool == 'param':
                result = read_param_result(res_file)
            else:
                raise RuntimeError("Bad tool")
        except Exception as e:
            print(e)
            return self._json_error("Unable to parse result file")
        finally:
            os.unlink(res_file)

        # Write pstorm result as canonical
        (res_fd,
         res_file) = tempfile.mkstemp(".result",
                                      dir=web_configuration.get_results_dir())
        os.close(res_fd)
        write_pstorm_result(res_file, result)

        if upload.filename in result_files:
            os.unlink(result_files[upload.filename])
        result_files[upload.filename] = res_file
        self._set_session('current_result', upload.filename)
        self._set_session('result_files', result_files)

        return self._json_ok({"file": upload.filename})
Esempio n. 5
0
 def _getResultData(self, name):
     #TODO what if there multiple properties for the same model??
     self.setup_results()
     result_files = self._get_session('result_files', {})
     if not name in result_files:
         logger.warning("No known solution file for %s", name)
         return None
     try:
         logger.debug("Found solution file %s", result_files[name])
         result = read_pstorm_result(result_files[name])
         return result
     except ParserError as e:
         logger.error(str(e))
         raise RuntimeError("Invalid solution file {}".format(
             result_files[name]))
     except Exception as e:
         logger.warning(str(e))
         return None
Esempio n. 6
0
    def get_parameter_constraints(self):
        if not self._has_model_set():
            raise NotEnoughInformationError("model missing")
        if self.pctlformula is None:
            raise NotEnoughInformationError(
                "pctl formula missing")  # TODO not strictly necessary

        ensure_dir_exists(prophesy.config.configuration.get_intermediate_dir())
        fd, resultfile = tempfile.mkstemp(
            suffix=".txt",
            dir=prophesy.config.configuration.get_intermediate_dir(),
            text=True)
        os.close(fd)

        constants_string = self.constants.to_key_value_string(
            to_float=False) if self.constants else ""

        args = [
            self.parameter_location, '--prop',
            str(self.pctlformula), '--parametric', '--parametric:resultfile',
            resultfile, '--onlyconstraints'
        ]
        if constants_string != "":
            args.append('-const')
            args.append(constants_string)

        if self.drnfile:
            args += ['-drn', self.drnfile.location]
        elif self.prismfile:
            args += ['--prism', self.prismfile.location]

        logger.info("Call storm")
        ret_code = run_tool(args, False)
        if ret_code != 0:
            # TODO throw exception?
            RuntimeError("Return code %s after call with %s", ret_code,
                         " ".join(args))
        else:
            logger.info("Storm call finished successfully")

        param_result = read_pstorm_result(resultfile, False)
        return param_result.welldefined_constraints, param_result.graph_preservation_constraints
Esempio n. 7
0
    def get(self, name=None):
        self.setup_results()
        result_files = self._get_session('result_files', {})
        if name is None:
            return self._json_ok({k: k for k in result_files.keys()})

        if not name in result_files:
            return self._json_error("Result data not found", 404)

        try:
            print(result_files[name])
            result = read_pstorm_result(result_files[name])
        except:
            return self._json_error("Error reading result data")
        str_result = str(result)
        # Replace ** with superscript
        str_result = re.sub(r'\*\*(\d+)', r'<sub>\1</sub>', str_result)
        # Replace * with dot symbol
        str_result = re.sub(r'\*', r'&#183;', str_result)
        # Replace <= with symbol
        str_result = re.sub(r'\<\=', r'&#8804;', str_result)
        # Replace >= with symbol
        str_result = re.sub(r'\>\=', r'&#8805;', str_result)
        return self._json_ok(str_result)
Esempio n. 8
0
def test_read_pstorm_result_brp():
    read_pstorm_result(get_example_path("brp", "brp_16-2.rat"))