Renders two aligned Activation Atlases of the given models' layers.

    Returns a generator of the two atlasses, and a nested generator for intermediate
    atlasses while they're being rendered.
973857
def aligned_activation_atlas(
    model1,
    layer1,
    model2,
    layer2,
    grid_size=10,
    icon_size=80,
    num_steps=1024,
    whiten_layers=True,
    number_activations=NUMBER_OF_AVAILABLE_SAMPLES,
    icon_batch_size=32,
    verbose=False,
):
    
    combined_activations = _combine_activations(
        layer1, layer2, number_activations=number_activations
    )
    layouts = aligned_umap(combined_activations, verbose=verbose)

    for model, layer, layout in zip((model1, model2), (layer1, layer2), layouts):
        directions, coordinates, densities = bin_laid_out_activations(
            layout, layer.activations[:number_activations, ...], grid_size, threshold=10
        )

        def _progressive_canvas_iterator():
            icons = []
            for directions_batch in chunked(directions, icon_batch_size):
                icon_batch, losses = render_icons(
                    directions_batch,
                    model,
                    alpha=False,
                    layer=layer.name,
                    size=icon_size,
                    n_steps=num_steps,
                    S=layer_inverse_covariance(layer) if whiten_layers else None,
                )
                icons += icon_batch
                yield make_canvas(icons, coordinates, grid_size)

        yield _progressive_canvas_iterator()
194651
def training_status_renderer_context(exercise_names: List[str], renderman: RenderingManager):
    
    renderer = TrainingStatusRenderer(exercise_names, renderman)
    try:
        yield renderer
    finally:
        renderer.clear_screen()
86033
def render(self, renderer=None, **kwargs):
        
        return Markup(get_renderer(current_app, renderer)(**kwargs).visit(
            self))
1180540
function Render (gl, animatedModel, dt, state) {
  // TODO: get # joints from model
  var selectedKeyframes = Object.keys(animatedModel.keyframes)
  .sort()
  .slice(state.currentAnimation[0], state.currentAnimation[1] + 1)
  .reduce(function (selectedKeyframes, currentKeyframe) {
    selectedKeyframes[currentKeyframe] = animatedModel.keyframes[currentKeyframe]
    return selectedKeyframes
  }, {})

  var interpolatedJointData = interpolateJoints(selectedKeyframes, dt, animatedModel.numJoints)

  gl.viewport(0, 0, state.viewport.width, state.viewport.height)
  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

  var pMatrix = makePerspective(Math.PI / 3, state.viewport.width / state.viewport.height, 1, 2000)

  var modelPosition = [0, 0, 0]

  var cameraMatrix = makeCamera(state.orbit, modelPosition)
  var viewMatrix = makeInverse(cameraMatrix)

  animatedModel.draw({
    interpolatedJoints: interpolatedJointData.interpolatedJoints,
    rotationQuats: interpolatedJointData.interpolatedRotQuaternions,
    translationQuats: interpolatedJointData.interpolatedTransQuaternions,
    position: modelPosition,
    perspectiveMatrix: pMatrix,
    viewMatrix: viewMatrix,
    numJoints: animatedModel.numJoints
  })
}
1238630
def add_layers(self, *layers):
		
		for layer in layers:
			if layer.name() in self.__layers.keys():
				raise ValueError('Layer "%s" already exists' % layer.name())
			self.__layers[layer.name()] = layer
1071855
def make_output_layers(self):
        
        self.output_layers = []
        # import pytest; pytest.set_trace()
        if hasattr(self.model, 'output_layers'):
            # find corresponding output layers in CoreML model
            # assume output layers are not shared
            # Helper function to recursively extract output layers
            # even if the model has a layer which is a nested model
            def extract_output_layers(keras_model):
                output_layers = []
                for layer in keras_model.output_layers:
                    if hasattr(layer,'output_layers'):
                        output_layers.extend(extract_output_layers(layer))
                    else:
                        output_layers.append(layer)
                return output_layers

            for kl in extract_output_layers(self.model):
                coreml_layers = self.get_coreml_layers(kl)
                if len(coreml_layers) > 0:
                    for cl in coreml_layers:
                        self.output_layers.append(cl)
        elif len(self.model.outputs) > 0:
            for model_output in self.model.outputs:
                for l in self.layer_list:
                    k_layer = self.keras_layer_map[l]
                    in_nodes = k_layer._inbound_nodes if hasattr(k_layer, '_inbound_nodes') else k_layer.inbound_nodes
                    for idx in range(len(in_nodes)):
                        out_tensor = k_layer.get_output_at(idx)
                        if out_tensor == model_output or (out_tensor.name in model_output.name):
                            self.output_layers.append(l)
        if len(self.output_layers) == 0:
            raise ValueError("No outputs can be identified")
45106
function (renderer, dx, dy, tmxTile) {

            // check if any transformation is required
            if (tmxTile.flipped) {
                renderer.save();
                // apply the tile current transform
                renderer.translate(dx, dy);
                renderer.transform(tmxTile.currentTransform);
                // reset both values as managed through transform();
                dx = dy = 0;
            }

            // check if the tile has an associated image
            if (this.isCollection === true) {
                // draw the tile
                renderer.drawImage(
                    this.imageCollection[tmxTile.tileId],
                    0, 0,
                    tmxTile.width, tmxTile.height,
                    dx, dy,
                    tmxTile.width, tmxTile.height
                );
            } else {
                // use the tileset texture
                var offset = this.atlas[this.getViewTileId(tmxTile.tileId)].offset;
                // draw the tile
                renderer.drawImage(
                    this.image,
                    offset.x, offset.y,
                    this.tilewidth, this.tileheight,
                    dx, dy,
                    this.tilewidth + renderer.uvOffset, this.tileheight + renderer.uvOffset
                );
            }

            if (tmxTile.flipped)  {
                // restore the context to the previous state
                renderer.restore();
            }
        }
698591
def tiles(self):
        
        images = self.parent.images
        for x, y, gid in [i for i in self.iter_data() if i[2]]:
            yield x, y, images[gid]
1370845
def layer(name, srs = nil)
      layer = Mapnik::Layer.new(name, srs)
      layer.map = self
      yield layer
      layers << layer
    end
1202845
def bind(cell1, cell2, moduleDimensions):
  
  cell1Coords = np.unravel_index(cell1, moduleDimensions)
  cell2Coords = np.unravel_index(cell2, moduleDimensions)
  transformCoords = [(c2 - c1) % m
                     for c1, c2, m in itertools.izip(cell1Coords, cell2Coords,
                                                     moduleDimensions)]
  return np.ravel_multi_index(transformCoords, moduleDimensions)
638624
def parallel_apply_transformations(x, transforms, black_border_size=0):
  
  transforms = tf.convert_to_tensor(transforms, dtype=tf.float32)
  x = _apply_black_border(x, black_border_size)

  num_transforms = transforms.get_shape().as_list()[0]
  im_shape = x.get_shape().as_list()[1:]

  # Pass a copy of x and a transformation to each iteration of the map_fn
  # callable
  tiled_x = tf.reshape(
      tf.tile(x, [num_transforms, 1, 1, 1]),
      [num_transforms, -1] + im_shape)
  elems = [tiled_x, transforms]
  transformed_ims = tf.map_fn(
      _apply_transformation,
      elems,
      dtype=tf.float32,
      parallel_iterations=1,  # Must be 1 to avoid keras race conditions
  )
  return transformed_ims
459547
def split_model_idx(model:nn.Module, idxs:Collection[int])->ModuleList:
    ""
    layers = flatten_model(model)
    if idxs[0] != 0: idxs = [0] + idxs
    if idxs[-1] != len(layers): idxs.append(len(layers))
    return [nn.Sequential(*layers[i:j]) for i,j in zip(idxs[:-1],idxs[1:])]
1310051
def insert_1d_permute_layers(self):
        
        idx, nb_layers = 0, len(self.layer_list)
        in_edges, out_edges = self._get_1d_interface_edges()

        # Hacky Warning: (1) use a 4-D permute, which is not likely to happen in Keras,
        # to represent actual permutation needed for (seq, c, h, w) in CoreML
        # (2) Assume 2-D input shape has meaning (seq, c), and during CoreML runtime,
        # it is represented as 4D blob, (seq, c, h, w)
        for in_edge in in_edges:
            src, snk = in_edge
            if src is None:
                permute_layer = '_permute_' + snk
            else:
                permute_layer = src + '_permute_' + snk
            keras_permute = _keras.layers.Permute(dims=(3,1,2,0)) # assume w = 1, switch seq and w
            self._insert_layer_between(src, snk, permute_layer, keras_permute)
        for out_edge in out_edges:
            src, snk = out_edge
            if snk is None:
                permute_layer = src + '_permute_'
            else:
                permute_layer = src + '_permute_' + snk
            keras_permute = _keras.layers.Permute(dims=(3,1,2,0)) # assume w = 1, switch seq and w back
            self._insert_layer_between(src, snk, permute_layer, keras_permute)
832000
def _iterContours(self, **kwargs):
        
        count = len(self)
        index = 0
        while count:
            yield self[index]
            count -= 1
            index += 1
154138
def render_children options = {}
      return if children.empty?

      flattened_children.map{ |child| render_child(child, options) }.join
    end
323235
def flatten_models(models):
        "  "
        if isinstance(models, MultiFitterModel):
            ans = [models]
        else:
            tasklist = MultiFitter._compile_models(models)
            ans = MultiFitter._flatten_models(tasklist)
        return ans
272760
protected void processLayer(GrayF32 image1 , GrayF32 image2 , GrayF32 derivX2 , GrayF32 derivY2) {

		float w = SOR_RELAXATION;
		float uf,vf;

		// outer Taylor expansion iterations
		for( int warp = 0; warp < numWarps; warp++ ) {

			initFlowX.setTo(flowX);
			initFlowY.setTo(flowY);

			warpImageTaylor(derivX2, initFlowX, initFlowY, warpDeriv2X);
			warpImageTaylor(derivY2, initFlowX, initFlowY, warpDeriv2Y);
			warpImageTaylor(image2, initFlowX, initFlowY, warpImage2);

			float error;
			int iter = 0;

			do {
				// inner SOR iteration.
				error = 0;

				// inner portion
				for( int y = 1; y < image1.height-1; y++ ) {
					int pixelIndex = y*image1.width+1;
					for (int x = 1; x < image1.width-1; x++, pixelIndex++ ) {
						// could speed this up a bit more by precomputing the constant portion before the do-while loop
						float ui = initFlowX.data[pixelIndex];
						float vi = initFlowY.data[pixelIndex];

						float u = flowX.data[pixelIndex];
						float v = flowY.data[pixelIndex];

						float I1 = image1.data[pixelIndex];
						float I2 = warpImage2.data[pixelIndex];

						float I2x = warpDeriv2X.data[pixelIndex];
						float I2y = warpDeriv2Y.data[pixelIndex];

						float AU = A(x,y,flowX);
						float AV = A(x,y,flowY);

						flowX.data[pixelIndex] = uf = (1-w)*u + w*((I1-I2+I2x*ui - I2y*(v-vi))*I2x + alpha2*AU)/(I2x*I2x + alpha2);
						flowY.data[pixelIndex] = vf = (1-w)*v + w*((I1-I2+I2y*vi - I2x*(uf-ui))*I2y + alpha2*AV)/(I2y*I2y + alpha2);

						error += (uf - u)*(uf - u) + (vf - v)*(vf - v);
					}
				}

				// border regions require special treatment
				int pixelIndex0 = 0;
				int pixelIndex1 = (image1.height-1)*image1.width;
				for (int x = 0; x < image1.width; x++ ) {
					error += iterationSorSafe(image1,x,0,pixelIndex0++);
					error += iterationSorSafe(image1,x,image1.height-1,pixelIndex1++);
				}

				pixelIndex0 = image1.width;
				 pixelIndex1 = image1.width + image1.width-1;
				for( int y = 1; y < image1.height-1; y++ ) {
					error += iterationSorSafe(image1,0,y,pixelIndex0);
					error += iterationSorSafe(image1,image1.width-1,y,pixelIndex1);

					pixelIndex0 += image1.width;
					pixelIndex1 += image1.width;
				}

			} while( error > convergeTolerance*image1.width*image1.height && ++iter < maxInnerIterations);
		}
	}