Create a QTT-representation of a uniform grid on an interval [a, b]
970202
def linspace(n, d=None, a=0.0, b=1.0, right=True, left=True):
    
    if isinstance(n, six.integer_types):
        n = [n]
    if d is None:
        n0 = _np.asanyarray(n, dtype=_np.int32)
    else:
        n0 = _np.array(n * d, dtype=_np.int32)
    d = n0.size
    t = xfun(n0)
    e = ones(n0)
    N = _np.prod(n0)  # Size
    if left and right:
        h = (b - a) * 1.0 / (N - 1)
        res = a * e + t * h
    elif left and not right:
        h = (b - a) * 1.0 / N
        res = a * e + t * h
    elif right and not left:
        h = (b - a) * 1.0 / N
        res = a * e + (t + e) * h
    else:
        h = (b - a) * 1.0 / (N - 1)
        res = a * e + (t + e) * h
    return res.round(1e-13)
1019870
def qr2scad(stream):
    """"""

    img = Image.open(stream)

    # Convert to black and white 8-bit
    if img.mode != 'L':
        img = img.convert('L')

    # Invert color to get the right bounding box
    img = ImageOps.invert(img)

    bbox = img.getbbox()

    # Crop to only contain contents within the PDPs
    img = img.crop(bbox)

    width, height = img.size

    assert width == height,\
        'The QR code should be a square, but we found it to be %(w)sx%(h)s' % {
            'w': width,
            'h': height
        }

    qr_side = width

    # QR code superpixel size
    qr_pixel_size = (list(img.getdata()).index(0) / PDP_SIDE)

    # Get the resize factor from the PDP size
    new_size = qr_side / qr_pixel_size

    # Set a more reasonable size
    img = img.resize((new_size, new_size))
    qr_side = new_size

    img_matrix = img.load()

    result = 'module _qr_code_dot() {\n'
    result += '    cube([%(block_side)s, %(block_side)s, 1]);\n' % {
        'block_side': BLOCK_SIDE
    }
    result += '}\n'

    result += 'module qr_code() {\n'
    for row in range(qr_side):
        for column in range(qr_side):
            if img_matrix[column, row] != 0:
                result += '    translate([%(x)s, %(y)s, 0])' % {
                    'x': BLOCK_SIZE * column - qr_side / 2,
                    'y': -BLOCK_SIZE * row + qr_side / 2
                }
                result += ' _qr_code_dot();\n'
    result += '}\n'
    result += 'qr_code_size = %d;' % (qr_side)

    return result
730628
def grid_list(data):
    '''
    
    '''
    a = []
    b = []
    M = []
    for i in data:
        a.append(i[0])  # np.array([i[1] for i in data], dtype=np.float64)
        b.append(i[1])  # np.array([i[0] for i in data], dtype=np.float64)
        M.append(i[2])  # np.array([i[2] for i in data], dtype=np.float64)
    a = np.array(a, dtype=np.float64).tolist()
    b = np.array(b, dtype=np.float64).tolist()
    M = np.array(M, dtype=np.float64).tolist()
    a = list(set(a))
    b = list(set(b))
    return a, b, M
510070
def vcontoursf1D(self, x1, x2, nx, levels, labels=False, decimals=0, color=None,
                     nudge=1e-6, newfig=True, figsize=None, layout=True, ax=None):
        
        naq = self.aq.naq
        xflow = np.linspace(x1 + nudge, x2 - nudge, nx)
        Qx = np.empty((naq, nx))
        for i in range(nx):
            Qx[:, i], Qydump = self.disvec(xflow[i], 0)
        zflow = np.empty(2 * naq)
        for i in range(self.aq.naq):
            zflow[2 * i] = self.aq.zaqtop[i]
            zflow[2 * i + 1] = self.aq.zaqbot[i]
        Qx = Qx[::-1] # set upside down
        Qxgrid = np.empty((2 * naq, nx))
        Qxgrid[0] = 0
        for i in range(naq - 1):
            Qxgrid[2 * i + 1] = Qxgrid[2 * i] - Qx[i]
            Qxgrid[2 * i + 2] = Qxgrid[2 * i + 1]
        Qxgrid[-1] = Qxgrid[-2] - Qx[-1]
        Qxgrid = Qxgrid[::-1] # index 0 at top
        if newfig:
            fig, ax = plt.subplots(1, 1, figsize=figsize)
        else:
            ax=ax
        cs = ax.contour(xflow, zflow, Qxgrid, levels, colors=color)
        if labels:
            fmt = '%1.' + str(decimals) + 'f'
            plt.clabel(cs, fmt=fmt)
672801
def _candidates_from_grid(self, n=1000):
        """"""
        used_vectors = set(tuple(v) for v in self.X)

        # if every point has been used before, gridding is done.
        grid_size = self.grid_width ** len(self.tunables)
        if len(used_vectors) == grid_size:
            return None

        all_vectors = set(itertools.product(*self._grid_axes))
        remaining_vectors = all_vectors - used_vectors
        candidates = np.array(list(map(np.array, remaining_vectors)))

        np.random.shuffle(candidates)
        return candidates[0:n]
691648
def interval_intersection_width(a, b, c, d):
    """"""
    return max(0, min(b, d) - max(a, c))
127565
function (ctx, size, texMeters) {

    if (this.data.grid == 'none') return;

    // one grid feature each 2 meters

    var num = Math.floor(texMeters / 2);
    var step = size / (texMeters / 2); // 2 meters == <step> pixels
    var i, j, ii;

    ctx.fillStyle = this.data.gridColor;

    switch (this.data.grid) {
      case '1x1':
      case '2x2': {
        if (this.data.grid == '1x1') {
          num = num * 2;
          step = size / texMeters;
        }
        for (i = 0; i < num; i++) {
          ii = Math.floor(i * step);
          ctx.fillRect(0, ii, size, 1);
          ctx.fillRect(ii, 0, 1, size);
        }
        break;
      }
      case 'crosses': {
        var l = Math.floor(step / 20);
        for (i = 0; i < num + 1; i++) {
          ii = Math.floor(i * step);
          for (j = 0; j < num + 1; j++) {
            var jj = Math.floor(-l + j * step);
            ctx.fillRect(jj, ii, l * 2, 1);
            ctx.fillRect(ii, jj, 1, l * 2);
          }
        }
        break;
      }
      case 'dots': {
        for (i = 0; i < num + 1; i++) {
          for (j = 0; j < num + 1; j++) {
            ctx.beginPath(); ctx.arc(Math.floor(j * step), Math.floor(i * step), 4, 0, Math.PI * 2); ctx.fill();
          }
        }
        break;
      }
      case 'xlines': {
        for (i = 0; i < num; i++) {
          ctx.fillRect(Math.floor(i * step), 0, 1, size);
        }
        break;
      }
      case 'ylines': {
        for (i = 0; i < num; i++) {
          ctx.fillRect(0, Math.floor(i * step), size, 1);
        }
        break;
      }
    }
  }
276803
def generate_numeric_range(items, lower_bound, upper_bound):
    

    quantile_grid = create_quantiles(items, lower_bound, upper_bound)
    labels, bounds = (zip(*quantile_grid))
    ranges = ((label, NumericRange(*bound))
              for label, bound in zip(labels, bounds))
    return ranges
1141732
def define_grid(self, matrix):
        
        self.style['grid-template-areas'] = ''.join("'%s'"%(' '.join(x)) for x in matrix)
512713
def plot_ecg_grids(ecg_grids, fs, units, time_units, axes):
    ""
    if ecg_grids == 'all':
        ecg_grids = range(0, len(axes))


    for ch in ecg_grids:
        # Get the initial plot limits
        auto_xlims = axes[ch].get_xlim()
        auto_ylims= axes[ch].get_ylim()

        (major_ticks_x, minor_ticks_x, major_ticks_y,
            minor_ticks_y) = calc_ecg_grids(auto_ylims[0], auto_ylims[1],
                                            units[ch], fs, auto_xlims[1],
                                            time_units)

        min_x, max_x = np.min(minor_ticks_x), np.max(minor_ticks_x)
        min_y, max_y = np.min(minor_ticks_y), np.max(minor_ticks_y)

        for tick in minor_ticks_x:
            axes[ch].plot([tick, tick], [min_y,  max_y], c='#ededed',
                          marker='|', zorder=1)
        for tick in major_ticks_x:
            axes[ch].plot([tick, tick], [min_y, max_y], c='#bababa',
                          marker='|', zorder=2)
        for tick in minor_ticks_y:
            axes[ch].plot([min_x, max_x], [tick, tick], c='#ededed',
                          marker='_', zorder=1)
        for tick in major_ticks_y:
            axes[ch].plot([min_x, max_x], [tick, tick], c='#bababa',
                          marker='_', zorder=2)

        # Plotting the lines changes the graph. Set the limits back
        axes[ch].set_xlim(auto_xlims)
        axes[ch].set_ylim(auto_ylims)
1240381
def q12d(grid, spacing=None, E=1e5, nu=0.3, dirichlet_boundary=True,
         format=None):
    
    X, Y = tuple(grid)

    if X < 1 or Y < 1:
        raise ValueError('invalid grid shape')

    if dirichlet_boundary:
        X += 1
        Y += 1

    pts = np.mgrid[0:X+1, 0:Y+1]
    pts = np.hstack((pts[0].T.reshape(-1, 1) - X / 2.0,
                     pts[1].T.reshape(-1, 1) - Y / 2.0))

    if spacing is None:
        DX, DY = 1, 1
    else:
        DX, DY = tuple(spacing)
        pts *= [DX, DY]

    # compute local stiffness matrix
    lame = E * nu / ((1 + nu) * (1 - 2*nu))  # Lame's first parameter
    mu = E / (2 + 2*nu)                   # shear modulus

    vertices = np.array([[0, 0], [DX, 0], [DX, DY], [0, DY]])
    K = q12d_local(vertices, lame, mu)

    nodes = np.arange((X+1)*(Y+1)).reshape(X+1, Y+1)
    LL = nodes[:-1, :-1]
    Id = (2*LL).repeat(K.size).reshape(-1, 8, 8)
    J = Id.copy()
    Id += np.tile([0, 1, 2, 3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8, 1))
    J += np.tile([0, 1, 2, 3, 2*X + 4, 2*X + 5, 2*X + 2, 2*X + 3], (8, 1)).T
    V = np.tile(K, (X*Y, 1))

    Id = np.ravel(Id)
    J = np.ravel(J)
    V = np.ravel(V)

    # sum duplicates
    A = coo_matrix((V, (Id, J)), shape=(pts.size, pts.size)).tocsr()
    A = A.tobsr(blocksize=(2, 2))

    del Id, J, V, LL, nodes

    B = np.zeros((2 * (X+1)*(Y+1), 3))
    B[0::2, 0] = 1
    B[1::2, 1] = 1
    B[0::2, 2] = -pts[:, 1]
    B[1::2, 2] = pts[:, 0]

    if dirichlet_boundary:
        mask = np.zeros((X+1, Y+1), dtype='bool')
        mask[1:-1, 1:-1] = True
        mask = np.ravel(mask)
        data = np.zeros(((X-1)*(Y-1), 2, 2))
        data[:, 0, 0] = 1
        data[:, 1, 1] = 1
        indices = np.arange((X-1)*(Y-1))
        indptr = np.concatenate((np.array([0]), np.cumsum(mask)))
        P = bsr_matrix((data, indices, indptr),
                       shape=(2*(X+1)*(Y+1), 2*(X-1)*(Y-1)))
        Pt = P.T
        A = P.T * A * P

        B = Pt * B

    return A.asformat(format), B
348840
function randCol (r, g, b, a) {
  return "rgba(" + Math.floor(Math.random() * r).toString() + "," +
                   Math.floor(Math.random() * g).toString() + "," +
                   Math.floor(Math.random() * b).toString() + "," + a + ")";
}
815641
private Grid getGridLayout(int count) {

        Grid grid = new Grid();
        int x, y, z, modolo = 0;
        x = count % 3;
        y = count % 5;
        z = count % 7;
        if ((z <= y) && (z <= x)) {
            modolo = 7;
        } else if ((y <= z) && (y <= x)) {
            modolo = 5;
        } else if ((x <= z) && (x <= y)) {
            modolo = 3;
        }

        if (count < modolo) {
            grid = new Grid(count, 1);
        } else if ((count % modolo) == 0) {
            grid = new Grid(count / modolo, modolo);
        } else {
            grid = new Grid((count / modolo) + 1, modolo);
        }
        return grid;
    }
972388
def transpose(self, interval, up=True):
        
        for cont in self.bar:
            cont[2].transpose(interval, up)
1156894
def grid(box, draw)
      x, y, w, h = box.x, box.y, box.width, box.height
      use_cairo do |cc|
        (x..@width + w).step(w)  { |ix| line_xy(ix, y - @height, ix, @height + y, draw) }
        (y..@height + h).step(h) { |iy| line_xy(x - @width, iy, @width + x, iy, draw) }
      end
    end
430868
def plot_grid(self, **kwargs):
        
        fig, ax = plt.subplots(1, 1)
        self.plot_grid_to_ax(ax, **kwargs)
        return fig, ax
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