Beispiel #1
0
def brute_force(window: int, data: str):
    """Brute force O(m * n) solution runs in plenty of time."""
    digits = get_data(data)
    max_product = product(digits[0:window])
    for x in range(1, len(digits) - window + 1):
        max_product = max(max_product, product(digits[x:x + window]))
    return max_product
    def fire(self, new_atom, cond_index, enqueue_func):
        if self.empty_atom_list_no:
            return

        # Binding: a (var_no, object) pair
        # Bindings: List-of(Binding)
        # BindingsFactor: List-of(Bindings)
        # BindingsFactors: List-of(BindingsFactor)
        bindings_factors = []
        for pos, cond in enumerate(self.conditions):
            if pos == cond_index:
                continue
            atoms = self.atoms_by_index[pos]
            assert atoms, "if we have no atoms, this should never be called"
            factor = [self._get_bindings(atom, cond) for atom in atoms]
            bindings_factors.append(factor)

        eff_args = self.prepare_effect(new_atom, cond_index)

        for bindings_list in tools.product(*bindings_factors):
            bindings = itertools.chain(*bindings_list)
            for var_no, obj in bindings:
                eff_args[var_no] = obj
            enqueue_func(self.effect.predicate, eff_args)
Beispiel #3
0
    def fire(self, new_atom, cond_index, enqueue_func):
        if self.empty_atom_list_no:
            return

        # Binding: a (var_no, object) pair
        # Bindings: List-of(Binding)
        # BindingsFactor: List-of(Bindings)
        # BindingsFactors: List-of(BindingsFactor)
        bindings_factors = []
        for pos, cond in enumerate(self.conditions):
            if pos == cond_index:
                continue
            atoms = self.atoms_by_index[pos]
            assert atoms, "if we have no atoms, this should never be called"
            factor = [self._get_bindings(atom, cond) for atom in atoms]
            bindings_factors.append(factor)

        eff_args = self.prepare_effect(new_atom, cond_index)

        for bindings_list in tools.product(*bindings_factors):
            bindings = itertools.chain(*bindings_list)
            for var_no, obj in bindings:
                eff_args[var_no] = obj
            enqueue_func(self.effect.predicate, eff_args)
Beispiel #4
0
def restriction(shape, dense=False):
    """
    Create a nonsquare restriction matrix by taking every second point along
    each axis in a 1D, 2D, or 3D domain.
    
    Parameters
    ----------
    shape : tuple of ints
        The (rectangular) geometry of the problem.
        
    Optional Parameters
    -------------------
    dense=False : bool
        Whether to use and return a sparse (CSR) restriction matrix.
        
    Returns
    -------
    R : ndarray
        Array of shape (N/(2**alpha), N), where the int N is the number of
        unknowns (product of shape ints), and alpha=len(shape).
    
    Requiring the shape of the domain is bad for the black-boxibility.
    Implementing a separate Ruge Steuben restriction method would avoid this.
    Returns a CSR matrix by default, but will return dense if dense=True is given.

    It would be nice to make this rely only on N, not shape. But, really, the
    restriction operator is problem-dependent. There are certainly problem
    domains where "dimensionality" means something other than spatial dimensions. 
    """
    # alpha is the dimensionality of the problem.
    alpha = len(shape)
    NX = shape[0]
    if alpha >= 2:
        NY = shape[1]
        #NZ = shape[3] # don't need this
    N = tools.product(shape)

    n = N / (2**alpha)
    if n in (0, 1):
        raise ValueError('New restriction matrix would have shape ' +
                         str((n, N)) + '. ' +
                         'Coarse set would have %d point(s)! ' % n +
                         'Try a larger problem or fewer gridLevels.')
    if dense:
        R = np.zeros((n, N))
    else:
        R = scipy.sparse.lil_matrix((n, N))

    # columns in the restriction matrix:
    if alpha == 1:
        coarseColumns = np.array(range(N)).reshape(shape)[::2].ravel()
    elif alpha == 2:
        coarseColumns = np.array(range(N)).reshape(shape)[::2, ::2].ravel()
    elif alpha == 3:
        coarseColumns = np.array(
            range(N)).reshape(shape)[::2, ::2, ::2].ravel()
    else:
        raise ValueError("restriction(): Greater than 3 dimensions is not"
                         "implemented. (shape was" + str(shape) + " .)")

    each = 1.0 / (2**alpha)
    for r, c in zip(range(n), coarseColumns):
        R[r, c] = each
        R[r, c + 1] = each
        if alpha >= 2:
            R[r, c + NX] = each
            R[r, c + NX + 1] = each
            if alpha == 3:
                R[r, c + NX * NY] = each
                R[r, c + NX * NY + 1] = each
                R[r, c + NX * NY + NX] = each
                R[r, c + NX * NY + NX + 1] = each

    if dense:
        return R
    else:
        return R.tocsr()
Beispiel #5
0
def restriction(shape, dense=False):
    """
    Create a nonsquare restriction matrix by taking every second point along
    each axis in a 1D, 2D, or 3D domain.
    
    Parameters
    ----------
    shape : tuple of ints
        The (rectangular) geometry of the problem.
        
    Optional Parameters
    -------------------
    dense=False : bool
        Whether to use and return a sparse (CSR) restriction matrix.
        
    Returns
    -------
    R : ndarray
        Array of shape (N/(2**alpha), N), where the int N is the number of
        unknowns (product of shape ints), and alpha=len(shape).
    
    Requiring the shape of the domain is bad for the black-boxibility.
    Implementing a separate Ruge Steuben restriction method would avoid this.
    Returns a CSR matrix by default, but will return dense if dense=True is given.

    It would be nice to make this rely only on N, not shape. But, really, the
    restriction operator is problem-dependent. There are certainly problem
    domains where "dimensionality" means something other than spatial dimensions. 
    """
    # alpha is the dimensionality of the problem.
    alpha = len(shape)
    NX = shape[0]
    if alpha >= 2:
        NY = shape[1]
        #NZ = shape[3] # don't need this
    N = tools.product(shape)

    n = N / (2 ** alpha)
    if n in (0, 1):
        raise ValueError('New restriction matrix would have shape ' + str((n,N))
                         + '. ' + 'Coarse set would have %d point(s)! ' % n+ 
                        'Try a larger problem or fewer gridLevels.')
    if dense:
        R = np.zeros((n, N))
    else:
        R = scipy.sparse.lil_matrix((n, N))
    
    # columns in the restriction matrix:
    if alpha == 1:
        coarseColumns = np.array(range(N)).reshape(shape)[::2].ravel()
    elif alpha == 2:
        coarseColumns = np.array(range(N)).reshape(shape)[::2, ::2].ravel()
    elif alpha == 3:
        coarseColumns = np.array(range(N)).reshape(shape)[::2, ::2, ::2].ravel()
    else:
        raise ValueError("restriction(): Greater than 3 dimensions is not"
                         "implemented. (shape was" + str(shape) +" .)")
    
    each = 1.0 / (2 ** alpha)
    for r, c in zip(range(n), coarseColumns):
        R[r, c] = each
        R[r, c + 1] = each
        if alpha >= 2:
            R[r, c + NX] = each
            R[r, c + NX + 1] = each
            if alpha == 3:
                R[r, c + NX * NY] = each
                R[r, c + NX * NY + 1] = each
                R[r, c + NX * NY + NX] = each
                R[r, c + NX * NY + NX + 1] = each

    if dense:
        return R
    else:
        return R.tocsr()
Beispiel #6
0
def test_product_4():
    gen = tools.product([3, 4], [0, 1, 2])
    assert [next(gen) for _ in range(5)] == [(3, 0), (3, 1), (3, 2), (4, 0), (4, 1)]
Beispiel #7
0
def test_product_3():
    gen = tools.product('123', [1, 2])
    assert [next(gen) for _ in range(5)] == [('1', 1), ('1', 2), ('2', 1), ('2', 2), ('3', 1)]
Beispiel #8
0
def test_product_2():
    assert next(tools.product('ABC', [1, 2])) == ('A', 1)
Beispiel #9
0
def test_product_1():
    assert list(tools.product('AB', [1, 2])) == [
        ('A', 1), ('A', 2), ('B', 1), ('B', 2)]