Example #1
0
    def test_add_ctx_normal(self):
        experiments_path = os.path.dirname(os.getcwd()) + "/experiments/"
        A = buildOTA(experiments_path + 'example3.json', 's')
        AA = buildAssistantOTA(A, 's')
        sigma = AA.sigma
        max_time_value = AA.max_time_value()

        H = buildOTA(experiments_path + 'example3_1.json', 'q')
        HH = buildAssistantOTA(H, 'q')

        # AA.show()
        # print("------------------------------")
        # HH.show()
        # print("------------------------------")
        # H.show()
        flag, ctx = equivalence_query_normal(max_time_value, AA, HH)
        # print("-------------ctx-----------------")
        # print(ctx.tws)
        ctxs = guess_ctx_reset(ctx.tws, AA)
        # print(len(ctxs))
        # for rtws in ctxs:
        #     print(rtws)
        # print("-------------local tws-----------------")
        for ctx in ctxs:
            local_tws = dRTWs_to_lRTWs(ctx)
            normalize(local_tws)
        #     #if check_guessed_reset(local_tws, table) == True:
        #     print(ctx)
        #     print(local_tws)
        #     pref = prefixes(local_tws)
        #     for tws in pref:
        #         print(tws)
        #     print("-------------------")

        T1_tables = init_table_normal(sigma, AA)
        T1_table_0 = T1_tables[0]
        test_E = [[Timedword('b', 2), Timedword('a', 4)], [Timedword('a', 5)]]
        T1_table_0.E = test_E
        # T1_table_0.show()
        # print("----------------------------------------")
        # tables = add_ctx_normal(ctx, T1_table_0, AA)
        #self.assertEqual(len(tables),65536)
        # tables[0].show()
        # tables[1].show()
        # tables[2].show()
        # tables[100].show()
        # tables[4095].show()
        # for table in tables:
        #     table.show()
        #     print("---------------------")

        T1_tables = init_table_normal(sigma, AA)
        T1_table_0 = T1_tables[0]
        test_E = [[Timedword('b', 2), Timedword('a', 4)]]
        T1_table_0.E = test_E
        # T1_table_0.show()
        # print("----------------------------------------")
        tables = add_ctx_normal(ctx, T1_table_0, AA)
        self.assertEqual(len(tables), 128)
Example #2
0
    def test_guess_resets_in_newsuffix(self):
        A = buildOTA('example6.json', 's')
        AA = buildAssistantOTA(A, 's')  # Assist
        #max_time_value = AA.max_time_value()
        sigma = AA.sigma

        T1_tables = init_table_normal(sigma, AA)
        T1_table_0 = T1_tables[0]
        test_E = [[Timedword('a', 2),
                   Timedword('b', 3),
                   Timedword('a', 1)], [Timedword('b', 2),
                                        Timedword('a', 4)]]
        T1_table_0.E = test_E
        suffixes_resets = guess_resets_in_newsuffix(T1_table_0, 0, 0, True,
                                                    True, AA)
        self.assertEqual(len(suffixes_resets), 1)
        self.assertEqual(len(suffixes_resets[0]), 4)
        self.assertEqual(
            suffixes_resets[0],
            [[True, None], [True, None], [True, None], [True, None]])

        test_E = [[Timedword('a', 2), Timedword('b', 3), Timedword('a', 1)]]
        T1_table_0.E = test_E
        suffixes_resets = guess_resets_in_newsuffix(T1_table_0, 0, 0, True,
                                                    True, AA)
        self.assertEqual(len(suffixes_resets), 256)
        self.assertEqual(len(suffixes_resets[34]), 4)
        self.assertEqual(suffixes_resets[1],
                         [[True, True, None], [True, True, None],
                          [True, True, None], [True, False, None]])
def equivalence_main():
    experiments_path = os.getcwd() + "/experiments/"
    A, _ = buildOTA(experiments_path + 'example3.json', 's')
    AA = buildAssistantOTA(A, 's')
    max_time_value = AA.max_time_value()

    # H, _ = buildOTA('example2_1.json', 'q')
    # HH = buildAssistantOTA(H, 'q')

    H, _ = buildOTA(experiments_path + 'example3_1.json', 'q')
    HH = buildAssistantOTA(H, 'q')

    AA.show()
    print("------------------------------")
    HH.show()
    print("------------------------------")
    H.show()
    flag, ctx = equivalence_query_normal(max_time_value, AA, HH)
    print(flag)
    print("-------------normal-----------------")
    print(ctx.tws)
    print()
    ctxs = guess_ctx_reset(ctx.tws)
    print(len(ctxs))
    for rtws in ctxs:
        print(rtws)

    # print("------------------------------")
    flag_pos, w_pos = ota_inclusion(max_time_value, HH, AA)
    print(flag_pos)
    #     flag_neg, w_neg = ota_inclusion(max_time_value, AA, HH)
    #     print(flag_neg)
    print(w_pos.show())
    print("--------------------------------------------")
    path1 = findpath(w_pos, 's', AA.sigma)
    for lw in path1:
        print(lw.show(), lw.action)
    print("----------------------------------------------")
    dtw = findDelayTimedwords(w_pos, 's', AA.sigma)
    print(dtw)
    print("----------------------------------------------")
    drtw = dTWs_to_dRTWs(w_pos, 's', AA)
    print(drtw)
    #flag, ctx = equivalence_query(max_time_value,AA,HH)
    #print(flag)
    print("------------------------------")
Example #4
0
    def test_init_table_normal(self):
        A = buildOTA('example6.json', 's')
        AA = buildAssistantOTA(A, 's')  # Assist
        #max_time_value = AA.max_time_value()
        sigma = AA.sigma

        tables = init_table_normal(sigma, AA)
        self.assertEqual(len(tables), 1)
def main():
    target = None
    while not target:
        target = pac_learn_ota(sys.argv[1], debug_flag=False)

    if target:
        A = buildOTA(sys.argv[1], 's')
        AA = buildAssistantOTA(A, 's')
        validateResult(AA, target)
Example #6
0
    def test_is_consistent(self):
        A = buildOTA('example2.json', 's')
        AA = buildAssistantOTA(A, 's')  # Assist
        max_time_value = AA.max_time_value()
        sigma = AA.sigma

        s1 = Element([], [0], [])
        s2 = Element([ResetTimedword('a', 0, True)], [-1], [])
        s3 = Element(
            [ResetTimedword('a', 1, False),
             ResetTimedword('b', 2, True)], [1], [])

        r1 = Element([ResetTimedword('b', 0, True)], [-1], [])
        r2 = Element(
            [ResetTimedword('a', 0, True),
             ResetTimedword('a', 0, True)], [-1], [])
        r3 = Element(
            [ResetTimedword('a', 0, True),
             ResetTimedword('b', 0, True)], [-1], [])
        r4 = Element([ResetTimedword('a', 1, False)], [0], [])
        r5 = Element([
            ResetTimedword('a', 1, False),
            ResetTimedword('b', 2, True),
            ResetTimedword('a', 0, False)
        ], [0], [])
        r6 = Element([
            ResetTimedword('a', 1, False),
            ResetTimedword('b', 2, True),
            ResetTimedword('b', 0, True)
        ], [-1], [])
        r7 = Element([ResetTimedword('b', 2, True)], [-1], [])

        new_S = [s1, s2, s3]
        new_R = [r1, r2, r3, r4, r5, r6, r7]
        for s in new_S:
            self.assertEqual(AA.is_accepted_delay(dRTWs_to_lRTWs(s.tws)),
                             s.value[0])
        for r in new_R:
            self.assertEqual(AA.is_accepted_delay(dRTWs_to_lRTWs(r.tws)),
                             r.value[0])
        new_E = []
        T5 = OTATable(new_S, new_R, new_E, parent=-1, reason="test")
        # T5.show()
        print("-----------is consistent----------------")
        flag, new_a, new_e_index, i, j, reset_i, reset_j = T5.is_consistent()
        self.assertEqual(flag, False)
        self.assertEqual(new_a, [ResetTimedword('b', 2, True)])
        self.assertEqual(new_e_index, 0)
        self.assertEqual(i, 0)
        self.assertEqual(j, 6)
        self.assertEqual(reset_i, True)
Example #7
0
    def test_make_closed(self):
        A = buildOTA('f.json', 's')
        AA = buildAssistantOTA(A, 's')  # Assist
        #max_time_value = AA.max_time_value()
        sigma = AA.sigma

        T1_tables = init_table_normal(sigma, AA)
        self.assertEqual(len(T1_tables), 2)
        #print("--------------------------------------------------")
        flag_closed, new_S, new_R, move = T1_tables[0].is_closed()
        self.assertEqual(flag_closed, False)
        tables = make_closed(new_S, new_R, move, T1_tables[0], sigma, AA)
        print("--------------make closed---------------------")
        self.assertEqual(len(tables), 2)
Example #8
0
    def test_guess_resets_in_suffixes(self):
        A = buildOTA('example6.json', 's')
        AA = buildAssistantOTA(A, 's')  # Assist
        #max_time_value = AA.max_time_value()
        sigma = AA.sigma

        T1_tables = init_table_normal(sigma, AA)
        T1_table_0 = T1_tables[0]
        test_E = [[Timedword('a', 2),
                   Timedword('b', 3),
                   Timedword('a', 1)], [Timedword('b', 2),
                                        Timedword('a', 4)],
                  [Timedword('a', 5)]]
        T1_table_0.E = test_E
        suffixes_resets = guess_resets_in_suffixes(T1_table_0)
        self.assertEqual(len(suffixes_resets), 8)
        self.assertEqual(len(suffixes_resets[5]), 3)
Example #9
0
    def test_make_consistent(self):
        A = buildOTA('example2.json', 's')
        AA = buildAssistantOTA(A, 's')  # Assist
        max_time_value = AA.max_time_value()
        sigma = AA.sigma

        s1 = Element([], [0], [])
        s2 = Element([ResetTimedword('a', 0, True)], [-1], [])
        s3 = Element(
            [ResetTimedword('a', 1, False),
             ResetTimedword('b', 2, True)], [1], [])

        r1 = Element([ResetTimedword('b', 0, True)], [-1], [])
        r2 = Element(
            [ResetTimedword('a', 0, True),
             ResetTimedword('a', 0, True)], [-1], [])
        r3 = Element(
            [ResetTimedword('a', 0, True),
             ResetTimedword('b', 0, True)], [-1], [])
        r4 = Element([ResetTimedword('a', 1, False)], [0], [])
        r5 = Element([
            ResetTimedword('a', 1, False),
            ResetTimedword('b', 2, True),
            ResetTimedword('a', 0, False)
        ], [0], [])
        r6 = Element([
            ResetTimedword('a', 1, False),
            ResetTimedword('b', 2, True),
            ResetTimedword('b', 0, True)
        ], [-1], [])
        r7 = Element([ResetTimedword('b', 2, True)], [-1], [])

        new_S = [s1, s2, s3]
        new_R = [r1, r2, r3, r4, r5, r6, r7]
        new_E = []
        T5 = OTATable(new_S, new_R, new_E, parent=-1, reason="test")
        # T5.show()
        print("-----------make consistent----------------")
        flag, new_a, new_e_index, i, j, reset_i, reset_j = T5.is_consistent()
        self.assertEqual(flag, False)
        tables = make_consistent(new_a, new_e_index, i, j, reset_i, reset_j,
                                 T5, sigma, AA)
        for tb in tables:
            S_U_R = [s for s in tb.S] + [r for r in tb.R]
            self.assertEqual(S_U_R[i].suffixes_resets[-1], [None])
            self.assertEqual(S_U_R[j].suffixes_resets[-1], [None])
Example #10
0
    def test_is_closed(self):
        A = buildOTA('example6.json', 's')
        AA = buildAssistantOTA(A, 's')  # Assist
        #max_time_value = AA.max_time_value()
        sigma = AA.sigma

        T1_tables = init_table_normal(sigma, AA)
        self.assertEqual(len(T1_tables), 1)
        #print("--------------------------------------------------")
        flag_closed, new_S, new_R, move = T1_tables[0].is_closed()
        self.assertEqual(flag_closed, False)
        self.assertEqual(new_S, [
            Element([], [0], []),
            Element([ResetTimedword('a', 0, True)], [-1], [])
        ])
        self.assertEqual(new_R, [
            Element([ResetTimedword('b', 0, True)], [-1], []),
            Element([ResetTimedword('c', 0, True)], [-1], [])
        ])
        self.assertEqual(move, Element([ResetTimedword('a', 0, True)], [-1],
                                       []))
Example #11
0
        else:
            dtw.append(Timedword(path[i].label, ltw[i].time - ltw[i - 1].time))

    return Element(dtw, [])


def sampleGeneration2(teacher, upperGuard, length):
    if random.randint(0, 1) == 0:
        return sampleGeneration(teacher.sigma, upperGuard,
                                len(teacher.locations), length)
    else:
        sample = None
        while sample is None:
            sample = sampleGeneration_valid(teacher, upperGuard, length)
        return sample


if __name__ == "__main__":
    random.seed(1)

    import sys
    from ota import buildOTA, buildAssistantOTA

    A = buildOTA(sys.argv[1], 's')
    AA = buildAssistantOTA(A, 's')
    A.show()
    for i in range(100):
        sample = sampleGeneration2(A, A.max_time_value(), 4)
        if sample:
            print(sample.tws)
Example #12
0
def main():
    #print("------------------A-----------------")
    paras = sys.argv
    A, _ = buildOTA(paras[1], 's')
    #A,_ = buildOTA("example.json", 's')
    #A.show()
    #print("------------------Assist-----------------")
    AA = buildAssistantOTA(A, 's')
    #AA.show()
    #print("--------------max value---------------------")
    max_time_value = A.max_time_value()
    #print(max_time_value)
    #print("--------------all regions---------------------")
    #regions = get_regions(max_time_value)
    # for r in regions:
    #     print(r.show())
    print("**************Start to learn ...*******************")
    print("---------------initial table-------------------")
    sigma = AA.sigma
    T1 = init_table(sigma, AA)
    t_number = 1
    print("Table " + str(t_number) + " is as follow.")
    T1.show()
    print("-----------------------------------------------")
    start = time.time()
    equivalent = False
    eq_total_time = 0
    table = copy.deepcopy(T1)
    eq_number = 0
    target = None
    while equivalent == False:
        prepared = table.is_prepared(AA)
        while prepared == False:
            flag_closed, new_S, new_R, move = table.is_closed()
            if flag_closed == False:
                temp = make_closed(new_S, new_R, move, table, sigma, AA)
                table = temp
                t_number = t_number + 1
                print("Table " + str(t_number) + " is as follow.")
                table.show()
                print("--------------------------------------------------")
            flag_consistent, new_a, new_e_index = table.is_consistent()
            if flag_consistent == False:
                temp = make_consistent(new_a, new_e_index, table, sigma, AA)
                table = temp
                t_number = t_number + 1
                print("Table " + str(t_number) + " is as follow.")
                table.show()
                print("--------------------------------------------------")
            flag_evi_closed, new_added = table.is_evidence_closed(AA)
            if flag_evi_closed == False:
                temp = make_evidence_closed(new_added, table, sigma, AA)
                table = temp
                t_number = t_number + 1
                print("Table " + str(t_number) + " is as follow.")
                table.show()
                print("--------------------------------------------------")
            prepared = table.is_prepared(AA)
        fa, sink_name = to_fa(table, t_number)
        #print("---------------------------------------------")
        #fa.show()
        #print("---------------------------------------------")
        h = fa_to_ota(fa, sink_name, sigma, t_number)
        #h.show()
        #print("---------------------------------------------")
        target = copy.deepcopy(h)
        eq_start = time.time()
        equivalent, ctx = equivalence_query(max_time_value, AA, h)
        eq_end = time.time()
        eq_total_time = eq_total_time + eq_end - eq_start
        #print(ctx.show())
        eq_number = eq_number + 1
        if equivalent == False:
            temp = add_ctx(ctx.tws, table, AA)
            table = temp
            t_number = t_number + 1
            print("Table " + str(t_number) + " is as follow.")
            table.show()
            print("--------------------------------------------------")
    end_learning = time.time()
    if target is None:
        print("Error! Learning Failed.")
        print("*******************Failed.***********************")
    else:
        print("Succeed! The learned OTA is as follows.")
        print("---------------------------------------------------")
        target.show()
        print("---------------------------------------------------")
        # print("Total time of learning: " + str(end-start))
        # print("---------------------------------------------------")
        # print("Time intervals simplification...")
        # print()
        print("Removing the sink location...")
        print()
        print("The learned One-clock Timed Automtaton: ")
        print()
        target_without_sink = remove_sinklocation(target)
        end_removesink = time.time()
        target_without_sink.show()
        print("---------------------------------------------------")
        print("Total time of learning: " + str(end_learning - start))
        #print("---------------------------------------------------")
        #print("Total time of equivalence queries: " + str(eq_total_time))
        print("---------------------------------------------------")
        print("Total time of learning + simplifying: " +
              str(end_removesink - start))
        print("---------------------------------------------------")
        print("The element number of S in the last table: " +
              str(len(table.S)))
        print("The element number of R in the last table: " +
              str(len(table.R)))
        print(
            "The element number of E in the last table (excluding the empty-word): "
            + str(len(table.E)))
        print("Total number of observation table: " + str(t_number))
        print("Total number of membership query: " +
              str((len(table.S) + len(table.R)) * (len(table.E) + 1)))
        print("Total number of equivalence query: " + str(eq_number))
        print("*******************Successful!***********************")
Example #13
0
def pac_learn_ota(paras, debug_flag):
    A = buildOTA(paras, 's')
    AA = buildAssistantOTA(A, 's')
    max_time_value = A.max_time_value()

    print("**************Start to learn ...*******************")
    print("---------------initial table-------------------")
    sigma = AA.sigma

    prev_ctx = []
    round_num = 0
    t_number = 0
    target = None

    def random_one_step(current_table):
        """Find a random successor of the current table.

        Here a successor is defined to be the table after executing
        one make_closed, one make_consistent, or one add_ctx_normal
        on existing counterexamples.

        """
        nonlocal t_number

        # First check if the table is closed
        flag_closed, new_S, new_R, move = current_table.is_closed()
        if not flag_closed:
            if debug_flag:
                print(
                    "------------------make closed--------------------------")
            temp_tables = make_closed(new_S, new_R, move, current_table, sigma,
                                      AA)
            if len(temp_tables) > 0:
                return random.choice(temp_tables)
            else:
                return 'failed'

        # If is closed, check if the table is consistent
        flag_consistent, new_a, new_e_index, reset_index_i, reset_index_j, reset_i, reset_j = current_table.is_consistent(
        )
        if not flag_consistent:
            if debug_flag:
                print(
                    "------------------make consistent--------------------------"
                )
            temp_tables = make_consistent(new_a, new_e_index, reset_index_i,
                                          reset_index_j, reset_i, reset_j,
                                          current_table, sigma, AA)
            if len(temp_tables) > 0:
                return random.choice(temp_tables)
            else:
                return 'failed'

        # If prepared, check conversion to FA
        t_number += 1
        fa_flag, fa, sink_name = to_fa(current_table, t_number)
        if not fa_flag:
            return 'failed'

        # Can convert to FA: convert to OTA and test equivalence
        h = fa_to_ota(fa, sink_name, sigma, t_number)

        equivalent, ctx = True, None
        if prev_ctx is not None:
            for ctx in prev_ctx:
                teacher_res = AA.is_accepted_delay(ctx.tws)
                hypothesis_res = h.is_accepted_delay(ctx.tws)
                if teacher_res != hypothesis_res and hypothesis_res != -2:
                    equivalent, ctx = False, ctx

        if equivalent:
            # If equivalent, the current table is a candidate
            return 'candidate'
        else:
            # Otherwise, add counterexample
            temp_tables = add_ctx_normal(ctx.tws, current_table, AA)
            if len(temp_tables) > 0:
                return random.choice(temp_tables)
            else:
                return 'failed'

    def random_steps(current_table, max_len, cur_h, comparator=True):
        """Execute random_one_step until reaching a candidate.

        Here a candidate means a prepared table that agrees with teacher
        on all existing counterexamples.

        """
        nonlocal t_number

        while current_table.effective_len() < max_len:
            res = random_one_step(current_table)
            if res == 'failed':
                return 'failed'
            elif res == 'candidate':
                # Find shortest difference
                if cur_h is None or not comparator:
                    return current_table
                else:
                    t_number += 1
                    fa_flag, fa, sink_name = to_fa(current_table, t_number)
                    if not fa_flag:
                        return 'failed'
                    h = fa_to_ota(fa, sink_name, sigma, t_number)
                    equivalent, ctx = equivalence_query_normal(
                        max_time_value, cur_h, h, None)
                    assert not equivalent
                    realValue = AA.is_accepted_delay(ctx.tws)
                    value = h.is_accepted_delay(ctx.tws)
                    if (realValue == 1 and value != 1) or (realValue != 1
                                                           and value == 1):
                        temp_tables = add_ctx_normal(ctx.tws, current_table,
                                                     AA)
                        if len(temp_tables) > 0:
                            current_table = random.choice(temp_tables)
                        else:
                            return 'failed'
                    else:
                        return current_table
            else:
                current_table = res
        return 'failed'

    def single_search():
        """Single path search: at each step, pick a random successor."""
        nonlocal round_num

        init_tables = init_table_normal(sigma, AA)
        current_table = random.choice(init_tables)

        # Current hypothesis
        cur_h = None

        while True:
            round_num += 1
            current_table = random_steps(current_table,
                                         15,
                                         cur_h,
                                         comparator=False)
            if current_table == 'failed':
                return None

            if current_table.effective_len() >= 15:
                return None

            print('ctx test:', current_table.effective_len())

            # If prepared, check conversion to FA
            fa_flag, fa, sink_name = to_fa(current_table, t_number)
            if not fa_flag:
                return None

            # Can convert to FA: convert to OTA and test equivalence
            cur_h = fa_to_ota(fa, sink_name, sigma, t_number)

            # equivalent, ctx = equivalence_query_normal(max_time_value, AA, cur_h, prev_ctx)
            equivalent, ctx, _ = pac_equivalence_query(A, max_time_value, AA,
                                                       cur_h, round_num, 0.001,
                                                       0.001)
            if ctx:
                print(ctx.tws)

            # Add counterexample to prev list
            if not equivalent and ctx not in prev_ctx:
                prev_ctx.append(ctx)

            if not equivalent:
                temp_tables = add_ctx_normal(ctx.tws, current_table, AA)
                if len(temp_tables) > 0:
                    current_table = random.choice(temp_tables)
                else:
                    return None
            else:
                return current_table, cur_h

    def parallel_search():
        """Parallel search.
        
        Maintain a list of current tables (of size width). At each iteration,
        pick a number of random successors (of size expand_factor) to form
        the new list of tables. Sort the new list and pick the best 'width'
        tables for the next iteration.

        """
        nonlocal round_num, t_number

        init_tables = init_table_normal(sigma, AA)
        width = 15
        expand_factor = 2
        tables = []
        for i in range(width):
            tables.append(random.choice(init_tables))

        while round_num < 10:
            round_num += 1
            print(round_num)

            new_tables = []
            for i in range(min(len(tables), width)):
                for j in range(expand_factor):
                    if round_num == 1:
                        current_table, cur_h = tables[i], None
                    else:
                        current_table, cur_h, ctx = tables[i]
                        temp_tables = add_ctx_normal(ctx.tws, current_table,
                                                     AA)
                        if len(temp_tables) > 0:
                            current_table = random.choice(temp_tables)
                        else:
                            continue

                    current_table = random_steps(current_table,
                                                 20,
                                                 cur_h,
                                                 comparator=False)
                    if current_table == 'failed':
                        continue

                    if current_table.effective_len() >= 20:
                        continue

                    # If prepared, check conversion to FA
                    t_number += 1
                    fa_flag, fa, sink_name = to_fa(current_table, t_number)
                    if not fa_flag:
                        continue

                    # Can convert to FA: convert to OTA and test equivalence
                    cur_h = fa_to_ota(fa, sink_name, sigma, t_number)

                    equivalent, ctx, sc = pac_equivalence_query(
                        A, max_time_value, AA, cur_h, round_num, 0.001, 0.001)

                    if not equivalent:
                        new_tables.append(
                            (sc, current_table, copy.deepcopy(cur_h), ctx))
                    else:
                        return current_table, cur_h

            new_tables = sorted(new_tables, reverse=True)
            tables = []
            for sc, table, cur_h, ctx in new_tables:
                print(sc, table.effective_len())
                tables.append((table, cur_h, ctx))
                if len(tables) >= width:
                    break

        return None

    res = parallel_search()

    if res is None:
        print("---------------------------------------------------")
        print("Error! Learning Failed.")
        print("*******************Failed.***********************")
        return False
    else:
        current_table, target = res
        print("---------------------------------------------------")
        print("Succeed! The learned OTA is as follows.")
        print("-------------Final table instance------------------")
        current_table.show()
        print("---------------Learned OTA-------------------------")
        target.show()
        print("---------------------------------------------------")
        print("Removing the sink location...")
        print()
        print("The learned One-clock Timed Automtaton: ")
        print()
        target_without_sink = remove_sinklocation(target)
        target_without_sink.show()
        print("---------------------------------------------------")
        print("Total number of membership query: " +
              str(len(AA.membership_query)))
        print("Total number of membership query (no-cache): " +
              str(AA.mem_query_num))
        print("Total number of equivalence query: " + str(len(prev_ctx) + 1))
        print("Total number of equivalence query (no-cache): " +
              str(AA.equiv_query_num))
        print("Total number of tables explored: " + str(t_number))
        # print("Total number of tables to explore: " + str(need_to_explore.qsize()))
        # print("Total time of learning: " + str(end_learning-start))
        return target_without_sink
Example #14
0
def learn_ota(paras, debug_flag):
    A = buildOTA(paras, 's')
    AA = buildAssistantOTA(A, 's')
    max_time_value = A.max_time_value()

    print("**************Start to learn ...*******************")
    print("---------------initial table-------------------")
    sigma = AA.sigma

    need_to_explore = queue.PriorityQueue()
    for table in init_table_normal(sigma, AA):
        need_to_explore.put((table.effective_len(), table))

    # List of existing counterexamples
    prev_ctx = []

    # Current number of tables
    t_number = 0
    start = time.time()
    eq_total_time = 0
    eq_number = 0
    target = None

    while True:
        if need_to_explore.qsize() == 0:
            break
        depth, current_table = need_to_explore.get()
        t_number = t_number + 1

        if t_number % 1 == 0:
            print(t_number, need_to_explore.qsize(), current_table.effective_len())
        if debug_flag:
            print("Table " + str(t_number) + " is as follow, %s has parent %s by %s" % (current_table.id, current_table.parent, current_table.reason))
            current_table.show()
            print("--------------------------------------------------")

        # First check if the table is closed
        flag_closed, new_S, new_R, move = current_table.is_closed()
        if not flag_closed:
            if debug_flag:
                print("------------------make closed--------------------------")
            temp_tables = make_closed(new_S, new_R, move, current_table, sigma, AA)
            if len(temp_tables) > 0:
                for table in temp_tables:
                    need_to_explore.put((table.effective_len(), table))
            continue

        # If is closed, check if the table is consistent
        flag_consistent, new_a, new_e_index, reset_index_i, reset_index_j, reset_i, reset_j = current_table.is_consistent()
        if not flag_consistent:
            if debug_flag:
                print("------------------make consistent--------------------------")
            temp_tables = make_consistent(new_a, new_e_index, reset_index_i, reset_index_j, reset_i, reset_j, current_table, sigma, AA)
            if len(temp_tables) > 0:
                for table in temp_tables:
                    need_to_explore.put((table.effective_len(), table))
            continue
        
        # If prepared, check conversion to FA
        fa_flag, fa, sink_name = to_fa(current_table, t_number)
        if not fa_flag:
            continue

        # Can convert to FA: convert to OTA and test equivalence
        h = fa_to_ota(fa, sink_name, sigma, t_number)
        eq_start = time.time()
        
        # equivalent, ctx = equivalence_query_normal(max_time_value, AA, h, prev_ctx)
        equivalent, ctx = True, None
        if prev_ctx is not None:
            for ctx in prev_ctx:
                teacher_res = AA.is_accepted_delay(ctx.tws)
                hypothesis_res = h.is_accepted_delay(ctx.tws)
                if teacher_res != hypothesis_res and hypothesis_res != -2:
                    equivalent, ctx = False, ctx
                    ctx = minimizeCounterexample(AA, h, ctx)

        if equivalent:
            AA.equiv_query_num += 1
            equivalent, ctx, _ = pac_equivalence_query(A, max_time_value, AA, h, AA.equiv_query_num, 0.001, 0.001)

        if not equivalent:
            # remove_sinklocation(copy.deepcopy(h)).show()
            print(ctx.tws)

        # print(ratio)

        # Add counterexample to prev list
        if not equivalent and ctx not in prev_ctx:
            prev_ctx.append(ctx)
        eq_end = time.time()
        eq_total_time = eq_total_time + eq_end - eq_start
        eq_number = eq_number + 1
        if not equivalent:
            temp_tables = add_ctx_normal(ctx.tws, current_table, AA)
            if len(temp_tables) > 0:
                for table in temp_tables:
                    need_to_explore.put((table.effective_len(), table))
        else:
            target = copy.deepcopy(h)
            break

    end_learning = time.time()
    if target is None:
        print("---------------------------------------------------")
        print("Error! Learning Failed.")
        print("*******************Failed.***********************")
        return False
    else:
        print("---------------------------------------------------")
        print("Succeed! The learned OTA is as follows.")
        print("-------------Final table instance------------------")
        current_table.show()
        print("---------------Learned OTA-------------------------")
        target.show()
        print("---------------------------------------------------")
        print("Removing the sink location...")
        print()
        print("The learned One-clock Timed Automtaton: ")
        print()
        target_without_sink = remove_sinklocation(target)
        end_removesink = time.time()
        target_without_sink.show()
        print("---------------------------------------------------")
        print("Number of transitions in teacher: " + str(len(A.trans)))
        print("Total number of membership query: " + str(len(AA.membership_query)))
        # print("Total number of membership query (no-cache): " + str(AA.mem_query_num))
        # print("Total number of equivalence query: " + str(len(prev_ctx) + 1))
        print("Total number of equivalence query (no-cache): " + str(AA.equiv_query_num))
        print("Total number of tests: " + str(AA.test_query_num))
        print("Total number of tables explored: " + str(t_number))
        # print("Total number of tables to explore: " + str(need_to_explore.qsize()))
        print("Number of locations in learned table: " + str(len(target_without_sink.locations)))
        print("Total time of learning: " + str(end_learning-start))
        return target_without_sink  
Example #15
0
def learn_ota_dfs(paras, depth, prev_ctx, debug_flag):
    A = buildOTA(paras, 's')
    AA = buildAssistantOTA(A, 's')
    max_time_value = A.max_time_value()

    sigma = AA.sigma

    # Current number of tables
    target = None
    t_number = 0

    def rec(current_table):
        """If solution is found, return target. Else, return None."""
        nonlocal t_number
        t_number += 1
        cur_depth = current_table.effective_len()
        if t_number % 10 == 0:
            print(t_number, cur_depth)

        if cur_depth > depth:
            return None

        # First check if the table is closed
        flag_closed, new_S, new_R, move = current_table.is_closed()
        if not flag_closed:
            temp_tables = make_closed(new_S, new_R, move, current_table, sigma, AA)
            for table in temp_tables:
                target = rec(table)
                if target is not None:
                    return target
            return None

        # If is closed, check if the table is consistent
        flag_consistent, new_a, new_e_index, reset_index_i, reset_index_j, reset_i, reset_j = current_table.is_consistent()
        if not flag_consistent:
            temp_tables = make_consistent(new_a, new_e_index, reset_index_i, reset_index_j, reset_i, reset_j, current_table, sigma, AA)
            for table in temp_tables:
                target = rec(table)
                if target is not None:
                    return target
            return None
        
        # If prepared, check conversion to FA
        fa_flag, fa, sink_name = to_fa(current_table, t_number)
        if not fa_flag:
            return None

        # Can convert to FA: convert to OTA and test equivalence
        h = fa_to_ota(fa, sink_name, sigma, t_number)
        equivalent, ctx = equivalence_query_normal(max_time_value, AA, h, prev_ctx)
        # Add counterexample to prev list
        if not equivalent and ctx not in prev_ctx:
            prev_ctx.append(ctx)
        if not equivalent:
            temp_tables = add_ctx_normal(ctx.tws, current_table, AA)
            for table in temp_tables:
                target = rec(table)
                if target is not None:
                    return target
            return None
        else:
            target = copy.deepcopy(h)
            return target


    tables = init_table_normal(sigma, AA)
    for table in tables:
        target = rec(table)
        if target is not None:
            return target, t_number

    return None, t_number