def test_split(self):
        sigma = CovarianceMatrix(
            [[4, 4, 8, 12], [4, 5, 8, 13], [8, 8, 20, 28], [12, 13, 28, 42]],
            names=['a', 'b', 'c', 'd'])
        sigma_xx, sigma_xy, sigma_yx, sigma_yy = sigma.split('a')
        print sigma_xx
        print sigma_xy
        for name in ['b', 'c', 'd']:
            assert name in sigma_xx.names
            assert name in sigma_xy.names
            assert name in sigma_yx.names
            assert name not in sigma_yy.names
        assert 'a' in sigma_yy.names
        assert 'a' not in sigma_xx.names
        assert 'a' not in sigma_xy.names
        assert 'a' not in sigma_yx.names
        for row, col in xproduct(['b', 'c', 'd'], ['b', 'c', 'd']):
            assert sigma_xx[row, col] == sigma[row, col]

        # Now lets test joint to conditional...
        # Since above we already took 'a' out of sigma_xx
        # we can now just re-split and remove 'd'
        sigma_xx, sigma_xy, sigma_yx, sigma_yy = sigma_xx.split('d')
        mu_x = MeansVector([[4], [9]])
        mu_y = MeansVector([[14]])
        beta_0, beta, sigma = joint_to_conditional(mu_x, mu_y, sigma_xx,
                                                   sigma_xy, sigma_yx,
                                                   sigma_yy)
        assert beta_0 == 1
        assert beta == Matrix([[1, 1]])
        assert sigma == Matrix([[1]])
Ejemplo n.º 2
0
Archivo: dfa.py Proyecto: wadoon/FPinTD
    def __pow__(self, amount):
        if amount == 1:
            return self

        if amount in self._productautomata:
            return self._productautomata[amount]

        Q = set(xproduct(self.Q, repeat=amount))
        delta = {(q, a): tuple(map(lambda s: self.d[s, a], q))
                 for q in Q
                 for a in self.A}

        q0 = tuple(itertools.repeat(self.s, amount))
        dea = DFA((Q, self.A, delta, q0, set()))

        self._productautomata[amount] = dea
        return dea
Ejemplo n.º 3
0
Archivo: dfa.py Proyecto: wadoon/FPinTD
    def inEquality(self):
        q = -1
        rev = ~(self ** 2)

        new_delta = rev.d.copy()
        for a in rev.A:
            new_delta[(q, q), a] = set()
            for p in xproduct(self.F, (self.Q - self.F)):
                new_delta[(q, q), a].add(p)

        tmpQ = rev.Q.copy()
        tmpQ.add((q, q))

        tmpA = DFA((tmpQ, self.A, new_delta, (self.s, self.s), self.F))
        Z = set()
        witness = {}
        for state, word in tmpA.search((q, q), False):
            Z.add(state)
            witness[state] = word[1:][::-1]
        return Z, witness
    def test_split(self):
        sigma = CovarianceMatrix(
            [
                [4, 4, 8, 12],
                [4, 5, 8, 13],
                [8, 8, 20, 28],
                [12, 13, 28, 42]],
            names=['a', 'b', 'c', 'd'])
        sigma_xx, sigma_xy, sigma_yx, sigma_yy = sigma.split('a')
        print(sigma_xx)
        print(sigma_xy)
        for name in ['b', 'c', 'd']:
            assert name in sigma_xx.names
            assert name in sigma_xy.names
            assert name in sigma_yx.names
            assert name not in sigma_yy.names
        assert 'a' in sigma_yy.names
        assert 'a' not in sigma_xx.names
        assert 'a' not in sigma_xy.names
        assert 'a' not in sigma_yx.names
        for row, col in xproduct(['b', 'c', 'd'], ['b', 'c', 'd']):
            assert sigma_xx[row, col] == sigma[row, col]

        # Now lets test joint to conditional...
        # Since above we already took 'a' out of sigma_xx
        # we can now just re-split and remove 'd'
        sigma_xx, sigma_xy, sigma_yx, sigma_yy = sigma_xx.split('d')
        mu_x = MeansVector([
            [4],
            [9]])
        mu_y = MeansVector([
            [14]])
        beta_0, beta, sigma = joint_to_conditional(
            mu_x, mu_y, sigma_xx, sigma_xy, sigma_yx, sigma_yy)
        assert beta_0 == 1
        assert beta == Matrix([[1, 1]])
        assert sigma == Matrix([[1]])
Ejemplo n.º 5
0
def build_gbn(*args, **kwds):
    '''Builds a Gaussian Bayesian Graph from
    a list of functions'''
    variables = set()
    name = kwds.get('name')
    variable_nodes = dict()
    factor_nodes = dict()

    if isinstance(args[0], list):
        # Assume the functions were all
        # passed in a list in the first
        # argument. This makes it possible
        # to build very large graphs with
        # more than 255 functions, since
        # Python functions are limited to
        # 255 arguments.
        args = args[0]

    for factor in args:
        factor_args = get_args(factor)
        variables.update(factor_args)
        node = GBNNode(factor)
        factor_nodes[factor.__name__] = node

    # Now lets create the connections
    # To do this we need to find the
    # factor node representing the variables
    # in a child factors argument and connect
    # it to the child node.
    # Note that calling original_factors
    # here can break build_gbn if the
    # factors do not correctly represent
    # a valid network. This will be fixed
    # in next release
    original_factors = get_original_factors(factor_nodes.values())
    for var_name, factor in original_factors.items():
        factor.variable_name = var_name
    for factor_node in factor_nodes.values():
        factor_args = get_args(factor_node)
        parents = [
            original_factors[arg] for arg in factor_args
            if original_factors[arg] != factor_node
        ]
        for parent in parents:
            connect(parent, factor_node)
    # Now process the raw_betas to create a dict
    for factor_node in factor_nodes.values():
        # Now we want betas to always be a dict
        # but in the case that the node only
        # has one parent we will allow the user to specify
        # the single beta for that parent simply
        # as a number and not a dict.
        if hasattr(factor_node.func, 'raw_betas'):
            if isinstance(factor_node.func.raw_betas, Number):
                # Make sure that if they supply a number
                # there is only one parent
                assert len(get_args(factor_node)) == 2
                betas = dict()
                for arg in get_args(factor_node):
                    if arg != factor_node.variable_name:
                        betas[arg] = factor_node.func.raw_betas
                factor_node.func.betas = betas
            else:
                factor_node.func.betas = factor_node.func.raw_betas
    gbn = GaussianBayesianGraph(original_factors, name=name)
    # Now for any conditional gaussian nodes
    # we need to tell the node function what the
    # parent parameters are so that the pdf can
    # be computed.
    sorted = gbn.get_topological_sort()
    joint_mu, joint_sigma = gbn.get_joint_parameters()
    for node in sorted:
        if hasattr(node.func, 'betas'):
            # This means its multivariate gaussian
            names = [n.variable_name
                     for n in node.parents] + [node.variable_name]
            node.func.joint_mu = MeansVector.zeros((len(names), 1),
                                                   names=names)
            for name in names:
                node.func.joint_mu[name] = joint_mu[name][0, 0]
            node.func.covariance_matrix = CovarianceMatrix.zeros(
                (len(names), len(names)), names)
            for row, col in xproduct(names, names):
                node.func.covariance_matrix[row, col] = joint_sigma[row, col]
    return gbn
def build_gbn(*args, **kwds):
    '''Builds a Gaussian Bayesian Graph from
    a list of functions'''
    variables = set()
    name = kwds.get('name')
    variable_nodes = dict()
    factor_nodes = dict()

    if isinstance(args[0], list):
        # Assume the functions were all
        # passed in a list in the first
        # argument. This makes it possible
        # to build very large graphs with
        # more than 255 functions, since
        # Python functions are limited to
        # 255 arguments.
        args = args[0]

    for factor in args:
        factor_args = get_args(factor)
        variables.update(factor_args)
        node = GBNNode(factor)
        factor_nodes[factor.__name__] = node

    # Now lets create the connections
    # To do this we need to find the
    # factor node representing the variables
    # in a child factors argument and connect
    # it to the child node.
    # Note that calling original_factors
    # here can break build_gbn if the
    # factors do not correctly represent
    # a valid network. This will be fixed
    # in next release
    original_factors = get_original_factors(list(factor_nodes.values()))
    for var_name, factor in list(original_factors.items()):
        factor.variable_name = var_name
    for factor_node in list(factor_nodes.values()):
        factor_args = get_args(factor_node)
        parents = [original_factors[arg] for arg in
                   factor_args if original_factors[arg] != factor_node]
        for parent in parents:
            connect(parent, factor_node)
    # Now process the raw_betas to create a dict
    for factor_node in list(factor_nodes.values()):
        # Now we want betas to always be a dict
        # but in the case that the node only
        # has one parent we will allow the user to specify
        # the single beta for that parent simply
        # as a number and not a dict.
        if hasattr(factor_node.func, 'raw_betas'):
            if isinstance(factor_node.func.raw_betas, Number):
                # Make sure that if they supply a number
                # there is only one parent
                assert len(get_args(factor_node)) == 2
                betas = dict()
                for arg in get_args(factor_node):
                    if arg != factor_node.variable_name:
                        betas[arg] = factor_node.func.raw_betas
                factor_node.func.betas = betas
            else:
                factor_node.func.betas = factor_node.func.raw_betas
    gbn = GaussianBayesianGraph(original_factors, name=name)
    # Now for any conditional gaussian nodes
    # we need to tell the node function what the
    # parent parameters are so that the pdf can
    # be computed.
    sorted = gbn.get_topological_sort()
    joint_mu, joint_sigma = gbn.get_joint_parameters()
    for node in sorted:
        if hasattr(node.func, 'betas'):
            # This means its multivariate gaussian
            names = [n.variable_name for n in node.parents] + [node.variable_name]
            node.func.joint_mu = MeansVector.zeros((len(names), 1), names=names)
            for name in names:
                node.func.joint_mu[name] = joint_mu[name][0, 0]
            node.func.covariance_matrix = CovarianceMatrix.zeros(
                (len(names), len(names)), names)
            for row, col in xproduct(names, names):
                node.func.covariance_matrix[row, col] = joint_sigma[row, col]
    return gbn