INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Join this array with another array. | def concatenate(self, arry, axis=0):
"""
Join this array with another array.
Paramters
---------
arry : ndarray or BoltArrayLocal
Another array to concatenate with
axis : int, optional, default=0
The axis along which arrays will be joined.
... |
Converts a BoltArrayLocal into a BoltArraySpark | def tospark(self, sc, axis=0):
"""
Converts a BoltArrayLocal into a BoltArraySpark
Parameters
----------
sc : SparkContext
The SparkContext which will be used to create the BoltArraySpark
axis : tuple or int, optional, default=0
The axis (or axes... |
Converts a BoltArrayLocal into an RDD | def tordd(self, sc, axis=0):
"""
Converts a BoltArrayLocal into an RDD
Parameters
----------
sc : SparkContext
The SparkContext which will be used to create the BoltArraySpark
axis : tuple or int, optional, default=0
The axis (or axes) across whi... |
Make an intermediate RDD where all records are combined into a list of keys and larger ndarray along a new 0th dimension. | def stack(self, size):
"""
Make an intermediate RDD where all records are combined into a
list of keys and larger ndarray along a new 0th dimension.
"""
def tostacks(partition):
keys = []
arrs = []
for key, arr in partition:
key... |
Unstack array and return a new BoltArraySpark via flatMap (). | def unstack(self):
"""
Unstack array and return a new BoltArraySpark via flatMap().
"""
from bolt.spark.array import BoltArraySpark
if self._rekeyed:
rdd = self._rdd
else:
rdd = self._rdd.flatMap(lambda kv: zip(kv[0], list(kv[1])))
return... |
Apply a function on each subarray. | def map(self, func):
"""
Apply a function on each subarray.
Parameters
----------
func : function
This is applied to each value in the intermediate RDD.
Returns
-------
StackedArray
"""
vshape = self.shape[self.split:]
... |
Split values of distributed array into chunks. | def _chunk(self, size="150", axis=None, padding=None):
"""
Split values of distributed array into chunks.
Transforms an underlying pair RDD of (key, value) into
records of the form: (key, chunk id), (chunked value).
Here, chunk id is a tuple identifying the chunk and
chu... |
Convert a chunked array back into a full array with ( key value ) pairs where key is a tuple of indices and value is an ndarray. | def unchunk(self):
"""
Convert a chunked array back into a full array with (key,value) pairs
where key is a tuple of indices, and value is an ndarray.
"""
plan, padding, vshape, split = self.plan, self.padding, self.vshape, self.split
nchunks = self.getnumber(plan, vshape... |
Move indices in the keys into the values. | def keys_to_values(self, axes, size=None):
"""
Move indices in the keys into the values.
Padding on these new value-dimensions is not currently supported and is set to 0.
Parameters
----------
axes : tuple
Axes from keys to move to values.
size : tu... |
Apply an array - > array function on each subarray. | def map(self, func, value_shape=None, dtype=None):
"""
Apply an array -> array function on each subarray.
The function can change the shape of the subarray, but only along
dimensions that are not chunked.
Parameters
----------
func : function
Functio... |
Apply a generic array - > object to each subarray | def map_generic(self, func):
"""
Apply a generic array -> object to each subarray
The resulting object is a BoltArraySpark of dtype object where the
blocked dimensions are replaced with indices indication block ID.
"""
def process_record(val):
newval = empty(... |
Identify a plan for chunking values along each dimension. | def getplan(self, size="150", axes=None, padding=None):
"""
Identify a plan for chunking values along each dimension.
Generates an ndarray with the size (in number of elements) of chunks
in each dimension. If provided, will estimate chunks for only a
subset of axes, leaving all ... |
Remove the padding from chunks. | def removepad(idx, value, number, padding, axes=None):
"""
Remove the padding from chunks.
Given a chunk and its corresponding index, use the plan and padding to remove any
padding from the chunk along with specified axes.
Parameters
----------
idx: tuple or arr... |
Obtain number of chunks for the given dimensions and chunk sizes. | def getnumber(plan, shape):
"""
Obtain number of chunks for the given dimensions and chunk sizes.
Given a plan for the number of chunks along each dimension,
calculate the number of chunks that this will lead to.
Parameters
----------
plan: tuple or array-like
... |
Obtain slices for the given dimensions padding and chunks. | def getslices(plan, padding, shape):
"""
Obtain slices for the given dimensions, padding, and chunks.
Given a plan for the number of chunks along each dimension and the amount of padding,
calculate a list of slices required to generate those chunks.
Parameters
---------... |
Obtain a binary mask by setting a subset of entries to true. | def getmask(inds, n):
"""
Obtain a binary mask by setting a subset of entries to true.
Parameters
----------
inds : array-like
Which indices to set as true.
n : int
The length of the target mask.
"""
inds = asarray(inds, 'int')
... |
Repartitions the underlying RDD | def repartition(self, npartitions):
"""
Repartitions the underlying RDD
Parameters
----------
npartitions : int
Number of partitions to repartion the underlying RDD to
"""
rdd = self._rdd.repartition(npartitions)
return self._constructor(rdd,... |
Aggregates records of a distributed array. | def stack(self, size=None):
"""
Aggregates records of a distributed array.
Stacking should improve the performance of vectorized operations,
but the resulting StackedArray object only exposes a restricted set
of operations (e.g. map, reduce). The unstack method can be used
... |
Align spark bolt array so that axes for iteration are in the keys. | def _align(self, axis):
"""
Align spark bolt array so that axes for iteration are in the keys.
This operation is applied before most functional operators.
It ensures that the specified axes are valid, and swaps
key/value axes so that functional operators can be applied
o... |
Return the first element of an array | def first(self):
"""
Return the first element of an array
"""
from bolt.local.array import BoltArrayLocal
rdd = self._rdd if self._ordered else self._rdd.sortByKey()
return BoltArrayLocal(rdd.values().first()) |
Apply a function across an axis. | def map(self, func, axis=(0,), value_shape=None, dtype=None, with_keys=False):
"""
Apply a function across an axis.
Array will be aligned so that the desired set of axes
are in the keys, which may incur a swap.
Parameters
----------
func : function
F... |
Filter array along an axis. | def filter(self, func, axis=(0,), sort=False):
"""
Filter array along an axis.
Applies a function which should evaluate to boolean,
along a single axis or multiple axes. Array will be
aligned so that the desired set of axes are in the keys,
which may incur a swap.
... |
Reduce an array along an axis. | def reduce(self, func, axis=(0,), keepdims=False):
"""
Reduce an array along an axis.
Applies a commutative/associative function of two
arguments cumulatively to all arrays along an axis.
Array will be aligned so that the desired set of axes
are in the keys, which may in... |
Compute a statistic over an axis. | def _stat(self, axis=None, func=None, name=None, keepdims=False):
"""
Compute a statistic over an axis.
Can provide either a function (for use in a reduce)
or a name (for use by a stat counter).
Parameters
----------
axis : tuple or int, optional, default=None
... |
Return the mean of the array over the given axis. | def mean(self, axis=None, keepdims=False):
"""
Return the mean of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
keepdims : boole... |
Return the variance of the array over the given axis. | def var(self, axis=None, keepdims=False):
"""
Return the variance of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
keepdims : bo... |
Return the standard deviation of the array over the given axis. | def std(self, axis=None, keepdims=False):
"""
Return the standard deviation of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
kee... |
Return the sum of the array over the given axis. | def sum(self, axis=None, keepdims=False):
"""
Return the sum of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
keepdims : boolean... |
Return the maximum of the array over the given axis. | def max(self, axis=None, keepdims=False):
"""
Return the maximum of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
keepdims : boo... |
Return the minimum of the array over the given axis. | def min(self, axis=None, keepdims=False):
"""
Return the minimum of the array over the given axis.
Parameters
----------
axis : tuple or int, optional, default=None
Axis to compute statistic over, if None
will compute over all axes
keepdims : boo... |
Join this array with another array. | def concatenate(self, arry, axis=0):
"""
Join this array with another array.
Paramters
---------
arry : ndarray, BoltArrayLocal, or BoltArraySpark
Another array to concatenate with
axis : int, optional, default=0
The axis along which arrays will ... |
Basic indexing ( for slices or ints ). | def _getbasic(self, index):
"""
Basic indexing (for slices or ints).
"""
key_slices = index[0:self.split]
value_slices = index[self.split:]
def key_check(key):
def inrange(k, s):
if s.step > 0:
return s.start <= k < s.stop
... |
Advanced indexing ( for sets lists or ndarrays ). | def _getadvanced(self, index):
"""
Advanced indexing (for sets, lists, or ndarrays).
"""
index = [asarray(i) for i in index]
shape = index[0].shape
if not all([i.shape == shape for i in index]):
raise ValueError("shape mismatch: indexing arrays could not be br... |
Mixed indexing ( combines basic and advanced indexes ) | def _getmixed(self, index):
"""
Mixed indexing (combines basic and advanced indexes)
Assumes that only a single advanced index is used, due to the complicated
behavior needed to be compatible with NumPy otherwise.
"""
# find the single advanced index
loc = where(... |
Chunks records of a distributed array. | def chunk(self, size="150", axis=None, padding=None):
"""
Chunks records of a distributed array.
Chunking breaks arrays into subarrays, using an specified
size of chunks along each value dimension. Can alternatively
specify an average chunk byte size (in kilobytes) and the size ... |
Swap axes from keys to values. | def swap(self, kaxes, vaxes, size="150"):
"""
Swap axes from keys to values.
This is the core operation underlying shape manipulation
on the Spark bolt array. It exchanges an arbitrary set of axes
between the keys and the valeus. If either is None, will only
move axes in... |
Return an array with the axes transposed. | def transpose(self, *axes):
"""
Return an array with the axes transposed.
This operation will incur a swap unless the
desiured permutation can be obtained
only by transpoing the keys or the values.
Parameters
----------
axes : None, tuple of ints, or n i... |
Return the array with two axes interchanged. | def swapaxes(self, axis1, axis2):
"""
Return the array with two axes interchanged.
Parameters
----------
axis1 : int
The first axis to swap
axis2 : int
The second axis to swap
"""
p = list(range(self.ndim))
p[axis1] = axis... |
Return an array with the same data but a new shape. | def reshape(self, *shape):
"""
Return an array with the same data but a new shape.
Currently only supports reshaping that independently
reshapes the keys, or the values, or both.
Parameters
----------
shape : tuple of ints, or n ints
New shape
... |
Check if the requested reshape can be broken into independant reshapes on the keys and values. If it can returns the index in the new shape separating keys from values otherwise returns - 1 | def _reshapebasic(self, shape):
"""
Check if the requested reshape can be broken into independant reshapes
on the keys and values. If it can, returns the index in the new shape
separating keys from values, otherwise returns -1
"""
new = tupleize(shape)
old_key_siz... |
Remove one or more single - dimensional axes from the array. | def squeeze(self, axis=None):
"""
Remove one or more single-dimensional axes from the array.
Parameters
----------
axis : tuple or int
One or more singleton axes to remove.
"""
if not any([d == 1 for d in self.shape]):
return self
... |
Cast the array to a specified type. | def astype(self, dtype, casting='unsafe'):
"""
Cast the array to a specified type.
Parameters
----------
dtype : str or dtype
Typecode or data-type to cast the array to (see numpy)
"""
rdd = self._rdd.mapValues(lambda v: v.astype(dtype, 'K', casting))... |
Clip values above and below. | def clip(self, min=None, max=None):
"""
Clip values above and below.
Parameters
----------
min : scalar or array-like
Minimum value. If array, will be broadcasted
max : scalar or array-like
Maximum value. If array, will be broadcasted.
""... |
Returns the contents as a local array. | def toarray(self):
"""
Returns the contents as a local array.
Will likely cause memory problems for large objects.
"""
rdd = self._rdd if self._ordered else self._rdd.sortByKey()
x = rdd.values().collect()
return asarray(x).reshape(self.shape) |
Coerce singletons and lists and ndarrays to tuples. | def tupleize(arg):
"""
Coerce singletons and lists and ndarrays to tuples.
Parameters
----------
arg : tuple, list, ndarray, or singleton
Item to coerce
"""
if arg is None:
return None
if not isinstance(arg, (tuple, list, ndarray, Iterable)):
return tuple((arg,))... |
Coerce a list of arguments to a tuple. | def argpack(args):
"""
Coerce a list of arguments to a tuple.
Parameters
----------
args : tuple or nested tuple
Pack arguments into a tuple, converting ((,...),) or (,) -> (,)
"""
if isinstance(args[0], (tuple, list, ndarray)):
return tupleize(args[0])
elif isinstance(a... |
Checks to see if a list of axes are contained within an array shape. | def inshape(shape, axes):
"""
Checks to see if a list of axes are contained within an array shape.
Parameters
----------
shape : tuple[int]
the shape of a BoltArray
axes : tuple[int]
the axes to check against shape
"""
valid = all([(axis < len(shape)) and (axis >= 0) fo... |
Test that a and b are close and match in shape. | def allclose(a, b):
"""
Test that a and b are close and match in shape.
Parameters
----------
a : ndarray
First array to check
b : ndarray
First array to check
"""
from numpy import allclose
return (a.shape == b.shape) and allclose(a, b) |
Flatten lists of indices and ensure bounded by a known dim. | def listify(lst, dim):
"""
Flatten lists of indices and ensure bounded by a known dim.
Parameters
----------
lst : list
List of integer indices
dim : tuple
Bounds for indices
"""
if not all([l.dtype == int for l in lst]):
raise ValueError("indices must be intege... |
Force a slice to have defined start stop and step from a known dim. Start and stop will always be positive. Step may be negative. | def slicify(slc, dim):
"""
Force a slice to have defined start, stop, and step from a known dim.
Start and stop will always be positive. Step may be negative.
There is an exception where a negative step overflows the stop needs to have
the default value set to -1. This is the only case of a negativ... |
Check to see if a proposed tuple of axes is a valid permutation of an old set of axes. Checks length axis repetion and bounds. | def istransposeable(new, old):
"""
Check to see if a proposed tuple of axes is a valid permutation
of an old set of axes. Checks length, axis repetion, and bounds.
Parameters
----------
new : tuple
tuple of proposed axes
old : tuple
tuple of old axes
"""
new, old =... |
Check to see if a proposed tuple of axes is a valid reshaping of the old axes by ensuring that they can be factored. | def isreshapeable(new, old):
"""
Check to see if a proposed tuple of axes is a valid reshaping of
the old axes by ensuring that they can be factored.
Parameters
----------
new : tuple
tuple of proposed axes
old : tuple
tuple of old axes
"""
new, old = tupleize(new)... |
If an ndarray has been split into multiple chunks by splitting it along each axis at a number of locations this function rebuilds the original array from chunks. | def allstack(vals, depth=0):
"""
If an ndarray has been split into multiple chunks by splitting it along
each axis at a number of locations, this function rebuilds the
original array from chunks.
Parameters
----------
vals : nested lists of ndarrays
each level of nesting of the list... |
Expand dimensions by iteratively append empty axes. | def iterexpand(arry, extra):
"""
Expand dimensions by iteratively append empty axes.
Parameters
----------
arry : ndarray
The original array
extra : int
The number of empty axes to append
"""
for d in range(arry.ndim, arry.ndim+extra):
arry = expand_dims(arry, a... |
Alternate version of Spark s zipWithIndex that eagerly returns count. | def zip_with_index(rdd):
"""
Alternate version of Spark's zipWithIndex that eagerly returns count.
"""
starts = [0]
if rdd.getNumPartitions() > 1:
nums = rdd.mapPartitions(lambda it: [sum(1 for _ in it)]).collect()
count = sum(nums)
for i in range(len(nums) - 1):
... |
Decorator to append routed docstrings | def wrapped(f):
"""
Decorator to append routed docstrings
"""
import inspect
def extract(func):
append = ""
args = inspect.getargspec(func)
for i, a in enumerate(args.args):
if i < (len(args) - len(args.defaults)):
append += str(a) + ", "
... |
Use arguments to route constructor. | def lookup(*args, **kwargs):
"""
Use arguments to route constructor.
Applies a series of checks on arguments to identify constructor,
starting with known keyword arguments, and then applying
constructor-specific checks
"""
if 'mode' in kwargs:
mode = kwargs['mode']
if mode n... |
Reshape just the keys of a BoltArraySpark returning a new BoltArraySpark. | def reshape(self, *shape):
"""
Reshape just the keys of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
shape : tuple
New proposed axes.
"""
new = argpack(shape)
old = self.shape
isreshapeable(new, old... |
Transpose just the keys of a BoltArraySpark returning a new BoltArraySpark. | def transpose(self, *axes):
"""
Transpose just the keys of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
axes : tuple
New proposed axes.
"""
new = argpack(axes)
old = range(self.ndim)
istransposeable(... |
Reshape just the values of a BoltArraySpark returning a new BoltArraySpark. | def reshape(self, *shape):
"""
Reshape just the values of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
shape : tuple
New proposed axes.
"""
new = argpack(shape)
old = self.shape
isreshapeable(new, o... |
Transpose just the values of a BoltArraySpark returning a new BoltArraySpark. | def transpose(self, *axes):
"""
Transpose just the values of a BoltArraySpark, returning a
new BoltArraySpark.
Parameters
----------
axes : tuple
New proposed axes.
"""
new = argpack(axes)
old = range(self.ndim)
istransposeabl... |
Create a local bolt array of ones. | def ones(shape, dtype=float64, order='C'):
"""
Create a local bolt array of ones.
Parameters
----------
shape : tuple
Dimensions of the desired array
dtype : data-type, optional, default=float64
The desired data-type for the array. (see numpy)
... |
Create a local bolt array of zeros. | def zeros(shape, dtype=float64, order='C'):
"""
Create a local bolt array of zeros.
Parameters
----------
shape : tuple
Dimensions of the desired array.
dtype : data-type, optional, default=float64
The desired data-type for the array. (see numpy)... |
Join a sequence of arrays together. | def concatenate(arrays, axis=0):
"""
Join a sequence of arrays together.
Parameters
----------
arrays : tuple
A sequence of array-like e.g. (a1, a2, ...)
axis : int, optional, default=0
The axis along which the arrays will be joined.
Ret... |
Returns A and B in y = Ax^B http:// mathworld. wolfram. com/ LeastSquaresFittingPowerLaw. html | def plfit_lsq(x,y):
"""
Returns A and B in y=Ax^B
http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
"""
n = len(x)
btop = n * (log(x)*log(y)).sum() - (log(x)).sum()*(log(y)).sum()
bbottom = n*(log(x)**2).sum() - (log(x).sum())**2
b = btop / bbottom
a = ( log(y).sum() - b ... |
A Python implementation of the Matlab code http:// www. santafe. edu/ ~aaronc/ powerlaws/ plfit. m from http:// www. santafe. edu/ ~aaronc/ powerlaws/ | def plfit(x,nosmall=False,finite=False):
"""
A Python implementation of the Matlab code http://www.santafe.edu/~aaronc/powerlaws/plfit.m
from http://www.santafe.edu/~aaronc/powerlaws/
See A. Clauset, C.R. Shalizi, and M.E.J. Newman, "Power-law distributions
in empirical data" SIAM Review, to appear... |
Plots CDF and powerlaw | def plotcdf(x,xmin,alpha):
"""
Plots CDF and powerlaw
"""
x=sort(x)
n=len(x)
xcdf = arange(n,0,-1,dtype='float')/float(n)
q = x[x>=xmin]
fcdf = (q/xmin)**(1-alpha)
nc = xcdf[argmax(x>=xmin)]
fcdf_norm = nc*fcdf
loglog(x,xcdf)
loglog(q,fcdf_norm) |
Plots PDF and powerlaw.... | def plotpdf(x,xmin,alpha,nbins=30,dolog=False):
"""
Plots PDF and powerlaw....
"""
x=sort(x)
n=len(x)
if dolog:
hb = hist(x,bins=logspace(log10(min(x)),log10(max(x)),nbins),log=True)
alpha += 1
else:
hb = hist(x,bins=linspace((min(x)),(max(x)),nbins))
h,b=hb[0],... |
CDF ( x ) for the piecewise distribution exponential x<xmin powerlaw x > = xmin This is the CDF version of the distributions drawn in fig 3. 4a of Clauset et al. | def plexp(x,xm=1,a=2.5):
"""
CDF(x) for the piecewise distribution exponential x<xmin, powerlaw x>=xmin
This is the CDF version of the distributions drawn in fig 3.4a of Clauset et al.
"""
C = 1/(-xm/(1 - a) - xm/a + math.exp(a)*xm/a)
Ppl = lambda X: 1+C*(xm/(1-a)*(X/xm)**(1-a))
Pexp = lamb... |
Inverse CDF for a piecewise PDF as defined in eqn. 3. 10 of Clauset et al. | def plexp_inv(P,xm,a):
"""
Inverse CDF for a piecewise PDF as defined in eqn. 3.10
of Clauset et al.
"""
C = 1/(-xm/(1 - a) - xm/a + math.exp(a)*xm/a)
Pxm = 1+C*(xm/(1-a))
pp = P
x = xm*(pp-1)*(1-a)/(C*xm)**(1/(1-a)) if pp >= Pxm else (math.log( ((C*xm/a)*math.exp(a)-pp)/(C*xm/a)) - a... |
Create a mappable function alpha to apply to each xmin in a list of xmins. This is essentially the slow version of fplfit/ cplfit though I bet it could be speeded up with a clever use of parellel_map. Not intended to be used by users. | def alpha_(self,x):
""" Create a mappable function alpha to apply to each xmin in a list of xmins.
This is essentially the slow version of fplfit/cplfit, though I bet it could
be speeded up with a clever use of parellel_map. Not intended to be used by users."""
def alpha(xmin,x=x):
... |
A pure - Python implementation of the Matlab code http:// www. santafe. edu/ ~aaronc/ powerlaws/ plfit. m from http:// www. santafe. edu/ ~aaronc/ powerlaws/ | def plfit(self,nosmall=True,finite=False,quiet=False,silent=False,
xmin=None, verbose=False):
"""
A pure-Python implementation of the Matlab code http://www.santafe.edu/~aaronc/powerlaws/plfit.m
from http://www.santafe.edu/~aaronc/powerlaws/
See A. Clauset, C.R. Shalizi, a... |
Create a mappable function alpha to apply to each xmin in a list of xmins. This is essentially the slow version of fplfit/ cplfit though I bet it could be speeded up with a clever use of parellel_map. Not intended to be used by users. | def alpha_gen(x):
""" Create a mappable function alpha to apply to each xmin in a list of xmins.
This is essentially the slow version of fplfit/cplfit, though I bet it could
be speeded up with a clever use of parellel_map. Not intended to be used by users.
Docstring for the generated alpha function::
... |
CDF ( x ) for the piecewise distribution exponential x<xmin powerlaw x > = xmin This is the CDF version of the distributions drawn in fig 3. 4a of Clauset et al. The constant C normalizes the PDF | def plexp_cdf(x,xmin=1,alpha=2.5, pl_only=False, exp_only=False):
"""
CDF(x) for the piecewise distribution exponential x<xmin, powerlaw x>=xmin
This is the CDF version of the distributions drawn in fig 3.4a of Clauset et al.
The constant "C" normalizes the PDF
"""
x = np.array(x)
C = 1/(-x... |
Inverse CDF for a piecewise PDF as defined in eqn. 3. 10 of Clauset et al. | def plexp_inv(P, xmin, alpha, guess=1.):
"""
Inverse CDF for a piecewise PDF as defined in eqn. 3.10
of Clauset et al.
(previous version was incorrect and lead to weird discontinuities in the
distribution function)
"""
def equation(x,prob):
return plexp_cdf(x, xmin, alpha)-prob
... |
Equation B. 8 in Clauset | def discrete_likelihood(data, xmin, alpha):
"""
Equation B.8 in Clauset
Given a data set, an xmin value, and an alpha "scaling parameter", computes
the log-likelihood (the value to be maximized)
"""
if not scipyOK:
raise ImportError("Can't import scipy. Need scipy for zeta function.")
... |
Compute the likelihood for all scaling parameters in the range ( alpharange ) for a given xmin. This is only part of the discrete value likelihood maximization problem as described in Clauset et al ( Equation B. 8 ) | def discrete_likelihood_vector(data, xmin, alpharange=(1.5,3.5), n_alpha=201):
"""
Compute the likelihood for all "scaling parameters" in the range (alpharange)
for a given xmin. This is only part of the discrete value likelihood
maximization problem as described in Clauset et al
(Equation B.8)
... |
Returns the * argument * of the max of the likelihood of the data given an input xmin | def discrete_max_likelihood_arg(data, xmin, alpharange=(1.5,3.5), n_alpha=201):
"""
Returns the *argument* of the max of the likelihood of the data given an input xmin
"""
likelihoods = discrete_likelihood_vector(data, xmin, alpharange=alpharange, n_alpha=n_alpha)
Largmax = np.argmax(likelihoods)
... |
Returns the * argument * of the max of the likelihood of the data given an input xmin | def discrete_max_likelihood(data, xmin, alpharange=(1.5,3.5), n_alpha=201):
"""
Returns the *argument* of the max of the likelihood of the data given an input xmin
"""
likelihoods = discrete_likelihood_vector(data, xmin, alpharange=alpharange, n_alpha=n_alpha)
Lmax = np.max(likelihoods)
return L... |
Return the most likely alpha for the data given an xmin | def most_likely_alpha(data, xmin, alpharange=(1.5,3.5), n_alpha=201):
"""
Return the most likely alpha for the data given an xmin
"""
alpha_vector = np.linspace(alpharange[0],alpharange[1],n_alpha)
return alpha_vector[discrete_max_likelihood_arg(data, xmin,
... |
Equation B. 17 of Clauset et al 2009 | def discrete_alpha_mle(data, xmin):
"""
Equation B.17 of Clauset et al 2009
The Maximum Likelihood Estimator of the "scaling parameter" alpha in the
discrete case is similar to that in the continuous case
"""
# boolean indices of positive data
gexmin = (data>=xmin)
nn = gexmin.sum()
... |
Use the maximum L to determine the most likely value of alpha | def discrete_best_alpha(data, alpharangemults=(0.9,1.1), n_alpha=201, approximate=True, verbose=True):
"""
Use the maximum L to determine the most likely value of alpha
*alpharangemults* [ 2-tuple ]
Pair of values indicating multiplicative factors above and below the
approximate alpha from ... |
given a sorted data set a minimum and an alpha returns the power law ks - test D value w/ data | def discrete_ksD(data, xmin, alpha):
"""
given a sorted data set, a minimum, and an alpha, returns the power law ks-test
D value w/data
The returned value is the "D" parameter in the ks test
(this is implemented differently from the continuous version because there
are potentially multiple ide... |
A Python implementation of the Matlab code http:// www. santafe. edu/ ~aaronc/ powerlaws/ plfit. m from http:// www. santafe. edu/ ~aaronc/ powerlaws/ | def plfit(self, nosmall=True, finite=False, quiet=False, silent=False,
usefortran=False, usecy=False, xmin=None, verbose=False,
discrete=None, discrete_approx=True, discrete_n_alpha=1000,
skip_consistency_check=False):
"""
A Python implementation of the Matlab c... |
Use the maximum likelihood to determine the most likely value of alpha | def discrete_best_alpha(self, alpharangemults=(0.9,1.1), n_alpha=201,
approximate=True, verbose=True, finite=True):
"""
Use the maximum likelihood to determine the most likely value of alpha
*alpharangemults* [ 2-tuple ]
Pair of values indicating multipli... |
Plot xmin versus the ks value for derived alpha. This plot can be used as a diagnostic of whether you have derived the best fit: if there are multiple local minima your data set may be well suited to a broken powerlaw or a different function. | def xminvsks(self, **kwargs):
"""
Plot xmin versus the ks value for derived alpha. This plot can be used
as a diagnostic of whether you have derived the 'best' fit: if there are
multiple local minima, your data set may be well suited to a broken
powerlaw or a different function.... |
Plot alpha versus the ks value for derived alpha. This plot can be used as a diagnostic of whether you have derived the best fit: if there are multiple local minima your data set may be well suited to a broken powerlaw or a different function. | def alphavsks(self,autozoom=True,**kwargs):
"""
Plot alpha versus the ks value for derived alpha. This plot can be used
as a diagnostic of whether you have derived the 'best' fit: if there are
multiple local minima, your data set may be well suited to a broken
powerlaw or a diff... |
Plots CDF and powerlaw | def plotcdf(self, x=None, xmin=None, alpha=None, pointcolor='k',
dolog=True, zoom=True, pointmarker='+', **kwargs):
"""
Plots CDF and powerlaw
"""
if x is None: x=self.data
if xmin is None: xmin=self._xmin
if alpha is None: alpha=self._alpha
x=np.... |
Plots PDF and powerlaw. | def plotpdf(self, x=None, xmin=None, alpha=None, nbins=50, dolog=True,
dnds=False, drawstyle='steps-post', histcolor='k', plcolor='r',
fill=False, dohist=True, **kwargs):
"""
Plots PDF and powerlaw.
kwargs is passed to pylab.hist and pylab.plot
"""
... |
Plots the power - law - predicted value on the Y - axis against the real values along the X - axis. Can be used as a diagnostic of the fit quality. | def plotppf(self,x=None,xmin=None,alpha=None,dolog=True,**kwargs):
"""
Plots the power-law-predicted value on the Y-axis against the real
values along the X-axis. Can be used as a diagnostic of the fit
quality.
"""
if not(xmin): xmin=self._xmin
if not(alpha): alp... |
Use the maximum likelihood estimator for a lognormal distribution to produce the best - fit lognormal parameters | def lognormal(self,doprint=True):
"""
Use the maximum likelihood estimator for a lognormal distribution to
produce the best-fit lognormal parameters
"""
# N = float(self.data.shape[0])
# mu = log(self.data).sum() / N
# sigmasquared = ( ( log(self.data) - mu )**2 )... |
Plot the fitted lognormal distribution | def plot_lognormal_pdf(self,**kwargs):
"""
Plot the fitted lognormal distribution
"""
if not hasattr(self,'lognormal_dist'):
return
normalized_pdf = self.lognormal_dist.pdf(self.data)/self.lognormal_dist.pdf(self.data).max()
minY,maxY = pylab.gca().get_ylim()... |
Plot the fitted lognormal distribution | def plot_lognormal_cdf(self,**kwargs):
"""
Plot the fitted lognormal distribution
"""
if not hasattr(self,'lognormal_dist'):
return
x=np.sort(self.data)
n=len(x)
xcdf = np.arange(n,0,-1,dtype='float')/float(n)
lcdf = self.lognormal_dist.sf(x)
... |
Sanitizes HTML removing not allowed tags and attributes. | def sanitize_turbo(html, allowed_tags=TURBO_ALLOWED_TAGS, allowed_attrs=TURBO_ALLOWED_ATTRS):
"""Sanitizes HTML, removing not allowed tags and attributes.
:param str|unicode html:
:param list allowed_tags: List of allowed tags.
:param dict allowed_attrs: Dictionary with attributes allowed for tags.
... |
Configure Yandex Metrika analytics counter. | def configure_analytics_yandex(self, ident, params=None):
"""Configure Yandex Metrika analytics counter.
:param str|unicode ident: Metrika counter ID.
:param dict params: Additional params.
"""
params = params or {}
data = {
'type': 'Yandex',
'... |
Generates a list of tags identifying those previously selected. | def tag_list(self, tags):
"""
Generates a list of tags identifying those previously selected.
Returns a list of tuples of the form (<tag name>, <CSS class name>).
Uses the string names rather than the tags themselves in order to work
with tag lists built from forms not fully su... |
Calculate the great circle distance between two points on the earth ( specified in decimal degrees ) | def gcd(self, lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])
# haversine... |
Calculate md5 fingerprint. | def hash_md5(self):
"""Calculate md5 fingerprint.
Shamelessly copied from http://stackoverflow.com/questions/6682815/deriving-an-ssh-fingerprint-from-a-public-key-in-python
For specification, see RFC4716, section 4."""
fp_plain = hashlib.md5(self._decoded_key).hexdigest()
retur... |
Calculate sha256 fingerprint. | def hash_sha256(self):
"""Calculate sha256 fingerprint."""
fp_plain = hashlib.sha256(self._decoded_key).digest()
return (b"SHA256:" + base64.b64encode(fp_plain).replace(b"=", b"")).decode("utf-8") |
Calculates sha512 fingerprint. | def hash_sha512(self):
"""Calculates sha512 fingerprint."""
fp_plain = hashlib.sha512(self._decoded_key).digest()
return (b"SHA512:" + base64.b64encode(fp_plain).replace(b"=", b"")).decode("utf-8") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.