_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q262700 | listify | validation | def listify(a):
"""
Convert a scalar ``a`` to a list and all iterables to list as well.
Examples
--------
>>> listify(0)
[0]
>>> listify([1,2,3])
[1, 2, 3]
>>> listify('a')
['a']
>>> listify(np.array([1,2,3]))
[1, 2, 3]
>>> listify('string')
['string']
""... | python | {
"resource": ""
} |
q262701 | delistify | validation | def delistify(a, b=None):
"""
If a single element list, extract the element as an object, otherwise
leave as it is.
Examples
--------
>>> delistify('string')
'string'
>>> delistify(['string'])
'string'
>>> delistify(['string', 'other'])
['string', 'other']
>>> delisti... | python | {
"resource": ""
} |
q262702 | aN | validation | def aN(a, dim=3, dtype='int'):
"""
Convert an integer or iterable list to numpy array of length dim. This func
is used to allow other methods to take both scalars non-numpy arrays with
flexibility.
Parameters
----------
a : number, iterable, array-like
The object to convert to numpy... | python | {
"resource": ""
} |
q262703 | patch_docs | validation | def patch_docs(subclass, superclass):
"""
Apply the documentation from ``superclass`` to ``subclass`` by filling
in all overridden member function docstrings with those from the
parent class
"""
funcs0 = inspect.getmembers(subclass, predicate=inspect.ismethod)
funcs1 = inspect.getmembers(sup... | python | {
"resource": ""
} |
q262704 | Tile.slicer | validation | def slicer(self):
"""
Array slicer object for this tile
>>> Tile((2,3)).slicer
(slice(0, 2, None), slice(0, 3, None))
>>> np.arange(10)[Tile((4,)).slicer]
array([0, 1, 2, 3])
"""
return tuple(np.s_[l:r] for l,r in zip(*self.bounds)) | python | {
"resource": ""
} |
q262705 | Tile.oslicer | validation | def oslicer(self, tile):
""" Opposite slicer, the outer part wrt to a field """
mask = None
vecs = tile.coords(form='meshed')
for v in vecs:
v[self.slicer] = -1
mask = mask & (v > 0) if mask is not None else (v>0)
return tuple(np.array(i).astype('int') for... | python | {
"resource": ""
} |
q262706 | Tile.corners | validation | def corners(self):
"""
Iterate the vector of all corners of the hyperrectangles
>>> Tile(3, dim=2).corners
array([[0, 0],
[0, 3],
[3, 0],
[3, 3]])
"""
corners = []
for ind in itertools.product(*((0,1),)*self.dim):
... | python | {
"resource": ""
} |
q262707 | Tile._format_vector | validation | def _format_vector(self, vecs, form='broadcast'):
"""
Format a 3d vector field in certain ways, see `coords` for a description
of each formatting method.
"""
if form == 'meshed':
return np.meshgrid(*vecs, indexing='ij')
elif form == 'vector':
vecs ... | python | {
"resource": ""
} |
q262708 | Tile.coords | validation | def coords(self, norm=False, form='broadcast'):
"""
Returns the coordinate vectors associated with the tile.
Parameters
-----------
norm : boolean
can rescale the coordinates for you. False is no rescaling, True is
rescaling so that all coordinates are fr... | python | {
"resource": ""
} |
q262709 | Tile.kvectors | validation | def kvectors(self, norm=False, form='broadcast', real=False, shift=False):
"""
Return the kvectors associated with this tile, given the standard form
of -0.5 to 0.5. `norm` and `form` arguments arethe same as that passed to
`Tile.coords`.
Parameters
-----------
r... | python | {
"resource": ""
} |
q262710 | Tile.contains | validation | def contains(self, items, pad=0):
"""
Test whether coordinates are contained within this tile.
Parameters
----------
items : ndarray [3] or [N, 3]
N coordinates to check are within the bounds of the tile
pad : integer or ndarray [3]
anisotropic p... | python | {
"resource": ""
} |
q262711 | Tile.intersection | validation | def intersection(tiles, *args):
"""
Intersection of tiles, returned as a tile
>>> Tile.intersection(Tile([0, 1], [5, 4]), Tile([1, 0], [4, 5]))
Tile [1, 1] -> [4, 4] ([3, 3])
"""
tiles = listify(tiles) + listify(args)
if len(tiles) < 2:
return tiles[... | python | {
"resource": ""
} |
q262712 | Tile.translate | validation | def translate(self, dr):
"""
Translate a tile by an amount dr
>>> Tile(5).translate(1)
Tile [1, 1, 1] -> [6, 6, 6] ([5, 5, 5])
"""
tile = self.copy()
tile.l += dr
tile.r += dr
return tile | python | {
"resource": ""
} |
q262713 | Tile.pad | validation | def pad(self, pad):
"""
Pad this tile by an equal amount on each side as specified by pad
>>> Tile(10).pad(2)
Tile [-2, -2, -2] -> [12, 12, 12] ([14, 14, 14])
>>> Tile(10).pad([1,2,3])
Tile [-1, -2, -3] -> [11, 12, 13] ([12, 14, 16])
"""
tile = self.copy... | python | {
"resource": ""
} |
q262714 | Image.filtered_image | validation | def filtered_image(self, im):
"""Returns a filtered image after applying the Fourier-space filters"""
q = np.fft.fftn(im)
for k,v in self.filters:
q[k] -= v
return np.real(np.fft.ifftn(q)) | python | {
"resource": ""
} |
q262715 | Image.set_filter | validation | def set_filter(self, slices, values):
"""
Sets Fourier-space filters for the image. The image is filtered by
subtracting values from the image at slices.
Parameters
----------
slices : List of indices or slice objects.
The q-values in Fourier space to filter.... | python | {
"resource": ""
} |
q262716 | RawImage.load_image | validation | def load_image(self):
""" Read the file and perform any transforms to get a loaded image """
try:
image = initializers.load_tiff(self.filename)
image = initializers.normalize(
image, invert=self.invert, scale=self.exposure,
dtype=self.float_precisi... | python | {
"resource": ""
} |
q262717 | RawImage.get_scale_from_raw | validation | def get_scale_from_raw(raw, scaled):
"""
When given a raw image and the scaled version of the same image, it
extracts the ``exposure`` parameters associated with those images.
This is useful when
Parameters
----------
raw : array_like
The image loaded... | python | {
"resource": ""
} |
q262718 | ProgressBar._draw | validation | def _draw(self):
""" Interal draw method, simply prints to screen """
if self.display:
print(self._formatstr.format(**self.__dict__), end='')
sys.stdout.flush() | python | {
"resource": ""
} |
q262719 | ProgressBar.update | validation | def update(self, value=0):
"""
Update the value of the progress and update progress bar.
Parameters
-----------
value : integer
The current iteration of the progress
"""
self._deltas.append(time.time())
self.value = value
self._percen... | python | {
"resource": ""
} |
q262720 | Model.check_consistency | validation | def check_consistency(self):
"""
Make sure that the required comps are included in the list of
components supplied by the user. Also check that the parameters are
consistent across the many components.
"""
error = False
regex = re.compile('([a-zA-Z_][a-zA-Z0-9_]*)... | python | {
"resource": ""
} |
q262721 | Model.check_inputs | validation | def check_inputs(self, comps):
"""
Check that the list of components `comp` is compatible with both the
varmap and modelstr for this Model
"""
error = False
compcats = [c.category for c in comps]
# Check that the components are all provided, given the categories
... | python | {
"resource": ""
} |
q262722 | lbl | validation | def lbl(axis, label, size=22):
""" Put a figure label in an axis """
at = AnchoredText(label, loc=2, prop=dict(size=size), frameon=True)
at.patch.set_boxstyle("round,pad=0.,rounding_size=0.0")
#bb = axis.get_yaxis_transform()
#at = AnchoredText(label,
# loc=3, prop=dict(size=18), frameon=... | python | {
"resource": ""
} |
q262723 | examine_unexplained_noise | validation | def examine_unexplained_noise(state, bins=1000, xlim=(-10,10)):
"""
Compares a state's residuals in real and Fourier space with a Gaussian.
Point out that Fourier space should always be Gaussian and white
Parameters
----------
state : `peri.states.State`
The state to examine.
... | python | {
"resource": ""
} |
q262724 | compare_data_model_residuals | validation | def compare_data_model_residuals(s, tile, data_vmin='calc', data_vmax='calc',
res_vmin=-0.1, res_vmax=0.1, edgepts='calc', do_imshow=True,
data_cmap=plt.cm.bone, res_cmap=plt.cm.RdBu):
"""
Compare the data, model, and residuals of a state.
Makes an image of any 2D slice of a state that co... | python | {
"resource": ""
} |
q262725 | trisect_image | validation | def trisect_image(imshape, edgepts='calc'):
"""
Returns 3 masks that trisect an image into 3 triangular portions.
Parameters
----------
imshape : 2-element list-like of ints
The shape of the image. Elements after the first 2 are ignored.
edgepts : Nested list-like, float, o... | python | {
"resource": ""
} |
q262726 | sim_crb_diff | validation | def sim_crb_diff(std0, std1, N=10000):
""" each element of std0 should correspond with the element of std1 """
a = std0*np.random.randn(N, len(std0))
b = std1*np.random.randn(N, len(std1))
return a - b | python | {
"resource": ""
} |
q262727 | twoslice | validation | def twoslice(field, center=None, size=6.0, cmap='bone_r', vmin=0, vmax=1,
orientation='vertical', figpad=1.09, off=0.01):
"""
Plot two parts of the ortho view, the two sections given by ``orientation``.
"""
center = center or [i//2 for i in field.shape]
slices = []
for i,c in enumerate(c... | python | {
"resource": ""
} |
q262728 | circles | validation | def circles(st, layer, axis, ax=None, talpha=1.0, cedge='white', cface='white'):
"""
Plots a set of circles corresponding to a slice through the platonic
structure. Copied from twoslice_overlay with comments, standaloneness.
Inputs
------
pos : array of particle positions; [N,3]
rad... | python | {
"resource": ""
} |
q262729 | missing_particle | validation | def missing_particle(separation=0.0, radius=RADIUS, SNR=20):
""" create a two particle state and compare it to featuring using a single particle guess """
# create a base image of one particle
s = init.create_two_particle_state(imsize=6*radius+4, axis='x', sigma=1.0/SNR,
delta=separation, radius... | python | {
"resource": ""
} |
q262730 | name_globals | validation | def name_globals(s, remove_params=None):
"""
Returns a list of the global parameter names.
Parameters
----------
s : :class:`peri.states.ImageState`
The state to name the globals of.
remove_params : Set or None
A set of unique additional parameters to remove from... | python | {
"resource": ""
} |
q262731 | get_num_px_jtj | validation | def get_num_px_jtj(s, nparams, decimate=1, max_mem=1e9, min_redundant=20):
"""
Calculates the number of pixels to use for J at a given memory usage.
Tries to pick a number of pixels as (size of image / `decimate`).
However, clips this to a maximum size and minimum size to ensure that
(1) too much m... | python | {
"resource": ""
} |
q262732 | vectorize_damping | validation | def vectorize_damping(params, damping=1.0, increase_list=[['psf-', 1e4]]):
"""
Returns a non-constant damping vector, allowing certain parameters to be
more strongly damped than others.
Parameters
----------
params : List
The list of parameter names, in order.
damping : ... | python | {
"resource": ""
} |
q262733 | find_particles_in_tile | validation | def find_particles_in_tile(positions, tile):
"""
Finds the particles in a tile, as numpy.ndarray of ints.
Parameters
----------
positions : `numpy.ndarray`
[N,3] array of the particle positions to check in the tile
tile : :class:`peri.util.Tile` instance
Tile of ... | python | {
"resource": ""
} |
q262734 | separate_particles_into_groups | validation | def separate_particles_into_groups(s, region_size=40, bounds=None,
doshift=False):
"""
Separates particles into convenient groups for optimization.
Given a state, returns a list of groups of particles. Each group of
particles are located near each other in the image. Every particle
located ... | python | {
"resource": ""
} |
q262735 | _check_groups | validation | def _check_groups(s, groups):
"""Ensures that all particles are included in exactly 1 group"""
ans = []
for g in groups:
ans.extend(g)
if np.unique(ans).size != np.size(ans):
return False
elif np.unique(ans).size != s.obj_get_positions().shape[0]:
return False
else:
... | python | {
"resource": ""
} |
q262736 | calc_particle_group_region_size | validation | def calc_particle_group_region_size(s, region_size=40, max_mem=1e9, **kwargs):
"""
Finds the biggest region size for LM particle optimization with a
given memory constraint.
Input Parameters
----------------
s : :class:`peri.states.ImageState`
The state with the particles
... | python | {
"resource": ""
} |
q262737 | get_residuals_update_tile | validation | def get_residuals_update_tile(st, padded_tile):
"""
Translates a tile in the padded image to the unpadded image.
Given a state and a tile that corresponds to the padded image, returns
a tile that corresponds to the the corresponding pixels of the difference
image
Parameters
----------
... | python | {
"resource": ""
} |
q262738 | find_best_step | validation | def find_best_step(err_vals):
"""
Returns the index of the lowest of the passed values. Catches nans etc.
"""
if np.all(np.isnan(err_vals)):
raise ValueError('All err_vals are nans!')
return np.nanargmin(err_vals) | python | {
"resource": ""
} |
q262739 | do_levmarq | validation | def do_levmarq(s, param_names, damping=0.1, decrease_damp_factor=10.,
run_length=6, eig_update=True, collect_stats=False, rz_order=0,
run_type=2, **kwargs):
"""
Runs Levenberg-Marquardt optimization on a state.
Convenience wrapper for LMGlobals. Same keyword args, but the defaults
have ... | python | {
"resource": ""
} |
q262740 | do_levmarq_particles | validation | def do_levmarq_particles(s, particles, damping=1.0, decrease_damp_factor=10.,
run_length=4, collect_stats=False, max_iter=2, **kwargs):
"""
Levenberg-Marquardt optimization on a set of particles.
Convenience wrapper for LMParticles. Same keyword args, but the
defaults have been set to useful va... | python | {
"resource": ""
} |
q262741 | do_levmarq_all_particle_groups | validation | def do_levmarq_all_particle_groups(s, region_size=40, max_iter=2, damping=1.0,
decrease_damp_factor=10., run_length=4, collect_stats=False, **kwargs):
"""
Levenberg-Marquardt optimization for every particle in the state.
Convenience wrapper for LMParticleGroupCollection. Same keyword args,
but ... | python | {
"resource": ""
} |
q262742 | do_levmarq_n_directions | validation | def do_levmarq_n_directions(s, directions, max_iter=2, run_length=2,
damping=1e-3, collect_stats=False, marquardt_damping=True, **kwargs):
"""
Optimization of a state along a specific set of directions in parameter
space.
Parameters
----------
s : :class:`peri.states.State`
... | python | {
"resource": ""
} |
q262743 | finish | validation | def finish(s, desc='finish', n_loop=4, max_mem=1e9, separate_psf=True,
fractol=1e-7, errtol=1e-3, dowarn=True):
"""
Crawls slowly to the minimum-cost state.
Blocks the global parameters into small enough sections such that each
can be optimized separately while including all the pixels (i.e. no... | python | {
"resource": ""
} |
q262744 | fit_comp | validation | def fit_comp(new_comp, old_comp, **kwargs):
"""
Fits a new component to an old component
Calls do_levmarq to match the .get() fields of the two objects. The
parameters of new_comp are modified in place.
Parameters
----------
new_comp : :class:`peri.comps.comp`
The new object, whose... | python | {
"resource": ""
} |
q262745 | LMEngine.reset | validation | def reset(self, new_damping=None):
"""
Keeps all user supplied options the same, but resets counters etc.
"""
self._num_iter = 0
self._inner_run_counter = 0
self._J_update_counter = self.update_J_frequency
self._fresh_JTJ = False
self._has_run = False
... | python | {
"resource": ""
} |
q262746 | LMEngine.do_run_1 | validation | def do_run_1(self):
"""
LM run, evaluating 1 step at a time.
Broyden or eigendirection updates replace full-J updates until
a full-J update occurs. Does not run with the calculated J (no
internal run).
"""
while not self.check_terminate():
self._has_r... | python | {
"resource": ""
} |
q262747 | LMEngine._run1 | validation | def _run1(self):
"""workhorse for do_run_1"""
if self.check_update_J():
self.update_J()
else:
if self.check_Broyden_J():
self.update_Broyden_J()
if self.check_update_eig_J():
self.update_eig_J()
#1. Assuming that J star... | python | {
"resource": ""
} |
q262748 | LMEngine._run2 | validation | def _run2(self):
"""Workhorse for do_run_2"""
if self.check_update_J():
self.update_J()
else:
if self.check_Broyden_J():
self.update_Broyden_J()
if self.check_update_eig_J():
self.update_eig_J()
#0. Find _last_residuals... | python | {
"resource": ""
} |
q262749 | LMEngine.do_internal_run | validation | def do_internal_run(self, initial_count=0, subblock=None, update_derr=True):
"""
Takes more steps without calculating J again.
Given a fixed damping, J, JTJ, iterates calculating steps, with
optional Broyden or eigendirection updates. Iterates either until
a bad step is taken or... | python | {
"resource": ""
} |
q262750 | LMEngine.find_LM_updates | validation | def find_LM_updates(self, grad, do_correct_damping=True, subblock=None):
"""
Calculates LM updates, with or without the acceleration correction.
Parameters
----------
grad : numpy.ndarray
The gradient of the model cost.
do_correct_damping : Bool, ... | python | {
"resource": ""
} |
q262751 | LMEngine.update_param_vals | validation | def update_param_vals(self, new_vals, incremental=False):
"""
Updates the current set of parameter values and previous values,
sets a flag to re-calculate J.
Parameters
----------
new_vals : numpy.ndarray
The new values to update to
increm... | python | {
"resource": ""
} |
q262752 | LMEngine.get_termination_stats | validation | def get_termination_stats(self, get_cos=True):
"""
Returns a dict of termination statistics
Parameters
----------
get_cos : Bool, optional
Whether or not to calcualte the cosine of the residuals
with the tangent plane of the model using the cu... | python | {
"resource": ""
} |
q262753 | LMEngine.check_completion | validation | def check_completion(self):
"""
Returns a Bool of whether the algorithm has found a satisfactory minimum
"""
terminate = False
term_dict = self.get_termination_stats(get_cos=self.costol is not None)
terminate |= np.all(np.abs(term_dict['delta_vals']) < self.paramtol)
... | python | {
"resource": ""
} |
q262754 | LMEngine.check_terminate | validation | def check_terminate(self):
"""
Returns a Bool of whether to terminate.
Checks whether a satisfactory minimum has been found or whether
too many iterations have occurred.
"""
if not self._has_run:
return False
else:
#1-3. errtol, paramtol, ... | python | {
"resource": ""
} |
q262755 | LMEngine.check_update_J | validation | def check_update_J(self):
"""
Checks if the full J should be updated.
Right now, just updates after update_J_frequency loops
"""
self._J_update_counter += 1
update = self._J_update_counter >= self.update_J_frequency
return update & (not self._fresh_JTJ) | python | {
"resource": ""
} |
q262756 | LMEngine.update_J | validation | def update_J(self):
"""Updates J, JTJ, and internal counters."""
self.calc_J()
# np.dot(j, j.T) is slightly faster but 2x as much mem
step = np.ceil(1e-2 * self.J.shape[1]).astype('int') # 1% more mem...
self.JTJ = low_mem_sq(self.J, step=step)
#copies still, since J is ... | python | {
"resource": ""
} |
q262757 | LMEngine.update_Broyden_J | validation | def update_Broyden_J(self):
"""Execute a Broyden update of J"""
CLOG.debug('Broyden update.')
delta_vals = self.param_vals - self._last_vals
delta_residuals = self.calc_residuals() - self._last_residuals
nrm = np.sqrt(np.dot(delta_vals, delta_vals))
direction = delta_vals... | python | {
"resource": ""
} |
q262758 | LMEngine.update_eig_J | validation | def update_eig_J(self):
"""Execute an eigen update of J"""
CLOG.debug('Eigen update.')
vls, vcs = np.linalg.eigh(self.JTJ)
res0 = self.calc_residuals()
for a in range(min([self.num_eig_dirs, vls.size])):
#1. Finding stiff directions
stif_dir = vcs[-(a+1)] ... | python | {
"resource": ""
} |
q262759 | LMEngine.calc_accel_correction | validation | def calc_accel_correction(self, damped_JTJ, delta0):
"""
Geodesic acceleration correction to the LM step.
Parameters
----------
damped_JTJ : numpy.ndarray
The damped JTJ used to calculate the initial step.
delta0 : numpy.ndarray
Th... | python | {
"resource": ""
} |
q262760 | LMFunction.calc_J | validation | def calc_J(self):
"""Updates self.J, returns nothing"""
del self.J
self.J = np.zeros([self.param_vals.size, self.data.size])
dp = np.zeros_like(self.param_vals)
f0 = self.model.copy()
for a in range(self.param_vals.size):
dp *= 0
dp[a] = self.dl[a]... | python | {
"resource": ""
} |
q262761 | LMFunction.update_function | validation | def update_function(self, param_vals):
"""Takes an array param_vals, updates function, returns the new error"""
self.model = self.func(param_vals, *self.func_args, **self.func_kwargs)
d = self.calc_residuals()
return np.dot(d.flat, d.flat) | python | {
"resource": ""
} |
q262762 | LMOptObj.update_function | validation | def update_function(self, param_vals):
"""Updates the opt_obj, returns new error."""
self.opt_obj.update_function(param_vals)
return self.opt_obj.get_error() | python | {
"resource": ""
} |
q262763 | OptState.calc_J | validation | def calc_J(self):
"""Calculates J along the direction."""
r0 = self.state.residuals.copy().ravel()
dl = np.zeros(self.param_vals.size)
p0 = self.param_vals.copy()
J = []
for a in range(self.param_vals.size):
dl *= 0
dl[a] += self.dl
sel... | python | {
"resource": ""
} |
q262764 | LMParticleGroupCollection.reset | validation | def reset(self, new_region_size=None, do_calc_size=True, new_damping=None,
new_max_mem=None):
"""
Resets the particle groups and optionally the region size and damping.
Parameters
----------
new_region_size : : Int or 3-element list-like of ints, optional
... | python | {
"resource": ""
} |
q262765 | LMParticleGroupCollection._do_run | validation | def _do_run(self, mode='1'):
"""workhorse for the self.do_run_xx methods."""
for a in range(len(self.particle_groups)):
group = self.particle_groups[a]
lp = LMParticles(self.state, group, **self._kwargs)
if mode == 'internal':
lp.J, lp.JTJ, lp._dif_til... | python | {
"resource": ""
} |
q262766 | LMParticleGroupCollection.do_internal_run | validation | def do_internal_run(self):
"""Calls LMParticles.do_internal_run for each group of particles."""
if not self.save_J:
raise RuntimeError('self.save_J=True required for do_internal_run()')
if not np.all(self._has_saved_J):
raise RuntimeError('J, JTJ have not been pre-compute... | python | {
"resource": ""
} |
q262767 | AugmentedState.reset | validation | def reset(self):
"""
Resets the initial radii used for updating the particles. Call
if any of the particle radii or positions have been changed
external to the augmented state.
"""
inds = list(range(self.state.obj_get_positions().shape[0]))
self._rad_nms = self.st... | python | {
"resource": ""
} |
q262768 | LMAugmentedState.reset | validation | def reset(self, **kwargs):
"""Resets the aug_state and the LMEngine"""
self.aug_state.reset()
super(LMAugmentedState, self).reset(**kwargs) | python | {
"resource": ""
} |
q262769 | Link.get_shares | validation | def get_shares(self):
'''
Returns an object with a the numbers of shares a link has had using
Buffer.
www will be stripped, but other subdomains will not.
'''
self.shares = self.api.get(url=PATHS['GET_SHARES'] % self.url)['shares']
return self.shares | python | {
"resource": ""
} |
q262770 | sample | validation | def sample(field, inds=None, slicer=None, flat=True):
"""
Take a sample from a field given flat indices or a shaped slice
Parameters
-----------
inds : list of indices
One dimensional (raveled) indices to return from the field
slicer : slice object
A shaped (3D) slicer that ret... | python | {
"resource": ""
} |
q262771 | State.update | validation | def update(self, params, values):
"""
Update a single parameter or group of parameters ``params``
with ``values``.
Parameters
----------
params : string or list of strings
Parameter names which to update
value : number or list of numbers
... | python | {
"resource": ""
} |
q262772 | State.build_funcs | validation | def build_funcs(self):
"""
Here, we build gradient and hessian functions based on the properties
of a state that are generally wanted. For each one, we fill in _grad or
_hess with a function that takes care of various options such as
slicing and flattening. For example, `m` below... | python | {
"resource": ""
} |
q262773 | ImageState.set_model | validation | def set_model(self, mdl):
"""
Setup the image model formation equation and corresponding objects into
their various objects. `mdl` is a `peri.models.Model` object
"""
self.mdl = mdl
self.mdl.check_inputs(self.comps)
for c in self.comps:
setattr(self, ... | python | {
"resource": ""
} |
q262774 | ImageState.model_to_data | validation | def model_to_data(self, sigma=0.0):
""" Switch out the data for the model's recreation of the data. """
im = self.model.copy()
im += sigma*np.random.randn(*im.shape)
self.set_image(util.NullImage(image=im)) | python | {
"resource": ""
} |
q262775 | ImageState.get_update_io_tiles | validation | def get_update_io_tiles(self, params, values):
"""
Get the tiles corresponding to a particular section of image needed to
be updated. Inputs are the parameters and values. Returned is the
padded tile, inner tile, and slicer to go between, but accounting for
wrap with the edge of ... | python | {
"resource": ""
} |
q262776 | ImageState.get | validation | def get(self, name):
""" Return component by category name """
for c in self.comps:
if c.category == name:
return c
return None | python | {
"resource": ""
} |
q262777 | ImageState._calc_loglikelihood | validation | def _calc_loglikelihood(self, model=None, tile=None):
"""Allows for fast local updates of log-likelihood"""
if model is None:
res = self.residuals
else:
res = model - self._data[tile.slicer]
sig, isig = self.sigma, 1.0/self.sigma
nlogs = -np.log(np.sqrt(2... | python | {
"resource": ""
} |
q262778 | ImageState.update_from_model_change | validation | def update_from_model_change(self, oldmodel, newmodel, tile):
"""
Update various internal variables from a model update from oldmodel to
newmodel for the tile `tile`
"""
self._loglikelihood -= self._calc_loglikelihood(oldmodel, tile=tile)
self._loglikelihood += self._calc... | python | {
"resource": ""
} |
q262779 | ImageState.set_mem_level | validation | def set_mem_level(self, mem_level='hi'):
"""
Sets the memory usage level of the state.
Parameters
----------
mem_level : string
Can be set to one of:
* hi : all mem's are np.float64
* med-hi : image, platonic are float32, rest ar... | python | {
"resource": ""
} |
q262780 | scramble_positions | validation | def scramble_positions(p, delete_frac=0.1):
"""randomly deletes particles and adds 1-px noise for a realistic
initial featuring guess"""
probs = [1-delete_frac, delete_frac]
m = np.random.choice([True, False], p.shape[0], p=probs)
jumble = np.random.randn(m.sum(), 3)
return p[m] + jumble | python | {
"resource": ""
} |
q262781 | create_img | validation | def create_img():
"""Creates an image, as a `peri.util.Image`, which is similar
to the image in the tutorial"""
# 1. particles + coverslip
rad = 0.5 * np.random.randn(POS.shape[0]) + 4.5 # 4.5 +- 0.5 px particles
part = objs.PlatonicSpheresCollection(POS, rad, zscale=0.89)
slab = objs.Slab(zpos... | python | {
"resource": ""
} |
q262782 | ParameterGroup.get_values | validation | def get_values(self, params):
"""
Get the value of a list or single parameter.
Parameters
----------
params : string, list of string
name of parameters which to retrieve
"""
return util.delistify(
[self.param_dict[p] for p in util.listify(... | python | {
"resource": ""
} |
q262783 | Component.set_shape | validation | def set_shape(self, shape, inner):
"""
Set the overall shape of the calculation area. The total shape of that
the calculation can possibly occupy, in pixels. The second, inner, is
the region of interest within the image.
"""
if self.shape != shape or self.inner != inner:
... | python | {
"resource": ""
} |
q262784 | Component.trigger_update | validation | def trigger_update(self, params, values):
""" Notify parent of a parameter change """
if self._parent:
self._parent.trigger_update(params, values)
else:
self.update(params, values) | python | {
"resource": ""
} |
q262785 | ComponentCollection.get | validation | def get(self):
""" Combine the fields from all components """
fields = [c.get() for c in self.comps]
return self.field_reduce_func(fields) | python | {
"resource": ""
} |
q262786 | ComponentCollection.set_shape | validation | def set_shape(self, shape, inner):
""" Set the shape for all components """
for c in self.comps:
c.set_shape(shape, inner) | python | {
"resource": ""
} |
q262787 | ComponentCollection.sync_params | validation | def sync_params(self):
""" Ensure that shared parameters are the same value everywhere """
def _normalize(comps, param):
vals = [c.get_values(param) for c in comps]
diff = any([vals[i] != vals[i+1] for i in range(len(vals)-1)])
if diff:
for c in comps... | python | {
"resource": ""
} |
q262788 | ComponentCollection.setup_passthroughs | validation | def setup_passthroughs(self):
"""
Inherit some functions from the components that we own. In particular,
let's grab all functions that begin with `param_` so the super class
knows how to get parameter groups. Also, take anything that is listed
under Component.exports and rename w... | python | {
"resource": ""
} |
q262789 | read_environment | validation | def read_environment():
""" Read all environment variables to see if they contain PERI """
out = {}
for k,v in iteritems(os.environ):
if transform(k) in default_conf:
out[transform(k)] = v
return out | python | {
"resource": ""
} |
q262790 | get_group_name | validation | def get_group_name(id_group):
"""Used for breadcrumb dynamic_list_constructor."""
group = Group.query.get(id_group)
if group is not None:
return group.name | python | {
"resource": ""
} |
q262791 | index | validation | def index():
"""List all user memberships."""
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 5, type=int)
q = request.args.get('q', '')
groups = Group.query_by_user(current_user, eager=True)
if q:
groups = Group.search(groups, q)
groups = groups... | python | {
"resource": ""
} |
q262792 | requests | validation | def requests():
"""List all pending memberships, listed only for group admins."""
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 5, type=int)
memberships = Membership.query_requests(current_user, eager=True).all()
return render_template(
'invenio_groups... | python | {
"resource": ""
} |
q262793 | invitations | validation | def invitations():
"""List all user pending memberships."""
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 5, type=int)
memberships = Membership.query_invitations(current_user, eager=True).all()
return render_template(
'invenio_groups/pending.html',
... | python | {
"resource": ""
} |
q262794 | new | validation | def new():
"""Create new group."""
form = GroupForm(request.form)
if form.validate_on_submit():
try:
group = Group.create(admins=[current_user], **form.data)
flash(_('Group "%(name)s" created', name=group.name), 'success')
return redirect(url_for(".index"))
... | python | {
"resource": ""
} |
q262795 | manage | validation | def manage(group_id):
"""Manage your group."""
group = Group.query.get_or_404(group_id)
form = GroupForm(request.form, obj=group)
if form.validate_on_submit():
if group.can_edit(current_user):
try:
group.update(**form.data)
flash(_('Group "%(name)s" w... | python | {
"resource": ""
} |
q262796 | delete | validation | def delete(group_id):
"""Delete group."""
group = Group.query.get_or_404(group_id)
if group.can_edit(current_user):
try:
group.delete()
except Exception as e:
flash(str(e), "error")
return redirect(url_for(".index"))
flash(_('Successfully removed... | python | {
"resource": ""
} |
q262797 | members | validation | def members(group_id):
"""List user group members."""
page = request.args.get('page', 1, type=int)
per_page = request.args.get('per_page', 5, type=int)
q = request.args.get('q', '')
s = request.args.get('s', '')
group = Group.query.get_or_404(group_id)
if group.can_see_members(current_user)... | python | {
"resource": ""
} |
q262798 | leave | validation | def leave(group_id):
"""Leave group."""
group = Group.query.get_or_404(group_id)
if group.can_leave(current_user):
try:
group.remove_member(current_user)
except Exception as e:
flash(str(e), "error")
return redirect(url_for('.index'))
flash(
... | python | {
"resource": ""
} |
q262799 | approve | validation | def approve(group_id, user_id):
"""Approve a user."""
membership = Membership.query.get_or_404((user_id, group_id))
group = membership.group
if group.can_edit(current_user):
try:
membership.accept()
except Exception as e:
flash(str(e), 'error')
return... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.