Example #1
0
def perform_alignments(log, petri_string, parameters=None):
    """
    Perform alignments

    Parameters
    ------------
    log
        Log
    net
        Petri net
    parameters
        Parameters of the algorithm

    Returns
    -------------
    petri
        SVG of the decorated Petri
    table
        SVG of the decorated table
    """
    if parameters is None:
        parameters = {}

    net, im, fm = pnml.import_petri_from_string(petri_string,
                                                parameters=parameters)

    parameters_align = copy(parameters)
    parameters_align["ret_tuple_as_trans_desc"] = True

    alignments = align_factory.apply(log,
                                     net,
                                     im,
                                     fm,
                                     parameters=parameters_align)
    decorations = alignments_decoration.get_alignments_decoration(
        net, im, fm, aligned_traces=alignments, parameters=parameters)

    gviz_on_petri = pn_vis_factory.apply(net,
                                         im,
                                         fm,
                                         aggregated_statistics=decorations,
                                         variant="alignments",
                                         parameters={"format": "svg"})
    svg_on_petri = get_base64_from_gviz(gviz_on_petri)

    parameters_table = copy(parameters)
    parameters_table["format"] = "svg"

    gviz_table = align_table_factory.apply(log,
                                           alignments,
                                           parameters=parameters_table)
    svg_table = get_base64_from_gviz(gviz_table)

    return svg_on_petri, svg_table
Example #2
0
def inductive_miner_petrinet_no_decor(log_file):
    net, i_m, f_m = inductive_miner.apply(log_file)
    gviz = pn_vis_factory.apply(net,
                                i_m,
                                f_m,
                                parameters={
                                    "format": "png",
                                    "debug": False
                                })

    pn_vis_factory.save(gviz, "static/inductive_miner_petnet_no_decor.png")
    return net, i_m, f_m
def execute_script():
    log = xes_importer.apply(
        os.path.join("..", "tests", "compressed_input_data",
                     "09_a32f0n00.xes.gz"))
    heu_net = heuristics_miner.apply_heu(
        log, parameters={"dependency_thresh": 0.99})
    gviz = hn_vis_factory.apply(heu_net, parameters={"format": "svg"})
    hn_vis_factory.view(gviz)
    net, im, fm = heuristics_miner.apply(
        log, parameters={"dependency_thresh": 0.99})
    gviz2 = petri_vis_factory.apply(net, im, fm, parameters={"format": "svg"})
    petri_vis_factory.view(gviz2)
Example #4
0
def SPAlphaMiner(context):
    args = context.args
    log = convert_df_pm_format(args.inputData)
    net, initial_marking, final_marking = alpha_miner.apply(log)
    gviz = pn_vis_factory.apply(net, initial_marking, final_marking)
    pn_vis_factory.save(gviz, os.path.join(args.outputData, "alpha-miner.png"))
    pnml_exporter.export_net(
        net,
        initial_marking,
        os.path.join(args.outputData, "petri_final.pnml"),
        final_marking=final_marking,
    )

    return args.outputData
Example #5
0
def explore_process(name, csv, miner, miner_name):
    event_log = csv_importer.import_log_from_string(csv)

    net, initial_marking, final_marking = miner.apply(event_log)
    gviz = pn_vis_factory.apply(net, initial_marking, final_marking)
    pn_vis_factory.save(gviz, join('solutions', name + '_' + miner_name + '_petri_net.png'))
    pn_vis_factory.save(gviz, join('solutions', name + '_' + miner_name + '_petri_net.pdf'))

    bpmn_graph, elements_correspondence, inv_elements_correspondence, el_corr_keys_map = bpmn_converter.apply(net, initial_marking, final_marking)

    bpmn_exporter.export_bpmn(bpmn_graph, join('solutions', name + '_' + miner_name + '.bpmn'))
    bpmn_figure = bpmn_vis_factory.apply(bpmn_graph)
    bpmn_vis_factory.save(bpmn_figure, join('solutions', name + '_' + miner_name + '_bpmn.png'))
    bpmn_vis_factory.save(bpmn_figure, join('solutions', name + '_' + miner_name + '_bpmn.pdf'))
Example #6
0
def visualize_as_petri_net(net, initial_marking, final_marking, path=''):
    if len(path) > 0:
        parameters = {
            pn_visualizer.Variants.WO_DECORATION.value.Parameters.FORMAT: "svg"
        }
        gviz = pn_visualizer.apply(net,
                                   initial_marking,
                                   final_marking,
                                   parameters=parameters)
        pn_visualizer.save(gviz, path)
    else:
        gviz = pn_vis_factory.apply(net, initial_marking, final_marking)
        pn_vis_factory.view(gviz)
    return net, initial_marking, final_marking
Example #7
0
def inductive_miner_petrinet_frequency(log_file):
    net, i_m, f_m = inductive_miner.apply(log_file)
    gviz = pn_vis_factory.apply(net,
                                i_m,
                                f_m,
                                parameters={
                                    "format": "png",
                                    "debug": False
                                },
                                variant="frequency",
                                log=log_file)

    pn_vis_factory.save(gviz, "static/inductive_miner_petnet_frequency.png")
    return "success!"
Example #8
0
def bot_hm(chat_id, dependency_threshold=0.99):
    log = get_current_log(chat_id)
    heu_net = heuristics_miner.apply_heu(
        log, parameters={"dependency_thresh": dependency_threshold})
    gviz = hn_vis_factory.apply(heu_net)
    new_file, filename = tempfile.mkstemp(suffix="png")
    hn_vis_factory.save(gviz, filename)

    net, im, fm = heuristics_miner.apply(
        log, parameters={"dependency_thresh": dependency_threshold})
    gviz = pn_vis_factory.apply(net, im, fm)
    new_file2, filename2 = tempfile.mkstemp(suffix="png")
    pn_vis_factory.save(gviz, filename2)

    return [filename, filename2]
Example #9
0
def generate_petri_net_visual(net, initial_marking, final_marking, xes_log):
    try:
        # visualizing the petri net using graphviz library, by passing net initial and final marking and viewing it
        parameters = {"format": "png"}
        gviz = pn_vis_factory.apply(net,
                                    initial_marking,
                                    final_marking,
                                    parameters=parameters,
                                    variant="frequency",
                                    log=xes_log)
        pn_vis_factory.view(gviz)
        print("By what name do you want to save the petri net image?")
        filename = str(input())
        pn_vis_factory.save(gviz, filename + ".png")
    except TypeError:
        print("Please check input values")
Example #10
0
def execute_script():
    # import the log
    log_path = os.path.join("..", "tests", "input_data", "receipt.xes")
    log = xes_importer.import_log(log_path)
    # apply Inductive Miner
    net, initial_marking, final_marking = inductive_miner.apply(log)
    # get visualization
    variant = "performance"
    parameters_viz = {"aggregationMeasure": "mean", "format": "svg"}
    gviz = pn_vis_factory.apply(net,
                                initial_marking,
                                final_marking,
                                log=log,
                                variant=variant,
                                parameters=parameters_viz)
    pn_vis_factory.view(gviz)
Example #11
0
    def show_log(self, log):
        # Miner application log file
        net, initial_marking, final_marking = alpha_miner.apply(log)

        # Visual interface application analysis results
        gviz = visualizer.apply(net, initial_marking, final_marking)

        file, _ = os.path.splitext(os.path.basename(self.fileName))
        output_full_name = "output_time_filtered_" + file + ".png"

        output_file = global_util.get_full_path_output_file(output_full_name)
        print(output_file)

        visualizer.save(gviz, output_file)

        return output_full_name
Example #12
0
def execute_script():
    log = xes_importer.apply(
        os.path.join("..", "tests", "input_data", "receipt.xes"))
    log = sorting.sort_timestamp(log)
    net, im, fm = inductive_miner.apply(log)
    log1 = EventLog(log[:500])
    log2 = EventLog(log[len(log) - 500:])
    statistics = element_usage_comparison.compare_element_usage_two_logs(
        net, im, fm, log1, log2)
    gviz = pn_vis_factory.apply(net,
                                im,
                                fm,
                                variant="frequency",
                                aggregated_statistics=statistics,
                                parameters={"format": "svg"})
    pn_vis_factory.view(gviz)
Example #13
0
def import_csv_file(filename):
    filename = os.path.basename(filename)

    file_path = global_util.get_full_path_input_file(filename)

    event_stream = csv_importer.import_event_stream(file_path)
    # dataframe = csv_import_adapter.import_dataframe_from_path(file_path, sep=",")

    log = conversion_factory.apply(
        event_stream,
        parameters={constants.PARAMETER_CONSTANT_TIMESTAMP_KEY: "日期和时间"})

    net, initial_marking, final_marking = alpha_miner.apply(log)

    gviz = visualizer.apply(net, initial_marking, final_marking)

    visualizer.view(gviz)
Example #14
0
def SPHeuristicsMiner(context):
    args = context.args
    inputFile = os.path.join(args.inputData, os.listdir(args.inputData)[0])
    log = xes_importer.import_log(inputFile)
    net, im, fm = heuristics_miner.apply(
        log,
        parameters={
            "dependency_thresh": args.dependencyThresh,
            "and_measure_thresh": args.andMeasureThresh,
            "min_act_count": args.minActCount,
            "min_dfg_occurrences": args.minDfgOccurrences,
            "dfg_pre_cleaning_noise_thresh": args.dfgPreCleaningNoiseThresh,
        },
    )
    gviz = pn_vis_factory.apply(net, im, fm)
    pn_vis_factory.save(gviz,
                        os.path.join(args.outputData, "heuristics-miner.png"))

    return args.outputData
Example #15
0
def import_csv_file(filename):
    filename = os.path.basename(filename)
    # 修改日志文件路径
    file_path = global_util.get_full_path_input_file(filename)

    # 将文件按 csv 文件格式导入,得到事件流结构
    event_stream = csv_importer.import_event_stream(file_path)
    # dataframe = csv_import_adapter.import_dataframe_from_path(file_path, sep=",")

    # 将事件流转换成 xes 结构
    log = conversion_factory.apply(event_stream, parameters={constants.PARAMETER_CONSTANT_TIMESTAMP_KEY: "日期和时间"})

    # 矿工应用日志文件,这里简单的应用阿尔法矿工
    net, initial_marking, final_marking = alpha_miner.apply(log)

    # 可视化界面应用分析结果
    gviz = visualizer.apply(net, initial_marking, final_marking)

    # 显示结果
    visualizer.view(gviz)
def execute_script():
    log_path = os.path.join("..", "tests", "input_data", "running-example.xes")
    log = xes_importer.import_log(log_path)
    net, marking, final_marking = alpha_factory.apply(log)
    for place in marking:
        print("initial marking " + place.name)
    for place in final_marking:
        print("final marking " + place.name)
    gviz = pn_vis_factory.apply(net,
                                marking,
                                final_marking,
                                parameters={"format": "svg"})
    pn_vis_factory.view(gviz)
    print("started token replay")
    aligned_traces = token_replay.apply(log, net, marking, final_marking)
    fit_traces = [x for x in aligned_traces if x['trace_is_fit']]
    perc_fitness = 0.00
    if len(aligned_traces) > 0:
        perc_fitness = len(fit_traces) / len(aligned_traces)
    print("perc_fitness=", perc_fitness)
Example #17
0
def execute_script():
    log_path = os.path.join("..", "tests", "input_data", "running-example.xes")

    log = xes_importer.import_log(log_path)

    net, marking, final_marking = inductive_factory.apply(log)
    for place in marking:
        print("initial marking " + place.name)
    for place in final_marking:
        print("final marking " + place.name)
    gviz = pn_vis_factory.apply(net, marking, final_marking, parameters={"format": "svg", "debug": True})
    pn_vis_factory.view(gviz)

    if True:
        fit_traces = []

        for i in range(0, len(log)):
            try:
                print("\n", i, [x["concept:name"] for x in log[i]])
                cf_result = pm4py.algo.conformance.alignments.versions.state_equation_a_star.apply(log[i], net, marking,
                                                                                                   final_marking)[
                    'alignment']
                if cf_result is None:
                    print("alignment is none!")
                else:
                    is_fit = True
                    for couple in cf_result:
                        print(couple)
                        if not (couple[0] == couple[1] or couple[0] == ">>" and couple[1] is None):
                            is_fit = False
                    print("isFit = " + str(is_fit))

                    if is_fit:
                        fit_traces.append(log[i])
            except TypeError:
                print("EXCEPTION ", i)
                traceback.print_exc()
        print(fit_traces)
        print(len(fit_traces))
Example #18
0
def startSimulator(env, df2, tns):
    #Using iloc to access can also use iat or at to access elements as matrix
    sfc_sim = str(df2.iloc[0]['SFC'])[:6]
    sfc_act = int(sfc_sim)
    sfc_gen = int(sfc_generator())
    print(sfc_act)
    print(sfc_gen)
    merged_sfc = str(sfc_act) + str(sfc_gen)
    print(f'Starting simulation for the SFC {merged_sfc}')
    #print(f'Processed at the resources {resource_list}')
    df_construct = {}
    new_df = pd.DataFrame()
    #print(new_df)
    for index, row in df2.iterrows():
        #print(index, row['OPERATION'],row['PROCESSING_TIME_SECS'],row['WAITING_TIME_SECS'])
        if index + 1 > tns:
            break
        row['SFC'] = merged_sfc
        row['case:concept:name'] = row['WORK_CENTER']
        row['concept:name'] = row['OPERATION']
        row['org:resource'] = row['RESRCE']
        #row['DATE_TIME'] = f"{datetime.now():%d-%m-%Y %H:%M:%S}"
        row['DATE_TIME'] = f"{datetime.fromtimestamp(env.now):%d-%m-%Y %H:%M:%S}"
        row['time:timestamp'] = row['DATE_TIME']
        curr_row = pd.DataFrame([row])
        pt_time = int(row['PROCESSING_TIME_SECS'])
        print(pt_time)
        yield env.timeout(pt_time)
        new_df = new_df.append([curr_row], ignore_index=True)

    #print(new_df)
    # Implementation of Petrin nets representation will be added
    log = conversion_factory.apply(new_df)
    print(log)
    net, initial_marking, final_marking = alpha_miner.apply(log)
    gviz = vis_factory.apply(net, initial_marking, final_marking)
    vis_factory.view(gviz)
def execute_script(variant="frequency"):
    # read the log using the nonstandard importer (faster)
    log_path = os.path.join("..", "tests", "input_data", "receipt.xes")
    log = xes_importer.import_log(log_path, variant="nonstandard")
    # applies Inductive Miner on the log
    net, initial_marking, final_marking = inductive_miner.apply(log)
    # find shortest paths in the net
    spaths = get_shortest_paths(net)

    # then we start to decorate the net
    # we decide if we should decorate it with frequency or performance
    # we decide the aggregation measure (sum, min, max, mean, median, stdev)
    aggregation_measure = "mean"
    if variant == "frequency":
        aggregation_measure = "sum"
    # we find the DFG
    dfg = dfg_factory.apply(log, variant=variant)
    # we find the number of activities occurrences in the trace log
    activities_count = attributes_filter.get_attribute_values(
        log, "concept:name")
    # we calculate the statistics on the Petri net applying the greedy algorithm
    aggregated_statistics = get_decorations_from_dfg_spaths_acticount(
        net,
        dfg,
        spaths,
        activities_count,
        variant=variant,
        aggregation_measure=aggregation_measure)
    # we find the gviz
    gviz = pn_vis_factory.apply(net,
                                initial_marking,
                                final_marking,
                                variant=variant,
                                aggregated_statistics=aggregated_statistics,
                                parameters={"format": "svg"})
    # we show the viz on screen
    pn_vis_factory.view(gviz)
Example #20
0
def show(model, tel, file_name, parameters):
    '''
    Show model and its quality measures
    :param model: model type (transition system, state based region, DFG miner, alpha miner)
    :param tel: input log
    :param file_name: img file name to show model
    :param parameters: parmater for transition system (afreq, sfreq)
    :return:
    '''

    tel_flag = False
    if isinstance(tel[0][0], tel_event):
        tel_flag = True

    if model in ['ts', 'sbr']:
        if tel_flag:
            output_file_path = os.path.join(
                "static", "images", file_name[:file_name.find('.')] + '_' +
                model + '_' + str(parameters['afreq_thresh']) + '_' +
                str(parameters['sfreq_thresh']) + ".png")
        else:
            output_file_path = os.path.join(
                "static", "images",
                "2" + "_" + file_name[:file_name.find('.')] + '_' + model +
                '_' + str(parameters[PARAM_KEY_DIRECTION]) + '_' +
                str(parameters[PARAM_KEY_WINDOW]) + "_" +
                str(parameters[PARAM_KEY_VIEW]) + ".png")
        auto = utils.discover_annotated_automaton(tel, parameters=parameters)

        max_thresh = {}
        max_afreq = 0
        max_sfreq = 0

        if tel_flag:
            for trans in auto.transitions:
                max_afreq = max(max_afreq, trans.afreq)
            for state in auto.states:
                max_sfreq = max(max_sfreq, state.sfreq)
        max_thresh['afreq'] = max_afreq
        max_thresh['sfreq'] = max_sfreq

        if model == 'ts':
            result = {}
            gviz = vis_factory.apply(auto)
            vis_factory.save(gviz, output_file_path)
            result['num of transitions'] = len(auto.transitions)
            result['num of states'] = len(auto.states)

        else:
            net, im, fm = sb.petri_net_synthesis(auto)
            gviz = petri_vis_factory.apply(net, im, fm)
            petri_vis_factory.save(gviz, output_file_path)
            result = evaluation(net, im, fm, tel)

    else:
        if tel_flag:
            output_file_path = os.path.join(
                "static", "images",
                file_name[:file_name.find('.')] + '_' + model + '_' + ".png")
        else:
            output_file_path = os.path.join(
                "static", "images", "2" + file_name[:file_name.find('.')] +
                '_' + model + '_' + ".png")

        if model == 'alpha':
            if isinstance(tel[0][0], Event):
                net, im, fm = trans_alpha(tel)
            else:
                net, im, fm = alpha_miner.apply(tel)
            gviz = petri_vis_factory.apply(net, im, fm)
            petri_vis_factory.save(gviz, output_file_path)
            result = evaluation(net, im, fm, tel)

        else:
            dfg = dfg_factory.apply(tel)
            if tel_flag:
                dfg_tel = inductive_revise.get_dfg_graph_trans(tel)
                #dfg = dfg_tel + dfg
                dfg = dfg_tel

            gviz = dfg_vis_factory.apply(dfg, log=tel)
            dfg_vis_factory.save(gviz, output_file_path)
            result = dict(
                sorted(dfg.items(), key=operator.itemgetter(1), reverse=True))

        max_thresh = None

    return output_file_path, result, max_thresh
Example #21
0
#Topic:
#-----------------------------
#libraries

from pm4py.algo.discovery.alpha import factory as alpha_miner
from pm4py.objects.log.importer.xes import factory as importer
from pm4py.visualization.petrinet import factory as visualizer
from pm4py.objects.log.importer.csv import factory as csv_importer
event_stream = csv_importer.import_event_stream(
    os.path.join("pmdata/", "running-example.csv"))
event_stream

event_stream_length = len(event_stream)
print(event_stream_length)
for event in event_stream:
    print(event)

from pm4py.objects.conversion.log import factory as conversion_factory

log = conversion_factory.apply(event_stream)

from pm4py.objects.log.exporter.csv import factory as csv_exporter

csv_exporter.export(event_stream, "data/outputFile1.csv")

#log = importer.apply('pmdata/running-example.xes')
net, initial_marking, final_marking = alpha_miner.apply(log)
gviz = visualizer.apply(net, initial_marking, final_marking)
visualizer.view(gviz)
Example #22
0
        inv1_p9, d_p10, h_p1, b_p11
    ]

    for arc in arcs:
        arc.source.out_arcs.add(arc)
        arc.target.in_arcs.add(arc)

    net.transitions.update(trans)
    net.places.update(places)
    net.arcs.update(arcs)

    init_marking = petri.Marking([p0])
    final_marking = petri.Marking([p11])

    out_fp = './net.dot'
    gviz = vis_factory.apply(net, init_marking, final_marking)
    gviz.save(out_fp)

    # out_fp = './test-net.pnml'
    # exporter.pnml.export_net(net, init_marking, out_fp, final_marking=final_marking)

    # build the reachability graph
    is_inv = lambda t: t.label is None
    rg, inv_states = build_reachability_graph(net, init_marking, is_inv)

    collapse_inv_trans(rg, inv_states)

#    out_fp = './image/test-rg.dot'
#    dot_gr = util.visualize_graphviz.visualize(rg)
#    dot_gr.save(out_fp, '.')
Example #23
0
def model(request, log_id, cube_id):
    values = request.GET.get("values")
    if (values == None):
        values = "{}"
    values = json.loads(values)

    def convert(value, dtype):
        if (dtype == 'float'):
            return float(value)
        elif (dtype == 'int'):
            return int(value)
        elif (dtype == 'date'):
            return convert_date(value)
        elif (dtype == 'bool'):
            return bool(value)
        else:
            return value

    def convert_date(value):
        # Construct datetime object to filter with pymongo
        time_format = "%Y-%m-%dT%H:%M:%S.%f"
        time_format = "%Y-%m-%d %H:%M:%S.%f"
        if ("." not in value):
            time_format = time_format[:-3]

        return datetime.strptime(value, time_format)

    algo = request.GET.get("algorithm")

    values_ = {}

    # Convert to attribute id to name like it is in the events.
    values_ = {}
    for key in values:
        if (key != 'log'):
            attribute = Attribute.objects.get(pk=key)
            if (":" in attribute.parent):
                parent = attribute.parent.split(':')[0]
                d_name = attribute.parent.split(':')[1]
                name = attribute.name

                # Query for elements of dictionary
                queryname = parent + ":" + d_name + ".children." + name
            else:
                queryname = attribute.name
                if (attribute.parent == "trace"):
                    queryname = 'trace:' + queryname

            if ("to" in values[key]):
                lower = values[key].split("to")[0].strip()
                upper = values[key].split('to')[1].strip()

                lower = convert(lower, attribute.dtype)
                upper = convert(upper, attribute.dtype)

                values_[queryname] = {'$gt': lower, '$lt': upper}
            else:
                value = convert(values[key], attribute.dtype)
                values_[queryname] = value

    values_['log'] = log_id
    values = values_

    client = MongoClient(host=DATABASES['default']['HOST'])
    db = client[DATABASES['default']['NAME']]
    trace_collection = db['traces']
    event_collection = db['events']

    t1 = time()
    all_events = event_collection.find(values)
    t2 = time()
    print("Time to get events: {}".format(t2 - t1))

    t1 = time()
    traces = groupby(all_events, key=lambda e: e['trace:_id'])
    t2 = time()
    print("Time to get traces: {}".format(t2 - t1))

    t1 = time()
    traces = [log_lib.log.Trace(g) for k, g in traces]
    t2 = time()
    print("Time to make list: {}".format(t2 - t1))

    # log_list = [log_lib.log.Trace([log_lib.log.Event(t_e) for t_e in all_events if t_e['trace:_id'] == db_trace['_id']]) for db_trace in db_traces]

    t1 = time()
    log = log_lib.log.EventLog(traces)
    t2 = time()
    print("Time to make event log: {}".format(t2 - t1))

    # for db_trace in db_traces:

    #     pm4py_trace = log_lib.log.Trace([log_lib.log.Event(t_e) for t_e in all_events if t_e['trace:_id'] == db_trace['_id']])

    #     log.append(pm4py_trace)
    #     print(len(log))

    # pm_events = []
    # traces = {str(e['trace:_id']): log_lib.log.Trace() for e in events}

    # for event in events:
    #     trace = trace_collection.find_one({"_id": event['trace:_id']})

    #     t = traces[str(event['trace:_id'])]
    #     del event['_id']
    #     del event['trace:_id']

    #     e = log_lib.log.Event(event)
    #     t.append(e)

    # log.append(traces.items())
    # for trace in traces:
    #     log.append(traces[trace])

    parameters = {"format": "svg"}

    event_log = EventLog.objects.get(pk=log_id)
    filename = str(event_log.pk) + algo + ".svg"

    t1 = time()
    if (algo == "alpha"):
        net, initial_marking, final_marking = alpha_miner.apply(log)
        gviz = pn_vis_factory.apply(net,
                                    initial_marking,
                                    final_marking,
                                    parameters=parameters)
        pn_vis_factory.save(gviz, filename)
    elif (algo == "inductive"):
        mine_tree = request.GET.get("mine_tree")
        if (mine_tree == 'true'):
            tree = inductive_miner.apply_tree(log)
            gviz = pt_vis_factory.apply(tree, parameters=parameters)
            pt_vis_factory.save(gviz, filename)
        else:
            net, initial_marking, final_marking = inductive_miner.apply(log)
            gviz = pn_vis_factory.apply(net,
                                        initial_marking,
                                        final_marking,
                                        parameters=parameters)
            pn_vis_factory.save(gviz, filename)
    elif (algo == "heuristic"):

        dependency_thresh = float(request.GET.get("dependency_thresh"))
        and_measure_thresh = float(request.GET.get("and_measure_thresh"))
        min_act_count = float(request.GET.get("min_act_count"))
        min_dfg_occurrences = float(request.GET.get("min_dfg_occurrences"))
        dfg_pre_cleaning_noise_thresh = float(
            request.GET.get("dfg_pre_cleaning_noise_thresh"))

        h_params = {
            'dependency_thresh': dependency_thresh,
            'and_measure_thresh': and_measure_thresh,
            'min_act_count': min_act_count,
            'min_dfg_occurrences': min_dfg_occurrences,
            'dfg_pre_cleaning_noise_thresh': dfg_pre_cleaning_noise_thresh,
        }

        net, im, fm = heuristics_miner.apply(log, parameters=h_params)
        gviz = pn_vis_factory.apply(net, im, fm, parameters=parameters)
        pn_vis_factory.save(gviz, filename)

    t2 = time()
    print("Time pm4py: {}".format(t2 - t1))

    svg = open(filename, "rb")
    svg_content = svg.read()
    svg.close()

    # Tdelete file, it's not required anymore
    os.remove(svg.name)

    return HttpResponse(svg_content, content_type="image/svg+xml")
#-----------------

from pm4py.objects.log.importer.csv import factory as csv_importer
excellentLog1A = csv_importer.import_event_stream('Excellent1A_fixed.csv')
from pm4py.objects.conversion.log import factory as conversion_factory
log1 = conversion_factory.apply(excellentLog1A)

from pm4py.visualization.dfg import factory as dfg_vis_factory

gviz = dfg_vis_factory.apply(dfg1, log=log1, variant="frequency")
dfg_vis_factory.view(gviz)

from pm4py.objects.conversion.dfg import factory as dfg_mining_factory

net, im, fm = dfg_mining_factory.apply(dfg1)

from pm4py.visualization.petrinet import factory as pn_vis_factory

gviz = pn_vis_factory.apply(net, im, fm)
pn_vis_factory.view(gviz)

from pm4py.evaluation.replay_fitness import factory as replay_factory
fitness_alpha = replay_factory.apply(log1, net, im, fm)

from pm4py.algo.conformance.alignments import factory as align_factory

alignments = align_factory.apply(log1, net, im, fm)

print(alignments)

#excellentLog1A = excellentLog1A.sort_values(by=['org:resource','case','time:timestamp'])
Example #25
0
def apply(dataframe, parameters=None):
    """
    Gets the Petri net through Inductive Miner, decorated by frequency metric

    Parameters
    ------------
    dataframe
        Dataframe
    parameters
        Parameters of the algorithm

    Returns
    ------------
    base64
        Base64 of an SVG representing the model
    model
        Text representation of the model
    format
        Format of the model
    """
    if parameters is None:
        parameters = {}

    decreasingFactor = parameters[
        "decreasingFactor"] if "decreasingFactor" in parameters else constants.DEFAULT_DEC_FACTOR

    activity_key = parameters[
        pm4_constants.
        PARAMETER_CONSTANT_ACTIVITY_KEY] if pm4_constants.PARAMETER_CONSTANT_ACTIVITY_KEY in parameters else xes.DEFAULT_NAME_KEY
    timestamp_key = parameters[
        pm4_constants.
        PARAMETER_CONSTANT_TIMESTAMP_KEY] if pm4_constants.PARAMETER_CONSTANT_TIMESTAMP_KEY in parameters else xes.DEFAULT_TIMESTAMP_KEY
    case_id_glue = parameters[
        pm4_constants.
        PARAMETER_CONSTANT_CASEID_KEY] if pm4_constants.PARAMETER_CONSTANT_CASEID_KEY in parameters else CASE_CONCEPT_NAME

    parameters[pm4_constants.RETURN_EA_COUNT_DICT_AUTOFILTER] = True
    dataframe = attributes_filter.filter_df_keeping_spno_activities(
        dataframe,
        activity_key=activity_key,
        max_no_activities=constants.MAX_NO_ACTIVITIES)
    dataframe, end_activities = auto_filter.apply_auto_filter(
        dataframe, parameters=parameters)
    end_activities = list(end_activities.keys())
    activities_count = attributes_filter.get_attribute_values(
        dataframe, activity_key, parameters=parameters)
    activities = list(activities_count.keys())
    start_activities = list(
        start_activities_filter.get_start_activities(
            dataframe, parameters=parameters).keys())

    dfg = df_statistics.get_dfg_graph(dataframe,
                                      activity_key=activity_key,
                                      timestamp_key=timestamp_key,
                                      case_id_glue=case_id_glue,
                                      sort_caseid_required=False,
                                      sort_timestamp_along_case_id=False)
    dfg = clean_dfg_based_on_noise_thresh(
        dfg,
        activities,
        decreasingFactor * constants.DEFAULT_DFG_CLEAN_MULTIPLIER,
        parameters=parameters)

    net, im, fm = inductive_miner.apply_dfg(dfg,
                                            parameters,
                                            activities=activities,
                                            start_activities=start_activities,
                                            end_activities=end_activities)
    spaths = get_shortest_paths(net)
    aggregated_statistics = get_decorations_from_dfg_spaths_acticount(
        net, dfg, spaths, activities_count, variant="frequency")
    gviz = pn_vis_factory.apply(net,
                                im,
                                fm,
                                parameters={"format": "svg"},
                                variant="frequency",
                                aggregated_statistics=aggregated_statistics)

    gviz_base64 = base64.b64encode(str(gviz).encode('utf-8'))

    ret_graph = get_graph.get_graph_from_petri(net, im, fm)

    return get_base64_from_gviz(gviz), export_petri_as_string(
        net, im, fm
    ), ".pnml", "parquet", activities, start_activities, end_activities, gviz_base64, ret_graph, "inductive", "freq", None, "", activity_key
Example #26
0
import os

from pm4py.objects.log.importer.csv import factory as csv_importer
from pm4py.objects.conversion.log import factory as conversion_factory
from pm4py.algo.discovery.alpha import factory as alpha_miner
from pm4py.visualization.petrinet import factory as vis_factory
from tests.translucent_event_log_new.algo.discover_petrinet.alpha_revise import trans_alpha

event_stream = csv_importer.import_event_stream(
    os.path.join("input_data", "sample.csv"))
log = conversion_factory.apply(event_stream)

net, im, fm = trans_alpha(log)
nett, imm, fmm = alpha_miner.apply(log)

gviz = vis_factory.apply(net, im, fm)
gvizz = vis_factory.apply(nett, imm, fmm)
vis_factory.view(gviz)
vis_factory.view(gvizz)
Example #27
0
def export_petri_net(path, output):
    net, i_m, f_m = output

    viz_params = {"format": "svg", "debug": True}
    gviz = pn_vis_factory.apply(net, i_m, f_m, parameters=viz_params)
    pn_vis_factory.save(gviz, path)
Example #28
0
def apply(log, parameters=None):
    """
    Gets the Petri net through Inductive Miner, decorated by frequency metric

    Parameters
    ------------
    log
        Log
    parameters
        Parameters of the algorithm

    Returns
    ------------
    base64
        Base64 of an SVG representing the model
    model
        Text representation of the model
    format
        Format of the model
    """
    if parameters is None:
        parameters = {}

    decreasingFactor = parameters[
        "decreasingFactor"] if "decreasingFactor" in parameters else constants.DEFAULT_DEC_FACTOR

    activity_key = parameters[
        pm4_constants.
        PARAMETER_CONSTANT_ACTIVITY_KEY] if pm4_constants.PARAMETER_CONSTANT_ACTIVITY_KEY in parameters else xes.DEFAULT_NAME_KEY

    # reduce the depth of the search done by token-based replay
    token_replay.MAX_REC_DEPTH = 1
    token_replay.MAX_IT_FINAL1 = 1
    token_replay.MAX_IT_FINAL2 = 1
    token_replay.MAX_REC_DEPTH_HIDTRANSENABL = 1

    log = attributes_filter.filter_log_on_max_no_activities(
        log,
        max_no_activities=constants.MAX_NO_ACTIVITIES,
        parameters=parameters)
    filtered_log = auto_filter.apply_auto_filter(log, parameters=parameters)

    activities_count = attributes_filter.get_attribute_values(
        filtered_log, activity_key)
    activities = list(activities_count.keys())
    start_activities = list(
        start_activities_filter.get_start_activities(
            filtered_log, parameters=parameters).keys())
    end_activities = list(
        end_activities_filter.get_end_activities(filtered_log,
                                                 parameters=parameters).keys())

    dfg = dfg_factory.apply(filtered_log, parameters=parameters)
    dfg = clean_dfg_based_on_noise_thresh(
        dfg,
        activities,
        decreasingFactor * constants.DEFAULT_DFG_CLEAN_MULTIPLIER,
        parameters=parameters)
    net, im, fm = inductive_miner.apply_dfg(dfg,
                                            parameters=parameters,
                                            activities=activities,
                                            start_activities=start_activities,
                                            end_activities=end_activities)

    parameters["format"] = "svg"
    gviz = pn_vis_factory.apply(net,
                                im,
                                fm,
                                log=filtered_log,
                                variant="frequency",
                                parameters=parameters)

    svg = get_base64_from_gviz(gviz)

    gviz_base64 = base64.b64encode(str(gviz).encode('utf-8'))

    ret_graph = get_graph.get_graph_from_petri(net, im, fm)

    return svg, export_petri_as_string(
        net, im, fm
    ), ".pnml", "xes", activities, start_activities, end_activities, gviz_base64, ret_graph, "inductive", "freq", None, "", activity_key
Example #29
0
                  (t2 - t1))
            print(
                "inductive is_sound_wfnet",
                check_soundness.check_petri_wfnet_and_soundness(
                    inductive_model, debug=True))

            parameters = {
                pmutil.constants.PARAMETER_CONSTANT_ACTIVITY_KEY: activity_key,
                pmutil.constants.PARAMETER_CONSTANT_ATTRIBUTE_KEY:
                activity_key,
                "format": "png"
            }

            alpha_vis = petri_vis_factory.apply(alpha_model,
                                                alpha_initial_marking,
                                                alpha_final_marking,
                                                log=log,
                                                parameters=parameters,
                                                variant="frequency")
            vis_save(alpha_vis,
                     os.path.join(pngFolder, logNamePrefix + "_alpha.png"))
            heuristics_vis = petri_vis_factory.apply(heu_model,
                                                     heu_initial_marking,
                                                     heu_final_marking,
                                                     log=log,
                                                     parameters=parameters,
                                                     variant="frequency")
            vis_save(
                heuristics_vis,
                os.path.join(pngFolder, logNamePrefix + "_heuristics.png"))
            inductive_vis = petri_vis_factory.apply(inductive_model,
                                                    inductive_im,
Example #30
0
event_log = json_importer.import_log(os.path.join("form_json.json"),
                                     parameters={"rename_map": rename})
event_log.sort()

trace_log = log_transform.transform_event_log_to_trace_log(event_log)
trace_log.sort()
trace_log.insert_trace_index_as_event_attribute()
net, marking, final_marking = alpha_factory.apply(trace_log)

for place in marking:
    print("initial marking " + place.name)
for place in final_marking:
    print("final marking " + place.name)
gviz = pn_vis_factory.apply(net,
                            marking,
                            final_marking,
                            parameters={"format": "svg"})
pn_vis_factory.view(gviz)

#xes_exporter.export_log(trace_log, "form_json.xes")

net, marking, final_marking = inductive_factory.apply(trace_log)
for place in marking:
    print("initial marking " + place.name)
for place in final_marking:
    print("final marking " + place.name)
gviz = pn_vis_factory.apply(net,
                            marking,
                            final_marking,
                            parameters={"format": "svg"})
pn_vis_factory.view(gviz)