INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Cost function for WeightedMinFill. The cost of eliminating a node is the sum of weights of the edges that need to be added to the graph due to its elimination where a weight of an edge is the product of the weights domain cardinality of its constituent vertices.
def cost(self, node): """ Cost function for WeightedMinFill. The cost of eliminating a node is the sum of weights of the edges that need to be added to the graph due to its elimination, where a weight of an edge is the product of the weights, domain cardinality, of its constituen...
The cost of a eliminating a node is the product of weights domain cardinality of its neighbors.
def cost(self, node): """ The cost of a eliminating a node is the product of weights, domain cardinality, of its neighbors. """ return np.prod([self.bayesian_model.get_cardinality(neig_node) for neig_node in self.moralized_model.neighbors(node)])
Returns a dictionary of STATICPROPERTIES
def get_static_properties(self): """ Returns a dictionary of STATICPROPERTIES Examples -------- >>> reader = XBNReader('xbn_test.xml') >>> reader.get_static_properties() {'FORMAT': 'MSR DTAS XML', 'VERSION': '0.2', 'CREATOR': 'Microsoft Research DTAS'} ""...
Returns a list of variables.
def get_variables(self): """ Returns a list of variables. Examples -------- >>> reader = XBNReader('xbn_test.xml') >>> reader.get_variables() {'a': {'TYPE': 'discrete', 'XPOS': '13495', 'YPOS': '10465', 'DESCRIPTION': '(a) Metastatic Cancer', ...
Returns a list of tuples. Each tuple contains two elements ( parent child ) for each edge.
def get_edges(self): """ Returns a list of tuples. Each tuple contains two elements (parent, child) for each edge. Examples -------- >>> reader = XBNReader('xbn_test.xml') >>> reader.get_edges() [('a', 'b'), ('a', 'c'), ('b', 'd'), ('c', 'd'), ('c', 'e')] ...
Returns a dictionary of name and its distribution. Distribution is a ndarray.
def get_distributions(self): """ Returns a dictionary of name and its distribution. Distribution is a ndarray. The ndarray is stored in the standard way such that the rightmost variable changes most often. Consider a CPD of variable 'd' which has parents 'b' and 'c' (distribution['CONDS...
Returns an instance of Bayesian Model.
def get_model(self): """ Returns an instance of Bayesian Model. """ model = BayesianModel() model.add_nodes_from(self.variables) model.add_edges_from(self.edges) model.name = self.model_name tabular_cpds = [] for var, values in self.variable_CPD.i...
Set attributes for ANALYSISNOTEBOOK tag
def set_analysisnotebook(self, **data): """ Set attributes for ANALYSISNOTEBOOK tag Parameters ---------- **data: dict {name: value} for the attributes to be set. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter ...
Set STATICPROPERTIES tag for the network
def set_static_properties(self, **data): """ Set STATICPROPERTIES tag for the network Parameters ---------- **data: dict {name: value} for name and value of the property. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNW...
Set variables for the network.
def set_variables(self, data): """ Set variables for the network. Parameters ---------- data: dict dict for variable in the form of example as shown. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter >>> wri...
Set edges/ arc in the network.
def set_edges(self, edge_list): """ Set edges/arc in the network. Parameters ---------- edge_list: array_like list, tuple, dict or set whose each elements has two values (parent, child). Examples -------- >>> from pgmpy.readwrite.XMLBeliefNet...
Set distributions in the network.
def set_distributions(self): """ Set distributions in the network. Examples -------- >>> from pgmpy.readwrite.XMLBeliefNetwork import XBNWriter >>> writer =XBNWriter() >>> writer.set_distributions() """ distributions = etree.SubElement(self.bnmode...
Add an edge between variable_node and factor_node.
def add_edge(self, u, v, **kwargs): """ Add an edge between variable_node and factor_node. Parameters ---------- u, v: nodes Nodes can be any hashable Python object. Examples -------- >>> from pgmpy.models import FactorGraph >>> G = F...
Check the model for various errors. This method checks for the following errors. In the same time it also updates the cardinalities of all the random variables.
def check_model(self): """ Check the model for various errors. This method checks for the following errors. In the same time it also updates the cardinalities of all the random variables. * Check whether bipartite property of factor graph is still maintained or not. ...
Returns variable nodes present in the graph.
def get_variable_nodes(self): """ Returns variable nodes present in the graph. Before calling this method make sure that all the factors are added properly. Examples -------- >>> from pgmpy.models import FactorGraph >>> from pgmpy.factors.discrete import...
Returns factors nodes present in the graph.
def get_factor_nodes(self): """ Returns factors nodes present in the graph. Before calling this method make sure that all the factors are added properly. Examples -------- >>> from pgmpy.models import FactorGraph >>> from pgmpy.factors.discrete import Di...
Converts the factor graph into markov model.
def to_markov_model(self): """ Converts the factor graph into markov model. A markov model contains nodes as random variables and edge between two nodes imply interaction between them. Examples -------- >>> from pgmpy.models import FactorGraph >>> from p...
Returns the factors that have been added till now to the graph.
def get_factors(self, node=None): """ Returns the factors that have been added till now to the graph. If node is not None, it would return the factor corresponding to the given node. Examples -------- >>> from pgmpy.models import FactorGraph >>> from pgm...
Computes a score that measures how much a \ given variable is \ influenced \ by a given list of potential parents.
def local_score(self, variable, parents): "Computes a score that measures how much a \ given variable is \"influenced\" by a given list of potential parents." var_states = self.state_names[variable] var_cardinality = len(var_states) state_counts = self.state_counts(variable, par...
Extracting the cliques from the junction tree which are a subset of the given nodes.
def _get_clique(self, junction_tree, nodes): """ Extracting the cliques from the junction tree which are a subset of the given nodes. Parameters: ---------- junction_tree: Junction tree from which the nodes are to be extracted. nodes: iterable contai...
Getting the evidence belonging to a particular timeslice.
def _get_evidence(self, evidence_dict, time_slice, shift): """ Getting the evidence belonging to a particular timeslice. Parameters: ---------- evidence: dict a dict key, value pair as {var: state_of_var_observed} None if no evidence time: int ...
Marginalizing the factor selectively for a set of variables.
def _marginalize_factor(self, nodes, factor): """ Marginalizing the factor selectively for a set of variables. Parameters: ---------- nodes: list, array-like A container of nodes (list, dict, set, etc.). factor: factor factor which is to be margi...
Method for updating the belief.
def _update_belief(self, belief_prop, clique, clique_potential, message=None): """ Method for updating the belief. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. in_clique: clique The factor w...
Extracts the required factor from the junction tree.
def _get_factor(self, belief_prop, evidence): """ Extracts the required factor from the junction tree. Parameters: ---------- belief_prop: Belief Propagation Belief Propagation which needs to be updated. evidence: dict a dict key, value pair as {...
Shifting the factor to a certain required time slice.
def _shift_factor(self, factor, shift): """ Shifting the factor to a certain required time slice. Parameters: ---------- factor: DiscreteFactor The factor which needs to be shifted. shift: int The new timeslice to which the factor should belong to....
Forward inference method using belief propagation.
def forward_inference(self, variables, evidence=None, args=None): """ Forward inference method using belief propagation. Parameters: ---------- variables: list list of variables for which you want to compute the probability evidence: dict a dict ...
Backward inference method using belief propagation.
def backward_inference(self, variables, evidence=None): """ Backward inference method using belief propagation. Parameters: ---------- variables: list list of variables for which you want to compute the probability evidence: dict a dict key, value...
Query method for Dynamic Bayesian Network using Interface Algorithm.
def query(self, variables, evidence=None, args='exact'): """ Query method for Dynamic Bayesian Network using Interface Algorithm. Parameters: ---------- variables: list list of variables for which you want to compute the probability evidence: dict ...
Adds a single node to the Graph.
def add_node(self, node, weight=None): """ Adds a single node to the Graph. Parameters ---------- node: str, int, or any hashable python object. The node to add to the graph. weight: int, float The weight of the node. Examples --...
Add multiple nodes to the Graph.
def add_nodes_from(self, nodes, weights=None): """ Add multiple nodes to the Graph. **The behviour of adding weights is different than in networkx. Parameters ---------- nodes: iterable container A container of nodes (list, dict, set, or any hashable python ...
Add an edge between u and v.
def add_edge(self, u, v, weight=None): """ Add an edge between u and v. The nodes u and v will be automatically added if they are not already in the graph. Parameters ---------- u, v : nodes Nodes can be any hashable Python object. weight: i...
Add all the edges in ebunch.
def add_edges_from(self, ebunch, weights=None): """ Add all the edges in ebunch. If nodes referred in the ebunch are not already present, they will be automatically added. Node names can be any hashable python object. **The behavior of adding weights is different than n...
Removes all the immoralities in the DAG and creates a moral graph ( UndirectedGraph ).
def moralize(self): """ Removes all the immoralities in the DAG and creates a moral graph (UndirectedGraph). A v-structure X->Z<-Y is an immorality if there is no directed edge between X and Y. Examples -------- >>> from pgmpy.base import DAG >>>...
Returns a list of roots of the graph.
def get_roots(self): """ Returns a list of roots of the graph. Examples -------- >>> from pgmpy.base import DAG >>> graph = DAG([('A', 'B'), ('B', 'C'), ('B', 'D'), ('E', 'B')]) >>> graph.get_roots() ['A', 'E'] """ return [node for node, i...
Computes independencies in the DAG by checking d - seperation.
def get_independencies(self, latex=False): """ Computes independencies in the DAG, by checking d-seperation. Parameters ---------- latex: boolean If latex=True then latex string of the independence assertion would be created. Examples ---...
Returns an instance of Independencies containing the local independencies of each of the variables.
def local_independencies(self, variables): """ Returns an instance of Independencies containing the local independencies of each of the variables. Parameters ---------- variables: str or array like variables whose local independencies are to be found. ...
Checks whether the given model is I - equivalent
def is_iequivalent(self, model): """ Checks whether the given model is I-equivalent Two graphs G1 and G2 are said to be I-equivalent if they have same skeleton and have same set of immoralities. Note: For same skeleton different names of nodes can work but for immoralities ...
Finds all the immoralities in the model A v - structure X - > Z < - Y is an immorality if there is no direct edge between X and Y.
def get_immoralities(self): """ Finds all the immoralities in the model A v-structure X -> Z <- Y is an immorality if there is no direct edge between X and Y . Returns ------- set: A set of all the immoralities in the model Examples --------- >>>...
Returns True if there is any active trail between start and end node Parameters ---------- start: Graph Node end: Graph Node observed: List of nodes ( optional ) If given the active trail would be computed assuming these nodes to be observed. additional_observed: List of nodes ( optional ) If given the active trail wou...
def is_active_trail(self, start, end, observed=None): """ Returns True if there is any active trail between start and end node Parameters ---------- start : Graph Node end : Graph Node observed : List of nodes (optional) If given the active trail would...
Returns a markov blanket for a random variable. In the case of Bayesian Networks the markov blanket is the set of node s parents its children and its children s other parents.
def get_markov_blanket(self, node): """ Returns a markov blanket for a random variable. In the case of Bayesian Networks, the markov blanket is the set of node's parents, its children and its children's other parents. Returns ------- list(blanket_nodes): List of ...
Returns a dictionary with the given variables as keys and all the nodes reachable from that respective variable as values. Parameters ---------- variables: str or array like variables whose active trails are to be found. observed: List of nodes ( optional ) If given the active trails would be computed assuming these no...
def active_trail_nodes(self, variables, observed=None): """ Returns a dictionary with the given variables as keys and all the nodes reachable from that respective variable as values. Parameters ---------- variables: str or array like variables whose active tra...
Returns a dictionary of all ancestors of all the observed nodes including the node itself. Parameters ---------- obs_nodes_list: string list - type name of all the observed nodes Examples -------- >>> from pgmpy. base import DAG >>> model = DAG ( [ ( D G ) ( I G ) ( G L )... ( I L ) ] ) >>> model. _get_ancestors_of ( G...
def _get_ancestors_of(self, obs_nodes_list): """ Returns a dictionary of all ancestors of all the observed nodes including the node itself. Parameters ---------- obs_nodes_list: string, list-type name of all the observed nodes Examples --------...
Add an edge between two clique nodes.
def add_edge(self, u, v, **kwargs): """ Add an edge between two clique nodes. Parameters ---------- u, v: nodes Nodes can be any list or set or tuple of nodes forming a clique. Examples -------- >>> from pgmpy.models import JunctionTree ...
Check the model for various errors. This method checks for the following errors. In the same time also updates the cardinalities of all the random variables.
def check_model(self): """ Check the model for various errors. This method checks for the following errors. In the same time also updates the cardinalities of all the random variables. * Checks if clique potentials are defined for all the cliques or not. * Check for runn...
Returns a copy of JunctionTree.
def copy(self): """ Returns a copy of JunctionTree. Returns ------- JunctionTree : copy of JunctionTree Examples -------- >>> import numpy as np >>> from pgmpy.factors.discrete import DiscreteFactor >>> from pgmpy.models import JunctionTr...
Generate ProbModelXML lines for model.
def generate_probmodelxml(model, encoding='utf-8', prettyprint=True): """ Generate ProbModelXML lines for model. Parameters ---------- model : Graph The Bayesian or Markov Model encoding : string (optional) Encoding for text data prettyprint: bool (optional) If True ...
Write model in ProbModelXML format to path.
def write_probmodelxml(model, path, encoding='utf-8', prettyprint=True): """ Write model in ProbModelXML format to path. Parameters ---------- model : A NetworkX graph Bayesian network or Markov network path : file or string File or filename to write. Filenam...
Returns the model_data based on the given model.
def get_probmodel_data(model): """ Returns the model_data based on the given model. Parameters ---------- model: BayesianModel instance Model to write Return ------ model_data: dict dictionary containing model data of the given model. Examples -------- >>> ...
Sets AdditionalProperties of the ProbModelXML.
def _add_additional_properties(position, properties_dict): """ Sets AdditionalProperties of the ProbModelXML. """ add_prop = etree.SubElement(position, 'AdditionalProperties') for key, value in properties_dict.items(): etree.SubElement(add_prop, 'Property', attrib={'n...
Adds a node to the ProbModelXML.
def _add_variable(self, variable): """ Adds a node to the ProbModelXML. """ # TODO: Add feature for accepting additional properties of states. variable_data = self.data['probnet']['Variables'][variable] variable_element = etree.SubElement(self.variables, 'Variable', attri...
Adds an edge to the ProbModelXML.
def _add_link(self, edge): """ Adds an edge to the ProbModelXML. """ edge_data = self.data['probnet']['edges'][edge] if isinstance(edge, six.string_types): edge = eval(edge) link = etree.SubElement(self.links, 'Link', attrib={'var1': edge[0], 'var2': edge[1], ...
Adds constraint to the ProbModelXML.
def _add_constraint(self, constraint): """ Adds constraint to the ProbModelXML. """ constraint_data = self.data['probnet']['AdditionalConstraints'][constraint] constraint_element = etree.SubElement( self.additional_constraints, 'Constraint', attrib={'name': constraint...
Adds Decision Criteria to the ProbModelXML.
def _add_decision_criteria(self, criteria_dict): """ Adds Decision Criteria to the ProbModelXML. Parameters ---------- criteria_dict: dict Dictionary containing Deecision Criteria data. For example: {'effectiveness': {}, 'cost': {}} Examples ...
Adds Potentials to the ProbModelXML.
def _add_potential(self, potential, parent_tag): """ Adds Potentials to the ProbModelXML. Parameters ---------- potential: dict Dictionary containing Potential data. For example: {'role': 'Utility', 'Variables': ['D0', 'D1', 'C0'...
Helper function to add variable tag to the potential_tag
def _add_element(potential, var, potential_tag): """ Helper function to add variable tag to the potential_tag Parameters ---------- potential: dict Dictionary containing Potential data. For example: {'role': 'Utility', 'Variables...
Dumps the data to stream after appending header.
def dump(self, stream): """ Dumps the data to stream after appending header. """ if self.prettyprint: self.indent(self.xml) document = etree.ElementTree(self.xml) header = '<?xml version="1.0" encoding="%s"?>' % self.encoding stream.write(header.encode...
Write the xml data into the file.
def write_file(self, filename): """ Write the xml data into the file. Parameters ---------- filename: Name of the file. Examples ------- >>> writer = ProbModelXMLWriter(model) >>> writer.write_file(test_file) """ writer = self.__s...
Returns a BayesianModel or MarkovModel object depending on the type of ProbModelXML passed to ProbModelXMLReader class.
def create_probnet(self): """ Returns a BayesianModel or MarkovModel object depending on the type of ProbModelXML passed to ProbModelXMLReader class. """ self.probnet = {} # Add general properties probnet_elem = self.xml.find('ProbNet') self.probnet['type'...
Adds Additional Constraints to the probnet dict.
def add_probnet_additionalconstraints(self, constraint): """ Adds Additional Constraints to the probnet dict. Parameters ---------- criterion: <Element Constraint at AdditionalConstraints Node in XML> etree Element consisting Constraint tag. Examples ...
Adds Decision Criteria to the probnet dict.
def add_criterion(self, criterion): """ Adds Decision Criteria to the probnet dict. Parameters ---------- criterion: <Element Criterion at Decision Criteria Node in XML> etree Element consisting DecisionCritera tag. Examples ------- >>> reade...
Adds Variables to the probnet dict.
def add_node(self, variable): """ Adds Variables to the probnet dict. Parameters ---------- variable: <Element Variable at Variables Node in XML> etree Element consisting Variable tag. Examples ------- >>> reader = ProbModelXMLReader() ...
Adds Edges to the probnet dict.
def add_edge(self, edge): """ Adds Edges to the probnet dict. Parameters ---------- edge: <Element Link at Links Node in XML> etree Element consisting Variable tag. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.add_edg...
Adds Potential to the potential dict.
def add_potential(self, potential, potential_dict): """ Adds Potential to the potential dict. Parameters ---------- potential: <Element Potential at Potentials node in XML> etree Element consisting Potential tag. potential_dict: dict{} Dictionary ...
Returns the model instance of the ProbModel.
def get_model(self): """ Returns the model instance of the ProbModel. Return --------------- model: an instance of BayesianModel. Examples ------- >>> reader = ProbModelXMLReader() >>> reader.get_model() """ if self.probnet.get('t...
Computes all possible directed acyclic graphs with a given set of nodes sparse ones first. 2 ** ( n * ( n - 1 )) graphs need to be searched given n nodes so this is likely not feasible for n > 6. This is a generator.
def all_dags(self, nodes=None): """ Computes all possible directed acyclic graphs with a given set of nodes, sparse ones first. `2**(n*(n-1))` graphs need to be searched, given `n` nodes, so this is likely not feasible for n>6. This is a generator. Parameters ---------- ...
Computes a list of DAGs and their structure scores ordered by score.
def all_scores(self): """ Computes a list of DAGs and their structure scores, ordered by score. Returns ------- list: a list of (score, dag) pairs A list of (score, dag)-tuples, where score is a float and model a acyclic nx.DiGraph. The list is ordered by...
Estimates the DAG structure that fits best to the given data set according to the scoring method supplied in the constructor. Exhaustively searches through all models. Only estimates network structure no parametrization.
def estimate(self): """ Estimates the `DAG` structure that fits best to the given data set, according to the scoring method supplied in the constructor. Exhaustively searches through all models. Only estimates network structure, no parametrization. Returns ------- ...
Adds variables to the NoisyOrModel.
def add_variables(self, variables, cardinality, inhibitor_probability): """ Adds variables to the NoisyOrModel. Parameters ---------- variables: list, tuple, dict (array like) array containing names of the variables that are to be added. cardinality: list, t...
Deletes variables from the NoisyOrModel.
def del_variables(self, variables): """ Deletes variables from the NoisyOrModel. Parameters ---------- variables: list, tuple, dict (array like) list of variables to be deleted. Examples -------- >>> from pgmpy.models import NoisyOrModel ...
A utility function to return samples according to type
def _return_samples(return_type, samples): """ A utility function to return samples according to type """ if return_type.lower() == "dataframe": if HAS_PANDAS: return pandas.DataFrame.from_records(samples) else: warn("Pandas installation not found. Returning n...
Method that finds gradient and its log at position
def _get_gradient_log_pdf(self): """ Method that finds gradient and its log at position """ sub_vec = self.variable_assignments - self.model.mean.flatten() grad = - np.dot(self.model.precision_matrix, sub_vec) log_pdf = 0.5 * np.dot(sub_vec, grad) return grad, lo...
Method to perform time splitting using leapfrog
def _get_proposed_values(self): """ Method to perform time splitting using leapfrog """ # Take half step in time for updating momentum momentum_bar = self.momentum + 0.5 * self.stepsize * self.grad_log_position # Take full step in time for updating position position ...
Returns cardinality of a given variable
def get_cardinality(self, variables): """ Returns cardinality of a given variable Parameters ---------- variables: list, array-like A list of variable names. Returns ------- dict: Dictionary of the form {variable: variable_cardinality} ...
Returns a list of assignments for the corresponding index.
def assignment(self, index): """ Returns a list of assignments for the corresponding index. Parameters ---------- index: list, array-like List of indices whose assignment is to be computed Returns ------- list: Returns a list of full assignme...
Returns the identity factor.
def identity_factor(self): """ Returns the identity factor. Def: The identity factor of a factor has the same scope and cardinality as the original factor, but the values for all the assignments is 1. When the identity factor is multiplied with the factor it returns th...
Modifies the factor with marginalized values.
def marginalize(self, variables, inplace=True): """ Modifies the factor with marginalized values. Parameters ---------- variables: list, array-like List of variables over which to marginalize. inplace: boolean If inplace=True it will modify the f...
Normalizes the values of factor so that they sum to 1.
def normalize(self, inplace=True): """ Normalizes the values of factor so that they sum to 1. Parameters ---------- inplace: boolean If inplace=True it will modify the factor itself, else would return a new factor Returns ------- ...
Reduces the factor to the context of given variable values.
def reduce(self, values, inplace=True): """ Reduces the factor to the context of given variable values. Parameters ---------- values: list, array-like A list of tuples of the form (variable_name, variable_state). inplace: boolean If inplace=True ...
DiscreteFactor sum with phi1.
def sum(self, phi1, inplace=True): """ DiscreteFactor sum with `phi1`. Parameters ---------- phi1: `DiscreteFactor` instance. DiscreteFactor to be added. inplace: boolean If inplace=True it will modify the factor itself, else would return ...
DiscreteFactor division by phi1.
def divide(self, phi1, inplace=True): """ DiscreteFactor division by `phi1`. Parameters ---------- phi1 : `DiscreteFactor` instance The denominator for division. inplace: boolean If inplace=True it will modify the factor itself, else would return...
Returns a copy of the factor.
def copy(self): """ Returns a copy of the factor. Returns ------- DiscreteFactor: copy of the factor Examples -------- >>> import numpy as np >>> from pgmpy.factors.discrete import DiscreteFactor >>> phi = DiscreteFactor(['x1', 'x2', 'x3'...
Generate the string from __str__ method.
def _str(self, phi_or_p="phi", tablefmt="grid", print_state_names=True): """ Generate the string from `__str__` method. Parameters ---------- phi_or_p: 'phi' | 'p' 'phi': When used for Factors. 'p': When used for CPDs. print_state_names:...
Checks whether given parameter is a 1d array like object and returns a numpy array object
def _check_1d_array_object(parameter, name_param): """ Checks whether given parameter is a 1d array like object, and returns a numpy array object """ if isinstance(parameter, (np.ndarray, list, tuple, np.matrix)): parameter = np.array(parameter) if parameter.ndim != 1: raise ...
Raises an error when the length of given two arguments is not equal
def _check_length_equal(param_1, param_2, name_param_1, name_param_2): """ Raises an error when the length of given two arguments is not equal """ if len(param_1) != len(param_2): raise ValueError("Length of {} must be same as Length of {}".format(name_param_1, name_param_2))
Returns list of variables of the network
def get_variables(self): """ Returns list of variables of the network Examples -------- >>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml") >>> reader.get_variables() ['light-on', 'bowel-problem', 'dog-out', 'hear-bark', 'family-out'] """ variable...
Returns the edges of the network
def get_edges(self): """ Returns the edges of the network Examples -------- >>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml") >>> reader.get_edges() [['family-out', 'light-on'], ['family-out', 'dog-out'], ['bowel-problem', 'dog-out'], ...
Returns the states of variables present in the network
def get_states(self): """ Returns the states of variables present in the network Examples -------- >>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml") >>> reader.get_states() {'bowel-problem': ['true', 'false'], 'dog-out': ['true', 'false'], 'fa...
Returns the parents of the variables present in the network
def get_parents(self): """ Returns the parents of the variables present in the network Examples -------- >>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml") >>> reader.get_parents() {'bowel-problem': [], 'dog-out': ['family-out', 'bowel-problem'], ...
Returns the CPD of the variables present in the network
def get_values(self): """ Returns the CPD of the variables present in the network Examples -------- >>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml") >>> reader.get_values() {'bowel-problem': array([[ 0.01], [ 0.99]]), ...
Returns the property of the variable
def get_property(self): """ Returns the property of the variable Examples -------- >>> reader = XMLBIF.XMLBIFReader("xmlbif_test.xml") >>> reader.get_property() {'bowel-problem': ['position = (190, 69)'], 'dog-out': ['position = (155, 165)'], 'f...
Add variables to XMLBIF
def get_variables(self): """ Add variables to XMLBIF Return ------ dict: dict of type {variable: variable tags} Examples -------- >>> writer = XMLBIFWriter(model) >>> writer.get_variables() {'bowel-problem': <Element VARIABLE at 0x7fe2860...
Add outcome to variables of XMLBIF
def get_states(self): """ Add outcome to variables of XMLBIF Return ------ dict: dict of type {variable: outcome tags} Examples -------- >>> writer = XMLBIFWriter(model) >>> writer.get_states() {'dog-out': [<Element OUTCOME at 0x7ffbabfcd...
Transform the input state_name into a valid state in XMLBIF. XMLBIF states must start with a letter an only contain letters numbers and underscores.
def _make_valid_state_name(self, state_name): """Transform the input state_name into a valid state in XMLBIF. XMLBIF states must start with a letter an only contain letters, numbers and underscores. """ s = str(state_name) s_fixed = pp.CharsNotIn(pp.alphanums + "_").setPa...
Add property to variables in XMLBIF
def get_properties(self): """ Add property to variables in XMLBIF Return ------ dict: dict of type {variable: property tag} Examples -------- >>> writer = XMLBIFWriter(model) >>> writer.get_property() {'light-on': <Element PROPERTY at 0x7...
Add Definition to XMLBIF
def get_definition(self): """ Add Definition to XMLBIF Return ------ dict: dict of type {variable: definition tag} Examples -------- >>> writer = XMLBIFWriter(model) >>> writer.get_definition() {'hear-bark': <Element DEFINITION at 0x7f1d4...
Add Table to XMLBIF.
def get_values(self): """ Add Table to XMLBIF. Return --------------- dict: dict of type {variable: table tag} Examples ------- >>> writer = XMLBIFWriter(model) >>> writer.get_values() {'dog-out': <Element TABLE at 0x7f240726f3c8>, ...
Write the xml data into the file.
def write_xmlbif(self, filename): """ Write the xml data into the file. Parameters ---------- filename: Name of the file. Examples ------- >>> writer = XMLBIFWriter(model) >>> writer.write_xmlbif(test_file) """ with open(filename,...
Returns the marginal distribution over variables.
def marginal_distribution(self, variables, inplace=True): """ Returns the marginal distribution over variables. Parameters ---------- variables: string, list, tuple, set, dict Variable or list of variables over which marginal distribution needs to...
Check if the Joint Probability Distribution satisfies the given independence condition.
def check_independence(self, event1, event2, event3=None, condition_random_variable=False): """ Check if the Joint Probability Distribution satisfies the given independence condition. Parameters ---------- event1: list random variable whose independence is to be chec...
Returns the independent variables in the joint probability distribution. Returns marginally independent variables if condition = None. Returns conditionally independent variables if condition! = None
def get_independencies(self, condition=None): """ Returns the independent variables in the joint probability distribution. Returns marginally independent variables if condition=None. Returns conditionally independent variables if condition!=None Parameter --------- ...