text stringlengths 81 112k |
|---|
Greatest common divisor using Euclid's algorithm.
def gcd2(a, b):
"""Greatest common divisor using Euclid's algorithm."""
while a:
a, b = b%a, a
return b |
Greatest common divisor.
Usage: gcd( [ 2, 4, 6 ] )
or: gcd( 2, 4, 6 )
def gcd( *a ):
"""Greatest common divisor.
Usage: gcd( [ 2, 4, 6 ] )
or: gcd( 2, 4, 6 )
"""
if len( a ) > 1: return reduce( gcd2, a )
if hasattr( a[0], "__iter__" ): return reduce( gcd2, a[0] )
return a[0] |
Least common multiple.
Usage: lcm( [ 3, 4, 5 ] )
or: lcm( 3, 4, 5 )
def lcm( *a ):
"""Least common multiple.
Usage: lcm( [ 3, 4, 5 ] )
or: lcm( 3, 4, 5 )
"""
if len( a ) > 1: return reduce( lcm2, a )
if hasattr( a[0], "__iter__" ): return reduce( lcm2, a[0] )
return a[0] |
Decompose n into a list of (prime,exponent) pairs.
def factorization( n ):
"""Decompose n into a list of (prime,exponent) pairs."""
assert isinstance( n, integer_types )
if n < 2: return []
result = []
d = 2
# Test the small primes:
for d in smallprimes:
if d > n: break
q, r = divmod( n, d )... |
Return the Euler totient function of n.
def phi( n ):
"""Return the Euler totient function of n."""
assert isinstance( n, integer_types )
if n < 3: return 1
result = 1
ff = factorization( n )
for f in ff:
e = f[1]
if e > 1:
result = result * f[0] ** (e-1) * ( f[0] - 1 )
else:
res... |
Return the Carmichael function of a number that is
represented as a list of (prime,exponent) pairs.
def carmichael_of_factorized( f_list ):
"""Return the Carmichael function of a number that is
represented as a list of (prime,exponent) pairs.
"""
if len( f_list ) < 1: return 1
result = carmichael_of_ppow... |
Carmichael function of the given power of the given prime.
def carmichael_of_ppower( pp ):
"""Carmichael function of the given power of the given prime.
"""
p, a = pp
if p == 2 and a > 2: return 2**(a-2)
else: return (p-1) * p**(a-1) |
Return the order of x in the multiplicative group mod m.
def order_mod( x, m ):
"""Return the order of x in the multiplicative group mod m.
"""
# Warning: this implementation is not very clever, and will
# take a long time if m is very large.
if m <= 1: return 0
assert gcd( x, m ) == 1
z = x
result... |
Return the largest factor of a relatively prime to b.
def largest_factor_relatively_prime( a, b ):
"""Return the largest factor of a relatively prime to b.
"""
while 1:
d = gcd( a, b )
if d <= 1: break
b = d
while 1:
q, r = divmod( a, d )
if r > 0:
break
a = q
return ... |
Return True if x is prime, False otherwise.
We use the Miller-Rabin test, as given in Menezes et al. p. 138.
This test is not exact: there are composite values n for which
it returns True.
In testing the odd numbers from 10000001 to 19999999,
about 66 composites got past the first test,
5 got past the sec... |
Return the smallest prime larger than the starting value.
def next_prime( starting_value ):
"Return the smallest prime larger than the starting value."
if starting_value < 2: return 2
result = ( starting_value + 1 ) | 1
while not is_prime( result ): result = result + 2
return result |
Uses feeder to read and convert from in_stream and write to out_stream.
def _feed_stream(feeder, in_stream, out_stream, block_size = BLOCK_SIZE):
'Uses feeder to read and convert from in_stream and write to out_stream.'
while True:
chunk = in_stream.read(block_size)
if not chunk:
b... |
Encrypts a stream of bytes from in_stream to out_stream using mode.
def encrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT):
'Encrypts a stream of bytes from in_stream to out_stream using mode.'
encrypter = Encrypter(mode, padding = padding)
_feed_stream(encrypt... |
Decrypts a stream of bytes from in_stream to out_stream using mode.
def decrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT):
'Decrypts a stream of bytes from in_stream to out_stream using mode.'
decrypter = Decrypter(mode, padding = padding)
_feed_stream(decrypt... |
Provide bytes to encrypt (or decrypt), returning any bytes
possible from this or any previous calls to feed.
Call with None or an empty string to flush the mode of
operation and return any final bytes; no further calls to
feed may be made.
def feed(self, data = None):
... |
Return a random integer k such that 1 <= k < order, uniformly
distributed across that range. For simplicity, this only behaves well if
'order' is fairly close (but below) a power of 256. The try-try-again
algorithm we use takes longer and longer time (on average) to complete as
'order' falls, rising to ... |
Create AUTHORS file using git commits.
def generate_authors(git_dir):
"""Create AUTHORS file using git commits."""
authors = []
emails = []
git_log_cmd = ['git', 'log', '--format=%aN|%aE']
tmp_authors = _run_shell_command(git_log_cmd, git_dir).split('\n')
for author_str in tmp_authors:
... |
Initalizes root node of the tree, i.e depth = 0
def _initalize_tree(self, position, momentum, slice_var, stepsize):
"""
Initalizes root node of the tree, i.e depth = 0
"""
position_bar, momentum_bar, _ = self.simulate_dynamics(self.model, position, momentum, stepsize,
... |
Recursively builds a tree for proposing new position and momentum
def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize):
"""
Recursively builds a tree for proposing new position and momentum
"""
# Parameter names in algorithm (here -> representation in algori... |
Returns a sample using a single iteration of NUTS
def _sample(self, position, stepsize):
"""
Returns a sample using a single iteration of NUTS
"""
# Re-sampling momentum
momentum = np.random.normal(0, 1, len(position))
# Initializations
depth = 0
positi... |
Method to return samples using No U Turn Sampler
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
state in markov chain.
num_samples: int
Number of samples to be generated
... |
Returns a generator type object whose each iteration yields a sample
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
state in markov chain.
num_samples: int
Number of samples to... |
Recursively builds a tree for proposing new position and momentum
def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize, position0, momentum0):
"""
Recursively builds a tree for proposing new position and momentum
"""
if depth == 0:
position_bar, m... |
Returns samples using No U Turn Sampler with dual averaging
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
state in markov chain.
num_adapt: int
The number of interations to ru... |
Returns a generator type object whose each iteration yields a sample
Parameters
----------
initial_pos: A 1d array like object
Vector representing values of parameter position, the starting
state in markov chain.
num_adapt: int
The number of interati... |
Discretizes the continuous distribution into discrete
probability masses using various methods.
Parameters
----------
method : A Discretizer Class from pgmpy.discretize
*args, **kwargs:
The parameters to be given to the Discretizer Class.
Returns
--... |
Reduces the factor to the context of the given variable values.
Parameters
----------
values: list, array-like
A list of tuples of the form (variable_name, variable_value).
inplace: boolean
If inplace=True it will modify the factor itself, else would return
... |
Marginalize the factor with respect to the given variables.
Parameters
----------
variables: list, array-like
List of variables with respect to which factor is to be maximized.
inplace: boolean
If inplace=True it will modify the factor itself, else would return
... |
Normalizes the pdf of the continuous factor so that it integrates to
1 over all the variables.
Parameters
----------
inplace: boolean
If inplace=True it will modify the factor itself, else would return
a new factor.
Returns
-------
Contin... |
Gives the ContinuousFactor operation (product or divide) with
the other factor.
Parameters
----------
other: ContinuousFactor
The ContinuousFactor to be multiplied.
operation: String
'product' for multiplication operation and 'divide' for
div... |
Gives the ContinuousFactor divide with the other factor.
Parameters
----------
other: ContinuousFactor
The ContinuousFactor to be divided.
Returns
-------
ContinuousFactor or None:
if inplace=True (default) returns None
... |
Returns factor product over `args`.
Parameters
----------
args: `BaseFactor` instances.
factors to be multiplied
Returns
-------
BaseFactor: `BaseFactor` representing factor product over all the `BaseFactor` instances in args.
Examples
--------
>>> from pgmpy.factors.discr... |
Returns `DiscreteFactor` representing `phi1 / phi2`.
Parameters
----------
phi1: Factor
The Dividend.
phi2: Factor
The Divisor.
Returns
-------
DiscreteFactor: `DiscreteFactor` representing factor division `phi1 / phi2`.
Examples
--------
>>> from pgmpy.factor... |
Method to estimate the model parameters (CPDs).
Parameters
----------
prior_type: 'dirichlet', 'BDeu', or 'K2'
string indicting which type of prior to use for the model parameters.
- If 'prior_type' is 'dirichlet', the following must be provided:
'pseudo_... |
Method to estimate the CPD for a given variable.
Parameters
----------
node: int, string (any hashable python object)
The name of the variable for which the CPD is to be estimated.
prior_type: 'dirichlet', 'BDeu', 'K2',
string indicting which type of prior to us... |
Generates sample(s) from joint distribution of the bayesian network.
Parameters
----------
size: int
size of sample to be generated
return_type: string (dataframe | recarray)
Return type for samples, either of 'dataframe' or 'recarray'.
Defaults to '... |
Generates sample(s) from joint distribution of the bayesian network,
given the evidence.
Parameters
----------
evidence: list of `pgmpy.factor.State` namedtuples
None if no evidence
size: int
size of sample to be generated
return_type: string (dat... |
Generates weighted sample(s) from joint distribution of the bayesian
network, that comply with the given evidence.
'Probabilistic Graphical Model Principles and Techniques', Koller and
Friedman, Algorithm 12.2 pp 493.
Parameters
----------
evidence: list of `pgmpy.factor... |
Computes the Gibbs transition models from a Bayesian Network.
'Probabilistic Graphical Model Principles and Techniques', Koller and
Friedman, Section 12.3.3 pp 512-513.
Parameters:
-----------
model: BayesianModel
The model from which probabilities will be computed.
... |
Computes the Gibbs transition models from a Markov Network.
'Probabilistic Graphical Model Principles and Techniques', Koller and
Friedman, Section 12.3.3 pp 512-513.
Parameters:
-----------
model: MarkovModel
The model from which probabilities will be computed.
def... |
Sample from the Markov Chain.
Parameters:
-----------
start_state: dict or array-like iterable
Representing the starting states of the variables. If None is passed, a random start_state is chosen.
size: int
Number of samples to be generated.
return_type: ... |
Generator version of self.sample
Return Type:
------------
List of State namedtuples, representing the assignment to all variables of the model.
Examples:
---------
>>> from pgmpy.factors.discrete import DiscreteFactor
>>> from pgmpy.sampling import GibbsSamplin... |
Return a list of states that the variable takes in the data
def _collect_state_names(self, variable):
"Return a list of states that the variable takes in the data"
states = sorted(list(self.data.ix[:, variable].dropna().unique()))
return states |
Return counts how often each state of 'variable' occured in the data.
If a list of parents is provided, counting is done conditionally
for each state configuration of the parents.
Parameters
----------
variable: string
Name of the variable for which the state count i... |
Return counts how often each state of 'variable' occured in the data.
If the variable has parents, counting is done conditionally
for each state configuration of the parents.
Parameters
----------
variable: string
Name of the variable for which the state count is to ... |
Add a single node to the cluster graph.
Parameters
----------
node: node
A node should be a collection of nodes forming a clique. It can be
a list, set or tuple of nodes
Examples
--------
>>> from pgmpy.models import ClusterGraph
>>> G = ... |
Add multiple nodes to the cluster graph.
Parameters
----------
nodes: iterable container
A container of nodes (list, dict, set, etc.).
Examples
--------
>>> from pgmpy.models import ClusterGraph
>>> G = ClusterGraph()
>>> G.add_nodes_from([('... |
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 ClusterGraph
>>> G = ClusterGraph()
>>> G.add_nodes_from([... |
Associate a factor to the graph.
See factors class for the order of potential values
Parameters
----------
*factor: pgmpy.factors.factors object
A factor object on any subset of the variables of the model which
is to be associated with the model.
Returns... |
Return 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 ClusterGraph
>>> from pgmpy.factors.discrete import DiscreteFactor
>>> ... |
Returns the cardinality of the node
Parameters
----------
node: any hashable python object (optional)
The node whose cardinality we want. If node is not specified returns a
dictionary with the given variable as keys and their respective cardinality
as values.... |
r"""
Returns the partition function for a given undirected graph.
A partition function is defined as
.. math:: \sum_{X}(\prod_{i=1}^{m} \phi_i)
where m is the number of factors present in the graph
and X are all the random variables present.
Examples
--------
... |
Check the model for various errors. This method checks for the following
errors.
* Checks if factors are defined for all the cliques or not.
* Check for running intersection property is not done explicitly over
here as it done in the add_edges method.
* Checks if cardinality i... |
Returns a copy of ClusterGraph.
Returns
-------
ClusterGraph: copy of ClusterGraph
Examples
-------
>>> from pgmpy.factors.discrete import DiscreteFactor
>>> G = ClusterGraph()
>>> G.add_nodes_from([('a', 'b'), ('b', 'c')])
>>> G.add_edge(('a', '... |
This is the message-update method.
Parameters
----------
sending_cluster: The resulting messages are lambda_{c-->s} from the given
cluster 'c' to all of its intersection_sets 's'.
Here 's' are the elements of intersection_sets_for_cluster_c.
Reference
--... |
Finds the index of the maximum values for all the single node dual objectives.
Reference:
code presented by Sontag in 2012 here: http://cs.nyu.edu/~dsontag/code/README_v2.html
def _local_decode(self):
"""
Finds the index of the maximum values for all the single node dual objectives.
... |
This method checks the integrality gap to ensure either:
* we have found a near to exact solution or
* stuck on a local minima.
Parameters
----------
dual_threshold: double
This sets the minimum width between the dual objective decrements. If the ... |
Finds all the triangles present in the given model
Examples
--------
>>> from pgmpy.models import MarkovModel
>>> from pgmpy.factors.discrete import DiscreteFactor
>>> from pgmpy.inference import Mplp
>>> mm = MarkovModel()
>>> mm.add_nodes_from(['x1', 'x2', 'x3'... |
From a set of variables forming a triangle in the model, we form the corresponding Clusters.
These clusters are then appended to the code.
Parameters
----------
triangle_list : list
The list of variables forming the triangles to be updated. It is of the form of
... |
Returns the score of each of the triplets found in the current model
Parameters
---------
triangles_list: list
The list of variables forming the triangles to be updated. It is of the form of
[['var_5', 'var_8', 'var_7'], ['var_4', 'var_5', 'var_7'... |
Updates messages until either Mplp converges or if doesn't converges; halts after no_iterations.
Parameters
--------
no_iterations: integer
Number of maximum iterations that we want MPLP to run.
def _run_mplp(self, no_iterations):
"""
Updates messages u... |
This method finds all the triplets that are eligible and adds them iteratively in the bunch of max_triplets
Parameters
----------
max_iterations: integer
Maximum number of times we tighten the relaxation
later_iter: integer
Number of maximum ... |
MAP query method using Max Product LP method.
This returns the best assignment of the nodes in the form of a dictionary.
Parameters
----------
init_iter: integer
Number of maximum iterations that we want MPLP to run for the first time.
later_iter: integer
... |
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.
Examples
--------
>>> from pgmpy.models import MarkovM... |
Associate a factor to the graph.
See factors class for the order of potential values
Parameters
----------
*factor: pgmpy.factors.factors object
A factor object on any subset of the variables of the model which
is to be associated with the model.
Returns... |
Returns all the factors containing the node. If node is not specified
returns all the factors that have been added till now to the graph.
Parameter
---------
node: any hashable python object (optional)
The node whose factor we want. If node is not specified
Examples... |
Check the model for various errors. This method checks for the following
errors -
* Checks if the cardinalities of all the variables are consistent across all the factors.
* Factors are defined for all the random variables.
Returns
-------
check: boolean
Tru... |
Converts the markov model into factor graph.
A factor graph contains two types of nodes. One type corresponds to
random variables whereas the second type corresponds to factors over
these variables. The graph only contains edges between variables and
factor nodes. Each factor node is as... |
Triangulate the graph.
If order of deletion is given heuristic algorithm will not be used.
Parameters
----------
heuristic: H1 | H2 | H3 | H4 | H5 | H6
The heuristic algorithm to use to decide the deletion order of
the variables to compute the triangulated graph... |
Creates a junction tree (or clique tree) for a given markov model.
For a given markov model (H) a junction tree (G) is a graph
1. where each node in G corresponds to a maximal clique in H
2. each sepset in G separates the variables strictly on one side of the
edge to other.
Exa... |
Returns all the local independencies present in the markov model.
Local independencies are the independence assertion in the form of
.. math:: {X \perp W - {X} - MB(X) | MB(X)}
where MB is the markov blanket of all the random variables in X
Parameters
----------
latex: ... |
Creates a Bayesian Model which is a minimum I-Map for this markov model.
The ordering of parents may not remain constant. It would depend on the
ordering of variable in the junction tree (which is not constant) all the
time.
Examples
--------
>>> from pgmpy.models impor... |
Returns the partition function for a given undirected graph.
A partition function is defined as
.. math:: \sum_{X}(\prod_{i=1}^{m} \phi_i)
where m is the number of factors present in the graph
and X are all the random variables present.
Examples
--------
>>> f... |
Returns a copy of this Markov Model.
Returns
-------
MarkovModel: Copy of this Markov model.
Examples
-------
>>> from pgmpy.factors.discrete import DiscreteFactor
>>> from pgmpy.models import MarkovModel
>>> G = MarkovModel()
>>> G.add_nodes_fro... |
Returns the probability density function(pdf).
Returns
-------
function: The probability density function of the distribution.
Examples
--------
>>> from pgmpy.factors.distributions import GaussianDistribution
>>> dist = GD(variables=['x1', 'x2', 'x3'],
... |
Returns the precision matrix of the distribution.
Precision is defined as the inverse of the variance. This method returns
the inverse matrix of the covariance.
Examples
--------
>>> import numpy as np
>>> from pgmpy.factors.distributions import GaussianDistribution as ... |
Modifies the distribution with marginalized values.
Parameters
----------
variables: iterator over any hashable object.
List of variables over which marginalization is to be done.
inplace: boolean
If inplace=True it will modify the distribution itself,
... |
Reduces the distribution to the context of the given variable values.
The formula for the obtained conditional distribution is given by -
For,
.. math:: N(X_j | X_i = x_i) ~ N(mu_{j.i} ; sig_{j.i})
where,
.. math:: mu_{j.i} = mu_j + sig_{j, i} * {sig_{i, i}^{-1}} * (x_i - mu_i... |
Normalizes the distribution. In case of a Gaussian Distribution the
distribution is always normalized, therefore this method doesn't do
anything and has been implemented only for a consistent API across
distributions.
def normalize(self, inplace=True):
"""
Normalizes the distrib... |
Return a copy of the distribution.
Returns
-------
GaussianDistribution: copy of the distribution
Examples
--------
>>> import numpy as np
>>> from pgmpy.factors.distributions import GaussianDistribution as GD
>>> gauss_dis = GD(variables=['x1', 'x2', 'x... |
u"""
Returns an equivalent CanonicalDistribution object.
The formulas for calculating the cannonical factor parameters
for N(μ; Σ) = C(K; h; g) are as follows -
K = sigma^(-1)
h = sigma^(-1) * mu
g = -(0.5) * mu.T * sigma^(-1) * mu -
log((2*pi)^(n/2) * det(s... |
Gives the CanonicalDistribution operation (product or divide) with
the other factor.
Parameters
----------
other: CanonicalDistribution
The CanonicalDistribution to be multiplied.
operation: String
'product' for multiplication operation and
'... |
TODO: Make it work when using `*` instead of product.
Returns the product of two gaussian distributions.
Parameters
----------
other: GaussianDistribution
The GaussianDistribution to be multiplied.
inplace: boolean
If True, modifies the distribution its... |
Returns the division of two gaussian distributions.
Parameters
----------
other: GaussianDistribution
The GaussianDistribution to be divided.
inplace: boolean
If True, modifies the distribution itself, otherwise returns a new
GaussianDistribution obj... |
Discretizes the continuous distribution into discrete
probability masses using specified method.
Parameters
----------
method: string, BaseDiscretizer instance
A Discretizer Class from pgmpy.factors.discretize
*args, **kwargs: values
The parameters to be... |
Reduces the factor to the context of the given variable values.
Parameters
----------
values: list, array-like
A list of tuples of the form (variable_name, variable_value).
inplace: boolean
If inplace=True it will modify the factor itself, else would return
... |
Marginalize the distribution with respect to the given variables.
Parameters
----------
variables: list, array-like
List of variables to be removed from the marginalized distribution.
inplace: boolean
If inplace=True it will modify the factor itself, else would ... |
Normalizes the pdf of the distribution so that it
integrates to 1 over all the variables.
Parameters
----------
inplace: boolean
If inplace=True it will modify the distribution itself, else would return
a new distribution.
Returns
-------
... |
Gives the CustomDistribution operation (product or divide) with
the other distribution.
Parameters
----------
other: CustomDistribution
The CustomDistribution to be multiplied.
operation: str
'product' for multiplication operation and 'divide' for
... |
Implementation of a generalized variable elimination.
Parameters
----------
variables: list, array-like
variables that are not to be eliminated.
operation: str ('marginalize' | 'maximize')
The operation to do for eliminating the variable.
evidence: dict
... |
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var: state_of_var_observed}
None if no evidence
elimination_order: list
order of variable elim... |
Computes the max-marginal over the variables given the evidence.
Parameters
----------
variables: list
list of variables over which we want to compute the max-marginal.
evidence: dict
a dict key, value pair as {var: state_of_var_observed}
None if no e... |
Computes the MAP Query over the variables given the evidence.
Note: When multiple variables are passed, it returns the map_query for each
of them individually.
Parameters
----------
variables: list
list of variables over which we want to compute the max-marginal.
... |
Returns the induced graph formed by running Variable Elimination on the network.
Parameters
----------
elimination_order: list, array like
List of variables in the order in which they are to be eliminated.
Examples
--------
>>> import numpy as np
>>>... |
Returns the width (integer) of the induced graph formed by running Variable Elimination on the network.
The width is the defined as the number of nodes in the largest clique in the graph minus 1.
Parameters
----------
elimination_order: list, array like
List of variables in ... |
This is belief-update method.
Parameters
----------
sending_clique: node (as the operation is on junction tree, node should be a tuple)
Node sending the message
recieving_clique: node (as the operation is on junction tree, node should be a tuple)
Node recieving t... |
Checks whether the calibration has converged or not. At convergence
the sepset belief would be precisely the sepset marginal.
Parameters
----------
operation: str ('marginalize' | 'maximize')
The operation to do for passing messages between nodes.
if operation ==... |
Generalized calibration of junction tree or clique using belief propagation. This method can be used for both
calibrating as well as max-calibrating.
Uses Lauritzen-Spiegelhalter algorithm or belief-update message passing.
Parameters
----------
operation: str ('marginalize' | 'm... |
This is a generalized query method that can be used for both query and map query.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
operation: str ('marginalize' | 'maximize')
The operation to do for passing mes... |
Query method using belief propagation.
Parameters
----------
variables: list
list of variables for which you want to compute the probability
evidence: dict
a dict key, value pair as {var: state_of_var_observed}
None if no evidence
joint: boo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.