Raw linear combination.
177497
def _lincomb(self, a, x1, b, x2, out):
        """"""
        self.tspace._lincomb(a, x1.tensor, b, x2.tensor, out.tensor)
1058359
def combine(method, images, masks=None, dtype=None,
            region=None, zeros=None, scales=None, weights=None,
            include_variance=True, datamodel=None, method_name=""):
    """'"""

    import numina.datamodel

    nimages = len(images)

    # processing masks
    if masks is None:
        intl_masks = [None for _ in images]
    elif isinstance(masks, Extension):
        intl_masks = [img[masks.name].data for img in images]
    elif isinstance(masks, collections.Sequence):
        intl_masks = [mask[0].data for mask in masks]
    else:
        raise TypeError('mask in invalid')

    if len(intl_masks) != nimages:
        raise TypeError('len(masks) != len(images)')

    # Processing region
    if region is None:
        region = Ellipsis # meaning arr[...]

    # processing zeros, scales and weights
    num_values = dict(zeros=None, scales=None, weights=None)
    arg_values = dict(zeros=zeros, scales=scales, weights=weights)

    for key in num_values:
        arg = arg_values[key] # locals()[key]
        value_arg, arg_is_func = _inspect_method(arg)
        if arg_is_func:
            num_values[key] = [value_arg(img, mask, region) for img, mask in zip(images, intl_masks)]
        else:
            num_values[key] = value_arg
        if num_values[key] is not None:
            # Intl combine works only with np arrays
            num_values[key] = numpy.array(num_values[key])

    arrays = [hdu[0].data for hdu in images]
    if masks is None:
        fmasks = None
    else:
        fmasks = intl_masks

    out = C.generic_combine(
        method, arrays, masks=fmasks, dtype=dtype, out=None,
        zeros=num_values['zeros'], scales=num_values['scales'],
        weights=num_values['weights'])

    # Build HDUList
    headers = [img[0].header for img in images]

    base_header = headers[0].copy()
    hdu1 = fits.PrimaryHDU(data=out[0], header=base_header)
    list_of_hdu = [hdu1]

    #_logger.debug('update result header')
    prolog = ""
    if prolog:
        #_logger.debug('write prolog')
        hdu1.header['history'] = prolog

    if method_name != "":
        #_logger.info("Combined %d images using '%s'", nimages, method.__name__)
        hdu1.header['history'] = "Combined %d images using '%s'" % (nimages, method)
    else:
        hdu1.header['history'] = "Combined %d images" % (nimages,)

    hdu1.header['history'] = 'Combination time {}'.format(datetime.datetime.utcnow().isoformat())

    if datamodel is None:
        datamodel = numina.datamodel.DataModel()

    for idx, img in enumerate(images, start=1):
        hdu1.header['history'] = "Image{} {}".format(idx, datamodel.get_imgid(img))

    prevnum = base_header.get('NUM-NCOM', 1)

    hdu1.header['NUM-NCOM'] = prevnum * nimages
    hdu1.header['UUID'] = str(uuid.uuid1())

    # Headers of last image
    # hdu1.header['TSUTC2'] = headers[-1]['TSUTC2']

    if include_variance:
        varhdu = fits.ImageHDU(out[1], name='VARIANCE')
        list_of_hdu.append(varhdu)

    num = fits.ImageHDU(out[2].astype('uint8'), name='MAP')
    list_of_hdu.append(num)

    result = fits.HDUList(list_of_hdu)
    return result
264365
def linear_interpolate(x1, y1, x2):
    
    li = LinInt(x1, y1)
    return li(x2)
228291
def sRGB1_to_sRGB1_linear(sRGB1):
    """"""
    sRGB1 = np.asarray(sRGB1, dtype=float)
    sRGB1_linear = C_linear(sRGB1)
    return sRGB1_linear
1115601
def combine(self, other, mean_free=False):
        
        w1 = self.w
        w2 = other.w
        w = w1 + w2
        # TODO: fix this div by zero error
        q = w2 / w1
        dsx = q * self.sx - other.sx
        dsy = q * self.sy - other.sy
        # update
        self.w = w1 + w2
        self.sx = self.sx + other.sx
        self.sy = self.sy + other.sy
        #
        if mean_free:
            if len(self.Mxy.shape) == 1:  # diagonal only
                d = dsx*dsy
            else:
                d = np.outer(dsx, dsy)
            self.Mxy += other.Mxy + (w1 / (w2 * w)) * d
        else:
            self.Mxy += other.Mxy
        return self
1096347
def feature_union_concat(Xs, nsamples, weights):
    """"""
    if any(x is FIT_FAILURE for x in Xs):
        return FIT_FAILURE
    Xs = [X if w is None else X * w for X, w in zip(Xs, weights) if X is not None]
    if not Xs:
        return np.zeros((nsamples, 0))
    if any(sparse.issparse(f) for f in Xs):
        return sparse.hstack(Xs).tocsr()
    return np.hstack(Xs)
975116
def hybrid_forward(self, F, x, sampled_values, label, weight, bias):
        """"""
        sampled_candidates, _, _ = sampled_values
        # (batch_size,)
        label = F.reshape(label, shape=(-1,))
        # (num_sampled+batch_size,)
        ids = F.concat(sampled_candidates, label, dim=0)
        # lookup weights and biases
        # (num_sampled+batch_size, dim)
        w_all = F.Embedding(data=ids, weight=weight,
                            input_dim=self._num_classes, output_dim=self._in_unit,
                            sparse_grad=self._sparse_grad)
        # (num_sampled+batch_size, 1)
        b_all = F.take(bias, indices=ids)
        return self._dense(x, sampled_values, label, w_all, b_all)
805465
function (m, u) {
        return [
            m[0][0] * u[0] + m[0][1] * u[1] + m[0][2] * u[2],
            m[1][0] * u[0] + m[1][1] * u[1] + m[1][2] * u[2],
            m[2][0] * u[0] + m[2][1] * u[1] + m[2][2] * u[2]
        ];
    }
4809
def mix(x1,
        x2,
        steps,
        is_training,
        min_prob=0.0,
        max_prob=1.0,
        mode="lin",
        simple=False,
        broadcast_last=False):
  """"""
  with tf.name_scope("mix"):
    if not is_training:
      if max_prob >= 1.0:
        return x1
      alpha_shape = shape_list(x1)
      if broadcast_last:
        alpha_shape = alpha_shape[:-1] + [1]
      alpha = tf.random_uniform(alpha_shape)
      alpha = to_float(tf.less(alpha, max_prob))
      return alpha * x1 + (1.0 - alpha) * x2

    def get_res():
      """Create the result.

      Separate function to speed it up later (see below).

      Returns:
        Tensor of mixed inputs.
      """
      if mode == "lin":
        alpha_p = inverse_lin_decay(steps)
      else:
        alpha_p = inverse_exp_decay(steps)
      alpha_p = alpha_p * (max_prob - min_prob) + min_prob
      if simple:
        return alpha_p * x1 + (1.0 - alpha_p) * x2
      alpha_shape = shape_list(x1)
      if broadcast_last:
        alpha_shape = alpha_shape[:-1] + [1]
      alpha = tf.random_uniform(alpha_shape)
      alpha = to_float(tf.less(alpha, alpha_p))
      return alpha * x1 + (1.0 - alpha) * x2

    if max_prob < 1.0:
      return get_res()

    # Prevent sampling after steps is passed to speed it up.
    if is_xla_compiled():
      return get_res()
    else:
      cur_step = tf.train.get_global_step()
      if cur_step is None:
        return x1  # Step not available, probably eval mode, don't mix.
      return tf.cond(tf.less(cur_step, steps), get_res, lambda: x1)
1242341
def sandwich_decompositions(coords0, coords1, samples=SAMPLES):
    """"""
    decomps = []
    for _ in range(samples):
        circ = qf.Circuit()
        circ += qf.CANONICAL(*coords0, 0, 1)
        circ += qf.random_gate([0])
        circ += qf.random_gate([1])
        circ += qf.CANONICAL(*coords1, 0, 1)
        gate = circ.asgate()

        coords = qf.canonical_coords(gate)
        decomps.append(coords)

    return decomps
526959
def tril(P, k=0):
    """"""
    A = P.A.copy()
    for key in P.keys:
        A[key] = numpy.tril(P.A[key])
    return Poly(A, dim=P.dim, shape=P.shape)
461974
def interpolate(v1, v2, t):
    '''
    '''
    return add(v1, mul(sub(v2, v1), t))
80098
function mix (r, s, or, cl) {
  if (!s || !r) {
    return r;
  }

  var i = 0,
    c, len;

  or = or || arguments.length === 2;

  if (cl && (len = cl.length)) {
    for (; i < len; i++) {
      c = cl[i];
      if ((c in s) && (or || !(c in r))) {
        r[c] = s[c];
      }
    }
  } else {
    for (c in s) {
      if (or || !(c in r)) {
        r[c] = s[c];
      }
    }
  }
  return r;
}
1175413
def zerocombine(arrays, masks, dtype=None, scales=None):
    

    result = median(arrays, masks=masks,
                    dtype=dtype, scales=scales)

    return result
239772
def _mix_simple(a, b, x):
    """"""
    x = np.clip(x, 0.0, 1.0)
    return (1.0 - x)*a + x*b
822167
def pairwise_point_combinations(xs, ys, anchors):
    
    for i in xs:
        anchors.append((i, max(ys)))
        anchors.append((i, min(ys)))
    for i in ys:
        anchors.append((max(xs), i))
        anchors.append((min(xs), i))
1084387
def random_combination(iterable, r):
    ""
    pool = tuple(iterable)
    n = len(pool)
    indices = sorted(random.sample(xrange(n), r))
    return tuple(pool[i] for i in indices)