Exemple #1
0
 def load_petri_net(self):
     """Load a petri net from a pnml file."""
     if self.pn_path.get() != "":
         self.pn_prev = PetriNet(pnml=self.petri_pnml)
         self.pn_prev.output_png(self.petri_png_prev)
         self.message_info("Petri Net loaded")
     else:
         self.message_error("Set output path")
Exemple #2
0
def main(argv):
    log = []
    with open(argv[1], 'r') as f:
        lines = f.readlines()
        for line in lines:
            log.append(line.strip().split(' '))
    print("Log:\n", log)
    print("---------------------")
    lm = footprint.Alpha(log)
    print(lm)
    pn = PetriNet()
    pn.from_alpha(lm, dotfile="{}.dot".format(os.path.basename(argv[1])))
Exemple #3
0
def export_petri_to_valmari(petri_net: PetriNet, filename):
    file = open(filename, "a")

    # file.write("samples = []")
    # file.write("omega = float('inf')")
    # file.write("def Init():")
    file.write("%d %d \n" % (petri_net.get_dim(), len(petri_net.get_transitions())))

    trun_num = 1
    for tran in petri_net.get_transitions():

        place_num = 1
        for p in (tran.get_incidence() + tran.get_pre()):
            if p <= 0:
                place_num += 1
                continue
            file.write("-%d \n" % trun_num)
            file.write("0 %d \n" % p)
            file.write("%d \n" % place_num)
            place_num += 1
        place_num = 1
        for p in tran.get_pre():
            if p <= 0:
                place_num += 1
                continue
            file.write("%d \n" % place_num)
            file.write("0 %d \n" % p)
            file.write("-%d \n" % trun_num)
            place_num += 1
        trun_num += 1

    file.write("0 \n")

    place_num = 1
    for p in petri_net.get_mark():
        if p <= 0:
            place_num += 1
            continue
        if p == float("inf"):
            file.write("-32767 \n")
            file.write("%d \n" % place_num)
        else:
            file.write("-%d \n" % p)
            file.write("%d \n" % place_num)
        place_num += 1

    file.write("0 \n")
    file.close()
Exemple #4
0
    def petri_net(self):
        """Create a Petri net from a segmentation analysis. The new net is
        saved as a png, json, and pnml file. Moreover, a configuration file is
        created in order to configure the petri net later."""
        if self.segmentation is not None:
            if self.output_path:
                self.pn = PetriNet(s=self.segmentation)
                self.pn.output_png(self.petri_png)
                self.pn.to_json(self.petri_json)
                self.pn.to_pnml(self.petri_pnml)
                utils.generate_configuration(self.configuration_yml, self.pn)

                self.message_info("Petri Net created")
            else:
                self.message_error("Set output path")
        else:
            self.message_error("Missing segmentation")
Exemple #5
0
def run_benchmark(name,
                  petri: petri_net.PetriNet,
                  time_out,
                  init_marking=None,
                  with_acc=True):
    benchmark = Benchmark(name)

    print("starting %s" % name + " numb of trans: " +
          str(len(petri.get_transitions())) + " num of places: " +
          str(petri.get_dim()))
    start_time = time.time()
    if init_marking is None:
        cov = CovTree(petri, petri.get_mark())
    else:
        cov = CovTree(petri, init_marking)
    cov.keep_accelerations = with_acc
    cov.type_of_graph_traversal = "DFS"
    cov.use_z3_to_guess_accelerations = False
    cov.check_for_correctness = False
    cov.verbose = True
    cov.timeout = time_out

    benchmark.clover = cov.generate_cov_tree()

    benchmark.timeout = benchmark.clover is None

    elapsed_time = time.time() - start_time
    benchmark.max_vertices = cov.max_size
    benchmark.max_accelerations = cov.max_size_of_acc
    benchmark.final_accelerations = len(cov._accelerations)
    benchmark.final_vertices = len(cov._verSet)
    benchmark.used_accelerations = cov.use_of_acc
    benchmark.time = elapsed_time
    benchmark.places = len(petri.get_places())
    benchmark.transitions = len(petri.get_transitions())
    benchmark.num_of_comparisons = cov.num_of_comparisons
    benchmark.num_of_recheck = cov.num_of_rechecks

    return benchmark, cov
Exemple #6
0
    def __init__(self, petri_net: PetriNet, mark: np.array):
        """
        Constructor
        """
        assert (isinstance(petri_net, PetriNet)), "Has to be a Petri Net"

        self._petriNet = petri_net
        self._dim = petri_net.get_dim()
        self._accelerations = np.array([])

        self._root = CovNode(mark, self._dim, 0, None)
        self._vertices = [self._root]  # a list of all the vertices
        self._front = [
            self._root
        ]  # a list of the vertices which still weren't processed
        self._verSet = {
            tuple(self._root.marking)
        }  # A set of all the marks, used to increase speed(hash)

        # Options for the run of generate_cov_tree():
        self.timeout = float("inf")  # The time out for generate_cov_tree()

        self.keep_accelerations = True  # Remember and reuse previous accelerations

        self.use_z3_to_guess_accelerations = False  # Use z3 to try to guess some accelerations before starting for
        self.z3_timeout = 10  # z3_timeout time

        self.check_for_correctness = True  # in the end of generate_cov_tree() preform a few checks for correctness

        # setting the graph traversal:
        self._type_of_graph_traversal = 1
        self.pushFront = self.push_into_front_function()
        self.popFront = self.pop_next_vertex_func()
        self.deleteFromFront = self.remove_from_front_function()

        # Variables for performance:
        self.verbose = False
        self.max_size = 1
        self.max_size_of_acc = 0
        self.use_of_acc = 0
        self.count = 0
        self.max_depth = 0
        self.number_of_deleted_nodes = 0
        self.number_of_deleted_decedents = 0
        self.max_depth_of_acc = 0
        self.average_num_of_successors = 0
        self.num_of_comparisons = 0
        self.average_vertics_size = 1
        self.num_of_accelaration_tried = 0
        self.num_of_rechecks = 0
    def __init__(self, name, action):
        PetriNet.__init__(self, name)
        self.action_ = action

        # Places.
        queue = PetriNetPlace('queue')
        started = PetriNetPlace('started')
        interrupted = PetriNetPlace('interrupted')
        self.finished_ = PetriNetPlace('finished')

        # Transitions.
        self.transitions_.append(RequestRobotTransition(action))
        self.transitions_.append(
            StartTransition('start', action, queue, started))
        self.transitions_.append(SeizeRobotTransition('seize_robot', action))
        self.transitions_.append(
            InterruptTransition('interrupt', action, started, interrupted))
        self.transitions_.append(
            FinishTransition('finish', action, started, interrupted,
                             self.finished_))

        # Put action token in queue.
        queue.AddToken(self.action_.name)
Exemple #8
0
    def test_cov_tree_accelerate(self):
        petri = PetriNet(4)
        mark1 = OmegaMarking(np.array([1, 3, 6, float("inf")]))
        node1 = CovNode(mark1, mark1.get_dim())
        mark2 = OmegaMarking(np.array([1, 3, 5, float("inf")]))
        node2 = CovNode(mark2, mark2.get_dim(), node1._depth, node1)

        tr = CovTree(petri, mark1)
        mark0 = OmegaMarking(np.array([0, 2, 5, 0]))
        node0 = CovNode(mark0, mark0.get_dim(), tr.get_root())
        node1.change_parent(node0)
        tr.add_node(node0)
        tr.add_node(node1)
        tr.add_node(node2)
        tr._accelerate(node2, True)
        self.assertTrue(len(tr._accelerations) == 1)
def load_petri_net_from_pnml(filename):
    places_names = []
    transitions_names = []
    pre_transitions = []
    incidence_transitions = []
    init_marking = []

    tree = ET.parse(filename)
    root = tree.getroot()
    net = root.find("{http://www.pnml.org/version-2009/grammar/pnml}net").find(
        "{http://www.pnml.org/version-2009/grammar/pnml}page")

    for place in net.iter(
            '{http://www.pnml.org/version-2009/grammar/pnml}place'):
        places_names.append(place.attrib["id"])
        init = place.find(
            "{http://www.pnml.org/version-2009/grammar/pnml}initialMarking")
        if init is None:
            init_marking.append(0)
        else:
            i = init.find(
                "{http://www.pnml.org/version-2009/grammar/pnml}text").text
            init_marking.append(int(i))

    dim = len(places_names)

    for tran in net.iter(
            '{http://www.pnml.org/version-2009/grammar/pnml}transition'):
        transitions_names.append(tran.attrib["id"])
        pre_transitions.append(numpy.zeros(dim))
        incidence_transitions.append(numpy.zeros(dim))

    for arc in net.iter('{http://www.pnml.org/version-2009/grammar/pnml}arc'):
        source = arc.attrib["source"]
        target = arc.attrib["target"]
        if source in places_names:
            p = places_names.index(source)
            t = transitions_names.index(target)
            pre_transitions[t][p] += 1
        else:
            p = places_names.index(target)
            t = transitions_names.index(source)
            incidence_transitions[t][p] += 1

    petri_net = PetriNet(dim)
    petri_net.mark_the_petri_net(OmegaMarking(np.array(init_marking)))

    for i in range(len(transitions_names)):
        petri_net.add_transition(
            OmegaTransition(pre_transitions[i], incidence_transitions[i]))

    return petri_net
Exemple #10
0
def export_petri_to_spec(petri_net: PetriNet, filename, write_initial_marking=False):
    file = open(filename, "a")
    place_names = []
    for p in petri_net.get_places():
        place_names.append("x" + str(p))

    file.write("vars\n\t")
    for place in place_names:
        file.write(place + " ")

    file.write("\n\nrules\n")
    for tran in petri_net.get_transitions():
        pre = tran.get_pre()
        first = True
        for p in petri_net.get_places():
            if pre[p] > 0:
                if first:
                    file.write("\t")
                else:
                    file.write(" , ")
                file.write(place_names[p] + " >= " + str(int(pre[p])))
                first = False
        file.write(" ->\n")
        first = True
        incidence = tran.get_incidence()
        for p in petri_net.get_places():
            if incidence[p] != 0:
                if not first:
                    file.write(",\n")
                if incidence[p] > 0:
                    file.write("\t\t" + place_names[p] + "' = " + place_names[p] + "+" + str(int(incidence[p])))
                else:
                    file.write("\t\t" + place_names[p] + "' = " + place_names[p] + "-" + str(int(incidence[p]) * (-1)))
                first = False
        file.write(";\n\n")
    if not write_initial_marking:
        file.close()
        return

    file.write("init\n\t")
    first = True
    init_mark = (petri_net.get_mark())
    for p in petri_net.get_places():
        if not first:
            file.write(" , ")
        if init_mark[p] == float("inf"):
            file.write(place_names[p] + " >= 1")
        else:
            file.write(place_names[p] + " = " + str(int(init_mark[p])))
        first = False
    file.close()
Exemple #11
0
    def test_cov_tree_create_insert_delete(self):
        petri = PetriNet(4)
        mark1 = OmegaMarking(np.array([1, 3, 6, float("inf")]))
        node1 = CovNode(mark1, mark1.get_dim())
        mark2 = OmegaMarking(np.array([1, 3, 5, float("inf")]))
        node2 = CovNode(mark2, mark2.get_dim(), node1._depth, node1)

        tr = CovTree(petri, mark1)
        mark0 = OmegaMarking(np.array([0, 2, 5, 0]))
        node0 = CovNode(mark0, mark0.get_dim(), tr.get_root())
        node1.change_parent(node0)
        tr.add_node(node0)
        tr.add_node(node1)
        tr.add_node(node2)
        #         print(node2.GetMark()._marking)
        self.assertEqual(len(tr.get_vertices()), 4)
        tr.delete_node(node2)
        self.assertEqual(len(tr.get_vertices()), 3)
        tr.delete_node(node0)
        self.assertEqual(len(tr.get_vertices()), 1)
def load_petri_net_from_apt(filename):
    MODES = ['.places', 'rules', 'init', 'target', 'invariants']
    num_places = 0
    places = []

    with open(filename) as input_file:
        places = 0
        for row in input_file:
            if row.strip() == MODES[0]:
                data = (next(input_file)).strip()
                num_places = len(data.split(' '))
                break
    petri = PetriNet(num_places)

    with open(filename) as input_file:
        mode = 'none'
        rules_acc = ''
        acc = ''
        taracc = ''
        init_mark = numpy.zeros(num_places)
        target = numpy.zeros(num_places)

        for row in input_file:
            data = row.strip()

            # Ignore empty/commented lines
            if len(data) == 0 or data[0] == '#':
                continue

            if data in MODES:
                mode = data
                if mode == MODES[1]:
                    places_indices = {
                        value: key
                        for key, value in enumerate(places)
                    }
            else:
                # Places
                if mode == MODES[0]:
                    places.extend(data.split(' '))
                # Rules
                elif mode == MODES[1]:
                    rules_acc += data
                    pos = rules_acc.find(';')

                    if pos >= 0:
                        add_transition(petri, places, rules_acc[:pos])
                        rules_acc = rules_acc[pos + 1:]
                # Initial values
                elif mode == MODES[2]:
                    acc = add_initial_mark(acc + data, places_indices,
                                           init_mark)
                #                     print(init_mark)
                # Target values
                elif mode == MODES[3]:
                    taracc = add_initial_target(taracc + data, places_indices,
                                                target)
                    # print("")
                    # currently don't care about the target

    petri.mark_the_petri_net(init_mark)
    if withTarget:
        return petri, target
    else:
        return petri
Exemple #13
0
class GraphicalInterface(Tkinter.Tk):
    def init_ui(self):
        """Initialization of the graphical interface"""
        # variables
        self.segmentation = None
        self.pn = None
        self.pn_prev = None
        self.petri_png_prev = "/tmp/pn-preview.png"

        # widgets
        nb = ttk.Notebook(self.parent, name='notebook')
        nb.pack(fill=Tkinter.BOTH, expand=Tkinter.Y)
        self._create_segmentation_tab(nb)
        self._create_petri_tab(nb)

        # options
        self.resizable(False, False)

    def _create_segmentation_tab(self, nb):
        """Add the frame and the widgets for the segmentation tab to a notebook.

        Args:
            nb (Notebook): Notebook to be updated.

        Returns:
            None
        """
        frame = Tkinter.Frame(nb)

        # widgets for load audio file
        self.audio_path = Tkinter.StringVar()
        audio_path_entry = Tkinter.Entry(frame, textvariable=self.audio_path)
        audio_path_entry.grid(column=0, row=0, sticky='EW', columnspan=3)
        audio_btn = Tkinter.Button(frame,
                                   text='Load',
                                   command=self.show_dialog)
        audio_btn.grid(column=3, row=0, sticky='EW')

        self.output_path = Tkinter.StringVar()
        output_path_entry = Tkinter.Entry(frame, textvariable=self.output_path)
        output_path_entry.grid(column=0, row=1, sticky='EW', columnspan=3)
        output_btn = Tkinter.Button(frame,
                                    text='Output',
                                    command=lambda: self.show_dialog_folder(1))
        output_btn.grid(column=3, row=1, sticky='EW')

        # buttons for actions
        seg_btn = Tkinter.Button(frame,
                                 text='Segmentation',
                                 command=self.create_segmentation)
        seg_btn.grid(column=0, row=2)
        draw_seg_btn = Tkinter.Button(frame,
                                      text='View Segmentation',
                                      command=self.visualize_segmentation)
        draw_seg_btn.grid(column=1, row=2)
        pn_btn = Tkinter.Button(frame,
                                text='Generate PN',
                                command=self.petri_net)
        pn_btn.grid(column=2, row=2)
        draw_pn_btn = Tkinter.Button(frame,
                                     text='View PN',
                                     command=self.visualize_petri_net)
        draw_pn_btn.grid(column=3, row=2)

        # add to notebook
        nb.add(frame, text='Segmentation')

    def _create_petri_tab(self, nb):
        """Add the frame and the widgets for the petri net tab to a notebook.

        Args:
            nb (Notebook): Notebook to be updated.

        Returns:
            None
        """
        frame = Tkinter.Frame(nb)

        for i in range(4):
            Tkinter.Grid.columnconfigure(frame, i, weight=1)

        # widget for looking for the petri net path
        self.pn_path = Tkinter.StringVar()
        pn_path_entry = Tkinter.Entry(frame, textvariable=self.pn_path)
        pn_path_entry.grid(column=0, row=0, sticky='EW', columnspan=3)
        pn_path_btn = Tkinter.Button(
            frame, text='Search', command=lambda: self.show_dialog_folder(2))
        pn_path_btn.grid(column=3, row=0, sticky='EW')

        # button to load the petri net
        load_pn_btn = Tkinter.Button(frame,
                                     text='Load',
                                     command=self.load_petri_net)
        load_pn_btn.grid(column=0, row=1, sticky='EW')

        # button to update the petri net
        update_pn_btn = Tkinter.Button(frame,
                                       text='Update',
                                       command=self.update_petri_net)
        update_pn_btn.grid(column=1, row=1, sticky='EW')

        # show petri net
        show_pn_btn = Tkinter.Button(frame,
                                     text='Show',
                                     command=self.preview_petri_net)
        show_pn_btn.grid(column=2, row=1, sticky='EW')

        # save to update the petri net
        save_pn_btn = Tkinter.Button(frame,
                                     text='Save',
                                     command=self.save_petri_net)
        save_pn_btn.grid(column=3, row=1, sticky='EW')

        # add to notebook
        nb.add(frame, text='Configuration')

    def __init__(self, parent):
        Tkinter.Tk.__init__(self, parent)
        self.parent = parent
        self.init_ui()

    def show_dialog(self):
        """Show window to choose the audio path"""
        audio_path = tkFileDialog.askopenfilename(title="Open file")
        if audio_path:
            self.audio_path.set(audio_path)

    def show_dialog_folder(self, option):
        """Show a window to choose the output folder for the segmentation,
        the oracle, the petri net, and the configuration.

        Args:
            option (int): If 1, set the output folder to save the segmentation
            and the oracle. Otherwise, set the output folder only for the petri
            net and the configuration.

        Returns:
            None
        """
        folder_path = tkFileDialog.askdirectory(title="Output folder")
        if folder_path:
            if option == 1:
                self.output_path.set(folder_path)
                self.segmentation_png = folder_path + "/segmentation.png"
                self.oracle_path = folder_path + "/audio-oracle"
            elif option == 2:
                self.pn_path.set(folder_path)

            self.petri_png = folder_path + "/petri-net.png"
            self.petri_json = folder_path + "/petri-net.json"
            self.configuration_yml = folder_path + "/configuration.yml"
            self.petri_pnml = folder_path + "/petri-net"

    @staticmethod
    def message_error(error_msg):
        """Show an error message.

        Args:
            error_msg (str): Message to be displayed.

        Returns:
            None
        """
        tkMessageBox.showerror('Message', error_msg)

    @staticmethod
    def message_info(msg):
        """Show a warning message

        Args:
            msg (str): Message to be displayed

        Returns:
            None
        """
        tkMessageBox.showinfo('Message', msg)

    def petri_net(self):
        """Create a Petri net from a segmentation analysis. The new net is
        saved as a png, json, and pnml file. Moreover, a configuration file is
        created in order to configure the petri net later."""
        if self.segmentation is not None:
            if self.output_path:
                self.pn = PetriNet(s=self.segmentation)
                self.pn.output_png(self.petri_png)
                self.pn.to_json(self.petri_json)
                self.pn.to_pnml(self.petri_pnml)
                utils.generate_configuration(self.configuration_yml, self.pn)

                self.message_info("Petri Net created")
            else:
                self.message_error("Set output path")
        else:
            self.message_error("Missing segmentation")

    def visualize_petri_net(self):
        """Visualize the png image of the petri net."""
        if self.pn is not None and self.output_path:
            self.viewer(self.petri_png)
        else:
            self.message_error("Missing Petri Net")

    def load_petri_net(self):
        """Load a petri net from a pnml file."""
        if self.pn_path.get() != "":
            self.pn_prev = PetriNet(pnml=self.petri_pnml)
            self.pn_prev.output_png(self.petri_png_prev)
            self.message_info("Petri Net loaded")
        else:
            self.message_error("Set output path")

    def update_petri_net(self):
        """Update the petri net from the configuration file."""
        if self.pn_prev is not None and self.pn_path.get() != "":
            self.pn_prev.update_from_config(self.configuration_yml)
            self.pn_prev.output_png(self.petri_png_prev)
            self.message_info("Petri Net updated")
        else:
            self.message_error("Missing Petri Net")

    def preview_petri_net(self):
        """Show an updated petri net."""
        if self.pn_prev is not None:
            self.viewer(self.petri_png_prev)
        else:
            self.message_error("Missing Petri Net")

    def save_petri_net(self):
        """Save the petri net as a json, pnml, and png file."""
        if self.pn_prev is not None and self.pn_path.get() != "":
            self.pn_prev.to_json(self.petri_json)
            self.pn_prev.to_pnml(self.petri_pnml)
            self.pn_prev.output_png(self.petri_png)
            self.message_info("Petri Net saved")
        else:
            self.message_error("Missing Petri Net")

    def visualize_segmentation(self):
        """Visualize the png image of the segmentation."""
        if self.segmentation is not None and self.output_path:
            self.viewer(self.segmentation_png)
        else:
            self.message_error("Missing Segmentation")

    def create_segmentation(self):
        """Generate the segmentation analysis from the audio file. The new
        analysis is saved as a png file and also it is saved the oracle created
        by vmo."""
        if self.audio_path.get():
            if self.output_path.get():
                self.segmentation = Segmentation(self.audio_path.get())
                self.segmentation.output_png(self.segmentation_png)
                self.segmentation.save_oracle(self.oracle_path)
                self.message_info("Segmentation done")
            else:
                self.message_error("Set output path")
        else:
            self.message_error("Set the audio file path")

    @staticmethod
    def viewer(path):
        """Visualize a png file.

        Args:
            path (str): Path of the image to be visualized

        Returns:
            None
        """
        load = Image.open(path)
        load.show()
Exemple #14
0
    def test_petri_net(self):
        """
        Testting basic properties of petri net
        """
        with self.assertRaises(Exception):
            PetriNet(0.5)
        with self.assertRaises(Exception):
            PetriNet(0)

        mark1 = OmegaMarking(np.array([1, 2, 3, float("inf")]))
        mark2 = OmegaMarking(np.array([1, 2, 3, float("inf"), 5]))
        tran1 = OmegaTransition(np.array([1, 2, 3, 5]), np.array([1, 4, 3,
                                                                  -5]))
        tran2 = OmegaTransition(np.array([1, float("inf"), 3, 5]),
                                np.array([2, 3, 3, -5]))
        tran3 = OmegaTransition(np.array([1, float("inf"), 2, 5]),
                                np.array([5, 5, float("inf"), -5]))

        petri = PetriNet(4)
        with self.assertRaises(Exception):
            petri.mark_the_petri_net(mark2)

        petri.mark_the_petri_net(mark1)
        petri.add_transition(tran1)
        petri.add_transition(tran2)
        petri.add_transition(tran3)

        self.assertEqual(len(petri.get_transitions()), 3)
Exemple #15
0
def export_petri_to_MP(petri_net: PetriNet, filename, name):
    file = open(filename, "a")

    # file.write("samples = []")
    # file.write("omega = float('inf')")
    # file.write("def Init():")

    file.write("#======================================\n")
    file.write("#======== %s ==============\n" % name)
    file.write("#======================================\n")

    file.write("tplus = []\n")
    file.write("tmin = []\n")
    i = 0
    for tran in petri_net.get_transitions():
        file.write("#t%d\n" % i)
        i += 1
        file.write("tplus += [[")
        is_first = True
        for p2 in (tran.get_incidence() + tran.get_pre()):
            if p2 < 0:
                p2 = 0
            # p2 = int(p2*(-1))
            if is_first:
                is_first = False
                file.write("%d" % p2)
                continue
            file.write(", %d" % p2)

        file.write("]]\n")

        file.write("tmin += [[")
        is_first = True
        for p in tran.get_pre():
            if p < 0:
                p = 0
            if is_first:
                is_first = False
                file.write("%d" % p)
                continue
            file.write(", %d" % p)

        file.write("]]\n")

    file.write("t0 = [")
    is_first = True
    for p in petri_net.get_mark().get_marking():
        if not is_first:
            file.write(", ")
        else:
            is_first = False
        if p == float("inf"):
            file.write("omega")
        else:
            file.write("%d" % p)

    file.write("]\n")

    file.write("samples.append(Sample(\"%s\", tplus, tmin, t0, None)) \n" % name)

    file.write("#======================================\n")
    file.write("#================END===================\n")
    file.write("#======================================\n")

    file.close()
Exemple #16
0
    def test_banana_land(self):
        petri = PetriNet(6)

        # Adding transitions:
        petri.add_transition(
            OmegaTransition(np.array([1, 0, 0, 0, 0, 0]),
                            np.array([-1, 1, 1, 0, 0, 0])))
        petri.add_transition(
            OmegaTransition(np.array([1, 0, 0, 0, 0, 0]),
                            np.array([-1, 1, 0, 1, 0, 0])))
        petri.add_transition(
            OmegaTransition(np.array([1, 0, 0, 0, 0, 0]),
                            np.array([-1, 0, 1, 1, 0, 0])))
        petri.add_transition(
            OmegaTransition(np.array([0, 1, 0, 0, 0, 0]),
                            np.array([0, 0, 0, 0, 1, 0])))
        petri.add_transition(
            OmegaTransition(np.array([0, 0, 0, 1, 0, 0]),
                            np.array([0, 0, 0, -1, 0, 1])))
        petri.add_transition(
            OmegaTransition(np.array([0, 0, 1, 0, 1, 0]),
                            np.array([0, 0, 0, 0, -1, 1])))

        # Marking the net:
        petri.mark_the_petri_net(OmegaMarking(np.array([1, 0, 0, 0, 0, 0])))

        # Initializing the tree:
        cov_tree = CovTree(petri, petri.get_mark())

        anti_chain = cov_tree.generate_cov_tree(True)

        self.assertEqual(len(anti_chain), 4)

        markings = []
        for node in anti_chain:
            markings.append(node.get_mark())

        self.assertTrue(OmegaMarking(np.array([1, 0, 0, 0, 0, 0])) in markings)
        self.assertTrue(
            OmegaMarking(np.array([0, 1, 1, 0,
                                   float("inf"),
                                   float("inf")])) in markings)
        self.assertTrue(
            OmegaMarking(np.array([0, 1, 0, 1, float("inf"), 0])) in markings)
        self.assertTrue(OmegaMarking(np.array([0, 0, 1, 1, 0, 0])) in markings)

        self.assertTrue(len(cov_tree._accelerations) == 2)
Exemple #17
0
    def test_Alain_2005(self):
        petri = PetriNet(7)

        # Adding transitoins:
        petri.add_transition(
            OmegaTransition(np.array([1, 0, 0, 0, 0, 0, 0]),
                            np.array([-1, 1, 0, 0, 0, 0, 0])))
        petri.add_transition(
            OmegaTransition(np.array([1, 0, 0, 0, 0, 0, 0]),
                            np.array([-1, 0, 0, 0, 0, 0, 1])))
        petri.add_transition(
            OmegaTransition(np.array([1, 0, 0, 0, 0, 0, 0]),
                            np.array([-1, 0, 0, 0, 0, 1, 0])))
        petri.add_transition(
            OmegaTransition(np.array([0, 0, 0, 0, 0, 1, 0]),
                            np.array([0, 0, 0, 1, 2, -1, 0])))
        petri.add_transition(
            OmegaTransition(np.array([0, 1, 0, 0, 0, 0, 0]),
                            np.array([0, -1, 1, 0, 0, 0, 0])))
        petri.add_transition(
            OmegaTransition(np.array([0, 0, 1, 0, 0, 0, 0]),
                            np.array([0, 0, -1, 1, 0, 0, 0])))
        petri.add_transition(
            OmegaTransition(np.array([0, 0, 0, 1, 0, 0, 0]),
                            np.array([0, 0, 1, -1, 1, 0, 0])))
        petri.add_transition(
            OmegaTransition(np.array([0, 0, 0, 0, 0, 0, 1]),
                            np.array([0, 1, 0, 0, 1, 0, -1])))

        # Marking the net:
        petri.mark_the_petri_net(OmegaMarking(np.array([1, 0, 0, 0, 0, 0, 0])))

        # Initializing the tree:
        cov_tree = CovTree(petri, petri.get_mark())

        anti_chain = cov_tree.generate_cov_tree()
        self.assertEqual(len(anti_chain), 6)
Exemple #18
0
def test_petri_net_enabled_transitions():
    t1 = Transition([0], [])
    t2 = Transition([1], [2])
    p = PetriNet([t1,t2])
    assert p.enabled_transitions(State([1, 0, 0])) == [t1]
Exemple #19
0
def main(argv):
    log = read(argv[1])
    lm = Alpha(log)
    pn = PetriNet()
    pn.from_alpha(lm, dotfile="{}.dot".format(os.path.basename(argv[1])))
Exemple #20
0
def test_net():
    t1 = Transition([0], [1])
    t2 = Transition([1], [0])
    p = PetriNet([t1, t2])
    state = State([0, 1], p)
    p.enabled_transitions(state) == [t2]