Example #1
0
class BinaryBayesStructure(Binary, PreBayesSpace):
    """A binary genotype with a Bayesian network structure phenotype.
    
    Bits indicate the presence or absence of an edge.
    
    Built on top of a variable space that determines the variables of the
    Bayes net. For example, a Euclidean space, say $\mathbb{R}^d$, would have
    $d$ :class:`GaussianVariable`s. Or, a Binary space would have
    :class:`BinaryVariable`s.
    
    The default choice of variable is controlled by the ``_mapping`` class
    variable based on the ``type`` field of the variable space. To have mixed
    networks, use a :class:`Product` space.
    
    :param space: The space of variables
    :type space: :class:`Space`
    
    """
    _mappings = {  # map space types to bayesian variables
        np.ndarray: GaussianVariable,
        TernaryString: BinaryVariable,
    }

    def __init__(self, space):
        self.space = space
        self.sampler = DAGSampler()

        if hasattr(space, 'dim'):
            self.numVariables = space.dim
        else:
            raise ValueError("Cannot determine the number of dimensions "
                             "for BinaryBayesStructure space based on given "
                             "space; expected space to have property dim "
                             "indicating the number of required variables. ")

        super(BinaryBayesStructure, self).__init__(self.numVariables**2)

        self.config = Config(numVariables=self.numVariables,
                             variableGenerator=self.variable,
                             randomizer=self.randomize,
                             sampler=self.sample)
        self.proposal = StructureProposal(**self.config.__properties__)
        self.config.structureGenerator = self.proposal

    def convert(self, x):
        if not isinstance(x, self.type):
            cname = self.__class__.__name__
            raise ValueError("Type mismatch in {0}.convert".format(cname))

        try:
            net = BayesNet(**self.config.__properties__)
            edges = []
            indexMap = {}
            for var in net.variables:
                indexMap[var.index] = var
            self.proposal.network = net
            for i in xrange(x.length):
                if x[i]:
                    frm, to = i % self.numVariables, i // self.numVariables
                    child = indexMap[frm]
                    parent = indexMap[to]
                    try:
                        self.proposal.addEdge(child, parent, self.config.data)
                    except CyclicException:
                        pass
            self.proposal.network = None
            return net
        except Exception:
            traceback.print_exc()
            raise ValueError("Unable to convert point due to exception")
Example #2
0
class BinaryBayesStructure(Binary, PreBayesSpace):
    """A binary genotype with a Bayesian network structure phenotype.
    
    Bits indicate the presence or absence of an edge.
    
    Built on top of a variable space that determines the variables of the
    Bayes net. For example, a Euclidean space, say $\mathbb{R}^d$, would have
    $d$ :class:`GaussianVariable`s. Or, a Binary space would have
    :class:`BinaryVariable`s.
    
    The default choice of variable is controlled by the ``_mapping`` class
    variable based on the ``type`` field of the variable space. To have mixed
    networks, use a :class:`Product` space.
    
    :param space: The space of variables
    :type space: :class:`Space`
    
    """
    _mappings = {  # map space types to bayesian variables
        np.ndarray: GaussianVariable,
        TernaryString: BinaryVariable,
    }
    
    def __init__(self, space):
        self.space = space
        self.sampler = DAGSampler()
        
        if hasattr(space, 'dim'):
            self.numVariables = space.dim
        else:
            raise ValueError("Cannot determine the number of dimensions "
                             "for BinaryBayesStructure space based on given "
                             "space; expected space to have property dim "
                             "indicating the number of required variables. ")
        
        super(BinaryBayesStructure, self).__init__(self.numVariables**2)
        
        self.config = Config(numVariables=self.numVariables,
                             variableGenerator=self.variable,
                             randomizer=self.randomize,
                             sampler=self.sample)
        self.proposal = StructureProposal(**self.config.__properties__)
        self.config.structureGenerator = self.proposal
        
       
    def convert(self, x):
        if not isinstance(x, self.type):
            cname = self.__class__.__name__
            raise ValueError("Type mismatch in {0}.convert".format(cname))
        
        try:
            net = BayesNet(**self.config.__properties__)
            edges = []
            indexMap = {}
            for var in net.variables:
                indexMap[var.index] = var
            self.proposal.network = net
            for i in xrange(x.length):
                if x[i]:
                    frm, to = i % self.numVariables, i // self.numVariables
                    child = indexMap[frm]
                    parent = indexMap[to]
                    try:
                        self.proposal.addEdge(child, parent, self.config.data)
                    except CyclicException:
                        pass
            self.proposal.network = None
            return net
        except Exception:
            traceback.print_exc()
            raise ValueError("Unable to convert point due to exception")