예제 #1
0
def main():
    n = sys.argv[1]
    # f = Model.parse_dimacs('data/%s.dimacs' % n)
    # f = Model.parse_dimacs('data/5_4_2_1_0.300000.dimacs')
    f = Model.parse_dimacs('data/random_240_1000_0.500000.dimacs')
    
    total_conflicts_count = 0

    f.unit_propagate()

    if f.clauses == []:
        print 'SAT'
        sys.exit(0)
    elif f.clauses == [[]]:
        print 'UNSAT'
        sys.exit(0)

    print 'f.clauses:', f.clauses

    forbidden = set()
    for clause in f.clauses:
        set_from_clause = set()
        for lit in clause:
            forbidden.add(frozenset([lit, -lit]))
            set_from_clause.add(-lit)
        forbidden.add(frozenset(set_from_clause))

    print 'forbidden:', forbidden

    formula_info = FormulaAnalyzer(f.clauses)
    variables_count = formula_info.count_variables()
    print 'Variables counts: %r' % variables_count

    # Gathering info about conflicts
    for clause in forbidden:
        mult = 1
        for lit in clause:
            mult *= variables_count[lit]
        mult /= fact(len(clause))
        print clause, ':', mult
        total_conflicts_count += mult

    print 'total_conflicts_count:', total_conflicts_count

    # sys.exit(0)

    # greedy(f, forbidden)
    sorted(f, forbidden)
예제 #2
0
def main():
    start = int(sys.argv[1])
    try: end = int(sys.argv[2])
    except: end = start
    x_range = range(start, end+1)
    y_range = []
    p_range = []
    #count_0s_range = []
    i = start
    while i <= end:
        build_model_start = time()
        sat = FactorizationModel()
        number = i
        bin_number = bin(number)[2:]
        len_bin_number = len(bin_number)
        N = sat.add_integer('N', number, length=len_bin_number)
        l = len(N)
        P = sat.add_seq('P', l)
        Q = sat.add_seq('Q', l)
        sat.add_multiplication_without_trivial_factors(P, Q, N)
        build_model_duration = time() - build_model_start

        # sat.unit_propagate()
        # for j in [1]:
        #     sat.resolution(j)
        #     print 'resolution: %d' % j
        #     print sat.clauses

        # sat.resolution(1)
        # sat.save_dimacs('data/%d.resolution_1.dimacs' % i)

        # sat.evaluation(1)
        # sat.save_dimacs('data/%d.evaluation_1.dimacs' % i)   

        # sat.evaluation(-1)
        # sat.save_dimacs('data/%d.evaluation_-1.dimacs' % i)

        print 'Expected number of satisfied clauses:', sat.sat_expectation()

        solve_model_start = time()
        solution = sat.solve()
        solve_model_duration = time() - solve_model_start

        sat.save_dimacs('data/%d.dimacs' % i)

        formula_info = FormulaAnalyzer(sat.clauses)

        #print sat.clauses
        print 'Time for building: %f, Time for solving: %f, # of factors: %d, # of vars: %d, # of clauses: %d' % (
            build_model_duration, 
            solve_model_duration,
            factors_count(number),
            sat.vars_count(),
            sat.clauses_count()
        )

        print 'Variables counts: %r' % formula_info.count_variables()
        literals_count = formula_info.count_literals()
        print 'Literal counts: %r' % literals_count
        try:
            print 'Positive/negative ratio: %f' % (literals_count['positive'] / float(literals_count['negative']))
        except ZeroDivisionError:
            print 'Number of negative literals is 0'
            
        collisions_count = formula_info.count_collisions()
        y_range.append(collisions_count)
        print 'Collision count: %d' % collisions_count

        #count_0s_range.append(count_0s(i) + y_range[0] - count_0s(start))

        sat_xor, solution_xor = solve_xor(sat)
        # sat_or, solution_or = solve_or(sat)
        print 'XOR SAT: %r' % sat_xor
        # print 'OR SAT: %r' % sat_or

        if sat_xor:
            print "Amazing ! - we've got a satisfiable XOR extension"

        if solution != 'UNSAT':
            p_range.append(0)
            factor1 = sat.get_decimal_value(P, solution)
            factor2 = sat.get_decimal_value(Q, solution)
            print '%d = %d * %d' % (number, factor1, factor2)
            if factor1 * factor2 != number:
                raise Exception("Bad factorization!")
            if factor1 == 1 or factor2 == 1:
                raise Exception("1 should not appear in prime factorization!")
        else:
            p_range.append(1)
            if factors_count(number) > 1:
                raise Exception("Number should not be treated as prime!")
            print '%d is prime' % number
        print '---------------------------------'
        i += 1

    plt.title('Collisions count')
    plt.xlabel('N')
    plt.ylabel('Collisions')
    plt.scatter(x_range, y_range, c=p_range, cmap='gray')
    #plt.scatter(x_range, count_0s_range, c='red')
    plt.show()
예제 #3
0
def main():
    # f = Model.parse_dimacs('data/binowa1.dimacs')
    # f = Model.parse_dimacs('data/5_4_2_1_0.300000.dimacs')
    # f = Model.parse_dimacs('data/10_7_4_3_0.300000.dimacs')
    # f = Model.parse_dimacs('data/20_12_6_4_0.300000.dimacs')

    # f = Model.parse_dimacs('data/random_100_1000_0.500000.dimacs')
    # f = Model.parse_dimacs('data/random_170_1000_0.500000.dimacs')
    # f = Model.parse_dimacs('data/random_200_1000_0.500000.dimacs')
    # f = Model.parse_dimacs('data/random_220_1000_0.500000.dimacs')
    # f = Model.parse_dimacs('data/random_230_1000_0.500000.dimacs')
    # f = Model.parse_dimacs('data/random_240_1000_0.000000.dimacs')
    # f = Model.parse_dimacs('data/random_240_1000_0.200000.dimacs')
    # f = Model.parse_dimacs('data/random_240_1000_0.500000.dimacs')
    # f = Model.parse_dimacs('data/random_240_1000_0.800000.dimacs')
    f = Model.parse_dimacs('data/random_240_1000_1.000000.dimacs')
    # f = Model.parse_dimacs('data/random_250_1000_0.500000.dimacs')
    # f = Model.parse_dimacs('data/random_500_1000_0.500000.dimacs')
    

    d = defaultdict(int)
    c = Counter()
    positive_counter = Counter()
    avg_positive_count = 0
    positive_vec = []

    occurences_counter = 0

    formula_info = FormulaAnalyzer(f.clauses)
    print 'literals_count:', formula_info.count_literals()
    variables_count = formula_info.count_variables()
    print 'Variables counts: %r' % variables_count

    l = len(set([abs(x) for x in variables_count.keys()]))
    for i in xrange(l):
        positive_counter[i] = 0

    fixed_set = set()

    total_count = 0
    # Number of auxiliary variables that are appearing set the same way (fixed) in all satisfying assignments
    fixed_set_count = 0

    # Propagating units and adding units as clauses
    # f.unit_propagate()

    # print 'After unit propagation:'
    # print f.clauses

    # for unit in f.all_units:
    #     f.clauses.append([unit])

    # print 'number of propagated units: ', len(f.all_units)

    for solution in f.itersolve():
        sol_tpl = tuple(solution)
        d[sol_tpl] += 1
        positive_count = len([x for x in sol_tpl if x > 0])
        positive_vec.append(positive_count)

        avg_positive_count += positive_count
        positive_counter[positive_count] += 1
        for elem in sol_tpl:
            c[elem] += 1
            if -elem not in c:
                c[-elem] = 0
        total_count += 1

        if total_count > LIMIT:
            break
        # print solution

    if total_count == 0:
        print 'UNSAT'
        sys.exit(-1)

    for k, v in d.iteritems():
         # print k, ':', v
         pass

    print 'len(d):', len(d) 
    print 'total_count:', total_count
    print 'most_common:'
    for k, v in c.most_common():
        # print k, ':', v
        if v == total_count:
            fixed_set.add(k)
            fixed_set_count += 1

    print 'fixed_set_count:', fixed_set_count
    print 'all_literals_count:', (len(c.keys()) + fixed_set_count) / 2

    fixed_set_positive_count = len([x for x in fixed_set if x > 0])
    print 'fixed_set_positive_count:', fixed_set_positive_count

    print 'Average number of positive literals in solution:', float(avg_positive_count) / total_count
    print 'min:', np.min(positive_vec)
    print 'median:', np.median(positive_vec)
    positive_vec_mean = np.mean(positive_vec)
    print 'avg:', positive_vec_mean
    print 'max:', np.max(positive_vec)
    print 'std:', np.std(positive_vec)
    print 'positive vars expected percentage:', positive_vec_mean / float(l)
    
    graph_distribution(positive_counter)

    graph_distribution(c)

    # fixed_set_minus_all_units = fixed_set - f.all_units
    # print 'fixed_set - f.all_units:', fixed_set_minus_all_units

    # for lit in fixed_set_minus_all_units:
    #     f.evaluation(lit)

    # f.unit_propagate()

    # print 'After unit propagation and taking advantage of fixed set:'
    # print f.clauses



    print 'positive_counter:', positive_counter
예제 #4
0
def main():
    n = sys.argv[1]
    f = Model.parse_dimacs("data/%s.dimacs" % n)

    products = []
    number_of_clauses = []
    x_range = []
    i = 0

    l = len(bin(int(n))[2:])

    # for i in xrange(1, 3*l+1):
    #     i += 1
    #     x_range.append(i)

    #     number_of_clauses.append(len(f.clauses))

    #     f.resolution(i)
    #     f.unit_propagate()
    #     f.superset_elimination()

    #     print 'len(f.clauses):', len(f.clauses)

    # print 'f.clauses after resolving N, P, Q variables:', f.clauses

    while True:
        i += 1

        f.unit_propagate()
        f.superset_elimination()

        x_range.append(i)
        number_of_clauses.append(len(f.clauses))

        print "len(f.clauses):", len(f.clauses)
        # print 'f.clauses:', f.clauses

        if f.clauses == []:
            print "SAT"
            break
        elif f.clauses == [[]]:
            print "UNSAT"
            break

        formula_info = FormulaAnalyzer(f.clauses)
        variables_count = formula_info.count_variables()

        minimal_product = float("inf")

        # print 'variables_count:', variables_count
        for k in variables_count.keys():
            kp = abs(k)
            km = -kp
            try:
                positive_k = variables_count[kp]
            except:
                positive_k = 0
            try:
                negative_k = variables_count[km]
            except:
                negative_k = 0
            product_k = negative_k * positive_k

            # print k, negative_k, positive_k, product_k

            if product_k < minimal_product:
                minimal_product = product_k
                resolution_var = kp

        products.append(minimal_product)

        print "Applying resolution on %d with product %d" % (resolution_var, minimal_product)
        f.resolution(resolution_var)

    # print 'Variables counts: %r' % formula_info.count_variables()

    # plt.scatter(x_range[:-1], products)
    plt.scatter(x_range, number_of_clauses)
    plt.show()
예제 #5
0
def main():
    n = sys.argv[1]
    f = Model.parse_dimacs('data/%s.dimacs' % n)

    print 'vars_count: %d' % f.vars_count() 
    print 'clauses_count: %d' % f.clauses_count()
    print 'clauses/vars ratio: %f' % f.clauses_to_vars_ratio()

    sys.exit(0)
    # Converting to SAT-3CNF
    # print f
    # print 'Before conversion to SAT-3CNF:', f.clauses
    # f.to_3cnf()
    # print 'After conversion to SAT-3CNF:', f.clauses
    # sys.exit(0)

    d = defaultdict(int)
    c = Counter()
    positive_counter = Counter()
    avg_positive_count = 0
    positive_vec = []
    decimals = defaultdict(list)

    odd_clauses_count = [0] * len(f.clauses)
    even_clauses_count = [0] * len(f.clauses)

    occurences_counter = 0
    intn = int(n)

    l = len(bin(intn)[2:])
    for i in xrange(4*l*l+3*l-1):
        positive_counter[i] = 0

    specific_clauses = f.clauses[:l-1]
    # f.clauses = f.clauses[l-1:]

    fixed_set = set()

    total_count = 0
    # Number of auxiliary variables that are appearing set the same way (fixed) in all satisfying assignments
    fixed_set_count = 0

    # Propagating units and adding units as clauses
    # f.unit_propagate()

    # print 'After unit propagation:'
    # print f.clauses

    # for unit in f.all_units:
    #     if abs(unit) >= l:
    #         f.clauses.append([unit])

    # print 'number of propagated units: ', len(f.all_units)

    parity_to_assignment = defaultdict(list)

    print 'specific_clauses: ', specific_clauses
    for solution in f.itersolve():
        decval_n = _get_decimal_value(solution[:l])
        decval_p = _get_decimal_value(solution[l:2*l])
        decval_q = _get_decimal_value(solution[2*l:3*l])
        # print decval_n
        # sol_tpl = tuple(solution[l:])
        sol_tpl = tuple(solution)
        sol_set = set(solution)

        d[sol_tpl] += 1
        positive_count = len([x for x in sol_tpl if x > 0])
        positive_vec.append(positive_count)
        decimals[positive_count].append((decval_n, decval_p, decval_q))

        total_odd = 0
        total_even = 0
        parity_str = ""

        for i, clause in enumerate(f.clauses):
            number_of_lits_in_sol = 0
            for lit in clause:
                if lit in sol_set:
                    number_of_lits_in_sol += 1
            if number_of_lits_in_sol % 2 == 0:
                parity_str += '0'
                total_even += 1
                even_clauses_count[i] += 1
            else:
                parity_str += '1'
                total_odd += 1
                odd_clauses_count[i] += 1

        parity_to_assignment[parity_str].append(sol_tpl)
        # print 'odd: %d, even: %d' % (total_odd, total_even)


        avg_positive_count += positive_count
        positive_counter[positive_count] += 1
        for elem in sol_tpl:
            c[elem] += 1
            if -elem not in c:
                c[-elem] = 0
        total_count += 1
        # print solution

    print 'Parity to assignment::'
    for k, v in parity_to_assignment.iteritems():
        print k, '-->', v

    print '# of distinct xorified formulas covering solution space: %d' % len(parity_to_assignment.keys())
    sys.exit(0)

    xor_clauses_file = open('xor_clauses_%d.cnf' % intn, 'w')
    always_odd_or_even_count = 0
    unit_clauses_count = 0
    for i, clause in enumerate(f.clauses):
        if len(clause) == 1:
            unit_clauses_count += 1
        if odd_clauses_count[i] == 0:
            always_odd_or_even_count += 1
            xor_clauses_file.write('x')
            xor_clauses_file.write(str(-clause[0]) + ' ')
            for j in xrange(1, len(clause)):
                xor_clauses_file.write(str(clause[j]) + ' ')
            xor_clauses_file.write('0\n')
        elif even_clauses_count[i] == 0:
            xor_clauses_file.write('x')
            for j in xrange(len(clause)):
                xor_clauses_file.write(str(clause[j]) + ' ')
            xor_clauses_file.write('0\n')
            always_odd_or_even_count += 1
        else:
            for j in xrange(len(clause)):
                xor_clauses_file.write(str(clause[j]) + ' ')
            xor_clauses_file.write('0\n')

        print '%d, odd: %d, even: %d' % (i, odd_clauses_count[i], even_clauses_count[i])

    print 'Percentage of always odd or even (crypto clauses): %f ' % (100 * float(always_odd_or_even_count) / len(f.clauses),) 
    print 'Percentage of unit clauses (with one literal only): %f ' % (100 * float(unit_clauses_count) / len(f.clauses),) 
    xor_clauses_file.close()

    sys.exit(0)

    for k, v in d.iteritems():
         # print k, ':', v
         pass

    for k in sorted(decimals):
        print k, ':', ['%d=%d*%d' % (x[0], x[1], x[2]) for x in decimals[k]] # [bin(x)[2:] for x in reversed(sorted(decimals[k]))]
    

    print 'len(d):', len(d) 
    print 'total_count:', total_count
    print 'most_common:'
    for k, v in c.most_common():
        # print k, ':', v
        if v == total_count:
            fixed_set.add(k)
            fixed_set_count += 1
    print 'fixed_set_count:', fixed_set_count
    print 'all_literals_count:', (len(c.keys()) + fixed_set_count) / 2

    fixed_set_positive_count = len([x for x in fixed_set if x > 0])
    print 'fixed_set_positive_count:', fixed_set_positive_count

    print 'Average number of positive literals in solution:', float(avg_positive_count) / total_count
    print 'min:', np.min(positive_vec)
    print 'median:', np.median(positive_vec)
    positive_vec_mean = np.mean(positive_vec)
    print 'avg:', positive_vec_mean
    print 'max:', np.max(positive_vec)
    print 'std:', np.std(positive_vec)
    print 'positive vars expected percentage:', positive_vec_mean / _number_of_vars(l)

    # sys.exit(0)
    
    graph_distribution(positive_counter)

    types_of_variables(l)
    graph_distribution(c)

    # fixed_set_minus_all_units = fixed_set - f.all_units
    # print 'fixed_set - f.all_units:', fixed_set_minus_all_units

    # for lit in fixed_set_minus_all_units:
    #     f.evaluation(lit)

    # f.unit_propagate()

    # print 'After unit propagation and taking advantage of fixed set:'
    # print f.clauses

    formula_info = FormulaAnalyzer(f.clauses)
    print 'literals_count:', formula_info.count_literals()
    print 'Variables counts: %r' % formula_info.count_variables()

    print 'positive_counter:', positive_counter