Maximum 3D pooling op.
338765
def MaxPool3D(a, k, strides, padding):
    
    patches = _pool_patches(a, k, strides, padding.decode("ascii"))
    return np.amax(patches, axis=tuple(range(-len(k), 0))),
1287251
def _run_opf(self, P, q, AA, ll, uu, xmin, xmax, x0, opt):
        
        AAcvx = tocvx(AA)
        nx = x0.shape[0] # number of variables
        # add var limits to linear constraints
        eyex = spmatrix(1.0, range(nx), range(nx))
        A = sparse([eyex, AAcvx])
        l = matrix([-xmin, ll])
        u = matrix([ xmax, uu])

        Ae, be, Ai, bi = split_linear_constraints(A, l, u)


        if len(P.V) > 0:
            cvx_sol = solvers.qp(P, q, Ai, bi, Ae, be, self.solver, {"x": x0})
        else:
            cvx_sol = solvers.lp(q, Ai, bi, Ae, be, self.solver, {"x": x0})

        return cvx_sol
163014
protected void findLocalScaleSpaceMax(PyramidFloat<T> ss, int layerID) {
		List<Point2D_I16> candidates = maximums;

		float scale0 = (float) ss.scale[layerID - 1];
		float scale1 = (float) ss.scale[layerID];
		float scale2 = (float) ss.scale[layerID + 1];

		float sigma0 = (float) ss.getSigma(layerID - 1);
		float sigma1 = (float) ss.getSigma(layerID);
		float sigma2 = (float) ss.getSigma(layerID + 1);

		// For laplacian its t^(2*gamma) where gamma = 3/4
		float ss0 = (float) (Math.pow(sigma0, 2.0 * 0.75)/scale0);// Is this divide by scale correct?
		float ss1 = (float) (Math.pow(sigma1, 2.0 * 0.75)/scale1);
		float ss2 = (float) (Math.pow(sigma2, 2.0 * 0.75)/scale2);

		for (Point2D_I16 c : candidates) {

			GrayF32 intensity = detector.getIntensity();

			float target = intensity.unsafe_get(c.x,c.y);
			float fx,fy;
			{
				float x0 = intensity.unsafe_get(c.x - 1, c.y);
				float x2 = intensity.unsafe_get(c.x + 1, c.y);
				float y0 = intensity.unsafe_get(c.x, c.y - 1);
				float y2 = intensity.unsafe_get(c.x, c.y + 1);

				fx = c.x + polyPeak(x0, target, x2);
				fy = c.y + polyPeak(y0, target, y2);
			}
//			fx=c.x;fy=c.y;

			sparseLaplace.setImage(ss.getLayer(layerID));
			float val = ss1 * (float) sparseLaplace.compute(c.x,c.y);
			// search for local maximum or local minimum
			float adj = Math.signum(val);
			val *= adj;


			// find pixel location in each image's local coordinate
			int x0 = (int) (fx * scale1 / scale0 + 0.5);
			int y0 = (int) (fy * scale1 / scale0 + 0.5);

			int x2 = (int) (fx * scale1 / scale2 + 0.5);
			int y2 = (int) (fy * scale1 / scale2 + 0.5);

			if (checkMax(ss.getLayer(layerID - 1), adj*ss0,val, x0, y0) && checkMax(ss.getLayer(layerID + 1), adj*ss2,val, x2, y2)) {
				sparseLaplace.setImage(ss.getLayer(layerID-1));
				float s0 = ss0 * (float) sparseLaplace.compute(x0,y0)*adj;
				sparseLaplace.setImage(ss.getLayer(layerID+1));
				float s2 = ss2 * (float) sparseLaplace.compute(x2,y2)*adj;

				double adjSigma;
				double sigmaInterp = polyPeak(s0, val, s2); // scaled from -1 to 1
				if( sigmaInterp < 0 ) {
					adjSigma = sigma0*(-sigmaInterp) + (1+sigmaInterp)*sigma1;
				} else {
					adjSigma = sigma2*sigmaInterp + (1-sigmaInterp)*sigma1;
				}

				// put features into the scale of the upper image
				foundPoints.add(new ScalePoint(fx * scale1, fy * scale1, adjSigma));
			}
		}
	}
195951
def capture(cb, pool, params):
    
    w, h = screen_resolution()

    # Re-adapt dimensions to match current plane ratio
    old_ratio = w / h
    new_ratio = params.plane_ratio
    if old_ratio > new_ratio:
        w = int(h * new_ratio)
    else:
        h = int(w / new_ratio)

    image = Image.new("RGB", (w, h), "white")
    pixels = image.load()

    # FIXME: refactor common code to get_palette(params)
    palette = PALETTES[params.palette][1]
    if params.reverse_palette:
        palette = palette[::-1]

    # All coordinates to be computed as single arguments for processes
    coords = [(x, y, w, h, params) for x in range(w) for y in range(h)]

    results = []
    # Dispatch work to pool and draw results as they come in
    for i, result in enumerate(pool.imap_unordered(compute_capture, coords, chunksize=256)):
        results.append(result)
        if i % 2000 == 0:
            draw_progress_bar(cb, "Capturing current scene...", i, w * h)
            cb.refresh()

    min_value = 0.0
    max_value = params.max_iterations
    max_iterations = params.max_iterations

    if params.adaptive_palette:
        from operator import itemgetter
        min_value = min(results, key=itemgetter(2))[2]
        max_value = max(results, key=itemgetter(2))[2]

    # Draw pixels
    for result in results:
        value = result[2]
        if params.adaptive_palette:
            # Remap values from (min_value, max_value) to (0, max_iterations)
            if max_value - min_value > 0:
                value = ((value - min_value) / (max_value - min_value)) * max_iterations
            else:
                value = max_iterations
        pixels[result[0], result[1]] = get_color(value, params.max_iterations, palette)

    if not os.path.exists("captures/"):
        os.makedirs("captures/")

    ts = datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d_%H-%M-%S")
    filename = "captures/almonds_%s.png" % ts
    image.save(filename, "PNG")
    params.log("Current scene captured!")
    params.log("(Used %d processes)" % pool._processes)

    open_file(filename)
1044815
def cublasZsyr(handle, uplo, n, alpha, x, incx, A, lda):
    

    status = _libcublas.cublasZsyr_v2(handle,
                                        _CUBLAS_FILL_MODE[uplo], n, 
                                        ctypes.byref(cuda.cuDoubleComplex(alpha.real,
                                                                        alpha.imag)),
                                        int(x), incx, int(A), lda)
    cublasCheckStatus(status)
661100
def global_lppooling(attrs, inputs, proto_obj):
    """"""
    p_value = attrs.get('p', 2)
    new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True,
                                                                'kernel': (1, 1),
                                                                'pool_type': 'lp',
                                                                'p_value': p_value})
    new_attrs = translation_utils._remove_attributes(new_attrs, ['p'])
    return 'Pooling', new_attrs, inputs
1058325
public SDVariable maxPooling2d(SDVariable input, Pooling2DConfig pooling2DConfig) {
        MaxPooling2D maxPooling2D = MaxPooling2D.builder()
                .input(input)
                .sameDiff(sameDiff())
                .config(pooling2DConfig)
                .build();

        return maxPooling2D.outputVariable();
    }
498994
def _amp2d_to_3d(self, amp, sigma_x, sigma_y):
        
        return amp / (np.sqrt(np.pi) * np.sqrt(sigma_x * sigma_y * 2))
375904
public static void depthTo3D(CameraPinholeBrown param , GrayU16 depth , FastQueue<Point3D_F64> cloud ) {
		cloud.reset();

		Point2Transform2_F64 p2n = LensDistortionFactory.narrow(param).undistort_F64(true,false);

		Point2D_F64 n = new Point2D_F64();

		for( int y = 0; y < depth.height; y++ ) {
			int index = depth.startIndex + y*depth.stride;
			for( int x = 0; x < depth.width; x++ ) {
				int mm = depth.data[index++] & 0xFFFF;

				// skip pixels with no depth information
				if( mm == 0 )
					continue;

				// this could all be precomputed to speed it up
				p2n.compute(x,y,n);

				Point3D_F64 p = cloud.grow();
				p.z = mm;
				p.x = n.x*p.z;
				p.y = n.y*p.z;
			}
		}
	}
988274
def cublasCher2k(handle, uplo, trans, n, k, alpha, A, lda, B, ldb, beta, C, ldc):
    
    
    status = _libcublas.cublasCher2k_v2(handle, 
                                        _CUBLAS_FILL_MODE[uplo], 
                                        _CUBLAS_OP[trans], 
                                        n, k, ctypes.byref(cuda.cuFloatComplex(alpha.real,                 
                                                                               alpha.imag)),
                                        int(A), lda, int(B), ldb, 
                                        ctypes.byref(cuda.cuFloatComplex(beta.real,
                                                                         beta.imag)),
                                        int(C), ldc)
    cublasCheckStatus(status)
17620
def conv3x3(in_planes, out_planes, fn, stride=1):
    """"""
    return fn(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
1374164
def cublasChpr(handle, uplo, n, alpha, x, incx, AP):
    
    
    status = _libcublas.cublasChpr_v2(handle, 
                                      _CUBLAS_FILL_MODE[uplo], 
                                      n, ctypes.byref(ctypes.c_float(alpha)),
                                      int(x), incx, int(AP))
    cublasCheckStatus(status)
398919
private void estimateAllFeatures(View seedA, View seedB ) {
		List<View> open = new ArrayList<>();

		// Add features for all the other views connected to the root view and determine the translation scale factor
		addUnvistedToStack(seedA, open);
		addUnvistedToStack(seedB, open);

		// Do a breath first search. The queue is first in first out
		while( !open.isEmpty() ) {
			if( stopRequested )
				return;
			if( verbose != null )
				verbose.println("### open.size="+open.size());

			// select the view with the 3D features. This view can be estimated which the highest degree of confience
			int bestCount = countFeaturesWith3D(open.get(0));
			int bestIndex = 0;

			for (int i = 1; i < open.size(); i++) {
				int count = countFeaturesWith3D(open.get(i));
				if( count > bestCount ) {
					bestCount = count;
					bestIndex = i;
				}
			}

			View v = open.remove(bestIndex);
			if( verbose != null )
				verbose.println("   processing view="+v.index+" | 3D Features="+bestCount);

			// Determine the view's location in the 3D view. This might have been previously estimated using
			// stereo and the estimated scale factor. That will be ignored and the new estimate used instead
			if( !determinePose(v) ) {
//				// The pose could not be determined, so remove it from the graph
//				if( verbose != null )
//					verbose.println("   Removing connection");
//				for (CameraMotion m : v.connections) {
//					CameraView a = m.destination(v);
//					a.connections.remove(m);
//					graph.edges.remove(m);
//				}
//				graph.nodes.remove(v);
//
//				for (int i = 0; i < graph.nodes.size(); i++) {
//					graph.nodes.get(i).index = i;
//				}

				// TODO mark instead of remove? Need a unit test for remove
				throw new RuntimeException("Crap handle this");
			} else {
				// If possible use triangulation from stereo
				addTriangulatedFeaturesForAllEdges(v);
				triangulateNoLocation(v);

				viewsAdded.add(v);

				// Update the open list
				addUnvistedToStack(v, open);
			}
		}
	}
1069790
def _fix_pooling(pool_type, inputs, new_attr):
    """"""
    stride = new_attr.get('stride')
    kernel = new_attr.get('kernel')
    padding = new_attr.get('pad')
    p_value = new_attr.get('p_value')

    # Adding default stride.
    if stride is None:
        stride = (1,) * len(kernel)

    # Add padding attr if not provided.
    if padding is None:
        padding = (0,) * len(kernel) * 2

    # Mxnet Pad operator supports only 4D/5D tensors.
    # For 1D case, these are the steps:
    #    Step 1. Add extra dummy dimension to make it 4D. Adding to  axis = 2
    #    Step 2. Apply padding to this changed tensor
    #    Step 3. Remove the extra dimension added in step 1.
    if len(kernel) == 1:
        dummy_axis = 2
        # setting 0 padding to the new dim to be added.
        padding = (0, padding[0], 0, padding[1])
        pad_width = (0, 0, 0, 0) + _pad_sequence_fix(padding, kernel_dim=2)

        # Step 1.
        curr_sym = symbol.expand_dims(inputs[0], axis=dummy_axis)

        # Step 2. Common for all tensor sizes
        new_pad_op = symbol.pad(curr_sym, mode='edge', pad_width=pad_width)

        # Step 3: Removing extra dim added.
        new_pad_op = symbol.split(new_pad_op, axis=dummy_axis, num_outputs=1, squeeze_axis=1)
    else:
        # For 2D/3D cases:
        # Apply padding
        pad_width = (0, 0, 0, 0) + _pad_sequence_fix(padding, kernel_dim=len(kernel))
        curr_sym = inputs[0]

        if pool_type == 'max':
            # For max pool : mode = 'edge', we should replicate the
            # edge values to pad, so that we only include  input data values
            # for calculating 'max'
            new_pad_op = symbol.pad(curr_sym, mode='edge', pad_width=pad_width)
        else:
            # For avg pool, we should add 'zeros' for padding  so mode='constant'
            new_pad_op = symbol.pad(curr_sym, mode='constant', pad_width=pad_width)

    # Apply pooling without pads.
    if pool_type == 'lp':
        new_pooling_op = symbol.Pooling(new_pad_op, pool_type=pool_type, stride=stride, kernel=kernel, p_value=p_value)
    else:
        new_pooling_op = symbol.Pooling(new_pad_op, pool_type=pool_type, stride=stride, kernel=kernel)
    return new_pooling_op
93326
public boolean estimatePlaneAtInfinity( DMatrixRMaj P2 , Vector3D_F64 v ) {
		PerspectiveOps.projectionSplit(P2,Q2,q2);

		// inv(K2)*(Q2*K1 + q2*v')
		CommonOps_DDF3.mult(K2_inv,q2,t2);
		CommonOps_DDF3.mult(K2_inv,Q2,tmpA);
		CommonOps_DDF3.mult(tmpA,K1,tmpB);

		// Find the rotation matrix R*t2 = [||t2||,0,0]^T
		computeRotation(t2,RR);

		// Compute W
		CommonOps_DDF3.mult(RR,tmpB,W);

		// Compute v, the plane at infinity
		// v = (w2 cross w3 / ||w3|| - w1 ) / ||t2||
		w2.set(W.a21,W.a22,W.a23);
		w3.set(W.a31,W.a32,W.a33);
		double n3 = w3.norm();
		v.cross(w2,w3); // approximation here, w2 and w3 might not be orthogonal
		v.divideIP(n3);
		v.x -= W.a11;
		v.y -= W.a12;
		v.z -= W.a13;
		v.divideIP(t2.a1);

		// really just a sanity check for bad input
		return !(UtilEjml.isUncountable(v.x) || UtilEjml.isUncountable(v.y) || UtilEjml.isUncountable(v.z));
	}
1187674
def apool(self,
              k_height,
              k_width,
              d_height=2,
              d_width=2,
              mode="VALID",
              input_layer=None,
              num_channels_in=None):
        """"""
        return self._pool("apool", pooling_layers.average_pooling2d, k_height,
                          k_width, d_height, d_width, mode, input_layer,
                          num_channels_in)
1020852
def _pool(input_layer, pool_fn, kernel, stride, edges, name):
  """"""
  input_layer.get_shape().assert_has_rank(4)
  if input_layer.get_shape().ndims not in (None, 4):
    raise ValueError('Pooling requires a rank 4 tensor: %s' %
                     input_layer.get_shape())
  kernel = _kernel(kernel)
  stride = _stride(stride)
  size = [1, kernel[0], kernel[1], 1]

  new_head = pool_fn(input_layer.tensor, size, stride, edges, name=name)
  return input_layer.with_tensor(new_head)