Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def parse_vasprun( self ):
self.vasprun_filename = match_filename( 'vasprun.xml' )
if not self.vasprun_filename:
raise FileNotFoundError( 'Could not find vasprun.xml or vasprun.xml.gz file' )
try:
self.vasp... | [
"\n Read in `vasprun.xml` as a pymatgen Vasprun object.\n\n Args:\n None\n\n Returns:\n None\n\n None:\n If the vasprun.xml is not well formed this method will catch the ParseError\n and set self.vasprun = None.\n "
] |
Please provide a description of the function:def functional( self ):
if self.potcars_are_pbe(): # PBE base funtional
if 'LHFCALC' in self.vasprun.parameters:
alpha = float( self.vasprun.parameters['AEXX'] )
else:
alpha = 0.0
if 'HFSCRE... | [
"\n String description of the calculation functional.\n \n Recognises:\n - PBE\n - PBEsol\n - PBE-based hybrids:\n - PBE0 (alpha=0.25, no screening)\n - HSE06 (alpha=0.25, mu=0.2)\n - generic hybrids (alpha=?, no scree... |
Please provide a description of the function:def read_projected_dos( self ):
pdos_list = []
for i in range( self.number_of_atoms ):
df = self.read_atomic_dos_as_df( i+1 )
pdos_list.append( df )
self.pdos = np.vstack( [ np.array( df ) for df in pdos_list ] ).resha... | [
"\n Read the projected density of states data into "
] |
Please provide a description of the function:def pdos_select( self, atoms=None, spin=None, l=None, m=None ):
valid_m_values = { 's': [],
'p': [ 'x', 'y', 'z' ],
'd': [ 'xy', 'yz', 'z2-r2', 'xz', 'x2-y2' ],
'f': [ 'y(3x2-y2... | [
"\n Returns a subset of the projected density of states array.\n\n Args:\n atoms (int or list(int)): Atom numbers to include in the selection. Atom numbers count from 1. \n Default is to select all atoms.\n spin (str): Select up or down, or both ... |
Please provide a description of the function:def delta_E( reactants, products, check_balance=True ):
if check_balance:
if delta_stoichiometry( reactants, products ) != {}:
raise ValueError( "reaction is not balanced: {}".format( delta_stoichiometry( reactants, products) ) )
return sum( ... | [
"\n Calculate the change in energy for reactants --> products.\n \n Args:\n reactants (list(vasppy.Calculation): A list of vasppy.Calculation objects. The initial state.\n products (list(vasppy.Calculation): A list of vasppy.Calculation objects. The final state.\n check_balance (bool:... |
Please provide a description of the function:def delta_stoichiometry( reactants, products ):
totals = Counter()
for r in reactants:
totals.update( ( r * -1.0 ).stoichiometry )
for p in products:
totals.update( p.stoichiometry )
to_return = {}
for c in totals:
if totals[... | [
"\n Calculate the change in stoichiometry for reactants --> products.\n\n Args:\n reactants (list(vasppy.Calculation): A list of vasppy.Calculation objects. The initial state.\n products (list(vasppy.Calculation): A list of vasppy.Calculation objects. The final state.\n\n Returns:\n (... |
Please provide a description of the function:def energy_string_to_float( string ):
energy_re = re.compile( "(-?\d+\.\d+)" )
return float( energy_re.match( string ).group(0) ) | [
"\n Convert a string of a calculation energy, e.g. '-1.2345 eV' to a float.\n\n Args:\n string (str): The string to convert.\n \n Return\n (float) \n "
] |
Please provide a description of the function:def import_calculations_from_file( filename ):
calcs = {}
with open( filename, 'r' ) as stream:
docs = yaml.load_all( stream, Loader=yaml.SafeLoader )
for d in docs:
stoichiometry = Counter()
for s in d['stoichiometry']:
... | [
"\n Construct a list of Calculation objects by reading a YAML file.\n Each YAML document should include 'title', 'stoichiometry', and 'energy' fields. e.g.::\n\n title: my calculation\n stoichiometry:\n - A: 1\n - B: 2\n energy: -0.1234 eV\n\n Separate calculation... |
Please provide a description of the function:def scale_stoichiometry( self, scaling ):
return { k:v*scaling for k,v in self.stoichiometry.items() } | [
"\n Scale the Calculation stoichiometry\n Returns the stoichiometry, scaled by the argument scaling.\n\n Args:\n scaling (float): The scaling factor.\n\n Returns:\n (Counter(Str:Int)): The scaled stoichiometry as a Counter of label: stoichiometry pairs\n "
] |
Please provide a description of the function:def angle( x, y ):
dot = np.dot( x, y )
x_mod = np.linalg.norm( x )
y_mod = np.linalg.norm( y )
cos_angle = dot / ( x_mod * y_mod )
return np.degrees( np.arccos( cos_angle ) ) | [
"\n Calculate the angle between two vectors, in degrees.\n\n Args:\n x (np.array): one vector.\n y (np.array): the other vector.\n\n Returns:\n (float): the angle between x and y in degrees.\n "
] |
Please provide a description of the function:def dr( self, r1, r2, cutoff=None ):
delta_r_cartesian = ( r1 - r2 ).dot( self.matrix )
delta_r_squared = sum( delta_r_cartesian**2 )
if cutoff != None:
cutoff_squared = cutoff ** 2
if delta_r_squared > cutoff_squared:... | [
"\n Calculate the distance between two fractional coordinates in the cell.\n \n Args:\n r1 (np.array): fractional coordinates for position 1.\n r2 (np.array): fractional coordinates for position 2.\n cutoff (optional:Bool): If set, returns None for distances gre... |
Please provide a description of the function:def minimum_image( self, r1, r2 ):
delta_r = r2 - r1
delta_r = np.array( [ x - math.copysign( 1.0, x ) if abs(x) > 0.5 else x for x in delta_r ] )
return( delta_r ) | [
"\n Find the minimum image vector from point r1 to point r2.\n\n Args:\n r1 (np.array): fractional coordinates of point r1.\n r2 (np.array): fractional coordinates of point r2.\n\n Returns:\n (np.array): the fractional coordinate vector from r1 to the nearest im... |
Please provide a description of the function:def minimum_image_dr( self, r1, r2, cutoff=None ):
delta_r_vector = self.minimum_image( r1, r2 )
return( self.dr( np.zeros( 3 ), delta_r_vector, cutoff ) ) | [
"\n Calculate the shortest distance between two points in the cell, \n accounting for periodic boundary conditions.\n\n Args:\n r1 (np.array): fractional coordinates of point r1.\n r2 (np.array): fractional coordinates of point r2.\n cutoff (:obj: `float`, optio... |
Please provide a description of the function:def lengths( self ):
return( np.array( [ math.sqrt( sum( row**2 ) ) for row in self.matrix ] ) ) | [
"\n The cell lengths.\n\n Args:\n None\n\n Returns:\n (np.array(a,b,c)): The cell lengths.\n "
] |
Please provide a description of the function:def angles( self ):
( a, b, c ) = [ row for row in self.matrix ]
return [ angle( b, c ), angle( a, c ), angle( a, b ) ] | [
"\n The cell angles (in degrees).\n\n Args:\n None\n\n Returns:\n (list(alpha,beta,gamma)): The cell angles.\n "
] |
Please provide a description of the function:def inside_cell( self, r ):
centre = np.array( [ 0.5, 0.5, 0.5 ] )
new_r = self.nearest_image( centre, r )
return new_r | [
"\n Given a fractional-coordinate, if this lies outside the cell return the equivalent point inside the cell.\n\n Args:\n r (np.array): Fractional coordinates of a point (this may be outside the cell boundaries).\n\n Returns:\n (np.array): Fractional coordinates of an equi... |
Please provide a description of the function:def volume( self ):
return np.dot( self.matrix[0], np.cross( self.matrix[1], self.matrix[2] ) ) | [
"\n The cell volume.\n\n Args:\n None\n\n Returns:\n (float): The cell volume.\n "
] |
Please provide a description of the function:def from_file( cls, filename ):
with open( filename, 'r' ) as stream:
data = yaml.load( stream, Loader=yaml.SafeLoader )
notes = data.get( 'notes' )
v_type = data.get( 'type' )
track = data.get( 'track' )
... | [
"\n Create a VASPMeta object by reading a `vaspmeta.yaml` file\n\n Args:\n filename (Str): filename to read in.\n\n Returns:\n (vasppy.VASPMeta): the VASPMeta object\n "
] |
Please provide a description of the function:def reciprocal_lattice_from_outcar( filename ): # from https://github.com/MaterialsDiscovery/PyChemia
outcar = open(filename, "r").read()
# just keeping the last component
recLat = re.findall(r"reciprocal\s*lattice\s*vectors\s*([-.\s\d]*)",
... | [
"\n Finds and returns the reciprocal lattice vectors, if more than\n one set present, it just returns the last one.\n Args:\n filename (Str): The name of the outcar file to be read\n\n Returns:\n List(Float): The reciprocal lattice vectors.\n "
] |
Please provide a description of the function:def final_energy_from_outcar( filename='OUTCAR' ):
with open( filename ) as f:
outcar = f.read()
energy_re = re.compile( "energy\(sigma->0\) =\s+([-\d\.]+)" )
energy = float( energy_re.findall( outcar )[-1] )
return energy | [
"\n Finds and returns the energy from a VASP OUTCAR file, by searching for the last `energy(sigma->0)` entry.\n\n Args:\n filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.\n\n Returns:\n (Float): The last energy read from the OUTCAR file.\n "
] |
Please provide a description of the function:def vasp_version_from_outcar( filename='OUTCAR' ):
with open( filename ) as f:
line = f.readline().strip()
return line | [
"\n Returns the first line from a VASP OUTCAR file, to get the VASP source version string.\n\n Args:\n filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.\n\n Returns:\n (Str): The first line read from the OUTCAR file.\n "
] |
Please provide a description of the function:def potcar_eatom_list_from_outcar( filename='OUTCAR' ):
with open( filename ) as f:
outcar = f.read()
eatom_re = re.compile( "energy of atom\s+\d+\s+EATOM=\s*([-\d\.]+)" )
eatom = [ float( e ) for e in eatom_re.findall( outcar ) ]
return eatom | [
"\n Returns a list of EATOM values for the pseudopotentials used.\n\n Args:\n filename (Str, optional): OUTCAR filename. Defaults to 'OUTCAR'.\n\n Returns:\n (List(Float)): A list of EATOM values, in the order they appear in the OUTCAR.\n "
] |
Please provide a description of the function:def fermi_energy_from_outcar( filename='OUTCAR' ):
outcar = open(filename, "r").read()
# returns a match object
fermi_energy = re.search(r"E-fermi\s*:\s*([-.\d]*)", outcar)
# take the first group - group(0) contains entire match
fermi_energy = float(... | [
"Finds and returns the fermi energy.\n Args:\n -filename: the name of the outcar file to be read\n\n Returns:\n (Float): The fermi energy as found in the OUTCAR \n "
] |
Please provide a description of the function:def build_description(node=None):
if node is None:
from logging_tree.nodes import tree
node = tree()
return '\n'.join([ line.rstrip() for line in describe(node) ]) + '\n' | [
"Return a multi-line string describing a `logging_tree.nodes.Node`.\n\n If no `node` argument is provided, then the entire tree of currently\n active `logging` loggers is printed out.\n\n "
] |
Please provide a description of the function:def _describe(node, parent):
name, logger, children = node
is_placeholder = isinstance(logger, logging.PlaceHolder)
if is_placeholder:
yield '<--[%s]' % name
else:
parent_is_correct = (parent is None) or (logger.parent is parent)
... | [
"Generate lines describing the given `node` tuple.\n\n This is the recursive back-end that powers ``describe()``. With its\n extra ``parent`` parameter, this routine remembers the nearest\n non-placeholder ancestor so that it can compare it against the\n actual value of the ``.parent`` attribute of eac... |
Please provide a description of the function:def describe_filter(f):
if f.__class__ is logging.Filter: # using type() breaks in Python <= 2.6
return 'name=%r' % f.name
return repr(f) | [
"Return text describing the logging filter `f`."
] |
Please provide a description of the function:def describe_handler(h):
t = h.__class__ # using type() breaks in Python <= 2.6
format = handler_formats.get(t)
if format is not None:
yield format % h.__dict__
else:
yield repr(h)
level = getattr(h, 'level', logging.NOTSET)
if l... | [
"Yield one or more lines describing the logging handler `h`."
] |
Please provide a description of the function:def tree():
root = ('', logging.root, [])
nodes = {}
items = list(logging.root.manager.loggerDict.items()) # for Python 2 and 3
items.sort()
for name, logger in items:
nodes[name] = node = (name, logger, [])
i = name.rfind('.', 0, le... | [
"Return a tree of tuples representing the logger layout.\n\n Each tuple looks like ``('logger-name', <Logger>, [...])`` where the\n third element is a list of zero or more child tuples that share the\n same layout.\n\n "
] |
Please provide a description of the function:def patched_str(self):
def red(words):
return u("\033[31m\033[49m%s\033[0m") % words
def white(words):
return u("\033[37m\033[49m%s\033[0m") % words
def blue(words):
return u("\033[34m\033[49m%s\033[0m") % words
def teal(words):
... | [
" Try to pretty-print the exception, if this is going on screen. "
] |
Please provide a description of the function:def patched_fax_init(self, twilio):
super(TwilioFax, self).__init__(twilio)
self.base_url = ''
self.account_sid = twilio.account_sid
# Versions
self._v1 = None | [
"\n Initialize the Fax Domain\n :returns: Domain for Fax\n :rtype: twilio.rest.fax.Fax\n "
] |
Please provide a description of the function:def patched_fax_v1_init(self, domain):
print(domain.__class__.__name__)
super(TwilioV1, self).__init__(domain)
self.version = "2010-04-01/Accounts/" + domain.account_sid
self._faxes = None | [
"\n Initialize the V1 version of Fax\n :returns: V1 version of Fax\n :rtype: twilio.rest.fax.v1.V1.V1\n "
] |
Please provide a description of the function:def find_this(search, filename=MODULE_PATH):
if not search:
return
for line in open(str(filename)).readlines():
if search.lower() in line.lower():
line = line.split("=")[1].strip()
if "'" in line or '"' in line or '', '')
... | [
"Take a string and a filename path string and return the found value.",
"' in line:\n line = line.replace(\"'\", \"\").replace('\"', '').replace('"
] |
Please provide a description of the function:def h(self):
r
if np.size(self._h) > 1:
assert np.size(self._h) == self.n_modelparams
return self._h
else:
return self._h * np.ones(self.n_modelparams) | [
"\n Returns the step size to be used in numerical differentiation with \n respect to the model parameters.\n \n The step size is given as a vector with length ``n_modelparams`` so \n that each model parameter can be weighted independently.\n "
] |
Please provide a description of the function:def score(self, outcomes, modelparams, expparams, return_L=False):
r
if len(modelparams.shape) == 1:
modelparams = modelparams[:, np.newaxis]
# compute likelihood at central point
L0 = self.likelihood(outcomes, mo... | [
"\n Returns the numerically computed score of the likelihood \n function, defined as:\n \n .. math::\n \n q(d, \\vec{x}; \\vec{e}) = \\vec{\\nabla}_{\\vec{x}} \\log \\Pr(d | \\vec{x}; \\vec{e}).\n \n Calls are represented as a four-index tensor\n ... |
Please provide a description of the function:def clear_cache(self):
self.underlying_model.clear_cache()
try:
logger.info('DirectView results has {} items. Clearing.'.format(
len(self._dv.results)
))
self._dv.purge_results('all')
if... | [
"\n Clears any cache associated with the serial model and the engines\n seen by the direct view.\n "
] |
Please provide a description of the function:def likelihood(self, outcomes, modelparams, expparams):
# By calling the superclass implementation, we can consolidate
# call counting there.
super(DirectViewParallelizedModel, self).likelihood(outcomes, modelparams, expparams)
# If ... | [
"\n Returns the likelihood for the underlying (serial) model, distributing\n the model parameter array across the engines controlled by this\n parallelized model. Returns what the serial model would return, see\n :attr:`~Model.likelihood`\n "
] |
Please provide a description of the function:def simulate_experiment(self, modelparams, expparams, repeat=1, split_by_modelparams=True):
# By calling the superclass implementation, we can consolidate
# simulation counting there.
super(DirectViewParallelizedModel, self).simulate_experime... | [
"\n Simulates the underlying (serial) model using the parallel \n engines. Returns what the serial model would return, see\n :attr:`~Simulatable.simulate_experiment`\n\n :param bool split_by_modelparams: If ``True``, splits up\n ``modelparams`` into `n_engines` chunks and dist... |
Please provide a description of the function:def _maybe_resample(self):
ess = self.n_ess
if ess <= 10:
warnings.warn(
"Extremely small n_ess encountered ({}). "
"Resampling is likely to fail. Consider adding particles, or "
"resampling... | [
"\n Checks the resample threshold and conditionally resamples.\n "
] |
Please provide a description of the function:def update(self, outcome, expparams, check_for_resample=True):
# First, record the outcome.
# TODO: record the experiment as well.
self._data_record.append(outcome)
self._just_resampled = False
# Perform the update.
... | [
"\n Given an experiment and an outcome of that experiment, updates the\n posterior distribution to reflect knowledge of that experiment.\n\n After updating, resamples the posterior distribution if necessary.\n\n :param int outcome: Label for the outcome that was observed, as defined\n ... |
Please provide a description of the function:def batch_update(self, outcomes, expparams, resample_interval=5):
r
# TODO: write a faster implementation here using vectorized calls to
# likelihood.
# Check that the number of outcomes and experiments is the same.
n_exps = ou... | [
"\n Updates based on a batch of outcomes and experiments, rather than just\n one.\n\n :param numpy.ndarray outcomes: An array of outcomes of the experiments that\n were performed.\n :param numpy.ndarray expparams: Either a scalar or record single-index\n array of ex... |
Please provide a description of the function:def resample(self):
if self.just_resampled:
warnings.warn(
"Resampling without additional data; this may not perform as "
"desired.",
ResamplerWarning
)
# Record that we have p... | [
"\n Forces the updater to perform a resampling step immediately.\n "
] |
Please provide a description of the function:def bayes_risk(self, expparams):
r
# for models whose outcome number changes with experiment, we
# take the easy way out and for-loop over experiments
n_eps = expparams.size
if n_eps > 1 and not self.model.is_n_outcomes_constant:
... | [
"\n Calculates the Bayes risk for hypothetical experiments, assuming the\n quadratic loss function defined by the current model's scale matrix\n (see :attr:`qinfer.abstract_model.Simulatable.Q`).\n\n :param expparams: The experiments at which to compute the risk.\n :type expparams... |
Please provide a description of the function:def expected_information_gain(self, expparams):
r
# This is a special case of the KL divergence estimator (see below),
# in which the other distribution is guaranteed to share support.
# for models whose outcome number changes with ex... | [
"\n Calculates the expected information gain for each hypothetical experiment.\n\n :param expparams: The experiments at which to compute expected\n information gain.\n :type expparams: :class:`~numpy.ndarray` of dtype given by the current\n model's :attr:`~qinfer.abstract_... |
Please provide a description of the function:def posterior_marginal(self, idx_param=0, res=100, smoothing=0, range_min=None, range_max=None):
# We need to sort the particles to get cumsum to make sense.
# interp1d would do it anyways (using argsort, too), so it's not a waste
s = np.ar... | [
"\n Returns an estimate of the marginal distribution of a given model parameter, based on\n taking the derivative of the interpolated cdf.\n\n :param int idx_param: Index of parameter to be marginalized.\n :param int res1: Resolution of of the axis.\n :param float smoothing: Stand... |
Please provide a description of the function:def plot_posterior_marginal(self, idx_param=0, res=100, smoothing=0,
range_min=None, range_max=None, label_xaxis=True,
other_plot_args={}, true_model=None
):
res = plt.plot(*self.posterior_marginal(
idx_param, res,... | [
"\n Plots a marginal of the requested parameter.\n\n :param int idx_param: Index of parameter to be marginalized.\n :param int res1: Resolution of of the axis.\n :param float smoothing: Standard deviation of the Gaussian kernel\n used to smooth; same units as parameter.\n ... |
Please provide a description of the function:def plot_covariance(self, corr=False, param_slice=None, tick_labels=None, tick_params=None):
if mpls is None:
raise ImportError("Hinton diagrams require mpltools.")
if param_slice is None:
param_slice = np.s_[:]
tick... | [
"\n Plots the covariance matrix of the posterior as a Hinton diagram.\n\n .. note::\n\n This function requires that mpltools is installed.\n\n :param bool corr: If `True`, the covariance matrix is first normalized\n by the outer product of the square root diagonal of the c... |
Please provide a description of the function:def posterior_mesh(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01):
# WARNING: fancy indexing is used here, which means that a copy is
# made.
locs = self.particle_locations[:, [idx_param1, idx_param2]]
... | [
"\n Returns a mesh, useful for plotting, of kernel density estimation\n of a 2D projection of the current posterior distribution.\n\n :param int idx_param1: Parameter to be treated as :math:`x` when\n plotting.\n :param int idx_param2: Parameter to be treated as :math:`y` when... |
Please provide a description of the function:def plot_posterior_contour(self, idx_param1=0, idx_param2=1, res1=100, res2=100, smoothing=0.01):
return plt.contour(*self.posterior_mesh(idx_param1, idx_param2, res1, res2, smoothing)) | [
"\n Plots a contour of the kernel density estimation\n of a 2D projection of the current posterior distribution.\n\n :param int idx_param1: Parameter to be treated as :math:`x` when\n plotting.\n :param int idx_param2: Parameter to be treated as :math:`y` when\n plo... |
Please provide a description of the function:def prior_bayes_information(self, expparams, n_samples=None):
if n_samples is None:
n_samples = self.particle_locations.shape[0]
return self._bim(self.prior.sample(n_samples), expparams) | [
"\n Evaluates the local Bayesian Information Matrix (BIM) for a set of\n samples from the SMC particle set, with uniform weights.\n\n :param expparams: Parameters describing the experiment that was\n performed.\n :type expparams: :class:`~numpy.ndarray` of dtype given by the\n... |
Please provide a description of the function:def posterior_bayes_information(self, expparams):
return self._bim(
self.particle_locations, expparams,
modelweights=self.particle_weights
) | [
"\n Evaluates the local Bayesian Information Matrix (BIM) over all particles\n of the current posterior distribution with corresponding weights.\n\n :param expparams: Parameters describing the experiment that was\n performed.\n :type expparams: :class:`~numpy.ndarray` of dtype... |
Please provide a description of the function:def update(self, outcome, expparams,check_for_resample=True):
# Before we update, we need to commit the new Bayesian information
# matrix corresponding to the measurement we just made.
self._current_bim += self.prior_bayes_information(exppara... | [
"\n Given an experiment and an outcome of that experiment, updates the\n posterior distribution to reflect knowledge of that experiment.\n\n After updating, resamples the posterior distribution if necessary.\n\n :param int outcome: Label for the outcome that was observed, as defined\n ... |
Please provide a description of the function:def design_expparams_field(self,
guess, field,
cost_scale_k=1.0, disp=False,
maxiter=None, maxfun=None,
store_guess=False, grad_h=None, cost_mult=False
):
r
# Define some short names for commonl... | [
"\n Designs a new experiment by varying a single field of a shape ``(1,)``\n record array and minimizing the objective function\n \n .. math::\n O(\\vec{e}) = r(\\vec{e}) + k \\$(\\vec{e}),\n \n where :math:`r` is the Bayes risk as calculated by the updater, and\... |
Please provide a description of the function:def particle_clusters(
particle_locations, particle_weights=None,
eps=0.5, min_particles=5, metric='euclidean',
weighted=False, w_pow=0.5,
quiet=True
):
if weighted == True and particle_weights is None:
raise ValueError(... | [
"\n Yields an iterator onto tuples ``(cluster_label, cluster_particles)``,\n where ``cluster_label`` is an `int` identifying the cluster (or ``NOISE``\n for the particles lying outside of all clusters), and where\n ``cluster_particles`` is an array of ``dtype`` `bool` specifying the indices\n of all ... |
Please provide a description of the function:def plot_rebit_modelparams(modelparams, rebit_axes=REBIT_AXES, **kwargs):
mps = modelparams[:, rebit_axes] * np.sqrt(2)
plt.scatter(mps[:, 0], mps[:, 1], **kwargs) | [
"\n Given model parameters representing rebits, plots the\n rebit states as a scatter plot. Additional keyword arguments\n are passed to :ref:`plt.scatter`.\n\n :param np.ndarray modelparams: Model parameters representing\n rebits.\n :param list rebit_axes: List containing indices for the :mat... |
Please provide a description of the function:def plot_decorate_rebits(basis=None, rebit_axes=REBIT_AXES):
ax = plt.gca()
if basis is not None:
labels = list(map(r'$\langle\!\langle {} | \rho \rangle\!\rangle$'.format,
# Pick out the x and z by default.
[basis.labels[rebit_a... | [
"\n Decorates a figure with the boundary of rebit state space\n and basis labels drawn from a :ref:`~qinfer.tomography.TomographyBasis`.\n\n :param qinfer.tomography.TomographyBasis basis: Basis to use in\n labeling axes.\n :param list rebit_axes: List containing indices for the :math:`x`\n ... |
Please provide a description of the function:def plot_rebit_prior(prior, rebit_axes=REBIT_AXES,
n_samples=2000, true_state=None, true_size=250,
force_mean=None,
legend=True,
mean_color_index=2
):
pallette = plt.rcParams['axes.color_cycle']
plot_rebit_modelparams(prior.s... | [
"\n Plots rebit states drawn from a given prior.\n\n :param qinfer.tomography.DensityOperatorDistribution prior: Distribution over\n rebit states to plot.\n :param list rebit_axes: List containing indices for the :math:`x`\n and :math:`z` axes.\n :param int n_samples: Number of samples to ... |
Please provide a description of the function:def plot_rebit_posterior(updater, prior=None, true_state=None, n_std=3, rebit_axes=REBIT_AXES, true_size=250,
legend=True,
level=0.95,
region_est_method='cov'
):
pallette = plt.rcParams['axes.color_cycle']
plot_rebit_mode... | [
"\n Plots posterior distributions over rebits, including covariance ellipsoids\n\n :param qinfer.smc.SMCUpdater updater: Posterior distribution over rebits.\n :param qinfer.tomography.DensityOperatorDistribution: Prior distribution\n over rebit states.\n :param np.ndarray true_state: Model parame... |
Please provide a description of the function:def data_to_params(data,
expparams_dtype,
col_outcomes=(0, 'counts'),
cols_expparams=None
):
BY_IDX, BY_NAME = range(2)
is_exp_scalar = np.issctype(expparams_dtype)
is_data_scalar = np.issctype(data.dtype) and not data.dtype.fiel... | [
"\n Given data as a NumPy array, separates out each column either as\n the outcomes, or as a field of an expparams array. Columns may be specified\n either as indices into a two-axis scalar array, or as field names for a one-axis\n record array.\n\n Since scalar arrays are homogenous in type, this ma... |
Please provide a description of the function:def simple_est_prec(data, freq_min=0.0, freq_max=1.0, n_particles=6000, return_all=False):
model = BinomialModel(SimplePrecessionModel(freq_min))
prior = UniformDistribution([0, freq_max])
data = load_data_or_txt(data, [
('counts', 'uint'),
... | [
"\n Estimates a simple precession (cos²) from experimental data.\n Note that this model is mainly for testing purposes, as it does not\n consider the phase or amplitude of precession, leaving only the frequency.\n\n :param data: Data to be used in estimating the precession frequency.\n :type data: se... |
Please provide a description of the function:def simple_est_rb(data, interleaved=False, p_min=0.0, p_max=1.0, n_particles=8000, return_all=False):
r
model = BinomialModel(RandomizedBenchmarkingModel(interleaved=interleaved))
prior = PostselectedDistribution(UniformDistribution([
[p_min, p_max],
... | [
"\n Estimates the fidelity of a gateset from a standard or interleaved randomized benchmarking\n experiment.\n \n :param data: Data to be used in estimating the gateset fidelity.\n :type data: see :ref:`simple_est_data_arg`\n :param float p_min: Minimum value of the parameter :math:`p`\n to... |
Please provide a description of the function:def canonicalize(self, modelparams):
modelparams = np.apply_along_axis(self.trunc_neg_eigs, 1, modelparams)
# Renormalizes particles if allow_subnormalized=False.
if not self._allow_subnormalied:
modelparams = self.renormalize(mod... | [
"\n Truncates negative eigenvalues and from each\n state represented by a tensor of model parameter\n vectors, and renormalizes as appropriate.\n\n :param np.ndarray modelparams: Array of shape\n ``(n_states, dim**2)`` containing model parameter\n representations of... |
Please provide a description of the function:def trunc_neg_eigs(self, particle):
arr = np.tensordot(particle, self._basis.data.conj(), 1)
w, v = np.linalg.eig(arr)
if np.all(w >= 0):
return particle
else:
w[w < 0] = 0
new_arr = np.dot(v * w, v... | [
"\n Given a state represented as a model parameter vector,\n returns a model parameter vector representing the same\n state with any negative eigenvalues set to zero.\n\n :param np.ndarray particle: Vector of length ``(dim ** 2, )``\n representing a state.\n :return: Th... |
Please provide a description of the function:def renormalize(self, modelparams):
# The 0th basis element (identity) should have
# a value 1 / sqrt{dim}, since the trace of that basis
# element is fixed to be sqrt{dim} by convention.
norm = modelparams[:, 0] * np.sqrt(self._dim)
... | [
"\n Renormalizes one or more states represented as model\n parameter vectors, such that each state has trace 1.\n\n :param np.ndarray modelparams: Array of shape ``(n_states,\n dim ** 2)`` representing one or more states as \n model parameter vectors.\n :return: The... |
Please provide a description of the function:def n_members(self):
if self.is_finite:
return reduce(mul, [domain.n_members for domain in self._domains], 1)
else:
return np.inf | [
"\n Returns the number of members in the domain if it\n `is_finite`, otherwise, returns `np.inf`.\n\n :type: ``int`` or ``np.inf``\n "
] |
Please provide a description of the function:def values(self):
separate_values = [domain.values for domain in self._domains]
return np.concatenate([
join_struct_arrays(list(map(np.array, value)))
for value in product(*separate_values)
]) | [
"\n Returns an `np.array` of type `dtype` containing\n some values from the domain.\n For domains where `is_finite` is ``True``, all elements\n of the domain will be yielded exactly once.\n\n :rtype: `np.ndarray`\n "
] |
Please provide a description of the function:def from_regular_arrays(self, arrays):
return self._mytype(join_struct_arrays([
array.astype(dtype)
for dtype, array in zip(self._dtypes, arrays)
])) | [
"\n Merges a list of arrays (of the same shape) of dtypes \n corresponding to the factor domains into a single array \n with the dtype of the ``ProductDomain``.\n\n :param list array: A list with each element of type ``np.ndarray``\n\n :rtype: `np.ndarray`\n "
] |
Please provide a description of the function:def in_domain(self, points):
return all([
domain.in_domain(array)
for domain, array in
zip(self._domains, separate_struct_array(points, self._dtypes))
]) | [
"\n Returns ``True`` if all of the given points are in the domain,\n ``False`` otherwise.\n\n :param np.ndarray points: An `np.ndarray` of type `self.dtype`.\n\n :rtype: `bool`\n "
] |
Please provide a description of the function:def example_point(self):
if not np.isinf(self.min):
return np.array([self.min], dtype=self.dtype)
if not np.isinf(self.max):
return np.array([self.max], dtype=self.dtype)
else:
return np.array([0], dtype=se... | [
"\n Returns any single point guaranteed to be in the domain, but\n no other guarantees; useful for testing purposes.\n This is given as a size 1 ``np.array`` of type ``dtype``.\n\n :type: ``np.ndarray``\n "
] |
Please provide a description of the function:def in_domain(self, points):
if np.all(np.isreal(points)):
are_greater = np.all(np.greater_equal(points, self._min))
are_smaller = np.all(np.less_equal(points, self._max))
return are_greater and are_smaller
else:
... | [
"\n Returns ``True`` if all of the given points are in the domain,\n ``False`` otherwise.\n\n :param np.ndarray points: An `np.ndarray` of type `self.dtype`.\n\n :rtype: `bool`\n "
] |
Please provide a description of the function:def min(self):
return int(self._min) if not np.isinf(self._min) else self._min | [
"\n Returns the minimum value of the domain.\n\n :rtype: `float` or `np.inf`\n "
] |
Please provide a description of the function:def max(self):
return int(self._max) if not np.isinf(self._max) else self._max | [
"\n Returns the maximum value of the domain.\n\n :rtype: `float` or `np.inf`\n "
] |
Please provide a description of the function:def is_finite(self):
return not np.isinf(self.min) and not np.isinf(self.max) | [
"\n Whether or not the domain contains a finite number of points.\n\n :type: `bool`\n "
] |
Please provide a description of the function:def n_members(self):
if self.is_finite:
return int(self.max - self.min + 1)
else:
return np.inf | [
"\n Returns the number of members in the domain if it\n `is_finite`, otherwise, returns `np.inf`.\n\n :type: ``int`` or ``np.inf``\n "
] |
Please provide a description of the function:def values(self):
if self.is_finite:
return np.arange(self.min, self.max + 1, dtype = self.dtype)
else:
return self.example_point | [
"\n Returns an `np.array` of type `self.dtype` containing\n some values from the domain.\n For domains where ``is_finite`` is ``True``, all elements\n of the domain will be yielded exactly once.\n\n :rtype: `np.ndarray`\n "
] |
Please provide a description of the function:def n_members(self):
return int(binom(self.n_meas + self.n_elements -1, self.n_elements - 1)) | [
"\n Returns the number of members in the domain if it\n `is_finite`, otherwise, returns `None`.\n\n :type: ``int``\n "
] |
Please provide a description of the function:def example_point(self):
return np.array([([self.n_meas] + [0] * (self.n_elements-1),)], dtype=self.dtype) | [
"\n Returns any single point guaranteed to be in the domain, but\n no other guarantees; useful for testing purposes.\n This is given as a size 1 ``np.array`` of type ``dtype``.\n\n :type: ``np.ndarray``\n "
] |
Please provide a description of the function:def values(self):
# This code comes from Jared Goguen at http://stackoverflow.com/a/37712597/1082565
partition_array = np.empty((self.n_members, self.n_elements), dtype=int)
masks = np.identity(self.n_elements, dtype=int)
for i, c in... | [
"\n Returns an `np.array` of type `self.dtype` containing\n some values from the domain.\n For domains where ``is_finite`` is ``True``, all elements\n of the domain will be yielded exactly once.\n\n :rtype: `np.ndarray`\n "
] |
Please provide a description of the function:def to_regular_array(self, A):
# this could be a static method, but we choose to be consistent with
# from_regular_array
return A.view((int, len(A.dtype.names))).reshape(A.shape + (-1,)) | [
"\n Converts from an array of type `self.dtype` to an array\n of type `int` with an additional index labeling the\n tuple indeces.\n\n :param np.ndarray A: An `np.array` of type `self.dtype`.\n\n :rtype: `np.ndarray`\n "
] |
Please provide a description of the function:def from_regular_array(self, A):
dims = A.shape[:-1]
return A.reshape((np.prod(dims),-1)).view(dtype=self.dtype).squeeze(-1).reshape(dims) | [
"\n Converts from an array of type `int` where the last index\n is assumed to have length `self.n_elements` to an array\n of type `self.d_type` with one fewer index.\n\n :param np.ndarray A: An `np.array` of type `int`.\n\n :rtype: `np.ndarray`\n "
] |
Please provide a description of the function:def in_domain(self, points):
array_view = self.to_regular_array(points)
non_negative = np.all(np.greater_equal(array_view, 0))
correct_sum = np.all(np.sum(array_view, axis=-1) == self.n_meas)
return non_negative and correct_sum | [
"\n Returns ``True`` if all of the given points are in the domain,\n ``False`` otherwise.\n\n :param np.ndarray points: An `np.ndarray` of type `self.dtype`.\n\n :rtype: `bool`\n "
] |
Please provide a description of the function:def start(self, max):
try:
self.widget.max = max
display(self.widget)
except:
pass | [
"\n Displays the progress bar for a given maximum value.\n\n :param float max: Maximum value of the progress bar.\n "
] |
Please provide a description of the function:def likelihood(self, outcomes, modelparams, expparams):
# By calling the superclass implementation, we can consolidate
# call counting there.
super(QubitStatePauliModel, self).likelihood(outcomes, modelparams, expparams)
... | [
"\n Calculates the likelihood function at the states specified \n by modelparams and measurement specified by expparams.\n This is given by the Born rule and is the probability of\n outcomes given the state and measurement operator.\n \n Parameters\n ----------\n ... |
Please provide a description of the function:def likelihood(self, outcomes, modelparams, expparams):
# By calling the superclass implementation, we can consolidate
# call counting there.
super(RebitStatePauliModel, self).likelihood(outcomes, modelparams, expparams)
... | [
"\n Calculates the likelihood function at the states specified \n by modelparams and measurement specified by expparams.\n This is given by the Born rule and is the probability of\n outcomes given the state and measurement operator.\n \n Parameters\n ----------\n ... |
Please provide a description of the function:def likelihood(self, outcomes, modelparams, expparams):
# By calling the superclass implementation, we can consolidate
# call counting there.
super(MultiQubitStatePauliModel, self).likelihood(outcomes, modelparams, expparams)
... | [
"\n Calculates the likelihood function at the states specified \n by modelparams and measurement specified by expparams.\n This is given by the Born rule and is the probability of\n outcomes given the state and measurement operator.\n "
] |
Please provide a description of the function:def simulate_experiment(self, modelparams, expparams, repeat=1):
super(PoisonedModel, self).simulate_experiment(modelparams, expparams, repeat)
return self.underlying_model.simulate_experiment(modelparams, expparams, repeat) | [
"\n Simulates experimental data according to the original (unpoisoned)\n model. Note that this explicitly causes the simulated data and the\n likelihood function to disagree. This is, strictly speaking, a violation\n of the assumptions made about `~qinfer.abstract_model.Model` subclasses... |
Please provide a description of the function:def domain(self, expparams):
return [IntegerDomain(min=0,max=n_o-1) for n_o in self.n_outcomes(expparams)] | [
"\n Returns a list of ``Domain``s, one for each input expparam.\n\n :param numpy.ndarray expparams: Array of experimental parameters. This\n array must be of dtype agreeing with the ``expparams_dtype``\n property, or, in the case where ``n_outcomes_constant`` is ``True``,\n ... |
Please provide a description of the function:def underlying_likelihood(self, binary_outcomes, modelparams, expparams):
original_mps = modelparams[..., self._orig_mps_slice]
return self.underlying_model.likelihood(binary_outcomes, original_mps, expparams) | [
"\n Given outcomes hypothesized for the underlying model, returns the likelihood\n which which those outcomes occur.\n "
] |
Please provide a description of the function:def n_outcomes(self, expparams):
# Standard combinatorial formula equal to the number of
# possible tuples whose non-negative integer entries sum to n_meas.
n = expparams['n_meas']
k = self.n_sides
return scipy.special.binom(... | [
"\n Returns an array of dtype ``uint`` describing the number of outcomes\n for each experiment specified by ``expparams``.\n \n :param numpy.ndarray expparams: Array of experimental parameters. This\n array must be of dtype agreeing with the ``expparams_dtype``\n pr... |
Please provide a description of the function:def domain(self, expparams):
return [
MultinomialDomain(n_elements=self.n_sides, n_meas=ep['n_meas'])
for ep in expparams
] | [
"\n Returns a list of :class:`Domain` objects, one for each input expparam.\n :param numpy.ndarray expparams: Array of experimental parameters. This\n array must be of dtype agreeing with the ``expparams_dtype``\n property.\n :rtype: list of ``Domain``\n "
] |
Please provide a description of the function:def est_update_covariance(self, modelparams):
if self._diagonal:
cov = (self._fixed_scale ** 2 if self._has_fixed_covariance \
else np.mean(modelparams[:, self._srw_idxs] ** 2, axis=0))
cov = np.diag(cov)
else:... | [
"\n Returns the covariance of the gaussian noise process for one \n unit step. In the case where the covariance is being learned,\n the expected covariance matrix is returned.\n \n :param modelparams: Shape `(n_models, n_modelparams)` shape array\n of model parameters.\n ... |
Please provide a description of the function:def are_expparam_dtypes_consistent(self, expparams):
if self.is_n_outcomes_constant:
# This implies that all domains are equal, so this must be true
return True
# otherwise we have to actually check all the dtypes
if ... | [
"\n Returns ``True`` iff all of the given expparams \n correspond to outcome domains with the same dtype.\n For efficiency, concrete subclasses should override this method \n if the result is always ``True``.\n\n :param np.ndarray expparams: Array of expparamms \n of t... |
Please provide a description of the function:def simulate_experiment(self, modelparams, expparams, repeat=1):
self._sim_count += modelparams.shape[0] * expparams.shape[0] * repeat
assert(self.are_expparam_dtypes_consistent(expparams)) | [
"\n Produces data according to the given model parameters and experimental\n parameters, structured as a NumPy array.\n\n :param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``\n array of model parameter vectors describing the hypotheses under\n which data sh... |
Please provide a description of the function:def distance(self, a, b):
r
return np.apply_along_axis(
lambda vec: np.linalg.norm(vec, 1),
1,
self.Q * (a - b)
) | [
"\n Gives the distance between two model parameter vectors :math:`\\vec{a}` and\n :math:`\\vec{b}`. By default, this is the vector 1-norm of the difference\n :math:`\\mathbf{Q} (\\vec{a} - \\vec{b})` rescaled by\n :attr:`~Model.Q`.\n \n :param np.ndarray a: Array of model p... |
Please provide a description of the function:def update_timestep(self, modelparams, expparams):
r
return np.tile(modelparams, (expparams.shape[0],1,1)).transpose((1,2,0)) | [
"\n Returns a set of model parameter vectors that is the update of an\n input set of model parameter vectors, such that the new models are\n conditioned on a particular experiment having been performed.\n By default, this is the trivial function\n :math:`\\vec{x}(t_{k+1}) = \\vec{... |
Please provide a description of the function:def likelihood(self, outcomes, modelparams, expparams):
r
# Count the number of times the inner-most loop is called.
self._call_count += (
safe_shape(outcomes) * safe_shape(modelparams) * safe_shape(expparams)
) | [
"\n Calculates the probability of each given outcome, conditioned on each\n given model parameter vector and each given experimental control setting.\n\n :param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``\n array of model parameter vectors describing the hypotheses ... |
Please provide a description of the function:def domain(self, expparams):
# As a convenience to most users, we define domain for them. If a
# fancier domain is desired, this method can easily be overridden.
if self.is_n_outcomes_constant:
return self._domain if expparams is... | [
"\n Returns a list of :class:`Domain` objects, one for each input expparam.\n\n :param numpy.ndarray expparams: Array of experimental parameters. This\n array must be of dtype agreeing with the ``expparams_dtype``\n property, or, in the case where ``n_outcomes_constant`` is ``Tr... |
Please provide a description of the function:def pr0_to_likelihood_array(outcomes, pr0):
pr0 = pr0[np.newaxis, ...]
pr1 = 1 - pr0
if len(np.shape(outcomes)) == 0:
outcomes = np.array(outcomes)[None]
return np.concatenate([
pr0 if out... | [
"\n Assuming a two-outcome measurement with probabilities given by the\n array ``pr0``, returns an array of the form expected to be returned by\n ``likelihood`` method.\n \n :param numpy.ndarray outcomes: Array of integers indexing outcomes.\n :param numpy.ndarray pr0: Arra... |
Please provide a description of the function:def fisher_information(self, modelparams, expparams):
if self.is_n_outcomes_constant:
outcomes = np.arange(self.n_outcomes(expparams))
scores, L = self.score(outcomes, modelparams, expparams, return_L=True)
... | [
"\n Returns the covariance of the score taken over possible outcomes,\n known as the Fisher information.\n \n The result is represented as the four-index tensor\n ``fisher[idx_modelparam_i, idx_modelparam_j, idx_model, idx_experiment]``,\n which gives the Fisher information... |
Please provide a description of the function:def get_qutip_module(required_version='3.2'):
try:
import qutip as qt
from distutils.version import LooseVersion
_qt_version = LooseVersion(qt.version.version)
if _qt_version < LooseVersion(required_version):
return None
... | [
"\n Attempts to return the qutip module, but\n silently returns ``None`` if it can't be\n imported, or doesn't have version at\n least ``required_version``.\n\n :param str required_version: Valid input to\n ``distutils.version.LooseVersion``.\n :return: The qutip module or ``None``.\n :r... |
Please provide a description of the function:def multinomial_pdf(n,p):
r
# work in log space to avoid overflow
log_N_fac = gammaln(np.sum(n, axis=0) + 1)[np.newaxis,...]
log_n_fac_sum = np.sum(gammaln(n + 1), axis=0)
# since working in log space, we need special
# consideration at p=0. deal wi... | [
"\n Returns the PDF of the multinomial distribution\n :math:`\\operatorname{Multinomial}(N, n, p)=\n \\frac{N!}{n_1!\\cdots n_k!}p_1^{n_1}\\cdots p_k^{n_k}`\n\n :param np.ndarray n : Array of outcome integers\n of shape ``(sides, ...)`` where sides is the number of\n sides on the dice ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.