r"""Join N 1D signals into one N-dimensional signal.
337054
def _join_signals(self):
        """
        joined = dict()
        for name in self.signals:
            name_base = name.rsplit('_', 1)[0]
            names = joined.get(name_base, list())
            names.append(name)
            joined[name_base] = names
        for name_base, names in joined.items():
            if len(names) > 1:
                names = sorted(names)  # ensure dim ordering (_0, _1, etc.)
                signal_nd = np.stack([self.signals[n] for n in names], axis=1)
                self.signals[name_base] = signal_nd
                for name in names:
                    del self.signals[name]
703299
def _join(segments):
    """"""
    new = []
    start = segments[0][0]
    end = segments[0][1]
    for i in range(len(segments)-1):
        if segments[i+1][0] != segments[i][1]:
            new.append((start, end))
            start = segments[i+1][0]
        end = segments[i+1][1]
    new.append((start, end))
    return new
844439
def make_data(n,m):
    """"""
    I = range(1,n+1)
    J = range(1,m+1)
    x,y,w = {},{},{}
    for i in I:
        x[i] = random.randint(0,100)
        y[i] = random.randint(0,100)
        w[i] = random.randint(1,5)
    return I,J,x,y,w
716374
def _concatenate_spike_clusters(*pairs):
    """"""
    pairs = [(_as_array(x), _as_array(y)) for (x, y) in pairs]
    concat = np.vstack(np.hstack((x[:, None], y[:, None]))
                       for x, y in pairs)
    reorder = np.argsort(concat[:, 0])
    concat = concat[reorder, :]
    return concat[:, 0].astype(np.int64), concat[:, 1].astype(np.int64)
460452
def denormalize_bboxes(bboxes, rows, cols):
    """"""
    return [denormalize_bbox(bbox, rows, cols) for bbox in bboxes]
1178991
def _whiteNoise(self, size):
        """"""
        if self.noise > 0.003921569:  # 1./255.
            w, h = size

            pixel = (lambda noise: round(255 * random.uniform(1-noise, 1)))

            n_image = Image.new('RGB', size, (0, 0, 0, 0))
            rnd_grid = map(lambda _: tuple([pixel(self.noise)]) * 3,
                           [0] * w * h)
            n_image.putdata(list(rnd_grid))
            return n_image
        else:
            return None
695018
def linear_positions(n_channels):
    """"""
    return np.c_[np.zeros(n_channels),
                 np.linspace(0., 1., n_channels)]
1269882
def _coupling_matrix(self, lmax, nwin=None, weights=None):
        """"""
        if nwin is None:
            nwin = self.nwin

        if weights is None:
            weights = self.weights

        tapers_power = _np.zeros((self.lwin+1, nwin))
        for i in range(nwin):
            tapers_power[:, i] = _spectrum(self.to_array(i),
                                           normalization='4pi',
                                           convention='power', unit='per_l')

        if weights is None:
            return _shtools.SHMTCouplingMatrix(lmax, tapers_power, k=nwin)
        else:
            return _shtools.SHMTCouplingMatrix(lmax, tapers_power, k=nwin,
                                               taper_wt=self.weights)
199190
def channel(layer, n_channel, batch=None):
  """"""
  if batch is None:
    return lambda T: tf.reduce_mean(T(layer)[..., n_channel])
  else:
    return lambda T: tf.reduce_mean(T(layer)[batch, ..., n_channel])
228471
def reshape_by_device(x, num_devices):
  """"""
  return layers.nested_map(
      x, lambda x: _reshape_by_device_single(x, num_devices))
424297
def mix_wave(src, dst):
    """"""
    if len(src) > len(dst):
        # output should be longer
        dst, src = src, dst

    for i, sv in enumerate(src):
        dv = dst[i]
        if sv < 128 and dv < 128:
            dst[i] = int(sv * dv / 128)
        else:
            dst[i] = int(2 * (sv + dv) - sv * dv / 128 - 256)
    return dst
1138010
def welch(timeseries, segmentlength, noverlap=None, **kwargs):
    
    # calculate PSD
    freqs, psd_ = scipy.signal.welch(
        timeseries.value,
        noverlap=noverlap,
        fs=timeseries.sample_rate.decompose().value,
        nperseg=segmentlength,
        **kwargs
    )
    # generate FrequencySeries and return
    unit = scale_timeseries_unit(
        timeseries.unit,
        kwargs.get('scaling', 'density'),
    )
    return FrequencySeries(
        psd_,
        unit=unit,
        frequencies=freqs,
        name=timeseries.name,
        epoch=timeseries.epoch,
        channel=timeseries.channel,
    )
721165
def conv3x3(in_channels, out_channels, stride=1):
    
    return nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
210279
def conv2d(x_input, w_matrix):
    """"""
    return tf.nn.conv2d(x_input, w_matrix, strides=[1, 1, 1, 1], padding='SAME')
668968
def _nanmedian(array, axis=None):
    """"""

    if isinstance(axis, tuple):
        array = _move_tuple_axes_first(array, axis=axis)
        axis = 0
    return bottleneck.nanmedian(array, axis=axis)
575535
def materialize_as_ndarray(a):
    """"""
    if type(a) in (list, tuple):
        if da is not None and any(isinstance(arr, da.Array) for arr in a):
            return da.compute(*a, sync=True)
        return tuple(np.asarray(arr) for arr in a)
    return np.asarray(a)
871911
def _merge_multi_context(outputs, major_axis):
    
    rets = []
    for tensors, axis in zip(outputs, major_axis):
        if axis >= 0:
            # pylint: disable=no-member,protected-access
            if len(tensors) == 1:
                rets.append(tensors[0])
            else:
                # Concatenate if necessary
                rets.append(nd.concat(*[tensor.as_in_context(tensors[0].context)
                                        for tensor in tensors],
                                      dim=axis))
            # pylint: enable=no-member,protected-access
        else:
            # negative axis means the there is no batch_size axis, and all the
            # results should be the same on each device. We simply take the
            # first one, without checking they are actually the same
            rets.append(tensors[0])
    return rets