Correlate records against one or many one-dimensional arrays.

        Parameters
        ----------
        signal : array-like
            One or more signals to correlate against.
764701
def correlate(self, signal):
        
        s = asarray(signal)

        if s.ndim == 1:
            if size(s) != self.shape[-1]:
                raise ValueError("Length of signal '%g' does not match record length '%g'"
                                 % (size(s), self.shape[-1]))

            return self.map(lambda x: corrcoef(x, s)[0, 1], index=[1])

        elif s.ndim == 2:
            if s.shape[1] != self.shape[-1]:
                raise ValueError("Length of signal '%g' does not match record length '%g'"
                                 % (s.shape[1], self.shape[-1]))
            newindex = arange(0, s.shape[0])
            return self.map(lambda x: array([corrcoef(x, y)[0, 1] for y in s]), index=newindex)

        else:
            raise Exception('Signal to correlate with must have 1 or 2 dimensions')
388800
function(observations, seriesKey, dimIdx, attrIdx) {
    if (observations === undefined || observations === null) return;

    // process each observation in object.
    for (var key in observations) {
      // convert key from string to an array of numbers
      var obsDimIdx = key.split(KEY_SEPARATOR).map(Number);
      obsDimIdx.forEach(updateObsKey);

      var value = observations[key];
      if (value === null) continue;

      results.push(
        iterator.call(
          context,
          // String of dimension id values e.g. 'M.FI.P.2000'
          obsKey.join(KEY_SEPARATOR),
          // Same as obsKey but without obs level dims
          seriesKey,
          // observation value
          value[0],
          // Array of dimension indices e.g. [ 0, 4, 5, 18 ]
          dimIdx.concat(obsDimIdx),
          // Array of attribute indices e.g. [ 1, 92, 27 ]
          attrIdx.concat(value.slice(1)),
          // Array of dimension objects
          allDims,
          // Array of attribute objects
          allAttrs
        )
      );
    }
  }
1104614
def _handle_signals(self):
        
        signal.signal(signal.SIGTERM, signal.SIG_DFL)
        signal.signal(signal.SIGINT, signal.SIG_IGN)
1231564
def _array_io(self, action, array, frames):
        """"""
        if (array.ndim not in (1, 2) or
                array.ndim == 1 and self.channels != 1 or
                array.ndim == 2 and array.shape[1] != self.channels):
            raise ValueError("Invalid shape: {0!r}".format(array.shape))
        if not array.flags.c_contiguous:
            raise ValueError("Data must be C-contiguous")
        ctype = self._check_dtype(array.dtype.name)
        assert array.dtype.itemsize == _ffi.sizeof(ctype)
        cdata = _ffi.cast(ctype + '*', array.__array_interface__['data'][0])
        return self._cdata_io(action, cdata, ctype, frames)
1350223
def _symmetrize_correlograms(correlograms):
    """"""

    n_clusters, _, n_bins = correlograms.shape
    assert n_clusters == _

    # We symmetrize c[i, j, 0].
    # This is necessary because the algorithm in correlograms()
    # is sensitive to the order of identical spikes.
    correlograms[..., 0] = np.maximum(correlograms[..., 0],
                                      correlograms[..., 0].T)

    sym = correlograms[..., 1:][..., ::-1]
    sym = np.transpose(sym, (1, 0, 2))

    return np.dstack((sym, correlograms))
1207710
private function correlate($xo, $x_stats, $yo, $y_stats) {
    $acc = 0;
    for($i = 0; $i < $this->sub; $i++) {
      $acc += ($this->buffers[0][($xo + $i) % $this->size] - $x_stats['mean']) *
        ($this->buffers[1][($yo + $i) % $this->size] - $y_stats['mean']);
    }
    $acc /= $this->sub;
    $stddevs = ($x_stats['stdevs'] * $y_stats['stdevs']);
    return ($stddevs == 0 ? 0 : $acc /$stddevs) ;
  }
137361
def add_layer_timing_signal_sinusoid_1d(x, layer, num_layers):
  

  channels = common_layers.shape_list(x)[-1]
  signal = get_layer_timing_signal_sinusoid_1d(channels, layer, num_layers)

  return x + signal
38063
def _determine_stream_spread_single(sigomatrixEig,
                                    thetasTrack,
                                    sigOmega,
                                    sigAngle,
                                    allinvjacsTrack):
    """"""
    #Estimate the spread in all frequencies and angles
    sigObig2= sigOmega(thetasTrack)**2.
    tsigOdiag= copy.copy(sigomatrixEig[0])
    tsigOdiag[numpy.argmax(tsigOdiag)]= sigObig2
    tsigO= numpy.dot(sigomatrixEig[1],
                     numpy.dot(numpy.diag(tsigOdiag),
                               numpy.linalg.inv(sigomatrixEig[1])))
    #angles
    if hasattr(sigAngle,'__call__'):
        sigangle2= sigAngle(thetasTrack)**2.
    else:
        sigangle2= sigAngle**2.
    tsigadiag= numpy.ones(3)*sigangle2
    tsigadiag[numpy.argmax(tsigOdiag)]= 1.
    tsiga= numpy.dot(sigomatrixEig[1],
                    numpy.dot(numpy.diag(tsigadiag),
                              numpy.linalg.inv(sigomatrixEig[1])))
    #correlations, assume half correlated for now (can be calculated)
    correlations= numpy.diag(0.5*numpy.ones(3))*numpy.sqrt(tsigOdiag*tsigadiag)
    correlations[numpy.argmax(tsigOdiag),numpy.argmax(tsigOdiag)]= 0.
    correlations= numpy.dot(sigomatrixEig[1],
                            numpy.dot(correlations,
                                      numpy.linalg.inv(sigomatrixEig[1])))
    #Now convert
    fullMatrix= numpy.empty((6,6))
    fullMatrix[:3,:3]= tsigO
    fullMatrix[3:,3:]= tsiga
    fullMatrix[3:,:3]= correlations
    fullMatrix[:3,3:]= correlations.T
    return numpy.dot(allinvjacsTrack,numpy.dot(fullMatrix,allinvjacsTrack.T))
977507
def subscribe_signal(signal_name, step=:first_pass, &block)
      key = SecureRandom.hex(5)
      @subscriptions ||= Hash.new()
      @subscriptions[signal_name] ||= Hash.new
      @subscriptions[signal_name][key] = block
      key
    end
609919
def read_block(handle, signal):
    
    signal_len = len(signal)
    it = (x[1] for x in groupby(handle,
        key=lambda row: row.strip()[:signal_len] == signal))
    found_signal = False
    for header in it:
        header = list(header)
        for h in header[:-1]:
            h = h.strip()
            if h[:signal_len] != signal:
                continue
            yield h, []  # Header only, no contents
        header = header[-1].strip()
        if header[:signal_len] != signal:
            continue
        found_signal = True
        seq = list(s.strip() for s in next(it))
        yield header, seq

    if not found_signal:
        handle.seek(0)
        seq = list(s.strip() for s in handle)
        yield None, seq
746284
def isConnected(self, signal, slot):
        
        sig_calls = self._callbacks.get(signal, [])
        for callback in sig_calls:
            if callback == slot:
                return True
        return False
854186
def calibrate_signal(signal, resp, fs, frange):
    """"""
    # remove dc offset from recorded response (synthesized orignal shouldn't have one)
    dc = np.mean(resp)
    resp = resp - dc

    npts = len(signal)
    f0 = np.ceil(frange[0] / (float(fs) / npts))
    f1 = np.floor(frange[1] / (float(fs) / npts))

    y = resp
    # y = y/np.amax(y) # normalize
    Y = np.fft.rfft(y)

    x = signal
    # x = x/np.amax(x) # normalize
    X = np.fft.rfft(x)

    H = Y / X

    # still issues warning because all of Y/X is executed to selected answers from
    # H = np.where(X.real!=0, Y/X, 1)
    # H[:f0].real = 1
    # H[f1:].real = 1
    # H = smooth(H)

    A = X / H

    return np.fft.irfft(A)
772271
def cross_correlate(observed, template_dispersion, template_fluxes,
    rebin="template", wavelength_range=None, continuum_degree=-1,
    apodize=0.10, rescale=False, z_limits=None, full_output=False):
    

    template_fluxes = np.atleast_2d(template_fluxes)
    template_dispersion = np.array(template_dispersion)
    if template_dispersion.shape[0] != template_fluxes.shape[1]:
        raise ValueError("template dispersion must have size (N_pixels,) and "\
            "template fluxes must have size (N_models, N_pixels)")

    try:
        continuum_degree = int(continuum_degree)
    except (TypeError, ValueError):
        raise TypeError("continuum order must be an integer-like object")

    if not (1 > apodize >= 0):
        raise ValueError("apodize fraction must be between 0 and 1")

    if rebin.lower() == "template":
        # Put the template fluxes onto the observed dispersion map.
        dispersion = observed.disp
        template_flux = template_fluxes \
            * resample(template_dispersion, observed.disp)
        observed_flux = observed.flux.copy()
        observed_ivar = observed.ivariance.copy()

    elif rebin.lower() == "observed":
        # Put the observed fluxes onto the template dispersion map.
        dispersion = template_dispersion
        template_flux = template_fluxes
        mat = resample(observed.disp, template_dispersion)
        observed_flux = observed.flux.copy() * mat
        observed_ivar = observed.ivariance.copy() * mat
        
    else:
        raise ValueError("rebin must be either `template` or `observed`")

    if wavelength_range is not None:
        if not isinstance(wavelength_range, (tuple, list, np.ndarray)) \
        or len(wavelength_range) != 2:
            raise TypeError("wavelength range must be a two length tuple")

        indices = np.clip(
            template_dispersion.searchsorted(wavelength_range) + [0, 1],
            0, template_dispersion.size)
        template_dispersion = template_dispersion[indices[0]:indices[1]]
        template_flux = template_flux[indices[0]:indices[1]]
        observed_flux = observed_flux[indices[0]:indices[1]]

    N_templates = template_fluxes.shape[0]

    # Clip out the non-finite edges, if they exist.
    _ = np.where(np.isfinite(template_flux[0] * observed_flux))[0]
    l_idx, u_idx = _[0], _[-1]

    dispersion = dispersion[l_idx:u_idx]
    observed_flux = observed_flux[l_idx:u_idx]
    observed_ivar = observed_ivar[l_idx:u_idx]
    template_flux = template_flux[:, l_idx:u_idx]

    # Ensure an even number of points.
    N = u_idx - l_idx
    N = N - 1 if N % 2 > 0 else N
    dispersion = dispersion[:N]
    observed_flux = observed_flux[:N]
    observed_ivar = observed_ivar[:N]
    template_flux = template_flux[:, :N]

    finite = np.isfinite(observed_flux * observed_ivar) * (observed_flux > 1e-3)
    
    # Continuum.
    if continuum_degree >= 0:
        coefficients = np.polyfit(dispersion[finite], observed_flux[finite],
            continuum_degree)
        observed_flux /= np.polyval(coefficients, dispersion)

    # Interpolate over non-finite pixels.
    observed_flux[~finite] = np.interp(dispersion[~finite], dispersion[finite],
        observed_flux[finite], left=1, right=1)

    # Scale the flux level to that the template intensities
    if rescale:
        observed_flux = (observed_flux * template_flux.ptp()) \
            + template_flux.min()

    # Apodize edges.
    edge_buffer = apodize * (dispersion[-1] - dispersion[0])
    low_w_indices = np.nonzero(dispersion < dispersion[0] + edge_buffer)[0]
    high_w_indices = np.nonzero(dispersion > dispersion[-1] - edge_buffer)[0]

    apod_curve = np.ones(N, dtype='d')
    apod_curve[low_w_indices] = (1.0 + np.cos(np.pi*(
        1.0 - (dispersion[low_w_indices] - dispersion[0])/edge_buffer)))/2.
    apod_curve[high_w_indices] = (1.0 + np.cos(np.pi*(
        1.0 - (dispersion[-1] - dispersion[high_w_indices])/edge_buffer)))/2.

    apod_observed_flux = observed_flux * apod_curve
    apod_template_flux = template_flux * apod_curve

    fft_observed_flux = np.fft.fft(apod_observed_flux)
    fft_template_flux = np.fft.fft(apod_template_flux)
    template_flux_corr = (fft_observed_flux * fft_template_flux.conjugate())
    template_flux_corr /= np.sqrt(
        np.inner(apod_observed_flux, apod_observed_flux))

    z_array = np.array(dispersion.copy())/dispersion[N/2] - 1.0

    z = np.ones(N_templates) * np.nan
    z_err = np.ones(N_templates) * np.nan
    R = np.ones(N_templates) * np.nan
    for i in range(N_templates):

        denominator = np.sqrt(
            np.inner(apod_template_flux[i, :], apod_template_flux[i, :]))
        flux_correlation = template_flux_corr[i, :] / denominator 
        correlation = np.fft.ifft(flux_correlation).real

        # Reflect about zero
        ccf = np.zeros(N)
        ccf[:N/2] = correlation[N/2:]
        ccf[N/2:] = correlation[:N/2]

        # Get height and redshift of best peak
        h = ccf.max()

        # Scale the CCF
        #ccf -= ccf.min()
        #ccf *= (h/ccf.max())
        
        R[i] = h
        z[i] = z_array[ccf.argmax()]
        try:
            z_err[i] = (np.ptp(z_array[np.where(ccf >= 0.5*h)])/2.35482)**2
        except ValueError:
            continue

    # Limits:
    if z_limits is not None:
        R[~((z_limits[1] >= z) * (z >= z_limits[0]))] = np.nan

    # Re-measure the velocity at the best peak.
    index = np.nanargmax(R)

    denominator = np.sqrt(
        np.inner(apod_template_flux[index, :], apod_template_flux[index, :]))

    flux_correlation = template_flux_corr[index, :] / denominator
    correlation = np.fft.ifft(flux_correlation).real

    # FReflect about zero.
    ccf = np.zeros(N)
    ccf[:N/2] = correlation[N/2:]
    ccf[N/2:] = correlation[:N/2]

    h = ccf.max()
    ccf -= ccf.min()
    ccf *= h/ccf.max()

    # Fit +/- 5 pixels
    idx = np.argmax(ccf) - 3, np.argmax(ccf) + 3

    coeffs = np.polyfit(z_array[idx[0]:idx[1]], ccf[idx[0]:idx[1]], 2)
    x_i = np.linspace(z_array[idx[0]], z_array[idx[1]], 1000)
    y_i = np.polyval(coeffs, x_i)

    # Update the value
    z[index] = x_i[y_i.argmax()]

    """
    # Fit the profile peak.
    fwhm = np.ptp(z_array[np.where(ccf >= 0.5)])
    p0 = np.array([z[index], fwhm/2.355, 1.0]) # mu, sigma, peak.
    use = (z_array > (p0[0] - 3 * p0[1])) * ((p0[0] + 3*p0[1]) > z_array)
    x, y = z_array[use], ccf[use]

    # Fit profile:
    f = lambda x, mu, sigma, peak: peak * np.exp(-(mu - x)**2/(2*sigma**2)) 
    
    import matplotlib.pyplot as plt
    plt.plot(z_array, ccf, c='k')
    plt.plot(x, y, c='b')
    plt.plot(x, f(x, *p0), c='r')

    p1 = curve_fit(f, x, y, p0=p0)
    plt.plot(x, f(x, *p1[0]), c='m')

    plt.gca().set_ylim(0,1)
    raise a

    p1 = curve_fit(f, x, y, p0=p0)
    """

    return (z * c, z_err * c, R)
1320743
def _add_observer(self, signal, observer):
        

        if observer not in self._observers[signal]:
            self._observers[signal].append(observer)
509883
def register_signal(alias: str, signal: pyqtSignal):
        
        if SignalDispatcher.signal_alias_exists(alias):
            raise SignalDispatcherError('Alias "' + alias + '" for signal already exists!')

        SignalDispatcher.signals[alias] = signal
1275179
def analyse(self, name):
        
        if name in self._cache:
            target = self._cache[name]
            if target['type'] == 'wav':
                signal = self._uploadController.loadSignal(target['filename'],
                                                           start=target['start'] if target['start'] != 'start' else None,
                                                           end=target['end'] if target['end'] != 'end' else None)
                if signal is not None:
                    # TODO allow user defined window
                    return getattr(signal, target['analysis'])(ref=1.0)
                else:
                    return None, 404
                pass
            elif target['type'] == 'hinge':
                hingePoints = np.array(target['hinge']).astype(np.float64)
                x = hingePoints[:, 1]
                y = hingePoints[:, 0]
                # extend as straight line from 0 to 500
                if x[0] != 0:
                    x = np.insert(x, 0, 0.0000001)
                    y = np.insert(y, 0, y[0])
                if x[-1] != 500:
                    x = np.insert(x, len(x), 500.0)
                    y = np.insert(y, len(y), y[-1])
                # convert the y axis dB values into a linear value
                y = 10 ** (y / 10)
                # perform a logspace interpolation
                f = self.log_interp1d(x, y)
                # remap to 0-500
                xnew = np.linspace(x[0], x[-1], num=500, endpoint=False)
                # and convert back to dB
                return xnew, 10 * np.log10(f(xnew))
            else:
                logger.error('Unknown target type with name ' + name)
        return None
696545
def update(self, signals):
        
        if self._sfd < 0:
            _err_closed()
        mask = sigset_t()
        sigemptyset(mask)
        if signals is not None:
            for signal in signals:
                sigaddset(mask, signal)
        # flags are ignored when sfd is not -1
        _signalfd(self._sfd, mask, 0)
        self._signals = frozenset(signals)