Store the previously computed pointwise predictive accuracy values (ics) in a 2D matrix.
488410
def _ic_matrix(ics, ic_i):
    """"""
    cols, _ = ics.shape
    rows = len(ics[ic_i].iloc[0])
    ic_i_val = np.zeros((rows, cols))

    for idx, val in enumerate(ics.index):
        ic = ics.loc[val][ic_i]

        if len(ic) != rows:
            raise ValueError("The number of observations should be the same across all models")

        ic_i_val[:, idx] = ic

    return rows, cols, ic_i_val
975434
def _update_parameters(self):
        
        self.repr_points, self.repr_points_log = self.sampler.get_samples(self.num_repr_points, self.proposal_function, self.burn_in_steps)

        if np.any(np.isnan(self.repr_points_log)) or np.any(np.isposinf(self.repr_points_log)):
            raise RuntimeError("Sampler generated representer points with invalid log values: {}".format(self.repr_points_log))

        # Removing representer points that have 0 probability of being the minimum (corresponding to log probability being minus infinity)
        idx_to_remove = np.where(np.isneginf(self.repr_points_log))[0]
        if len(idx_to_remove) > 0:
            idx = list(set(range(self.num_repr_points)) - set(idx_to_remove))
            self.repr_points = self.repr_points[idx, :]
            self.repr_points_log = self.repr_points_log[idx]

        # We predict with the noise as we need to make sure that var is indeed positive definite.
        mu, _ = self.model.predict(self.repr_points)
        # we need a vector
        mu = np.ndarray.flatten(mu)
        var = self.model.predict_covariance(self.repr_points)
        
        self.logP, self.dlogPdMu, self.dlogPdSigma, self.dlogPdMudMu = epmgp.joint_min(mu, var, with_derivatives=True)
        # add a second dimension to the array
        self.logP = np.reshape(self.logP, (self.logP.shape[0], 1))
1369277
def store_single_col_data(fns, prottable_id_map, pacc_map, pqdbmethod,
                          protacc_colnr, colmap):
    """"""
    to_store = []
    for fn, header, pquant in tsvreader.generate_tsv_pep_protein_quants(fns):
        pacc_id = pacc_map[pquant[header[protacc_colnr]]]
        pqdata = (pacc_id, prottable_id_map[fn], pquant[colmap[fn]])
        to_store.append(pqdata)
        if len(to_store) > 10000:
            pqdbmethod(to_store)
            to_store = []
    pqdbmethod(to_store)
872580
def _post_compute(self):
        """"""
        self._x_labels, self._y_labels = self._y_labels, self._x_labels
        self._x_labels_major, self._y_labels_major = (
            self._y_labels_major, self._x_labels_major
        )
        self._x_2nd_labels, self._y_2nd_labels = (
            self._y_2nd_labels, self._x_2nd_labels
        )
        self.show_y_guides, self.show_x_guides = (
            self.show_x_guides, self.show_y_guides
        )
1302048
def set_data_matrix(self, X):
        
        X = check_array(X, accept_sparse=sparse_formats)
        self.X = X
463051
private void computeBitLocations() {
		int N = numRows;
		int row = N-1;
		int col = N-1;
		int direction = -1;

		while (col > 0) {
			if (col == 6)
				col -= 1;

			if (!get(row,col)) {
				bits.add( new Point2D_I32(col,row));
			}
			if (!get(row,col-1)) {
				bits.add( new Point2D_I32(col-1,row));
			}

			row += direction;

			if (row < 0 || row >= N) {
				direction = -direction;
				col -= 2;
				row += direction;
			}
		}
	}
428692
def _project_on_ellipsoid(c, r, locations):
    """"""
    p0 = locations - c  # original locations

    l2 = 1 / np.sum(p0**2 / r**2, axis=1, keepdims=True)
    p = p0 * np.sqrt(l2)  # initial approximation (projection of points towards center of ellipsoid)

    fun = lambda x: np.sum((x.reshape(p0.shape) - p0)**2)              # minimize distance between new and old points
    con = lambda x: np.sum(x.reshape(p0.shape)**2 / r**2, axis=1) - 1  # new points constrained to surface of ellipsoid
    res = sp.optimize.minimize(fun, p, constraints={'type': 'eq', 'fun': con}, method='SLSQP')

    return res['x'].reshape(p0.shape) + c
840889
def __init_from_np2d(self, mat, params_str, ref_dataset):
        """"""
        if len(mat.shape) != 2:
            raise ValueError('Input numpy.ndarray must be 2 dimensional')

        self.handle = ctypes.c_void_p()
        if mat.dtype == np.float32 or mat.dtype == np.float64:
            data = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False)
        else:
            # change non-float data to float data, need to copy
            data = np.array(mat.reshape(mat.size), dtype=np.float32)

        ptr_data, type_ptr_data, _ = c_float_array(data)
        _safe_call(_LIB.LGBM_DatasetCreateFromMat(
            ptr_data,
            ctypes.c_int(type_ptr_data),
            ctypes.c_int(mat.shape[0]),
            ctypes.c_int(mat.shape[1]),
            ctypes.c_int(C_API_IS_ROW_MAJOR),
            c_str(params_str),
            ref_dataset,
            ctypes.byref(self.handle)))
        return self
176821
protected void align() {
		if (!isReady()) {
			return;
		}

		long timeStart = System.nanoTime();

		int[] dim = getScoreMatrixDimensions();
		if (storingScoreMatrix) {
			scores = new int[dim[0]][dim[1]][dim[2]];
		} else {
			scores = new int[dim[0]][][];
			scores[0] = new int[dim[1]][dim[2]];
			scores[1] = new int[dim[1]][dim[2]];
		}
		boolean linear = (gapPenalty.getType() == GapPenalty.Type.LINEAR);
		Last[][][] traceback = new Last[dim[0]][][];
		List<Step> sx = new ArrayList<Step>(), sy = new ArrayList<Step>();

		if (!local) {
			xyMax = new int[] { dim[0] - 1, dim[1] - 1 };
			xyStart = new int[] { 0, 0 };
			score = 0;
			List<Subproblem> problems = Subproblem.getSubproblems(anchors, xyMax[0], xyMax[1]);
			assert problems.size() == anchors.size() + 1;
			for (int i = 0; i < problems.size(); i++) {
				Subproblem subproblem = problems.get(i);
				for (int x = subproblem.getQueryStartIndex(); x <= subproblem.getQueryEndIndex(); x++) {

					traceback[x] =

					  linear ?
						setScoreVector(x, subproblem, gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x, subproblem), storingScoreMatrix, scores) :

						setScoreVector(x, subproblem, gapPenalty.getOpenPenalty(), gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x, subproblem), storingScoreMatrix, scores);
				}
			}
			setSteps(traceback, scores, sx, sy);
			score = Integer.MIN_VALUE;
			int[] finalScore = scores[xyMax[0]][xyMax[1]];
			for (int z = 0; z < finalScore.length; z++) {
				score = Math.max(score, finalScore[z]);
			}
		} else {
			for (int x = 0; x < dim[0]; x++) {

				traceback[x] =

				  linear ?
					setScoreVector(x, gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x), storingScoreMatrix, scores, xyMax, score) :

					setScoreVector(x, gapPenalty.getOpenPenalty(), gapPenalty.getExtensionPenalty(), getSubstitutionScoreVector(x), storingScoreMatrix, scores, xyMax, score);

				if (xyMax[0] == x) {
					score = scores[x][xyMax[1]][0];
				}
			}
			xyStart = local ? setSteps(traceback, xyMax, sx, sy) : setSteps(traceback, scores, sx, sy);
		}

		setProfile(sx, sy);

		if (!storingScoreMatrix) {
			scores = null;
		}

		time = System.nanoTime() - timeStart;
	}
1166769
private void precomputeSlope() {
        float invDirX = 1.0f / dirX;
        float invDirY = 1.0f / dirY;
        float invDirZ = 1.0f / dirZ;
        s_yx = dirX * invDirY;
        s_xy = dirY * invDirX;
        s_zy = dirY * invDirZ;
        s_yz = dirZ * invDirY;
        s_xz = dirZ * invDirX;
        s_zx = dirX * invDirZ;
        c_xy = originY - s_xy * originX;
        c_yx = originX - s_yx * originY;
        c_zy = originY - s_zy * originZ;
        c_yz = originZ - s_yz * originY;
        c_xz = originZ - s_xz * originX; // <- original paper had a bug here. It switched originZ/originX
        c_zx = originX - s_zx * originZ; // <- original paper had a bug here. It switched originZ/originX
        int sgnX = signum(dirX);
        int sgnY = signum(dirY);
        int sgnZ = signum(dirZ);
        classification = (byte) ((sgnZ+1) << 4 | (sgnY+1) << 2 | (sgnX+1));
    }
1144039
def store(self, t, step):
        
        max_cache = int(self.system.tds.config.max_cache)
        if len(self.vars) >= max_cache > 0:
            self.dump()
            self.vars = list()
            self.t = list()
            self.k = list()
            logger.debug(
                'varout cache cleared at simulation t = {:g}.'.format(
                    self.system.dae.t))
            self._mode = 'a'

        var_data = matrix([self.system.dae.x, self.system.dae.y])

        # ===== This code block is deprecated =====
        self.t.append(t)
        self.k.append(step)
        self.vars.append(var_data)
        # =========================================

        # clear data cache if written to disk
        if self.np_nrows >= max_cache > 0:
            self.dump_np_vars()
            self.np_vars = np.zeros(self._np_block_shape)
            self.np_nrows = 0
            self.np_t = np.zeros((self._np_block_rows,))
            self.np_k = np.zeros((self._np_block_rows,))
            logger.debug(
                'np_vars cache cleared at simulation t = {:g}.'.format(
                    self.system.dae.t))
            self._mode = 'a'

        # initialize before first-time adding data
        if self.np_nrows == 0:
            self.np_ncols = len(var_data)
            self._np_block_shape = (self._np_block_rows, self.np_ncols)
            self.np_vars = np.zeros(self._np_block_shape)
            self.np_t = np.zeros((self._np_block_rows,))
            self.np_k = np.zeros((self._np_block_rows,))

        # adding data to the matrix
        # self.np_vars[self.np_nrows, 0] = t
        self.np_t[self.np_nrows] = t
        self.np_k[self.np_nrows] = step
        self.np_vars[self.np_nrows, :] = np.array(var_data).reshape((-1))
        self.np_nrows += 1

        # check if matrix extension is needed
        if self.np_nrows >= self.np_vars.shape[0]:
            self.np_vars = np.concatenate([self.np_vars, np.zeros(self._np_block_shape)], axis=0)
            self.np_t = np.concatenate([self.np_t, np.zeros((self._np_block_rows,))], axis=0)
            self.np_k = np.concatenate([self.np_k, np.zeros((self._np_block_rows,))], axis=0)

        # remove the post-computed variables from the variable list
        if self.system.tds.config.compute_flows:
            self.system.dae.y = self.system.dae.y[:self.system.dae.m]
1158312
private static void compute(Kernel kernel, int[] in, int[] out, int width, int height, boolean alpha, int edge)
    {
        final float[] matrix = kernel.getMatrix();
        final int cols = kernel.getWidth();
        final int cols2 = cols / 2;

        for (int y = 0; y < height; y++)
        {
            int index = y;
            final int ioffset = y * width;
            for (int x = 0; x < width; x++)
            {
                compute(matrix, in, out, x, index, ioffset, cols2, width, alpha, edge);
                index += height;
            }
        }
    }
641204
def multigrid(bounds, points_count):
    
    if len(bounds)==1:
        return np.linspace(bounds[0][0], bounds[0][1], points_count).reshape(points_count, 1)
    x_grid_rows = np.meshgrid(*[np.linspace(b[0], b[1], points_count) for b in bounds])
    x_grid_columns = np.vstack([x.flatten(order='F') for x in x_grid_rows]).T
    return x_grid_columns
764775
def copy(self):
        
        return cspmatrix(self.symb, blkval = +self.blkval, factor = self.is_factor)
492780
def as_2d_array(theta):
    
    v = theta.view(np.float)
    N = theta.shape[0]
    v.shape = (N, - 1)
    # raise an error if v cannot be reshaped without creating a copy
    return v
381995
def take_2d_multi(arr, indexer, out=None, fill_value=np.nan, mask_info=None,
                  allow_fill=True):
    
    if indexer is None or (indexer[0] is None and indexer[1] is None):
        row_idx = np.arange(arr.shape[0], dtype=np.int64)
        col_idx = np.arange(arr.shape[1], dtype=np.int64)
        indexer = row_idx, col_idx
        dtype, fill_value = arr.dtype, arr.dtype.type()
    else:
        row_idx, col_idx = indexer
        if row_idx is None:
            row_idx = np.arange(arr.shape[0], dtype=np.int64)
        else:
            row_idx = ensure_int64(row_idx)
        if col_idx is None:
            col_idx = np.arange(arr.shape[1], dtype=np.int64)
        else:
            col_idx = ensure_int64(col_idx)
        indexer = row_idx, col_idx
        if not allow_fill:
            dtype, fill_value = arr.dtype, arr.dtype.type()
            mask_info = None, False
        else:
            # check for promotion based on types only (do this first because
            # it's faster than computing a mask)
            dtype, fill_value = maybe_promote(arr.dtype, fill_value)
            if dtype != arr.dtype and (out is None or out.dtype != dtype):
                # check if promotion is actually required based on indexer
                if mask_info is not None:
                    (row_mask, col_mask), (row_needs, col_needs) = mask_info
                else:
                    row_mask = row_idx == -1
                    col_mask = col_idx == -1
                    row_needs = row_mask.any()
                    col_needs = col_mask.any()
                    mask_info = (row_mask, col_mask), (row_needs, col_needs)
                if row_needs or col_needs:
                    if out is not None and out.dtype != dtype:
                        raise TypeError('Incompatible type for fill_value')
                else:
                    # if not, then depromote, set fill_value to dummy
                    # (it won't be used but we don't want the cython code
                    # to crash when trying to cast it to dtype)
                    dtype, fill_value = arr.dtype, arr.dtype.type()

    # at this point, it's guaranteed that dtype can hold both the arr values
    # and the fill_value
    if out is None:
        out_shape = len(row_idx), len(col_idx)
        out = np.empty(out_shape, dtype=dtype)

    func = _take_2d_multi_dict.get((arr.dtype.name, out.dtype.name), None)
    if func is None and arr.dtype != out.dtype:
        func = _take_2d_multi_dict.get((out.dtype.name, out.dtype.name), None)
        if func is not None:
            func = _convert_wrapper(func, out.dtype)
    if func is None:

        def func(arr, indexer, out, fill_value=np.nan):
            _take_2d_multi_object(arr, indexer, out, fill_value=fill_value,
                                  mask_info=mask_info)

    func(arr, indexer, out=out, fill_value=fill_value)
    return out
1225049
def da2cf(dataarray, epoch=EPOCH):
        """"""
        new_data = dataarray.copy()

        # Remove the area
        new_data.attrs.pop('area', None)

        anc = [ds.attrs['name']
               for ds in new_data.attrs.get('ancillary_variables', [])]
        if anc:
            new_data.attrs['ancillary_variables'] = ' '.join(anc)
        # TODO: make this a grid mapping or lon/lats
        # new_data.attrs['area'] = str(new_data.attrs.get('area'))
        for key, val in new_data.attrs.copy().items():
            if val is None:
                new_data.attrs.pop(key)
        new_data.attrs.pop('_last_resampler', None)

        if 'time' in new_data.coords:
            new_data['time'].encoding['units'] = epoch
            new_data['time'].attrs['standard_name'] = 'time'
            new_data['time'].attrs.pop('bounds', None)
            if 'time' not in new_data.dims:
                new_data = new_data.expand_dims('time')

        if 'x' in new_data.coords:
            new_data['x'].attrs['standard_name'] = 'projection_x_coordinate'
            new_data['x'].attrs['units'] = 'm'

        if 'y' in new_data.coords:
            new_data['y'].attrs['standard_name'] = 'projection_y_coordinate'
            new_data['y'].attrs['units'] = 'm'

        new_data.attrs.setdefault('long_name', new_data.attrs.pop('name'))
        if 'prerequisites' in new_data.attrs:
            new_data.attrs['prerequisites'] = [np.string_(str(prereq)) for prereq in new_data.attrs['prerequisites']]
        return new_data