flatten the mesh and distribute into a feature matrix
971225
def _flatten_mesh(self, Xs, term):
        """"""
        n = Xs[0].size

        if self.terms[term].istensor:
            terms = self.terms[term]
        else:
            terms = [self.terms[term]]

        X = np.zeros((n, self.statistics_['m_features']))
        for term_, x in zip(terms, Xs):
            X[:, term_.feature] = x.ravel()
        return X
682373
def _build_matrix_non_uniform(p, q, coords, k):
    """"""
    A = [[1] * (p+q+1)]
    for i in range(1, p + q + 1):
        line = [(coords[k+j] - coords[k])**i for j in range(-p, q+1)]
        A.append(line)
    return np.array(A)
173075
function gridMesh(nx, ny, origin, dx, dy) {
  //Unpack default arguments
  origin = origin || [0,0]
  if(!dx || dx.length < origin.length) {
    dx = dup(origin.length)
    if(origin.length > 0) {
      dx[0] = 1
    }
  }
  if(!dy || dy.length < origin.length) {
    dy = dup(origin.length)
    if(origin.length > 1) {
      dy[1] = 1
    }
  }
  //Initialize cells
  var cells = []
    , positions = dup([(nx+1) * (ny+1), origin.length])
    , i, j, k, q, d = origin.length
  for(j=0; j<ny; ++j) {
    for(i=0; i<nx; ++i) {
      cells.push([ p(i,j,nx), p(i+1, j,nx), p(i, j+1,nx) ])
      cells.push([ p(i+1,j,nx), p(i+1,j+1,nx), p(i,j+1,nx) ])
    }
  }
  //Initialize positions
  for(j=0; j<=ny; ++j) {
    for(i=0; i<=nx; ++i) {
      q = positions[ p(i, j, nx) ]
      for(k=0; k<d; ++k) {
        q[k] = origin[k] + dx[k] * i + dy[k] * j
      }
    }
  }
  return {
    positions: positions,
    cells: cells
  }
}
1197449
function subdivide( face, detail ) {

		var cols = Math.pow( 2, detail );
		var a = prepare( that.vertices[ face.a ] );
		var b = prepare( that.vertices[ face.b ] );
		var c = prepare( that.vertices[ face.c ] );
		var v = [];

		// Construct all of the vertices for this subdivision.

		for ( var i = 0 ; i <= cols; i ++ ) {

			v[ i ] = [];

			var aj = prepare( a.clone().lerp( c, i / cols ) );
			var bj = prepare( b.clone().lerp( c, i / cols ) );
			var rows = cols - i;

			for ( var j = 0; j <= rows; j ++ ) {

				if ( j === 0 && i === cols ) {

					v[ i ][ j ] = aj;

				} else {

					v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );

				}

			}

		}

		// Construct all of the faces.

		for ( var i = 0; i < cols ; i ++ ) {

			for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {

				var k = Math.floor( j / 2 );

				if ( j % 2 === 0 ) {

					make(
						v[ i ][ k + 1 ],
						v[ i + 1 ][ k ],
						v[ i ][ k ]
					);

				} else {

					make(
						v[ i ][ k + 1 ],
						v[ i + 1 ][ k + 1 ],
						v[ i + 1 ][ k ]
					);

				}

			}

		}

	}
569797
def convert_flatten(builder, layer, input_names, output_names, keras_layer):
    
    input_name, output_name = (input_names[0], output_names[0])

    # blob_order == 0 if the input blob needs not be rearranged
    # blob_order == 1 if the input blob needs to be rearranged
    blob_order = 0

    # using keras_layer.input.shape have a "?" (Dimension[None] at the front),
    # making a 3D tensor with unknown batch size 4D
    if len(keras_layer.input.shape) == 4:
        blob_order = 1

    builder.add_flatten(name=layer, mode=blob_order, input_name=input_name, output_name=output_name)
486847
def scipy_sparse_to_spmatrix(A):
    """"""
    coo = A.tocoo()
    SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
    return SP
739612
def flatten(self, keep_prob=1):
        
        self.count['flat'] += 1
        scope = 'flat_' + str(self.count['flat'])
        with tf.variable_scope(scope):
            # Reshape function
            input_nodes = tf.Dimension(
                self.input.get_shape()[1] * self.input.get_shape()[2] * self.input.get_shape()[3])
            output_shape = tf.stack([-1, input_nodes])
            self.input = tf.reshape(self.input, output_shape)

            # Dropout function
            if keep_prob != 1:
                self.input = tf.nn.dropout(self.input, keep_prob=keep_prob)
        print(scope + ' output: ' + str(self.input.get_shape()))
278933
def grid_from_coordinate_transform(numPix, Mpix2coord, ra_at_xy_0, dec_at_xy_0):
    
    a = np.arange(numPix)
    matrix = np.dstack(np.meshgrid(a, a)).reshape(-1, 2)
    x_grid = matrix[:, 0]
    y_grid = matrix[:, 1]
    ra_grid = x_grid * Mpix2coord[0, 0] + y_grid * Mpix2coord[0, 1] + ra_at_xy_0
    dec_grid = x_grid * Mpix2coord[1, 0] + y_grid * Mpix2coord[1, 1] + dec_at_xy_0
    return ra_grid, dec_grid
96216
def _vmomentsurfacemassGrid(self,n,m,grid):
        """"""
        if len(grid.df.shape) == 3: tlist= True
        else: tlist= False
        if tlist: 
            nt= grid.df.shape[2]
            out= []
            for ii in range(nt):
                out.append(nu.dot(grid.vRgrid**n,nu.dot(grid.df[:,:,ii],grid.vTgrid**m))*\
                    (grid.vRgrid[1]-grid.vRgrid[0])*(grid.vTgrid[1]-grid.vTgrid[0]))
            return nu.array(out)
        else:
            return nu.dot(grid.vRgrid**n,nu.dot(grid.df,grid.vTgrid**m))*\
                (grid.vRgrid[1]-grid.vRgrid[0])*(grid.vTgrid[1]-grid.vTgrid[0])
322211
def spline_matrix2d(x,y,px,py,mask=None):
    ''''''
    V = np.kron(spline_matrix(x,px),spline_matrix(y,py))
    
    lenV = len(V)
    
    if mask is not None:
        indices = np.nonzero(mask.T.flatten())
        if len(indices)>1:
            indices = np.nonzero(mask.T.flatten())[1][0]
        newV=V.T[indices]
        V=newV.T
        
        V=V.reshape((V.shape[0],V.shape[1]))
        
    return V
164087
def _reduction_output_shape(x, output_shape, reduced_dim):
  """"""
  if output_shape is None:
    if reduced_dim is None:
      return Shape([])
    else:
      if reduced_dim not in x.shape.dims:
        raise ValueError(
            "reduced_dim=%s not in x.shape.dims=%s" % (reduced_dim, x.shape))
      return x.shape - reduced_dim
  if reduced_dim is not None:
    if [reduced_dim] != [d for d in x.shape.dims if d not in output_shape.dims]:
      raise ValueError(
          "reduced_dim contradicts output_shape:"
          "x=%s output_shape=%s reduced_dim=%s" %
          (x, output_shape, reduced_dim))
  return output_shape
704943
def make_mesh( coor, ngroups, conns, mesh_in ):
    """"""
    mat_ids = []
    for ii, conn in enumerate( conns ):
        mat_id = nm.empty( (conn.shape[0],), dtype = nm.int32 )
        mat_id.fill( mesh_in.mat_ids[ii][0] )
        mat_ids.append( mat_id )
        
    mesh_out = Mesh.from_data( 'merged mesh', coor, ngroups, conns,
                               mat_ids, mesh_in.descs )
    return mesh_out
1006894
def apply_transform(self, matrix):
        
        matrix = np.asanyarray(matrix, dtype=np.float64)
        if matrix.shape != (4, 4):
            raise ValueError('shape must be 4,4')

        center = np.dot(matrix,
                        np.append(self.primitive.center, 1.0))[:3]
        self.primitive.center = center
606680
function flatten(array, target) {
	const result = target || [];

	for (let i = 0; i < array.length; ++i) {
		if (Array.isArray(array[i])) {
			flatten(array[i], result);
		}
		else {
			result.push(array[i]);
		}
	}

	return result;
}
842921
def reshape(attrs, inputs, proto_obj):
    """"""
    if len(inputs) == 1:
        return 'reshape', attrs, inputs[0]
    reshape_shape = list(proto_obj._params[inputs[1].name].asnumpy())
    reshape_shape = [int(i) for i in reshape_shape]
    new_attrs = {'shape': reshape_shape}
    return 'reshape', new_attrs, inputs[:1]
17299
def spm(x, model, y=None, n_samples=None, dx_min=-0.1,
        dx_max=0.1, n_dxs=5, dy_min=-0.1, dy_max=0.1, n_dys=5,
        angle_min=-30, angle_max=30, n_angles=31, black_border_size=0):
  
  if y is None:
    preds = model.get_probs(x)
    # Using model predictions as ground truth to avoid label leaking
    preds_max = reduce_max(preds, 1, keepdims=True)
    y = tf.to_float(tf.equal(preds, preds_max))
    y = tf.stop_gradient(y)
    del preds
  y = y / reduce_sum(y, 1, keepdims=True)

  # Define the range of transformations
  dxs = np.linspace(dx_min, dx_max, n_dxs)
  dys = np.linspace(dy_min, dy_max, n_dys)
  angles = np.linspace(angle_min, angle_max, n_angles)

  if n_samples is None:
    import itertools
    transforms = list(itertools.product(*[dxs, dys, angles]))
  else:
    sampled_dxs = np.random.choice(dxs, n_samples)
    sampled_dys = np.random.choice(dys, n_samples)
    sampled_angles = np.random.choice(angles, n_samples)
    transforms = zip(sampled_dxs, sampled_dys, sampled_angles)
  transformed_ims = parallel_apply_transformations(
      x, transforms, black_border_size)

  def _compute_xent(x):
    preds = model.get_logits(x)
    return tf.nn.softmax_cross_entropy_with_logits_v2(
        labels=y, logits=preds)

  all_xents = tf.map_fn(
      _compute_xent,
      transformed_ims,
      parallel_iterations=1)  # Must be 1 to avoid keras race conditions

  # Return the adv_x with worst accuracy

  # all_xents is n_total_samples x batch_size (SB)
  all_xents = tf.stack(all_xents)  # SB

  # We want the worst case sample, with the largest xent_loss
  worst_sample_idx = tf.argmax(all_xents, axis=0)  # B

  batch_size = tf.shape(x)[0]
  keys = tf.stack([
      tf.range(batch_size, dtype=tf.int32),
      tf.cast(worst_sample_idx, tf.int32)
  ], axis=1)
  transformed_ims_bshwc = tf.einsum('sbhwc->bshwc', transformed_ims)
  after_lookup = tf.gather_nd(transformed_ims_bshwc, keys)  # BHWC
  return after_lookup
1073999
def _apply_mask(self,p,mat):
        """"""
        mask = p.mask
        ms=p.mask_shape
        if ms is not None:
            mask = ms(x=p.x+p.size*(ms.x*np.cos(p.orientation)-ms.y*np.sin(p.orientation)),
                      y=p.y+p.size*(ms.x*np.sin(p.orientation)+ms.y*np.cos(p.orientation)),
                      orientation=ms.orientation+p.orientation,size=ms.size*p.size,
                      bounds=p.bounds,ydensity=p.ydensity,xdensity=p.xdensity)
        if mask is not None:
            mat*=mask