text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
⌀
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getPcn(dsz, Nv, dimN=2, dimC=1, crp=False, zm=False): """Construct the constraint set projection function for convolutional dictionary update problem. Parame...
fncdict = {(False, False): _Pcn, (False, True): _Pcn_zm, (True, False): _Pcn_crp, (True, True): _Pcn_zm_crp} fnc = fncdict[(crp, zm)] return functools.partial(fnc, dsz=dsz, Nv=Nv, dimN=dimN, dimC=dimC)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tiledict(D, sz=None): """Construct an image allowing visualization of dictionary content. Parameters D : array_like Dictionary matrix/array. sz : tuple Size ...
# Handle standard 2D (non-convolutional) dictionary if D.ndim == 2: D = D.reshape((sz + (D.shape[1],))) sz = None dsz = D.shape if D.ndim == 4: axisM = 3 szni = 3 else: axisM = 2 szni = 2 # Construct dictionary atom size vector if not provided ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def extractblocks(img, blksz, stpsz=None): """Extract blocks from an ndarray signal into an ndarray. Parameters img : ndarray or tuple of ndarrays nd array of im...
# See http://stackoverflow.com/questions/16774148 and # sklearn.feature_extraction.image.extract_patches_2d if isinstance(img, tuple): img = np.stack(img, axis=-1) if stpsz is None: stpsz = (1,) * len(blksz) imgsz = img.shape # Calculate the number of blocks that can fit in ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def averageblocks(blks, imgsz, stpsz=None): """Average blocks together from an ndarray to reconstruct ndarray signal. Parameters blks : ndarray nd array of block...
blksz = blks.shape[:-1] if stpsz is None: stpsz = tuple(1 for _ in blksz) # Calculate the number of blocks that can fit in each dimension of # the images numblocks = tuple(int(np.floor((a-b)/c)+1) for a, b, c in zip_longest(imgsz, blksz, stpsz, fillvalue=1)) n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combineblocks(blks, imgsz, stpsz=None, fn=np.median): """Combine blocks from an ndarray to reconstruct ndarray signal. Parameters blks : ndarray nd array of ...
# Construct a vectorized append function def listapp(x, y): x.append(y) veclistapp = np.vectorize(listapp, otypes=[np.object_]) blksz = blks.shape[:-1] if stpsz is None: stpsz = tuple(1 for _ in blksz) # Calculate the number of blocks that can fit in each dimension of # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def complex_randn(*args): """Return a complex array of samples drawn from a standard normal distribution. Parameters Dimensions of the random array Returns -----...
return np.random.randn(*args) + 1j*np.random.randn(*args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def spnoise(s, frc, smn=0.0, smx=1.0): """Return image with salt & pepper noise imposed on it. Parameters s : ndarray Input image frc : float Desired fraction of...
sn = s.copy() spm = np.random.uniform(-1.0, 1.0, s.shape) sn[spm < frc - 1.0] = smn sn[spm > 1.0 - frc] = smx return sn
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pca(U, centre=False): """Compute the PCA basis for columns of input array `U`. Parameters U : array_like 2D data array with rows corresponding to different v...
if centre: C = np.mean(U, axis=1, keepdims=True) U = U - C else: C = None B, S, _ = np.linalg.svd(U, full_matrices=False, compute_uv=True) return B, S**2, C
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tikhonov_filter(s, lmbda, npd=16): r"""Lowpass filter based on Tikhonov regularization. Lowpass filter image(s) and return low and high frequency components,...
grv = np.array([-1.0, 1.0]).reshape([2, 1]) gcv = np.array([-1.0, 1.0]).reshape([1, 2]) Gr = sla.fftn(grv, (s.shape[0] + 2*npd, s.shape[1] + 2*npd), (0, 1)) Gc = sla.fftn(gcv, (s.shape[0] + 2*npd, s.shape[1] + 2*npd), (0, 1)) A = 1.0 + lmbda*np.conj(Gr)*Gr + lmbda*np.conj(Gc)*Gc if s.ndim > 2:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gaussian(shape, sd=1.0): """Sample a multivariate Gaussian pdf, normalised to have unit sum. Parameters shape : tuple Shape of output array. sd : float, opti...
gfn = lambda x, sd: np.exp(-(x**2) / (2.0 * sd**2)) / \ (np.sqrt(2.0 * np.pi) *sd) gc = 1.0 if isinstance(shape, int): shape = (shape,) for k, n in enumerate(shape): x = np.linspace(-3.0, 3.0, n).reshape( (1,) * k + (n,) + (1,) * (len(shape) - k - 1)...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convdicts(): """Access a set of example learned convolutional dictionaries. Returns ------- cdd : dict A dict associating description strings with dictionari...
pth = os.path.join(os.path.dirname(__file__), 'data', 'convdict.npz') npz = np.load(pth) cdd = {} for k in list(npz.keys()): cdd[k] = npz[k] return cdd
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def netgetdata(url, maxtry=3, timeout=10): """ Get content of a file via a URL. Parameters url : string URL of the file to be downloaded maxtry : int, optional (...
err = ValueError('maxtry parameter should be greater than zero') for ntry in range(maxtry): try: rspns = urlrequest.urlopen(url, timeout=timeout) cntnt = rspns.read() break except urlerror.URLError as e: err = e if not isinstance(e.re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image(self, fname, group=None, scaled=None, dtype=None, idxexp=None, zoom=None, gray=None): """Get named image. Parameters fname : string Filename of image g...
if scaled is None: scaled = self.scaled if dtype is None: if self.dtype is None: dtype = np.uint8 else: dtype = self.dtype if scaled and np.issubdtype(dtype, np.integer): dtype = np.float32 if zoom is None:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def elapsed(self, label=None, total=True): """Get elapsed time since timer start. Parameters label : string, optional (default None) Specify the label of the tim...
# Get current time t = timer() # Default label is self.dfltlbl if label is None: label = self.dfltlbl # Return 0.0 if default timer selected and it is not initialised if label not in self.t0: return 0.0 # Raise exception if ti...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def elapsed(self, total=True): """Return the elapsed time for the timer. Parameters total : bool, optional (default True) If ``True`` return the total elapsed ti...
return self.timer.elapsed(self.label, total=total)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_keypress(fig, scaling=1.1): """ Attach a key press event handler that configures keys for closing a figure and changing the figure size. Keys 'e' and ...
def press(event): if event.key == 'q': plt.close(fig) elif event.key == 'e': fig.set_size_inches(scaling * fig.get_size_inches(), forward=True) elif event.key == 'c': fig.set_size_inches(fig.get_size_inches() / scaling, forward=True) # Avoid multipl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach_zoom(ax, scaling=2.0): """ Attach an event handler that supports zooming within a plot using the mouse scroll wheel. Parameters ax : :class:`matplotli...
# See https://stackoverflow.com/questions/11551049 def zoom(event): # Get the current x and y limits cur_xlim = ax.get_xlim() cur_ylim = ax.get_ylim() # Get event location xdata = event.xdata ydata = event.ydata # Return if cursor is not over valid regio...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def config_notebook_plotting(): """ Configure plotting functions for inline plotting within a Jupyter Notebook shell. This function has no effect when not within...
# Check whether running within a notebook shell and have # not already monkey patched the plot function from sporco.util import in_notebook module = sys.modules[__name__] if in_notebook() and module.plot.__name__ == 'plot': # Set inline backend (i.e. %matplotlib inline) if in a notebook s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_vars(self, S, dimK): """Initalise variables required for sparse coding and dictionary update for training data `S`."""
Nv = S.shape[0:self.dimN] if self.cri is None or Nv != self.cri.Nv: self.cri = cr.CDU_ConvRepIndexing(self.dsz, S, dimK, self.dimN) if self.opt['CUDA_CBPDN']: if self.cri.Cd > 1 or self.cri.Cx > 1: raise ValueError('CUDA CBPDN solver can only...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def manage_itstat(self): """Compute, record, and display iteration statistics."""
# Extract and record iteration stats itst = self.iteration_stats() self.itstat.append(itst) self.display_status(self.fmtstr, itst)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def display_start(self): """Start status display if option selected."""
if self.opt['Verbose'] and self.opt['StatusHeader']: print(self.hdrstr) print("-" * self.nsep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xstep(self, S, W, lmbda, dimK): """Solve CSC problem for training data `S`."""
if self.opt['CUDA_CBPDN']: Z = cuda.cbpdnmsk(self.D.squeeze(), S[..., 0], W.squeeze(), lmbda, self.opt['CBPDN']) Z = Z.reshape(self.cri.Nv + (1, 1, self.cri.M,)) self.Z[:] = np.asarray(Z, dtype=self.dtype) self.Zf = sl.rfftn(self.Z,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keycmp(a, b, pth=()): """Recurse down the tree of nested dicts `b`, at each level checking that it does not have any keys that are not also at the same level...
akey = list(a.keys()) # Iterate over all keys in b for key in list(b.keys()): # If a key is encountered that is not in a, raise an # UnknownKeyError exception. if key not in akey: raise UnknownKeyError(pth + (key,)) else: # If corresponding values in...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, d): """Update the dict with the dict tree in parameter d. Parameters d : dict New dict content """
# Call __setitem__ for all keys in d for key in list(d.keys()): self.__setitem__(key, d[key])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check(self, key, value): """Check whether key,value pair is allowed. The key is allowed if there is a corresponding key in the defaults class attribute dict....
# This test necessary to avoid unpickling errors in Python 3 if hasattr(self, 'dflt'): # Get corresponding node to self, as determined by pth # attribute, of the defaults dict tree a = self.__class__.getnode(self.dflt, self.pth) # Raise UnknownKeyError e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getparent(d, pth): """Get the parent node of a subdict as specified by the key path in `pth`. Parameters d : dict Dict tree in which access is required pth :...
c = d for key in pth[:-1]: if not isinstance(c, dict): raise InvalidValueError(c) elif key not in c: raise UnknownKeyError(pth) else: c = c.__getitem__(key) return c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def par_relax_AX(i): """Parallel implementation of relaxation if option ``RelaxParam`` != 1.0. """
global mp_X global mp_Xnr global mp_DX global mp_DXnr mp_Xnr[mp_grp[i]:mp_grp[i+1]] = mp_X[mp_grp[i]:mp_grp[i+1]] mp_DXnr[i] = mp_DX[i] if mp_rlx != 1.0: grpind = slice(mp_grp[i], mp_grp[i+1]) mp_X[grpind] = mp_rlx * mp_X[grpind] + (1-mp_rlx)*mp_Y1[grpind] mp_DX[i] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def par_final_stepgrp(i): """The parallel step grouping of the final iteration in solve. A cyclic permutation of the steps is done to require only one merge per ...
par_y0bstep(i) par_y1step(i) par_u0step(i) par_u1step(i)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def par_compute_residuals(i): """Compute components of the residual and stopping thresholds that can be done in parallel. Parameters i : int Index of group to co...
# Compute the residuals in parallel, need to check if the residuals # depend on alpha global mp_ry0 global mp_ry1 global mp_sy0 global mp_sy1 global mp_nrmAx global mp_nrmBy global mp_nrmu mp_ry0[i] = np.sum((mp_DXnr[i] - mp_Y0[i])**2) mp_ry1[i] = mp_alpha**2*np.sum((mp_Xnr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_pool(self): """Initialize multiprocessing pool if necessary."""
# initialize the pool if needed if self.pool is None: if self.nproc > 1: self.pool = mp.Pool(processes=self.nproc) else: self.pool = None else: print('pool already initialized?')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def distribute(self, f, n): """Distribute the computations amongst the multiprocessing pools Parameters f : function Function to be distributed to the processors...
if self.pool is None: return [f(i) for i in range(n)] else: return self.pool.map(f, range(n))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def terminate_pool(self): """Terminate and close the multiprocessing pool if necessary."""
if self.pool is not None: self.pool.terminate() self.pool.join() del(self.pool) self.pool = None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def eval_objfn(self): """Compute components of regularisation function as well as total objective function. """
dfd = self.obfn_dfd() prj = sp.proj_l1(self.obfn_gvar(), self.gamma, axis=self.cri.axisN + (self.cri.axisC, self.cri.axisM)) cns = np.linalg.norm(prj - self.obfn_gvar()) return (dfd, cns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ystep(self): """This method is inserted into the inner cbpdn object, replacing its own ystep method, thereby providing a hook for applying the additional ste...
# Extract AMS part of ystep argument so that it is not # affected by the main part of the ystep amidx = self.index_addmsk() Yi = self.cbpdn.AX[amidx] + self.cbpdn.U[amidx] # Perform main part of ystep from inner cbpdn object self.inner_ystep() # Apply mask to AM...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def obfn_gvar(self): """This method is inserted into the inner cbpdn object, replacing its own obfn_gvar method, thereby providing a hook for applying the additi...
# Get inner cbpdn object gvar gv = self.inner_obfn_gvar().copy() # Set slice corresponding to the coefficient map of the final # filter (the impulse inserted for the AMS method) to zero so # that it does not affect the results (e.g. l1 norm) computed # from this variabl...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve(self): """Call the solve method of the inner cbpdn object and return the result. """
# Call solve method of inner cbpdn object Xi = self.cbpdn.solve() # Copy attributes from inner cbpdn object self.timer = self.cbpdn.timer self.itstat = self.cbpdn.itstat # Return result of inner cbpdn object return Xi
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reconstruct(self, b, X=None): """Reconstruct representation of signal b in signal set."""
if X is None: X = self.getcoef() Xf = sl.rfftn(X, None, self.cbpdn.cri.axisN) slc = (slice(None),)*self.dimN + \ (slice(self.chncs[b], self.chncs[b+1]),) Sf = np.sum(self.cbpdn.Df[slc] * Xf, axis=self.cbpdn.cri.axisM) return sl.irfftn(Sf, self.cbpdn.cr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _fix_dynamic_class_lookup(cls, pstfx): """Fix name lookup problem that prevents pickling of dynamically defined classes. Parameters cls : class Dynamically g...
# Extended name for the class that will be added to the module namespace extnm = '_' + cls.__name__ + '_' + pstfx # Get the module in which the dynamic class is defined mdl = sys.modules[cls.__module__] # Allow lookup of the dynamically generated class within the module via # its extended name...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def solve_status_str(hdrlbl, fmtmap=None, fwdth0=4, fwdthdlt=6, fprec=2): """Construct header and format details for status display of an iterative solver. Param...
if fmtmap is None: fmtmap = {} fwdthn = fprec + fwdthdlt # Construct a list specifying the format string for each field. # Use format string from fmtmap if specified, otherwise use # a %d specifier with field width fwdth0 for the first field, # or a %e specifier with field width fwdth...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_attr(self, name, val, dval=None, dtype=None, reset=False): """Set an object attribute by its name. The attribute value can be specified as a primary valu...
# If `val` is None and `dval` is not None, replace it with dval if dval is not None and val is None: val = dval # If dtype is not None, assume val is numeric and convert it to # type dtype if dtype is not None and val is not None: if isinstance(dtype, t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_rank_limits(comm, arrlen): """Determine the chunk of the grid that has to be computed per process. The grid has been 'flattened' and has arrlen length. ...
rank = comm.Get_rank() # Id of this process size = comm.Get_size() # Total number of processes in communicator end = 0 # The scan should be done with ints, not floats ranklen = int(arrlen / size) if rank < arrlen % size: ranklen += 1 # Compute upper limit based on the sizes cover...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def relax_AX(self): """The parent class method that this method overrides only implements the relaxation step for the variables of the baseline consensus algorit...
super(ConvCnstrMODMaskDcpl_Consensus, self).relax_AX() self.AX1nr = sl.irfftn(sl.inner(self.Zf, self.swapaxes(self.Xf), axis=self.cri.axisM), self.cri.Nv, self.cri.axisN) if self.rlx == 1.0: self.AX1 = self.AX1n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def xstep(self): """The xstep of the baseline consensus class from which this class is derived is re-used to implement the xstep of the modified algorithm by rep...
self.YU1[:] = self.Y1 - self.U1 self.ZSf = np.conj(self.Zf) * (self.Sf + sl.rfftn( self.YU1, None, self.cri.axisN)) rho = self.rho self.rho = 1.0 super(ConvCnstrMODMaskDcpl_Consensus, self).xstep() self.rho = rho
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compute_residuals(self): """Compute residuals and stopping thresholds. The parent class method is overridden to ensure that the residual calculations include...
# The full primary residual is straightforward to compute from # the primary residuals for the baseline algorithm and for the # additional variables r0 = self.rsdl_r(self.AXnr, self.Y) r1 = self.AX1nr - self.Y1 - self.S r = np.sqrt(np.sum(r0**2) + np.sum(r1**2)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def obfn_fvar(self): """Variable to be evaluated in computing regularisation term, depending on 'fEvalX' option value. """
if self.opt['fEvalX']: return self.X else: return self.cnst_c() - self.cnst_B(self.Y)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def normalise(v): """Normalise columns of matrix. Parameters v : array_like Array with columns to be normalised Returns ------- vnrm : ndarray Normalised array "...
vn = np.sqrt(np.sum(v**2, 0)) vn[vn == 0] = 1.0 return np.asarray(v / vn, dtype=v.dtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rhochange(self): """Re-factorise matrix when rho changes"""
self.lu, self.piv = sl.lu_factor(self.Z, self.rho) self.lu = np.asarray(self.lu, dtype=self.dtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cupy_wrapper(func): """A wrapper function that converts numpy ndarray arguments to cupy arrays, and convert any cupy arrays returned by the wrapped function ...
@functools.wraps(func) def wrapped(*args, **kwargs): args = list(args) for n, a in enumerate(args): if isinstance(a, np.ndarray): args[n] = cp.asarray(a) for k, v in kwargs.items(): if isinstance(v, np.ndarray): kwargs[k] = cp.asa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block_sep1(self, Y): """Separate variable into component corresponding to Y1 in Y."""
Y1 = Y[..., self.cri.M:] # If cri.Cd > 1 (multi-channel dictionary), we need to undo the # reshape performed in block_cat if self.cri.Cd > 1: shp = list(Y1.shape) shp[self.cri.axisM] = self.cri.dimN shp[self.cri.axisC] = self.cri.Cd Y1 =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def block_cat(self, Y0, Y1): """Concatenate components corresponding to Y0 and Y1 blocks into Y. """
# Axes are swapped here for similar reasons to those # motivating swapping in cbpdn.ConvTwoBlockCnstrnt.block_cat Y1sa = np.swapaxes(Y1, self.cri.axisM, -1)[..., 0] # If cri.Cd > 1 (multi-channel dictionary) Y0 has a singleton # channel axis but Y1 has a non-singleton channel ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def obfn_g0var(self): """Variable to be evaluated in computing the TV regularisation term, depending on the ``gEvalY`` option value. """
# Use of self.block_sep0(self.AXnr) instead of self.cnst_A0(self.X) # reduces number of calls to self.cnst_A0 return self.var_y0() if self.opt['gEvalY'] else \ self.block_sep0(self.AXnr)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rhochange(self): """Re-factorise matrix when rho changes."""
self.lu, self.piv = sl.cho_factor(self.D, self.rho) self.lu = np.asarray(self.lu, dtype=self.dtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rhochange(self): """Action to be taken when rho parameter is changed."""
self.Gamma = 1.0 / (1.0 + (self.lmbda/self.rho)*(self.Alpha**2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpu_info(): """Return a list of namedtuples representing attributes of each GPU device. """
GPUInfo = namedtuple('GPUInfo', ['name', 'driver', 'totalmem', 'freemem']) gpus = GPUtil.getGPUs() info = [] for g in gpus: info.append(GPUInfo(g.name, g.driver, g.memoryTotal, g.memoryFree)) return info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gpu_load(wproc=0.5, wmem=0.5): """Return a list of namedtuples representing the current load for each GPU device. The processor and memory loads are fraction...
GPULoad = namedtuple('GPULoad', ['processor', 'memory', 'weighted']) gpus = GPUtil.getGPUs() load = [] for g in gpus: wload = (wproc * g.load + wmem * g.memoryUtil) / (wproc + wmem) load.append(GPULoad(g.load, g.memoryUtil, wload)) return load
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def device_by_load(wproc=0.5, wmem=0.5): """Get a list of GPU device ids ordered by increasing weighted average of processor and memory load. """
gl = gpu_load(wproc=wproc, wmem=wmem) # return np.argsort(np.asarray(gl)[:, -1]).tolist() return [idx for idx, load in sorted(enumerate( [g.weighted for g in gl]), key=(lambda x: x[1]))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_device_by_load(wproc=0.5, wmem=0.5): """Set the current device for cupy as the device with the lowest weighted average of processor and memory load. "...
ids = device_by_load(wproc=wproc, wmem=wmem) cp.cuda.Device(ids[0]).use() return ids[0]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_module(name): """Load the named module without registering it in ``sys.modules``. Parameters name : string Module name Returns ------- mod : module Load...
spec = importlib.util.find_spec(name) mod = importlib.util.module_from_spec(spec) mod.__spec__ = spec mod.__loader__ = spec.loader spec.loader.exec_module(mod) return mod
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def patch_module(name, pname, pfile=None, attrib=None): """Create a patched copy of the named module and register it in ``sys.modules``. Parameters name : string...
if attrib is None: attrib = {} spec = importlib.util.find_spec(name) spec.name = pname if pfile is not None: spec.origin = pfile spec.loader.name = pname mod = importlib.util.module_from_spec(spec) mod.__spec__ = spec mod.__loader__ = spec.loader sys.modules[pname] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sporco_cupy_patch_module(name, attrib=None): """Create a copy of the named sporco module, patch it to replace numpy with cupy, and register it in ``sys.modul...
# Patched module name is constructed from source module name # by replacing 'sporco.' with 'sporco.cupy.' pname = re.sub('^sporco.', 'sporco.cupy.', name) # Attribute dict always maps cupy module to 'np' attribute in # patched module if attrib is None: attrib = {} attrib.update({'n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _list2array(lst): """Convert a list to a numpy array."""
if lst and isinstance(lst[0], cp.ndarray): return cp.hstack(lst) else: return cp.asarray(lst)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_by_list_order(sortlist, reflist, reverse=False, fltr=False, slemap=None): """ Sort a list according to the order of entries in a reference list. Paramet...
def keyfunc(entry): if slemap is not None: rle = slemap(entry) if rle in reflist: # Ordering index taken from reflist return reflist.index(rle) else: # Ordering index taken from sortlist, offset # by the length of reflist so that ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_module_classes(module): """ Get a list of module member classes. Parameters module : string or module object Module for which member list is to be genera...
clslst = get_module_members(module, type=inspect.isclass) return list(filter(lambda cls: not issubclass(cls, Exception), clslst))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_module_docs(pkgname, modpath, tmpltpath, outpath): """ Write the autosummary style docs for the specified package. Parameters pkgname : string Name of ...
dw = DocWriter(outpath, tmpltpath) modlst = get_module_names(modpath, pkgname) print('Making api docs:', end='') for modname in modlst: # Don't generate docs for cupy or cuda subpackages if 'cupy' in modname or 'cuda' in modname: continue try: mod = i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write(self, module): """ Write the RST source document for generating the docs for a specified module. Parameters module : module object Module for which mem...
modname = module.__name__ # Based on code in generate_autosummary_docs in https://git.io/fxpJS ns = {} ns['members'] = dir(module) ns['functions'] = list(map(lambda x: x.__name__, get_module_functions(module))) ns['classes'] = list(ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isxmap(xmethod, opt): """Return ``isxmap`` argument for ``.IterStatsConfig`` initialiser. """
if xmethod == 'admm': isx = {'XPrRsdl': 'PrimalRsdl', 'XDlRsdl': 'DualRsdl', 'XRho': 'Rho'} else: isx = {'X_F_Btrack': 'F_Btrack', 'X_Q_Btrack': 'Q_Btrack', 'X_ItBt': 'IterBTrack', 'X_L': 'L', 'X_Rsdl': 'Rsdl'} if not opt['AccurateDFid']: isx.update(ev...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def isfld(xmethod, dmethod, opt): """Return ``isfld`` argument for ``.IterStatsConfig`` initialiser. """
fld = ['Iter', 'ObjFun', 'DFid', 'RegL1', 'Cnstr'] if xmethod == 'admm': fld.extend(['XPrRsdl', 'XDlRsdl', 'XRho']) else: if opt['CBPDN', 'BackTrack', 'Enabled']: fld.extend(['X_F_Btrack', 'X_Q_Btrack', 'X_ItBt', 'X_L', 'X_Rsdl']) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iterstats(self, j, t, isx, isd, evl): """Construct IterationStats namedtuple from X step and D step IterationStats namedtuples. Parameters j : int Iteration ...
vlst = [] # Iterate over the fields of the IterationStats namedtuple # to be populated with values. If a field name occurs as a # key in the isxmap dictionary, use the corresponding key # value as a field name in the isx namedtuple for the X # step object and append the...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def printiterstats(self, itst): """Print iteration statistics. Parameters itst : namedtuple IterationStats namedtuple as returned by :meth:`iterstats` """
itdsp = tuple([getattr(itst, self.hdrmap[col]) for col in self.hdrtxt]) print(self.fmtstr % itdsp)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def norm_nuclear(X): r"""Compute the nuclear norm .. math:: \| X \|_* = \sum_i \sigma_i where :math:`\sigma_i` are the singular values of matrix :math:`X`. Param...
return np.sum(np.linalg.svd(sl.promote16(X), compute_uv=False))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deprecate(func): """ A deprecation warning emmiter as a decorator. """
@wraps(func) def wrapper(*args, **kwargs): warn("Deprecated, this will be removed in the future", DeprecationWarning) return func(*args, **kwargs) wrapper.__doc__ = "Deprecated.\n" + (wrapper.__doc__ or "") return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_module_names(package_path, pattern="lazy_*.py*"): """ All names in the package directory that matches the given glob, without their extension. Repeated n...
package_contents = glob(os.path.join(package_path[0], pattern)) relative_path_names = (os.path.split(name)[1] for name in package_contents) no_ext_names = (os.path.splitext(name)[0] for name in relative_path_names) return sorted(set(no_ext_names))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_modules(package_name, module_names): """ List of module objects from the package, keeping the name order. """
def get_module(name): return __import__(".".join([package_name, name]), fromlist=[package_name]) return [get_module(name) for name in module_names]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def docstring_with_summary(docstring, pairs, key_header, summary_type): """ Return a string joining the docstring with the pairs summary table. """
return "\n".join( [docstring, "Summary of {}:".format(summary_type), ""] + summary_table(pairs, key_header) + [""] )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def memoize(func): """ Decorator for unerasable memoization based on function arguments, for functions without keyword arguments. """
class Memoizer(dict): def __missing__(self, args): val = func(*args) self[args] = val return val memory = Memoizer() @wraps(func) def wrapper(*args): return memory[args] return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_to_16bit_wave_file(fname, sig, rate): """ Save a given signal ``sig`` to file ``fname`` as a 16-bit one-channel wave with the given ``rate`` sample rate...
with closing(wave.open(fname, "wb")) as wave_file: wave_file.setnchannels(1) wave_file.setsampwidth(2) wave_file.setframerate(rate) for chunk in chunks((clip(sig) * 2 ** 15).map(int), dfmt="h", padval=0): wave_file.writeframes(chunk)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_note_track(env, synth): """ Audio track with the frequencies. Parameters env: Envelope Stream (which imposes the duration). synth: One-argument function ...
list_env = list(env) return chain.from_iterable(synth(freq) * list_env for freq in freq_gen())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tostream(func, module_name=None): """ Decorator to convert the function output into a Stream. Useful for generator functions. Note ---- Always use the ``modu...
@wraps(func) def new_func(*args, **kwargs): return Stream(func(*args, **kwargs)) if module_name is not None: new_func.__module__ = module_name return new_func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def thub(data, n): """ Tee or "T" hub auto-copier to help working with Stream instances as well as with numbers. Parameters data : Input to be copied. Can be any...
return StreamTeeHub(data, n) if isinstance(data, Iterable) else data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def blocks(self, *args, **kwargs): """ Interface to apply audiolazy.blocks directly in a stream, returning another stream. Use keyword args. """
return Stream(blocks(iter(self), *args, **kwargs))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def take(self, n=None, constructor=list): """ Returns a container with the n first elements from the Stream, or less if there aren't enough. Use this without arg...
if n is None: return next(self._data) if isinf(n) and n > 0: return constructor(self._data) if isinstance(n, float): n = rint(n) if n > 0 else 0 # So this works with -inf and nan return constructor(next(self._data) for _ in xrange(n))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def skip(self, n): """ Throws away the first ``n`` values from the Stream. Note ---- Performs the evaluation lazily, i.e., the values are thrown away only after ...
def skipper(data): for _ in xrange(int(round(n))): next(data) for el in data: yield el self._data = skipper(self._data) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def limit(self, n): """ Enforces the Stream to finish after ``n`` items. """
data = self._data self._data = (next(data) for _ in xrange(int(round(n)))) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filter(self, func): """ A lazy way to skip elements in the stream that gives False for the given function. """
self._data = xfilter(func, self._data) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def accumulate(iterable): " Return series of accumulated sums. " iterator = iter(iterable) sum_data = next(iterator) yield sum_data for el in iterator: sum_data += el yield sum_data
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tee(data, n=2): """ Tee or "T" copy to help working with Stream instances as well as with numbers. Parameters data : Input to be copied. Can be anything. n :...
if isinstance(data, (Stream, Iterator)): return tuple(Stream(cp) for cp in it.tee(data, n)) else: return tuple(data for unused in xrange(n))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def factorial(n): """ Factorial function that works with really big numbers. """
if isinstance(n, float): if n.is_integer(): n = int(n) if not isinstance(n, INT_TYPES): raise TypeError("Non-integer input (perhaps you need Euler Gamma " "function or Gauss Pi function)") if n < 0: raise ValueError("Input shouldn't be negative") return reduce(operator.mul...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mgl_seq(x): """ Sequence whose sum is the Madhava-Gregory-Leibniz series. Returns ------- An endless sequence that has the property ``atan(x) = sum(mgl_seq(x...
odd_numbers = thub(count(start=1, step=2), 2) return Stream(1, -1) * x ** odd_numbers / odd_numbers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def atan_mgl(x, n=10): """ Finds the arctan using the Madhava-Gregory-Leibniz series. """
acc = 1 / (1 - z ** -1) # Accumulator filter return acc(mgl_seq(x)).skip(n-1).take()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lagrange(pairs): """ Waring-Lagrange interpolator function. Parameters pairs : Iterable with pairs (tuples with two values), corresponding to points ``(x, y)...
prod = lambda args: reduce(operator.mul, args) xv, yv = xzip(*pairs) return lambda k: sum( yv[j] * prod( (k - rk) / (rj - rk) for rk in xv if rj != rk ) for j, rj in enumerate(xv) )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resample(sig, old=1, new=1, order=3, zero=0.): """ Generic resampler based on Waring-Lagrange interpolators. Parameters sig : Input signal (any iterable). ol...
sig = Stream(sig) threshold = .5 * (order + 1) step = old / new data = deque([zero] * (order + 1), maxlen=order + 1) data.extend(sig.take(rint(threshold))) idx = int(threshold) isig = iter(sig) if isinstance(step, Iterable): step = iter(step) while True: yield lagrange(enumerate(data))(id...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_polynomial(self): """ Tells whether it is a linear combination of natural powers of ``x``. """
return all(isinstance(k, INT_TYPES) and k >= 0 for k in self._data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def order(self): """ Finds the polynomial order. Examples -------- 1 18 0 Traceback (most recent call last): AttributeError: Power needs to be positive integers...
if not self.is_polynomial(): raise AttributeError("Power needs to be positive integers") return max(key for key in self._data) if self._data else 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def integrate(self): """ Integrate without adding an integration constant. """
if -1 in self._data: raise ValueError("Unable to integrate term that powers to -1") return Poly(OrderedDict((k + 1, v / (k + 1)) for k, v in iteritems(self._data)), zero=self.zero)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def roots(self): """ Returns a list with all roots. Needs Numpy. """
import numpy as np return np.roots(list(self.values())[::-1]).tolist()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _exec_eval(data, expr): """ Internal function to isolate an exec. Executes ``data`` and returns the ``expr`` evaluation afterwards. """
ns = {} exec(data, ns) return eval(expr, ns)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def highpass(cutoff): """ This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the one-pole Laplace lowpass filte...
R = thub(exp(cutoff - pi), 2) return (1 - R) / (1 + R * z ** -1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def lowpass(cutoff): """ This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the single pole and single zero Lap...
R = thub(exp(cutoff - pi), 2) G = (R + 1) / 2 return G * (1 + z ** -1) / (1 + R * z ** -1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def highpass(cutoff): """ This strategy uses an exponential approximation for cut-off frequency calculation, found by matching the single pole and single zero La...
R = thub(exp(-cutoff), 2) G = (R + 1) / 2 return G * (1 - z ** -1) / (1 - R * z ** -1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_linear(self): """ Tests whether all filters in the list are linear. CascadeFilter and ParallelFilter instances are also linear if all filters they group a...
return all(isinstance(filt, LinearFilter) or (hasattr(filt, "is_linear") and filt.is_linear()) for filt in self.callables)