Beispiel #1
0
def natural_spline(t, knots=None, order=3, intercept=False):
    """ Return a Formula containing a natural spline

    Spline for a Term with specified `knots` and `order`.

    Parameters
    ----------
    t : ``Term``
    knots : None or sequence, optional
       Sequence of float.  Default None (same as empty list)
    order : int, optional
       Order of the spline. Defaults to a cubic (==3)
    intercept : bool, optional
       If True, include a constant function in the natural
       spline. Default is False

    Returns
    -------
    formula : Formula
         A Formula with (len(knots) + order) Terms
         (if intercept=False, otherwise includes one more Term), 
         made up of the natural spline functions.

    Examples
    --------
    The following results depend on machine byte order
       
    >>> x = Term('x')
    >>> n = natural_spline(x, knots=[1,3,4], order=3)
    >>> xval = np.array([3,5,7.]).view(np.dtype([('x', np.float)]))
    >>> n.design(xval, return_float=True)
    array([[   3.,    9.,   27.,    8.,    0.,   -0.],
           [   5.,   25.,  125.,   64.,    8.,    1.],
           [   7.,   49.,  343.,  216.,   64.,   27.]])
    >>> d = n.design(xval)
    >>> print d.dtype.descr
    [('ns_1(x)', '<f8'), ('ns_2(x)', '<f8'), ('ns_3(x)', '<f8'), ('ns_4(x)', '<f8'), ('ns_5(x)', '<f8'), ('ns_6(x)', '<f8')]
    >>>                    
                    
    """
    if knots is None:
        knots = {}
    fns = []
    for i in range(order + 1):
        n = 'ns_%d' % i

        def f(x, i=i):
            return x**i

        s = aliased_function(n, f)
        fns.append(s(t))

    for j, k in enumerate(knots):
        n = 'ns_%d' % (j + i + 1, )

        def f(x, k=k, order=order):
            return (x - k)**order * np.greater(x, k)

        s = aliased_function(n, f)
        fns.append(s(t))

    if not intercept:
        fns.pop(0)

    ff = Formula(fns)
    return ff
    parser.add_argument('-S', help="The strategy to be used")
    parser.add_argument('input_file',
                        help="The input file containing the SAT problem")

    # Parse the arguments
    arguments = parser.parse_args()

    if not arguments.input_file:
        raise Exception("Invalid input file")

utils.lambda_value = 0.45
utils.beta_value = 0.5

split_method = SplitMethod.DEFAULT
if arguments.S == "2":
    split_method = SplitMethod.MOM
elif arguments.S == "3":
    split_method = SplitMethod.TK

formula = Formula(Operation.AND)
formula.add_elements_from_file(arguments.input_file)

sat_solver = SatSolver(formula, split_method)
solved, values = sat_solver.solve()

output_file_name = f'{arguments.input_file}.out'
file_saver = FileSaver()
if solved:
    file_saver.save_values_in_dimacs(values, output_file_name)
else:
    file_saver.save_values_in_dimacs({}, output_file_name)
Beispiel #3
0
    signal(SIGPIPE, SIG_DFL)

    parser = argparse.ArgumentParser(
        description="Dynamic programming on a TD of a MaxSAT instance")
    parser.add_argument("file")
    parser.add_argument("--log", default="info")
    args = parser.parse_args()

    log_level_number = getattr(logging, args.log.upper(), None)
    if not isinstance(log_level_number, int):
        raise ValueError(f"Invalid log level: {loglevel}")
    logging.basicConfig(level=log_level_number)

    with open(args.file) as f:
        print("Parsing...")
        formula = Formula(f)
        log.debug(formula)
        print("Constructing primal graph...")
        g = formula.primal_graph()
        log.debug(g)
        print("Decomposing...")
        tds = Decomposer(g,
                         Graph.min_degree_vertex,
                         normalize=TD.weakly_normalize).decompose()
        assert len(tds) == 1
        td = tds[0]
        log.debug(td)
        root_table = Table(td, formula)
        print("Solving...")
        root_table.compute()
Beispiel #4
0
 def formula(self):
     """
     Return a Formula with only terms=[self].
     """
     return Formula([self])
Beispiel #5
0
    def _construct_tree(self):
        def add_vertex(stage):
            vertex = self._graph.add_vertex()
            index = self._graph.vertex_index[vertex]

            self._vertices[index] = stage

            return index

        def add_edge(i, j):
            self._graph.add_edge(i, j)

        phi = Formula()
        phi.assert_some_states_present(self.protocol.initial_states)

        root_stage = Stage(set(), set(), set(), set(), phi)
        root_index = add_vertex(root_stage)
        unprocessed = [(root_index, root_stage)]
        mem = {"K": {}, "K_": {}}  # For memoization

        while len(unprocessed) > 0:
            index, stage = unprocessed.pop(0)
            children, refined = new_stages(self.protocol, stage, mem,
                                           self._use_t_invariants)

            if not refined:
                # TODO find criterion to continue if refinement fails
                self._failed_stages.add(index)
                continue
                #self._strong_witness = False
                #self._all_good = False

            # If node failed to be expanded,
            # then flag as failure and skip to next iteration
            if children is None:
                self._failed_stages.add(index)
                continue

            # Check termination witness
            if self._check_termination_witness:
                witness = check_termination_witness(self.protocol, stage,
                                                    refined)
                if witness is None:
                    self._failed_witness_stages.add(index)
                elif witness is False:
                    self._strong_witness = False
                    self._all_good = False
                elif self._all_good:
                    self._all_good = is_good(self.protocol, stage, mem,
                                             self._use_t_invariants)

            # If stage in stable consensus, then flag its consensus
            if self.protocol.false_states <= stage.absent:
                self._true_stages.add(index)
            elif self.protocol.true_states <= stage.absent:
                self._false_stages.add(index)

            # Construct stage successors
            is_terminal = True

            for child_stage in children:
                is_terminal = False

                # Add child if depth does not exceed max depth
                if ((self._max_depth is None)
                        or (child_stage.depth() <= self._max_depth)):
                    child_index = add_vertex(child_stage)
                    add_edge(index, child_index)

                    unprocessed.append((child_index, child_stage))

            # If stage is terminal, then flag as terminal
            if is_terminal:
                self._terminal_stages.add(index)
sizes = list(product(range(2, 10), repeat=3))
print(len(sizes))
architectures = [NeuralNet(size) for size in sizes]
for i, nn in enumerate(architectures):
    start = time.time()
    nn.train()
    print(i, time.time() - start)
scores = [0 for _ in architectures]

testFormulas = FormulaSource()
testFormulas.gen_data(NUM_TEST_FORMULAS)
numCorrect = 0
numTotal = 0
for f in testFormulas.data:
    t = TruthTable(Formula(f))

    oracle(t)
    oracleT = copy(t.table)

    baseline(t)
    baseT = copy(t.table)
    nn_tables = []
    for nn in architectures:
        nn.solve_table(t)
        nn_tables.append(copy(t.table))
    for k in oracleT:
        numTotal += 1
        if oracleT[k] == baseT[k]:
            numCorrect += 1
        for i, nnT in enumerate(nn_tables):
Beispiel #7
0
def get_formula(formula):
    """Parsing formula to store as an element -> number of atoms dictionary"""
    parsed_formula = Formula(formula).parse_formula_to_elem_numatoms()
    return parsed_formula
Beispiel #8
0
 def __init__(self: PropagatingFormula, file_object: TextIO) -> None:
     self.formula = Formula(file_object)
     self.decision_level: DecisionLevel = 0
     self.propagate()
     self.decision_history: List[Optional[Tuple[Variable, Value]]] = [None]
def new_stage(protocol, stage, valuation, mem):
    new_valuation = new_stage_valuation(protocol, valuation, stage.disabled)

    if is_stable_or_dead(protocol, new_valuation, stage.disabled):
        return Stage(Formula(new_valuation),
                     new_valuation,
                     stage.disabled,
                     speed=Speed.ZERO,
                     parent=stage)

    F, J, graph, vertices, edges, V = eventually_disabled(
        protocol, new_valuation, stage.disabled, mem)

    # Compute new_formula (Φ) and new_disabled (T)
    if len(F) > 0:
        if len(J) > 0:
            new_disabled = set(stage.disabled) | set(J)
            new_formula = Formula(new_valuation, new_disabled)

            if v_disabled(J, valuation):
                new_formula.assert_valuation(valuation)
            elif v_enabled(J, valuation):
                K = posts_from_pres(protocol, new_valuation, J)
                new_formula.assert_some_pair_present(K)

            # Compute speed
            if is_very_fast(protocol, new_valuation, stage.disabled):
                new_speed = Speed.QUADRATIC
            elif is_fast(protocol, new_valuation, stage.disabled):
                new_speed = Speed.QUADRATIC_LOG
            else:
                new_speed = Speed.CUBIC
            small, emptycommons = is_small(protocol, new_valuation,
                                           stage.disabled, J, graph, vertices,
                                           edges, V)
            if small and emptycommons:
                new_speed = Speed.QUADRATIC
            elif small and (not (new_speed == Speed.QUADRATIC)):
                new_speed = Speed.QUADRATIC_LOG
        else:
            new_disabled = set(stage.disabled) | set(F)
            new_formula = Formula(new_valuation, new_disabled)
            new_speed = Speed.POLYNOMIAL
    else:
        new_disabled = set(stage.disabled)
        new_formula = Formula(new_valuation, new_disabled)
        new_speed = Speed.EXPONENTIAL

        I = compute_I(protocol, new_valuation, stage.disabled)

        if any(valuation[Var(q)] is True for q in I):
            L = compute_L(protocol, new_valuation, stage.disabled, I)

            new_formula.assert_all_states_absent(I)
            new_formula.assert_some_pair_present(L)
        elif all(valuation[Var(q)] is False for q in I):
            new_formula.assert_valuation(valuation)
        else:
            new_formula.assert_all_states_absent(I)

    return Stage(new_formula,
                 new_valuation,
                 new_disabled,
                 speed=new_speed,
                 parent=stage)