Search is not available for this dataset
text
stringlengths
75
104k
def low_mem_sq(m, step=100000): """np.dot(m, m.T) with low mem usage, by doing it in small steps""" if not m.flags.c_contiguous: raise ValueError('m must be C ordered for this to work with less mem.') # -- can make this even faster with pre-allocating arrays, but not worth it # right now # m...
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 ...
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 ...
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: ...
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 ...
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 ---------- ...
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)
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 ...
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...
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 ...
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` ...
def burn(s, n_loop=6, collect_stats=False, desc='', rz_order=0, fractol=1e-4, errtol=1e-2, mode='burn', max_mem=1e9, include_rad=True, do_line_min='default', partial_log=False, dowarn=True): """ Optimizes all the parameters of a state. Burns a state through calling LMParticleGroupCollection...
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...
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...
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 ...
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...
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...
def do_run_2(self): """ LM run evaluating 2 steps (damped and not) and choosing the best. After finding the best of 2 steps, runs with that damping + Broyden or eigendirection updates, until deciding to do a full-J update. Only changes damping after full-J updates. """ ...
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...
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...
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, ...
def _calc_lm_step(self, damped_JTJ, grad, subblock=None): """Calculates a Levenberg-Marquard step w/o acceleration""" delta0, res, rank, s = np.linalg.lstsq(damped_JTJ, -0.5*grad, rcond=self.min_eigval) if self._fresh_JTJ: CLOG.debug('%d degenerate of %d total directi...
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...
def find_expected_error(self, delta_params='calc'): """ Returns the error expected after an update if the model were linear. Parameters ---------- delta_params : {numpy.ndarray, 'calc', or 'perfect'}, optional The relative change in parameters. If 'calc', use...
def calc_model_cosine(self, decimate=None, mode='err'): """ Calculates the cosine of the residuals with the model. Parameters ---------- decimate : Int or None, optional Decimate the residuals by `decimate` pixels. If None, no decimation is us...
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...
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) ...
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, ...
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)
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 ...
def calc_grad(self): """The gradient of the cost w.r.t. the parameters.""" residuals = self.calc_residuals() return 2*np.dot(self.J, residuals)
def _rank_1_J_update(self, direction, values): """ Does J += np.outer(direction, new_values - old_values) without using lots of memory """ vals_to_sub = np.dot(direction, self.J) delta_vals = values - vals_to_sub for a in range(direction.size): self.J[...
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...
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)] ...
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...
def update_select_J(self, blk): """ Updates J only for certain parameters, described by the boolean mask `blk`. """ p0 = self.param_vals.copy() self.update_function(p0) #in case things are not put back... r0 = self.calc_residuals().copy() dl = np.zeros(p0...
def _set_err_paramvals(self): """ Must update: self.error, self._last_error, self.param_vals, self._last_vals """ # self.param_vals = p0 #sloppy... self._last_vals = self.param_vals.copy() self.error = self.update_function(self.param_vals) self._last_e...
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]...
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)
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()
def update_function(self, param_vals): """Updates with param_vals[i] = distance from self.p0 along self.direction[i].""" dp = np.zeros(self.p0.size) for a in range(param_vals.size): dp += param_vals[a] * self.directions[a] self.state.update(self.state.params, self.p0 + dp) ...
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...
def update_select_J(self, blk): """ Updates J only for certain parameters, described by the boolean mask blk. """ self.update_function(self.param_vals) params = np.array(self.param_names)[blk].tolist() blk_J = -self.state.gradmodel(params=params, inds=self._inds, ...
def find_expected_error(self, delta_params='calc', adjust=True): """ Returns the error expected after an update if the model were linear. Parameters ---------- delta_params : {numpy.ndarray, 'calc', or 'perfect'}, optional The relative change in parameters. I...
def calc_model_cosine(self, decimate=None, mode='err'): """ Calculates the cosine of the residuals with the model. Parameters ---------- decimate : Int or None, optional Decimate the residuals by `decimate` pixels. If None, no decimation is us...
def calc_grad(self): """The gradient of the cost w.r.t. the parameters.""" if self._fresh_JTJ: return self._graderr else: residuals = self.calc_residuals() return 2*np.dot(self.J, residuals)
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 ...
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...
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...
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...
def _poly(self, z): """Right now legval(z)""" shp = self.state.oshape.shape zmax = float(shp[0]) zmin = 0.0 zmid = zmax * 0.5 coeffs = self.param_vals[self.rscale_mask].copy() if coeffs.size == 0: ans = 0*z else: ans = np.polynomia...
def update(self, param_vals): """Updates all the parameters of the state + rscale(z)""" self.update_rscl_x_params(param_vals[self.rscale_mask]) self.state.update(self.param_names, param_vals[self.globals_mask]) self.param_vals[:] = param_vals.copy() if np.any(np.isnan(self.state....
def reset(self, **kwargs): """Resets the aug_state and the LMEngine""" self.aug_state.reset() super(LMAugmentedState, self).reset(**kwargs)
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
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...
def save(state, filename=None, desc='', extra=None): """ Save the current state with extra information (for example samples and LL from the optimization procedure). Parameters ---------- state : peri.states.ImageState the state object which to save filename : string if prov...
def load(filename): """ Load the state from the given file, moving to the file's directory during load (temporarily, moving back after loaded) Parameters ---------- filename : string name of the file to open, should be a .pkl file """ path, name = os.path.split(filename) pat...
def error(self): """ Class property: Sum of the squared errors, :math:`E = \sum_i (D_i - M_i(\\theta))^2` """ r = self.residuals.ravel() return np.dot(r,r)
def loglikelihood(self): """ Class property: loglikelihood calculated by the model error, :math:`\\mathcal{L} = - \\frac{1}{2} \\sum\\left[ \\left(\\frac{D_i - M_i(\\theta)}{\sigma}\\right)^2 + \\log{(2\pi \sigma^2)} \\right]` """ sig = self.hyper_parameters.get_v...
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 ...
def push_update(self, params, values): """ Perform a parameter update and keep track of the change on the state. Same call structure as :func:`peri.states.States.update` """ curr = self.get_values(params) self.stack.append((params, curr)) self.update(params, value...
def pop_update(self): """ Pop the last update from the stack push by :func:`peri.states.States.push_update` by undoing the chnage last performed. """ params, values = self.stack.pop() self.update(params, values)
def temp_update(self, params, values): """ Context manager to temporarily perform a parameter update (by using the stack structure). To use: with state.temp_update(params, values): # measure the cost or something state.error """ self.p...
def _grad_one_param(self, funct, p, dl=2e-5, rts=False, nout=1, **kwargs): """ Gradient of `func` wrt a single parameter `p`. (see _graddoc) """ vals = self.get_values(p) f0 = funct(**kwargs) self.update(p, vals+dl) f1 = funct(**kwargs) if rts: ...
def _hess_two_param(self, funct, p0, p1, dl=2e-5, rts=False, **kwargs): """ Hessian of `func` wrt two parameters `p0` and `p1`. (see _graddoc) """ vals0 = self.get_values(p0) vals1 = self.get_values(p1) f00 = funct(**kwargs) self.update(p0, vals0+dl) f10...
def _grad(self, funct, params=None, dl=2e-5, rts=False, nout=1, out=None, **kwargs): """ Gradient of `func` wrt a set of parameters params. (see _graddoc) """ if params is None: params = self.param_all() ps = util.listify(params) f0 = funct(**kwar...
def _jtj(self, funct, params=None, dl=2e-5, rts=False, **kwargs): """ jTj of a `func` wrt to parmaeters `params`. (see _graddoc) """ grad = self._grad(funct=funct, params=params, dl=dl, rts=rts, **kwargs) return np.dot(grad, grad.T)
def _hess(self, funct, params=None, dl=2e-5, rts=False, **kwargs): """ Hessian of a `func` wrt to parmaeters `params`. (see _graddoc) """ if params is None: params = self.param_all() ps = util.listify(params) f0 = funct(**kwargs) # get the shape of t...
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...
def crb(self, params=None, *args, **kwargs): """ Calculate the diagonal elements of the minimum covariance of the model with respect to parameters params. ``*args`` and ``**kwargs`` go to ``fisherinformation``. """ fish = self.fisherinformation(params=params, *args, **kwa...
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, ...
def set_image(self, image): """ Update the current comparison (real) image """ if isinstance(image, np.ndarray): image = util.Image(image) if isinstance(image, util.NullImage): self.model_as_data = True else: self.model_as_data = False...
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))
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 ...
def update(self, params, values): """ Actually perform an image (etc) update based on a set of params and values. These parameter can be any present in the components in any number. If there is only one component affected then difference image updates will be employed. ""...
def get(self, name): """ Return component by category name """ for c in self.comps: if c.category == name: return c return None
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...
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...
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...
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
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...
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(...
def set_values(self, params, values): """ Directly set the values corresponding to certain parameters. This does not necessarily trigger and update of the calculation, See also -------- :func:`~peri.comp.comp.ParameterGroup.update` : full update func """ ...
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: ...
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)
def split_params(self, params, values=None): """ Split params, values into groups that correspond to the ordering in self.comps. For example, given a sphere collection and slab:: [ (spheres) [pos rad etc] [pos val, rad val, etc] (slab) [slab params] [...
def get(self): """ Combine the fields from all components """ fields = [c.get() for c in self.comps] return self.field_reduce_func(fields)
def set_shape(self, shape, inner): """ Set the shape for all components """ for c in self.comps: c.set_shape(shape, inner)
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...
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...
def get_conf_filename(): """ The configuration file either lives in ~/.peri.json or is specified on the command line via the environment variables PERI_CONF_FILE """ default = os.path.join(os.path.expanduser("~"), ".peri.json") return os.environ.get('PERI_CONF_FILE', default)
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
def load_conf(): """ Load the configuration with the priority: 1. environment variables 2. configuration file 3. defaults here (default_conf) """ try: conf = copy.copy(default_conf) conf.update(json.load(open(get_conf_filename()))) conf.update(read_environ...
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
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...
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...
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', ...
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")) ...
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...
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...