Exemplo n.º 1
0
    def model_to_objects(self, verbose=False, debug=False):
        '''
        Take the current model, print it to pysim with hyst, and return the result python objects:

        returns a 3-tuple (HybridAutomaton, List of HyperRectangle, PysimSettings). 

        This is useful to extract model parameters, such as the reachability time or time step, 
        or to process the model in python.
        '''

        e = Engine('pysim')

        filename = os.path.join(tempfile.gettempdir(), "pysim_" + random_string() + ".py")
        e.set_output(filename)

        e.set_verbose(verbose)
        e.set_debug(debug)

        if self.input_[0] is not None:
            e.set_input(self.input_[0], self.input_[1])
        elif self.gen[0] is not None:
            e.set_generator(self.gen[0], self.gen[1])
        else:
            raise RuntimeError('input or generator must be set prior to calling model_as_object()')

        result = e.run(run_tool=False)

        if result['code'] != Engine.SUCCESS:
            raise RuntimeError('Printing model to pysim failed: {}'.format(result))

        mod_name, _ = os.path.splitext(os.path.split(filename)[-1])
        pysim_model = imp.load_source(mod_name, filename)

        define_settings = getattr(pysim_model, 'define_settings')
        define_ha = getattr(pysim_model, 'define_ha')
        define_init_states = getattr(pysim_model, 'define_init_states')

        ha = define_ha()

        return (ha, define_init_states(ha), define_settings())
Exemplo n.º 2
0
    def run(self, run_hyst=True, run_tool=True, timeout=None, image_path=None, save_stdout=False, print_stdout=False, 
            stdout_func=None, parse_output=False):
        '''
        Converts the model in Hyst, runs it with the appropriate tool, 
        produces a plot image, and python results object.

        non-obvious parameters:
        stdout_func - a 3-param user function for processing of stream stdout. Params are: line, time, tool_name
        parse_output - should tool's output be parsed into a python object? If True, 'output' in the result is set.
                       using this option forces save_stdout to True

        returns a dictionary object with the following keys:
        'code' - exit code - engine.SUCCESS if successful, an engine.ERROR_* code otherwise
        'hyst_time' - time in seconds for hyst to run, only returned if run_hyst == True
        'tool_time' - time in seconds for tool(+image) to run, only returned if run_tool == True
        'time' - total run time in seconds
        'stdout' - the list of lines anything produced to stdout, only returned if save_stdout == True
        'tool_stdout' - the list of lines the tool produced to stdout, only returned if save_stdout == True
        'hypy_stdout' - the list of lines hypy produces to stdout, only returned if save_stdout == True
        'output' - tool-specific processed output object, only returned if successful and parse_output == True
        '''

        start_time = time.time()
        tool = TOOLS.get(self.printer[0])

        if self.output is None:
            self.output = os.path.join(tempfile.gettempdir(), self.printer[0] + \
                    "_" + random_string() + tool.default_ext())

        rv = {}
        rv['code'] = Engine.SUCCESS
        stdout_lines = None

        if parse_output:
            save_stdout = True
        
        if save_stdout:
            stdout_lines = []

        # wrapper function to capture all stdout in order
        def stdout_wrapper(line, secs, tool):
            'wrapper to capture lines produced by stdout from any tool'
    
            if stdout_lines is not None:
                stdout_lines.append(line)

            if stdout_func is not None:
                stdout_func(line, secs, tool)

            if print_stdout:
                print line
                sys.stdout.flush() # flush after each line

        hypy_out = OutputHandler(save_stdout, 'hypy', user_func=stdout_wrapper)

        if run_hyst is False:
            self.output = self.input_[0] # running the tool directly (no hyst)
        else:
            hypy_out.add_line("Running Hyst...")
            hyst_start_time = time.time()
            hyst_out = OutputHandler(save_stdout, 'hyst', user_func=stdout_wrapper)
            rv['code'] = self._run_hyst(hypy_out, hyst_out)
            rv['hyst_time'] = time.time() - hyst_start_time
            hypy_out.add_line("Seconds for Hyst conversion: {}\n".format(rv['hyst_time']))

            if save_stdout:
                rv['hyst_stdout'] = hyst_out.lines

        if rv['code'] == Engine.SUCCESS and run_tool:
            temp_dir = None

            if parse_output:
                temp_dir = os.path.join(tempfile.gettempdir(), "hypy_" + random_string())

            tool_start_time = time.time()

            tool_out = OutputHandler(save_stdout, self.printer[0], user_func=stdout_wrapper)
            code = hybrid_tool.run_tool(tool, self.output, image_path, timeout, tool_out.stdout_handler, temp_dir)

            rv['tool_time'] = time.time() - tool_start_time

            if code == hybrid_tool.RunCode.TIMEOUT:
                rv['code'] = Engine.TIMEOUT_TOOL
            elif code == hybrid_tool.RunCode.SKIP:
                rv['code'] = Engine.ERROR_UNSUPPORTED
            elif code != hybrid_tool.RunCode.SUCCESS:
                rv['code'] = Engine.ERROR_TOOL
            elif parse_output:
                rv['output'] = tool.parse_output(temp_dir, tool_out.lines, hypy_out)
             
            if temp_dir is not None:   
                shutil.rmtree(temp_dir)

            if save_stdout:
                rv['tool_stdout'] = tool_out.lines

        if save_stdout:
            rv['stdout'] = stdout_lines

        rv['time'] = time.time() - start_time
        hypy_out.add_line("Hypy Elapsed Seconds: {}\n".format(rv['time']))
        hypy_out.add_line("Hypy Result: {}\n".format(rv['code']))

        return rv
Exemplo n.º 3
0
    def run(self, run_hyst=True, run_tool=True, make_image=True):
        """Converts the model in Hyst (optional) and runs it with the appropriate
        tool (optional) to produce a plot file.

        returns SUCCESS if successful, otherwise can return one of the
        ERROR_* codes
        """

        assert self.model_path != None, "set_model() should be called before run()"
        assert self.tool_name != None, "set_tool() should be called before run()"

        image_path = None

        if make_image == True:
            if self.image_path is None:
                image_path = os.path.splitext(self.model_path)[0] + ".png"
            else:
                image_path = self.image_path

        start_time = time.time()
        tool = TOOLS.get(self.tool_name)

        if self.save_model_path is None:
            self.save_model_path = os.path.join(
                tempfile.gettempdir(), self.tool_name + "_" + random_string() + tool.default_ext()
            )

        rv = RUN_CODES.SUCCESS

        if run_hyst == False:
            self.save_model_path = self.model_path
        else:
            rv = self._run_hyst()  # will assign save_model_path

        if rv == RUN_CODES.SUCCESS and run_tool:

            if self.process_output_dir is not None:
                self.process_output_dir = os.path.join(tempfile.gettempdir(), "hypy_" + random_string())

                tool.output_obj = {}  # new output object created
                tool.output_obj["lines"] = []  # (stdout_line, timestamp) tuple list

            self.running_tool = tool
            code = hybrid_tool.run_tool(
                tool, self.save_model_path, image_path, self.timeout_tool, self._stdout_handler, self.process_output_dir
            )
            self.running_tool = None

            if code == hybrid_tool.RunCode.TIMEOUT:
                rv = RUN_CODES.TIMEOUT_TOOL
            elif code == hybrid_tool.RunCode.SKIP:
                rv = RUN_CODES.ERROR_UNSUPPORTED
            elif code != hybrid_tool.RunCode.SUCCESS:
                rv = RUN_CODES.ERROR_TOOL
            elif self.process_output_dir is not None:
                tool.create_output(self.process_output_dir)

                self.result_obj = tool.output_obj
                shutil.rmtree(self.process_output_dir)

        dif_time = time.time() - start_time
        self._add_terminal_output("Elapsed Seconds: " + str(dif_time) + "\n")
        self._add_terminal_output("Result: " + str(rv) + "\n")

        return rv
Exemplo n.º 4
0
    def run(self, run_hyst=True, run_tool=True, timeout=None, image_path=None, save_stdout=False, print_stdout=False, 
            stdout_func=None, parse_output=False):
        '''
        Converts the model in Hyst, runs it with the appropriate tool, 
        produces a plot image, and python results object.

        non-obvious parameters:
        stdout_func - a 3-param user function for processing of stream stdout. Params are: line, time, tool_name
        parse_output - should tool's output be parsed into a python object? If True, 'output' in the result is set.
                       using this option forces save_stdout to True

        returns a dictionary object with the following keys:
        'code' - exit code - engine.SUCCESS if successful, an engine.ERROR_* code otherwise
        'hyst_time' - time in seconds for hyst to run, only returned if run_hyst == True
        'tool_time' - time in seconds for tool(+image) to run, only returned if run_tool == True
        'time' - total run time in seconds
        'stdout' - the list of lines anything produced to stdout, only returned if save_stdout == True
        'tool_stdout' - the list of lines the tool produced to stdout, only returned if save_stdout == True
        'hypy_stdout' - the list of lines hypy produces to stdout, only returned if save_stdout == True
        'output' - tool-specific processed output object, only returned if successful and parse_output == True
        '''

        #image_path = os.path.splitext(filename)[0] + ".png" if filename is not None else "generated.png"

        start_time = time.time()
        tool = TOOLS.get(self.printer[0])

        if self.output is None:
            self.output = os.path.join(tempfile.gettempdir(), self.printer[0] + \
                    "_" + random_string() + tool.default_ext())

        rv = {}
        rv['code'] = Engine.SUCCESS
        stdout_lines = None

        if parse_output:
            save_stdout = True
        
        if save_stdout:
            stdout_lines = []

        # wrapper function to capture all stdout in order
        def stdout_wrapper(line, secs, tool):
            'wrapper to capture lines produced by stdout from any tool'
    
            if stdout_lines is not None:
                stdout_lines.append(line)

            if stdout_func is not None:
                stdout_func(line, secs, tool)

            if print_stdout:
                print line
                sys.stdout.flush() # flush after each line

        hypy_out = OutputHandler(save_stdout, 'hypy', user_func=stdout_wrapper)

        if run_hyst is False:
            self.output = self.input_[0] # running the tool directly (no hyst)
        else:
            hypy_out.add_line("Running Hyst...")
            hyst_start_time = time.time()
            hyst_out = OutputHandler(save_stdout, 'hyst', user_func=stdout_wrapper)
            rv['code'] = self._run_hyst(hypy_out, hyst_out)
            rv['hyst_time'] = time.time() - hyst_start_time
            hypy_out.add_line("Seconds for Hyst conversion: {}\n".format(rv['hyst_time']))

            if save_stdout:
                rv['hyst_stdout'] = hyst_out.lines

        if rv['code'] == Engine.SUCCESS and run_tool:

            temp_dir = None

            if parse_output:
                temp_dir = os.path.join(tempfile.gettempdir(), "hypy_" + random_string())

            tool_start_time = time.time()

            tool_out = OutputHandler(save_stdout, self.printer[0], user_func=stdout_wrapper)
            code = hybrid_tool.run_tool(tool, self.output, image_path, timeout, tool_out.stdout_handler, temp_dir)

            rv['tool_time'] = time.time() - tool_start_time

            if code == hybrid_tool.RunCode.TIMEOUT:
                rv['code'] = Engine.TIMEOUT_TOOL
            elif code == hybrid_tool.RunCode.SKIP:
                rv['code'] = Engine.ERROR_UNSUPPORTED
            elif code != hybrid_tool.RunCode.SUCCESS:
                rv['code'] = Engine.ERROR_TOOL
            elif parse_output:
                rv['output'] = tool.parse_output(temp_dir, tool_out.lines, hypy_out)
             
            if temp_dir is not None:   
                shutil.rmtree(temp_dir)

            if save_stdout:
                rv['tool_stdout'] = tool_out.lines

        if save_stdout:
            rv['stdout'] = stdout_lines

        rv['time'] = time.time() - start_time
        hypy_out.add_line("Hypy Elapsed Seconds: {}\n".format(rv['time']))
        hypy_out.add_line("Hypy Result: {}\n".format(rv['code']))

        return rv
Exemplo n.º 5
0
Arquivo: hypy.py Projeto: ystex/hyst
    def run(self, run_hyst=True, run_tool=True, make_image=True):
        '''Converts the model in Hyst (optional) and runs it with the appropriate
        tool (optional) to produce a plot file.

        returns SUCCESS if successful, otherwise can return one of the
        ERROR_* codes
        '''

        assert self.model_path != None, 'set_model() should be called before run()'
        assert self.tool_name != None, 'set_tool() should be called before run()'

        image_path = None

        if make_image == True:
            if self.image_path is None:
                image_path = os.path.splitext(self.model_path)[0] + ".png"
            else:
                image_path = self.image_path

        start_time = time.time()
        tool = TOOLS.get(self.tool_name)

        if self.save_model_path is None:
            self.save_model_path = os.path.join(tempfile.gettempdir(), self.tool_name + \
                    "_" + random_string() + tool.default_ext())

        rv = RUN_CODES.SUCCESS

        if run_hyst == False:
            self.save_model_path = self.model_path
        else:
            rv = self._run_hyst()  # will assign save_model_path

        if rv == RUN_CODES.SUCCESS and run_tool:

            if self.process_output_dir is not None:
                self.process_output_dir = os.path.join(
                    tempfile.gettempdir(), "hypy_" + random_string())

                tool.output_obj = {}  # new output object created
                tool.output_obj['lines'] = [
                ]  # (stdout_line, timestamp) tuple list

            self.running_tool = tool
            code = hybrid_tool.run_tool(tool, self.save_model_path, image_path, \
                                        self.timeout_tool, self._stdout_handler,
                                        self.process_output_dir)
            self.running_tool = None

            if code == hybrid_tool.RunCode.TIMEOUT:
                rv = RUN_CODES.TIMEOUT_TOOL
            elif code == hybrid_tool.RunCode.SKIP:
                rv = RUN_CODES.ERROR_UNSUPPORTED
            elif code != hybrid_tool.RunCode.SUCCESS:
                rv = RUN_CODES.ERROR_TOOL
            elif self.process_output_dir is not None:
                tool.create_output(self.process_output_dir)

                self.result_obj = tool.output_obj
                shutil.rmtree(self.process_output_dir)

        dif_time = time.time() - start_time
        self._add_terminal_output("Elapsed Seconds: " + str(dif_time) + "\n")
        self._add_terminal_output("Result: " + str(rv) + "\n")

        return rv