Unit-level magnitude pruning.
975485
def unit_targeting(w, k):
  """"""
  k = tf.to_int32(k)
  w_shape = shape_list(w)
  size = tf.to_int32(tf.reduce_prod(w_shape[:-1]))
  w = tf.reshape(w, [size, w_shape[-1]])

  norm = tf.norm(w, axis=0)
  thres = tf.contrib.framework.sort(norm, axis=0)[k]
  mask = to_float(thres >= norm)[None, :]
  mask = tf.tile(mask, [size, 1])

  return tf.reshape(mask, w_shape)
983654
def prune(self, node_thres, edge_thres, paths, color_nodes_by_selftime):
        """"""

        # compute the prune ratios
        for function in compat_itervalues(self.functions):
            try:
                function.weight = function[TOTAL_TIME_RATIO]
            except UndefinedEvent:
                pass

            for call in compat_itervalues(function.calls):
                callee = self.functions[call.callee_id]

                if TOTAL_TIME_RATIO in call:
                    # handle exact cases first
                    call.weight = call[TOTAL_TIME_RATIO] 
                else:
                    try:
                        # make a safe estimate
                        call.weight = min(function[TOTAL_TIME_RATIO], callee[TOTAL_TIME_RATIO]) 
                    except UndefinedEvent:
                        pass

        # prune the nodes
        for function_id in compat_keys(self.functions):
            function = self.functions[function_id]
            if function.weight is not None:
                if function.weight < node_thres:
                    del self.functions[function_id]
        
        # prune file paths
        for function_id in compat_keys(self.functions):
            function = self.functions[function_id]
            if paths and function.filename and not any(function.filename.startswith(path) for path in paths):
                del self.functions[function_id]
            elif paths and function.module and not any((function.module.find(path)>-1) for path in paths):
                del self.functions[function_id]

        # prune the edges
        for function in compat_itervalues(self.functions):
            for callee_id in compat_keys(function.calls):
                call = function.calls[callee_id]
                if callee_id not in self.functions or call.weight is not None and call.weight < edge_thres:
                    del function.calls[callee_id]

        if color_nodes_by_selftime:
            weights = []
            for function in compat_itervalues(self.functions):
                try:
                    weights.append(function[TIME_RATIO])
                except UndefinedEvent:
                    pass
            max_ratio = max(weights or [1])

            # apply rescaled weights for coloriung
            for function in compat_itervalues(self.functions):
                try:
                    function.weight = function[TIME_RATIO] / max_ratio
                except (ZeroDivisionError, UndefinedEvent):
                    pass
802461
def conv(attrs, inputs, proto_obj):
    """"""
    new_attrs = translation_utils._fix_attribute_names(attrs, {'kernel_shape' : 'kernel',
                                                               'strides' : 'stride',
                                                               'pads': 'pad',
                                                               'dilations': 'dilate',
                                                               'group': 'num_group'})
    new_attrs = translation_utils._add_extra_attributes(new_attrs, {'num_group' : 1})
    new_attrs = translation_utils._fix_bias('Convolution', new_attrs, len(inputs))

    new_attrs = translation_utils._fix_channels('Convolution', new_attrs, inputs, proto_obj)
    kernel = new_attrs['kernel']
    stride = new_attrs['stride'] if 'stride' in new_attrs else []
    padding = new_attrs['pad'] if 'pad' in new_attrs else []
    dilations = new_attrs['dilate'] if 'dilate' in new_attrs else []
    num_filter = new_attrs['num_filter']
    num_group = new_attrs['num_group']
    no_bias = new_attrs['no_bias'] if 'no_bias' in new_attrs else 0
    bias = None if no_bias is True else inputs[2]

    # Unlike ONNX, MXNet's convolution operator does not support asymmetric padding, so we first
    # use 'Pad' operator, which supports asymmetric padding. Then use the convolution operator.
    pad_width = (0, 0, 0, 0) + translation_utils._pad_sequence_fix(padding, kernel_dim=len(kernel))
    pad_op = symbol.pad(inputs[0], mode='constant', pad_width=pad_width)

    conv_op = symbol.Convolution(pad_op, inputs[1], bias,
                                 kernel=kernel, stride=stride, dilate=dilations,
                                 num_filter=num_filter, num_group=num_group, no_bias=no_bias)

    return conv_op, new_attrs, inputs
618504
def _extract_gaussian_gradient_magnitude(image, mask = slice(None), sigma = 1, voxelspacing = None):
    
    # set voxel spacing
    if voxelspacing is None:
        voxelspacing = [1.] * image.ndim
        
    # determine gaussian kernel size in voxel units
    sigma = _create_structure_array(sigma, voxelspacing)
        
    return _extract_intensities(scipy_gaussian_gradient_magnitude(image, sigma), mask)
388148
def pruneWeights(self, minWeight):
    
    if minWeight == 0.0:
      return

    # Collect all weights
    weights = [v for k, v in self.named_parameters() if 'weight' in k]
    for w in weights:
      # Filter weights above threshold
      mask = torch.ge(torch.abs(w.data), minWeight)
      # Zero other weights
      w.data.mul_(mask.type(torch.float32))
413888
def maskedFilter(arr, mask, ksize=30, fill_mask=True,
                 fn='median'):
    '''
    
    '''

    if fill_mask:
        mask1 = mask
        out = arr
    else:
        mask1 = ~mask
        out = np.full_like(arr, fill_value=np.nan)
    mask2 = ~mask

    if fn == 'mean':
        _calcMean(arr, mask1, mask2, out, ksize // 2)
    else:
        buff = np.empty(shape=(ksize * ksize), dtype=arr.dtype)
        _calcMedian(arr, mask1, mask2, out, ksize // 2, buff)
    return out
1017029
def _threshold_batch(self,
                         vectors,
                         batch_size,
                         threshold,
                         show_progressbar,
                         return_names):
        """"""
        vectors = self.normalize(vectors)

        # Single transpose, makes things faster.
        reference_transposed = self.norm_vectors.T

        for i in tqdm(range(0, len(vectors), batch_size),
                      disable=not show_progressbar):

            distances = vectors[i: i+batch_size].dot(reference_transposed)
            # For safety we clip
            distances = np.clip(distances, a_min=.0, a_max=1.0)
            for lidx, dists in enumerate(distances):
                indices = np.flatnonzero(dists >= threshold)
                sorted_indices = indices[np.argsort(-dists[indices])]
                if return_names:
                    yield [(self.indices[d], dists[d])
                           for d in sorted_indices]
                else:
                    yield list(dists[sorted_indices])
1309932
def _prune_edges(G, X, traj_lengths, pruning_thresh=0.1, verbose=False):
  ''''''
  W = G.matrix('dense', copy=True)
  degree = G.degree(kind='out', weighted=False)
  i = 0
  num_bad = 0
  for n in traj_lengths:
    s, t = np.nonzero(W[i:i+n-1])
    graph_edges = X[t] - X[s+i]
    traj_edges = np.diff(X[i:i+n], axis=0)
    traj_edges = np.repeat(traj_edges, degree[i:i+n-1], axis=0)
    theta = paired_distances(graph_edges, traj_edges, 'cosine')
    bad_edges = theta > pruning_thresh
    s, t = s[bad_edges], t[bad_edges]
    if verbose:  # pragma: no cover
      num_bad += np.count_nonzero(W[s,t])
    W[s,t] = 0
    i += n
  if verbose:  # pragma: no cover
    print('removed %d bad edges' % num_bad)
  return Graph.from_adj_matrix(W)
165763
def _coarsenImage(image, f):
    '''
    
    '''
    from skimage.morphology import square
    from skimage.filters import rank
    from skimage.transform._warps import rescale
    selem = square(f)
    arri = rank.mean(image, selem=selem)
    return rescale(arri, 1 / f, order=0)
1363236
def normalize_features(features):
    """"""
    return (features - N.min(features)) / (N.max(features) - N.min(features))
826835
private ContributorList calcXContrib(double xscale, double fwidth, int srcwidth, InterpolationFilter pFilter, int i) {
        // TODO: What to do when fwidth > srcwidyj or dstwidth

        double width;
        double fscale;
        double center;
        double weight;

        ContributorList contribX = new ContributorList();

        if (xscale < 1.0) {
            /* Shrinking image */
            width = fwidth / xscale;
            fscale = 1.0 / xscale;

            if (width <= .5) {
                // Reduce to point sampling.
                width = .5 + 1.0e-6;
                fscale = 1.0;
            }

            //contribX.n = 0;
            contribX.p = new Contributor[(int) (width * 2.0 + 1.0 + 0.5)];

            center = (double) i / xscale;
            int left = (int) Math.ceil(center - width);// Note: Assumes width <= .5
            int right = (int) Math.floor(center + width);

            double density = 0.0;

            for (int j = left; j <= right; j++) {
                weight = center - (double) j;
                weight = pFilter.filter(weight / fscale) / fscale;
                int n;
                if (j < 0) {
                    n = -j;
                }
                else if (j >= srcwidth) {
                    n = (srcwidth - j) + srcwidth - 1;
                }
                else {
                    n = j;
                }

                /**/
                if (n >= srcwidth) {
                    n = n % srcwidth;
                }
                else if (n < 0) {
                    n = srcwidth - 1;
                }
                /**/

                int k = contribX.n++;
                contribX.p[k] = new Contributor();
                contribX.p[k].pixel = n;
                contribX.p[k].weight = weight;

                density += weight;

            }

            if ((density != 0.0) && (density != 1.0)) {
                //Normalize.
                density = 1.0 / density;
                for (int k = 0; k < contribX.n; k++) {
                    contribX.p[k].weight *= density;
                }
            }
        }
        else {
            /* Expanding image */
            //contribX.n = 0;
            contribX.p = new Contributor[(int) (fwidth * 2.0 + 1.0 + 0.5)];

            center = (double) i / xscale;
            int left = (int) Math.ceil(center - fwidth);
            int right = (int) Math.floor(center + fwidth);

            for (int j = left; j <= right; j++) {
                weight = center - (double) j;
                weight = pFilter.filter(weight);

                int n;
                if (j < 0) {
                    n = -j;
                }
                else if (j >= srcwidth) {
                    n = (srcwidth - j) + srcwidth - 1;
                }
                else {
                    n = j;
                }

                /**/
                if (n >= srcwidth) {
                    n = n % srcwidth;
                }
                else if (n < 0) {
                    n = srcwidth - 1;
                }
                /**/

                int k = contribX.n++;
                contribX.p[k] = new Contributor();
                contribX.p[k].pixel = n;
                contribX.p[k].weight = weight;
            }
        }
        return contribX;
    }
1016176
public static void magnitude( ImageInterleaved transform , GrayF magnitude ) {
		if( transform instanceof InterleavedF32 ) {
			DiscreteFourierTransformOps.magnitude((InterleavedF32) transform, (GrayF32) magnitude);
		} else if( transform instanceof InterleavedF64 ) {
			DiscreteFourierTransformOps.magnitude((InterleavedF64) transform, (GrayF64) magnitude);
		} else {
			throw new IllegalArgumentException("Unknown image type");
		}
	}
193844
def _preprocess_inputs(x, weights):
    
    if weights is None:
        w_arr = np.ones(len(x))
    else:
        w_arr = np.array(weights)
    x_arr = np.array(x)
    if x_arr.ndim == 2:
        if w_arr.ndim == 1:
            w_arr = w_arr[:, np.newaxis]
    return x_arr, w_arr
785699
def tenengrad(img, ksize=3):
    '''''''
    Gx = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=ksize)
    Gy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=ksize)
    FM = Gx*Gx + Gy*Gy
    mn = cv2.mean(FM)[0]
    if np.isnan(mn):
        return np.nanmean(FM)
    return mn
1061010
void pruneNearlyIdenticalAngles() {
		for (int i = 0; i < listInfo.size(); i++) {
			NodeInfo infoN = listInfo.get(i);

			for (int j = 0; j < infoN.edges.size(); ) {
				int k = (j+1)%infoN.edges.size;

				double angularDiff = UtilAngle.dist(infoN.edges.get(j).angle,infoN.edges.get(k).angle);
				if( angularDiff < UtilAngle.radian(5)) {
					NodeInfo infoJ = infoN.edges.get(j).target;
					NodeInfo infoK = infoN.edges.get(k).target;

					double distJ = infoN.ellipse.center.distance(infoJ.ellipse.center);
					double distK = infoN.ellipse.center.distance(infoK.ellipse.center);

					if( distJ < distK ) {
						infoN.edges.remove(k);
					} else {
						infoN.edges.remove(j);
					}

				} else {
					j++;
				}
			}
		}
	}
699394
private static double snorm(double[] x, int itol) {
        int n = x.length;

        if (itol <= 3) {
            double ans = 0.0;
            for (int i = 0; i < n; i++) {
                ans += x[i] * x[i];
            }
            return Math.sqrt(ans);
        } else {
            int isamax = 0;
            for (int i = 0; i < n; i++) {
                if (Math.abs(x[i]) > Math.abs(x[isamax])) {
                    isamax = i;
                }
            }

            return Math.abs(x[isamax]);
        }
    }
250236
def separable_conv_block(inputs, filters, dilation_rates_and_kernel_sizes,
                         **kwargs):
  """"""
  return conv_block_internal(separable_conv, inputs, filters,
                             dilation_rates_and_kernel_sizes, **kwargs)