INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Edit the order at which statuses for the specified social media profile will be sent out of the buffer.
def reorder(self, updates_ids, offset=None, utc=None): ''' Edit the order at which statuses for the specified social media profile will be sent out of the buffer. ''' url = PATHS['REORDER'] % self.profile_id order_format = "order[]=%s&" post_data = '' if offset: post_data +=...
Create one or more new status updates.
def new(self, text, shorten=None, now=None, top=None, media=None, when=None): ''' Create one or more new status updates. ''' url = PATHS['CREATE'] post_data = "text=%s&" % text post_data += "profile_ids[]=%s&" % self.profile_id if shorten: post_data += "shorten=%s&" % shorten ...
Set the logging level ( which types of logs are actually printed/ recorded ) to one of [ debug info warn error fatal ] in that order of severity
def set_level(self, level='info', handlers=None): """ Set the logging level (which types of logs are actually printed / recorded) to one of ['debug', 'info', 'warn', 'error', 'fatal'] in that order of severity """ for h in self.get_handlers(handlers): h.setLev...
Set the text format of messages to one of the pre - determined forms one of [ quiet minimal standard verbose ]
def set_formatter(self, formatter='standard', handlers=None): """ Set the text format of messages to one of the pre-determined forms, one of ['quiet', 'minimal', 'standard', 'verbose'] """ for h in self.get_handlers(handlers): h.setFormatter(logging.Formatter(formatte...
Add another handler to the logging system if not present already. Available handlers are currently: [ console - bw console - color rotating - log ]
def add_handler(self, name='console-color', level='info', formatter='standard', **kwargs): """ Add another handler to the logging system if not present already. Available handlers are currently: ['console-bw', 'console-color', 'rotating-log'] """ # make sure the the log file has ...
Remove handler from the logging system if present already. Available handlers are currently: [ console - bw console - color rotating - log ]
def remove_handler(self, name): """ Remove handler from the logging system if present already. Available handlers are currently: ['console-bw', 'console-color', 'rotating-log'] """ if name in self.handlers: self.log.removeHandler(self.handlers[name])
Temporarily do not use any formatter so that text printed is raw
def noformat(self): """ Temporarily do not use any formatter so that text printed is raw """ try: formats = {} for h in self.get_handlers(): formats[h] = h.formatter self.set_formatter(formatter='quiet') yield except Exception as e:...
Set the verbosity level of a certain log handler or of all handlers.
def set_verbosity(self, verbosity='vvv', handlers=None): """ Set the verbosity level of a certain log handler or of all handlers. Parameters ---------- verbosity : 'v' to 'vvvvv' the level of verbosity, more v's is more verbose handlers : string, or list of ...
Normalize a field to a ( min max ) exposure range default is ( 0 255 ). ( min max ) exposure values. Invert the image if requested.
def normalize(im, invert=False, scale=None, dtype=np.float64): """ Normalize a field to a (min, max) exposure range, default is (0, 255). (min, max) exposure values. Invert the image if requested. """ if dtype not in {np.float16, np.float32, np.float64}: raise ValueError('dtype must be numpy...
Generates a centered boolean mask of a 3D sphere
def generate_sphere(radius): """Generates a centered boolean mask of a 3D sphere""" rint = np.ceil(radius).astype('int') t = np.arange(-rint, rint+1, 1) x,y,z = np.meshgrid(t, t, t, indexing='ij') r = np.sqrt(x*x + y*y + z*z) sphere = r < radius return sphere
Local max featuring to identify bright spherical particles on a dark background.
def local_max_featuring(im, radius=2.5, noise_size=1., bkg_size=None, minmass=1., trim_edge=False): """Local max featuring to identify bright spherical particles on a dark background. Parameters ---------- im : numpy.ndarray The image to identify particles in. radius...
Otsu threshold on data.
def otsu_threshold(data, bins=255): """ Otsu threshold on data. Otsu thresholding [1]_is a method for selecting an intensity value for thresholding an image into foreground and background. The sel- ected intensity threshold maximizes the inter-class variance. Parameters ---------- ...
Harris - motivated feature detection on a d - dimensional image.
def harris_feature(im, region_size=5, to_return='harris', scale=0.05): """ Harris-motivated feature detection on a d-dimensional image. Parameters --------- im region_size to_return : {'harris','matrix','trace-determinant'} """ ndim = im.ndim #1. Gradient of image ...
Identifies slabs in an image.
def identify_slab(im, sigma=5., region_size=10, masscut=1e4, asdict=False): """ Identifies slabs in an image. Functions by running a Harris-inspired edge detection on the image, thresholding the edge, then clustering. Parameters ---------- im : numpy.ndarray 3D array of the...
ax = fig. add_axes ( [ 0. 6 0. 6 0. 28 0. 28 ] ) ax. plot ( rad crb [: 0: ] lw = 2. 5 ) for c error in enumerate ( errors ): mu = np. sqrt (( error ** 2 ). mean ( axis = 1 )) [: 0: ] std = np. std ( np. sqrt (( error ** 2 )) axis = 1 ) [: 0: ]
def plot_errors_single(rad, crb, errors, labels=['trackpy', 'peri']): fig = pl.figure() comps = ['z', 'y', 'x'] markers = ['o', '^', '*'] colors = COLORS for i in reversed(range(3)): pl.plot(rad, crb[:,0,i], lw=2.5, label='CRB-'+comps[i], color=colors[i]) for c, (error, label) in enume...
Cumulative distribution function for the traingle distribution
def sphere_triangle_cdf(dr, a, alpha): """ Cumulative distribution function for the traingle distribution """ p0 = (dr+alpha)**2/(2*alpha**2)*(0 > dr)*(dr>-alpha) p1 = 1*(dr>0)-(alpha-dr)**2/(2*alpha**2)*(0<dr)*(dr<alpha) return (1-np.clip(p0+p1, 0, 1))
Analytically calculate the sphere s functional form by convolving the Heavyside function with first order approximation to the sinc a Gaussian. The alpha parameters controls the width of the approximation -- should be 1 but is fit to be roughly 0. 2765
def sphere_analytical_gaussian(dr, a, alpha=0.2765): """ Analytically calculate the sphere's functional form by convolving the Heavyside function with first order approximation to the sinc, a Gaussian. The alpha parameters controls the width of the approximation -- should be 1, but is fit to be roug...
See sphere_analytical_gaussian_exact.
def sphere_analytical_gaussian_trim(dr, a, alpha=0.2765, cut=1.6): """ See sphere_analytical_gaussian_exact. I trimmed to terms from the functional form that are essentially zero (1e-8) for r0 > cut (~1.5), a fine approximation for these platonic anyway. """ m = np.abs(dr) <= cut # only co...
See sphere_analytical_gaussian_trim but implemented in C with fast erf and exp approximations found at Abramowitz and Stegun: Handbook of Mathematical Functions A Fast Compact Approximation of the Exponential Function
def sphere_analytical_gaussian_fast(dr, a, alpha=0.2765, cut=1.20): """ See sphere_analytical_gaussian_trim, but implemented in C with fast erf and exp approximations found at Abramowitz and Stegun: Handbook of Mathematical Functions A Fast, Compact Approximation of the Exponential Function ...
Sphere generated by a cubic interpolant constrained to be ( 1 0 ) on ( r0 - sqrt ( 3 )/ 2 r0 + sqrt ( 3 )/ 2 ) the size of the cube in the ( 111 ) direction.
def sphere_constrained_cubic(dr, a, alpha): """ Sphere generated by a cubic interpolant constrained to be (1,0) on (r0-sqrt(3)/2, r0+sqrt(3)/2), the size of the cube in the (111) direction. """ sqrt3 = np.sqrt(3) b_coeff = a*0.5/sqrt3*(1 - 0.6*sqrt3*alpha)/(0.15 + a*a) rscl = np.clip(dr, -0...
Perform an iterative method to calculate the effective sphere that perfectly ( up to the volume_error ) conserves volume. Return the resulting image
def exact_volume_sphere(rvec, pos, radius, zscale=1.0, volume_error=1e-5, function=sphere_analytical_gaussian, max_radius_change=1e-2, args=()): """ Perform an iterative method to calculate the effective sphere that perfectly (up to the volume_error) conserves volume. Return the resulting image ...
Get the update tile surrounding particle n
def _tile(self, n): """Get the update tile surrounding particle `n` """ pos = self._trans(self.pos[n]) return Tile(pos, pos).pad(self.support_pad)
Parameter to indices returns ( coord index ) e. g. for a pos pos: ( x 100 )
def _p2i(self, param): """ Parameter to indices, returns (coord, index), e.g. for a pos pos : ('x', 100) """ g = param.split('-') if len(g) == 3: return g[2], int(g[1]) else: raise ValueError('`param` passed as incorrect format')
Start from scratch and initialize all objects/ draw self. particles
def initialize(self): """Start from scratch and initialize all objects / draw self.particles""" self.particles = np.zeros(self.shape.shape, dtype=self.float_precision) for p0, arg0 in zip(self.pos, self._drawargs()): self._draw_particle(p0, *listify(arg0))
Clips a list of inds to be on [ 0 self. N ]
def _vps(self, inds): """Clips a list of inds to be on [0, self.N]""" return [j for j in inds if j >= 0 and j < self.N]
Translate index info to parameter name
def _i2p(self, ind, coord): """ Translate index info to parameter name """ return '-'.join([self.param_prefix, str(ind), coord])
Get the amount of support size required for a particular update.
def get_update_tile(self, params, values): """ Get the amount of support size required for a particular update.""" doglobal, particles = self._update_type(params) if doglobal: return self.shape.copy() # 1) store the current parameters of interest values0 = self.get_v...
Update the particles field given new parameter values
def update(self, params, values): """ Update the particles field given new parameter values """ #1. Figure out if we're going to do a global update, in which # case we just draw from scratch. global_update, particles = self._update_type(params) # if we are doin...
Get position and radius of one or more particles
def param_particle(self, ind): """ Get position and radius of one or more particles """ ind = self._vps(listify(ind)) return [self._i2p(i, j) for i in ind for j in ['z', 'y', 'x', 'a']]
Get position of one or more particles
def param_particle_pos(self, ind): """ Get position of one or more particles """ ind = self._vps(listify(ind)) return [self._i2p(i, j) for i in ind for j in ['z', 'y', 'x']]
Get radius of one or more particles
def param_particle_rad(self, ind): """ Get radius of one or more particles """ ind = self._vps(listify(ind)) return [self._i2p(i, 'a') for i in ind]
Add a particle or list of particles given by a list of positions and radii both need to be array - like.
def add_particle(self, pos, rad): """ Add a particle or list of particles given by a list of positions and radii, both need to be array-like. Parameters ---------- pos : array-like [N, 3] Positions of all new particles rad : array-like [N] ...
Remove the particle at index inds may be a list. Returns [ 3 N ] [ N ] element numpy. ndarray of pos rad.
def remove_particle(self, inds): """ Remove the particle at index `inds`, may be a list. Returns [3,N], [N] element numpy.ndarray of pos, rad. """ if self.rad.shape[0] == 0: return inds = listify(inds) # Here's the game plan: # 1. get all p...
Returns dozscale and particle list of update
def _update_type(self, params): """ Returns dozscale and particle list of update """ dozscale = False particles = [] for p in listify(params): typ, ind = self._p2i(p) particles.append(ind) dozscale = dozscale or typ == 'zscale' particles = set(...
Get the tile surrounding particle n
def _tile(self, n): """ Get the tile surrounding particle `n` """ zsc = np.array([1.0/self.zscale, 1, 1]) pos, rad = self.pos[n], self.rad[n] pos = self._trans(pos) return Tile(pos - zsc*rad, pos + zsc*rad).pad(self.support_pad)
Calls an update but clips radii to be > 0
def update(self, params, values): """Calls an update, but clips radii to be > 0""" # radparams = self.param_radii() params = listify(params) values = listify(values) for i, p in enumerate(params): # if (p in radparams) & (values[i] < 0): if (p[-2:] == '-a'...
Generate the composite rotation matrix that rotates the slab normal.
def rmatrix(self): """ Generate the composite rotation matrix that rotates the slab normal. The rotation is a rotation about the x-axis, followed by a rotation about the z-axis. """ t = self.param_dict[self.lbl_theta] r0 = np.array([ [np.cos(t), -np.sin(t), 0], ...
A fast j2 defined in terms of other special functions
def j2(x): """ A fast j2 defined in terms of other special functions """ to_return = 2./(x+1e-15)*j1(x) - j0(x) to_return[x==0] = 0 return to_return
Returns Hermite - Gauss quadrature points for even functions
def calc_pts_hg(npts=20): """Returns Hermite-Gauss quadrature points for even functions""" pts_hg, wts_hg = np.polynomial.hermite.hermgauss(npts*2) pts_hg = pts_hg[npts:] wts_hg = wts_hg[npts:] * np.exp(pts_hg*pts_hg) return pts_hg, wts_hg
Returns Gauss - Laguerre quadrature points rescaled for line scan integration
def calc_pts_lag(npts=20): """ Returns Gauss-Laguerre quadrature points rescaled for line scan integration Parameters ---------- npts : {15, 20, 25}, optional The number of points to Notes ----- The scale is set internally as the best rescaling for a line scan ...
Returns the wavefront aberration for an aberrated defocused lens.
def f_theta(cos_theta, zint, z, n2n1=0.95, sph6_ab=None, **kwargs): """ Returns the wavefront aberration for an aberrated, defocused lens. Calculates the portions of the wavefront distortion due to z, theta only, for a lens with defocus and spherical aberration induced by coverslip mismatch. (The r...
Returns a prefactor in the electric field integral.
def get_Kprefactor(z, cos_theta, zint=100.0, n2n1=0.95, get_hdet=False, **kwargs): """ Returns a prefactor in the electric field integral. This is an internal function called by get_K. The returned prefactor in the integrand is independent of which integral is being called; it is a combinat...
Calculates one of three electric field integrals.
def get_K(rho, z, alpha=1.0, zint=100.0, n2n1=0.95, get_hdet=False, K=1, Kprefactor=None, return_Kprefactor=False, npts=20, **kwargs): """ Calculates one of three electric field integrals. Internal function for calculating point spread functions. Returns one of three electric field integrals th...
Calculates the symmetric and asymmetric portions of a confocal PSF.
def get_hsym_asym(rho, z, get_hdet=False, include_K3_det=True, **kwargs): """ Calculates the symmetric and asymmetric portions of a confocal PSF. Parameters ---------- rho : numpy.ndarray Rho in cylindrical coordinates, in units of 1/k. z : numpy.ndarray Z in cyl...
Calculates the perfect - pinhole PSF for a set of points ( x y z ).
def calculate_pinhole_psf(x, y, z, kfki=0.89, zint=100.0, normalize=False, **kwargs): """ Calculates the perfect-pinhole PSF, for a set of points (x,y,z). Parameters ----------- x : numpy.ndarray The x-coordinate of the PSF in units of 1/ the wavevector of the in...
Calculates a set of Gauss quadrature points & weights for polydisperse light.
def get_polydisp_pts_wts(kfki, sigkf, dist_type='gaussian', nkpts=3): """ Calculates a set of Gauss quadrature points & weights for polydisperse light. Returns a list of points and weights of the final wavevector's distri- bution, in units of the initial wavevector. Parameters ---------- ...
Calculates the perfect - pinhole PSF for a set of points ( x y z ).
def calculate_polychrome_pinhole_psf(x, y, z, normalize=False, kfki=0.889, sigkf=0.1, zint=100., nkpts=3, dist_type='gaussian', **kwargs): """ Calculates the perfect-pinhole PSF, for a set of points (x,y,z). Parameters ----------- x : numpy.ndarray The x-coordinate of the PS...
Calculates a scalar ( non - vectorial light ) approximation to a confocal PSF
def get_psf_scalar(x, y, z, kfki=1., zint=100.0, normalize=False, **kwargs): """ Calculates a scalar (non-vectorial light) approximation to a confocal PSF The calculation is approximate, since it ignores the effects of polarization and apodization, but should be ~3x faster. Parameters --------...
Calculates the illumination PSF for a line - scanning confocal with the confocal line oriented along the x direction.
def calculate_linescan_ilm_psf(y,z, polar_angle=0., nlpts=1, pinhole_width=1, use_laggauss=False, **kwargs): """ Calculates the illumination PSF for a line-scanning confocal with the confocal line oriented along the x direction. Parameters ---------- y : numpy.ndarray Th...
Calculates the point spread function of a line - scanning confocal.
def calculate_linescan_psf(x, y, z, normalize=False, kfki=0.889, zint=100., polar_angle=0., wrap=True, **kwargs): """ Calculates the point spread function of a line-scanning confocal. Make x,y,z __1D__ numpy.arrays, with x the direction along the scan line. (to make the calculation faster sinc...
Calculates the point spread function of a line - scanning confocal with polydisperse dye emission.
def calculate_polychrome_linescan_psf(x, y, z, normalize=False, kfki=0.889, sigkf=0.1, zint=100., nkpts=3, dist_type='gaussian', wrap=True, **kwargs): """ Calculates the point spread function of a line-scanning confocal with polydisperse dye emission. Make x,y,z __1D__ numpy.arrays, wi...
Wraps a point - spread function in x and y.
def wrap_and_calc_psf(xpts, ypts, zpts, func, **kwargs): """ Wraps a point-spread function in x and y. Speeds up psf calculations by a factor of 4 for free / some broadcasting by exploiting the x->-x, y->-y symmetry of a psf function. Pass x and y as the positive (say) values of the coordinates at ...
Transforms a vector np. arange ( - N M dx ) to np. arange ( min ( |vec| ) max ( N M ) dx ) ]
def vec_to_halfvec(vec): """Transforms a vector np.arange(-N, M, dx) to np.arange(min(|vec|), max(N,M),dx)]""" d = vec[1:] - vec[:-1] if ((d/d.mean()).std() > 1e-14) or (d.mean() < 0): raise ValueError('vec must be np.arange() in increasing order') dx = d.mean() lowest = np.abs(vec).min() ...
Convert a scalar a to a list and all iterables to list as well.
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'] ""...
If a single element list extract the element as an object otherwise leave as it is.
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...
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.
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...
Conditionally delete key ( or list of keys ) k from dict d
def cdd(d, k): """ Conditionally delete key (or list of keys) 'k' from dict 'd' """ if not isinstance(k, list): k = [k] for i in k: if i in d: d.pop(i)
Apply the documentation from superclass to subclass by filling in all overridden member function docstrings with those from the parent class
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...
Context manager for switching the current path of the process. Can be used:
def indir(path): """ Context manager for switching the current path of the process. Can be used: with indir('/tmp'): <do something in tmp> """ cwd = os.getcwd() try: os.chdir(path) yield except Exception as e: raise finally: os.chdir(cwd)
Array slicer object for this tile
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))
Opposite slicer the outer part wrt to a field
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...
Return the frequency center of the tile ( says fftshift )
def kcenter(self): """ Return the frequency center of the tile (says fftshift) """ return np.array([ np.abs(np.fft.fftshift(np.fft.fftfreq(q))).argmin() for q in self.shape ]).astype('float')
Iterate the vector of all corners of the hyperrectangles
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): ...
Format a 3d vector field in certain ways see coords for a description of each formatting method.
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 ...
Returns the coordinate vectors associated with the tile.
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...
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.
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...
Test whether coordinates are contained within this tile.
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...
Intersection of tiles returned as a tile
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[...
Translate a tile by an amount dr
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
Pad this tile by an equal amount on each side as specified by pad
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...
Get the left and right absolute overflow -- the amount of box overhanging tile can be viewed as self \\ tile ( set theory relative complement but in a bounding sense )
def overhang(self, tile): """ Get the left and right absolute overflow -- the amount of box overhanging `tile`, can be viewed as self \\ tile (set theory relative complement, but in a bounding sense) """ ll = np.abs(amin(self.l - tile.l, aN(0, dim=self.dim))) rr =...
Compute the overhang and reflect it internally so respect periodic padding rules ( see states. _tile_from_particle_change ). Returns both the inner tile and the inner tile with necessary pad.
def reflect_overhang(self, clip): """ Compute the overhang and reflect it internally so respect periodic padding rules (see states._tile_from_particle_change). Returns both the inner tile and the inner tile with necessary pad. """ orig = self.copy() tile = self.co...
Returns a filtered image after applying the Fourier - space filters
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))
Sets Fourier - space filters for the image. The image is filtered by subtracting values from the image at slices.
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....
Read the file and perform any transforms to get a loaded image
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...
If exposure was not set in the __init__ get the exposure associated with this RawImage so that it may be used in other: class: ~peri. util. RawImage. This is useful for transferring exposure parameters to a series of images.
def get_scale(self): """ If exposure was not set in the __init__, get the exposure associated with this RawImage so that it may be used in other :class:`~peri.util.RawImage`. This is useful for transferring exposure parameters to a series of images. Returns -----...
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
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...
Interal draw method simply prints to screen
def _draw(self): """ Interal draw method, simply prints to screen """ if self.display: print(self._formatstr.format(**self.__dict__), end='') sys.stdout.flush()
Update the value of the progress and update progress bar.
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...
Flask application initialization.
def init_app(self, app): """Flask application initialization.""" self.init_config(app) app.register_blueprint(blueprint) app.extensions['invenio-groups'] = 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.
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_]*)...
Check that the list of components comp is compatible with both the varmap and modelstr for this Model
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 ...
Get the equation corresponding to a variation wrt category. For example if::
def get_difference_model(self, category): """ Get the equation corresponding to a variation wrt category. For example if:: modelstr = { 'full' :'H(I) + B', 'dH' : 'dH(I)', 'dI' : 'H(dI)', 'dB' : 'dB' } ...
Map component function funcname result into model variables dictionary for use in eval of the model. If diffmap is provided then that symbol is translated into d + diffmap. key and is replaced by diffmap. value. ** kwargs are passed to the comp. funcname ( ** kwargs ).
def map_vars(self, comps, funcname='get', diffmap=None, **kwargs): """ Map component function ``funcname`` result into model variables dictionary for use in eval of the model. If ``diffmap`` is provided then that symbol is translated into 'd'+diffmap.key and is replaced by diffma...
Calculate the output of a model. It is recommended that at some point before using evaluate that you make sure the inputs are valid using: class: ~peri. models. Model. check_inputs
def evaluate(self, comps, funcname='get', diffmap=None, **kwargs): """ Calculate the output of a model. It is recommended that at some point before using `evaluate`, that you make sure the inputs are valid using :class:`~peri.models.Model.check_inputs` Parameters -------...
Put a figure label in an axis
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=...
Samples x y z r are created by: b = s. blocks_particle ( # ) h = runner. sample_state ( s b stepout = 0. 05 N = 2000 doprint = True ) z y x r = h. get_histogram (). T
def generative_model(s,x,y,z,r, factor=1.1): """ Samples x,y,z,r are created by: b = s.blocks_particle(#) h = runner.sample_state(s, b, stepout=0.05, N=2000, doprint=True) z,y,x,r = h.get_histogram().T """ pl.close('all') slicez = int(round(z.mean())) slicex = s.image.shape[2]//2 ...
Compares a state s residuals in real and Fourier space with a Gaussian.
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. ...
Compare the data model and residuals of a state.
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...
Returns 3 masks that trisect an image into 3 triangular portions.
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...
Clips data on [ vmin vmax ] ; then rescales to [ 0 1 ]
def center_data(data, vmin, vmax): """Clips data on [vmin, vmax]; then rescales to [0,1]""" ans = data - vmin ans /= (vmax - vmin) return np.clip(ans, 0, 1)
each element of std0 should correspond with the element of std1
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
To run do:
def crb_compare(state0, samples0, state1, samples1, crb0=None, crb1=None, zlayer=None, xlayer=None): """ To run, do: s,h = pickle... s1,h1 = pickle... i.e. /media/scratch/bamf/vacancy/vacancy_zoom-1.tif_t002.tif-featured-v2.pkl i.e. /media/scratch/bamf/frozen-particles/0.tif-fea...
Plot two parts of the ortho view the two sections given by orientation.
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...
Plots a set of circles corresponding to a slice through the platonic structure. Copied from twoslice_overlay with comments standaloneness.
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...
create a two particle state and compare it to featuring using a single particle guess
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...
Calculates a random approximation to J by returning J only at a set of random pixel/ voxel locations.
def get_rand_Japprox(s, params, num_inds=1000, include_cost=False, **kwargs): """ Calculates a random approximation to J by returning J only at a set of random pixel/voxel locations. Parameters ---------- s : :class:`peri.states.State` The state to calculate J for. param...
Returns a list of the global parameter names.
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...
Calculates the number of pixels to use for J at a given memory usage.
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...
Returns a non - constant damping vector allowing certain parameters to be more strongly damped than others.
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 : ...