Choose a proper grid for the binning process
320704
def _setup_grid(self, cutoff, unit_cell, grid):
        """"""
        if grid is None:
            # automatically choose a decent grid
            if unit_cell is None:
                grid = cutoff/2.9
            else:
                # The following would be faster, but it is not reliable
                # enough yet.
                #grid = unit_cell.get_optimal_subcell(cutoff/2.0)
                divisions = np.ceil(unit_cell.spacings/cutoff)
                divisions[divisions<1] = 1
                grid = unit_cell/divisions

        if isinstance(grid, float):
            grid_cell = UnitCell(np.array([
                [grid, 0, 0],
                [0, grid, 0],
                [0, 0, grid]
            ]))
        elif isinstance(grid, UnitCell):
            grid_cell = grid
        else:
            raise TypeError("Grid must be None, a float or a UnitCell instance.")

        if unit_cell is not None:
            # The columns of integer_matrix are the unit cell vectors in
            # fractional coordinates of the grid cell.
            integer_matrix = grid_cell.to_fractional(unit_cell.matrix.transpose()).transpose()
            if abs((integer_matrix - np.round(integer_matrix))*self.unit_cell.active).max() > 1e-6:
                raise ValueError("The unit cell vectors are not an integer linear combination of grid cell vectors.")
            integer_matrix = integer_matrix.round()
            integer_cell = UnitCell(integer_matrix, unit_cell.active)
        else:
            integer_cell = None

        return grid_cell, integer_cell
1371757
def _bins_to_json(h2):
    
    south = h2.get_bin_left_edges(0)
    north = h2.get_bin_right_edges(0)
    west = h2.get_bin_left_edges(1)
    east = h2.get_bin_right_edges(1)
    return {
        "type":"FeatureCollection",
        "features": [
            {
                "type": "Feature",
                "geometry": {
                    "type": "Polygon",
                    # Note that folium and GeoJson have them swapped
                    "coordinates": [[
                        [east[j], south[i]],
                        [east[j], north[i]],
                        [west[j], north[i]],
                        [west[j], south[i]],
                        [east[j], south[i]]]],
                },
                "properties" : {
                    "count": float(h2.frequencies[i, j])
                }
            }
            for i in range(h2.shape[0])
            for j in range(h2.shape[1])
        ]
    }
254125
def homogenize_grid(grid_old, dx, dy):
    

    # 1 line fit
    x = grid_old.electrodes[:, 0]
    y = grid_old.electrodes[:, 1]
    sort_indices = np.argsort(x)
    x_sort = x[sort_indices]
    y_sort = y[sort_indices]
    p = np.polyfit(x_sort, y_sort, 1)

    # 2. rotate around first electrode
    offsetx = x_sort[0]
    offsety = y_sort[0]

    alpha = -np.arctan2(p[0], 1.0)  # * 180 / np.pi

    xn = []
    yn = []
    for xc, yc in zip(x, y):
        rotx, roty = rotate_point(offsetx, offsety, xc, yc, alpha)
        xn.append(rotx + offsetx)
        yn.append(roty + offsety)

    new_coordinates = np.vstack((xn, yn)).T

    # move vertically

    # this line is a horizontal line
    p_rot = np.polyfit(
        new_coordinates[:, 0],
        new_coordinates[:, 1],
        1
    )
    y_rot = np.polyval(
        p_rot,
        new_coordinates[:, 0],
    )
    ymax = y_rot[0]

    new_coordinates_trans = np.copy(new_coordinates)
    new_coordinates_trans[:, 1] -= ymax

    #
    fig, ax = plt.subplots(1, 1)
    ax.scatter(x, y, color='r', label='original')

    ax.plot(
        x,
        np.polyval(p, x),
        '-',
        label='fit',
        color='r',
    )

    ax.scatter(
        xn, yn,
        color='c',
        label='rotated',
    )

    ax.plot(
        xn,
        y_rot,
        '-',
        label='fit',
        color='c',
    )

    ax.scatter(
        new_coordinates_trans[:, 0],
        new_coordinates_trans[:, 1],
        label='homog',
    )

    # plot the line through the new coordintes
    pnew = np.polyfit(
        new_coordinates_trans[:, 0],
        new_coordinates_trans[:, 1],
        1
    )
    ax.plot(
        new_coordinates_trans[:, 0],
        np.polyval(pnew, new_coordinates_trans[:, 0]),
        '-',
        label='fit homogenized',
    )

    ax.legend(loc='best')

    ax.set_xlabel('x [m]')
    ax.set_ylabel('y [m]')

    fig.tight_layout()
    fig.savefig('output_electrodes.png', dpi=300)

    # electrodes = np.hstack((
    # boundaries
    bx = new_coordinates_trans[sort_indices, 0]
    by = new_coordinates_trans[sort_indices, 1]
    btype = [12 for i in bx]

    # add boundary
    # get deepest boundary coordinate
    y1 = by[-1] - dy
    y2 = by[0] - dy

    ymin = min(y1, y2)

    bx = np.hstack(
        (bx[0] - dx,
         bx,
         [bx[-1] + dx, bx[-1] + dx, bx[0] - dx])
    )

    by = np.hstack(
        (by[0],
         by,
         [by[-1], ymin, ymin]
         )
    )

    btype = np.hstack((12,
                       btype,
                       [11, 11, 11]))

    boundaries = np.vstack((bx, by, btype)).T

    # fig, ax = plt.subplots(1, 1)
    # ax.scatter(bx, by)
    # ax.set_aspect('equal')
    # fig.tight_layout()
    # fig.savefig('boundaries.png', dpi=300)

    grid_new = grid_container(None, None, grid_old.char_length_file)
    grid_new.boundaries = np.copy(boundaries)
    grid_new.electrodes = np.copy(new_coordinates_trans)

    fig, ax = plt.subplots(1, 1)
    ax.scatter(bx, by, color='g', label='boundaries')
    ax.scatter(new_coordinates[:, 0], new_coordinates[:, 1], color='g',
               label='electrodes')
    ax.set_aspect('equal')
    ax.legend()
    fig.tight_layout()
    fig.savefig('output_boundaries.png', dpi=300)

    def transform_back(data):
        new_data = np.copy(data)
        new_data[:, 1] += ymax
        new_data[:, 0] -= offsetx
        new_data[:, 1] -= offsety

        tmpx = (new_data[:, 0]) * np.cos(-alpha) - (new_data[:, 1]) * np.sin(
            -alpha)
        tmpy = (new_data[:, 0]) * np.sin(-alpha) + (new_data[:, 1]) * np.cos(
            -alpha)
        tmpx += offsetx
        tmpy += offsety
        return tmpx, tmpy

    shell_script = ''
    shell_script += '#!/bin/bash\n'
    shell_script += 'cr_trig_create grid\n'

    cmd1 = ''.join((
        'grid_translate -e grid/elem.dat ',
        '--dx {0} --dz {1} -o elem_trans1.dat'.format(
            offsetx, ymax - offsety)
    ))
    cmd2 = ''.join((
        'grid_rotate -e elem_trans1.dat ',
        '-a {0} -o elem_trans1_rot1.dat'.format(-alpha * 180 / np.pi)
    ))
    cmd3 = ''.join((
        'grid_translate -e elem_trans1_rot1.dat ',
        '--dx {0} --dz {1} -o elem_trans1_rot1_trans2.dat'.format(
            offsetx, offsety)
    ))
    shell_script += cmd1 + '\n'
    shell_script += cmd2 + '\n'
    shell_script += cmd3 + '\n'

    shell_script += ''.join((
        'grid_plot_wireframe --fancy -t grid/elec.dat ',
        '-e elem_trans1_rot1_trans2.dat -o trans1_rot1_trans2.png'
    ))

    grid_new.script = shell_script

    tmpx, tmpy = transform_back(grid_new.electrodes)
    bx, by = transform_back(grid_new.boundaries[:, 0:2])

    grid_map = grid_container(char_length_file=grid_old.char_length_file)
    grid_map.electrodes = np.vstack((tmpx, tmpy)).T
    grid_map.boundaries = np.vstack((bx, by, grid_new.boundaries[:, 2])).T

    fig, ax = plt.subplots(1, 1)
    ax.scatter(tmpx, tmpy, color='r', label='new')
    ax.scatter(x, y, color='b', label='old')
    ax.scatter(bx, by, color='g', label='boundaries')
    ax.set_aspect('equal')
    ax.legend()
    fig.tight_layout()
    fig.savefig('output_map.png', dpi=300)

    return grid_new, grid_map
961380
def grid(self, grid):
        """"""

        if not isinstance(grid, bool):
            raise TypeError("grid must be boolean, not '%s'" % grid)
        self._x_grid = self._y_grid = grid
1195991
private SquareGrid assembleGrid( List<List<SquareNode>> listRows) {
		SquareGrid grid = grids.grow();
		grid.reset();

		List<SquareNode> row0 = listRows.get(0);
		List<SquareNode> row1 = listRows.get(1);

		int offset = row0.get(0).getNumberOfConnections() == 1 ? 0 : 1;

		grid.columns = row0.size() + row1.size();
		grid.rows = listRows.size();

		// initialize grid to null
		for (int i = 0; i < grid.columns * grid.rows; i++) {
			grid.nodes.add(null);
		}

		// fill in the grid
		for (int row = 0; row < listRows.size(); row++) {
			List<SquareNode> list = listRows.get(row);
			int startCol = offset - row%2 == 0 ? 0 : 1;
			// make sure there is the expected number of elements in the row
			int adjustedLength = grid.columns-startCol;
			if( (adjustedLength)-adjustedLength/2 != list.size() ) {
				return null;
			}
			int listIndex = 0;
			for (int col = startCol; col < grid.columns; col += 2) {
				grid.set(row,col,list.get(listIndex++));
			}
		}
		return grid;
	}
1217938
def grid_prep(self):
        
        if len(self.grid_props) == 0:
            return

        if self.grid_geostruct is None:
            self.logger.warn("grid_geostruct is None,"\
                  " using ExpVario with contribution=1 and a=(max(delc,delr)*10")
            dist = 10 * float(max(self.m.dis.delr.array.max(),
                                           self.m.dis.delc.array.max()))
            v = pyemu.geostats.ExpVario(contribution=1.0,a=dist)
            self.grid_geostruct = pyemu.geostats.GeoStruct(variograms=v)
46111
def get_bin_edges_from_axis(axis) -> np.ndarray:
    
    # Don't include over- or underflow bins
    bins = range(1, axis.GetNbins() + 1)
    # Bin edges
    bin_edges = np.empty(len(bins) + 1)
    bin_edges[:-1] = [axis.GetBinLowEdge(i) for i in bins]
    bin_edges[-1] = axis.GetBinUpEdge(axis.GetNbins())

    return bin_edges
452566
public Grid setupGrid(float[] vertices) {
        int vc = vertices.length / 3;
        //CTM_POSITION_ELEMENT_COUNT == 3
        // Calculate the mesh boundinggrid. box
        float[] min = new float[3];
        float[] max = new float[3];
        int[] division = new int[3];

        for (int i = 0; i < 3; ++i) {
            min[i] = max[i] = vertices[i];

        }
        for (int i = 1; i < vc; ++i) {
            for (int j = 0; j < 3; j++) {
                min[j] = min(min[j], vertices[i * 3 + j]);
                max[j] = max(max[j], vertices[i * 3 + j]);
            }
        }

        // Determine optimal grid resolution, based on the number of vertices and
        // the bounding box.
        // NOTE: This algorithm is quite crude, and could very well be optimized for
        // better compression levels in the future without affecting the file format
        // or backward compatibility at all.

        float[] factor = new float[3];
        for (int i = 0; i < 3; ++i) {
            factor[i] = max[i] - min[i];
        }

        float sum = factor[0] + factor[1] + factor[2];

        if (sum > 1e-30f) {
            sum = 1.0f / sum;
            for (int i = 0; i < 3; ++i) {
                factor[i] *= sum;
            }
            double wantedGrids = pow(100.0f * vc, 1.0f / 3.0f);
            for (int i = 0; i < 3; ++i) {
                division[i] = (int) ceil(wantedGrids * factor[i]);
                if (division[i] < 1) {
                    division[i] = 1;
                }
            }
        } else {
            division[0] = 4;
            division[1] = 4;
            division[2] = 4;
        }

        return new Grid(Vec3f.from(min), Vec3f.from(max), Vec3i.from(division));
    }
1309205
def _bin_zfill(num, width=None):
    
    s = bin(num)[2:]
    return s if width is None else s.zfill(width)
57471
def work(self, i):
        
        n1, n2 = self.p[i]

        # initialize the total arrays for this process
        sum1 = numpy.zeros_like(self.sum1g)
        sum2 = 1.
        if not self.pts_only: sum2 = numpy.zeros_like(self.sum2g)

        if self.compute_mean_coords:
            N = numpy.zeros_like(self.N)
            centers_sum = [numpy.zeros_like(c) for c in self.centers]
        else:
            N = None; centers_sum = None

        if self.bins.enable_fast_node_count:
            # field x points is not supported.
            # because it is more likely need to deal
            # with broadcasting
            sum1attrs = [ d.attr for d in self.data ]

            counts, sum1c = n1.count(n2, self.bins.edges,
                                attrs=sum1attrs)
            sum1[..., :-1] = sum1c
            sum1[..., -1] = 0
        else:

            def callback(r, i, j):
                # just call the binning function, passing the
                # sum arrays to fill in
                self.bins.update_sums(r, i, j, self.data[0], self.data[1], sum1, sum2, N=N, centers_sum=centers_sum)

            n1.enum(n2, self.bins.Rmax, process=callback)

        if not self.compute_mean_coords:
            return sum1, sum2
        else:
            return sum1, sum2, N, centers_sum
1078217
def solveBinPacking(s,B):
    
    n = len(s)
    U = len(FFD(s,B)) # upper bound of the number of bins
    model = bpp(s,B)
    x,y = model.data

    model.optimize()

    bins = [[] for i in range(U)]
    for (i,j) in x:
        if model.getVal(x[i,j]) > .5:
            bins[j].append(s[i])
    for i in range(bins.count([])):
        bins.remove([])
    for b in bins:
        b.sort()
    bins.sort()
    return bins
460452
def denormalize_bboxes(bboxes, rows, cols):
    """"""
    return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
897656
def grid(self, start=None, stop=None, St=None, **kwargs):
        

        lb = 0.75
        rb = 1.25
        if not any((start, stop, St)) and self.St is None:
            St = np.mean([op.K for op in self.options], axis=0)
            start = St * lb
            stop = St * rb
        elif not any((start, stop)):
            St = self.St if St is None else St
            start = np.max(St) * lb
            stop = np.max(St) * rb
        St = np.linspace(start, stop, **kwargs)
        payoffs = self.payoff(St=St)
        profits = self.profit(St=St)
        return St, payoffs, profits
253409
def calc_bins(n, min_val, max_val, h=None, binwidth=None):
    
    if not h:
        h = max(10, math.log(n + 1, 2))
    if binwidth == 0:
        binwidth = 0.1
    if binwidth is None:
        binwidth = (max_val - min_val) / h
    for b in drange(min_val, max_val, step=binwidth, include_stop=True):
        if b.is_integer():
            yield int(b)
        else:
            yield b
325220
def all_axis_bin_centers(self, axis):
        """"""
        # Arcane hack that seems to work, at least in 3d... hope
        axis = self.get_axis_number(axis)
        return np.meshgrid(*self.bin_centers(), indexing='ij')[axis]
461728
def fixed_width_binning(data=None, bin_width: Union[float, int] = 1, *, range=None, includes_right_edge=False, **kwargs) -> FixedWidthBinning:
    
    result = FixedWidthBinning(bin_width=bin_width, includes_right_edge=includes_right_edge,
                               **kwargs)
    if range:
        result._force_bin_existence(range[0])
        result._force_bin_existence(range[1], includes_right_edge=True)
        if not kwargs.get("adaptive"):
            return result  # Otherwise we want to adapt to data
    if data is not None and data.shape[0]:
        # print("Jo, tady")
        result._force_bin_existence([np.min(data), np.max(data)],
                                    includes_right_edge=includes_right_edge)
    return result
1263616
def linspace_bins(self,dim,*args,**kwargs):
        
        return self.spike_times.get_label(dim).linspace_bins(*args,**kwargs)