Small fully connected model.
161787
def basic_fc_small():
  """"""
  hparams = common_hparams.basic_params1()
  hparams.learning_rate = 0.1
  hparams.batch_size = 128
  hparams.hidden_size = 256
  hparams.num_hidden_layers = 2
  hparams.initializer = "uniform_unit_scaling"
  hparams.initializer_gain = 1.0
  hparams.weight_decay = 0.0
  hparams.dropout = 0.0
  return hparams
662532
def smallStepsPerLargeStep(self, smallStepsPerLargeStep):
        
        self._smallStepsPerLargeStep = smallStepsPerLargeStep
        self._smallStepFactor = np.power(self.largeStepFactor, 1.0 / smallStepsPerLargeStep)
505876
function(seg, n, d)
{
    var a = vdot(n, seg.ta) - seg.r;
    var b = vdot(n, seg.tb) - seg.r;
    return min(a, b) - d;
}
487153
def ppo_tiny_world_model():
  """"""
  hparams = ppo_original_params()
  hparams.policy_network = "next_frame_basic_deterministic"
  hparams_keys = hparams.values().keys()
  video_hparams = basic_deterministic_params.next_frame_tiny()
  for (name, value) in six.iteritems(video_hparams.values()):
    if name in hparams_keys:
      hparams.set_hparam(name, value)
    else:
      hparams.add_hparam(name, value)
  hparams.weight_decay = 0
  return hparams
1088259
def model1(inps, lims, logger=None):
    
    a_arr, c_ = inps
    ilim, jlim = lims

    i_bs = sympy.symbols('i_lb i_ub', integer=True)
    i = sympy.Idx('i', i_bs)

    j_bs = sympy.symbols('j_lb j_ub', integer=True)
    j = sympy.Idx('j', j_bs)

    a = sympy.IndexedBase('a')

    c = sympy.Symbol('c', real=True)

    x = sympy.IndexedBase('x')
    y = sympy.IndexedBase('y')

    eqs = [
        sympy.Eq(x[i], (a[i]/3-1)**i+c),
        sympy.Eq(y[j], a[j]-j),
    ]

    ex_code = ExampleCode(eqs, (a[i], c), (i, j),
                          logger=logger, save_temp=True)
    x_, y_ = ex_code(inps, bounds=(ilim, jlim))
    x_ref = (a_arr/3-1)**np.arange(ilim[0], ilim[1]) + c_
    y_ref = a_arr[jlim[0]:jlim[1]] - np.arange(jlim[0], jlim[1])
    assert np.allclose(x_, x_ref)
    assert np.allclose(y_, y_ref)
1082084
def correlation_model(prediction, fm):
    
    (_, r_x) = calc_resize_factor(prediction, fm.image_size)
    fdm = compute_fdm(fm, scale_factor = r_x)
    return np.corrcoef(fdm.flatten(), prediction.flatten())[0,1]
365489
def mtf_bitransformer_tiny():
  """"""
  hparams = mtf_bitransformer_base()
  hparams.batch_size = 2
  hparams.mesh_shape = ""
  hparams.d_model = 128
  hparams.encoder_layers = ["self_att", "drd"] * 2
  hparams.decoder_layers = ["self_att", "enc_att", "drd"] * 2
  hparams.num_heads = 4
  hparams.d_ff = 512
  return hparams
1288754
def flesh_out(X, W, embed_dim, CC_labels, dist_mult=2.0, angle_thresh=0.2,
              min_shortcircuit=4, max_degree=5, verbose=False):
  ''''''
  W = W.astype(bool)
  assert np.all(W == W.T), 'graph given to flesh_out must be symmetric'
  D = pairwise_distances(X, metric='sqeuclidean')

  # compute average edge lengths for each point
  avg_edge_length = np.empty(X.shape[0])
  for i,nbr_mask in enumerate(W):
    avg_edge_length[i] = D[i,nbr_mask].mean()

  # candidate edges must satisfy edge length for at least one end point
  dist_thresh = dist_mult * avg_edge_length
  dist_mask = (D < dist_thresh) | (D < dist_thresh[:,None])
  # candidate edges must connect points >= min_shortcircuit hops away
  hops_mask = np.isinf(dijkstra(W, unweighted=True, limit=min_shortcircuit-1))
  # candidate edges must not already be connected, or in the same initial CC
  CC_mask = CC_labels != CC_labels[:,None]
  candidate_edges = ~W & dist_mask & hops_mask & CC_mask
  if verbose:  # pragma: no cover
    print('before F:', candidate_edges.sum(), 'potentials')

  # calc subspaces
  subspaces, _ = cluster_subspaces(X, embed_dim, CC_labels.max()+1, CC_labels)

  # upper triangular avoids p,q <-> q,p repeats
  ii,jj = np.where(np.triu(candidate_edges))
  # Get angles
  edge_dirs = X[ii] - X[jj]
  ssi = subspaces[CC_labels[ii]]
  ssj = subspaces[CC_labels[jj]]
  F = edge_cluster_angle(edge_dirs, ssi, ssj)

  mask = F < angle_thresh
  edge_ii = ii[mask]
  edge_jj = jj[mask]
  edge_order = np.argsort(F[mask])
  if verbose:  # pragma: no cover
    print('got', len(edge_ii), 'potential edges')
  # Prevent any one node from getting a really high degree
  degree = W.sum(axis=0)
  sorted_edges = np.column_stack((edge_ii, edge_jj))[edge_order]
  for e in sorted_edges:
    if degree[e].max() < max_degree:
      W[e[0],e[1]] = True
      W[e[1],e[0]] = True
      degree[e] += 1
  return Graph.from_adj_matrix(np.where(W, np.sqrt(D), 0))
1069007
def _build_model(self):
        

        # Set up LSTM modules
        self.lstms = nn.ModuleList(
            [
                RNN(
                    num_classes=0,
                    num_tokens=self.word_dict.s,
                    emb_size=self.settings["emb_dim"],
                    lstm_hidden=self.settings["hidden_dim"],
                    attention=self.settings["attention"],
                    dropout=self.settings["dropout"],
                    bidirectional=self.settings["bidirectional"],
                    use_cuda=self.settings["host_device"] in self._gpu,
                )
            ]
            * self.settings["relation_arity"]
        )

        if "input_dim" not in self.settings:
            raise ValueError("Model parameter input_dim cannot be None.")

        # Set up final linear layer
        self.sparse_linear = SparseLinear(
            self.settings["input_dim"], self.cardinality, self.settings["bias"]
        )
1025184
def rlmb_dqn_tiny():
  """"""
  hparams = rlmb_dqn_base()
  hparams = hparams.override_from_dict(_rlmb_tiny_overrides())
  update_hparams(hparams, dict(
      simulated_rollout_length=2,
      dqn_time_limit=2,
      dqn_num_frames=128,
      real_dqn_replay_buffer_replay_capacity=100,
      dqn_replay_buffer_replay_capacity=100,
      real_dqn_agent_min_replay_history=10,
      dqn_agent_min_replay_history=10,
  ))
  return hparams
222176
def vq_discrete_unbottleneck(x, hparams):
  """"""
  x_shape = common_layers.shape_list(x)
  bottleneck_size = 2**hparams.bottleneck_bits
  means = hparams.means
  x_flat = tf.reshape(x, [-1, bottleneck_size])
  result = tf.matmul(x_flat, means)
  result = tf.reshape(result, x_shape[:-1] + [hparams.hidden_size])
  return result
561195
protected void createLinearSystem( List<AssociatedTriple> observations ) {
		int N = observations.size();

		A.reshape(4*N,27);
		A.zero();

		for( int i = 0; i < N; i++ ) {
			AssociatedTriple t = observations.get(i);

			N1.apply(t.p1,p1_norm);
			N2.apply(t.p2,p2_norm);
			N3.apply(t.p3,p3_norm);

			insert(i,0 , p1_norm.x); // tensor 1
			insert(i,1 , p1_norm.y); // tensor 2
			insert(i,2 ,1); // tensor 3
		}
	}
154043
public void solveVandermondeSystem(int[] x, byte[][] y, 
                                     int len, int dataStart, int dataLen) {
    assert(x.length <= len && y.length <= len);
    int dataEnd = dataStart + dataLen;
    for (int i = 0; i < len - 1; i++) {
      for (int j = len - 1; j > i; j--) {
        for (int k = dataStart; k < dataEnd; k++) {
          y[j][k] = (byte)(y[j][k] ^ mulTable[x[i]][y[j - 1][k] & 0x000000FF]);
        }
      }
    }
    for (int i = len - 1; i >= 0; i--) {
      for (int j = i + 1; j < len; j++) {
        for (int k = dataStart; k < dataEnd; k++) {
          y[j][k] = (byte)(divTable[y[j][k] & 0x000000FF][x[j] ^ x[j - i - 1]]);
        }
      }
      for (int j = i; j < len - 1; j++) {
        for (int k = dataStart; k < dataEnd; k++) {
          y[j][k] = (byte)(y[j][k] ^ y[j + 1][k]);
        }
      }
    }
  }
311354
def FullyConnected(
        inputs,
        units,
        activation=None,
        use_bias=True,
        kernel_initializer=None,
        bias_initializer=tf.zeros_initializer(),
        kernel_regularizer=None,
        bias_regularizer=None,
        activity_regularizer=None):
    
    if kernel_initializer is None:
        if get_tf_version_tuple() <= (1, 12):
            kernel_initializer = tf.contrib.layers.variance_scaling_initializer(2.0)
        else:
            kernel_initializer = tf.keras.initializers.VarianceScaling(2.0, distribution='untruncated_normal')

    inputs = batch_flatten(inputs)
    with rename_get_variable({'kernel': 'W', 'bias': 'b'}):
        layer = tf.layers.Dense(
            units=units,
            activation=activation,
            use_bias=use_bias,
            kernel_initializer=kernel_initializer,
            bias_initializer=bias_initializer,
            kernel_regularizer=kernel_regularizer,
            bias_regularizer=bias_regularizer,
            activity_regularizer=activity_regularizer,
            _reuse=tf.get_variable_scope().reuse)
        ret = layer.apply(inputs, scope=tf.get_variable_scope())
        ret = tf.identity(ret, name='output')

    ret.variables = VariableHolder(W=layer.kernel)
    if use_bias:
        ret.variables.b = layer.bias
    return ret
195776
def _fit_strel_to_im_2d(im, strel, r, x, y):
    
    """
    elem = strel.copy()
    x_dim, y_dim = im.shape
    x_min = x-r
    x_max = x+r+1
    y_min = y-r
    y_max = y+r+1
    if x_min < 0:
        x_adj = -x_min
        elem = elem[x_adj:, :]
        x_min = 0
    elif x_max > x_dim:
        x_adj = x_max - x_dim
        elem = elem[:-x_adj, :]
    if y_min < 0:
        y_adj = -y_min
        elem = elem[:, y_adj:]
        y_min = 0
    elif y_max > y_dim:
        y_adj = y_max - y_dim
        elem = elem[:, :-y_adj]
    ex, ey = elem.shape
    im[x_min:x_min+ex, y_min:y_min+ey] += elem
    return im
1206852
def _generate_energy_edges_single(ene):
    """"""
    midene = np.sqrt((ene[1:] * ene[:-1]))
    elo, ehi = np.zeros(len(ene)) * ene.unit, np.zeros(len(ene)) * ene.unit
    elo[1:] = ene[1:] - midene
    ehi[:-1] = midene - ene[:-1]
    elo[0] = ene[0] * (1 - ene[0] / (ene[0] + ehi[0]))
    ehi[-1] = elo[-1]
    return u.Quantity([elo, ehi])
1035602
def remove_small_objects(image, min_size=50, connectivity=1):
    
    return skimage.morphology.remove_small_objects(image,
                                                   min_size=min_size,
                                                   connectivity=connectivity)